A 3D model pipeline, pushed by GPT-6.2-Astra
agent (cont.)
+26:22exec_commandPYTHONPATH=tools:art/cast OPENBLAS_NUM_THREADS=1 python3 - <<'PY'
command
PYTHONPATH=tools:art/cast OPENBLAS_NUM_THREADS=1 python3 - <<'PY' from cast import CAST import cage,rig, vroid_portrait as p from vrm import VRM v=VRM(cage.path_for('arm_f_strong',CAST['arm_f_strong']['cage'])) r=rig.Rig(v,dict(shoulder_w=.012,arms=1.09,torso=1.025,legs=1.07)) for n in r.names: if n.startswith(('J_Bip_C_','J_Bip_R_','J_Adj_R_FaceEye')) and not any(k in n for k in ['Index','Ring','Middle','Thumb','Little']): print(n,r.pos(p.BUST_POSE,n).round(3)) PY sed -n '54,103p' tools/vrm.py; sed -n '182,209p' tools/export_glb.py; sed -n '1,45p' tools/mobs.pyresult, 4 lines
Script completed Wall time 0.4 seconds Output: {"chunk_id":"136935","wall_time_seconds":0.229052305,"exit_code":0,"original_token_count":1748,"output":"J_Bip_C_Hips [ 0. 1.012 -0.024]\nJ_Bip_C_Spine [-0. 1.083 -0.038]\nJ_Bip_C_Chest [-0. 1.24 -0.046]\nJ_Bip_C_UpperChest [-0. 1.391 -0.035]\nJ_Bip_C_Neck [-0. 1.578 -0.002]\nJ_Bip_C_Head [-0. 1.638 -0.044]\nJ_Adj_R_FaceEye [ 0.016 1.706 -0.067]\nJ_Bip_R_Shoulder [ 0.025 1.513 -0.031]\nJ_Bip_R_UpperArm [ 0.166 1.482 -0.026]\nJ_Bip_R_LowerArm [ 0.23 1.183 -0.026]\nJ_Bip_R_Hand [ 0.285 0.921 -0.026]\nJ_Bip_R_UpperLeg [ 0.103 0.999 -0.017]\nJ_Bip_R_LowerLeg [ 0.103 0.532 -0.05 ]\nJ_Bip_R_Foot [ 0.103 0.111 -0.017]\nJ_Bip_R_ToeBase [ 0.103 0.03 -0.161]\n im = self.j[\"images\"][i]\n bv = self.j[\"bufferViews\"][im[\"bufferView\"]]\n data = self.bin[bv.get(\"byteOffset\", 0):bv.get(\"byteOffset\", 0) + bv[\"byteLength\"]]\n self._img[i] = np.asarray(Image.open(io.BytesIO(data)).convert(\"RGBA\"))\n return self._img[i]\n\n def material_texture(self, mi):\n m = self.j[\"materials\"][mi]\n t = m.get(\"pbrMetallicRoughness\", {}).get(\"baseColorTexture\")\n if t is None:\n return None\n return self.image(self.j[\"textures\"][t[\"index\"]][\"source\"])\n\n def material_cutout(self, mi):\n m = self.j[\"materials\"][mi]\n return m.get(\"alphaMode\", \"OPAQUE\") in (\"MASK\", \"BLEND\")\n\n def nodes_by_name(self):\n return {n.get(\"name\"): i for i, n in enumerate(self.j[\"nodes\"])}\n\n def local_matrix(self, i, pose=None):\n \"\"\"Local matrix of node i with an optional pose adjustment applied in the node's own frame:\n a 3x3 (rotation / scale) or a 4x4 (with a translation offset).\"\"\"\n n = self.j[\"nodes\"][i]\n if \"matrix\" in n:\n m = np.array(n[\"matrix\"], float).reshape(4, 4).T\n else:\n t = np.eye(4)\n t[:3, 3] = n.get(\"translation\", [0, 0, 0])\n x, y, z, w = n.get(\"rotation\", [0, 0, 0, 1])\n r = np.eye(4)\n r[:3, :3] = [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],\n [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],\n [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]\n m = t @ r @ np.diag(list(n.get(\"scale\", [1, 1, 1])) + [1])\n adj = (pose or {}).get(n.get(\"name\"))\n if adj is not None:\n adj = np.asarray(adj, float)\n if adj.shape == (3, 3):\n a4 = np.eye(4)\n a4[:3, :3] = adj\n adj = a4\n m = m @ adj\n return m\n\n def parents(self):\n return {c: i for i, n in enumerate(self.j[\"nodes\"]) for c in n.get(\"children\", [])}\n\n def node_world(self, pose=None):\n \"\"\"World matrix of every node. pose: {node name: 3x3 rotation/scale or 4x4 adjustment\n\ndef scene_info(portrait, palette):\n \"\"\"Everything the browser's pixel renderer and cloth solver need besides the meshes: palette\n bands per role, the lights, body colliders, cloth grids and the mouth curve (model space,\n turned to face +z like the GLB).\"\"\"\n import vroid_portrait as vp\n from vrm import bone_weight\n hexp = lambda c: palette[c]\n bands = lambda tbl: [[thr if thr > -5 else -9, hexp(c)] for thr, c in tbl]\n roles = {\"face\": dict(mode=\"bands\", bands=bands(vp.SKIN_BANDS)),\n \"body\": dict(mode=\"bands\", bands=bands(vp.SKIN_BANDS), cap=hexp(\"4\")),\n \"shadow\": dict(mode=\"flat\", color=hexp(\"3\")),\n \"hair\": dict(mode=\"bands\", bands=bands(vp.HAIR_BANDS)),\n \"cloth\": dict(mode=\"bands\", bands=bands(vp.CLOTH_BANDS)),\n \"line\": dict(mode=\"flat\", color=hexp(\"o\")), \"brow\": dict(mode=\"flat\", color=hexp(\"A\")),\n \"mouth\": dict(mode=\"flat\", color=hexp(\"1\")), \"white\": dict(mode=\"flat\", color=hexp(\"w\")),\n \"highlight\": dict(mode=\"flat\", color=hexp(\"w\")),\n \"iris\": dict(mode=\"iris\", colors=[hexp(\"r\"), hexp(\"s\"), hexp(\"t\")], cuts=[0.25, 0.5])}\n for r, tbl in vp.MATERIALS.items():\n roles[r] = dict(mode=\"bands\", bands=bands(tbl), world=r in vp.WORLD_ROLES)\n names = portrait.v.nodes_by_name()\n W = portrait.v.node_world(portrait.pose_now)\n body = [p for p, r in zip(portrait.prims, portrait.roles) if r == \"body\"][0]\n caps = []\n for a, b in CAPSULES:\n if a not in names or b not in names:\n continue\n A, B = W[names[a]][:3, 3], W[names[b]][:3, 3]\n\"\"\"Common enemy units: one costume per class, built from gear.py on any base body. Generic but detailed:\nlayered padding, mail and plate, riveted straps, an army colour on the cloth and shields (portrait\nguide, lesson 15). Pair each with a build and a face from gear.BUILDS / gear.FACES in the cast.\n\"\"\"\nimport numpy as np\n\nimport outfit as O\nimport gear as G\nfrom fitting import Surface, merge_surfaces\nfrom vrm import bone_weight\n\n\ndef _base(fit, shirt=\"padding\", legs=\"cloth\", boots=\"boot\", gloves=\"glove\", knee=None, shirt_subdiv=0, boot_top=None):\n \"\"\"Under layers every class shares: a shirt with sleeves to the wrist, trousers, boots to below\n the knee (or to boot_top: above the knee, they take the thigh too), gloves. Returns the pieces and\n the shirt (what coats are fitted over).\"\"\"\n B = fit.bone\n nk, hips = B[\"J_Bip_C_Neck\"], B[\"J_Bip_C_Hips\"]\n knee = B[\"J_Bip_L_LowerLeg\"][1] if knee is None else knee\n\n def cuff(side):\n a, h = B[f\"J_Bip_{side}_LowerArm\"], B[f\"J_Bip_{side}_Hand\"]\n n = (h - a) / np.linalg.norm(h - a)\n return n, n @ (h - n * 0.02)\n torso = (\"Spine\", \"Chest\", \"UpperChest\", \"Bust\", \"Shoulder\", \"UpperArm\", \"LowerArm\", \"Neck\", \"Hips\")\n # the neckline: a straight hem, lower at the throat than at the back of the neck (a level cut of\n # whole triangles left a saw-tooth edge, and a big trapezius showed above it)\n nh = np.array([0.0, 1.0, -0.3]) / np.linalg.norm([0.0, 1.0, -0.3])\n neckline = (nh, float(nh @ (nk + np.array([0.0, 0.012, 0.0]))))\n s = O.wrap(fit, \"shirt\", shirt, torso, offset=0.006, exclude=(\"UpperLeg\",), y_min=hips[1] - 0.04,\n y_max=nk[1] + 0.05, cut=neckline, hems=[cuff(\"L\"), cuff(\"R\"), neckline], subdiv=shirt_subdiv)\n t = O.wrap(fit, \"trousers\", legs, (\"Hips\", \"UpperLeg\", \"LowerLeg\"), offset=0.007, y_max=hips[1] + 0.02, subdiv=1)\n top = knee - 0.07 if boot_top is None else boot_top\n b = O.wrap(fit, \"boots\", boots, (\"LowerLeg\", \"Foot\", \"ToeBase\") + ((\"UpperLeg\",) if top > knee else ()), offset=0.015,\n y_max=top, subdiv=1, hems=[((0, 1, 0), top - 0.005)])\n g = O.wrap(fit, \"gloves\", gloves, (\"Hand\", \"Thumb\", \"Index\", \"Middle\", \"Ring\", \"Little\"), offset=0.003, min_w=0.3, smooth=4)\n out = [p for p in (s, t, b, g) if p is not None]\n for p, grp in zip(out, (\"doublet\", \"trousers\", \"boots\", \"gloves\")):\n p[\"group\"] = grp\n return out, s, t, b\n\n\ndef underwear(fit, band=False):\n \"\"\"Plain shorts (and a chest band with band=True) for inspecting bare bodies (the armory page, built\n in the T-pose): hips to mid-thigh, close to the skin.\"\"\"\n"}exec_commandsed -n '160,188p' tools/hair.py && sed -n '528,583p' tools/export_glb.py && sed -n '43,88p' tools/poses.py && rg -n 'def shape|height\]' tools/vroid_portrait.py | head -8 && cat ~/context/reflect/lowmarch.html | sed -n '1p'
command
sed -n '160,188p' tools/hair.py && sed -n '528,583p' tools/export_glb.py && sed -n '43,88p' tools/poses.py && rg -n 'def shape|height\]' tools/vroid_portrait.py | head -8 && cat ~/context/reflect/lowmarch.html | sed -n '1p'
result, 4 lines
Script completed Wall time 0.2 seconds Output: {"chunk_id":"a6076a","wall_time_seconds":0.000005441,"exit_code":0,"original_token_count":1540,"output":"\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 for name, keys in (clips or {}).items():\n times = np.array([t for t, _ in keys], np.float32)\n tacc = add_acc(times.reshape(-1, 1), \"SCALAR\", 5126, minmax=True)\n samplers, channels = [], []\n for i in order:\n mats = [F4 @ v.local_matrix(i, vp.bone_pose(v, portrait.shape, pose)) @ F4 for _, pose in keys]\n trs = [_trs(m) for m in mats]\n T = np.array([a for a, _, _ in trs], np.float32)\n Q = np.array([b for _, b, _ in trs], np.float32)\n for k in range(1, len(Q)): # keep quaternions on one hemisphere\n if np.dot(Q[k], Q[k - 1]) < 0:\n Q[k] = -Q[k]\n t0, q0, _ = _trs(local_ref[i])\n if np.dot(Q[0], q0) < 0:\n q0 = -q0\n # a channel whenever the clip leaves the reference pose, even if it then holds still\n if np.abs(Q - q0).max() > 1e-5:\n samplers.append(dict(input=tacc, output=add_acc(Q, \"VEC4\", 5126), interpolation=\"LINEAR\"))\n channels.append(dict(sampler=len(samplers) - 1, target=dict(node=node_of[i], path=\"rotation\")))\n if np.abs(T - t0).max() > 1e-5:\n samplers.append(dict(input=tacc, output=add_acc(T, \"VEC3\", 5126), interpolation=\"LINEAR\"))\n channels.append(dict(sampler=len(samplers) - 1, target=dict(node=node_of[i], path=\"translation\")))\n anims.append(dict(name=name, samplers=samplers, channels=channels))\n root = len(gnodes)\n gnodes.append(dict(name=\"character\", children=roots + mesh_nodes))\n gltf = dict(asset=dict(version=\"2.0\", generator=\"lowmarch export_skinned\"), scene=0, scenes=[dict(nodes=[root])],\n nodes=gnodes, meshes=meshes, materials=materials, skins=[skin], accessors=accessors, bufferViews=views,\n buffers=[dict(byteLength=len(bin_))], samplers=[dict(magFilter=9729, minFilter=9987)])\n if textures:\n gltf.update(textures=textures, images=images)\n if anims:\n gltf[\"animations\"] = anims\n js = json.dumps(gltf, separators=(\",\", \":\")).encode()\n js += b\" \" * ((4 - len(js) % 4) % 4)\n while len(bin_) % 4:\n bin_.append(0)\n out = struct.pack(\"<4sII\", b\"glTF\", 2, 12 + 8 + len(js) + 8 + len(bin_))\n out += struct.pack(\"<I4s\", len(js), b\"JSON\") + js + struct.pack(\"<I4s\", len(bin_), b\"BIN\\x00\") + bytes(bin_)\n open(path, \"wb\").write(out)\n return len(out)\n\n\ndef fist(side, curl=(70, 85, 55), thumb=35):\n \"\"\"Curl the fingers of one hand toward the palm (a grip).\"\"\"\n sz = -1 if side == \"R\" else 1 # rotation about local z that bends toward -y\n out = {}\n for f in (\"Index\", \"Middle\", \"Ring\", \"Little\"):\n for i, a in enumerate(curl, 1):\n out[f\"J_Bip_{side}_{f}{i}\"] = rot((0, 0, 1), sz * a)\n out[f\"J_Bip_{side}_Thumb2\"] = rot((0, 1, 0), (1 if side == \"R\" else -1) * thumb)\n out[f\"J_Bip_{side}_Thumb3\"] = rot((0, 0, 1), sz * 30)\n return out\n\n\n# Bust: arms down from the T-pose, shoulders relaxed.\nBUST = {\"J_Bip_L_UpperArm\": rot((0, 0, 1), 72), \"J_Bip_R_UpperArm\": rot((0, 0, 1), -72),\n \"J_Bip_L_Shoulder\": rot((0, 0, 1), 6), \"J_Bip_R_Shoulder\": rot((0, 0, 1), -6)}\n\n# Battle idle: sword in the right hand held forward, left arm loose, feet apart.\nBATTLE_IDLE = merge(BUST, {\n \"J_Bip_R_UpperArm\": rot((0, 1, 0), 18), # swing the right arm a little forward\n \"J_Bip_R_LowerArm\": rot((0, 1, 0), 55), # bend the elbow, forearm forward\n \"J_Bip_R_Hand\": rot((1, 0, 0), -20), # tip the blade up a little\n \"J_Bip_L_LowerArm\": rot((0, 1, 0), -20),\n \"J_Bip_L_UpperLeg\": rot((0, 0, 1), -5) @ rot((1, 0, 0), 8),\n \"J_Bip_R_UpperLeg\": rot((0, 0, 1), 5) @ rot((1, 0, 0), -10),\n \"J_Bip_R_LowerLeg\": rot((1, 0, 0), 12),\n}, fist(\"R\"), fist(\"L\", curl=(25, 35, 20), thumb=10))\n\n\n# ---- battle clips: (time in seconds, pose) keyframes ------------------------------------------------------------\n# Signs (VRoid rest frame): the character faces -z. For the right arm, rot_z(+) raises it,\n# rot_y(+) swings it forward. For legs, rot_x(+) swings the leg forward, rot_x(-) on a lower leg\n# bends the knee. For the spine, rot_y(+) turns the shoulders toward the left (the attack side),\n# rot_x(-) leans forward.\nWIND_UP = merge(BATTLE_IDLE, {\n \"J_Bip_C_Hips\": move(0, -0.02, 0.05),\n \"J_Bip_C_Spine\": rot((0, 1, 0), -22),\n \"J_Bip_C_Chest\": rot((1, 0, 0), 4),\n \"J_Bip_R_UpperArm\": rot((0, 0, 1), 95) @ rot((0, 1, 0), -40),\n \"J_Bip_R_LowerArm\": rot((0, 1, 0), 45),\n \"J_Bip_R_Hand\": rot((1, 0, 0), 25),\n \"J_Bip_L_UpperArm\": rot((0, 1, 0), -25),\n \"J_Bip_L_UpperLeg\": rot((1, 0, 0), 12),\n \"J_Bip_R_LowerLeg\": rot((1, 0, 0), -14),\n})\n<!doctype html>\n"}exec_commandcat > review/tide-keeper/forms.py <<'PY'
command
cat > review/tide-keeper/forms.py <<'PY' """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)): closed=sweep==(0,360) a=np.linspace(*np.radians(sweep),64,endpoint=not closed) pts=c+rx*np.outer(np.cos(a),ex)+ry*np.outer(np.sin(a),ey) return pipe(fit,name,role,pts,r,bone,closed) def cuff_grid(a,b,rx,rz,fractions,scales,shift=0.0): a,b=np.array(a),np.array(b) axis=(b-a)/np.linalg.norm(b-a) front=np.array([0.,0.,-1.]) front-=axis*(front@axis) front/=np.linalg.norm(front) side=np.cross(front,axis) theta=np.linspace(-np.pi,np.pi,49) rings=[] for t,s in zip(fractions,scales): c=a+(b-a)*t rings.append(c+np.outer(np.sin(theta)*rx*s,side)+np.outer(np.cos(theta)*rz*s+shift,front)) return np.stack(rings,axis=1) PY cat > review/tide-keeper/coiffure.py <<'PY' """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)) # Two blade-shaped hairpins over the exposed ear. for j in range(2): a=ch.point(67+j*8,60,off=.024) b=ch.point(118+j*7,79+j*3,off=.021) out.append(rod(fit,"hairpin","brass",a,b,.0035,.002,HEAD)) out.append(bead(fit,"pinhead","coral",a,.006,HEAD)) for side in (-1,1): ear=ch.point(side*92,99,off=.007) out.append(ring(fit,"earring","brass",ear+[0,-.012,0],[0,0,1],[0,1,0],.013,.021,.0025,HEAD)) out.append(bead(fit,"ear_drop","glaze",ear+[0,-.036,0],.007,HEAD,(.75,1.4,1))) return out PYresult, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"594042","wall_time_seconds":0.000007071,"exit_code":0,"original_token_count":0,"output":""}exec_commandcat > review/tide-keeper/tailoring.py <<'PY'
command
cat > review/tide-keeper/tailoring.py <<'PY' """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_Bip_{side}_UpperArm"; a,b=fit.bone[bone],fit.bone[f"J_Bip_{side}_LowerArm"] g=cuff_grid(a,b,.066,.063,[.22,.36,.64,.85,1.0],[1.16,1.24,1.26,1.13,.84]) out+=layered_sheet(fit,"rolled_sleeve_"+side,"canvas","vermilion",g,bone,(a+b)/2,"weft") out.append(pipe(fit,"sleeve_turnup","reef",g[:,3],.008,bone)) return out def instrument(fit): c,axis,side,flat,_=gear._hand_frame(fit) bone="J_Bip_R_Hand" out=[] def at(h): return c+axis*h out.append(rod(fit,"sounding_rod","wood",at(-1.19),at(.61),.012,.014,bone)) out.append(rod(fit,"heel_ferrule","brass",at(-1.19),at(-1.105),.015,.015,bone)) out.append(rod(fit,"bound_grip","saddle",at(-.083),at(.085),.018,.017,bone)) for j in range(14): y=-1.095+j*.073 out.append(rod(fit,"scale_"+str(j),"ivory" if j%3 else "brass",at(y),at(y+(.018 if j%3 else .033)),.0148,.0148,bone)) for y in [-.091,.089,.53,.582]: out.append(rod(fit,"socket","brass",at(y),at(y+.012),.019,.019,bone)) # An open brass tide dial. A separate plumb hangs through its centre. pivot=at(.71) across=side*.7+flat*.714 out+= [ring(fit,"astrolabe_limb","brass",pivot,across,axis,.091,.105,.007,bone), ring(fit,"alidade","glaze",pivot,across,axis,.075,.086,.004,bone,sweep=(188,350))] for deg in range(0,360,15): phi=np.radians(deg); d=across*.088*np.cos(phi)+axis*.101*np.sin(phi) out.append(rod(fit,"dial_tick","ivory" if deg%45 else "brass",pivot+d*.96, pivot+d*(.83 if deg%45==0 else .91),.002,.002,bone,8)) for sign in [-1,1]: out.append(pipe(fit,"fork","seasteel",curve([at(.48),at(.54)+sign*.021*across, at(.59)+sign*.053*across,at(.63)+sign*.059*across]),.007,bone)) out.append(rod(fit,"plumb_line","brass",at(.805),at(.70),.0028,.0028,bone)) out.append(rod(fit,"plumb_top","glaze",at(.715),at(.680),.004,.021,bone,6)) out.append(rod(fit,"plumb_tip","glaze",at(.680),at(.633),.021,.001,bone,6)) return out def outfit(fit): hips=fit.bone[HIP]; nk=fit.bone["J_Bip_C_Neck"] waist=hips[1]+.078 pcs,shirt,trousers,boots=mobs._base(fit,shirt="reef",legs="deepsea",boots="boot",gloves="glove", boot_top=fit.bone["J_Bip_L_LowerLeg"][1]+.07,shirt_subdiv=1) chest_surface=Surface(*O.without(shirt,("UpperArm","LowerArm","Shoulder","Hand"))) chart=TorsoChart(chest_surface,hips[1]-.050,nk[1]-.005,cz=hips[2],du=4.,dv=.009) torso=("Spine","Chest","UpperChest","Bust","Hips","Shoulder") # Armour closes high at the sides, dipping under the sternum to let the # front plates overlap like the shell ridges on the shoulder. for j,(y0,y1,col) in enumerate([(.00,.12,"seasteel"),(.095,.232,"seasteel"),(.201,.361,"porcelain")]): lower=lambda a:waist+y0+.033*(1-np.cos(np.radians(a)))+.014*abs(np.sin(np.radians(2*a))) upper=lambda a:waist+y1+.015*np.cos(np.radians(a*2)) p,g=body_panel(fit,chart,"corselet_"+str(j),col,(-177,177),lower,upper,.022+j*.002,torso,"armour") pcs.append(p); pcs.append(pipe(fit,"cuirass_roll","brass",g[:,0],.0038,torso)) if j==2: pcs.append(pipe(fit,"cuirass_neckline","reef",g[:,-1],.0055,torso)) belt,g=body_panel(fit,chart,"harness","saddle",(-180,180),lambda a:waist-.033+.012*np.sin(np.radians(a)), lambda a:waist+.014+.012*np.sin(np.radians(a)),.037,HIP) pcs.extend([belt,pipe(fit,"belt_stitch","brass",g[:,1],.002,HIP)]) # A diagonal leather baldric anchors the chart case at the near hip. a=np.linspace(-36,86,44) y=np.linspace(nk[1]-.10,waist-.010,44) strap=np.stack([chart.point(a+j,y,.041) for j in [-5,5]],axis=1) pcs.append(skin_grid(fit,"sounding_harness","saddle",strap,torso,[0,waist,hips[2]])) pcs.append(pipe(fit,"baldric_edge","brass",strap[:,0],.0018,torso)) centre=chart.point(78,waist,.048)+[.02,-.090,.013] ex=np.array([.17,.13,-.976]); ey=np.array([-.015,.991,.13]); n=np.cross(ex,ey) for name,role,coords,offset,thick in [ ("chart_case","saddle",[(-.083,.07),(.08,.07),(.09,-.04),(.063,-.097),(-.068,-.088),(-.086,-.045)],0,.044), ("case_flap","reef",[(-.088,.074),(.087,.076),(.085,.020),(.028,-.027),(-.06,-.016)],.027,.012)]: p=flat_piece(name,role,coords,centre+n*offset,ex,ey,thickness=thick) pcs.append(attach(fit,p,HIP)) pcs.append(bead(fit,"case_fastening","brass",centre+.038*n,.009,HIP)) for offset in [-.05,.05]: start=centre+offset*ex+.065*ey pcs.append(rod(fit,"belt_loop","saddle",start,start+[0,.055,-.01],.009,.010,HIP)) pcs+=coat(fit,chart,waist)+scarf(fit,chart) pcs+=gauntlets(fit,shirt)+shell_armour(fit,"R")+shell_armour(fit,"L")+legs(fit,boots) pcs+=instrument(fit)+coiffure(fit) return pcs PYresult, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"688bb5","wall_time_seconds":0.0000053,"exit_code":0,"original_token_count":0,"output":""}exec_commanddate -u
command
date -u sed -n '1,111p' tools/vrm.py sed -n '383,429p' tools/export_glb.py rg -n 'HairBack|repose|role_of' tools/vroid_portrait.py | head -16 rg -n 'def material_texture|def _trs' tools/{vrm,export_glb}.py which blenderresult, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"a90508","wall_time_seconds":0.00000517,"exit_code":0,"original_token_count":1864,"output":"Tue Nov 17 23:15:19 UTC 2026\n\"\"\"VRM / glTF-binary loader and a small software rasterizer, no dependencies beyond numpy + PIL.\n\nVRoid models are our 3D base (CC0 samples, see docs/vroid.md). This module reads them and\nrasterizes triangles into per-pixel buffers (depth, primitive id, normal, uv, local position) that\nthe portrait renderer shades in our palette. Nothing from the model's textures is copied into the\ngame except through those buffers (eye/brow/lash shapes come from alpha-tested texture masks).\n\"\"\"\nimport io\nimport json\nimport struct\n\nimport numpy as np\nfrom PIL import Image\n\n_CT = {5120: np.int8, 5121: np.uint8, 5122: np.int16, 5123: np.uint16, 5125: np.uint32, 5126: np.float32}\n_NC = {\"SCALAR\": 1, \"VEC2\": 2, \"VEC3\": 3, \"VEC4\": 4, \"MAT4\": 16}\n\n\nclass VRM:\n def __init__(self, path):\n b = open(path, \"rb\").read()\n magic, _, _ = struct.unpack(\"<4sII\", b[:12])\n assert magic == b\"glTF\", path\n jlen, _ = struct.unpack(\"<II\", b[12:20])\n self.j = json.loads(b[20:20 + jlen])\n off = 20 + jlen\n blen, _ = struct.unpack(\"<II\", b[off:off + 8])\n self.bin = b[off + 8:off + 8 + blen]\n self._img = {}\n self.meta = self.j.get(\"extensions\", {}).get(\"VRM\", {}).get(\"meta\", {})\n\n # ---- raw data --------------------------------------------------------------\n def accessor(self, i):\n a = self.j[\"accessors\"][i]\n dt, nc = _CT[a[\"componentType\"]], _NC[a[\"type\"]]\n n = a[\"count\"]\n if \"bufferView\" not in a:\n return np.zeros((n, nc), np.float32)\n bv = self.j[\"bufferViews\"][a[\"bufferView\"]]\n start = bv.get(\"byteOffset\", 0) + a.get(\"byteOffset\", 0)\n size = np.dtype(dt).itemsize\n stride = bv.get(\"byteStride\", size * nc)\n if stride == size * nc:\n arr = np.frombuffer(self.bin, dt, n * nc, start).reshape(n, nc)\n else:\n raw = np.frombuffer(self.bin, np.uint8, stride * (n - 1) + size * nc, start)\n arr = np.stack([np.frombuffer(raw[k * stride:k * stride + size * nc].tobytes(), dt) for k in range(n)])\n if a.get(\"normalized\"):\n arr = arr.astype(np.float32) / np.iinfo(dt).max\n return arr\n\n def image(self, i):\n if i not in self._img:\n im = self.j[\"images\"][i]\n bv = self.j[\"bufferViews\"][im[\"bufferView\"]]\n data = self.bin[bv.get(\"byteOffset\", 0):bv.get(\"byteOffset\", 0) + bv[\"byteLength\"]]\n self._img[i] = np.asarray(Image.open(io.BytesIO(data)).convert(\"RGBA\"))\n return self._img[i]\n\n def material_texture(self, mi):\n m = self.j[\"materials\"][mi]\n t = m.get(\"pbrMetallicRoughness\", {}).get(\"baseColorTexture\")\n if t is None:\n return None\n return self.image(self.j[\"textures\"][t[\"index\"]][\"source\"])\n\n def material_cutout(self, mi):\n m = self.j[\"materials\"][mi]\n return m.get(\"alphaMode\", \"OPAQUE\") in (\"MASK\", \"BLEND\")\n\n def nodes_by_name(self):\n return {n.get(\"name\"): i for i, n in enumerate(self.j[\"nodes\"])}\n\n def local_matrix(self, i, pose=None):\n \"\"\"Local matrix of node i with an optional pose adjustment applied in the node's own frame:\n a 3x3 (rotation / scale) or a 4x4 (with a translation offset).\"\"\"\n n = self.j[\"nodes\"][i]\n if \"matrix\" in n:\n m = np.array(n[\"matrix\"], float).reshape(4, 4).T\n else:\n t = np.eye(4)\n t[:3, 3] = n.get(\"translation\", [0, 0, 0])\n x, y, z, w = n.get(\"rotation\", [0, 0, 0, 1])\n r = np.eye(4)\n r[:3, :3] = [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],\n [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],\n [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]\n m = t @ r @ np.diag(list(n.get(\"scale\", [1, 1, 1])) + [1])\n adj = (pose or {}).get(n.get(\"name\"))\n if adj is not None:\n adj = np.asarray(adj, float)\n if adj.shape == (3, 3):\n a4 = np.eye(4)\n a4[:3, :3] = adj\n adj = a4\n m = m @ adj\n return m\n\n def parents(self):\n return {c: i for i, n in enumerate(self.j[\"nodes\"]) for c in n.get(\"children\", [])}\n\n def node_world(self, pose=None):\n \"\"\"World matrix of every node. pose: {node name: 3x3 rotation/scale or 4x4 adjustment\n applied in the node's own frame on top of its rest local transform}.\"\"\"\n pose = pose or {}\n nodes = self.j[\"nodes\"]\n parent = {}\n for i, n in enumerate(nodes):\n for c in n.get(\"children\", []):\n parent[c] = i\n out = {}\n clips: {name: [(time, pose dict), ...]} -> glTF animations (rotation, plus translation where a\n pose moves a bone). Scenery is left out (export it with export()).\"\"\"\n import vroid_portrait as vp\n v = portrait.v\n nodes_v = v.j[\"nodes\"]\n names = v.nodes_by_name()\n parent = v.parents()\n used = set()\n for p in portrait.prims:\n if \"jnames\" in p and not p.get(\"world\"):\n used.update(n for n in p[\"jnames\"] if n in names)\n joints = set()\n for nm in used: # every used bone plus its ancestors\n i = names[nm]\n while i is not None and i not in joints:\n joints.add(i)\n i = parent.get(i)\n order = sorted(joints)\n jidx = {nodes_v[i].get(\"name\"): k for k, i in enumerate(order)}\n ref = portrait.pose_ref\n local_ref = {i: F4 @ v.local_matrix(i, ref) @ F4 for i in order}\n world_ref = {}\n\n def wref(i):\n if i not in world_ref:\n world_ref[i] = (wref(parent[i]) @ local_ref[i]) if parent.get(i) in joints else local_ref[i]\n return world_ref[i]\n\n # glTF assembly (reuses the static exporter's buffer helpers by building a fresh document)\n bin_ = bytearray()\n views, accessors, meshes, gnodes, materials, textures, images, anims = [], [], [], [], [], [], [], []\n tex_index = {}\n\n def add_view(data, target=None):\n while len(bin_) % 4:\n bin_.append(0)\n off = len(bin_)\n bin_.extend(data)\n vw = dict(buffer=0, byteOffset=off, byteLength=len(data))\n if target:\n vw[\"target\"] = target\n views.append(vw)\n return len(views) - 1\n\n def add_acc(arr, kind, comp, target=None, minmax=False):\n arr = np.ascontiguousarray(arr)\n a = dict(bufferView=add_view(arr.tobytes(), target), componentType=comp, count=int(arr.shape[0]), type=kind)\n40: (\"Face_00_SKIN\", \"face\"), (\"Body_00_SKIN\", \"body\"), (\"HairBack\", \"hair\"), (\"_HAIR\", \"hair\"),\n78:def role_of(material):\n95:def repose(v, prims, ref, target):\n818: F = [p[\"pos\"][p[\"tri\"]] for p in prs if role_of(p[\"material\"]) == \"face\" and len(p[\"tri\"])]\n819: M = [p[\"pos\"][np.unique(p[\"tri\"])] for p in prs if role_of(p[\"material\"]) == \"mouth\" and len(p[\"tri\"])]\n960: hroles = [role_of(p[\"material\"]) for p in hp]\n962: dst = landmarks(self.prims, [role_of(p[\"material\"]) for p in self.prims])\n977: self.roles = [p.get(\"role\") or role_of(p[\"material\"]) for p in self.prims]\n1033: repose(self.v, [p for p in self.prims if not p.get(\"world\")], pose, target_pose)\ntools/export_glb.py:296:def _trs(m):\ntools/vrm.py:60: def material_texture(self, mi):\n~/.local/bin/blender\n"}exec_commandcat > review/tide-keeper/build.py <<'PY'
command
cat > review/tide-keeper/build.py <<'PY' """Build the fitted and animated tide surveyor in metres. Only reads the armory cache.""" from pathlib import Path import sys, json, time import numpy as np HERE=Path(__file__).resolve().parent ROOT=HERE.parents[1] CACHE=ROOT/"review/out/tide-keeper" sys.path[:0]=[str(ROOT/"tools"),str(ROOT/"art/cast"),str(ROOT/"review/high-water")] from cast import CAST import cage, vroid_portrait as vp, poses, rig, export_glb from vrm import VRM from tailoring import outfit import figure as first COLOURS={"canvas":"#e8d7af","porcelain":"#bcd8d0","seasteel":"#477278","deepsea":"#233f48", "reef":"#223843","vermilion":"#c34e38","poppy":"#e69a58","ivory":"#f3dfb5", "brass":"#d1a461","glaze":"#459795","saddle":"#81503b","boot":"#463b3d","rubber":"#292e36", "wood":"#523d32","glove":"#4c3e3c","inkhair":"#282c37","bluehair":"#3d4049", "umberhair":"#573e40","silk":"#e3c5a2","redcord":"#b14b3e","coral":"#d87556","skin":"#d8a57f"} METALS={"brass","porcelain","seasteel","glaze"} def action(v,shape): # The step and staff use the opening study's contact points. She sights the # crossing with the left hand, now above the brow, and leans over her lead leg. pose=first.make_pose(v,shape) r=rig.Rig(v,shape,ortho=True) head=r.pos(pose,"J_Bip_C_Head") pose=r.arm_ik(pose,"L",head+[-.116,.115,-.114],[-.95,-.2,.25]) pose=r.aim(pose,"J_Bip_L_Hand",[-1,0,0],[.92,.14,-.21]) for finger in ("Index","Middle","Ring","Little"): for i,k in enumerate((6,8,5),1): pose[f"J_Bip_L_{finger}{i}"]=poses.rot((0,0,1),k) keys=[] for t,s,turn in [(0,0,0),(.8,1,-2.0),(1.6,0,0),(2.4,-.65,2.5),(3.2,0,0)]: q=poses.merge(pose,{"J_Bip_C_Chest":poses.rot((1,0,0),s*1.4), "J_Bip_C_Head":poses.rot((0,1,0),turn)@poses.rot((1,0,0),s*2.4)}) # Replant the shaft through the moving shoulder at each authored extreme. grip=rig.grip_points(v,shape,vp.BUST_POSE)["R"]["point"] target=r.held(pose,"J_Bip_R_Hand",vp.BUST_POSE,grip) q=r.grip(q,"R",vp.BUST_POSE,grip,target,[-.16,1,.035],[.95,-.65,.4],iters=3) keys.append((t,q)) return keys def build(): start=time.perf_counter() CACHE.mkdir(exist_ok=True,parents=True) cast=CAST["arm_f_strong"] path=cage.path_for("arm_f_strong",cast["cage"]) shape=dict(vp.NEUTRAL,**cast["shape"]) shape.update(shoulder_w=.012,arms=1.09,legs=1.06,torso=1.025,neck=1.045, cheek=.55,jaw=.62,nose=.75,chin_w=.37,eye=.97,iris=.96,blush=.25) actor=vp.Portrait(path,shape=shape,pose=vp.BUST_POSE,costume=outfit, morphs={"Fcl_BRW_Angry":.24,"Fcl_EYE_Angry":.16,"Fcl_MTH_Fun":.16}) # Remove every donated hair mesh, including the painted hair base. The new # cut uses its own continuous shell, hairline and individual swept locks. keep=[(p,r) for p,r in zip(actor.prims,actor.roles) if r!="hair"] actor.prims,actor.roles=map(list,zip(*keep)) actor.paint={k:dict(kind="steel" if k in METALS else "cloth",base=c) for k,c in COLOURS.items()} for k in ["skin","glove","boot"]: actor.paint[k]=COLOURS[k] actor.paint.update(gold=COLOURS["brass"],hair=COLOURS["inkhair"]) palette=dict(vp.PALETTE,**cast["colors"]) palette.update(A="#352729",r="#302822",s="#69796d",t="#d8bd7f") from portable import finish print(f"Fit, hair, coat and armour {time.perf_counter()-start:.2f}s",flush=True) t=time.perf_counter() export_glb.export_skinned(actor,palette,CACHE/"base.glb",max_tex=1024) print(f"Base GLB {time.perf_counter()-t:.2f}s",flush=True) t=time.perf_counter() keys=action(actor.v,shape) info=export_glb.scene_info(actor,palette) finish(actor,keys,info,COLOURS,METALS,CACHE) (CACHE/"camera.json").write_text(json.dumps({"characters":[{"name":"figure","info":info}]})) print(f"Animation, dye maps and packaging {time.perf_counter()-t:.2f}s",flush=True) print(f"Build total {time.perf_counter()-start:.2f}s",flush=True) if __name__=="__main__": build() PY cat > review/tide-keeper/dyes.py <<'PY' """Portable base-colour maps. The large map on the coat is an original contour drawing.""" import numpy as np from PIL import Image, ImageDraw, ImageColor def dye(name,base): w=h=768 canvas=Image.new("RGB",(w,h),base) d=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 PYresult, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"ec247e","wall_time_seconds":0.00000461,"exit_code":0,"original_token_count":0,"output":""}