Subagent: Two-handed longsword clips

agent
Claude Code subagent (clips2h)
model
claude-opus-5-5
harness
Claude Code
started
2026-11-10 11:09 UTC
took
70 min · 249 turns

user

+0:00
<teammate-message teammate_id="team-lead" summary="Two-handed longsword clips"> You are helping finish one character ("Wren") in the lowmarch repo, a code-built anime character pipeline. Work ONLY in the git worktree `~/Projects/lowmarch-fable52` (branch `fable52`). Your job: author two-handed longsword battle clips for her, in a new file `tools/whole/clips2h.py`.

Hard rules

  • Edit files only under ~/Projects/lowmarch-fable52. Create only tools/whole/clips2h.py (plus scratch files under review/out/whole-clips/, which is git-ignored). Do NOT edit tools/whole/build.py, tools/whole/shoot.py, or any existing repo file; if you need a change there, say so in your report. Do not commit.
  • [redacted: private path]/ is read-only data. Never write there. Never run tools/cage.py (it writes there). Never touch [redacted: private path] or any other repo.
  • Headless only. No Windows programs, nothing under /mnt/c, no installs, no full test suite, no ssh, no network uploads, never push. Don't contact other sessions; don't use led, cw, tracker.
  • Always run python with OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 (numpy thread overhead otherwise triples run time). Run python3 without -I.
  • The Yin/Yang rigs and FE8 references under the data dir are off limits (don't open or show them).

Context you need

  • tools/whole/build.py builds the character "wren" (body arm_f_slender, a cached VRoid body) with a costume and animation clips into a site folder, and tools/whole/shoot.py SPEC.json OUT.png shoots a frame of that site headless in the project's painted renderer (7 s a frame). Read both files first (they're short), then tools/clips.py (the existing one-handed "sword" clips and the two-handed "polearm" clips, which are your closest template), tools/rig.py (Rig: leg_ik, aim, grip, arm_ik, rotate_world, pos, held; grip_points), tools/duel.py (clear_grip, stance, and how the duel grips a two-handed sword: "a two-handed fighter's left fist sits 9.5 cm down the grip"), tools/poses.py, tools/checks.py (Body.clearance, Body.worst, report), and tools/outfit.py sword() (the sword is rigid in the RIGHT hand; in the hand's frame the blade runs along (0,0,-1): clips.BLADE).
  • build.py already has the hook: when env WHOLE_STANCE=longsword, it calls clips2h.clips(vrm, shape) (your file, imported from tools/whole/) instead of the kit's clips. It must return the same structure as tools/clips.py: {"idle": [(t, pose), ...], "attack": [(t, pose), ...]} with pose dicts as the kit uses them. Keep the attack's total length near 1.5 s and the idle a loop near 2 s (first and last pose equal).
  • Model coordinates: metres, y up, the character's forward is -z, the character's left is -x (see tools/outfit.py side_of). The sword in the current costume (outfit.knight_dress) is sword(fit, "R", blade_len=0.84, blade_w=0.046, grip_len=0.21, ...): a long grip meant for two hands. The costume will be replaced by a new one (shorter split surcoat over breeches, a cuirass, a bigger pauldron on the LEFT shoulder), but the sword keeps about those dimensions, so design the clips for the body, not the dress.
  • A test site for you already exists: review/out/whole-clips/site (a copy of the built site, including the enemy soldier, whose 9 minute build you must not repeat). Rebuild only her into it with: LOWMARCH_SITE=whole-clips WHOLE_STANCE=longsword OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 tools/whole/build.py arm_f_slender wren (about 30 s; it prints the arm-through-body checks per keyframe). Shoot with WHOLE_SITE=review/out/whole-clips/site python3 tools/whole/shoot.py SPEC.json OUT.png. tools/whole/frame.json is a working spec: copy it, set "w": 960, "h": 540, "scale": 1 for quick looks, change clips (e.g. {"wren": ["attack", 0.56], "mob_soldier": ["idle", 0.0]}), place (her yaw 62 faces screen right with her front turned toward the camera; 90 is pure profile), size (metres of height in frame) and centre. Write specs and PNGs under review/out/whole-clips/shots/. Look at the PNGs yourself with the Read tool; judge them as pictures.

What the clips must do

  1. Both hands on the grip in every key: right fist just under the cross-guard, left fist lower on the grip near the pommel (about 9 to 11 cm from the right fist along the grip, measured the way duel.py does). Use rig.grip/duel.clear_grip so the fists really land on the grip and the blade points where the key says.
  2. Idle: a proper longsword guard that reads well from the side battle camera (for example a middle guard with the point toward the enemy's face, or a high "roof" guard; pick what looks best in the frame), weight sunk a little, lead (left) foot forward, shoulders turned, a slow breathing loop. Not a T-pose with a sword: elbows bent and relaxed, no locked straight arms.
  3. Attack: anticipation (a wind-up that pulls the blade back and up over the right shoulder while the weight shifts back), a committed descending diagonal cut with a lunge step of the lead foot and hip/shoulder rotation, a follow-through low on the left, then a recovery to the guard. Give it clear arcs and a little overshoot; timing roughly like the kit's attack (wind by 0.32 to 0.44 s, cut at 0.56, follow 0.68 to 1.05, home by 1.5).
  4. No arm through the body: the build's check lines ("N with an arm through the body") must report none for both clips. The current one-handed attack fails this at 0.68 s and 1.05 s (right upper arm 2.7 cm inside the body); don't repeat it. Also keep the blade and the hands out of her own head, hair mass and the left pauldron's space (assume a pauldron standing 5 to 6 cm off the left shoulder), and keep the head looking at the enemy.
  5. Feet planted or stepped with leg IK (no sliding, no feet under the ground), hips not hyperextended.

Deliver

  • tools/whole/clips2h.py with a short docstring, written in the repo's terse style (no em dashes in comments).
  • A contact sheet PNG at review/out/whole-clips/shots/sheet.png: about 8 tiles at 960x540 (idle at 2 times, attack at 0.20, 0.38, 0.56, 0.68, 0.90, 1.30 s), built from your shots with PIL.
  • A report: what the guard and attack are, the check output lines from your final build, anything that still looks wrong in the pictures (be blunt; your eye is a floor, not a verdict), wall time spent on each step (solve, build, shoot), and any change you need in build.py.
</teammate-message>

agent

+0:03
  • Bashwc -l tools/whole/build.py tools/whole/shoot.py tools/clips.py tools/rig.py tools/duel.py tools/poses.py tools/checks.py tools/outfit.py && ls tools/whole review/out/whole-clips review/out/whole-clips/site && cat tools/whole/frame.json

    command

    wc -l tools/whole/build.py tools/whole/shoot.py tools/clips.py tools/rig.py tools/duel.py tools/poses.py tools/checks.py tools/outfit.py && ls tools/whole review/out/whole-clips review/out/whole-clips/site && cat tools/whole/frame.json

    result, 79 lines

       137 tools/whole/build.py
       108 tools/whole/shoot.py
       139 tools/clips.py
       190 tools/rig.py
       140 tools/duel.py
       115 tools/poses.py
       300 tools/checks.py
      1272 tools/outfit.py
      2401 total
    review/out/whole-clips:
    site
    
    review/out/whole-clips/site:
    camera.json
    checks.json
    index.html
    mob_soldier.glb.json
    plains.glb.json
    wren.glb.json
    
    tools/whole:
    build.py
    frame.json
    notes
    __pycache__
    shoot.py
    {
     "w": 1920,
     "h": 1080,
     "scale": 2,
     "size": 2.3,
     "pitch": 7,
     "yaw": 0,
     "centre": [
      -0.07,
      1.02,
      0
     ],
     "place": {
      "wren": {
       "pos": [
        -0.9,
        0,
        0
       ],
       "yaw": 62
      },
      "mob_soldier": {
       "pos": [
        1.3,
        0,
        0
       ],
       "yaw": -70
      }
     },
     "clips": {
      "wren": [
       "attack",
       0.4
      ],
      "mob_soldier": [
       "idle",
       0.0
      ]
     },
     "key": {
      "wren": [
       0.85,
       0.42,
       0.3
      ]
     },
     "sky": [
      "#8fb4d6",
      "#c9dde6",
      "#eef0e2"
     ]
    }
  • Bashcat tools/whole/build.py tools/whole/shoot.py tools/clips.py

    command

    cat tools/whole/build.py tools/whole/shoot.py tools/clips.py

    result, 384 lines

    """One whole character on a current armory body: dressed by the old costume kit, rigged with the battle clips,
    built into a painted-renderer site of its own.
    
      OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 tools/whole/build.py [BODY [NAME...]]
          -> review/out/whole/site/ (git-ignored). BODY: an armory body (default arm_f_slender).
          NAME: rebuild only these (wren, mob_soldier); the others stay as last built.
    
    Reads the cached cage body; never rebuilds one. Nothing in cage's cache key is touched.
    One numpy thread matters: measured 2026-11-10, her build took 84 s with the default threads (most of it system
    time) and 22 to 25 s with one. The soldier took 513 s with the default threads; not re-measured with one.
    Then: python3 tools/whole/shoot.py tools/whole/frame.json OUT.png (7 s a frame).
    """
    import json
    import os
    import shutil
    import sys
    import time
    
    os.environ.setdefault("LOWMARCH_SITE", "whole")
    HERE = os.path.dirname(os.path.abspath(__file__))
    ROOT = os.path.dirname(os.path.dirname(HERE))
    sys.path[:0] = [os.path.join(ROOT, "review", "vroid-02"), HERE]
    import build  # noqa: E402  (puts tools/ and art/cast on the path)
    import outfit  # noqa: E402
    import terrain  # noqa: E402
    import clips  # noqa: E402
    import numpy as np  # noqa: E402
    import cast  # noqa: E402
    from cast import CAST  # noqa: E402
    
    NAME = "wren"
    BODY = sys.argv[1] if len(sys.argv) > 1 else "arm_f_slender"
    
    
    def smooth_plate(pc, under, rounds=60, every=1, clear=0.006):
        """A breastplate as one rigid shell: its inside smoothed with its rims held, then kept
        `clear` off it. On this body the kit's plate came out moulded to the bust, with the bodice showing through."""
        pos, tri = pc["pos"].copy(), pc["tri"]
        n = len(pos)
        rim = np.zeros(n, bool)
        for loop in pc.get("loops", []):
            rim[np.asarray(loop)] = True
        e = np.concatenate([tri[:, [0, 1]], tri[:, [1, 2]], tri[:, [2, 0]], tri[:, [1, 0]], tri[:, [2, 1]], tri[:, [0, 2]]])
        deg = np.maximum(np.bincount(e[:, 0], minlength=n), 1)[:, None]
        for k in range(rounds):
            acc = np.zeros_like(pos)
            np.add.at(acc, e[:, 0], pos[e[:, 1]])
            pos[~rim] = (acc / deg)[~rim]
            if k % every == every - 1 or k == rounds - 1:
                d, cp, ti = under.query(pos)
                low = (~rim) & (d < clear)
                pos[low] = cp[low] + under.fn[ti[low]] * clear
        pc["pos"] = pos
        pc["nrm"] = outfit.vertex_normals(pos, tri)
        return pc
    
    
    def dress(fit):
        """Elaine's knight dress, minus her kit hair: the body keeps the VRoid hair its head came with."""
        out = []
        for pc in outfit.knight_dress(fit):
            m = pc["material"]
            if pc.get("role") == "hair" or "bun" in m or "braid" in m or "ribbon" in m or "HAIR" in m.upper():
                continue
            out.append(pc)
        by = {pc["material"]: pc for pc in out}
        plate, bodice = by.get("OUTFIT_breastplate"), by.get("OUTFIT_bodice")
        if PLATE_FIX and plate is not None and bodice is not None:
            smooth_plate(plate, outfit.Surface(bodice["pos"], bodice["tri"]))
        return out
    
    
    PLATE_FIX = os.environ.get("PLATE_FIX", "1") == "1"
    outfit.COSTUMES["whole_knight"] = dress
    src, ela = CAST[BODY], CAST["elaine"]
    HAIR, EYE = cast.HAIRS["auburn"], cast.EYES["amber"]
    # her own colours (not Elaine's blonde and blue, which was drawn after another studio's character): auburn hair,
    # one deep teal cloth, warm steel, a cream hem
    CAST[NAME] = dict(src, label="Wren", costume="whole_knight", stance="sword",
                      shape=dict(src["shape"], rest={"Fcl_BRW_Angry": 0.3}),
                      colors=dict(src["colors"], A=HAIR[0], B=HAIR[1], C=HAIR[2], D=HAIR[3], E=HAIR[4], r=EYE[0], s=EYE[1], t=EYE[2],
                                  K="#0f2e2c", L="#17474a", M="#1f6064", P="#4a9a96", Q="#0f111b", R="#1b1e2c", S="#2a2e42", T="#41465e"),
                      paint=dict(ela["paint"], signature="#1d5b5e", doublet="#1c2026", heraldry="#efe6d2", steel="#c3c6cc",
                                 gold="#c29a4a", hair=HAIR[2], grain=dict(signature=0.015)))
    # her stance: "sword" is the kit's one-handed clips; "longsword" is tools/whole/clips2h.py (both hands on the grip)
    STANCE = os.environ.get("WHOLE_STANCE", "sword")
    CAST[NAME]["stance"] = STANCE
    _kit_clips = clips.clips
    
    
    def _clips(vrm, shape=None, stance="sword"):
        if stance == "longsword":
            import clips2h
            return clips2h.clips(vrm, shape)
        return _kit_clips(vrm, shape, stance)
    
    
    clips.clips = _clips
    FOE = "mob_soldier"                                     # the enemy across from her: the old kit's soldier, as built
    build.LABELS = {NAME: "Wren", FOE: "Soldier"}
    _model_path = build.model_path
    build.model_path = lambda name, c: _model_path(BODY if name == NAME else name, CAST[BODY] if name == NAME else c)
    _plains = terrain.plains
    terrain.plains = lambda **kw: _plains(**dict(dict(width=9.0, depth=3.2, tufts=70, stones=9), **kw))   # room for two and a wide frame
    # where each stands on the stage (metres). Yaw 90 faces screen right in profile and -90 screen left; nearer 0 turns
    # the front toward the camera. The frame spec's own "place" overrides this without a rebuild.
    PLACE = {NAME: dict(pos=[-0.9, 0, 0.0], yaw=62), FOE: dict(pos=[1.3, 0, 0.0], yaw=-70)}
    
    if __name__ == "__main__":
        t0 = time.time()
        os.makedirs(build.OUT, exist_ok=True)
        want = [n for n in (NAME, FOE) if not sys.argv[2:] or n in sys.argv[2:]]
        entries, chk = [], {}
        old = json.load(open(f"{build.OUT}/camera.json")) if os.path.exists(f"{build.OUT}/camera.json") else {}
        prev = {c["name"]: c for c in old.get("characters", [])}
        for n in (NAME, FOE):
            if n not in want:
                entries.append(prev[n])
                continue
            t1 = time.time()
            r = build.character((n, None))
            print(f"{n}.glb {r['size'] / 1e6:.1f} MB, {time.time() - t1:.0f}s")
            print("  " + r["checks"]["summary"])
            for item in r["checks"]["through"]:
                print("    ! " + item["text"])
            entries.append(dict(name=n, label=build.LABELS[n], info=r["info"], cams=r["cams"]))
            chk[n] = r["checks"]
        build.scenery(NAME)
        cam = entries[0]["cams"]["battle"]
        out = dict(characters=entries,
                   duel=dict(order=dict(player=NAME, opponent=FOE), place=PLACE,
                             cam=dict(cam, pivot_px=[cam["w"] // 2, cam["pivot_px"][1]]), clip="idle"),
                   lineup=dict(order=[], spacing=0.95))
        json.dump(out, open(f"{build.OUT}/camera.json", "w"), indent=1, default=build.as_list)
        json.dump(chk, open(f"{build.OUT}/checks.json", "w"), indent=1)
        shutil.copy(os.path.join(ROOT, "review", "vroid-02", "index.html"), build.OUT)
        print(f"-> {build.OUT}  {time.time() - t0:.0f}s")
    """Shoot one composed battle frame from the built site (tools/whole/build.py), headless, in the painted renderer.
    
      python3 tools/whole/shoot.py SPEC.json OUT.png
    
    Works on a patched scratch copy of the site: the page in the repo is not changed. The patch lets the duel sheet take
    its tiles from the URL, pose each fighter with a clip and time of their own, move the key light, and paint a sky.
    SPEC: w, h (pixels), scale, size (metres of height in frame), pitch, yaw (the stage's turn), centre [x, y, z],
    clips {name: [clip, seconds]}, place {name: {pos, yaw}}, key [x, y, z] or {name: [x, y, z]} (optional), sky [top, bottom] (optional), hide [...].
    """
    import base64
    import io
    import json
    import os
    import re
    import shutil
    import socket
    import subprocess
    import sys
    import tempfile
    import time
    import urllib.parse
    
    from PIL import Image
    
    ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    SITE = os.environ.get("WHOLE_SITE", os.path.join(ROOT, "review", "out", "whole", "site"))
    
    PATCHES = [
        # tiles from the URL
        ("function holdPose(clip, t) {",
         'if (params.get("tiles")) DUEL_ROWS.splice(0, DUEL_ROWS.length, ...JSON.parse(params.get("tiles")));\n'
         "function holdPose(clip, t) {"),
        # a clip and a time per fighter
        ("    const a = c.actions[clip] || c.actions.idle;\n    a.reset(); a.setEffectiveWeight(1); a.play(); a.time = t; c.mixer.update(0);",
         "    const own = clip && typeof clip === 'object' ? (clip[c.name] || ['idle', 0]) : [clip, t];\n"
         "    if (own[0] === 'ref') continue;\n"
         "    const a = c.actions[own[0]] || c.actions.idle;\n    a.reset(); a.setEffectiveWeight(1); a.play(); a.time = own[1]; c.mixer.update(0);"),
        # the key light, and a centre for the frame
        ("      frameAt(centre, h, tw_, th_, pitch);",
         "      if (tile.centre) centre = new THREE.Vector3(...tile.centre);\n"
         "      if (tile.key) active().forEach(c => {            // one key for all, or one per fighter by name\n"
         "        const kv = Array.isArray(tile.key) ? tile.key : tile.key[c.name]; if (!kv) return;\n"
         "        const k = new THREE.Vector3(...kv).normalize();\n"
         "        [...c.meshes, ...c.cloths.map(cl => cl.display)].forEach(o => { const m = o && o.userData.mats && o.userData.mats.painted;\n"
         "          if (m && m.uniforms.uKind.value !== 6) m.uniforms.uKey.value.copy(k); }); });\n"
         "      frameAt(centre, h, tw_, th_, pitch);"),
        # where each fighter stands, from the URL
        ("        const pl = CAM.duel.place[c.name];",
         '        const pl = (params.get("place") ? JSON.parse(params.get("place")) : CAM.duel.place)[c.name];'),
        # a sky behind the tile
        ("      ctx.drawImage(R.domElement, x, y0, tw_, th_);",
         "      if (tile.sky) { const g = ctx.createLinearGradient(0, y0, 0, y0 + th_);\n"
         "        tile.sky.forEach((c, i) => g.addColorStop(i / (tile.sky.length - 1), c));\n"
         "        ctx.fillStyle = g; ctx.fillRect(x, y0, tw_, th_); }\n"
         "      ctx.drawImage(R.domElement, x, y0, tw_, th_);"),
    ]
    
    
    def patched_site():
        d = tempfile.mkdtemp(prefix="whole_site_")
        for f in os.listdir(SITE):
            if f != "index.html":
                os.symlink(os.path.join(SITE, f), os.path.join(d, f))
        s = open(os.path.join(SITE, "index.html")).read()
        for old, new in PATCHES:
            if s.count(old) != 1:
                raise SystemExit(f"patch target not found once: {old[:60]!r}")
            s = s.replace(old, new)
        open(os.path.join(d, "index.html"), "w").write(s)
        return d
    
    
    def shoot(spec, out):
        scale = spec.get("scale", 2)
        tile = dict(clip=spec["clips"], t=0, yaw=spec.get("yaw", 0), pitch=spec.get("pitch", 6), size=spec.get("size", 2.3),
                    label="", **{k: spec[k] for k in ("centre", "key", "sky", "hide") if k in spec})
        rows = [dict(label="", tw=spec["w"] // scale, th=spec["h"] // scale, tiles=[tile])]
        site = patched_site()
        s = socket.socket()
        s.bind(("127.0.0.1", 0))
        port = s.getsockname()[1]
        s.close()
        server = subprocess.Popen([sys.executable, "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", site],
                                  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        try:
            time.sleep(0.5)
            url = f"http://127.0.0.1:{port}/index.html?sheet=duel&scale={scale}&tiles={urllib.parse.quote(json.dumps(rows))}"
            if spec.get("place"):
                url += f"&place={urllib.parse.quote(json.dumps(spec['place']))}"
            r = subprocess.run([os.environ.get("CHROMIUM", "/snap/bin/chromium"), "--headless=new", "--use-angle=swiftshader",
                                "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist", "--window-size=1280,900",
                                "--virtual-time-budget=600000", "--dump-dom", url], capture_output=True, text=True, timeout=900)
            m = re.search(r'id="sheetOut"[^>]*>[redacted: data-URI prefix]([A-Za-z0-9+/=]+)<', r.stdout)
            if not m:
                err = re.search(r'id="sheetOut"[^>]*>([^<]*)<', r.stdout)
                raise SystemExit("FAILED " + (err.group(1)[:400] if err else r.stderr[-800:]))
            im = Image.open(io.BytesIO(base64.b64decode(m.group(1))))
            gap, head = 6, 30                                   # the sheet's margins: crop to the one tile
            im.crop((gap, gap + head, gap + spec["w"], gap + head + spec["h"])).convert("RGB").save(out)
        finally:
            server.terminate()
            shutil.rmtree(site, ignore_errors=True)
    
    
    if __name__ == "__main__":
        t0 = time.time()
        shoot(json.load(open(sys.argv[1])), sys.argv[2])
        print(sys.argv[2], f"{time.time() - t0:.0f}s")
    """Battle animation clips, authored as a few key poses and finished with the rig tools (feet
    planted or stepped with leg IK, the sword aimed by direction rather than by wrist angles).
    
      clips(vrm, shape, stance) -> {name: [(time, pose), ...]}
    """
    import numpy as np
    
    import poses as P
    from rig import Rig
    
    BLADE = (0, 0, -1)          # the sword's blade in the right hand's frame (see outfit.sword)
    
    
    def clips(vrm, shape=None, stance="sword"):
        """stance: "sword" (one hand, the cast's default) or "polearm" (both hands, see polearm())."""
        if stance == "polearm":
            return polearm(vrm, shape)
        rig = Rig(vrm, shape)
        idle = P.BATTLE_IDLE
        foot = {s: rig.pos(idle, f"J_Bip_{s}_Foot") for s in "LR"}
        step = np.array([0.0, 0.0, -0.36])                     # the lead (left) foot steps forward
    
        def finish(pose, lead=0.0, blade=None):
            pose = rig.leg_ik(pose, "L", foot["L"] + step * lead)
            pose = rig.leg_ik(pose, "R", foot["R"])
            if blade is not None:
                pose = rig.aim(pose, "J_Bip_R_Hand", BLADE, blade)
            return pose
    
        wind = finish(P.WIND_UP, 0.0, blade=(0.15, 0.55, 1.0))       # blade back over the shoulder
        slash = finish(P.SLASH, 1.0, blade=(0.1, -0.55, -1.0))       # forward and down through the target
        follow = finish(P.FOLLOW, 1.0, blade=(-0.45, -1.0, -0.15))   # carried down across the body
        breathe = finish(P.IDLE_BREATH, 0.0)
        return {
            "idle": [(0.0, idle), (0.9, breathe), (1.8, idle)],
            "attack": [(0.0, idle), (0.32, wind), (0.44, wind), (0.56, slash), (0.68, follow), (1.05, follow),
                       (1.5, idle)],
        }
    
    
    def fists(rig):
        """Where each fist closes in the reference pose: the point a held weapon's shaft runs through, as
        gear._hand_frame places it (rig.grip_points: measured from the curled fingers)."""
        from rig import grip_points
        return {side: g["point"] for side, g in grip_points(rig.v, rig.shape, P.BUST).items()}
    
    
    # The polearm's keys: hips drop and forward shift, turn of the shoulders (- brings the left one
    # forward), forward lean, the lead foot's step; the right fist from the right shoulder in arm lengths
    # (x: the fighter's right, -z forward), the shaft's direction (head end), and the left arm's reach
    # (shoulder to fist, in arm lengths): the left fist holds the shaft where that reach meets it, so
    # every build gets bent elbows rather than a fixed hand spacing that some arms can't span.
    POLEARM = {
        "wind": dict(drop=0.075, turn=-26.0, lean=3.0, fwd=-0.03, lead=0.0, fist=(0.13, -0.52, -0.04),
                     shaft=(-0.22, 0.30, -0.93), reach=0.78),
        "thrust": dict(drop=0.09, turn=-18.0, lean=14.0, fwd=0.17, lead=0.30, fist=(-0.10, -0.42, -0.50),
                       shaft=(-0.28, 0.06, -0.96), reach=0.92),
        "follow": dict(drop=0.095, turn=-16.0, lean=16.0, fwd=0.19, lead=0.30, fist=(-0.12, -0.46, -0.52),
                       shaft=(-0.28, 0.0, -0.96), reach=0.92),
    }
    # The guard's idle, after the study of Unicorn Overlord's idles (a mercenary's, tracked frame by frame):
    # a 2 s loop with the feet planted; the hips sink about 2% of the height and ease forward, the chest
    # sinks further (the lean deepens) and the head stays level; a slow rise, a short hold at the top, a
    # quicker sink and a longer settle; the weapon's head dips as the body sinks, a beat behind it.
    # GUARD_TOP and GUARD_LOW are the two ends; IDLE_SINK says how far sunk (0 top, 1 low) over the loop,
    # eased between its points; the loop is sampled every IDLE_STEP and each sample grips afresh.
    GUARD_TOP = dict(drop=0.050, turn=-14.0, lean=3.0, fwd=0.0, lead=0.0, fist=(0.04, -0.60, -0.26),
                     shaft=(-0.32, 0.44, -0.84), reach=0.80)
    GUARD_LOW = dict(drop=0.092, turn=-16.0, lean=11.0, fwd=0.014, lead=0.0, fist=(0.04, -0.60, -0.26),
                     shaft=(-0.32, 0.37, -0.87), reach=0.80)
    IDLE_LOOP, IDLE_STEP, SHAFT_LAG = 2.0, 0.1, 0.1
    IDLE_SINK = [(0.0, 1.0), (0.15, 1.0), (0.85, 0.0), (1.15, 0.0), (1.55, 1.0), (2.0, 1.0)]
    
    
    def sink(t):
        """How far sunk the guard is at time t of the idle loop (0 top .. 1 low), eased between points."""
        t = t % IDLE_LOOP
        for (t0, a), (t1, b) in zip(IDLE_SINK[:-1], IDLE_SINK[1:]):
            if t0 <= t <= t1:
                x = (t - t0) / max(t1 - t0, 1e-9)
                return a + (b - a) * x * x * (3 - 2 * x)
        return IDLE_SINK[-1][1]
    
    
    def guard_at(t):
        """The guard's parameters at time t of the idle loop."""
        k, ks = sink(t), sink(t - SHAFT_LAG)
        out = {n: (GUARD_TOP[n] + (GUARD_LOW[n] - GUARD_TOP[n]) * k) if isinstance(GUARD_TOP[n], float) else GUARD_TOP[n]
               for n in GUARD_TOP}
        out["shaft"] = tuple(a + (b - a) * ks for a, b in zip(GUARD_TOP["shaft"], GUARD_LOW["shaft"]))
        return out
    
    
    def polearm(vrm, shape=None, keys=None):
        """A halberd in both hands (it is rigid on the right hand), after the study's soldiers: a wide,
        low guard, left foot forward, the shaft across the body with its head forward and up, the right
        fist by the hip and the left up the shaft at chest height, elbows bent and out of the body. The
        attack draws the shaft back and thrusts it forward on a lunge, both hands on it throughout.
        Each key grips with rig.grip so the left fist lands on the shaft where the right hand holds it."""
        from checks import Body
        from duel import clear_grip
        rig = Rig(vrm, shape)
        body = Body(vrm, shape)
        f = fists(rig)
        ref = dict(ref_pose=P.BUST, fist_R=f["R"], fist_L=f["L"])
        base = P.merge(P.BATTLE_IDLE, P.fist("L"))
        foot = {s: rig.pos(base, f"J_Bip_{s}_Foot") for s in "LR"}
        arm = {s: rig.pos(P.BUST, f"J_Bip_{s}_LowerArm") - rig.pos(P.BUST, f"J_Bip_{s}_UpperArm") for s in "LR"}
        span = {s: float(np.linalg.norm(arm[s]) + np.linalg.norm(f[s] - rig.pos(P.BUST, f"J_Bip_{s}_LowerArm"))) for s in "LR"}
    
        def guard(drop, turn, lean, fwd, lead, fist, shaft, reach):
            # the lean comes mostly from the hips: a bent spine pushed the breastplate's hem through the belt
            pose = P.merge(base, {
                "J_Bip_C_Hips": P.move(0, -drop, -fwd, P.rot((1, 0, 0), -lean * 0.65)),
                "J_Bip_C_Spine": P.rot((0, 1, 0), turn * 0.6) @ P.rot((1, 0, 0), -lean * 0.2),
                "J_Bip_C_Chest": P.rot((0, 1, 0), turn * 0.4) @ P.rot((1, 0, 0), -lean * 0.15),
                "J_Bip_C_Neck": P.rot((0, 1, 0), -turn * 0.5) @ P.rot((1, 0, 0), lean * 0.35),
                "J_Bip_C_Head": P.rot((0, 1, 0), -turn * 0.3) @ P.rot((1, 0, 0), lean * 0.35)})   # the gaze stays level
            pose = rig.leg_ik(pose, "L", foot["L"] + np.array([-0.07, 0, -0.14 - lead]))
            pose = rig.leg_ik(pose, "R", foot["R"] + np.array([0.06, 0, 0.12]), pole=(0, -0.2, -1))
            D = np.asarray(shaft, float) / np.linalg.norm(shaft)
            fr = rig.pos(pose, "J_Bip_R_UpperArm") + span["R"] * np.asarray(fist, float)
            # the left fist: the point up the shaft at `reach` from the left shoulder
            q = fr - rig.pos(pose, "J_Bip_L_UpperArm")
            b, c = float(D @ q), float(q @ q) - (reach * span["L"]) ** 2
            t = -b + np.sqrt(max(b * b - c, 0.0))          # (out of reach: the shaft's nearest point)
            t = float(np.clip(t, 0.22, 0.48))
            pose = clear_grip(rig, body, pose, "R", ref, fr, D, (0.6, -0.4, 0.7))
            return clear_grip(rig, body, pose, "L", ref, fr + D * t, D, (-0.8, -1.0, 0.1))
        k = {n: guard(**v) for n, v in (keys or POLEARM).items()}
        n = int(round(IDLE_LOOP / IDLE_STEP))
        idle = [(round(i * IDLE_STEP, 3), guard(**guard_at(i * IDLE_STEP))) for i in range(n)]
        idle.append((IDLE_LOOP, idle[0][1]))                     # the loop closes on its first pose
        rest = idle[0][1]
        return {
            "idle": idle,
            "attack": [(0.0, rest), (0.32, k["wind"]), (0.44, k["wind"]), (0.56, k["thrust"]), (0.68, k["follow"]),
                       (1.05, k["follow"]), (1.5, rest)],
        }
  • Bashcat tools/rig.py tools/duel.py tools/poses.py

    command

    cat tools/rig.py tools/duel.py tools/poses.py

    result, 445 lines

    """Small rig tools for authoring poses on a VRoid skeleton: rotate a bone in world space, two-bone
    leg and arm IK, aiming a held prop (the sword) at a direction, and gripping a sword so its blade
    runs through a given point.
    
    Poses here are the same dicts as tools/poses.py (bone name -> 3x3 or 4x4 adjustment in the bone's
    own frame). Everything is solved in model space (VRoid: the character faces -z, y up).
    """
    import numpy as np
    
    from poses import as4
    
    
    def rot_between(a, b):
        a = np.asarray(a, float) / np.linalg.norm(a)
        b = np.asarray(b, float) / np.linalg.norm(b)
        v, c = np.cross(a, b), float(np.dot(a, b))
        if c < -0.999999:
            axis = np.cross(a, [1, 0, 0]) if abs(a[0]) < 0.9 else np.cross(a, [0, 1, 0])
            axis /= np.linalg.norm(axis)
            return 2 * np.outer(axis, axis) - np.eye(3)
        vx = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
        return np.eye(3) + vx + vx @ vx / (1 + c)
    
    
    class Rig:
        def __init__(self, vrm, shape=None, ortho=False):
            """ortho: rotate bones through the parent's pure rotation (exact with scaled bones, see
            rotate_world). Off by default so clips authored before it (Aldric's, frozen) stay identical."""
            import vroid_portrait as vp
            self.v = vrm
            self.shape = dict(vp.NEUTRAL, **(shape or {}))
            self.names = vrm.nodes_by_name()
            self._bp = vp.bone_pose
            self.ortho = ortho
            self._par = vrm.parents()
    
        def world(self, pose):
            return self.v.node_world(self._bp(self.v, self.shape, pose))
    
        def pos(self, pose, bone):
            return self.world(pose)[self.names[bone]][:3, 3]
    
        def rotate_world(self, pose, bone, R):
            """Pre-multiply the bone's world rotation by R (about its joint) by editing its local pose.
            With proportion scales on the skeleton the bone's world matrix is not a rotation; the
            default (legacy) form then leaks shear into the pose and an iterated solve can diverge.
            ortho mode conjugates by the pure rotation of the frame the adjustment lives in."""
            W = self.world(pose)
            i = self.names[bone]
            cur = W[i][:3, :3]
            adj_old = as4(pose.get(bone, np.eye(3)))
            if self.ortho:
                par = self._par.get(i)
                base = (W[par] if par is not None else np.eye(4)) @ self.v.local_matrix(i, None)
                u, _, vt = np.linalg.svd(base[:3, :3])
                Q = u @ vt                                               # nearest rotation
                out = dict(pose)
                a = adj_old.copy()
                a[:3, :3] = Q.T @ R @ Q @ adj_old[:3, :3]
                out[bone] = a
                return out
            base = cur @ np.linalg.inv(adj_old[:3, :3])                 # world rotation without this bone's adjustment
            new_rot = np.linalg.inv(base) @ (R @ cur)
            out = dict(pose)
            a = adj_old.copy()
            a[:3, :3] = new_rot
            out[bone] = a
            return out
    
        def leg_ik(self, pose, side, target, pole=(0, 0, -1)):
            """Bend the leg so the ankle lands on `target`, knee toward `pole` (forward)."""
            up, lo, ft = f"J_Bip_{side}_UpperLeg", f"J_Bip_{side}_LowerLeg", f"J_Bip_{side}_Foot"
            H, K, A = self.pos(pose, up), self.pos(pose, lo), self.pos(pose, ft)
            l1, l2 = np.linalg.norm(K - H), np.linalg.norm(A - K)
            T = np.asarray(target, float)
            d = np.clip(np.linalg.norm(T - H), 1e-4, l1 + l2 - 1e-4)
            u = (T - H) / np.linalg.norm(T - H)
            w = np.asarray(pole, float) - u * np.dot(pole, u)
            w /= np.linalg.norm(w)
            ca = np.clip((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1)
            K2 = H + l1 * (ca * u + np.sqrt(1 - ca * ca) * w)
            pose = self.rotate_world(pose, up, rot_between(K - H, K2 - H))
            K, A = self.pos(pose, lo), self.pos(pose, ft)
            return self.rotate_world(pose, lo, rot_between(A - K, H + u * d - K))
    
        def plant_feet(self, pose, reference):
            """Keep both ankles where they are in `reference` (feet stay on the ground while the hips move)."""
            for side in "LR":
                pose = self.leg_ik(pose, side, self.pos(reference, f"J_Bip_{side}_Foot"))
            return pose
    
        def aim(self, pose, bone, local_dir, target_dir):
            """Turn `bone` so its local direction (e.g. the sword blade, hand -z) points along target_dir."""
            W = self.world(pose)[self.names[bone]][:3, :3]
            cur = W @ np.asarray(local_dir, float)
            return self.rotate_world(pose, bone, rot_between(cur, target_dir))
    
        def arm_ik(self, pose, side, target, pole):
            """Bend the arm so the wrist lands on `target`, elbow toward `pole`."""
            up, lo, hd = f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_Hand"
            S, E, W = self.pos(pose, up), self.pos(pose, lo), self.pos(pose, hd)
            l1, l2 = np.linalg.norm(E - S), np.linalg.norm(W - E)
            T = np.asarray(target, float)
            d = np.clip(np.linalg.norm(T - S), abs(l1 - l2) + 1e-3, l1 + l2 - 1e-4)
            u = (T - S) / np.linalg.norm(T - S)
            w = np.asarray(pole, float) - u * np.dot(pole, u)
            w /= np.linalg.norm(w)
            ca = np.clip((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1)
            E2 = S + l1 * (ca * u + np.sqrt(1 - ca * ca) * w)
            pose = self.rotate_world(pose, up, rot_between(E - S, E2 - S))
            E, W = self.pos(pose, lo), self.pos(pose, hd)
            return self.rotate_world(pose, lo, rot_between(W - E, S + u * d - E))
    
        def held(self, pose, bone, ref_pose, point):
            """Where a point attached to `bone` (given in the reference pose, model space) is in `pose`."""
            i = self.names[bone]
            M = self.world(pose)[i] @ np.linalg.inv(self.world(ref_pose)[i])
            return M[:3, :3] @ np.asarray(point, float) + M[:3, 3]
    
        def grip(self, pose, side, ref_pose, fist_ref, fist_target, blade_dir, pole, local_blade=(0, 0, -1), iters=14):
            """Put the fist (a point on the hand, from the reference pose) on `fist_target` with the hand's
            `local_blade` axis along `blade_dir`. An analytic arm IK gets close (elbow toward `pole`);
            then cyclic corrections that measure the real fist after every step (aim the hand, swing
            the forearm, swing the upper arm) finish it, which converges even when proportion scales
            shear the arm and the analytic solve alone undershoots."""
            hd, lo, up = f"J_Bip_{side}_Hand", f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_UpperArm"
            T = np.asarray(fist_target, float)
            D = np.asarray(blade_dir, float) / np.linalg.norm(blade_dir)
            wrist = T - (self.held(pose, hd, ref_pose, fist_ref) - self.pos(pose, hd))
            pose = self.arm_ik(pose, side, wrist, pole)
            for _ in range(iters):
                for _ in range(2):
                    M = self.world(pose)[self.names[hd]][:3, :3]
                    pose = self.rotate_world(pose, hd, rot_between(M @ np.asarray(local_blade, float), D))
                for bone in (lo, up):
                    j = self.pos(pose, bone)
                    f = self.held(pose, hd, ref_pose, fist_ref)
                    if np.linalg.norm(f - j) > 1e-4 and np.linalg.norm(T - j) > 1e-4:
                        pose = self.rotate_world(pose, bone, rot_between(f - j, T - j))
                miss = np.linalg.norm(T - self.held(pose, hd, ref_pose, fist_ref))
                M = self.world(pose)[self.names[hd]][:3, :3]
                bd = M @ np.asarray(local_blade, float)
                if miss < 2e-3 and np.dot(bd / np.linalg.norm(bd), D) > 0.9995:
                    break
            for _ in range(2):                              # the blade direction is what reads; finish on it
                M = self.world(pose)[self.names[hd]][:3, :3]
                pose = self.rotate_world(pose, hd, rot_between(M @ np.asarray(local_blade, float), D))
            return pose
    
    
    def grip_points(vrm, shape, ref_pose, fingers=("Index", "Middle", "Ring", "Little")):
        """Where each fist closes: the centre of the hole the curled fingers make (poses.fist), in model
        space in `ref_pose` (the hand doesn't move when the fingers curl, so a weapon built there and bound
        to the hand sits in the fist whenever the fingers are curled). Each finger's joints and fingertip
        (the last segment again, bent by its own joint) are fitted with a circle in the plane across the
        hole (the hand's local z runs through it, palm to fingertips in x and y); the hole's centre is the
        mean of the fingers' circle centres. A fixed offset from the wrist, tuned on one hand, missed on
        larger or differently made hands (the shaft ran over the knuckles, the fingers closed under it).
        Returns {side: dict(point, axis, radius)}: radius is the finger-centreline circle's (the shaft's
        radius plus a finger's half-thickness fits)."""
        import vroid_portrait as vp
        import poses as P
        sh = dict(vp.NEUTRAL, **(shape or {}))
        names = vrm.nodes_by_name()
        out = {}
        for side in "LR":
            sx = 1.0 if side == "R" else -1.0
            W = vrm.node_world(vp.bone_pose(vrm, sh, P.merge(ref_pose, P.fist(side))))
            H = W[names[f"J_Bip_{side}_Hand"]]
            R = H[:3, :3] / np.linalg.norm(H[:3, :3], axis=0)
            o, e1, e2, ax = H[:3, 3], R[:, 0] * sx, R[:, 1], R[:, 2]
            cs, axial, rads = [], [], []
            for f in fingers:
                ks = [names.get(f"J_Bip_{side}_{f}{k}") for k in (1, 2, 3)]
                if any(k is None for k in ks):
                    continue
                js = [W[k][:3, 3] for k in ks]
                M3 = W[ks[2]][:3, :3] / np.linalg.norm(W[ks[2]][:3, :3], axis=0)
                pts = js + [js[2] + M3 @ np.array([sx, 0.0, 0.0]) * 0.85 * np.linalg.norm(js[2] - js[1])]
                Q = np.array([[(p - o) @ e1, (p - o) @ e2] for p in pts])
                A = np.c_[2 * Q, np.ones(len(Q))]                       # algebraic circle fit
                b = (Q ** 2).sum(1)
                cx, cy, c0 = np.linalg.lstsq(A, b, rcond=None)[0]
                cs.append((cx, cy))
                rads.append(float(np.sqrt(c0 + cx * cx + cy * cy)))
                axial.append(float((js[0] - o) @ ax))
            c = np.mean(cs, 0)
            out[side] = dict(point=o + c[0] * e1 + c[1] * e2 + np.mean(axial) * ax, axis=ax, radius=float(np.mean(rads)),
                             centres=[o + x * e1 + y * e2 + a * ax for (x, y), a in zip(cs, axial)])
        return out
    """Two characters locked in a sword bind (a struggle over crossed blades), authored on one shared
    stage so the blades really meet.
    
    Stage space is the viewer's world: x to the right, y up, z toward the default camera. A character
    stands at `pos`, turned `yaw` degrees about y. Its GLB faces +z (the exporter's FLIP of VRoid's -z),
    so model point m lands at  pos + Ry(yaw) @ (FLIP * m).  The player stands on the right facing left,
    the opponent on the left facing right, both turned a little toward the camera (the study: battle
    sprites are drawn three-quarter, not in profile).
    
    Each character's sword is rigid on its right hand (outfit.sword): the fist point and blade axis are
    taken from the hand in the reference pose. Arms reach with rig.grip so each blade runs through the
    shared crossing point; a two-handed fighter's left fist sits further down the grip.
    
      duel_clips({name: (vrm, shape, ref_pose, sword_info)}, cast) -> {name: [(t, pose)...]}, placements
    """
    import math
    
    import numpy as np
    
    import poses as P
    from rig import Rig
    
    FLIP = np.array([-1.0, 1.0, -1.0])
    
    
    def ry(deg):
        a = math.radians(deg)
        return np.array([[math.cos(a), 0, math.sin(a)], [0, 1, 0], [-math.sin(a), 0, math.cos(a)]])
    
    
    def to_model(w, place):
        return FLIP * (ry(-place["yaw"]) @ (np.asarray(w, float) - np.asarray(place["pos"], float)))
    
    
    def dir_to_model(d, place):
        return FLIP * (ry(-place["yaw"]) @ np.asarray(d, float))
    
    
    # The bind, in stage space. Fists sit below and outside the crossing point; the blades rise
    # through it in an X above the fighters' heads.
    CROSS = np.array([0.0, 1.47, -0.02])
    SIDES = {
        # name: stands on, turned, fist offset from the crossing point, hands, stance. `reach`, if given,
        # places the fighter instead of `x`: where the fist sits from the chest across and forward (model
        # space x, z: +x the fighter's right, -z forward). A two-handed grip close in and a little to the
        # left keeps both arms bent and out of the body (checks.Body measured 2 cm clear; further out,
        # the short left arm straightens across the chest)
        "player": dict(x=0.66, yaw=-62.0, fist=(0.29, -0.25, -0.07), two_hands=False, step=(0.20, 0.22)),
        "opponent": dict(yaw=62.0, fist=(-0.22, -0.25, 0.04), two_hands=True, step=(0.09, 0.11),   # a long dress: a short stance
                         reach=(-0.04, -0.29)),
    }
    # elbow directions tried for a gripping arm (model space, right arm; mirrored for the left): the
    # first that keeps the arm clear of the body wins, else the clearest
    POLES = [(0.9, -0.8, 0.0), (1.0, -0.5, -0.2), (0.6, -1.0, -0.3), (1.0, -0.2, -0.4), (0.4, -1.0, 0.6)]
    CLEAR = 0.02
    # the struggle: the crossing point drifts toward whoever is giving ground; hips press in
    BEATS = [(0.0, 0.0), (0.8, 1.0), (1.6, -1.0), (2.4, 0.0)]      # (time, push: + player winning)
    
    
    def stance(rig, base, lead_step=0.20, back_step=0.22, spread=0.11, drop=0.07, lean=9.0, push=0.0):
        """A fencing stance in model space: left foot forward, right foot back, knees bent, hips low,
        torso leaning into the bind. push > 0 presses forward, < 0 gives ground."""
        pose = P.merge(base, {
            "J_Bip_C_Hips": P.move(0, -drop, -0.035 - 0.025 * push),
            "J_Bip_C_Spine": P.rot((1, 0, 0), -lean * 0.5 - 2.5 * push),
            "J_Bip_C_Chest": P.rot((1, 0, 0), -lean * 0.5 - 1.5 * push),
            "J_Bip_C_Neck": P.rot((1, 0, 0), 6 + 2 * push),
            "J_Bip_C_Head": P.rot((1, 0, 0), 4),
        })
        foot = {s: rig.pos(base, f"J_Bip_{s}_Foot") for s in "LR"}
        lead = foot["L"] + np.array([-spread * 0.3, 0, -lead_step])
        back = foot["R"] + np.array([spread * 0.3, 0, back_step])
        pose = rig.leg_ik(pose, "L", lead, pole=(0, 0, -1))
        return rig.leg_ik(pose, "R", back, pole=(0, -0.2, -1))
    
    
    def placements(order, chars=None):
        """order: {"player": name, "opponent": name} -> {name: {pos, yaw}}. A side with `reach` stands
        where its fist (chest + reach, in its stance) lands on its fist point in the bind; height
        follows from the fist point."""
        out = {}
        for r in ("player", "opponent"):
            sd, name = SIDES[r], order[r]
            if "reach" not in sd:
                out[name] = dict(pos=[sd["x"], 0.0, 0.0], yaw=sd["yaw"])
                continue
            c = chars[name]
            rig = Rig(c["vrm"], c["shape"], ortho=True)
            pose = stance(rig, P.BATTLE_IDLE, lead_step=sd["step"][0], back_step=sd["step"][1])
            fist_m = rig.pos(pose, "J_Bip_C_UpperChest") + np.array([sd["reach"][0], 0.0, sd["reach"][1]])
            pos = CROSS + np.array(sd["fist"]) - ry(sd["yaw"]) @ (FLIP * fist_m)
            out[name] = dict(pos=[round(float(pos[0]), 4), 0.0, round(float(pos[2]), 4)], yaw=sd["yaw"])
        return out
    
    
    def clear_grip(rig, body, pose, side, c, fist_m, blade_m, pole0):
        """rig.grip, trying elbow directions until the arm clears the body (a checks.Body)."""
        mirror = np.array([-1.0, 1.0, 1.0]) if side == "L" else np.ones(3)
        limbs = [f"{side}_UpperArm", f"{side}_LowerArm", f"{side}_Hand"]
        best = None
        for pole in [pole0] + [tuple(np.array(q) * mirror) for q in POLES]:
            p = rig.grip(pose, side, c["ref_pose"], c[f"fist_{side}"], fist_m, blade_m, pole=pole)
            cl = body.worst(p, limbs)
            if cl >= CLEAR:
                return p
            if best is None or cl > best[0]:
                best = (cl, p)
        return best[1]
    
    
    def duel_clips(chars, order):
        """chars: {name: dict(vrm, shape, ref_pose, fist_R, fist_L)} (fists: reference-pose model points on
        each hand). Returns {name: [(t, pose), ...]} for the 'clash' clip, and the placements."""
        from checks import Body
        place = placements(order, chars)
        out = {}
        for role in ("player", "opponent"):
            name = order[role]
            c, sd, pl = chars[name], SIDES[role], place[name]
            rig = Rig(c["vrm"], c["shape"], ortho=True)
            body = Body(c["vrm"], c["shape"]) if sd["two_hands"] else None
            base = P.merge(P.BATTLE_IDLE, P.fist("L") if sd["two_hands"] else {})
            keys = []
            for t, push in BEATS:
                mine = push if role == "player" else -push
                cross = CROSS + np.array([-0.035 * push, -0.012 * abs(push), 0])
                fist_w = cross + np.array(sd["fist"]) + np.array([-0.02 * push, 0, 0]) * (1 if role == "player" else 1)
                blade_w = (cross - fist_w) / np.linalg.norm(cross - fist_w)
                fist_m, blade_m = to_model(fist_w, pl), dir_to_model(blade_w, pl)
                pose = stance(rig, base, lead_step=sd["step"][0], back_step=sd["step"][1], push=mine)
                if sd["two_hands"]:                          # both arms in front of the body: keep them out of it
                    pose = clear_grip(rig, body, pose, "R", c, fist_m, blade_m, (0.7, -1.0, 0.35))
                    pose = clear_grip(rig, body, pose, "L", c, fist_m - blade_m * 0.095, blade_m, (-0.7, -1.0, 0.35))
                else:                                        # free arm (shield) braced low and out for balance
                    pose = rig.grip(pose, "R", c["ref_pose"], c["fist_R"], fist_m, blade_m, pole=(0.7, -1.0, 0.35))
                    pose = rig.arm_ik(pose, "L", rig.pos(pose, "J_Bip_L_UpperArm") + np.array([-0.12, -0.38, 0.06]),
                                      pole=(-0.3, -0.2, 1.0))
                keys.append((t, pose))
            out[name] = keys
        return out, place
    """Poses for VRoid skeletons: bone name -> 3x3 rotation applied in the bone's own (rest) frame.
    
    Rest pose is a T-pose with identity bone rotations, so local axes start aligned with the model:
    x = character's left is -x, y up, the character faces -z. For the RIGHT arm the bones run along
    +x and the palm faces -y; for the LEFT arm along -x.
    """
    import math
    
    import numpy as np
    
    
    def rot(axis, deg):
        a = math.radians(deg)
        c, s = math.cos(a), math.sin(a)
        x, y, z = np.asarray(axis, float) / np.linalg.norm(axis)
        return np.array([[c + x * x * (1 - c), x * y * (1 - c) - z * s, x * z * (1 - c) + y * s],
                         [y * x * (1 - c) + z * s, c + y * y * (1 - c), y * z * (1 - c) - x * s],
                         [z * x * (1 - c) - y * s, z * y * (1 - c) + x * s, c + z * z * (1 - c)]])
    
    
    def as4(r):
        r = np.asarray(r, float)
        if r.shape == (4, 4):
            return r
        m = np.eye(4)
        m[:3, :3] = r
        return m
    
    
    def move(dx=0.0, dy=0.0, dz=0.0, r=None):
        """A 4x4 adjustment: translate (in the bone's parent frame units, metres) and optionally rotate."""
        m = as4(np.eye(3) if r is None else r)
        m[:3, 3] = (dx, dy, dz)
        return m
    
    
    def merge(*poses):
        out = {}
        for p in poses:
            for k, r in p.items():
                out[k] = as4(out[k]) @ as4(r) if k in out else r
        return out
    
    
    def fist(side, curl=(70, 85, 55), thumb=35):
        """Curl the fingers of one hand toward the palm (a grip)."""
        sz = -1 if side == "R" else 1               # rotation about local z that bends toward -y
        out = {}
        for f in ("Index", "Middle", "Ring", "Little"):
            for i, a in enumerate(curl, 1):
                out[f"J_Bip_{side}_{f}{i}"] = rot((0, 0, 1), sz * a)
        out[f"J_Bip_{side}_Thumb2"] = rot((0, 1, 0), (1 if side == "R" else -1) * thumb)
        out[f"J_Bip_{side}_Thumb3"] = rot((0, 0, 1), sz * 30)
        return out
    
    
    # Bust: arms down from the T-pose, shoulders relaxed.
    BUST = {"J_Bip_L_UpperArm": rot((0, 0, 1), 72), "J_Bip_R_UpperArm": rot((0, 0, 1), -72),
            "J_Bip_L_Shoulder": rot((0, 0, 1), 6), "J_Bip_R_Shoulder": rot((0, 0, 1), -6)}
    
    # Battle idle: sword in the right hand held forward, left arm loose, feet apart.
    BATTLE_IDLE = merge(BUST, {
        "J_Bip_R_UpperArm": rot((0, 1, 0), 18),       # swing the right arm a little forward
        "J_Bip_R_LowerArm": rot((0, 1, 0), 55),       # bend the elbow, forearm forward
        "J_Bip_R_Hand": rot((1, 0, 0), -20),          # tip the blade up a little
        "J_Bip_L_LowerArm": rot((0, 1, 0), -20),
        "J_Bip_L_UpperLeg": rot((0, 0, 1), -5) @ rot((1, 0, 0), 8),
        "J_Bip_R_UpperLeg": rot((0, 0, 1), 5) @ rot((1, 0, 0), -10),
        "J_Bip_R_LowerLeg": rot((1, 0, 0), 12),
    }, fist("R"), fist("L", curl=(25, 35, 20), thumb=10))

    45 more lines not shown.