@margoengine/rigging 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +969 -3
  4. package/dist/autorig.d.ts +50 -0
  5. package/dist/autorig.js +660 -0
  6. package/dist/bar-grip.d.ts +7 -0
  7. package/dist/checks.d.ts +50 -0
  8. package/dist/contact.d.ts +175 -0
  9. package/dist/contact.js +739 -0
  10. package/dist/correctives.d.ts +92 -0
  11. package/dist/correctives.js +162 -0
  12. package/dist/errors-D8rc8kzg.js +7 -0
  13. package/dist/face.d.ts +93 -0
  14. package/dist/face.js +144 -0
  15. package/dist/hands.d.ts +209 -0
  16. package/dist/hands.js +510 -0
  17. package/dist/heat.d.ts +38 -0
  18. package/dist/hinged-contact.d.ts +7 -0
  19. package/dist/hulls.d.ts +54 -0
  20. package/dist/hulls.js +134 -0
  21. package/dist/ik.d.ts +109 -0
  22. package/dist/ik.js +358 -0
  23. package/dist/index.d.ts +6 -0
  24. package/dist/index.js +390 -0
  25. package/dist/joint-limits.d.ts +44 -0
  26. package/dist/joint-limits.js +74 -0
  27. package/dist/limb-collision.d.ts +99 -0
  28. package/dist/loading-CZaYr1N7.js +67 -0
  29. package/dist/mesh-CyvLHNp0.js +142 -0
  30. package/dist/mesh.d.ts +47 -0
  31. package/dist/mtoon-data.d.ts +118 -0
  32. package/dist/mtoon-legacy.d.ts +17 -0
  33. package/dist/mtoon-shader.d.ts +4 -0
  34. package/dist/mtoon.d.ts +84 -0
  35. package/dist/mtoon.js +990 -0
  36. package/dist/paint.d.ts +82 -0
  37. package/dist/pose-tracking.d.ts +117 -0
  38. package/dist/pose-tracking.js +488 -0
  39. package/dist/retarget.d.ts +71 -0
  40. package/dist/retarget.js +351 -0
  41. package/dist/rig-BawZ5OLb.js +127 -0
  42. package/dist/rig.d.ts +65 -0
  43. package/dist/shared/gltf.d.ts +257 -0
  44. package/dist/shared/layers.d.ts +16 -0
  45. package/dist/springs.d.ts +180 -0
  46. package/dist/springs.js +458 -0
  47. package/dist/strand-springs.d.ts +46 -0
  48. package/dist/strand-springs.js +168 -0
  49. package/dist/swim.d.ts +55 -0
  50. package/dist/swim.js +167 -0
  51. package/dist/transfer.d.ts +41 -0
  52. package/dist/transfer.js +136 -0
  53. package/dist/voxel-weights-48ok-Dax.js +255 -0
  54. package/dist/voxel-weights.d.ts +42 -0
  55. package/dist/voxel-weights.js +1 -0
  56. package/dist/voxels.d.ts +36 -0
  57. package/dist/vrm-constraints.d.ts +60 -0
  58. package/dist/vrm-constraints.js +261 -0
  59. package/dist/vrm-first-person.d.ts +115 -0
  60. package/dist/vrm-first-person.js +618 -0
  61. package/dist/vrm-presets-CU4V4yq6.js +47 -0
  62. package/dist/vrm-presets.d.ts +1 -0
  63. package/dist/vrm.d.ts +298 -0
  64. package/dist/vrm.js +574 -0
  65. package/dist/vrm0.d.ts +134 -0
  66. package/dist/vrm0.js +377 -0
  67. package/dist/vrma.d.ts +90 -0
  68. package/dist/vrma.js +315 -0
  69. package/dist/weight-map-D8cAONQQ.js +92 -0
  70. package/dist/weight-map.d.ts +58 -0
  71. package/package.json +175 -6
