Skip to content

Official Codebase of 3DCodeVerse

Python

urdf: coupled mechanisms — <mimic> is honoured end to end

ziyao9e19e1b926cd
diff --git a/harness/codeverse/contracts/plan.py b/harness/codeverse/contracts/plan.py
index e27e75ac..a98f60ba 100644
--- a/harness/codeverse/contracts/plan.py
+++ b/harness/codeverse/contracts/plan.py
@@ -175,6 +175,24 @@ class StaticPlan(BaseModel):
return sum(p.leaf_count for p in self.parts)
+class MimicPlan(BaseModel):
+ """This joint is driven by another: ``q = multiplier * q[joint] + offset``.
+
+ A coupled mechanism (umbrella ribs on one runner, a pantograph, a tambour) has ONE
+ input and many moving links. Declaring the coupling lets the sweep pose it the way
+ it really moves; without it every link is driven independently."""
+
+ joint: str = Field(description="the joint this one follows, by name")
+ multiplier: float = Field(default=1.0, description="q_this = multiplier * q_that + offset")
+ offset: float = Field(default=0.0)
+
+ @model_validator(mode="after")
+ def _sane(self) -> MimicPlan:
+ if abs(self.multiplier) < 1e-9:
+ raise ValueError(f"mimic of {self.joint}: multiplier 0 means the joint cannot move; use type=fixed")
+ return self
+
+
class JointPlan(BaseModel):
name: str
@@ -191,6 +209,7 @@ class JointPlan(BaseModel):
upper: float = Field(default=0.0)
rest: float = Field(default=0.0, description="joint value in the authored rest pose")
motion: str = Field(default="", description="what moving this joint does, one line")
+ mimic: MimicPlan | None = Field(default=None, description="set when this joint is driven by another")
@model_validator(mode="after")
def _sane(self) -> JointPlan:
@@ -486,8 +505,38 @@ class ArticulatedPlan(StaticPlan):
raise ValueError(f"link {link} is not connected to root {self.root_link} (single-root tree required)")
seen.add(cur)
cur = parent_of[cur]
+ self._check_mimics()
return self
+ def _check_mimics(self) -> None:
+ """Every declared coupling must name a joint that exists, moves, and does not
+ lead back to the joint that follows it."""
+ by_key = {to_snake(j.name): j for j in self.joints}
+ for j in self.joints:
+ if j.mimic is None:
+ continue
+ if j.type == "fixed":
+ raise ValueError(f"joint {j.name}: a fixed joint cannot mimic {j.mimic.joint}")
+ src = by_key.get(to_snake(j.mimic.joint))
+ if src is None:
+ raise ValueError(
+ f"joint {j.name}: mimic joint {j.mimic.joint} is not a joint in this plan; the joints are: "
+ f"{', '.join(sorted(x.name for x in self.joints))}")
+ if src.type == "fixed":
+ raise ValueError(f"joint {j.name}: mimics {src.name}, which is fixed and never moves")
+ if to_snake(src.name) == to_snake(j.name):
+ raise ValueError(f"joint {j.name}: mimics itself")
+ seen, cur = {to_snake(j.name)}, src
+ while cur.mimic is not None:
+ key = to_snake(cur.name)
+ if key in seen:
+ raise ValueError(f"joint {j.name}: mimic chain loops back through {cur.name}")
+ seen.add(key)
+ nxt = by_key.get(to_snake(cur.mimic.joint))
+ if nxt is None:
+ raise ValueError(f"joint {cur.name}: mimic joint {cur.mimic.joint} is not a joint in this plan")
+ cur = nxt
+
class ZonePlan(BaseModel):
name: str = Field(description="PascalCase zone name, e.g. Harbour")
diff --git a/harness/codeverse/languages/urdf/__init__.py b/harness/codeverse/languages/urdf/__init__.py
index d6fca341..255ccd61 100644
--- a/harness/codeverse/languages/urdf/__init__.py
+++ b/harness/codeverse/languages/urdf/__init__.py
@@ -191,6 +191,9 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
joint_names: list[str] = []
parent_of: dict[str, str] = {}
+ # <mimic> may name a joint declared later in the file, so the whole name set is
+ # collected before any joint is linted
+ all_joint_names = {el.get("name", "") for el in joints if el.get("name")}
for el in joints:
jname = el.get("name", "")
if not jname:
@@ -199,7 +202,7 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
if jname in joint_names:
out.append(_f(Severity.ERROR, f"duplicate joint name '{jname}'", target=jname, fix="Joint names must be unique."))
joint_names.append(jname)
- _lint_joint(el, jname, link_names, parent_of, out)
+ _lint_joint(el, jname, link_names, parent_of, out, all_joint_names)
# tree structure
children = set(parent_of)
@@ -284,7 +287,8 @@ def _lint_origin(o: ET.Element | None, what: str, target: str, out: list[GateFin
fix=f'<origin {attr}="0 0 0"/>'))
-def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: dict[str, str], out: list[GateFinding]) -> None:
+def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: dict[str, str],
+ out: list[GateFinding], joint_names: set[str] | None = None) -> None:
jtype = el.get("type", "")
if jtype not in JOINT_TYPES:
out.append(_f(Severity.ERROR, f"joint '{jname}': type '{jtype}' must be one of {JOINT_TYPES}", target=jname,
@@ -349,8 +353,26 @@ def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: di
elif jtype == "continuous" and lim is not None and (lim.get("lower") is not None or lim.get("upper") is not None):
out.append(_f(Severity.WARN, f"joint '{jname}': continuous joints have no lower/upper (ignored)", target=jname,
fix='<limit effort="10" velocity="1"/> or use type=revolute'))
- if el.find("mimic") is not None:
- out.append(_f(Severity.WARN, f"joint '{jname}': <mimic> is ignored by the harness (sweeps move it independently)", target=jname))
+ mim = el.find("mimic")
+ if mim is not None:
+ src = (mim.get("joint") or "").strip()
+ if not src:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> without joint=", target=jname,
+ fix='<mimic joint="runner_slide" multiplier="1" offset="0"/>'))
+ elif src == jname:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> names itself", target=jname))
+ elif joint_names is not None and src not in joint_names:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic joint=\"{src}\"> names no joint in this file",
+ target=jname, fix=f"one of: {', '.join(sorted(joint_names))}"))
+ if jtype == "fixed":
+ out.append(_f(Severity.ERROR, f"joint '{jname}': a fixed joint has nothing to mimic", target=jname,
+ fix="give it a type and a limit, or drop the <mimic>"))
+ try:
+ if abs(float(mim.get("multiplier", 1) or 1)) < 1e-12:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic multiplier=\"0\"> — the joint cannot move",
+ target=jname, fix="use type=fixed, or a non-zero multiplier"))
+ except ValueError:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> multiplier/offset must be numbers", target=jname))
# ------------------------------------------------------------------ model.py
@@ -471,6 +493,7 @@ class JointRow:
lower: float | None
upper: float | None
rest: float = 0.0 # plan rest value the limits were shifted by (0 → limits == plan limits)
+ mimic: tuple[str, float, float] | None = None # (driving joint, multiplier, offset)
@dataclass
@@ -525,9 +548,13 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
lower = upper = None
if j.type in ("revolute", "prismatic"):
lower, upper = j.lower - j.rest, j.upper - j.rest
+ mim = None
+ if j.mimic is not None:
+ # instanced links get one joint each; each copy follows the same driver
+ mim = (to_snake(j.mimic.joint), float(j.mimic.multiplier), float(j.mimic.offset))
joints.append(JointRow(name=to_snake(j.name) + suffix, type=j.type, parent=parent, child=child,
origin_xyz=(0.0, 0.0, 0.0), axis=tuple(float(v) for v in j.axis), lower=lower, upper=upper,
- rest=float(j.rest) if lower is not None else 0.0))
+ rest=float(j.rest) if lower is not None else 0.0, mimic=mim))
for j in plan.joints:
parent, child = to_snake(j.parent), to_snake(j.child)
@@ -550,7 +577,7 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
cf = links[jr.child].frame_xyz
fixed.append(JointRow(name=jr.name, type=jr.type, parent=jr.parent, child=jr.child,
origin_xyz=tuple(c - p for c, p in zip(cf, pf, strict=True)), axis=jr.axis,
- lower=jr.lower, upper=jr.upper, rest=jr.rest))
+ lower=jr.lower, upper=jr.upper, rest=jr.rest, mimic=jr.mimic))
return UrdfFrames(robot_name=to_snake(plan.object_name), root=root, links=links, joints=fixed)
@@ -585,6 +612,10 @@ def render_urdf(frames: UrdfFrames) -> str:
if jr.lower is not None and jr.upper is not None:
lim = f'lower="{_fmt(jr.lower)}" upper="{_fmt(jr.upper)}" ' + lim
lines.append(f" <limit {lim}/>" + _limit_note(jr))
+ if jr.mimic is not None:
+ src, mult, off = jr.mimic
+ lines.append(f' <mimic joint="{src}" multiplier="{_fmt(mult)}" offset="{_fmt(off)}"/>'
+ " <!-- driven: the sweep moves the driver, this joint follows -->")
lines.append(" </joint>")
lines.append("</robot>")
return "\n".join(lines) + "\n"
diff --git a/harness/codeverse/prompts/tracks/plan_articulated.j2 b/harness/codeverse/prompts/tracks/plan_articulated.j2
index 00decd4f..fa53db05 100644
--- a/harness/codeverse/prompts/tracks/plan_articulated.j2
+++ b/harness/codeverse/prompts/tracks/plan_articulated.j2
@@ -40,6 +40,11 @@ WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
* Count the moving parts the brief names (doors, drawers, lids, arms, wheels): that is the number of
non-fixed joints, give or take one. Do not add joints to reach a part count — a rigid feature is a
sub-part, not a link.
+ * A mechanism with ONE input and several moving links (umbrella ribs on a runner, scissor/
+ pantograph arms, a tambour's slats, folding legs braced together) declares the coupling:
+ give every follower joint `mimic: {joint: "<the driving joint>", multiplier: <ratio>, offset: 0}`.
+ The harness then moves the driver and lets the followers follow; without it the sweep poses
+ each link on its own and the mechanism is judged in states it cannot reach.
* `parent` / `child` name top-level `parts` (links) — NEVER a sub-part: anything a joint moves must be
its own link (the harness promotes a referenced sub-part to a link, but plan it as a link yourself).
A `revolute` range stays within 2π; a part that turns freely (swivel, wheel) is `continuous`.
diff --git a/harness/codeverse/prompts/urdf/contract.md b/harness/codeverse/prompts/urdf/contract.md
index f2756e12..317462bc 100644
--- a/harness/codeverse/prompts/urdf/contract.md
+++ b/harness/codeverse/prompts/urdf/contract.md
@@ -52,7 +52,10 @@ You never export.
## Allowed / forbidden
Same as the blender contract for `model.py` (bpy, bmesh, mathutils, math, random).
URDF: no `<gazebo>`, `<transmission>`, `<sensor>`, xacro, `package://`, mesh scale,
-inline primitives, `mimic` (unless the plan has it). Inertial blocks are optional.
+inline primitives. Inertial blocks are optional. `<mimic joint="..." multiplier="..."
+offset="..."/>` IS honoured: the sweep drives the named joint and every follower follows it,
+so a one-input mechanism (umbrella ribs, scissor arms, coupled folding legs) must declare it
+— write one `<mimic>` per follower, naming the joint that drives the mechanism.
## COMPLETE minimal example (verified: harness build + FK check + joint sweep)
A pedal bin: body + lid hinged at the back edge, knob fixed on the lid. q = 0 = lid closed.
diff --git a/harness/codeverse/skills/cv3d-urdf-joints/SKILL.md b/harness/codeverse/skills/cv3d-urdf-joints/SKILL.md
index dd08db48..885560b2 100644
--- a/harness/codeverse/skills/cv3d-urdf-joints/SKILL.md
+++ b/harness/codeverse/skills/cv3d-urdf-joints/SKILL.md
@@ -143,9 +143,11 @@ collision geometry. Planning groups, end effectors, group states and disabled co
are SRDF concepts; this harness has no SRDF, so do not invent them. The URDF contract also
forbids `gazebo`, `transmission`, `sensor`, xacro, `package://` and inline primitives. Two of
these the linter measures directly: a `mesh scale` attribute is a WARN ("model in meters in
-model.py instead"), and a `mimic` joint is a WARN because **the harness ignores it — the sweep
-moves the mimicking joint independently**, so a mechanism that depends on mimic will be posed
-in states you never intended.
+model.py instead"), and a `mimic` joint is checked, not dismissed: the sweep drives the
+joint a `<mimic>` names and every follower follows it, so a one-input mechanism (umbrella
+ribs, scissor arms, coupled folding legs) is posed the way it really moves. Declare one
+`<mimic joint="<driver>" multiplier="<ratio>" offset="0"/>` per follower; a coupling that
+names no joint, names itself, or closes a loop is a lint ERROR.
## Finish
diff --git a/harness/codeverse/spatial/joints_model.py b/harness/codeverse/spatial/joints_model.py
index 5cb787b6..4751c6f7 100644
--- a/harness/codeverse/spatial/joints_model.py
+++ b/harness/codeverse/spatial/joints_model.py
@@ -113,6 +113,21 @@ def parse_origin(elem: ET.Element | None, what: str) -> np.ndarray:
# ------------------------------------------------------------------ model
+@dataclass(frozen=True)
+class Mimic:
+ """A joint driven by another: ``q = multiplier * q[joint] + offset`` (URDF <mimic>).
+
+ Coupled mechanisms (umbrella ribs on one runner, a pantograph's crossing arms, a
+ tambour's slats) have one degree of freedom and many moving links; without this the
+ sweep drives every link independently and poses the mechanism in states it cannot
+ reach (compare_art_v3/v4: umbrella, scissor_mirror and folding_workbench are the
+ lowest-scoring prompts on the battery)."""
+
+ joint: str
+ multiplier: float = 1.0
+ offset: float = 0.0
+
+
@dataclass
class Joint:
name: str
@@ -125,11 +140,17 @@ class Joint:
upper: float | None = None
effort: float = 0.0
velocity: float = 0.0
+ mimic: Mimic | None = None
@property
def movable(self) -> bool:
return self.type in MOVABLE_TYPES
+ @property
+ def driven(self) -> bool:
+ """Moves, but not on its own: its value follows another joint's."""
+ return self.movable and self.mimic is not None
+
def motion(self, q: float) -> np.ndarray:
"""Local motion transform for joint value ``q`` (identity for fixed)."""
T = np.eye(4)
@@ -174,6 +195,10 @@ class Robot:
def movable_joints(self) -> list[Joint]:
return [j for j in self.joints.values() if j.movable]
+ def independent_joints(self) -> list[Joint]:
+ """The degrees of freedom: movable joints that do not follow another one."""
+ return [j for j in self.joints.values() if j.movable and j.mimic is None]
+
def link_order(self) -> list[str]:
"""Links in parent-before-child order (DFS from root)."""
out: list[str] = []
@@ -289,6 +314,19 @@ def _joint_from_xml(el: ET.Element) -> Joint:
raise UrdfError(f"joint {name}: {jtype} joints need <limit lower upper>")
if j.upper < j.lower:
raise UrdfError(f"joint {name}: upper {j.upper} < lower {j.lower}")
+ mim = el.find("mimic")
+ if mim is not None:
+ src = mim.get("joint")
+ if not src:
+ raise UrdfError(f"joint {name}: <mimic> needs joint=\"<other joint>\"")
+ try:
+ mult = float(mim.get("multiplier", 1.0) or 1.0)
+ off = float(mim.get("offset", 0.0) or 0.0)
+ except ValueError as e:
+ raise UrdfError(f"joint {name}: <mimic> multiplier/offset must be numbers") from e
+ if abs(mult) < 1e-12:
+ raise UrdfError(f"joint {name}: <mimic multiplier=\"0\"> — the joint cannot move; use type=fixed")
+ j.mimic = Mimic(joint=src, multiplier=mult, offset=off)
return j
@@ -328,6 +366,26 @@ def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, lo
if len(set(children)) != len(children):
dup = sorted({c for c in children if children.count(c) > 1})
raise UrdfError(f"links with more than one parent joint: {dup}")
+ for j in joints.values():
+ if j.mimic is None:
+ continue
+ if not j.movable:
+ raise UrdfError(f"joint {j.name}: <mimic> on a {j.type} joint has nothing to follow")
+ src = joints.get(j.mimic.joint)
+ if src is None:
+ raise UrdfError(f"joint {j.name}: <mimic joint=\"{j.mimic.joint}\"> names no joint; known: {sorted(joints)}")
+ if not src.movable:
+ raise UrdfError(f"joint {j.name}: mimics {src.name!r}, which is {src.type} and never moves")
+ seen = {j.name}
+ cur = src
+ while cur.mimic is not None:
+ if cur.name in seen:
+ raise UrdfError(f"joint {j.name}: <mimic> chain is a cycle through {cur.name!r}")
+ seen.add(cur.name)
+ nxt = joints.get(cur.mimic.joint)
+ if nxt is None:
+ raise UrdfError(f"joint {cur.name}: <mimic joint=\"{cur.mimic.joint}\"> names no joint")
+ cur = nxt
roots = [n for n in links if n not in children]
if len(roots) != 1:
raise UrdfError(f"expected exactly one root link, found {roots}")
@@ -338,12 +396,35 @@ def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, lo
# ------------------------------------------------------------------ FK
+def resolve_q(robot: Robot, q: dict[str, float] | None = None) -> dict[str, float]:
+ """``q`` with every mimicking joint's value computed from the joint it follows.
+
+ A value given for a driven joint is ignored: the mechanism has one input, and the
+ sweep must not be able to pose it out of its own coupling."""
+ out = {k: float(v) for k, v in (q or {}).items()}
+ for j in robot.joints.values():
+ if j.mimic is None:
+ continue
+ cur, chain = j, []
+ while cur.mimic is not None:
+ chain.append(cur)
+ cur = robot.joints[cur.mimic.joint]
+ v = float(out.get(cur.name, 0.0))
+ for link_j in reversed(chain):
+ assert link_j.mimic is not None
+ v = link_j.mimic.multiplier * v + link_j.mimic.offset
+ out[j.name] = v
+ return out
+
+
def fk(robot: Robot, q: dict[str, float] | None = None) -> dict[str, np.ndarray]:
- """World transform of every link frame for joint values ``q`` (missing → 0)."""
+ """World transform of every link frame for joint values ``q`` (missing → 0).
+ Mimicking joints follow the joint they name, whatever ``q`` says about them."""
q = q or {}
unknown = set(q) - set(robot.joints)
if unknown:
raise UrdfError(f"fk: unknown joints {sorted(unknown)}; known: {sorted(robot.joints)}")
+ q = resolve_q(robot, q)
out: dict[str, np.ndarray] = {robot.root: np.eye(4)}
for name in robot.link_order():
if name == robot.root:
diff --git a/harness/codeverse/spatial/joints_poses.py b/harness/codeverse/spatial/joints_poses.py
index aef4a76c..ef3ea9fc 100644
--- a/harness/codeverse/spatial/joints_poses.py
+++ b/harness/codeverse/spatial/joints_poses.py
@@ -25,7 +25,10 @@ def pose_samples(robot: Robot, n_random: int = 8, seed: int = 0) -> list[dict[st
"""Deterministic pose set: rest, each joint at lower/mid/upper (others at 0),
then ``n_random`` seeded random combinations within limits.
Continuous joints sample 0, ±π/2, π and random in [-π, π]."""
- movable = robot.movable_joints()
+ # only the degrees of freedom are driven: a mimicking joint follows its source
+ # through fk, so sampling it independently would pose a coupled mechanism in a
+ # state the mechanism cannot reach
+ movable = robot.independent_joints()
poses: list[dict[str, float]] = [{}]
for j in movable:
for v in _joint_values(j):
diff --git a/harness/codeverse/spatial/joints_sweep.py b/harness/codeverse/spatial/joints_sweep.py
index 2756efcc..b1f24a2b 100644
--- a/harness/codeverse/spatial/joints_sweep.py
+++ b/harness/codeverse/spatial/joints_sweep.py
@@ -346,17 +346,24 @@ def motion_direction_check(robot: Robot, joint: str, expected: str, *, probe: fl
j = robot.joints.get(joint)
if j is None or not j.movable:
raise UrdfError(f"motion_direction_check: {joint!r} is not a movable joint")
+ driven_by = None
+ if j.mimic is not None: # a driven joint has no input of its own: probe what drives it
+ driven_by = j
+ while driven_by.mimic is not None:
+ driven_by = robot.joints[driven_by.mimic.joint]
mesh = robot.links[j.child].mesh
if mesh is None:
raise UrdfError(f"motion_direction_check: link {j.child!r} has no mesh")
+ src = driven_by or j # the joint the probe is applied to
if probe is None:
- hi = j.upper if j.upper is not None else math.pi
- lo = j.lower if j.lower is not None else -math.pi
+ hi = src.upper if src.upper is not None else math.pi
+ lo = src.lower if src.lower is not None else -math.pi
probe = hi if abs(hi) >= abs(lo) else lo
- if j.type != "prismatic":
+ if src.type != "prismatic":
probe = math.copysign(min(abs(probe), 0.35), probe) if probe else 0.35
+ drive = src.name
c0 = trimesh.transform_points([mesh.centroid], fk(robot, {})[j.child])[0]
- c1 = trimesh.transform_points([mesh.centroid], fk(robot, {joint: probe})[j.child])[0]
+ c1 = trimesh.transform_points([mesh.centroid], fk(robot, {drive: probe})[j.child])[0]
delta = c1 - c0
n = float(np.linalg.norm(delta))
d = delta / n if n > 1e-9 else delta
@@ -382,7 +389,8 @@ def motion_direction_check(robot: Robot, joint: str, expected: str, *, probe: fl
suggested = tuple(round(float(v), 3) for v in R_joint.T @ (s / n_s))
return MotionCheck(joint=joint, expected=expected, observed_dir=tuple(round(float(v), 4) for v in d), ok=ok,
cos=round(cos, 4), suggested_axis=suggested,
- message=(f"{joint}: child '{j.child}' moves {tuple(round(float(v),3) for v in d)} for q={probe:+.3g}; "
+ message=((f"{joint} (driven by {drive})" if driven_by is not None else f"{joint}")
+ + f": child '{j.child}' moves {tuple(round(float(v),3) for v in d)} for q={probe:+.3g}; "
f"expected {expected} ({'ok' if ok else 'WRONG — flip the axis sign or swap limits'})"))
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 30248ac4..bf547379 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -494,7 +494,8 @@ $0.02–0.03 (flash) / ~$0.2 (pro); api-agent generation 3–6 min per object ro
cannot verify caps a run at 0.60 AND fails it, so on the scene track only the spec's
`must_have` list keeps that priority (the plan's own checklist is `should`).
* Articulated: candidate selection uses the quick 4-view sheet (not pose views);
- mimic joints ignored; sweep is O(links² × poses).
+ mimic joints are honoured (the sweep drives independent joints only and resolves
+ followers through the chain); sweep is O(links² × poses).
* Scenes: fps is a relative cost; camera-in-geometry can miss open-back enclosures.
* threejs: textures are stripped on GLB export (the texture pass re-adds them as a
derived pack); `userData.tick` cannot survive export.
diff --git a/harness/tests/urdf_joints/test_mimic.py b/harness/tests/urdf_joints/test_mimic.py
new file mode 100644
index 00000000..970f9935
--- /dev/null
+++ b/harness/tests/urdf_joints/test_mimic.py
@@ -0,0 +1,134 @@
+"""Coupled mechanisms: a <mimic> joint follows the joint it names, everywhere.
+
+compare_art_v3/v4: umbrella, scissor_mirror and folding_workbench are the lowest scorers
+on the battery, and all three are one-input mechanisms with many moving links. Before
+this the sweep drove every link independently and posed them in states the mechanism
+cannot reach."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from codeverse.languages.urdf import lint_workspace, render_urdf
+from codeverse.spatial.joints import (
+ UrdfError,
+ load_urdf,
+ motion_direction_check,
+ pose_samples,
+ sweep_collisions,
+)
+from codeverse.spatial.joints_model import fk, resolve_q
+from tests.urdf_joints.conftest import box_glb
+
+RIB = """<?xml version="1.0"?>
+<robot name="umbrella">
+ <link name="shaft"><visual><geometry><mesh filename="meshes/shaft.glb"/></geometry></visual></link>
+ <link name="runner"><visual><geometry><mesh filename="meshes/runner.glb"/></geometry></visual></link>
+ <link name="rib_a"><visual><geometry><mesh filename="meshes/rib_a.glb"/></geometry></visual></link>
+ <link name="rib_b"><visual><geometry><mesh filename="meshes/rib_b.glb"/></geometry></visual></link>
+ <joint name="runner_slide" type="prismatic">
+ <parent link="shaft"/><child link="runner"/>
+ <origin xyz="0 0 0.5" rpy="0 0 0"/><axis xyz="0 0 1"/>
+ <limit lower="0" upper="0.3" effort="10" velocity="1"/>
+ </joint>
+ <joint name="rib_a_hinge" type="revolute">
+ <parent link="shaft"/><child link="rib_a"/>
+ <origin xyz="0 0 1" rpy="0 0 0"/><axis xyz="0 1 0"/>
+ <limit lower="0" upper="1.2" effort="10" velocity="1"/>
+ <mimic joint="runner_slide" multiplier="4" offset="0"/>
+ </joint>
+ <joint name="rib_b_hinge" type="revolute">
+ <parent link="shaft"/><child link="rib_b"/>
+ <origin xyz="0 0 1" rpy="0 0 0"/><axis xyz="0 -1 0"/>
+ <limit lower="0" upper="1.2" effort="10" velocity="1"/>
+ <mimic joint="rib_a_hinge" multiplier="1" offset="0"/>
+ </joint>
+</robot>
+"""
+
+
+def _robot(tmp_path: Path, urdf_text: str = RIB):
+ meshes = tmp_path / "meshes"
+ box_glb(meshes / "shaft.glb", (0, 0, 0.6), (0.04, 0.04, 1.2))
+ box_glb(meshes / "runner.glb", (0, 0, 0.5), (0.08, 0.08, 0.06))
+ box_glb(meshes / "rib_a.glb", (0.25, 0, 1.0), (0.5, 0.02, 0.02))
+ box_glb(meshes / "rib_b.glb", (-0.25, 0, 1.0), (0.5, 0.02, 0.02))
+ urdf = tmp_path / "robot.urdf"
+ urdf.write_text(urdf_text)
+ return load_urdf(urdf, meshes)
+
+
+def test_a_driven_joint_follows_its_driver_through_the_chain(tmp_path):
+ r = _robot(tmp_path)
+ assert [j.name for j in r.independent_joints()] == ["runner_slide"]
+ assert r.joints["rib_a_hinge"].driven and r.joints["rib_b_hinge"].driven
+ q = resolve_q(r, {"runner_slide": 0.2})
+ assert q["rib_a_hinge"] == pytest.approx(0.8) # multiplier 4
+ assert q["rib_b_hinge"] == pytest.approx(0.8) # follows rib_a_hinge, multiplier 1
+ # a value handed in for a driven joint is ignored: the mechanism has one input
+ assert resolve_q(r, {"runner_slide": 0.1, "rib_a_hinge": 99.0})["rib_a_hinge"] == pytest.approx(0.4)
+ # the rib hinges about its own frame origin, so the coupling shows in the rotation
+ assert fk(r, {"runner_slide": 0.1})["rib_a"][:3, :3].tolist() != fk(r, {})["rib_a"][:3, :3].tolist()
+ assert fk(r, {"runner_slide": 0.1})["runner"][2, 3] == pytest.approx(fk(r, {})["runner"][2, 3] + 0.1)
+
+
+def test_pose_samples_drive_only_the_degrees_of_freedom(tmp_path):
+ r = _robot(tmp_path)
+ poses = pose_samples(r)
+ assert all(set(p) <= {"runner_slide"} for p in poses), poses
+ assert any(p.get("runner_slide") == pytest.approx(0.3) for p in poses)
+ # the ribs still move: the sweep sees the coupled pose, not a frozen one
+ opened = [p for p in poses if p.get("runner_slide")][0]
+ assert fk(r, opened)["rib_a"][:3, :3].tolist() != fk(r, {})["rib_a"][:3, :3].tolist()
+
+
+def test_the_sweep_poses_the_mechanism_the_way_it_moves(tmp_path):
+ r = _robot(tmp_path)
+ rep = sweep_collisions(r, pose_samples(r))
+ assert {p.label for p in rep.per_pose} == {"rest", "runner_slide@upper", "runner_slide@mid"}
+ assert rep.summary.n_poses == 3 # one input, not three
+
+
+def test_a_driven_joint_is_probed_through_its_driver(tmp_path):
+ r = _robot(tmp_path)
+ chk = motion_direction_check(r, "rib_a_hinge", "up")
+ assert "driven by runner_slide" in chk.message
+ assert chk.observed_dir != (0.0, 0.0, 0.0)
+
+
[email protected]("bad,msg", [
+ ('<mimic joint="nope"/>', "names no joint"),
+ ('<mimic joint="rib_a_hinge" multiplier="0"/>', "cannot move"),
+ ('<mimic joint="rib_b_hinge"/>', "cycle"),
+])
+def test_a_broken_coupling_is_refused_at_load(tmp_path, bad, msg):
+ text = RIB.replace('<mimic joint="runner_slide" multiplier="4" offset="0"/>', bad)
+ with pytest.raises(UrdfError, match=msg):
+ _robot(tmp_path, text)
+
+
+def test_the_skeleton_writes_the_plan_s_coupling(cabinet_plan):
+ from codeverse.contracts.plan import MimicPlan
+ from codeverse.languages.urdf import compute_urdf_frames
+
+ plan = cabinet_plan.model_copy(deep=True)
+ plan.joints[0].mimic = MimicPlan(joint="handle_mount", multiplier=2.0, offset=0.1)
+ plan.joints[1].type = "revolute"
+ plan.joints[1].lower, plan.joints[1].upper, plan.joints[1].rest = 0.0, 1.0, 0.0
+ urdf = render_urdf(compute_urdf_frames(plan))
+ assert '<mimic joint="handle_mount" multiplier="2" offset="0.1"/>' in urdf
+
+
+def test_the_lint_accepts_a_real_coupling_and_names_a_broken_one(tmp_path, monkeypatch):
+ from codeverse.workspace import Workspace
+
+ ws = Workspace(tmp_path / "ws").create()
+ (ws.src / "robot.urdf").write_text(RIB)
+ (ws.src / "model.py").write_text("import bpy\n")
+ findings = [f for f in lint_workspace(ws).findings if "mimic" in f.message]
+ assert findings == []
+ (ws.src / "robot.urdf").write_text(RIB.replace('joint="runner_slide" multiplier="4"', 'joint="ghost" multiplier="4"'))
+ errs = [f for f in lint_workspace(ws).findings if "mimic" in f.message and f.severity.value == "error"]
+ assert len(errs) == 1 and "names no joint" in errs[0].message