A 3D model pipeline, pushed by GPT-6-Astra
agent (cont.)
+2:41exec_commandmkdir -p review/astra review/out/astra/site review/out/astra/browser && cat > review/astra/build.py <<'PY'
command
mkdir -p review/astra review/out/astra/site review/out/astra/browser && cat > review/astra/build.py <<'PY' """One isolated costume study. Reads the cached body, never rebuilds shared data. Run: OPENBLAS_NUM_THREADS=1 python3 review/astra/build.py """ from pathlib import Path import base64 import json import os import sys import time ROOT = Path(__file__).resolve().parents[2] sys.path[:0] = [str(ROOT / 'tools'), str(ROOT / 'art/cast')] import numpy as np import cage from cast import CAST import vroid_portrait as vp import export_glb as E import outfit as O import gear as G import mobs import poses as P from fitting import Surface, merge_surfaces from rig import Rig, grip_points from vrm import VRM, vertex_normals OUT = ROOT / 'review/out/astra/site' OUT.mkdir(parents=True, exist_ok=True) def warden(fit): B = fit.bone hips, neck = B['J_Bip_C_Hips'], B['J_Bip_C_Neck'] knee = B['J_Bip_L_LowerLeg'][1] out, shirt, trousers, boots = mobs._base(fit, shirt='linen', legs='cloth', boots='boot', shirt_subdiv=1) G.loose_sleeves(fit, shirt, ease=0.042, cuff=0.55, folds=5) G.breeches(fit, trousers, boots, hips[1] - 0.22, knee - 0.075, ease=0.025, folds=5) under = mobs._under(shirt) # A short teal quilted coat, steel chest, cream sleeves, one shoulder plate. out += G.quilted(fit, under, role='signature', y_hem=hips[1] - 0.31, flare=0.085, split=18, stitch=24, sleeves=False) coat = mobs._surf(out, 'gambeson') out += G.breastplate(fit, coat, y_top=neck[1]-0.085, y_bottom=hips[1]+0.11, plackart=False, keel=0.006, arm=63) plate = mobs._surf(out, 'breastplate', prefix=True) cuffs = G.cuffs(fit, role='glove', length=0.55, flare=0.029) G.tuck_sleeves(fit, shirt, cuffs) out += cuffs waist = merge_surfaces((shirt['pos'],shirt['tri']), coat) belt, front = O.belt(fit, 'warden_belt', 'leather', waist, hips[1]+0.065, height=0.045, offset=0.013, tilt=0.055) belt['group']='belt'; out.append(belt) buckle = O.box('warden_buckle','gold',front+[0,0,-0.008],np.eye(3),(0.024,0.025,0.005)) out.append(fit.bind(buckle,rigid='J_Bip_C_Hips')) # Collar and a short travelling cape. Its hem is authored for this still, not simulated. collar, rim, _ = O.collar(fit,'warden_collar','signature',height_back=0.055,height_front=0.025,gap_deg=42) out.append(collar) out.append(O.inherit(O.ribbon('collar_edge','heraldry',rim,width=0.007,normals=O.near_normals(collar,rim)),collar)) shoulder = merge_surfaces((shirt['pos'],shirt['tri']), plate, (collar['pos'],collar['tri']), (fit.pos,fit.tri)) cape, grid = O.cape(fit,'warden_cape','cape',shoulder,length=0.86,phi=0.57,folds=4,fold_depth=0.012) # Sweep the lower cloth to the character's left. Keep the attachment ring fixed. t=np.linspace(0,1,grid.shape[1])[None,:,None] grid += t**1.6 * np.array([-0.22,0.045,0.10]) cape['pos']=grid.reshape(-1,3); cape['nrm']=vertex_normals(cape['pos'],cape['tri']) out.append(cape) for k,line in enumerate([grid[:,-1],grid[0],grid[-1]]): out.append(O.inherit(O.ribbon('cape_edge'+str(k),'heraldry',line,width=0.013, normals=O.near_normals(cape,line)),cape)) pcs,rims=O.pauldron(fit,'warden_pauldron','steel',shoulder,side='L', lames=((0,60,0.023,0.030),(50,83,0.022,0.028)),spread=108) for pc,rim in zip(pcs,rims): pc['group']='plate';out.append(pc) out.append(O.inherit(O.pipe('shoulder_roll','metal',rim,r=0.003),pc)) # A plain spear keeps a clear long silhouette and avoids the old sword costume's identity. out += G.spear(fit,length=2.18,grip=0.77,head=0.32) for p in out: if 'grid' in p: p.pop('grid') return out def main(): start=time.perf_counter() body='arm_f_strong' path=Path(cage.path_for(body,CAST[body]['cage'])) if not path.is_file(): raise SystemExit('Cached body missing; this study will not rebuild data.') shape=dict(CAST[body]['shape'], rest={'Fcl_BRW_Angry':0.16}, arm_out=4) v=VRM(str(path)); rig=Rig(v,shape,ortho=True) pose=P.merge(P.BUST,P.fist('R'),P.fist('L',curl=(18,25,18),thumb=10),{ 'J_Bip_C_Hips':P.move(0,-0.018,0,r=P.rot((0,0,1),-2)), 'J_Bip_C_Chest':P.rot((0,1,0),-5), 'J_Bip_C_Head':P.rot((0,1,0),12), 'J_Bip_L_UpperLeg':P.rot((0,0,1),-6)@P.rot((1,0,0),7), 'J_Bip_R_UpperLeg':P.rot((0,0,1),4)@P.rot((1,0,0),-5), }) feet={s:rig.pos(P.BUST,f'J_Bip_{s}_Foot') for s in 'LR'} for s,delta in [('L',[-0.065,0,-0.075]),('R',[0.055,0,0.04])]: pose=rig.leg_ik(pose,s,feet[s]+delta) grip=grip_points(v,shape,P.BUST) # Hand beside the waist, spear almost upright. The other hand rests at the hip. target=rig.pos(P.BUST,'J_Bip_C_Hips')+np.array([0.35,0.09,-0.18]) pose=rig.grip(pose,'R',P.BUST,grip['R']['point'],target,[0.12,1,-0.08],[1,-0.4,0.3]) targetL=rig.pos(P.BUST,'J_Bip_C_Hips')+np.array([-0.23,0.07,-0.075]) pose=rig.arm_ik(pose,'L',targetL,[-1,0,0.35]) portrait=vp.Portrait(str(path),shape=shape,pose=P.BUST,costume=warden) portrait.paint=dict(signature='#24575b',doublet='#303e42',linen='#c4c3ad',heraldry='#b7ad83', cape='#24575b',steel='#929d9e',gold='#b49a5e',metal='#929d9e',leather='#604737', boot='#333b3d',glove='#4f4640',hair='#88442d',skin='#e6bc9f',wood=dict(kind='leather',base='#55483c'), grain=dict(signature=0.025,linen=0.025,cape=0.025)) pal=dict(vp.PALETTE,**CAST[body]['colors'],A='#2d211e',B='#583327',C='#88442d',D='#b46642',E='#d18c59', r='#20333b',s='#507b7b',t='#a2b5a0') clips={'idle':[(0,pose),(1,pose)],'watch':[(0,pose),(1,pose)],'apose':[(0,P.BUST),(1,P.BUST)]} size=E.export_skinned(portrait,pal,str(OUT/'warden.glb'),clips=clips) raw=(OUT/'warden.glb').read_bytes() (OUT/'warden.glb.json').write_text(json.dumps({'glb':base64.b64encode(raw).decode()})) info=E.scene_info(portrait,pal);info['cloth']={} info['paint']['cape']={'kind':'cloth','base':'#24575b','grain':0.025} cams={k:portrait.frame(k) for k in ['bust','battle']} (OUT/'camera.json').write_text(json.dumps({'characters':[{'name':'warden','label':'Border warden','cams':cams,'info':info}], 'page':{'title':'Border warden','duel':False},'lineup':{'order':[],'spacing':1}})) pose_json={k:np.asarray(val).tolist() for k,val in pose.items()} (OUT/'pose.json').write_text(json.dumps(pose_json,indent=2)) timing={'build_seconds':round(time.perf_counter()-start,3),'body':str(path),'glb_bytes':len(raw),'pieces':len(portrait.prims)} (OUT/'build.json').write_text(json.dumps(timing,indent=2)); print(json.dumps(timing),flush=True) if __name__=='__main__': main() PY OPENBLAS_NUM_THREADS=1 python3 review/astra/build.pyresult, 4 lines
Script completed Wall time 0.5 seconds Output: {"chunk_id":"8c3ecd","wall_time_seconds":0.276823684,"exit_code":1,"original_token_count":65,"output":"Traceback (most recent call last):\n File \"~/work/lowmarch/review/astra/build.py\", line 24, in <module>\n from vrm import VRM, vertex_normals\nImportError: cannot import name 'vertex_normals' from 'vrm' (~/work/lowmarch/tools/vrm.py)\n"}exec_commandrg -n 'import.*vertex_normals' tools/outfit.py && sed -n '323,337p' tools/gear.py && cat ~/context/sortie-node_modules/three/package.json | head -20 (+1 more)
command
rg -n 'import.*vertex_normals' tools/outfit.py && sed -n '323,337p' tools/gear.py && cat ~/context/sortie-node_modules/three/package.json | head -20 sed -i 's/from vrm import VRM, vertex_normals/from vrm import VRM\nfrom fitting import vertex_normals/' review/astra/build.py OPENBLAS_NUM_THREADS=1 python3 review/astra/build.py
result, 4 lines
Script completed Wall time 1.2 seconds Output: {"chunk_id":"1c4307","wall_time_seconds":0.00000593,"exit_code":1,"original_token_count":0,"output":""}{"chunk_id":"a9b38a","wall_time_seconds":1.001975205,"session_id":5666,"original_token_count":0,"output":""}exec_commandhead -22 ~/context/sortie-node_modules/three/package.json && head -70 ~/context/sortie-node_modules/three/examples/jsm/loaders/GLTFLoader.js && sed -n '323,337p' tools/gear.py && sed -n '600,632p' review/vroid-02/index.html && rg -n 'new THREE.WebGLRenderer|stageEl|const FIGURE' review/vroid-02/index.html (+1 more)
command
head -22 ~/context/sortie-node_modules/three/package.json && head -70 ~/context/sortie-node_modules/three/examples/jsm/loaders/GLTFLoader.js && sed -n '323,337p' tools/gear.py && sed -n '600,632p' review/vroid-02/index.html && rg -n 'new THREE.WebGLRenderer|stageEl|const FIGURE' review/vroid-02/index.html cat > review/astra/prepare.py <<'PY' """Copy the current painted renderer, with an isolated capture hook and local three.js.""" from pathlib import Path import shutil ROOT=Path(__file__).resolve().parents[2] OUT=ROOT/'review/out/astra/site' THREE=Path('~/context/sortie-node_modules/three') for sub in ['build','examples/jsm']: shutil.copytree(THREE/sub,OUT/'vendor'/sub,dirs_exist_ok=True) s=(ROOT/'review/vroid-02/index.html').read_text() s=s.replace('https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js','./vendor/build/three.module.js') s=s.replace('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/','./vendor/examples/jsm/') s=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">','') # No change to the project renderer; only this generated copy gets the hook. s=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)') (OUT/'index.html').write_text(s) print(OUT/'index.html') PY cat > review/astra/capture.js <<'JS' // Injected inside the existing renderer module. Plain JS, no transpiler helpers. state.cloth = false; state.physics = false; await setView('bust'); state.view = 'battle'; state.hidden = new Set(); applyMaterials(); holdPose('watch', 0); R.setPixelRatio(1); R.setSize(1440, 1200, false); window.study = { shot(options = {}) { const w = options.w || 1440, h = options.h || 1200; R.setSize(w,h,false); setYaw(options.yaw ?? -25); holdPose(options.pose || 'watch',0); const centre = new THREE.Vector3(options.x ?? -0.03, options.y ?? 1.03, 0); frameAt(centre, options.span || 2.55, w,h, options.pitch ?? 3); render(); return R.domElement.toDataURL('image/png'); }, meshInfo() { return active()[0].meshes.map(o=>({name:o.userData.material,role:o.userData.role,group:o.userData.group})); } }; document.title = 'astra ready'; JS python3 review/astra/prepare.py cat > review/astra/shoot.cjs <<'JS' const { chromium } = require('~/context/sortie-node_modules/playwright'); const fs = require('fs'); const path = require('path'); const { spawn } = require('child_process'); const ROOT = path.resolve(__dirname, '../..'); const OUT = path.join(ROOT,'review/out/astra'); (async()=>{ const start=performance.now(); const server=spawn('python3',['-m','http.server','8765','--bind','127.0.0.1','--directory',path.join(OUT,'site')],{stdio:'ignore'}); let browser; try { browser=await chromium.launch({headless:true,args:['--no-sandbox','--use-angle=swiftshader','--enable-unsafe-swiftshader'],env:{...process.env,TMPDIR:path.join(OUT,'browser')}}); const page=await browser.newPage({viewport:{width:1440,height:1200},deviceScaleFactor:1}); const errors=[]; page.on('pageerror',e=>{errors.push(e.message); console.error(e.message)}); page.on('console',m=>{if(m.type()==='error') {errors.push(m.text());console.error(m.text().slice(0,1600))}}); await page.goto('http://127.0.0.1:8765/?astra=1'); await page.waitForFunction(()=>document.title==='astra ready',{},{timeout:60000}); const opts=JSON.parse(process.argv[2] || '{}'); const data=await page.evaluate(o=>window.study.shot(o),opts); const name=process.argv[3] || 'probe.png'; fs.writeFileSync(path.join(OUT,name),Buffer.from(data.split(',')[1],'base64')); fs.writeFileSync(path.join(OUT,'meshes.json'),JSON.stringify(await page.evaluate(()=>window.study.meshInfo()),null,2)); const result={render_seconds:+((performance.now()-start)/1000).toFixed(3),errors,options:opts,file:name}; fs.writeFileSync(path.join(OUT,'render.json'),JSON.stringify(result,null,2));console.log(result); if(errors.length) process.exitCode=1; } finally {if(browser) await browser.close();server.kill()} })().catch(e=>{console.error(e);process.exitCode=1}); JS NODE_PATH=~/context/sortie-node_modules node review/astra/shoot.cjsresult, 4 lines
Script completed Wall time 1.3 seconds Output: {"chunk_id":"a2a6a5","wall_time_seconds":0.00000428,"exit_code":0,"original_token_count":1314,"output":"{\n \"name\": \"three\",\n \"version\": \"0.186.1\",\n \"description\": \"JavaScript 3D library\",\n \"type\": \"module\",\n \"main\": \"./build/three.cjs\",\n \"module\": \"./build/three.module.js\",\n \"exports\": {\n \".\": {\n \"import\": \"./build/three.module.js\",\n \"require\": \"./build/three.cjs\"\n },\n \"./examples/fonts/*\": \"./examples/fonts/*\",\n \"./examples/jsm/*\": \"./examples/jsm/*\",\n \"./addons\": \"./examples/jsm/Addons.js\",\n \"./addons/*\": \"./examples/jsm/*\",\n \"./src/*\": \"./src/*\",\n \"./webgpu\": \"./build/three.webgpu.js\",\n \"./tsl\": \"./build/three.tsl.js\"\n },\n \"repository\": {\n \"type\": \"git\",\nimport {\n\tAnimationClip,\n\tBone,\n\tBox3,\n\tBufferAttribute,\n\tBufferGeometry,\n\tClampToEdgeWrapping,\n\tColor,\n\tColorManagement,\n\tDirectionalLight,\n\tDoubleSide,\n\tFileLoader,\n\tFrontSide,\n\tGroup,\n\tImageBitmapLoader,\n\tInstancedMesh,\n\tInterleavedBuffer,\n\tInterleavedBufferAttribute,\n\tInterpolant,\n\tInterpolateDiscrete,\n\tInterpolateLinear,\n\tLine,\n\tLineBasicMaterial,\n\tLineLoop,\n\tLineSegments,\n\tLinearFilter,\n\tLinearMipmapLinearFilter,\n\tLinearMipmapNearestFilter,\n\tLinearSRGBColorSpace,\n\tLoader,\n\tLoaderUtils,\n\tMaterial,\n\tMathUtils,\n\tMatrix4,\n\tMesh,\n\tMeshBasicMaterial,\n\tMeshPhysicalMaterial,\n\tMeshStandardMaterial,\n\tMirroredRepeatWrapping,\n\tNearestFilter,\n\tNearestMipmapLinearFilter,\n\tNearestMipmapNearestFilter,\n\tNumberKeyframeTrack,\n\tObject3D,\n\tOrthographicCamera,\n\tPerspectiveCamera,\n\tPointLight,\n\tPoints,\n\tPointsMaterial,\n\tPropertyBinding,\n\tQuaternion,\n\tQuaternionKeyframeTrack,\n\tRepeatWrapping,\n\tSkeleton,\n\tSkinnedMesh,\n\tSphere,\n\tSpotLight,\n\tTexture,\n\tTextureLoader,\n\tTriangleFanDrawMode,\n\tTriangleStripDrawMode,\n\tVector2,\n\tVector3,\n\tVectorKeyframeTrack,\n\tSRGBColorSpace,\n\tInstancedBufferAttribute\n} from 'three';\nimport { toTrianglesDrawMode } from '../utils/BufferGeometryUtils.js';\nimport { clone } from '../utils/SkeletonUtils.js';\n\ndef spear(fit, length=2.0, grip=0.55, head=0.26, hand=\"R\", shaft_role=\"wood\", name=\"spear\"):\n \"\"\"A spear held a little behind its middle: an ash shaft, a leaf blade with a socket, a butt cap.\"\"\"\n fist, fwd, side, flat, _ = _hand_frame(fit, hand)\n start = fist - fwd * grip\n out = [O.tube(f\"{name}_shaft\", shaft_role, start, fwd, length, 0.0135)]\n tip0 = start + fwd * length\n out.append(O.tube(f\"{name}_socket\", \"steel\", tip0 - fwd * 0.06, fwd, 0.08, 0.016, 0.012))\n leaf = [(0.0, 0.0), (0.024, head * 0.30), (0.018, head * 0.65), (0.0, head), (-0.018, head * 0.65), (-0.024, head * 0.30)]\n out.append(flat_piece(f\"{name}_head\", \"steel\", leaf, tip0 + fwd * 0.015, side, fwd, thickness=0.006))\n out.append(O.ball(f\"{name}_butt\", \"steel\", start - fwd * 0.01, 0.016, squash=(1, 1, 1.6)))\n _bind(fit, out, f\"J_Bip_{hand}_Hand\")\n return _group(out, \"weapon\")\n\n\ndef axe(fit, haft=0.85, blade=0.24, double=False, hand=\"R\", shaft_role=\"wood\", name=\"axe\", grip=0.18):\n float hair = 0.0;\n for (int s = 1; s <= 4; s++) { vec4 a = texture2D(tInfo, uv + vec2(0.0, float(s)) * uSil * px); int ra = rid(a); if (a.a > 0.5 && (ra == 3 || ra == 11)) hair = 1.0; }\n col = mix(col, col * vec3(0.84, 0.74, 0.76), 0.75 * hair);\n }\n }\n gl_FragColor = vec4(col, 1.0);\n }`;\n\nconst compCam = new THREE.Camera();\nfunction compPass(fs, uniforms) {\n const mat = new THREE.ShaderMaterial({ uniforms, vertexShader: `void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }`,\n fragmentShader: fs, transparent: true });\n const s = new THREE.Scene(); s.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat));\n return { mat, scene: s };\n}\n\n// ---- the renderer ---------------------------------------------------------------------------------------------------\nconst stageEl = $(\"stage\");\nconst R = new THREE.WebGLRenderer({ antialias: false, alpha: true, preserveDrawingBuffer: !!SHEET });\nR.setClearColor(0x000000, 0);\nR.outputColorSpace = THREE.LinearSRGBColorSpace;\nstageEl.appendChild(R.domElement);\nconst paint = compPass(PAINT_COMP, { tColor: { value: null }, tInfo: { value: null }, tDepth: { value: null }, uRes: { value: new THREE.Vector2() },\n uNear: { value: 0.1 }, uFar: { value: 40 }, uGap: { value: 0.012 }, uSil: { value: 2 }, uInner: { value: 1 }, uPpm: { value: 1000 } });\nconst ctl = new OrbitControls(camera, R.domElement);\nctl.enableDamping = true; ctl.zoomToCursor = true; ctl.screenSpacePanning = true;\nctl.minZoom = 0.3; ctl.maxZoom = 12;\nlet freeLook = false;\nctl.addEventListener(\"start\", () => { freeLook = true; });\nR.domElement.addEventListener(\"dblclick\", focusAt);\nconst targets = { rt: null, rtInfo: null, key: \"\" };\nfunction targetsFor(w, h) {\n const key = `${w}x${h}`;\n617:const stageEl = $(\"stage\");\n618:const R = new THREE.WebGLRenderer({ antialias: false, alpha: true, preserveDrawingBuffer: !!SHEET });\n621:stageEl.appendChild(R.domElement);\n1184: const W = stageEl.clientWidth, H = stageEl.clientHeight, mpp = (camera.right - camera.left) / camera.zoom / Math.max(1, W);\n1211: const W = stageEl.clientWidth || 1, H = stageEl.clientHeight || 1, ins = insets();\n1220: const w = stageEl.clientWidth, h = stageEl.clientHeight;\n1226:const FIGURE = { duel: { w: 2.9, top: 1.28, bottom: -1.18 }, battle: { w: 1.5, top: 1.24, bottom: -1.14 },\n1691:new ResizeObserver(() => size()).observe(stageEl);\n"}{"chunk_id":"894c59","wall_time_seconds":1.002306011,"session_id":81751,"original_token_count":15,"output":"~/work/lowmarch/review/out/astra/site/index.html\n"}write_stdinpoll session 5666 (+1 more)
input
const results=await Promise.allSettled([tools.write_stdin({session_id:5666,chars:"",yield_time_ms:1000,max_output_tokens:2500}),tools.write_stdin({session_id:81751,chars:"",yield_time_ms:1000,max_output_tokens:2500})]);results.forEach(text);result, 4 lines
Script completed Wall time 5.0 seconds Output: {"status":"fulfilled","value":{"chunk_id":"cd2d2a","wall_time_seconds":0.00000305,"exit_code":1,"original_token_count":179,"output":"Traceback (most recent call last):\n File \"~/work/lowmarch/review/astra/build.py\", line 125, in <module>\n if __name__=='__main__': main()\n File \"~/work/lowmarch/review/astra/build.py\", line 104, in main\n portrait=vp.Portrait(str(path),shape=shape,pose=P.BUST,costume=warden)\n File \"~/work/lowmarch/tools/vroid_portrait.py\", line 996, in __init__\n for pc in costume(fit):\n File \"~/work/lowmarch/review/astra/build.py\", line 49, in warden\n waist = merge_surfaces((shirt['pos'],shirt['tri']), coat)\n File \"~/work/lowmarch/tools/fitting.py\", line 88, in merge_surfaces\n for p, t in meshes:\nTypeError: cannot unpack non-iterable Surface object\n"}}{"status":"fulfilled","value":{"chunk_id":"dcd991","wall_time_seconds":5.004377007,"session_id":81751,"original_token_count":35,"output":"Failed to load resource: the server responded with a status of 404 (File not found)\nUnexpected token '<', \"<!DOCTYPE \"... is not valid JSON\n"}}exec_commandsed -n '40,100p' tools/fitting.py && rg -n '^class Surface|self\.' tools/fitting.py | head -18 (+1 more)
command
sed -n '40,100p' tools/fitting.py && rg -n '^class Surface|self\.' tools/fitting.py | head -18 sed -i "s/(shirt\['pos'\],shirt\['tri'\]), coat)/(shirt['pos'],shirt['tri']), (coat.pos,coat.tri))/; s/(shirt\['pos'\],shirt\['tri'\]), plate,/(shirt['pos'],shirt['tri']), (plate.pos,plate.tri),/" review/astra/build.py OPENBLAS_NUM_THREADS=1 python3 review/astra/build.py
result, 4 lines
Script completed Wall time 1.2 seconds Output: {"chunk_id":"ac552e","wall_time_seconds":0.00000502,"exit_code":0,"original_token_count":715,"output":"\nclass Surface:\n \"\"\"A triangle mesh you can measure against: signed distance (outside = +, from the closest\n face's normal), closest point, the triangle hit, and ray casts.\"\"\"\n\n def __init__(self, pos, tri):\n self.pos, self.tri = np.asarray(pos, float), np.asarray(tri)\n T = self.pos[self.tri]\n self.T = T\n fn = np.cross(T[:, 1] - T[:, 0], T[:, 2] - T[:, 0])\n self.fn = fn / np.maximum(np.linalg.norm(fn, axis=1, keepdims=True), 1e-12)\n self.tree = cKDTree(T.mean(1))\n\n def query(self, q, k=24):\n q = np.atleast_2d(np.asarray(q, float))\n _, idx = self.tree.query(q, k=min(k, len(self.tri)))\n idx = np.atleast_2d(idx)\n T = self.T[idx]\n cp = closest_on_tris(q[:, None], T[:, :, 0], T[:, :, 1], T[:, :, 2])\n d = np.linalg.norm(cp - q[:, None], axis=-1)\n j = np.argmin(d, 1)\n r = np.arange(len(q))\n cpb, db, ti = cp[r, j], d[r, j], idx[r, j]\n s = np.sign(((q - cpb) * self.fn[ti]).sum(-1))\n s[s == 0] = 1\n return s * db, cpb, ti\n\n def cast(self, o, d, rmax=0.3, far=True):\n \"\"\"Distance along the ray o + t d to the farthest (outer) or nearest hit; nan if none.\"\"\"\n a, b, c = self.T[:, 0], self.T[:, 1], self.T[:, 2]\n e1, e2 = b - a, c - a\n h = np.cross(d, e2)\n det = (e1 * h).sum(1)\n ok = np.abs(det) > 1e-12\n inv = np.where(ok, 1 / np.where(ok, det, 1), 0)\n s = o - a\n u = (s * h).sum(1) * inv\n qv = np.cross(s, e1)\n v = (qv @ d) * inv\n t = (e2 * qv).sum(1) * inv\n hit = ok & (u >= 0) & (v >= 0) & (u + v <= 1) & (t > 0) & (t < rmax)\n if not hit.any():\n return np.nan\n return t[hit].max() if far else t[hit].min()\n\n\ndef merge_surfaces(*meshes):\n pos, tri, off = [], [], 0\n for p, t in meshes:\n pos.append(p)\n tri.append(np.asarray(t) + off)\n off += len(p)\n return Surface(np.concatenate(pos), np.concatenate(tri))\n\n\n# ---- mesh operations ------------------------------------------------------------------\ndef weld(pos, tri, eps=1e-5):\n \"\"\"Merge vertices at the same position (VRoid splits them along UV seams).\"\"\"\n pairs = cKDTree(pos).query_pairs(eps, output_type=\"ndarray\")\n rep = np.arange(len(pos))\n for a, b in sorted(map(tuple, np.sort(pairs, 1)), key=lambda t: t[1]):\n41:class Surface:\n46: self.pos, self.tri = np.asarray(pos, float), np.asarray(tri)\n47: T = self.pos[self.tri]\n48: self.T = T\n50: self.fn = fn / np.maximum(np.linalg.norm(fn, axis=1, keepdims=True), 1e-12)\n51: self.tree = cKDTree(T.mean(1))\n55: _, idx = self.tree.query(q, k=min(k, len(self.tri)))\n57: T = self.T[idx]\n63: s = np.sign(((q - cpb) * self.fn[ti]).sum(-1))\n69: a, b, c = self.T[:, 0], self.T[:, 1], self.T[:, 2]\n"}{"chunk_id":"4b9004","wall_time_seconds":1.001113294,"session_id":36843,"original_token_count":0,"output":""}clock__curr_time, write_stdinclock__curr_time (+2 more)
input
text(await tools.clock__curr_time({}));text(await tools.write_stdin({session_id:81751,chars:"",yield_time_ms:1000,max_output_tokens:1500}));text(await tools.write_stdin({session_id:36843,chars:"",yield_time_ms:1000,max_output_tokens:1500}));result, 4 lines
Script completed Wall time 10.0 seconds Output: {"current_time":"2026-11-15 03:16:49 UTC"}{"chunk_id":"008ffb","wall_time_seconds":5.000802195,"session_id":81751,"original_token_count":0,"output":""}{"chunk_id":"67f1d7","wall_time_seconds":5.001210269,"session_id":36843,"original_token_count":0,"output":""}exec_commandps -eo pid,etime,rss,args | rg 'review/astra|http.server 8765|python3 review/astra/build' (+1 more)
command
ps -eo pid,etime,rss,args | rg 'review/astra|http.server 8765|python3 review/astra/build' sed -n '1,40p' tools/outfit.py && sed -n '111,135p' tools/outfit.py && sed -n '251,305p' tools/outfit.py
result, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"1b10e1","wall_time_seconds":0.00000356,"exit_code":0,"original_token_count":115,"output":" 376 00:35 112780 node review/astra/shoot.cjs\n 387 00:34 18556 python3 -m http.server 8765 --bind 127.0.0.1 --directory ~/work/lowmarch/review/out/astra/site\n 482 00:20 139820 python3 review/astra/build.py\n 488 00:00 3408 /bin/bash -c ps -eo pid,etime,rss,args | rg 'review/astra|http.server 8765|python3 review/astra/build'\n 490 00:00 4632 rg review/astra|http.server 8765|python3 review/astra/build\n"}{"chunk_id":"0c4f5a","wall_time_seconds":0.00000456,"exit_code":0,"original_token_count":1553,"output":"\"\"\"Fantasy costume pieces, generated in code and fitted onto a VRoid body.\n\nCoordinates are the model's (metres, y up, the character faces -z, its left is -x). Pieces are\nbuilt once in the reference pose (the bust pose, arms down) and carry skin weights (J, W, jnames)\nso the renderer can pose them with the body through the skeleton: soft layers copy the weights of\nthe body under them, hard parts ride one bone.\n\nKinds of piece (see docs/portrait-guide.md lesson 07 for the measurements behind the offsets):\n\n wrap a garment shrink-wrapped onto a body region chosen by bones (tunic, trousers, boots,\n gloves): seams welded, smoothed without shrinking, every vertex set at an offset\n collar a standing collar fitted to the neck by ray casts, rising toward the back\n pauldron three overlapping lames whose shape comes from ray casts to what they cover\n drape cloth (cape, tunic tails) settled by a small cloth simulation against the body\n belt a band around the waist on top of the tunic\n trim a band along a piece's edge (gold trim, piping), lifted off its surface\n props sword and hardware built from boxes, tubes and balls\n\nA costume is a function of a Fit (body + bones in the reference pose) returning a list of pieces.\n\"\"\"\nimport math\nimport os\n\nimport numpy as np\nfrom scipy.spatial import cKDTree\n\nfrom fitting import (Surface, merge_surfaces, weld, compact, subdivide, shrink_wrap, flatten_hem, limb_hull,\n boundary_loops, vertex_normals, transfer_weights, rigid_weights, blend_weights, taubin)\n\n\n# ---- mesh helpers --------------------------------------------------------------\ndef grid_mesh(P):\n \"\"\"P: (U, V, 3) grid of points -> (pos, tri).\"\"\"\n U, V = P.shape[:2]\n idx = np.arange(U * V).reshape(U, V)\n a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]\n tri = np.concatenate([np.stack([a, b, c], -1).reshape(-1, 3), np.stack([a, c, d], -1).reshape(-1, 3)])\n return P.reshape(-1, 3), tri\n\n\n\n\ndef tube(name, role, start, axis, length, r0, r1=None, seg=16, rows=2):\n r1 = r0 if r1 is None else r1\n a, b, c = frame_axes(axis)\n ang = np.linspace(0, 2 * math.pi, seg, endpoint=False)\n P = np.zeros((seg + 1, rows, 3))\n for j, t in enumerate(np.linspace(0, 1, rows)):\n r = r0 + (r1 - r0) * t\n ring = np.asarray(start) + a * length * t + (np.outer(np.cos(ang), b) + np.outer(np.sin(ang), c)) * r\n P[:seg, j] = ring\n P[seg, j] = ring[0]\n pos, tri = grid_mesh(P)\n return piece(name, role, pos, tri, outward_from=np.asarray(start) + a * length / 2, axis=a)\n\n\ndef ball(name, role, centre, r, seg=14, rows=8, squash=(1, 1, 1)):\n th = np.linspace(0, math.pi, rows)\n ph = np.linspace(0, 2 * math.pi, seg + 1)\n P = np.zeros((seg + 1, rows, 3))\n for j, t in enumerate(th):\n P[:, j, 0] = np.sin(t) * np.cos(ph) * r * squash[0]\n P[:, j, 1] = np.cos(t) * r * squash[1]\n P[:, j, 2] = np.sin(t) * np.sin(ph) * r * squash[2]\n P += np.asarray(centre)\ndef wrap(fit, name, role, bones, offset, min_w=0.5, exclude=(), y_min=None, y_max=None, subdiv=0,\n base=None, hems=(), smooth=15, cut=None, refloor=False, clamp=False):\n \"\"\"A garment shrink-wrapped onto the body region that follows `bones`. cut: (normal, d), keep only\n the skin below that plane (n.p < d, give or take a centimetre; pair it with a hem on the same plane).\n refloor: after the hems, push out whatever a hem pulled into the skin (a hem moves its edge straight\n along the plane's normal, which sinks it into a sloping hip; off by default so finished costumes\n don't drift). clamp: every vertex past a hem's plane goes onto it, not just the edge's (pass y_min\n and y_max a few centimetres past the hems: large skin triangles crossing a hem line otherwise leave\n notches as deep as a triangle).\"\"\"\n T = fit.tris_for(bones, min_w, exclude, y_min, y_max)\n if cut is not None:\n n_ = np.asarray(cut[0], float) / np.linalg.norm(cut[0])\n T = T[(fit.pos[T] @ n_).max(1) < cut[1] + 0.01]\n if not len(T):\n return None\n pos, tri, used = compact(fit.pos, T)\n levels = []\n for _ in range(subdiv):\n pos, tri, par = subdivide(pos, tri, with_parents=True)\n levels.append(par)\n out = shrink_wrap(pos, tri, base or fit.surf, offset, smooth=smooth)\n for n, d in hems:\n out = flatten_hem(out, tri, n, d)\n if clamp:\n n_ = np.asarray(n, float) / np.linalg.norm(n)\n over = out @ n_ - d\n out = out - np.outer(np.maximum(over, 0.0), n_)\n if refloor and hems:\n surf = base or fit.surf\n d2, cp2, ti2 = surf.query(out)\n low = d2 < offset * 0.75\n out[low] = cp2[low] + surf.fn[ti2[low]] * offset * 0.75\n pc = piece(name, role, out, tri)\n # weights come from the exact skin each vertex grew from: copying from the nearest skin instead\n # let the inside of one boot pick up the other leg's bones\n pc[\"J\"], pc[\"W\"] = blend_weights(fit.J[used], fit.W[used], int(fit.J.max()) + 1, levels)\n pc[\"jnames\"] = fit.jnames\n if getattr(fit, \"cloth_hull\", False): # a body with muscle relief: sleeves span the hollows\n hw = lambda b: (np.array([b == n for n in fit.jnames])[pc[\"J\"]] * pc[\"W\"]).sum(1)\n axes = []\n for sd in (\"L\", \"R\"):\n for b0, b1 in ((\"UpperArm\", \"LowerArm\"), (\"LowerArm\", \"Hand\"), (\"UpperLeg\", \"LowerLeg\"), (\"LowerLeg\", \"Foot\"),\n (\"Foot\", \"ToeBase\")): # (boots over the foot: no toes showing)\n n0, n1 = f\"J_Bip_{sd}_{b0}\", f\"J_Bip_{sd}_{b1}\"\n if n0 in fit.bone and n1 in fit.bone:\n m = hw(n0) + (hw(n1) if b0 == \"Foot\" else 0.0) # the foot's segment takes the toes too\n axes.append((m >= 0.6, fit.bone[n0], fit.bone[n1], b0 == \"Foot\"))\n pc[\"pos\"] = limb_hull(pc[\"pos\"], tri, axes)\n pc[\"nrm\"] = vertex_normals(pc[\"pos\"], tri)\n pc[\"loops\"] = boundary_loops(tri)\n return pc\n\n\ndef loop_trim(name, role, garment, pick, width=0.008, lift=0.0015):\n \"\"\"Trim along one of a garment's open edges: the loop that scores highest under `pick`.\"\"\"\n"}write_stdinpoll session 36843 (+1 more)
input
text(await tools.write_stdin({session_id:36843,chars:"",yield_time_ms:1000,max_output_tokens:2000}));text(await tools.write_stdin({session_id:81751,chars:"",yield_time_ms:1000,max_output_tokens:1500}));result, 4 lines
Script completed Wall time 5.0 seconds Output: {"chunk_id":"995061","wall_time_seconds":0.000002421,"exit_code":1,"original_token_count":100,"output":"Traceback (most recent call last):\n File \"~/work/lowmarch/review/astra/build.py\", line 125, in <module>\n if __name__=='__main__': main()\n File \"~/work/lowmarch/review/astra/build.py\", line 109, in main\n pal=dict(vp.PALETTE,**CAST[body]['colors'],A='#2d211e',B='#583327',C='#88442d',D='#b46642',E='#d18c59',\nTypeError: dict() got multiple values for keyword argument 'A'\n"}{"chunk_id":"f84f0c","wall_time_seconds":5.000625539,"session_id":81751,"original_token_count":0,"output":""}exec_commandpython3 - <<'PY'
command
python3 - <<'PY' p='review/astra/build.py' s=open(p).read().replace("pal=dict(vp.PALETTE,**CAST[body]['colors'],A=", "pal=dict({**vp.PALETTE,**CAST[body]['colors']},A=") open(p,'w').write(s) PY OPENBLAS_NUM_THREADS=1 python3 review/astra/build.pyresult, 4 lines
Script completed Wall time 1.2 seconds Output: {"chunk_id":"50335f","wall_time_seconds":1.00137821,"session_id":44458,"original_token_count":0,"output":""}