package/README.md CHANGED
@@ -1,3 +1,969 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/rigging
2
+
3
+ Import `margoengine/rigging` from the `margoengine` package, or `@margoengine/rigging` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Rigging and animation authoring for characters made in Margo or anywhere else: smooth automatic skin weights, weight painting with undo, the skin checks game engines need before export, IK chains with poles and retarget presets that play Mixamo, Godot and Roblox clips on any humanoid. Everything here is plain data in, plain data out: no engine, renderer or GPU is needed, core is never imported, and an app that does not import this package ships none of it.
6
+
7
+ ## Automatic weights (bone heat)
8
+
9
+ `boneHeatWeights(mesh, joints)` gives every vertex smooth weights from a rest skeleton, by bone heat diffusion (I. Baran and J. Popović, "Automatic rigging and animation of 3D characters", SIGGRAPH 2007). Each joint moves the vertices around its bone, the segment from the joint to each child (a point at a leaf joint), and weights blend smoothly across joints. Weights are 0 or more and sum to 1 per vertex. Heat only reaches a vertex from bones it can see, so an arm's weight does not leak into the hip it hangs beside.
10
+
11
+ ```ts
12
+ import { boneHeatWeights, checkSkin, type RigJoint } from 'margoengine/rigging';
13
+
14
+ // Any triangle mesh (positions xyz, optional indices) and a rest skeleton in the same space.
15
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 2, 0]);
16
+ const indices = new Uint32Array([0, 1, 2, 2, 1, 3]);
17
+ const joints: RigJoint[] = [
18
+ { name: 'hips', parent: -1, position: [0.5, 0, 0] },
19
+ { name: 'spine', parent: 0, position: [0.5, 1, 0] },
20
+ { name: 'head', parent: 1, position: [0.5, 2, 0] },
21
+ ];
22
+ const weights = await boneHeatWeights({ positions, indices }, joints, { visibility: false });
23
+ const { joints: JOINTS_0, weights: WEIGHTS_0 } = weights.toInfluences(4); // glTF's four strongest per vertex
24
+ console.log(JOINTS_0.length, WEIGHTS_0.length); // 16 16
25
+ console.log(checkSkin({ weights: weights.toInfluences(4), joints }).ok); // true
26
+ ```
27
+
28
+ Options, each with its default:
29
+
30
+ | Option | Default | Meaning |
31
+ | --- | --- | --- |
32
+ | `skip` | `[]` | Joints (indices or names) that move no vertices, such as a root at the feet. |
33
+ | `visibility` | `true` | Heat only from visible bones; uses `@margoengine/bvh`, loaded on first use. `false` takes the nearest bone (faster; fine for convex parts). Or pass `(from, to) => boolean`. |
34
+ | `heat` | `1` | Heat constant c in H = c / d². Larger keeps vertices closer to their nearest bone. |
35
+ | `weld` | `1e-6` | Vertices closer than this fraction of the mesh size are one point, so weights cross UV seams and split faces. |
36
+ | `tolerance` | `1e-6` | Largest weight error per vertex when a bone's solve stops. |
37
+ | `maxIterations` | `2000` | Conjugate-gradient iterations per bone; a `MargoError` with code `failed` when not enough. |
38
+ | `threshold` | `1e-4` | Weights below this share are dropped before renormalising. |
39
+ | `signal` | none | `AbortSignal`; the promise rejects with its reason. The solve yields to the event loop every 30 ms. |
40
+
41
+ Vertices at one position always get the same weights. Pass `joints` from `@margoengine/exporters/skin`'s `humanoidJoints()`, or turn any glTF skeleton into joints with `rigJoints(retargetRig(model))`.
42
+
43
+ ## Weight painting
44
+
45
+ `WeightPainter` paints a `WeightMap` with brush dabs: `add`, `subtract`, `replace` (toward `value`) and `smooth` (toward the neighbours' average). Each dab keeps every vertex it touches summing to 1: when one bone gains or loses weight, the other unlocked bones on that vertex make up the difference. Locked bones never change. Every stroke returns its undo.
46
+
47
+ ```ts
48
+ import { WeightMap, WeightPainter } from 'margoengine/rigging';
49
+
50
+ const mesh = { positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), indices: new Uint32Array([0, 1, 2]) };
51
+ const map = new WeightMap(3, 2, [1, 0, 1, 0, 1, 0]);
52
+ const painter = new WeightPainter(map, mesh, { parents: [-1, 0], locked: [] });
53
+ const stroke = painter.stroke({ mode: 'add', bone: 1, center: [0, 1, 0], radius: 0.8, strength: 0.5, falloff: 'smooth' });
54
+ painter.smoothAll({ iterations: 2, strength: 0.5 });
55
+ stroke.undo(); // undo strokes newest first
56
+ painter.normalize();
57
+ ```
58
+
59
+ | Stroke field | Default | Meaning |
60
+ | --- | --- | --- |
61
+ | `mode` | required | `add`, `subtract`, `replace` or `smooth`. |
62
+ | `bone` | required except for `smooth` | The bone painted. |
63
+ | `center`, `radius` | required | Brush sphere in mesh space. |
64
+ | `strength` | `0.5` | Amount at the centre (0-1). |
65
+ | `value` | `1` | `replace`'s target weight. |
66
+ | `falloff` | `smooth` | `smooth` (smoothstep), `linear` or `constant`. |
67
+
68
+ Subtracting from a vertex whose other bones hold nothing passes the weight to the bone's parent (pass `parents`); with no unlocked parent the vertex keeps it, so a vertex never ends up unweighted. `WeightMap` is dense (`values[vertex * boneCount + bone]`); `toInfluences(4)` returns the strongest four per vertex, renormalised, and `WeightMap.fromInfluences({joints, weights})` reads them back.
69
+
70
+ ## Skin checks before export
71
+
72
+ `checkSkin` reports what Unity, Unreal, Godot, Roblox and glTF validators reject or render wrongly: unweighted vertices, more than four influences, weights that don't sum to 1, negative or non-finite weights, joint indices outside the skin (in any slot, weighted or not), one joint in two weighted slots of a vertex (`duplicate-joint`; glTF 2.0 3.7.3.3 forbids both), and degenerate bones (each counted once) (a joint on its parent, or a non-invertible inverse bind matrix). `assertSkin` throws a `RangeError` naming each fault and its fix.
73
+
74
+ ```ts
75
+ import { WeightMap, assertSkin, checkSkin } from 'margoengine/rigging';
76
+
77
+ const weights = new WeightMap(2, 2, [0.6, 0.6, 0, 0]);
78
+ const report = checkSkin({ weights, maxInfluences: 4, tolerance: 1e-3 });
79
+ for (const issue of report.issues) console.log(issue.code, issue.count, issue.vertices, issue.message);
80
+ // not-normalized 1 [0] "1 vertex(es) have weights that don't sum to 1; call normalize()"
81
+ // unweighted 1 [1] "1 vertex(es) have no weight; paint them or run boneHeatWeights"
82
+ weights.normalize();
83
+ try {
84
+ assertSkin({ weights });
85
+ } catch (error) {
86
+ console.log((error as RangeError).message); // still names vertex 1 as unweighted
87
+ }
88
+ ```
89
+
90
+ Input is a `WeightMap` or per-vertex influences (`{joints, weights, influences?}`, glTF's JOINTS_0 / WEIGHTS_0 at the default width 4); add `joints` (the rest skeleton) or `inverseBindMatrices` to check bones too. Defaults: `maxInfluences` 4, `tolerance` 1e-3.
91
+
92
+ ## IK chains with pole targets (`margoengine/rigging/ik`)
93
+
94
+ FABRIK (A. Aristidou and J. Lasenby, 2011) chains of any length with a pole: the joints move so the last one reaches the target, every bone keeps its length, and the bend faces the pole (a knee or elbow hint). Solve on an Animator every frame, on a `Skeleton` while authoring a pose, or on raw joint positions.
95
+
96
+ ```ts
97
+ import { EngineKernel } from 'margoengine/core';
98
+ import { loadGLTF } from 'margoengine/gltf/pbr';
99
+ import { Animation } from 'margoengine/animation';
100
+ import { Animator } from 'margoengine/animator';
101
+ import { addIKChain, type AnimatorIKChain } from 'margoengine/rigging/ik';
102
+ import { detectSkeleton, humanoidBones } from 'margoengine/rigging/retarget';
103
+
104
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, { backend: 'webgpu' });
105
+ const model = await loadGLTF(engine, '/character.glb');
106
+ const animator = Animator.attach(Animation.attach(model), { initial: 'idle', states: { idle: 'Idle' } });
107
+ // Bones by name: Mixamo (any mixamorig prefix), Godot, Roblox R15 or humanoid names, whichever the rig uses.
108
+ const names = model.asset.doc.nodes!.map((n) => n.name ?? '');
109
+ const bone = humanoidBones(names, detectSkeleton(names)?.preset ?? 'humanoid'); // humanoid bone -> node index
110
+ const reach: AnimatorIKChain = {
111
+ joints: [bone.get('leftUpperArm')!, bone.get('leftLowerArm')!, bone.get('leftHand')!], // each the child of the one before
112
+ target: [0.4, 1.3, 0.5], // world space; write into it every frame
113
+ pole: [0.3, 1.2, -0.6], // the elbow bends toward this point
114
+ weight: 1, // 0 keeps the animated pose
115
+ iterations: 32, // default 32
116
+ tolerance: 1e-4, // default 1e-4, world units
117
+ };
118
+ const remove = addIKChain(animator, reach);
119
+ engine.start();
120
+ remove(); // when done
121
+ ```
122
+
123
+ For joint limits use `addCCDChain` from `margoengine/animator`. While authoring (no engine), `solveSkeletonIK(skeleton, {joints, target, pole})` poses an `@margoengine/animation` `Skeleton` by bone names or indices, `solvePoseIK({parents, local}, chain)` solves on a local pose array (10 numbers per bone, as `retargetRig` makes), and `solveFABRIK(points, target, {pole})` moves raw joint positions:
124
+
125
+ ```ts
126
+ import { Skeleton } from 'margoengine/animation';
127
+ import { solveFABRIK, solveSkeletonIK } from 'margoengine/rigging/ik';
128
+
129
+ const leg = new Skeleton([
130
+ { name: 'hip', parent: -1 },
131
+ { name: 'knee', parent: 0, translation: [0, -0.45, 0] },
132
+ { name: 'ankle', parent: 1, translation: [0, -0.42, 0] },
133
+ ]);
134
+ const result = solveSkeletonIK(leg, { joints: ['hip', 'knee', 'ankle'], target: [0.1, -0.7, 0.2], pole: [0, -0.4, 1] });
135
+ console.log(result.reached, result.distance, result.iterations);
136
+
137
+ const points = new Float64Array([0, 0, 0, 0, 1, 0, 0, 2, 0]); // xyz per joint, the first one fixed
138
+ solveFABRIK(points, [1, 1, 0], { pole: [2, 0, 0], iterations: 32, tolerance: 1e-4 });
139
+ ```
140
+
141
+ Unreachable targets straighten the chain toward them (`reached` false, `distance` the gap). A straight chain starts bending toward the pole (or, with none, a fixed side).
142
+
143
+ **With `@margoengine/kinematics-constraints`.** `elbowEvaluator(upperLength, lowerLength, pole)` is the `ElbowEvaluator` an `AvoidanceSolver` needs: the elbow of a two-bone arm reaching from the shoulder to the target, turned `poleAngle` about the shoulder-target line from the pole's side. The solver then searches that angle for an elbow that clears the body's capsules and spheres:
144
+
145
+ ```ts
146
+ import { AvoidanceSolver, CapsuleVolume } from 'margoengine/kinematics-constraints';
147
+ import { elbowEvaluator } from 'margoengine/rigging/ik';
148
+
149
+ const torso = new CapsuleVolume({ start: [0, 0.9, 0], end: [0, 1.5, 0], radius: 0.18 });
150
+ const avoid = new AvoidanceSolver([torso], { minClearance: 0.01, targetRadius: 0.04 });
151
+ const evaluate = elbowEvaluator(0.3, 0.28, [0.2, 1.2, -0.5]); // upper arm, forearm, pole
152
+ const shoulder = new Float32Array([0.2, 1.4, 0]), hand = new Float32Array([0.5, 1.2, 0.2]);
153
+ const solved = avoid.solve(shoulder, hand, [-0.1, 1.2, 0.35], 0.3, 0.28, 0.05, 0.04, 1 / 60, evaluate);
154
+ console.log(solved.status, solved.elbow, solved.target);
155
+ ```
156
+
157
+ Root motion and look-at / aim constraints live with the Animator: `addRootMotion`, `addLookAt` and `addAimConstraint` in [`@margoengine/animator`](../animator/README.md).
158
+
159
+ ## Hand and foot contacts (`margoengine/rigging/contact`)
160
+
161
+ `solveContactIK` puts the point on the hand, shoe or hoof that actually touches the surface at a chosen position and orientation. The chain runs through the wrist, ankle or hoof. `anchor` is the palm, sole or other landmark in the final joint's own coordinates. Read `locked` before applying a grip pose or firing a contact sound. The solve measures the actual landmark after posing and returns its position, angular error and remaining gap. Approaching with `weight` below 1 blends the landmark and wrist toward the contact. A pole selects the bend side. Calibrate each limited joint's neutral rotation and axes from the rig. A hinge gives an elbow, knee or hock one bounded axis. A cone limits wrist or ball-joint swing and signed twist independently. Per-axis limits suit a joint with separate rotation controls.
162
+
163
+ ```ts
164
+ import { solveContactIK } from 'margoengine/rigging/contact';
165
+
166
+ const parents = [-1, 0, 1];
167
+ const local = new Float64Array([
168
+ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
169
+ 0.3, 0, 0, 0, 0, 0, 1, 1, 1, 1,
170
+ 0.26, 0, 0, 0, 0, 0, 1, 1, 1, 1,
171
+ ]);
172
+ const contact = solveContactIK({ parents, local }, {
173
+ joints: [0, 1, 2],
174
+ point: [0.46, 0.16 * Math.sqrt(3), 0],
175
+ rotation: [0, 0, 0.5, Math.sqrt(3) / 2],
176
+ anchor: [0.06, 0, 0],
177
+ pole: [0.3, 0, 0],
178
+ reach: 'hinged',
179
+ limits: [
180
+ { joint: 1, neutral: [0, 0, 0, 1], limit: { type: 'hinge', axis: [0, 0, 1], min: 0, max: 2.35 } },
181
+ { joint: 2, neutral: [0, 0, 0, 1], limit: { type: 'cone', axis: [1, 0, 0], angle: 0.85, twist: [-0.35, 0.35] } },
182
+ ],
183
+ tolerance: 0.002,
184
+ });
185
+ console.log(contact.locked, contact.distance);
186
+ ```
187
+
188
+ Pose and contact points use skeleton space and the same units. Ancestor scales must be uniform and positive. The end joint can have different positive scales along its axes. Default tolerances are 0.0001 scene units and 0.02 radians. Each solve uses up to 64 CCD sweeps by default. The chain can contain 2–256 joints inside a larger rig. `checkRig` accepts up to 65,536 joints, the number of joint indices representable by glTF unsigned shorts. A weight of 0 measures the input pose exactly. A gap or orientation outside either tolerance leaves `locked` false. Start from the sampled animation pose each frame so corrections cannot accumulate.
189
+
190
+ Use `reach: 'hinged'` with an explicit pole to keep the elbow or knee on one authored bend plane across samples.
191
+ The final three joints form the two links and the penultimate joint needs a hinge whose axis is perpendicular to
192
+ both links in its neutral pose. An optional hinge twist axis follows the lower link. Earlier joints carry the reach
193
+ and retain their sampled pose within their limits. Animate the pole smoothly off the reach axis. Unreachable goals
194
+ clamp to the calibrated reach, and a collision rejects the sample without choosing a different bend plane.
195
+ `PalmContactRig` accepts the same option on a target with calibrated elbow and `elbowPole`.
196
+
197
+ The contact landmark follows [*Footskate Cleanup for Motion Capture Editing*, Kovar, Gleicher and Schreiner (2002)](https://research.cs.wisc.edu/graphics/Papers/Gleicher/Mocap/cleanup.pdf). The chain solve uses the Animator's constrained CCD solver. [*Parametrization and Range of Motion of the Ball-and-Socket Joint*, Baerlocher and Boulic (2000)](https://infoscience.epfl.ch/bitstreams/949101d1-ec81-4e38-91d8-c414ee95c8fc/download) describes swing and twist boundaries. Position error is at the surface landmark because the joint origin and the surface point differ, as in the hand and foot annotations of [*CIMI4D*, Yan et al. (2023)](https://openaccess.thecvf.com/content/CVPR2023/papers/Yan_CIMI4D_A_Large_Multimodal_Climbing_Motion_Dataset_Under_Human-Scene_Interactions_CVPR_2023_paper.pdf).
198
+
199
+ ### Human palm and cylindrical grips
200
+
201
+ `PalmContactRig` measures the palm and digits from the rig's bind pose, aligns a palm pad to a contact point and its
202
+ surface normal, and closes the fingers in proportion to the actual contact. Arm reach and finger closure are separate
203
+ inputs. While a reach is active, the contact layer owns the digits, including any earlier keyed grip. Closure eases to
204
+ zero when the palm is farther away or more misaligned than its tolerance. A reversed palm cannot engage the grip.
205
+ `addPalmContact` evaluates this same solve after the Animator's pose and earlier solvers.
206
+
207
+ ```ts
208
+ import type { Animator } from 'margoengine/animator';
209
+ import { addPalmContact, type PalmContactTarget } from 'margoengine/rigging/contact';
210
+
211
+ export function attachRailGrip(animator: Animator, upperArm: number, elbow: number, wrist: number) {
212
+ let target: PalmContactTarget | undefined;
213
+ const dispose = addPalmContact(animator, {
214
+ side: 'right',
215
+ preset: 'mixamo',
216
+ joints: [upperArm, elbow, wrist],
217
+ elbow: { joint: elbow, flexDirection: [0, 0, 1] },
218
+ }, () => target);
219
+ return {
220
+ reach(point: PalmContactTarget['point']) {
221
+ target = { point, normal: [0, 0, 1], towardsFingers: [0, 1, 0], diameter: 0.035 };
222
+ },
223
+ release() { target = undefined; },
224
+ dispose,
225
+ };
226
+ }
227
+ ```
228
+
229
+ Use node indices from the avatar and directions in its skeleton space. Supply a custom humanoid `bones` map for
230
+ an unfamiliar naming scheme. For offline posing, construct `new PalmContactRig(rig, calibration)` and call
231
+ `solve(sampledLocal, target)` once per sample. Both routes report the achieved position, distance, angle, contact
232
+ state and `gripWeight`. Resolve moving holds into model space at the sample time. Supply `close` to animate
233
+ release and `weight` to blend the reach. Return `undefined` to give control to the underlying animation.
234
+
235
+ Default registration tolerances are 3 mm on metre-scale rigs and 5 degrees. With elbow calibration, the forearm
236
+ bends about its measured flexion axis, defaults to −0.035 to 2.55 radians relative to bind and rolls ±1.25 radians
237
+ about its length. Use `roll: false` for a separately authored twist joint. The measured wrist defaults to 1.15
238
+ radians of swing and ±0.22 radians of axial twist. Use `limits` to set per-character bounds and `anchor` for a
239
+ measured palm-pad point in wrist-local coordinates. The default anchor starts at 56% of the wrist-to-middle-knuckle
240
+ distance. A forward thumb base can move it up to 88% to keep the bar away from the thumb web. The outward pad offset
241
+ is 8.5% of palm length. Cylindrical poses use the measured digit lengths and a diameter
242
+ above 0 and below 1 m. The solver measures palm registration, and per-digit skin collision requires its own
243
+ geometry and verification.
244
+
245
+ The grip model draws on [*The Computer Animation of Human Hand Grasping*, Rijpkema and Girard (1991)](https://doi.org/10.1145/127719.127748)
246
+ and [*Handrix*, ElKoura and Singh (2003)](https://doi.org/10.2312/SCA03/110-119).
247
+ The wrist also checks the angle between the forearm and the measured palm frame, with defaults of 1.12 radians
248
+ of flexion, 1.0 of extension, and 0.46 of sideways deviation. Calibrate these through `wrist` for the character
249
+ and action. A compatible custom constraint can take over this check with `wrist: false`. The cylindrical fit
250
+ uses the same diameter as the palm target. It chooses a pose for each digit from its measured lengths, fits the
251
+ thumb on the opposing side, and checks for proxy intersections from the open approach through six stages of
252
+ closure. The anchor's clearance from the thumb base leaves room to oppose and curl the thumb together.
253
+ A second search tests coupled thumb flexion along the same bar when a base turn alone leaves the joints rigid.
254
+ A hand with very short
255
+ digits or an oversized bar can still have a gap. Check the final deformed skin against the production geometry.
256
+
257
+ The independent forearm and wrist controls follow the distinct axes described in
258
+ [*From Skin to Skeleton*, Keller et al. (2023)](https://doi.org/10.1145/3618381) and
259
+ [*In Vivo Analysis of the Mechanical Axes of the Wrist During Dynamic Motion*, Crisco et al. (2011)](https://pmc.ncbi.nlm.nih.gov/articles/PMC3016043/).
260
+ The functional ranges measured by [Ryu, Cooney, Askew, An and Chao (1991)](https://pubmed.ncbi.nlm.nih.gov/1861019/)
261
+ guide the additional pose check. The opposing thumb follows the grip observations in
262
+ [*The GRASP Taxonomy of Human Grasp Types*, Feix et al. (2016)](https://www.eng.yale.edu/grablab/pubs/Feix_THMS2016.pdf)
263
+ and [*In Vivo Kinematics of the Thumb Carpometacarpal Joint During Three Isometric Functional Tasks*, Halilaj et al. (2014)](https://pmc.ncbi.nlm.nih.gov/articles/PMC3940759/).
264
+ These are rig-space defaults that can be calibrated to the actor's proportions, bind orientation and authored controls.
265
+
266
+ ### Character self-collision during contact
267
+
268
+ `LimbCollisionRig` attaches capsules and spheres to a human or animal skeleton. Configure a chain of limb links,
269
+ the body volumes it can hit, and optional joint directions relative to bones such as the chest or pelvis. Capsule
270
+ radii are in skeleton units. Measure them with clothing or fur included, then trim shared segments at the shoulder
271
+ or hip to allow the intended attachment. The same API works for a quadruped foreleg, a wing, or a tail when given
272
+ the corresponding landmarks and joint slots.
273
+
274
+ ```ts
275
+ import { LimbCollisionRig, type PalmContactTarget } from 'margoengine/rigging/contact';
276
+
277
+ export function guardReach(parents: readonly number[], lowerSpine: number, chest: number) {
278
+ const guard = new LimbCollisionRig(parents, [
279
+ { start: { joint: lowerSpine }, end: { joint: chest }, radius: 0.12 },
280
+ ], [
281
+ { start: 0, end: 1, radius: 0.04, range: [0.35, 1] },
282
+ { start: 1, end: 2, radius: 0.035 },
283
+ ], [
284
+ { start: 0, end: 1, reference: chest, forward: [0, 0, 1] },
285
+ ]);
286
+ return (local: Float64Array, target: PalmContactTarget): PalmContactTarget => {
287
+ guard.setBodyPose(local);
288
+ return { ...target, clearance: guard.clearance };
289
+ };
290
+ }
291
+ ```
292
+
293
+ Pass the resulting target to `PalmContactRig.solve` with the same three chain slots ordered shoulder, elbow and
294
+ wrist. `solveContactIK` also accepts the clearance callback. Negative values reject the candidate. The solver
295
+ tries alternate elbow directions when the preferred pose is blocked, and leaves the input arm pose in place if it
296
+ finds no clear solution. Check `blocked` and choose a reachable hold or a safe fallback pose. The result's `clearance`
297
+ combines proxy separation and the margin to the configured joint directions and wrist range.
298
+
299
+ Use `snapshot` for the accepted limb at two consecutive poses and `sweep` to test the intervening proxy motion
300
+ and direction limits. Capsule endpoints and the vectors between the configured limb joints are linearly
301
+ interpolated. Each reference axis follows a short spherical arc as the torso turns. Include intermediate poses for curved joint motion or opposite reference
302
+ axes. A sweep that cannot certify clearance returns `clear: false` and `exhausted: true`. Legacy snapshots without
303
+ the direction channel still check capsule motion. Use the same snapshot format at both ends.
304
+
305
+ ```ts
306
+ import { LimbCollisionRig } from 'margoengine/rigging/contact';
307
+
308
+ export function checkShoulderTravel(before: number[], after: number[]) {
309
+ const guard = new LimbCollisionRig(
310
+ [-1],
311
+ [{ start: { joint: 0 }, radius: 0.16 }],
312
+ [{ start: 0, end: 1, radius: 0.04 }],
313
+ [{ start: 0, end: 1, reference: 0, forward: [0, 0, 1] }],
314
+ );
315
+ guard.setBodyPose([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]);
316
+ return guard.sweep(guard.snapshot(before), guard.snapshot(after));
317
+ }
318
+ ```
319
+
320
+ The alternate elbow search draws on [*Real-Time Inverse Kinematics Techniques for Anthropomorphic Limbs*, Tolani,
321
+ Goswami and Badler (2000)](https://www.ambarish.com/paper/Tolani_Goswami_Badler_IK.pdf) and [*Analytical Inverse
322
+ Kinematics with Body Posture Control*, Kallmann (2008)](https://mkallmann.github.io/papers/08-cavw-bodyik.pdf).
323
+ The explicit-pole mode uses the analytical elbow circle described by Tolani, Goswami and Badler. Keeping the bend
324
+ plane on a continuous authored curve follows the use of smooth pose corrections in [*A Hierarchical Approach to
325
+ Interactive Motion Editing for Human-like Figures*, Jehee Lee and Sung Yong Shin (1999)](https://doi.org/10.1145/311535.311539).
326
+ Capsule gaps use the segment-distance construction in [*On Fast Computation of Distance Between Line Segments*,
327
+ Lumelsky (1985)](https://doi.org/10.1016/0020-0190(85)90032-8). The continuous check adapts conservative advancement
328
+ to straight proxy paths, following [*Fast Continuous Collision Detection for Articulated Models*, Redon, Lin and
329
+ Manocha (2004)](https://diglib.eg.org/items/13aac165-e652-4c78-a0a6-0b42305f0753).
330
+ The direction limit uses a body-relative axis, as in [*Parametrization and Range of Motion of the Ball-and-Socket
331
+ Joint*, Paolo Baerlocher and Ronan Boulic (2000)](https://infoscience.epfl.ch/bitstreams/949101d1-ec81-4e38-91d8-c414ee95c8fc/download).
332
+ The sweep uses the angular speed of that axis and the linear speed of the limb vector
333
+ to bound gap changes. See [*Animating Rotation with Quaternion Curves*, Ken Shoemake (1985)](https://doi.org/10.1145/325334.325242)
334
+ for spherical interpolation and [*Continuous Collision Detection for Articulated Models Using Taylor Models
335
+ and Temporal Culling*, Zhang, Redon, Lee and Kim (2007)](https://doi.org/10.1145/1239451.1239466) for
336
+ angular motion bounds in conservative advancement.
337
+
338
+ ## Joint hulls (`margoengine/rigging/hulls`)
339
+
340
+ `jointHulls(model, options)` finds the convex hull of the vertices each joint carries, from a skinned mesh in its bind pose. A hull is a short list of corners, so a clearance or collision test can use the real shape of a torso, head or forearm instead of a sphere or capsule. Run it once at load. It uses `@margoengine/geometry`'s quickhull, and only this entry imports it.
341
+
342
+ ```ts
343
+ import { jointHulls } from 'margoengine/rigging/hulls';
344
+
345
+ // A column of four rings of box corners; the lower two rings follow joint 0, the upper two follow joint 1.
346
+ const positions: number[] = [];
347
+ const joints: number[] = [];
348
+ for (let ring = 0; ring < 4; ring++)
349
+ for (const x of [-0.5, 0.5])
350
+ for (const z of [-0.5, 0.5]) {
351
+ positions.push(x, ring, z);
352
+ joints.push(ring < 2 ? 0 : 1);
353
+ }
354
+ const skin = { joints: Uint16Array.from(joints), weights: new Float32Array(joints.length).fill(1), influences: 1 };
355
+
356
+ // Joint 1 sits at y = 2 in the bind pose; its inverse bind matrix (glTF column-major) moves the world down by 2.
357
+ const translateDown = (y: number) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -y, 0, 1];
358
+ const inverseBindMatrices = [...translateDown(0), ...translateDown(2)];
359
+ for (const hull of jointHulls({ positions, skin }, { inverseBindMatrices }))
360
+ console.log(hull.joint, hull.vertexCount, hull.points.length / 3); // 0 8 8, then 1 8 8
361
+ ```
362
+
363
+ | Option | Default | Meaning |
364
+ | --- | --- | --- |
365
+ | `minWeight` | `0.5` | A vertex counts toward a joint when the joint carries at least this much of it (0 to 1). The default gives each vertex to its main joint, so neighbouring hulls meet without overlapping; lower it so blended vertices (an elbow) reach into both. |
366
+ | `maxPoints` | `64` | Most corners a hull keeps (8-1,024). Larger hulls keep the corners that reach farthest in directions spread over the sphere; every kept point is still a corner of the full hull, so the reduced hull lies inside it. |
367
+ | `inverseBindMatrices` | none | 16 numbers per joint. With them each hull is in its joint's own space, so the joint's world matrix places it; without them the corners stay in mesh space. |
368
+
369
+ The model is `{positions, skin}`: bind-pose `positions` (xyz per vertex) and `skin` as a `WeightMap` or per-vertex influences (`{joints, weights, influences?}`). A joint repeated in several slots of one vertex counts its weights together. Joints that own fewer than four vertices, or whose vertices lie on a line or plane, have no hull and are left out of the result. Positions or weights that are not finite, a skin whose vertex count differs from the positions, and a joint with no inverse bind matrix throw a `RangeError` that names the fix.
370
+
371
+ ## Spring bones and jiggle (`margoengine/rigging/springs`)
372
+
373
+ Secondary motion for hair, tails, cloth strips and accessories with no physics world: `addSpringBones(animator, options)` swings chains of bones after the frame's animation, against sphere and capsule colliders. The settings mean what `VRMC_springBone` 1.0's mean, so a VRM's values work as authored. Tails follow the animated pose, so a clip keeps its say and the chain settles back on it. The step is corrected for time: the same character swings the same at 30, 60 or 144 frames a second.
374
+
375
+ ```ts
376
+ import { SpringBones } from 'margoengine/rigging/springs';
377
+
378
+ // Plain data: a bone at the top and a rope of two bones hanging from it.
379
+ const parents = [-1, 0, 1];
380
+ const bone = (y: number) => [0, y, 0, 0, 0, 0, 1, 1, 1, 1];
381
+ const springs = new SpringBones(parents, {
382
+ chains: [{ joints: [0, 1, 2], stiffness: 1, drag: 0.4, gravity: 0.5, radius: 0.02 }],
383
+ colliders: [{ offset: [0.4, -1, 0], radius: 0.25 }],
384
+ });
385
+ for (let frame = 0; frame < 60; frame++) {
386
+ const local = Float64Array.from([...bone(0), ...bone(-1), ...bone(-1)]); // this frame's animated pose
387
+ local[0] = frame * 0.02;
388
+ springs.stepPose({ parents, local }, 1 / 60); // rotations swing in place
389
+ }
390
+ ```
391
+
392
+ On a character, joints and collider nodes are glTF node indices; find them by name:
393
+
394
+ ```ts
395
+ import {Engine} from 'margoengine/core';
396
+ import {loadGLTF} from 'margoengine/gltf/pbr';
397
+ import {Animation} from 'margoengine/animation';
398
+ import {Animator} from 'margoengine/animator';
399
+ import { detectSkeleton, humanoidBones } from 'margoengine/rigging/retarget';
400
+ import { addSpringBones } from 'margoengine/rigging/springs';
401
+ const engine = await Engine.create(document.querySelector('canvas')!);
402
+ const model = await loadGLTF(engine, '/character.glb');
403
+ const animator = Animator.attach(Animation.attach(model), {initial: 'walk', states: {walk: 'Walk'}});
404
+ const names = model.asset.doc.nodes!.map((n) => n.name ?? '');
405
+ const bone = humanoidBones(names, detectSkeleton(names)?.preset ?? 'humanoid'); // head, chest and the rest
406
+ const node = (name: string) => names.indexOf(name); // the model's own extra bones
407
+ const head = bone.get('head')!;
408
+ const hair = addSpringBones(animator, {
409
+ chains: [
410
+ { joints: [node('Hair1'), node('Hair2'), node('Hair3')], stiffness: 1.5, drag: 0.4, gravity: 0.3, center: head }, // measured against the head
411
+ { joints: [node('LeftEarring')], tail: [0, -0.06, 0], stiffness: 0.8 }, // an earring: one joint and an end point
412
+ ],
413
+ colliders: [{ node: head, radius: 0.09 }, { node: bone.get('upperChest')!, tail: [0, 0.3, 0], radius: 0.12 }],
414
+ jiggles: [{ joint: node('Belly'), frequency: 3, damping: 0.3, limit: 0.03 }], // lags and wobbles in place
415
+ });
416
+ hair.reset(); // after moving the character by hand
417
+ hair[Symbol.dispose]();
418
+ ```
419
+
420
+ `options` is kept and read every frame, so settings change live. `SpringBones` runs without an engine: `stepPose` for plain data, `stepSkeleton` for a `Skeleton` from `@margoengine/animation`, `step` for your own bones.
421
+
422
+ | Chain field | Default | Meaning |
423
+ | --- | --- | --- |
424
+ | `joints` | required | Bones root to tip, each an ancestor of the next (up to 256). Bones left out ride along. The last is only a tail and does not turn, unless `tail` is set. A joint belongs to one chain. |
425
+ | `stiffness` | `1` | Pull back toward the animated direction, 0 or more. |
426
+ | `drag` | `0.5` | Share of the speed lost each 1/60 s, 0 to 1. |
427
+ | `gravity` | `0` | Strength of gravity on the tail. |
428
+ | `gravityDirection` | `[0, -1, 0]` | World direction of gravity. |
429
+ | `radius` | `0` | Size of the tail against colliders. |
430
+ | `settings` | none | Any of the five above per joint, by position in `joints`. |
431
+ | `tail` | none | End point past the last joint, in its local space, so that joint turns too. |
432
+ | `center` | none | `joints[0]` or an ancestor: motion of this bone does not swing the chain. Gravity stays in world space. |
433
+ | `colliders` | all | Indices into `options.colliders` this chain hits. |
434
+
435
+ | Option | Default | Meaning |
436
+ | --- | --- | --- |
437
+ | `chains`, `colliders`, `jiggles` | none | What to simulate. A collider is `{node, offset, tail, radius}`: a sphere, or a capsule when `tail` is set; with no `node` its points are world points. |
438
+ | `force` | none | Extra world force on every tail, such as wind, in `gravity` units. |
439
+ | `weight` | `1` | Blend from the animated pose (0) to the simulated one (1). |
440
+ | `teleportSpeed` | `100` | World speed in units a second above which a chain restarts from the animated pose instead of whipping across the gap. |
441
+
442
+ | Jiggle field | Default | Meaning |
443
+ | --- | --- | --- |
444
+ | `joint` | required | The bone. Its position trails the animated one on a damped spring, solved exactly each step (stable at any frequency and damping); steady motion leaves no lag. |
445
+ | `frequency` | `4` | Wobbles a second, up to 15. |
446
+ | `damping` | `0.35` | Share of critical damping: 1 stops without a wobble. |
447
+ | `limit` | `0.05` | Farthest the bone strays from its animated position. |
448
+ | `amount` | `1` | Share of the movement shown. |
449
+
450
+ A model scaled up swings the same, only larger: forces, `radius`, collider radii and `limit` follow the bones' world scale. Joints and their ancestors need positive scales; a scale a little off uniform, as exported rigs often have, reads as its mean. A `delta` of 0 holds the motion, and a long frame takes at most 8 steps of 1/60 s, so a stall slows the swing and cannot blow it up. Spring bones run after other solvers in the order they were added.
451
+
452
+ ## VRM avatars (`margoengine/rigging/vrm`)
453
+
454
+ VRM 1.0 avatars from any tool that writes them. `readVRM` takes a `.vrm` file's bytes and gives the avatar's data; `addVRM` puts it to work on the model: the 18 preset expressions and any custom ones, the look-at, the spring bones and a mouth and blink channel for your own lip sync. `writeVRM` puts an avatar back into a `.vrm`, and `createVRM` makes one from any rigged glTF.
455
+
456
+ ```ts
457
+ import { loadGLTF } from 'margoengine/gltf/pbr';
458
+ import { Animation } from 'margoengine/animation';
459
+ import { addVRM, readVRM } from 'margoengine/rigging/vrm';
460
+ import {Engine} from 'margoengine/core';
461
+ const engine = await Engine.create(document.querySelector('canvas')!);
462
+ const url = 'Seed-san.vrm';
463
+ const avatar = readVRM(new Uint8Array(await (await fetch(url)).arrayBuffer()));
464
+ console.log(avatar.meta.name, avatar.meta.authors, avatar.meta.commercialUsage); // what its author allows
465
+
466
+ const model = await loadGLTF(engine, url); // a .vrm is a binary glTF
467
+ const animation = new Animation(model);
468
+ const vrm = addVRM(animation, avatar);
469
+ vrm.expressions.set('happy', 1); // 0 to 1, shown from the next frame
470
+ vrm.lookAtTarget = [0, 1.5, 2]; // the eyes follow this world point
471
+ console.log(vrm.unsupported); // what this renderer cannot show, by expression
472
+ vrm[Symbol.dispose](); // back to neutral
473
+ ```
474
+
475
+ Read `avatar.meta` before you use someone's avatar: it is the author's own statement of what may be done with it (`avatarPermission`, `commercialUsage`, `allowRedistribution` and the rest), and the licence named in `licenseUrl` applies. Margo reads it and keeps it; it enforces nothing.
476
+
477
+ Pass an `Animator` from `margoengine/animator` as `animator` and the avatar runs inside its frame, after your clips, in the order the specification recommends: look-at, expressions, then spring bones. With none, it runs by itself as an engine plugin. `update(delta)` runs one frame by hand. Dispose the avatar before its `Animation`; disposing the model stops the avatar by itself.
478
+
479
+ ```ts
480
+ import { splitGLB } from 'margoengine/exporters';
481
+ import { detectSkeleton, humanoidBones } from 'margoengine/rigging/retarget';
482
+ import { createVRM, readVRM, writeVRM } from 'margoengine/rigging/vrm';
483
+ const rigged = new Uint8Array(await (await fetch('/rigged.glb')).arrayBuffer()); // any .glb with a skin
484
+ const { json } = splitGLB(rigged);
485
+ const nodes = json.nodes as { name?: string; mesh?: number }[],
486
+ meshes = json.meshes as { extras?: { targetNames?: string[] } }[];
487
+ const names = nodes.map((n) => n.name ?? '');
488
+ const face = names.indexOf('Face'); // the node of the mesh with the face shapes
489
+ const blink = meshes[nodes[face].mesh!].extras?.targetNames?.indexOf('eyeBlinkLeft') ?? -1;
490
+ const out = writeVRM(
491
+ rigged,
492
+ createVRM({
493
+ name: 'Scout',
494
+ authors: ['Sam'],
495
+ bones: humanoidBones(names, detectSkeleton(names)?.preset ?? 'humanoid'), // every humanoid bone the names give
496
+ expressions: { preset: { blink: { morphTargetBinds: [{ node: face, index: blink, weight: 1 }] } } },
497
+ }),
498
+ ); // a .vrm
499
+ console.log(readVRM(out).humanoid.humanBones.head?.node === names.indexOf('mixamorig:Head')); // true for a Mixamo rig
500
+ ```
501
+
502
+ | Name | Meaning |
503
+ | --- | --- |
504
+ | `readVRM(bytes or doc)` | The avatar: `meta`, `humanoid`, `expressions`, `lookAt`, `firstPerson`, `springBone`, as the file's own JSON, so nothing is lost. Refuses VRM 0.x and a file with no `VRMC_vrm`. |
505
+ | `checkVRM(avatar, doc)` | Problems as strings: a missing required bone, a node or morph index out of range. Empty when sound. |
506
+ | `writeVRM(glb, avatar)` | A new `.vrm`: the glTF's own bytes and extensions kept, with the avatar in place of any earlier one. |
507
+ | `createVRM(options)` | An avatar from a bone map; `licenseUrl` defaults to VRM Public License 1.0, `lookAt`, `expressions` and `springBone` are optional. |
508
+ | `vrmSprings(avatar)` | The file's spring bones as `addSpringBones` options. |
509
+ | `VRMExpressions` | The expression rules with no engine: `set`, `get`, `resolve`, `evaluate`, `names`; `isBinary` and the `override*` blocks act as the specification says. |
510
+ | `vrmGaze`, `vrmEyeAngles`, `vrmLookWeights` | The look-at maths: yaw and pitch from the head to a point, then bone angles or expression weights through the file's range maps. |
511
+
512
+ | `addVRM` option | Default | Meaning |
513
+ | --- | --- | --- |
514
+ | `animator` | none | Run inside this `Animator`; with none, run as an engine plugin. |
515
+ | `springs` | `true` | Run the file's spring bones. |
516
+ | `mouth`, `blink`, `lookAt` | none | Custom expression names that an expression's `overrideMouth`, `overrideBlink` or `overrideLookAt` also holds back, beside the presets the specification names. |
517
+
518
+ Expressions drive morph targets, `color` and `emissionColor` of materials, and texture moves. The other colour binds exist only in MToon and land in `unsupported`, because Margo draws MToon materials by their plain glTF fallback: no toon shading or outlines. `VRMC_node_constraint` data stays in the file through `writeVRM` and does not run.
519
+
520
+ With `MToon` from `@margoengine/rigging/mtoon` attached, MToon UV animation is computed in float64 and sent as small phases, so a scrolling or turning texture keeps its 1/60 s steps after days of running; [details and limits](../../docs/rigging-mtoon.md).
521
+
522
+ ## VRM first person (`margoengine/rigging/vrm-first-person`)
523
+
524
+ A VRM 1.0 file says which meshes the wearer sees through their own eyes (`firstPerson.meshAnnotations`): `thirdPersonOnly` meshes (the head, the hair) stay out of the first-person view, `firstPersonOnly` meshes appear only in it, `both` show everywhere, and `auto` (also a mesh with no annotation) means "cut the head off for me". `loadVRM` makes that cut before the model loads: each `auto` skinned mesh is split into the triangles weighted to the head bone or a bone below it, drawn in third person only, and the rest. `addVRMFirstPerson` then puts each mesh on a render layer and gives you the two view masks, so every camera, mirror, probe and XR eye filters the avatar the way the file asks.
525
+
526
+ ```ts
527
+ import { Engine } from 'margoengine/core';
528
+ import { Reflector } from 'margoengine/environment/reflector';
529
+ import { addVRMFirstPerson, loadVRM } from 'margoengine/rigging/vrm-first-person';
530
+ const engine = await Engine.create(document.querySelector('canvas')!);
531
+ const model = await loadVRM(engine, 'Seed-san.vrm'); // `auto` meshes come back split into head and body
532
+ const fp = addVRMFirstPerson(model, { firstPersonCameras: [engine.camera] }); // this camera looks through the eyes
533
+ engine.render({ delta: 0 }); // world matrices, so viewpoint() reads the posed head
534
+ const eye = fp.viewpoint();
535
+ engine.camera.position = eye;
536
+ engine.camera.target = [eye[0], eye[1], eye[2] + 1]; // a VRM 1.0 avatar faces +Z
537
+ const mirror = Reflector.attach(engine, { width: 2, height: 2, layers: fp.thirdPersonLayers }); // the mirror shows the head
538
+ mirror.node.setPosition([0, eye[1], 1]).setRotation([0, Math.PI, 0]);
539
+ engine.start();
540
+ // In a headset: xr.layers = fp.firstPersonLayers (margoengine/xr) hides the head in both eyes.
541
+ ```
542
+
543
+ | Name | Meaning |
544
+ | --- | --- |
545
+ | `loadVRM(engine, url or bytes, options)` | Fetches (at most `maxDownloadBytes`, 64 MiB by default), splits and loads a VRM 1.0 file as a gltf/pbr `PBRModel`. Takes gltf/pbr's load options, `threshold` and `signal`. For VRM 0.x, run `convertVRM0Bytes` from `margoengine/rigging/vrm0` first. |
546
+ | `splitVRMFirstPerson(glb, options)` | The split alone, bytes in and bytes out: no `auto` left, every other byte of the file kept. A second split changes nothing. |
547
+ | `addVRMFirstPerson(model, options)` | Applies the annotations through render layers and returns the handle below. Throws a coded `state` error when a mesh is still `auto` (load it with `loadVRM`). |
548
+ | `fp.firstPersonLayers`, `fp.thirdPersonLayers` | View masks: every layer but the third-person one, and every layer but the first-person one. Give the second to any mirror, probe or outside camera. |
549
+ | `fp.viewpoint(out?)` | World position of the eyes: `lookAt.offsetFromHeadBone` on the head bone. |
550
+ | `fp.meshAnnotations` | Each mesh node and the type it resolved to. |
551
+ | `fp.dispose()` | Puts every mask back as it was (also `using`). |
552
+
553
+ | Option | Default | Meaning |
554
+ | --- | --- | --- |
555
+ | `threshold` (`loadVRM`, `splitVRMFirstPerson`) | `0` | Skin weight a vertex must pass on the head to count as head. 0 is the specification's rule; raise it when a stray head weight pulls collar triangles out of first person. |
556
+ | `firstPersonOnlyLayer`, `thirdPersonOnlyLayer` | `29`, `30` | The layers the two kinds of mesh go on (`FIRST_PERSON_ONLY_LAYER`, `THIRD_PERSON_ONLY_LAYER`). |
557
+ | `firstPersonCameras` | none | Cameras that get `firstPersonLayers`. |
558
+ | `thirdPersonCameras` | the engine camera | Cameras that get `thirdPersonLayers`, only when the file has a `firstPersonOnly` mesh. |
559
+
560
+ A camera, mirror or probe with no mask draws every layer, so it shows `firstPersonOnly` meshes until you give it `fp.thirdPersonLayers`. Shadows are not filtered: the avatar casts its whole shadow, head included, in every view, which is what you want when you look down at your own shadow. Draco and meshopt compressed meshes are read through `margoengine/decoders`, loaded only for a file that needs them. Limits and the measured GPU checks: [VRM first person](../../docs/rigging-vrm-first-person.md).
561
+
562
+ ## Voxel weights (`margoengine/rigging/voxel-weights`)
563
+
564
+ Automatic skin weights for meshes bone heat cannot solve: holes, doubled or flipped faces, non-manifold edges, loose parts, and shells inside shells, such as a coat modelled over a body. The mesh is voxelized, the bones are burned into the grid, and each bone's distance is measured through the solid. Two limbs close together stay apart as long as the grid can see the gap.
565
+
566
+ ```ts
567
+ import type { RigJoint } from 'margoengine/rigging';
568
+ import { voxelWeights } from 'margoengine/rigging/voxel-weights';
569
+
570
+ const positions = new Float32Array([0, 0, 0.1, 0.1, 0, -0.1, -0.1, 0, -0.1, 0, 2, 0]);
571
+ const joints: RigJoint[] = [
572
+ { name: 'base', parent: -1, position: [0, 0, 0] },
573
+ { name: 'tip', parent: 0, position: [0, 2, 0] },
574
+ ];
575
+ const { weights, unreached } = await voxelWeights(
576
+ { positions, indices: [0, 1, 3, 1, 2, 3, 2, 0, 3] }, // the bottom face is missing
577
+ joints,
578
+ );
579
+ console.log(weights.toInfluences(), unreached); // JOINTS_0 and WEIGHTS_0
580
+ ```
581
+
582
+ | Option | Default | Meaning |
583
+ | --- | --- | --- |
584
+ | `resolution` | `96` | Voxels along the longest side, 8 to 512. Parts closer than about one voxel join. |
585
+ | `skip` | none | Joints that move no vertices, such as a root at the feet. |
586
+ | `falloff`, `curve` | `4`, `0.75` | The weight of a bone at distance d voxels is `((1 - curve) * d + curve * d * d) ** -falloff`: a larger `falloff` keeps vertices closer to their nearest bone. |
587
+ | `influences` | `4` | Most bones per vertex. |
588
+ | `closing` | `0` | Closes gaps up to this many voxels before filling. Parts closer than twice this fuse. |
589
+ | `weld` | `1e-6` | Welding tolerance as a fraction of the mesh's size. |
590
+ | `signal` | none | Cancels the solve between bones. |
591
+
592
+ The result also gives `grid`, `voxels` and `unreached`: vertices no bone reached through the solid, such as a hat that floats clear of the head, which take the same falloff from straight-line distances. Where a hole lets the outside into the mesh, the fill grows from the bones through voxels with surface on at least four of the six axis directions. Pick bone heat for clean, closed meshes: it is faster and its weights flow along the surface.
593
+
594
+ ## Automatic rig (`margoengine/rigging/autorig`)
595
+
596
+ Places a humanoid skeleton inside a mesh nobody rigged, then weights it. Give it a figure standing in a T or A pose, in any units, turned any way about `up`; the mesh may be broken or in many parts. Joints carry VRM humanoid names, so `margoengine/rigging/retarget` reads them as they are, and `joints` and `weights` go straight to `margoengine/exporters/skin`. Here the figure is made of boxes, so the example runs by itself:
597
+
598
+ ```ts
599
+ import { autoRig } from 'margoengine/rigging/autorig';
600
+
601
+ const positions: number[] = [];
602
+ const indices: number[] = [];
603
+ const box = (x0: number, y0: number, z0: number, x1: number, y1: number, z1: number) => {
604
+ const first = positions.length / 3;
605
+ for (const z of [z0, z1]) for (const y of [y0, y1]) for (const x of [x0, x1]) positions.push(x, y, z);
606
+ for (const [a, b, c, d] of [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]])
607
+ indices.push(first + a, first + b, first + c, first + a, first + c, first + d);
608
+ };
609
+ box(-0.17, 0.85, -0.1, 0.17, 1.42, 0.1); // trunk
610
+ box(-0.06, 1.4, -0.05, 0.06, 1.5, 0.05); // neck
611
+ box(-0.1, 1.48, -0.1, 0.1, 1.74, 0.1); // head
612
+ for (const side of [-1, 1]) {
613
+ box(side * 0.1 - 0.06, 0.05, -0.06, side * 0.1 + 0.06, 0.9, 0.06); // leg
614
+ box(side * 0.1 - 0.06, 0, -0.06, side * 0.1 + 0.06, 0.08, 0.2); // foot
615
+ const [near, far] = [side * 0.15, side * 0.85].sort((p, q) => p - q);
616
+ box(near, 1.32, -0.04, far, 1.4, 0.04); // arm
617
+ }
618
+
619
+ const rig = await autoRig({ positions, indices });
620
+ console.log(rig.joints[rig.humanoid.leftHand].position, rig.forward); // on +x, facing +z
621
+ console.log(rig.weights?.toInfluences()); // JOINTS_0 and WEIGHTS_0
622
+ ```
623
+
624
+ | Option | Default | Meaning |
625
+ | --- | --- | --- |
626
+ | `resolution` | `128` | Voxels along the longest side, 32 to 384. Thin arms need more. |
627
+ | `up` | `[0, 1, 0]` | The mesh's up direction. |
628
+ | `forward` | read from the feet | The way the figure faces, which says which side is its left. A forward along `up` is a `RangeError`. |
629
+ | `closing` | `1` | Closes gaps up to this many voxels before filling, joining parts that nearly touch. |
630
+ | `symmetric` | `true` | Evens left and right joints across the body's centre when they already nearly agree. |
631
+ | `weights` | `'voxel'` | `'voxel'` weights with `voxelWeights`; with `'none'`, pass `joints` to `boneHeatWeights` or any other solver. |
632
+ | `weld` | `1e-6` | Welding tolerance as a fraction of the mesh's size. |
633
+ | `signal` | none | Cancels the fit between stages and the weights between bones. |
634
+
635
+ The result gives `joints`, `humanoid` (each bone's index, by name), `pose` (the same skeleton as local transforms), `weights`, `forward`, `facingFound` and `voxels`. When `facingFound` is false the feet showed no clear front, +z was assumed and left and right may be swapped: pass `forward`. A figure with no head, two feet and two hands to find fails with a `MargoError` of code `failed`. Fingers are not placed. On real files the joints land about 2 to 4 percent of the figure's height from where people put them; the limits are in [docs/limits.md](../../docs/limits.md).
636
+
637
+ ## Corrective shapes (`margoengine/rigging/correctives`)
638
+
639
+ Linear skinning collapses elbows, knees and shoulders. A corrective is a blend shape sculpted to fix that, and this entry drives it from the joint's rotation: full at the pose you sculpted it for, off at rest. `addCorrectives` runs after the pose and after any IK added before it.
640
+
641
+ ```ts
642
+ import {Engine} from 'margoengine/core';
643
+ import {loadGLTF} from 'margoengine/gltf/pbr';
644
+ import {Animation} from 'margoengine/animation';
645
+ import {Animator} from 'margoengine/animator';
646
+ import { addCorrectives } from 'margoengine/rigging/correctives';
647
+ import { detectSkeleton, humanoidBones } from 'margoengine/rigging/retarget';
648
+ const engine = await Engine.create(document.querySelector('canvas')!);
649
+ const model = await loadGLTF(engine, '/character.glb');
650
+ const animator = Animator.attach(Animation.attach(model), {initial: 'walk', states: {walk: 'Walk'}});
651
+ // The mesh node, its sculpted morph target and the elbow joint, all by name.
652
+ const doc = model.asset.doc,
653
+ names = doc.nodes!.map((n) => n.name ?? '');
654
+ const body = names.indexOf('Body');
655
+ const target = (doc.meshes![doc.nodes![body].mesh!].extras as { targetNames: string[] }).targetNames.indexOf('LeftElbowFix');
656
+ const joint = humanoidBones(names, detectSkeleton(names)?.preset ?? 'humanoid').get('leftLowerArm')!;
657
+ const s = Math.sin(1);
658
+ const elbow = addCorrectives(animator, {
659
+ shapes: [{ node: body, target, joint, pose: [s, 0, 0, Math.cos(1)], curve: 'smooth' }], // full at two radians
660
+ });
661
+ elbow.dispose(); // shapes back to 0
662
+ ```
663
+
664
+ A joint that swings every way, a shoulder, needs several sculpted poses. Give them as a pose space: each sample holds exactly its own weights, and rotations between them blend. Include the rest pose with zero weights, or the shapes stay on away from every sample.
665
+
666
+ ```ts
667
+ import { Correctives } from 'margoengine/rigging/correctives';
668
+
669
+ const r = Math.SQRT1_2;
670
+ const shoulder = new Correctives({
671
+ spaces: [
672
+ {
673
+ joint: 7,
674
+ shapes: [
675
+ { node: 2, target: 4 }, // arm raised
676
+ { node: 2, target: 5 }, // arm forward
677
+ ],
678
+ samples: [
679
+ { rotation: [0, 0, 0, 1], weights: [0, 0] },
680
+ { rotation: [0, 0, r, r], weights: [1, 0] },
681
+ { rotation: [r, 0, 0, r], weights: [0, 1] },
682
+ ],
683
+ },
684
+ ],
685
+ });
686
+ console.log(shoulder.evaluate(() => [0, 0, r, r])); // [{ node: 2, target: 4, weight: 1 }, { node: 2, target: 5, weight: 0 }]
687
+ ```
688
+
689
+ | Shape field | Default | Meaning |
690
+ | --- | --- | --- |
691
+ | `node`, `target` | required | The mesh's glTF node and the morph target. |
692
+ | `joint` | required | The bone that drives it. |
693
+ | `pose` | required | The joint's local rotation where the shape is full. |
694
+ | `rest` | the joint's rest | The joint's local rotation where the shape is off. |
695
+ | `cone` | none | Radians off the line from `rest` to `pose` at which the shape has faded out. With none only the bend along that line counts, so a hinge's twist does nothing. |
696
+ | `start` | `0` | Reading where the shape starts: `0.5` keeps it off for the first half of the bend. |
697
+ | `curve` | `'linear'` | `'smooth'` eases in and out. |
698
+ | `amount` | `1` | Weight at full bend. |
699
+
700
+ Shapes on one target add up, then clamp to 0 to 1. `width` on a pose space sets the Gaussian width in radians; the default is the mean angle from each sample to its nearest neighbour. Pose spaces are solved once when made. `Correctives` is plain data, so `evaluate(rotationOf, restOf)` runs with no engine. A driven morph target belongs to the correctives: a clip's track on it is overwritten.
701
+
702
+ ## Weight transfer (`margoengine/rigging/transfer`)
703
+
704
+ Copies skin weights from a rigged mesh to clothing, or to any mesh around it. Each vertex takes the weights at the closest point of the source's surface, read across that triangle. A match counts only when it is near and the two surfaces lie alike, so a sleeve vertex next to the torso does not take the torso's weights; those vertices are filled in from the matched ones around them, over the target's own surface.
705
+
706
+ ```ts
707
+ import { WeightMap } from 'margoengine/rigging';
708
+ import { transferWeights } from 'margoengine/rigging/transfer';
709
+
710
+ // A rigged triangle with one bone per corner, and a smaller one 1 cm in front of it.
711
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);
712
+ const body = { positions, indices: [0, 1, 2], weights: new WeightMap(3, 3, [1, 0, 0, 0, 1, 0, 0, 0, 1]) };
713
+ const shirt = { positions: new Float32Array([0.1, 0.1, 0.01, 0.5, 0.1, 0.01, 0.1, 0.5, 0.01]), indices: [0, 1, 2] };
714
+ const { weights, matched, filled } = await transferWeights(body, shirt);
715
+ console.log(weights.toInfluences(), matched, filled);
716
+ ```
717
+
718
+ `weights` on the source is a `WeightMap`, or `{ joints, weights }` as JOINTS_0 and WEIGHTS_0 hold them. Both meshes share one space, so pose them alike first.
719
+
720
+ | Option | Default | Meaning |
721
+ | --- | --- | --- |
722
+ | `maxDistance` | `0.05` | Farthest a match may be, as a fraction of the source's size. |
723
+ | `maxAngle` | `60` | Largest angle between the two surfaces at a match, degrees. Either facing counts, because cloth is often one layer with its normals any way round. |
724
+ | `iterations` | `1000` | Most conjugate-gradient steps of the fill per bone; it stops once the harmonic system's residual is 1e-10 of where it started. |
725
+ | `threshold` | `1e-4` | Weights below this are dropped before renormalising. |
726
+ | `boneCount` | the source's | Bones in the result, for influences that do not use the last ones. |
727
+ | `weld` | `1e-6` | Welding tolerance of the target as a fraction of its size. |
728
+ | `signal` | none | Cancels the transfer. |
729
+
730
+ `matched` and `filled` count target points. A part of the target with no match at all, such as a hat clear of the head, keeps the closest weights as they are.
731
+
732
+ ## Face tracking (`margoengine/rigging/face`)
733
+
734
+ Puts a tracked face on a character. Face trackers report the same 52 values from 0 to 1, one per facial movement: Apple's ARKit, Google's MediaPipe Face Landmarker and Live Link Face all do. `addFace` reads a frame in any of their shapes, smooths it and drives the model's morph targets, found by name, or a VRM avatar's expressions.
735
+
736
+ ```ts
737
+ import { loadGLTF } from 'margoengine/gltf/pbr';
738
+ import { Animation } from 'margoengine/animation';
739
+ import { addFace } from 'margoengine/rigging/face';
740
+ import {Engine} from 'margoengine/core';
741
+ const engine = await Engine.create(document.querySelector('canvas')!);
742
+ const animation = new Animation(await loadGLTF(engine, 'character.glb'));
743
+ const face = addFace(animation, { mirror: true }); // a selfie camera: swap sides
744
+ console.log(face.matched, face.missing); // which of the 52 this model can show
745
+
746
+ // Call this with each tracker frame, at the tracker's own rate.
747
+ face.push({ jawOpen: 0.4, eyeBlinkLeft: 1 });
748
+ face.push(null); // tracking lost: back to neutral
749
+ face.dispose();
750
+ ```
751
+
752
+ A frame is a record of names to values, or a list of `{ categoryName, score }`, so MediaPipe's `result.faceBlendshapes[0].categories` goes straight in. Names are matched by `faceShapeOf`, which ignores case, separators and any prefix and knows `_L` and `_R`: `EyeBlinkLeft`, `eye_blink_left`, `eyeBlink_L` and `ARKit_eyeBlinkLeft` all read as `eyeBlinkLeft`. Model morph targets are read from `extras.targetNames` on every mesh, so head, teeth and lashes move together. For other names, pass `map`:
753
+
754
+ ```ts
755
+ import { addFace } from 'margoengine/rigging/face';
756
+ import { addVRM, readVRM } from 'margoengine/rigging/vrm';
757
+ import { Animation } from 'margoengine/animation';
758
+ import { loadGLTF } from 'margoengine/gltf/pbr';
759
+ import { Engine } from 'margoengine/core';
760
+ const engine = await Engine.create(document.querySelector('canvas')!);
761
+ const url = '/avatar.vrm';
762
+ const animation = Animation.attach(await loadGLTF(engine, url));
763
+ const avatar = addVRM(animation, readVRM(new Uint8Array(await (await fetch(url)).arrayBuffer())));
764
+ const byName = addFace(animation, { map: { jawOpen: 'Mouth_Open', eyeBlinkLeft: ['Blink_L', 'Lash_L'] } });
765
+ byName.dispose(); // one face per model: dispose it before adding another
766
+ addFace(animation, { vrm: avatar }); // or a VRM avatar: drives its preset expressions
767
+ ```
768
+
769
+ | `addFace` option | Default | Meaning |
770
+ | --- | --- | --- |
771
+ | `smoothing` | `0.05` | Time constant in seconds; 0 follows the tracker exactly. The same at any frame rate. |
772
+ | `gain` | `1` | Multiplies values before they clamp to 0 to 1: one number, or per shape. |
773
+ | `mirror` | `false` | Swaps left and right, for a mirrored camera. |
774
+ | `map` | none | Morph target names for shapes the names alone do not find. |
775
+ | `vrm` | none | Drive this avatar's expressions rather than morph targets. |
776
+ | `animator` | none | Run inside this `Animator`; with none, run as an engine plugin. |
777
+
778
+ `FaceMapper` is the same thing as plain data, with no engine: `push(frame)`, `update(delta)`, `get(shape)`, `values`. `vrmFaceExpressions(get)` gives the VRM presets: what both eyes share goes to `blink` and the rest to `blinkLeft` and `blinkRight`, the eyes' mean to the look presets, `jawOpen`, `mouthPucker`, `mouthFunnel`, the mouth's lower lip and stretch to `aa`, `ou`, `oh`, `ih`, `ee`, and smile, frown, brow and wide eyes to `happy`, `sad`, `angry` and `surprised`. No tracker value stands for `relaxed`. A driven morph target belongs to the face: a clip's track on it is overwritten. A model has one face at a time: a second `addFace` throws `MargoError` code `state` until the first is disposed.
779
+
780
+ ARKit is a trademark of Apple Inc. MediaPipe is a trademark of Google LLC. Live Link Face is a product of Epic Games, Inc. Margo is not affiliated with them. The 52 names are Apple's published `ARFaceAnchor.BlendShapeLocation` identifiers.
781
+
782
+ ## Retarget presets (`margoengine/rigging/retarget`)
783
+
784
+ Clips made for one skeleton play on another: `prepareRetarget(source, target)` recognises each rig's naming (Mixamo with any `mixamorig` prefix, Godot's humanoid profile, Roblox R15, MPFB (MakeHuman's default rig), Character Creator's CC3+ skeleton (`CC_Base_Hip`, `CC_Base_L_Upperarm`, ...; its twist and share bones stay at rest and follow their limb through the skin), the joints of `@margoengine/exporters/skin`'s `humanoidJoints()`, or the 55 humanoid bone names themselves), maps every target bone to its source bone, and by default turns the target's reference pose so each bone points the way the source's does at rest (an A-pose character driven by T-pose clips). Pass the result to `@margoengine/animation`'s `Retarget`:
785
+
786
+ ```ts
787
+ import { Animation, applyKeyframeClip } from 'margoengine/animation';
788
+ import { Retarget, retargetRig } from 'margoengine/animation/skeleton-utils';
789
+ import { createStage } from 'margoengine';
790
+ import { loadGLTF } from 'margoengine/gltf/pbr';
791
+ import { detectSkeleton, prepareRetarget } from 'margoengine/rigging/retarget';
792
+ const stage = await createStage('#viewport', { backend: 'webgpu' });
793
+ const [mixamoModel, godotHero] = await Promise.all(
794
+ ['/mixamo-walk.glb', '/godot-hero.glb'].map((url) => loadGLTF(stage.engine, url)),
795
+ );
796
+ const source = retargetRig(mixamoModel), target = retargetRig(godotHero);
797
+ console.log(detectSkeleton(source.names)); // { preset: 'mixamo', bones: (humanoid bones found) }, or null
798
+ const prepared = prepareRetarget(source, target); // or { from: 'mixamo', to: 'godot', alignRest: true }
799
+ console.log(prepared.from, prepared.to, prepared.hip, prepared.unmapped); // mixamo godot Hips [...]
800
+ const retarget = new Retarget(source, prepared.target, prepared); // names and hip come from prepared
801
+ const walk = retarget.clip({ animation: Animation.attach(mixamoModel), clip: 'Walk' }, { fps: 30 });
802
+ applyKeyframeClip(walk, Animation.attach(godotHero), 0.5);
803
+ ```
804
+
805
+ | Option | Default | Meaning |
806
+ | --- | --- | --- |
807
+ | `from` | detected | The source's naming: `mixamo`, `godot`, `roblox`, `margo`, `mpfb`, `characterCreator`, `cmu` (CMU motion capture, as `@margoengine/loaders/mocap` `parseASF` names its joints) or `humanoid`. |
808
+ | `to` | detected | The target's naming. |
809
+ | `alignRest` | `true` | Turn the target's limbs (arms, hands, fingers, legs, feet) to point as the source's do at rest, so a T-pose source drives an A-pose target. The trunk, neck and collarbones keep the target's own rest: their directions are body layout, and aiming them along a motion-capture skeleton's would hunch and shrug the target. `false` keeps the target's whole rest pose (both rigs already stand alike). |
810
+
811
+ Rest alignment matches palm roll when both rigs map the wrist and the bases of the middle, index and little fingers. The wrist-to-middle direction sets the aim, and the direction across the knuckles sets the roll about that aim. With missing or collinear landmarks, the wrist uses the aim alone. This uses the humanoid landmarks from [VRM 1.0](https://github.com/vrm-c/vrm-specification/blob/master/specification/VRMC_vrm-1.0/humanoid.md) and draws on the use of anatomical frames in [*Semantics2Hands*, Ye et al. (2023)](https://arxiv.org/abs/2308.05920). Rest alignment prepares the skeleton for motion transfer. Maintaining hand or foot contact with a surface during a clip requires a separate constraint, as described in [*Retargeting Motion to New Characters*, Gleicher (1998)](https://graphics.cs.wisc.edu/Papers/1998/Gle98/).
812
+
813
+ Target bones with no source bone (a Godot `Root`, Roblox's `HumanoidRootPart`, fingers a source lacks) map to `''` and stay at rest; the humanoid bones among them are listed in `unmapped`. Roblox R15 has no neck, shoulders, toes or fingers, so clips from it leave those at rest; its `UpperTorso` maps to `spine`, which VRM 1.0 requires (chest is optional). Both rigs' model spaces must face the same way (glTF: +z forward, the figure's left at +x). `humanoidBones(names, preset)` gives the humanoid bone -> index map for your own tools, and `HUMANOID_BONES` lists every humanoid bone, parents first. An unrecognised naming throws a `RangeError` that asks for `from` or `to`.
814
+
815
+ ## Hands (`margoengine/rigging/hands`)
816
+
817
+ Named hand poses and a per-hand layer on an `@margoengine/animator` Animator. Body clips often carry flat or no finger
818
+ tracks, which read as dead hands; `addHands` blends a relaxed rest pose into every clip whose finger tracks stay under
819
+ 15 degrees on average, cross-faded with the Animator's own transitions, and leaves clips that key their fingers alone.
820
+ Each hand also takes keyed poses over time: `relaxed()`, `fist()`, `flat()`, `point()`, `pinch()`, `grip(diameter)`
821
+ (a power grip solved for a bar of that diameter in metres) or `handPose(table)` with your own joint angles. The
822
+ fingers are found through the retarget presets: Mixamo, VRM, MPFB (MakeHuman), Godot and the humanoid names.
823
+
824
+ ```ts
825
+ import { Animation } from 'margoengine/animation';
826
+ import { Animator } from 'margoengine/animator';
827
+ import { createStage } from 'margoengine';
828
+ import { loadGLTF } from 'margoengine/gltf/pbr';
829
+ import { addHands, grip, relaxed } from 'margoengine/rigging/hands';
830
+ const stage = await createStage('#viewport', { backend: 'webgpu' });
831
+ const model = await loadGLTF(stage.engine, '/mixamo-walk.glb');
832
+ const animator = Animator.attach(Animation.attach(model), { initial: 'walk', states: { walk: 'Walk' } });
833
+ const hands = addHands(animator); // relaxed fingers on every clip with flat finger tracks
834
+ console.log(hands.flat.left); // the clips whose flat fingers get the relaxed pose
835
+ hands.right.set(grip(0.035), { blend: 0.3 }); // close the right hand on a 35 mm rail over 0.3 s
836
+ hands.right.set(relaxed()); // and open it again later
837
+ hands.dispose(); // the clips play as authored again
838
+ ```
839
+
840
+ | Option | Default | What it does |
841
+ | --- | --- | --- |
842
+ | `left`, `right` | null | A pose each hand takes from the start; null leaves the hand to the clip (and the relaxed default). |
843
+ | `auto` | true | Blend `rest` into clips whose finger tracks stay under `threshold`. |
844
+ | `threshold` | 15 | Mean finger turn from rest, degrees, under which a clip counts as having flat fingers. |
845
+ | `rest` | `relaxed()` | The pose `auto` blends in. |
846
+ | `preset`, `bones` | detected | The rig's naming, or your own humanoid bone map, when detection cannot tell. |
847
+
848
+ `hands.left.keys` and `hands.right.keys` are plain `{time, pose, blend, weight}` lists, so a film can write them ahead
849
+ of time; with `hands.time` set the hands are a pure function of time and a seek gives what playing gives. A key with
850
+ `pose: null` hands the hand back to the clip over its blend. A digit a pose leaves out (the relaxed pose leaves out the
851
+ thumb, which a bind pose splays away from the palm) keeps the clip's own rotation and fades back to it.
852
+
853
+ The poses follow the grasp literature: fingers close joint by joint until they meet the bar, the tip joint at 2/3 of
854
+ the middle one (Rijpkema and Girard 1991), flexion grows from the index to the little finger (Santello, Flanders and
855
+ Soechting 1998), the grip and rest classes of Feix et al. 2016, and the rest posture's ranges after Wheatland et al.
856
+ 2015. Without the engine, `measureHands(rig)`, `poseTable(pose, hand)`, `handRotations(hand, table)` and
857
+ `gripFinger(lengths, diameter)` give the same numbers as plain data:
858
+
859
+ ```ts
860
+ import { gripFinger } from 'margoengine/rigging/hands';
861
+ const index = gripFinger([0.045, 0.026, 0.019], 0.035); // phalanx lengths in metres, a 35 mm bar
862
+ console.log(index.flex.map(Math.round), index.tipGap < 0.0005); // joint angles in degrees; the tip meets the bar
863
+ ```
864
+
865
+ ## Joint-space limits (`margoengine/rigging/joint-limits`)
866
+
867
+ Calibrate a hinge or swing-and-twist cone in the joint's local frame. `PoseJointLimits` projects packed local TRS
868
+ samples in place and preserves translations and scales. Use it after clip blending, or install the same projection as a
869
+ final Animator solver with `addPoseJointLimits(animator, limits)`. `redistributeJointTwist` can move excessive axial
870
+ rotation from a joint to its parent while preserving that joint's attachment and world orientation.
871
+
872
+ ```ts
873
+ import { PoseJointLimits } from 'margoengine/rigging/joint-limits';
874
+ const elbowPose = new Float64Array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]);
875
+ const limit = new PoseJointLimits(1, [
876
+ { joint: 0, neutral: [0, 0, 0, 1], limit: { type: 'hinge', axis: [0, 0, 1], min: 0, max: 2.35 } },
877
+ ]);
878
+ limit.apply(elbowPose);
879
+ console.log(elbowPose[6]);
880
+ ```
881
+
882
+ Author these axes for the skeleton's bind pose. For human limbs, the limits are per-rig constraints on permitted
883
+ motion rather than an estimate of anatomy from a bone name. See [Akhter and Black, Pose-Conditioned Joint Angle
884
+ Limits for 3D Human Pose Reconstruction (2015)](https://openaccess.thecvf.com/content_cvpr_2015/html/Akhter_Pose-Conditioned_Joint_Angle_2015_CVPR_paper.html)
885
+ and [Crisco et al., The Mechanical Axes of the Wrist Are Oriented Obliquely to the Anatomical Axes (2011)](https://pmc.ncbi.nlm.nih.gov/articles/PMC3016043/).
886
+
887
+ ## Swimming (`margoengine/rigging/swim`)
888
+
889
+ `createSwimRig` creates a head-to-tail chain in metres, with +Y up and +Z forward. A shark or reef fish sweeps laterally.
890
+ A dolphin or humpback flexes in the vertical plane and feathers its flukes. The ray profile supplies fin hinges by
891
+ default. Custom fin hinges may include a distal joint to introduce a delayed second bend. Use arbitrary
892
+ increasing station fractions to match measured landmark spacing, or choose a uniform segment count. Feed the local
893
+ TRS frames to your skin or bake quaternion keys into an animation. Update the caller's world path independently.
894
+
895
+ ```ts
896
+ import { createSwimRig, sampleSwimPose, swimCadence } from 'margoengine/rigging/swim';
897
+ const rig = createSwimRig('reef-shark', { length: 1.4, segments: 28 });
898
+ const phase = 0.25 * swimCadence(rig, 0.9);
899
+ const pose = sampleSwimPose(rig, { phase, effort: 0.8, turn: 0.1 });
900
+ console.log(rig.names.length, pose.length);
901
+ ```
902
+
903
+ With variable speed, accumulate phase across steps or sample a continuous phase curve. Fade effort to zero while
904
+ coasting. `swimCadence` estimates cruising frequency from speed and the profile's peak-to-peak tail or fin excursion.
905
+ The profiles are kinematic. They illustrate tail and fin mechanics and leave thrust, buoyancy, ecological behaviour
906
+ and model-specific skin weights to the caller. The travelling wave and constant-length spine draw on [Lighthill,
907
+ Large-Amplitude Elongated-Body Theory of Fish Locomotion (1971)](https://doi.org/10.1098/rspb.1971.0085),
908
+ [Wilga and Lauder, Function of the Heterocercal Tail in Sharks (2002)](https://bpb-us-e1.wpmucdn.com/sites.harvard.edu/dist/6/58/files/2022/03/WilgaLauder2002.pdf),
909
+ [Fish, Power Output and Propulsive Efficiency of Swimming Bottlenose Dolphins (1993)](https://doi.org/10.1242/jeb.185.1.179),
910
+ [Gazzola, Argentina and Mahadevan, Scaling Macroscopic Aquatic Locomotion (2014)](https://doi.org/10.1038/nphys3078),
911
+ [Smits, Undulatory and Oscillatory Swimming (2019)](https://doi.org/10.1017/jfm.2019.284),
912
+ [Segre et al., A Hydrodynamically Active Flipper-Stroke in Humpback Whales (2017)](https://pubmed.ncbi.nlm.nih.gov/28697357/),
913
+ and [Blevins and Lauder, Rajiform Locomotion in the Freshwater Stingray Potamotrygon orbignyi (2012)](https://bpb-us-e1.wpmucdn.com/sites.harvard.edu/dist/6/58/files/2022/03/Blevins.Lauder.2012.pdf).
914
+
915
+ ## Test character
916
+
917
+ The examples above run as written against an original test character the README runner makes
918
+ (`scripts/support/readme-humanoid.mjs`): a skinned figure of boxes with Mixamo-named bones (`/character.glb`,
919
+ `/rigged.glb`, `/mixamo-walk.glb`) or Godot humanoid-profile names (`/godot-hero.glb`), the 52 ARKit face shapes,
920
+ elbow and shoulder correctives, `Hair1` to `Hair3`, `LeftEarring` and `Belly` bones, and `Idle` and `Walk` clips;
921
+ `/avatar.vrm` is the same figure as a VRM 1.0 avatar with face shapes under other names (`Mouth_Open`, `Blink_L`,
922
+ `Blink_R`, `Lash_L`). Mixamo is a trademark of Adobe Inc. and Godot of the Godot Foundation; Margo is not affiliated
923
+ with them and uses only their published bone names.
924
+
925
+ ## Sources
926
+
927
+ Written clean room from the published papers listed in [docs/clean-room.md](../../docs/clean-room.md#rigging-margoenginerigging).
928
+
929
+ ## Film time
930
+
931
+ `MToon.advanceTime(delta)` moves the UV scroll and rotation clock (`mtoon.time`); the frame update runs it, so `seek` from `@margoengine/cutscene/seek` starts a film scene on the UV phase a continuous run shows.
932
+
933
+ ## Physical strand spring bones
934
+
935
+ The optional strand rig binds weighted bones to an SI fibre model with gravity, drag,
936
+ ground, and body contact. Load it through the existing `SpringAccess` or attach it after
937
+ an `Animator` pose with `addStrandSpringRig(animator, options)`.
938
+
939
+ ```ts
940
+ import { Engine } from 'margoengine';
941
+ import { StrandSpringRig } from 'margoengine/rigging/strand-springs';
942
+ import { springAccess } from 'margoengine/rigging/springs';
943
+
944
+ const engine = await Engine.create(document.querySelector('canvas')!);
945
+ const scalp = engine.createMesh().setPosition([0, 1.72, 0]);
946
+ const root = engine.createMesh().setParent(scalp).setPosition([0, 0, -0.12]);
947
+ const tip = engine.createMesh().setParent(root).setPosition([0, -0.24, -0.02]);
948
+ const rig = await StrandSpringRig.load(springAccess({ root: scalp, nodes: [scalp, root, tip] }), {
949
+ chains: [{ joints: [1, 2], radius: 0.006, dragWidth: 0.025 }],
950
+ });
951
+ scalp.setPosition([0.08, 1.72, 0]);
952
+ rig.advance(20); // 20 frames on the 240 Hz world clock
953
+ console.log(rig.solver.sample(0, 1).position);
954
+ ```
955
+
956
+ Pass the chain's ordered glTF indices in `joints`. A single attached earring or antenna
957
+ also takes a `tip` in its bone's local metres. Bone and ancestor transforms require positive
958
+ uniform scales. Each bundle can override its native radius, density, material and drag
959
+ width. The physics controls are the same as in the physics package's strand guide entry.
960
+ Set the same `wind` and `bed` fields as the surrounding scene. Each `colliders` entry can
961
+ be world-space or attached to a glTF node and moves with that node.
962
+
963
+ For a VRM avatar, get the authored joint and collider lists from `vrmSprings(avatar)`.
964
+ Use `addVRM(animation, avatar, { animator, springs: false })` with the physical attachment
965
+ and supply the matching collider list. The physical rig takes its own fibre properties
966
+ in metres and pascals. A pure per-chain `anchor(time)` gives exact replay across display
967
+ rates and a `seek(frame)` from the initial snapshot. The default live bone attachments
968
+ sample the current animation pose. To replay those, evaluate the same animation frames in
969
+ the same order. Call `dispose()` on the Animator attachment to stop its updates.