A 3D model pipeline, pushed by GPT-6.2-Astra
agent (cont.)
+38:43exec_command, view_imagepython3 - <<'PY' (+1 more)
input
text((await tools.exec_command({cmd:`python3 - <<'PY' from PIL import Image p='review/out/tide-keeper/' im=Image.open(p+'lens.png');bg=Image.new('RGB',im.size,'#89998f');bg.paste(im,mask=im.getchannel('A'));bg.resize((800,568)).save(p+'facecheck.jpg') PY rg -n 'def (aim|arm_ik)|finger' tools/rig.py && cat review/high-water/figure.py | head -108 && cat review/out/tide-keeper/camera.json | cut -c1-1000`,max_output_tokens:1200})).output);image((await tools.view_image({path:"~/work/lowmarch/review/out/tide-keeper/facecheck.jpg"})).image_url)result, 92 lines
Script completed Wall time 0.2 seconds Output: Warning: truncated output (original token count: 1700) Total output lines: 121 92: def aim(self, pose, bone, local_dir, target_dir): 98: def arm_ik(self, pose, side, target, pole): 151:def grip_points(vrm, shape, ref_pose, fingers=("Index", "Middle", "Ring", "Little")): 152: """Where each fist closes: the centre of the hole the curled fingers make (poses.fist), in model 153: space in `ref_pose` (the hand doesn't move when the fingers curl, so a weapon built there and bound 154: to the hand sits in the fist whenever the fingers are curled). Each finger's joints and fingertip 156: hole (the hand's local z runs through it, palm to fingertips in x and y); the hole's centre is the 157: mean of the fingers' circle centres. A fixed offset from the wrist, tuned on one hand, missed on 158: larger or differently made hands (the shaft ran over the knuckles, the fingers closed under it). 159: Returns {side: dict(point, axis, radius)}: radius is the finger-centreline circle's (the shaft's 160: radius plus a finger's half-thickness fits).""" 173: for f in fingers: """Pose a cached armory body in the existing caster kit for the high-water study.""" import json import sys from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent ROOT = HERE.parents[1] CACHE = ROOT / "review/out/high-water" sys.path[:0] = [str(ROOT / "tools"), str(ROOT / "art/cast")] import cage from cast import CAST import export_glb import gear import mobs import outfit import poses import rig import vroid_portrait as vp from fitting import merge_surfaces, vertex_normals from plates import Canvas, flat_piece from vrm import VRM def hem_pattern(): """A woven border of alternating crests, each with a brass drop in its hollow.""" cloth = Canvas(1024, 384) for k in range(14): x = k / 14 crest = [(0, .078), (.21, .13), (.44, .21), (.63, .22), (.76, .186), (.62, .187), (.51, .162), (.52, .142), (.62, .131), (.78, .142), (1, .177), (1, .148), (.78, .112), (.56, .103), (.39, .117), (.29, .107), (0, .055)] cloth.poly([(x + u / 14, v) for u, v in crest], "paint") cloth.dot((x + .79 / 14, .184), 2.3, 2.3, "gold") for v in (.035, .046, .245): cloth.line([(0, v), (1, v)], 1.6, "gold") return cloth.array() def chart_bag(fit, skirt, belt): hips = fit.bone["J_Bip_C_Hips"] waist = hips[1] + .06 side = skirt["pos"…500 tokens truncated….mod(np.arctan2(pos[:, 0], -(pos[:, 2] - fit.bone["J_Bip_C_Hips"][2])), 2 * np.pi) t = skirt["plate"][:, 3] fall = (1 - t) ** 1.6 front = (1 + np.cos(angle)) / 2 fold = (.010 * np.cos(9 * angle + t) + .008 * np.sin(5 * angle - t)) * fall pos[:, 0] += np.sin(angle) * fold - .025 * fall pos[:, 2] += (.175 - .09 * front) * fall - np.cos(angle) * fold pos[:, 1] += (.12 + .16 * front + .024 * np.cos(5 * angle)) * fall skirt["uv"] = np.column_stack([angle / (2 * np.pi), t]) skirt["decal"] = hem_pattern() skirt["nrm"] = vertex_normals(pos, skirt["tri"]) skirt["role"] = "tidecoat" belt = next(p for p in pieces if p["material"] == "OUTFIT_sash") pieces.extend(chart_bag(fit, skirt, belt)) for p in pieces: if p["material"].startswith("OUTFIT_hat"): if p["material"] == "OUTFIT_hat": pos = p["pos"] tip = np.clip((pos[:, 1] - pos[:, 1].min()) / .32, 0, 1) pos[:, 2] += .20 * tip ** 2 pos[:, 1] -= .115 * tip ** 2 p["nrm"] = vertex_normals(pos, p["tri"]) if p["role"] == "signature": p["role"] = "tidecoat" body = next(p for p in pieces if p["material"] == "OUTFIT_robe") over = merge_surfaces((fit.pos, fit.tri), (body["pos"], body["tri"])) mantle, grid, hood = outfit.mantle(fit, "wrap", "scarf", over) {"characters": [{"name": "figure", "info": {"roles": {"face": {"mode": "bands", "bands": [[0.8, "#fff6d8"], [0.62, "#fbd99c"], [0.38, "#eca067"], [-9, "#b06e4b"]]}, "body": {"mode": "bands", "bands": [[0.8, "#fff6d8"], [0.62, "#fbd99c"], [0.38, "#eca067"], [-9, "#b06e4b"]], "cap": "#fbd99c"}, "shadow": {"mode": "flat", "color": "#eca067"}, "hair": {"mode": "bands", "bands": [[0.86, "#e8905a"], [0.66, "#c45a30"], [0.42, "#9a3a1e"], [-9, "#6a2414"]]}, "cloth": {"mode": "bands", "bands": [[0.85, "#a84848"], [0.6, "#7e2a30"], [0.35, "#5e2026"], [-9, "#3a1418"]]}, "line": {"mode": "flat", "color": "#2f1e3c"}, "brow": {"mode": "flat", "color": "#352729"}, "mouth": {"mode": "flat", "color": "#6e4247"}, "white": {"mode": "flat", "color": "#f4fbff"}, "highlight": {"mode": "flat", "color": "#f4fbff"}, "iris": {"mode": "iris", "colors": ["#302822", "#69796d", "#d8bd7f"], "cuts": [0.25, 0.5]}, "coat": {"mode": "bands", "bands": [[0.85, "#a84848"], [0.6, "#7e2a30"], [0.35, "#5e2026"], [-9, "#3a1418exec_commandsed -n '20,152p' tools/rig.py && rg -A41 'def make_pose' review/high-water/figure.py && rg -A25 'function rawTex|function applySkin' review/out/tide-keeper/index.html && rg -n 'uKind == [3456]|uEye|uFlat' review/out/tide-keeper/index.html | head -27 && cat review/tide-keeper/dyes.py | head -13 && rg -n 'def head_chart|class HeadChart|def lock' tools/hair.py
command
sed -n '20,152p' tools/rig.py && rg -A41 'def make_pose' review/high-water/figure.py && rg -A25 'function rawTex|function applySkin' review/out/tide-keeper/index.html && rg -n 'uKind == [3456]|uEye|uFlat' review/out/tide-keeper/index.html | head -27 && cat review/tide-keeper/dyes.py | head -13 && rg -n 'def head_chart|class HeadChart|def lock' tools/hair.py
result, 189 lines
Script completed Wall time 0.1 seconds Output: Warning: truncated output (original token count: 3422) Total output lines: 236 return 2 * np.outer(axis, axis) - np.eye(3) vx = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) return np.eye(3) + vx + vx @ vx / (1 + c) class Rig: def __init__(self, vrm, shape=None, ortho=False): """ortho: rotate bones through the parent's pure rotation (exact with scaled bones, see rotate_world). Off by default so clips authored before it (Aldric's, frozen) stay identical.""" import vroid_portrait as vp self.v = vrm self.shape = dict(vp.NEUTRAL, **(shape or {})) self.names = vrm.nodes_by_name() self._bp = vp.bone_pose self.ortho = ortho self._par = vrm.parents() def world(self, pose): return self.v.node_world(self._bp(self.v, self.shape, pose)) def pos(self, pose, bone): return self.world(pose)[self.names[bone]][:3, 3] def rotate_world(self, pose, bone, R): """Pre-multiply the bone's world rotation by R (about its joint) by editing its local pose. With proportion scales on the skeleton the bone's world matrix is not a rotation; the default (legacy) form then leaks shear into the pose and an iterated solve can diverge. ortho mode conjugates by the pure rotation of the frame the adjustment lives in.""" W = self.world(pose) i = self.names[bone] cur = W[i][:3, :3] adj_old = as4(pose.get(bone, np.eye(3))) if self.ortho: par = self._par.get(i) base = (W[par] if par is not None else np.eye(4)) @ self.v.local_matrix(i, None) u, _, vt = np.linalg.svd(base[:3, :3]) Q = u @ vt # nearest rotation out = dict(pose) a = adj_old.copy() a[:3, :3] = Q.T @ R @ Q @ adj_old[:3, :3] out[bone] = a return out base = cur @ np.linalg.inv(adj_old[:3, :3]) # world rotation without this bone's adjustment new_rot = np.linalg.inv(base) @ (R @ cur) out = dict(pose) a = adj_old.copy() a[:3, :3] = new_rot out[bone] = a return out def leg_ik(self, pose, side, target, pole=(0, 0, -1)): """Bend the leg so the ankle lands on `target`, knee toward `pole` (forward).""" up, lo, ft = f"J_Bip_{side}_UpperLeg", f"J_Bip_{side}_LowerLeg", f"J_Bip_{side}_Foot" H, K, A = self.pos(pose, up), self.pos(pose, lo), self.pos(pose, ft) l1, l2 = np.linalg.norm(K - H), np.linalg.norm(A - K) T = np.asarray(target, float) d = np.clip(np.linalg.norm(T - H), 1e-4, l1 + l2 - 1e-4) u = (T - H) / np.linalg.norm(T - H) w = np.asarray(pole, float) - u * np.dot(pole, u) w /= np.linalg.norm(w) ca = np.clip((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1) K2 = H + l1 * (ca * u + np.sqrt(1 - ca * ca) * w) pose = self.rotate_world(pose, up, rot_between(K - H, K2 - H)) K, A = self.pos(pose, lo), self.pos(pose, ft) return self.rotate_world(pose, lo, rot_between(A - K, H + u * d - K)) def plant_feet(self, pose, reference): """Keep both ankles where they are in `reference` (feet stay on the ground while the hips move).""" for side in "LR": pose = self.leg_ik(pose, side, self.pos(reference, f"J_Bip_{side}_Foot")) return pose def aim(self, pose, bone, local_dir, target_dir): """Turn `bone` so its local direction (e.g. the sword blade, hand -z) points along target_dir.""" W = self.world(pose)[self.names[bone]][:3, :3] cur = W @ np.asarray(local_dir, float) return self.rotate_world(pose, bone, rot_between(cur, target_dir)) def arm_ik(self, pose, side, target, pole): """Bend the arm so the wrist lands on `target`, elbow toward `pole`.""" up, lo, hd = f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_Hand" S, E, W = self.pos(pose, up), self.pos(pose, lo), self.pos(pose, hd) l1, l2 = np.linalg.norm(E - S), np.linalg.norm(W - E) T = np.asarray(target, float) d = np.clip(np.linalg.norm(T - S), abs(l1 - l2) + 1e-3, l1 + l2 - 1e-4) u = (T - S) / np.linalg.norm(T - S) w = np.asarray(pole, float) - u * np.dot(pole, u) w /= np.linalg.norm(w) ca = np.clip((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1) E2 = S + l1 * (ca * u + np.sqrt(1 - ca * ca) * w) pose = self.rotate_world(pose, up, rot_between(E - S, E2 - S)) E, W = self.pos(pose, lo), self.pos(pose, hd) return self.rotate_world(pose, lo, rot_between(W - E, S + u * d - E)) def held(self, pose, bone, ref_pose, point): """Where a point attached to `bone` (given in the reference pose, model space) is in `pose`.""" i = self.names[bone] M = self.world(pose)[i] @ np.linalg.inv(self.world(ref_pose)[i]) return M[:3, :3] @ np.asarray(point, float) + M[:3, 3] def grip(self, pose, side, ref_pose, fist_ref, fist_target, blade_dir, pole, local_blade=(0, 0, -1), iters=14): """Put the fist (a point on the hand, from the reference pose) on …822 tokens truncated…ding staff separate silhouettes. return skeleton.grip(pose, "R", ref, hand, shoulder + [-.080, -.245, -.54], [-.16, 1, .035], [.95, -.65, .4]) def main(): CACHE.mkdir(parents=True, exist_ok=True) name = "arm_f_strong" cast = CAST[name] path = cage.path_for(name, cast["cage"]) model = VRM(path) shape = dict(vp.NEUTRAL, **cast["shape"]) pose = make_pose(model, shape) actor = vp.Portrait(path, shape=shape, pose=pose, costume=costume, morphs={"Fcl_EYE_Angry": .15, "Fcl_MTH_Fun": .12}) actor.paint = dict(signature="#ad5239", tidecoat="#34575b", scarf="#a23e2f", doublet="#393c49", hair="#ead4aa", skin="#e4b48e", boot="#514343", gaiter="#826548", glove="#553e39", wood=dict(kind="leather", base="#65503d"), gold="#c3985c", heraldry="#e2bd85", motif="#ccbf95") palette = dict(vp.PALETTE, **cast["colors"]) function applySkin(meshes) { // the picked tone on every skin material (face, body, shadow cards); the built tone is kept to go back to const tone = state.skin && PAGE && PAGE.skins ? PAGE.skins.find(s => s.name === state.skin) : null; for (const o of meshes) { const m = o.userData.mats && o.userData.mats.painted, u = m && m.uniforms; if (!u || !u.uSkinRamp || u.uKind.value !== 1) continue; if (!o.userData.builtSkin) o.userData.builtSkin = [u.uSkinRamp.value, u.uSkinL.value.clone(), u.uSkinS.value.clone(), u.uSkinC.value.clone()]; if (tone) { u.uSkinRamp.value = 1; u.uSkinL.value.copy(hex(tone.ramp[0])); u.uSkinS.value.copy(hex(tone.ramp[1])); u.uSkinC.value.copy(hex(tone.ramp[2])); } else { const b = o.userData.builtSkin; u.uSkinRamp.value = b[0]; u.uSkinL.value.copy(b[1]); u.uSkinS.value.copy(b[2]); u.uSkinC.value.copy(b[3]); } } } function render() { const meshes = allMeshes(), cs = active(); applySkin(meshes); const cloths = cs.flatMap(c => c.cloths); if (state.mode === "3d") { meshes.forEach(o => o.material = o.userData.mat3d); cloths.forEach(c => c.lines3d.visible = trimsShown(c)); sun.position.copy(camera.position).add(new THREE.Vector3(-3, 4, 0)); sun.target.position.copy(ctl.target); sun.target.updateMatrixWorld(); R.setRenderTarget(null); R.setClearColor(0x191626, 1); R.clear(); R.render(scene, camera); R.setClearColor(0x000000, 0); return; } const buf = R.getDrawingBufferSize(new THREE.Vector2()); targetsFor(buf.x, buf.y); cloths.forEach(c => c.lines3d.visible = false); meshes.forEach(o => { o.material = o.userData.mats.painted; o.material.uniforms.uPass.value = 0; }); 319: uniform float uFlattice; uniform float uFlChin; uniform float uFlFall; uniform vec3 uFlPivot; 324: if (uFlattice > 0.0) { // Flattice: squash toward the pivot's plane, along pivot-to-camera 327: mv.xyz -= u * dot(mv.xyz - uFlPivot, u) * w * uFlattice; 351: uniform int uPass; uniform vec4 uInfo; uniform vec3 uEye[3]; uniform vec3 uFlat; uniform vec3 uSkinRef; 438: if (uKind == 0 || uKind == 5 || uKind == 6) { // cloth, leather, ground 441: float sh = uKind == 5 ? 0.93 : (cool ? 0.70 : 0.96); 445: float l = lit + (g1 - 0.5) * uGrain - (uKind == 6 ? 0.22 : 0.0); // ground: a flat top sits at the base colour 447: if (uKind == 5) col *= 0.965 + 0.07 * vnoise(vObj * 22.0); // mottled leather 473: } else if (uKind == 3 || uKind == 4) { // steel, gold 476: bool gilt = uKind == 4 || (plate && w > 0.0 && e < w); // an outline plate's gold border 477: col = metal(gilt, gilt && uKind == 3 ? uGold : uBase, n, v, lit, plate ? vPlate.w : -1.0); 486: col = l < 0.3 ? mix(uEye[0], uEye[1], l / 0.3) : mix(uEye[1], uEye[2], clamp((l - 0.3) / 0.6, 0.0, 1.0)); 493: else { col = uFlat; } 872: uFlattice: { value: 0 }, uFlChin: { value: 0 }, uFlFall: { value: 0.05 }, uFlPivot: { value: new THREE.Vector3() }, 874: uEye: { value: V.roles.iris.colors.map(hex) }, uFlat: { value: new THREE.Color() }, uSkinRef: { value: new THREE.Vector3(0.965, 0.878, 0.80) }, 896: else if (role === "white" || role === "highlight") { u.uKind.value = map ? 8 : 9; if (map) u.uAlpha.value = 1; u.uFlat.value = hex(Rl.color || "#ffffff"); } 897: else if (!P && Rl.mode === "flat") { u.uKind.value = 9; u.uFlat.value = hex(Rl.color); if (map) u.uAlpha.value = role === "line" ? 2 : 1; } 1552: if (!mu || !mu.uFlattice) continue; 1553: mu.uFlattice.value = tile.flat || 0; """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 22:class HeadChart(_Chart): 91:def lock(name, chart, path, width, thick=0.006, n=28, seg=10, taper=(0.45, 1.0), tip=0.04, flat_to=None, 162:def head_chart(fit, ear_x=None):exec_commandrg -n 'outputColorSpace|toneMapping|HemisphereLight|DirectionalLight' review/out/tide-keeper/index.html; rg -n 'Fcl_|eye_.*(tilt|slant)|brow' tools/vroid_portrait.py | head -45
command
rg -n 'outputColorSpace|toneMapping|HemisphereLight|DirectionalLight' review/out/tide-keeper/index.html; rg -n 'Fcl_|eye_.*(tilt|slant)|brow' tools/vroid_portrait.py | head -45 PYTHONPATH=tools python3 - <<'PY' from vrm import VRM from pathlib import Path from PIL import Image import numpy as np p=Path('review/out/tide-keeper');m=VRM(p/'ione.glb'); j=m.j print('mesh/material/joints',len(j['meshes']),len(j['materials']),len(j['skins'][0]['joints'])) for n in j['nodes']: if n.get('extras',{}).get('role') not in ('iris','face','body','line','highlight'):continue q=j['meshes'][n['mesh']]['primitives'][0]; role=n['extras']['role']; mat=j['materials'][q['material']]['pbrMetallicRoughness']; print(n['name'],mat) if 'baseColorTexture' not in mat:continue im=Image.fromarray(m.image(j['textures'][mat['baseColorTexture']['index']]['source'])) if role in ('iris','face'): im.thumbnail((350,350));im.save(p/(role+'.png')) uv=m.accessor(q['attributes']['TEXCOORD_0']);print(uv.min(0),uv.max(0)) PYresult, 38 lines
Script completed Wall time 0.5 seconds Output: Warning: truncated output (original token count: 928) Total output lines: 37 303:const hemi = new THREE.HemisphereLight(0xfff6ee, 0x3a3450, 1.35); 304:const sun = new THREE.DirectionalLight(0xffffff, 1.6); 629:R.outputColorSpace = THREE.LinearSRGBColorSpace; 4:palette tones (skin/hair/cloth bands from normals; eyes, brows, lashes from alpha-tested masks) 39: ("FaceEyeline", "line"), ("FaceEyelash", "line"), ("FaceMouthLine", "line"), ("FaceBrow", "brow"), ("FaceMouth", "mouth"), 161:# 3. resting expression: VRoid's own shapes (hooded eyes, stern brows) held at a low weight 164: face_len=0.0, jaw=0.0, chin_w=0.0, chin_len=0.0, cheek=0.0, brow_ridge=0.0, 166: eye=1.0, eye_tilt=0.0, iris=1.0, lash=1.0, mouth=1.0, arm_out=0.0, age_lines=0.0, blush=1.0, curl=0.0, 170:SCULPT_ROLES = ("face", "body", "mouth", "brow", "line", "white", "iris", "highlight", "hair") 341: move("ridge" + sd, np.array([0, -0.0015, -0.004]) * sh["brow_ridge"]) 397: instead of patches that jump as the head turns. The face, its brows, lines and mouth and the skull take it in 417: if r in ("face", "brow", "line", "mouth"): 459: both = sum(mo.get(k, 0.0) for k in ("Fcl_EYE_Close", "Fcl_EYE_Joy", "Fcl_ALL_Joy")) 460: return {s_: both + sum(mo.get(f"Fcl_EYE_{k}{s_}", 0.0) for k in ("Close_", "Joy_", "Close@", "Joy@")) 474: out[f"Fcl_EYE_Close@{side}"] = out.get(f"Fcl_EYE_Close@{side}", 0.0) + f * shut 477: for k in ("Fcl_EYE_Iris_Hide", "Fcl_EYE_Highlight_Hide"): 529: furthest. P_now: the eyeline as the expression has it; P_unit: fully closed by Fcl_EYE_Close; P_open: neutral.""" 679: (from the nose'…128 tokens truncated… self.v.primitives(dict(eyes, Fcl_EYE_Close=1.0), pose)[ln[0]]] 1040: if self.roles[k] in ("line", "brow", "iris", "highlight", "white", "hair", "mouth"): 1137: if k in self.tex and self.roles[k] in ("line", "brow", "iris", "highlight", "white", "hair", "mouth")} 1208: elif r == "brow": 1369: "line": hexrgb("o"), "brow": hexrgb("B"), "mouth": hexrgb("2"), "white": hexrgb("w"), mesh/material/joints 250 250 59 N00_000_00_EyeIris_00_EYE (Instance)_60 {'metallicFactor': 0.0, 'roughnessFactor': 0.9, 'baseColorTexture': {'index': 9}, 'baseColorFactor': [1, 1, 1, 1]} [0.120198 0.2504233] [0.879802 0.7737576] N00_000_00_EyeHighlight_00_EYE (Instance)_61 {'metallicFactor': 0.0, 'roughnessFactor': 0.9, 'baseColorTexture': {'index': 2}} N00_000_00_Face_00_SKIN (Instance)_62 {'metallicFactor': 0.0, 'roughnessFactor': 0.9, 'baseColorTexture': {'index': 10}, 'baseColorFactor': [1, 1, 1, 1]} [0.00436002 0.00750262] [0.99564 0.993477] N00_000_00_FaceEyelash_00_FACE (Instance)_65 {'metallicFactor': 0.0, 'roughnessFactor': 0.9, 'baseColorTexture': {'index': 6}, 'baseColorFactor': [0.0595112381629812, 0.0295568344378088, 0.043735029256973465, 1]} N00_000_00_FaceEyeline_00_FACE (Instance)_66 {'metallicFactor': 0.0, 'roughnessFactor': 0.9, 'baseColorTexture': {'index': 7}, 'baseColorFactor': [0.0595112381629812, 0.0295568344378088, 0.043735029256973465, 1]} N00_000_00_Body_00_SKIN (Instance)_67 {'metallicFactor': 0.0, 'roughnessFactor': 0.9, 'baseColorFactor': [0.6866853124353135, 0.3762621229909065, 0.21223075741405523, 1]}view_image~/work/lowmarch/review/out/tide-keeper/${n}.png
input
for(const n of ["iris","face"]) image((await tools.view_image({path:"~/work/lowmarch/review/out/tide-keeper/${n}.png"})).image_url)result, 4 lines
Script completed Wall time 0.0 seconds Output:
exec_commandrg -A74 'class TorsoChart' tools/plates.py && rg -n 'def _base' tools/mobs.py && sed -n '479,496p;863,899p' review/out/tide-keeper/index.html && head -42 review/tide-keeper/portable.py && rg -A19 'def make_pose' review/high-water/figure.py
command
rg -A74 'class TorsoChart' tools/plates.py && rg -n 'def _base' tools/mobs.py && sed -n '479,496p;863,899p' review/out/tide-keeper/index.html && head -42 review/tide-keeper/portable.py && rg -A19 'def make_pose' review/high-water/figure.py
result, 147 lines
Script completed Wall time 0.1 seconds Output: Warning: truncated output (original token count: 2817) Total output lines: 193 class TorsoChart(_Chart): """u = degrees round the vertical axis through (cx, cz) (0 = front, -z; +90 = the character's right, +x), v = height in metres. `over`: the Surface the plates sit on.""" def __init__(self, over, y0, y1, cx=0.0, cz=0.0, du=3.0, dv=0.01, smooth=(1.5, 1.2), shell=True, rmax=0.4): self.cx, self.cz, self.wrap = cx, cz, True self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, y0, dv, dv * 0.5 us = np.arange(-180.0, 180.0, du) vs = np.arange(y0, y1 + dv * 0.5, dv) R = np.full((len(us), len(vs)), np.nan) for i, u in enumerate(us): d = np.array([math.sin(math.radians(u)), 0.0, -math.cos(math.radians(u))]) for j, v in enumerate(vs): R[i, j] = over.cast(np.array([cx, v, cz]), d, rmax=rmax, far=True) self._setup(R, smooth, shell, True) def ray(self, u, v): u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) ur = np.radians(u) d = np.stack([np.sin(ur), np.zeros_like(ur), -np.cos(ur)], -1) o = np.stack([np.full_like(u, self.cx), v, np.full_like(u, self.cz)], -1) return o, d def metric(self, u, v): """(arc length round the body, height) in metres: distances along the surface for trim.""" return np.stack([np.radians(u) * self.radius(u, v), np.asarray(v, float) + 0 * np.asarray(u, float)], -1) def centre(self, v): return np.array([self.cx, v, self.cz]) class ConeChart(TorsoChart): """A TorsoChart whose radius is a function r(u, v) instead of ray casts: a skirt's cone, a plate standing off a skirt. r_fn takes and returns arrays.""" def __init__(self, r_fn, cx=0.0, cz=0.0, ev=0.005): self.cx, self.cz, self.r_fn, self.ev, self.wrap = cx, cz, r_fn, ev, True def radius(self, u, v): u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) return np.asarray(self.r_fn(u, v), float) + 0 * u class LimbChart(_Chart): """u = degrees round the bone from a to b (0 = toward `front`, +90 = toward front x axis, i.e. the right-handed turn about the bone), v = fraction along it (0 at a, 1 at b; -0.2..1.2 covered).""" def __init__(self, over, a, b, front=(0, 0, -1), du=6.0, dv=0.025, smooth=(1.2, 1.2), shell=True, rmax=0.14, v_range=(-0.2, 1.2)): self.a, self.b = np.asarray(a, float), np.asarray(b, float) ax = self.b - self.a self.L = float(np.linalg.norm(ax)) self.ax = ax / self.L f = np.asarray(front, float) - self.ax * (np.asarray(front, float) @ self.ax) self.f = f / np.linalg.norm(f) self.s = np.cross(self.ax, self.f) self.wrap = True self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, v_range[0], dv, dv * 0.5 us = np.arange(-180.0, 180.0, du) vs = np.arange(v_range[0], v_range[1] + dv * 0.5, dv) R = np.full((len(us), len(vs)), np.nan) for i, u in enumerate(us): ur = math.radians(u) d = self.f * math.cos(ur) + self.s * math.sin(ur) for j, v in enumerate(vs): R[i, j] = over.cast(self.a + self.ax * self.L * v, d, rmax=rmax, far=True) self._setup(R, smooth, shell, True) def ray(self, u, v): u, v = np.broadcast_arrays(np.asarray(u, …1137 tokens truncated…r / 0.973, c.g / 0.882, c.b / 0.835); } if (role === "face" && map) u.uFaceTex.value = 1; if (role === "hair" && map) u.uAlpha.value = 1; if (role === "iris") { u.uKind.value = 7; u.uAlpha.value = 1; } else if (role === "white" || role === "highlight") { u.uKind.value = map ? 8 : 9; if (map) u.uAlpha.value = 1; u.uFlat.value = hex(Rl.color || "#ffffff"); } else if (!P && Rl.mode === "flat") { u.uKind.value = 9; u.uFlat.value = hex(Rl.color); if (map) u.uAlpha.value = role === "line" ? 2 : 1; } if (role === "brow") u.uLift.value = BROW_LIFT; if (role === "mouth" && map) u.uKind.value = 10; """Complete the Lowmarch skinned export with portable PBR, cloth morphs and pose keys.""" import io import json import struct import numpy as np from PIL import Image, ImageColor import export_glb as glb import vroid_portrait as vp from vrm import VRM from dyes import dye,face_map def linear(col): a=np.array(ImageColor.getrgb(col))/255 return np.where(a<=.04045,a/12.92,((a+.055)/1.055)**2.4).tolist() def finish(actor,keys,info,colours,metals,directory): base=VRM(directory/"base.glb"); doc=base.j; data=bytearray(base.bin) def view(blob,target=None): data.extend(b"\0"*((-len(data))%4)); off=len(data); data.extend(blob) v=dict(buffer=0,byteOffset=off,byteLength=len(blob)) if target: v["target"]=target doc["bufferViews"].append(v) return len(doc["bufferViews"])-1 def accessor(a,kind,target=None): a=np.ascontiguousarray(a,dtype=np.float32) v=view(a.tobytes(),target); flat=a.reshape(len(a),-1) doc["accessors"].append(dict(bufferView=v,componentType=5126,count=len(a),type=kind, min=flat.min(0).tolist(),max=flat.max(0).tolist())) return len(doc["accessors"])-1 textures={} def texture(key,fn): if key not in textures: im=fn() b=io.BytesIO(); im.save(b,"PNG",optimize=False) doc["images"].append(dict(bufferView=view(b.getvalue()),mimeType="image/png",name=key)) doc["textures"].append(dict(source=len(doc["images"])-1,sampler=0)) textures[key]=len(doc["textures"])-1 return {"index":textures[key]} def original(pbr): def make_pose(model, shape): ref = vp.BUST_POSE skeleton = rig.Rig(model, shape, ortho=True) pose = poses.merge(poses.BATTLE_IDLE, { "J_Bip_C_Hips": poses.move(dy=-.043), "J_Bip_C_Spine": poses.rot((1, 0, 0), -12), "J_Bip_C_Head": poses.rot((0, 1, 0), -32) @ poses.rot((1, 0, 0), 5), "J_Bip_L_UpperArm": poses.rot((0, 1, 0), 25), "J_Bip_L_LowerArm": poses.rot((0, 1, 0), -16), }) for side, dz in (("L", -.17), ("R", .135)): foot = skeleton.pos(ref, f"J_Bip_{side}_Foot") pose = skeleton.leg_ik(pose, side, foot + [0, .015 if side == "R" else 0, dz]) # Catch the brim with the far hand. The elbow opens to the side so the # glove and the bent sleeve separate from her face in three-quarter view. head = skeleton.pos(pose, "J_Bip_C_Head") pose = skeleton.arm_ik(pose, "L", head + [-.203, .027, -.080], [-.95, -.35, .15]) pose = skeleton.aim(pose, "J_Bip_L_Hand", [-1, 0, 0], [.54, .66, -.13]) hand = rig.grip_points(model, shape, ref)["R"]["point"] shoulder = skeleton.pos(pose, "J_Bip_R_UpperArm")exec_commandPYTHONPATH=tools:art/cast python3 - <<'PY'
command
PYTHONPATH=tools:art/cast python3 - <<'PY' from cast import CAST import cage,vroid_portrait as vp,rig from vrm import VRM v=VRM(cage.path_for("arm_f_strong",CAST["arm_f_strong"]["cage"])) r=rig.Rig(v);import numpy as np for p in [{},vp.BUST_POSE]: for n in ('Head','Neck','Hips','L_Hand','L_Index1','L_Middle1','L_Little1','L_Thumb1'): name='J_Bip_'+('C_' if '_' not in n else '')+n print(n,r.pos(p,name).round(3)) PY rg -n 'MOUTH|BUST_POSE|eye_tilt' tools/vroid_portrait.py | head -12 && rg -A16 'def flat_piece' tools/plates.py && cat review/out/tide-keeper/render.logresult, 48 lines
Script completed Wall time 0.7 seconds Output: Head [-0. 1.638 -0.044] Neck [-0. 1.578 -0.002] Hips [ 0. 1.012 -0.024] L_Hand [-0.73 1.496 -0.026] L_Index1 [-0.81 1.505 -0.05 ] L_Middle1 [-0.811 1.505 -0.029] L_Little1 [-0.805 1.505 0.01 ] L_Thumb1 [-0.734 1.484 -0.046] Head [-0. 1.638 -0.044] Neck [-0. 1.578 -0.002] Hips [ 0. 1.012 -0.024] L_Hand [-0.273 0.922 -0.026] L_Index1 [-0.299 0.845 -0.05 ] L_Middle1 [-0.299 0.844 -0.029] L_Little1 [-0.298 0.85 0.01 ] L_Thumb1 [-0.262 0.915 -0.046] 92:from poses import rot, BUST as BUST_POSE, BATTLE_IDLE # noqa: E402,F401 166: eye=1.0, eye_tilt=0.0, iris=1.0, lash=1.0, mouth=1.0, arm_out=0.0, age_lines=0.0, blush=1.0, curl=0.0, 809:MOUTH_ROOM = 0.002 # m: an open mouth's inside stays this far within the face's lower outline 838: """A recipe's mouth shapes (Fcl_MTH_*, together) scaled down until the mouth's inside stays MOUTH_ROOM within the 842: if not keys or mouth_room(v, mo, pose) >= MOUTH_ROOM: 848: lo, hi = (mid, hi) if mouth_room(v, scaled(mid), pose) >= MOUTH_ROOM else (lo, mid) 878: if r in ("iris", "white", "highlight", "line") and (sh["eye"] != 1 or sh["eye_tilt"]): 883: q[:, 1] += sh["eye_tilt"] * np.sign(c[0]) * q[:, 0] * 0.4 906: def __init__(self, path, morphs=None, pose=BUST_POSE, shape=None, hair_from=None, costume=None, 907: mouth="curve", world=None, ref_pose=BUST_POSE, hair_trim=None): def flat_piece(name, role, outline, origin, ex, ey, thickness=0.002, decal=(), px=4000): """A flat convex shape (outline: (x, y) points in metres, in order) on the plane origin + x ex + y ey, given thickness along ex x ey, with an optional decal in the same (x, y) coordinates.""" from outfit import piece O, ex, ey = (np.asarray(a, float) for a in (origin, ex, ey)) nz = np.cross(ex, ey) nz /= np.linalg.norm(nz) P2 = np.asarray(outline, float) c2 = P2.mean(0) m = len(P2) lo, hi = P2.min(0), P2.max(0) span = np.maximum(hi - lo, 1e-6) pts = np.vstack([c2, P2]) top = O + pts[:, :1] * ex + pts[:, 1:] * ey + nz * thickness / 2 bot = top - nz * thickness k = np.arange(m) fan = 1 + _ear_clip(P2) # any simple outline, concave too (an axe's crescent) staff contact [ 735.095052943677, 719.6584947449164 ]exec_commandpython3 - <<'PY'
command
python3 - <<'PY' from pathlib import Path p=Path('review/tide-keeper/build.py');s=p.read_text();a=s.index(' pose=r.arm_ik');b=s.index(' keys=[]',a) s=s[:a]+''' head_frame=r.world(pose)[r.names["J_Bip_C_Head"]][:3,:3] axes=np.linalg.svd(head_frame) head_frame=axes[0]@axes[2] hand="J_Bip_L_Hand" pose=r.arm_ik(pose,"L",head+head_frame@[-.148,.135,-.108],[-.95,-.24,.12]) # Lay the palm level above the sight line. Both the fingers' direction # and their spread matter here, otherwise the thumb drops over the eye. W=r.world(pose)[r.names[hand]][:3,:3] U,_,V=np.linalg.svd(W) destination=[redacted: email]((0,1,0),165)@poses.rot((1,0,0),-10)@poses.rot((0,0,1),6) pose=r.rotate_world(pose,hand,destination@(U@V).T) for k,finger in enumerate(("Index","Middle","Ring","Little")): for i,curl in enumerate((3,5,7),1): pose[f"J_Bip_L_{finger}{i}"]=poses.rot((0,0,1),curl+.9*k) '''+s[b:] s=s.replace('jaw=.62,nose=.75,chin_w=.37,eye=.97,iris=.96','jaw=.76,nose=1.04,brow_ridge=.65,chin_w=.50,eye=.96,eye_tilt=.23,iris=.97').replace('"Fcl_EYE_Angry":.16','"Fcl_EYE_Angry":.24') p.write_text(s) p=Path('review/tide-keeper/coiffure.py');s=p.read_text().replace(' blade("forelock_"+str(i),role,[(root,22,.022),(root*.48,43,.029),((root+end)*.52,58,.026),\n (end,low,.011)],w,.011)',''' lift=.009 if role=="silk" else 0 blade("forelock_"+str(i),role,[(root,22,.022+lift),(root*.48,43,.029+lift),((root+end)*.52,58,.026+lift), (end,low,.011+lift*.5)],w,.011)''');p.write_text(s) p=Path('review/tide-keeper/tailoring.py');s=p.read_text().replace('at(-1.19)','at(-1.224)').replace('(.151-.008*j)','(.142-.008*j)') s=s.replace(' if j==0:\n out.append(pipe', ''' if j==0: # The fluted crown is pressed from a single shell blank. Five # narrow raised flutes open like a fan towards the lower lip. for index in [5,13,21,35,43,50]: ridge=grid[index,3:-2].copy() cross=ridge-cap ridge+=.0015*cross/np.linalg.norm(cross,axis=1)[:,None] out.append(pipe(fit,"pressed_flute","seasteel",ridge,.0018,upper)) if index in [13,35,50]: out.append(bead(fit,"flute_foot","brass",ridge[-1],.004,upper)) out.append(pipe''') a=s.index(' centre=chart.point(78') s=s[:a]+''' # A neckerchief tucked under a stamped brass clasp makes the neckline # legible from the front, with one long folded point hanging off centre. u=np.linspace(0,1,27)[:,None]; t=np.linspace(0,1,19)[None,:] angle=-39+84*u ytop=nk[1]-.031-.026*np.sin(np.pi*u) drop=.030+.099*np.maximum(0,1-np.abs(u-.41)*2.4) g=chart.point(angle,ytop-drop*t,.038+.008*np.cos(4*np.pi*u+.6*t)*t) pcs+=layered_sheet(fit,"kerchief_point","vermilion","poppy",g,torso,nk,"weft",hem=False) pcs.append(pipe(fit,"kerchief_selvedge","poppy",g[:,-1],.0027,torso)) eye=chart.point(-12,nk[1]-.114,.055) ex=np.array([.98,0,-.20]); ey=np.array([0,1.,0]); normal=np.cross(ey,ex) outer=ring(fit,"surveyor_clasp","brass",eye,ex,ey,.027,.033,.0042,CHEST) pcs.append(outer) for off in [-.016,.016]: pcs.append(rod(fit,"clasp_cross","brass",eye-.019*ex+off*ey,eye+.019*ex+off*ey,.0022,.0022,CHEST,8)) clasp=flat_piece("clasp_needle","glaze",[(0,-.022),(.010,-.004),(0,.025),(-.010,.004)],eye+normal*.002,ex,ey,thickness=.004) pcs.append(attach(fit,clasp,CHEST)) '''+s[a:] p.write_text(s) PY rg -A8 'def rot\(' tools/poses.py rg -A11 'def point\(' tools/plates.py | head -13result, 25 lines
Script completed Wall time 0.2 seconds Output: def rot(axis, deg): a = math.radians(deg) c, s = math.cos(a), math.sin(a) x, y, z = np.asarray(axis, float) / np.linalg.norm(axis) return np.array([[c + x * x * (1 - c), x * y * (1 - c) - z * s, x * z * (1 - c) + y * s], [y * x * (1 - c) + z * s, c + y * y * (1 - c), y * z * (1 - c) - x * s], [z * x * (1 - c) - y * s, z * y * (1 - c) + x * s, c + z * z * (1 - c)]]) def point(self, u, v, off=0.0): o, d = self.ray(u, v) return o + d * (self.radius(u, v) + off)[..., None] def normal(self, u, v, eu=1.0, ev=None): """The chart surface's outward normal (finite differences of point()).""" ev = self.ev if ev is None else ev pu = self.point(np.asarray(u) + eu, v) - self.point(np.asarray(u) - eu, v) pv = self.point(u, np.asarray(v) + ev) - self.point(u, np.asarray(v) - ev) n = np.cross(pv, pu) _, d = self.ray(u, v) n = np.where((np.einsum("...i,...i->...", n, d) < 0)[..., None], -n, n)exec_commandrg -A14 'def _base' tools/mobs.py; sed -n '480,494p;622,629p' review/out/tide-keeper/index.html; sed -n '65,110p' review/tide-keeper/coiffure.py; rg -A4 'def _trs' tools/export_glb.py; cat .gitignore; date -u
command
rg -A14 'def _base' tools/mobs.py; sed -n '480,494p;622,629p' review/out/tide-keeper/index.html; sed -n '65,110p' review/tide-keeper/coiffure.py; rg -A4 'def _trs' tools/export_glb.py; cat .gitignore; date -u
result, 66 lines
Script completed Wall time 0.1 seconds Output: Warning: truncated output (original token count: 967) Total output lines: 73 def _base(fit, shirt="padding", legs="cloth", boots="boot", gloves="glove", knee=None, shirt_subdiv=0, boot_top=None): """Under layers every class shares: a shirt with sleeves to the wrist, trousers, boots to below the knee (or to boot_top: above the knee, they take the thigh too), gloves. Returns the pieces and the shirt (what coats are fitted over).""" B = fit.bone nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"] knee = B["J_Bip_L_LowerLeg"][1] if knee is None else knee def cuff(side): a, h = B[f"J_Bip_{side}_LowerArm"], B[f"J_Bip_{side}_Hand"] n = (h - a) / np.linalg.norm(h - a) return n, n @ (h - n * 0.02) torso = ("Spine", "Chest", "UpperChest", "Bust", "Shoulder", "UpperArm", "LowerArm", "Neck", "Hips") # the neckline: a straight hem, lower at the throat than at the back of the neck (a level cut of # whole triangles left a saw-tooth edge, and a big trapezius showed above it) float l1 = 1.0 - smoothstep(0.0010, 0.0010 + aa, abs(e - (w + 0.0050))); float l2 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - w)); col = mix(col, col * 0.42, max(l1, l2 * 0.8)); } } else if (uKind == 7) { // iris float l = dot(tex.rgb, vec3(1.0 / 3.0)); col = l < 0.3 ? mix(uEye[0], uEye[1], l / 0.3) : mix(uEye[1], uEye[2], clamp((l - 0.3) / 0.6, 0.0, 1.0)); } else if (uKind == 8) { col = tex.rgb; } else if (uKind == 10) { …217 tokens truncated…= THREE.LinearSRGBColorSpace; 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 def _trs(m): t = m[:3, 3].copy() sc = np.linalg.norm(m[:3, :3], axis=0) return t, _quat(m[:3, :3] / sc), sc # Study references (third-party art) never live in this repo; see docs/study.md refs/ study/ __pycache__/ *.pyc review/out/ Tue Nov 17 23:25:25 UTC 2026exec_commandrg -A54 'def sabaton' tools/outfit.py; rg -A11 'def piece' tools/outfit.py; rg -n 'primitives|class VRM|image\(' tools/vrm.py | head -12
command
rg -A54 'def sabaton' tools/outfit.py; rg -A11 'def piece' tools/outfit.py; rg -n 'primitives|class VRM|image\(' tools/vrm.py | head -12result, 73 lines
Script completed Wall time 0.1 seconds Output: Warning: truncated output (original token count: 1017) Total output lines: 74 def sabaton(fit, name, side, role="metal", pad=0.010, ridges=3, seg=26, rows=14): """A steel shoe over the whole foot (hides the base model's toes), built as a shoe last from the foot's measurements: sole outline rounded at heel and toe and widest at the ball, top rising from a rounded toe over the instep to the ankle at the heel. Lame ridges follow its cross-section over the instep. Rides the foot bone. (A squashed ellipsoid read as a triangular hoof; a shell projected onto the foot's convex hull creased on the hull's facets.)""" w = fit.weight((f"{side}_Foot", f"{side}_ToeBase")) P = fit.pos[w > 0.5] P = P[(P[:, 0] < 0.01) if side == "L" else (P[:, 0] > -0.01)] lo, hi = P.min(0), P.max(0) sole = lo[1] - 0.003 ankle = fit.bone[f"J_Bip_{side}_Foot"][1] z_heel, z_toe = hi[2] + pad, lo[2] - pad # the foot points -z width = (hi[0] - lo[0]) + 2 * pad S = np.linspace(0, 1, seg) # centreline: the foot's middle at each station, smoothed cx = np.array([np.median(P[np.abs(P[:, 2] - (z_heel + t * (z_toe - z_heel))) < 0.02, 0]) if (np.abs(P[:, 2] - (z_heel + t * (z_toe - z_heel))) < 0.02).any() else (lo[0] + hi[0]) / 2 for t in S]) cx = np.convolve(np.pad(cx, 3, mode="edge"), np.ones(7) / 7, "valid") ends = np.sin(np.pi * np.clip(S, 0, 1)) ** 0.42 # rounds the heel and the toe half_w = width / 2 * ends * (0.80 + 0.20 * np.sin(np.pi * np.clip(S * 1.2, 0, 1))) # widest at the ball tall = (ankle + 0.02 - sole) * (1 - 0.62 * np.clip((S - 0.25) / 0.6, 0, 1) ** 0.8) # ankle at the heel, low toe tall = np.maximum(tall * np.sin(np.pi * np.clip(S, 0, 1)) ** 0.22, 0.004) phi = np.linspace(0, np.pi, rows) G = np.zeros((seg, rows, 3)) for …117 tokens truncated…nd(t * (seg - 1))) ring = G[i, 1:-1] + np.stack([np.cos(phi[1:-1]), np.sin(phi[1:-1]) * 1.0, np.zeros(rows - 2)], 1) * 0.0018 out.append(pipe(f"{name}_ridge{k}", role, ring, r=0.0024)) for q_ in out: fit.bind(q_, rigid=f"J_Bip_{side}_Foot") return out def knight_dress(fit): """A blonde knight-princess: a long blue dress with a white petticoat edge, a fitted steel breastplate, small spaulders, steel gauntlets and armoured boots, a two-handed sword with a gold hilt, and her hair up in a braided bun with a ribbon.""" B = fit.bone nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"] knee = B["J_Bip_L_LowerLeg"][1] out = [] def grouped(pcs, g): for pc in pcs: if pc is not None: pc["group"] = g def piece(name, role, pos, tri, nrm=None, outward_from=None, axis=None): """outward_from: a point (or, with axis, a line) the normals should face away from, so the renderer knows which side is the outside of a one-sided sheet.""" pos = np.asarray(pos, float) tri = np.asarray(tri) nrm = vertex_normals(pos, tri) if nrm is None else nrm if outward_from is not None: d = pos - np.asarray(outward_from, float) if axis is not None: a = np.asarray(axis, float) / np.linalg.norm(axis) d -= np.outer(d @ a, a) if (np.einsum("ij,ij->i", nrm, d) < 0).mean() > 0.5: 19:class VRM: 52: def image(self, i): 65: return self.image(self.j["textures"][t["index"]]["source"]) 146: def primitives(self, morphs=None, pose=None): 155: mesh["primitives"][0].get("extras", {}).get("targetNames") or [] 156: for pr in mesh["primitives"]: 191: mesh["primitives"][0].get("extras", {}).get("targetNames")exec_commandrg -A39 'def sabaton' tools/outfit.py | tail -10; sed -n '36,60p' tools/vrm.py; sed -n '875,890p' review/out/tide-keeper/index.html
command
rg -A39 'def sabaton' tools/outfit.py | tail -10; sed -n '36,60p' tools/vrm.py; sed -n '875,890p' review/out/tide-keeper/index.html
result, 34 lines
Script completed Wall time 0.1 seconds Output: Warning: truncated output (original token count: 846) Total output lines: 51 c = np.array([(lo[0] + hi[0]) / 2, sole, (z_heel + z_toe) / 2]) pc = piece(name, role, pos, tri, outward_from=c - [0, 0.05, 0]) out = [pc] for k, t in enumerate(np.linspace(0.50, 0.74, ridges)): # lames over the instep i = int(round(t * (seg - 1))) ring = G[i, 1:-1] + np.stack([np.cos(phi[1:-1]), np.sin(phi[1:-1]) * 1.0, np.zeros(rows - 2)], 1) * 0.0018 out.append(pipe(f"{name}_ridge{k}", role, ring, r=0.0024)) for q_ in out: fit.bind(q_, rigid=f"J_Bip_{side}_Foot") return out n = a["count"] if "bufferView" not in a: return np.zeros((n, nc), np.float32) bv = self.j["bufferViews"][a["bufferView"]] start = bv.get("byteOffset", 0) + a.get("byteOffset", 0) size = np.dtype(dt).itemsize stride = bv.get("byteStride", size * nc) if stride == size * nc: …396 tokens truncated…ue: hex((V.paint && V.paint.motif && V.paint.motif.base) || "#3a44a0") }, uLift: { value: 0 } }; if (P) { u.uKind.value = KIND[P.kind] ?? 0; if (P.base) u.uBase.value = hex(P.base); if (P.grain != null) u.uGrain.value = P.grain; } else if (Rl.bands) { u.uKind.value = Rl.world ? 6 : 0; u.uBase.value = hex(Rl.bands[Math.min(1, Rl.bands.length - 1)][1]); } if (P && P.kind === "world") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.12; } if (P && P.shade) u.uShadeOnly.value = 1; // shadow cards: skin, always in its shade tone if (P && P.kind === "skin" && P.ramp) { // a designed ramp: lit, shade, deep shade u.uSkinRamp.value = 1; u.uSkinL.value = hex(P.ramp[0]); u.uSkinS.value = hex(P.ramp[1]); u.uSkinC.value = hex(P.ramp[2]); } if (P && P.kind === "skin" && P.base) { // skin tone: the base colour against the default light skinexec_commandPYTHONPATH=tools python3 - <<'PY'
command
PYTHONPATH=tools python3 - <<'PY' from vrm import VRM m=VRM('review/out/tide-keeper/ione.glb').j print(m['scenes'],m['nodes'][0].get('name'),m['skins'][0]['skeleton']) print([m['nodes'][i]['name'] for i in m['skins'][0]['joints'] if 'Bip' not in m['nodes'][i]['name']]) print(m['materials'][67].keys()) PY rg -A36 'def sabaton' tools/outfit.py | tail -12result, 19 lines
Script completed Wall time 0.5 seconds Output: [{'nodes': [309]}] Root 0 ['Root', 'J_Sec_L_Bust1', 'J_Sec_L_Bust2', 'J_Sec_R_Bust1', 'J_Sec_R_Bust2', 'J_Adj_L_FaceEye', 'J_Adj_R_FaceEye'] dict_keys(['name', 'doubleSided', 'pbrMetallicRoughness']) G = np.zeros((seg, rows, 3)) for i, t in enumerate(S): z = z_heel + t * (z_toe - z_heel) G[i] = np.stack([cx[i] + half_w[i] * np.cos(phi), sole + tall[i] * np.sin(phi), np.full(rows, z)], 1) pos, tri = grid_mesh(G) c = np.array([(lo[0] + hi[0]) / 2, sole, (z_heel + z_toe) / 2]) pc = piece(name, role, pos, tri, outward_from=c - [0, 0.05, 0]) out = [pc] for k, t in enumerate(np.linspace(0.50, 0.74, ridges)): # lames over the instep i = int(round(t * (seg - 1))) ring = G[i, 1:-1] + np.stack([np.cos(phi[1:-1]), np.sin(phi[1:-1]) * 1.0, np.zeros(rows - 2)], 1) * 0.0018 out.append(pipe(f"{name}_ridge{k}", role, ring, r=0.0024))exec_commandPYTHONPATH=tools python3 - <<'PY'
command
PYTHONPATH=tools python3 - <<'PY' from vrm import VRM from collections import Counter j=VRM('review/out/tide-keeper/ione.glb').j print(Counter(n.get('extras',{}).get('group') for n in j['nodes'])) print(j['materials'][75]) PYresult, 6 lines
Script completed Wall time 0.2 seconds Output: Counter({'costume': 187, None: 60, 'hair': 39, 'body': 10, 'trim': 7, 'belt': 3, 'doublet': 1, 'trousers': 1, 'boots': 1, 'gloves': 1}) {'name': 'trim:deepsea', 'doubleSided': True, 'pbrMetallicRoughness': {'metallicFactor': 0.0, 'roughnessFactor': 0.78, 'baseColorFactor': [0.016807375752887384, 0.04970656598412723, 0.06480326669290577, 1]}}exec_commandsed -n '470,485p' tools/export_glb.py; rg -A27 '^def piece\(' tools/outfit.py; rg -A22 'def bind\(' tools/fitting.py; rg -A20 'def group_of' tools/export_glb.py && sed -n '55,70p' tools/vrm.py
command
sed -n '470,485p' tools/export_glb.py; rg -A27 '^def piece\(' tools/outfit.py; rg -A22 'def bind\(' tools/fitting.py; rg -A20 'def group_of' tools/export_glb.py && sed -n '55,70p' tools/vrm.pyresult, 62 lines
Script completed Wall time 0.1 seconds Output: Warning: truncated output (original token count: 972) Total output lines: 81 pos = (p["pos"][usedv] * FLIP).astype(np.float32) nrm = p["nrm"][usedv] * FLIP nrm = (nrm / np.maximum(np.linalg.norm(nrm, axis=1, keepdims=True), 1e-9)).astype(np.float32) remap = np.array([jidx.get(n, jidx.get("J_Bip_C_Head")) for n in p["jnames"]]) J = remap[p["J"][usedv]].astype(np.uint16) W = p["W"][usedv].astype(np.float32) W /= np.maximum(W.sum(1, keepdims=True), 1e-9) attrs = dict(POSITION=add_acc(pos, "VEC3", 5126, 34962), NORMAL=add_acc(nrm, "VEC3", 5126, 34962), JOINTS_0=add_acc(J, "VEC4", 5123, 34962), WEIGHTS_0=add_acc(W, "VEC4", 5126, 34962)) if "plate" in p: # outline plates (tools/plates.py): border, engraving, gradient attrs["_PLATE"] = add_acc(np.asarray(p["plate"])[usedv].astype(np.float32), "VEC4", 5126, 34962) mat = dict(name=f"{group_of(p, role)}:{role}", doubleSided=True, pbrMetallicRoughness=dict(metallicFactor=0.0, roughnessFactor=0.9)) tone = ROLE_TONE.get(role) extra = getattr(portrait, "paint", None) or {} color = hex_rgb(palette[tone]) if tone in palette else \ def piece(name, role, pos, tri, nrm=None, outward_from=None, axis=None): """outward_from: a point (or, with axis, a line) the normals should face away from, so the …292 tokens truncated… if p.get("world"): return "terrain" if p.get("group"): return p["group"] if role in ("face", "body", "shadow", "iris", "white", "highlight", "line", "brow", "mouth"): return "body" if role == "hair": return "hair" name = p["material"].replace("OUTFIT_", "") for key in ("trim", "edge", "hem", "placket", "buckle", "clasp"): if key in name: return "trim" for key in ("pauldron", "cape", "collar", "tunic", "tails", "belt", "trousers", "boots", "gloves"): if name.startswith(key): return key if name in ("blade", "guard", "grip", "pommel", "fuller"): return "sword" return "costume" bv = self.j["bufferViews"][im["bufferView"]] data = self.bin[bv.get("byteOffset", 0):bv.get("byteOffset", 0) + bv["byteLength"]] self._img[i] = np.asarray(Image.open(io.BytesIO(data)).convert("RGBA")) return self._img[i] def material_texture(self, mi): m = self.j["materials"][mi] t = m.get("pbrMetallicRoughness", {}).get("baseColorTexture") if t is None: return None return self.image(self.j["textures"][t["index"]]["source"]) def material_cutout(self, mi): m = self.j["materials"][mi] return m.get("alphaMode", "OPAQUE") in ("MASK", "BLEND")


