Subagent: Model export and lens shot

agent (cont.)

+0:12
  • Read[redacted: private path]/tool-results/bu5i6w1hv.txt

    input

    {
      "file_path": "[redacted: private path]/tool-results/bu5i6w1hv.txt"
    }

    result, 568 lines

    1	"""Export a composed character (VRoid base + our shapes, costume, props, scenery) to GLB for the
    2	browser 3D viewer.
    3	
    4	Each primitive becomes a mesh named by its group (body, hair, costume pieces, sword, terrain) so
    5	the viewer can toggle and x-ray them. Face, eye, line, brow, mouth and hair keep VRoid's textures
    6	(downscaled) for alpha and detail; everything else gets the character's palette colour. The model
    7	is turned to face +z, the direction a default three.js camera looks from.
    8	"""
    9	import io
    10	import math
    11	import json
    12	import struct
    13	
    14	import numpy as np
    15	from PIL import Image
    16	
    17	FLIP = np.array([-1.0, 1.0, -1.0])
    18	TEXTURED = ("face", "iris", "white", "highlight", "line", "brow", "mouth", "hair")
    19	ROLE_TONE = {"face": "5", "body": "4", "shadow": "3", "hair": "D", "brow": "B", "coat": "M", "cape": "W", "metal": "8",
    20	             "signature": "M", "doublet": "S", "heraldry": "N",
    21	             "steel": "8", "gold": "H", "leather": "v", "boot": "v", "glove": "x", "cloth": "M",
    22	             "grass": "c", "dirt": "f", "stone": "l", "mouth": "2", "line": "o", "iris": "s", "white": "w",
    23	             "highlight": "w"}
    24	
    25	
    26	def group_of(p, role):
    27	    if p.get("world"):
    28	        return "terrain"
    29	    if p.get("group"):
    30	        return p["group"]
    31	    if role in ("face", "body", "shadow", "iris", "white", "highlight", "line", "brow", "mouth"):
    32	        return "body"
    33	    if role == "hair":
    34	        return "hair"
    35	    name = p["material"].replace("OUTFIT_", "")
    36	    for key in ("trim", "edge", "hem", "placket", "buckle", "clasp"):
    37	        if key in name:
    38	            return "trim"
    39	    for key in ("pauldron", "cape", "collar", "tunic", "tails", "belt", "trousers", "boots", "gloves"):
    40	        if name.startswith(key):
    41	            return key
    42	    if name in ("blade", "guard", "grip", "pommel", "fuller"):
    43	        return "sword"
    44	    return "costume"
    45	
    46	
    47	def skin_ramp(h):
    48	    """A skin tone's lit, shade and deep-shade colours from its lit colour. The shade is darker and a little more
    49	    saturated, its hue nudged toward red on human tones (so deep skin stays rich and warm, not ashy) and toward
    50	    violet on the fantasy blues, greens and greys. Hex strings, light to dark."""
    51	    import colorsys
    52	    r, g, b = (int(h[i:i + 2], 16) / 255 for i in (1, 3, 5))
    53	    hue, sat, val = colorsys.rgb_to_hsv(r, g, b)
    54	    warm = hue < 0.17 or hue > 0.9
    55	    dh = -0.015 if warm else (0.025 if hue < 0.75 else -0.025)
    56	
    57	    def tone(k, dv, ds):
    58	        rr, gg, bb = colorsys.hsv_to_rgb((hue + k * dh) % 1.0, min(1.0, sat + (1 - sat) * ds), val * dv)
    59	        return "#%02x%02x%02x" % tuple(int(round(c * 255)) for c in (rr, gg, bb))
    60	    return [h, tone(1, 0.80, 0.12), tone(2, 0.50, 0.22)]
    61	
    62	
    63	def hex_rgb(h):
    64	    h = h.lstrip("#")
    65	    return [int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)]
    66	
    67	
    68	def export(portrait, palette, path, max_tex=512, only_world=False):
    69	    """portrait: vroid_portrait.Portrait. palette: full char -> hex map. only_world: export just
    70	    the scenery (the character goes out skinned through export_skinned)."""
    71	    bin_ = bytearray()
    72	    views, accessors, meshes, nodes, materials, textures, images = [], [], [], [], [], [], []
    73	    tex_index = {}
    74	
    75	    def add_view(data, target=None):
    76	        while len(bin_) % 4:
    77	            bin_.append(0)
    78	        off = len(bin_)
    79	        bin_.extend(data)
    80	        v = dict(buffer=0, byteOffset=off, byteLength=len(data))
    81	        if target:
    82	            v["target"] = target
    83	        views.append(v)
    84	        return len(views) - 1
    85	
    86	    def add_acc(arr, kind, comp, target):
    87	        arr = np.ascontiguousarray(arr)
    88	        vi = add_view(arr.tobytes(), target)
    89	        a = dict(bufferView=vi, componentType=comp, count=int(arr.shape[0]), type=kind)
    90	        if kind == "VEC3" and comp == 5126:
    91	            a["min"] = arr.min(0).tolist()
    92	            a["max"] = arr.max(0).tolist()
    93	        accessors.append(a)
    94	        return len(accessors) - 1
    95	
    96	    def add_texture(key, rgba):
    97	        if key in tex_index:
    98	            return tex_index[key]
    99	        im = Image.fromarray(rgba)
    100	        if max(im.size) > max_tex:
    101	            k = max_tex / max(im.size)
    102	            im = im.resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS)
    103	        b = io.BytesIO()
    104	        im.save(b, "PNG", optimize=True)
    105	        vi = add_view(b.getvalue())
    106	        images.append(dict(bufferView=vi, mimeType="image/png"))
    107	        textures.append(dict(source=len(images) - 1, sampler=0))
    108	        tex_index[key] = len(textures) - 1
    109	        return tex_index[key]
    110	
    111	    for k, (p, role) in enumerate(zip(portrait.prims, portrait.roles)):
    112	        if role == "skip" or not len(p["tri"]) or (only_world and not p.get("world")):
    113	            continue
    114	        used, inv = np.unique(p["tri"], return_inverse=True)
    115	        pos = (p["pos"][used] * FLIP).astype(np.float32)
    116	        nrm = p["nrm"][used] * FLIP
    117	        nrm = (nrm / np.maximum(np.linalg.norm(nrm, axis=1, keepdims=True), 1e-9)).astype(np.float32)
    118	        tri = inv.reshape(-1, 3).astype(np.uint32)               # FLIP is a 180-degree turn: winding holds
    119	        attrs = dict(POSITION=add_acc(pos, "VEC3", 5126, 34962), NORMAL=add_acc(nrm, "VEC3", 5126, 34962))
    120	        mat = dict(name=f"{group_of(p, role)}:{role}", doubleSided=True,
    121	                   pbrMetallicRoughness=dict(metallicFactor=0.0, roughnessFactor=0.9))
    122	        tone = ROLE_TONE.get(role)
    123	        color = hex_rgb(palette[tone]) if tone in palette else [0.8, 0.8, 0.8]
    124	        tex = portrait.tex.get(k)
    125	        if role == "face":
    126	            tex = portrait.v.material_texture(p["mi"])
    127	        if role in TEXTURED and tex is not None:
    128	            uv = p["uv"][used].astype(np.float32)
    129	            attrs["TEXCOORD_0"] = add_acc(uv, "VEC2", 5126, 34962)
    130	            src = portrait._hair_v if role == "hair" and getattr(portrait, "_hair_v", None) is not None \
    131	                and "_HAIR" in p["material"] else portrait.v
    132	            raw = src.material_texture(p["mi"])
    133	            mat["pbrMetallicRoughness"]["baseColorTexture"] = dict(index=add_texture((id(src), p["mi"], role), raw))
    134	            if role == "hair":                        # strands are grey in the texture: tint them
    135	                mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0]
    136	            if role in ("hair", "line", "brow", "iris", "highlight"):
    137	                mat["alphaMode"] = "MASK"
    138	                mat["alphaCutoff"] = 0.5
    139	        else:
    140	            mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0]
    141	        if role in ("metal", "steel", "gold"):
    142	            mat["pbrMetallicRoughness"].update(metallicFactor=0.6, roughnessFactor=0.35)
    143	        materials.append(mat)
    144	        meshes.append(dict(name=group_of(p, role), primitives=[dict(
    145	            attributes=attrs, indices=add_acc(tri.reshape(-1), "SCALAR", 5125, 34963), material=len(materials) - 1)]))
    146	        nodes.append(dict(name=f"{group_of(p, role)}/{p['material']}", mesh=len(meshes) - 1,
    147	                          extras=dict(group=group_of(p, role), role=role, world=bool(p.get("world")), material=p["material"])))
    148	    gltf = dict(asset=dict(version="2.0", generator="lowmarch export_glb"), scene=0,
    149	                scenes=[dict(nodes=list(range(len(nodes))))], nodes=nodes, meshes=meshes, materials=materials,
    150	                accessors=accessors, bufferViews=views, buffers=[dict(byteLength=len(bin_))],
    151	                samplers=[dict(magFilter=9729, minFilter=9987)])
    152	    if textures:
    153	        gltf.update(textures=textures, images=images)
    154	    js = json.dumps(gltf, separators=(",", ":")).encode()
    155	    js += b" " * ((4 - len(js) % 4) % 4)
    156	    while len(bin_) % 4:
    157	        bin_.append(0)
    158	    out = struct.pack("<4sII", b"glTF", 2, 12 + 8 + len(js) + 8 + len(bin_))
    159	    out += struct.pack("<I4s", len(js), b"JSON") + js + struct.pack("<I4s", len(bin_), b"BIN\x00") + bytes(bin_)
    160	    open(path, "wb").write(out)
    161	    return len(out)
    162	
    163	
    164	# ---- data for the real-time viewer ----------------------------------------------------------
    165	CAPSULES = [("J_Bip_C_Hips", "J_Bip_C_Spine"), ("J_Bip_C_Spine", "J_Bip_C_Chest"),
    166	            ("J_Bip_C_Chest", "J_Bip_C_UpperChest"), ("J_Bip_C_UpperChest", "J_Bip_C_Neck"),
    167	            ("J_Bip_C_Neck", "J_Bip_C_Head")] + \
    168	           [(f"J_Bip_{s}_{a}", f"J_Bip_{s}_{b}") for s in "LR" for a, b in
    169	            (("UpperArm", "LowerArm"), ("LowerArm", "Hand"), ("UpperLeg", "LowerLeg"), ("LowerLeg", "Foot"))]
    170	# simulated cloth: piece -> (its static trims, hidden while the cloth simulates; the role whose colour
    171	# the simulated border band takes; the bones whose colliders it meets, None for all). Panels hanging
    172	# from the belt meet the legs only: the hip collider's round end pushes them out behind.
    173	LEGS = ("UpperLeg", "LowerLeg")
    174	CLOTH = {"OUTFIT_cape": (("OUTFIT_cape_trim", "OUTFIT_cape_hem", "OUTFIT_cape_edge0", "OUTFIT_cape_edge1"), "gold", None),
    175	         "OUTFIT_tails": (("OUTFIT_tails_hem",), "gold", LEGS),
    176	         "OUTFIT_tabard": (("OUTFIT_tabard_hem", "OUTFIT_tabard_edge0", "OUTFIT_tabard_edge1"), "heraldry", LEGS),
    177	         "OUTFIT_tabard_back": (("OUTFIT_tabard_back_hem", "OUTFIT_tabard_back_edge0", "OUTFIT_tabard_back_edge1"),
    178	                                "heraldry", LEGS),
    179	         "OUTFIT_skirt": (("OUTFIT_skirt_hem",), "heraldry", LEGS)}
    180	CLOTH_HEM_ONLY = {"OUTFIT_skirt"}            # border band on the hem row only (its waist has a gold trim)
    181	
    182	
    183	def scene_info(portrait, palette):
    184	    """Everything the browser's pixel renderer and cloth solver need besides the meshes: palette
    185	    bands per role, the lights, body colliders, cloth grids and the mouth curve (model space,
    186	    turned to face +z like the GLB)."""
    187	    import vroid_portrait as vp
    188	    from vrm import bone_weight
    189	    hexp = lambda c: palette[c]
    190	    bands = lambda tbl: [[thr if thr > -5 else -9, hexp(c)] for thr, c in tbl]
    191	    roles = {"face": dict(mode="bands", bands=bands(vp.SKIN_BANDS)),
    192	             "body": dict(mode="bands", bands=bands(vp.SKIN_BANDS), cap=hexp("4")),
    193	             "shadow": dict(mode="flat", color=hexp("3")),
    194	             "hair": dict(mode="bands", bands=bands(vp.HAIR_BANDS)),
    195	             "cloth": dict(mode="bands", bands=bands(vp.CLOTH_BANDS)),
    196	             "line": dict(mode="flat", color=hexp("o")), "brow": dict(mode="flat", color=hexp("A")),
    197	             "mouth": dict(mode="flat", color=hexp("1")), "white": dict(mode="flat", color=hexp("w")),
    198	             "highlight": dict(mode="flat", color=hexp("w")),
    199	             "iris": dict(mode="iris", colors=[hexp("r"), hexp("s"), hexp("t")], cuts=[0.25, 0.5])}
    200	    for r, tbl in vp.MATERIALS.items():
    201	        roles[r] = dict(mode="bands", bands=bands(tbl), world=r in vp.WORLD_ROLES)
    202	    names = portrait.v.nodes_by_name()
    203	    W = portrait.v.node_world(portrait.pose_now)
    204	    body = [p for p, r in zip(portrait.prims, portrait.roles) if r == "body"][0]
    205	    caps = []
    206	    for a, b in CAPSULES:
    207	        if a not in names or b not in names:
    208	            continue
    209	        A, B = W[names[a]][:3, 3], W[names[b]][:3, 3]
    210	        wv = bone_weight(body, (a,))
    211	        pts = body["pos"][wv > 0.5]
    212	        if len(pts) < 8:
    213	            continue
    214	        ab = B - A
    215	        t = np.clip(((pts - A) @ ab) / (ab @ ab), 0, 1)
    216	        d = np.linalg.norm(pts - (A + t[:, None] * ab), axis=1)
    217	        caps.append(dict(a=(A * FLIP).tolist(), b=(B * FLIP).tolist(), r=float(np.percentile(d, 70) + 0.012),
    218	                         bones=[a, b]))
    219	    cloth = {}
    220	    for p in portrait.prims:
    221	        if p["material"] in CLOTH and "grid" in p:
    222	            trims, band, collide = CLOTH[p["material"]]
    223	            cloth[p["material"]] = dict(u=int(p["grid"][0]), v=int(p["grid"][1]), trims=list(trims), band=band,
    224	                                        collide=list(collide) if collide else None, closed=bool(p.get("closed")),
    225	                                        edges="hem" if p["material"] in CLOTH_HEM_ONLY else "all")
    226	    curve = None
    227	    if getattr(portrait, "mouth_curve", None) is not None:
    228	        face = [p for p, r in zip(portrait.prims, portrait.roles) if r == "face"]
    229	        allp = np.concatenate([p["pos"] for p in face])
    230	        alln = np.concatenate([p["nrm"] for p in face])
    231	        from scipy.spatial import cKDTree
    232	        _, i = cKDTree(allp).query(portrait.mouth_curve)
    233	        curve = ((portrait.mouth_curve + alln[i] * 0.0015) * FLIP).tolist()
    234	    marks = None
    235	    if getattr(portrait, "marks", None):
    236	        m = next(iter(portrait.marks.values()))
    237	        img = Image.fromarray(np.where(m == 1, 128, 0).astype(np.uint8), "L")     # nose mark only; the mouth is a line
    238	        b = io.BytesIO()
    239	        img.save(b, "PNG", optimize=True)
    240	        import base64
    241	        marks = base64.b64encode(b.getvalue()).decode()
    242	    # painted renderer: a material kind and one base colour per role; the shader builds the ramp
    243	    pc = dict(signature="#7d1e2c", doublet="#2a2d3d", heraldry="#dfe2e8", leather="#5f3e2b", boot="#4a3326", glove="#5f3e2b",
    244	              steel="#a6adbb", gold="#b08b3f", hair=hexp("C"), trim="#b08b3f")
    245	    pc.update(getattr(portrait, "paint", None) or {})
    246	    skin = dict(kind="skin", base=pc.get("skin") or "#f8e1d5")                       # light skin unless a tone is set
    247	    skin["ramp"] = skin_ramp(skin["base"])                                              # its lit, shade and deep shade
    248	    paint = {"face": dict(skin), "body": dict(skin), "shadow": dict(skin, shade=True),   # shadow cards: skin in shade
    249	             "hair": dict(kind="hair", base=pc["hair"]),
    250	             "coat": dict(kind="cloth", base=pc["signature"]), "cape": dict(kind="cloth", base=pc["signature"]),
    251	             "signature": dict(kind="cloth", base=pc["signature"]), "doublet": dict(kind="cloth", base=pc["doublet"]),
    252	             "cloth": dict(kind="cloth", base=pc["doublet"]), "heraldry": dict(kind="cloth", base=pc["heraldry"]),
    253	             "leather": dict(kind="leather", base=pc["leather"]), "boot": dict(kind="leather", base=pc["boot"]),
    254	             "glove": dict(kind="leather", base=pc["glove"]), "metal": dict(kind="steel", base=pc["steel"]),
    255	             "steel": dict(kind="steel", base=pc["steel"]), "gold": dict(kind="gold", base=pc["gold"]),
    256	             "grass": dict(kind="world", base="#5a7a3a"), "dirt": dict(kind="world", base="#6a4a32"),
    257	             "stone": dict(kind="world", base="#7c7a86"),
    258	             "motif": dict(kind="cloth", base=pc.get("motif", "#3a44a0"))}       # decal paint on steel (tools/plates.py)
    259	    for role, val in pc.items():                             # extra roles a cast entry names (cloth unless it says)
    260	        if role not in paint and isinstance(val, str) and val.startswith("#"):
    261	            paint[role] = dict(kind="cloth", base=val)
    262	        elif role not in paint and isinstance(val, dict) and "base" in val:
    263	            paint[role] = dict(kind=val.get("kind", "cloth"), base=val["base"])
    264	    for role, g in (pc.get("grain") or {}).items():          # optional per-role brush grain (big flat cloth mottles)
    265	        if role in paint:
    266	            paint[role]["grain"] = g
    267	    return dict(roles=roles, light=vp.LIGHT.tolist(), sun=vp.SUN.tolist(), capsules=caps, cloth=cloth, face_marks=marks,
    268	                paint=paint,
    269	                mouth_curve=curve, mouth_bone="J_Bip_C_Head", ink=dict(o=hexp("o"), skin=hexp("1"), hair=hexp("A")),
    270	                skin=[hexp(c) for c in "12345"], depth_gap=0.012)
    271	
    272	
    273	# ---- skinned export: one rigged character + animation clips --------------------------------------------------------
    274	F4 = np.diag([-1.0, 1.0, -1.0, 1.0])
    275	
    276	
    277	def _quat(R):
    278	    """Rotation matrix -> quaternion (x, y, z, w)."""
    279	    t = np.trace(R)
    280	    if t > 0:
    281	        s = math.sqrt(t + 1.0) * 2
    282	        w, x, y, z = 0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s
    283	    elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
    284	        s = math.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2]) * 2
    285	        w, x, y, z = (R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s
    286	    elif R[1, 1] > R[2, 2]:
    287	        s = math.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2]) * 2
    288	        w, x, y, z = (R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s
    289	    else:
    290	        s = math.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1]) * 2
    291	        w, x, y, z = (R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s
    292	    q = np.array([x, y, z, w])
    293	    return q / np.linalg.norm(q)
    294	
    295	
    296	def _trs(m):
    297	    t = m[:3, 3].copy()
    298	    sc = np.linalg.norm(m[:3, :3], axis=0)
    299	    return t, _quat(m[:3, :3] / sc), sc
    300	
    301	
    302	def fill_line_specks(rgba, most=400):
    303	    """A line texture's specks filled: pale or clear texels enclosed by the painted (dark, opaque) line, up to `most`
    304	    texels a speck, take the line's colour. VRoid paints small highlights inside its lash lines; the painted
    305	    renderer drops pale texels, so they showed as skin-coloured specks, plainest in a closed lid."""
    306	    from scipy import ndimage
    307	    dark = (rgba[..., 3] >= 128) & (rgba[..., :3].mean(-1) < 0.42 * 255)
    308	    holes = ndimage.binary_fill_holes(dark) & ~dark
    309	    lab, n = ndimage.label(holes)
    310	    if not n:
    311	        return rgba
    312	    size = ndimage.sum(holes, lab, np.arange(1, n + 1))
    313	    fill = np.isin(lab, np.nonzero(size <= most)[0] + 1)
    314	    out = rgba.copy()
    315	    out[fill] = np.append(np.median(rgba[dark][:, :3], 0), 255).astype(rgba.dtype)
    316	    return out
    317	
    318	
    319	def fill_lid(rgba, v_edge, close=3):
    320	    """A shut lid's lash texture: the lash as one solid stroke. Above its lid-edge row (v_edge), each eye's half of
    321	    the texture keeps its main stroke (the biggest piece of ink once gaps up to 2 * close texels are closed, so the
    322	    wisps touching it join it), solid down each texture column from its top ink to its bottom ink (the lash's
    323	    thickness runs down v), its pale streaks and hollows taking the line's colour; other ink there (a crease line or
    324	    a loose wisp above the lash) is cleared. An open eye reads those as shine and a crease; over a closed lid they
    325	    split it into separate lines. Below the edge row (the corner hook, the lower line's art) is left alone."""
    326	    from scipy import ndimage
    327	    dark = (rgba[..., 3] >= 128) & (rgba[..., :3].mean(-1) < 0.42 * 255)
    328	    rows = int(np.ceil(v_edge * rgba.shape[0])) + 1
    329	    d = dark[:rows]
    330	    st = np.ones((2 * close + 1, 2 * close + 1), bool)
    331	    cl = ndimage.binary_closing(np.pad(d, close + 1), st)[close + 1:-close - 1, close + 1:-close - 1]
    332	    keep = np.zeros_like(d)
    333	    w = d.shape[1]
    334	    for x0, x1 in ((0, w // 2), (w // 2, w)):                    # VRoid's eyeline: one eye on each half
    335	        lab, n = ndimage.label(cl[:, x0:x1])
    336	        if n:
    337	            big = lab == np.argmax(ndimage.sum(cl[:, x0:x1], lab, range(1, n + 1))) + 1
    338	            r = np.arange(big.shape[0])[:, None]               # solid down each column, top ink to bottom ink
    339	            top, bot = np.argmax(big, 0), big.shape[0] - 1 - np.argmax(big[::-1], 0)
    340	            keep[:, x0:x1] = (r >= top[None]) & (r <= bot[None]) & big.any(0)[None]
    341	    out = rgba.copy()
    342	    top = out[:rows]
    343	    top[keep] = np.append(np.median(rgba[dark][:, :3], 0), 255).astype(rgba.dtype)
    344	    top[d & ~keep, 3] = 0
    345	    return out
    346	
    347	
    348	# VRoid's mouth map has one layout on every face (its UVs): the teeth top left, the tongue top right, the mouth's
    349	# inside below. Where to measure each part's own colour on it (u0, u1, v0, v1, image rows from the top).
    350	MOUTH_PARTS = dict(teeth=(0.02, 0.33, 0.02, 0.48), tongue=(0.50, 0.99, 0.02, 0.48), inside=(0.02, 0.98, 0.55, 0.95))
    351	# what the painted renderer's split (index.html, material kind 10) was tuned on: the inside, the tongue, the teeth
    352	MOUTH_EVEN = np.array([[0.80, 0.46, 0.47], [0.93, 0.69, 0.66], [0.99, 0.98, 0.97]])
    353	
    354	
    355	def even_mouth(rgba):
    356	    """The mouth map recoloured so the renderer's fixed split into teeth, tongue and dark inside holds on every face.
    357	    Each map's own inside (median), tongue (its light pink: the 90th percentile of green over the tongue's part) and
    358	    teeth (90th percentile of their least channel: white, where the tongue's light is pink) are measured, every texel placed between them, and painted
    359	    in the colours the split was tuned on. A face whose whole mouth is darker (the sexy woman's) read solid maroon
    360	    under fixed thresholds, with no tongue."""
    361	    rgb = rgba[..., :3].astype(np.float64) / 255
    362	    H, W = rgb.shape[:2]
    363	    part = {k: rgb[int(v0 * H):int(v1 * H), int(u0 * W):int(u1 * W)].reshape(-1, 3)
    364	            for k, (u0, u1, v0, v1) in MOUTH_PARTS.items()}
    365	    g_in, l_in = np.median(part["inside"][:, 1]), np.median(part["inside"].min(1))
    366	    g_tg = np.percentile(part["tongue"][:, 1], 90)
    367	    l_th = np.percentile(part["teeth"].min(1), 90)
    368	    if g_tg - g_in < 0.03 or l_th - l_in < 0.05:              # no tongue or teeth to tell apart: as painted
    369	        return rgba
    370	    ss = lambda x, a, b: np.clip((x - a) / (b - a), 0, 1) ** 2 * (3 - 2 * np.clip((x - a) / (b - a), 0, 1))
    371	    tongue = ss((rgb[..., 1] - g_in) / (g_tg - g_in), 0.25, 0.45)
    372	    teeth = ss((rgb.min(-1) - l_in) / (l_th - l_in), 0.55, 0.70)
    373	    c = MOUTH_EVEN[0] + tongue[..., None] * (MOUTH_EVEN[1] - MOUTH_EVEN[0])
    374	    c = c + teeth[..., None] * (MOUTH_EVEN[2] - c)
    375	    out = rgba.copy()
    376	    out[..., :3] = np.round(c * 255).astype(rgba.dtype)
    377	    return out
    378	
    379	
    380	def export_skinned(portrait, palette, path, clips=None, max_tex=512):
    381	    """The character in its reference pose as a skinned glTF: the VRoid skeleton (with our bone
    382	    scales) drives the body, face, hair and every costume piece through the weights they carry.
    383	    clips: {name: [(time, pose dict), ...]} -> glTF animations (rotation, plus translation where a
    384	    pose moves a bone). Scenery is left out (export it with export())."""
    385	    import vroid_portrait as vp
    386	    v = portrait.v
    387	    nodes_v = v.j["nodes"]
    388	    names = v.nodes_by_name()
    389	    parent = v.parents()
    390	    used = set()
    391	    for p in portrait.prims:
    392	        if "jnames" in p and not p.get("world"):
    393	            used.update(n for n in p["jnames"] if n in names)
    394	    joints = set()
    395	    for nm in used:                                   # every used bone plus its ancestors
    396	        i = names[nm]
    397	        while i is not None and i not in joints:
    398	            joints.add(i)
    399	            i = parent.get(i)
    400	    order = sorted(joints)

    168 more lines not shown.

  • Bashgrep -n "def \|wrap_json\|export_skinned\|scene_info\|glb" review/vroid-02/build.py | head -60

    command

    grep -n "def \|wrap_json\|export_skinned\|scene_info\|glb" review/vroid-02/build.py | head -60

    result, 31 lines

    7:  <name>.glb.json     each character, skinned, in the reference (bust) pose, with animation clips:
    10:                      .json but not .glb, so the model is base64-wrapped.
    11:  plains.glb.json     the battle ground (static)
    39:import export_glb  # noqa: E402
    89:def costume_of(c):
    106:def model_path(name, c):
    137:def arm_room(name, c, need=0.006, most=16):
    155:def portrait(name, view):
    165:def springs(v):
    183:def wrap_json(path):
    184:    json.dump({"glb": base64.b64encode(open(path, "rb").read()).decode()}, open(path + ".json", "w"))
    188:def character(args):
    203:    path = f"{OUT}/{name}.glb"
    204:    size = export_glb.export_skinned(p, pal, path, clips=cl)
    205:    wrap_json(path)
    209:                    info=dict(export_glb.scene_info(p, pal), springs=springs(p.v)), checks=proportion_checks(name, c))
    214:    return dict(name=name, size=size, cams=dict(bust=cam_bust, battle=cam_battle), info=export_glb.scene_info(p, pal),
    218:def save_geometry(name, p):
    231:def _fit_of(c):
    243:def _nth(p):
    248:def proportion_checks(name, c):
    310:def scenery(name):
    312:    path = f"{OUT}/plains.glb"
    313:    size = export_glb.export(p, dict(vp.PALETTE, **c["colors"]), path, only_world=True)
    314:    wrap_json(path)
    318:def duel_cached():
    332:def as_list(o):
    346:        fs = ex.submit(scenery, names[0]) if not sys.argv[1:] or not os.path.exists(f"{OUT}/plains.glb.json") else None
    349:            print(f"plains.glb {fs.result() / 1e6:.2f} MB")
    351:        print(f"{n}.glb {r['size'] / 1e6:.1f} MB")
    381:            out["page"]["skins"] = [dict(name=n, label=lab, group=grp, ramp=export_glb.skin_ramp(cast.SKINS[n]))
  • Bashsed -n 1,30p review/vroid-02/build.py && sed -n 150,230p review/vroid-02/build.py

    command

    sed -n 1,30p review/vroid-02/build.py && sed -n 150,230p review/vroid-02/build.py

    result, 109 lines

    """Build the model-viewer review page for the cast on stage, and their duel.
    
      python3 review/vroid-02/build.py              every character, the ground and the page
      python3 review/vroid-02/build.py elaine       just Elaine (the others stay as last built)
    
    Writes to review/out/vroid-02/site/:
      <name>.glb.json     each character, skinned, in the reference (bust) pose, with animation clips:
                          idle, attack, clash (the two-character sword bind) and apose (arms out, for
                          checking a costume where hanging arms would hide it). Artifact hosting serves
                          .json but not .glb, so the model is base64-wrapped.
      plains.glb.json     the battle ground (static)
      camera.json         per character: the cameras for both views plus what the live renderer needs
                          (palette roles, lights, colliders, cloth grids); the duel's stage camera and
                          where each fighter stands
      checks.json         per character: the automatic checks (tools/checks.py) over every keyframe: arms
                          through the body, and garments showing through plate
    and review/out/vroid-02/geom/<name>.npz (every piece as built), which tools/regress.py compares with the
    last published version (snapshot.py) after each build.
    then copies index.html next to them. The duel's poses are cached (they take about a minute to
    solve) and re-solved when the rig, the duel or the cast entries change.
    """
    import base64
    import hashlib
    import json
    import os
    import pickle
    import shutil
    import sys
    from concurrent.futures import ProcessPoolExecutor
    
    
    
    ARMORY = bool(WORKSHOPS.get(SITE, {}).get("armory"))   # T-posed and bare: the reference pose is the T-pose
    
    
    def portrait(name, view):
        c = CAST[name]
        if (c.get("mh") or c.get("qt") or c.get("mass") or c.get("cage")) and "arm_out" not in c["shape"] and not ARMORY:
            c["shape"]["arm_out"] = arm_room(name, c)
        return vp.Portrait(model_path(name, c), shape=c["shape"],
                           hair_from=os.path.join(VROID, c["hair"]) if c.get("hair") else None,
                           costume=costume_of(c), pose={} if ARMORY else vp.BUST_POSE, hair_trim=c.get("hair_trim"),
                           world=terrain.plains() if view == "battle" else None), c
    
    
    def springs(v):
        """The model's spring bones (VRM 0.x secondaryAnimation: VRoid's women's base has its breasts', a hairstyle its
        hair's, tools/heads.py): each group's root bones, settings and collision spheres (on a bone, offset in its own
        frame, before the export's turn), for the viewer's physics."""
        sa = v.j.get("extensions", {}).get("VRM", {}).get("secondaryAnimation", {})
        nodes = v.j["nodes"]
        spheres = [[dict(bone=nodes[cg["node"]]["name"], offset=[c["offset"]["x"], c["offset"]["y"], c["offset"]["z"]],
                         radius=c["radius"]) for c in cg.get("colliders", [])] for cg in sa.get("colliderGroups", [])]
        out = []
        for g in sa.get("boneGroups", []):
            gd = g.get("gravityDir", {"x": 0, "y": -1, "z": 0})
            out.append(dict(bones=[nodes[b]["name"] for b in g["bones"]], stiffness=g.get("stiffiness", 1.0),
                            gravity=g.get("gravityPower", 0.0), gravity_dir=[gd["x"], gd["y"], gd["z"]],
                            drag=g.get("dragForce", 0.4), radius=g.get("hitRadius", 0.02), comment=g.get("comment", ""),
                            colliders=[c for k in g.get("colliderGroups", []) if k < len(spheres) for c in spheres[k]]))
        return out
    
    
    def wrap_json(path):
        json.dump({"glb": base64.b64encode(open(path, "rb").read()).decode()}, open(path + ".json", "w"))
        os.remove(path)
    
    
    def character(args):
        """The rigged character (reference pose) with its clips, its cameras, the live renderer's data and
        its checks."""
        name, clash = args
        p, c = portrait(name, "bust")
        p.paint = c.get("paint")
        pal = dict(vp.PALETTE, **c["colors"])
        cam_bust, cam_battle = p.frame("bust"), p.frame("battle")
        if ARMORY:                                          # nothing moves: every clip holds the T-pose
            cl = {k: [(0.0, {}), (1.0, {})] for k in ("idle", "attack", "apose")}
        else:
            cl = clips.clips(p.v, c["shape"], c.get("stance", "sword"))
            if clash:
                cl["clash"] = clash
            cl["apose"] = [(0.0, APOSE), (1.0, APOSE)]
        path = f"{OUT}/{name}.glb"
        size = export_glb.export_skinned(p, pal, path, clips=cl)
        wrap_json(path)
        save_geometry(name, p)
        if ARMORY:                                          # the armory's checks are proportions (tools/proportions.py)
            return dict(name=name, size=size, cams=dict(bust=cam_bust, battle=cam_battle),
                        info=dict(export_glb.scene_info(p, pal), springs=springs(p.v)), checks=proportion_checks(name, c))
        body = checks.Body(p.v, c["shape"])
        keyed = {k: v for k, v in cl.items() if k != "apose"}
        head, bad, touch = checks.report(name, keyed, body)
        layers = checks.layer_report(name, keyed, checks.Layers(p, body))
        return dict(name=name, size=size, cams=dict(bust=cam_bust, battle=cam_battle), info=export_glb.scene_info(p, pal),
                    checks=dict(summary=head, through=bad, touching=touch, layers=layers))
    
    
    def save_geometry(name, p):
        """Every piece's vertices as built (reference pose), for tools/regress.py to compare builds."""
        os.makedirs(GEOM, exist_ok=True)
        arrays, seen = {}, {}
        for q in p.prims:
            key = q["material"]
            seen[key] = seen.get(key, 0) + 1
            if seen[key] > 1:
                key = f"{key}#{seen[key]}"
            arrays[key] = q["pos"][np.unique(q["tri"])].astype(np.float32) if len(q["tri"]) else q["pos"].astype(np.float32)
        np.savez_compressed(os.path.join(GEOM, f"{name}.npz"), **arrays)
  • Bashgrep -n "loadCharacter\|KIND\|function \|uKind\|GLTFLoader\|importmap\|three@" review/out/whole-lens/site/index.html | head -150

    command

    grep -n "loadCharacter\|KIND\|function \|uKind\|GLTFLoader\|importmap\|three@" review/out/whole-lens/site/index.html | head -150

    result, 71 lines

    218:<script type="importmap">
    219:{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
    220:               "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/" } }
    225:import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
    343:  uniform int uKind; uniform vec3 uBase; uniform vec3 uKey; uniform sampler2D uMap; uniform int uAlpha;
    427:    else if (uCastOn == 1 && uKind == 1 && int(uInfo.x * 255.0 + 0.5) == 2 && castShadow() > 0.5)
    431:    if (uKind == 0 || uKind == 5 || uKind == 6) {                    // cloth, leather, ground
    434:      float sh = uKind == 5 ? 0.93 : (cool ? 0.70 : 0.96);
    438:      float l = lit + (g1 - 0.5) * uGrain - (uKind == 6 ? 0.22 : 0.0);  // ground: a flat top sits at the base colour
    440:      if (uKind == 5) col *= 0.965 + 0.07 * vnoise(vObj * 22.0);       // mottled leather
    441:    } else if (uKind == 1) {                                           // skin: pale, nearly unshaded from the front
    458:    } else if (uKind == 2) {                                           // hair: four even bands, hard strand highlights
    466:    } else if (uKind == 3 || uKind == 4) {                             // steel, gold
    469:      bool gilt = uKind == 4 || (plate && w > 0.0 && e < w);            // an outline plate's gold border
    470:      col = metal(gilt, gilt && uKind == 3 ? uGold : uBase, n, v, lit, plate ? vPlate.w : -1.0);
    477:    } else if (uKind == 7) {                                           // iris
    480:    } else if (uKind == 8) { col = tex.rgb; }
    481:    else if (uKind == 10) {                                            // the open mouth: VRoid's map read as three parts,
    487:    if (vPlate.x > 0.5 && vPlate.z > 0.0 && uKind != 3 && uKind != 4) {   // a cloth outline piece's gold border,
    507:    if (uKind <= 6) {
    509:      col *= uKind == 1 && uSkinRamp == 1 ? mix(vec3(1.0), grade, 0.3) : grade;   // a designed skin ramp takes less of it
    513:      if (uKind != 1) col *= 1.0 + (g2 - 0.5) * 0.06;
    609:function compPass(fs, uniforms) {
    631:function targetsFor(w, h) {
    858:const KIND = { cloth: 0, skin: 1, hair: 2, steel: 3, gold: 4, leather: 5, world: 6 };
    859:function paintMaterial(V, role, map, index, infoRole = role, decal = false) {
    861:  const u = { uKind: { value: 9 }, uBase: { value: new THREE.Color(0.8, 0.8, 0.8) }, uKey: { value: KEY.clone() },
    873:  if (P) { u.uKind.value = KIND[P.kind] ?? 0; if (P.base) u.uBase.value = hex(P.base); if (P.grain != null) u.uGrain.value = P.grain; }
    874:  else if (Rl.bands) { u.uKind.value = Rl.world ? 6 : 0; u.uBase.value = hex(Rl.bands[Math.min(1, Rl.bands.length - 1)][1]); }
    885:  if (role === "iris") { u.uKind.value = 7; u.uAlpha.value = 1; }
    886:  else if (role === "white" || role === "highlight") { u.uKind.value = map ? 8 : 9; if (map) u.uAlpha.value = 1; u.uFlat.value = hex(Rl.color || "#ffffff"); }
    887:  else if (!P && Rl.mode === "flat") { u.uKind.value = 9; u.uFlat.value = hex(Rl.color); if (map) u.uAlpha.value = role === "line" ? 2 : 1; }
    889:  if (role === "mouth" && map) u.uKind.value = 10;
    899:const loader = new GLTFLoader();
    912:async function parseGlb(file) {
    918:function prepMesh(o, V, opts = {}) {
    946:async function loadCharacter(name) {
    983:async function loadGround() {
    994:function applyMaterials() {
    1011:function setClip(name, blendFrom = null) {
    1024:function animate(dt) {
    1051:function armSide(c, side) {                          // +1 when the arm points along the model's +x
    1060:function turnBone(c, name, deg) {                    // about the model's front axis, at the bone's own joint
    1068:function applyPose(c) {
    1081:function applyMotion(c, dt) {
    1099:function makeSprings(c, groups) {
    1123:function stepSprings(c, dt) {
    1156:function layoutCompare() {
    1179:function placeTags() {                               // the names under the feet
    1193:function compareChanged() {                          // the comparison is in the link, to share it
    1203:function insets() {
    1209:function fitFrustum() {
    1219:function size() {
    1229:function matchCamera() {
    1245:function focusAt(e) {
    1255:function setYaw(y) {
    1265:function buildParts() {
    1275:function groupedSelect(label, skip, onPick) {      // every model in its group, as one dropdown
    1289:function buildWho() {
    1331:async function setView(view, clip) {
    1338:    const cs = await Promise.all(activeNames().map(loadCharacter));
    1377:function applySkin(meshes) {
    1382:    if (!u || !u.uSkinRamp || u.uKind.value !== 1) continue;
    1388:function render() {
    1487:function holdPose(clip, t) {
    1497:function settleCloth() {
    1503:function frameAt(centre, h, tw, th, pitch) {
    1510:async function runSheet(kind) {
    1600:async function loadChecks() {
    1647:function setPanel(open) {
    1695:function frame(now) {
  • Bashsed -n 840,1010p review/out/whole-lens/site/index.html

    command

    sed -n 840,1010p review/out/whole-lens/site/index.html

    result, 171 lines

            X[3 * k] = q.x; X[3 * k + 1] = q.y; X[3 * k + 2] = q.z;
            pr = r; ph = h; pt = tt;
          }
        }
        this.prev.set(X);
      }
      reset() { this.push.fill(0); this.pose(0, true); }
      step(dt) { this.pose(dt, false); }
    }
    
    // ---- materials per mesh ----------------------------------------------------------------------------------------------
    const KEY = new THREE.Vector3(-0.45, 0.55, 0.70).normalize();
    // stage grades: ambient multiply, key colour, back rim (characters and stage share them)
    const GRADE = { battle: { ambient: [0.84, 0.87, 0.98], key: [1.05, 1.0, 0.92], rim: [0.38, 0.34, 0.26] },
                    bust: { ambient: [0.90, 0.90, 0.98], key: [1.03, 1.0, 0.96], rim: [0.24, 0.24, 0.34] } };
    // Brows draw over the bangs: they are lifted this far (m) toward the camera, more than the bangs stand off the
    // forehead and much less than the head is deep, so a brow still hides behind the skull when the head turns away.
    const BROW_LIFT = 0.04;
    const KIND = { cloth: 0, skin: 1, hair: 2, steel: 3, gold: 4, leather: 5, world: 6 };
    function paintMaterial(V, role, map, index, infoRole = role, decal = false) {
      const Rl = V.roles[role] || { mode: "flat", color: "#ff00ff" }, P = (V.paint || {})[role];
      const u = { uKind: { value: 9 }, uBase: { value: new THREE.Color(0.8, 0.8, 0.8) }, uKey: { value: KEY.clone() },
        uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 },
        uInfo: { value: new THREE.Vector4(roleId(infoRole) / 255, (index % 256) / 255, Math.floor(index / 256) / 255, 1) },
        uEye: { value: V.roles.iris.colors.map(hex) }, uFlat: { value: new THREE.Color() }, uSkinRef: { value: new THREE.Vector3(0.965, 0.878, 0.80) },
        uGold: { value: hex((V.paint && V.paint.gold && V.paint.gold.base) || "#b08b3f") },
        uAmbient: { value: new THREE.Vector3(1, 1, 1) }, uKeyCol: { value: new THREE.Vector3(1, 1, 1) }, uRimCol: { value: new THREE.Vector3() },
        uGrain: { value: 0.05 }, uFaceTex: { value: 0 }, uDecal: { value: decal ? 1 : 0 }, uBand: { value: null },
        uSkinTone: { value: new THREE.Vector3(1, 1, 1) }, uShadeOnly: { value: 0 },
        uSkinRamp: { value: 0 }, uSkinL: { value: new THREE.Color() }, uSkinS: { value: new THREE.Color() }, uSkinC: { value: new THREE.Color() },
        tCastInfo: { value: null }, tCastDepth: { value: null }, uCastRes: { value: new THREE.Vector2(1, 1) }, uCastOn: { value: 0 },
        uCastNear: { value: 0.1 }, uCastFar: { value: 40 }, uCastPpm: { value: 1 },
        uMotif: { value: hex((V.paint && V.paint.motif && V.paint.motif.base) || "#3a44a0") }, uLift: { value: 0 } };
      if (P) { u.uKind.value = KIND[P.kind] ?? 0; if (P.base) u.uBase.value = hex(P.base); if (P.grain != null) u.uGrain.value = P.grain; }
      else if (Rl.bands) { u.uKind.value = Rl.world ? 6 : 0; u.uBase.value = hex(Rl.bands[Math.min(1, Rl.bands.length - 1)][1]); }
      if (P && P.kind === "world") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.12; }
      if (P && P.shade) u.uShadeOnly.value = 1;         // shadow cards: skin, always in its shade tone
      if (P && P.kind === "skin" && P.ramp) {           // a designed ramp: lit, shade, deep shade
        u.uSkinRamp.value = 1; u.uSkinL.value = hex(P.ramp[0]); u.uSkinS.value = hex(P.ramp[1]); u.uSkinC.value = hex(P.ramp[2]);
      }
      if (P && P.kind === "skin" && P.base) {           // skin tone: the base colour against the default light skin
        const c = hex(P.base); u.uSkinTone.value.set(c.r / 0.973, c.g / 0.882, c.b / 0.835);
      }
      if (role === "face" && map) u.uFaceTex.value = 1;
      if (role === "hair" && map) u.uAlpha.value = 1;
      if (role === "iris") { u.uKind.value = 7; u.uAlpha.value = 1; }
      else if (role === "white" || role === "highlight") { u.uKind.value = map ? 8 : 9; if (map) u.uAlpha.value = 1; u.uFlat.value = hex(Rl.color || "#ffffff"); }
      else if (!P && Rl.mode === "flat") { u.uKind.value = 9; u.uFlat.value = hex(Rl.color); if (map) u.uAlpha.value = role === "line" ? 2 : 1; }
      if (role === "brow") u.uLift.value = BROW_LIFT;
      if (role === "mouth" && map) u.uKind.value = 10;
      u.uBand.value = u.uGold.value.clone();
      const m = new THREE.ShaderMaterial({ uniforms: u, vertexShader: PAINT_VS, fragmentShader: PAINT_FS, side: THREE.DoubleSide,
                                           extensions: { derivatives: true } });
      // meshes without plate data or a cloth edge read zeros, not whatever another program left in that slot
      m.defaultAttributeValues = { ...m.defaultAttributeValues, _plate: [0, 0, 0, 0], edge: [0] };
      return m;
    }
    
    // ---- models ------------------------------------------------------------------------------------------------------
    const loader = new GLTFLoader();
    const chars = new Map();          // name -> loaded character
    let ground = null;
    const stage = new THREE.Group();  // the duel: both fighters stand on it; the turn slider rotates it
    scene.add(stage);
    // the lineup: every enemy model standing in a row (camera.json's lineup), each turning in place
    const LINEUP = CAM.lineup || { order: [], spacing: 0.9 };
    const ROW_VIEW = () => state.view === "lineup" || state.view === "compare";     // several models in a row, each turning in place
    const CAM_VIEW = () => state.view === "duel" || ROW_VIEW() ? CAM.duel.cam : charDef(state.who).cams[state.view];
    const activeNames = () => state.view === "duel" ? [CAM.duel.order.player, CAM.duel.order.opponent]
                            : state.view === "lineup" ? LINEUP.order : state.view === "compare" ? state.compare : [state.who];
    const active = () => activeNames().map(n => chars.get(n)).filter(Boolean);
    
    async function parseGlb(file) {
      const j = await (await fetch(file)).json();
      const bin = Uint8Array.from(atob(j.glb), c => c.charCodeAt(0));
      return await new Promise((ok, bad) => loader.parse(bin.buffer, "", ok, bad));
    }
    let meshIndex = 1;
    function prepMesh(o, V, opts = {}) {
      const m0 = o.material, role = o.userData.role || "body", raw = rawTex(m0.map);
      const infoRole = role === "hair" && opts.hairB ? "hair_b" : role === "shadow" ? "body" : role;
      const decal = !!(m0.userData && m0.userData.decal);              // the map is a design mask, not a colour
      const base = { map: decal ? null : (m0.map || null), color: m0.color.clone(), side: THREE.DoubleSide, alphaTest: m0.alphaTest || 0 };
      const clay = new THREE.MeshStandardMaterial({ ...base, roughness: 0.85, metalness: m0.metalness || 0 });
      const toon = new THREE.MeshToonMaterial({ ...base, gradientMap: gradient });
      if (role === "hair" && m0.map && V.paint && V.paint.hair) {
        // the VRoid sample's hair texture carries its own colour (dark on some samples): in 3D use the
        // character's hair colour, with the texture's light and dark only for strand detail
        for (const m of [clay, toon]) {
          m.color = hex(V.paint.hair.base);
          m.onBeforeCompile = sh => { sh.fragmentShader = sh.fragmentShader.replace("#include <map_fragment>",
            `#ifdef USE_MAP
              vec4 texel_ = texture2D(map, vMapUv);
              diffuseColor.rgb *= mix(1.0, clamp(dot(texel_.rgb, vec3(0.3333)) / 0.5, 0.45, 1.35), 0.6);
              diffuseColor.a *= texel_.a;
            #endif`); };
          m.customProgramCacheKey = () => "hairlum";
        }
      }
      o.userData.mats = { clay, toon, painted: paintMaterial(V, role, raw, meshIndex, infoRole, decal) };
      meshIndex++;
      o.userData.group = o.userData.group || "body";
      o.userData.role = role;
      o.frustumCulled = false;
    }
    
    async function loadCharacter(name) {
      if (chars.has(name)) return chars.get(name);
      const def = charDef(name), V = def.info, ci = CAM.characters.indexOf(def);
      const gltf = await parseGlb(`${name}.glb.json`);
      const turn = new THREE.Group(), holder = new THREE.Group();
      turn.add(holder); holder.add(gltf.scene);
      const meshes = [];
      gltf.scene.traverse(o => { if (o.isMesh) { prepMesh(o, V, { hairB: ci > 0 }); meshes.push(o); } });
      gltf.scene.updateMatrixWorld(true);
      const bone = n => gltf.scene.getObjectByName(n);
      const cloths = [], world = new THREE.Group();
      for (const [cname, info] of Object.entries(V.cloth || {})) {
        const skinned = meshes.find(m => m.userData.material === cname);
        if (!skinned) continue;
        const trims = meshes.filter(m => info.trims.includes(m.userData.material));
        const caps = V.capsules.filter(c => !info.collide || info.collide.some(k => c.bones[0].includes(k)));
        const cl = info.closed ? new SkirtRig(skinned, info.u, info.v, trims, caps, bone, info.edges === "hem")
                               : new Cloth(skinned, info.u, info.v, trims, caps, bone, false, info.edges === "hem");
        const band = info.band || "gold", BR = V.roles[band] || V.roles.gold;
        const gold = hex(BR.bands ? BR.bands[Math.min(1, BR.bands.length - 1)][1] : BR.color);
        const PB = (V.paint || {})[band];
        if (PB && PB.base) skinned.userData.mats.painted.uniforms.uBand.value = hex(PB.base);   // gold stays gold for decals
        cl.lines3d = new THREE.LineSegments(cl.lines.geometry, new THREE.LineBasicMaterial({ color: gold }));
        cl.lines3d.frustumCulled = false;
        world.add(cl.display, cl.lines3d);
        cloths.push(cl);
      }
      const mixer = new THREE.AnimationMixer(gltf.scene);
      const actions = Object.fromEntries(gltf.animations.map(c => [c.name, mixer.clipAction(c)]));
      const skeleton = meshes.find(m => m.isSkinnedMesh)?.skeleton;
      const c = { name, info: V, turn, holder, root: gltf.scene, meshes, cloths, world, mixer, actions, skeleton,
                  clip: "idle", t: 0, groups: [...new Set(meshes.map(m => m.userData.group))] };
      c.springs = makeSprings(c, V.springs);
      chars.set(name, c);
      return c;
    }
    
    async function loadGround() {
      if (ground) return ground;
      const V = CAM.characters[0].info, gltf = await parseGlb("plains.glb.json"), meshes = [];
      gltf.scene.traverse(o => { if (o.isMesh) { prepMesh(o, V); meshes.push(o); } });
      ground = { root: gltf.scene, meshes };
      return ground;
    }
    
    const allMeshes = () => [...active().flatMap(c => [...c.meshes, ...c.cloths.map(cl => cl.display)]),
                             ...(ground && ground.root.parent && state.view !== "bust" ? ground.meshes : [])];
    const isSimTrim = o => state.cloth && active().some(c => c.cloths.some(cl => cl.trims.includes(o) || cl.skinned === o));
    function applyMaterials() {
      allMeshes().forEach(o => {
        const mat = state.toon ? o.userData.mats.toon : o.userData.mats.clay;
        const x = state.xray && COSTUME.has(o.userData.group);
        mat.transparent = x; mat.opacity = x ? 0.28 : 1; mat.depthWrite = !x; mat.needsUpdate = true;
        o.userData.mat3d = mat;
        const isDisplay = o.userData.cloth;
        o.visible = !state.hidden.has(o.userData.group) && (isDisplay ? state.cloth : !isSimTrim(o));
      });
    }
    const trimsShown = c => state.cloth && !state.hidden.has("trim") && !state.hidden.has(c.skinned.userData.group);
    
    // ---- animation ------------------------------------------------------------------------------------------------------
    // A clip only carries the bones it moves away from the reference pose, so each one starts from the
    // reference pose (otherwise "arms out" would keep the idle's legs).
    const CLIP_VIEW = { clash: "duel", idle: "battle", attack: "battle", apose: "battle" };
    const lineupX = i => (i - (LINEUP.order.length - 1) / 2) * LINEUP.spacing;
  • Bashgrep -n "^#" [redacted: private path] | head -60; grep -n -i "flattice\|flat lattice" [redacted: private path] | head -30no result

    command

    grep -n "^#" [redacted: private path] | head -60; grep -n -i "flattice\|flat lattice" [redacted: private path] | head -30

agent

+0:49

[redacted: private notes read: a handoff file]

  • Bashsed -n 83,245p [redacted: private path]; sed -n 330,357p [redacted: private path]no result

    command

    sed -n 83,245p [redacted: private path]; sed -n 330,357p [redacted: private path]

agent

+0:53

[redacted: private notes read: a handoff file]