An AI agent skill that turns any subject into a 3D film or app
Add arm audit and human arm helper, update frame-guard, looks and self-review notes; release 0.4.4
Nguyen Xuan An868e325282f3
diff --git a/plugins/visualize-in-3d/.claude-plugin/plugin.json b/plugins/visualize-in-3d/.claude-plugin/plugin.jsonindex 5380d88..afcc41f 100644--- a/plugins/visualize-in-3d/.claude-plugin/plugin.json+++ b/plugins/visualize-in-3d/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "visualize-in-3d",- "version": "0.4.3",+ "version": "0.4.4","description": "Turn hard-to-picture places, systems, objects and events into a 3D world you can watch, learn from or click through: a live three.js app with a dashboard, a lesson app, a documentary film, or an illustrated cutaway book, built from real layouts and models made from real references.","author": {"name": "CodePawl",diff --git a/plugins/visualize-in-3d/skills/visualize-in-3d/references/looks.md b/plugins/visualize-in-3d/skills/visualize-in-3d/references/looks.mdindex f0e18ef..8e04481 100644--- a/plugins/visualize-in-3d/skills/visualize-in-3d/references/looks.md+++ b/plugins/visualize-in-3d/skills/visualize-in-3d/references/looks.md@@ -75,7 +75,9 @@ frames, music or text). Fits a case file or a piece of history: a crime, a disapthe street. A public domain period map (USGS historical topo, an old city plan) traced or shaded dark works.- 3D reconstructions: dark low-poly rooms and buildings lit by a few warm windows and one red light pool where thecrime happened (the red light stands in for violence: never blood, bodies or wounds). People are flat solid- silhouettes: white for the victim or witness in focus, blue for police, translucent grey for others.+ silhouettes: white for the victim or witness in focus, blue for police, translucent grey for others. Unlit one-colour+ material on a rigged base mesh works, with a flat tapered tube from chest to below the hips so the bare waist and hips do+ not read as a naked muscled body, and the head held up when bending so the outline keeps a head.- Labels: small boxed captions in spaced caps with thin leader lines (`PC THOMAS BARRETT`, `SUSPECT`), red dots atthe anchor; a thin red timeline across the top with times and events (`04:45 BODY IS FOUND`), a note that timesare approximate.@@ -267,9 +269,28 @@ reference app (a chip fab with a roof cut away, three.js with react-three-fiber)- Film: a virtual clock and real clicks on units and list rows, ending on the world (see `film.md`).- Traps: a second accent colour, a dark theme, camera too low (loses the cutaway), KPI numbers that do not move.+## White model documentary++A case told as an architect's model: studied from LEMMiNO's documentaries and built for a full film.++- Every lit set is pale matte grey with light edges (`EdgesGeometry` at 35 degrees on low-vertex meshes), one soft shadowed+ sun aimed per set plus a hemisphere light, and the frame's corners falling to dark. Practical lights stay as weak accents.+- Convert in one pass after assets load. Change materials in place: beats hold references and fade them. Scanned wood and+ carpet lose their maps, paper with information keeps them. Keep the bloom threshold near 0.9.+- Colour only for what is being told: screens, warning lights, the person the scene is about (flat red). One object the+ story names as black stays black with pale edges, which makes it the subject of every wide shot.+- People are flat unlit cut-outs with outlines that read: charcoal on pale sets, never white-grey. They cast shadows.+- A white box reads as empty, so build what the real place has: floor joints, skirting, pilasters, trusses, frames on walls.+ Rooms need a fourth wall facing inward only, so cameras outside it still see in. Hide what hangs above a high camera.+- 2D material sits on a charcoal card with a torn glowing white border: mono text between two rules, quote marks, source,+ date, citation number. A quote read aloud gets its own acting voice with a narrowed band, not the narrator's.+- Traps: exposure blowing the floors white, mapped surfaces staying dark, fades that lose their references when materials are+ replaced instead of changed, a light multiplier applied every frame to a value set only once.+## Choosing-Clean ops world is the default for a system that runs (an operation with units, tasks and flows). Toy isometric (a+A case that needs its action and places clearly seen can go white model documentary; dark documentary suits a case that lives on+what stays hidden. Clean ops world is the default for a system that runs (an operation with units, tasks and flows). Toy isometric (amore playful diorama on a slab, stronger colour) stays as an alternative when the user asks for it or the subject islight-hearted. A showcase film always uses dither + ASCII with the modelrendered clean. The point-cloud look can read as dull on a busy site, so use it whendiff --git a/plugins/visualize-in-3d/skills/visualize-in-3d/references/self-review.md b/plugins/visualize-in-3d/skills/visualize-in-3d/references/self-review.mdindex 2d46bdc..d7968d0 100644--- a/plugins/visualize-in-3d/skills/visualize-in-3d/references/self-review.md+++ b/plugins/visualize-in-3d/skills/visualize-in-3d/references/self-review.md@@ -30,6 +30,9 @@ Reading map: read "Every film" always, then only the groups that match what youRead always.+- A refine or remake of a film is shown before it stands next to the old film, frame against frame at the same moments. Better parts do not count if the whole film reads worse (An, 2026-10-30: "sao nó tệ hơn trước vậy").+- "More realistic" came out as dirt: blotchy tiled ground filling the frame, stains on the skin, grey gloom, over-reflective glass. Realism comes from shape, clean light and soft shadows; keep the stage calm and bright unless the subject asks otherwise.+- The camera hides what the step is about: a lowered flap seen from above and ahead sits behind the wing and only its track fairings show, as spikes. Film a moving part from the side where it moves into view.- The subject the viewer follows leaves the frame or shrinks under about 40 pixels tall.- An effect or a panel covers that subject for more than 0.3 s.- A colour, material or texture breaks for a few frames (a flat tint, a missing texture, z-fighting flicker).@@ -43,6 +46,10 @@ Read always.- A colour cast added by the encode grade: compare one raw render frame with the same frame of the encoded film. Run`eq` and `vignette` on YUV and the blend on gbrp. An `eq` on gbrp frames before a screen blend turned a whole filmpurple.+- A beat that renders empty or wrong only when the render runs into it from the beat before. The cause is state+ (opacity, visibility, near plane) set inside one beat's branch and never reset: a vanished cabinet stayed invisible+ through the next shot. Reset such state on every frame. After any partial re-render, sheet the whole film at 1 fps+ before sending, not just the spans you changed.- A result card or toasts over the last beat of a film that should end on the world itself. End on the simulationunless the plan asks for a card.@@ -132,10 +139,36 @@ Anything that walks, crawls, drives or is simulated.- Flying units that pass low over signs and stations and cover them (same day). Rise vertically, cruise above thetallest object, and descend vertically into an open spot. Paint station names on the floor like the belt labelsinstead of on floating sign cards, and keep landing spots off that text.+- A figure that glitches while it reaches (An, 2026-10-30: "con người nó cứ bị glitch"). A solver that answers each frame on its+ own can land on another pose in the next frame. Bake its answers, hold and smooth them, play them back by time, and fail the+ render on travel per frame (above about 12 cm for the pelvis or 22 cm for a hand at 30 fps). Also smooth facing across a path's corners.+- A hand that floats near what it holds (An, 2026-10-30: "k cầm vào cái cạnh tủ mà lại lơ lửng"). Every hold, pull or+ turn gets a socket on the prop, a contact on the hand, two-bone IK and a registered grip: `registerGrip` / `measureGrips`+ in `scripts/frame-guard.js` fail the render above 1 cm. Then look at the shot: an arm that cannot reach makes the body lunge.+ Measure the torso against the prop per frame too: every grip passed while the reach solver walked a chest 17 cm into a cabinet. Use the+ hand on the prop's side, and read a solver's largest reach: a value at its cap means it failed. A held prop rides the hand (`carryProp` in+ `scripts/human-arm.js`); only rails or a slot may lead it until it clears them. Hold things upright in the fist, palm on the long side.+- A hand that touches but is bent like no hand can bend (An, 2026-10-30: "hướng tay cầm bị dị dạng ... giới hạn tay chân, cách cầm+ thoải mái theo khớp gân"): the grip took its whole rotation from the prop, wrist at 149 degrees, and the palm axis had been+ written backwards. `scripts/human-arm.js`: read the palm axis off the finger bones (where they curl, where the thumb sits) and never+ assume it. A socket says only what the contact fixes (palm normal on a face, thumb side along an edge); the hand takes the rest+ from the forearm and is clamped to the comfortable range. `keepArmInRange` is the last stop on every posed arm, stock clips too.+ Fail the render on the anatomical range: elbow 0-145, pronation 80, supination 85, wrist flexion 80, extension 70, radial 20,+ ulnar 30. `scripts/arm-audit.mjs` lists every fault in a film without capturing. Look at each grip with a lit close camera,+ because a black figure hides this. Ask what holds the prop up: a palm on one side of a box holds nothing, so wrap an edge, or+ put fingers behind and the thumb in front. And which side of a door or panel the body is on before choosing push or pull.+- Props that collide by keyframe (a book shutting through its cover). Bake a rigid-body sim in Blender and play the+ transforms back by time, with a per-frame gap probe; the film stays in three.js.- Units that stand still while idle or working (An, 2026-10-29, Factory: "lúc nó idle hay làm việc thì nó k có tươngtác gì, nhìn nó bị nhạt"). Give each role its own readable work loop with the station's prop (typing, page turns,scanning with a magnifier), idle fidgets out of sync (bounce, look around, turn to a neighbour), and a small payoffwhen a task ends. Moving units also leave a path trail, flights included.+- A seated character offset from the seat: Blocky passengers sat 0.26 m back, their torsos inside the seatback (An,+ 2026-10-30, "người ngồi trong cabin đang bị lệch so với vị trí ghế"). Measure the seated body against the cushion and+ the backrest's front face, not the seat's bounding box, which includes the seatback and tray.+- A recline that turns the whole part: rotating the whole seat about the floor tipped it forward (An, same day, "sao tự+ nhiên ghế đẩy ra trước"). Split the moving piece (the backrest out of a one-mesh seat, by triangle position) and+ hinge it where it meets the fixed part; check the hinge angle's sign on a still.- A soft chain built from dozens of tiny rigid physics links: it is unstable (in Unreal Chaos, links of about 2 cm exploded on the first tick and force-driven chains flew apart). Drive the motion kinematically and use physics only for contact.### Vehicles, roads and terrain@@ -145,6 +178,12 @@ Built places, traffic, ground.- A town or site with no streets: houses and cars standing on grass because the layout had lots but no road graph.Every built place gets its circulation first (roads with curbs, sidewalks and lane paint, driveways, yard paths),and every vehicle drives on it.+- A vehicle that could not do what the story asks: a quadcopter docking with an airliner at cruise (An, 2026-10-30:+ "nó bay k kịp so với tốc độ máy bay này"). Check speed, range and size against the real class before modelling;+ a 900 km/h rendezvous needs a fixed-wing drone that matches speed and a capture rig.+- A vehicle that pops between cuts: the drone rose straight out of the bay across a cut (An, same day, "0:14 drone+ nó bị glitch"). Drive arrivals and departures on one continuous clock across the cut, and let a departing vehicle+ leave the frame fully before the next shot.- Vehicles that ignore the ground and the road: a car keeps its flat height and yaw on a hill, so it sinks into theslope going up and floats going down, or points off the lane. Sample the ground under the front and rear axles everyframe, set height and pitch from them (and roll from both sides), yaw from the lane tangent, wheels spinning with@@ -160,6 +199,37 @@ Built places, traffic, ground.Rain, water, beams.+- A beat about weather with no weather in the sky: a reroute card said "storm cell ahead" over clear clouds (An,+ 2026-10-30, "storm mà sao trong environment lại k có hiện bất kỳ storm nào"). Put the hazard on screen where the+ camera looks (a cumulonimbus tower with lightning lit from inside), and move it in frame as the vehicle avoids it.+- An avoidance where the obstacle moves instead of the vehicle: the storm slid aside while the plane held still in+ frame and the clouds stood still (An, 2026-10-30, "sao né bão mà bão lại tự né nhỉ"). Fix the obstacle in world+ space, turn and bank the vehicle against a camera that does not turn with it, and keep the ground or clouds+ scrolling so speed reads. Place the obstacle so it passes beside the vehicle inside the shot: r6 left the cell 13 km+ ahead on the turn side, so it barely moved in 4 s and the plane still looked headed into it ("chưa thấy né").+- An object that appears with no visible mechanism: a dinner rose out of a console with no hatch or lift (An, same+ day, "đồ ăn từ đâu hiện ra từ dưới lên"). Show the opening, the platform and the moving part before the object.+- A hand-off nobody sees: the meal vanished from the lift and reappeared on the robot, hidden under its head (An,+ 2026-10-30, "con robot phải lấy rồi mới đưa đồ ăn cầm theo"). Show the reach, the object moving across, and the+ carrier holding it in view on the way; frame the hand-off side-on or from above, not behind the carrier.+- A part that overhangs its housing: a lift hatch ran 9 cm past the console's end, so the sinking tray clipped the+ console face, and a lamp floated off the end (An, same day, "đồ ăn nó bị dính vào tường"). Check every opening+ and fixture against its housing's box.+- A cover under the body: a duvet thinner than the sleeper and set at mattress height sat inside her (An, same day,+ "cái mền đắp sao lại ở dưới thân"). Measure the body's top and put covers over it.+- A device that moves into a face: a tablet arm swung to the reader's head (An, same day). Reach to the hands or+ lap, and put controls where the person can reach them (the reading light in the seatback ahead, tapped on).+- An ending that cuts on the climax: the film stopped 3 s after touchdown (An, 2026-10-30, "khúc cuối hơi cục, để cho nó+ đáp một đoạn nữa rồi hết vid"). Let the action finish and settle (rollout to a stop, a held beat), then the end title,+ placed where it does not cover the subject.+- A beat moved in the cut keeps its old lighting: check a re-cut shot against the clock and time of day around it, and+ sample between lightning flashes as well as on them, since a flash hides a storm that is invisible the rest of the time.+- A feature shown as one on/off moment: the seat device only toggled a lamp (An, 2026-10-30, "nên hiện scene tương tác được,+ hiển thị sự tiện lợi và tân tiến"). Show the control itself in use, with its values changing and the real thing answering.+- A camera inside a character: seats this close put an over-the-shoulder camera inside the head. Go first person and hide the head.+- An AI action people would not expect for the moment: for a sleeper the "air off her face" vent read as odd, and+ a body tilted against its reclining seat looked pushed up (An, same day, "t tưởng đắp gì lên mắt"). Pick the+ action a real passenger knows (an eye mask, the seat, the shade, the light) and keep the body moving with the seat.- Falling water drawn as opaque white sprites or a row of identical streaks. At phone size it reads as foam clumps ora barcode. Draw clear falling water as a thin, mostly transparent sheet that catches light on its edges.It turns white only where it breaks, and its width varies.diff --git a/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/arm-audit.mjs b/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/arm-audit.mjsnew file mode 100644index 0000000..52b3d14--- /dev/null+++ b/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/arm-audit.mjs@@ -0,0 +1,77 @@+// Walks the whole film without capturing a picture and lists where a visible arm passes what a human arm can do.+// node tools/arm_audit.mjs [fromStorySeconds] [toStorySeconds] [framesPerSecond] (needs the dev server on 5441)+// Same measure as the render's arm limit check in tools/film.mjs, but it finds every fault instead of stopping at the first.+import { chromium } from 'playwright'+++const STORY_MINUS_OUTPUT = 5+const fromStory = Number(process.argv[2] ?? 18)+const toStory = Number(process.argv[3] ?? 269.2)+const framesPerSecond = Number(process.argv[4] ?? 6)++function virtualClock() {+ let now = 0+ window.filmMode = true+ let nextId = 1+ const callbacks = new Map()+ window.requestAnimationFrame = (callback) => {+ const id = nextId+++ callbacks.set(id, callback)+ return id+ }+ window.cancelAnimationFrame = (id) => callbacks.delete(id)+ performance.now = () => now+ window.advanceVirtualFrame = (milliseconds) => {+ now += milliseconds+ const due = [...callbacks.values()]+ callbacks.clear()+ due.forEach((callback) => callback(now))+ }+}++const browser = await chromium.launch({ headless: true, args: ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist'] })+const page = await browser.newPage({ viewport: { width: 320, height: 180 } })+await page.addInitScript(virtualClock)+await page.goto('http://localhost:5441/film.html', { timeout: 120000 })+await page.waitForSelector('canvas')+const advance = (milliseconds) => page.evaluate((amount) => window.advanceVirtualFrame(amount), milliseconds)+for (let attempt = 0; attempt < 600 && !(await page.evaluate(() => window.film?.ready)); attempt++) {+ await advance(33)+ await page.waitForTimeout(40)+}++const runs = []+const worst = new Map()+const openRuns = new Map()+const seen = new Set()+await page.evaluate((at) => window.film.start(at), fromStory - STORY_MINUS_OUTPUT - 1 / framesPerSecond)+for (let frame = 0; frame < (toStory - fromStory) * framesPerSecond; frame++) {+ await advance(1000 / framesPerSecond)+ const story = fromStory + frame / framesPerSecond+ const arms = await page.evaluate(() => window.measureArms())+ Object.keys(arms.largest).forEach((key) => seen.add(key.split(' ')[0]))+ const now = new Set(arms.faults.map((fault) => fault.key))+ for (const fault of arms.faults) {+ if (!openRuns.has(fault.key)) openRuns.set(fault.key, { key: fault.key, from: story, over: 0 })+ const run = openRuns.get(fault.key)+ run.to = story+ run.over = Math.max(run.over, fault.over)+ worst.set(fault.key, Math.max(worst.get(fault.key) ?? 0, fault.over))+ }+ for (const [key, run] of openRuns) {+ if (!now.has(key)) {+ runs.push(run)+ openRuns.delete(key)+ }+ }+}+runs.push(...openRuns.values())+await browser.close()+console.log('mannequins seen:', [...seen].join(', '))+const clock = (story) => {+ const output = Math.max(0, story - STORY_MINUS_OUTPUT)+ return Math.floor(output / 60) + ':' + (output % 60).toFixed(1).padStart(4, '0')+}+runs.sort((first, second) => first.from - second.from)+for (const run of runs) console.log(clock(run.from) + '-' + clock(run.to), run.key.padEnd(26), '+' + run.over.toFixed(0) + ' deg')+console.log(runs.length === 0 ? 'no arm past its limit' : runs.length + ' runs past a limit')diff --git a/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/frame-guard.js b/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/frame-guard.jsindex 9cb3f68..dc4a226 100644--- a/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/frame-guard.js+++ b/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/frame-guard.js@@ -203,3 +203,41 @@ export function measureContacts(pairs, { minimumGap = 0.0002, penetrationToleranreturn { name, ok: faults.length === 0, lowestGap, vertexCount, faults };});}++// Grip guard (registerGrip / measureGrips): a hand that holds, pulls or turns something must TOUCH it. A hand animated to be+// "near" a prop reads as floating, so every hand-on-object moment registers a grip and the render fails when they separate.+// 1. Put a named socket (an Object3D) on the prop, in the prop's own space (a panel's edge, a lever's tip). It moves with the prop.+// 2. Put a contact Object3D on the hand bone (the palm or finger crook that should touch the socket).+// 3. Once, at build time: registerGrip({ name: 'panel-edge', hand: handBone, contact, socket, from: 126.5, to: 127.1 }).+// from/to are the seconds in which the hand is fully on the prop, not the approach or the release.+// 4. Each frame, after two-bone IK has put contact on socket: const results = measureGrips(time). Fail the render when any+// result has ok false (distance in metres, GRIP_LIMIT = 1 cm). Each result is { name, distance, active, ok }.+// The prop's motion stays time-driven and the arm follows it. When the arm cannot reach, the body turns, leans and steps; look at+// that move in the shot, since a lunge across a low camera blacks out the frame. A push near the hinge needs less reach than the edge.+const registeredGrips = [];+export const GRIP_LIMIT = 0.01;++export function registerGrip({ name, hand, contact, socket, from, to }) {+ const existing = registeredGrips.findIndex((grip) => grip.name === name);+ if (existing >= 0) {+ registeredGrips.splice(existing, 1);+ }+ registeredGrips.push({ name, hand, contact, socket, from, to });+}++const gripContactPoint = new THREE.Vector3();+const gripSocketPoint = new THREE.Vector3();++export function measureGrips(time, { limit = GRIP_LIMIT } = {}) {+ return registeredGrips.map((grip) => {+ if (time < grip.from || time > grip.to) {+ return { name: grip.name, distance: null, active: false, ok: true };+ }+ grip.contact.updateWorldMatrix(true, false);+ grip.socket.updateWorldMatrix(true, false);+ grip.contact.getWorldPosition(gripContactPoint);+ grip.socket.getWorldPosition(gripSocketPoint);+ const distance = gripContactPoint.distanceTo(gripSocketPoint);+ return { name: grip.name, distance, active: true, ok: distance <= limit };+ });+}diff --git a/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/human-arm.js b/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/human-arm.jsnew file mode 100644index 0000000..8e4123e--- /dev/null+++ b/plugins/visualize-in-3d/skills/visualize-in-3d/scripts/human-arm.js@@ -0,0 +1,282 @@+// What a human arm can do, for any mannequin with upperarm_/lowerarm_/hand_ bones (Quaternius, UE-style).+// A hand on a prop used to take its whole rotation from the prop, whatever that did to the wrist: the man held the cartridge with+// the wrist bent 149 degrees and sideways 130. Here a grip says only what the contact fixes (the+// palm's normal on a flat face, the thumb-side axis along an edge) and the hand takes the rest from the forearm, then the result is+// clamped into the comfortable range. tools/film.mjs fails a render when any visible arm passes the anatomical range.+// Angles come from the bone positions and the hand's axes only, so they measure what the viewer sees, not how a bone happens to roll.+import * as THREE from 'three'++// Degrees. Anatomical range: standard goniometry reference values (elbow 0-145; forearm pronation 80, supination 85; wrist flexion+// 80, extension 70, radial 20, ulnar 30). Comfort: functional wrist motion is about 40 each way (Palmer 1985, Ryu 1991), and a held+// grip keeps inside that; a push may extend further, which `GRIP_COMFORT` allows.+export const ARM_LIMITS = { elbowFlexion: 145, pronation: 80, supination: 85, wristFlexion: 80, wristExtension: 70, radial: 20, ulnar: 30 }+export const GRIP_COMFORT = { pronation: 70, supination: 75, wristFlexion: 40, wristExtension: 55, radial: 12, ulnar: 22 }+// With the elbow nearly straight the forearm's rotation cannot be told from the shoulder's, so it is neither clamped nor checked.+const ELBOW_BENT_ENOUGH = { from: 10, to: 30 }++const DEGREES = 180 / Math.PI+const vector = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z)+const smooth = (value) => {+ const clamped = Math.min(1, Math.max(0, value))+ return clamped * clamped * (3 - 2 * clamped)+}++// Hand bone axes, measured from the finger bones of this rig: fingers along local +y, the index side +z on both hands, and the palm+// (where the fingers curl and the thumb sits) local -x on the right hand and +x on the left.+export const palmLocal = (side) => vector(side === 'r' ? -1 : 1, 0, 0)+const FINGERS_LOCAL = vector(0, 1, 0)+const INDEX_LOCAL = vector(0, 0, 1)++// The hand's world rotation for a palm direction and a finger direction (made perpendicular to the palm).+export function handFromPalm(side, palm, fingers) {+ const palmUnit = palm.clone().normalize()+ const fingersUnit = fingers.clone().addScaledVector(palmUnit, -fingers.dot(palmUnit)).normalize()+ const index = palmUnit.clone().cross(fingersUnit)+ if (side === 'r') index.negate()+ const localX = side === 'r' ? palmUnit.clone().negate() : palmUnit+ return new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(localX, fingersUnit, index))+}++// The hand's world rotation for an edge it wraps: the index side along `edge`, the fingers (made perpendicular to it) across.+export function handFromEdge(side, edge, fingers) {+ const edgeUnit = edge.clone().normalize()+ const fingersUnit = fingers.clone().addScaledVector(edgeUnit, -fingers.dot(edgeUnit)).normalize()+ const palm = side === 'r' ? edgeUnit.clone().cross(fingersUnit) : fingersUnit.clone().cross(edgeUnit)+ return handFromPalm(side, palm, fingersUnit)+}++// Puts a held prop on the hand, so it goes wherever the arm goes: run it after the arm is posed, every frame. `socket` is a child of+// the prop with userData.grip { palm or edge, fingers } in the prop's axes and `contact` a child of the hand bone at the grip point.+// `weight` below 1 leaves part of the pose to whatever else moves the prop, such as the rails it slides out of.+export function carryProp(prop, socket, side, contact, weight = 1) {+ const { palm, edge, fingers } = socket.userData.grip+ const handInProp = palm ? handFromPalm(side, palm, fingers) : handFromEdge(side, edge, fingers)+ const propWorld = contact.getWorldQuaternion(new THREE.Quaternion()).multiply(handInProp.invert())+ const propWorldPosition = contact.getWorldPosition(vector()).sub(socket.position.clone().applyQuaternion(propWorld))+ const parentWorld = prop.parent.getWorldQuaternion(new THREE.Quaternion())+ prop.quaternion.slerp(parentWorld.invert().multiply(propWorld), weight)+ prop.position.lerp(prop.parent.worldToLocal(propWorldPosition), weight)+ prop.updateWorldMatrix(true, true)+}++// Shoulder, elbow and wrist of one arm, and the forearm's rotation: 0 is a handshake (palm toward the body's middle), positive turns+// the palm toward the upper arm's far side (pronation, palm down with the elbow at a right angle).+function armGeometry(bones, side) {+ const shoulder = bones['upperarm_' + side].getWorldPosition(vector())+ const elbow = bones['lowerarm_' + side].getWorldPosition(vector())+ const wrist = bones['hand_' + side].getWorldPosition(vector())+ return { upper: elbow.clone().sub(shoulder).normalize(), forearm: wrist.clone().sub(elbow).normalize() }+}++function forearmRotation(side, upper, forearm, palm) {+ const hinge = upper.clone().cross(forearm).normalize()+ const towardMiddle = side === 'r' ? hinge.negate() : hinge+ const palmFlat = palm.clone().addScaledVector(forearm, -palm.dot(forearm)).normalize()+ const upperFlat = upper.clone().addScaledVector(forearm, -upper.dot(forearm)).normalize()+ return Math.atan2(palmFlat.dot(upperFlat), palmFlat.dot(towardMiddle))+}++function wristAngles(forearm, palm, fingers, index) {+ const along = forearm.dot(fingers)+ return { flexion: Math.atan2(-forearm.dot(palm), along), radial: Math.atan2(-forearm.dot(index), along) }+}++export function armAngles(bones, side) {+ bones['hand_' + side].updateWorldMatrix(true, false)+ const { upper, forearm } = armGeometry(bones, side)+ const rotation = bones['hand_' + side].getWorldQuaternion(new THREE.Quaternion())+ const palm = palmLocal(side).applyQuaternion(rotation)+ const fingers = FINGERS_LOCAL.clone().applyQuaternion(rotation)+ const index = INDEX_LOCAL.clone().applyQuaternion(rotation)+ const wrist = wristAngles(forearm, palm, fingers, index)+ const elbowFlexion = Math.acos(Math.min(1, Math.max(-1, upper.dot(forearm)))) * DEGREES+ return {+ elbowFlexion,+ rotation: elbowFlexion > ELBOW_BENT_ENOUGH.to ? forearmRotation(side, upper, forearm, palm) * DEGREES : null,+ flexion: wrist.flexion * DEGREES,+ radial: wrist.radial * DEGREES,+ }+}++// Puts an angle inside its range without a jump. Clamping to the nearer end flips the joint from one end to the other when the wanted+// angle passes through the unreachable side: a 17 cm one-frame hand pop. Here the angle walks back through the range+// while the wanted angle crosses the unreachable arc, so the result is continuous all the way round.+function foldIntoRange(angle, low, high) {+ if (angle >= low && angle <= high) return angle+ const fullTurn = 2 * Math.PI+ const pastHigh = ((angle - high) % fullTurn + fullTurn) % fullTurn+ return high - ((high - low) * pastHigh) / (fullTurn - (high - low))+}++// A hand rotation near `hand` whose wrist and forearm stay inside `limits`, for this upper arm and forearm.+export function limitHand(hand, side, upper, forearm, limits = GRIP_COMFORT) {+ const limited = hand.clone()+ const palm = palmLocal(side).applyQuaternion(limited)+ const elbowFlexion = Math.acos(Math.min(1, Math.max(-1, upper.dot(forearm)))) * DEGREES+ const rollWeight = smooth((elbowFlexion - ELBOW_BENT_ENOUGH.from) / (ELBOW_BENT_ENOUGH.to - ELBOW_BENT_ENOUGH.from))+ if (rollWeight > 0) {+ const rotation = forearmRotation(side, upper, forearm, palm)+ const allowed = foldIntoRange(rotation, -limits.supination / DEGREES, limits.pronation / DEGREES)+ // A turn about the forearm raises the rotation on the left arm and lowers it on the right: the two palms mirror each other.+ const sign = side === 'r' ? 1 : -1+ limited.premultiply(new THREE.Quaternion().setFromAxisAngle(forearm, sign * (rotation - allowed) * rollWeight))+ }+ const palmNow = palmLocal(side).applyQuaternion(limited)+ const fingersNow = FINGERS_LOCAL.clone().applyQuaternion(limited)+ const indexNow = INDEX_LOCAL.clone().applyQuaternion(limited)+ const wrist = wristAngles(forearm, palmNow, fingersNow, indexNow)+ const flexion = foldIntoRange(wrist.flexion, -limits.wristExtension / DEGREES, limits.wristFlexion / DEGREES)+ const radial = foldIntoRange(wrist.radial, -limits.ulnar / DEGREES, limits.radial / DEGREES)+ // Where the forearm should lie in the hand's own axes, then the smallest turn that puts it there.+ const forearmWanted = fingersNow.clone().addScaledVector(palmNow, -Math.tan(flexion)).addScaledVector(indexNow, -Math.tan(radial)).normalize()+ return limited.premultiply(new THREE.Quaternion().setFromUnitVectors(forearmWanted, forearm))+}++// The last stop for any posed arm, a stock clip included (the walk clip swings the wrists 26 degrees toward the thumb): turns the+// hand back inside the anatomical range, two degrees short of it. An arm already inside is left exactly as it is.+const LAST_STOP = Object.fromEntries(Object.entries(ARM_LIMITS).map(([joint, limit]) => [joint, limit - 2]))+export function keepArmInRange(bones, side) {+ const hand = bones['hand_' + side]+ hand.updateWorldMatrix(true, false)+ const { upper, forearm } = armGeometry(bones, side)+ const rotation = limitHand(hand.getWorldQuaternion(new THREE.Quaternion()), side, upper, forearm, LAST_STOP)+ const parentRotation = hand.parent.getWorldQuaternion(new THREE.Quaternion())+ hand.quaternion.copy(parentRotation.invert().multiply(rotation))+ hand.updateWorldMatrix(false, true)+}++// Which way the arm's bones roll, read from a relaxed clip pose (the rig has no twist bones). `twoBoneArm` keeps the elbow bending+// about the rig's own hinge, so the skin folds where an elbow folds.+export function captureArmRest(bones, side) {+ const upperBone = bones['upperarm_' + side]+ const lowerBone = bones['lowerarm_' + side]+ const handBone = bones['hand_' + side]+ handBone.updateWorldMatrix(true, false)+ const { upper, forearm } = armGeometry(bones, side)+ const hinge = upper.clone().cross(forearm).normalize()+ return {+ upperHinge: hinge.clone().applyQuaternion(upperBone.getWorldQuaternion(new THREE.Quaternion()).invert()),+ lowerHinge: hinge.clone().applyQuaternion(lowerBone.getWorldQuaternion(new THREE.Quaternion()).invert()),+ handInLower: handBone.quaternion.clone(),+ }+}++// Turns `bone` about `axis` (world) so its local `localDirection` lies as close to `wanted` as a turn about that axis can put it.+function rollBoneTo(bone, axis, localDirection, wanted) {+ const rotation = bone.getWorldQuaternion(new THREE.Quaternion())+ const current = localDirection.clone().applyQuaternion(rotation)+ const currentFlat = current.addScaledVector(axis, -current.dot(axis))+ const wantedFlat = wanted.clone().addScaledVector(axis, -wanted.dot(axis))+ if (currentFlat.lengthSq() < 1e-6 || wantedFlat.lengthSq() < 1e-6) return+ const angle = Math.atan2(currentFlat.clone().cross(wantedFlat).dot(axis), currentFlat.dot(wantedFlat))+ rotateBoneWorld(bone, axis, angle)+}++function rotateBoneWorld(bone, axis, angle) {+ const rotation = bone.getWorldQuaternion(new THREE.Quaternion()).premultiply(new THREE.Quaternion().setFromAxisAngle(axis, angle))+ const parentRotation = bone.parent.getWorldQuaternion(new THREE.Quaternion())+ bone.quaternion.copy(parentRotation.invert().multiply(rotation))+ bone.updateWorldMatrix(false, true)+}++function aimBone(bone, tipBone, target) {+ bone.updateWorldMatrix(true, true)+ const origin = bone.getWorldPosition(vector())+ const current = tipBone.getWorldPosition(vector()).sub(origin).normalize()+ const desired = target.clone().sub(origin).normalize()+ rotateBoneByDelta(bone, new THREE.Quaternion().setFromUnitVectors(current, desired))+}++function rotateBoneByDelta(bone, delta) {+ const rotation = bone.getWorldQuaternion(new THREE.Quaternion()).premultiply(delta)+ const parentRotation = bone.parent.getWorldQuaternion(new THREE.Quaternion())+ bone.quaternion.copy(parentRotation.invert().multiply(rotation))+ bone.updateWorldMatrix(false, true)+}++// Two-bone IK with a pole: puts the wrist at `target` (clamped to the arm's reach), the elbow bending toward `pole`, and each bone+// rolled so the elbow folds about the rig's own hinge. Returns how far the wrist falls short.+export function twoBoneArm(bones, side, rest, target, pole) {+ const upperBone = bones['upperarm_' + side]+ const lowerBone = bones['lowerarm_' + side]+ const handBone = bones['hand_' + side]+ upperBone.updateWorldMatrix(true, true)+ const shoulder = upperBone.getWorldPosition(vector())+ const elbow = lowerBone.getWorldPosition(vector())+ const wrist = handBone.getWorldPosition(vector())+ const upperLength = elbow.distanceTo(shoulder)+ const lowerLength = wrist.distanceTo(elbow)+ const toTarget = target.clone().sub(shoulder)+ const wanted = toTarget.length()+ const distance = Math.min(wanted, (upperLength + lowerLength) * 0.9999)+ const axis = toTarget.normalize()+ const along = (upperLength ** 2 - lowerLength ** 2 + distance ** 2) / (2 * distance)+ const height = Math.sqrt(Math.max(0, upperLength ** 2 - along ** 2))+ const perpendicular = pole.clone().addScaledVector(axis, -pole.dot(axis)).normalize()+ const elbowTarget = shoulder.clone().addScaledVector(axis, along).addScaledVector(perpendicular, height)+ const wristTarget = shoulder.clone().addScaledVector(axis, distance)+ const hinge = perpendicular.clone().cross(axis).normalize()+ aimBone(upperBone, lowerBone, elbowTarget)+ rollBoneTo(upperBone, elbowTarget.clone().sub(shoulder).normalize(), rest.upperHinge, hinge)+ aimBone(lowerBone, handBone, wristTarget)+ rollBoneTo(lowerBone, wristTarget.clone().sub(elbowTarget).normalize(), rest.lowerHinge, hinge)+ return wanted - distance+}++// Without a twist bone, all the forearm's rotation would wring the skin at one joint. The lower arm takes this share and the wrist+// keeps the rest, the way the radius turns along the length of a real forearm.+const FOREARM_ROLL_SHARE = 0.6+export function shareForearmRoll(bones, side, rest, handRotation) {+ const lowerBone = bones['lowerarm_' + side]+ const handBone = bones['hand_' + side]+ lowerBone.updateWorldMatrix(true, true)+ const axis = handBone.getWorldPosition(vector()).sub(lowerBone.getWorldPosition(vector())).normalize()+ const lowerRotation = lowerBone.getWorldQuaternion(new THREE.Quaternion())+ const lowerWanted = handRotation.clone().multiply(rest.handInLower.clone().invert())+ const current = rest.lowerHinge.clone().applyQuaternion(lowerRotation)+ const wanted = rest.lowerHinge.clone().applyQuaternion(lowerWanted)+ const currentFlat = current.addScaledVector(axis, -current.dot(axis))+ const wantedFlat = wanted.addScaledVector(axis, -wanted.dot(axis))+ if (currentFlat.lengthSq() < 1e-6 || wantedFlat.lengthSq() < 1e-6) return+ const angle = Math.atan2(currentFlat.clone().cross(wantedFlat).dot(axis), currentFlat.dot(wantedFlat))+ rotateBoneWorld(lowerBone, axis, angle * FOREARM_ROLL_SHARE)+}++// The film's check: every mannequin registers its arms, and tools/film.mjs reads measureWatchedArms() on each frame.+const watchedArms = []+export function watchArms(name, bones, group) {+ watchedArms.push({ name, bones, group })+}++function isShown(object) {+ for (let node = object; node; node = node.parent) {+ if (!node.visible) return false+ }+ return true+}++export function measureWatchedArms() {+ const faults = []+ const largest = {}+ watchedArms.forEach(({ name, bones, group }) => {+ if (!bones.hand_r || !isShown(group)) return+ ;['l', 'r'].forEach((side) => {+ const angles = armAngles(bones, side)+ const excess = {+ elbowFlexion: angles.elbowFlexion - ARM_LIMITS.elbowFlexion,+ pronation: angles.rotation === null ? -1 : angles.rotation - ARM_LIMITS.pronation,+ supination: angles.rotation === null ? -1 : -angles.rotation - ARM_LIMITS.supination,+ wristFlexion: angles.flexion - ARM_LIMITS.wristFlexion,+ wristExtension: -angles.flexion - ARM_LIMITS.wristExtension,+ radial: angles.radial - ARM_LIMITS.radial,+ ulnar: -angles.radial - ARM_LIMITS.ulnar,+ }+ Object.entries(excess).forEach(([joint, over]) => {+ const key = name + ' ' + side + ' ' + joint+ largest[key] = Math.max(largest[key] ?? -Infinity, over)+ if (over > 0) faults.push({ key, over })+ })+ })+ })+ return { faults, largest }+}