agent (cont.)

+2:56
  • read_file{"Path":"~/work/lowmarch/tools/saber_study.py"}

    input

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

    result, 542 lines

    Showing lines 1-541 of 541
    1: """Benchmark only, NOT FOR THE GAME: Saber (Fate/stay night) in her armoured dress, built with the
    2: outline-plate kit (tools/plates.py) to measure how close it can get to a well-known design. Saber is
    3: Type-Moon's; the game's characters are original designs at this level of detail.
    4: 
    5: Built from a written study of the official art (model sheets front, back and three-quarter, and a
    6: figure for the hidden sides), never from the images themselves. Sizes are fractions of her height H
    7: (skull to sole) or of her head height hd, read off the study and placed on Elaine's base body, whose
    8: landmarks agree with the study's to a few percent (chin 0.14 H, waist 0.30-0.32 H, ankle 0.94 H).
    9: """
    10: import math
    11: 
    12: import numpy as np
    13: 
    14: import outfit as O
    15: from fitting import Surface, merge_surfaces
    16: from plates import TorsoChart, LimbChart, ConeChart, outline_plate, stiffen, flat_piece, taper
    17: 
    18: 
    19: def _grouped(pcs, g):
    20:     for pc in pcs:
    21:         if pc is not None:
    22:             pc["group"] = g
    23:     return [pc for pc in pcs if pc is not None]
    24: 
    25: 
    26: # ---- decal shapes, in a chart's (u, v) with sizes in metres --------------------------------------
    27: def _to_uv(chart, u0, v0, pts):
    28:     """Metric offsets (across, up) from (u0, v0) on a torso-type chart -> (u, v) points."""
    29:     r = float(chart.radius(u0, v0))
    30:     return [(u0 + math.degrees(dx / r), v0 + dy) for dx, dy in pts]
    31: 
    32: 
    33: def leaf(chart, u0, v0, ang, length, width, ch="paint"):
    34:     """A tapering blade from (u0, v0) at `ang` degrees from straight up (+ toward +u)."""
    35:     a = math.radians(ang)
    36:     al, ac = np.array([math.sin(a), math.cos(a)]), np.array([math.cos(a), -math.sin(a)])
    37:     t = np.linspace(0, 1, 14)
    38:     w = width / 2 * np.sqrt(t + 0.08) * (1 - t) ** 0.85 * 1.6
    39:     left = [tuple(al * length * ti + ac * wi) for ti, wi in zip(t, w)]
    40:     right = [tuple(al * length * ti - ac * wi) for ti, wi in zip(t[::-1], w[::-1])]
    41:     return ("poly", _to_uv(chart, u0, v0, left + right), ch)
    42: 
    43: 
    44: def curl(chart, u0, v0, radius, turns=1.25, width=0.0022, flip=1, ch="paint"):
    45:     """A spiral stroke (the swirl glyphs), unwinding from its centre."""
    46:     th = np.linspace(0, turns * 2 * math.pi, 40)
    47:     rr = radius * (0.25 + 0.75 * th / th[-1])
    48:     pts = [(flip * r * math.cos(x), r * math.sin(x)) for r, x in zip(rr, th)]
    49:     return ("line", _to_uv(chart, u0, v0, pts), width, ch)
    50: 
    51: 
    52: def stroke(chart, u0, v0, pts, width=0.0022, ch="paint"):
    53:     return ("line", _to_uv(chart, u0, v0, pts), width, ch)
    54: 
    55: 
    56: def build(fit):
    57:     B = fit.bone
    58:     P = fit.pos[np.unique(fit.tri)]
    59:     top, sole = float(P[:, 1].max()), float(P[:, 1].min())
    60:     H = top - sole
    61:     hd = H / 7.06                                       # this base's head height (measured)
    62:     y = lambda f: top - f * H                           # a height given as a fraction of H from the skull
    63:     nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"]
    64:     cz = float(hips[2])
    65:     knee = B["J_Bip_L_LowerLeg"][1]
    66:     out = []
    67: 
    68:     def cuff_plane(side):                               # sleeves end inside the gauntlet
    69:         a, hd_ = B[f"J_Bip_{side}_LowerArm"], B[f"J_Bip_{side}_Hand"]
    70:         n = (hd_ - a) / np.linalg.norm(hd_ - a)
    71:         return n, n @ (a + (hd_ - a) * 0.7)
    72: 
    73:     # ---- under layers: dress bodice and sleeves, dark tights, leg shells, black gloves ----------
    74:     torso = ("Spine", "Chest", "UpperChest", "Bust", "Shoulder", "UpperArm", "LowerArm", "Neck", "Hips")
    75:     bodice = O.wrap(fit, "bodice", "signature", torso, offset=0.006, exclude=("UpperLeg",),
    76:                     y_min=hips[1] + 0.02, y_max=nk[1] + 0.012, hems=[cuff_plane("L"), cuff_plane("R")])
    77:     tights = O.wrap(fit, "tights", "doublet", ("Hips", "UpperLeg", "LowerLeg"), offset=0.004, y_max=hips[1] + 0.03, subdiv=1)
    78:     boots = O.wrap(fit, "boots", "metal", ("LowerLeg", "Foot"), offset=0.012, y_max=knee - 0.10, exclude=("ToeBase",),
    79:                    subdiv=1, hems=[((0, 1, 0), knee - 0.105)])
    80:     gloves = O.wrap(fit, "gloves", "glove", ("Hand", "Thumb", "Index", "Middle", "Ring", "Little"),
    81:                     offset=0.0035, min_w=0.3, smooth=4)
    82:     out += _grouped([bodice], "dress") + _grouped([tights], "trousers") + _grouped([boots], "boots") + _grouped([gloves], "gloves")
    83:     torso_only = O.without(bodice, ("Shoulder", "UpperArm", "LowerArm", "Hand"))
    84:     chest = Surface(*torso_only)
    85: 
    86:     # ---- collar: a close stand collar, gold band along its top, gold line down the front ----------
    87:     col, rim, fronts = O.collar(fit, "collar", "signature", height_back=0.040, height_front=0.034, gap_deg=6,
    88:                                 clear=(0.008, 0.012))
    89:     band = rim - np.array([0, 0.0042, 0])
    90:     out += _grouped([col, O.inherit(O.ribbon("collar_band", "gold", band, width=0.0075, lift=0.0012,
    91:                                              normals=O.near_normals(col, band)), col)], "dress")
    92:     for k, edge in enumerate(fronts):
    93:         out += _grouped([O.inherit(O.ribbon(f"collar_front{k}", "gold", edge, width=0.0035, lift=0.0012,
    94:                                             normals=O.near_normals(col, edge)), col)], "dress")
    95: 
    96:     # ---- the chest chart (the bodice without its sleeves) --------------------------------------
    97:     tc = TorsoChart(chest, y(0.36), y(0.14), cz=cz, du=2.0, dv=0.006, smooth=(1.6, 1.4))
    98: 
    99:     # back: two short gold strips from the collar base, down and outward (a Lambda)
    100:     for s in (-1, 1):
    101:         pts = tc.point(np.array([180 + s * 6, 180 + s * 26]), np.array([y(0.165), y(0.215)]), off=0.002)
    102:         out += _grouped(_bind_strip(fit, pts, s, tc, y), "dress")
    103: 
    104:     # ---- cuirass: domed panels between grooves, studs at the junctions, painted blue motifs -------
    105:     yb, yv, ybust = y(0.303), y(0.280), y(0.246)
    106: 
    107:     def front_top(u):
    108:         a = abs(u)
    109:         if a <= 34:
    110:             return y(0.197)
    111:         if a <= 80:
    112:             return y(0.197) + (y(0.226) - y(0.197)) * ((a - 34) / 46) ** 1.3
    113:         return y(0.226) + (y(0.236) - y(0.226)) * min(1.0, (a - 80) / 18)
    114: 
    115:     seams, studs = [], []
    116:     for s in (-1, 1):
    117:         seams += [[(s * 34, y(0.199)), (s * 60, ybust), (s * 38, y(0.262)), (s * 14, y(0.274)), (0, yv)],
    118:                   [(s * 60, ybust), (s * 99, ybust)],
    119:                   [(s * 31, y(0.267)), (s * 52, y(0.288)), (s * 60, yb - 0.004)]]
    120:         studs += [(s * 60, ybust), (s * 31, y(0.267)), (s * 60, yb + 0.012)]
    121:     seams.append([(0, yv), (0, yb - 0.004)])
    122:     motif = []
    123:     # bust panel: a curl glyph with a dot, a stem down to the V, a fan of six blades rising from it
    124:     motif += [curl(tc, 0, y(0.213), 0.0075, turns=1.1), ("dot", (0, y(0.205)), 0.0023, "paint"),
    125:               stroke(tc, 0, y(0.219), [(0, 0), (0, -(y(0.219) - y(0.276)))], width=0.0016)]
    126:     for s in (-1, 1):
    127:         for ang, L in ((20, 0.056), (40, 0.072), (60, 0.086)):
    128:             motif.append(leaf(tc, 0, y(0.277), s * ang, L, 0.016))
    129:         for ang, L in ((22, 0.034), (46, 0.040), (70, 0.036)):   # the abdomen panels: small fans up and out
    130:             motif.append(leaf(tc, s * 14, y(0.301), s * ang, L, 0.010))
    131:     front, fx = outline_plate("cuirass", "steel", tc, -99, 99, lambda u: yb, front_top, offset=0.011, crown=0.004,
    132:                               thickness=0.003, nu=110, nv=44, roll=0.0022, roll_edges=("top",), roll_role="steel",
    133:                               seams=seams, groove=(0.0060, 0.0022), panel_crown=0.0035, studs=studs, stud_r=0.0038,
    134:                               decal=motif, decal_px=1600)
    135:     back_top = lambda u: y(0.190) + (y(0.236) - y(0.190)) * (abs(((u % 360) - 180)) / 82) ** 1.6
    136:     bseams = [[(129, ybust), (180, y(0.262)), (231, ybust)], [(99, y(0.283)), (261, y(0.283))]]
    137:     back, bx = outline_plate("backplate", "steel", tc, 99, 261, lambda u: yb, back_top, offset=0.011, crown=0.004,
    138:                              thickness=0.003, nu=80, nv=36, roll=0.0022, roll_edges=("top",), roll_role="steel",
    139:                              seams=bseams, groove=(0.0035, 0.0018), panel_crown=0.003,
    140:                              studs=[(129, ybust), (231, ybust)], stud_r=0.0038, decal_px=1200)
    141:     # the gorget: a separate plate over the collar's foot, stepping out from the chest
    142:     gmotif = [curl(tc, -2.0, y(0.178), 0.0060, turns=1.0), curl(tc, 2.0, y(0.181), 0.0060, turns=1.0, flip=-1)]
    143:     for s in (-1, 1):
    144:         gmotif += [leaf(tc, s * 9, y(0.188), s * 50, 0.028, 0.0062), leaf(tc, s * 13, y(0.192), s * 68, 0.030, 0.0062)]
    145:     gorget, gx = outline_plate("gorget", "steel", tc, -38, 38,
    146:                                lambda u: y(0.201) - 0.007 * (1 - (u / 38) ** 2),
    147:                                lambda u: y(0.170) - 0.008 * max(0.0, (abs(u) - 28) / 10) ** 2,
    148:                                offset=0.023, crown=0.003, thickness=0.003, nu=48, nv=18, roll=0.0022,
    149:                                roll_edges=("top", "bottom"), roll_role="steel",
    150:                                studs=[(-33, y(0.197)), (33, y(0.197))], stud_r=0.0036, decal=gmotif, decal_px=1800)
    151:     for pc in (front, back, gorget):
    152:         fit.bind(pc, allow=("Spine", "Chest", "UpperChest", "Bust"), fallback="J_Bip_C_Chest")
    153:     for pc in fx:
    154:         O.inherit(pc, front)
    155:     for pc in bx:
    156:         O.inherit(pc, back)
    157:     for pc in gx:
    158:         O.inherit(pc, gorget)
    159:     gorget["W"][:] = 0
    160:     gorget["J"][:, 0] = fit.jnames.index("J_Bip_C_UpperChest")
    161:     gorget["W"][:, 0] = 1.0
    162:     for pc in gx:
    163:         O.inherit(pc, gorget)
    164:     out += _grouped([front, back, gorget] + fx + bx + gx, "plate")
    165: 
    166:     # ---- belt: near-black leather at the natural waist, laced at the front -----------------------
    167:     belt, bfront = O.belt(fit, "belt", "leather", chest, y(0.311), height=0.034, offset=0.004, thickness=0.005)
    168:     out += _grouped([belt], "belt")
    169:     lace = []
    170:     ex, ey_ = np.array([1.0, 0, 0]), np.array([0, 1.0, 0])
    171:     c0 = bfront + np.array([0, 0, -0.006])
    172:     eye = {(sx, k): c0 + ex * sx * 0.011 + ey_ * (0.011 - 0.016 * k) for sx in (-1, 1) for k in range(3)}
    173:     for k in range(2):
    174:         for sx in (-1, 1):
    175:             a, b = eye[(sx, k)], eye[(-sx, k + 1)]
    176:             lace.append(O.pipe(f"lace{k}{(sx + 1) // 2}", "glove", np.linspace(a, b, 6) + np.array([0, 0, -0.002 * (k + 1)]),
    177:                                r=0.0017, seg=6))
    178:     for (sx, k), p in eye.items():
    179:         lace.append(O.ball(f"eyelet{k}{(sx + 1) // 2}", "steel", p, 0.0028, seg=8, rows=5, squash=(1, 1, 0.5)))
    180:     for pc in lace:
    181:         fit.bind(pc, rigid="J_Bip_C_Hips")
    182:     out += _grouped(lace, "belt")
    183: 
    184:     # ---- skirts: the white petticoat (cloth), the open blue overskirt, the violet front panel ------
    185:     y_top, y_hem = y(0.322), y(0.790)
    186:     r_hem = 0.24 * H
    187:     r0 = lambda u: tc.radius(u, y(0.322)) + 0.014
    188:     r0_mean = float(np.mean([r0(u) for u in range(-180, 180, 10)]))
    189: 
    190:     def r_base(u, v):                                   # the overskirt's cone before it clears the petticoat
    191:         t = np.clip((y_top - v) / (y_top - y_hem), 0, 1.15)
    192:         return r0(u) + (r_hem - r0_mean) * t ** 1.45
    193: 
    194:     # petticoat: full circle, to mid-calf, the hem cut into sawtooth teeth with a gold lozenge on each
    195:     legs = merge_surfaces((tights["pos"], tights["tri"]), (boots["pos"], boots["tri"]))
    196:     waist = merge_surfaces(torso_only, (tights["pos"], tights["tri"]))
    197:     pt_top = y(0.335)
    198:     seg, rows, teeth = 96, 24, 48
    199:     # not simulated: the viewer's cloth pushes a skirt out of the legs by a few centimetres, which took
    200:     # it through the stiff overskirt; skinned like the overskirt instead, the two move together
    201:     pet, grid = O.skirt(fit, "petticoat", "heraldry", waist, legs, pt_top, pt_top - y(0.858), flare=r_hem - 0.165,
    202:                         seg=seg, rows=rows, folds=8, fold_depth=0.006)
    203:     # the upper part is always hidden under the overskirt and tassets, and the settle crumples it over
    204:     # the hips (a fold whose surface faces inward): rebuild it as a smooth ring between the body and the
    205:     # overskirt's base cone, blending into the settled cloth below
    206:     body_c = TorsoChart(waist, y(0.56), y(0.32), cz=cz, du=3.0, dv=0.01, smooth=(1.2, 1.2))
    207:     Pp = pet["pos"].reshape(seg, rows, 3)
    208:     hz = np.stack([Pp[..., 0], Pp[..., 2] - cz], -1)             # horizontal offset from the axis
    209:     rr = np.linalg.norm(hz, axis=-1)
    210:     d0 = hz / np.maximum(rr[..., None], 1e-9)
    211:     dcol = np.repeat(d0[:, :1], rows, 1)                        # each column's own direction, from its
    212:     a_ = np.clip((Pp[..., 1] - y(0.52)) / (y(0.46) - y(0.52)), 0, 1)   # top point (columns that crossed
    213:     dn = d0 * (1 - a_[..., None]) + dcol * a_[..., None]               # over each other made the fold)
    214:     dn /= np.maximum(np.linalg.norm(dn, axis=-1, keepdims=True), 1e-9)
    215:     up = np.degrees(np.arctan2(dn[..., 0], -dn[..., 1]))
    216:     ring = np.maximum(body_c.radius(up, Pp[..., 1]) + 0.006, r_base(up, Pp[..., 1]) - 0.010)
    217:     r_new = rr + (ring - rr) * a_
    218:     Pp[..., 0] = dn[..., 0] * r_new
    219:     Pp[..., 2] = cz + dn[..., 1] * r_new
    220:     pet["pos"] = Pp.reshape(-1, 3)
    221:     G = pet["pos"].reshape(seg, rows, 3)
    222:     # the settle swings a flared skirt down, so it hangs longer than asked: scale it back to end at mid-calf
    223:     y0_, y1_ = G[:, 0, 1].mean(), G[0::2, -1, 1].mean()
    224:     G[..., 1] = y0_ - (y0_ - G[..., 1]) * (y0_ - y(0.858)) / (y0_ - y1_)
    225:     G[1::2, -1] = G[1::2, -2] + (G[1::2, -1] - G[1::2, -2]) * 0.05    # every other column ends a row early: teeth
    226:     pet["pos"] = G.reshape(-1, 3)
    227:     pet["nrm"] = O.vertex_normals(pet["pos"], pet["tri"])
    228:     # decal: the hem's lozenges, in (s, t) = (round the skirt, folded at the back so the seam repeats
    229:     # nothing; up the skirt, the lowest fifth only)
    230:     from plates import Canvas
    231:     cv = Canvas(512, 256)
    232:     for i in range(0, seg // 2 + 1, 2):
    233:         s_ = 1 - abs(2 * i / seg - 1)
    234:         cv.dot((s_, 0.5 / 0.2 / (rows - 1)), 2.0, 26, "gold")
    235:     pet["decal"] = cv.array()
    236:     ii, jj = np.meshgrid(np.arange(seg), np.arange(rows), indexing="ij")
    237:     s_uv = 1 - np.abs(2 * ii / seg - 1)
    238:     t_uv = np.clip((1 - jj / (rows - 1)) / 0.2, 0, 1)
    239:     t_uv[1::2, -1] = np.clip((1 - (rows - 2 + 0.05) / (rows - 1)) / 0.2, 0, 1)
    240:     pet["uv"] = np.stack([s_uv, t_uv], -1).reshape(-1, 2)
    241:     stiffen(pet, fit, share=0.65)
    242:     pet.pop("closed", None)
    243:     pet["covered_by"] = ["overskirt", "front_panel"]      # for the layer check: it must never show through them
    244:     out += _grouped([pet], "dress")
    245:     # the overskirt's cone, kept a centimetre outside the petticoat everywhere: the petticoat settles
    246:     # against the body, which bulges out behind the hips past a plain cone (it showed through there)
    247:     under = TorsoChart(Surface(pet["pos"], pet["tri"]), y(0.80), y(0.335), cz=cz, du=3.0, dv=0.01, smooth=(1.2, 1.2))
    248: 
    249:     def r_over(u, v):
    250:         base = r_base(u, v)
    251:         # outside the petticoat by 1.6 cm over the hips and below; at the waist the band hugs the body
    252:         w = np.clip((y(0.335) - v) / (y(0.335) - y(0.380)), 0, 1)
    253:         return base + np.maximum(0, under.radius(u, v) + 0.016 - base) * w
    254: 
    255:     cone = ConeChart(r_over, cz=cz)
    256: 
    257:     # overskirt: a stiff cone, open at the front, a gold-edged slit at the back
    258:     slit_h, slit_w = 0.34 * (y_top - y_hem), math.degrees(0.2 * hd / r_hem)
    259: 
    260:     def over_bottom(u):
    261:         return y_hem + slit_h * max(0.0, 1 - abs(u - 180) / slit_w)
    262: 
    263:     over, _ = outline_plate("overskirt", "signature", cone, 27, 333, over_bottom, lambda u: y_top + 0.012, offset=0.0,
    264:                             thickness=0.004, nu=150, nv=26, trim=0.035 * hd, roll=0)
    265:     # layers over the petticoat take its weights (nearest vertex): weights copied from the body
    266:     # differ between a layer close to the thighs and one further out, and the layers then cross
    267:     O.inherit(over, pet)
    268:     out += _grouped([over], "dress")
    269: 
    270:     # front panel: a violet apron from the belt, filling the overskirt's opening, scooped corners
    271:     # ending in points with silver pendants, gold edges, two crescent hooks and a small triangle
    272:     y_ph, y_tip = y(0.745), y(0.690)
    273:     panel_r = lambda u, v: r_over(u, v) - 0.0025
    274: 
    275:     def p_top(u):
    276:         a = abs(u)
    277:         if a <= 24:
    278:             return y_top + 0.010
    279:         return y(0.625) - (y(0.625) - y_tip) * ((a - 24) / 8) ** 0.55
    280: 
    281:     def p_bottom(u):
    282:         a = abs(u)
    283:         return y_ph if a <= 26 else y_ph + (y_tip - y_ph) * (a - 26) / 6
    284: 
    285:     pcone = ConeChart(panel_r, cz=cz)
    286:     deco = []
    287:     for s in (-1, 1):
    288:         cx_, cy_ = s * 15.5, y_ph + 0.024
    289:         th = np.linspace(math.radians(200), math.radians(-20), 16)
    290:         arc = [(s * 0.016 * math.cos(t_), 0.010 * math.sin(t_) + 0.002) for t_ in th]
    291:         deco.append(stroke(pcone, cx_, cy_, arc, width=0.0042, ch="gold"))
    292:     deco.append(("poly", _to_uv(pcone, 0, y_ph, [(-0.012, 0.0), (0.012, 0.0), (0.0, 0.020)]), "gold"))
    293:     panel, _ = outline_plate("front_panel", "violet", pcone, -32, 32, p_bottom, p_top, offset=0.0, thickness=0.003,
    294:                              nu=130, nv=30, trim=0.0055, roll=0, decal=deco, decal_px=900)
    295:     O.inherit(panel, pet)                                # moves with the petticoat under it
    296:     out += _grouped([panel], "dress")
    297:     pend = []
    298:     for k, (u_, v_) in enumerate([(-32, y_tip), (32, y_tip), (-26, y_ph), (26, y_ph)]):
    299:         p0 = pcone.point(u_, v_, off=0.003)
    300:         pend.append(O.ball(f"pendant_bead{k}", "steel", p0 - np.array([0, 0.004, 0]), 0.0055, seg=10, rows=6))
    301:         drop = O.ball(f"pendant{k}", "steel", p0 - np.array([0, 0.036, 0]), 0.0085, seg=12, rows=10, squash=(1, 3.6, 1))
    302:         D = drop["pos"]
    303:         tt = np.clip((D[:, 1] - D[:, 1].min()) / np.ptp(D[:, 1]), 0, 1)       # a teardrop: thin at the top
    304:         c_ = D.mean(0)
    305:         D[:, [0, 2]] = c_[[0, 2]] + (D[:, [0, 2]] - c_[[0, 2]]) * (1 - 0.75 * tt ** 1.5)[:, None]
    306:         drop["nrm"] = O.vertex_normals(D, drop["tri"])
    307:         pend.append(drop)
    308:     for pc in pend:
    309:         O.inherit(pc, panel)
    310:     out += _grouped(pend, "dress")
    311: 
    312:     # ---- tassets: three faceted plates over each hip, shingled, notched at the inner corners -------
    313:     tas_r = lambda u, v: r_over(u, v) + 0.010
    314:     tcone = ConeChart(tas_r, cz=cz)
    315:     notch = 0.1 * hd
    316:     for side, s in (("R", 1), ("L", -1)):
    317:         for k, (vt, vb, uf, ub) in enumerate([(y(0.316), y(0.420), 21, 157), (y(0.408), y(0.520), 24, 154),
    318:                                               (y(0.508), y(0.660), 28, 150)]):
    319:             nd = math.degrees(notch / float(tas_r(90, vb)))
    320: 
    321:             def bot(u, vb=vb, uf=uf, ub=ub, nd=nd):
    322:                 a = abs(u)
    323:                 return vb + notch if (a - uf < nd or ub - a < nd) else vb
    324:             u0, u1 = (uf, ub) if s > 0 else (-ub, -uf)
    325:             fac = [u0, s * 72, s * 114, u1] if s > 0 else [u0, s * 114, s * 72, u1]
    326:             st_ = [(s * (uf + 2.5), vt - 0.016), (s * (uf + 6.5), vt - 0.016)] if k == 0 else []
    327:             st_ += [(s * (uf + nd + 2.5), vb + notch + 0.012), (s * (ub - nd - 2.5), vb + notch + 0.012)]
    328:             pl, px_ = outline_plate(f"tasset_{side}{k}", "steel", tcone, u0, u1, bot, lambda u, vt=vt: vt, offset=0.004,
    329:                                     thickness=0.004, nu=64, nv=16, roll=0, facets=fac,
    330:                                     flare=lambda u, v, s_, t: 0.010 * (1 - t) ** 1.3, studs=st_, stud_r=0.0032)
    331:             fit.bind(pl, blend={"J_Bip_C_Hips": 0.7 - 0.15 * k, f"J_Bip_{side}_UpperLeg": 0.3 + 0.15 * k})
    332:             for pc in px_:
    333:                 O.inherit(pc, pl)
    334:             out += _grouped([pl] + px_, "plate")
    335: 
    336:     # ---- puffed sleeves: boxy, peaked at the outer top, gathered at the armpit; gold piping ---------
    337:     for side, s in (("R", 1), ("L", -1)):
    338:         out += _grouped(_puff(fit, side, s, hd), "dress")
    339: 
    340:     # ---- gauntlets: four stacked bands, ribbed, riveted on the inner edge; a knuckle plate ---------
    341:     for side, s in (("R", 1), ("L", -1)):
    342:         la, hd_ = B[f"J_Bip_{side}_LowerArm"], B[f"J_Bip_{side}_Hand"]
    343:         fore = O.limb_surface(fit, (f"{side}_LowerArm", f"{side}_Hand"), side)
    344:         lc = LimbChart(fore, la, hd_, front=(0, 0, -1), v_range=(-0.2, 1.5))
    345:         outside = 90.0 * s
    346:         inside = -outside                                # the inner forearm, in -180..180
    347:         bands = [(0.36, 0.57), (0.55, 0.76), (0.74, 0.95), (0.93, 1.20)]
    348:         for k, (v0, v1) in enumerate(bands):
    349:             off = 0.026 + 0.0035 * k
    350:             fl = (lambda u, v, s_, t: 0.006 * t ** 1.5) if k == 0 else None
    351:             band, bxs = outline_plate(f"gauntlet_{side}{k}", "steel", lc, -180, 180, lambda u, v1=v1: v1,
    352:                                       lambda u, v0=v0: v0, offset=off, flare=fl, thickness=0.0035, nu=64, nv=10,
    353:                                       roll=0.0024, roll_edges=("top",), roll_role="steel",
    354:                                       studs=[(inside, v0 + (v1 - v0) * 0.55)], stud_r=0.0032)
    355:             ribs = []
    356:             for j, du in enumerate((-15, 15)):
    357:                 vv = np.linspace(v0 + (v1 - v0) * 0.2, v0 + (v1 - v0) * 0.8, 8)
    358:                 pts = lc.point(np.full(8, outside + du), vv, off=off + 0.0025)
    359:                 ribs.append(O.pipe(f"gauntlet_{side}{k}_rib{j}", "steel", pts, r=0.0034, seg=8))
    360:             for pc in [band] + bxs + ribs:
    361:                 fit.bind(pc, rigid=f"J_Bip_{side}_LowerArm")
    362:             out += _grouped([band] + bxs + ribs, "plate")
    363:         hand = O.limb_surface(fit, (f"{side}_Hand", f"{side}_Index", f"{side}_Middle", f"{side}_Ring", f"{side}_Little"), side)
    364:         hc = LimbChart(hand, hd_, B[f"J_Bip_{side}_Middle1"], front=(0, 0, -1), v_range=(-0.3, 1.4))
    365:         kn, _ = outline_plate(f"knuckles_{side}", "steel", hc, outside - 60, outside + 60, lambda u: 0.55,
    366:                               lambda u: 1.12, offset=0.006, crown=0.003, thickness=0.003, nu=24, nv=10, roll=0)
    367:         fit.bind(kn, rigid=f"J_Bip_{side}_Hand")
    368:         out += _grouped([kn], "plate")
    369: 
    370:     # ---- legs: smooth greaves seamed at the back, a raised ankle ring with bosses, sabatons ---------
    371:     for side, s in (("R", 1), ("L", -1)):
    372:         ll, ft = B[f"J_Bip_{side}_LowerLeg"], B[f"J_Bip_{side}_Foot"]
    373:         shin = O.side_of(boots, side)
    374:         gc = LimbChart(shin, ll, ft, front=(0, 0, -1), v_range=(-0.1, 1.15))
    375:         gv, _ = outline_plate(f"greave_{side}", "steel", gc, -180, 180, lambda u: 0.93, lambda u: 0.32, offset=0.004,
    376:                               thickness=0.003, nu=64, nv=22, roll=0.0022, roll_edges=("top",), roll_role="steel",
    377:                               seams=[[(180, 0.33), (180, 0.92)]], groove=(0.003, 0.0012))
    378:         ring, _ = outline_plate(f"ankle_{side}", "steel", gc, -180, 180, lambda u: 1.0, lambda u: 0.925, offset=0.011,
    379:                                 thickness=0.004, nu=64, nv=6, roll=0.0026, roll_edges=("top", "bottom"), roll_role="steel")
    380:         bosses = []
    381:         for j, u_ in enumerate((90.0, -90.0)):
    382:             c_ = gc.point(u_, 0.962, off=0.013)
    383:             n_ = gc.normal(u_, 0.962)
    384:             bs, _ = O.dome(f"ankle_boss_{side}{j}", "steel", c_, n_, (0, 1, 0), 0.0115, 0.007, rows=6)
    385:             bosses.append(bs)
    386:         for pc in [gv, ring] + bosses:
    387:             fit.bind(pc, rigid=f"J_Bip_{side}_LowerLeg")
    388:         out += _grouped([gv, ring] + bosses, "boots")
    389:         sab = O.sabaton(fit, f"sabaton_{side}", side, ridges=0)
    390:         shoe = sab[0]
    391:         Gs = shoe["pos"].reshape(26, 14, 3)
    392:         Ns = shoe["nrm"].reshape(26, 14, 3)
    393:         extra = []
    394:         for k, base in enumerate((0.46, 0.60)):         # instep plates: front edges in Vs pointing to the toe
    395:             phi = np.linspace(0, np.pi, 14)[1:-1]
    396:             stn = (base + 0.10 * np.sin(phi)) * 25
    397:             i0 = np.clip(np.floor(stn).astype(int), 0, 24)
    398:             fr = stn - i0
    399:             rows_ = np.arange(1, 13)

    142 more lines not shown.

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

    input

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

    result, 251 lines

    Showing lines 1-250 of 1272
    1: """Fantasy costume pieces, generated in code and fitted onto a VRoid body.
    2: 
    3: Coordinates are the model's (metres, y up, the character faces -z, its left is -x). Pieces are
    4: built once in the reference pose (the bust pose, arms down) and carry skin weights (J, W, jnames)
    5: so the renderer can pose them with the body through the skeleton: soft layers copy the weights of
    6: the body under them, hard parts ride one bone.
    7: 
    8: Kinds of piece (see docs/portrait-guide.md lesson 07 for the measurements behind the offsets):
    9: 
    10:   wrap      a garment shrink-wrapped onto a body region chosen by bones (tunic, trousers, boots,
    11:             gloves): seams welded, smoothed without shrinking, every vertex set at an offset
    12:   collar    a standing collar fitted to the neck by ray casts, rising toward the back
    13:   pauldron  three overlapping lames whose shape comes from ray casts to what they cover
    14:   drape     cloth (cape, tunic tails) settled by a small cloth simulation against the body
    15:   belt      a band around the waist on top of the tunic
    16:   trim      a band along a piece's edge (gold trim, piping), lifted off its surface
    17:   props     sword and hardware built from boxes, tubes and balls
    18: 
    19: A costume is a function of a Fit (body + bones in the reference pose) returning a list of pieces.
    20: """
    21: import math
    22: import os
    23: 
    24: import numpy as np
    25: from scipy.spatial import cKDTree
    26: 
    27: from fitting import (Surface, merge_surfaces, weld, compact, subdivide, shrink_wrap, flatten_hem, limb_hull,
    28:                      boundary_loops, vertex_normals, transfer_weights, rigid_weights, blend_weights, taubin)
    29: 
    30: 
    31: # ---- mesh helpers --------------------------------------------------------------
    32: def grid_mesh(P):
    33:     """P: (U, V, 3) grid of points -> (pos, tri)."""
    34:     U, V = P.shape[:2]
    35:     idx = np.arange(U * V).reshape(U, V)
    36:     a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]
    37:     tri = np.concatenate([np.stack([a, b, c], -1).reshape(-1, 3), np.stack([a, c, d], -1).reshape(-1, 3)])
    38:     return P.reshape(-1, 3), tri
    39: 
    40: 
    41: def piece(name, role, pos, tri, nrm=None, outward_from=None, axis=None):
    42:     """outward_from: a point (or, with axis, a line) the normals should face away from, so the
    43:     renderer knows which side is the outside of a one-sided sheet."""
    44:     pos = np.asarray(pos, float)
    45:     tri = np.asarray(tri)
    46:     nrm = vertex_normals(pos, tri) if nrm is None else nrm
    47:     if outward_from is not None:
    48:         d = pos - np.asarray(outward_from, float)
    49:         if axis is not None:
    50:             a = np.asarray(axis, float) / np.linalg.norm(axis)
    51:             d -= np.outer(d @ a, a)
    52:         if (np.einsum("ij,ij->i", nrm, d) < 0).mean() > 0.5:
    53:             nrm = -nrm
    54:             tri = tri[:, ::-1]
    55:     return dict(mesh="outfit", material=f"OUTFIT_{name}", mi=-1, role=role, pos=pos,
    56:                 nrm=nrm, uv=np.zeros((len(pos), 2)), tri=tri)
    57: 
    58: 
    59: def thick_grid(P, thickness, outward_from, axis=None):
    60:     """A grid sheet given real thickness: outer face, inner face, and the four edges closed, so
    61:     rims read as solid and the inside never shows."""
    62:     pos, tri = grid_mesh(P)
    63:     n = vertex_normals(pos, tri)
    64:     d = pos - np.asarray(outward_from, float)
    65:     if axis is not None:
    66:         a = np.asarray(axis, float) / np.linalg.norm(axis)
    67:         d -= np.outer(d @ a, a)
    68:     if (np.einsum("ij,ij->i", n, d) < 0).mean() > 0.5:
    69:         n, tri = -n, tri[:, ::-1]
    70:     U, V = P.shape[:2]
    71:     inner = (pos - n * thickness).reshape(U, V, 3)
    72:     outer = pos.reshape(U, V, 3)
    73:     mid = outer.reshape(-1, 3).mean(0)
    74:     allp, allt, off = [], [], 0
    75:     parts = [(outer, tri, None), (inner, tri[:, ::-1], None)]
    76:     for edge in (lambda G: G[:, 0], lambda G: G[:, -1], lambda G: G[0, :], lambda G: G[-1, :]):
    77:         strip = np.stack([edge(outer), edge(inner)], 1)
    78:         p_, t_ = grid_mesh(strip)
    79:         nn = vertex_normals(p_, t_)
    80:         if (np.einsum("ij,ij->i", nn, p_ - mid) < 0).mean() > 0.5:
    81:             t_ = t_[:, ::-1]
    82:         parts.append((strip, t_, True))
    83:     for G, t_, _ in parts:
    84:         allp.append(G.reshape(-1, 3))
    85:         allt.append(t_ + off)
    86:         off += G.shape[0] * G.shape[1]
    87:     return np.concatenate(allp), np.concatenate(allt), outer
    88: 
    89: 
    90: def frame_axes(a, hint=(0, 1, 0)):
    91:     a = np.asarray(a, float) / np.linalg.norm(a)
    92:     b = np.cross(a, hint)
    93:     if np.linalg.norm(b) < 1e-6:
    94:         b = np.cross(a, (1, 0, 0))
    95:     b /= np.linalg.norm(b)
    96:     return a, b, np.cross(a, b)
    97: 
    98: 
    99: def box(name, role, centre, axes, half):
    100:     c = np.asarray(centre, float)
    101:     ax = [np.asarray(v, float) * h for v, h in zip(axes, half)]
    102:     corners = np.array([c + sx * ax[0] + sy * ax[1] + sz * ax[2]
    103:                         for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1)])
    104:     quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]
    105:     pos, tri = [], []
    106:     for q in quads:
    107:         base = len(pos)
    108:         pos += [corners[i] for i in q]
    109:         tri += [(base, base + 1, base + 2), (base, base + 2, base + 3)]
    110:     return piece(name, role, np.array(pos), np.array(tri), outward_from=c)
    111: 
    112: 
    113: def tube(name, role, start, axis, length, r0, r1=None, seg=16, rows=2):
    114:     r1 = r0 if r1 is None else r1
    115:     a, b, c = frame_axes(axis)
    116:     ang = np.linspace(0, 2 * math.pi, seg, endpoint=False)
    117:     P = np.zeros((seg + 1, rows, 3))
    118:     for j, t in enumerate(np.linspace(0, 1, rows)):
    119:         r = r0 + (r1 - r0) * t
    120:         ring = np.asarray(start) + a * length * t + (np.outer(np.cos(ang), b) + np.outer(np.sin(ang), c)) * r
    121:         P[:seg, j] = ring
    122:         P[seg, j] = ring[0]
    123:     pos, tri = grid_mesh(P)
    124:     return piece(name, role, pos, tri, outward_from=np.asarray(start) + a * length / 2, axis=a)
    125: 
    126: 
    127: def ball(name, role, centre, r, seg=14, rows=8, squash=(1, 1, 1)):
    128:     th = np.linspace(0, math.pi, rows)
    129:     ph = np.linspace(0, 2 * math.pi, seg + 1)
    130:     P = np.zeros((seg + 1, rows, 3))
    131:     for j, t in enumerate(th):
    132:         P[:, j, 0] = np.sin(t) * np.cos(ph) * r * squash[0]
    133:         P[:, j, 1] = np.cos(t) * r * squash[1]
    134:         P[:, j, 2] = np.sin(t) * np.sin(ph) * r * squash[2]
    135:     P += np.asarray(centre)
    136:     pos, tri = grid_mesh(P)
    137:     return piece(name, role, pos, tri, outward_from=centre)
    138: 
    139: 
    140: def ribbon(name, role, curve, width=0.006, lift=0.002, normals=None, away=None, closed=False):
    141:     """A band along a 3D polyline, lifted off a surface. normals: the surface normal at each
    142:     point (the band lies flat on it); otherwise it faces away from `away`."""
    143:     C = np.asarray(curve, float)
    144:     N = None if normals is None else np.asarray(normals, float)
    145:     if closed:
    146:         C = np.concatenate([C, C[:1]])
    147:         N = None if N is None else np.concatenate([N, N[:1]])
    148:     t = np.gradient(C, axis=0)
    149:     t /= np.maximum(np.linalg.norm(t, axis=1, keepdims=True), 1e-9)
    150:     nrm = N if N is not None else C - np.asarray(away if away is not None else C.mean(0))
    151:     nrm = nrm - t * np.einsum("ij,ij->i", nrm, t)[:, None]
    152:     nrm /= np.maximum(np.linalg.norm(nrm, axis=1, keepdims=True), 1e-9)
    153:     side = np.cross(t, nrm)
    154:     P = np.stack([C - side * width / 2 + nrm * lift, C + side * width / 2 + nrm * lift], 1)
    155:     pos, tri = grid_mesh(P)
    156:     vn = np.repeat(nrm, 2, axis=0)
    157:     if (vertex_normals(pos, tri) * vn).sum(1).mean() < 0:
    158:         tri = tri[:, ::-1]
    159:     return piece(name, role, pos, tri, nrm=vn)
    160: 
    161: 
    162: # ---- body fit -----------------------------------------------------------------------
    163: class Fit:
    164:     """What a costume is built against: the body skin (welded, measurable) and the bones, all in
    165:     the reference pose, plus the skin weights so pieces can be bound to the skeleton."""
    166: 
    167:     def __init__(self, vrm, pose, prims, roles):
    168:         self._prims, self._roles = prims, roles
    169:         W = vrm.node_world(pose)
    170:         names = vrm.nodes_by_name()
    171:         self.world = {k: W[i].copy() for k, i in names.items() if k}
    172:         self.bone = {k: m[:3, 3].copy() for k, m in self.world.items()}
    173:         skin = [p for p, r in zip(prims, roles) if r == "body"]
    174:         self.body = skin[0]
    175:         self.pos = self.body["pos"]
    176:         self.J, self.W, self.jnames = self.body["J"], self.body["W"], self.body["jnames"]
    177:         self.tri = weld(self.pos, np.concatenate([p["tri"] for p in skin]))
    178:         self.surf = Surface(self.pos, self.tri)
    179:         self.skin = self.pos[np.unique(self.tri)]
    180:         # MakeHuman bodies (tools/makehuman.py) have real muscle relief; VRoid's limbs are smooth tubes
    181:         self.cloth_hull = vrm.j.get("asset", {}).get("generator", "").startswith("lowmarch makehuman") \
    182:             and not os.environ.get("LOWMARCH_NO_HULL")
    183: 
    184:     def head_surface(self):
    185:         """The head's skin (face and scalp), for charts over the skull (tools/hair.py)."""
    186:         from vrm import bone_weight
    187:         pos, tri, off = [], [], 0
    188:         for p, r in zip(self._prims, self._roles):
    189:             if r in ("face", "body") and "J" in p and len(p["tri"]):
    190:                 w = bone_weight(p, ("Head",))
    191:                 T = p["tri"][(w[p["tri"]] > 0.5).all(1)]
    192:                 if len(T):
    193:                     pos.append(p["pos"])
    194:                     tri.append(T + off)
    195:                     off += len(p["pos"])
    196:         return Surface(np.concatenate(pos), np.concatenate(tri))
    197: 
    198:     def weight(self, bones):
    199:         hit = np.array([any(b in n for b in bones) for n in self.jnames])
    200:         return (hit[self.J] * self.W).sum(1)
    201: 
    202:     def tris_for(self, bones, min_w=0.5, exclude=(), y_min=None, y_max=None):
    203:         w = self.weight(bones)
    204:         if exclude:
    205:             w = w - self.weight(exclude)
    206:         T = self.tri[(w[self.tri] >= min_w).all(1)]
    207:         tp = self.pos[T]
    208:         sel = np.ones(len(T), bool)
    209:         if y_min is not None:
    210:             sel &= tp[:, :, 1].min(1) > y_min
    211:         if y_max is not None:
    212:             sel &= tp[:, :, 1].max(1) < y_max
    213:         return T[sel]
    214: 
    215:     def bind(self, pc, allow=None, fallback=None, rigid=None, blend=None, surface=None):
    216:         """Attach skin weights to a piece: copied from the body under it (optionally limited to
    217:         some bones), or rigid on one bone / a fixed blend."""
    218:         if pc is None:
    219:             return None
    220:         n = len(pc["pos"])
    221:         if rigid or blend:
    222:             pc["J"], pc["W"] = rigid_weights(n, self.jnames, rigid, blend)
    223:         else:
    224:             pc["J"], pc["W"] = transfer_weights(pc["pos"], None, self.J, self.W, surface=surface or self.surf,
    225:                                                 allow=allow, jnames=self.jnames, fallback=fallback)
    226:         pc["jnames"] = self.jnames
    227:         return pc
    228: 
    229: 
    230: def without(pc, bones, max_w=0.3):
    231:     """A piece's triangles away from some bones, as (pos, tri) for merge_surfaces: a bodice's torso
    232:     without its sleeves. Casting a waist ring onto a garment with its sleeves in it catches the
    233:     hanging arms at the sides (the reference pose has the arms down beside the hips)."""
    234:     hit = np.array([any(b in n for b in bones) for n in pc["jnames"]])
    235:     w = (hit[pc["J"]] * pc["W"]).sum(1)
    236:     return pc["pos"], pc["tri"][(w[pc["tri"]] < max_w).all(1)]
    237: 
    238: 
    239: def inherit(child, parent):
    240:     """Trim and hardware take the weights of the nearest vertex of the piece they sit on."""
    241:     _, i = cKDTree(parent["pos"]).query(child["pos"])
    242:     child["J"], child["W"], child["jnames"] = parent["J"][i], parent["W"][i], parent["jnames"]
    243:     return child
    244: 
    245: 
    246: def near_normals(pc, pts):
    247:     return pc["nrm"][cKDTree(pc["pos"]).query(pts)[1]]
    248: 
    249: 
    250: # ---- garments ------------------------------------------------------------------------
  • read_file{"EndLine":250,"Path":"~/work/lowmarch/tools/clips.py","StartLine":1}

    input

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

    result, 140 lines

    Showing lines 1-139 of 139
    1: """Battle animation clips, authored as a few key poses and finished with the rig tools (feet
    2: planted or stepped with leg IK, the sword aimed by direction rather than by wrist angles).
    3: 
    4:   clips(vrm, shape, stance) -> {name: [(time, pose), ...]}
    5: """
    6: import numpy as np
    7: 
    8: import poses as P
    9: from rig import Rig
    10: 
    11: BLADE = (0, 0, -1)          # the sword's blade in the right hand's frame (see outfit.sword)
    12: 
    13: 
    14: def clips(vrm, shape=None, stance="sword"):
    15:     """stance: "sword" (one hand, the cast's default) or "polearm" (both hands, see polearm())."""
    16:     if stance == "polearm":
    17:         return polearm(vrm, shape)
    18:     rig = Rig(vrm, shape)
    19:     idle = P.BATTLE_IDLE
    20:     foot = {s: rig.pos(idle, f"J_Bip_{s}_Foot") for s in "LR"}
    21:     step = np.array([0.0, 0.0, -0.36])                     # the lead (left) foot steps forward
    22: 
    23:     def finish(pose, lead=0.0, blade=None):
    24:         pose = rig.leg_ik(pose, "L", foot["L"] + step * lead)
    25:         pose = rig.leg_ik(pose, "R", foot["R"])
    26:         if blade is not None:
    27:             pose = rig.aim(pose, "J_Bip_R_Hand", BLADE, blade)
    28:         return pose
    29: 
    30:     wind = finish(P.WIND_UP, 0.0, blade=(0.15, 0.55, 1.0))       # blade back over the shoulder
    31:     slash = finish(P.SLASH, 1.0, blade=(0.1, -0.55, -1.0))       # forward and down through the target
    32:     follow = finish(P.FOLLOW, 1.0, blade=(-0.45, -1.0, -0.15))   # carried down across the body
    33:     breathe = finish(P.IDLE_BREATH, 0.0)
    34:     return {
    35:         "idle": [(0.0, idle), (0.9, breathe), (1.8, idle)],
    36:         "attack": [(0.0, idle), (0.32, wind), (0.44, wind), (0.56, slash), (0.68, follow), (1.05, follow),
    37:                    (1.5, idle)],
    38:     }
    39: 
    40: 
    41: def fists(rig):
    42:     """Where each fist closes in the reference pose: the point a held weapon's shaft runs through, as
    43:     gear._hand_frame places it (rig.grip_points: measured from the curled fingers)."""
    44:     from rig import grip_points
    45:     return {side: g["point"] for side, g in grip_points(rig.v, rig.shape, P.BUST).items()}
    46: 
    47: 
    48: # The polearm's keys: hips drop and forward shift, turn of the shoulders (- brings the left one
    49: # forward), forward lean, the lead foot's step; the right fist from the right shoulder in arm lengths
    50: # (x: the fighter's right, -z forward), the shaft's direction (head end), and the left arm's reach
    51: # (shoulder to fist, in arm lengths): the left fist holds the shaft where that reach meets it, so
    52: # every build gets bent elbows rather than a fixed hand spacing that some arms can't span.
    53: POLEARM = {
    54:     "wind": dict(drop=0.075, turn=-26.0, lean=3.0, fwd=-0.03, lead=0.0, fist=(0.13, -0.52, -0.04),
    55:                  shaft=(-0.22, 0.30, -0.93), reach=0.78),
    56:     "thrust": dict(drop=0.09, turn=-18.0, lean=14.0, fwd=0.17, lead=0.30, fist=(-0.10, -0.42, -0.50),
    57:                    shaft=(-0.28, 0.06, -0.96), reach=0.92),
    58:     "follow": dict(drop=0.095, turn=-16.0, lean=16.0, fwd=0.19, lead=0.30, fist=(-0.12, -0.46, -0.52),
    59:                    shaft=(-0.28, 0.0, -0.96), reach=0.92),
    60: }
    61: # The guard's idle, after the study of Unicorn Overlord's idles (a mercenary's, tracked frame by frame):
    62: # a 2 s loop with the feet planted; the hips sink about 2% of the height and ease forward, the chest
    63: # sinks further (the lean deepens) and the head stays level; a slow rise, a short hold at the top, a
    64: # quicker sink and a longer settle; the weapon's head dips as the body sinks, a beat behind it.
    65: # GUARD_TOP and GUARD_LOW are the two ends; IDLE_SINK says how far sunk (0 top, 1 low) over the loop,
    66: # eased between its points; the loop is sampled every IDLE_STEP and each sample grips afresh.
    67: GUARD_TOP = dict(drop=0.050, turn=-14.0, lean=3.0, fwd=0.0, lead=0.0, fist=(0.04, -0.60, -0.26),
    68:                  shaft=(-0.32, 0.44, -0.84), reach=0.80)
    69: GUARD_LOW = dict(drop=0.092, turn=-16.0, lean=11.0, fwd=0.014, lead=0.0, fist=(0.04, -0.60, -0.26),
    70:                  shaft=(-0.32, 0.37, -0.87), reach=0.80)
    71: IDLE_LOOP, IDLE_STEP, SHAFT_LAG = 2.0, 0.1, 0.1
    72: IDLE_SINK = [(0.0, 1.0), (0.15, 1.0), (0.85, 0.0), (1.15, 0.0), (1.55, 1.0), (2.0, 1.0)]
    73: 
    74: 
    75: def sink(t):
    76:     """How far sunk the guard is at time t of the idle loop (0 top .. 1 low), eased between points."""
    77:     t = t % IDLE_LOOP
    78:     for (t0, a), (t1, b) in zip(IDLE_SINK[:-1], IDLE_SINK[1:]):
    79:         if t0 <= t <= t1:
    80:             x = (t - t0) / max(t1 - t0, 1e-9)
    81:             return a + (b - a) * x * x * (3 - 2 * x)
    82:     return IDLE_SINK[-1][1]
    83: 
    84: 
    85: def guard_at(t):
    86:     """The guard's parameters at time t of the idle loop."""
    87:     k, ks = sink(t), sink(t - SHAFT_LAG)
    88:     out = {n: (GUARD_TOP[n] + (GUARD_LOW[n] - GUARD_TOP[n]) * k) if isinstance(GUARD_TOP[n], float) else GUARD_TOP[n]
    89:            for n in GUARD_TOP}
    90:     out["shaft"] = tuple(a + (b - a) * ks for a, b in zip(GUARD_TOP["shaft"], GUARD_LOW["shaft"]))
    91:     return out
    92: 
    93: 
    94: def polearm(vrm, shape=None, keys=None):
    95:     """A halberd in both hands (it is rigid on the right hand), after the study's soldiers: a wide,
    96:     low guard, left foot forward, the shaft across the body with its head forward and up, the right
    97:     fist by the hip and the left up the shaft at chest height, elbows bent and out of the body. The
    98:     attack draws the shaft back and thrusts it forward on a lunge, both hands on it throughout.
    99:     Each key grips with rig.grip so the left fist lands on the shaft where the right hand holds it."""
    100:     from checks import Body
    101:     from duel import clear_grip
    102:     rig = Rig(vrm, shape)
    103:     body = Body(vrm, shape)
    104:     f = fists(rig)
    105:     ref = dict(ref_pose=P.BUST, fist_R=f["R"], fist_L=f["L"])
    106:     base = P.merge(P.BATTLE_IDLE, P.fist("L"))
    107:     foot = {s: rig.pos(base, f"J_Bip_{s}_Foot") for s in "LR"}
    108:     arm = {s: rig.pos(P.BUST, f"J_Bip_{s}_LowerArm") - rig.pos(P.BUST, f"J_Bip_{s}_UpperArm") for s in "LR"}
    109:     span = {s: float(np.linalg.norm(arm[s]) + np.linalg.norm(f[s] - rig.pos(P.BUST, f"J_Bip_{s}_LowerArm"))) for s in "LR"}
    110: 
    111:     def guard(drop, turn, lean, fwd, lead, fist, shaft, reach):
    112:         # the lean comes mostly from the hips: a bent spine pushed the breastplate's hem through the belt
    113:         pose = P.merge(base, {
    114:             "J_Bip_C_Hips": P.move(0, -drop, -fwd, P.rot((1, 0, 0), -lean * 0.65)),
    115:             "J_Bip_C_Spine": P.rot((0, 1, 0), turn * 0.6) @ P.rot((1, 0, 0), -lean * 0.2),
    116:             "J_Bip_C_Chest": P.rot((0, 1, 0), turn * 0.4) @ P.rot((1, 0, 0), -lean * 0.15),
    117:             "J_Bip_C_Neck": P.rot((0, 1, 0), -turn * 0.5) @ P.rot((1, 0, 0), lean * 0.35),
    118:             "J_Bip_C_Head": P.rot((0, 1, 0), -turn * 0.3) @ P.rot((1, 0, 0), lean * 0.35)})   # the gaze stays level
    119:         pose = rig.leg_ik(pose, "L", foot["L"] + np.array([-0.07, 0, -0.14 - lead]))
    120:         pose = rig.leg_ik(pose, "R", foot["R"] + np.array([0.06, 0, 0.12]), pole=(0, -0.2, -1))
    121:         D = np.asarray(shaft, float) / np.linalg.norm(shaft)
    122:         fr = rig.pos(pose, "J_Bip_R_UpperArm") + span["R"] * np.asarray(fist, float)
    123:         # the left fist: the point up the shaft at `reach` from the left shoulder
    124:         q = fr - rig.pos(pose, "J_Bip_L_UpperArm")
    125:         b, c = float(D @ q), float(q @ q) - (reach * span["L"]) ** 2
    126:         t = -b + np.sqrt(max(b * b - c, 0.0))          # (out of reach: the shaft's nearest point)
    127:         t = float(np.clip(t, 0.22, 0.48))
    128:         pose = clear_grip(rig, body, pose, "R", ref, fr, D, (0.6, -0.4, 0.7))
    129:         return clear_grip(rig, body, pose, "L", ref, fr + D * t, D, (-0.8, -1.0, 0.1))
    130:     k = {n: guard(**v) for n, v in (keys or POLEARM).items()}
    131:     n = int(round(IDLE_LOOP / IDLE_STEP))
    132:     idle = [(round(i * IDLE_STEP, 3), guard(**guard_at(i * IDLE_STEP))) for i in range(n)]
    133:     idle.append((IDLE_LOOP, idle[0][1]))                     # the loop closes on its first pose
    134:     rest = idle[0][1]
    135:     return {
    136:         "idle": idle,
    137:         "attack": [(0.0, rest), (0.32, k["wind"]), (0.44, k["wind"]), (0.56, k["thrust"]), (0.68, k["follow"]),
    138:                    (1.05, k["follow"]), (1.5, rest)],
    139:     }