A 3D model pipeline, pushed by GPT-6.2-Astra

agent (cont.)

+33:38
  • exec_commandcat > review/tide-keeper/portable.py <<'PY'

    command

    cat > review/tide-keeper/portable.py <<'PY'
    """Complete the Lowmarch skinned export with portable PBR, cloth morphs and pose keys."""
    import io
    import json
    import struct
    import numpy as np
    from PIL import Image, ImageColor
    
    import export_glb as glb
    import vroid_portrait as vp
    from vrm import VRM
    from dyes import dye,face_map
    
    
    def linear(col):
        a=np.array(ImageColor.getrgb(col))/255
        return np.where(a<=.04045,a/12.92,((a+.055)/1.055)**2.4).tolist()
    
    
    def finish(actor,keys,info,colours,metals,directory):
        base=VRM(directory/"base.glb"); doc=base.j; data=bytearray(base.bin)
        def view(blob,target=None):
            data.extend(b"\0"*((-len(data))%4)); off=len(data); data.extend(blob)
            v=dict(buffer=0,byteOffset=off,byteLength=len(blob))
            if target: v["target"]=target
            doc["bufferViews"].append(v)
            return len(doc["bufferViews"])-1
        def accessor(a,kind,target=None):
            a=np.ascontiguousarray(a,dtype=np.float32)
            v=view(a.tobytes(),target); flat=a.reshape(len(a),-1)
            doc["accessors"].append(dict(bufferView=v,componentType=5126,count=len(a),type=kind,
                                         min=flat.min(0).tolist(),max=flat.max(0).tolist()))
            return len(doc["accessors"])-1
        textures={}
        def texture(key,fn):
            if key not in textures:
                im=fn()
                b=io.BytesIO(); im.save(b,"PNG",optimize=False)
                doc["images"].append(dict(bufferView=view(b.getvalue()),mimeType="image/png",name=key))
                doc["textures"].append(dict(source=len(doc["images"])-1,sampler=0))
                textures[key]=len(doc["textures"])-1
            return {"index":textures[key]}
        def original(pbr):
            idx=pbr["baseColorTexture"]["index"]
            return Image.fromarray(base.image(doc["textures"][idx]["source"]))
        eligible=[(p,r) for p,r in zip(actor.prims,actor.roles) if r!="skip" and len(p["tri"]) and "J" in p and not p.get("world")]
        mesh_nodes=[(i,n) for i,n in enumerate(doc["nodes"]) if "mesh" in n]
        assert len(mesh_nodes)==len(eligible)
        morph_nodes=[]
        for (pc,role),(index,node) in zip(eligible,mesh_nodes):
            mesh=doc["meshes"][node["mesh"]]; prim=mesh["primitives"][0]
            mat=doc["materials"][prim["material"]]; pbr=mat["pbrMetallicRoughness"]
            name=pc["material"].removeprefix("OUTFIT_")
            node["name"]=name+"_"+str(index); mesh["name"]=name
            used=np.unique(pc["tri"])
            if role in colours:
                pbr["baseColorFactor"]=linear(colours[role])+[1]
                pbr["metallicFactor"]=.52 if role=="brass" else .25 if role in metals else 0.
                pbr["roughnessFactor"]=.32 if role in metals else .55 if role in ("saddle","boot") else .78
            if pc.get("pigment"):
                pattern=pc["pigment"]
                bitmap=texture(role+"_"+pattern,lambda:dye(pattern,colours[role]))
                prim["attributes"]["TEXCOORD_0"]=accessor(pc["uv"][used],"VEC2",34962)
                pbr["baseColorTexture"]=bitmap; pbr["baseColorFactor"]=[1,1,1,1]
                mat["extras"]={"pigment":True}
            if pc.get("strands"):
                # The shared kit's strand texture is grey. Tint it into a finished
                # colour map with a smooth broad highlight and fine, winding grooves.
                def strand():
                    yy,xx=np.mgrid[:256,:256]; u=xx/255; v=yy/255
                    shade=.86+.19*(np.cos(2*np.pi*(u-.14))*.5+.5)+.10*np.sin(8*np.pi*(u+.035*np.sin(5*v)))**8
                    c=np.array(ImageColor.getrgb(colours[role]))
                    return Image.fromarray(np.uint8(np.clip(c*shade[...,None],0,255)))
                pbr["baseColorTexture"]=texture("locks_"+role,strand)
                pbr["baseColorFactor"]=[1,1,1,1]; mat["extras"]={"pigment":True}
            if role=="face":
                ref=original(pbr)
                def face():
                    a=np.array(face_map(ref),dtype=float)
                    return Image.fromarray(np.uint8(np.clip(a*(np.array(ImageColor.getrgb(colours["skin"]))/[246,224,204]),0,255)))
                pbr["baseColorTexture"]=texture("sun_freckles",face)
                pbr["baseColorFactor"]=[1,1,1,1]
            elif role in ("body","shadow"):
                pbr["baseColorFactor"]=linear(colours["skin"] if role=="body" else "#bf896f")+[1]
            elif role=="iris":
                raw=original(pbr)
                def iris():
                    a=np.array(raw); v=a[:,:,:3].mean(2)/255
                    out=np.stack([np.interp(v,[0,.29,1],[int(k[1:][j:j+2],16) for k in info["roles"]["iris"]["colors"]]) for j in (0,2,4)],axis=-1)
                    return Image.fromarray(np.dstack([np.uint8(out),a[:,:,3]]))
                pbr["baseColorTexture"]=texture("estuary_iris",iris)
                pbr["baseColorFactor"]=[1,1,1,1]
            elif role in ("line","brow"):
                pbr["baseColorFactor"]=linear("#45303b" if role=="line" else "#574044")+[1]
            if "gust" in pc:
                a=pc["gust"][used]*glb.FLIP
                prim["targets"]=[{"POSITION":accessor(a,"VEC3",34962)}]
                mesh["weights"]=[0.0]; mesh["extras"]={"targetNames":["Crosswind"]}
                morph_nodes.append(index)
        # Compute the local transforms once per key. Geometry remains in the
        # neutral fitting pose and uses the original inverse bind matrices.
        names=actor.v.nodes_by_name()
        frames=[vp.bone_pose(actor.v,actor.shape,p) for _,p in keys]
        times=accessor(np.array([t for t,_ in keys]),"SCALAR")
        samplers=[]; channels=[]
        def track(index,path,array,kind):
            samplers.append(dict(input=times,output=accessor(array,kind),interpolation="LINEAR"))
            channels.append(dict(sampler=len(samplers)-1,target=dict(node=index,path=path)))
        for i in doc["skins"][0]["joints"]:
            node=doc["nodes"][i]; source=names[node["name"]]
            samples=[glb._trs(glb.F4@actor.v.local_matrix(source,p)@glb.F4) for p in frames]
            for j,(path,kind) in enumerate([("translation","VEC3"),("rotation","VEC4"),("scale","VEC3")]):
                a=np.array([s[j] for s in samples])
                if path=="rotation":
                    for k in range(1,len(a)):
                        if np.dot(a[k-1],a[k])<0:a[k]*=-1
                node[path]=a[0].tolist()
                if abs(a-a[0]).max()>1e-5: track(i,path,a,kind)
        wind_id=len(samplers)
        samplers.append(dict(input=times,output=accessor(np.array([0,.74,.95,.33,0]),"SCALAR"),interpolation="LINEAR"))
        for i in morph_nodes:channels.append(dict(sampler=wind_id,target=dict(node=i,path="weights")))
        doc["animations"]=[dict(name="Read the tide",samplers=samplers,channels=channels)]
        doc["nodes"][doc["scenes"][0]["nodes"][0]]["name"]="Ione • Tide keeper"
        doc["asset"]["generator"]="Lowmarch export_glb + Tide Keeper"
        doc["asset"]["extras"]={"units":"metres","front":"+Z","study":"High water","clip":"Read the tide"}
        data.extend(b"\0"*((-len(data))%4)); doc["buffers"][0]["byteLength"]=len(data)
        js=json.dumps(doc,separators=(",",":"),allow_nan=False).encode()
        js+=b" "*((-len(js))%4)
        (directory/"ione.glb").write_bytes(struct.pack("<4sII",b"glTF",2,28+len(js)+len(data))+
            struct.pack("<I4s",len(js),b"JSON")+js+struct.pack("<I4s",len(data),b"BIN\0")+data)
    PY
    OPENBLAS_NUM_THREADS=1 python3 -u review/tide-keeper/build.py > review/out/tide-keeper/build.log 2>&1

    result, 4 lines

    Script completed
    Wall time 0.4 seconds
    Output:
    {"chunk_id":"490ec6","wall_time_seconds":0.252792324,"session_id":9992,"original_token_count":0,"output":""}
  • exec_commandcat review/out/tide-keeper/build.log

    command

    cat review/out/tide-keeper/build.log
    sed -n '1375,1441p;1500,1513p' review/vroid-02/index.html
    rg -n 'new THREE.WebGLRenderer|.morphTarget|uCast' review/vroid-02/index.html | head -15
    cat review/tide-keeper/patch_lens_flattice.py | head -12

    result, 4 lines

    Script completed
    Wall time 0.1 seconds
    Output:
    {"chunk_id":"be7a96","wall_time_seconds":0.0000049,"exit_code":0,"original_token_count":2018,"output":"Fit, hair, coat and armour 18.08s\nBase GLB 1.54s\n\n// ---- rendering -------------------------------------------------------------------------------------------------------\nfunction applySkin(meshes) {\n  // the picked tone on every skin material (face, body, shadow cards); the built tone is kept to go back to\n  const tone = state.skin && PAGE && PAGE.skins ? PAGE.skins.find(s => s.name === state.skin) : null;\n  for (const o of meshes) {\n    const m = o.userData.mats && o.userData.mats.painted, u = m && m.uniforms;\n    if (!u || !u.uSkinRamp || u.uKind.value !== 1) continue;\n    if (!o.userData.builtSkin) o.userData.builtSkin = [u.uSkinRamp.value, u.uSkinL.value.clone(), u.uSkinS.value.clone(), u.uSkinC.value.clone()];\n    if (tone) { u.uSkinRamp.value = 1; u.uSkinL.value.copy(hex(tone.ramp[0])); u.uSkinS.value.copy(hex(tone.ramp[1])); u.uSkinC.value.copy(hex(tone.ramp[2])); }\n    else { const b = o.userData.builtSkin; u.uSkinRamp.value = b[0]; u.uSkinL.value.copy(b[1]); u.uSkinS.value.copy(b[2]); u.uSkinC.value.copy(b[3]); }\n  }\n}\nfunction render() {\n  const meshes = allMeshes(), cs = active();\n  applySkin(meshes);\n  const cloths = cs.flatMap(c => c.cloths);\n  if (state.mode === \"3d\") {\n    meshes.forEach(o => o.material = o.userData.mat3d);\n    cloths.forEach(c => c.lines3d.visible = trimsShown(c));\n    sun.position.copy(camera.position).add(new THREE.Vector3(-3, 4, 0)); sun.target.position.copy(ctl.target); sun.target.updateMatrixWorld();\n    R.setRenderTarget(null); R.setClearColor(0x191626, 1); R.clear(); R.render(scene, camera); R.setClearColor(0x000000, 0);\n    return;\n  }\n  const buf = R.getDrawingBufferSize(new THREE.Vector2());\n  targetsFor(buf.x, buf.y);\n  cloths.forEach(c => c.lines3d.visible = false);\n  meshes.forEach(o => { o.material = o.userData.mats.painted; o.material.uniforms.uPass.value = 0; });\n  const G = GRADE[state.view === \"bust\" ? \"bust\" : \"battle\"];      // stage grade, shared by the characters and the stage\n  for (const o of meshes) { const mu = o.material.uniforms; mu.uAmbient.value.set(...G.ambient); mu.uKeyCol.value.set(...G.key); mu.uRimCol.value.set(...G.rim); }\n  // the info pass (roles, ids, depth) first: the colour pass reads it for cast shadows\n  meshes.forEach(o => {                              // unbound while it is drawn: reading it now would be a feedback loop\n    const mu = o.material.uniforms; mu.uPass.value = 1; mu.uCastOn.value = 0; mu.tCastInfo.value = null; mu.tCastDepth.value = null;\n  });\n  R.setRenderTarget(targets.rtInfo); R.clear(); R.render(scene, camera);\n  const ppmBuf = buf.y / (camera.top - camera.bottom) * camera.zoom;\n  for (const o of meshes) {\n    const mu = o.material.uniforms;\n    mu.uPass.value = 0; mu.uCastOn.value = 1; mu.tCastInfo.value = targets.rtInfo.texture; mu.tCastDepth.value = targets.rtInfo.depthTexture;\n    mu.uCastRes.value.set(buf.x, buf.y); mu.uCastNear.value = camera.near; mu.uCastFar.value = camera.far; mu.uCastPpm.value = ppmBuf;\n  }\n  R.setRenderTarget(targets.rt); R.clear(); R.render(scene, camera);\n  const u = paint.mat.uniforms;\n  u.tColor.value = targets.rt.texture; u.tInfo.value = targets.rtInfo.texture; u.tDepth.value = targets.rtInfo.depthTexture;\n  u.uRes.value.set(buf.x, buf.y); u.uNear.value = camera.near; u.uFar.value = camera.far;\n  // line weight follows the figure's size on screen (study: ~0.4% of its height)\n  const ppm = buf.y / (camera.top - camera.bottom) * camera.zoom, dpr = R.getPixelRatio();\n  u.uSil.value = THREE.MathUtils.clamp(1.75 * ppm * 0.0042, dpr, 2.6 * dpr);\n  u.uInner.value = Math.max(dpr * 0.75, u.uSil.value * 0.55);\n  u.uPpm.value = ppm;\n  R.setRenderTarget(null); R.clear(); R.render(paint.scene, compCam);\n}\n\n// ---- check sheets ----------------------------------------------------------------------------------------------------\n// ?sheet=<name> poses one character through every check view; ?sheet=duel shows the bind. Each tile\n// is posed, its cloth settled at that angle, rendered by the same painted renderer as the page, and\n// drawn into one image, which lands in #sheetOut as a PNG data URL (a headless browser reads it).\nconst ARMS_YAWS = [0, 45, 90, 135, 180, 270];\nconst CHAR_ROWS = [\n  // arms down, as character design sheets are drawn: the row to compare against references\n  { label: \"Reference pose\", tiles: [0, 30, 90, 180, 270, 330].map(y => ({ clip: \"ref\", t: 0, yaw: y, pitch: 0, hide: [\"sword\", \"weapon\"], label: `${y}°` })) },\n  { label: \"Head\", tiles: [0, 30, 90, 150, 180, 270].map(y => ({ clip: \"ref\", t: 0, yaw: y, pitch: 4, focus: \"J_Bip_C_Head\", dy: 0.03,\n      size: 0.42, hide: [\"sword\", \"weapon\"], label: `${y}°` })) },\n  { label: \"Arms out\", tiles: ARMS_YAWS.map(y => ({ clip: \"apose\", t: 0, yaw: y, label: `${y}°` })) },\n  { label: \"Idle\", tiles: ARMS_YAWS.map(y => ({ clip: \"idle\", t: 0, yaw: y, label: `${y}°` })) },\n  // the idle loop through time from one side (the camera holds still: the body's rise and sink shows)\n  { label: \"Idle loop\", tiles: [0, 0.4, 0.8, 1.0, 1.3, 1.6].map(t => ({ clip: \"idle\", t, yaw: 300, label: `${t.toFixed(1)} s` })) },\n  for (let s = 0; s < 150; s++) cs.forEach(c => c.cloths.forEach(cl => cl.step(1 / 120, s / 120)));\n  cs.forEach(c => c.cloths.forEach(cl => cl.write()));\n}\nfunction frameAt(centre, h, tw, th, pitch) {\n  const w = h * tw / th, a = THREE.MathUtils.degToRad(pitch);\n  camera.left = -w / 2; camera.right = w / 2; camera.top = h / 2; camera.bottom = -h / 2; camera.zoom = 1;\n  camera.updateProjectionMatrix();\n  camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(15));\n  camera.up.set(0, 1, 0); camera.lookAt(centre); ctl.target.copy(centre);\n}\nasync function runSheet(kind) {\n  document.body.classList.add(\"sheet\");\n  const lineup = kind === \"lineup\", duel = kind === \"duel\" || lineup;\n  if (!duel) state.who = kind;\n348:  uniform sampler2D tCastInfo; uniform sampler2D tCastDepth; uniform vec2 uCastRes; uniform int uCastOn;\n349:  uniform float uCastNear; uniform float uCastFar; uniform float uCastPpm;\n354:    vec2 uv = gl_FragCoord.xy / uCastRes, px = 1.0 / uCastRes;\n355:    float z0 = uCastNear + texture2D(tCastDepth, uv).x * (uCastFar - uCastNear);\n362:      vec2 q = uv + dir * dm * uCastPpm * px;\n367:      float zq = uCastNear + texture2D(tCastDepth, q).x * (uCastFar - uCastNear);\n427:    else if (uCastOn == 1 && uKind == 1 && int(uInfo.x * 255.0 + 0.5) == 2 && castShadow() > 0.5)\n618:const R = new THREE.WebGLRenderer({ antialias: false, alpha: true, preserveDrawingBuffer: !!SHEET });\n870:    tCastInfo: { value: null }, tCastDepth: { value: null }, uCastRes: { value: new THREE.Vector2(1, 1) }, uCastOn: { value: 0 },\n871:    uCastNear: { value: 0.1 }, uCastFar: { value: 40 }, uCastPpm: { value: 1 },\n1407:    const mu = o.material.uniforms; mu.uPass.value = 1; mu.uCastOn.value = 0; mu.tCastInfo.value = null; mu.tCastDepth.value = null;\n1413:    mu.uPass.value = 0; mu.uCastOn.value = 1; mu.tCastInfo.value = targets.rtInfo.texture; mu.tCastDepth.value = targets.rtInfo.depthTexture;\n1414:    mu.uCastRes.value.set(buf.x, buf.y); mu.uCastNear.value = camera.near; mu.uCastFar.value = camera.far; mu.uCastPpm.value = ppmBuf;\n\"\"\"Patch a scratch copy of the built armory page: tiles may take a close-up lens (`lens`, mm on a 36 mm wide frame)\nand Flattice (`flat`, 0..1), drawn by the page's own painted renderer.\n\nFlattice is DillonGoo's add-on done in the vertex shader: every vertex is squashed toward a plane through the head\nbone's head, along the line from there to the camera, by `flat` times a weight that is 1 above the chin and fades to\n0 over 5 cm below it (the add-on's MOD-Flattice group with the cursor at the chin). Normals are left as they were, as\nthe Yin rig shades from normals stored before its lattice. Under a lens the outline pass reads perspective depth.\nAt flat 1 every layer of the head lands on one plane and a depth buffer can't order them (hair, skin and mouth\ninterior fight); 0.85 keeps enough depth, and the outline pass's depth step shrinks with the squash.\n\n  python3 patch_lens_flattice.py SITE_DIR\n\"\"\"\n"}
  • exec_commandpwd && ls -la && ls -la ~/out && cat ~/context/brief-lowmarch-full.md

    command

    pwd && ls -la && ls -la ~/out && cat ~/context/brief-lowmarch-full.md

    result, 4 lines

    Script completed
    Wall time 0.1 seconds
    Output:
    {"chunk_id":"be8dd1","wall_time_seconds":0.00001005,"exit_code":0,"original_token_count":1121,"output":"~/work/lowmarch\ntotal 36\ndrwx------ 7 runner runner 4096 Nov 17 22:43 .\ndrwx------ 3 runner runner 4096 Nov 17 22:43 ..\n-rw------- 1 runner runner   49 Nov 17 22:43 .envrc\ndrwx------ 7 runner runner 4096 Nov 17 23:09 .git\n-rw------- 1 runner runner  124 Nov 17 22:43 .gitignore\ndrwx------ 5 runner runner 4096 Nov 17 22:43 art\ndrwx------ 2 runner runner 4096 Nov 17 22:43 docs\ndrwx------ 8 runner runner 4096 Nov 17 23:10 review\ndrwx------ 6 runner runner 4096 Nov 17 22:47 tools\ntotal 452\ndrwx------ 2 runner runner   4096 Nov 17 23:07 .\ndrwx------ 7 runner runner   4096 Nov 17 22:48 ..\n-rw------- 1 runner runner 444314 Nov 17 23:05 high-water.jpg\n-rw------- 1 runner runner   6239 Nov 17 23:08 index.html\nYou are running as GPT-6.2-Astra (gpt-6.2-astra) at effort high, in a session of your own. The owner, severian (he/him), asked to see what GPT-6.2-Astra would do with one of their lines of work, lowmarch, and to see one visual artifact you can make with what the project already has. The project's own session runs on a different model and is not to be touched; you are a separate, parallel look.\n\n## What lowmarch is\nA code-built anime character pipeline for a tactics game: VRoid bases reshaped in code, costumes, armour and hair generated in code, drawn by the project's own renderers (a painted three.js renderer is the target; the pixel renderer is abandoned). On 11-08 the owner decided to restart with one character from scratch, to find a faster, better way of working together; they haven't started yet.\n\nRead, in this order:\n1. `docs/handbook.md` in your worktree (entry point: each rule marked earned or guessed; guessed rules don't bind the restart)\n2. `~/context/reflect/lowmarch.html` (the 11-08 reflection; the box at the top is the restart plan)\n3. `~/context/lowmarch.md` (state, how to run things; numpy is in the user site, so run python3 without -I)\n4. `docs/portrait-guide.md`, `docs/vroid.md`, and whatever else in the repo you judge useful.\n\n## Your workspace\n- Your current folder is the git worktree `~/work/lowmarch` (branch `astra62`, made for you from master a97f25f). Work only here; you may commit here. Never touch any other repo.\n- Data lives in `~/.local/share/lowmarch/`: read it, don't modify it.\n- Output folder: `~/out/` (copied to the owner's review route afterwards).\n- Licences: the Yin/Yang rigs are personal-use study material (keep them out of the visual); FE8 references are study only, never traced or shown; VRoid CC0 bodies and the AvatarSample faces are fine for renders.\n\n## Rules\n- Headless only: no windows on the owner's desktop. Never run anything that drives Windows programs (no tools/winvroid, no powershell.exe, cmd.exe or anything under /mnt/c). Browser rendering via headless Chromium only (Playwright is at `~/context/sortie-node_modules/playwright`; page-side code compiled by tsx can throw \"__name is not defined\", so keep page-side code as plain .js evaluated as text). Blender only with `-b`.\n- Don't install packages. Don't run the full test suite (a test run once ate 36 GB); targeted checks only.\n- Nothing runs on the C1 machine; no ssh. No network uploads, no publishing anywhere. Never push.\n- Edit files only in your worktree and your output folder. Never push.\n\n## Deliverable\nOne self-contained HTML page, `index.html` in your output folder, with its images (or a short clip) beside it. The owner finds wordy interfaces tiring: organise, don't narrate; short labelled sections, plain words, no em dashes. At the top: \"GPT-6.2-Astra (gpt-6.2-astra), effort high\" and the date.\n1. **Your read of this line of work:** what's working, what isn't, what you'd keep and drop, and what you would do differently in the restart. Give opinions plainly; disagree with the reflection page where you do.\n2. **What you'd do next** if you ran the restart's first session: a short, concrete sequence.\n3. **The one visual:** a single visual artifact made with what the project already has (its tools, kits, renderers, models, data). Your choice of what it is; pick the thing that best shows what you'd do with this work. Show it large, then say in a few lines how it was made (the commands, wall time) and what you'd change next.\nKeep it to one visual; don't build a gallery. Aim to be done in roughly 90 minutes of work.\n\nWhen done, end your turn with: the page path, a 5-line summary, and any commits on your branch. If something only the owner can decide blocks you, say so and stop rather than guessing.\n"}
  • exec_commandcat review/out/tide-keeper/build.log && ls -lh review/out/tide-keeper && cat review/high-water/shoot.cjs review/high-water/shot.js

    command

    cat review/out/tide-keeper/build.log && ls -lh review/out/tide-keeper && cat review/high-water/shoot.cjs review/high-water/shot.js

    result, 86 lines

    Script completed
    Wall time 0.2 seconds
    Output:
    Fit, hair, coat and armour 18.08s
    Base GLB 1.54s
    Animation, dye maps and packaging 7.52s
    Build total 27.14s
    total 20M
    -rw------- 1 runner runner 8.2M Nov 17 23:18 base.glb
    -rw------- 1 runner runner  108 Nov 17 23:18 build.log
    -rw------- 1 runner runner  11K Nov 17 23:18 camera.json
    -rw------- 1 runner runner 112K Nov 17 23:10 index.html
    -rw------- 1 runner runner  12M Nov 17 23:18 ione.glb
    // Read the project viewer directly so its colour, depth and outline passes stay together.
    // Playwright serves all inputs from disk. Chromium never needs a network connection.
    const fs = require("node:fs/promises");
    const path = require("node:path");
    const os = require("node:os");
    
    const root = path.resolve(__dirname, "../..");
    const cache = path.join(root, "review/out/high-water");
    const packages = process.env.LOWMARCH_NODE_MODULES || path.join(os.homedir(), "context/sortie-node_modules");
    const three = path.join(packages, "three");
    const { chromium } = require(path.join(packages, "playwright-core"));
    
    async function main() {
      const profile = path.join(cache, "browser");
      await fs.mkdir(profile, { recursive: true });
      process.env.TMPDIR = profile;
      const viewer = await fs.readFile(path.join(root, "review/vroid-02/index.html"), "utf8");
      const ending = viewer.indexOf("if (!LINEUP.order.length)");
      if (ending === -1) throw new Error("Cannot find the viewer entry point");
      const shot = await fs.readFile(path.join(__dirname, "shot.js"), "utf8");
      const html = viewer.slice(0, ending).replace(/<link [^>]+>/g, "").replaceAll("https://cdn.jsdelivr.net/npm/three@0.160.0/", "/three/") + shot + "\n</script>";
      const binary = await fs.readFile(path.join(cache, "figure.glb"));
      const browser = await chromium.launch({ headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
      try {
        const page = await browser.newPage();
        const errors = [];
        page.on("pageerror", e => errors.push(String(e)));
        page.on("console", msg => { if (msg.type() === "error") errors.push(msg.text() + " " + JSON.stringify(msg.location())); });
        await page.route("**/*", async route => {
          const url = new URL(route.request().url());
          if (url.origin !== "http://lowmarch.local") return route.abort();
          const p = url.pathname;
          if (p === "/") return route.fulfill({ body: html, contentType: "text/html" });
          if (p === "/figure.glb.json") return route.fulfill({ json: {glb: binary.toString("base64")} });
          if (p === "/camera.json") return route.fulfill({ path: path.join(cache, "camera.json") });
          if (p.startsWith("/three/") && p.endsWith(".js")) {
            return route.fulfill({ path: path.join(three, p.slice(7)), contentType: "text/javascript" });
          }
          return route.abort();
        });
        await page.goto("http://lowmarch.local/?sheet=figure");
        if (errors.length) throw new Error(errors.join("\n"));
        await page.waitForFunction(() => !!window.studyPNG, null, { timeout: 45000 }).catch(e => { throw new Error(errors.join("\n") || e.message); });
        const png = await page.evaluate(() => window.studyPNG);
        if (!png || errors.length) throw new Error(errors.join("\n") || "No painted frame");
        await fs.writeFile(path.join(cache, "figure.png"), Buffer.from(png.split(",")[1], "base64"));
      } finally {
        await browser.close();
      }
    }
    main().catch(err => { console.error(err); process.exitCode = 1; });
    // Runs as the final lines of the review viewer's module in headless Chromium.
    state.view = "battle";
    state.cloth = false;
    const actor = await loadCharacter("figure");
    stage.add(actor.turn);
    actor.turn.rotation.y = THREE.MathUtils.degToRad(62);
    const height = 2.36, width = 2.65, middle = .99;
    R.setPixelRatio(1);
    R.setSize(1590, 1416, false);
    camera.left = -.43 * width;
    camera.right = .57 * width;
    camera.top = height / 2;
    camera.bottom = -height / 2;
    camera.position.set(0, middle + .40, 5.5);
    camera.lookAt(0, middle, 0);
    camera.updateProjectionMatrix();
    for (const mesh of actor.meshes) {
      mesh.userData.mats.painted.uniforms.uKey.value.set(.43, .56, .70).normalize();
    }
    render();
    window.studyPNG = R.domElement.toDataURL("image/png");
    
  • exec_commandrg -n 'function (render|lensAndFlat|loadCharacter|prepMesh)|const PAINT_FS|gl_FragColor = vec4\(clamp|uGrain|beginnormal_vertex|begin_vertex|skinning_pars_vertex|function frameAt' review/out/tide-keeper/index.html && cat review/tide-keeper/build.py && tail -115 review/tide-keeper/portable.py

    command

    rg -n 'function (render|lensAndFlat|loadCharacter|prepMesh)|const PAINT_FS|gl_FragColor = vec4\(clamp|uGrain|beginnormal_vertex|begin_vertex|skinning_pars_vertex|function frameAt' review/out/tide-keeper/index.html && cat review/tide-keeper/build.py && tail -115 review/tide-keeper/portable.py

    result, 214 lines

    Script completed
    Wall time 0.1 seconds
    Output:
    310:  #include <skinning_pars_vertex>`;
    311:const SKIN_BODY = `#include <beginnormal_vertex>
    314:    #include <begin_vertex>
    349:const PAINT_FS = `
    352:  uniform vec3 uGold; uniform vec3 uAmbient; uniform vec3 uKeyCol; uniform vec3 uRimCol; uniform float uGrain;
    445:      float l = lit + (g1 - 0.5) * uGrain - (uKind == 6 ? 0.22 : 0.0);  // ground: a flat top sits at the base colour
    522:    gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
    877:    uGrain: { value: 0.05 }, uFaceTex: { value: 0 }, uDecal: { value: decal ? 1 : 0 }, uBand: { value: null },
    883:  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; }
    885:  if (P && P.kind === "world") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.12; }
    928:function prepMesh(o, V, opts = {}) {
    956:async function loadCharacter(name) {
    1398:function render() {
    1515:function frameAt(centre, h, tw, th, pitch) {
    1522:function lensAndFlat(tile, centre, h, tw, th, pitch) {
    """Build the fitted and animated tide surveyor in metres. Only reads the armory cache."""
    from pathlib import Path
    import sys, json, time
    import numpy as np
    
    HERE=Path(__file__).resolve().parent
    ROOT=HERE.parents[1]
    CACHE=ROOT/"review/out/tide-keeper"
    sys.path[:0]=[str(ROOT/"tools"),str(ROOT/"art/cast"),str(ROOT/"review/high-water")]
    from cast import CAST
    import cage, vroid_portrait as vp, poses, rig, export_glb
    from vrm import VRM
    from tailoring import outfit
    import figure as first
    
    COLOURS={"canvas":"#e8d7af","porcelain":"#bcd8d0","seasteel":"#477278","deepsea":"#233f48",
             "reef":"#223843","vermilion":"#c34e38","poppy":"#e69a58","ivory":"#f3dfb5",
             "brass":"#d1a461","glaze":"#459795","saddle":"#81503b","boot":"#463b3d","rubber":"#292e36",
             "wood":"#523d32","glove":"#4c3e3c","inkhair":"#282c37","bluehair":"#3d4049",
             "umberhair":"#573e40","silk":"#e3c5a2","redcord":"#b14b3e","coral":"#d87556","skin":"#d8a57f"}
    METALS={"brass","porcelain","seasteel","glaze"}
    
    
    def action(v,shape):
        # The step and staff use the opening study's contact points. She sights the
        # crossing with the left hand, now above the brow, and leans over her lead leg.
        pose=first.make_pose(v,shape)
        r=rig.Rig(v,shape,ortho=True)
        head=r.pos(pose,"J_Bip_C_Head")
        pose=r.arm_ik(pose,"L",head+[-.116,.115,-.114],[-.95,-.2,.25])
        pose=r.aim(pose,"J_Bip_L_Hand",[-1,0,0],[.92,.14,-.21])
        for finger in ("Index","Middle","Ring","Little"):
            for i,k in enumerate((6,8,5),1):
                pose[f"J_Bip_L_{finger}{i}"]=poses.rot((0,0,1),k)
        keys=[]
        for t,s,turn in [(0,0,0),(.8,1,-2.0),(1.6,0,0),(2.4,-.65,2.5),(3.2,0,0)]:
            q=poses.merge(pose,{"J_Bip_C_Chest":poses.rot((1,0,0),s*1.4),
                                 "J_Bip_C_Head":poses.rot((0,1,0),turn)@poses.rot((1,0,0),s*2.4)})
            # Replant the shaft through the moving shoulder at each authored extreme.
            grip=rig.grip_points(v,shape,vp.BUST_POSE)["R"]["point"]
            target=r.held(pose,"J_Bip_R_Hand",vp.BUST_POSE,grip)
            q=r.grip(q,"R",vp.BUST_POSE,grip,target,[-.16,1,.035],[.95,-.65,.4],iters=3)
            keys.append((t,q))
        return keys
    
    
    def build():
        start=time.perf_counter()
        CACHE.mkdir(exist_ok=True,parents=True)
        cast=CAST["arm_f_strong"]
        path=cage.path_for("arm_f_strong",cast["cage"])
        shape=dict(vp.NEUTRAL,**cast["shape"])
        shape.update(shoulder_w=.012,arms=1.09,legs=1.06,torso=1.025,neck=1.045,
                     cheek=.55,jaw=.62,nose=.75,chin_w=.37,eye=.97,iris=.96,blush=.25)
        actor=vp.Portrait(path,shape=shape,pose=vp.BUST_POSE,costume=outfit,
                          morphs={"Fcl_BRW_Angry":.24,"Fcl_EYE_Angry":.16,"Fcl_MTH_Fun":.16})
        # Remove every donated hair mesh, including the painted hair base. The new
        # cut uses its own continuous shell, hairline and individual swept locks.
        keep=[(p,r) for p,r in zip(actor.prims,actor.roles) if r!="hair"]
        actor.prims,actor.roles=map(list,zip(*keep))
        actor.paint={k:dict(kind="steel" if k in METALS else "cloth",base=c) for k,c in COLOURS.items()}
        for k in ["skin","glove","boot"]: actor.paint[k]=COLOURS[k]
        actor.paint.update(gold=COLOURS["brass"],hair=COLOURS["inkhair"])
        palette=dict(vp.PALETTE,**cast["colors"])
        palette.update(A="#352729",r="#302822",s="#69796d",t="#d8bd7f")
        from portable import finish
        print(f"Fit, hair, coat and armour {time.perf_counter()-start:.2f}s",flush=True)
        t=time.perf_counter()
        export_glb.export_skinned(actor,palette,CACHE/"base.glb",max_tex=1024)
        print(f"Base GLB {time.perf_counter()-t:.2f}s",flush=True)
        t=time.perf_counter()
        keys=action(actor.v,shape)
        info=export_glb.scene_info(actor,palette)
        finish(actor,keys,info,COLOURS,METALS,CACHE)
        (CACHE/"camera.json").write_text(json.dumps({"characters":[{"name":"figure","info":info}]}))
        print(f"Animation, dye maps and packaging {time.perf_counter()-t:.2f}s",flush=True)
        print(f"Build total {time.perf_counter()-start:.2f}s",flush=True)
    
    
    if __name__=="__main__": build()
        a=np.array(ImageColor.getrgb(col))/255
        return np.where(a<=.04045,a/12.92,((a+.055)/1.055)**2.4).tolist()
    
    
    def finish(actor,keys,info,colours,metals,directory):
        base=VRM(directory/"base.glb"); doc=base.j; data=bytearray(base.bin)
        def view(blob,target=None):
            data.extend(b"\0"*((-len(data))%4)); off=len(data); data.extend(blob)
            v=dict(buffer=0,byteOffset=off,byteLength=len(blob))
            if target: v["target"]=target
            doc["bufferViews"].append(v)
            return len(doc["bufferViews"])-1
        def accessor(a,kind,target=None):
            a=np.ascontiguousarray(a,dtype=np.float32)
            v=view(a.tobytes(),target); flat=a.reshape(len(a),-1)
            doc["accessors"].append(dict(bufferView=v,componentType=5126,count=len(a),type=kind,
                                         min=flat.min(0).tolist(),max=flat.max(0).tolist()))
            return len(doc["accessors"])-1
        textures={}
        def texture(key,fn):
            if key not in textures:
                im=fn()
                b=io.BytesIO(); im.save(b,"PNG",optimize=False)
                doc["images"].append(dict(bufferView=view(b.getvalue()),mimeType="image/png",name=key))
                doc["textures"].append(dict(source=len(doc["images"])-1,sampler=0))
                textures[key]=len(doc["textures"])-1
            return {"index":textures[key]}
        def original(pbr):
            idx=pbr["baseColorTexture"]["index"]
            return Image.fromarray(base.image(doc["textures"][idx]["source"]))
        eligible=[(p,r) for p,r in zip(actor.prims,actor.roles) if r!="skip" and len(p["tri"]) and "J" in p and not p.get("world")]
        mesh_nodes=[(i,n) for i,n in enumerate(doc["nodes"]) if "mesh" in n]
        assert len(mesh_nodes)==len(eligible)
        morph_nodes=[]
        for (pc,role),(index,node) in zip(eligible,mesh_nodes):
            mesh=doc["meshes"][node["mesh"]]; prim=mesh["primitives"][0]
            mat=doc["materials"][prim["material"]]; pbr=mat["pbrMetallicRoughness"]
            name=pc["material"].removeprefix("OUTFIT_")
            node["name"]=name+"_"+str(index); mesh["name"]=name
            used=np.unique(pc["tri"])
            if role in colours:
                pbr["baseColorFactor"]=linear(colours[role])+[1]
                pbr["metallicFactor"]=.52 if role=="brass" else .25 if role in metals else 0.
                pbr["roughnessFactor"]=.32 if role in metals else .55 if role in ("saddle","boot") else .78
            if pc.get("pigment"):
                pattern=pc["pigment"]
                bitmap=texture(role+"_"+pattern,lambda:dye(pattern,colours[role]))
                prim["attributes"]["TEXCOORD_0"]=accessor(pc["uv"][used],"VEC2",34962)
                pbr["baseColorTexture"]=bitmap; pbr["baseColorFactor"]=[1,1,1,1]
                mat["extras"]={"pigment":True}
            if pc.get("strands"):
                # The shared kit's strand texture is grey. Tint it into a finished
                # colour map with a smooth broad highlight and fine, winding grooves.
                def strand():
                    yy,xx=np.mgrid[:256,:256]; u=xx/255; v=yy/255
                    shade=.86+.19*(np.cos(2*np.pi*(u-.14))*.5+.5)+.10*np.sin(8*np.pi*(u+.035*np.sin(5*v)))**8
                    c=np.array(ImageColor.getrgb(colours[role]))
                    return Image.fromarray(np.uint8(np.clip(c*shade[...,None],0,255)))
                pbr["baseColorTexture"]=texture("locks_"+role,strand)
                pbr["baseColorFactor"]=[1,1,1,1]; mat["extras"]={"pigment":True}
            if role=="face":
                ref=original(pbr)
                def face():
                    a=np.array(face_map(ref),dtype=float)
                    return Image.fromarray(np.uint8(np.clip(a*(np.array(ImageColor.getrgb(colours["skin"]))/[246,224,204]),0,255)))
                pbr["baseColorTexture"]=texture("sun_freckles",face)
                pbr["baseColorFactor"]=[1,1,1,1]
            elif role in ("body","shadow"):
                pbr["baseColorFactor"]=linear(colours["skin"] if role=="body" else "#bf896f")+[1]
            elif role=="iris":
                raw=original(pbr)
                def iris():
                    a=np.array(raw); v=a[:,:,:3].mean(2)/255
                    out=np.stack([np.interp(v,[0,.29,1],[int(k[1:][j:j+2],16) for k in info["roles"]["iris"]["colors"]]) for j in (0,2,4)],axis=-1)
                    return Image.fromarray(np.dstack([np.uint8(out),a[:,:,3]]))
                pbr["baseColorTexture"]=texture("estuary_iris",iris)
                pbr["baseColorFactor"]=[1,1,1,1]
            elif role in ("line","brow"):
                pbr["baseColorFactor"]=linear("#45303b" if role=="line" else "#574044")+[1]
            if "gust" in pc:
                a=pc["gust"][used]*glb.FLIP
                prim["targets"]=[{"POSITION":accessor(a,"VEC3",34962)}]
                mesh["weights"]=[0.0]; mesh["extras"]={"targetNames":["Crosswind"]}
                morph_nodes.append(index)
        # Compute the local transforms once per key. Geometry remains in the
        # neutral fitting pose and uses the original inverse bind matrices.
        names=actor.v.nodes_by_name()
        frames=[vp.bone_pose(actor.v,actor.shape,p) for _,p in keys]
        times=accessor(np.array([t for t,_ in keys]),"SCALAR")
        samplers=[]; channels=[]
        def track(index,path,array,kind):
            samplers.append(dict(input=times,output=accessor(array,kind),interpolation="LINEAR"))
            channels.append(dict(sampler=len(samplers)-1,target=dict(node=index,path=path)))
        for i in doc["skins"][0]["joints"]:
            node=doc["nodes"][i]; source=names[node["name"]]
            samples=[glb._trs(glb.F4@actor.v.local_matrix(source,p)@glb.F4) for p in frames]
            for j,(path,kind) in enumerate([("translation","VEC3"),("rotation","VEC4"),("scale","VEC3")]):
                a=np.array([s[j] for s in samples])
                if path=="rotation":
                    for k in range(1,len(a)):
                        if np.dot(a[k-1],a[k])<0:a[k]*=-1
                node[path]=a[0].tolist()
                if abs(a-a[0]).max()>1e-5: track(i,path,a,kind)
        wind_id=len(samplers)
        samplers.append(dict(input=times,output=accessor(np.array([0,.74,.95,.33,0]),"SCALAR"),interpolation="LINEAR"))
        for i in morph_nodes:channels.append(dict(sampler=wind_id,target=dict(node=i,path="weights")))
        doc["animations"]=[dict(name="Read the tide",samplers=samplers,channels=channels)]
        doc["nodes"][doc["scenes"][0]["nodes"][0]]["name"]="Ione • Tide keeper"
        doc["asset"]["generator"]="Lowmarch export_glb + Tide Keeper"
        doc["asset"]["extras"]={"units":"metres","front":"+Z","study":"High water","clip":"Read the tide"}
        data.extend(b"\0"*((-len(data))%4)); doc["buffers"][0]["byteLength"]=len(data)
        js=json.dumps(doc,separators=(",",":"),allow_nan=False).encode()
        js+=b" "*((-len(js))%4)
        (directory/"ione.glb").write_bytes(struct.pack("<4sII",b"glTF",2,28+len(js)+len(data))+
            struct.pack("<I4s",len(js),b"JSON")+js+struct.pack("<I4s",len(data),b"BIN\0")+data)
    
  • exec_commandsed -n '354,403p;928,990p;1398,1445p;1510,1563p' review/out/tide-keeper/index.html && cat review/tide-keeper/tailoring.py | tail -75 && rg -n 'staff|compose|CACHE' review/high-water/marsh.py && date -u

    command

    sed -n '354,403p;928,990p;1398,1445p;1510,1563p' review/out/tide-keeper/index.html && cat review/tide-keeper/tailoring.py | tail -75 && rg -n 'staff|compose|CACHE' review/high-water/marsh.py && date -u

    result, 252 lines

    Script completed
    Wall time 0.1 seconds
    Output:
    Warning: truncated output (original token count: 4627)
    Total output lines: 296
    
      uniform int uSkinRamp; uniform vec3 uSkinL; uniform vec3 uSkinS; uniform vec3 uSkinC;
      uniform sampler2D tCastInfo; uniform sampler2D tCastDepth; uniform vec2 uCastRes; uniform int uCastOn;
      uniform float uCastNear; uniform float uCastFar; uniform float uCastPpm;
      // Cast shadows on skin, in screen space (the "depth offset" shadows of anime toon shaders): walk from this pixel
      // toward the key light across the info pass already drawn; if the face (the jaw) or hair stands in front of that
      // ray, this pixel is in its shadow. The shape is the caster's own outline as the camera sees it, at any angle.
      float castShadow() {
        vec2 uv = gl_FragCoord.xy / uCastRes, px = 1.0 / uCastRes;
        float z0 = uCastNear + texture2D(tCastDepth, uv).x * (uCastFar - uCastNear);
        float sxy = length(uKey.xy);
        if (sxy < 0.05) return 0.0;
        vec2 dir = uKey.xy / sxy;
        float lz = uKey.z / sxy;                                    // the ray's rise toward the camera per metre across
        for (int s = 1; s <= 14; s++) {
          float dm = float(s) * 0.003;                              // 3 mm steps across the screen, up to 4.2 cm
          vec2 q = uv + dir * dm * uCastPpm * px;
          vec4 ni = texture2D(tCastInfo, q);
          if (ni.a < 0.5) continue;
          int r = int(ni.r * 255.0 + 0.5);
          if (r != 1 && r != 3 && r != 11) continue;                // casters: the face (jaw, chin) and hair
          float zq = uCastNear + texture2D(tCastDepth, q).x * (uCastFar - uCastNear);
          float zr = z0 - lz * dm;
          if (zq < zr - 0.004 && zq > zr - 0.20) return 1.0;
        }
        return 0.0;
      }
      varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying float vEdge; varying vec4 vPlate;
      ${HSV}
      float hash(vec3 p) { p = fract(p * 0.3183099 + 0.1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }
      float vnoise(vec3 x) {
        vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f);
        return mix(mix(mix(hash(i), hash(i + vec3(1,0,0)), f.x), mix(hash(i + vec3(0,1,0)), hash(i + vec3(1,1,0)), f.x), f.y),
                   mix(mix(hash(i + vec3(0,0,1)), hash(i + vec3(1,0,1)), f.x), mix(hash(i + vec3(0,1,1)), hash(i + vec3(1,1,1)), f.x), f.y), f.z);
      }
      float toward(float h, float target, float amt) { float d = target - h; d -= floor(d + 0.5); return fract(h + clamp(d, -amt, amt)); }
      vec3 tone(vec3 base, float hue, float amt, float sMul, float vMul) {
        vec3 h = rgb2hsv(base);
        return hsv2rgb(vec3(toward(h.x, hue, amt), clamp(h.y * sMul, 0.0, 1.0), clamp(h.z * vMul, 0.0, 1.0)));
      }
      float st(float x, float t) { return smoothstep(t - 0.03, t + 0.03, x); }
      // Steel and gold. Hard reflection bands (dark below the horizon, a dark core under a white streak)
      // read well where the surface turns fast: rims, tubes, lames. On a broad plate the reflection
      // barely changes, so a band there fills the whole plate (the blotches): bands fade by how sharply
      // the surface curves (normal change per metre on screen), and broad plates get a soft tone that
      // lightens up each outline plate (hgt: height in the plate 0..1, or -1 without plate data).
      vec3 metal(bool gold, vec3 base, vec3 n, vec3 v, float lit, float hgt) {
        vec3 r = reflect(-v, n);
        float ry = r.y + (vnoise(vObj * vec3(3.0, 14.0, 3.0)) - 0.5) * 0.14;   // jitter the bands along their length, not into blobs
        float curv = length(fwidth(n)) / max(length(fwidth(vView)), 1e-5);
        float sharp = smoothstep(5.0, 14.0, curv);
    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;
    function render() {
      const meshes = allMeshes(), cs = active();
      applySkin(meshes);
      const cloths = cs.flatMap(c => c.cloths);
      if (state.mode === "3d") {
        mes…927 tokens truncated…;
      camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(15));
      camera.up.set(0, 1, 0); camera.lookAt(centre); ctl.target.copy(centre);
    }
    function lensAndFlat(tile, centre, h, tw, th, pitch) {
      const pu = paint.mat.uniforms;
      pu.uPersp.value = 0; camera.near = 0.1; camera.far = 40;
      if (pu.uGap.userData === undefined) pu.uGap.userData = pu.uGap.value;
      pu.uGap.value = pu.uGap.userData * (1 - (tile.flat || 0));   // depth steps shrink with the squash; so does the line test
      const chr = active()[0];
      if (tile.lens) {
        const w = h * tw / th, d = w * tile.lens / 36, a = THREE.MathUtils.degToRad(pitch), n = 0.01;
        camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(d));
        camera.lookAt(centre); camera.updateMatrixWorld(true);
        camera.near = n; camera.far = 40;
        camera.projectionMatrix.makePerspective(-w / 2 * n / d, w / 2 * n / d, h / 2 * n / d, -h / 2 * n / d, n, 40);
        camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
        pu.uPersp.value = 1;
      }
      const face = chr.meshes.find(o => /Face_00_SKIN/.test(o.name + " " + (o.userData.material || "")));
      face.geometry.computeBoundingBox();
      let pivot = chr.root.getObjectByName("J_Bip_C_Head").getWorldPosition(new THREE.Vector3());
      if (tile.pivot === "chin") {                      // the chin's front: the face's lowest points, the most forward of them
        const P = face.geometry.attributes.position, low = face.geometry.boundingBox.min.y, v = new THREE.Vector3();
        let best = null;
        for (let i = 0; i < P.count; i++) {
          v.fromBufferAttribute(P, i);
          if (v.y < low + 0.006 && (!best || v.z > best.z)) best = v.clone();
        }
        pivot = best.applyMatrix4(face.matrixWorld);
      }
      pivot.applyMatrix4(camera.matrixWorldInverse);
      for (const o of chr.meshes) {
        const mu = o.material.uniforms;
        if (!mu || !mu.uFlattice) continue;
        mu.uFlattice.value = tile.flat || 0;
        mu.uFlChin.value = tile.whole ? -100 : face.geometry.boundingBox.min.y + 0.01;   // whole: the body too
        mu.uFlFall.value = 0.05; mu.uFlPivot.value.copy(pivot);
      }
    }
    async function runSheet(kind) {
      document.body.classList.add("sheet");
      const lineup = kind === "lineup", duel = kind === "duel" || lineup;
      if (!duel) state.who = kind;
      if (params.get("mode") === "3d") state.mode = "3d";      // ?mode=3d: the plain 3D renderer (tells a geometry fault from a shading one)
      await setView(lineup ? "lineup" : duel ? "duel" : "battle");
            out.append(pipe(fit,"sleeve_turnup","reef",g[:,3],.008,bone))
        return out
    
    
    def instrument(fit):
        c,axis,side,flat,_=gear._hand_frame(fit)
        bone="J_Bip_R_Hand"
        out=[]
        def at(h): return c+axis*h
        out.append(rod(fit,"sounding_rod","wood",at(-1.19),at(.61),.012,.014,bone))
        out.append(rod(fit,"heel_ferrule","brass",at(-1.19),at(-1.105),.015,.015,bone))
        out.append(rod(fit,"bound_grip","saddle",at(-.083),at(.085),.018,.017,bone))
        for j in range(14):
            y=-1.095+j*.073
            out.append(rod(fit,"scale_"+str(j),"ivory" if j%3 else "brass",at(y),at(y+(.018 if j%3 else .033)),.0148,.0148,bone))
        for y in [-.091,.089,.53,.582]:
            out.append(rod(fit,"socket","brass",at(y),at(y+.012),.019,.019,bone))
        # An open brass tide dial. A separate plumb hangs through its centre.
        pivot=at(.71)
        across=side*.7+flat*.714
        out+= [ring(fit,"astrolabe_limb","brass",pivot,across,axis,.091,.105,.007,bone),
               ring(fit,"alidade","glaze",pivot,across,axis,.075,.086,.004,bone,sweep=(188,350))]
        for deg in range(0,360,15):
            phi=np.radians(deg); d=across*.088*np.cos(phi)+axis*.101*np.sin(phi)
            out.append(rod(fit,"dial_tick","ivory" if deg%45 else "brass",pivot+d*.96,
                           pivot+d*(.83 if deg%45==0 else .91),.002,.002,bone,8))
        for sign in [-1,1]:
            out.append(pipe(fit,"fork","seasteel",curve([at(.48),at(.54)+sign*.021*across,
                         at(.59)+sign*.053*across,at(.63)+sign*.059*across]),.007,bone))
        out.append(rod(fit,"plumb_line","brass",at(.805),at(.70),.0028,.0028,bone))
        out.append(rod(fit,"plumb_top","glaze",at(.715),at(.680),.004,.021,bone,6))
        out.append(rod(fit,"plumb_tip","glaze",at(.680),at(.633),.021,.001,bone,6))
        return out
    
    
    def outfit(fit):
        hips=fit.bone[HIP]; nk=fit.bone["J_Bip_C_Neck"]
        waist=hips[1]+.078
        pcs,shirt,trousers,boots=mobs._base(fit,shirt="reef",legs="deepsea",boots="boot",gloves="glove",
                                           boot_top=fit.bone["J_Bip_L_LowerLeg"][1]+.07,shirt_subdiv=1)
        chest_surface=Surface(*O.without(shirt,("UpperArm","LowerArm","Shoulder","Hand")))
        chart=TorsoChart(chest_surface,hips[1]-.050,nk[1]-.005,cz=hips[2],du=4.,dv=.009)
        torso=("Spine","Chest","UpperChest","Bust","Hips","Shoulder")
        # Armour closes high at the sides, dipping under the sternum to let the
        # front plates overlap like the shell ridges on the shoulder.
        for j,(y0,y1,col) in enumerate([(.00,.12,"seasteel"),(.095,.232,"seasteel"),(.201,.361,"porcelain")]):
            lower=lambda a:waist+y0+.033*(1-np.cos(np.radians(a)))+.014*abs(np.sin(np.radians(2*a)))
            upper=lambda a:waist+y1+.015*np.cos(np.radians(a*2))
            p,g=body_panel(fit,chart,"corselet_"+str(j),col,(-177,177),lower,upper,.022+j*.002,torso,"armour")
            pcs.append(p); pcs.append(pipe(fit,"cuirass_roll","brass",g[:,0],.0038,torso))
            if j==2: pcs.append(pipe(fit,"cuirass_neckline","reef",g[:,-1],.0055,torso))
        belt,g=body_panel(fit,chart,"harness","saddle",(-180,180),lambda a:waist-.033+.012*np.sin(np.radians(a)),
                          lambda a:waist+.014+.012*np.sin(np.radians(a)),.037,HIP)
        pcs.extend([belt,pipe(fit,"belt_stitch","brass",g[:,1],.002,HIP)])
        # A diagonal leather baldric anchors the chart case at the near hip.
        a=np.linspace(-36,86,44)
        y=np.linspace(nk[1]-.10,waist-.010,44)
        strap=np.stack([chart.point(a+j,y,.041) for j in [-5,5]],axis=1)
        pcs.append(skin_grid(fit,"sounding_harness","saddle",strap,torso,[0,waist,hips[2]]))
        pcs.append(pipe(fit,"baldric_edge","brass",strap[:,0],.0018,torso))
        centre=chart.point(78,waist,.048)+[.02,-.090,.013]
        ex=np.array([.17,.13,-.976]); ey=np.array([-.015,.991,.13]); n=np.cross(ex,ey)
        for name,role,coords,offset,thick in [
            ("chart_case","saddle",[(-.083,.07),(.08,.07),(.09,-.04),(.063,-.097),(-.068,-.088),(-.086,-.045)],0,.044),
            ("case_flap","reef",[(-.088,.074),(.087,.076),(.085,.020),(.028,-.027),(-.06,-.016)],.027,.012)]:
            p=flat_piece(name,role,coords,centre+n*offset,ex,ey,thickness=thick)
            pcs.append(attach(fit,p,HIP))
        pcs.append(bead(fit,"case_fastening","brass",centre+.038*n,.009,HIP))
        for offset in [-.05,.05]:
            start=centre+offset*ex+.065*ey
            pcs.append(rod(fit,"belt_loop","saddle",start,start+[0,.055,-.01],.009,.010,HIP))
        pcs+=coat(fit,chart,waist)+scarf(fit,chart)
        pcs+=gauntlets(fit,shirt)+shell_armour(fit,"R")+shell_armour(fit,"L")+legs(fit,boots)
        pcs+=instrument(fit)+coiffure(fit)
        return pcs
    11:CACHE = HERE.parents[1] / "review/out/high-water"
    342:def compose(output):
    358:    actor = Image.open(CACHE/"figure.png").convert("RGBA")
    377:    # Cast the silhouette toward the near bank. Keep the staff shadow faint in
    413:    compose(parser.parse_args().output)
    Tue Nov 17 23:21:32 UTC 2026