Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(figures): build the first society figure from a CC0 rig through a contract gate

rubenluetke10-beepeabca1f96371
diff --git a/.gitignore b/.gitignore
index 0cb931b138..dbfe943153 100644
--- a/.gitignore
+++ b/.gitignore
@@ -464,3 +464,6 @@ scripts/ci/privacy_gate/references/secret-allowlist.tsv
# the machine that ran the tests into its header, so it is a personal-data leak
# as much as it is a cache. Regenerated on demand; never committed.
.hypothesis/
+
+# Figure build: fetched CC0 sources and generated sheets (scripts/figures/README.md)
+scripts/figures/cache/
diff --git a/jarvis/ui/web/frontend/src/assets/society/figures/SOURCES.md b/jarvis/ui/web/frontend/src/assets/society/figures/SOURCES.md
new file mode 100644
index 0000000000..e267a11450
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/assets/society/figures/SOURCES.md
@@ -0,0 +1,13 @@
+# Figure assets — provenance ledger
+
+One row per shipped file (docs/agent-society/character-pipeline.md §11, gate check 15). Every
+GLB here is produced by `scripts/figures/build_figures.py` from the recorded source; nothing is
+hand-exported. Sources are fetched by URL into `scripts/figures/cache/` and verified by sha256
+before the build touches them (`scripts/figures/sources/*.json`).
+
+| File | Source | License | Source sha256 | What the build changed |
+|---|---|---|---|---|
+| `biped-medium.glb` | KayKit Character Pack: Adventurers 1.0 — `Rogue.glb` (Kay Lousberg, kaylousberg.com) | CC0-1.0 | `e825437cd4d2ee9c1960b517a74a69101e33eb409ae7fa8cedc7134a998fbb7d` | kept the six body meshes, joined them into one; dropped 18 IK/control bones; renamed 23 deform bones to the contract; kept 9 of 76 clips, renamed, root XZ zeroed, loops closed; faces re-UV'd onto the 16-cell palette strip of a generated 128×128 sheet; `FWD` marker; extras |
+
+Licenses recorded at fetch time (2026-09-01): CC0 — free for personal, educational and commercial
+use, no attribution required. Credit is given anyway: KayKit by Kay Lousberg.
diff --git a/jarvis/ui/web/frontend/src/assets/society/figures/biped-medium.glb b/jarvis/ui/web/frontend/src/assets/society/figures/biped-medium.glb
new file mode 100644
index 0000000000..1a69afebb4
Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/biped-medium.glb differ
diff --git a/scripts/ci/check_society_figures.py b/scripts/ci/check_society_figures.py
new file mode 100644
index 0000000000..5996650d26
--- /dev/null
+++ b/scripts/ci/check_society_figures.py
@@ -0,0 +1,372 @@
+#!/usr/bin/env python
+"""Figure-asset gate — every shipped society figure honours the character contract.
+
+Why this exists: the agent society's island renders any character through ONE
+runtime that knows archetypes, bone names, clip names and a forward axis
+(docs/agent-society/character-pipeline.md). A figure that faces -Z walks
+backwards; a clip with root motion makes the feet slide; a mirrored node
+turns the shading inside out; a hips-rooted rig breaks the heading maths. None
+of that is caught by TypeScript, a build or a unit test — only by reading the
+binary and checking it against ``scripts/figures/contract.json``. So this gate
+does exactly that, with the stdlib only (``scripts/figures/glb_tools.py``), and
+runs in pre-commit, in CI, and at the end of every build.
+
+Exit codes: 0 = every figure passes, 1 = a violation, 78 = nothing to check
+(no ``.glb`` shipped yet), so callers can treat "could not measure" as neutral.
+Covered by ``tests/unit/ui/test_society_figures_gate.py``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import importlib.util
+import json
+import math
+import sys
+from pathlib import Path
+
+_REPO = Path(__file__).resolve().parents[2]
+_FIGURES = _REPO / "jarvis" / "ui" / "web" / "frontend" / "src" / "assets" / "society" / "figures"
+_CONTRACT = _REPO / "scripts" / "figures" / "contract.json"
+_TOOLS = _REPO / "scripts" / "figures" / "glb_tools.py"
+
+NEAREST = 9728
+FORBIDDEN_EXTENSIONS = {
+ "KHR_draco_mesh_compression",
+ "EXT_meshopt_compression",
+ "KHR_texture_basisu",
+}
+ALLOWED_ATTRIBUTES = {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"}
+EXIT_SKIPPED = 78
+
+
+def _load_tools():
+ if "glb_tools" in sys.modules:
+ return sys.modules["glb_tools"]
+ spec = importlib.util.spec_from_file_location("glb_tools", _TOOLS)
+ mod = importlib.util.module_from_spec(spec)
+ assert spec and spec.loader
+ # Registered BEFORE exec: dataclasses resolve their annotations through
+ # sys.modules[cls.__module__], which is None for a loose module (3.14).
+ sys.modules["glb_tools"] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def load_contract(path: Path = _CONTRACT) -> dict:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def _skin_joint_names(doc: dict, skin: dict) -> list[str]:
+ return [doc["nodes"][j].get("name", "") for j in skin["joints"]]
+
+
+def _top_joints(doc: dict, skin: dict, gt) -> list[str]:
+ joints = set(skin["joints"])
+ parents = gt.parent_map(doc)
+ return [doc["nodes"][j].get("name", "") for j in skin["joints"] if parents[j] not in joints]
+
+
+def check_file(
+ path: Path,
+ contract: dict | None = None,
+ sources_md: Path | None = None,
+) -> list[str]:
+ """Every contract violation of one GLB, as human-readable lines (empty = pass)."""
+ gt = _load_tools()
+ contract = contract or load_contract()
+ limits = contract["limits"]
+ problems: list[str] = []
+ try:
+ glb = gt.read_glb(path)
+ except (ValueError, OSError) as exc: # a broken file is a failed gate, not a crash
+ return [f"unreadable: {exc}"]
+ doc = glb.doc
+
+ # 1 — extras
+ figure = gt.figure_extras(doc)
+ part = gt.part_extras(doc)
+ extras = figure or part
+ if extras is None:
+ return ["no asset.extras.jarvis_figure / jarvis_part block (contract §4.2)"]
+ if extras.get("contract") != contract["contract"]:
+ problems.append(f"contract version {extras.get('contract')!r} != {contract['contract']}")
+ archetype_name = extras.get("archetype")
+ archetype = contract["archetypes"].get(archetype_name)
+ if archetype is None:
+ return problems + [f"unknown archetype {archetype_name!r}"]
+ if figure and figure.get("variant") not in archetype["variants"]:
+ problems.append(f"unknown variant {figure.get('variant')!r} for {archetype_name}")
+ if figure and figure.get("forward") != "+Z":
+ problems.append(f"forward must be '+Z', got {figure.get('forward')!r}")
+
+ nodes = doc.get("nodes", [])
+ worlds = gt.world_matrices(doc)
+ names = gt.node_index_by_name(doc)
+
+ # 2 — FWD marker
+ if figure:
+ if "FWD" not in names:
+ problems.append("no FWD marker node (contract §4.1)")
+ else:
+ m = worlds[names["FWD"]]
+ if m[14] < 0.9:
+ problems.append(f"FWD marker sits at z={m[14]:.2f}; the figure faces the wrong way")
+
+ # 3 — scales
+ eps = limits["scale_epsilon"]
+ for node in nodes:
+ _t, _r, s = gt.node_local_trs(node)
+ if any(v <= 0 for v in s):
+ problems.append(f"node {node.get('name')!r} has a negative/zero scale {s}")
+ elif any(abs(v - 1.0) > eps for v in s):
+ problems.append(f"node {node.get('name')!r} carries a scale {s}; apply transforms")
+
+ # 5 — skeleton
+ skins = doc.get("skins", [])
+ skin = skins[0] if skins else None
+ if figure and skin is None:
+ problems.append("figure has no skin")
+ if skin is not None:
+ joint_names = _skin_joint_names(doc, skin)
+ expected = set(archetype["bones"])
+ allowed = expected | set(archetype.get("optional_bones", []))
+ have = set(joint_names)
+ if figure:
+ missing = expected - have
+ extra = have - allowed
+ if missing:
+ problems.append(f"missing bones {sorted(missing)}")
+ if extra:
+ problems.append(f"unexpected bones {sorted(extra)}")
+ tops = _top_joints(doc, skin, gt)
+ if tops != ["root"]:
+ problems.append(f"top joint must be exactly ['root'], got {tops}")
+ if part and not have <= allowed:
+ problems.append(f"part binds to bones outside the archetype: {sorted(have - allowed)}")
+
+ # 4 — origin, height, feet
+ skinned = gt.skinned_mesh_nodes(doc)
+ if figure and skinned:
+ lo = [math.inf] * 3
+ hi = [-math.inf] * 3
+ for n in skinned:
+ mlo, mhi = gt.mesh_bounds(doc, doc["meshes"][nodes[n]["mesh"]])
+ lo = [min(a, b) for a, b in zip(lo, mlo, strict=True)]
+ hi = [max(a, b) for a, b in zip(hi, mhi, strict=True)]
+ if abs(lo[1]) > limits["origin_epsilon"]:
+ problems.append(f"lowest vertex at y={lo[1]:.3f}; the feet must stand on y=0")
+ height = hi[1] - lo[1]
+ if abs(height - float(figure.get("height_m", 0))) > 0.01 * max(height, 1e-6):
+ problems.append(f"extras.height_m {figure.get('height_m')} != measured {height:.4f}")
+ cx = (lo[0] + hi[0]) / 2
+ cz = (lo[2] + hi[2]) / 2
+ if abs(cx) > limits["center_epsilon"] or abs(cz) > limits["center_epsilon"]:
+ problems.append(f"body centred at ({cx:.3f}, {cz:.3f}); must stand on the origin")
+
+ # 6 — mesh budgets
+ budget = archetype["budget"]
+ tri_total = 0
+ prim_total = 0
+ for n in skinned or [i for i, nd in enumerate(nodes) if "mesh" in nd]:
+ mesh = doc["meshes"][nodes[n]["mesh"]]
+ tri_total += gt.triangle_count(doc, mesh)
+ prim_total += len(mesh["primitives"])
+ for prim in mesh["primitives"]:
+ attrs = set(prim["attributes"])
+ if not attrs <= ALLOWED_ATTRIBUTES:
+ problems.append(
+ f"mesh {mesh.get('name')!r} carries attributes "
+ f"{sorted(attrs - ALLOWED_ATTRIBUTES)}"
+ )
+ if "JOINTS_1" in prim["attributes"]:
+ problems.append(
+ f"mesh {mesh.get('name')!r} uses more than "
+ f"{limits['max_influences']} influences"
+ )
+ tri_limit = limits["part_triangles"] if part else budget["triangles"]
+ if tri_total > tri_limit:
+ problems.append(f"{tri_total} triangles > budget {tri_limit}")
+ if figure and prim_total > budget["primitives"]:
+ problems.append(f"{prim_total} primitives > budget {budget['primitives']}")
+ if len(doc.get("materials", [])) > budget["materials"]:
+ problems.append(f"{len(doc['materials'])} materials > budget {budget['materials']}")
+
+ # 7 — images and samplers
+ for i, img in enumerate(doc.get("images", [])):
+ if img.get("mimeType") != "image/png" or "bufferView" not in img:
+ problems.append(f"image {i} must be an embedded PNG")
+ continue
+ try:
+ w, h = gt.png_size(gt.image_bytes(glb, i))
+ except ValueError as exc:
+ problems.append(f"image {i}: {exc}")
+ continue
+ if w != h or w & (w - 1) or w > limits["max_texture"]:
+ problems.append(
+ f"image {i} is {w}x{h}; square power-of-two up to {limits['max_texture']} only"
+ )
+ for i, sampler in enumerate(doc.get("samplers", [])):
+ if sampler.get("magFilter") != NEAREST or sampler.get("minFilter") != NEAREST:
+ problems.append(f"sampler {i} is not NEAREST/NEAREST (pixel sheets must not blur)")
+ if doc.get("textures") and not doc.get("samplers"):
+ problems.append("textures without an explicit NEAREST sampler")
+ for i, mat in enumerate(doc.get("materials", [])):
+ if mat.get("alphaMode", "OPAQUE") not in ("OPAQUE", "MASK"):
+ problems.append(
+ f"material {i} uses alphaMode {mat.get('alphaMode')}; OPAQUE or MASK only"
+ )
+
+ # 8 — palette strip
+ sheet = contract["sheet"]
+ if doc.get("images") and not extras.get("paletteLocked"):
+ try:
+ w, h, channels, rows = gt.decode_png(gt.image_bytes(glb, 0))
+ except ValueError as exc:
+ problems.append(f"sheet: {exc}")
+ else:
+ if w == sheet["size"] and h == sheet["size"]:
+ cw, ch = sheet["cell_width"], sheet["cell_height"]
+ for cell in range(len(sheet["cells"])):
+ x0 = cell * cw
+ first = rows[0][x0 * channels : x0 * channels + 3]
+ flat = all(
+ rows[y][x * channels : x * channels + 3] == first
+ for y in range(ch)
+ for x in range(x0, x0 + cw)
+ )
+ if not flat:
+ problems.append(
+ f"palette cell {cell} ({sheet['cells'][cell]}) is not one flat colour"
+ )
+ break
+ else:
+ problems.append(
+ f"sheet is {w}x{h}; the palette strip layout needs "
+ f"{sheet['size']}x{sheet['size']}"
+ )
+
+ # 9–12 — clips
+ anims = doc.get("animations", [])
+ by_name = {a.get("name"): a for a in anims}
+ if part and anims:
+ problems.append(f"part carries {len(anims)} animations; parts have none")
+ if figure:
+ for clip, spec in archetype["clips"].items():
+ anim = by_name.get(clip)
+ if anim is None:
+ problems.append(f"clip {clip!r} missing")
+ continue
+ duration = gt.clip_duration(glb, anim)
+ lo_d, hi_d = spec["duration"]
+ if not lo_d <= duration <= hi_d:
+ problems.append(f"clip {clip!r} lasts {duration:.3f}s; band is {lo_d}-{hi_d}s")
+ for ch in anim["channels"]:
+ target = ch["target"]
+ if "node" not in target:
+ continue
+ node_name = nodes[target["node"]].get("name")
+ sampler = anim["samplers"][ch["sampler"]]
+ values = gt.accessor_values(glb, sampler["output"])
+ if target["path"] == "scale":
+ problems.append(f"clip {clip!r} animates scale on {node_name!r}")
+ if target["path"] == "translation" and node_name == "root" and values:
+ xs = [v[0] for v in values]
+ zs = [v[2] for v in values]
+ if max(xs) - min(xs) > 1e-3 or max(zs) - min(zs) > 1e-3:
+ problems.append(
+ f"clip {clip!r} moves root in XZ (root motion); clips are in place"
+ )
+ if spec["loop"] and len(values) > 1:
+ first, last = values[0], values[-1]
+ if target["path"] == "rotation":
+ # Same orientation within loop_epsilon_deg (q and -q are one rotation).
+ dot = abs(sum(a * b for a, b in zip(first, last, strict=True)))
+ same = min(dot, 1.0) >= math.cos(
+ math.radians(limits["loop_epsilon_deg"]) / 2
+ )
+ else:
+ same = all(
+ abs(a - b) <= limits["loop_epsilon"]
+ for a, b in zip(first, last, strict=True)
+ )
+ if not same:
+ problems.append(
+ f"clip {clip!r} does not loop cleanly on {node_name!r}/{target['path']}"
+ )
+ break
+ if spec.get("stride"):
+ recorded = float(figure.get("clips", {}).get(clip, {}).get("stride_m", 0) or 0)
+ measured = gt.measure_stride(glb, anim, archetype["feet"])
+ if recorded <= 0:
+ problems.append(f"clip {clip!r} has no stride_m in extras")
+ elif abs(measured - recorded) > 0.1 * recorded:
+ problems.append(f"clip {clip!r} stride_m {recorded} != measured {measured:.4f}")
+ for name in by_name:
+ if name not in archetype["clips"]:
+ problems.append(f"clip {name!r} is not in the {archetype_name} clip set")
+
+ # 13 — parts
+ if part:
+ slot = part.get("slot")
+ if not slot:
+ problems.append("part without a slot")
+
+ # 14 — packaging
+ size_kb = path.stat().st_size / 1024
+ cap = limits["part_file_kb"] if part else limits["base_file_kb"]
+ if size_kb > cap:
+ problems.append(f"{size_kb:.0f} KB > {cap} KB")
+ used = set(doc.get("extensionsUsed", [])) | set(doc.get("extensionsRequired", []))
+ if used & FORBIDDEN_EXTENSIONS:
+ problems.append(f"needs a decoder we do not ship: {sorted(used & FORBIDDEN_EXTENSIONS)}")
+
+ # 15 — provenance
+ ledger = sources_md if sources_md is not None else path.parent / "SOURCES.md"
+ if not ledger.exists() or f"`{path.name}`" not in ledger.read_text(encoding="utf-8"):
+ problems.append(f"no row for `{path.name}` in {ledger.name}")
+
+ return problems
+
+
+def check_dir(directory: Path = _FIGURES) -> dict[str, list[str]]:
+ contract = load_contract()
+ return {
+ p.relative_to(directory).as_posix(): check_file(p, contract, directory / "SOURCES.md")
+ for p in sorted(directory.rglob("*.glb"))
+ }
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
+ parser.add_argument(
+ "paths", nargs="*", help="GLB files or directories (default: the shipped figures)"
+ )
+ args = parser.parse_args(argv)
+ targets = [Path(p) for p in args.paths] or [_FIGURES]
+ results: dict[str, list[str]] = {}
+ for target in targets:
+ if target.is_dir():
+ results.update(check_dir(target))
+ elif target.exists():
+ results[target.name] = check_file(target)
+ if not results:
+ print("check_society_figures: no figure assets to check (skipped)")
+ return EXIT_SKIPPED
+ failed = {k: v for k, v in results.items() if v}
+ for name, problems in failed.items():
+ print(f"{name}:")
+ for p in problems:
+ print(f" - {p}")
+ if failed:
+ print(
+ f"\ncheck_society_figures: {len(failed)} of {len(results)} figure(s) "
+ "violate the contract"
+ )
+ return 1
+ print(f"check_society_figures: OK - {len(results)} figure(s) honour the contract")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/figures/README.md b/scripts/figures/README.md
new file mode 100644
index 0000000000..c41141c8d5
--- /dev/null
+++ b/scripts/figures/README.md
@@ -0,0 +1,22 @@
+# scripts/figures — the character build
+
+The build side of [`docs/agent-society/character-pipeline.md`](../../docs/agent-society/character-pipeline.md).
+
+- `contract.json` — archetypes, bone sets, clip sets, sheet layout, budgets, build targets.
+ The CI gate (`scripts/ci/check_society_figures.py`) reads the same file.
+- `sources/<name>.json` — one recorded source per asset pack: URL, sha256 per file, license,
+ bone map, clip map, per-character atlas-cell → palette-cell map, default palette.
+- `glb_tools.py` — stdlib GLB reader/writer, pruning, PNG codec, clip sampling and the stride
+ measurement. Shared by the build's finish step and the gate; no third-party imports.
+- `build_figures.py` — runs INSIDE Blender (5.0+), headless:
+
+```
+blender -b --python scripts/figures/build_figures.py -- --target biped-medium
+```
+
+ Output lands in `jarvis/ui/web/frontend/src/assets/society/figures/`; every produced file is
+ validated by the gate before the script exits 0.
+- `cache/` — fetched sources and generated sheets; gitignored.
+
+Adding a character from an existing source = a `targets` entry in `contract.json` plus a
+`characters` entry (body meshes, cell map, palette) in the source file. No code.
diff --git a/scripts/figures/build_figures.py b/scripts/figures/build_figures.py
new file mode 100644
index 0000000000..35941ef5d2
--- /dev/null
+++ b/scripts/figures/build_figures.py
@@ -0,0 +1,523 @@
+"""Build every shipped figure GLB from its recorded source — inside Blender, headless.
+
+ blender -b --python scripts/figures/build_figures.py -- --out <dir> [--target biped-medium]
+
+The ONLY producer of the GLBs under ``src/assets/society/figures/``
+(docs/agent-society/character-pipeline.md §7). What it does per target in
+``contract.json``:
+
+1. fetch the source file named in ``sources/<source>.json`` into ``cache/``
+ (gitignored) and verify its sha256 — a build never touches an unverified byte;
+2. import it, keep only the base body meshes, drop IK/control bones, rename the
+ deform bones to the archetype's contract names;
+3. keep only the clips the archetype needs, rename them, zero the root's XZ
+ motion (locomotion is the runtime's job), close the loops;
+4. join the body into one mesh, re-UV every face onto the 16-cell palette strip
+ of a fresh 128×128 sheet (nearest-filtered), one material;
+5. add the ``FWD`` marker, export a binary glTF;
+6. finish it with stdlib tools: strip constant channels, prune, write the
+ ``asset.extras.jarvis_figure`` block with the measured height, feet and stride;
+7. run the CI gate on the result — a failing figure fails the build.
+
+Runs on Windows, macOS and Linux (Blender needs no display in ``-b`` mode). It
+never imports ``jarvis.*``: Blender ships its own interpreter.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import importlib.util
+import json
+import re
+import sys
+import urllib.request
+from pathlib import Path
+
+import bpy # type: ignore[import-not-found]
+
+HERE = Path(__file__).resolve().parent
+REPO = HERE.parents[1]
+CACHE = HERE / "cache"
+sys.path.insert(0, str(HERE))
+import glb_tools as gt # noqa: E402
+
+CONTRACT = json.loads((HERE / "contract.json").read_text(encoding="utf-8"))
+
+
+def log(msg: str) -> None:
+ print(f"[figures] {msg}", flush=True)
+
+
+# ---------------------------------------------------------------------------
+# sources
+# ---------------------------------------------------------------------------
+
+
+def load_source(name: str) -> dict:
+ return json.loads((HERE / "sources" / f"{name}.json").read_text(encoding="utf-8"))
+
+
+def fetch_source_file(source: dict, filename: str) -> Path:
+ CACHE.mkdir(exist_ok=True)
+ expected = source["files"][filename]
+ dest = CACHE / f"{source_slug(source)}-{filename}"
+ if not dest.exists():
+ url = source["base_url"] + filename
+ log(f"fetching {url}")
+ with urllib.request.urlopen(url, timeout=120) as resp: # noqa: S310 - pinned URL + sha256
+ dest.write_bytes(resp.read())
+ digest = hashlib.sha256(dest.read_bytes()).hexdigest()
+ if digest != expected:
+ raise SystemExit(f"{dest.name}: sha256 {digest} != recorded {expected}; refusing to build")
+ return dest
+
+
+def source_slug(source: dict) -> str:
+ return re.sub(r"[^a-z0-9]+", "-", source["name"].lower()).strip("-")
+
+
+# ---------------------------------------------------------------------------
+# Blender helpers
+# ---------------------------------------------------------------------------
+
+
+def reset_scene() -> None:
+ # The scene keeps the source's frame rate: keys imported onto integer frames
+ # are sampled exactly on export, so a closed loop stays closed.
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+
+
+def import_glb(path: Path, fps: int) -> None:
+ # The importer lands keys on frames at the SCENE rate; at the source's own
+ # rate they sit on integer frames, so the export samples every key exactly
+ # and a loop closed on the last key stays closed after sampling.
+ bpy.context.scene.render.fps = fps
+ bpy.ops.import_scene.gltf(filepath=str(path), import_shading="NORMALS")
+
+
+def find_armature() -> bpy.types.Object:
+ arms = [o for o in bpy.data.objects if o.type == "ARMATURE"]
+ if len(arms) != 1:
+ raise SystemExit(f"expected exactly one armature, found {[a.name for a in arms]}")
+ return arms[0]
+
+
+def iter_fcurves(action: bpy.types.Action):
+ """Every F-curve of an action across the legacy and the slotted API."""
+ seen = False
+ try:
+ for fc in action.fcurves:
+ seen = True
+ yield fc
+ except (AttributeError, RuntimeError):
+ seen = False
+ if seen:
+ return
+ for layer in getattr(action, "layers", []):
+ for strip in layer.strips:
+ for bag in getattr(strip, "channelbags", []):
+ yield from bag.fcurves
+
+
+def remove_fcurve(action: bpy.types.Action, fc) -> None:
+ try:
+ action.fcurves.remove(fc)
+ return
+ except (AttributeError, RuntimeError):
+ pass
+ for layer in getattr(action, "layers", []):
+ for strip in layer.strips:
+ for bag in getattr(strip, "channelbags", []):
+ if fc in list(bag.fcurves):
+ bag.fcurves.remove(fc)
+ return
+
+
+def set_mode(obj: bpy.types.Object, mode: str) -> None:
+ bpy.context.view_layer.objects.active = obj
+ obj.select_set(True)
+ bpy.ops.object.mode_set(mode=mode)
+
+
+def bone_name_of(data_path: str) -> str | None:
+ m = re.match(r'pose\.bones\["([^"]+)"\]', data_path)
+ return m.group(1) if m else None
+
+
+# ---------------------------------------------------------------------------
+# build steps
+# ---------------------------------------------------------------------------
+
+
+def keep_only_body(arm: bpy.types.Object, body_meshes: list[str]) -> list[bpy.types.Object]:
+ keep = set(body_meshes)
+ bodies = []
+ for obj in list(bpy.data.objects):
+ if obj is arm:
+ continue
+ if obj.type == "MESH" and obj.name in keep:
+ bodies.append(obj)
+ continue
+ bpy.data.objects.remove(obj, do_unlink=True)
+ missing = keep - {b.name for b in bodies}
+ if missing:
+ raise SystemExit(f"body meshes not found in source: {sorted(missing)}")
+ return bodies
+
+
+def drop_bones(arm: bpy.types.Object, patterns: list[str]) -> list[str]:
+ victims = [b.name for b in arm.data.bones if any(p in b.name for p in patterns)]
+ set_mode(arm, "EDIT")
+ for name in victims:
+ eb = arm.data.edit_bones.get(name)
+ if eb is not None:
+ arm.data.edit_bones.remove(eb)
+ bpy.ops.object.mode_set(mode="OBJECT")
+ for action in bpy.data.actions:
+ for fc in list(iter_fcurves(action)):
+ bone = bone_name_of(fc.data_path)
+ if bone in victims:
+ remove_fcurve(action, fc)
+ return victims
+
+
+def rename_bones(arm: bpy.types.Object, bone_map: dict[str, str], expected: list[str]) -> None:
+ for old, new in bone_map.items():
+ bone = arm.data.bones.get(old)
+ if bone is None:
+ raise SystemExit(f"bone {old!r} missing in source armature")
+ bone.name = new
+ have = {b.name for b in arm.data.bones}
+ extra = have - set(expected)
+ missing = set(expected) - have
+ if extra or missing:
+ raise SystemExit(f"bone set mismatch: extra={sorted(extra)} missing={sorted(missing)}")
+
+
+def filter_clips(clip_map: dict[str, str], clip_spec: dict) -> dict[str, bpy.types.Action]:
+ by_source = {v: k for k, v in clip_map.items()}
+ kept: dict[str, bpy.types.Action] = {}
+ for action in list(bpy.data.actions):
+ target = by_source.get(action.name)
+ if target is None:
+ bpy.data.actions.remove(action)
+ continue
+ action.name = target
+ action.use_fake_user = True
+ kept[target] = action
+ missing = set(clip_spec) - set(kept)
+ if missing:
+ raise SystemExit(f"clips missing in source: {sorted(missing)} (have {sorted(kept)})")
+ return kept
+
+
+def normalize_clip(action: bpy.types.Action, loop: bool) -> None:
+ for fc in iter_fcurves(action):
+ bone = bone_name_of(fc.data_path)
+ keys = fc.keyframe_points
+ if not len(keys):
+ continue
+ if bone == "root" and fc.data_path.endswith(".location") and fc.array_index in (0, 2):
+ for k in keys:
+ k.co[1] = 0.0
+ k.handle_left[1] = 0.0
+ k.handle_right[1] = 0.0
+ if loop and len(keys) > 1:
+ keys[-1].co[1] = keys[0].co[1]
+ fc.update()
+
+
+def join_bodies(bodies: list[bpy.types.Object]) -> bpy.types.Object:
+ for obj in bpy.data.objects:
+ obj.select_set(False)
+ for obj in bodies:
+ obj.select_set(True)
+ bpy.context.view_layer.objects.active = bodies[0]
+ if len(bodies) > 1:
+ bpy.ops.object.join()
+ body = bpy.context.view_layer.objects.active
+ body.name = "Body"
+ body.data.name = "Body"
+ return body
+
+
+def cell_of(u: float, v_bottom_up: float, grid: dict) -> str:
+ col = min(int(u * grid["columns"]), grid["columns"] - 1)
+ row = min(int((1.0 - v_bottom_up) * grid["rows"]), grid["rows"] - 1)
+ return f"c{col}r{row}"
+
+
+def reuv_to_palette(
+ body: bpy.types.Object, source_names: dict[str, str], cell_map: dict, grid: dict
+) -> dict:
+ """Move every face's UVs onto its semantic palette cell; report the mapping used."""
+ sheet = CONTRACT["sheet"]
+ cells = sheet["cells"]
+ mesh = body.data
+ uv_layer = mesh.uv_layers.active
+ if uv_layer is None:
+ raise SystemExit("body has no UV layer")
+ # A joined mesh keeps no per-object identity; material index / original
+ # object is gone, so per-mesh overrides are resolved by the polygon's
+ # original object recorded before the join (see build_target).
+ origin = mesh.attributes.get("jarvis_origin")
+ used: dict[str, int] = {}
+ unmapped: dict[str, int] = {}
+ for poly in mesh.polygons:
+ us = [uv_layer.data[li].uv[0] for li in poly.loop_indices]
+ vs = [uv_layer.data[li].uv[1] for li in poly.loop_indices]
+ cell = cell_of(sum(us) / len(us), sum(vs) / len(vs), grid)
+ obj_name = source_names.get(str(origin.data[poly.index].value), "*") if origin else "*"
+ semantic = cell_map.get(obj_name, {}).get(cell) or cell_map.get("*", {}).get(cell)
+ if semantic is None:
+ unmapped[cell] = unmapped.get(cell, 0) + 1
+ semantic = "primary"
+ idx = cells.index(semantic)
+ used[semantic] = used.get(semantic, 0) + 1
+ cu = (idx + 0.5) / len(cells)
+ cv = 1.0 - (sheet["cell_height"] / 2) / sheet["size"]
+ for li in poly.loop_indices:
+ uv_layer.data[li].uv = (cu, cv)
+ if unmapped:
+ log(f"WARNING unmapped atlas cells (painted primary): {unmapped}")
+ return {"used": used, "unmapped": unmapped}
+
+
+def hex_rgb(value: str) -> tuple[int, int, int]:
+ v = value.lstrip("#")
+ return int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16)
+
+
+def write_sheet(path: Path, palette: dict[str, str]) -> None:
+ sheet = CONTRACT["sheet"]
+ size = sheet["size"]
+ cw, ch = sheet["cell_width"], sheet["cell_height"]
+ rows: list[bytes] = []
+ for y in range(size):
+ row = bytearray()
+ for x in range(size):
+ if y < ch:
+ name = sheet["cells"][min(x // cw, len(sheet["cells"]) - 1)]
+ r, g, b = hex_rgb(palette[name])
+ else:
+ r, g, b = (128, 128, 128)
+ row += bytes((r, g, b, 255))
+ rows.append(bytes(row))
+ path.write_bytes(gt.encode_png(size, size, rows, 4))
+
+
+def apply_sheet_material(body: bpy.types.Object, sheet_path: Path, name: str) -> None:
+ img = bpy.data.images.load(str(sheet_path))
+ img.colorspace_settings.name = "sRGB"
+ mat = bpy.data.materials.new(name)
+ mat.use_nodes = True
+ nodes = mat.node_tree.nodes
+ links = mat.node_tree.links
+ bsdf = nodes.get("Principled BSDF")
+ tex = nodes.new("ShaderNodeTexImage")
+ tex.image = img
+ tex.interpolation = "Closest"
+ links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
+ bsdf.inputs["Roughness"].default_value = 1.0
+ bsdf.inputs["Metallic"].default_value = 0.0
+ body.data.materials.clear()
+ body.data.materials.append(mat)
+
+
+def add_forward_marker(arm: bpy.types.Object) -> None:
+ fwd = bpy.data.objects.new("FWD", None)
+ fwd.empty_display_type = "ARROWS"
+ fwd.empty_display_size = 0.2
+ # glTF (0, 0.5, 1) == Blender (0, -1, 0.5): the exporter maps Blender -Y to glTF +Z.
+ fwd.location = (0.0, -1.0, 0.5)
+ fwd.parent = arm
+ bpy.context.scene.collection.objects.link(fwd)
+
+
+def export_glb(path: Path) -> None:
+ bpy.ops.export_scene.gltf(
+ filepath=str(path),
+ export_format="GLB",
+ export_apply=True,
+ export_yup=True,
+ export_extras=True,
+ export_texcoords=True,
+ export_normals=True,
+ export_tangents=False,
+ export_materials="EXPORT",
+ export_image_format="AUTO",
+ export_skins=True,
+ export_def_bones=False,
+ export_rest_position_armature=True,
+ export_animations=True,
+ export_animation_mode="ACTIONS",
+ export_force_sampling=True,
+ export_frame_step=1,
+ export_optimize_animation_size=True,
+ export_leaf_bone=False,
+ use_selection=False,
+ )
+
+
+# ---------------------------------------------------------------------------
+# finish (stdlib): extras, samplers, pruning
+# ---------------------------------------------------------------------------
+
+
+def finish(glb_path: Path, target: dict, source: dict, archetype: dict, uv_report: dict) -> None:
+ glb = gt.read_glb(glb_path)
+ doc = glb.doc
+ for sampler in doc.get("samplers", []):
+ sampler["magFilter"] = 9728
+ sampler["minFilter"] = 9728
+ sampler["wrapS"] = 33071
+ sampler["wrapT"] = 33071
+ if not doc.get("samplers") and doc.get("textures"):
+ doc["samplers"] = [{"magFilter": 9728, "minFilter": 9728, "wrapS": 33071, "wrapT": 33071}]
+ for tex in doc["textures"]:
+ tex["sampler"] = 0
+ for mat in doc.get("materials", []):
+ mat["alphaMode"] = "OPAQUE"
+ mat.pop("doubleSided", None)
+
+ # Strip constant scale channels (identity) — KayKit bakes one per bone.
+ for anim in doc.get("animations", []):
+ keep_channels = []
+ for ch in anim["channels"]:
+ if ch["target"].get("path") == "scale":
+ vals = gt.accessor_values(glb, anim["samplers"][ch["sampler"]]["output"])
+ if all(abs(v - 1.0) < 1e-3 for vec in vals for v in vec):
+ continue
+ keep_channels.append(ch)
+ anim["channels"] = keep_channels
+ used = sorted({ch["sampler"] for ch in keep_channels})
+ remap = {old: new for new, old in enumerate(used)}
+ anim["samplers"] = [anim["samplers"][i] for i in used]
+ for ch in keep_channels:
+ ch["sampler"] = remap[ch["sampler"]]
+
+ collapsed = gt.collapse_constant_channels(glb)
+ glb = gt.prune_unused(glb)
+ doc = glb.doc
+ log(f"collapsed {collapsed} constant channels")
+
+ # Facts the runtime and the gate read.
+ skinned = gt.skinned_mesh_nodes(doc)
+ lo, hi = gt.mesh_bounds(doc, doc["meshes"][doc["nodes"][skinned[0]]["mesh"]])
+ clips: dict[str, dict] = {}
+ for name, spec in archetype["clips"].items():
+ anim = gt.clip_by_name(doc, name)
+ if anim is None:
+ continue
+ entry: dict = {
+ "duration": round(gt.clip_duration(glb, anim), 4),
+ "loop": bool(spec["loop"]),
+ }
+ if spec.get("stride"):
+ entry["stride_m"] = round(gt.measure_stride(glb, anim, archetype["feet"]), 4)
+ clips[name] = entry
+ doc.setdefault("asset", {})["extras"] = {
+ "jarvis_figure": {
+ "contract": CONTRACT["contract"],
+ "archetype": target["archetype"],
+ "variant": target["variant"],
+ "forward": "+Z",
+ "height_m": round(hi[1] - lo[1], 4),
+ "target_height_m": archetype["variants"][target["variant"]]["height_m"],
+ "clips": clips,
+ "palette_cells": uv_report["used"],
+ "source": f"{source['name']} ({source['license']}) / {target['character']}",
+ }
+ }
+ doc["asset"]["generator"] = "Personal Jarvis build_figures.py"
+ gt.write_glb(glb_path, doc, glb.blob)
+ log(f"finished {glb_path.name}: {glb_path.stat().st_size // 1024} KB, clips {clips}")
+
+
+def run_gate(glb_path: Path) -> None:
+ gate = REPO / "scripts" / "ci" / "check_society_figures.py"
+ if not gate.exists():
+ log("gate not present yet — skipping validation")
+ return
+ spec = importlib.util.spec_from_file_location("check_society_figures", gate)
+ mod = importlib.util.module_from_spec(spec)
+ assert spec and spec.loader
+ sys.modules["check_society_figures"] = mod
+ spec.loader.exec_module(mod)
+ problems = mod.check_file(glb_path)
+ if problems:
+ for p in problems:
+ log(f"GATE {glb_path.name}: {p}")
+ raise SystemExit(f"{glb_path.name} violates the figure contract")
+ log(f"gate OK for {glb_path.name}")
+
+
+# ---------------------------------------------------------------------------
+# one target
+# ---------------------------------------------------------------------------
+
+
+def build_target(target: dict, out_dir: Path) -> Path:
+ archetype = CONTRACT["archetypes"][target["archetype"]]
+ source = load_source(target["source"])
+ character = source["characters"][target["character"]]
+ src_file = fetch_source_file(source, f"{target['character']}.glb")
+ log(f"building {target['id']} from {src_file.name}")
+
+ reset_scene()
+ import_glb(src_file, int(source.get("fps", 30)))
+ arm = find_armature()
+ bodies = keep_only_body(arm, character["body_meshes"])
+
+ # Remember which source object each polygon came from (per-mesh cell overrides).
+ source_names: dict[str, str] = {}
+ for n, obj in enumerate(bodies):
+ attr = obj.data.attributes.get("jarvis_origin") or obj.data.attributes.new(
+ "jarvis_origin", "INT", "FACE"
+ )
+ for poly in obj.data.polygons:
+ attr.data[poly.index].value = n
+ source_names[str(n)] = obj.name
+
+ dropped = drop_bones(arm, source["drop_bone_patterns"])
+ log(f"dropped {len(dropped)} control bones")
+ rename_bones(arm, source["bone_map"], archetype["bones"])
+ kept = filter_clips(source["clip_map"], archetype["clips"])
+ for name, action in kept.items():
+ normalize_clip(action, archetype["clips"][name]["loop"])
+ log(f"clips: {sorted(kept)}")
+
+ body = join_bodies(bodies)
+ uv_report = reuv_to_palette(body, source_names, character["cell_map"], source["atlas_grid"])
+ body.data.attributes.remove(body.data.attributes["jarvis_origin"])
+ sheet_path = CACHE / f"{target['id']}-sheet.png"
+ write_sheet(sheet_path, character["default_palette"])
+ apply_sheet_material(body, sheet_path, f"{target['id']}-sheet")
+ add_forward_marker(arm)
+
+ out_dir.mkdir(parents=True, exist_ok=True)
+ out = out_dir / f"{target['id']}.glb"
+ export_glb(out)
+ finish(out, target, source, archetype, uv_report)
+ run_gate(out)
+ return out
+
+
+def main() -> None:
+ argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--out", default=str(REPO / "jarvis/ui/web/frontend/src/assets/society/figures")
+ )
+ parser.add_argument("--target", default=None)
+ args = parser.parse_args(argv)
+ targets = [t for t in CONTRACT["targets"] if args.target in (None, t["id"])]
+ if not targets:
+ raise SystemExit(f"no target named {args.target!r}")
+ for target in targets:
+ build_target(target, Path(args.out))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/figures/contract.json b/scripts/figures/contract.json
new file mode 100644
index 0000000000..755f1b8876
--- /dev/null
+++ b/scripts/figures/contract.json
@@ -0,0 +1,147 @@
+{
+ "$comment": "Figure asset contract v1 — docs/agent-society/character-pipeline.md §4/§5. The build (build_figures.py) and the CI gate (scripts/ci/check_society_figures.py) both read this file; the runtime reads the extras the build writes from it.",
+ "contract": 1,
+ "sheet": {
+ "size": 128,
+ "cell_width": 8,
+ "cell_height": 16,
+ "cells": [
+ "skin",
+ "skin_shade",
+ "hair",
+ "eyes",
+ "primary",
+ "primary_shade",
+ "secondary",
+ "secondary_shade",
+ "accent",
+ "metal",
+ "leather",
+ "fur",
+ "fur_shade",
+ "shoes",
+ "eye_white",
+ "emissive"
+ ]
+ },
+ "archetypes": {
+ "biped": {
+ "bones": [
+ "root",
+ "hips",
+ "spine",
+ "chest",
+ "head",
+ "upper_arm_l",
+ "lower_arm_l",
+ "wrist_l",
+ "hand_l",
+ "handslot_l",
+ "upper_arm_r",
+ "lower_arm_r",
+ "wrist_r",
+ "hand_r",
+ "handslot_r",
+ "upper_leg_l",
+ "lower_leg_l",
+ "foot_l",
+ "toes_l",
+ "upper_leg_r",
+ "lower_leg_r",
+ "foot_r",
+ "toes_r"
+ ],
+ "feet": ["toes_l", "toes_r"],
+ "clips": {
+ "idle": { "loop": true, "duration": [0.8, 6.0] },
+ "walk": { "loop": true, "duration": [0.8, 1.2], "stride": true },
+ "run": { "loop": true, "duration": [0.5, 0.9], "stride": true },
+ "work": { "loop": true, "duration": [0.5, 4.0] },
+ "talk": { "loop": true, "duration": [0.8, 3.0] },
+ "sit": { "loop": true, "duration": [1.0, 6.0] },
+ "sleep": { "loop": true, "duration": [1.0, 6.0] },
+ "celebrate": { "loop": false, "duration": [0.5, 4.0] },
+ "wave": { "loop": false, "duration": [0.5, 3.0] }
+ },
+ "variants": {
+ "small": { "height_m": 1.15 },
+ "medium": { "height_m": 1.75 },
+ "large": { "height_m": 2.3 }
+ },
+ "budget": { "triangles": 4500, "materials": 1, "primitives": 1 }
+ },
+ "quadruped": {
+ "bones": [
+ "root",
+ "hips",
+ "spine",
+ "chest",
+ "neck",
+ "head",
+ "jaw",
+ "tail_1",
+ "tail_2",
+ "upper_leg_fl",
+ "lower_leg_fl",
+ "foot_fl",
+ "upper_leg_fr",
+ "lower_leg_fr",
+ "foot_fr",
+ "upper_leg_bl",
+ "lower_leg_bl",
+ "foot_bl",
+ "upper_leg_br",
+ "lower_leg_br",
+ "foot_br"
+ ],
+ "optional_bones": ["ear_l", "ear_r", "wing_l", "wing_r"],
+ "feet": ["foot_fl", "foot_fr", "foot_bl", "foot_br"],
+ "clips": {
+ "idle": { "loop": true, "duration": [0.8, 6.0] },
+ "walk": { "loop": true, "duration": [0.6, 1.4], "stride": true },
+ "run": { "loop": true, "duration": [0.4, 0.9], "stride": true },
+ "talk": { "loop": true, "duration": [0.8, 3.0] },
+ "sit": { "loop": true, "duration": [1.0, 6.0] },
+ "sleep": { "loop": true, "duration": [1.0, 6.0] },
+ "celebrate": { "loop": false, "duration": [0.5, 4.0] }
+ },
+ "variants": { "default": { "height_m": 0.9 } },
+ "budget": { "triangles": 4500, "materials": 1, "primitives": 1 }
+ },
+ "spirit": {
+ "bones": ["root", "body", "face"],
+ "feet": [],
+ "clips": {
+ "idle": { "loop": true, "duration": [0.8, 6.0] },
+ "walk": { "loop": true, "duration": [0.6, 2.0], "stride": false },
+ "talk": { "loop": true, "duration": [0.8, 3.0] },
+ "sleep": { "loop": true, "duration": [1.0, 6.0] },
+ "celebrate": { "loop": false, "duration": [0.5, 4.0] },
+ "wave": { "loop": false, "duration": [0.5, 3.0] }
+ },
+ "variants": { "default": { "height_m": 1.9 } },
+ "budget": { "triangles": 1200, "materials": 3, "primitives": 3 }
+ }
+ },
+ "limits": {
+ "part_triangles": 600,
+ "base_file_kb": 512,
+ "part_file_kb": 120,
+ "max_texture": 256,
+ "max_influences": 4,
+ "loop_epsilon": 0.002,
+ "loop_epsilon_deg": 1.0,
+ "origin_epsilon": 0.01,
+ "center_epsilon": 0.1,
+ "scale_epsilon": 0.0001
+ },
+ "targets": [
+ {
+ "id": "biped-medium",
+ "archetype": "biped",
+ "variant": "medium",
+ "source": "kaykit-adventurers",
+ "character": "Rogue"
+ }
+ ]
+}
diff --git a/scripts/figures/glb_tools.py b/scripts/figures/glb_tools.py
new file mode 100644
index 0000000000..b08557230c
--- /dev/null
+++ b/scripts/figures/glb_tools.py
@@ -0,0 +1,631 @@
+"""Stdlib-only GLB tools shared by the figure build and the figure CI gate.
+
+A GLB is a 12-byte header, a JSON chunk and one binary chunk; accessors are
+typed arrays inside that chunk. Everything the character pipeline needs to
+inspect or finish a figure — reading, pruning, rewriting, decoding the sheet
+PNG, evaluating a clip's forward kinematics to measure a stride — fits in
+this file without a dependency, so the gate runs in CI, in pre-commit and
+inside Blender's own interpreter alike (docs/agent-society/character-pipeline.md §10).
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import struct
+import zlib
+from dataclasses import dataclass, field
+from pathlib import Path
+
+GLB_MAGIC = 0x46546C67
+JSON_CHUNK = 0x4E4F534A
+BIN_CHUNK = 0x004E4942
+
+COMPONENT_FORMATS = {5120: "b", 5121: "B", 5122: "h", 5123: "H", 5125: "I", 5126: "f"}
+COMPONENT_MAX = {5120: 127.0, 5121: 255.0, 5122: 32767.0, 5123: 65535.0}
+TYPE_COUNTS = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT2": 4, "MAT3": 9, "MAT4": 16}
+
+Vec3 = tuple[float, float, float]
+Quat = tuple[float, float, float, float]
+Mat4 = tuple[float, ...] # 16 floats, column-major like glTF
+
+
+@dataclass
+class Glb:
+ doc: dict
+ blob: bytes
+ path: Path | None = None
+ warnings: list[str] = field(default_factory=list)
+
+
+def read_glb(path: Path | str) -> Glb:
+ data = Path(path).read_bytes()
+ if len(data) < 12:
+ raise ValueError(f"{path}: too short to be a GLB")
+ magic, _version, length = struct.unpack_from("<III", data, 0)
+ if magic != GLB_MAGIC:
+ raise ValueError(f"{path}: not a GLB (magic {magic:#x})")
+ offset = 12
+ doc: dict | None = None
+ blob = b""
+ while offset + 8 <= min(length, len(data)):
+ chunk_len, chunk_type = struct.unpack_from("<II", data, offset)
+ payload = data[offset + 8 : offset + 8 + chunk_len]
+ if chunk_type == JSON_CHUNK:
+ doc = json.loads(payload.decode("utf-8"))
+ elif chunk_type == BIN_CHUNK:
+ blob = bytes(payload)
+ offset += 8 + chunk_len
+ if doc is None:
+ raise ValueError(f"{path}: GLB without a JSON chunk")
+ return Glb(doc=doc, blob=blob, path=Path(path))
+
+
+def write_glb(path: Path | str, doc: dict, blob: bytes) -> None:
+ json_bytes = json.dumps(doc, separators=(",", ":")).encode("utf-8")
+ json_bytes += b" " * (-len(json_bytes) % 4)
+ bin_bytes = blob + b"\x00" * (-len(blob) % 4)
+ if doc.get("buffers"):
+ doc["buffers"][0]["byteLength"] = len(blob)
+ json_bytes = json.dumps(doc, separators=(",", ":")).encode("utf-8")
+ json_bytes += b" " * (-len(json_bytes) % 4)
+ total = 12 + 8 + len(json_bytes) + 8 + len(bin_bytes)
+ out = bytearray()
+ out += struct.pack("<III", GLB_MAGIC, 2, total)
+ out += struct.pack("<II", len(json_bytes), JSON_CHUNK) + json_bytes
+ out += struct.pack("<II", len(bin_bytes), BIN_CHUNK) + bin_bytes
+ Path(path).write_bytes(bytes(out))
+
+
+# ---------------------------------------------------------------------------
+# accessors
+# ---------------------------------------------------------------------------
+
+
+def accessor_values(glb: Glb, index: int) -> list[tuple[float, ...]]:
+ """Every element of an accessor as a tuple of floats (normalized ints scaled)."""
+ acc = glb.doc["accessors"][index]
+ count = acc["count"]
+ comps = TYPE_COUNTS[acc["type"]]
+ fmt = COMPONENT_FORMATS[acc["componentType"]]
+ size = struct.calcsize(fmt)
+ if "bufferView" not in acc:
+ return [tuple(0.0 for _ in range(comps)) for _ in range(count)]
+ view = glb.doc["bufferViews"][acc["bufferView"]]
+ stride = view.get("byteStride", comps * size)
+ base = view.get("byteOffset", 0) + acc.get("byteOffset", 0)
+ scale = COMPONENT_MAX.get(acc["componentType"]) if acc.get("normalized") else None
+ out: list[tuple[float, ...]] = []
+ for i in range(count):
+ raw = struct.unpack_from("<" + fmt * comps, glb.blob, base + i * stride)
+ if scale:
+ out.append(tuple(max(v / scale, -1.0) for v in raw))
+ else:
+ out.append(tuple(float(v) for v in raw))
+ return out
+
+
+def accessor_ints(glb: Glb, index: int) -> list[tuple[int, ...]]:
+ acc = glb.doc["accessors"][index]
+ comps = TYPE_COUNTS[acc["type"]]
+ fmt = COMPONENT_FORMATS[acc["componentType"]]
+ size = struct.calcsize(fmt)
+ view = glb.doc["bufferViews"][acc["bufferView"]]
+ stride = view.get("byteStride", comps * size)
+ base = view.get("byteOffset", 0) + acc.get("byteOffset", 0)
+ return [
+ tuple(int(v) for v in struct.unpack_from("<" + fmt * comps, glb.blob, base + i * stride))
+ for i in range(acc["count"])
+ ]
+
+
+def image_bytes(glb: Glb, image_index: int) -> bytes:
+ img = glb.doc["images"][image_index]
+ view = glb.doc["bufferViews"][img["bufferView"]]
+ start = view.get("byteOffset", 0)
+ return glb.blob[start : start + view["byteLength"]]
+
+
+# ---------------------------------------------------------------------------
+# appending and collapsing — the finish step's only writes into the blob
+# ---------------------------------------------------------------------------
+
+
+def append_accessor(glb: Glb, values: list[tuple[float, ...]], gltf_type: str) -> int:
+ """Append float data as a new bufferView + accessor; return the accessor index."""
+ comps = TYPE_COUNTS[gltf_type]
+ payload = b"".join(struct.pack("<" + "f" * comps, *v) for v in values)
+ blob = bytearray(glb.blob)
+ blob += b"\x00" * (-len(blob) % 4)
+ offset = len(blob)
+ blob += payload
+ glb.blob = bytes(blob)
+ doc = glb.doc
+ doc.setdefault("bufferViews", []).append(
+ {"buffer": 0, "byteOffset": offset, "byteLength": len(payload)}
+ )
+ acc: dict = {
+ "bufferView": len(doc["bufferViews"]) - 1,
+ "componentType": 5126,
+ "count": len(values),
+ "type": gltf_type,
+ }
+ if values:
+ acc["min"] = [min(v[k] for v in values) for k in range(comps)]
+ acc["max"] = [max(v[k] for v in values) for k in range(comps)]
+ doc.setdefault("accessors", []).append(acc)
+ return len(doc["accessors"]) - 1
+
+
+def collapse_constant_channels(glb: Glb, epsilon: float = 1e-6) -> int:
+ """Rewrite every channel whose value never changes as two keys (start, end).
+
+ A baked export carries a key per frame for bones that never move; the
+ pose must survive (a constant is not necessarily the rest pose), the
+ bytes need not. Returns the number of channels collapsed.
+ """
+ doc = glb.doc
+ collapsed = 0
+ for anim in doc.get("animations", []):
+ for ch in anim["channels"]:
+ sampler = anim["samplers"][ch["sampler"]]
+ values = accessor_values(glb, sampler["output"])
+ if len(values) <= 2:
+ continue
+ first = values[0]
+ if any(abs(a - b) > epsilon for v in values for a, b in zip(v, first, strict=True)):
+ continue
+ times = accessor_values(glb, sampler["input"])
+ span = [(times[0][0],), (times[-1][0],)]
+ gltf_type = doc["accessors"][sampler["output"]]["type"]
+ new_sampler = {
+ "input": append_accessor(glb, span, "SCALAR"),
+ "output": append_accessor(glb, [first, first], gltf_type),
+ "interpolation": "LINEAR",
+ }
+ anim["samplers"].append(new_sampler)
+ ch["sampler"] = len(anim["samplers"]) - 1
+ collapsed += 1
+ return collapsed
+
+
+# ---------------------------------------------------------------------------
+# pruning — drop accessors/bufferViews nothing references, rebuild the blob
+# ---------------------------------------------------------------------------
+
+
+def prune_unused(glb: Glb) -> Glb:
+ doc = glb.doc
+ used_acc: set[int] = set()
+ for mesh in doc.get("meshes", []):
+ for prim in mesh["primitives"]:
+ used_acc.update(prim["attributes"].values())
+ if "indices" in prim:
+ used_acc.add(prim["indices"])
+ for target in prim.get("targets", []):
+ used_acc.update(target.values())
+ for skin in doc.get("skins", []):
+ if "inverseBindMatrices" in skin:
+ used_acc.add(skin["inverseBindMatrices"])
+ for anim in doc.get("animations", []):
+ for sampler in anim["samplers"]:
+ used_acc.add(sampler["input"])
+ used_acc.add(sampler["output"])
+ acc_order = sorted(used_acc)
+ acc_remap = {old: new for new, old in enumerate(acc_order)}
+
+ used_views: set[int] = set()
+ for i in acc_order:
+ acc = doc["accessors"][i]
+ if "bufferView" in acc:
+ used_views.add(acc["bufferView"])
+ for img in doc.get("images", []):
+ if "bufferView" in img:
+ used_views.add(img["bufferView"])
+ view_order = sorted(used_views)
+ view_remap = {old: new for new, old in enumerate(view_order)}
+
+ new_blob = bytearray()
+ new_views = []
+ for old in view_order:
+ view = dict(doc["bufferViews"][old])
+ start = view.get("byteOffset", 0)
+ chunk = glb.blob[start : start + view["byteLength"]]
+ new_blob += b"\x00" * (-len(new_blob) % 4)
+ view["byteOffset"] = len(new_blob)
+ view["buffer"] = 0
+ new_blob += chunk
+ new_views.append(view)
+
+ new_accessors = []
+ for old in acc_order:
+ acc = dict(doc["accessors"][old])
+ if "bufferView" in acc:
+ acc["bufferView"] = view_remap[acc["bufferView"]]
+ new_accessors.append(acc)
+
+ for mesh in doc.get("meshes", []):
+ for prim in mesh["primitives"]:
+ prim["attributes"] = {k: acc_remap[v] for k, v in prim["attributes"].items()}
+ if "indices" in prim:
+ prim["indices"] = acc_remap[prim["indices"]]
+ if "targets" in prim:
+ prim["targets"] = [{k: acc_remap[v] for k, v in t.items()} for t in prim["targets"]]
+ for skin in doc.get("skins", []):
+ if "inverseBindMatrices" in skin:
+ skin["inverseBindMatrices"] = acc_remap[skin["inverseBindMatrices"]]
+ for anim in doc.get("animations", []):
+ for sampler in anim["samplers"]:
+ sampler["input"] = acc_remap[sampler["input"]]
+ sampler["output"] = acc_remap[sampler["output"]]
+ for img in doc.get("images", []):
+ if "bufferView" in img:
+ img["bufferView"] = view_remap[img["bufferView"]]
+
+ doc["accessors"] = new_accessors
+ doc["bufferViews"] = new_views
+ doc["buffers"] = [{"byteLength": len(new_blob)}]
+ return Glb(doc=doc, blob=bytes(new_blob), path=glb.path, warnings=glb.warnings)
+
+
+# ---------------------------------------------------------------------------
+# PNG — enough of the format for an 8-bit RGB/RGBA sheet
+# ---------------------------------------------------------------------------
+
+
+def decode_png(data: bytes) -> tuple[int, int, int, list[bytes]]:
+ """Return (width, height, channels, rows) for a non-interlaced 8-bit RGB/RGBA PNG."""
+ if data[:8] != b"\x89PNG\r\n\x1a\n":
+ raise ValueError("not a PNG")
+ pos = 8
+ width = height = 0
+ channels = 0
+ idat = bytearray()
+ while pos + 8 <= len(data):
+ length, ctype = struct.unpack_from(">I4s", data, pos)
+ payload = data[pos + 8 : pos + 8 + length]
+ if ctype == b"IHDR":
+ width, height, depth, color, _c, _f, interlace = struct.unpack(">IIBBBBB", payload)
+ if depth != 8 or interlace != 0:
+ raise ValueError("only 8-bit non-interlaced PNGs are supported")
+ channels = {2: 3, 6: 4, 0: 1, 4: 2}.get(color, 0)
+ if channels == 0:
+ raise ValueError(f"unsupported PNG colour type {color}")
+ elif ctype == b"IDAT":
+ idat += payload
+ elif ctype == b"IEND":
+ break
+ pos += 12 + length
+ raw = zlib.decompress(bytes(idat))
+ stride = width * channels
+ rows: list[bytes] = []
+ prev = bytearray(stride)
+ offset = 0
+ for _ in range(height):
+ filt = raw[offset]
+ line = bytearray(raw[offset + 1 : offset + 1 + stride])
+ offset += 1 + stride
+ for i in range(stride):
+ a = line[i - channels] if i >= channels else 0
+ b = prev[i]
+ c = prev[i - channels] if i >= channels else 0
+ if filt == 1:
+ line[i] = (line[i] + a) & 0xFF
+ elif filt == 2:
+ line[i] = (line[i] + b) & 0xFF
+ elif filt == 3:
+ line[i] = (line[i] + ((a + b) >> 1)) & 0xFF
+ elif filt == 4:
+ p = a + b - c
+ pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
+ pred = a if pa <= pb and pa <= pc else (b if pb <= pc else c)
+ line[i] = (line[i] + pred) & 0xFF
+ rows.append(bytes(line))
+ prev = line
+ return width, height, channels, rows
+
+
+def encode_png(width: int, height: int, rows: list[bytes], channels: int = 4) -> bytes:
+ color = {1: 0, 2: 4, 3: 2, 4: 6}[channels]
+
+ def chunk(ctype: bytes, payload: bytes) -> bytes:
+ crc = zlib.crc32(ctype + payload) & 0xFFFFFFFF
+ return struct.pack(">I", len(payload)) + ctype + payload + struct.pack(">I", crc)
+
+ raw = b"".join(b"\x00" + row for row in rows)
+ ihdr = struct.pack(">IIBBBBB", width, height, 8, color, 0, 0, 0)
+ return (
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", zlib.compress(raw, 9))
+ + chunk(b"IEND", b"")
+ )
+
+
+def png_size(data: bytes) -> tuple[int, int]:
+ if data[:8] != b"\x89PNG\r\n\x1a\n":
+ raise ValueError("not a PNG")
+ width, height = struct.unpack_from(">II", data, 16)
+ return width, height
+
+
+# ---------------------------------------------------------------------------
+# matrices and node hierarchy
+# ---------------------------------------------------------------------------
+
+
+def mat_identity() -> Mat4:
+ return (1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
+
+
+def mat_mul(a: Mat4, b: Mat4) -> Mat4:
+ """Column-major a @ b."""
+ out = [0.0] * 16
+ for col in range(4):
+ for row in range(4):
+ out[col * 4 + row] = sum(a[k * 4 + row] * b[col * 4 + k] for k in range(4))
+ return tuple(out)
+
+
+def mat_from_trs(t: Vec3, r: Quat, s: Vec3) -> Mat4:
+ x, y, z, w = r
+ xx, yy, zz = x * x, y * y, z * z
+ xy, xz, yz = x * y, x * z, y * z
+ wx, wy, wz = w * x, w * y, w * z
+ m = [
+ (1 - 2 * (yy + zz)) * s[0],
+ (2 * (xy + wz)) * s[0],
+ (2 * (xz - wy)) * s[0],
+ 0.0,
+ (2 * (xy - wz)) * s[1],
+ (1 - 2 * (xx + zz)) * s[1],
+ (2 * (yz + wx)) * s[1],
+ 0.0,
+ (2 * (xz + wy)) * s[2],
+ (2 * (yz - wx)) * s[2],
+ (1 - 2 * (xx + yy)) * s[2],
+ 0.0,
+ t[0],
+ t[1],
+ t[2],
+ 1.0,
+ ]
+ return tuple(m)
+
+
+def mat_point(m: Mat4, p: Vec3) -> Vec3:
+ return (
+ m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12],
+ m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13],
+ m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14],
+ )
+
+
+def node_local_trs(node: dict) -> tuple[Vec3, Quat, Vec3]:
+ if "matrix" in node:
+ m = node["matrix"]
+ t = (m[12], m[13], m[14])
+ sx = math.sqrt(m[0] ** 2 + m[1] ** 2 + m[2] ** 2)
+ sy = math.sqrt(m[4] ** 2 + m[5] ** 2 + m[6] ** 2)
+ sz = math.sqrt(m[8] ** 2 + m[9] ** 2 + m[10] ** 2)
+ # rotation from the normalized 3x3 (good enough for validation)
+ r = _quat_from_mat3(
+ [
+ m[0] / sx,
+ m[1] / sx,
+ m[2] / sx,
+ m[4] / sy,
+ m[5] / sy,
+ m[6] / sy,
+ m[8] / sz,
+ m[9] / sz,
+ m[10] / sz,
+ ]
+ )
+ return t, r, (sx, sy, sz)
+ t = tuple(node.get("translation", [0.0, 0.0, 0.0]))
+ r = tuple(node.get("rotation", [0.0, 0.0, 0.0, 1.0]))
+ s = tuple(node.get("scale", [1.0, 1.0, 1.0]))
+ return t, r, s # type: ignore[return-value]
+
+
+def _quat_from_mat3(m: list[float]) -> Quat:
+ # m is column-major 3x3: m[col*3+row]
+ m00, m10, m20, m01, m11, m21, m02, m12, m22 = m
+ trace = m00 + m11 + m22
+ if trace > 0:
+ s = math.sqrt(trace + 1.0) * 2
+ return ((m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s, 0.25 * s)
+ if m00 > m11 and m00 > m22:
+ s = math.sqrt(1.0 + m00 - m11 - m22) * 2
+ return (0.25 * s, (m01 + m10) / s, (m02 + m20) / s, (m21 - m12) / s)
+ if m11 > m22:
+ s = math.sqrt(1.0 + m11 - m00 - m22) * 2
+ return ((m01 + m10) / s, 0.25 * s, (m12 + m21) / s, (m02 - m20) / s)
+ s = math.sqrt(1.0 + m22 - m00 - m11) * 2
+ return ((m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s)
+
+
+def parent_map(doc: dict) -> dict[int, int | None]:
+ parents: dict[int, int | None] = {i: None for i in range(len(doc.get("nodes", [])))}
+ for i, node in enumerate(doc.get("nodes", [])):
+ for child in node.get("children", []):
+ parents[child] = i
+ return parents
+
+
+def node_index_by_name(doc: dict) -> dict[str, int]:
+ return {n.get("name", ""): i for i, n in enumerate(doc.get("nodes", []))}
+
+
+def world_matrices(doc: dict, local: dict[int, Mat4] | None = None) -> list[Mat4]:
+ """World matrix per node from the given local matrices (rest pose when None)."""
+ nodes = doc.get("nodes", [])
+ parents = parent_map(doc)
+ cache: dict[int, Mat4] = {}
+
+ def local_of(i: int) -> Mat4:
+ if local is not None and i in local:
+ return local[i]
+ t, r, s = node_local_trs(nodes[i])
+ return mat_from_trs(t, r, s)
+
+ def world(i: int) -> Mat4:
+ if i in cache:
+ return cache[i]
+ p = parents[i]
+ m = local_of(i) if p is None else mat_mul(world(p), local_of(i))
+ cache[i] = m
+ return m
+
+ return [world(i) for i in range(len(nodes))]
+
+
+# ---------------------------------------------------------------------------
+# animation sampling
+# ---------------------------------------------------------------------------
+
+
+def clip_by_name(doc: dict, name: str) -> dict | None:
+ for anim in doc.get("animations", []):
+ if anim.get("name") == name:
+ return anim
+ return None
+
+
+def clip_duration(glb: Glb, anim: dict) -> float:
+ end = 0.0
+ for sampler in anim["samplers"]:
+ acc = glb.doc["accessors"][sampler["input"]]
+ if "max" in acc:
+ end = max(end, float(acc["max"][0]))
+ else:
+ times = accessor_values(glb, sampler["input"])
+ if times:
+ end = max(end, times[-1][0])
+ return end
+
+
+def _lerp(a: tuple[float, ...], b: tuple[float, ...], f: float) -> tuple[float, ...]:
+ return tuple(x + (y - x) * f for x, y in zip(a, b, strict=True))
+
+
+def _nlerp(a: Quat, b: Quat, f: float) -> Quat:
+ dot = sum(x * y for x, y in zip(a, b, strict=True))
+ if dot < 0:
+ b = tuple(-v for v in b) # type: ignore[assignment]
+ q = _lerp(a, b, f)
+ n = math.sqrt(sum(v * v for v in q)) or 1.0
+ return tuple(v / n for v in q) # type: ignore[return-value]
+
+
+def sample_clip(glb: Glb, anim: dict, t: float) -> dict[int, tuple[Vec3, Quat, Vec3]]:
+ """Local TRS per animated node at time t (rest values fill the untouched parts)."""
+ nodes = glb.doc["nodes"]
+ state: dict[int, list] = {}
+ for channel in anim["channels"]:
+ target = channel["target"]
+ if "node" not in target:
+ continue
+ idx = target["node"]
+ if idx not in state:
+ state[idx] = list(node_local_trs(nodes[idx]))
+ sampler = anim["samplers"][channel["sampler"]]
+ times = [v[0] for v in accessor_values(glb, sampler["input"])]
+ values = accessor_values(glb, sampler["output"])
+ if not times:
+ continue
+ interp = sampler.get("interpolation", "LINEAR")
+ if interp == "CUBICSPLINE":
+ values = values[1::3] # the in-tangent/value/out-tangent triplets → values
+ if t <= times[0]:
+ v = values[0]
+ elif t >= times[-1]:
+ v = values[-1]
+ else:
+ k = 0
+ while k + 1 < len(times) and times[k + 1] < t:
+ k += 1
+ f = (t - times[k]) / (times[k + 1] - times[k]) if times[k + 1] > times[k] else 0.0
+ if interp == "STEP":
+ v = values[k]
+ elif target["path"] == "rotation":
+ v = _nlerp(values[k], values[k + 1], f) # type: ignore[arg-type]
+ else:
+ v = _lerp(values[k], values[k + 1], f)
+ slot = {"translation": 0, "rotation": 1, "scale": 2}.get(target["path"])
+ if slot is not None:
+ state[idx][slot] = tuple(v)
+ return {i: (tuple(s[0]), tuple(s[1]), tuple(s[2])) for i, s in state.items()} # type: ignore[misc]
+
+
+def joint_positions_over_clip(
+ glb: Glb, anim: dict, joint_names: list[str], samples: int = 48
+) -> dict[str, list[Vec3]]:
+ names = node_index_by_name(glb.doc)
+ duration = clip_duration(glb, anim)
+ out: dict[str, list[Vec3]] = {n: [] for n in joint_names}
+ for k in range(samples):
+ t = duration * k / samples
+ trs = sample_clip(glb, anim, t)
+ local = {i: mat_from_trs(*v) for i, v in trs.items()}
+ worlds = world_matrices(glb.doc, local)
+ for n in joint_names:
+ if n in names:
+ m = worlds[names[n]]
+ out[n].append((m[12], m[13], m[14]))
+ return out
+
+
+def measure_stride(glb: Glb, anim: dict, feet: list[str], samples: int = 48) -> float:
+ """Ground distance one loop covers: twice the mean forward (Z) excursion of the feet."""
+ tracks = joint_positions_over_clip(glb, anim, feet, samples)
+ excursions = []
+ for name in feet:
+ zs = [p[2] for p in tracks.get(name, [])]
+ if zs:
+ excursions.append(max(zs) - min(zs))
+ if not excursions:
+ return 0.0
+ return 2.0 * sum(excursions) / len(excursions)
+
+
+# ---------------------------------------------------------------------------
+# mesh facts
+# ---------------------------------------------------------------------------
+
+
+def triangle_count(doc: dict, mesh: dict) -> int:
+ total = 0
+ for prim in mesh["primitives"]:
+ mode = prim.get("mode", 4)
+ if mode != 4:
+ continue
+ if "indices" in prim:
+ total += doc["accessors"][prim["indices"]]["count"] // 3
+ else:
+ total += doc["accessors"][prim["attributes"]["POSITION"]]["count"] // 3
+ return total
+
+
+def mesh_bounds(doc: dict, mesh: dict) -> tuple[Vec3, Vec3]:
+ lo = [math.inf] * 3
+ hi = [-math.inf] * 3
+ for prim in mesh["primitives"]:
+ acc = doc["accessors"][prim["attributes"]["POSITION"]]
+ for k in range(3):
+ lo[k] = min(lo[k], acc["min"][k])
+ hi[k] = max(hi[k], acc["max"][k])
+ return (lo[0], lo[1], lo[2]), (hi[0], hi[1], hi[2])
+
+
+def skinned_mesh_nodes(doc: dict) -> list[int]:
+ return [i for i, n in enumerate(doc.get("nodes", [])) if "mesh" in n and "skin" in n]
+
+
+def figure_extras(doc: dict) -> dict | None:
+ return (doc.get("asset", {}).get("extras") or {}).get("jarvis_figure")
+
+
+def part_extras(doc: dict) -> dict | None:
+ return (doc.get("asset", {}).get("extras") or {}).get("jarvis_part")
diff --git a/scripts/figures/sources/kaykit-adventurers.json b/scripts/figures/sources/kaykit-adventurers.json
new file mode 100644
index 0000000000..14ea901e69
--- /dev/null
+++ b/scripts/figures/sources/kaykit-adventurers.json
@@ -0,0 +1,100 @@
+{
+ "$comment": "KayKit Character Pack: Adventurers 1.0 by Kay Lousberg — CC0 (LICENSE.txt in the repo). Used as the biped skeleton + clip base (character-pipeline.md §8 route A, §11). Every file is fetched by URL into scripts/figures/cache/ and verified by sha256 before the build touches it.",
+ "name": "KayKit Character Pack: Adventurers 1.0",
+ "author": "Kay Lousberg (kaylousberg.com)",
+ "license": "CC0-1.0",
+ "license_url": "https://github.com/KayKit-Game-Assets/KayKit-Character-Pack-Adventures-1.0/blob/main/LICENSE.txt",
+ "base_url": "https://raw.githubusercontent.com/KayKit-Game-Assets/KayKit-Character-Pack-Adventures-1.0/main/addons/kaykit_character_pack_adventures/Characters/gltf/",
+ "files": {
+ "Rogue.glb": "e825437cd4d2ee9c1960b517a74a69101e33eb409ae7fa8cedc7134a998fbb7d",
+ "Knight.glb": "60428e3abc09ba83e595d256e3af8c5c976b46cdae599f0802fc82b4a3445168",
+ "Mage.glb": "cf898585da33fab50c724d31605fb931eb2912e6d2280092141e98ca81ad507d"
+ },
+ "atlas_grid": { "columns": 8, "rows": 4 },
+ "fps": 30,
+ "bone_map": {
+ "root": "root",
+ "hips": "hips",
+ "spine": "spine",
+ "chest": "chest",
+ "head": "head",
+ "upperarm.l": "upper_arm_l",
+ "lowerarm.l": "lower_arm_l",
+ "wrist.l": "wrist_l",
+ "hand.l": "hand_l",
+ "handslot.l": "handslot_l",
+ "upperarm.r": "upper_arm_r",
+ "lowerarm.r": "lower_arm_r",
+ "wrist.r": "wrist_r",
+ "hand.r": "hand_r",
+ "handslot.r": "handslot_r",
+ "upperleg.l": "upper_leg_l",
+ "lowerleg.l": "lower_leg_l",
+ "foot.l": "foot_l",
+ "toes.l": "toes_l",
+ "upperleg.r": "upper_leg_r",
+ "lowerleg.r": "lower_leg_r",
+ "foot.r": "foot_r",
+ "toes.r": "toes_r"
+ },
+ "drop_bone_patterns": ["IK", "control-"],
+ "clip_map": {
+ "idle": "Idle",
+ "walk": "Walking_A",
+ "run": "Running_A",
+ "work": "Spellcasting",
+ "talk": "Use_Item",
+ "sit": "Sit_Chair_Idle",
+ "sleep": "Lie_Idle",
+ "celebrate": "Cheer",
+ "wave": "Interact"
+ },
+ "characters": {
+ "Rogue": {
+ "body_meshes": [
+ "Rogue_Body",
+ "Rogue_Head",
+ "Rogue_ArmLeft",
+ "Rogue_ArmRight",
+ "Rogue_LegLeft",
+ "Rogue_LegRight"
+ ],
+ "cell_map": {
+ "*": {
+ "c0r0": "skin",
+ "c1r0": "hair",
+ "c2r0": "eyes",
+ "c3r0": "metal",
+ "c0r1": "primary",
+ "c1r1": "secondary_shade",
+ "c5r0": "secondary",
+ "c6r0": "leather",
+ "c7r1": "leather",
+ "c5r2": "primary",
+ "c3r2": "primary_shade"
+ },
+ "Rogue_Head": { "c3r0": "eye_white" },
+ "Rogue_LegLeft": { "c7r1": "shoes" },
+ "Rogue_LegRight": { "c7r1": "shoes" }
+ },
+ "default_palette": {
+ "skin": "#f4b68f",
+ "skin_shade": "#d99a75",
+ "hair": "#9e5d47",
+ "eyes": "#1b2427",
+ "primary": "#096153",
+ "primary_shade": "#07483d",
+ "secondary": "#b16f51",
+ "secondary_shade": "#008c55",
+ "accent": "#e8c46b",
+ "metal": "#919da2",
+ "leather": "#9a5944",
+ "fur": "#b87556",
+ "fur_shade": "#8d4c39",
+ "shoes": "#4a2e22",
+ "eye_white": "#e6ecef",
+ "emissive": "#ffd166"
+ }
+ }
+ }
+}
diff --git a/tests/unit/ui/test_society_figures_gate.py b/tests/unit/ui/test_society_figures_gate.py
new file mode 100644
index 0000000000..bd57176dcf
--- /dev/null
+++ b/tests/unit/ui/test_society_figures_gate.py
@@ -0,0 +1,107 @@
+"""The figure gate must hold: every shipped society figure honours the contract,
+and the gate still catches a figure that breaks it.
+
+A character that faces -Z walks backwards on the island; a clip with root
+motion slides its feet; a mirrored node shades inside out. Nothing but the
+gate reads the binary, so these tests protect the gate's teeth, not one asset
+(docs/agent-society/character-pipeline.md §10).
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+_REPO = Path(__file__).resolve().parents[3]
+_GATE = _REPO / "scripts" / "ci" / "check_society_figures.py"
+_TOOLS = _REPO / "scripts" / "figures" / "glb_tools.py"
+_FIGURES = _REPO / "jarvis" / "ui" / "web" / "frontend" / "src" / "assets" / "society" / "figures"
+
+
+def _load(path: Path, name: str):
+ if name in sys.modules:
+ return sys.modules[name]
+ spec = importlib.util.spec_from_file_location(name, path)
+ mod = importlib.util.module_from_spec(spec)
+ assert spec and spec.loader
+ sys.modules[name] = mod # dataclasses need the module registered before exec
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _shipped() -> list[Path]:
+ return sorted(_FIGURES.rglob("*.glb")) if _FIGURES.exists() else []
+
+
+def test_every_shipped_figure_honours_the_contract():
+ gate = _load(_GATE, "check_society_figures")
+ results = gate.check_dir(_FIGURES) if _FIGURES.exists() else {}
+ failed = {k: v for k, v in results.items() if v}
+ assert failed == {}, f"figures violating the contract: {json.dumps(failed, indent=2)}"
+
+
+def test_png_codec_round_trips():
+ gt = _load(_TOOLS, "glb_tools")
+ rows = [
+ bytes(b for x in range(16) for b in ((x * 7) & 0xFF, (y * 13) & 0xFF, 200, 255))
+ for y in range(4)
+ ]
+ data = gt.encode_png(16, 4, rows, 4)
+ w, h, channels, decoded = gt.decode_png(data)
+ assert (w, h, channels) == (16, 4, 4)
+ assert decoded == rows
+
+
[email protected](not _shipped(), reason="no figure asset built yet")
+ "mutate, expected",
+ [
+ ("turn_around", "faces the wrong way"),
+ ("mirror", "negative/zero scale"),
+ ("drop_walk", "clip 'walk' missing"),
+ ("root_motion", "root motion"),
+ ("blur", "NEAREST"),
+ ],
+)
+def test_the_gate_catches_a_broken_figure(tmp_path: Path, mutate: str, expected: str):
+ gate = _load(_GATE, "check_society_figures")
+ gt = _load(_TOOLS, "glb_tools")
+ source = _shipped()[0]
+ glb = gt.read_glb(source)
+ doc = glb.doc
+ names = gt.node_index_by_name(doc)
+ if mutate == "turn_around":
+ doc["nodes"][names["FWD"]]["translation"] = [0.0, 0.5, -1.0]
+ elif mutate == "mirror":
+ doc["nodes"][names["hips"]]["scale"] = [-1.0, 1.0, 1.0]
+ elif mutate == "drop_walk":
+ doc["animations"] = [a for a in doc["animations"] if a.get("name") != "walk"]
+ elif mutate == "root_motion":
+ walk = gt.clip_by_name(doc, "walk")
+ root = names["root"]
+ # Point a thigh's rotation output at the root's translation: a walking
+ # thigh swings, so the root now drifts in XZ (any spread > 1e-3 counts).
+ thigh = names["upper_leg_l"]
+ for ch in walk["channels"]:
+ if ch["target"] == {"node": thigh, "path": "rotation"}:
+ ch["target"] = {"node": root, "path": "translation"}
+ break
+ elif mutate == "blur":
+ for sampler in doc["samplers"]:
+ sampler["magFilter"] = 9729
+ broken = tmp_path / source.name
+ gt.write_glb(broken, doc, glb.blob)
+ (tmp_path / "SOURCES.md").write_text(
+ f"| `{source.name}` | test | CC0 | - | mutated |\n", encoding="utf-8"
+ )
+ problems = gate.check_file(broken, sources_md=tmp_path / "SOURCES.md")
+ assert any(expected in p for p in problems), f"gate missed {mutate!r}: {problems}"
+
+
+def test_main_reports_skipped_when_nothing_is_shipped(tmp_path: Path):
+ gate = _load(_GATE, "check_society_figures")
+ assert gate.main([str(tmp_path)]) == gate.EXIT_SKIPPED