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

agent (cont.)

+37:28
  • exec_commandsed -n '411,435p;1398,1437p;1512,1522p' review/out/tide-keeper/index.html && sed -n '342,409p' review/high-water/marsh.py && rg -n 'active =|function active|function allMeshes|actor|V =|uSkinRef' review/out/tide-keeper/index.html | tail -22

    command

    sed -n '411,435p;1398,1437p;1512,1522p' review/out/tide-keeper/index.html && sed -n '342,409p' review/high-water/marsh.py && rg -n 'active =|function active|function allMeshes|actor|V =|uSkinRef' review/out/tide-keeper/index.html | tail -22

    result, 158 lines

    Script completed
    Wall time 0.1 seconds
    Output:
        vec3 hard = mix(s0, s1, st(ry, -0.42));                          // facing down: dark
        hard = mix(hard, s2, st(ry, -0.08));                             // facing us: the plate's own grey
        hard = mix(hard, s0, st(ry, 0.36));                              // dark core under the streak
        hard = mix(hard, s3, st(ry, 0.47));                              // the white streak
        hard = mix(hard, s2 * 1.06, st(ry, 0.70));
        float k = smoothstep(-0.55, 0.30, r.y);                          // broad: darker toward the ground (no jitter:
        if (hgt >= 0.0) k = clamp(k * 0.45 + hgt * 0.80 - 0.18, 0.0, 1.0);   // on a flat plate it streaks)
        else k = clamp(k * 0.6 + n.y * 0.35 + 0.05, 0.0, 1.0);           // without plate data: lighter facing up
        vec3 soft = mix(s1 * 0.9, s2, k);
        float hl = dot(n, normalize(uKey + v));                          // the key's highlight, a hard-edged shape
        if (hgt >= 0.0) soft = mix(soft, mix(s2, s3, 0.6), st(hl, 0.955) * smoothstep(0.45, 0.8, hgt));   // the upper part only
        vec3 col = mix(soft, hard, sharp);
        return mix(col * 0.72 + s0 * 0.28, col, st(lit, 0.30));
      }
      void main() {
        vec4 tex = texture2D(uMap, vUv);
        if (uAlpha == 1 && tex.a < 0.5) discard;
        if (uAlpha == 2 && (tex.a < 0.5 || dot(tex.rgb, vec3(1.0 / 3.0)) >= 0.42)) discard;
        if (uPass == 1) { gl_FragColor = uInfo; return; }
        vec3 n = normalize(vN); if (!gl_FrontFacing) n = -n;
        vec3 v = normalize(vView);
        float lit = dot(n, uKey) * 0.5 + 0.5;
        if (uShadeOnly == 1) lit = min(lit, 0.37);                        // shadow cards only ever darken skin, to a soft shade
        else if (uCastOn == 1 && uKind == 1 && int(uInfo.x * 255.0 + 0.5) == 2 && castShadow() > 0.5)
          lit = min(lit, 0.37);                                           // body skin under the jaw's or the hair's shadow
    function render() {
      const meshes = allMeshes(), cs = active();
      applySkin(meshes);
      const cloths = cs.flatMap(c => c.cloths);
      if (state.mode === "3d") {
        meshes.forEach(o => o.material = o.userData.mat3d);
        cloths.forEach(c => c.lines3d.visible = trimsShown(c));
        sun.position.copy(camera.position).add(new THREE.Vector3(-3, 4, 0)); sun.target.position.copy(ctl.target); sun.target.updateMatrixWorld();
        R.setRenderTarget(null); R.setClearColor(0x191626, 1); R.clear(); R.render(scene, camera); R.setClearColor(0x000000, 0);
        return;
      }
      const buf = R.getDrawingBufferSize(new THREE.Vector2());
      targetsFor(buf.x, buf.y);
      cloths.forEach(c => c.lines3d.visible = false);
      meshes.forEach(o => { o.material = o.userData.mats.painted; o.material.uniforms.uPass.value = 0; });
      const G = GRADE[state.view === "bust" ? "bust" : "battle"];      // stage grade, shared by the characters and the stage
      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); }
      // the info pass (roles, ids, depth) first: the colour pass reads it for cast shadows
      meshes.forEach(o => {                              // unbound while it is drawn: reading it now would be a feedback loop
        const mu = o.material.uniforms; mu.uPass.value = 1; mu.uCastOn.value = 0; mu.tCastInfo.value = null; mu.tCastDepth.value = null;
      });
      R.setRenderTarget(targets.rtInfo); R.clear(); R.render(scene, camera);
      const ppmBuf = buf.y / (camera.top - camera.bottom) * camera.zoom;
      for (const o of meshes) {
        const mu = o.material.uniforms;
        mu.uPass.value = 0; mu.uCastOn.value = 1; mu.tCastInfo.value = targets.rtInfo.texture; mu.tCastDepth.value = targets.rtInfo.depthTexture;
        mu.uCastRes.value.set(buf.x, buf.y); mu.uCastNear.value = camera.near; mu.uCastFar.value = camera.far; mu.uCastPpm.value = ppmBuf;
      }
      R.setRenderTarget(targets.rt); R.clear(); R.render(scene, camera);
      const u = paint.mat.uniforms;
      u.tColor.value = targets.rt.texture; u.tInfo.value = targets.rtInfo.texture; u.tDepth.value = targets.rtInfo.depthTexture;
      u.uRes.value.set(buf.x, buf.y); u.uNear.value = camera.near; u.uFar.value = camera.far;
      // line weight follows the figure's size on screen (study: ~0.4% of its height)
      const ppm = buf.y / (camera.top - camera.bottom) * camera.zoom, dpr = R.getPixelRatio();
      u.uSil.value = THREE.MathUtils.clamp(1.75 * ppm * 0.0042, dpr, 2.6 * dpr);
      u.uInner.value = Math.max(dpr * 0.75, u.uSil.value * 0.55);
      u.uPpm.value = ppm;
      R.setRenderTarget(null); R.clear(); R.render(paint.scene, compCam);
    }
    
      for (let s = 0; s < 150; s++) cs.forEach(c => c.cloths.forEach(cl => cl.step(1 / 120, s / 120)));
      cs.forEach(c => c.cloths.forEach(cl => cl.write()));
    }
    function frameAt(centre, h, tw, th, pitch) {
      const w = h * tw / th, a = THREE.MathUtils.degToRad(pitch);
      camera.left = -w / 2; camera.right = w / 2; camera.top = h / 2; camera.bottom = -h / 2; camera.zoom = 1;
      camera.updateProjectionMatrix();
      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) {
    def compose(output):
        im = sky()
        wash_clouds(im)
        d = ImageDraw.Draw(im)
        d.ellipse((1046,195,1174,323),fill="#fce8be")
        d.polygon([(1020,299),(1080,297),(1149,298),(1206,295),(1171,301),(1088,300)],fill="#ebd8b7")
        ridge(im,[(-5,341),(144,354),(277,382),(425,368),(600,394),(787,371),(939,355),(1130,382),(1340,327),(1475,320),(1604,289)],"#bac0b2",6,12)
        ridge(im,[(-5,365),(106,374),(287,386),(442,403),(633,392),(805,414),(967,393),(1146,405),(1312,371),(1490,357),(1604,341)],"#a9b5a9",4,17)
        ridge(im,[(-5,388),(152,383),(312,408),(467,424),(636,418),(800,434),(963,414),(1132,418),(1269,398),(1460,386),(1603,367)],"#98a9a0",4,19)
        distant_trees(im)
        gate(im)
        for x,y,s,lift in [(941,265,1.05,6),(1005,249,.75,9),(1057,265,.56,5),(991,275,.57,7),(1098,257,.45,8)]:
            bird(d,x,y,s,lift)
        ridge(im,[(0,419),(95,412),(223,421),(386,430),(572,439),(796,443),(958,435),(1089,438),(1246,426),(1421,417),(1600,408)],"#899e91",2.8,23)
        water(im)
        # Figure reflection is laid in before the figure. Broken horizontal bands carry the coat colour into the water.
        actor = Image.open(CACHE/"figure.png").convert("RGBA")
        actor = actor.resize((round(actor.width*.56),round(actor.height*.56)),Image.Resampling.LANCZOS)
        anchor_x, anchor_y = 190, -2
        waterline = 744
        refl = ImageOps.flip(actor).resize((actor.width, round(actor.height*.69)),Image.Resampling.BILINEAR)
        reflected = np.array(refl)
        reflected[..., :3] = reflected[..., :3]*.53 + rgb("#89a39e")*.47
        reflected[..., 3] = (reflected[...,3]*.28).astype(np.uint8)
        reflected = Image.fromarray(reflected)
        for i in range(0,165,3):
            dx = int(3*math.sin(i*.18) + 3*math.sin(i*.64) + i*.022)
            strip = reflected.crop((0,i+28,actor.width,i+30))
            if i%15 != 0:
                im.alpha_composite(strip,(anchor_x+dx,waterline+i))
        shore(im)
        for i in range(30):
            x = rng.uniform(-35,370); y = 705 + x*.03 + rng.uniform(-2,32)
            reeds(im,x,y,rng.uniform(8,36),rng.randint(4,20),["#727e69","#899176","#a8a180"],i+40)
        field_markers(im)
        # Cast the silhouette toward the near bank. Keep the staff shadow faint in
        # the water while the two soles make short, dark marks on the stone.
        contact = Image.new("L", im.size)
        contact.paste(actor.getchannel("A"), (anchor_x,anchor_y))
        shear, slope, baseline = .49, .065, 743
        shadow = contact.transform(im.size,Image.Transform.AFFINE,
                                   (1,shear/slope,-shear*baseline/slope,0,-1/slope,baseline*(1+1/slope)),
                                   resample=Image.Resampling.BILINEAR).filter(ImageFilter.GaussianBlur(2))
        im.paste("#405851", (0,0,W,H), shadow.point(lambda a: a*.37))
        d=ImageDraw.Draw(im)
        d.ellipse((622,724,706,731),fill="#626f66")
        d.polygon([(543,747),(564,749),(573,752),(566,755),(528,753)],fill="#525e59")
        surface_rings(im,737,730,53,"#cecfb7")
        surface_rings(im,737,731,40,"#779490")
        im.alpha_composite(actor,(anchor_x,anchor_y))
        # Submerge the bottom few centimetres and break the reflection at the surface.
        d.polygon([(731,730),(740,729),(747,731),(739,735),(727,735)],fill="#99afaa")
        d.line([(715,731),(729,730),(738,731),(746,730),(756,731)],fill="#e0dbbb",width=2)
        for x,y,scale,count,i in [(22,865,149,74,12),(115,811,69,28,28),(160,790,33,11,31),
                                  (1550,907,92,30,14),(1604,884,140,37,25),(1460,884,53,15,57)]:
            reeds(im,x,y,scale,count,["#435b59","#576d63","#687865","#8c9073"],i)
        sea_lavender(im,94,821,123,11,22)
        sea_lavender(im,27,877,91,7,85)
        sea_lavender(im,1480,899,70,5,9)
        # A fine common paper tooth puts the sky, shaded mesh and water on the same surface.
        base = np.array(im.convert("RGB"),dtype=float)
        y,x = np.ogrid[:H,:W]
        tooth = rand.normal(0,1.7,(H,W)) + 2.3*fine_noise(W,H,9) + 3*fine_noise(W,H,60)
        vignette = 2.2*((x-W*.5)/(W*.5))**2+1.7*((y-H*.5)/(H*.5))**2
        out = np.uint8(np.clip(base+(tooth-vignette)[...,None],0,255))
        Image.fromarray(out).save(output,quality=94,subsampling=0,optimize=True)
    
    
    333:const HSV = `
    351:  uniform int uPass; uniform vec4 uInfo; uniform vec3 uEye[3]; uniform vec3 uFlat; uniform vec3 uSkinRef;
    452:      if (uFaceTex == 1) col *= clamp(tex.rgb / uSkinRef, 0.55, 1.05);
    456:        float d = 0.0, sl = dot(uSkinRef, vec3(1.0 / 3.0));
    657:    this.skinned = skinned; this.U = U; this.V = V; this.trims = trims; this.closed = closed; this.hemOnly = hemOnly;
    803:    const U = this.U, V = this.V, X = this.x, idx = (i, j) => i * V + j;
    874:    uEye: { value: V.roles.iris.colors.map(hex) }, uFlat: { value: new THREE.Color() }, uSkinRef: { value: new THREE.Vector3(0.965, 0.878, 0.80) },
    920:const active = () => activeNames().map(n => chars.get(n)).filter(Boolean);
    958:  const def = charDef(name), V = def.info, ci = CAM.characters.indexOf(def);
    995:  const V = CAM.characters[0].info, gltf = await parseGlb("plains.glb.json"), meshes = [];
    

agent

+37:37

The first GLB is built. Ione now has a broader jaw and shoulders, a hand-braided hairstyle with an ivory forelock, and a four-panel coat with a survey chart printed into the cloth. I’m checking how those choices read at the original camera distance and whether the rig and materials survive a standard GLB import.

  • exec_commandcat > review/tide-keeper/shot.js <<'EOF'

    command

    cat > review/tide-keeper/shot.js <<'EOF'
    state.view = "battle";
    state.cloth = false;
    const actor = await loadCharacter("figure");
    stage.add(actor.turn);
    R.setPixelRatio(1);
    const original = actor.meshes.map(mesh => mesh.material);
    for (const mesh of actor.meshes) {
      const u = mesh.userData.mats.painted.uniforms;
      u.uKey.value.set(.43,.56,.70).normalize();
      u.uPigment = {value: mesh.material.userData.pigment ? 1 : 0};
      if (mesh.userData.role === "face") u.uSkinRef.value.set(216/255,165/255,127/255);
      mesh.material = mesh.userData.mats.painted;
    }
    const vec = (x,y,z) => new THREE.Vector3(x,y,z);
    window.drawKeeper = kind => {
      const profile = kind === "side" || kind === "rear";
      const plain = kind === "pbr";
      const crossing = kind === "crossing";
      const full = profile || crossing || plain;
      const turn = {crossing:62, lens:32, rear:195, side:100, pbr:32}[kind];
      const w=crossing?1590:full?850:1280, h=crossing?1416:full?960:910;
      R.setSize(w,h,false);
      actor.turn.rotation.y = THREE.MathUtils.degToRad(turn);
      scene.updateMatrixWorld(true);
      const head = actor.root.getObjectByName("J_Bip_C_Head").getWorldPosition(vec());
      const centre=full?vec(0,1,0):head.clone().add(vec(.025,-.12,0));
      const height=full?2.36:.69;
      frameAt(centre,height,w,h,3);
      lensAndFlat({flat:0},centre,height,w,h,3);
      if(crossing){
        camera.left=-.43*2.65; camera.right=.57*2.65; camera.top=2.36/2; camera.bottom=-2.36/2;
        camera.position.set(0,1.39,5.5); camera.lookAt(0,.99,0); camera.updateProjectionMatrix();
      } else if(!plain) lensAndFlat({lens:full?64:40,flat:full?0:.48},centre,height,w,h,3);
      if(plain) {
        const persp = new THREE.PerspectiveCamera(26,w/h,.01,40);
        persp.position.copy(centre).add(vec(0,.35,5.05)); persp.lookAt(centre);
        actor.meshes.forEach((m,i)=>m.material=original[i]);
        const ambient=new THREE.HemisphereLight(0xfff3df,0x8a929a,1.5);
        const key=new THREE.DirectionalLight(0xffedda,2); key.position.set(-3,4,4);
        scene.add(key,ambient); R.setRenderTarget(null); R.clear(); R.render(scene,persp);
        scene.remove(key,ambient);
      } else render();
      const snapshot=R.domElement.toDataURL("image/png");
      actor.meshes.forEach(m=>m.material=m.userData.mats.painted);
      if(crossing){
        const tip=actor.meshes.find(m=>m.name.includes("heel_ferrule"));
        const points=[]; const v=vec();
        for(let i=0;i<tip.geometry.attributes.position.count;i++){
          tip.getVertexPosition(i,v);v.applyMatrix4(tip.matrixWorld).project(camera);
          points.push([(v.x+1)*w*.28+190,(1-v.y)*h*.28-2]);
        }
        points.sort((a,b)=>b[1]-a[1]);window.contact=points[0];
      }
      return snapshot;
    };
    EOF
    python3 - <<'PY'
    from pathlib import Path
    src=Path('review/high-water/shoot.cjs').read_text().replace('review/out/high-water','review/out/tide-keeper').replace('path.join(root, "review/vroid-02/index.html")','path.join(cache, "index.html")').replace('"figure.glb"','"ione.glb"')
    src=src.replace('viewer.slice(0, ending).replace','''viewer.slice(0, ending)
        .replace("uniform float uGrain;", "uniform float uPigment; uniform float uGrain;")
        .replace("gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);", `if (uPigment > .5) {
          float value = dot(col, vec3(.299,.587,.114)) / max(.025, dot(uBase, vec3(.299,.587,.114)));
          col = tex.rgb * clamp(value, .22, 1.85);
        } gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);`)
        .replace("#include <skinning_pars_vertex>", "#include <morphtarget_pars_vertex>\\n  #include <skinning_pars_vertex>")
        .replace("#include <begin_vertex>", "#include <begin_vertex>\\n    #include <morphtarget_vertex>")
        .replace("mu.uPass.value = 0; mu.uCastOn.value = 1;", "mu.uPass.value = 0; mu.uCastOn.value = paint.mat.uniforms.uPersp.value ? 0 : 1;")
        .replace''')
    a=src.index('    await page.waitForFunction'); b=src.index('  } finally',a)
    src=src[:a]+'''    await page.waitForFunction(() => !!window.drawKeeper, null, { timeout: 45000 }).catch(e => { throw new Error(errors.join("\\n") || e.message); });
        const views=process.argv.length>2?process.argv.slice(2):["crossing","lens","rear","side","pbr"];
        for (const view of views) {
          const png = await page.evaluate(name => window.drawKeeper(name), view);
          if (!png || errors.length) throw new Error(errors.join("\\n") || "No frame");
          await fs.writeFile(path.join(cache, (view==="crossing"?"figure":view)+".png"), Buffer.from(png.split(",")[1], "base64"));
          if(view==="crossing") console.log("staff contact",await page.evaluate(()=>window.contact));
        }
    '''+src[b:]
    Path('review/tide-keeper/shoot.cjs').write_text(src)
    PY
    node review/tide-keeper/shoot.cjs > review/out/tide-keeper/render.log 2>&1

    result, 4 lines

    Script completed
    Wall time 0.4 seconds
    Output:
    {"chunk_id":"f43b33","wall_time_seconds":0.251253908,"session_id":62159,"original_token_count":0,"output":""}
  • exec_commandcat ~/out/index.html && cat review/out/tide-keeper/render.log && command -v blender; rg -n 'def export_skinned|jnames|all_bones|used_bones' tools/export_glb.py && head -75 review/tide-keeper/coiffure.py

    command

    cat ~/out/index.html && cat review/out/tide-keeper/render.log && command -v blender; rg -n 'def export_skinned|jnames|all_bones|used_bones' tools/export_glb.py && head -75 review/tide-keeper/coiffure.py

    result, 192 lines

    Script completed
    Wall time 0.2 seconds
    Output:
    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="color-scheme" content="light">
    <title>High water · Lowmarch</title>
    <style>
      :root {
        --paper: #f7f5ef;
        --ink: #26352f;
        --muted: #54605a;
        --hairline: #cecfc4;
        --rust: #904a33;
        --serif: "Spectral", Georgia, "Times New Roman", serif;
        --sans: "Source Sans 3", "Segoe UI", system-ui, sans-serif;
      }
      * { box-sizing: border-box; }
      body { margin: 0; background: var(--paper); color: var(--ink); font: 1rem/1.5 var(--sans); }
      main { max-width: 83rem; padding: 0 clamp(1.1rem, 4.5vw, 4rem) 4rem; margin: auto; }
      header { display: flex; align-items: baseline; justify-content: space-between; gap: .25rem 1rem;
        flex-wrap: wrap; border-bottom: 1px solid #9caaa0; padding: 1.15rem 0 .82rem; font-size: .8rem; }
      time { color: var(--muted); font-variant-numeric: tabular-nums; }
      .heading { display: flex; align-items: baseline; justify-content: space-between; gap: .75rem 2rem;
        flex-wrap: wrap; padding: clamp(1rem, 3vw, 2.5rem) 0 1.2rem; }
      h1, h2 { font-family: var(--serif); font-weight: 400; margin: 0; }
      h1 { font-size: clamp(3.3rem, 6.3vw, 5.2rem); line-height: 1; letter-spacing: -.055em; }
      .project { color: var(--muted); font-size: .92rem; }
      .project b { color: var(--ink); font-weight: 620; }
      figure { margin: 0; }
      figure a { display: block; }
      img { display: block; width: 100%; height: auto; background: #c6c4b0; }
      figcaption { margin: .84rem 0 0; display: grid; grid-template-columns: minmax(0, 1.22fr) minmax(0,.78fr);
        gap: .7rem 3.5rem; align-items: start; font-size: .91rem; color: var(--muted); }
      p { margin: 0; }
      strong { font-weight: 650; color: var(--ink); }
      a:focus-visible, summary:focus-visible { outline: 2px solid var(--rust); outline-offset: 4px; }
      details { font-size: .84rem; margin-top: .65rem; }
      summary { display: list-item; width: fit-content; cursor: pointer; color: var(--rust); font-weight: 600; }
      .timing { margin-top: .6rem; color: var(--muted); max-width: 73ch; }
      pre { overflow-x: auto; padding: .85rem 1rem; margin: .45rem 0 0; font: .79rem/1.65 ui-monospace, monospace;
        background: #eaece3; border-left: 2px solid #a8b3a7; }
      .notes { margin-top: 2.1rem; padding-top: 1.5rem; border-top: 1px solid var(--hairline);
        display: grid; grid-template-columns: 1.08fr 1fr; gap: clamp(2rem, 5vw, 5rem); }
      h2 { font-size: clamp(1.9rem, 3.2vw, 2.7rem); line-height: 1.1; letter-spacing: -.04em; margin: 0 0 1rem; }
      .read p + p { margin-top: .72rem; }
      .read p, li { max-width: 56ch; }
      ol { padding: 0 0 0 1.65rem; margin: 0; }
      li { padding-left: .32rem; margin-bottom: .57rem; }
      li::marker { color: var(--rust); font-family: var(--serif); font-weight: bold; }
      @media(max-width: 720px) {
        main { padding-bottom: 2rem; }
        figcaption, .notes { grid-template-columns: 1fr; }
        .notes { gap: 1.45rem; margin-top: 1.3rem; }
        .heading { align-items: start; flex-direction: column; gap: .32rem; padding: 1.45rem 0 1rem; }
        header { font-size: .76rem; }
        figure a { margin-inline: calc(-1 * clamp(1.1rem, 4.5vw, 4rem)); }
      }
      @media print { main { max-width: none; padding: 0; } .notes { margin-top: 1rem; } }
    </style>
    </head>
    <body>
    <main>
      <header>
        <span>GPT-6.2-Astra (gpt-6.2-astra), effort high</span>
        <time datetime="2026-11-17">17 November 2026</time>
      </header>
      <div class="heading">
        <h1>High water</h1>
        <p class="project"><b>Lowmarch</b> · A crossing study</p>
      </div>
      <figure>
        <a href="high-water.jpg" aria-label="Open High water at full size">
          <img src="high-water.jpg" width="1600" height="900" alt="A mage holds her hat against the wind and dips a marked staff into the water. Half-submerged stones lead toward a distant bell tower.">
        </a>
        <figcaption>
          <p>I dressed <strong>the armory’s strong woman</strong> in the caster kit, cut the hem for a step and posed each hand. Lowmarch’s painted renderer drew her. I drew the marsh in code around her boots and staff.</p>
          <p><strong>Next change.</strong> Her scarf catches the wind. The skirt still looks stiff. I’d lift its trailing edge as her weight settles on the forward foot.</p>
        </figcaption>
      </figure>
      <details>
        <summary>Render commands · 30 seconds from the cached body</summary>
        <p class="timing">About 20 minutes to make and revise the picture. The final build took 25 seconds for the figure, 3 seconds in headless Chromium and 2 seconds for the marsh and composite.</p>
        <pre><code>cd ~/work/lowmarch/review/high-water
    OPENBLAS_NUM_THREADS=1 python3 figure.py
    node shoot.cjs
    python3 marsh.py ~/out/high-water.jpg</code></pre>
      </details>
      <div class="notes">
        <section class="read">
          <h2>My read</h2>
          <p><strong>Keep the cage and the fitting kit.</strong> You called the bare bodies “perfect.” An older robe fit this body well enough that I could spend my time on what she was doing.</p>
          <p><strong>Keep the blind picks. Park the cast-wide passes.</strong> You picked one version’s mouth and another’s smirk. That settled two questions of taste. Fourteen expression sheets still leave me guessing who I’m looking at.</p>
          <p><strong>I’d bring motion into the first hour.</strong> The restart plan saves it for later. In my first pose the staff covered her eye. Reaching forward cleared her face and gave the staff a purpose.</p>
        </section>
        <section>
          <h2>The first session</h2>
          <ol>
            <li>You bring one picture you wish were a game frame. We pick one thing the person in it needs to do.</li>
            <li>I match the camera and figure size. You see two rough clothed silhouettes in the same pose beside your picture. Pick one, mark it up, or cross both out.</li>
            <li>I put your pick in the painted view at the start and end of the gesture. We check whether you can still see the face, the hands and what they’re doing.</li>
            <li>We keep the frame you chose, your words for why, and the time from your answer to the next picture. You tell me which round to cut next time.</li>
          </ol>
        </section>
      </div>
    </main>
    </body>
    </html>
    ~/.local/bin/blender
    380:def export_skinned(portrait, palette, path, clips=None, max_tex=512):
    392:        if "jnames" in p and not p.get("world"):
    393:            used.update(n for n in p["jnames"] if n in names)
    473:        remap = np.array([jidx.get(n, jidx.get("J_Bip_C_Head")) for n in p["jnames"]])
    """A swept crop gathered into a three-part wind braid, designed on Ione's skull."""
    import numpy as np
    import hair
    from forms import HEAD, attach, bead, curve, pipe, ring, rod
    from fitting import vertex_normals
    import outfit as O
    
    
    def coiffure(fit):
        ch=hair.head_chart(fit)
        out=[]
        hairline=lambda u: np.interp(abs(u),[0,35,62,89,115,160,180],[60,61,68,87,113,123,125])
        shell=hair.cap("ink_underlayer",ch,hairline,lift=.006,crown=.014,role="inkhair")
        out.append(attach(fit,shell,HEAD))
    
        def blade(name, role, path, width, thick=.009, fullest=.48):
            points=[("uv",*p) for p in path]
            piece=hair.lock(name,ch,points,width,thick=thick,n=33,seg=12,role=role,
                            profile=lambda t:hair.clump(t,fullest,.48,1.15))
            out.append(attach(fit,piece,HEAD))
    
        # Broad combed sections converge into a high, off-centre knot. Back view
        # has its own parting and alternating ridges rather than a smooth cap.
        for i,u in enumerate(np.linspace(-170,176,22)):
            s=np.sign(u) or 1
            v=hairline(u)
            blade(f"combed_{i}",("umberhair","inkhair","bluehair")[i%3],
                  [(u-14*s,13,.009),(u-7*s,36,.018),(u,56,.013),(u+8*s,v+4,.007)],
                  .039+.006*np.cos(i*3),.009)
        # An ivory forelock emerges from the part; the larger dark masses share
        # its direction while ending at different points along the near temple.
        for i,(root,end,low,w,role) in enumerate([
            (-47,24,73,.045,"silk"),(-29,42,81,.046,"umberhair"),(-15,56,87,.043,"inkhair"),
            (4,67,94,.036,"bluehair"),(17,75,101,.027,"umberhair"),
            (-55,-76,88,.034,"umberhair"),(-37,-56,83,.039,"inkhair")]):
            blade("forelock_"+str(i),role,[(root,22,.022),(root*.48,43,.029),((root+end)*.52,58,.026),
                                          (end,low,.011)],w,.011)
        for side in (-1,1):
            for j,(u,low,w) in enumerate([(66,113,.037),(78,123,.034),(91,112,.035)]):
                blade(f"side_{side}_{j}","umberhair" if j==0 else "inkhair",
                      [(side*(u-21),43,.014),(side*(u-7),67,.018),(side*u,89,.014),
                       (side*(u-5),low,.011)],w)
        # Cross three elliptical cords. They narrow into an engraved ferrule and
        # a forked brush tip; a fourth fine strand is a woven surveyor's red cord.
        root=ch.point(151,60,off=.009)
        path=curve([root,root+[.042,.046,.103],root+[.076,.010,.215],root+[.13,-.088,.328],
                    root+[.165,-.116,.465],root+[.17,-.082,.575]],92)
        t=np.linspace(0,1,len(path))
        tangent=np.gradient(path,axis=0)
        tangent/=np.linalg.norm(tangent,axis=1)[:,None]
        across=np.cross(tangent,np.array([0.,1.,0.]))
        across/=np.linalg.norm(across,axis=1)[:,None]
        up=np.cross(across,tangent)
        gust=np.column_stack([.026*t**2,-.085*t**1.55,-.028*t**2])
        for j,(role,radius) in enumerate([("umberhair",.026),("inkhair",.026),("bluehair",.026),("redcord",.0048)]):
            phase=2*np.pi*(2.45*t+j/3)+(1.1 if j==3 else 0)
            amp=(.027 if j<3 else .048)*(1-.70*t)
            centre=path+amp[:,None]*(across*np.cos(phase)[:,None]+up*np.sin(phase)[:,None])
            pc=O.pipe("plait_"+str(j),role,centre,r=radius,seg=12)
            section=pc["pos"].reshape(len(t),13,3)
            section[:]=centre[:,None]+(section-centre[:,None])*(1-.72*t[:,None,None])
            pc["nrm"]=vertex_normals(pc["pos"],pc["tri"])
            pc["gust"]=np.repeat(gust,13,axis=0)
            out.append(attach(fit,pc,HEAD))
        for j,k in enumerate([7,78,84]):
            rad=.041 if j==0 else .020
            p=ring(fit,"braid_cuff_"+str(j),"brass",path[k],across[k],up[k],rad,rad,.0055,HEAD)
            p["gust"]=np.tile(gust[k],(len(p["pos"]),1))
            out.append(p)
        for j in range(3):
            p=hair.lock("free_end_"+str(j),ch,[("xyz",*path[-11]),("xyz",*path[-1]),
                      ("xyz",*(path[-1]+[.003*j,-.024+j*.019,.098-.014*j]))],
                      width=.037-j*.005,thick=.009,n=26,role="silk" if j==1 else "umberhair")
            p["gust"]=np.tile(gust[-1],(len(p["pos"]),1))
            out.append(attach(fit,p,HEAD))
    
  • exec_commandls -lh review/out/tide-keeper/*.png; cat review/out/tide-keeper/render.log; sed -n '380,427p;457,496p' tools/export_glb.py; cat review/tide-keeper/forms.py | head -70

    command

    ls -lh review/out/tide-keeper/*.png; cat review/out/tide-keeper/render.log; sed -n '380,427p;457,496p' tools/export_glb.py; cat review/tide-keeper/forms.py | head -70

    result, 154 lines

    Script completed
    Wall time 0.1 seconds
    Output:
    Warning: truncated output (original token count: 1810)
    Total output lines: 160
    
    -rw------- 1 runner runner 731K Nov 17 23:22 review/out/tide-keeper/figure.png
    staff contact [ 735.095052943677, 719.6584947449164 ]
    def export_skinned(portrait, palette, path, clips=None, max_tex=512):
        """The character in its reference pose as a skinned glTF: the VRoid skeleton (with our bone
        scales) drives the body, face, hair and every costume piece through the weights they carry.
        clips: {name: [(time, pose dict), ...]} -> glTF animations (rotation, plus translation where a
        pose moves a bone). Scenery is left out (export it with export())."""
        import vroid_portrait as vp
        v = portrait.v
        nodes_v = v.j["nodes"]
        names = v.nodes_by_name()
        parent = v.parents()
        used = set()
        for p in portrait.prims:
            if "jnames" in p and not p.get("world"):
                used.update(n for n in p["jnames"] if n in names)
        joints = set()
        for nm in used:                                   # every used bone plus its ancestors
            i = names[nm]
            while i is not None and i not in joints:
                joints.add(i)
                i = parent.get(i)
        order = sorted(joints)
        jidx = {nodes_v[i].get("name"): k for k, i in enumerate(order)}
        ref = portrait.pose_ref
        local_ref = {i: F4 @ v.local_matrix(i, ref) @ F4 for i in order}
        world_ref = {}
    
        def wref(i):
            if i not in world_ref:
                world_ref[i] = (wref(parent[i]) @ local_ref[i]) if parent.get(i) in joints else local_ref[i]
            return world_ref[i]
    
        # glTF assembly (reuses the static exporter's buffer helpers by building a fresh document)
        bin_ = bytearray()
        views, accessors, meshes, gnodes, materials, textures, images, anims = [], [], [], [], [], [], [], []
        tex_index = {}
    
        def add_view(data, target=None):
            while len(bin_) % 4:
                bin_.append(0)
            off = len(bin_)
            bin_.extend(data)
            vw = dict(buffer=0, byteOffset=off, byteLength=len(data))
            if target:
                vw["target"] = target
            views.append(vw)
            return len(views) - 1
    
        def add_acc(arr, kind, comp, target=None, minmax=False):
        for i in order:
            kids = [node_of[c] for c in nodes_v[i].get("children", []) if c in joints]
            if kids:
                gnodes[node_of[i]]["children"] = kids
        roots = [node_of[i] for i in order if parent.get(i) not in joints]
        ibm = np.stack([np.linalg.inv(wref(i)).T for i in order]).astype(np.float32)   # column-major
        skin = dict(joints=[node_of[i] for i in order], inverseBindMatrices=add_acc(ibm.reshape(-1, 16), "MAT4", 5126),
                    skeleton=roots[0])
        mesh_nodes = []
        for k, (p, role) in enumerate(zip(portrait.prims, portrait.roles)):
            if role == "skip" or not len(p["tri"]) or p.get("world") or "J" not in p:
                continue
            usedv, inv = np.unique(p["tri"], return_inverse=True)
            pos = (p["pos"][usedv] * FLIP).astype(np.float32)
            nrm = p["nrm"][usedv] * FLIP
            nrm = (nrm / np.maximum(np.linalg.norm(nrm, axis=1, keepdims=True), 1e-9)).astype(np.float32)
            remap = np.array([jidx.get(n, jidx.g…260 tokens truncated…
            if role in TEXTURED:
                src = portrait._hair_v if role == "hair" and getattr(portrait, "_hair_v", None) is not None \
                    and "_HAIR" in p["material"] else portrait.v
                raw = src.material_texture(p["mi"]) if p["mi"] >= 0 else None
                if raw is not None and role == "line":
                    raw = fill_line_specks(raw)
                    if p.get("lid_fill") is not None:          # a shut eye's lid (vroid_portrait): its lash solid
                        raw = fill_lid(raw, p["lid_fill"])
                if raw is not None and role == "mouth":
                    raw = even_mouth(raw)
    """Pattern pieces, piping and metalwork in the body's fitting coordinates (+y up, -z front)."""
    import numpy as np
    from scipy.interpolate import CubicSpline
    import outfit as O
    from fitting import vertex_normals
    
    HIP = "J_Bip_C_Hips"
    HEAD = "J_Bip_C_Head"
    CHEST = "J_Bip_C_UpperChest"
    
    
    def curve(points, count=40):
        points = np.asarray(points, float)
        return CubicSpline(np.linspace(0, 1, len(points)), points, bc_type="natural")(np.linspace(0, 1, count))
    
    
    def attach(fit, p, bone):
        if isinstance(bone, str):
            return fit.bind(p, rigid=bone)
        return fit.bind(p, allow=bone, fallback=CHEST)
    
    
    def skin_grid(fit, name, role, grid, bone, origin, pattern=None, flutter=None):
        pos, tri = O.grid_mesh(grid)
        pc = O.piece(name, role, pos, tri, outward_from=origin)
        nu,nv = grid.shape[:2]
        u,v = np.meshgrid(np.linspace(0,1,nu),np.linspace(0,1,nv),indexing="ij")
        pc["uv"] = np.stack([u,v],axis=-1).reshape(-1,2)
        if pattern:
            pc["pigment"] = pattern
        if flutter is not None:
            pc["gust"] = flutter.reshape(-1,3)
        return attach(fit,pc,bone)
    
    
    def pipe(fit, name, role, pts, radius, bone, closed=False, gust=None, seg=8):
        pts = np.asarray(pts)
        p = O.pipe(name,role,pts,r=radius,seg=seg,closed=closed)
        if gust is not None:
            p["gust"] = np.repeat(gust,seg+1,axis=0)
        return attach(fit,p,bone)
    
    
    def bead(fit,name,role,point,r,bone,shape=(1,1,1)):
        return attach(fit,O.ball(name,role,point,r,seg=16,rows=10,squash=shape),bone)
    
    
    def rod(fit,name,role,a,b,r,tip,bone,n=16):
        a,b=np.array(a),np.array(b)
        length=np.linalg.norm(b-a)
        p=O.tube(name,role,a,(b-a)/length,length,r,tip,seg=n)
        return attach(fit,p,bone)
    
    
    def layered_sheet(fit,name,outer,inner,grid,bone,origin,pattern=None,flutter=None,hem=True):
        face=skin_grid(fit,name,outer,grid,bone,origin,pattern,flutter)
        normals=face["nrm"].reshape(grid.shape)
        lining=skin_grid(fit,name+"_lining",inner,grid-normals*.003,bone,origin,None,flutter)
        lining["tri"]=lining["tri"][:,::-1]
        lining["nrm"]=-lining["nrm"]
        pieces=[face,lining]
        if hem:
            for i,index in enumerate(((slice(None),-1),(0,slice(None)),(-1,slice(None)))):
                pcs=pipe(fit,name+"_binding"+str(i),"brass",grid[index]-.001*normals[index],
                         .0024,bone,gust=None if flutter is None else flutter[index],seg=6)
                pieces.append(pcs)
        return pieces
    
    
    def ring(fit,name,role,c,ex,ey,rx,ry,r,bone,sweep=(0,360)):
    
  • exec_commandls -lh review/out/tide-keeper/*.png && python3 - <<'PY'

    command

    ls -lh review/out/tide-keeper/*.png && python3 - <<'PY'
    from PIL import Image,ImageOps,ImageDraw
    from pathlib import Path
    p=Path('review/out/tide-keeper')
    imgs=[]
    for n in ('figure','lens','side','rear','pbr'):
     if (p/(n+'.png')).exists():
      im=Image.open(p/(n+'.png')); im.thumbnail((512,512)); bg=Image.new('RGB',im.size,'#93a49c'); bg.paste(im,mask=im.getchannel('A')); imgs.append(bg)
    o=Image.new('RGB',(sum(i.width for i in imgs),max(i.height for i in imgs)),'#888888')
    x=0
    for im in imgs:o.paste(im,(x,0));x+=im.width
    o.save(p/'check.jpg')
    PY

    result, 9 lines

    Script completed
    Wall time 0.4 seconds
    Output:
    -rw------- 1 runner runner 731K Nov 17 23:22 review/out/tide-keeper/figure.png
    -rw------- 1 runner runner 786K Nov 17 23:22 review/out/tide-keeper/lens.png
    -rw------- 1 runner runner 270K Nov 17 23:22 review/out/tide-keeper/pbr.png
    -rw------- 1 runner runner 317K Nov 17 23:22 review/out/tide-keeper/rear.png
    -rw------- 1 runner runner 386K Nov 17 23:22 review/out/tide-keeper/side.png
    
  • view_image~/work/lowmarch/review/out/tide-keeper/check.jpg

    input

    image((await tools.view_image({path:"~/work/lowmarch/review/out/tide-keeper/check.jpg"})).image_url)
    

    result, 4 lines

    Script completed
    Wall time 0.1 seconds
    Output:
    
    check_3.jpg
    check_3.jpg
  • exec_commandcat review/tide-keeper/tailoring.py | head -174 && cat review/tide-keeper/dyes.py && sed -n '486,548p' tools/export_glb.py

    command

    cat review/tide-keeper/tailoring.py | head -174 && cat review/tide-keeper/dyes.py && sed -n '486,548p' tools/export_glb.py

    result, 292 lines

    Script completed
    Wall time 0.1 seconds
    Output:
    Warning: truncated output (original token count: 4089)
    Total output lines: 308
    
    """Ione's storm coat, tide armour and sounding instrument."""
    import numpy as np
    import gear
    import mobs
    import outfit as O
    from fitting import Surface
    from plates import TorsoChart, flat_piece
    from forms import (HIP, CHEST, HEAD, attach, bead, cuff_grid, curve, layered_sheet, pipe, ring, rod, skin_grid)
    from coiffure import coiffure
    
    
    def body_panel(fit, chart, name, role, angles, low, high, clearance, bone, design=None):
        u=np.linspace(*angles,60)
        t=np.linspace(0,1,16)
        y0=np.array([low(a) for a in u])
        y1=np.array([high(a) for a in u])
        y=y0[:,None]+(y1-y0)[:,None]*t
        g=chart.point(u[:,None],y,clearance)
        p=skin_grid(fit,name,role,g,bone,[0,np.mean(y),chart.cz],design)
        return p,g
    
    
    def coat(fit,chart,waist):
        out=[]
        # Each gore is a separate lined, bound sheet cut higher at the front.
        # The outer corner catches the wind while the seam under the belt is still.
        for i,(a0,a1,role,lining,pigment) in enumerate([
            (10,136,"canvas","vermilion","chart"),(122,222,"deepsea","vermilion","wake"),
            (208,346,"canvas","reef","chart"),(-20,32,"vermilion","deepsea","pennant")]):
            u=np.linspace(0,1,50)[:,None]
            v=np.linspace(0,1,32)[None,:]
            phi=np.radians(a0+(a1-a0)*u)
            front=(1+np.cos(phi))/2
            arch=np.sin(np.pi*u)
            length=.48+.22*(1-front)+.15*arch-.07*np.cos(2*np.pi*u)
            if i==3:
                length=.30+.17*arch
            root_y=waist+.018
            rad=chart.radius(np.degrees(phi),root_y)+.021+.002*i
            fold=(.025*np.sin(5*np.pi*u+.9*v)+.010*np.sin(8*np.pi*u-2*v))*v**1.3
            sweep=(.10+.30*(1-front)+.17*arch)*(v**1.8)
            if i==3:
                sweep*=.16
            radial=rad+.083*v+.068*v**2+fold
            x=(np.sin(phi)*radial + .035*np.sin(phi)*v + .042*v**2)
            z=chart.cz-np.cos(phi)*radial+sweep
            y=root_y-length*v+(.12+.12*arch)*(1-front)*v**3+.045*np.sin(2*np.pi*u+.7)*v**2
            grid=np.stack(np.broadcast_arrays(x,y,z),axis=-1)
            weight=v**1.55*(.55+.45*arch)
            flutter=np.stack(np.broadcast_arrays(.020*weight*np.sin(phi),.086*weight*np.sin(phi+.4),
                                                  .097*weight),axis=-1)
            out+=layered_sheet(fit,"gore_"+str(i),role,lining,grid,HIP,[0,waist-.28,chart.cz],pigment,flutter)
        return out
    
    
    def scarf(fit,chart):
        out=[]
        nk=fit.bone["J_Bip_C_Neck"]
        a=np.linspace(-np.pi,np.pi,62)[:,None]
        v=np.linspace(0,1,12)[None,:]
        r=.080+.023*(1-v)+.005*np.sin(3*a+4*v)
        y=nk[1]-.079+.084*v-.023*np.cos(a+.6)
        g=np.stack(np.broadcast_arrays(np.sin(a)*r,y,nk[2]-np.cos(a)*r*.95),axis=-1)
        out+=layered_sheet(fit,"cravat","vermilion","reef",g,CHEST,nk,hem=False)
        # Ends are cut on the bias. One end twists over to expose its lining.
        start=nk+np.array([.050,-.058,.054])
        for j,length in enumerate([.60,.43]):
            T=np.linspace(0,1,39); V=np.linspace(-1,1,9)
            c=start+np.column_stack([(.11+j*.04)*T,.06*np.sin(2.8*np.pi*T)*T-.16*T+.04*j*T,length*T])
            twist=.5+.91*np.sin(2*np.pi*T+.3*j)
            normal=np.stack([np.cos(twist),np.sin(twist),.15*np.cos(3*T)],axis=1)
            w=(.043+.012*np.sin(np.pi*T))*(1-.88*T**6)
            grid=(c[:,None]+V[None,:,None]*w[:,None,None]*normal[:,None])
            d=np.zeros_like(grid); d[:,:,1]=.092*T[:,None]**1.7; d[:,:,0]=-.033*T[:,None]**1.7
            out+=layered_sheet(fit,"cravat_tail_"+str(j),"vermilion","poppy",grid,CHEST,nk,"weft",d,False)
        return out
    
    
    def shell_armour(fit,side):
        """Interleaved enamel scallops on the staff shoulder; one light plate on the free shoulder."""
        sign=1 if side=="R" else -1
        shoulder=fit.bone[f"J_Bip_{side}_UpperArm"]
        upper=f"J_Bip_{side}_UpperArm"
        scapula=f"J_Bip_{side}_Shoulder"
        out=[]
        cap=shoulder+np.array([sign*.010,.015,0])
        for j in range(4 if side=="R" else 2):
            a=np.linspace(-np.pi,np.pi,55)[:,None]
            v=np.linspace(0,1,15)[None,:]
            # The ridge turns down in a point on the outside of the upper arm.
            reach=.77+.23*np.cos(a)
            lo=(.20 if j==0 else .70+.22*j)
            ph=lo+v*((1.19+.23*j)-lo)+(.12*np.cos(3*a)+.14*reach)*v
            rx=(.151-.008*j)*(.89 if side=="L" else 1)
            rz=.130-.007*j
            x=cap[0]+sign*rx*np.cos(a)*np.sin(ph)
            y=cap[1]+.105*np.cos(ph)-j*.031-.025*reach*v
            z=cap[2]+rz*np.sin(a)*np.sin(ph)
            grid=np.stack(np.broadcast_arrays(x,y,z),axis=-1)
            piece=skin_grid(fit,f"shoulder_{side}_{j}","porcelain" if j%2==0 else "seasteel",grid,upper,cap,
                            "armour" if j==0 else None)
            out.append(piece)
            out.append(pipe(fit,"scallop_lip","brass",grid[:,-1],.004 if j==0 else .003,upper))
            if j==0:
                out.append(pipe(fit,"shoulder_ridge","seasteel",grid[27],.0033,upper))
                for k in (9,17,29,39,47):
                    out.append(bead(fit,"shoulder_rivet","brass",grid[k,-3],.005,upper))
        return out
    
    
    def legs(fit,boots):
        out=[]
        for side in ("R","L"):
            bone=f"J_Bip_{side}_LowerLeg"
            knee,ankle=fit.bone[bone],fit.bone[f"J_Bip_{side}_Foot"]
            # High folded gaiter, a rigid ceramic shin shield over a soft boot.
            over=O.side_of(boots,side)
            bands,rims=O.limb_lames(fit,"wader_strap_"+side,"saddle",over,knee,ankle,
                                    ((.20,.28,.007,.009),(.51,.565,.006,.008),(.82,.88,.007,.009)))
            for band,edges in zip(bands,rims):
                out.append(attach(fit,band,bone))
                out.append(pipe(fit,"wader_stitch","brass",edges[0],.002,bone))
                k=20 if side=="R" else 9
                out.append(bead(fit,"strap_pin","brass",edges[0][k],.005,bone))
            a=np.linspace(-1.18,1.18,28)[:,None]; t=np.linspace(0,1,23)[None,:]
            top=.075+.095*np.abs(np.sin(a))
            low=.83-.15*np.abs(np.sin(a))
            frac=top+ t*(low-top)
            c=knee[None,None]+(ankle-knee)[None,None]*frac[:,:,None]
            rx=.068-.027*t; rz=.084-.032*t
            g=c+np.stack(np.broadcast_arrays(np.sin(a)*rx,np.zeros_like(frac),-np.cos(a)*rz),axis=-1)
            out+=layered_sheet(fit,"shin_"+side,"seasteel","saddle",g,bone,(knee+ankle)/2,"armour")
            out.append(pipe(fit,"greave_spine","brass",g[len(g)//2],.0024,bone))
            shoe=O.sabaton(fit,"last_"+side,side,role="boot",pad=.022,ridges=0)[0]
            out.append(shoe)
            # A real outsole gives the toes and heel a common contact plane.
            toe=fit.bone[f"J_Bip_{side}_ToeBase"]; ft=f"J_Bip_{side}_Foot"
            cy=min(shoe["pos"][:,1])
            outline=np.array([[-.041,.049],[-.051,.011],[-.044,-.050],[-.052,-.136],[-.049,-.174],
                              [-.026,-.202],[.024,-.202],[.051,-.179],[.055,-.143],[.040,-.060],
                              [.051,.013],[.039,.048]])
            orig=np.array([ankle[0],cy+.005,ankle[2]])
            sole=flat_piece("outsole_"+side,"rubber",outline,orig,[1,0,0],[0,0,1],thickness=.019)
            out.append(attach(fit,sole,ft))
            welt=orig+np.column_stack([outline[:,0],np.full(len(outline),.009),outline[:,1]])
            out.append(pipe(fit,"boot_welt","saddle",welt,.0038,ft,True))
        return out
    
    
    def gauntlets(fit,shirt):
        out=[]
        for side in ("L","R"):
            bone=f"J_Bip_{side}_LowerArm"; a,b=fit.bone[bone],fit.bone[f"J_Bip_{side}_Hand"]
            # The glove and shell overlap on both sides of the wrist joint.
            g=cuff_grid(a,b,.052,.048,[.24,.32,.53,.81,1.055],[1.17,1.21,1.02,.78,.72])
            out+=layered_sheet(fit,"bracer_"+side,"seasteel" if side=="R" else "saddle","reef",g,bone,(a+b)/2,
                               "armour" if side=="R" else "weft")
            for k in (0,2,4):
                out.append(pipe(fit,"bracer_edge","brass" if k!=2 else "deepsea",g[:,k],.0035,bone))
            bone=f"J_B…239 tokens truncated…ImageDraw.Draw(canvas)
        ink="#344e54"; red="#af4c39"; ochre="#c8a465"; ivory="#eadab9"
        if name in ("chart","wake","pennant"):
            x=np.arange(-8,w+9,3)
            # Deep water rises up the back hem. The outlines above it are depth
            # contours. The interrupted brass arcs are the graduations of the tide dial.
            y=.76*h+.13*h*np.sin(x/w*5.1+.13)+.047*h*np.sin(x/w*12.4+1.2)
            d.polygon([(int(a),round(b)) for a,b in zip(x,y)]+[(w+8,h),(-8,h)],fill=ink)
            for j in range(8):
                z=y-13-j*8+np.sin(x/w*11+j*.5)*j*2.9
                d.line([(int(a),round(b)) for a,b in zip(x,z)],fill=ochre if j%3==0 else "#8c9e8d",width=2 if j%3==0 else 1)
            cx,cy=440,565
            for rad,width,colour,angles in [(102,6,ochre,(26,301)),(88,2,ivory,(10,356)),(75,4,red,(170,310))]:
                d.arc((cx-rad,cy-rad,cx+rad,cy+rad),*angles,fill=colour,width=width)
            for a in np.linspace(-2.8,1.2,26):
                ox,oy=np.cos(a),np.sin(a)
                d.line([(cx+ox*90,cy+oy*90),(cx+ox*100,cy+oy*100)],fill=ochre,width=2)
            d.polygon([(cx-19,cy+42),(cx-4,cy-4),(cx+32,cy-62),(cx+6,cy+6)],fill=red)
            d.ellipse((cx-6,cy-6,cx+6,cy+6),fill=ochre)
            for off in (16,25,54):
                d.line([(0,h-off),(w,h-off)],fill=ivory if off==25 else ochre,width=3)
            for px in range(-32,w,49):
                d.polygon([(px,h-33),(px+6,h-43),(px+13,h-33),(px+6,h-37)],fill=ochre)
        elif name=="weft":
            for y,width,col in [(h-49,10,red),(h-64,3,ochre),(h-23,4,ochre),(22,3,ochre)]:
                d.line([(0,y),(w,y)],fill=col,width=width)
            for x in range(0,w,34):
                d.line([(x,h-35),(x+13,h-35)],fill=ivory,width=2)
        elif name=="armour":
            for y in [14,h-16]:
                d.line([(0,y),(w,y)],fill=ochre,width=4)
            for x in range(9,w,48):
                d.line([(x,h-28),(x+12,h-28)],fill=ochre,width=2)
            # An etched meridian, small enough to yield to the plate's scalar shape.
            for cx in (w*.23,w*.73):
                cy=h*.48
                for r in [55,42]:
                    d.arc((cx-r,cy-r,cx+r,cy+r),204,506,fill=ochre,width=3)
                d.line([(cx-66,cy),(cx+64,cy)],fill=ochre,width=3)
                d.polygon([(cx,cy-40),(cx+7,cy-1),(cx,cy+23),(cx-6,cy)],fill=red)
        a=np.array(canvas,dtype=float)
        y,x=np.mgrid[:h,:w]; grain=np.random.default_rng(719).normal(0,.8,(h,w))
        if name!="armour": grain+=.6*np.sin(x*np.pi*.52)+.6*np.sin(y*np.pi*.57)
        return Image.fromarray(np.clip(a+grain[:,:,None],0,255).astype(np.uint8))
    
    
    def face_map(image):
        # Work on the face's shared UV island. Test the shell area at the brow and
        # the pale skin around each cheek; the original mouth/eyelids stay visible.
        a=np.array(image.convert("RGB"),float)
        h,w=a.shape[:2]; yy,xx=np.mgrid[:h,:w]; u=xx/w; v=yy/h
        shade=(np.exp(-((np.abs(u-.5)-.117)/.067)**2-((v-.64)/.043)**2))
        a+=shade[...,None]*[2,-9,-10]
        im=Image.fromarray(np.clip(a,0,255).astype(np.uint8))
        draw=ImageDraw.Draw(im)
        r=np.random.default_rng(75)
        for j in range(118):
            sx=r.choice([-1,1]); x=r.normal(.50+sx*.096,.043); y=r.normal(.637,.013)
            px=int(np.clip(x*w,0,w-1)); py=int(np.clip(y*h,0,h-1))
            pigment=np.array(im.getpixel((px,py)))*r.uniform(.60,.83)
            radius=r.uniform(.00068,.0017)*w
            draw.ellipse((px-radius,py-radius,px+radius,py+radius),fill=tuple(pigment.astype(int)))
        return im
                hex_rgb(extra[role]) if isinstance(extra.get(role), str) else [0.8, 0.8, 0.8]
            if role in TEXTURED:
                src = portrait._hair_v if role == "hair" and getattr(portrait, "_hair_v", None) is not None \
                    and "_HAIR" in p["material"] else portrait.v
                raw = src.material_texture(p["mi"]) if p["mi"] >= 0 else None
                if raw is not None and role == "line":
                    raw = fill_line_specks(raw)
                    if p.get("lid_fill") is not None:          # a shut eye's lid (vroid_portrait): its lash solid
                        raw = fill_lid(raw, p["lid_fill"])
                if raw is not None and role == "mouth":
                    raw = even_mouth(raw)
                if raw is not None:
                    attrs["TEXCOORD_0"] = add_acc(p["uv"][usedv].astype(np.float32), "VEC2", 5126, 34962)
                    mat["pbrMetallicRoughness"]["baseColorTexture"] = dict(
                        index=add_texture((id(src), p["mi"], p.get("lid_fill")), raw))
                    if role == "hair":
                        mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0]
                    if role in ("hair", "line", "brow", "iris", "highlight"):
                        mat["alphaMode"], mat["alphaCutoff"] = "MASK", 0.5
                else:
                    mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0]
            else:
                mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0]
            if role in ("metal", "steel", "gold"):
                mat["pbrMetallicRoughness"].update(metallicFactor=0.6, roughnessFactor=0.35)
            if p.get("strands"):                          # kit hair (tools/hair.py): one shared strand texture
                import hair as _hair
                attrs["TEXCOORD_0"] = add_acc(np.asarray(p["uv"], np.float32)[usedv], "VEC2", 5126, 34962)
                mat["pbrMetallicRoughness"]["baseColorTexture"] = dict(index=add_texture(("strands",), _hair.STRANDS))
            if "decal" in p:                              # a design in the piece's own coordinates (tools/plates.py Canvas)
                uvd = np.asarray(p["uv"], np.float32)[usedv].copy()
                uvd[:, 1] = 1 - uvd[:, 1]                 # the canvas draws t up; glTF's texture origin is the top left
                attrs["TEXCOORD_0"] = add_acc(uvd, "VEC2", 5126, 34962)
                mat["pbrMetallicRoughness"]["baseColorTexture"] = dict(index=add_texture(("decal", k), p["decal"], limit=1024))
                mat["extras"] = dict(decal=True)
            materials.append(mat)
            meshes.append(dict(name=group_of(p, role), primitives=[dict(attributes=attrs,
                         indices=add_acc(inv.reshape(-1).astype(np.uint32), "SCALAR", 5125, 34963), material=len(materials) - 1)]))
            mesh_nodes.append(len(gnodes))
            gnodes.append(dict(name=f"{group_of(p, role)}/{p['material']}", mesh=len(meshes) - 1, skin=0,
                               extras=dict(group=group_of(p, role), role=role, material=p["material"])))
        # animations
        for name, keys in (clips or {}).items():
            times = np.array([t for t, _ in keys], np.float32)
            tacc = add_acc(times.reshape(-1, 1), "SCALAR", 5126, minmax=True)
            samplers, channels = [], []
            for i in order:
                mats = [F4 @ v.local_matrix(i, vp.bone_pose(v, portrait.shape, pose)) @ F4 for _, pose in keys]
                trs = [_trs(m) for m in mats]
                T = np.array([a for a, _, _ in trs], np.float32)
                Q = np.array([b for _, b, _ in trs], np.float32)
                for k in range(1, len(Q)):                      # keep quaternions on one hemisphere
                    if np.dot(Q[k], Q[k - 1]) < 0:
                        Q[k] = -Q[k]
                t0, q0, _ = _trs(local_ref[i])
                if np.dot(Q[0], q0) < 0:
                    q0 = -q0
                # a channel whenever the clip leaves the reference pose, even if it then holds still
                if np.abs(Q - q0).max() > 1e-5:
                    samplers.append(dict(input=tacc, output=add_acc(Q, "VEC4", 5126), interpolation="LINEAR"))
                    channels.append(dict(sampler=len(samplers) - 1, target=dict(node=node_of[i], path="rotation")))
                if np.abs(T - t0).max() > 1e-5:
                    samplers.append(dict(input=tacc, output=add_acc(T, "VEC3", 5126), interpolation="LINEAR"))