agent (cont.)

+3:10
  • read_file{"EndLine":300,"Path":"~/work/lowmarch/tools/vroid_portrait.py","StartLine":1}

    input

    {
      "EndLine": 300,
      "Path": "~/work/lowmarch/tools/vroid_portrait.py",
      "StartLine": 1
    }

    result, 301 lines

    Showing lines 1-300 of 1407
    1: """Render a VRoid model as a GBA-style portrait (96x80) in our palette.
    2: 
    3: Pipeline: rasterize at SSx (vrm.rasterize) -> classify each pixel by material role -> shade in
    4: palette tones (skin/hair/cloth bands from normals; eyes, brows, lashes from alpha-tested masks)
    5: -> reduce to 1x with feature priority -> outline (silhouette, strand separations, jaw over neck)
    6: -> hair shadow on the forehead.
    7: 
    8:   python3 tools/vroid_portrait.py MODEL.vrm [--yaw 35] [--png out.png] [--scale 6]
    9: """
    10: import argparse
    11: import math
    12: import os
    13: import sys
    14: 
    15: import numpy as np
    16: from PIL import Image
    17: 
    18: HERE = os.path.dirname(os.path.abspath(__file__))
    19: sys.path.insert(0, HERE)
    20: from vrm import VRM, rasterize, interpolate  # noqa: E402
    21: from head3d import rotation, SKIN, HAIR_TONES, COAT  # noqa: E402
    22: 
    23: SS = 4
    24: EYES = {"w": "#f4fbff", "r": "#33264a", "s": "#4a5ca8", "t": "#8fb4e8"}
    25: CAPE = {"U": "#3a1a2a", "V": "#6a2a3a", "W": "#9a3a4a", "X": "#c86070"}
    26: METAL = {"6": "#3a3e58", "7": "#6a7090", "8": "#a8b0c8", "9": "#eef2fa"}
    27: GOLD = {"G": "#8a5a1a", "H": "#d8a640", "I": "#fff0a0"}
    28: LEATHER = {"u": "#4b2b21", "v": "#83502f", "x": "#b98351"}
    29: DOUBLET = {"Q": "#14151d", "R": "#22242f", "S": "#333646", "T": "#4c5064"}     # dark under-layer (never skin-like)
    30: HERALDRY = {"F": "#6a6e7c", "J": "#a4a8b4", "N": "#d4d7de", "O": "#f1f2f5"}    # cool white: borders, devices
    31: GRASS = {"a": "#22401f", "b": "#36652c", "c": "#58923a", "d": "#93c257"}
    32: DIRT = {"e": "#3e2a1e", "f": "#6e4a30", "i": "#9c7450"}
    33: STONE = {"k": "#46465a", "l": "#76768a", "m": "#b2b2c0"}
    34: PALETTE = {**SKIN, **HAIR_TONES, **COAT, **EYES, **CAPE, **METAL, **GOLD, **LEATHER, **DOUBLET, **HERALDRY, **GRASS,
    35:            **DIRT, **STONE}
    36: 
    37: # material name fragment -> role (first match wins)
    38: ROLES = [("EyeHighlight", "highlight"), ("EyeIris", "iris"), ("EyeWhite", "white"), ("EyeExtra", "skip"),
    39:          ("FaceEyeline", "line"), ("FaceEyelash", "line"), ("FaceMouthLine", "line"), ("FaceBrow", "brow"), ("FaceMouth", "mouth"),
    40:          ("Face_00_SKIN", "face"), ("Body_00_SKIN", "body"), ("HairBack", "hair"), ("_HAIR", "hair"),
    41:          ("CLOTH", "cloth")]
    42: PRIORITY = {"o": 8, "r": 5, "s": 5, "t": 4, "w": 3, "A": 3, "1": 8}   # features win the 4x4 vote
    43: FACE_MARK = 0.70        # face-texture texels darker than this are painted lines (lip line, nose mark)
    44: MARK_GROW = 4           # texels of dilation so a 1.5 mm painted line survives the 4x4 vote
    45: LIP_DROP = 0.014        # UV distance below the lip line that gets the lower-lip shade
    46: # VRoid face textures share one layout: marks only count inside the nose-and-mouth window
    47: MARK_WINDOW = dict(u=(0.32, 0.68), v=(0.58, 0.86), nose_below=0.70)
    48: 
    49: # High-resolution pixel rendering (2026-10-08): a 640x360 base screen (scales cleanly to 1080p/4K).
    50: BUST_SIZE, BUST_EYE_CHIN, BUST_EYE_AT = (192, 160), 38.0, (92, 60)   # portrait: canvas, eye-to-chin px, eye line
    51: BATTLE_SIZE, BATTLE_PX_PER_M, BATTLE_GROUND_AT = (640, 360), 90.0, (420, 318)   # battle: canvas, scale, feet
    52: SUN = np.array([-0.30, 0.85, 0.45]) / np.linalg.norm([-0.30, 0.85, 0.45])   # scenery light (camera space)
    53: LID_CORE = 70                               # eyeline texels darker than this are the lash line
    54: LIGHT = np.array([0.08, 0.06, 1.0]) / np.linalg.norm([0.08, 0.06, 1.0])
    55: SKIN_BANDS = [(0.80, "5"), (0.62, "4"), (0.38, "3"), (-9, "2")]
    56: HAIR_BANDS = [(0.86, "E"), (0.66, "D"), (0.42, "C"), (-9, "B")]
    57: CLOTH_BANDS = [(0.85, "P"), (0.6, "M"), (0.35, "L"), (-9, "K")]
    58: # costume materials: role -> bands (metal has a narrow bright streak and hard darks)
    59: MATERIALS = {"coat": CLOTH_BANDS,
    60:              "signature": CLOTH_BANDS,                   # the character's one colour (tabard, mantle, shield)
    61:              "doublet": [(0.85, "T"), (0.6, "S"), (0.35, "R"), (-9, "Q")],
    62:              "heraldry": [(0.85, "O"), (0.6, "N"), (0.35, "J"), (-9, "F")],
    63:              "cape": [(0.85, "X"), (0.6, "W"), (0.35, "V"), (-9, "U")],
    64:              "metal": [(0.975, "9"), (0.86, "8"), (0.55, "7"), (-9, "6")],
    65:              "gold": [(0.80, "I"), (0.45, "H"), (-9, "G")],
    66:              "leather": [(0.75, "x"), (0.4, "v"), (-9, "u")],
    67:              "boot": [(0.80, "x"), (0.45, "v"), (-9, "u")],
    68:              "glove": [(0.75, "x"), (0.4, "v"), (-9, "u")],
    69:              "steel": [(0.90, "9"), (0.70, "8"), (0.40, "7"), (-9, "6")],
    70:              "grass": [(0.90, "d"), (0.70, "c"), (0.40, "b"), (-9, "a")],
    71:              "dirt": [(0.70, "i"), (0.35, "f"), (-9, "e")],
    72:              "stone": [(0.80, "m"), (0.45, "l"), (-9, "k")]}
    73: WORLD_ROLES = ("grass", "dirt", "stone")
    74: DARKER = {c: tbl[min(i + 1, len(tbl) - 1)][1] for tbl in MATERIALS.values() for i, (_, c) in enumerate(tbl)}
    75: FLIP = np.array([-1.0, 1.0, -1.0])          # VRoid faces -z; we want the face toward +z (the viewer)
    76: 
    77: 
    78: def role_of(material):
    79:     for frag, role in ROLES:
    80:         if frag in material:
    81:             return role
    82:     return "cloth"
    83: 
    84: 
    85: def bands(v, table):
    86:     out = np.full(v.shape, table[-1][1], "<U1")
    87:     for thr, ch in reversed(table):
    88:         out[v >= thr] = ch
    89:     return out
    90: 
    91: 
    92: from poses import rot, BUST as BUST_POSE, BATTLE_IDLE  # noqa: E402,F401
    93: 
    94: 
    95: def repose(v, prims, ref, target):
    96:     """Move prims built in the `ref` pose to the `target` pose: each bone's change
    97:     W_target(j) @ W_ref(j)^-1, blended by the skin weights (bones missing from this skeleton,
    98:     like another model's hair bones, follow the head)."""
    99:     names = v.nodes_by_name()
    100:     Wr, Wt = v.node_world(ref), v.node_world(target)
    101:     cache = {}
    102: 
    103:     def delta(nm):
    104:         if nm not in cache:
    105:             i = names.get(nm, names["J_Bip_C_Head"])
    106:             cache[nm] = Wt[i] @ np.linalg.inv(Wr[i])
    107:         return cache[nm]
    108: 
    109:     for p in prims:
    110:         if "J" not in p:
    111:             continue
    112:         D = np.stack([delta(nm) for nm in p["jnames"]])          # (nj,4,4)
    113:         M = (D[p["J"]] * p["W"][:, :, None, None]).sum(1)        # (N,4,4)
    114:         p["pos"] = np.einsum("nij,nj->ni", M[:, :3, :3], p["pos"]) + M[:, :3, 3]
    115:         n = np.einsum("nij,nj->ni", M[:, :3, :3], p["nrm"])
    116:         p["nrm"] = n / np.maximum(np.linalg.norm(n, axis=1, keepdims=True), 1e-12)
    117: 
    118: 
    119: def reduce_blocks(char, depth, pid, role, h, w):
    120:     """Majority vote over each SSxSS block, weighted by PRIORITY so thin features survive. Returns
    121:     the winning char per pixel plus the depth / primitive / role of its nearest sample."""
    122:     blk = lambda a: a.reshape(h, SS, w, SS).transpose(0, 2, 1, 3).reshape(h * w, SS * SS)
    123:     cb, db, pb, rb = blk(char), blk(depth), blk(pid), blk(role)
    124:     codes, ci = np.unique(cb, return_inverse=True)
    125:     ci = ci.reshape(cb.shape)
    126:     nc = len(codes)
    127:     counts = np.bincount((np.arange(h * w)[:, None] * nc + ci).ravel(), minlength=h * w * nc).reshape(h * w, nc)
    128:     empty = np.nonzero(codes == "")[0]
    129:     filled = SS * SS - (counts[:, empty[0]] if len(empty) else 0)
    130:     score = counts * np.array([0 if c_ == "" else PRIORITY.get(c_, 1) for c_ in codes])[None]
    131:     best = np.argmax(score, 1)
    132:     ok = filled >= SS * SS / 2
    133:     sel = ci == best[:, None]
    134:     i = np.argmax(np.where(sel, db, -np.inf), 1)
    135:     r = np.arange(h * w)
    136:     out = np.where(ok, codes[best], "").astype("<U1")
    137:     dep = np.where(ok, db[r, i], -np.inf)
    138:     prim = np.where(ok, pb[r, i], -1)
    139:     rol = np.where(ok, rb[r, i], "")
    140:     return out.reshape(h, w), dep.reshape(h, w), prim.reshape(h, w), rol.reshape(h, w)
    141: 
    142: 
    143: def camera_rotation(yaw, pitch):
    144:     """Model -> camera: turn the character by yaw (positive faces screen left), then look down on
    145:     it from `pitch` degrees above (a camera elevation, not a nod)."""
    146:     y, p = math.radians(yaw), math.radians(pitch)
    147:     Ry = np.array([[math.cos(y), 0, -math.sin(y)], [0, 1, 0], [math.sin(y), 0, math.cos(y)]])
    148:     Rx = np.array([[1, 0, 0], [0, math.cos(p), -math.sin(p)], [0, math.sin(p), math.cos(p)]])
    149:     return Rx @ Ry
    150: 
    151: 
    152: def smooth(t):
    153:     t = np.clip(t, 0, 1)
    154:     return t * t * (3 - 2 * t)
    155: 
    156: 
    157: # Archetype shape controls, in three layers (0 / 1 / {} = unchanged):
    158: #  1. proportions through the skeleton: bone scales, the way VRoid varies builds
    159: #  2. face sculpting: anatomical points move, anchors (eyes, ears, skull, neck) hold still, and a
    160: #     smooth RBF field fills in between
    161: #  3. resting expression: VRoid's own shapes (hooded eyes, stern brows) held at a low weight
    162: NEUTRAL = dict(head=1.0, neck=1.0, chest=1.0, height=1.0,
    163:                shoulders=1.0, arms=1.0, torso=1.0, legs=1.0, leg_len=1.0, hands=1.0, shoulder_w=0.0,
    164:                face_len=0.0, jaw=0.0, chin_w=0.0, chin_len=0.0, cheek=0.0, brow_ridge=0.0,
    165:                nose=0.0, nose_w=0.0,
    166:                eye=1.0, eye_tilt=0.0, iris=1.0, lash=1.0, mouth=1.0, arm_out=0.0, age_lines=0.0, blush=1.0, curl=0.0,
    167:                face_normals=1.0, hair_normals=0.0, shadow_cards=1.0, fangs=1.0, rest={})
    168: # hair is reshaped with the face: beards (built on the face before the face is sculpted) and side locks
    169: # must follow a wider jaw or a longer chin, or the skin comes through them
    170: SCULPT_ROLES = ("face", "body", "mouth", "brow", "line", "white", "iris", "highlight", "hair")
    171: 
    172: 
    173: def bone_pose(v, sh, base_pose):
    174:     """Pose dict (bone -> 3x3) = base rotations combined with proportion scales. Each scaled bone
    175:     resets its children to scale 1 except the head, whose children (hair bones) grow with it."""
    176:     # Body proportions (all 1.0 = VRoid's): shoulders lengthens the clavicles (wider shoulders), arms
    177:     # and legs thicken the limbs, torso broadens the waist-to-chest, leg_len lengthens thigh and shin
    178:     # (the hips are lifted to keep the feet on the ground), hands scales the hands.
    179:     a, lg, t = sh["arms"], sh["legs"], sh["torso"]
    180:     spec = {"J_Bip_C_Head": ((sh["head"],) * 3, True),
    181:             "J_Bip_C_Neck": ((sh["neck"], 1.0, sh["neck"]), False),
    182:             "J_Bip_C_UpperChest": ((sh["chest"], 1.0, 1 + (sh["chest"] - 1) * 0.6), False),
    183:             "J_Bip_C_Spine": ((1 + (t - 1) * 0.7, 1.0, 1 + (t - 1) * 0.5), False),
    184:             "J_Bip_C_Chest": ((t, 1.0, 1 + (t - 1) * 0.7), False)}
    185:     for side in "LR":
    186:         spec[f"J_Bip_{side}_Shoulder"] = ((sh["shoulders"], 1.0, 1.0), False)
    187:         for b in ("UpperArm", "LowerArm"):
    188:             spec[f"J_Bip_{side}_{b}"] = ((1.0, a, a), False)          # arm bones run along x
    189:         for b in ("UpperLeg", "LowerLeg"):
    190:             spec[f"J_Bip_{side}_{b}"] = ((lg, sh["leg_len"], lg), False)  # leg bones run along y
    191:         spec[f"J_Bip_{side}_Hand"] = ((sh["hands"],) * 3, True)
    192:     spec = {k: v for k, v in spec.items() if not np.allclose(v[0], 1.0)}
    193:     nodes = v.j["nodes"]
    194:     parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])}
    195:     own = {}
    196: 
    197:     def own_of(i):
    198:         if i in own:
    199:             return own[i]
    200:         nm = nodes[i].get("name")
    201:         if nm in spec:
    202:             own[i] = np.array(spec[nm][0], float)
    203:         elif i in parent and nodes[parent[i]].get("name") in spec and spec[nodes[parent[i]]["name"]][1]:
    204:             own[i] = own_of(parent[i])
    205:         elif i in parent and (own_of(parent[i]) != 1).any() and nodes[parent[i]].get("name") not in spec:
    206:             own[i] = own_of(parent[i])          # inherited chain (below the head)
    207:         else:
    208:             own[i] = np.ones(3)
    209:         return own[i]
    210: 
    211:     def as4(r):
    212:         r = np.asarray(r, float)
    213:         if r.shape == (4, 4):
    214:             return r
    215:         m = np.eye(4)
    216:         m[:3, :3] = r
    217:         return m
    218:     pose = {k: as4(r) for k, r in base_pose.items()}
    219:     for i, n in enumerate(nodes):
    220:         nm = n.get("name")
    221:         if not nm:
    222:             continue
    223:         mine = own_of(i)
    224:         par = own_of(parent[i]) if i in parent else np.ones(3)
    225:         adj = mine / par
    226:         if np.allclose(adj, 1):
    227:             continue
    228:         pose[nm] = pose.get(nm, np.eye(4)) @ np.diag(list(adj) + [1.0])
    229:     if sh["shoulder_w"]:                        # wider shoulders by moving the arm joints out (no shear, unlike
    230:         for side, sx in (("L", -1.0), ("R", 1.0)):  # `shoulders`, which scales the clavicle and skews a turned arm)
    231:             mv = np.eye(4)
    232:             mv[0, 3] = sx * sh["shoulder_w"]
    233:             nm = f"J_Bip_{side}_UpperArm"
    234:             pose[nm] = mv @ pose.get(nm, np.eye(4))
    235:     if sh.get("curl"):                          # relaxed hands (degrees per finger joint) wherever the pose
    236:         for side, sg in (("L", 1.0), ("R", -1.0)):  # leaves the fingers alone: an open hand reads as a paddle
    237:             for f in ("Index", "Middle", "Ring", "Little"):
    238:                 for j, kf in ((1, 0.6), (2, 1.0), (3, 0.8)):
    239:                     nm = f"J_Bip_{side}_{f}{j}"
    240:                     if nm in base_pose:
    241:                         continue
    242:                     a = np.radians(sg * sh["curl"] * kf * (1.0 + 0.12 * ("Index", "Middle", "Ring", "Little").index(f)))
    243:                     r = np.eye(4)
    244:                     r[:2, :2] = [[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]]
    245:                     pose[nm] = pose.get(nm, np.eye(4)) @ r
    246:     if sh.get("arm_out"):                       # arms held further from the body (degrees): a broad torso
    247:         for side, sg in (("L", -1.0), ("R", 1.0)):  # needs room for hanging arms
    248:             a = np.radians(sg * sh["arm_out"])
    249:             r = np.eye(4)
    250:             r[:2, :2] = [[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]]
    251:             nm = f"J_Bip_{side}_UpperArm"
    252:             pose[nm] = r @ pose.get(nm, np.eye(4))
    253:     if sh["leg_len"] != 1.0:                    # longer legs: lift the hips so the feet stay on the ground
    254:         W = v.node_world()
    255:         names = v.nodes_by_name()
    256:         leg = W[names["J_Bip_L_UpperLeg"]][1, 3] - W[names["J_Bip_L_Foot"]][1, 3]
    257:         lift = np.eye(4)
    258:         lift[1, 3] = (sh["leg_len"] - 1.0) * leg
    259:         pose["J_Bip_C_Hips"] = lift @ pose.get("J_Bip_C_Hips", np.eye(4))
    260:     if sh["height"] != 1.0:                     # the whole figure scaled from the hips (everything below them
    261:         W = v.node_world()                      # grows with them), lifted so the soles stay on the ground
    262:         names = v.nodes_by_name()
    263:         hip = W[names["J_Bip_C_Hips"]][1, 3] + (sh["leg_len"] - 1.0) * (
    264:             W[names["J_Bip_L_UpperLeg"]][1, 3] - W[names["J_Bip_L_Foot"]][1, 3])
    265:         if getattr(v, "_sole", None) is None:   # (reading every mesh is slow; this runs for every pose)
    266:             v._sole = min(float(p_["pos"][:, 1].min()) for p_ in v.primitives() if len(p_["pos"]))
    267:         sole = v._sole
    268:         lift = np.eye(4)
    269:         lift[1, 3] = (sh["height"] - 1.0) * (hip - sole)
    270:         pose["J_Bip_C_Hips"] = lift @ pose.get("J_Bip_C_Hips", np.eye(4)) @ np.diag([sh["height"]] * 3 + [1.0])
    271:     return pose
    272: 
    273: 
    274: def landmarks(prims, roles):
    275:     def verts(*rs):
    276:         return np.concatenate([p["pos"][np.unique(p["tri"])] for p, r in zip(prims, roles) if r in rs])
    277:     iris = verts("iris")
    278:     face = verts("face")
    279:     body = verts("body")
    280:     mid = face[np.abs(face[:, 0]) < 0.006]
    281:     chin = mid[np.argmin(mid[:, 1])]
    282:     eyeL, eyeR = iris[iris[:, 0] < 0].mean(0), iris[iris[:, 0] > 0].mean(0)
    283:     eye_y = (eyeL[1] + eyeR[1]) / 2
    284:     span = eye_y - chin[1]
    285:     mouth = verts("mouth").mean(0)
    286:     band = mid[(mid[:, 1] > mouth[1] + 0.005) & (mid[:, 1] < eyeL[1] - 0.01)]
    287:     nose = band[np.argmin(band[:, 2])]
    288: 
    289:     skin = np.concatenate([face, body[body[:, 1] > chin[1] - 0.02]])
    290: 
    291:     def window(pts, cond_y, cond_x=None):
    292:         for tol in (0.004, 0.008, 0.016):
    293:             ok = np.abs(pts[:, 1] - cond_y) < tol
    294:             if cond_x is not None:
    295:                 ok &= cond_x(pts, tol)
    296:             if ok.any():
    297:                 return pts[ok]
    298:         raise ValueError("no landmark near y=%.3f" % cond_y)
    299: 
    300:     def edge(y, side, pts=face):
  • read_file{"EndLine":250,"Path":"~/work/lowmarch/tools/duel.py","StartLine":1}

    input

    {
      "EndLine": 250,
      "Path": "~/work/lowmarch/tools/duel.py",
      "StartLine": 1
    }

    result, 141 lines

    Showing lines 1-140 of 140
    1: """Two characters locked in a sword bind (a struggle over crossed blades), authored on one shared
    2: stage so the blades really meet.
    3: 
    4: Stage space is the viewer's world: x to the right, y up, z toward the default camera. A character
    5: stands at `pos`, turned `yaw` degrees about y. Its GLB faces +z (the exporter's FLIP of VRoid's -z),
    6: so model point m lands at  pos + Ry(yaw) @ (FLIP * m).  The player stands on the right facing left,
    7: the opponent on the left facing right, both turned a little toward the camera (the study: battle
    8: sprites are drawn three-quarter, not in profile).
    9: 
    10: Each character's sword is rigid on its right hand (outfit.sword): the fist point and blade axis are
    11: taken from the hand in the reference pose. Arms reach with rig.grip so each blade runs through the
    12: shared crossing point; a two-handed fighter's left fist sits further down the grip.
    13: 
    14:   duel_clips({name: (vrm, shape, ref_pose, sword_info)}, cast) -> {name: [(t, pose)...]}, placements
    15: """
    16: import math
    17: 
    18: import numpy as np
    19: 
    20: import poses as P
    21: from rig import Rig
    22: 
    23: FLIP = np.array([-1.0, 1.0, -1.0])
    24: 
    25: 
    26: def ry(deg):
    27:     a = math.radians(deg)
    28:     return np.array([[math.cos(a), 0, math.sin(a)], [0, 1, 0], [-math.sin(a), 0, math.cos(a)]])
    29: 
    30: 
    31: def to_model(w, place):
    32:     return FLIP * (ry(-place["yaw"]) @ (np.asarray(w, float) - np.asarray(place["pos"], float)))
    33: 
    34: 
    35: def dir_to_model(d, place):
    36:     return FLIP * (ry(-place["yaw"]) @ np.asarray(d, float))
    37: 
    38: 
    39: # The bind, in stage space. Fists sit below and outside the crossing point; the blades rise
    40: # through it in an X above the fighters' heads.
    41: CROSS = np.array([0.0, 1.47, -0.02])
    42: SIDES = {
    43:     # name: stands on, turned, fist offset from the crossing point, hands, stance. `reach`, if given,
    44:     # places the fighter instead of `x`: where the fist sits from the chest across and forward (model
    45:     # space x, z: +x the fighter's right, -z forward). A two-handed grip close in and a little to the
    46:     # left keeps both arms bent and out of the body (checks.Body measured 2 cm clear; further out,
    47:     # the short left arm straightens across the chest)
    48:     "player": dict(x=0.66, yaw=-62.0, fist=(0.29, -0.25, -0.07), two_hands=False, step=(0.20, 0.22)),
    49:     "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
    50:                      reach=(-0.04, -0.29)),
    51: }
    52: # elbow directions tried for a gripping arm (model space, right arm; mirrored for the left): the
    53: # first that keeps the arm clear of the body wins, else the clearest
    54: 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)]
    55: CLEAR = 0.02
    56: # the struggle: the crossing point drifts toward whoever is giving ground; hips press in
    57: BEATS = [(0.0, 0.0), (0.8, 1.0), (1.6, -1.0), (2.4, 0.0)]      # (time, push: + player winning)
    58: 
    59: 
    60: def stance(rig, base, lead_step=0.20, back_step=0.22, spread=0.11, drop=0.07, lean=9.0, push=0.0):
    61:     """A fencing stance in model space: left foot forward, right foot back, knees bent, hips low,
    62:     torso leaning into the bind. push > 0 presses forward, < 0 gives ground."""
    63:     pose = P.merge(base, {
    64:         "J_Bip_C_Hips": P.move(0, -drop, -0.035 - 0.025 * push),
    65:         "J_Bip_C_Spine": P.rot((1, 0, 0), -lean * 0.5 - 2.5 * push),
    66:         "J_Bip_C_Chest": P.rot((1, 0, 0), -lean * 0.5 - 1.5 * push),
    67:         "J_Bip_C_Neck": P.rot((1, 0, 0), 6 + 2 * push),
    68:         "J_Bip_C_Head": P.rot((1, 0, 0), 4),
    69:     })
    70:     foot = {s: rig.pos(base, f"J_Bip_{s}_Foot") for s in "LR"}
    71:     lead = foot["L"] + np.array([-spread * 0.3, 0, -lead_step])
    72:     back = foot["R"] + np.array([spread * 0.3, 0, back_step])
    73:     pose = rig.leg_ik(pose, "L", lead, pole=(0, 0, -1))
    74:     return rig.leg_ik(pose, "R", back, pole=(0, -0.2, -1))
    75: 
    76: 
    77: def placements(order, chars=None):
    78:     """order: {"player": name, "opponent": name} -> {name: {pos, yaw}}. A side with `reach` stands
    79:     where its fist (chest + reach, in its stance) lands on its fist point in the bind; height
    80:     follows from the fist point."""
    81:     out = {}
    82:     for r in ("player", "opponent"):
    83:         sd, name = SIDES[r], order[r]
    84:         if "reach" not in sd:
    85:             out[name] = dict(pos=[sd["x"], 0.0, 0.0], yaw=sd["yaw"])
    86:             continue
    87:         c = chars[name]
    88:         rig = Rig(c["vrm"], c["shape"], ortho=True)
    89:         pose = stance(rig, P.BATTLE_IDLE, lead_step=sd["step"][0], back_step=sd["step"][1])
    90:         fist_m = rig.pos(pose, "J_Bip_C_UpperChest") + np.array([sd["reach"][0], 0.0, sd["reach"][1]])
    91:         pos = CROSS + np.array(sd["fist"]) - ry(sd["yaw"]) @ (FLIP * fist_m)
    92:         out[name] = dict(pos=[round(float(pos[0]), 4), 0.0, round(float(pos[2]), 4)], yaw=sd["yaw"])
    93:     return out
    94: 
    95: 
    96: def clear_grip(rig, body, pose, side, c, fist_m, blade_m, pole0):
    97:     """rig.grip, trying elbow directions until the arm clears the body (a checks.Body)."""
    98:     mirror = np.array([-1.0, 1.0, 1.0]) if side == "L" else np.ones(3)
    99:     limbs = [f"{side}_UpperArm", f"{side}_LowerArm", f"{side}_Hand"]
    100:     best = None
    101:     for pole in [pole0] + [tuple(np.array(q) * mirror) for q in POLES]:
    102:         p = rig.grip(pose, side, c["ref_pose"], c[f"fist_{side}"], fist_m, blade_m, pole=pole)
    103:         cl = body.worst(p, limbs)
    104:         if cl >= CLEAR:
    105:             return p
    106:         if best is None or cl > best[0]:
    107:             best = (cl, p)
    108:     return best[1]
    109: 
    110: 
    111: def duel_clips(chars, order):
    112:     """chars: {name: dict(vrm, shape, ref_pose, fist_R, fist_L)} (fists: reference-pose model points on
    113:     each hand). Returns {name: [(t, pose), ...]} for the 'clash' clip, and the placements."""
    114:     from checks import Body
    115:     place = placements(order, chars)
    116:     out = {}
    117:     for role in ("player", "opponent"):
    118:         name = order[role]
    119:         c, sd, pl = chars[name], SIDES[role], place[name]
    120:         rig = Rig(c["vrm"], c["shape"], ortho=True)
    121:         body = Body(c["vrm"], c["shape"]) if sd["two_hands"] else None
    122:         base = P.merge(P.BATTLE_IDLE, P.fist("L") if sd["two_hands"] else {})
    123:         keys = []
    124:         for t, push in BEATS:
    125:             mine = push if role == "player" else -push
    126:             cross = CROSS + np.array([-0.035 * push, -0.012 * abs(push), 0])
    127:             fist_w = cross + np.array(sd["fist"]) + np.array([-0.02 * push, 0, 0]) * (1 if role == "player" else 1)
    128:             blade_w = (cross - fist_w) / np.linalg.norm(cross - fist_w)
    129:             fist_m, blade_m = to_model(fist_w, pl), dir_to_model(blade_w, pl)
    130:             pose = stance(rig, base, lead_step=sd["step"][0], back_step=sd["step"][1], push=mine)
    131:             if sd["two_hands"]:                          # both arms in front of the body: keep them out of it
    132:                 pose = clear_grip(rig, body, pose, "R", c, fist_m, blade_m, (0.7, -1.0, 0.35))
    133:                 pose = clear_grip(rig, body, pose, "L", c, fist_m - blade_m * 0.095, blade_m, (-0.7, -1.0, 0.35))
    134:             else:                                        # free arm (shield) braced low and out for balance
    135:                 pose = rig.grip(pose, "R", c["ref_pose"], c["fist_R"], fist_m, blade_m, pole=(0.7, -1.0, 0.35))
    136:                 pose = rig.arm_ik(pose, "L", rig.pos(pose, "J_Bip_L_UpperArm") + np.array([-0.12, -0.38, 0.06]),
    137:                                   pole=(-0.3, -0.2, 1.0))
    138:             keys.append((t, pose))
    139:         out[name] = keys
    140:     return out, place
  • read_file{"EndLine":250,"Path":"~/work/lowmarch/review/vroid-02/duel_check.py","StartLine":1}

    input

    {
      "EndLine": 250,
      "Path": "~/work/lowmarch/review/vroid-02/duel_check.py",
      "StartLine": 1
    }

    result, 60 lines

    Showing lines 1-59 of 59
    1: """Numeric check of the sword bind: for each beat, where each fist and blade ended up in stage space,
    2: and how close the two blades come to each other and to the crossing point."""
    3: import os
    4: import sys
    5: 
    6: HERE = os.path.dirname(os.path.abspath(__file__))
    7: ROOT = os.path.dirname(os.path.dirname(HERE))
    8: sys.path[:0] = [os.path.join(ROOT, "tools"), os.path.join(ROOT, "art", "cast")]
    9: import numpy as np  # noqa: E402
    10: import poses as P  # noqa: E402
    11: import duel  # noqa: E402
    12: from rig import Rig  # noqa: E402
    13: from vrm import VRM  # noqa: E402
    14: from cast import CAST  # noqa: E402
    15: 
    16: VROID = os.environ.get("LOWMARCH_VROID", os.path.expanduser("~/.local/share/lowmarch/vroid"))
    17: 
    18: 
    19: def sword_ref(vrm, shape):
    20:     rig = Rig(vrm, shape)
    21:     out = {}
    22:     for side, sx in (("R", 1), ("L", -1)):
    23:         M = rig.world(P.BUST)[rig.names[f"J_Bip_{side}_Hand"]]
    24:         R = M[:3, :3] / np.linalg.norm(M[:3, :3], axis=0)
    25:         out[side] = M[:3, 3] + R @ np.array([sx * 0.045, -0.018, 0.0])
    26:     return out
    27: 
    28: 
    29: def chars_for(names):
    30:     out = {}
    31:     for n in names:
    32:         c = CAST[n]
    33:         v = VRM(os.path.join(VROID, c["model"]))
    34:         f = sword_ref(v, c["shape"])
    35:         out[n] = dict(vrm=v, shape=c["shape"], ref_pose=P.BUST, fist_R=f["R"], fist_L=f["L"])
    36:     return out
    37: 
    38: 
    39: if __name__ == "__main__":
    40:     order = {"player": "aldric", "opponent": "elaine"}
    41:     chars = chars_for(order.values())
    42:     clips, place = duel.duel_clips(chars, order)
    43:     for n, keys in clips.items():
    44:         rig = Rig(chars[n]["vrm"], chars[n]["shape"], ortho=True)
    45:         pl = place[n]
    46:         for t, pose in keys:
    47:             fist_m = rig.held(pose, "J_Bip_R_Hand", P.BUST, chars[n]["fist_R"])
    48:             M = rig.world(pose)[rig.names["J_Bip_R_Hand"]]
    49:             blade_m = M[:3, :3] @ np.array([0, 0, -1.0]); blade_m /= np.linalg.norm(blade_m)
    50:             to_w = lambda m: np.asarray(pl["pos"]) + duel.ry(pl["yaw"]) @ (duel.FLIP * m)
    51:             fist_w = to_w(fist_m); blade_w = duel.ry(pl["yaw"]) @ (duel.FLIP * blade_m)
    52:             c = duel.CROSS
    53:             d = np.linalg.norm(np.cross(c - fist_w, blade_w))
    54:             shoulder = to_w(rig.pos(pose, "J_Bip_R_UpperArm"))
    55:             head = to_w(rig.pos(pose, "J_Bip_C_Head"))
    56:             feet = [to_w(rig.pos(pose, f"J_Bip_{s}_Foot")) for s in "LR"]
    57:             print(f"{n:7s} t={t:.1f} fist {np.round(fist_w, 3)} blade {np.round(blade_w, 2)} "
    58:                   f"blade-to-cross {d * 1000:.0f} mm reach {np.linalg.norm(fist_w - shoulder):.3f} "
    59:                   f"head {np.round(head, 2)} feet y {feet[0][1]:.3f},{feet[1][1]:.3f}")
  • read_file{"EndLine":250,"Path":"~/work/lowmarch/review/vroid-02/battle_test.py","StartLine":1}

    input

    {
      "EndLine": 250,
      "Path": "~/work/lowmarch/review/vroid-02/battle_test.py",
      "StartLine": 1
    }

    result, 30 lines

    Showing lines 1-29 of 29
    1: """Quick look: Aldric in the full lord costume with a sword, standing on plains, battle view."""
    2: import os
    3: import sys
    4: 
    5: HERE = os.path.dirname(os.path.abspath(__file__))
    6: ROOT = os.path.dirname(os.path.dirname(HERE))
    7: sys.path[:0] = [os.path.join(ROOT, "tools"), os.path.join(ROOT, "art", "cast")]
    8: from PIL import Image  # noqa: E402
    9: import vroid_portrait as vp  # noqa: E402
    10: import terrain  # noqa: E402
    11: from cast import CAST  # noqa: E402
    12: 
    13: VROID = os.environ.get("LOWMARCH_VROID", os.path.expanduser("~/.local/share/lowmarch/vroid"))
    14: OUT = os.path.join(ROOT, "review", "out", "vroid-02")
    15: yaws = [int(v) for v in (sys.argv[1] if len(sys.argv) > 1 else "60").split(",")]
    16: c = CAST["aldric"]
    17: p = vp.Portrait(os.path.join(VROID, c["model"]), shape=c["shape"], hair_from=os.path.join(VROID, c["hair"]),
    18:                 costume="lord_full", pose=vp.BATTLE_IDLE, world=terrain.plains())
    19: tiles = []
    20: for y in yaws:
    21:     px = vp.image(p.render(y, view="battle"), palette=c["colors"])
    22:     sm = vp.smooth_view(p, y, palette=c["colors"], view="battle")
    23:     bg = Image.new("RGBA", px.size, (16, 14, 24, 255)); bg.alpha_composite(px)
    24:     px.save(f"{OUT}/battle_{y}.png"); sm.save(f"{OUT}/battle3d_{y}.png")
    25:     tiles.append((bg.resize((480, 320), Image.NEAREST), sm.resize((480, 320))))
    26: sheet = Image.new("RGB", (len(tiles) * 486 + 6, 2 * 326 + 6), (16, 14, 24))
    27: for i, (a, b) in enumerate(tiles):
    28:     sheet.paste(a, (6 + i * 486, 6)); sheet.paste(b, (6 + i * 486, 332))
    29: sheet.save(f"{OUT}/battle_sheet.png")