agent (cont.)

+27:47
  • write_file{"Content":"\"\"\"Build and shoot one composed tactics battle frame on MakeHuman-caged VRoid bodies.\n\nUses the project's cached caged bodies (arm_f_strong, arm_m_strong), parametric armour and\ngarment kits (outfit.py, plates.py, gear.py, hair.py), IK stances (rig.py, clips.py, duel.py),\nterrain (terrain.py), and painted WebGL renderer (review/slice/index.html).\n\n python3 tools/battle_slice.py [--png ~/out/battle_frame.png]\n\"\"\"\nimport argparse\nimport base64\nimport json\nimport math\nimport os\nimport re\nimport socket\nimport subprocess\nimport sys\nimport time\n\nimport numpy as np\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(HERE)\nsys.path[:0] = [HERE, os.path.join(ROOT, \"art\", \"cast\")]\n\nimport cage # noqa: E402\nimport checks # noqa: E402\nimport duel # noqa: E402\nimport export_glb # noqa: E402\nimport gear as G # noqa: E402\nimport hair as H # noqa: E402\nimport mobs # noqa: E402\nimport outfit as O # noqa: E402\nimport poses as P # noqa: E402\nimport terrain # noqa: E402\nimport vroid_portrait as vp # noqa: E402\nfrom cast import CAST # noqa: E402\nfrom fitting import Surface, merge_surfaces # noqa: E402\nfrom plates import LimbChart, flat_piece, outline_plate # noqa: E402\nfrom rig import Rig, grip_points # noqa: E402\n\nSLICE_HTML = os.path.join(ROOT, \"review\", \"slice\", \"index.html\")\nOUT_DIR = os.path.join(ROOT, \"review\", \"out\", \"slice\")\nLOCAL_THREE = \"~/context/sortie-node_modules/three\"\n\n\ndef cached_cage_vrm(name):\n \"\"\"Resolve a pre-built caged VRM strictly read-only.\"\"\"\n p = cage.path_for(name, CAST[name][\"cage\"])\n if not os.path.exists(p):\n raise SystemExit(f\"Missing cached cage body: {p}\")\n return p\n\n\ndef arm_room(v, shape, need=0.008, most=16):\n limbs = [f\"{s}_{a}\" for s in \"LR\" for a in (\"UpperArm\", \"LowerArm\")]\n for deg in range(0, most + 1, 2):\n b = checks.Body(v, dict(shape, arm_out=float(deg)))\n if min(b.worst(pose, limbs) for pose in (P.BUST, P.BATTLE_IDLE)) >= need:\n return float(deg)\n return float(most)\n\n\ndef add_scalp_cap(fit, hairline_front=52.0):\n \"\"\"Dark inner hair under-cap 2 mm off the skull so parted or warped VRoid hair never shows pale scalp.\"\"\"\n ch = H.head_chart(fit)\n hl = lambda u: float(np.interp(abs(u), [0, 38, 68, 105, 145, 180],\n [hairline_front, hairline_front + 6, 82, 118, 134, 140]))\n pc = H.cap(\"scalp_cap\", ch, hl, lift=0.0022, crown=0.0010, nu=64, nv=20, role=\"hair_cap\")\n fit.bind(pc, rigid=\"J_Bip_C_Head\")\n pc[\"group\"] = \"hair\"\n return pc\n\n\ndef knightly_longsword(fit, hand=\"R\", blade_len=0.86, blade_w=0.044, grip_len=0.17):\n \"\"\"Arming/bastard sword with curved crossguard quillons, faceted wheel pommel, and fuller.\"\"\"\n fist, fwd, side, flat, _ = G._hand_frame(fit, hand)\n out = [\n O.tube(\"grip\", \"leather\", fist - fwd * grip_len * 0.56, fwd, grip_len, 0.0135),\n O.ball(\"pommel\", \"gold\", fist - fwd * (grip_len * 0.56 + 0.018), 0.022, squash=(1.0, 0.58, 1.0)),\n O.ball(\"pommel_boss\", \"steel\", fist - fwd * (grip_len * 0.56 + 0.018), 0.013, squash=(1.0, 0.78, 1.0)),\n ]\n guard_c = fist + fwd * (grip_len * 0.44 + 0.008)\n ts = np.linspace(-1.0, 1.0, 17)\n q_pts = np.array([guard_c + side * (0.088 * x) + fwd * (0.014 * x * x) for x in ts])\n out.append(O.pipe(\"guard\", \"gold\", q_pts, r=0.0068, seg=8))\n for sx in (-1.0, 1.0):\n out.append(O.ball(f\"quillon_{1 if sx > 0 else 0}\", \"gold\",\n guard_c + side * (0.090 * sx) + fwd * 0.015, 0.009))\n\n base = guard_c + fwd * 0.008\n rows = 14\n P_grid = np.zeros((5, rows, 3))\n for j, t in enumerate(np.linspace(0, 1, rows)):\n taper = 1.0 if t < 0.80 else max(0.0, (1.0 - t) / 0.20) ** 0.85\n w = blade_w / 2 * (1.0 - 0.18 * t) * taper\n th = 0.0048 * taper\n c = base + fwd * blade_len * t\n P_grid[:, j] = [c + side * w, c + flat * th, c - side * w, c - flat * th, c + side * w]\n pos, tri = O.grid_mesh(P_grid)\n out.append(O.piece(\"blade\", \"steel\", pos, tri, outward_from=base + fwd * blade_len / 2, axis=fwd))\n for sg in (-1.0, 1.0):\n out.append(O.ribbon(\n f\"fuller_{1 if sg > 0 else 0}\", \"metal\",\n [base + fwd * blade_len * t + flat * (sg * 0.0049) for t in np.linspace(0.03, 0.68, 10)],\n width=blade_w * 0.16, lift=0.0004, normals=np.tile(flat * sg, (10, 1))\n ))\n for pc in out:\n fit.bind(pc, rigid=f\"J_Bip_{hand}_Hand\")\n pc[\"group\"] = \"sword\"\n return out\n\n\ndef crescent_poleaxe(fit, length=1.96, grip=0.54, hand=\"R\", name=\"poleaxe\"):\n \"\"\"Bearded crescent halberd/poleaxe with honed edge bevel, back fluke, spear tip, brass collars, and tassel.\"\"\"\n fist, fwd, side, flat, _ = G._hand_frame(fit, hand)\n start = fist - fwd * grip\n out = [O.tube(f\"{name}_haft\", \"wood\", start, fwd, length, 0.015)]\n top = start + fwd * length\n\n # Bearded crescent axe blade\n a = np.linspace(-1.0, 1.0, 17)\n edge = [(0.19 * (0.76 + 0.24 * math.cos(x * 1.15)), -0.05 + 0.15 * x) for x in a]\n cres = [\n (0.018, -0.09),\n (0.075, -0.19),\n ] + edge + [\n (0.065, 0.10),\n (0.018, 0.045),\n ]\n bevel_line = [(0.165 * (0.76 + 0.24 * math.cos(x * 1.15)), -0.05 + 0.14 * x) for x in a]\n deco = [(\"line\", bevel_line, 0.0035, \"groove\")]\n out.append(flat_piece(f\"{name}_blade\", \"steel\", cres, top - fwd * 0.11, side, fwd, thickness=0.008, decal=deco))\n\n # Curved rear fluke hook\n hook = [(-0.018, -0.06), (-0.095, -0.095), (-0.135, -0.045), (-0.090, 0.015), (-0.018, 0.025)]\n out.append(flat_piece(f\"{name}_fluke\", \"steel\", hook, top - fwd * 0.11, side, fwd, thickness=0.007))\n\n # Tapered diamond spear spike\n spike = [(0.0, -0.01), (0.024, 0.045), (0.014, 0.16), (0.0, 0.29), (-0.014, 0.16), (-0.024, 0.045)]\n out.append(flat_piece(f\"{name}_spike\", \"steel\", spike, top - fwd * 0.02, side, fwd, thickness=0.008))\n\n # Steel langet socket + brass collar rings + crimson tassel\n out.append(O.tube(f\"{name}_socket\", \"steel\", top - fwd * 0.30, fwd, 0.29, 0.018))\n for k, off in enumerate((0.02, 0.29)):\n c_ring = top - fwd * off\n ang = np.linspace(0, 2 * math.pi, 18, endpoint=False)\n ring = np.array([c_ring + (side * math.cos(th) + flat * math.sin(th)) * 0.020 for th in ang])\n out.append(O.pipe(f\"{name}_collar{k}\", \"gold\", ring, r=0.0038, seg=6, closed=True))\n\n tassel_root = top - fwd * 0.30 - side * 0.018\n t_pts = np.array([tassel_root + np.array([0.0, -0.032 * s, 0.008 * s]) - side * (0.018 * s)\n for s in np.linspace(0, 1, 7)])\n out.append(O.pipe(f\"{name}_tassel\", \"signature\", t_pts, r=0.0075, seg=6))\n out.append(O.ball(f\"{name}_butt\", \"steel\", start - fwd * 0.012, 0.019, squash=(1, 1, 1.5)))\n G._bind(fit, out, f\"J_Bip_{hand}_Hand\")\n return G._group(out, \"weapon\")\n\n\ndef cloak_clasps(fit, under, role=\"gold\", cord_role=\"gold\", y_off=-0.036, x_deg=34.0):\n \"\"\"Pair of domed collarbone cloak-clasps with a draped chest cord between them.\"\"\"\n nk = fit.bone[\"J_Bip_C_Neck\"]\n pts = []\n out = []\n for k, sgn in enumerate((-1.0, 1.0)):\n a = math.radians(sgn * x_deg)\n d = np.array([math.sin(a), 0.0, -math.cos(a)])\n o = np.array([nk[0], nk[1] + y_off, nk[2]])\n r = under.cast(o, d, rmax=0.26, far=True)\n p = o + d * ((0.09 if np.isnan(r) else r) + 0.008)\n pts.append(p)\n cl = O.ball(f\"clasp_{k}\", role, p, 0.014, seg=12, rows=7, squash=(1.0, 1.0, 0.55))\n fit.bind(cl, rigid=\"J_Bip_C_UpperChest\")\n cl[\"group\"] = \"trim\"\n out.append(cl)\n ts = np.linspace(0, 1, 15)\n cord = []\n for t in ts:\n q = pts[0] * (1 - t) + pts[1] * t + np.array([0.0, -0.022 * math.sin(math.pi * t), -0.010 * math.sin(math.pi * t)])\n cord.append(q)\n cp = O.pipe(\"clasp_cord\", cord_role, np.array(cord), r=0.0032, seg=6)\n fit.bind(cp, rigid=\"J_Bip_C_UpperChest\")\n cp[\"group\"] = \"trim\"\n out.append(cp)\n return out\n\n\ndef vanguard_captain(fit):\n \"\"\"Original Lowmarch vanguard officer costume fitted to arm_f_strong.\"\"\"\n B = fit.bone\n hips, nk = B[\"J_Bip_C_Hips\"], B[\"J_Bip_C_Neck\"]\n knee = B[\"J_Bip_L_LowerLeg\"][1]\n cuff_len = 0.56\n boot_top = knee + 0.055\n y_waist = hips[1] + 0.055\n y_skirt = hips[1] - 0.25\n\n out, shirt, trousers, boots = mobs._base(\n fit, shirt=\"signature\", legs=\"doublet\", boots=\"boot\", gloves=\"glove\",\n shirt_subdiv=0, boot_top=boot_top\n )\n G.loose_sleeves(fit, shirt, ease=0.028, cuff=cuff_len, folds=6)\n G.flare_boots(fit, boots, boot_top - 0.005, ease=0.010)\n\n # Hide bare-foot toes under armoured steel sabatons\n for side in (\"L\", \"R\"):\n sabs = O.sabaton(fit, f\"sabaton_{side}\", side, role=\"steel\", pad=0.011, ridges=3)\n out += G._group(sabs, \"plate\")\n\n under = mobs._under(shirt)\n skirt_pcs = G.pleated_skirt(\n fit, under, y_waist, y_skirt, role=\"signature\", name=\"battle_skirt\",\n flare=0.098, pleats=24, depth=0.011, split=20.0\n )\n for sp in skirt_pcs:\n if \"plate\" in sp:\n sp[\"plate\"][:, 2] = 0.009\n out += skirt_pcs\n G.slim_under(fit, trousers, y_skirt)\n\n # Sculpted steel cuirass + plackart with antique-gold border\n bp = G.breastplate(fit, under, role=\"steel\", arm=62.0, keel=0.009)\n for pc in bp:\n if \"plate\" in pc:\n pc[\"plate\"][:, 2] = 0.0075\n out += bp\n\n # Standing indigo officer collar with gold rim\n col_pc, col_top, _ = O.collar(fit, \"collar\", \"signature\", height_back=0.042, height_front=0.026, gap_deg=54)\n col_trim = O.inherit(O.pipe(\"collar_trim\", \"gold\", col_top, r=0.0025, seg=6), col_pc)\n col_pc[\"group\"] = col_trim[\"group\"] = \"collar\"\n out += [col_pc, col_trim]\n\n # Fuller 3-lame steel spaulders + smooth LimbChart shin greaves with gold borders\n plate_surf = merge_surfaces(*[(p[\"pos\"], p[\"tri\"]) for p in out if p.get(\"group\") == \"plate\"], (fit.pos, fit.tri))\n for side in (\"L\", \"R\"):\n sp, rims = O.pauldron(\n fit, f\"spaulder_{side}\", \"steel\", plate_surf, side=side,\n lames=((0, 56, 0.022, 0.030), (47, 74, 0.020, 0.027), (66, 92, 0.018, 0.024)), spread=116\n )\n out += G._group(\n sp + [O.inherit(O.pipe(f\"spaulder_{side}_roll{k}\", \"gold\" if k == 0 else \"steel\", r_, r=0.0026), pc)\n for k, (pc, r_) in enumerate(zip(sp, rims))],\n \"plate\"\n )\n ll, ft = B[f\"J_Bip_{side}_LowerLeg\"], B[f\"J_Bip_{side}_Foot\"]\n lc = LimbChart(O.side_of(boots, side), ll, ft, front=(0, 0, -1), smooth=(1.6, 1.5))\n gv, gx = outline_plate(\n f\"greave_{side}\", \"steel\", lc, -108, 108,\n lambda u: 0.80 - 0.04 * (abs(u) / 108) ** 1.5,\n lambda u: 0.16 + 0.05 * max(0.0, 1.0 - (u / 45.0) ** 2),\n offset=0.008, crown=0.004, thickness=0.004, nu=40, nv=16,\n trim=0.0055, roll=0.0026, roll_edges=(\"top\", \"bottom\")\n )\n fit.bind(gv, rigid=f\"J_Bip_{side}_LowerLeg\")\n out += G._group([gv] + [O.inherit(q, gv) for q in gx], \"plate\")\n\n # Waist belt + gold buckle\n belt_over = mobs._surf(out, \"breastplate\", prefix=True)\n belt_pc, front_pt = O.belt(fit, \"belt\", \"leather\", belt_over, hips[1] + 0.048, height=0.036, offset=0.005)\n buckle = fit.bind(O.box(\"buckle\", \"gold\", front_pt + np.array([0, 0, -0.005]),\n ([1, 0, 0], [0, 1, 0], [0, 0, 1]), (0.025, 0.025, 0.006)), rigid=\"J_Bip_C_Hips\")\n buckle[\"group\"] = \"belt\"\n out += [belt_pc, buckle]\n\n cuff_pcs = G.cuffs(fit, role=\"glove\", length=cuff_len, flare=0.028)\n G.tuck_sleeves(fit, shirt, cuff_pcs)\n out += cuff_pcs\n\n # Flowing crimson officer cloak clasped at collarbones\n cape_under = merge_surfaces(\n *[(p[\"pos\"], p[\"tri\"]) for p in out if p.get(\"group\") in (\"plate\", \"doublet\")],\n (fit.pos, fit.tri)\n )\n cape_pc, _ = O.cape(fit, \"cape\", \"cape\", cape_under, length=0.96, phi=0.58, seg=44, rows=18, clear=(0.016, 0.055))\n cape_pc[\"group\"] = \"cape\"\n out.append(cape_pc)\n out += cloak_clasps(fit, cape_under, role=\"gold\", cord_role=\"gold\", y_off=-0.038, x_deg=35.0)\n\n # Heater shield with heraldic gold chevron + inner grip straps so the left hand holds a real enarme\n emblem = [\n (\"poly\", [(-0.11, 0.06), (0.0, 0.16), (0.11, 0.06), (0.11, 0.01), (0.0, 0.11), (-0.11, 0.01)], \"gold\"),\n (\"poly\", [(-0.045, -0.01), (0.045, -0.01), (0.0, -0.17)], \"gold\"),\n ]\n sh_pcs = G.shield(fit, \"heater\", side=\"L\", role=\"signature\", width=0.36, height=0.50, curve=0.44, emblem=emblem)\n E_l, H_l = B[\"J_Bip_L_LowerArm\"], B[\"J_Bip_L_Hand\"]\n ax_l = (H_l - E_l) / np.linalg.norm(H_l - E_l)\n lat_l = np.array([-1.0, 0.0, 0.0]) - ax_l * (-ax_l[0])\n lat_l /= np.linalg.norm(lat_l)\n grip_bar = O.tube(\"shield_enarme\", \"leather\", H_l + lat_l * 0.035 - np.array([0, 0, 0.05]),\n np.array([0, 0, 1.0]), 0.10, 0.010)\n fit.bind(grip_bar, rigid=\"J_Bip_L_LowerArm\")\n grip_bar[\"group\"] = \"shield\"\n out += sh_pcs + [grip_bar]\n\n out += knightly_longsword(fit, \"R\")\n out.append(add_scalp_cap(fit, hairline_front=54.0))\n return out\n\n\ndef heavy_housecarl(fit):\n \"\"\"Original Lowmarch heavy housecarl costume fitted to arm_m_strong (unhelmeted so face/hair read).\"\"\"\n B = fit.bone\n hips = B[\"J_Bip_C_Hips\"]\n knee = B[\"J_Bip_L_LowerLeg\"][1]\n boot_top = knee - 0.075\n y_gambeson = hips[1] - 0.24\n y_mail = hips[1] - 0.15\n\n out, shirt, trousers, boots = mobs._base(\n fit, shirt=\"padding\", legs=\"doublet\", boots=\"boot\", gloves=\"glove\", boot_top=boot_top\n )\n G.breeches(fit, trousers, boots, y_gambeson, boot_top - 0.005, ease=0.040)\n # Smooth leather shoe-lasts over both feet so VRoid toes never show\n for side in (\"L\", \"R\"):\n lasts = O.sabaton(fit, f\"boot_last_{side}\", side, role=\"boot\", pad=0.011, ridges=0)\n out += G._group(lasts, \"boots\")\n\n under = mobs._under(shirt)\n out += G.quilted(fit, under, role=\"padding\", y_hem=y_gambeson, sleeve_end=0.92)\n gam = mobs._surf(out, \"gambeson\", \"gambeson_skirt\")\n out += G.mail_shirt(fit, gam, role=\"mail\", y_hem=y_mail, sleeve=0.52)\n mail = mobs._surf(out, \"hauberk\", prefix=True)\n out += G.riveted_vest(fit, mail, role=\"leather\", rivet_role=\"steel\")\n\n # Exact torso pieces only (never hauberk_sleeve_*) so the belt hugs the waist cleanly\n vest_torso = mobs._surf(out, \"brigandine_front\", \"brigandine_back\", \"hauberk\")\n belt_pc, front_pt = O.belt(fit, \"belt\", \"leather\", vest_torso, hips[1] + 0.038, height=0.046, offset=0.006)\n buckle = fit.bind(O.box(\"buckle\", \"steel\", front_pt + np.array([0, 0, -0.006]),\n ([1, 0, 0], [0, 1, 0], [0, 0, 1]), (0.028, 0.028, 0.007)), rigid=\"J_Bip_C_Hips\")\n buckle[\"group\"] = \"belt\"\n out += [belt_pc, buckle]\n\n # Standing oxblood wool collar + draped battle cloak pinned cleanly behind shoulders (zero chest pokethrough)\n col_pc, col_top, _ = O.collar(fit, \"collar\", \"signature\", height_back=0.044, height_front=0.028, gap_deg=60,\n clear=(0.013, 0.019))\n col_pc[\"group\"] = \"collar\"\n out.append(col_pc)\n\n cape_under = merge_surfaces(\n *[(p[\"pos\"], p[\"tri\"]) for p in out if p[\"material\"] in (\"OUTFIT_brigandine_front\", \"OUTFIT_brigandine_back\",\n \"OUTFIT_hauberk\", \"OUTFIT_gambeson\")],\n (fit.pos, fit.tri)\n )\n cape_pc, _ = O.cape(fit, \"cape\", \"signature\", cape_under, length=0.94, phi=0.54, seg=42, rows=18,\n clear=(0.018, 0.058))\n cape_pc[\"group\"] = \"cape\"\n out.append(cape_pc)\n out += cloak_clasps(fit, cape_under, role=\"steel\", cord_role=\"leather\", y_off=-0.042, x_deg=36.0)\n\n out += G.cuffs(fit, role=\"glove\", length=0.35, flare=0.032)\n out += crescent_poleaxe(fit, length=1.96, grip=0.54, hand=\"R\")\n out.append(add_scalp_cap(fit, hairline_front=50.0))\n return out\n\n\ndef vanguard_pose(vrm, shape):\n \"\"\"Grounded fencing guard for Valen: sword poised forward, heater shield angled cleanly on outer guard.\"\"\"\n rig = Rig(vrm, shape, ortho=True)\n body = checks.Body(vrm, shape)\n f = {s: g[\"point\"] for s, g in grip_points(vrm, shape, P.BUST).items()}\n ref = dict(ref_pose=P.BUST, fist_R=f[\"R\"], fist_L=f[\"L\"])\n\n base = P.merge(P.BATTLE_IDLE, P.fist(\"L\", curl=(68, 80, 55), thumb=32), {\n \"J_Bip_C_Hips\": P.move(0, -0.055, -0.02, P.rot((0, 1, 0), -10.0) @ P.rot((1, 0, 0), -4.5)),\n \"J_Bip_C_Spine\": P.rot((0, 1, 0), -8.0) @ P.rot((1, 0, 0), -3.0),\n \"J_Bip_C_Chest\": P.rot((0, 1, 0), -6.0) @ P.rot((1, 0, 0), -2.0),\n \"J_Bip_C_Neck\": P.rot((0, 1, 0), 11.0) @ P.rot((1, 0, 0), 3.0),\n \"J_Bip_C_Head\": P.rot((0, 1, 0), 10.0) @ P.rot((1, 0, 0), 2.5),\n })\n foot = {s: rig.pos(P.BATTLE_IDLE, f\"J_Bip_{s}_Foot\") for s in \"LR\"}\n pose = rig.leg_ik(base, \"L\", foot[\"L\"] + np.array([-0.06, 0.0, -0.17]), pole=(0, 0, -1))\n pose = rig.leg_ik(pose, \"R\", foot[\"R\"] + np.array([0.07, 0.0, 0.14]), pole=(0, -0.2, -1))\n\n sh_r = rig.pos(pose, \"J_Bip_R_UpperArm\")\n fist_r = sh_r + np.array([0.09, -0.34, -0.22])\n blade_dir = np.array([-0.24, 0.48, -0.84])\n pose = duel.clear_grip(rig, body, pose, \"R\", ref, fist_r, blade_dir, (0.7, -0.9, 0.35))\n\n # Left arm braced outward and rotated about forearm axis so the shield's heraldic face turns ~42° toward camera\n sh_l = rig.pos(pose, \"J_Bip_L_UpperArm\")\n pose = rig.arm_ik(pose, \"L\", sh_l + np.array([-0.22, -0.24, -0.08]), pole=(-0.9, -0.6, 0.4))\n ax_la = rig.pos(pose, \"J_Bip_L_Hand\") - rig.pos(pose, \"J_Bip_L_LowerArm\")\n pose = rig.rotate_world(pose, \"J_Bip_L_LowerArm\", P.rot(ax_la, -52.0))\n return [(0.0, pose), (1.0, pose)]\n\n\ndef housecarl_pose(vrm, shape):\n \"\"\"Two-handed poleaxe guard for Korin: wide planted stance, head angled cleanly toward opponent.\"\"\"\n rig = Rig(vrm, shape, ortho=True)\n body = checks.Body(vrm, shape)\n f = {s: g[\"point\"] for s, g in grip_points(vrm, shape, P.BUST).items()}\n ref = dict(ref_pose=P.BUST, fist_R=f[\"R\"], fist_L=f[\"L\"])\n\n arm_l = rig.pos(P.BUST, \"J_Bip_L_LowerArm\") - rig.pos(P.BUST, \"J_Bip_L_UpperArm\")\n span_l = float(np.linalg.norm(arm_l) + np.linalg.norm(f[\"L\"] - rig.pos(P.BUST, \"J_Bip_L_LowerArm\")))\n arm_r = rig.pos(P.BUST, \"J_Bip_R_LowerArm\") - rig.pos(P.BUST, \"J_Bip_R_UpperArm\")\n span_r = float(np.linalg.norm(arm_r) + np.linalg.norm(f[\"R\"] - rig.pos(P.BUST, \"J_Bip_R_LowerArm\")))\n\n base = P.merge(P.BATTLE_IDLE, P.fist(\"L\"), {\n \"J_Bip_C_Hips\": P.move(0, -0.070, -0.015, P.rot((1, 0, 0), -5.0)),\n \"J_Bip_C_Spine\": P.rot((0, 1, 0), -12.0) @ P.rot((1, 0, 0), -2.0),\n \"J_Bip_C_Chest\": P.rot((0, 1, 0), -8.0) @ P.rot((1, 0, 0), -1.5),\n \"J_Bip_C_Neck\": P.rot((0, 1, 0), 7.0) @ P.rot((1, 0, 0), 3.0),\n \"J_Bip_C_Head\": P.rot((0, 1, 0), 5.0) @ P.rot((1, 0, 0), 2.5),\n })\n foot = {s: rig.pos(P.BATTLE_IDLE, f\"J_Bip_{s}_Foot\") for s in \"LR\"}\n pose = rig.leg_ik(base, \"L\", foot[\"L\"] + np.array([-0.08, 0.0, -0.16]), pole=(0, 0, -1))\n pose = rig.leg_ik(pose, \"R\", foot[\"R\"] + np.array([0.08, 0.0, 0.15]), pole=(0, -0.2, -1))\n\n D = np.array([0.14, 0.54, -0.83])\n D /= np.linalg.norm(D)\n fr = rig.pos(pose, \"J_Bip_R_UpperArm\") + span_r * np.array([0.05, -0.58, -0.22])\n q = fr - rig.pos(pose, \"J_Bip_L_UpperArm\")\n b, c = float(D @ q), float(q @ q) - (0.82 * span_l) ** 2\n t = float(np.clip(-b + math.sqrt(max(b * b - c, 0.0)), 0.24, 0.48))\n\n pose = duel.clear_grip(rig, body, pose, \"R\", ref, fr, D, (0.6, -0.5, 0.7))\n pose = duel.clear_grip(rig, body, pose, \"L\", ref, fr + D * t, D, (-0.8, -0.9, 0.2))\n return [(0.0, pose), (1.0, pose)]\n\n\ndef apply_forward_face_normals(p, forward=0.10, pull=0.45):\n \"\"\"Apply head-proxy normals with forward offset so 3/4 cheeks wrap into clean shadow.\"\"\"\n lm_now = vp.landmarks(p.prims, p.roles)\n names = p.v.nodes_by_name()\n Wn = p.v.node_world(p.pose_ref)\n neck = (Wn[names[\"J_Bip_C_Neck\"]][:3, 3], Wn[names[\"J_Bip_C_Head\"]][:3, 3])\n vp.face_normals(p.prims, p.roles, lm_now, amount=1.0, hair=0.0, forward=forward, pull=pull, neck=neck)\n\n\ndef wrap_glb_json(path):\n with open(path, \"rb\") as f:\n b64 = base64.b64encode(f.read()).decode()\n with open(path + \".json\", \"w\") as f:\n json.dump({\"glb\": b64}, f)\n os.remove(path)\n\n\ndef build_unit(spec):\n vrm_path = cached_cage_vrm(spec[\"cage_body\"])\n v0 = vp.VRM(vrm_path)\n shape = dict(spec[\"shape\"], face_normals=0.0)\n shape[\"arm_out\"] = arm_room(v0, shape)\n\n p = vp.Portrait(\n vrm_path,\n morphs=spec[\"morphs\"],\n pose=vp.BUST_POSE,\n ref_pose=vp.BUST_POSE,\n shape=shape,\n costume=spec[\"costume\"],\n )\n apply_forward_face_normals(p, forward=0.10, pull=0.45)\n p.paint = dict(spec[\"paint\"], hair_cap=spec[\"paint\"][\"hair\"])\n pal = dict(vp.PALETTE, **spec[\"colors\"])\n\n cl = {\"idle\": spec[\"pose_fn\"](p.v, shape)}\n glb_path = os.path.join(OUT_DIR, f\"{spec['name']}.glb\")\n export_glb.export_skinned(p, pal, glb_path, clips=cl, max_tex=1024)\n wrap_glb_json(glb_path)\n\n info = export_glb.scene_info(p, pal)\n info[\"roles\"][\"hair_cap\"] = info[\"roles\"][\"hair\"]\n info[\"paint\"][\"hair_cap\"] = dict(kind=\"hair\", base=spec[\"paint\"][\"hair\"], shade=True)\n return dict(\n name=spec[\"name\"],\n label=spec[\"label\"],\n place=spec[\"place\"],\n clip=\"idle\",\n clip_t=0.0,\n wind=spec.get(\"wind\", 0.0),\n info=info,\n )\n\n\ndef build_scene():\n os.makedirs(OUT_DIR, exist_ok=True)\n with open(SLICE_HTML) as f:\n html = f.read()\n with open(os.path.join(OUT_DIR, \"index.html\"), \"w\") as f:\n f.write(html)\n\n three_link = os.path.join(OUT_DIR, \"three\")\n if not os.path.exists(three_link):\n os.symlink(LOCAL_THREE, three_link)\n\n units = [\n dict(\n name=\"valen\",\n label=\"Valen (Vanguard Captain)\",\n cage_body=\"arm_f_strong\",\n morphs={\"Fcl_BRW_Angry\": 0.38, \"Fcl_EYE_Angry\": 0.18},\n shape={\"blush\": 0.25},\n costume=vanguard_captain,\n pose_fn=vanguard_pose,\n place={\"pos\": [-0.74, 0.0, 0.04], \"yaw\": 32.0},\n wind=-5.2,\n colors={\n \"r\": \"#1e2e52\", \"s\": \"#3b629c\", \"t\": \"#8bb8ea\",\n \"A\": \"#2f1a18\", \"o\": \"#241618\",\n },\n paint={\n \"skin\": \"#f5dcd0\",\n \"hair\": \"#542c26\",\n \"signature\": \"#243b61\",\n \"cape\": \"#822330\",\n \"doublet\": \"#252836\",\n \"heraldry\": \"#e8e2d4\",\n \"steel\": \"#b6becb\",\n \"gold\": \"#c89e48\",\n \"leather\": \"#523526\",\n \"glove\": \"#462d21\",\n \"boot\": \"#38251c\",\n \"wood\": \"#6b482e\",\n },\n ),\n dict(\n name=\"korin\",\n label=\"Korin (Heavy Housecarl)\",\n cage_body=\"arm_m_strong\",\n morphs={\"Fcl_BRW_Angry\": 0.48, \"Fcl_EYE_Angry\": 0.22},\n shape={\"blush\": 0.0},\n costume=heavy_housecarl,\n pose_fn=housecarl_pose,\n place={\"pos\": [0.76, 0.0, -0.02], \"yaw\": -33.0},\n wind=4.2,\n colors={\n \"r\": \"#2c1d14\", \"s\": \"#7a4e26\", \"t\": \"#c49052\",\n \"A\": \"#181920\", \"o\": \"#1e1412\",\n },\n paint={\n \"skin\": \"#b87a54\",\n \"hair\": \"#252730\",\n \"signature\": \"#7a252c\",\n \"padding\": \"#cec2ac\",\n \"mail\": {\"kind\": \"steel\", \"base\": \"#7d8492\"},\n \"doublet\": \"#363b37\",\n \"heraldry\": \"#ddd8cc\",\n \"steel\": \"#a0a8b6\",\n \"gold\": \"#b38b3d\",\n \"leather\": \"#583827\",\n \"glove\": \"#452d20\",\n \"boot\": \"#38251c\",\n \"wood\": \"#68462c\",\n },\n ),\n ]\n\n built_chars = [build_unit(u) for u in units]\n\n world_holder = type(\"WorldPortrait\", (), {})()\n world_holder.prims = terrain.plains(width=4.8, depth=2.1, thick=0.30, seed=5, tufts=34, stones=7)\n world_holder.roles = [p[\"role\"] for p in world_holder.prims]\n world_holder.tex = {}\n plains_path = os.path.join(OUT_DIR, \"plains.glb\")\n export_glb.export(world_holder, vp.PALETTE, plains_path, only_world=True)\n wrap_glb_json(plains_path)\n\n scene_data = dict(\n characters=built_chars,\n camera=dict(target=[0.02, 0.94, 0.0], height=2.12, pitch=6.5),\n key=[-0.62, 0.48, 0.62],\n grade=dict(ambient=[0.86, 0.88, 0.96], key=[1.03, 1.00, 0.94], rim=[0.26, 0.23, 0.18]),\n )\n with open(os.path.join(OUT_DIR, \"scene.json\"), \"w\") as f:\n json.dump(scene_data, f)\n\n\ndef shoot(png_path, width=1920, height=1080, ss=2):\n os.makedirs(os.path.dirname(os.path.abspath(png_path)), exist_ok=True)\n sock = socket.socket()\n sock.bind((\"127.0.0.1\", 0))\n port = sock.getsockname()[1]\n sock.close()\n\n server = subprocess.Popen(\n [sys.executable, \"-m\", \"http.server\", str(port), \"--bind\", \"127.0.0.1\", \"--directory\", OUT_DIR],\n stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,\n )\n try:\n time.sleep(0.4)\n url = f\"http://127.0.0.1:{port}/index.html?shot=1&w={width}&h={height}&ss={ss}\"\n r = subprocess.run(\n [\n os.environ.get(\"CHROMIUM\", \"/snap/bin/chromium\"),\n \"--headless=new\",\n \"--use-angle=swiftshader\",\n \"--enable-unsafe-swiftshader\",\n \"--ignore-gpu-blocklist\",\n f\"--window-size={width},{height}\",\n \"--virtual-time-budget=600000\",\n \"--dump-dom\",\n url,\n ],\n capture_output=True, text=True, timeout=300,\n )\n m = re.search(r'id=\"sheetOut\"[^>]*>[redacted: data-URI prefix]([A-Za-z0-9+/=]+)<', r.stdout)\n if not m:\n raise RuntimeError(f\"Render failed:\\nSTDOUT:\\n{r.stdout[-600:]}\\nSTDERR:\\n{r.stderr[-800:]}\")\n with open(png_path, \"wb\") as f:\n f.write(base64.b64decode(m.group(1)))\n finally:\n server.terminate()\n\n\ndef main():\n ap = argparse.ArgumentParser()\n ap.add_argument(\"--png\", default=os.path.join(OUT_DIR, \"battle_frame.png\"))\n ap.add_argument(\"--width\", type=int, default=1920)\n ap.add_argument(\"--height\", type=int, default=1080)\n ap.add_argument(\"--ss\", type=int, default=2)\n args = ap.parse_args()\n\n t0 = time.time()\n build_scene()\n t_build = time.time() - t0\n t1 = time.time()\n shoot(args.png, args.width, args.height, args.ss)\n t_shoot = time.time() - t1\n print(f\"wrote {args.png} (build {t_build:.1f}s, render {t_shoot:.1f}s, total {time.time() - t0:.1f}s)\")\n\n\nif __name__ == \"__main__\":\n main()\n","Overwrite":true,"Path":"~/work/lowmarch/tools/battle_slice.py"}

    input

    {
      "Content": "\"\"\"Build and shoot one composed tactics battle frame on MakeHuman-caged VRoid bodies.\n\nUses the project's cached caged bodies (arm_f_strong, arm_m_strong), parametric armour and\ngarment kits (outfit.py, plates.py, gear.py, hair.py), IK stances (rig.py, clips.py, duel.py),\nterrain (terrain.py), and painted WebGL renderer (review/slice/index.html).\n\n  python3 tools/battle_slice.py [--png ~/out/battle_frame.png]\n\"\"\"\nimport argparse\nimport base64\nimport json\nimport math\nimport os\nimport re\nimport socket\nimport subprocess\nimport sys\nimport time\n\nimport numpy as np\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(HERE)\nsys.path[:0] = [HERE, os.path.join(ROOT, \"art\", \"cast\")]\n\nimport cage  # noqa: E402\nimport checks  # noqa: E402\nimport duel  # noqa: E402\nimport export_glb  # noqa: E402\nimport gear as G  # noqa: E402\nimport hair as H  # noqa: E402\nimport mobs  # noqa: E402\nimport outfit as O  # noqa: E402\nimport poses as P  # noqa: E402\nimport terrain  # noqa: E402\nimport vroid_portrait as vp  # noqa: E402\nfrom cast import CAST  # noqa: E402\nfrom fitting import Surface, merge_surfaces  # noqa: E402\nfrom plates import LimbChart, flat_piece, outline_plate  # noqa: E402\nfrom rig import Rig, grip_points  # noqa: E402\n\nSLICE_HTML = os.path.join(ROOT, \"review\", \"slice\", \"index.html\")\nOUT_DIR = os.path.join(ROOT, \"review\", \"out\", \"slice\")\nLOCAL_THREE = \"~/context/sortie-node_modules/three\"\n\n\ndef cached_cage_vrm(name):\n    \"\"\"Resolve a pre-built caged VRM strictly read-only.\"\"\"\n    p = cage.path_for(name, CAST[name][\"cage\"])\n    if not os.path.exists(p):\n        raise SystemExit(f\"Missing cached cage body: {p}\")\n    return p\n\n\ndef arm_room(v, shape, need=0.008, most=16):\n    limbs = [f\"{s}_{a}\" for s in \"LR\" for a in (\"UpperArm\", \"LowerArm\")]\n    for deg in range(0, most + 1, 2):\n        b = checks.Body(v, dict(shape, arm_out=float(deg)))\n        if min(b.worst(pose, limbs) for pose in (P.BUST, P.BATTLE_IDLE)) >= need:\n            return float(deg)\n    return float(most)\n\n\ndef add_scalp_cap(fit, hairline_front=52.0):\n    \"\"\"Dark inner hair under-cap 2 mm off the skull so parted or warped VRoid hair never shows pale scalp.\"\"\"\n    ch = H.head_chart(fit)\n    hl = lambda u: float(np.interp(abs(u), [0, 38, 68, 105, 145, 180],\n                                   [hairline_front, hairline_front + 6, 82, 118, 134, 140]))\n    pc = H.cap(\"scalp_cap\", ch, hl, lift=0.0022, crown=0.0010, nu=64, nv=20, role=\"hair_cap\")\n    fit.bind(pc, rigid=\"J_Bip_C_Head\")\n    pc[\"group\"] = \"hair\"\n    return pc\n\n\ndef knightly_longsword(fit, hand=\"R\", blade_len=0.86, blade_w=0.044, grip_len=0.17):\n    \"\"\"Arming/bastard sword with curved crossguard quillons, faceted wheel pommel, and fuller.\"\"\"\n    fist, fwd, side, flat, _ = G._hand_frame(fit, hand)\n    out = [\n        O.tube(\"grip\", \"leather\", fist - fwd * grip_len * 0.56, fwd, grip_len, 0.0135),\n        O.ball(\"pommel\", \"gold\", fist - fwd * (grip_len * 0.56 + 0.018), 0.022, squash=(1.0, 0.58, 1.0)),\n        O.ball(\"pommel_boss\", \"steel\", fist - fwd * (grip_len * 0.56 + 0.018), 0.013, squash=(1.0, 0.78, 1.0)),\n    ]\n    guard_c = fist + fwd * (grip_len * 0.44 + 0.008)\n    ts = np.linspace(-1.0, 1.0, 17)\n    q_pts = np.array([guard_c + side * (0.088 * x) + fwd * (0.014 * x * x) for x in ts])\n    out.append(O.pipe(\"guard\", \"gold\", q_pts, r=0.0068, seg=8))\n    for sx in (-1.0, 1.0):\n        out.append(O.ball(f\"quillon_{1 if sx > 0 else 0}\", \"gold\",\n                          guard_c + side * (0.090 * sx) + fwd * 0.015, 0.009))\n\n    base = guard_c + fwd * 0.008\n    rows = 14\n    P_grid = np.zeros((5, rows, 3))\n    for j, t in enumerate(np.linspace(0, 1, rows)):\n        taper = 1.0 if t < 0.80 else max(0.0, (1.0 - t) / 0.20) ** 0.85\n        w = blade_w / 2 * (1.0 - 0.18 * t) * taper\n        th = 0.0048 * taper\n        c = base + fwd * blade_len * t\n        P_grid[:, j] = [c + side * w, c + flat * th, c - side * w, c - flat * th, c + side * w]\n    pos, tri = O.grid_mesh(P_grid)\n    out.append(O.piece(\"blade\", \"steel\", pos, tri, outward_from=base + fwd * blade_len / 2, axis=fwd))\n    for sg in (-1.0, 1.0):\n        out.append(O.ribbon(\n            f\"fuller_{1 if sg > 0 else 0}\", \"metal\",\n            [base + fwd * blade_len * t + flat * (sg * 0.0049) for t in np.linspace(0.03, 0.68, 10)],\n            width=blade_w * 0.16, lift=0.0004, normals=np.tile(flat * sg, (10, 1))\n        ))\n    for pc in out:\n        fit.bind(pc, rigid=f\"J_Bip_{hand}_Hand\")\n        pc[\"group\"] = \"sword\"\n    return out\n\n\ndef crescent_poleaxe(fit, length=1.96, grip=0.54, hand=\"R\", name=\"poleaxe\"):\n    \"\"\"Bearded crescent halberd/poleaxe with honed edge bevel, back fluke, spear tip, brass collars, and tassel.\"\"\"\n    fist, fwd, side, flat, _ = G._hand_frame(fit, hand)\n    start = fist - fwd * grip\n    out = [O.tube(f\"{name}_haft\", \"wood\", start, fwd, length, 0.015)]\n    top = start + fwd * length\n\n    # Bearded crescent axe blade\n    a = np.linspace(-1.0, 1.0, 17)\n    edge = [(0.19 * (0.76 + 0.24 * math.cos(x * 1.15)), -0.05 + 0.15 * x) for x in a]\n    cres = [\n        (0.018, -0.09),\n        (0.075, -0.19),\n    ] + edge + [\n        (0.065, 0.10),\n        (0.018, 0.045),\n    ]\n    bevel_line = [(0.165 * (0.76 + 0.24 * math.cos(x * 1.15)), -0.05 + 0.14 * x) for x in a]\n    deco = [(\"line\", bevel_line, 0.0035, \"groove\")]\n    out.append(flat_piece(f\"{name}_blade\", \"steel\", cres, top - fwd * 0.11, side, fwd, thickness=0.008, decal=deco))\n\n    # Curved rear fluke hook\n    hook = [(-0.018, -0.06), (-0.095, -0.095), (-0.135, -0.045), (-0.090, 0.015), (-0.018, 0.025)]\n    out.append(flat_piece(f\"{name}_fluke\", \"steel\", hook, top - fwd * 0.11, side, fwd, thickness=0.007))\n\n    # Tapered diamond spear spike\n    spike = [(0.0, -0.01), (0.024, 0.045), (0.014, 0.16), (0.0, 0.29), (-0.014, 0.16), (-0.024, 0.045)]\n    out.append(flat_piece(f\"{name}_spike\", \"steel\", spike, top - fwd * 0.02, side, fwd, thickness=0.008))\n\n    # Steel langet socket + brass collar rings + crimson tassel\n    out.append(O.tube(f\"{name}_socket\", \"steel\", top - fwd * 0.30, fwd, 0.29, 0.018))\n    for k, off in enumerate((0.02, 0.29)):\n        c_ring = top - fwd * off\n        ang = np.linspace(0, 2 * math.pi, 18, endpoint=False)\n        ring = np.array([c_ring + (side * math.cos(th) + flat * math.sin(th)) * 0.020 for th in ang])\n        out.append(O.pipe(f\"{name}_collar{k}\", \"gold\", ring, r=0.0038, seg=6, closed=True))\n\n    tassel_root = top - fwd * 0.30 - side * 0.018\n    t_pts = np.array([tassel_root + np.array([0.0, -0.032 * s, 0.008 * s]) - side * (0.018 * s)\n                      for s in np.linspace(0, 1, 7)])\n    out.append(O.pipe(f\"{name}_tassel\", \"signature\", t_pts, r=0.0075, seg=6))\n    out.append(O.ball(f\"{name}_butt\", \"steel\", start - fwd * 0.012, 0.019, squash=(1, 1, 1.5)))\n    G._bind(fit, out, f\"J_Bip_{hand}_Hand\")\n    return G._group(out, \"weapon\")\n\n\ndef cloak_clasps(fit, under, role=\"gold\", cord_role=\"gold\", y_off=-0.036, x_deg=34.0):\n    \"\"\"Pair of domed collarbone cloak-clasps with a draped chest cord between them.\"\"\"\n    nk = fit.bone[\"J_Bip_C_Neck\"]\n    pts = []\n    out = []\n    for k, sgn in enumerate((-1.0, 1.0)):\n        a = math.radians(sgn * x_deg)\n        d = np.array([math.sin(a), 0.0, -math.cos(a)])\n        o = np.array([nk[0], nk[1] + y_off, nk[2]])\n        r = under.cast(o, d, rmax=0.26, far=True)\n        p = o + d * ((0.09 if np.isnan(r) else r) + 0.008)\n        pts.append(p)\n        cl = O.ball(f\"clasp_{k}\", role, p, 0.014, seg=12, rows=7, squash=(1.0, 1.0, 0.55))\n        fit.bind(cl, rigid=\"J_Bip_C_UpperChest\")\n        cl[\"group\"] = \"trim\"\n        out.append(cl)\n    ts = np.linspace(0, 1, 15)\n    cord = []\n    for t in ts:\n        q = pts[0] * (1 - t) + pts[1] * t + np.array([0.0, -0.022 * math.sin(math.pi * t), -0.010 * math.sin(math.pi * t)])\n        cord.append(q)\n    cp = O.pipe(\"clasp_cord\", cord_role, np.array(cord), r=0.0032, seg=6)\n    fit.bind(cp, rigid=\"J_Bip_C_UpperChest\")\n    cp[\"group\"] = \"trim\"\n    out.append(cp)\n    return out\n\n\ndef vanguard_captain(fit):\n    \"\"\"Original Lowmarch vanguard officer costume fitted to arm_f_strong.\"\"\"\n    B = fit.bone\n    hips, nk = B[\"J_Bip_C_Hips\"], B[\"J_Bip_C_Neck\"]\n    knee = B[\"J_Bip_L_LowerLeg\"][1]\n    cuff_len = 0.56\n    boot_top = knee + 0.055\n    y_waist = hips[1] + 0.055\n    y_skirt = hips[1] - 0.25\n\n    out, shirt, trousers, boots = mobs._base(\n        fit, shirt=\"signature\", legs=\"doublet\", boots=\"boot\", gloves=\"glove\",\n        shirt_subdiv=0, boot_top=boot_top\n    )\n    G.loose_sleeves(fit, shirt, ease=0.028, cuff=cuff_len, folds=6)\n    G.flare_boots(fit, boots, boot_top - 0.005, ease=0.010)\n\n    # Hide bare-foot toes under armoured steel sabatons\n    for side in (\"L\", \"R\"):\n        sabs = O.sabaton(fit, f\"sabaton_{side}\", side, role=\"steel\", pad=0.011, ridges=3)\n        out += G._group(sabs, \"plate\")\n\n    under = mobs._under(shirt)\n    skirt_pcs = G.pleated_skirt(\n        fit, under, y_waist, y_skirt, role=\"signature\", name=\"battle_skirt\",\n        flare=0.098, pleats=24, depth=0.011, split=20.0\n    )\n    for sp in skirt_pcs:\n        if \"plate\" in sp:\n            sp[\"plate\"][:, 2] = 0.009\n    out += skirt_pcs\n    G.slim_under(fit, trousers, y_skirt)\n\n    # Sculpted steel cuirass + plackart with antique-gold border\n    bp = G.breastplate(fit, under, role=\"steel\", arm=62.0, keel=0.009)\n    for pc in bp:\n        if \"plate\" in pc:\n            pc[\"plate\"][:, 2] = 0.0075\n    out += bp\n\n    # Standing indigo officer collar with gold rim\n    col_pc, col_top, _ = O.collar(fit, \"collar\", \"signature\", height_back=0.042, height_front=0.026, gap_deg=54)\n    col_trim = O.inherit(O.pipe(\"collar_trim\", \"gold\", col_top, r=0.0025, seg=6), col_pc)\n    col_pc[\"group\"] = col_trim[\"group\"] = \"collar\"\n    out += [col_pc, col_trim]\n\n    # Fuller 3-lame steel spaulders + smooth LimbChart shin greaves with gold borders\n    plate_surf = merge_surfaces(*[(p[\"pos\"], p[\"tri\"]) for p in out if p.get(\"group\") == \"plate\"], (fit.pos, fit.tri))\n    for side in (\"L\", \"R\"):\n        sp, rims = O.pauldron(\n            fit, f\"spaulder_{side}\", \"steel\", plate_surf, side=side,\n            lames=((0, 56, 0.022, 0.030), (47, 74, 0.020, 0.027), (66, 92, 0.018, 0.024)), spread=116\n        )\n        out += G._group(\n            sp + [O.inherit(O.pipe(f\"spaulder_{side}_roll{k}\", \"gold\" if k == 0 else \"steel\", r_, r=0.0026), pc)\n                  for k, (pc, r_) in enumerate(zip(sp, rims))],\n            \"plate\"\n        )\n        ll, ft = B[f\"J_Bip_{side}_LowerLeg\"], B[f\"J_Bip_{side}_Foot\"]\n        lc = LimbChart(O.side_of(boots, side), ll, ft, front=(0, 0, -1), smooth=(1.6, 1.5))\n        gv, gx = outline_plate(\n            f\"greave_{side}\", \"steel\", lc, -108, 108,\n            lambda u: 0.80 - 0.04 * (abs(u) / 108) ** 1.5,\n            lambda u: 0.16 + 0.05 * max(0.0, 1.0 - (u / 45.0) ** 2),\n            offset=0.008, crown=0.004, thickness=0.004, nu=40, nv=16,\n            trim=0.0055, roll=0.0026, roll_edges=(\"top\", \"bottom\")\n        )\n        fit.bind(gv, rigid=f\"J_Bip_{side}_LowerLeg\")\n        out += G._group([gv] + [O.inherit(q, gv) for q in gx], \"plate\")\n\n    # Waist belt + gold buckle\n    belt_over = mobs._surf(out, \"breastplate\", prefix=True)\n    belt_pc, front_pt = O.belt(fit, \"belt\", \"leather\", belt_over, hips[1] + 0.048, height=0.036, offset=0.005)\n    buckle = fit.bind(O.box(\"buckle\", \"gold\", front_pt + np.array([0, 0, -0.005]),\n                            ([1, 0, 0], [0, 1, 0], [0, 0, 1]), (0.025, 0.025, 0.006)), rigid=\"J_Bip_C_Hips\")\n    buckle[\"group\"] = \"belt\"\n    out += [belt_pc, buckle]\n\n    cuff_pcs = G.cuffs(fit, role=\"glove\", length=cuff_len, flare=0.028)\n    G.tuck_sleeves(fit, shirt, cuff_pcs)\n    out += cuff_pcs\n\n    # Flowing crimson officer cloak clasped at collarbones\n    cape_under = merge_surfaces(\n        *[(p[\"pos\"], p[\"tri\"]) for p in out if p.get(\"group\") in (\"plate\", \"doublet\")],\n        (fit.pos, fit.tri)\n    )\n    cape_pc, _ = O.cape(fit, \"cape\", \"cape\", cape_under, length=0.96, phi=0.58, seg=44, rows=18, clear=(0.016, 0.055))\n    cape_pc[\"group\"] = \"cape\"\n    out.append(cape_pc)\n    out += cloak_clasps(fit, cape_under, role=\"gold\", cord_role=\"gold\", y_off=-0.038, x_deg=35.0)\n\n    # Heater shield with heraldic gold chevron + inner grip straps so the left hand holds a real enarme\n    emblem = [\n        (\"poly\", [(-0.11, 0.06), (0.0, 0.16), (0.11, 0.06), (0.11, 0.01), (0.0, 0.11), (-0.11, 0.01)], \"gold\"),\n        (\"poly\", [(-0.045, -0.01), (0.045, -0.01), (0.0, -0.17)], \"gold\"),\n    ]\n    sh_pcs = G.shield(fit, \"heater\", side=\"L\", role=\"signature\", width=0.36, height=0.50, curve=0.44, emblem=emblem)\n    E_l, H_l = B[\"J_Bip_L_LowerArm\"], B[\"J_Bip_L_Hand\"]\n    ax_l = (H_l - E_l) / np.linalg.norm(H_l - E_l)\n    lat_l = np.array([-1.0, 0.0, 0.0]) - ax_l * (-ax_l[0])\n    lat_l /= np.linalg.norm(lat_l)\n    grip_bar = O.tube(\"shield_enarme\", \"leather\", H_l + lat_l * 0.035 - np.array([0, 0, 0.05]),\n                      np.array([0, 0, 1.0]), 0.10, 0.010)\n    fit.bind(grip_bar, rigid=\"J_Bip_L_LowerArm\")\n    grip_bar[\"group\"] = \"shield\"\n    out += sh_pcs + [grip_bar]\n\n    out += knightly_longsword(fit, \"R\")\n    out.append(add_scalp_cap(fit, hairline_front=54.0))\n    return out\n\n\ndef heavy_housecarl(fit):\n    \"\"\"Original Lowmarch heavy housecarl costume fitted to arm_m_strong (unhelmeted so face/hair read).\"\"\"\n    B = fit.bone\n    hips = B[\"J_Bip_C_Hips\"]\n    knee = B[\"J_Bip_L_LowerLeg\"][1]\n    boot_top = knee - 0.075\n    y_gambeson = hips[1] - 0.24\n    y_mail = hips[1] - 0.15\n\n    out, shirt, trousers, boots = mobs._base(\n        fit, shirt=\"padding\", legs=\"doublet\", boots=\"boot\", gloves=\"glove\", boot_top=boot_top\n    )\n    G.breeches(fit, trousers, boots, y_gambeson, boot_top - 0.005, ease=0.040)\n    # Smooth leather shoe-lasts over both feet so VRoid toes never show\n    for side in (\"L\", \"R\"):\n        lasts = O.sabaton(fit, f\"boot_last_{side}\", side, role=\"boot\", pad=0.011, ridges=0)\n        out += G._group(lasts, \"boots\")\n\n    under = mobs._under(shirt)\n    out += G.quilted(fit, under, role=\"padding\", y_hem=y_gambeson, sleeve_end=0.92)\n    gam = mobs._surf(out, \"gambeson\", \"gambeson_skirt\")\n    out += G.mail_shirt(fit, gam, role=\"mail\", y_hem=y_mail, sleeve=0.52)\n    mail = mobs._surf(out, \"hauberk\", prefix=True)\n    out += G.riveted_vest(fit, mail, role=\"leather\", rivet_role=\"steel\")\n\n    # Exact torso pieces only (never hauberk_sleeve_*) so the belt hugs the waist cleanly\n    vest_torso = mobs._surf(out, \"brigandine_front\", \"brigandine_back\", \"hauberk\")\n    belt_pc, front_pt = O.belt(fit, \"belt\", \"leather\", vest_torso, hips[1] + 0.038, height=0.046, offset=0.006)\n    buckle = fit.bind(O.box(\"buckle\", \"steel\", front_pt + np.array([0, 0, -0.006]),\n                            ([1, 0, 0], [0, 1, 0], [0, 0, 1]), (0.028, 0.028, 0.007)), rigid=\"J_Bip_C_Hips\")\n    buckle[\"group\"] = \"belt\"\n    out += [belt_pc, buckle]\n\n    # Standing oxblood wool collar + draped battle cloak pinned cleanly behind shoulders (zero chest pokethrough)\n    col_pc, col_top, _ = O.collar(fit, \"collar\", \"signature\", height_back=0.044, height_front=0.028, gap_deg=60,\n                                  clear=(0.013, 0.019))\n    col_pc[\"group\"] = \"collar\"\n    out.append(col_pc)\n\n    cape_under = merge_surfaces(\n        *[(p[\"pos\"], p[\"tri\"]) for p in out if p[\"material\"] in (\"OUTFIT_brigandine_front\", \"OUTFIT_brigandine_back\",\n                                                                 \"OUTFIT_hauberk\", \"OUTFIT_gambeson\")],\n        (fit.pos, fit.tri)\n    )\n    cape_pc, _ = O.cape(fit, \"cape\", \"signature\", cape_under, length=0.94, phi=0.54, seg=42, rows=18,\n                        clear=(0.018, 0.058))\n    cape_pc[\"group\"] = \"cape\"\n    out.append(cape_pc)\n    out += cloak_clasps(fit, cape_under, role=\"steel\", cord_role=\"leather\", y_off=-0.042, x_deg=36.0)\n\n    out += G.cuffs(fit, role=\"glove\", length=0.35, flare=0.032)\n    out += crescent_poleaxe(fit, length=1.96, grip=0.54, hand=\"R\")\n    out.append(add_scalp_cap(fit, hairline_front=50.0))\n    return out\n\n\ndef vanguard_pose(vrm, shape):\n    \"\"\"Grounded fencing guard for Valen: sword poised forward, heater shield angled cleanly on outer guard.\"\"\"\n    rig = Rig(vrm, shape, ortho=True)\n    body = checks.Body(vrm, shape)\n    f = {s: g[\"point\"] for s, g in grip_points(vrm, shape, P.BUST).items()}\n    ref = dict(ref_pose=P.BUST, fist_R=f[\"R\"], fist_L=f[\"L\"])\n\n    base = P.merge(P.BATTLE_IDLE, P.fist(\"L\", curl=(68, 80, 55), thumb=32), {\n        \"J_Bip_C_Hips\": P.move(0, -0.055, -0.02, P.rot((0, 1, 0), -10.0) @ P.rot((1, 0, 0), -4.5)),\n        \"J_Bip_C_Spine\": P.rot((0, 1, 0), -8.0) @ P.rot((1, 0, 0), -3.0),\n        \"J_Bip_C_Chest\": P.rot((0, 1, 0), -6.0) @ P.rot((1, 0, 0), -2.0),\n        \"J_Bip_C_Neck\": P.rot((0, 1, 0), 11.0) @ P.rot((1, 0, 0), 3.0),\n        \"J_Bip_C_Head\": P.rot((0, 1, 0), 10.0) @ P.rot((1, 0, 0), 2.5),\n    })\n    foot = {s: rig.pos(P.BATTLE_IDLE, f\"J_Bip_{s}_Foot\") for s in \"LR\"}\n    pose = rig.leg_ik(base, \"L\", foot[\"L\"] + np.array([-0.06, 0.0, -0.17]), pole=(0, 0, -1))\n    pose = rig.leg_ik(pose, \"R\", foot[\"R\"] + np.array([0.07, 0.0, 0.14]), pole=(0, -0.2, -1))\n\n    sh_r = rig.pos(pose, \"J_Bip_R_UpperArm\")\n    fist_r = sh_r + np.array([0.09, -0.34, -0.22])\n    blade_dir = np.array([-0.24, 0.48, -0.84])\n    pose = duel.clear_grip(rig, body, pose, \"R\", ref, fist_r, blade_dir, (0.7, -0.9, 0.35))\n\n    # Left arm braced outward and rotated about forearm axis so the shield's heraldic face turns ~42° toward camera\n    sh_l = rig.pos(pose, \"J_Bip_L_UpperArm\")\n    pose = rig.arm_ik(pose, \"L\", sh_l + np.array([-0.22, -0.24, -0.08]), pole=(-0.9, -0.6, 0.4))\n    ax_la = rig.pos(pose, \"J_Bip_L_Hand\") - rig.pos(pose, \"J_Bip_L_LowerArm\")\n    pose = rig.rotate_world(pose, \"J_Bip_L_LowerArm\", P.rot(ax_la, -52.0))\n    return [(0.0, pose), (1.0, pose)]\n\n\ndef housecarl_pose(vrm, shape):\n    \"\"\"Two-handed poleaxe guard for Korin: wide planted stance, head angled cleanly toward opponent.\"\"\"\n    rig = Rig(vrm, shape, ortho=True)\n    body = checks.Body(vrm, shape)\n    f = {s: g[\"point\"] for s, g in grip_points(vrm, shape, P.BUST).items()}\n    ref = dict(ref_pose=P.BUST, fist_R=f[\"R\"], fist_L=f[\"L\"])\n\n    arm_l = rig.pos(P.BUST, \"J_Bip_L_LowerArm\") - rig.pos(P.BUST, \"J_Bip_L_UpperArm\")\n    span_l = float(np.linalg.norm(arm_l) + np.linalg.norm(f[\"L\"] - rig.pos(P.BUST, \"J_Bip_L_LowerArm\")))\n    arm_r = rig.pos(P.BUST, \"J_Bip_R_LowerArm\") - rig.pos(P.BUST, \"J_Bip_R_UpperArm\")\n    span_r = float(np.linalg.norm(arm_r) + np.linalg.norm(f[\"R\"] - rig.pos(P.BUST, \"J_Bip_R_LowerArm\")))\n\n    base = P.merge(P.BATTLE_IDLE, P.fist(\"L\"), {\n        \"J_Bip_C_Hips\": P.move(0, -0.070, -0.015, P.rot((1, 0, 0), -5.0)),\n        \"J_Bip_C_Spine\": P.rot((0, 1, 0), -12.0) @ P.rot((1, 0, 0), -2.0),\n        \"J_Bip_C_Chest\": P.rot((0, 1, 0), -8.0) @ P.rot((1, 0, 0), -1.5),\n        \"J_Bip_C_Neck\": P.rot((0, 1, 0), 7.0) @ P.rot((1, 0, 0), 3.0),\n        \"J_Bip_C_Head\": P.rot((0, 1, 0), 5.0) @ P.rot((1, 0, 0), 2.5),\n    })\n    foot = {s: rig.pos(P.BATTLE_IDLE, f\"J_Bip_{s}_Foot\") for s in \"LR\"}\n    pose = rig.leg_ik(base, \"L\", foot[\"L\"] + np.array([-0.08, 0.0, -0.16]), pole=(0, 0, -1))\n    pose = rig.leg_ik(pose, \"R\", foot[\"R\"] + np.array([0.08, 0.0, 0.15]), pole=(0, -0.2, -1))\n\n    D = np.array([0.14, 0.54, -0.83])\n    D /= np.linalg.norm(D)\n    fr = rig.pos(pose, \"J_Bip_R_UpperArm\") + span_r * np.array([0.05, -0.58, -0.22])\n    q = fr - rig.pos(pose, \"J_Bip_L_UpperArm\")\n    b, c = float(D @ q), float(q @ q) - (0.82 * span_l) ** 2\n    t = float(np.clip(-b + math.sqrt(max(b * b - c, 0.0)), 0.24, 0.48))\n\n    pose = duel.clear_grip(rig, body, pose, \"R\", ref, fr, D, (0.6, -0.5, 0.7))\n    pose = duel.clear_grip(rig, body, pose, \"L\", ref, fr + D * t, D, (-0.8, -0.9, 0.2))\n    return [(0.0, pose), (1.0, pose)]\n\n\ndef apply_forward_face_normals(p, forward=0.10, pull=0.45):\n    \"\"\"Apply head-proxy normals with forward offset so 3/4 cheeks wrap into clean shadow.\"\"\"\n    lm_now = vp.landmarks(p.prims, p.roles)\n    names = p.v.nodes_by_name()\n    Wn = p.v.node_world(p.pose_ref)\n    neck = (Wn[names[\"J_Bip_C_Neck\"]][:3, 3], Wn[names[\"J_Bip_C_Head\"]][:3, 3])\n    vp.face_normals(p.prims, p.roles, lm_now, amount=1.0, hair=0.0, forward=forward, pull=pull, neck=neck)\n\n\ndef wrap_glb_json(path):\n    with open(path, \"rb\") as f:\n        b64 = base64.b64encode(f.read()).decode()\n    with open(path + \".json\", \"w\") as f:\n        json.dump({\"glb\": b64}, f)\n    os.remove(path)\n\n\ndef build_unit(spec):\n    vrm_path = cached_cage_vrm(spec[\"cage_body\"])\n    v0 = vp.VRM(vrm_path)\n    shape = dict(spec[\"shape\"], face_normals=0.0)\n    shape[\"arm_out\"] = arm_room(v0, shape)\n\n    p = vp.Portrait(\n        vrm_path,\n        morphs=spec[\"morphs\"],\n        pose=vp.BUST_POSE,\n        ref_pose=vp.BUST_POSE,\n        shape=shape,\n        costume=spec[\"costume\"],\n    )\n    apply_forward_face_normals(p, forward=0.10, pull=0.45)\n    p.paint = dict(spec[\"paint\"], hair_cap=spec[\"paint\"][\"hair\"])\n    pal = dict(vp.PALETTE, **spec[\"colors\"])\n\n    cl = {\"idle\": spec[\"pose_fn\"](p.v, shape)}\n    glb_path = os.path.join(OUT_DIR, f\"{spec['name']}.glb\")\n    export_glb.export_skinned(p, pal, glb_path, clips=cl, max_tex=1024)\n    wrap_glb_json(glb_path)\n\n    info = export_glb.scene_info(p, pal)\n    info[\"roles\"][\"hair_cap\"] = info[\"roles\"][\"hair\"]\n    info[\"paint\"][\"hair_cap\"] = dict(kind=\"hair\", base=spec[\"paint\"][\"hair\"], shade=True)\n    return dict(\n        name=spec[\"name\"],\n        label=spec[\"label\"],\n        place=spec[\"place\"],\n        clip=\"idle\",\n        clip_t=0.0,\n        wind=spec.get(\"wind\", 0.0),\n        info=info,\n    )\n\n\ndef build_scene():\n    os.makedirs(OUT_DIR, exist_ok=True)\n    with open(SLICE_HTML) as f:\n        html = f.read()\n    with open(os.path.join(OUT_DIR, \"index.html\"), \"w\") as f:\n        f.write(html)\n\n    three_link = os.path.join(OUT_DIR, \"three\")\n    if not os.path.exists(three_link):\n        os.symlink(LOCAL_THREE, three_link)\n\n    units = [\n        dict(\n            name=\"valen\",\n            label=\"Valen (Vanguard Captain)\",\n            cage_body=\"arm_f_strong\",\n            morphs={\"Fcl_BRW_Angry\": 0.38, \"Fcl_EYE_Angry\": 0.18},\n            shape={\"blush\": 0.25},\n            costume=vanguard_captain,\n            pose_fn=vanguard_pose,\n            place={\"pos\": [-0.74, 0.0, 0.04], \"yaw\": 32.0},\n            wind=-5.2,\n            colors={\n                \"r\": \"#1e2e52\", \"s\": \"#3b629c\", \"t\": \"#8bb8ea\",\n                \"A\": \"#2f1a18\", \"o\": \"#241618\",\n            },\n            paint={\n                \"skin\": \"#f5dcd0\",\n                \"hair\": \"#542c26\",\n                \"signature\": \"#243b61\",\n                \"cape\": \"#822330\",\n                \"doublet\": \"#252836\",\n                \"heraldry\": \"#e8e2d4\",\n                \"steel\": \"#b6becb\",\n                \"gold\": \"#c89e48\",\n                \"leather\": \"#523526\",\n                \"glove\": \"#462d21\",\n                \"boot\": \"#38251c\",\n                \"wood\": \"#6b482e\",\n            },\n        ),\n        dict(\n            name=\"korin\",\n            label=\"Korin (Heavy Housecarl)\",\n            cage_body=\"arm_m_strong\",\n            morphs={\"Fcl_BRW_Angry\": 0.48, \"Fcl_EYE_Angry\": 0.22},\n            shape={\"blush\": 0.0},\n            costume=heavy_housecarl,\n            pose_fn=housecarl_pose,\n            place={\"pos\": [0.76, 0.0, -0.02], \"yaw\": -33.0},\n            wind=4.2,\n            colors={\n                \"r\": \"#2c1d14\", \"s\": \"#7a4e26\", \"t\": \"#c49052\",\n                \"A\": \"#181920\", \"o\": \"#1e1412\",\n            },\n            paint={\n                \"skin\": \"#b87a54\",\n                \"hair\": \"#252730\",\n                \"signature\": \"#7a252c\",\n                \"padding\": \"#cec2ac\",\n                \"mail\": {\"kind\": \"steel\", \"base\": \"#7d8492\"},\n                \"doublet\": \"#363b37\",\n                \"heraldry\": \"#ddd8cc\",\n                \"steel\": \"#a0a8b6\",\n                \"gold\": \"#b38b3d\",\n                \"leather\": \"#583827\",\n                \"glove\": \"#452d20\",\n                \"boot\": \"#38251c\",\n                \"wood\": \"#68462c\",\n            },\n        ),\n    ]\n\n    built_chars = [build_unit(u) for u in units]\n\n    world_holder = type(\"WorldPortrait\", (), {})()\n    world_holder.prims = terrain.plains(width=4.8, depth=2.1, thick=0.30, seed=5, tufts=34, stones=7)\n    world_holder.roles = [p[\"role\"] for p in world_holder.prims]\n    world_holder.tex = {}\n    plains_path = os.path.join(OUT_DIR, \"plains.glb\")\n    export_glb.export(world_holder, vp.PALETTE, plains_path, only_world=True)\n    wrap_glb_json(plains_path)\n\n    scene_data = dict(\n        characters=built_chars,\n        camera=dict(target=[0.02, 0.94, 0.0], height=2.12, pitch=6.5),\n        key=[-0.62, 0.48, 0.62],\n        grade=dict(ambient=[0.86, 0.88, 0.96], key=[1.03, 1.00, 0.94], rim=[0.26, 0.23, 0.18]),\n    )\n    with open(os.path.join(OUT_DIR, \"scene.json\"), \"w\") as f:\n        json.dump(scene_data, f)\n\n\ndef shoot(png_path, width=1920, height=1080, ss=2):\n    os.makedirs(os.path.dirname(os.path.abspath(png_path)), exist_ok=True)\n    sock = socket.socket()\n    sock.bind((\"127.0.0.1\", 0))\n    port = sock.getsockname()[1]\n    sock.close()\n\n    server = subprocess.Popen(\n        [sys.executable, \"-m\", \"http.server\", str(port), \"--bind\", \"127.0.0.1\", \"--directory\", OUT_DIR],\n        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,\n    )\n    try:\n        time.sleep(0.4)\n        url = f\"http://127.0.0.1:{port}/index.html?shot=1&w={width}&h={height}&ss={ss}\"\n        r = subprocess.run(\n            [\n                os.environ.get(\"CHROMIUM\", \"/snap/bin/chromium\"),\n                \"--headless=new\",\n                \"--use-angle=swiftshader\",\n                \"--enable-unsafe-swiftshader\",\n                \"--ignore-gpu-blocklist\",\n                f\"--window-size={width},{height}\",\n                \"--virtual-time-budget=600000\",\n                \"--dump-dom\",\n                url,\n            ],\n            capture_output=True, text=True, timeout=300,\n        )\n        m = re.search(r'id=\"sheetOut\"[^>]*>[redacted: data-URI prefix]([A-Za-z0-9+/=]+)<', r.stdout)\n        if not m:\n            raise RuntimeError(f\"Render failed:\\nSTDOUT:\\n{r.stdout[-600:]}\\nSTDERR:\\n{r.stderr[-800:]}\")\n        with open(png_path, \"wb\") as f:\n            f.write(base64.b64decode(m.group(1)))\n    finally:\n        server.terminate()\n\n\ndef main():\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"--png\", default=os.path.join(OUT_DIR, \"battle_frame.png\"))\n    ap.add_argument(\"--width\", type=int, default=1920)\n    ap.add_argument(\"--height\", type=int, default=1080)\n    ap.add_argument(\"--ss\", type=int, default=2)\n    args = ap.parse_args()\n\n    t0 = time.time()\n    build_scene()\n    t_build = time.time() - t0\n    t1 = time.time()\n    shoot(args.png, args.width, args.height, args.ss)\n    t_shoot = time.time() - t1\n    print(f\"wrote {args.png} (build {t_build:.1f}s, render {t_shoot:.1f}s, total {time.time() - t0:.1f}s)\")\n\n\nif __name__ == \"__main__\":\n    main()\n",
      "Overwrite": true,
      "Path": "~/work/lowmarch/tools/battle_slice.py"
    }

    result, 1 line

    Created file.
  • read_file{"Path":"~/work/lowmarch/tools/battle_slice.py"}

    input

    {
      "Path": "~/work/lowmarch/tools/battle_slice.py"
    }

    result, 626 lines

    Showing lines 1-625 of 625
    1: """Build and shoot one composed tactics battle frame on MakeHuman-caged VRoid bodies.
    2: 
    3: Uses the project's cached caged bodies (arm_f_strong, arm_m_strong), parametric armour and
    4: garment kits (outfit.py, plates.py, gear.py, hair.py), IK stances (rig.py, clips.py, duel.py),
    5: terrain (terrain.py), and painted WebGL renderer (review/slice/index.html).
    6: 
    7:   python3 tools/battle_slice.py [--png ~/out/battle_frame.png]
    8: """
    9: import argparse
    10: import base64
    11: import json
    12: import math
    13: import os
    14: import re
    15: import socket
    16: import subprocess
    17: import sys
    18: import time
    19: 
    20: import numpy as np
    21: 
    22: HERE = os.path.dirname(os.path.abspath(__file__))
    23: ROOT = os.path.dirname(HERE)
    24: sys.path[:0] = [HERE, os.path.join(ROOT, "art", "cast")]
    25: 
    26: import cage  # noqa: E402
    27: import checks  # noqa: E402
    28: import duel  # noqa: E402
    29: import export_glb  # noqa: E402
    30: import gear as G  # noqa: E402
    31: import hair as H  # noqa: E402
    32: import mobs  # noqa: E402
    33: import outfit as O  # noqa: E402
    34: import poses as P  # noqa: E402
    35: import terrain  # noqa: E402
    36: import vroid_portrait as vp  # noqa: E402
    37: from cast import CAST  # noqa: E402
    38: from fitting import Surface, merge_surfaces  # noqa: E402
    39: from plates import LimbChart, flat_piece, outline_plate  # noqa: E402
    40: from rig import Rig, grip_points  # noqa: E402
    41: 
    42: SLICE_HTML = os.path.join(ROOT, "review", "slice", "index.html")
    43: OUT_DIR = os.path.join(ROOT, "review", "out", "slice")
    44: LOCAL_THREE = "~/context/sortie-node_modules/three"
    45: 
    46: 
    47: def cached_cage_vrm(name):
    48:     """Resolve a pre-built caged VRM strictly read-only."""
    49:     p = cage.path_for(name, CAST[name]["cage"])
    50:     if not os.path.exists(p):
    51:         raise SystemExit(f"Missing cached cage body: {p}")
    52:     return p
    53: 
    54: 
    55: def arm_room(v, shape, need=0.008, most=16):
    56:     limbs = [f"{s}_{a}" for s in "LR" for a in ("UpperArm", "LowerArm")]
    57:     for deg in range(0, most + 1, 2):
    58:         b = checks.Body(v, dict(shape, arm_out=float(deg)))
    59:         if min(b.worst(pose, limbs) for pose in (P.BUST, P.BATTLE_IDLE)) >= need:
    60:             return float(deg)
    61:     return float(most)
    62: 
    63: 
    64: def add_scalp_cap(fit, hairline_front=52.0):
    65:     """Dark inner hair under-cap 2 mm off the skull so parted or warped VRoid hair never shows pale scalp."""
    66:     ch = H.head_chart(fit)
    67:     hl = lambda u: float(np.interp(abs(u), [0, 38, 68, 105, 145, 180],
    68:                                    [hairline_front, hairline_front + 6, 82, 118, 134, 140]))
    69:     pc = H.cap("scalp_cap", ch, hl, lift=0.0022, crown=0.0010, nu=64, nv=20, role="hair_cap")
    70:     fit.bind(pc, rigid="J_Bip_C_Head")
    71:     pc["group"] = "hair"
    72:     return pc
    73: 
    74: 
    75: def knightly_longsword(fit, hand="R", blade_len=0.86, blade_w=0.044, grip_len=0.17):
    76:     """Arming/bastard sword with curved crossguard quillons, faceted wheel pommel, and fuller."""
    77:     fist, fwd, side, flat, _ = G._hand_frame(fit, hand)
    78:     out = [
    79:         O.tube("grip", "leather", fist - fwd * grip_len * 0.56, fwd, grip_len, 0.0135),
    80:         O.ball("pommel", "gold", fist - fwd * (grip_len * 0.56 + 0.018), 0.022, squash=(1.0, 0.58, 1.0)),
    81:         O.ball("pommel_boss", "steel", fist - fwd * (grip_len * 0.56 + 0.018), 0.013, squash=(1.0, 0.78, 1.0)),
    82:     ]
    83:     guard_c = fist + fwd * (grip_len * 0.44 + 0.008)
    84:     ts = np.linspace(-1.0, 1.0, 17)
    85:     q_pts = np.array([guard_c + side * (0.088 * x) + fwd * (0.014 * x * x) for x in ts])
    86:     out.append(O.pipe("guard", "gold", q_pts, r=0.0068, seg=8))
    87:     for sx in (-1.0, 1.0):
    88:         out.append(O.ball(f"quillon_{1 if sx > 0 else 0}", "gold",
    89:                           guard_c + side * (0.090 * sx) + fwd * 0.015, 0.009))
    90: 
    91:     base = guard_c + fwd * 0.008
    92:     rows = 14
    93:     P_grid = np.zeros((5, rows, 3))
    94:     for j, t in enumerate(np.linspace(0, 1, rows)):
    95:         taper = 1.0 if t < 0.80 else max(0.0, (1.0 - t) / 0.20) ** 0.85
    96:         w = blade_w / 2 * (1.0 - 0.18 * t) * taper
    97:         th = 0.0048 * taper
    98:         c = base + fwd * blade_len * t
    99:         P_grid[:, j] = [c + side * w, c + flat * th, c - side * w, c - flat * th, c + side * w]
    100:     pos, tri = O.grid_mesh(P_grid)
    101:     out.append(O.piece("blade", "steel", pos, tri, outward_from=base + fwd * blade_len / 2, axis=fwd))
    102:     for sg in (-1.0, 1.0):
    103:         out.append(O.ribbon(
    104:             f"fuller_{1 if sg > 0 else 0}", "metal",
    105:             [base + fwd * blade_len * t + flat * (sg * 0.0049) for t in np.linspace(0.03, 0.68, 10)],
    106:             width=blade_w * 0.16, lift=0.0004, normals=np.tile(flat * sg, (10, 1))
    107:         ))
    108:     for pc in out:
    109:         fit.bind(pc, rigid=f"J_Bip_{hand}_Hand")
    110:         pc["group"] = "sword"
    111:     return out
    112: 
    113: 
    114: def crescent_poleaxe(fit, length=1.96, grip=0.54, hand="R", name="poleaxe"):
    115:     """Bearded crescent halberd/poleaxe with honed edge bevel, back fluke, spear tip, brass collars, and tassel."""
    116:     fist, fwd, side, flat, _ = G._hand_frame(fit, hand)
    117:     start = fist - fwd * grip
    118:     out = [O.tube(f"{name}_haft", "wood", start, fwd, length, 0.015)]
    119:     top = start + fwd * length
    120: 
    121:     # Bearded crescent axe blade
    122:     a = np.linspace(-1.0, 1.0, 17)
    123:     edge = [(0.19 * (0.76 + 0.24 * math.cos(x * 1.15)), -0.05 + 0.15 * x) for x in a]
    124:     cres = [
    125:         (0.018, -0.09),
    126:         (0.075, -0.19),
    127:     ] + edge + [
    128:         (0.065, 0.10),
    129:         (0.018, 0.045),
    130:     ]
    131:     bevel_line = [(0.165 * (0.76 + 0.24 * math.cos(x * 1.15)), -0.05 + 0.14 * x) for x in a]
    132:     deco = [("line", bevel_line, 0.0035, "groove")]
    133:     out.append(flat_piece(f"{name}_blade", "steel", cres, top - fwd * 0.11, side, fwd, thickness=0.008, decal=deco))
    134: 
    135:     # Curved rear fluke hook
    136:     hook = [(-0.018, -0.06), (-0.095, -0.095), (-0.135, -0.045), (-0.090, 0.015), (-0.018, 0.025)]
    137:     out.append(flat_piece(f"{name}_fluke", "steel", hook, top - fwd * 0.11, side, fwd, thickness=0.007))
    138: 
    139:     # Tapered diamond spear spike
    140:     spike = [(0.0, -0.01), (0.024, 0.045), (0.014, 0.16), (0.0, 0.29), (-0.014, 0.16), (-0.024, 0.045)]
    141:     out.append(flat_piece(f"{name}_spike", "steel", spike, top - fwd * 0.02, side, fwd, thickness=0.008))
    142: 
    143:     # Steel langet socket + brass collar rings + crimson tassel
    144:     out.append(O.tube(f"{name}_socket", "steel", top - fwd * 0.30, fwd, 0.29, 0.018))
    145:     for k, off in enumerate((0.02, 0.29)):
    146:         c_ring = top - fwd * off
    147:         ang = np.linspace(0, 2 * math.pi, 18, endpoint=False)
    148:         ring = np.array([c_ring + (side * math.cos(th) + flat * math.sin(th)) * 0.020 for th in ang])
    149:         out.append(O.pipe(f"{name}_collar{k}", "gold", ring, r=0.0038, seg=6, closed=True))
    150: 
    151:     tassel_root = top - fwd * 0.30 - side * 0.018
    152:     t_pts = np.array([tassel_root + np.array([0.0, -0.032 * s, 0.008 * s]) - side * (0.018 * s)
    153:                       for s in np.linspace(0, 1, 7)])
    154:     out.append(O.pipe(f"{name}_tassel", "signature", t_pts, r=0.0075, seg=6))
    155:     out.append(O.ball(f"{name}_butt", "steel", start - fwd * 0.012, 0.019, squash=(1, 1, 1.5)))
    156:     G._bind(fit, out, f"J_Bip_{hand}_Hand")
    157:     return G._group(out, "weapon")
    158: 
    159: 
    160: def cloak_clasps(fit, under, role="gold", cord_role="gold", y_off=-0.036, x_deg=34.0):
    161:     """Pair of domed collarbone cloak-clasps with a draped chest cord between them."""
    162:     nk = fit.bone["J_Bip_C_Neck"]
    163:     pts = []
    164:     out = []
    165:     for k, sgn in enumerate((-1.0, 1.0)):
    166:         a = math.radians(sgn * x_deg)
    167:         d = np.array([math.sin(a), 0.0, -math.cos(a)])
    168:         o = np.array([nk[0], nk[1] + y_off, nk[2]])
    169:         r = under.cast(o, d, rmax=0.26, far=True)
    170:         p = o + d * ((0.09 if np.isnan(r) else r) + 0.008)
    171:         pts.append(p)
    172:         cl = O.ball(f"clasp_{k}", role, p, 0.014, seg=12, rows=7, squash=(1.0, 1.0, 0.55))
    173:         fit.bind(cl, rigid="J_Bip_C_UpperChest")
    174:         cl["group"] = "trim"
    175:         out.append(cl)
    176:     ts = np.linspace(0, 1, 15)
    177:     cord = []
    178:     for t in ts:
    179:         q = pts[0] * (1 - t) + pts[1] * t + np.array([0.0, -0.022 * math.sin(math.pi * t), -0.010 * math.sin(math.pi * t)])
    180:         cord.append(q)
    181:     cp = O.pipe("clasp_cord", cord_role, np.array(cord), r=0.0032, seg=6)
    182:     fit.bind(cp, rigid="J_Bip_C_UpperChest")
    183:     cp["group"] = "trim"
    184:     out.append(cp)
    185:     return out
    186: 
    187: 
    188: def vanguard_captain(fit):
    189:     """Original Lowmarch vanguard officer costume fitted to arm_f_strong."""
    190:     B = fit.bone
    191:     hips, nk = B["J_Bip_C_Hips"], B["J_Bip_C_Neck"]
    192:     knee = B["J_Bip_L_LowerLeg"][1]
    193:     cuff_len = 0.56
    194:     boot_top = knee + 0.055
    195:     y_waist = hips[1] + 0.055
    196:     y_skirt = hips[1] - 0.25
    197: 
    198:     out, shirt, trousers, boots = mobs._base(
    199:         fit, shirt="signature", legs="doublet", boots="boot", gloves="glove",
    200:         shirt_subdiv=0, boot_top=boot_top
    201:     )
    202:     G.loose_sleeves(fit, shirt, ease=0.028, cuff=cuff_len, folds=6)
    203:     G.flare_boots(fit, boots, boot_top - 0.005, ease=0.010)
    204: 
    205:     # Hide bare-foot toes under armoured steel sabatons
    206:     for side in ("L", "R"):
    207:         sabs = O.sabaton(fit, f"sabaton_{side}", side, role="steel", pad=0.011, ridges=3)
    208:         out += G._group(sabs, "plate")
    209: 
    210:     under = mobs._under(shirt)
    211:     skirt_pcs = G.pleated_skirt(
    212:         fit, under, y_waist, y_skirt, role="signature", name="battle_skirt",
    213:         flare=0.098, pleats=24, depth=0.011, split=20.0
    214:     )
    215:     for sp in skirt_pcs:
    216:         if "plate" in sp:
    217:             sp["plate"][:, 2] = 0.009
    218:     out += skirt_pcs
    219:     G.slim_under(fit, trousers, y_skirt)
    220: 
    221:     # Sculpted steel cuirass + plackart with antique-gold border
    222:     bp = G.breastplate(fit, under, role="steel", arm=62.0, keel=0.009)
    223:     for pc in bp:
    224:         if "plate" in pc:
    225:             pc["plate"][:, 2] = 0.0075
    226:     out += bp
    227: 
    228:     # Standing indigo officer collar with gold rim
    229:     col_pc, col_top, _ = O.collar(fit, "collar", "signature", height_back=0.042, height_front=0.026, gap_deg=54)
    230:     col_trim = O.inherit(O.pipe("collar_trim", "gold", col_top, r=0.0025, seg=6), col_pc)
    231:     col_pc["group"] = col_trim["group"] = "collar"
    232:     out += [col_pc, col_trim]
    233: 
    234:     # Fuller 3-lame steel spaulders + smooth LimbChart shin greaves with gold borders
    235:     plate_surf = merge_surfaces(*[(p["pos"], p["tri"]) for p in out if p.get("group") == "plate"], (fit.pos, fit.tri))
    236:     for side in ("L", "R"):
    237:         sp, rims = O.pauldron(
    238:             fit, f"spaulder_{side}", "steel", plate_surf, side=side,
    239:             lames=((0, 56, 0.022, 0.030), (47, 74, 0.020, 0.027), (66, 92, 0.018, 0.024)), spread=116
    240:         )
    241:         out += G._group(
    242:             sp + [O.inherit(O.pipe(f"spaulder_{side}_roll{k}", "gold" if k == 0 else "steel", r_, r=0.0026), pc)
    243:                   for k, (pc, r_) in enumerate(zip(sp, rims))],
    244:             "plate"
    245:         )
    246:         ll, ft = B[f"J_Bip_{side}_LowerLeg"], B[f"J_Bip_{side}_Foot"]
    247:         lc = LimbChart(O.side_of(boots, side), ll, ft, front=(0, 0, -1), smooth=(1.6, 1.5))
    248:         gv, gx = outline_plate(
    249:             f"greave_{side}", "steel", lc, -108, 108,
    250:             lambda u: 0.80 - 0.04 * (abs(u) / 108) ** 1.5,
    251:             lambda u: 0.16 + 0.05 * max(0.0, 1.0 - (u / 45.0) ** 2),
    252:             offset=0.008, crown=0.004, thickness=0.004, nu=40, nv=16,
    253:             trim=0.0055, roll=0.0026, roll_edges=("top", "bottom")
    254:         )
    255:         fit.bind(gv, rigid=f"J_Bip_{side}_LowerLeg")
    256:         out += G._group([gv] + [O.inherit(q, gv) for q in gx], "plate")
    257: 
    258:     # Waist belt + gold buckle
    259:     belt_over = mobs._surf(out, "breastplate", prefix=True)
    260:     belt_pc, front_pt = O.belt(fit, "belt", "leather", belt_over, hips[1] + 0.048, height=0.036, offset=0.005)
    261:     buckle = fit.bind(O.box("buckle", "gold", front_pt + np.array([0, 0, -0.005]),
    262:                             ([1, 0, 0], [0, 1, 0], [0, 0, 1]), (0.025, 0.025, 0.006)), rigid="J_Bip_C_Hips")
    263:     buckle["group"] = "belt"
    264:     out += [belt_pc, buckle]
    265: 
    266:     cuff_pcs = G.cuffs(fit, role="glove", length=cuff_len, flare=0.028)
    267:     G.tuck_sleeves(fit, shirt, cuff_pcs)
    268:     out += cuff_pcs
    269: 
    270:     # Flowing crimson officer cloak clasped at collarbones
    271:     cape_under = merge_surfaces(
    272:         *[(p["pos"], p["tri"]) for p in out if p.get("group") in ("plate", "doublet")],
    273:         (fit.pos, fit.tri)
    274:     )
    275:     cape_pc, _ = O.cape(fit, "cape", "cape", cape_under, length=0.96, phi=0.58, seg=44, rows=18, clear=(0.016, 0.055))
    276:     cape_pc["group"] = "cape"
    277:     out.append(cape_pc)
    278:     out += cloak_clasps(fit, cape_under, role="gold", cord_role="gold", y_off=-0.038, x_deg=35.0)
    279: 
    280:     # Heater shield with heraldic gold chevron + inner grip straps so the left hand holds a real enarme
    281:     emblem = [
    282:         ("poly", [(-0.11, 0.06), (0.0, 0.16), (0.11, 0.06), (0.11, 0.01), (0.0, 0.11), (-0.11, 0.01)], "gold"),
    283:         ("poly", [(-0.045, -0.01), (0.045, -0.01), (0.0, -0.17)], "gold"),
    284:     ]
    285:     sh_pcs = G.shield(fit, "heater", side="L", role="signature", width=0.36, height=0.50, curve=0.44, emblem=emblem)
    286:     E_l, H_l = B["J_Bip_L_LowerArm"], B["J_Bip_L_Hand"]
    287:     ax_l = (H_l - E_l) / np.linalg.norm(H_l - E_l)
    288:     lat_l = np.array([-1.0, 0.0, 0.0]) - ax_l * (-ax_l[0])
    289:     lat_l /= np.linalg.norm(lat_l)
    290:     grip_bar = O.tube("shield_enarme", "leather", H_l + lat_l * 0.035 - np.array([0, 0, 0.05]),
    291:                       np.array([0, 0, 1.0]), 0.10, 0.010)
    292:     fit.bind(grip_bar, rigid="J_Bip_L_LowerArm")
    293:     grip_bar["group"] = "shield"
    294:     out += sh_pcs + [grip_bar]
    295: 
    296:     out += knightly_longsword(fit, "R")
    297:     out.append(add_scalp_cap(fit, hairline_front=54.0))
    298:     return out
    299: 
    300: 
    301: def heavy_housecarl(fit):
    302:     """Original Lowmarch heavy housecarl costume fitted to arm_m_strong (unhelmeted so face/hair read)."""
    303:     B = fit.bone
    304:     hips = B["J_Bip_C_Hips"]
    305:     knee = B["J_Bip_L_LowerLeg"][1]
    306:     boot_top = knee - 0.075
    307:     y_gambeson = hips[1] - 0.24
    308:     y_mail = hips[1] - 0.15
    309: 
    310:     out, shirt, trousers, boots = mobs._base(
    311:         fit, shirt="padding", legs="doublet", boots="boot", gloves="glove", boot_top=boot_top
    312:     )
    313:     G.breeches(fit, trousers, boots, y_gambeson, boot_top - 0.005, ease=0.040)
    314:     # Smooth leather shoe-lasts over both feet so VRoid toes never show
    315:     for side in ("L", "R"):
    316:         lasts = O.sabaton(fit, f"boot_last_{side}", side, role="boot", pad=0.011, ridges=0)
    317:         out += G._group(lasts, "boots")
    318: 
    319:     under = mobs._under(shirt)
    320:     out += G.quilted(fit, under, role="padding", y_hem=y_gambeson, sleeve_end=0.92)
    321:     gam = mobs._surf(out, "gambeson", "gambeson_skirt")
    322:     out += G.mail_shirt(fit, gam, role="mail", y_hem=y_mail, sleeve=0.52)
    323:     mail = mobs._surf(out, "hauberk", prefix=True)
    324:     out += G.riveted_vest(fit, mail, role="leather", rivet_role="steel")
    325: 
    326:     # Exact torso pieces only (never hauberk_sleeve_*) so the belt hugs the waist cleanly
    327:     vest_torso = mobs._surf(out, "brigandine_front", "brigandine_back", "hauberk")
    328:     belt_pc, front_pt = O.belt(fit, "belt", "leather", vest_torso, hips[1] + 0.038, height=0.046, offset=0.006)
    329:     buckle = fit.bind(O.box("buckle", "steel", front_pt + np.array([0, 0, -0.006]),
    330:                             ([1, 0, 0], [0, 1, 0], [0, 0, 1]), (0.028, 0.028, 0.007)), rigid="J_Bip_C_Hips")
    331:     buckle["group"] = "belt"
    332:     out += [belt_pc, buckle]
    333: 
    334:     # Standing oxblood wool collar + draped battle cloak pinned cleanly behind shoulders (zero chest pokethrough)
    335:     col_pc, col_top, _ = O.collar(fit, "collar", "signature", height_back=0.044, height_front=0.028, gap_deg=60,
    336:                                   clear=(0.013, 0.019))
    337:     col_pc["group"] = "collar"
    338:     out.append(col_pc)
    339: 
    340:     cape_under = merge_surfaces(
    341:         *[(p["pos"], p["tri"]) for p in out if p["material"] in ("OUTFIT_brigandine_front", "OUTFIT_brigandine_back",
    342:                                                                  "OUTFIT_hauberk", "OUTFIT_gambeson")],
    343:         (fit.pos, fit.tri)
    344:     )
    345:     cape_pc, _ = O.cape(fit, "cape", "signature", cape_under, length=0.94, phi=0.54, seg=42, rows=18,
    346:                         clear=(0.018, 0.058))
    347:     cape_pc["group"] = "cape"
    348:     out.append(cape_pc)
    349:     out += cloak_clasps(fit, cape_under, role="steel", cord_role="leather", y_off=-0.042, x_deg=36.0)
    350: 
    351:     out += G.cuffs(fit, role="glove", length=0.35, flare=0.032)
    352:     out += crescent_poleaxe(fit, length=1.96, grip=0.54, hand="R")
    353:     out.append(add_scalp_cap(fit, hairline_front=50.0))
    354:     return out
    355: 
    356: 
    357: def vanguard_pose(vrm, shape):
    358:     """Grounded fencing guard for Valen: sword poised forward, heater shield angled cleanly on outer guard."""
    359:     rig = Rig(vrm, shape, ortho=True)
    360:     body = checks.Body(vrm, shape)
    361:     f = {s: g["point"] for s, g in grip_points(vrm, shape, P.BUST).items()}
    362:     ref = dict(ref_pose=P.BUST, fist_R=f["R"], fist_L=f["L"])
    363: 
    364:     base = P.merge(P.BATTLE_IDLE, P.fist("L", curl=(68, 80, 55), thumb=32), {
    365:         "J_Bip_C_Hips": P.move(0, -0.055, -0.02, P.rot((0, 1, 0), -10.0) @ P.rot((1, 0, 0), -4.5)),
    366:         "J_Bip_C_Spine": P.rot((0, 1, 0), -8.0) @ P.rot((1, 0, 0), -3.0),
    367:         "J_Bip_C_Chest": P.rot((0, 1, 0), -6.0) @ P.rot((1, 0, 0), -2.0),
    368:         "J_Bip_C_Neck": P.rot((0, 1, 0), 11.0) @ P.rot((1, 0, 0), 3.0),
    369:         "J_Bip_C_Head": P.rot((0, 1, 0), 10.0) @ P.rot((1, 0, 0), 2.5),
    370:     })
    371:     foot = {s: rig.pos(P.BATTLE_IDLE, f"J_Bip_{s}_Foot") for s in "LR"}
    372:     pose = rig.leg_ik(base, "L", foot["L"] + np.array([-0.06, 0.0, -0.17]), pole=(0, 0, -1))
    373:     pose = rig.leg_ik(pose, "R", foot["R"] + np.array([0.07, 0.0, 0.14]), pole=(0, -0.2, -1))
    374: 
    375:     sh_r = rig.pos(pose, "J_Bip_R_UpperArm")
    376:     fist_r = sh_r + np.array([0.09, -0.34, -0.22])
    377:     blade_dir = np.array([-0.24, 0.48, -0.84])
    378:     pose = duel.clear_grip(rig, body, pose, "R", ref, fist_r, blade_dir, (0.7, -0.9, 0.35))
    379: 
    380:     # Left arm braced outward and rotated about forearm axis so the shield's heraldic face turns ~42° toward camera
    381:     sh_l = rig.pos(pose, "J_Bip_L_UpperArm")
    382:     pose = rig.arm_ik(pose, "L", sh_l + np.array([-0.22, -0.24, -0.08]), pole=(-0.9, -0.6, 0.4))
    383:     ax_la = rig.pos(pose, "J_Bip_L_Hand") - rig.pos(pose, "J_Bip_L_LowerArm")
    384:     pose = rig.rotate_world(pose, "J_Bip_L_LowerArm", P.rot(ax_la, -52.0))
    385:     return [(0.0, pose), (1.0, pose)]
    386: 
    387: 
    388: def housecarl_pose(vrm, shape):
    389:     """Two-handed poleaxe guard for Korin: wide planted stance, head angled cleanly toward opponent."""
    390:     rig = Rig(vrm, shape, ortho=True)
    391:     body = checks.Body(vrm, shape)
    392:     f = {s: g["point"] for s, g in grip_points(vrm, shape, P.BUST).items()}
    393:     ref = dict(ref_pose=P.BUST, fist_R=f["R"], fist_L=f["L"])
    394: 
    395:     arm_l = rig.pos(P.BUST, "J_Bip_L_LowerArm") - rig.pos(P.BUST, "J_Bip_L_UpperArm")
    396:     span_l = float(np.linalg.norm(arm_l) + np.linalg.norm(f["L"] - rig.pos(P.BUST, "J_Bip_L_LowerArm")))
    397:     arm_r = rig.pos(P.BUST, "J_Bip_R_LowerArm") - rig.pos(P.BUST, "J_Bip_R_UpperArm")
    398:     span_r = float(np.linalg.norm(arm_r) + np.linalg.norm(f["R"] - rig.pos(P.BUST, "J_Bip_R_LowerArm")))
    399: 

    226 more lines not shown.