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

agent (cont.)

+20:59
  • exec_commandcat ~/context/brief-lowmarch-full.md; cat review/astra/build.py; cat review/astra/prepare.py; cat review/astra/capture.js (+1 more)

    command

    cat ~/context/brief-lowmarch-full.md; cat review/astra/build.py; cat review/astra/prepare.py; cat review/astra/capture.js
    
    cat tools/hair.py

    result, 4 lines

    Script completed
    Wall time 0.2 seconds
    Output:
    {"chunk_id":"72e052","wall_time_seconds":0.0000046,"exit_code":0,"original_token_count":4318,"output":"You are running as GPT-6-Astra (gpt-6-astra) at effort high, in a session of your own. The owner, severian (they/them), asked to see what GPT-6-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 `astra`, 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-Astra (gpt-6-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\"\"\"One isolated costume study. Reads the cached body, never rebuilds shared data.\nRun: OPENBLAS_NUM_THREADS=1 python3 review/astra/build.py\n\"\"\"\nfrom pathlib import Path\nimport base64\nimport json\nimport sys\nimport time\n\nROOT = Path(__file__).resolve().parents[2]\nsys.path[:0] = [str(ROOT / 'tools'), str(ROOT / 'art/cast')]\nimport numpy as np\nimport cage\nfrom cast import CAST\nimport vroid_portrait as vp\nimport export_glb as E\nimport outfit as O\nimport gear as G\nimport mobs\nimport poses as P\nfrom fitting import Surface, merge_surfaces\nfrom rig import Rig, grip_points\nfrom vrm import VRM, bone_weight\nfrom fitting import vertex_normals\n\nOUT = ROOT / 'review/out/astra/site'\nOUT.mkdir(parents=True, exist_ok=True)\n\n\ndef warden(fit):\n    B = fit.bone\n    hips, neck = B['J_Bip_C_Hips'], B['J_Bip_C_Neck']\n    knee = B['J_Bip_L_LowerLeg'][1]\n    out, shirt, trousers, boots = mobs._base(fit, shirt='linen', legs='cloth', boots='boot', shirt_subdiv=1)\n    G.loose_sleeves(fit, shirt, ease=0.042, cuff=0.55, folds=5)\n    G.breeches(fit, trousers, boots, hips[1] - 0.22, knee - 0.075, ease=0.025, folds=5)\n    under = mobs._under(shirt)\n    # A short teal quilted coat, steel chest, cream sleeves, one shoulder plate.\n    out += G.quilted(fit, under, role='signature', y_hem=hips[1] - 0.31, flare=0.085,\n                     split=18, stitch=24, sleeves=False)\n    coat = mobs._surf(out, 'gambeson')\n    # Broader chart smoothing keeps the cuirass a single shell over the chest.\n    torso_chart = G.TorsoChart\n    def broad_chart(*args, **kwargs):\n        return torso_chart(*args, **dict(kwargs, smooth=(7.0, 5.0)))\n    G.TorsoChart = broad_chart\n    try:\n        out += G.breastplate(fit, coat, y_top=neck[1]-0.085, y_bottom=hips[1]+0.085,\n                            plackart=False, keel=0.003, arm=63)\n    finally:\n        G.TorsoChart = torso_chart\n    plate = mobs._surf(out, 'breastplate', prefix=True)\n    cuffs = G.cuffs(fit, role='glove', length=0.55, flare=0.029)\n    G.tuck_sleeves(fit, shirt, cuffs)\n    out += cuffs\n    # The wrap makes stockings at the toes; the existing shoe last supplies actual boots.\n    for side in 'LR':\n        out += O.sabaton(fit, 'warden_shoe_'+side, side, role='boot', pad=0.025, ridges=0)\n    foot_y = max(B['J_Bip_L_Foot'][1], B['J_Bip_R_Foot'][1]) - 0.025\n    boots['tri'] = boots['tri'][boots['pos'][boots['tri'],1].max(1) > foot_y]\n    # Continuous torso surfaces through the coat's front split, with no sleeve triangles.\n    skirt = mobs._surf(out, 'gambeson_skirt')\n    waist = merge_surfaces((under.pos,under.tri),(coat.pos,coat.tri),(skirt.pos,skirt.tri),(plate.pos,plate.tri))\n    belt, front = O.belt(fit, 'warden_belt', 'leather', waist, hips[1]+0.050,\n                         height=0.042, offset=0.013, tilt=0.012)\n    belt['group']='belt'; out.append(belt)\n    buckle = O.box('warden_buckle','gold',front+[0,0,-0.008],np.eye(3),(0.024,0.025,0.005))\n    out.append(fit.bind(buckle,rigid='J_Bip_C_Hips'))\n    # Collar and a short travelling cape. Its hem is authored for this still, not simulated.\n    collar, rim, _ = O.collar(fit,'warden_collar','signature',height_back=0.055,height_front=0.025,gap_deg=42)\n    out.append(collar)\n    out.append(O.inherit(O.ribbon('collar_edge','heraldry',rim,width=0.007,normals=O.near_normals(collar,rim)),collar))\n    shoulder = merge_surfaces((shirt['pos'],shirt['tri']), (plate.pos,plate.tri), (collar['pos'],collar['tri']), (fit.pos,fit.tri))\n    cape, grid = O.cape(fit,'warden_cape','cape',shoulder,length=0.86,phi=0.57,folds=4,fold_depth=0.012)\n    # Sweep the lower cloth to the character's left. Keep the attachment ring fixed.\n    t=np.linspace(0,1,grid.shape[1])[None,:,None]\n    grid += t**1.6 * np.array([-0.22,0.045,0.10])\n    # The upper back needs extra room after the chest turns in the authored pose.\n    back = np.maximum(np.cos(np.linspace(-0.57,0.57,grid.shape[0])*np.pi),0)[:,None]\n    grid[:,:,2] += back * (0.045*np.sin(np.pi*np.clip(t[0,:,0]*2,0,1)))[None,:]\n    cape['pos']=grid.reshape(-1,3); cape['nrm']=vertex_normals(cape['pos'],cape['tri'])\n    out.append(cape)\n    for k,line in enumerate([grid[:,-1],grid[0],grid[-1]]):\n        out.append(O.inherit(O.ribbon('cape_edge'+str(k),'heraldry',line,width=0.013,\n                                      normals=O.near_normals(cape,line)),cape))\n    pcs,rims=O.pauldron(fit,'warden_pauldron','steel',shoulder,side='L',\n                        lames=((0,60,0.023,0.030),(50,83,0.022,0.028)),spread=108)\n    for pc,rim in zip(pcs,rims):\n        pc['group']='plate';out.append(pc)\n        out.append(O.inherit(O.pipe('shoulder_roll','metal',rim,r=0.003),pc))\n    # A plain spear keeps a clear long silhouette and avoids the old sword costume's identity.\n    out += G.spear(fit,length=1.90,grip=0.91,head=0.26)\n    # The pale shirt is visible only as sleeves; its torso and lower hem stay dark.\n    sleeve_mask = bone_weight(shirt, ('Shoulder','UpperArm','LowerArm'))[shirt['tri']].mean(1) > 0.35\n    sleeves = dict(shirt, material='OUTFIT_warden_sleeves', tri=shirt['tri'][sleeve_mask].copy())\n    shirt['tri'] = shirt['tri'][~sleeve_mask]\n    shirt['role'] = 'signature'\n    out.append(sleeves)\n    for p in out:\n        if 'grid' in p: p.pop('grid')\n    return out\n\n\ndef main():\n    start=time.perf_counter()\n    body='arm_f_strong'\n    path=Path(cage.path_for(body,CAST[body]['cage']))\n    if not path.is_file(): raise SystemExit('Cached body missing; this study will not rebuild data.')\n    shape=dict(CAST[body]['shape'], rest={'Fcl_BRW_Angry':0.20,'Fcl_EYE_Close':0.08}, arm_out=4)\n    v=VRM(str(path)); rig=Rig(v,shape,ortho=True)\n    pose=P.merge(P.BUST,P.fist('R'),P.fist('L',curl=(18,25,18),thumb=10),{\n        'J_Bip_C_Hips':P.move(0,-0.018,0,r=P.rot((0,0,1),-2)),\n        'J_Bip_C_Chest':P.rot((0,1,0),-5),\n        'J_Bip_C_Head':P.rot((0,1,0),12),\n        'J_Bip_L_UpperLeg':P.rot((0,0,1),-6)@P.rot((1,0,0),7),\n        'J_Bip_R_UpperLeg':P.rot((0,0,1),4)@P.rot((1,0,0),-5),\n    })\n    feet={s:rig.pos(P.BUST,f'J_Bip_{s}_Foot') for s in 'LR'}\n    for s,delta in [('L',[-0.065,0,-0.075]),('R',[0.055,0,0.04])]:\n        pose=rig.leg_ik(pose,s,feet[s]+delta)\n    grip=grip_points(v,shape,P.BUST)\n    # Hand beside the waist, spear almost upright. The other hand rests at the hip.\n    target=rig.pos(P.BUST,'J_Bip_C_Hips')+np.array([0.42,0.03,-0.12])\n    pose=rig.grip(pose,'R',P.BUST,grip['R']['point'],target,[0.12,1,-0.08],[1,-0.4,0.3])\n    targetL=rig.pos(P.BUST,'J_Bip_C_Hips')+np.array([-0.235,0.015,-0.045])\n    pose=rig.arm_ik(pose,'L',targetL,[-1,0,0.35])\n    desired=P.rot((0,0,1),90)\n    current=rig.world(pose)[rig.names['J_Bip_L_Hand']][:3,:3]\n    u,_,vt=np.linalg.svd(current)\n    pose=rig.rotate_world(pose,'J_Bip_L_Hand',desired@(u@vt).T)\n    portrait=vp.Portrait(str(path),shape=shape,pose=P.BUST,costume=warden)\n    portrait.paint=dict(signature='#24575b',doublet='#303e42',linen='#c4c3ad',heraldry='#b7ad83',\n        cape='#24575b',steel='#929d9e',gold='#b49a5e',metal='#929d9e',leather='#604737',\n        boot='#333b3d',glove='#4f4640',hair='#88442d',skin='#e6bc9f',wood=dict(kind='leather',base='#55483c'),\n        grain=dict(signature=0.025,linen=0.025,cape=0.025))\n    pal=dict({**vp.PALETTE,**CAST[body]['colors']},A='#2d211e',B='#583327',C='#88442d',D='#b46642',E='#d18c59',\n             r='#20333b',s='#507b7b',t='#a2b5a0')\n    clips={'idle':[(0,pose),(1,pose)],'watch':[(0,pose),(1,pose)],'apose':[(0,P.BUST),(1,P.BUST)]}\n    import pickle\n    (OUT/'portrait.pkl').write_bytes(pickle.dumps(portrait))\n    size=E.export_skinned(portrait,pal,str(OUT/'warden.glb'),clips=clips)\n    raw=(OUT/'warden.glb').read_bytes()\n    (OUT/'warden.glb.json').write_text(json.dumps({'glb':base64.b64encode(raw).decode()}))\n    from stage import causeway\n    stage = causeway()\n    portrait.prims.extend(stage); portrait.roles.extend(p['role'] for p in stage)\n    E.export(portrait,pal,str(OUT/'plains.glb'),only_world=True)\n    (OUT/'plains.glb.json').write_text(json.dumps({'glb':base64.b64encode((OUT/'plains.glb').read_bytes()).decode()}))\n    info=E.scene_info(portrait,pal);info['cloth']={}\n    info['paint']['grass']={'kind':'world','base':'#929c87'}\n    info['paint']['dirt']={'kind':'world','base':'#777f70'}\n    info['paint']['stone']={'kind':'world','base':'#a5a998'}\n    info['paint']['contact']={'kind':'world','base':'#717e63'}\n    info['paint']['cape']={'kind':'cloth','base':'#24575b','grain':0.025}\n    cams={k:portrait.frame(k) for k in ['bust','battle']}\n    (OUT/'camera.json').write_text(json.dumps({'characters':[{'name':'warden','label':'Border warden','cams':cams,'info':info}],\n        'page':{'title':'Border warden','duel':False},'lineup':{'order':[],'spacing':1}}))\n    pose_json={k:np.asarray(val).tolist() for k,val in pose.items()}\n    (OUT/'pose.json').write_text(json.dumps(pose_json,indent=2))\n    timing={'build_seconds':round(time.perf_counter()-start,3),'body':str(path),'glb_bytes':len(raw),'pieces':len(portrait.prims)}\n    (OUT/'build.json').write_text(json.dumps(timing,indent=2)); print(json.dumps(timing),flush=True)\n\nif __name__=='__main__': main()\n\"\"\"Copy the current painted renderer, with an isolated capture hook and local three.js.\"\"\"\nfrom pathlib import Path\nimport shutil\nROOT=Path(__file__).resolve().parents[2]\nOUT=ROOT/'review/out/astra/site'\nTHREE=Path('~/context/sortie-node_modules/three')\nfor sub in ['build','examples/jsm']:\n    shutil.copytree(THREE/sub,OUT/'vendor'/sub,dirs_exist_ok=True)\ns=(ROOT/'review/vroid-02/index.html').read_text()\ns=s.replace('https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js','./vendor/build/three.module.js')\ns=s.replace('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/','./vendor/examples/jsm/')\ns=s.replace('<link href=\"https://fonts.googleapis.com/css2?family=Alegreya+Sans:ital,wght@0,400;0,500;0,700;1,400&family=Pixelify+Sans:wght@500;700&family=Silkscreen&display=swap\" rel=\"stylesheet\">','')\n# Ground shares the renderer but has no dark contour competing with the character.\ns=s.replace('const ROLE_ID = { face:', 'const ROLE_ID = { world: 250, face:')\ns=s.replace('const infoRole = role ===', 'const infoRole = opts.world ? \"world\" : role ===')\ns=s.replace('prepMesh(o, V); meshes.push(o);', 'prepMesh(o, V, {world:true}); meshes.push(o);')\ns=s.replace('if (r >= 4 && r <= 7)', 'if (r == 250 || (r >= 4 && r <= 7))')\ns=s.replace('bool feature = r0 >= 4 && r0 <= 9;', 'bool feature = (r0 >= 4 && r0 <= 9) || r0 == 250;')\n# Shot-specific art direction, applied only to this generated copy.\ns=s.replace('mix(s2, s3, 0.6)', 'mix(s2, s3, 0.28)')\ns=s.replace('u.uGrain.value = 0.12;', 'u.uGrain.value = 0.015;')\ns=s.replace('new THREE.Vector3(-0.45, 0.55, 0.70)', 'new THREE.Vector3(-0.65, 0.60, 0.55)')\ns=s.replace('col = mix(col, sL, st(lit, 0.38));', 'col = mix(col, sL, st(lit, uFaceTex == 1 ? 0.57 : 0.38));')\ns=s.replace('st(sp, 0.90) * (1.0 - st(sp, 0.985))', '0.25 * st(sp, 0.90) * (1.0 - st(sp, 0.985))')\ns=s.replace('gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);',\n    'if (uKind == 6) { float sy=gl_FragCoord.y/uCastRes.y; vec3 fog=sy<0.42 ? mix(vec3(0.573,0.620,0.549),vec3(0.761,0.792,0.737),sy/0.42) : mix(vec3(0.761,0.792,0.737),vec3(0.851,0.867,0.816),(sy-0.42)/0.58); col = mix(col, fog, smoothstep(15.0,25.0,vView.z)); }\\n    gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);')\n# No change to the project renderer; only this generated copy gets the hook.\ns=s.replace('if (SHEET) {\\n  runSheet(SHEET)', 'if (params.has(\"astra\")) {\\n' + (ROOT/'review/astra/capture.js').read_text() + '\\n} else if (SHEET) {\\n  runSheet(SHEET)')\n(OUT/'index.html').write_text(s)\nprint(OUT/'index.html')\n// Injected inside the existing renderer module. Plain JS, no transpiler helpers.\nstate.cloth = false; state.physics = false;\nawait setView('bust');\nstate.view = 'battle';\nif (params.has('stage')) { const g=await loadGround(); scene.add(g.root); }\nstate.hidden = new Set();\napplyMaterials();\nholdPose('watch', 0);\nR.setPixelRatio(1);\nR.setSize(1600, 1200, false);\n\nfunction backdrop(w,h) {\n  const cv=document.createElement('canvas');cv.width=w;cv.height=h;\n  const ctx=cv.getContext('2d');\n  const sky=ctx.createLinearGradient(0,0,0,h);\n  sky.addColorStop(0,'#d9ddd0');sky.addColorStop(.58,'#c2cabc');sky.addColorStop(1,'#929e8c');\n  ctx.fillStyle=sky;ctx.fillRect(0,0,w,h);\n  // Low distant land, deliberately quieter than the character.\n  for (let layer=0;layer<3;layer++) {\n    ctx.fillStyle=['#c3caba','#b7c1b1','#a9b6a5'][layer];\n    ctx.beginPath();ctx.moveTo(0,h);\n    for(let x=0;x<=w+10;x+=10){\n      const y=h*(.57+layer*.035)+Math.sin(x/w*7+layer*1.8)*h*.026+Math.sin(x/w*19+layer)*h*.009;\n      ctx.lineTo(x,y);\n    }\n    ctx.lineTo(w,h);ctx.fill();\n  }\n  return cv;\n}\nwindow.study = {\n  shot(options = {}) {\n    const w=options.w || 1600,h=options.h || 1200;\n    R.setPixelRatio(options.samples || 2);\n    R.setSize(w,h,false);\n    if (ground) ground.root.visible = options.stage !== false;\n    setYaw(options.yaw ?? -25);\n    holdPose(options.pose || 'watch',0);\n    const centre = new THREE.Vector3(options.x ?? -0.08, options.y ?? 1.14, 0);\n    frameAt(centre, options.span || 2.72, w,h, options.pitch ?? 4);\n    render();\n    if (!options.background) return R.domElement.toDataURL('image/png');\n    const cv=backdrop(w,h),ctx=cv.getContext('2d');\n    ctx.drawImage(R.domElement,0,0,w,h);\n    return cv.toDataURL('image/png');\n  },\n  meshInfo() { return active()[0].meshes.map(o=>({name:o.userData.material,role:o.userData.role,group:o.userData.group})); }\n};\ndocument.title = 'astra ready';\n"}{"chunk_id":"6b8d4a","wall_time_seconds":0.000004591,"exit_code":0,"original_token_count":4415,"output":"\"\"\"The hair kit: hair built as locks combed over the skull, instead of borrowing a VRoid sample's hair\ncards (portrait guide, lesson 14).\n\nHeadChart  u = degrees round the head (0 front, +90 the character's right), v = degrees down from the\n           crown (0 top, 90 level with the skull's centre, ~130 the jaw): rays from the skull's centre\n           onto the head skin, smoothed into a shell (as plates.TorsoChart does for the body).\ncap        the hair's base volume: a shell over the scalp down to a hairline given as v(u).\nlock       one lock: a path of (u, v, lift) points over the head (lift = metres off the scalp), smoothed\n           and sampled, then swept with a flat lens-shaped section whose flat side lies along the head,\n           width tapering to a point. Past the chart's lower edge a path just continues in 3D.\nEvery piece gets UVs (around, along) and shares one strand texture, so the painted renderer draws\nstrand highlights along each lock; every piece rides the head bone.\n\"\"\"\nimport math\n\nimport numpy as np\n\nfrom plates import _Chart, _fill_nan\nfrom scipy.ndimage import gaussian_filter\n\n\nclass HeadChart(_Chart):\n    def __init__(self, head, centre, du=4.0, dv=3.0, v_max=150.0, smooth=(1.0, 1.0)):\n        self.c = np.asarray(centre, float)\n        self.wrap = True\n        self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, 0.0, dv, 0.8\n        us = np.arange(-180.0, 180.0, du)\n        vs = np.arange(0.0, v_max + dv * 0.5, dv)\n        R = np.full((len(us), len(vs)), np.nan)\n        for i, u in enumerate(us):\n            for j, v in enumerate(vs):\n                o, d = self.ray(u, v)\n                R[i, j] = head.cast(o, d, rmax=0.3, far=True)\n        R = _fill_nan(R, True)\n        self.R = gaussian_filter(R, smooth, mode=(\"wrap\", \"nearest\"))\n\n    def ray(self, u, v):\n        u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float))\n        ur, vr = np.radians(u), np.radians(v)\n        d = np.stack([np.sin(vr) * np.sin(ur), np.cos(vr), -np.sin(vr) * np.cos(ur)], -1)\n        return np.broadcast_to(self.c, d.shape).copy(), d\n\n    def centre(self, v=None):\n        return self.c\n\n    @property\n    def L(self):\n        \"\"\"Metres per degree of v (decals and seams measure plates on this chart in metres).\"\"\"\n        return float(np.mean(self.R)) * np.pi / 180\n\n    def metric(self, u, v):\n        \"\"\"(arc across, arc down) in metres, for seams and decals on helmets.\"\"\"\n        r = self.radius(u, v)\n        return np.stack([np.radians(u) * r * np.sin(np.radians(np.asarray(v, float))), np.radians(v) * r + 0 * np.asarray(u, float)], -1)\n\n\n# ---- the shared strand texture: fine light and dark lines running along each lock -----------------\ndef strand_texture(n=256, seed=3):\n    rng = np.random.default_rng(seed)\n    x = np.arange(n)\n    stripes = np.zeros(n)\n    for f, a in ((3, 0.18), (7, 0.12), (17, 0.10), (41, 0.06)):\n        stripes += a * np.sin(2 * np.pi * (f * x / n + rng.random()))\n    stripes += 0.08 * gaussian_filter(rng.standard_normal(n), 1.2, mode=\"wrap\")\n    col = np.clip(0.62 + stripes, 0.25, 0.95)\n    along = 1.0 - 0.10 * np.linspace(0, 1, n)[:, None]           # a touch darker toward the tip\n    img = (np.repeat(col[None, :], n, 0) * along * 255).astype(np.uint8)\n    return np.dstack([img, img, img, np.full((n, n), 255, np.uint8)])\n\n\nSTRANDS = strand_texture()\n\n\ndef _smooth_path(P, n):\n    \"\"\"Catmull-Rom through control points P (k, 3), sampled at n points.\"\"\"\n    P = np.asarray(P, float)\n    if len(P) == 2:\n        return P[0] + (P[1] - P[0]) * np.linspace(0, 1, n)[:, None]\n    Q = np.vstack([2 * P[0] - P[1], P, 2 * P[-1] - P[-2]])\n    seg = len(P) - 1\n    out = []\n    for t in np.linspace(0, seg, n):\n        i = min(int(t), seg - 1)\n        s = t - i\n        p0, p1, p2, p3 = Q[i], Q[i + 1], Q[i + 2], Q[i + 3]\n        out.append(0.5 * ((2 * p1) + (-p0 + p2) * s + (2 * p0 - 5 * p1 + 4 * p2 - p3) * s * s\n                          + (-p0 + 3 * p1 - 3 * p2 + p3) * s ** 3))\n    return np.array(out)\n\n\ndef lock(name, chart, path, width, thick=0.006, n=28, seg=10, taper=(0.45, 1.0), tip=0.04, flat_to=None,\n         role=\"hair\", root_width=None, profile=None):\n    \"\"\"A lock along `path`: (u, v, lift) points on the chart, or 3D points (arrays of length 3 with\n    a flag), mixed freely as (\"uv\", u, v, lift) / (\"xyz\", x, y, z). Width tapers from\n    taper[0] of the way along to a point at the end (tip: the last fraction kept a hair's width).\n    The flat side faces `flat_to` (a point the section looks away from; default the skull's centre).\"\"\"\n    from outfit import piece\n    pts = []\n    for p in path:\n        if p[0] == \"uv\":\n            _, u, v, lift = p\n            pts.append(chart.point(u, v, off=lift))\n        else:\n            pts.append(np.array(p[1:], float))\n    C = _smooth_path(pts, n)\n    T = np.gradient(C, axis=0)\n    T /= np.maximum(np.linalg.norm(T, axis=1, keepdims=True), 1e-9)\n    away = C - np.asarray(flat_to if flat_to is not None else chart.c, float)\n    N = away - T * np.einsum(\"ij,ij->i\", away, T)[:, None]\n    N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-9)\n    Bv = np.cross(T, N)\n    t = np.linspace(0, 1, n)\n    w0 = width if root_width is None else root_width\n    w = np.where(t < 0.12, w0 + (width - w0) * t / 0.12, width)\n    k = np.clip((t - taper[0]) / max(taper[1] - taper[0], 1e-6), 0, 1)\n    w = w * (1 - k ** 1.6) + tip * 0.01 * k\n    if profile is not None:                            # a clump: profile(t) = width as a fraction of `width`\n        w = width * np.array([profile(x) for x in t]) + 0.0004\n        k = np.clip((t - 0.6) / 0.4, 0, 1)\n    th = thick * np.maximum(1 - k ** 1.3, 0.15)\n    a = np.linspace(0, 2 * np.pi, seg + 1)\n    G = (C[:, None] + Bv[:, None] * (w[:, None] / 2 * np.cos(a)[None, :])[..., None]\n         + N[:, None] * (th[:, None] / 2 * np.sin(a)[None, :])[..., None])\n    from outfit import grid_mesh\n    pos, tri = grid_mesh(G)\n    pc = piece(name, role, pos, tri, outward_from=None)\n    from fitting import vertex_normals\n    fn = vertex_normals(pos, tri)\n    radial = (pos - np.repeat(C, seg + 1, 0))\n    if (np.einsum(\"ij,ij->i\", fn, radial) < 0).mean() > 0.5:\n        pc[\"tri\"] = tri[:, ::-1]\n        pc[\"nrm\"] = -fn\n    uu, vv = np.meshgrid(a / (2 * np.pi), t, indexing=\"xy\")\n    pc[\"uv\"] = np.stack([uu.ravel(), vv.ravel()], 1)\n    pc[\"strands\"] = True\n    pc[\"group\"] = \"hair\"\n    return pc\n\n\ndef cap(name, chart, hairline, lift=0.010, crown=0.006, nu=72, nv=26, role=\"hair\"):\n    \"\"\"The hair's base volume: a shell over the scalp from the crown down to hairline(u) (degrees of v),\n    lifted `lift` off the scalp plus `crown` more at the top.\"\"\"\n    from outfit import piece, grid_mesh\n    U = np.linspace(-180, 180, nu)\n    G = np.zeros((nu, nv, 3))\n    UV = np.zeros((nu, nv, 2))\n    for i, u in enumerate(U):\n        vmax = hairline(u)\n        for j, s in enumerate(np.linspace(0, 1, nv)):\n            v = vmax * s                                    # from the crown itself (a gap there showed as a dot)\n            G[i, j] = chart.point(u, v, off=lift + crown * (1 - s) ** 2)\n            UV[i, j] = (i / (nu - 1) * 6, s)                # strands run from the crown down (u repeats)\n    pos, tri = grid_mesh(G)\n    pc = piece(name, role, pos, tri, outward_from=chart.c)\n    pc[\"uv\"] = UV.reshape(-1, 2)\n    pc[\"strands\"] = True\n    pc[\"group\"] = \"hair\"\n    return pc\n\n\n# ---- hairstyles -----------------------------------------------------------------------------------\ndef head_chart(fit, ear_x=None):\n    \"\"\"The chart over this body's skull, centred in the head skin's bounding box. The ears are left\n    out (triangles further than ear_x to the side, by default 0.835 of the head's half width, 8.6 cm\n    on the VRoid heads): cast onto them, every lock passing the sides was pushed out past the ears and\n    the hair became a bowl.\"\"\"\n    from fitting import Surface\n    head = fit.head_surface()\n    P = head.pos[np.unique(head.tri)]\n    centre = (P.min(0) + P.max(0)) / 2\n    if ear_x is None:\n        ear_x = min(0.086, 0.835 * float(P[:, 0].max() - centre[0]))\n    cx = head.pos[head.tri].mean(1)[:, 0]\n    skull = Surface(head.pos, head.tri[np.abs(cx - centre[0]) < ear_x])\n    return HeadChart(skull, centre)\n\n\ndef clump(t, widest=0.55, root=0.42, point=1.6):\n    \"\"\"A bang's width along it, as a fraction of its widest: it grows out of the hair mass, is widest\n    past its middle, then comes to a point.\"\"\"\n    if t < widest:\n        return root + (1 - root) * math.sin(math.pi / 2 * t / widest)\n    return max(0.0, 1 - ((t - widest) / (1 - widest)) ** point) ** 0.9\n\n\ndef elaine(fit):\n    \"\"\"Elaine's hair: a short bob with side-swept bangs, side locks framing the face, the back down to\n    the nape; her bun, braid and ribbon (outfit.updo) sit on top, and one upright strand curls forward\n    from the crown.\n    The bangs follow a study of Unicorn Overlord's character art (lesson 14): a few clumps of clearly\n    different widths and lengths fanning from a part off the centre, widest past their middle, a thin\n    strand or two between them; not a row of matching points (the user found seven of them jarring).\"\"\"\n    ch = head_chart(fit)\n    # the hairline: low at the nape (about the earlobe's bottom), and down in front of the ear over the\n    # temple (the base's untextured temple skin showed as a white triangle there)\n    out = [cap(\"hair_cap\", ch, lambda u: float(np.interp(abs(u), [0, 40, 60, 75, 90, 110, 130, 150, 180],\n                                                         [56, 62, 76, 100, 108, 110, 126, 140, 146])),\n               lift=0.007, crown=0.009)]\n    part = -24.0                                        # over her left eye\n    bangs = [  # name, path of (u, v, lift), widest width, (where widest, root fraction)\n        (\"sweep\", [(part + 4, 34, 0.006), (0, 60, 0.014), (20, 84, 0.017), (33, 96, 0.016)], 0.050, (0.50, 0.40)),\n        (\"sweep_back\", [(part + 12, 40, 0.005), (16, 64, 0.011), (40, 86, 0.013), (50, 95, 0.012)], 0.036, (0.55, 0.40)),\n        (\"fall\", [(part, 34, 0.006), (part - 1, 64, 0.016), (-10, 90, 0.019), (-5, 103, 0.018)], 0.030, (0.50, 0.45)),\n        (\"left\", [(part - 6, 36, 0.006), (part - 16, 64, 0.013), (-42, 88, 0.016), (-48, 97, 0.015)], 0.036, (0.55, 0.45)),\n        (\"strand_r\", [(part + 8, 42, 0.005), (8, 70, 0.018), (14, 99, 0.020)], 0.011, (0.35, 0.6)),\n        (\"strand_l\", [(-46, 48, 0.006), (-55, 76, 0.016), (-57, 98, 0.017)], 0.012, (0.35, 0.6)),\n    ]\n    for nm, path, w, (widest, root) in bangs:\n        out.append(lock(f\"hair_bang_{nm}\", ch, [(\"uv\", *p) for p in path], width=w, thick=0.008, n=32,\n                        profile=lambda t, a=widest, b=root: clump(t, a, b)))\n    # side locks: one in front of the ear down to the jaw, one over the ear's top\n    for s, side in ((1, \"R\"), (-1, \"L\")):\n        out.append(lock(f\"hair_side{side}0\", ch, [(\"uv\", s * 50, 24, 0.008), (\"uv\", s * 68, 68, 0.012),\n                                                   (\"uv\", s * 70, 108, 0.013), (\"uv\", s * 64, 140, 0.011)],\n                        width=0.030, thick=0.007, taper=(0.5, 1.0), root_width=0.013))\n        out.append(lock(f\"hair_side{side}1\", ch, [(\"uv\", s * 84, 40, 0.005), (\"uv\", s * 100, 70, 0.012),\n                                                   (\"uv\", s * 108, 104, 0.012), (\"uv\", s * 112, 122, 0.010)],\n                        width=0.032, thick=0.008, taper=(0.55, 1.0), root_width=0.015))\n    # the back: locks from the crown down to the nape, overlapping\n    for k, u in enumerate((112, 132, 152, 172, 192, 212, 232, 252)):\n        side = abs(u - 180) / 68                      # 1 at the sides, 0 at the middle of the back\n        sw = (1 if u < 180 else -1) * 22 * side       # sweep toward the nape as they fall\n        out.append(lock(f\"hair_back{k}\", ch, [(\"uv\", u, 30, 0.005), (\"uv\", u + sw * 0.2, 62, 0.010 + 0.006 * (1 - side)),\n                                              (\"uv\", u + sw * 0.6, 98, 0.010 + 0.004 * (1 - side)),\n                                              (\"uv\", u + sw, 146 - 14 * side, 0.008)],\n                        width=0.050, thick=0.009, taper=(0.75, 1.0), tip=0.3, root_width=0.020))\n    # the upright strand: from the crown, up and curling forward; flat side to the side\n    root = ch.point(0, 6, off=0.010)\n    up = np.array([0, 1.0, 0])\n    fwd = np.array([0, 0, -1.0])\n    out.append(lock(\"hair_ahoge\", ch, [(\"xyz\", *root), (\"xyz\", *(root + up * 0.030 - fwd * 0.004)),\n                                        (\"xyz\", *(root + up * 0.055 + fwd * 0.012)),\n                                        (\"xyz\", *(root + up * 0.050 + fwd * 0.040)),\n                                        (\"xyz\", *(root + up * 0.036 + fwd * 0.052))],\n                    width=0.016, thick=0.004, taper=(0.35, 1.0), flat_to=ch.c + np.array([-1.0, 0, 0]), n=24))\n    for pc in out:\n        fit.bind(pc, rigid=\"J_Bip_C_Head\")\n    return out\n\n\n# ---- facial hair -----------------------------------------------------------------------------------------\ndef _face_marks(ch, head, mouth=None):\n    \"\"\"Chart angles of the chin (the front's lowest point) and the mouth: the mouth's own centre when\n    given (a long face puts it well over 13 degrees above the chin), else 13 degrees above the chin.\"\"\"\n    P = head.pos[np.unique(head.tri)]\n    front = P[(np.abs(P[:, 0] - ch.c[0]) < 0.012) & (P[:, 2] < ch.c[2] - 0.04)]\n    chin = front[np.argmin(front[:, 1])]\n\n    def angle(q):\n        d = q - ch.c\n        return float(np.degrees(np.arccos(np.clip(d[1] / np.linalg.norm(d), -1, 1))))\n    v_chin = angle(chin)\n    return v_chin, (angle(mouth) if mouth is not None else v_chin - 13.0)\n\n\ndef beard(fit, style=\"full\", role=\"hair\", length=0.0):\n    \"\"\"Facial hair on the head chart. style: 'full' (jaw, chin and cheeks, open round the mouth, with a\n    moustache), 'short' (close-cropped, the same outline), 'goatee' (chin and moustache), 'moustache'.\n    length: metres of beard hanging below the chin (locks).\"\"\"\n    from plates import outline_plate\n    ch = head_chart(fit)\n    head = fit.head_surface()\n    mouth = [p[\"pos\"][np.unique(p[\"tri\"])] for p, r in zip(fit._prims, fit._roles) if r == \"mouth\" and len(p[\"tri\"])]\n    v_chin, v_mouth = _face_marks(ch, head, np.concatenate(mouth).mean(0) if mouth and getattr(fit, \"cloth_hull\", False) else None)\n    out = []\n    thick = 0.022 if style == \"full\" else 0.009\n    if style in (\"full\", \"short\"):\n        def top(u):\n            a = abs(u)\n            if a < 22:\n                return v_mouth + 8.0\n            if a < 62:\n                return v_mouth + 8.0 - (v_mouth + 8.0 - 110.0) * ((a - 22) / 40) ** 0.8\n            return 110.0 - 14.0 * min(1.0, (a - 62) / 30)\n        bottom = lambda u: min(149.0, v_chin + 7.0 - 3.0 * (abs(u) / 95))\n        fl = lambda u, v, s, t: thick * (1 - t) ** 0.7 * (0.6 + 0.4 * math.cos(math.radians(u)))\n        # solid: filled from its outer face down to the face (a shell standing off the jaw read as paper\n        # from below and from the side; the study draws beards as one mass)\n        pc, _ = outline_plate(\"beard\", role, ch, -96, 96, bottom, top, offset=0.004, flare=fl,\n                              thickness=lambda u, v, s, t: 0.003 + fl(u, v, s, t), nu=48, nv=14, roll=0,\n                              pattern=(STRANDS, 0.03))\n        out.append(pc)\n    if style == \"goatee\":\n        pc, _ = outline_plate(\"beard\", role, ch, -22, 22, lambda u: min(149.0, v_chin + 6.0), lambda u: v_mouth + 8.0,\n                              offset=0.004, flare=lambda u, v, s, t: 0.010 * (1 - t),\n                              thickness=lambda u, v, s, t: 0.003 + 0.010 * (1 - t), nu=20, nv=10, roll=0,\n                              pattern=(STRANDS, 0.03))\n        out.append(pc)\n    if style in (\"full\", \"short\", \"goatee\", \"moustache\"):          # the moustache: two locks from under the nose\n        for s in (-1, 1):\n            out.append(lock(f\"moustache{(s + 1) // 2}\", ch, [(\"uv\", s * 2, v_mouth - 7, 0.006), (\"uv\", s * 14, v_mouth - 4, 0.010),\n                                                             (\"uv\", s * 26, v_mouth + 3, 0.009)],\n                            width=0.016 if style != \"short\" else 0.010, thick=0.006, n=16, taper=(0.5, 1.0)))\n    if length > 0 and style in (\"full\", \"goatee\"):                  # the beard's fall below the chin\n        # one solid mass, wide at the jaw and tapering to a point (three thin locks read as a ruff, and\n        # a mass that stayed wide read as a bib)\n        p0 = ch.point(0, v_chin + 4, off=0.015) + np.array([0.0, 0.006, -0.006])\n        full = style == \"full\"\n        out.append(lock(\"beard_fall\", ch, [(\"xyz\", *p0), (\"xyz\", *(p0 + np.array([0, -length * 0.55, -0.010]))),\n                                           (\"xyz\", *(p0 + np.array([0, -length, -0.004])))],\n                        width=0.080 if full else 0.045, thick=0.026 if full else 0.018, n=16, seg=16,\n                        flat_to=p0 + np.array([0, 0, 0.3]), profile=lambda t: (1 - t) ** 1.1))   # a spade, to a point\n    for pc in out:\n        if \"decal\" in pc:                                           # the strand texture, not a decal\n            pc.pop(\"decal\")\n        pc[\"strands\"] = True\n        pc[\"group\"] = \"hair\"\n        fit.bind(pc, rigid=\"J_Bip_C_Head\")\n    return out\n\n\ndef crop(fit, lift=0.006, front=58.0, back=122.0):\n    \"\"\"A short crop: the cap alone, a hairline from the forehead (v=front) round to the nape (v=back).\"\"\"\n    ch = head_chart(fit)\n    hl = lambda u: float(np.interp(abs(u), [0, 50, 80, 105, 130, 180], [front, front + 6, front + 34, front + 40, back - 6, back]))\n    pc = cap(\"hair_cap\", ch, hl, lift=lift, crown=0.004)\n    fit.bind(pc, rigid=\"J_Bip_C_Head\")\n    return [pc]\n"}