agent-manifesto-kit 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env python3
2
+ """Explicit, consumer-local Blender task state; Python standard library only.
3
+
4
+ All reference paths are relative to the state file's directory, never the CWD.
5
+ Evidence stores SHA-256 of its declared inputs and the acceptance references.
6
+ Only changed dependencies invalidate a check. Run --help for the small CLI.
7
+ """
8
+
9
+ import argparse
10
+ import hashlib
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import sys
15
+ import tempfile
16
+
17
+
18
+ PROFILES = {"quick": 1, "standard": 2, "production": 3}
19
+ RESULTS = ("pass", "fail", "not_tested")
20
+
21
+
22
+ def natural(value):
23
+ try:
24
+ number = int(value)
25
+ except ValueError:
26
+ raise argparse.ArgumentTypeError("expected a nonnegative integer")
27
+ if number < 0 or str(number) != value:
28
+ raise argparse.ArgumentTypeError("expected a nonnegative integer")
29
+ return number
30
+
31
+
32
+ def ref(base, value):
33
+ if not value.strip():
34
+ raise ValueError("reference paths must not be empty")
35
+ path = Path(value)
36
+ path = path if path.is_absolute() else base / path
37
+ return os.path.relpath(path.resolve(), base)
38
+
39
+
40
+ def digest(base, value):
41
+ path = base / value
42
+ if not path.is_file():
43
+ return None
44
+ hasher = hashlib.sha256()
45
+ with path.open("rb") as stream:
46
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
47
+ hasher.update(chunk)
48
+ return hasher.hexdigest()
49
+
50
+
51
+ def write_state(path, state, create=False):
52
+ payload = json.dumps(state, indent=2, allow_nan=False) + "\n"
53
+ path.parent.mkdir(parents=True, exist_ok=True)
54
+ if create:
55
+ with path.open("x", encoding="utf-8") as stream:
56
+ stream.write(payload)
57
+ stream.flush()
58
+ os.fsync(stream.fileno())
59
+ return
60
+ name = None
61
+ try:
62
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent,
63
+ prefix=".task-state-", delete=False) as stream:
64
+ name = stream.name
65
+ stream.write(payload)
66
+ stream.flush()
67
+ os.fsync(stream.fileno())
68
+ os.replace(name, path)
69
+ finally:
70
+ if name and os.path.exists(name):
71
+ os.unlink(name)
72
+
73
+
74
+ def read_state(path):
75
+ state = json.loads(path.read_text(encoding="utf-8"))
76
+ if (not isinstance(state, dict) or state.get("schema_version") != 1
77
+ or state.get("profile") not in PROFILES
78
+ or not isinstance(state.get("evidence"), dict)
79
+ or not isinstance(state.get("handoffs"), dict)
80
+ or not all(isinstance(state.get(key), list)
81
+ for key in ("artifacts", "acceptance_refs", "required", "repairs"))
82
+ or type(state.get("max_repairs")) is not int or state["max_repairs"] < 0):
83
+ raise ValueError("invalid task state schema")
84
+ return state
85
+
86
+
87
+ def nonempty(value):
88
+ if not value.strip():
89
+ raise argparse.ArgumentTypeError("value must not be empty")
90
+ return value
91
+
92
+
93
+ def status(state, base):
94
+ checks = {}
95
+ for name in sorted(set(state["required"]) | set(state["evidence"])):
96
+ record = state["evidence"].get(name)
97
+ reasons = []
98
+ if record is None:
99
+ result = "not_tested"
100
+ reasons.append("missing evidence")
101
+ else:
102
+ result = record["result"]
103
+ for dependency in record["dependencies"]:
104
+ actual = digest(base, dependency["path"])
105
+ if actual is None:
106
+ reasons.append("missing: " + dependency["path"])
107
+ elif actual != dependency["sha256"]:
108
+ reasons.append("changed: " + dependency["path"])
109
+ checks[name] = {"result": result, "valid": not reasons, "reasons": reasons,
110
+ "required": name in state["required"]}
111
+ missing_refs = [value for value in state["artifacts"] + state["acceptance_refs"]
112
+ if digest(base, value) is None]
113
+ considered = state["required"]
114
+ accepted = bool(considered) and not missing_refs and all(
115
+ checks[name]["valid"] and checks[name]["result"] == "pass" for name in considered)
116
+ failed = any(checks[name]["result"] == "fail" for name in considered)
117
+ return {"profile": state["profile"], "acceptance": "pass" if accepted else
118
+ ("fail" if failed else "not_tested"), "checks": checks,
119
+ "missing_refs": missing_refs, "repairs_used": len(state["repairs"]),
120
+ "max_repairs": state["max_repairs"],
121
+ "repairs_remaining": max(0, state["max_repairs"] - len(state["repairs"])),
122
+ "handoffs": state["handoffs"]}, accepted
123
+
124
+
125
+ def main():
126
+ parser = argparse.ArgumentParser(description=__doc__)
127
+ commands = parser.add_subparsers(dest="command", required=True)
128
+ init = commands.add_parser("init", help="create state; refuses an existing file")
129
+ init.add_argument("--profile", choices=PROFILES, default="standard")
130
+ init.add_argument("--artifact", action="append", default=[])
131
+ init.add_argument("--acceptance", action="append", default=[])
132
+ init.add_argument("--require", action="append", type=nonempty, default=[])
133
+ init.add_argument("--max-repairs", type=natural)
134
+ evidence = commands.add_parser("evidence", help="record a check and its content dependencies")
135
+ evidence.add_argument("--name", required=True, type=nonempty)
136
+ evidence.add_argument("--result", required=True, choices=RESULTS)
137
+ evidence.add_argument("--depends", action="append", default=[])
138
+ evidence.add_argument("--report")
139
+ evidence.add_argument("--note", default="")
140
+ inspect = commands.add_parser("status", help="diagnostic JSON status")
141
+ inspect.add_argument("--strict", action="store_true", help="exit 1 unless required checks pass; optional checks never block")
142
+ repair = commands.add_parser("repair", help="consume one repair round before doing the work")
143
+ repair.add_argument("--reason", required=True, type=nonempty)
144
+ handoff = commands.add_parser("handoff", help="persist separate compact build/fix handoffs")
145
+ handoff.add_argument("--phase", required=True, choices=("build", "fix"))
146
+ handoff.add_argument("--summary", required=True, type=nonempty)
147
+ handoff.add_argument("--next", action="append", type=nonempty, default=[])
148
+ handoff.add_argument("--ref", action="append", default=[])
149
+ for command in (init, evidence, inspect, repair, handoff):
150
+ command.add_argument("--state", type=Path, required=True)
151
+ args = parser.parse_args()
152
+ path = args.state.resolve()
153
+ base = path.parent
154
+ try:
155
+ if args.command == "init":
156
+ state = {"schema_version": 1, "profile": args.profile,
157
+ "artifacts": list(dict.fromkeys(ref(base, p) for p in args.artifact)),
158
+ "acceptance_refs": list(dict.fromkeys(ref(base, p) for p in args.acceptance)),
159
+ "required": list(dict.fromkeys(args.require)), "evidence": {},
160
+ "max_repairs": args.max_repairs if args.max_repairs is not None
161
+ else PROFILES[args.profile], "repairs": [],
162
+ "handoffs": {"build": None, "fix": None}}
163
+ write_state(path, state, create=True)
164
+ else:
165
+ state = read_state(path)
166
+ if args.command == "status":
167
+ report, accepted = status(state, base)
168
+ print(json.dumps(report, allow_nan=False))
169
+ return 1 if args.strict and not accepted else 0
170
+ if args.command == "evidence":
171
+ paths = [ref(base, p) for p in args.depends] + state["acceptance_refs"]
172
+ if args.report:
173
+ paths.append(ref(base, args.report))
174
+ paths = list(dict.fromkeys(paths))
175
+ if args.result != "not_tested" and not paths:
176
+ raise ValueError("pass/fail evidence needs at least one --depends, --report, or acceptance reference")
177
+ dependencies = [{"path": p, "sha256": digest(base, p)} for p in paths]
178
+ if args.result != "not_tested" and any(d["sha256"] is None for d in dependencies):
179
+ raise ValueError("pass/fail evidence dependencies must be existing regular files")
180
+ state["evidence"][args.name] = {"result": args.result, "dependencies": dependencies,
181
+ "report": ref(base, args.report) if args.report else None,
182
+ "note": args.note}
183
+ elif args.command == "repair":
184
+ if len(state["repairs"]) >= state["max_repairs"]:
185
+ raise ValueError("repair limit reached; stop and report the remaining failure")
186
+ state["repairs"].append({"round": len(state["repairs"]) + 1, "reason": args.reason})
187
+ elif args.command == "handoff":
188
+ state["handoffs"][args.phase] = {"summary": args.summary, "next": args.next,
189
+ "refs": [ref(base, p) for p in args.ref]}
190
+ write_state(path, state)
191
+ print(json.dumps(state, allow_nan=False))
192
+ return 0
193
+ except (OSError, ValueError, KeyError, TypeError) as error:
194
+ print("task_state: " + str(error), file=sys.stderr)
195
+ return 2
196
+
197
+
198
+ if __name__ == "__main__":
199
+ sys.exit(main())
@@ -0,0 +1,105 @@
1
+ # Declarative instructions for the calling agent/manager; not executable automation.
2
+ version: 1
3
+ name: blender-asset
4
+ purpose: Choose the smallest workflow that meets the task's acceptance criteria.
5
+ entry: blender-asset
6
+ contract:
7
+ required:
8
+ - brief and authoritative input/output paths
9
+ - profile with reason and measurable acceptance criteria
10
+ - required evidence IDs, views/checks and task-specific tolerances
11
+ - allowed changes, units/axes/origin and deliverables
12
+ optional:
13
+ - reference priority and intentional deviations
14
+ - source motion, root-motion mode and expected clip names
15
+ - target engine, intended gameplay size and deformation constraints
16
+ - local model/effort preset and usage/render budget
17
+ selection:
18
+ owner: calling agent or manager
19
+ rules:
20
+ - Honor an explicitly requested profile; never silently weaken its required gates.
21
+ - Choose quick for a simple prop, prototype, material/origin edit or isolated repair.
22
+ - Choose standard for reference matching, modular assets or ordinary game-ready delivery.
23
+ - Choose production for strict fidelity, complex assemblies, critical deformation or dependent deliverables.
24
+ - Classify by acceptance risk and dependencies, not polygon count alone.
25
+ - Record the choice briefly; only ask about a missing decision that changes acceptance.
26
+ profiles:
27
+ quick:
28
+ stages: [contract, build, technical_checks, affected_views, conditional_review, delivery]
29
+ reviewer: optional_only_when_requested_or_material_uncertainty
30
+ max_repairs: 1
31
+ standard:
32
+ stages: [contract, proportions, build, reference_comparison_if_applicable, technical_checks, conditional_review, delivery]
33
+ reviewer: required_when_requested_or_identity_or_acceptance_remains_uncertain
34
+ max_repairs: 2
35
+ production:
36
+ stages: [contract, blockout_checkpoint, refine, technical_checks, independent_review, delivery]
37
+ reviewer: required
38
+ max_repairs: 3
39
+ stage_owners:
40
+ contract: calling agent records criteria, required evidence IDs and repair limit before building
41
+ proportions: builder establishes dimensions and primary forms before detail
42
+ blockout_checkpoint: compare primary forms to acceptance; resolve material ambiguity before refining
43
+ build: blender-asset, or blender-reference-model when matching a supplied reference
44
+ refine: same builder capability with the accepted blockout and scoped changes
45
+ technical_checks: builder runs only the contract's relevant geometry, material, motion and export checks
46
+ reference_comparison_if_applicable: blender-reference-model produces matched views and identity-detail evidence
47
+ affected_views: builder renders only views needed to judge the changed region and its dependencies
48
+ conditional_review: visual-reviewer if the profile's condition holds; otherwise record why unnecessary
49
+ independent_review: visual-reviewer receives a compact evidence packet in a fresh context
50
+ delivery: calling agent evaluates every required criterion against current evidence
51
+ capability_additions:
52
+ reference:
53
+ when: task requires fidelity to a supplied reference
54
+ capability: blender-reference-model
55
+ rule: Supply view priorities and tolerances; no universal silhouette IoU target.
56
+ motion:
57
+ when: task rigs or retargets existing source motion onto an existing character
58
+ capability: blender-mocap-retarget
59
+ rule: Preserve the authoritative model; add source comparison, rest-pose identity and motion checks without restarting modeling.
60
+ export:
61
+ when: task requests an interchange or engine-ready deliverable
62
+ tools: blender-mocap-retarget/scripts/verify_gltf.py; godot_verify.py only for a Godot target
63
+ rule: Declare expected clip set and required geometry/skin/rig; re-import the exported artifact and run target checks when required.
64
+ review:
65
+ default_team: none
66
+ production_reviewers: 1
67
+ packet:
68
+ - brief, priorities, intentional deviations and acceptance criteria
69
+ - reference/source images when relevant, current evidence and intended display size
70
+ - changed regions, unresolved findings and missing views/checks
71
+ rules:
72
+ - Do not send full session transcripts, repeated skill text or builder code.
73
+ - If image viewing or an independent agent is unavailable, record review as not_tested.
74
+ - A required review that cannot run blocks acceptance; deliver partial progress and identify the missing capability.
75
+ - A Quick or Standard reviewer trigger adds a gate without automatically escalating the entire profile.
76
+ repair:
77
+ owner: calling agent
78
+ rules:
79
+ - Initialize task_state.py with the profile limit before building and reserve each repair before starting it.
80
+ - Each repair targets the highest-priority unmet criteria; preserve successful work.
81
+ - A separate fix session resumes from task state, asset/script paths and current findings, not the full transcript.
82
+ - Reuse evidence only if all its declared input dependencies still match; hashes cannot infer omitted dependencies.
83
+ - After a change, rerun affected checks and views, including required reviewer findings affected by the change.
84
+ - Include asset, script, task contract, references, render settings and export inputs as appropriate dependencies.
85
+ - If a repair makes no material progress or the limit is exhausted, stop repairing and report remaining defects with a scoped next step.
86
+ - Never reset task state or raise a limit silently to continue; a further work budget requires a user decision.
87
+ - Escalate profile only when new acceptance risk requires it; retain valid evidence and consumed rounds.
88
+ usage:
89
+ rules:
90
+ - The coordinator is the sole writer of task state and usage journals; serialize writes and collect child metrics instead of concurrent appends.
91
+ - Record separate create, review, fix and delivery phases with model, effort and parent/child call identity when available.
92
+ - Record own per-call usage only; do not add child usage to an already inclusive parent total.
93
+ - Record tokens, API/tool calls, render count/time and acceptance; unknown metrics remain null, never zero.
94
+ - Treat cost estimates as advisory unless complete live metering exists; report coverage and price source.
95
+ - Stop new work when a declared measurable render/time/token budget is exhausted; report remaining criteria and request a revised budget.
96
+ - When a required hard budget cannot be metered, report that limitation before proceeding under it; do not infer room from unknown usage.
97
+ - Select model and effort from consumer configuration; do not assume a cheaper model achieves equal quality.
98
+ - Prefer one builder and bounded fixes; delegate only independent work likely to justify its context and review cost.
99
+ completion:
100
+ rules:
101
+ - All required checks and reviews must pass with current evidence; not_tested or stale evidence blocks acceptance.
102
+ - Visual approval cannot replace a technical or engine gate; technical pass cannot replace required visual review.
103
+ - Optional defects and untested optional capabilities are disclosed without forcing extra rounds.
104
+ - Deliver editable source, persisted scripts, requested exports, evidence summary and measured usage coverage.
105
+ - Record outcome as accepted, partial or blocked; never claim savings without comparable accepted-task measurements.
@@ -5,18 +5,27 @@ description: Rig, skin and retarget an existing motion-capture or library clip (
5
5
 
6
6
  # Blender Mocap Retarget
7
7
 
8
- ## Outcome
8
+ ## Scope
9
9
 
10
- The existing character performs the source motion on its own skeleton, with its proportions,
11
- materials and modular parts unchanged. Feet plant without sliding or sinking, limbs clear the
12
- body and equipment, the loop is seamless, and the export plays exactly the intended clips in the
13
- target engine.
10
+ Rig, skin and retarget source motion onto an existing character while preserving its appearance.
11
+ Work to the task's motion, root displacement, loop and delivery criteria. Profile selection,
12
+ independent review and bounded repairs are owned by `../blender-asset/workflows/asset.yml`;
13
+ adding animation does not require restarting the modeling workflow.
14
+
15
+ ## Prerequisites
16
+
17
+ - Install the complete `blender-3d` bundle; its sibling skills and workflow are required context.
18
+ - Install [Blender](https://www.blender.org/download/); verify `blender --version`.
19
+ - Install [Python 3](https://www.python.org/downloads/) and `python3 -m pip install Pillow numpy`
20
+ for sibling [Pillow](https://pillow.readthedocs.io/) / [NumPy](https://numpy.org/) image helpers; verify `python3 -c "import PIL, numpy"`.
21
+ - Only for a required Godot check: install [Godot 4](https://godotengine.org/download/) and
22
+ verify `godot --version`; set `GODOT` if the executable is not on `PATH`.
23
+ - Resolve script paths from their skill directories; keep executable paths in consumer config.
14
24
 
15
25
  ## Invariants
16
26
 
17
27
  - Do not remodel. The rest pose must render identically to the unrigged model: render
18
- baseline views before rigging and diff them against rest-pose renders afterwards (Method
19
- steps 1 and 7). If deformation truly needs geometry (for example extra loops at joints), add it
28
+ baseline views before rigging and diff them against rest-pose renders afterwards. If deformation truly needs geometry (for example extra loops at joints), add it
20
29
  without changing the rest-pose renders, and show the diff.
21
30
  - Build the armature on the character's own joints. Never stretch the character to the source
22
31
  skeleton; absorb differences in the retarget.
@@ -36,42 +45,49 @@ Scripts in this skill's `scripts/` folder (Blender scripts run with `blender -b
36
45
  | `check_motion.py` | Ground penetration, planted-foot slide, interpenetration beyond the rest baseline, loop seam |
37
46
  | `render_frames.py` | Frame renders from several angles with following cameras and a checker floor |
38
47
  | `export_gltf_clip.py` | GLB export with exactly one clip per named action |
39
- | `verify_gltf.py` | Re-import the export; report meshes, skinned meshes and bones; fail on missing clips or clips not starting at frame 0 |
48
+ | `verify_gltf.py` | Re-import; check requested mesh/skin/rig requirements and clip timing; `--exact-clips` rejects extra or missing original clip names |
40
49
  | `godot_verify.py` | Optional: headless Godot import of the GLB, checking meshes, bones, clips and key timing |
41
50
 
42
51
  The sibling skill's scripts are used too, at `../blender-reference-model/scripts/` relative to
43
52
  this skill's folder (not the working directory): `render_views.py` and `diff_renders.py` for the
44
53
  rest-pose check, and `contact_sheet.py` to tile frame renders.
45
54
 
46
- ## Method That Works
47
-
48
- 1. Before touching the model, render baseline views with `render_views.py` (the model's
49
- `ref_spec.json`, or any spec whose views frame the character) into a `before/` folder.
50
- 2. Inspect the source. Plan from its fps, range, rest pose (T or A), root motion and loop
51
- structure (library walks often end on the first pose plus one stride).
52
- 3. Build the rig with source-compatible bone names (for example Mixamo names without the
53
- `mixamorig:` prefix) at the character's joints.
54
- 4. Retarget each bone's world-space rotation relative to its rest pose, so differing rest poses
55
- cancel out. Scale root motion by the leg-length or hip-height ratio: that scale is what stops
56
- planted feet from sliding. Solve feet with two-bone IK (soft limit, no knee pop) toward the
57
- scaled source ankle, and add a ground pass that keeps soles on the floor while planted.
58
- 5. For bulky or equipped characters, add an outward arm offset (larger on the back-swing) and
59
- damp long clavicles, so arms clear the torso and belt kit. Let hip-mounted props swing with the
60
- thigh through socket bones.
61
- 6. Skin with blend zones at shoulders, elbows, wrists, fingers, hips, knees, ankles and neck.
62
- Keep hair and beards rigid to the head.
63
- 7. Render the rigged model with the same spec (armatures render in rest pose by default) and run
64
- `diff_renders.py before/ after/`. It must report the views identical within tolerance.
65
- 8. Iterate with `check_motion.py` and frame renders from front, side, 3/4, back and close-ups at
66
- the hips, shoulders and feet. Targets that worked: ground within about 3 mm, planted-foot slide
67
- of a few mm per frame, no interpenetration beyond the rest baseline, zero rotation difference
68
- at the loop seam.
69
- 9. Export with `export_gltf_clip.py`, then run `verify_gltf.py`, and `godot_verify.py` when the
70
- target is Godot.
71
- 10. Have the `visual-reviewer` agent review contact sheets of the motion before handing over.
72
- Include a contact sheet of the source clip at the same frames when you can render it, plus
73
- the user's requirements. If the reviewer cannot run or cannot view images, say so in the
74
- evidence.
55
+ ## Procedure
56
+
57
+ Apply Stop Conditions immediately during every step; return the blocked work and evidence gaps.
58
+
59
+ 1. Capture baseline views with the character's spec (or a spec that frames the asset), using
60
+ reproducible render settings. Identify authoritative asset, source clip, output and allowed edits.
61
+ 2. Inspect source fps, range, rest pose, root motion and loop structure. Select and record root
62
+ motion deliberately: preserve source distance, scale proportionally, or make in-place.
63
+ Do not change the requested displacement merely to hide foot slide.
64
+ 3. Build the rig on the character's joints and retarget rest-relative rotations. Account for
65
+ source offsets and scale. Use foot constraints/IK only as needed; compare source and target
66
+ at aligned phase/time, including a non-looping end when relevant.
67
+ 4. Skin deforming regions with appropriate blend zones; bind rigid attachments to their intended
68
+ bones/sockets. Correct observed collisions with the smallest local adjustment. Outward arm
69
+ offsets, clavicle damping and prop swing are optional measured corrections, never defaults;
70
+ preserve source performance and verify each correction against it.
71
+ 5. Repeat the baseline rest-pose renders with identical settings and run `diff_renders.py`.
72
+ A difference outside the agreed tolerance fails appearance preservation.
73
+ 6. Run `check_motion.py` on named feet, pairs and frame range. Record coverage and statuses.
74
+ Choose task-specific ground, planted-slide, overlap and loop tolerances; do not apply walking
75
+ or looping criteria to a jump or non-looping clip. Strict mode needs at least one threshold
76
+ and fails unmet thresholds or missing requested coverage. Run with `--python-exit-code 1`.
77
+ 7. Inspect affected frame contact sheets at the intended size, including representative contacts,
78
+ transitions and extremes. Missing views cannot prove motion continuity; report sampling limits.
79
+ 8. For requested exports, isolate intended actions and export. Use `verify_gltf.py` with
80
+ `--expect-clips Walk,Run --exact-clips` (substitute the contract's exact names) and the required
81
+ `--require-mesh`, `--require-skin`, `--require-rig` flags. For a static export the expected clip
82
+ set is empty. Run target-engine checks when required by the contract.
83
+ 9. Return motion evidence and unresolved defects after this stage. The companion workflow
84
+ decides review and any further reserved repair; it does not require fresh modeling.
85
+
86
+ ## Stop Conditions
87
+
88
+ Missing authoritative assets/source, conflicting displacement requirements, or a required
89
+ appearance-changing edit outside scope blocks the affected work. Mark missing tool/check
90
+ coverage `not_tested`; never claim delivery acceptance with a missing required check or review.
75
91
 
76
92
  ## Known Pitfalls
77
93
 
@@ -89,8 +105,11 @@ rest-pose check, and `contact_sheet.py` to tile frame renders.
89
105
  - Overlap tests between adjacent regions of one mesh report shared edges. Pair regions that
90
106
  should never touch.
91
107
 
92
- ## Evidence To Report
108
+ ## Output Contract
109
+
110
+ `Skill: blender-mocap-retarget - output below`
93
111
 
94
- Source facts, the rest-pose identity check, `check_motion.py` results, contact sheets from
95
- several angles, the export verification output, the review findings with their resolution, and
96
- any motion that could only be judged in the engine.
112
+ Report source facts and root-motion mode; editable asset and persisted script; rest-pose diff;
113
+ motion-check statuses, thresholds and sampled frames/objects; source/target contact sheets;
114
+ requested export/engine verification; unresolved defects and missing evidence. Distinguish
115
+ technical pass from visual judgment and engine checks that have not run.
@@ -15,23 +15,52 @@ regions that should never touch (arm vs belt kit, arm vs torso front) rather tha
15
15
  A part is an object name, optionally narrowed to polygons whose dominant vertex group contains a
16
16
  substring: "Shirt@LeftArm" = Shirt polygons weighted mostly to a group containing "LeftArm".
17
17
  Judge motion quality from playback renders too; these numbers catch regressions, not style.
18
+
19
+ Use --strict with one or more task-defined --max-ground-penetration-mm,
20
+ --max-planted-slide-mm-per-frame, --max-extra-overlap-tris, or --max-loop-rotation-deg
21
+ thresholds to fail violations and missing requested coverage. Without --strict, diagnostic
22
+ exit behavior is preserved. JSON checks distinguish measured coverage from acceptance:
23
+ no threshold or missing samples is not_tested, never a passing acceptance decision.
24
+ Pass Blender --python-exit-code 1 before --python to propagate Python failures.
18
25
  """
19
26
  import argparse
20
27
  import json
21
28
  import math
29
+ import re
22
30
  import sys
23
31
 
24
32
  import bpy
25
33
  from mathutils.bvhtree import BVHTree
26
34
 
27
35
  argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
36
+
37
+
38
+ def finite(value):
39
+ number = float(value)
40
+ if not math.isfinite(number):
41
+ raise argparse.ArgumentTypeError("must be finite")
42
+ return number
43
+
44
+
45
+ def nonnegative(value):
46
+ number = finite(value)
47
+ if number < 0:
48
+ raise argparse.ArgumentTypeError("must be nonnegative")
49
+ return number
50
+
51
+
28
52
  p = argparse.ArgumentParser()
29
53
  p.add_argument("--rig", required=True)
30
54
  p.add_argument("--feet", default="", help="comma-separated parts that touch the floor")
31
55
  p.add_argument("--pairs", default="", help="semicolon-separated A:B part pairs to test for overlap")
32
56
  p.add_argument("--frames", help="START-END; default is the scene range")
33
- p.add_argument("--contact-mm", type=float, default=6.0, help="height that counts as floor contact")
34
- p.add_argument("--ground-z", type=float, default=0.0)
57
+ p.add_argument("--contact-mm", type=nonnegative, default=6.0, help="height that counts as floor contact")
58
+ p.add_argument("--ground-z", type=finite, default=0.0)
59
+ p.add_argument("--strict", action="store_true", help="fail requested thresholds when exceeded or untested; requires at least one threshold")
60
+ p.add_argument("--max-ground-penetration-mm", type=nonnegative)
61
+ p.add_argument("--max-planted-slide-mm-per-frame", type=nonnegative)
62
+ p.add_argument("--max-extra-overlap-tris", type=nonnegative)
63
+ p.add_argument("--max-loop-rotation-deg", type=nonnegative)
35
64
  p.add_argument("--json")
36
65
  args = p.parse_args(argv)
37
66
 
@@ -39,9 +68,22 @@ scene = bpy.context.scene
39
68
  rig = bpy.data.objects.get(args.rig)
40
69
  if rig is None or rig.type != "ARMATURE":
41
70
  raise SystemExit(f"--rig: no armature object named {args.rig}")
42
- f0, f1 = (int(x) for x in args.frames.split("-")) if args.frames else (scene.frame_start, scene.frame_end)
71
+ if args.frames:
72
+ match = re.fullmatch(r"(-?\d+)-(-?\d+)", args.frames)
73
+ if not match:
74
+ p.error("--frames must be START-END with integer frames")
75
+ f0, f1 = map(int, match.groups())
76
+ else:
77
+ f0, f1 = scene.frame_start, scene.frame_end
78
+ if f1 < f0:
79
+ p.error("--frames end must be at least start")
80
+ frame_property = scene.bl_rna.properties["frame_current"]
81
+ if f0 < frame_property.hard_min or f1 > frame_property.hard_max:
82
+ p.error(f"--frames must be within Blender's range {frame_property.hard_min:g}-{frame_property.hard_max:g}")
43
83
  feet = [s for s in args.feet.split(",") if s]
44
84
  pairs = [tuple(pair.split(":")) for pair in args.pairs.split(";") if pair]
85
+ if any(len(pair) != 2 or not all(pair) for pair in pairs):
86
+ p.error("--pairs must contain A:B entries separated by semicolons")
45
87
  contact = args.contact_mm / 1000.0
46
88
 
47
89
 
@@ -56,7 +98,10 @@ def parse(part):
56
98
  def select_polys(ob, group):
57
99
  me = ob.data
58
100
  if not group:
59
- return [list(poly.vertices) for poly in me.polygons]
101
+ chosen = [list(poly.vertices) for poly in me.polygons]
102
+ if not chosen:
103
+ raise SystemExit(f"no polygons in {ob.name}")
104
+ return chosen
60
105
  names = {g.index: g.name for g in ob.vertex_groups}
61
106
  chosen = []
62
107
  for poly in me.polygons:
@@ -141,22 +186,59 @@ for pair in pairs:
141
186
  "first_frames": [f for f, _ in hits[pair]][:12]}
142
187
 
143
188
  act = rig.animation_data.action if rig.animation_data else None
144
- if act:
145
- a0, a1 = (int(round(v)) for v in act.frame_range)
189
+ loop_rotation = None
190
+ if act and rig.pose.bones and act.frame_range[1] > act.frame_range[0]:
191
+ a0, a1 = (float(v) for v in act.frame_range)
146
192
 
147
193
  def pose(frame):
148
- scene.frame_set(frame)
194
+ whole_frame = math.floor(frame)
195
+ scene.frame_set(whole_frame, subframe=frame - whole_frame)
149
196
  return {pb.name: (pb.matrix_basis.to_quaternion(), pb.matrix_basis.to_translation()) for pb in rig.pose.bones}
150
197
 
151
198
  pa, pb_ = pose(a0), pose(a1)
152
199
  worst = max(pa, key=lambda n: pa[n][0].rotation_difference(pb_[n][0]).angle)
153
200
  root = next(b.name for b in rig.data.bones if b.parent is None)
201
+ loop_rotation = math.degrees(pa[worst][0].rotation_difference(pb_[worst][0]).angle)
154
202
  report["loop_seam"] = {"action": act.name, "action_range": [a0, a1],
155
- "max_rotation_diff_deg": round(math.degrees(pa[worst][0].rotation_difference(pb_[worst][0]).angle), 3),
203
+ "max_rotation_diff_deg": round(loop_rotation, 3),
156
204
  "worst_bone": worst, "root_bone": root,
157
205
  "root_delta_bone_space_m": [round(v, 4) for v in (pb_[root][1] - pa[root][1])]}
158
206
 
207
+ # Keep legacy diagnostic metrics above. Decisions use full precision, not rounded display values.
208
+ # Slide coverage requires a contact transition for EVERY requested foot.
209
+ measurements = {
210
+ "ground": (args.max_ground_penetration_mm,
211
+ max((max(0.0, -z * 1000) for values in ground.values() for _, z in values), default=None),
212
+ bool(feet), "no feet supplied"),
213
+ "slide": (args.max_planted_slide_mm_per_frame,
214
+ max((v * 1000 for values in slide.values() for _, v in values), default=None),
215
+ bool(feet) and all(slide[foot] for foot in feet),
216
+ "no planted contact transitions for: " + ", ".join(foot for foot in feet if not slide[foot]) if feet else "no feet supplied"),
217
+ "interpenetration": (args.max_extra_overlap_tris,
218
+ max((n for values in hits.values() for _, n in values), default=0) if pairs else None,
219
+ bool(pairs), "no pairs supplied"),
220
+ "loop_seam": (args.max_loop_rotation_deg, loop_rotation, loop_rotation is not None,
221
+ "no active action spanning distinct frames with pose bones"),
222
+ }
223
+ report["checks"] = {}
224
+ for name, (threshold, observed, tested, reason) in measurements.items():
225
+ requested = threshold is not None
226
+ status = "not_tested" if not tested or not requested else ("pass" if observed <= threshold else "fail")
227
+ check = {"status": status, "tested": tested, "requested": requested, "threshold": threshold, "observed": observed}
228
+ if not tested:
229
+ check["reason"] = reason
230
+ elif not requested:
231
+ check["reason"] = "no acceptance threshold supplied"
232
+ report["checks"][name] = check
233
+ requested_checks = [check for check in report["checks"].values() if check["requested"]]
234
+ report["strict"] = args.strict
235
+ report["status"] = ("fail" if any(check["status"] == "fail" for check in requested_checks)
236
+ or (args.strict and (not requested_checks or any(check["status"] != "pass" for check in requested_checks)))
237
+ else "pass" if requested_checks and all(check["status"] == "pass" for check in requested_checks)
238
+ else "not_tested")
239
+
159
240
  print(json.dumps(report, indent=2))
160
241
  if args.json:
161
242
  with open(args.json, "w") as f:
162
243
  json.dump(report, f, indent=2)
244
+ sys.exit(1 if args.strict and report["status"] != "pass" else 0)