A 3D model pipeline, pushed by Fable 5.2

agent

+36:46

Two workers are running (two-handed sword clips; model export and lens shot). I'm now reading the armour kit to design her own costume.

  • Bashcd ~/Projects/lowmarch-fable52 && date +%H:%M:%S && sed -n 1,28p tools/plates.py && sed -n 53,62p tools/plates.py && sed -n 95,140p tools/plates.py && sed -n 218,300p tools/plates.py

    command

    cd ~/Projects/lowmarch-fable52 && date +%H:%M:%S && sed -n 1,28p tools/plates.py && sed -n 53,62p tools/plates.py && sed -n 95,140p tools/plates.py && sed -n 218,300p tools/plates.py

    result, 168 lines

    19:09:41
    """Plates drawn as outlines: the armour kit's second generation (portrait guide, lesson 13).
    
    The first kit builds plate as bands (limb_lames, pauldron lames) or shrink-wraps (the cuirass): fine
    for stacked lames, but it can't draw a shape. Here a plate is drawn like a pattern piece laid on a
    dress form.
    
    A chart wraps a body region in two coordinates:
      TorsoChart  u = degrees round the body (0 front, +90 the character's right, 180 back), v = height (m)
      LimbChart   u = degrees round a bone (0 = `front`), v = fraction along it (0 at the joint)
    point(u, v) is on the surface the chart covers: a ray out of the chart's axis, at a radius taken from
    a field of ray casts that is filled and smoothed (and, as a shell, kept from following hollows), so
    plates come out as shells rather than mouldings of the skin.
    
    A plate is the region between two edge curves over a range of u, bottom(u) and top(u), so its outline
    is exactly the mesh boundary (no jagged clipping) and a pointed waist, a scooped neckline or a pointed
    cuff is one function each. It sits `offset` off the chart, is domed by `crown`, given thickness, and
    carries per-vertex plate data for the painted renderer:
      plate = (1, distance to the outline in metres, gold border width in metres, height in the plate 0..1)
    from which the shader paints the border, an engraved line inside it, and a top-to-bottom gradient
    so a flat plate doesn't read as one flat value.
    """
    import math
    
    import numpy as np
    from scipy.ndimage import gaussian_filter
    from scipy.spatial import cKDTree
    
    
    class _Chart:
        """Shared: a radius field R[u, v] over a grid, sampled bilinearly (u wraps)."""
    
        def _setup(self, R, smooth, shell, wrap_u):
            R = _fill_nan(R, wrap_u)
            mode = ("wrap" if wrap_u else "nearest", "nearest")
            if shell:                                      # bridge hollows (between the breasts, the spine)
                R = np.maximum(R, gaussian_filter(R, (smooth[0] * 3, smooth[1] * 3), mode=mode))
            self.R = gaussian_filter(R, smooth, mode=mode)
    
    class TorsoChart(_Chart):
        """u = degrees round the vertical axis through (cx, cz) (0 = front, -z; +90 = the character's
        right, +x), v = height in metres. `over`: the Surface the plates sit on."""
    
        def __init__(self, over, y0, y1, cx=0.0, cz=0.0, du=3.0, dv=0.01, smooth=(1.5, 1.2), shell=True, rmax=0.4):
            self.cx, self.cz, self.wrap = cx, cz, True
            self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, y0, dv, dv * 0.5
            us = np.arange(-180.0, 180.0, du)
            vs = np.arange(y0, y1 + dv * 0.5, dv)
            R = np.full((len(us), len(vs)), np.nan)
            for i, u in enumerate(us):
                d = np.array([math.sin(math.radians(u)), 0.0, -math.cos(math.radians(u))])
                for j, v in enumerate(vs):
                    R[i, j] = over.cast(np.array([cx, v, cz]), d, rmax=rmax, far=True)
            self._setup(R, smooth, shell, True)
    
        def ray(self, u, v):
            u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float))
            ur = np.radians(u)
            d = np.stack([np.sin(ur), np.zeros_like(ur), -np.cos(ur)], -1)
            o = np.stack([np.full_like(u, self.cx), v, np.full_like(u, self.cz)], -1)
            return o, d
    
        def metric(self, u, v):
            """(arc length round the body, height) in metres: distances along the surface for trim."""
            return np.stack([np.radians(u) * self.radius(u, v), np.asarray(v, float) + 0 * np.asarray(u, float)], -1)
    
        def centre(self, v):
            return np.array([self.cx, v, self.cz])
    
    
    class ConeChart(TorsoChart):
        """A TorsoChart whose radius is a function r(u, v) instead of ray casts: a skirt's cone, a
        plate standing off a skirt. r_fn takes and returns arrays."""
    
        def __init__(self, r_fn, cx=0.0, cz=0.0, ev=0.005):
            self.cx, self.cz, self.r_fn, self.ev, self.wrap = cx, cz, r_fn, ev, True
    
        def radius(self, u, v):
            u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float))
            return np.asarray(self.r_fn(u, v), float) + 0 * u
    
    
    class LimbChart(_Chart):
        """u = degrees round the bone from a to b (0 = toward `front`, +90 = toward front x axis, i.e.
        the right-handed turn about the bone), v = fraction along it (0 at a, 1 at b; -0.2..1.2 covered)."""
    class Canvas:
        """Draw shapes given in (s, t) in 0..1 (t up) at w x h pixels, supersampled for clean edges."""
    
        def __init__(self, w, h, ss=3):
            from PIL import Image, ImageDraw
            self.w, self.h, self.ss = int(w), int(h), ss
            self.layers = [Image.new("L", (self.w * ss, self.h * ss), 0) for _ in range(3)]
            self.draw = [ImageDraw.Draw(im) for im in self.layers]
    
        def _xy(self, st):
            st = np.atleast_2d(np.asarray(st, float))
            return [(float(s * self.w * self.ss), float((1 - t) * self.h * self.ss)) for s, t in st]
    
        def poly(self, st, ch):
            self.draw[CHANNEL[ch]].polygon(self._xy(st), fill=255)
    
        def line(self, st, width_px, ch):
            xy = self._xy(st)
            w = max(1, int(round(width_px * self.ss)))
            self.draw[CHANNEL[ch]].line(xy, fill=255, width=w, joint="curve")
            r = w / 2
            for x, y in (xy[0], xy[-1]):                   # round caps
                self.draw[CHANNEL[ch]].ellipse((x - r, y - r, x + r, y + r), fill=255)
    
        def dot(self, st, rx_px, ry_px, ch):
            (x, y), = self._xy(st)
            self.draw[CHANNEL[ch]].ellipse((x - rx_px * self.ss, y - ry_px * self.ss, x + rx_px * self.ss, y + ry_px * self.ss),
                                           fill=255)
    
        def array(self):
            from PIL import Image
            chans = [np.asarray(im.resize((self.w, self.h), Image.LANCZOS)) for im in self.layers]
            return np.dstack(chans + [np.full((self.h, self.w), 255, np.uint8)]).astype(np.uint8)
    
    
    def _seg_distance(P, A, B):
        """Distance from points P (N,2) to segments A->B (M,2): (N,) minimum."""
        d = B - A
        L2 = np.maximum((d * d).sum(1), 1e-18)
        t = np.clip(((P[:, None] - A[None]) * d[None]).sum(-1) / L2[None], 0, 1)
        Q = A[None] + t[..., None] * d[None]
        return np.linalg.norm(P[:, None] - Q, axis=-1).min(1)
    
    
    def outline_plate(name, role, chart, u0, u1, bottom, top, offset=0.012, crown=0.0, flare=None, thickness=0.003,
                      nu=48, nv=18, trim=0.0, roll=0.0026, roll_edges=("bottom", "top", "left", "right"),
                      roll_role=None, rivets=None, rivet_role="gold", seams=(), groove=(0.004, 0.0025),
                      panel_crown=0.0, studs=(), stud_r=0.004, stud_role=None, facets=None, decal=(), decal_px=1400,
                      pattern=None):
        """A plate between bottom(u) and top(u) over u in [u0, u1] on `chart`.
        offset: off the chart surface; crown: extra rise in the middle of the plate (0 at the outline);
        flare(u, v, s, t) -> extra offset (s across, t up, both 0..1), e.g. a cuff belling out at one end;
        thickness: metres, or thickness(u, v, s, t) per point (a beard filled down to the face);
        trim: gold border width painted by the renderer (0 = none); roll: rolled-edge tube radius along
        `roll_edges` (0 = none); rivets: (spacing, inset, radius) studs inside the outline (rivet_role).
        seams: polylines [(u, v), ...] dividing the plate into panels: each panel domes by panel_crown,
          the seams sink into grooves (width, depth) and are painted as dark grooves;
        studs: (u, v) points (seam junctions) given domed studs of radius stud_r;
        facets: u angles where the plate turns a corner: flat between them (a TorsoChart's horizontal rows);
        decal: shapes in chart coordinates painted on the plate (see Canvas):
          ("poly", [(u, v), ...], channel) / ("line", [(u, v), ...], width_m, channel) / ("dot", (u, v), r_m, channel)
          channels: "paint" (the character's motif colour), "groove", "gold".
        Returns (plate piece, [extra pieces: rolls, rivets, studs]); bind them all before export."""
        from outfit import piece, pipe, ball
        U = np.linspace(u0, u1, nu)
        S = np.linspace(0, 1, nu)
        T = np.linspace(0, 1, nv)
        vb = np.array([bottom(u) for u in U])
        vt = np.array([top(u) for u in U])
        uu = np.repeat(U[:, None], nv, 1)
        vv = vb[:, None] + (vt - vb)[:, None] * T[None, :]
        n = chart.normal(uu, vv)
        lift = np.full(uu.shape, float(offset))
        if crown:
            lift += crown * np.sqrt(np.clip(np.sin(np.pi * S)[:, None] * np.sin(np.pi * T)[None, :], 0, 1))
        if flare is not None:
            lift += np.array([[flare(U[i], vv[i, j], S[i], T[j]) for j in range(nv)] for i in range(nu)])
        if seams:                                          # panels dome between seams that sink into grooves
            M = chart.metric(uu, vv).reshape(-1, 2)
            segs = [(chart.metric(np.array([a[0], b[0]]), np.array([a[1], b[1]]))) for L in seams for a, b in zip(L[:-1], L[1:])]
            A = np.array([sg[0] for sg in segs])
            Bv = np.array([sg[1] for sg in segs])
            dseam = _seg_distance(M, A, Bv).reshape(uu.shape)
  • Bashcd ~/Projects/lowmarch-fable52 && grep -n "^def \|^ def " tools/saber_study.py && sed -n 1,60p tools/saber_study.py

    command

    cd ~/Projects/lowmarch-fable52 && grep -n "^def \|^    def " tools/saber_study.py && sed -n 1,60p tools/saber_study.py

    result, 78 lines

    19:def _grouped(pcs, g):
    27:def _to_uv(chart, u0, v0, pts):
    33:def leaf(chart, u0, v0, ang, length, width, ch="paint"):
    44:def curl(chart, u0, v0, radius, turns=1.25, width=0.0022, flip=1, ch="paint"):
    52:def stroke(chart, u0, v0, pts, width=0.0022, ch="paint"):
    56:def build(fit):
    68:    def cuff_plane(side):                               # sleeves end inside the gauntlet
    107:    def front_top(u):
    190:    def r_base(u, v):                                   # the overskirt's cone before it clears the petticoat
    249:    def r_over(u, v):
    260:    def over_bottom(u):
    275:    def p_top(u):
    281:    def p_bottom(u):
    417:def _bind_strip(fit, pts, s, chart, y):
    424:def _puff(fit, side, s, hd):
    440:    def surf(d):
    471:def _nape_bow(fit):
    498:def _excalibur(fit, hand="R", blade_len=0.84, blade_w=0.044, grip_len=0.22):
    """Benchmark only, NOT FOR THE GAME: Saber (Fate/stay night) in her armoured dress, built with the
    outline-plate kit (tools/plates.py) to measure how close it can get to a well-known design. Saber is
    Type-Moon's; the game's characters are original designs at this level of detail.
    
    Built from a written study of the official art (model sheets front, back and three-quarter, and a
    figure for the hidden sides), never from the images themselves. Sizes are fractions of her height H
    (skull to sole) or of her head height hd, read off the study and placed on Elaine's base body, whose
    landmarks agree with the study's to a few percent (chin 0.14 H, waist 0.30-0.32 H, ankle 0.94 H).
    """
    import math
    
    import numpy as np
    
    import outfit as O
    from fitting import Surface, merge_surfaces
    from plates import TorsoChart, LimbChart, ConeChart, outline_plate, stiffen, flat_piece, taper
    
    
    def _grouped(pcs, g):
        for pc in pcs:
            if pc is not None:
                pc["group"] = g
        return [pc for pc in pcs if pc is not None]
    
    
    # ---- decal shapes, in a chart's (u, v) with sizes in metres --------------------------------------
    def _to_uv(chart, u0, v0, pts):
        """Metric offsets (across, up) from (u0, v0) on a torso-type chart -> (u, v) points."""
        r = float(chart.radius(u0, v0))
        return [(u0 + math.degrees(dx / r), v0 + dy) for dx, dy in pts]
    
    
    def leaf(chart, u0, v0, ang, length, width, ch="paint"):
        """A tapering blade from (u0, v0) at `ang` degrees from straight up (+ toward +u)."""
        a = math.radians(ang)
        al, ac = np.array([math.sin(a), math.cos(a)]), np.array([math.cos(a), -math.sin(a)])
        t = np.linspace(0, 1, 14)
        w = width / 2 * np.sqrt(t + 0.08) * (1 - t) ** 0.85 * 1.6
        left = [tuple(al * length * ti + ac * wi) for ti, wi in zip(t, w)]
        right = [tuple(al * length * ti - ac * wi) for ti, wi in zip(t[::-1], w[::-1])]
        return ("poly", _to_uv(chart, u0, v0, left + right), ch)
    
    
    def curl(chart, u0, v0, radius, turns=1.25, width=0.0022, flip=1, ch="paint"):
        """A spiral stroke (the swirl glyphs), unwinding from its centre."""
        th = np.linspace(0, turns * 2 * math.pi, 40)
        rr = radius * (0.25 + 0.75 * th / th[-1])
        pts = [(flip * r * math.cos(x), r * math.sin(x)) for r, x in zip(rr, th)]
        return ("line", _to_uv(chart, u0, v0, pts), width, ch)
    
    
    def stroke(chart, u0, v0, pts, width=0.0022, ch="paint"):
        return ("line", _to_uv(chart, u0, v0, pts), width, ch)
    
    
    def build(fit):
        B = fit.bone
        P = fit.pos[np.unique(fit.tri)]
        top, sole = float(P[:, 1].max()), float(P[:, 1].min())
        H = top - sole
  • Bashcd ~/Projects/lowmarch-fable52 && sed -n 60,190p tools/saber_study.py

    command

    cd ~/Projects/lowmarch-fable52 && sed -n 60,190p tools/saber_study.py

    result, 131 lines

        H = top - sole
        hd = H / 7.06                                       # this base's head height (measured)
        y = lambda f: top - f * H                           # a height given as a fraction of H from the skull
        nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"]
        cz = float(hips[2])
        knee = B["J_Bip_L_LowerLeg"][1]
        out = []
    
        def cuff_plane(side):                               # sleeves end inside the gauntlet
            a, hd_ = B[f"J_Bip_{side}_LowerArm"], B[f"J_Bip_{side}_Hand"]
            n = (hd_ - a) / np.linalg.norm(hd_ - a)
            return n, n @ (a + (hd_ - a) * 0.7)
    
        # ---- under layers: dress bodice and sleeves, dark tights, leg shells, black gloves ----------
        torso = ("Spine", "Chest", "UpperChest", "Bust", "Shoulder", "UpperArm", "LowerArm", "Neck", "Hips")
        bodice = O.wrap(fit, "bodice", "signature", torso, offset=0.006, exclude=("UpperLeg",),
                        y_min=hips[1] + 0.02, y_max=nk[1] + 0.012, hems=[cuff_plane("L"), cuff_plane("R")])
        tights = O.wrap(fit, "tights", "doublet", ("Hips", "UpperLeg", "LowerLeg"), offset=0.004, y_max=hips[1] + 0.03, subdiv=1)
        boots = O.wrap(fit, "boots", "metal", ("LowerLeg", "Foot"), offset=0.012, y_max=knee - 0.10, exclude=("ToeBase",),
                       subdiv=1, hems=[((0, 1, 0), knee - 0.105)])
        gloves = O.wrap(fit, "gloves", "glove", ("Hand", "Thumb", "Index", "Middle", "Ring", "Little"),
                        offset=0.0035, min_w=0.3, smooth=4)
        out += _grouped([bodice], "dress") + _grouped([tights], "trousers") + _grouped([boots], "boots") + _grouped([gloves], "gloves")
        torso_only = O.without(bodice, ("Shoulder", "UpperArm", "LowerArm", "Hand"))
        chest = Surface(*torso_only)
    
        # ---- collar: a close stand collar, gold band along its top, gold line down the front ----------
        col, rim, fronts = O.collar(fit, "collar", "signature", height_back=0.040, height_front=0.034, gap_deg=6,
                                    clear=(0.008, 0.012))
        band = rim - np.array([0, 0.0042, 0])
        out += _grouped([col, O.inherit(O.ribbon("collar_band", "gold", band, width=0.0075, lift=0.0012,
                                                 normals=O.near_normals(col, band)), col)], "dress")
        for k, edge in enumerate(fronts):
            out += _grouped([O.inherit(O.ribbon(f"collar_front{k}", "gold", edge, width=0.0035, lift=0.0012,
                                                normals=O.near_normals(col, edge)), col)], "dress")
    
        # ---- the chest chart (the bodice without its sleeves) --------------------------------------
        tc = TorsoChart(chest, y(0.36), y(0.14), cz=cz, du=2.0, dv=0.006, smooth=(1.6, 1.4))
    
        # back: two short gold strips from the collar base, down and outward (a Lambda)
        for s in (-1, 1):
            pts = tc.point(np.array([180 + s * 6, 180 + s * 26]), np.array([y(0.165), y(0.215)]), off=0.002)
            out += _grouped(_bind_strip(fit, pts, s, tc, y), "dress")
    
        # ---- cuirass: domed panels between grooves, studs at the junctions, painted blue motifs -------
        yb, yv, ybust = y(0.303), y(0.280), y(0.246)
    
        def front_top(u):
            a = abs(u)
            if a <= 34:
                return y(0.197)
            if a <= 80:
                return y(0.197) + (y(0.226) - y(0.197)) * ((a - 34) / 46) ** 1.3
            return y(0.226) + (y(0.236) - y(0.226)) * min(1.0, (a - 80) / 18)
    
        seams, studs = [], []
        for s in (-1, 1):
            seams += [[(s * 34, y(0.199)), (s * 60, ybust), (s * 38, y(0.262)), (s * 14, y(0.274)), (0, yv)],
                      [(s * 60, ybust), (s * 99, ybust)],
                      [(s * 31, y(0.267)), (s * 52, y(0.288)), (s * 60, yb - 0.004)]]
            studs += [(s * 60, ybust), (s * 31, y(0.267)), (s * 60, yb + 0.012)]
        seams.append([(0, yv), (0, yb - 0.004)])
        motif = []
        # bust panel: a curl glyph with a dot, a stem down to the V, a fan of six blades rising from it
        motif += [curl(tc, 0, y(0.213), 0.0075, turns=1.1), ("dot", (0, y(0.205)), 0.0023, "paint"),
                  stroke(tc, 0, y(0.219), [(0, 0), (0, -(y(0.219) - y(0.276)))], width=0.0016)]
        for s in (-1, 1):
            for ang, L in ((20, 0.056), (40, 0.072), (60, 0.086)):
                motif.append(leaf(tc, 0, y(0.277), s * ang, L, 0.016))
            for ang, L in ((22, 0.034), (46, 0.040), (70, 0.036)):   # the abdomen panels: small fans up and out
                motif.append(leaf(tc, s * 14, y(0.301), s * ang, L, 0.010))
        front, fx = outline_plate("cuirass", "steel", tc, -99, 99, lambda u: yb, front_top, offset=0.011, crown=0.004,
                                  thickness=0.003, nu=110, nv=44, roll=0.0022, roll_edges=("top",), roll_role="steel",
                                  seams=seams, groove=(0.0060, 0.0022), panel_crown=0.0035, studs=studs, stud_r=0.0038,
                                  decal=motif, decal_px=1600)
        back_top = lambda u: y(0.190) + (y(0.236) - y(0.190)) * (abs(((u % 360) - 180)) / 82) ** 1.6
        bseams = [[(129, ybust), (180, y(0.262)), (231, ybust)], [(99, y(0.283)), (261, y(0.283))]]
        back, bx = outline_plate("backplate", "steel", tc, 99, 261, lambda u: yb, back_top, offset=0.011, crown=0.004,
                                 thickness=0.003, nu=80, nv=36, roll=0.0022, roll_edges=("top",), roll_role="steel",
                                 seams=bseams, groove=(0.0035, 0.0018), panel_crown=0.003,
                                 studs=[(129, ybust), (231, ybust)], stud_r=0.0038, decal_px=1200)
        # the gorget: a separate plate over the collar's foot, stepping out from the chest
        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)]
        for s in (-1, 1):
            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)]
        gorget, gx = outline_plate("gorget", "steel", tc, -38, 38,
                                   lambda u: y(0.201) - 0.007 * (1 - (u / 38) ** 2),
                                   lambda u: y(0.170) - 0.008 * max(0.0, (abs(u) - 28) / 10) ** 2,
                                   offset=0.023, crown=0.003, thickness=0.003, nu=48, nv=18, roll=0.0022,
                                   roll_edges=("top", "bottom"), roll_role="steel",
                                   studs=[(-33, y(0.197)), (33, y(0.197))], stud_r=0.0036, decal=gmotif, decal_px=1800)
        for pc in (front, back, gorget):
            fit.bind(pc, allow=("Spine", "Chest", "UpperChest", "Bust"), fallback="J_Bip_C_Chest")
        for pc in fx:
            O.inherit(pc, front)
        for pc in bx:
            O.inherit(pc, back)
        for pc in gx:
            O.inherit(pc, gorget)
        gorget["W"][:] = 0
        gorget["J"][:, 0] = fit.jnames.index("J_Bip_C_UpperChest")
        gorget["W"][:, 0] = 1.0
        for pc in gx:
            O.inherit(pc, gorget)
        out += _grouped([front, back, gorget] + fx + bx + gx, "plate")
    
        # ---- belt: near-black leather at the natural waist, laced at the front -----------------------
        belt, bfront = O.belt(fit, "belt", "leather", chest, y(0.311), height=0.034, offset=0.004, thickness=0.005)
        out += _grouped([belt], "belt")
        lace = []
        ex, ey_ = np.array([1.0, 0, 0]), np.array([0, 1.0, 0])
        c0 = bfront + np.array([0, 0, -0.006])
        eye = {(sx, k): c0 + ex * sx * 0.011 + ey_ * (0.011 - 0.016 * k) for sx in (-1, 1) for k in range(3)}
        for k in range(2):
            for sx in (-1, 1):
                a, b = eye[(sx, k)], eye[(-sx, k + 1)]
                lace.append(O.pipe(f"lace{k}{(sx + 1) // 2}", "glove", np.linspace(a, b, 6) + np.array([0, 0, -0.002 * (k + 1)]),
                                   r=0.0017, seg=6))
        for (sx, k), p in eye.items():
            lace.append(O.ball(f"eyelet{k}{(sx + 1) // 2}", "steel", p, 0.0028, seg=8, rows=5, squash=(1, 1, 0.5)))
        for pc in lace:
            fit.bind(pc, rigid="J_Bip_C_Hips")
        out += _grouped(lace, "belt")
    
        # ---- skirts: the white petticoat (cloth), the open blue overskirt, the violet front panel ------
        y_top, y_hem = y(0.322), y(0.790)
        r_hem = 0.24 * H
        r0 = lambda u: tc.radius(u, y(0.322)) + 0.014
        r0_mean = float(np.mean([r0(u) for u in range(-180, 180, 10)]))
    
        def r_base(u, v):                                   # the overskirt's cone before it clears the petticoat
  • Bashcd ~/Projects/lowmarch-fable52 && grep -n "shape.get(\|shape\[\"" tools/vroid_portrait.py | sed 's/^\([0-9]*\):.*shape\(\.get(\|\[\)\("[a-z_]*"\).*/\1 \3/' | awk '{print $2}' | sort -u | tr '\n' ' '; echo; grep -n " def __init__" -A28 tools/vroid_portrait.py | sed -n 1,60p

    command

    cd ~/Projects/lowmarch-fable52 && grep -n "shape.get(\|shape\[\"" tools/vroid_portrait.py | sed 's/^\([0-9]*\):.*shape\(\.get(\|\[\)\("[a-z_]*"\).*/\1 \3/' | awk '{print $2}' | sort -u | tr '\n' ' '; echo; grep -n "    def __init__" -A28 tools/vroid_portrait.py | sed -n 1,60p

    result, 29 lines

    906:    def __init__(self, path, morphs=None, pose=BUST_POSE, shape=None, hair_from=None, costume=None,
    907-                 mouth="curve", world=None, ref_pose=BUST_POSE, hair_trim=None):
    908-        """mouth: how the closed mouth is drawn. 'texture' = VRoid's painted lip line, thickened;
    909-        'texture+lip' = that plus a lower-lip shade; 'drawn' = an FE8-style mouth between the
    910-        projected mouth corners; 'none' = geometry only (the line disappears when closed)."""
    911-        self.mouth = mouth
    912-        self.v = VRM(path)
    913-        sh = dict(NEUTRAL, **(shape or {}))
    914-        mo = dict(sh["rest"])
    915-        for k_, w_ in (morphs or {}).items():
    916-            mo[k_] = min(1.0, mo.get(k_, 0.0) + w_)
    917-        if sh["fangs"] < 1.0:                            # some faces' teeth have fangs (sample V's); 0 files them away
    918-            mo["Fcl_HA_Short"] = max(mo.get("Fcl_HA_Short", 0.0), 1.0 - sh["fangs"])
    919-        # everything is built in the reference pose (arms down), then posed through the skeleton
    920-        target_pose = bone_pose(self.v, sh, pose)
    921-        pose = bone_pose(self.v, sh, ref_pose)
    922-        mo, self.mouth_hold = hold_mouth(self.v, mo, pose)
    923-        closure = eye_closure(mo)
    924-        lines = None
    925-        if max(closure.values()) > 0.05 or sh["lash"] != 1.0:   # the eyeline open, and how far a shut eye must close
    926-            eyes = {k_: w_ for k_, w_ in mo.items() if "EYE_" not in k_ and "ALL_" not in k_}
    927-            now = self.v.primitives(mo, pose)
    928-            ln = [i_ for i_, p_ in enumerate(now) if "FaceEyeline" in p_["material"]]
    929-            if ln:
    930-                prs = [self.v.primitives(eyes, pose)[ln[0]], now[ln[0]],
    931-                       self.v.primitives(dict(eyes, Fcl_EYE_Close=1.0), pose)[ln[0]]]
    932-                eye = eye_lines(prs[0])
    933-                # the character's one lash size: set on the open lash, which every closed lid is moved from
    934-                lines = (ln[0], lash_size(prs[0]["pos"].copy(), prs[0]["uv"], eye, sh["lash"]), eye, now)
  • Bashcd ~/Projects/lowmarch-fable52 && grep -n "^NEUTRAL" -A22 tools/vroid_portrait.py | head -45; sed -n 934,1010p tools/vroid_portrait.py

    command

    cd ~/Projects/lowmarch-fable52 && grep -n "^NEUTRAL" -A22 tools/vroid_portrait.py | head -45; sed -n 934,1010p tools/vroid_portrait.py

    result, 100 lines

    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)}
                    lines = (ln[0], lash_size(prs[0]["pos"].copy(), prs[0]["uv"], eye, sh["lash"]), eye, now)
                    further = lid_gap(prs[1]["pos"], prs[2]["pos"], prs[0]["pos"], lines[2], prs[0]["uv"], prs[0]["tri"],
                                      self.v.material_texture(prs[0]["mi"]))
            mo = hide_closed_irises(mo, further if lines else None)
            self.pose_now = target_pose
            self.pose_ref = pose
            self.shape = sh
            self.prims = self.v.primitives(mo, pose)
            if lines:                                        # a closing lid is the model's own open lash, moved
                k_, P_open, eye, now = lines
                p_ = self.prims[k_]
                keep_lash_weight(p_, P_open, p_["uv"], eye, closure)
                lash_size(p_["pos"], p_["uv"], {s_: v_ for s_, v_ in eye.items() if closure[s_] <= 0.05}, sh["lash"])
                keep_lash_fan(self.prims, now, k_, eye, closure)
                for side, (up, others, edge, _) in eye.items():   # a shut eye is one closed lid:
                    if closure[side] < 0.9:
                        continue
                    if others:                                  # its lower line goes,
                        p_["tri"] = p_["tri"][~np.isin(p_["tri"], np.concatenate(others)).all(1)]
                    m = np.isin(p_["tri"], up).all(1)           # and its lash is drawn solid (export_glb.fill_lid):
                    self.prims.append(dict(p_, tri=p_["tri"][m], lid_fill=float(p_["uv"][edge, 1].max())))
                    p_["tri"] = p_["tri"][~m]                   # the open lash's pale streaks and hollows read as
                                                                # shine beside an eye, but split a lid over skin
            if hair_from:                                    # swap in another model's hair
                hv = VRM(hair_from)
                hp = hv.primitives(None, ref_pose)
                hroles = [role_of(p["material"]) for p in hp]
                src = landmarks(hp, hroles)
                dst = landmarks(self.prims, [role_of(p["material"]) for p in self.prims])
                k = (abs(dst["eyeR"][0] - dst["eyeL"][0]) / abs(src["eyeR"][0] - src["eyeL"][0])
                     + (dst["eye_y"] - dst["chin"][1]) / (src["eye_y"] - src["chin"][1])) / 2
                c_src = (src["eyeL"] + src["eyeR"]) / 2
                c_dst = (dst["eyeL"] + dst["eyeR"]) / 2
                hair = [p for p in hp if "_HAIR" in p["material"]]
                for p in hair:
                    p["pos"] = c_dst + (p["pos"] - c_src) * k
                    n_ = len(p["pos"])                       # rides our head bone from here on
                    p["J"], p["W"], p["jnames"] = np.zeros((n_, 4), np.int64), np.tile([1.0, 0, 0, 0], (n_, 1)), ["J_Bip_C_Head"]
                self.prims = [p for p in self.prims if "_HAIR" not in p["material"]] + hair
                self._hair_v = hv
            if hair_trim:                                    # drop hair pieces reaching past |x| = hair_trim (e.g. twin tails)
                self.prims = [p for p in self.prims if "_HAIR" not in p["material"]
                              or np.abs(p["pos"][np.unique(p["tri"]), 0]).max() <= hair_trim]
            self.roles = [p.get("role") or role_of(p["material"]) for p in self.prims]
            for side, c in eye_closure(mo).items():          # a shut eye shows no white (it can poke between the lids)
                if c < 0.9:
                    continue
                for p, r in zip(self.prims, self.roles):
                    if r == "white" and len(p["tri"]):
                        cx = p["pos"][p["tri"]].mean(1)[:, 0]
                        p["tri"] = p["tri"][(cx < 0) != (side == "L")]
            self.lm = landmarks(self.prims, self.roles)
            if costume:                                      # replace VRoid's clothes with ours
                import outfit
                fit = outfit.Fit(self.v, pose, self.prims, self.roles)
                import rig
                fit.grip = rig.grip_points(self.v, sh, ref_pose)  # where each fist closes (weapons sit there)
                keep_ = [k for k, r in enumerate(self.roles) if r != "cloth"]
                self.prims = [self.prims[k] for k in keep_]
                self.roles = [self.roles[k] for k in keep_]
                costume = outfit.COSTUMES[costume] if isinstance(costume, str) else costume
                fit.keep_skin = ()                       # a costume may leave skin bare (fit.keep_skin = bones)
                for pc in costume(fit):
                    self.prims.append(pc)
                    self.roles.append(pc["role"])
            # body skin below the neck is always under clothes in a bust; drop it so it can't poke through
            cy = self.lm["chin"][1]
            from vrm import bone_weight
            for p, r in zip(self.prims, self.roles):
                if r != "body":
                    continue
                if costume:                     # keep head, neck and upper chest (the throat shows in the collar opening)
                    wv = bone_weight(p, ("Head", "Neck", "UpperChest") + tuple(getattr(fit, "keep_skin", ())))
                    p["tri"] = p["tri"][(wv[p["tri"]] >= 0.5).all(1)]
                    if getattr(fit, "drop_skin", None) is not None:      # a costume may hide the skin it covers
                        p["tri"] = p["tri"][~fit.drop_skin(p)[p["tri"]].all(1)]
                else:
  • Bashcd ~/Projects/lowmarch-fable52 && sed -n 163,232p tools/outfit.py; grep -n "^def landmarks" -A30 tools/vroid_portrait.py | head -50

    command

    cd ~/Projects/lowmarch-fable52 && sed -n 163,232p tools/outfit.py; grep -n "^def landmarks" -A30 tools/vroid_portrait.py | head -50

    result, 101 lines

    class Fit:
        """What a costume is built against: the body skin (welded, measurable) and the bones, all in
        the reference pose, plus the skin weights so pieces can be bound to the skeleton."""
    
        def __init__(self, vrm, pose, prims, roles):
            self._prims, self._roles = prims, roles
            W = vrm.node_world(pose)
            names = vrm.nodes_by_name()
            self.world = {k: W[i].copy() for k, i in names.items() if k}
            self.bone = {k: m[:3, 3].copy() for k, m in self.world.items()}
            skin = [p for p, r in zip(prims, roles) if r == "body"]
            self.body = skin[0]
            self.pos = self.body["pos"]
            self.J, self.W, self.jnames = self.body["J"], self.body["W"], self.body["jnames"]
            self.tri = weld(self.pos, np.concatenate([p["tri"] for p in skin]))
            self.surf = Surface(self.pos, self.tri)
            self.skin = self.pos[np.unique(self.tri)]
            # MakeHuman bodies (tools/makehuman.py) have real muscle relief; VRoid's limbs are smooth tubes
            self.cloth_hull = vrm.j.get("asset", {}).get("generator", "").startswith("lowmarch makehuman") \
                and not os.environ.get("LOWMARCH_NO_HULL")
    
        def head_surface(self):
            """The head's skin (face and scalp), for charts over the skull (tools/hair.py)."""
            from vrm import bone_weight
            pos, tri, off = [], [], 0
            for p, r in zip(self._prims, self._roles):
                if r in ("face", "body") and "J" in p and len(p["tri"]):
                    w = bone_weight(p, ("Head",))
                    T = p["tri"][(w[p["tri"]] > 0.5).all(1)]
                    if len(T):
                        pos.append(p["pos"])
                        tri.append(T + off)
                        off += len(p["pos"])
            return Surface(np.concatenate(pos), np.concatenate(tri))
    
        def weight(self, bones):
            hit = np.array([any(b in n for b in bones) for n in self.jnames])
            return (hit[self.J] * self.W).sum(1)
    
        def tris_for(self, bones, min_w=0.5, exclude=(), y_min=None, y_max=None):
            w = self.weight(bones)
            if exclude:
                w = w - self.weight(exclude)
            T = self.tri[(w[self.tri] >= min_w).all(1)]
            tp = self.pos[T]
            sel = np.ones(len(T), bool)
            if y_min is not None:
                sel &= tp[:, :, 1].min(1) > y_min
            if y_max is not None:
                sel &= tp[:, :, 1].max(1) < y_max
            return T[sel]
    
        def bind(self, pc, allow=None, fallback=None, rigid=None, blend=None, surface=None):
            """Attach skin weights to a piece: copied from the body under it (optionally limited to
            some bones), or rigid on one bone / a fixed blend."""
            if pc is None:
                return None
            n = len(pc["pos"])
            if rigid or blend:
                pc["J"], pc["W"] = rigid_weights(n, self.jnames, rigid, blend)
            else:
                pc["J"], pc["W"] = transfer_weights(pc["pos"], None, self.J, self.W, surface=surface or self.surf,
                                                    allow=allow, jnames=self.jnames, fallback=fallback)
            pc["jnames"] = self.jnames
            return pc
    
    
    def without(pc, bones, max_w=0.3):
        """A piece's triangles away from some bones, as (pos, tri) for merge_surfaces: a bodice's torso
        without its sleeves. Casting a waist ring onto a garment with its sleeves in it catches the
    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):
    301-        """Outermost face point at height y on one side (-1 = character's left, -x)."""
    302-        row = window(pts, y, lambda q, t: np.sign(q[:, 0]) == side)
    303-        return row[np.argmax(np.abs(row[:, 0]))]
    304-
  • Bashcd ~/Projects/lowmarch-fable52 && OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 - <<'E'

    command

    cd ~/Projects/lowmarch-fable52 && OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 - <<'E'
    import sys,os,time
    sys.argv=["x"]
    sys.path.insert(0,"tools/whole")
    os.environ["LOWMARCH_SITE"]="whole-scratch"
    import importlib.util
    s=importlib.util.spec_from_file_location('wb','tools/whole/build.py'); wb=importlib.util.module_from_spec(s); s.loader.exec_module(wb)
    import numpy as np, vroid_portrait as vp
    from cast import CAST
    c=CAST["wren"]
    t=time.time()
    p=vp.Portrait(wb.build.model_path("wren",c), shape=c["shape"], costume=None, pose=vp.BUST_POSE)
    print("portrait",round(time.time()-t,1),"s")
    print({k:(np.round(v,3).tolist() if hasattr(v,'tolist') else v) for k,v in p.lm.items() if k in("eyeL","eyeR","eye_y","chin","nose","brow_y","top")}, list(p.lm.keys()))
    for q,r in zip(p.prims,p.roles):
        P=q["pos"][np.unique(q["tri"])] if len(q["tri"]) else q["pos"]
        print(r, q["material"][:40], len(q["pos"]), len(q["tri"]), np.round(P.min(0),3), np.round(P.max(0),3), sorted(set(q.get("jnames",[])))[:0])
    hb=p.v.nodes_by_name()
    import pickle
    print(sorted(k for k in p.prims[0].keys()))
    E

    result, 15 lines

    portrait 1.7 s
    {'eyeL': [-0.036, 1.524, -0.111], 'eyeR': [0.037, 1.524, -0.111], 'eye_y': 1.524, 'chin': [-0.0, 1.434, -0.11], 'nose': [-0.0, 1.492, -0.142]} ['eyeL', 'eyeR', 'eye_y', 'chin', 'mouth', 'nose', 'span', 'gonionL', 'cheekL', 'chinsideL', 'ridgeL', 'wingL', 'earL', 'gonionR', 'cheekR', 'chinsideR', 'ridgeR', 'wingR', 'earR', 'crown', 'occiput', 'forehead', 'neck_front', 'neck_back']
    mouth N00_000_00_FaceMouth_00_FACE (Instance) 4286 1696 [-0.022  1.456 -0.128] [ 0.022  1.48  -0.092] []
    iris N00_000_00_EyeIris_00_EYE (Instance) 4286 435 [-0.051  1.509 -0.116] [ 0.051  1.537 -0.105] []
    highlight N00_000_00_EyeHighlight_00_EYE (Instance 4286 145 [-0.05   1.514 -0.116] [ 0.052  1.53  -0.104] []
    face N00_000_00_Face_00_SKIN (Instance) 4286 4232 [-0.101  1.434 -0.142] [ 0.101  1.65  -0.01 ] []
    white N00_000_00_EyeWhite_00_EYE (Instance) 4286 528 [-0.066  1.507 -0.117] [ 0.066  1.538 -0.095] []
    brow N00_000_00_FaceBrow_00_FACE (Instance) 4286 92 [-0.071  1.53  -0.128] [ 0.071  1.555 -0.103] []
    line N00_000_00_FaceEyelash_00_FACE (Instance 4286 90 [-0.069  1.521 -0.123] [ 0.069  1.53  -0.1  ] []
    line N00_000_00_FaceEyeline_00_FACE (Instance 4286 220 [-0.076  1.507 -0.125] [ 0.076  1.543 -0.098] []
    body N00_000_00_Body_00_SKIN (Instance) 7338 1294 [-0.085  1.299 -0.114] [0.085 1.656 0.067] []
    hair N00_000_Hair_00_HAIR lm 23222 28576 [-0.159  1.151 -0.156] [0.168 1.675 0.181] []
    hair N00_000_00_HairBack_00_HAIR lm 23222 1296 [-0.09   1.461 -0.123] [0.09  1.662 0.067] []
    shadow SHADOW_nose 60 84 [-0.005  1.486 -0.142] [ 0.005  1.49  -0.138] []
    ['J', 'W', 'jnames', 'material', 'mesh', 'mi', 'nrm', 'pos', 'tri', 'uv']
  • Bashcd ~/Projects/lowmarch-fable52 && cat > [redacted: private path]/scratchpad/hairprobe.py <<'E'

    command

    cd ~/Projects/lowmarch-fable52 && cat > [redacted: private path]/scratchpad/hairprobe.py <<'E'
    import sys,os,time
    sys.argv=["x"]
    sys.path.insert(0,"tools/whole")
    os.environ["LOWMARCH_SITE"]="whole-scratch"
    import importlib.util
    s=importlib.util.spec_from_file_location('wb','tools/whole/build.py'); wb=importlib.util.module_from_spec(s); s.loader.exec_module(wb)
    import numpy as np, vroid_portrait as vp
    from cast import CAST
    c=CAST["wren"]
    p=vp.Portrait(wb.build.model_path("wren",c), shape=c["shape"], costume=None, pose=vp.BUST_POSE)
    h=[q for q,r in zip(p.prims,p.roles) if r=="hair"][0]
    P=h["pos"]
    for zc in (-0.085,-0.10,-0.12):
        row=[]
        for x0 in np.arange(-0.09,0.0901,0.015):
            m=(np.abs(P[:,0]-x0)<0.0075)&(P[:,2]<zc)&(P[:,1]>1.40)
            row.append(f"{P[m,1].min():.3f}" if m.any() else "  -  ")
        print(zc, " ".join(row))
    print("jnames", [n for n in h["jnames"] if "Hair" in n][:12], len(h["jnames"]))
    # which bones weight the front region
    m=(np.abs(P[:,0])<0.06)&(P[:,2]<-0.09)&(P[:,1]<1.60)
    J=h["J"][m]; W=h["W"][m]
    import collections
    cnt=collections.Counter()
    for j,w in zip(J.reshape(-1),W.reshape(-1)):
        if w>0.2: cnt[h["jnames"][j]]+=1
    print(cnt.most_common(12))
    E
    OMP_NUM_THREADS=1 python3 [redacted: private path]/scratchpad/hairprobe.py

    result, 5 lines

    -0.085 1.497 1.436 1.439 1.441 1.524 1.523 1.523 1.523 1.525 1.439 1.437 1.437 1.463
    -0.1 1.508 1.492 1.449 1.441 1.524 1.523 1.523 1.523 1.525 1.439 1.448 1.471 1.523
    -0.12   -     -   1.523 1.526 1.524 1.523 1.523 1.523 1.525 1.526 1.523   -     -  
    jnames ['J_Sec_Hair1_01', 'J_Sec_Hair2_01', 'J_Sec_Hair3_01', 'J_Sec_Hair1_02', 'J_Sec_Hair2_02', 'J_Sec_Hair3_02', 'J_Sec_Hair1_03', 'J_Sec_Hair2_03', 'J_Sec_Hair3_03', 'J_Sec_Hair1_04', 'J_Sec_Hair2_04', 'J_Sec_Hair3_04'] 221
    [('J_Bip_C_Head', 471), ('J_Sec_Hair1_03', 138), ('J_Sec_Hair2_01', 130), ('J_Sec_Hair1_01', 126), ('J_Sec_Hair1_06', 114), ('J_Sec_Hair2_03', 100), ('J_Sec_Hair1_05', 88), ('J_Sec_Hair1_04', 84), ('J_Sec_Hair1_02', 84), ('J_Sec_Hair2_06', 80), ('J_Sec_Hair2_02', 79), ('J_Sec_Hair2_05', 70)]

agent

+38:37

Measured the fringe: it ends exactly at eye-centre height, which is why her eyes were hidden. Reading a few more kit functions, then writing her new costume file.

  • Bashcd ~/Projects/lowmarch-fable52 && sed -n 60,126p tools/mobs.py; sed -n 745,830p tools/gear.py; sed -n 926,943p tools/gear.py; grep -n "^SKINS" -A10 art/cast/cast.py | head -14

    command

    cd ~/Projects/lowmarch-fable52 && sed -n 60,126p tools/mobs.py; sed -n 745,830p tools/gear.py; sed -n 926,943p tools/gear.py; grep -n "^SKINS" -A10 art/cast/cast.py | head -14

    result, 182 lines

                              exclude=("Shoulder", "Arm", "Hand", "Thumb", "Index", "Middle", "Ring", "Little"),
                              hems=[((0, 1, 0), bhi - 0.005), ((0, -1, 0), -(blo + 0.005))], refloor=True, clamp=True))
        out = [p for p in out if p is not None]
        for p in out:
            p["group"] = "underwear"
        fit.keep_skin = ("J_",)                          # bare everywhere else: keep all the skin (VRoid 2 weights some to J_Sec_ bones)
        # but not the skin well inside the shorts: on fitted bodies (tools/fit.py) it came through the waistband.
        # Never the arms', which hang beside the hips in the fitting pose
        arms = ("Shoulder", "Arm", "Hand", "Thumb", "Index", "Middle", "Ring", "Little")
        fit.drop_skin = lambda p: ((p["pos"][:, 1] > lo + 0.015) & (p["pos"][:, 1] < hi - 0.015)
                                   & (bone_weight(p, arms) < 0.05))
        return out
    
    
    def underwear_f(fit):
        return underwear(fit, band=True)
    
    
    def _under(shirt):
        return Surface(*O.without(shirt, ("Shoulder", "UpperArm", "LowerArm", "Hand")))
    
    
    def _surf(pcs, *names, prefix=False):
        sel = [p for p in pcs if (p["material"].startswith(tuple("OUTFIT_" + n for n in names)) if prefix
                                  else p["material"] in tuple("OUTFIT_" + n for n in names))]
        return merge_surfaces(*[(p["pos"], p["tri"]) for p in sel])
    
    
    def soldier(fit, legs="breeches"):
        """Halberd infantry, after the study's Soldier: a kettle hat, a doublet in the army colour with
        full sleeves bagging into gauntlets that reach almost to the elbow, a short breastplate with a
        plackart (full width to the armpits), a fauld of round scales to mid-thigh, a belt, a halberd
        held in both hands (the cast's polearm stance, tools/clips.py). No puff or band on the upper arm:
        the study's soldiers have neither, and on a real arm a puff read as a bicep.
        legs: "breeches" (baggy, bagging over calf boots: the study's men) or "tights" (with boots to
        above the knee: the study's women)."""
        B = fit.bone
        hips = B["J_Bip_C_Hips"]
        knee = B["J_Bip_L_LowerLeg"][1]
        gauntlet = 0.70                                         # of the forearm, from the wrist
        y_hem = hips[1] - 0.20                                  # the fauld's
        boot_top = knee + 0.08 if legs == "tights" else knee - 0.07
        out, shirt, trousers, boots = _base(fit, shirt="signature", legs="cloth", boots="boot", shirt_subdiv=1,
                                            boot_top=boot_top)
        G.loose_sleeves(fit, shirt, cuff=gauntlet)
        if legs == "breeches":
            G.breeches(fit, trousers, boots, y_hem, boot_top - 0.005)
        else:
            G.flare_boots(fit, boots, boot_top - 0.005, ease=0.008)
        under = _under(shirt)
        out += G.breastplate(fit, under, arm=64.0)
        plate = _surf(out, "breastplate", prefix=True)
        # the guard's wide stance: the fauld follows the thighs closely and clears the seat
        out += G.scale_skirt(fit, under, hips[1] + 0.06, y_hem, role="mail", share=0.15,
                             clear=Surface(trousers["pos"], trousers["tri"]))
        G.slim_under(fit, trousers, y_hem)                      # and what it hides can't come through it
        belt, front = O.belt(fit, "belt", "leather", plate, hips[1] + 0.05, height=0.034, offset=0.004)
        out.append(belt)
        cuffs = G.cuffs(fit, length=gauntlet, flare=0.034)
        G.tuck_sleeves(fit, shirt, cuffs)
        out += cuffs
        out += G.coif(fit, role="padding")
        out += G.helmet(fit, "kettle")
        out += G.halberd(fit, grip=0.50)                         # the rear hand near the butt, as the study holds it
        return out
    
    
    def _leg_s(fit, y):
        """A height on the (left) leg as _limb_frame's distance along it: 0 at the hip joint, 1 at the knee,
        2 at the ankle (the reference pose stands straight)."""
        B = fit.bone
        h, k, a = (float(B[f"J_Bip_L_{n}"][1]) for n in LIMBS["leg"])
        return (h - y) / (h - k) if y > k else 1 + (k - y) / (k - a)
    
    
    def flare_boots(fit, boots, y_top, ease=0.010):
        """Boot tops that stand a little off the leg (leather, not a stocking), easing back over a third of
        the shin. Changes `boots` in place."""
        s_b = _leg_s(fit, y_top)
        return _let_out(fit, boots, "leg", [s_b - 0.05, s_b + 0.01, s_b + 0.30, 2.2], [1.0, 1.0, 0.0, 0.0], ease, folds=5,
                        toward=0.5, behind=0.0, fold_amp=(0.12, 0.0), size=0.42)
    
    
    def breeches(fit, trousers, boots, y_hem, y_boot, ease=0.040, folds=7):
        """Baggy breeches after the study's soldiers: the trousers let out below the fauld's hem (y_hem),
        fullest just above the boot top (y_boot) where they bag over it, less on the inner thigh, with
        folds down the leg; the boots' tops flare a little, and the breeches are drawn inside them.
        Changes `trousers` and `boots` in place."""
        s_f, s_b = _leg_s(fit, y_hem), _leg_s(fit, y_boot)
        flare_boots(fit, boots, y_boot)
        _let_out(fit, trousers, "leg", [-0.3, s_f - 0.02, s_f + 0.16, 0.85, s_b - 0.12, s_b - 0.02, s_b + 0.10, 2.2],
                 [0.0, 0.12, 0.6, 0.92, 1.0, 1.0, 0.0, 0.0], ease, folds, toward=0.6, behind=0.1, fold_amp=(0.15, 0.25),
                 fold_from=0.5, size=0.42)
        _tuck(fit, trousers, [boots], "leg", gap=0.004, both=True, span=(1.0, 1.95))
        return trousers, boots
    
    
    def slim_under(fit, trousers, y_hem, pull=0.018, ramp=0.05):
        """Trousers drawn in toward the thigh bones where a skirt hides them (above y_hem, easing back to
        full width over `ramp` above the hem). A stiff skirt follows the hips more than the thighs, and in
        a wide stance or a lunge the thighs swing out through it; slimmer under it, they clear it. The
        skin under the trousers is culled, so nothing else shows. Changes `trousers` in place."""
        P = trousers["pos"]
        for side in ("L", "R"):
            hit = np.array([n == f"J_Bip_{side}_UpperLeg" for n in trousers["jnames"]])
            w = (hit[trousers["J"]] * trousers["W"]).sum(1)
            sel = np.nonzero(w > 0.05)[0]
            if not len(sel):
                continue
            _, u, r, _, _ = _limb_frame(fit, side, P[sel], "leg")
            k = np.clip((P[sel, 1] - y_hem) / ramp, 0, 1)
            k = k * k * (3 - 2 * k)
            d = np.minimum(pull * k * np.clip(w[sel], 0, 1), np.maximum(r - 0.03, 0))
            P[sel] -= u * d[:, None]
        trousers["nrm"] = O.vertex_normals(P, trousers["tri"])
        return trousers
    
    
    def breastplate(fit, under, role="steel", name="breastplate", y_top=None, y_bottom=None, plackart=True, keel=0.008,
                    back=True, arm=54.0):
        """A breastplate (and backplate) as outline plates: a scooped neckline, armholes cut away at the
        sides, a slight point at the waist, a central ridge, rolled edges; a plackart over the belly.
        arm: where the armhole's scoop begins (degrees round the torso from the front); larger keeps the
        plate's full width up to the armpits instead of a bib over the middle of the chest."""
        B = fit.bone
        nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"]
        y_top = nk[1] - 0.05 if y_top is None else y_top
        y_bottom = hips[1] + 0.03 if y_bottom is None else y_bottom
        cz = float(hips[2])
        tc = TorsoChart(under, y_bottom - 0.04, y_top + 0.04, cz=cz, du=2.5, dv=0.007)
        span = y_top - y_bottom
        top = lambda u: y_top - 0.035 * max(0.0, 1 - abs(u) / 34) ** 1.4 - 0.11 * span * max(0.0, (abs(u) - arm) / 42) ** 1.3
        bottom = lambda u: y_bottom - 0.018 * max(0.0, 1 - abs(u) / 40) ** 1.5
        ridge = lambda u, v, s, t: keel * math.exp(-(u / 9.0) ** 2) * math.sin(math.pi * min(1.0, t * 1.15))
        front, fx = outline_plate(name, role, tc, -96, 96, bottom, top, offset=0.014, crown=0.010, flare=ridge, thickness=0.004,
                                  nu=72, nv=26, roll=0.0034, roll_edges=("top", "bottom"))
        fit.bind(front, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips"), fallback="J_Bip_C_Chest")
        out = [front] + [O.inherit(p, front) for p in fx]
        if back:
            btop = lambda u: y_top - 0.01 - 0.11 * span * max(0.0, (abs(((u % 360) - 180)) - (arm - 4)) / 44) ** 1.3
            bk, bx = outline_plate(f"{name}_back", role, tc, 96, 264, lambda u: y_bottom, btop, offset=0.014, crown=0.006,
                                   thickness=0.004, nu=60, nv=22, roll=0.0034, roll_edges=("top", "bottom"))
            fit.bind(bk, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips"), fallback="J_Bip_C_Chest")
            out += [bk] + [O.inherit(p, bk) for p in bx]
        if plackart:                                            # over the belly, its top rounded up to a point
            ptop = lambda u: y_bottom + 0.36 * span - 0.10 * span * (abs(u) / 50) ** 1.6
            pl, px = outline_plate(f"{name}_plackart", role, tc, -50, 50, bottom, ptop, offset=0.020, crown=0.008, flare=ridge,
                                   thickness=0.004, nu=40, nv=12, roll=0.0034, roll_edges=("top",),
                                   rivets=(0.05, 0.010, 0.0035), rivet_role=role)
            fit.bind(pl, allow=("Spine", "Chest", "Hips"), fallback="J_Bip_C_Spine")
            out += [pl] + [O.inherit(p, pl) for p in px]
        return _group(out, "plate")
    
    def cuffs(fit, role="glove", name="cuff", length=0.38, flare=0.030, lift=0.010):
        """Big flared gauntlet cuffs over the lower forearm (oversized, as the study's units wear them)."""
        B = fit.bone
        out = []
        for side in ("L", "R"):
            la, hd = B[f"J_Bip_{side}_LowerArm"], B[f"J_Bip_{side}_Hand"]
            fore = O.limb_surface(fit, (f"{side}_LowerArm",), side)
            lc = LimbChart(fore, la, hd, front=(0, 0, -1))
            pc, ex = outline_plate(f"{name}_{side}", role, lc, -180, 180, lambda u: 1.04, lambda u: 1.0 - length, offset=lift,
                                   flare=lambda u, v, s, t: flare * t ** 1.5, thickness=0.005, nu=40, nv=10, roll=0.004,
                                   roll_edges=("top",))
            fit.bind(pc, rigid=f"J_Bip_{side}_LowerArm")
            for p in ex:
                fit.bind(p, rigid=f"J_Bip_{side}_LowerArm")
            out += [pc] + ex
        return _group(out, "gloves")
    
    
    26:SKINS = {"light": None, "fair": "#f4dccb", "tan": "#e3bf9c", "olive": "#d6b08a", "brown": "#b08060",
    27-         "dark": "#8a5e44", "pale": "#f6e6e2",           # the mobs' older tones, kept as they were
    28-         # the skin range (2026-10-30): the lit colour of each tone; tools/export_glb.py skin_ramp derives its shade
    29-         # and deep shade. People, light to deep, undertones in the names:
    30-         "porcelain": "#f9e8e1", "ivory": "#f8e1d5", "peach": "#f4d3bd", "sand": "#e7c3a0", "honey": "#d9aa7d",
    31-         "olive_mid": "#c8a881", "amber": "#c18b5e", "caramel": "#a87047", "chestnut": "#8b5638", "umber": "#6e4129",
    32-         "mahogany": "#5a3122", "ebony": "#432a1f",
    33-         # fantasy
    34-         "drow_ash": "#6d6888", "drow_slate": "#4a4560", "ashen": "#b8b5ad", "orc": "#7e9659", "orc_deep": "#566c3e",
    35-         "sea": "#6f97c3", "infernal": "#b25648"}
    36-