@needle-tools/three-mesh-effects 0.0.0-stage → 0.1.0-alpha.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -2
  3. package/build/deformation-runtime.js +2143 -0
  4. package/build/deformation-runtime.js.map +7 -0
  5. package/build/impostor-runtime-needle-engine.js +42 -0
  6. package/build/impostor-runtime-needle-engine.js.map +7 -0
  7. package/build/impostor-runtime.js +1333 -0
  8. package/build/impostor-runtime.js.map +7 -0
  9. package/build/internal/deformation/cloth-surface.js +288 -0
  10. package/build/internal/deformation/cloth-surface.js.map +7 -0
  11. package/build/internal/deformation/fur-surface.js +130 -0
  12. package/build/internal/deformation/fur-surface.js.map +7 -0
  13. package/build/internal/deformation/ik-constraints.js +44 -0
  14. package/build/internal/deformation/ik-constraints.js.map +7 -0
  15. package/build/internal/deformation/joints-json.js +197 -0
  16. package/build/internal/deformation/joints-json.js.map +7 -0
  17. package/build/internal/deformation/limits.js +16 -0
  18. package/build/internal/deformation/limits.js.map +7 -0
  19. package/build/internal/deformation/motion-settings.js +12 -0
  20. package/build/internal/deformation/motion-settings.js.map +7 -0
  21. package/build/internal/deformation/pin-cloth.js +196 -0
  22. package/build/internal/deformation/pin-cloth.js.map +7 -0
  23. package/build/internal/deformation/pin-ik.js +650 -0
  24. package/build/internal/deformation/pin-ik.js.map +7 -0
  25. package/build/internal/deformation/pin-types.js +12 -0
  26. package/build/internal/deformation/pin-types.js.map +7 -0
  27. package/build/internal/deformation/pin-wiggle.js +249 -0
  28. package/build/internal/deformation/pin-wiggle.js.map +7 -0
  29. package/build/internal/deformation/pose-slots.js +84 -0
  30. package/build/internal/deformation/pose-slots.js.map +7 -0
  31. package/build/internal/deformation/pose-timeline.js +210 -0
  32. package/build/internal/deformation/pose-timeline.js.map +7 -0
  33. package/build/internal/deformation/rig-drivers.js +48 -0
  34. package/build/internal/deformation/rig-drivers.js.map +7 -0
  35. package/build/internal/deformation/rig-extension.js +334 -0
  36. package/build/internal/deformation/rig-extension.js.map +7 -0
  37. package/build/internal/deformation/rig-runtime.js +2141 -0
  38. package/build/internal/deformation/rig-runtime.js.map +7 -0
  39. package/build/internal/deformation/wind.js +34 -0
  40. package/build/internal/deformation/wind.js.map +7 -0
  41. package/build/internal/impostor/impostor-metadata.js +77 -0
  42. package/build/internal/impostor/impostor-metadata.js.map +7 -0
  43. package/build/internal/impostor/impostor-node-material.js +1331 -0
  44. package/build/internal/impostor/impostor-node-material.js.map +7 -0
  45. package/build/internal/impostor/impostor-runtime-support.js +162 -0
  46. package/build/internal/impostor/impostor-runtime-support.js.map +7 -0
  47. package/build/internal/impostor/octahedral.js +232 -0
  48. package/build/internal/impostor/octahedral.js.map +7 -0
  49. package/build/internal/pixel-impostor/pixel-impostor-display.js +728 -0
  50. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +7 -0
  51. package/build/internal/pixel-impostor/pixel-impostor-metadata.js +71 -0
  52. package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +7 -0
  53. package/build/internal/pixel-impostor/pixel-impostor-runtime.js +150 -0
  54. package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +7 -0
  55. package/build/internal/rendering/skin-projection.js +4630 -0
  56. package/build/internal/rendering/skin-projection.js.map +7 -0
  57. package/build/internal/rendering/surface-query.js +4519 -0
  58. package/build/internal/rendering/surface-query.js.map +7 -0
  59. package/build/internal/rendering/wireframe.js +112 -0
  60. package/build/internal/rendering/wireframe.js.map +7 -0
  61. package/build/internal/rendering/wrap-preview-settings.js +126 -0
  62. package/build/internal/rendering/wrap-preview-settings.js.map +7 -0
  63. package/build/internal/rendering/wrap-preview.js +5610 -0
  64. package/build/internal/rendering/wrap-preview.js.map +7 -0
  65. package/build/internal/rendering/wrap-skin.js +4746 -0
  66. package/build/internal/rendering/wrap-skin.js.map +7 -0
  67. package/build/pixel-impostor-runtime.js +876 -0
  68. package/build/pixel-impostor-runtime.js.map +7 -0
  69. package/build/types/deformation/cloth-surface.d.ts +39 -0
  70. package/build/types/deformation/cloth-surface.js +1 -0
  71. package/build/types/deformation/fur-surface.d.ts +27 -0
  72. package/build/types/deformation/fur-surface.js +1 -0
  73. package/build/types/deformation/ik-constraints.d.ts +18 -0
  74. package/build/types/deformation/ik-constraints.js +1 -0
  75. package/build/types/deformation/joints-json.d.ts +17 -0
  76. package/build/types/deformation/joints-json.js +1 -0
  77. package/build/types/deformation/limits.d.ts +23 -0
  78. package/build/types/deformation/limits.js +1 -0
  79. package/build/types/deformation/motion-settings.d.ts +9 -0
  80. package/build/types/deformation/motion-settings.js +1 -0
  81. package/build/types/deformation/pin-cloth.d.ts +28 -0
  82. package/build/types/deformation/pin-cloth.js +1 -0
  83. package/build/types/deformation/pin-ik.d.ts +37 -0
  84. package/build/types/deformation/pin-ik.js +1 -0
  85. package/build/types/deformation/pin-types.d.ts +53 -0
  86. package/build/types/deformation/pin-types.js +1 -0
  87. package/build/types/deformation/pin-wiggle.d.ts +16 -0
  88. package/build/types/deformation/pin-wiggle.js +1 -0
  89. package/build/types/deformation/pose-slots.d.ts +41 -0
  90. package/build/types/deformation/pose-slots.js +1 -0
  91. package/build/types/deformation/pose-timeline.d.ts +65 -0
  92. package/build/types/deformation/pose-timeline.js +1 -0
  93. package/build/types/deformation/rig-drivers.d.ts +19 -0
  94. package/build/types/deformation/rig-drivers.js +1 -0
  95. package/build/types/deformation/rig-extension.d.ts +33 -0
  96. package/build/types/deformation/rig-extension.js +1 -0
  97. package/build/types/deformation/rig-runtime.d.ts +95 -0
  98. package/build/types/deformation/rig-runtime.js +1 -0
  99. package/build/types/deformation/wind.d.ts +16 -0
  100. package/build/types/deformation/wind.js +1 -0
  101. package/build/types/impostor/impostor-metadata.d.ts +61 -0
  102. package/build/types/impostor/impostor-metadata.js +1 -0
  103. package/build/types/impostor/impostor-node-material.d.ts +140 -0
  104. package/build/types/impostor/impostor-node-material.js +1 -0
  105. package/build/types/impostor/impostor-runtime-support.d.ts +52 -0
  106. package/build/types/impostor/impostor-runtime-support.js +1 -0
  107. package/build/types/impostor/octahedral.d.ts +84 -0
  108. package/build/types/impostor/octahedral.js +1 -0
  109. package/build/types/pixel-impostor/pixel-impostor-display.d.ts +48 -0
  110. package/build/types/pixel-impostor/pixel-impostor-display.js +1 -0
  111. package/build/types/pixel-impostor/pixel-impostor-metadata.d.ts +34 -0
  112. package/build/types/pixel-impostor/pixel-impostor-metadata.js +1 -0
  113. package/build/types/pixel-impostor/pixel-impostor-runtime.d.ts +18 -0
  114. package/build/types/pixel-impostor/pixel-impostor-runtime.js +1 -0
  115. package/build/types/public/deformation-runtime.d.ts +3 -0
  116. package/build/types/public/deformation-runtime.js +1 -0
  117. package/build/types/public/impostor-runtime-needle-engine.d.ts +31 -0
  118. package/build/types/public/impostor-runtime-needle-engine.js +1 -0
  119. package/build/types/public/impostor-runtime.d.ts +6 -0
  120. package/build/types/public/impostor-runtime.js +1 -0
  121. package/build/types/public/pixel-impostor-runtime.d.ts +3 -0
  122. package/build/types/public/pixel-impostor-runtime.js +1 -0
  123. package/build/types/public/wrap-effects.d.ts +4 -0
  124. package/build/types/public/wrap-effects.js +1 -0
  125. package/build/types/rendering/skin-projection.d.ts +44 -0
  126. package/build/types/rendering/skin-projection.js +1 -0
  127. package/build/types/rendering/surface-query.d.ts +66 -0
  128. package/build/types/rendering/surface-query.js +1 -0
  129. package/build/types/rendering/wireframe.d.ts +25 -0
  130. package/build/types/rendering/wireframe.js +1 -0
  131. package/build/types/rendering/wrap-preview-settings.d.ts +22 -0
  132. package/build/types/rendering/wrap-preview-settings.js +1 -0
  133. package/build/types/rendering/wrap-preview.d.ts +39 -0
  134. package/build/types/rendering/wrap-preview.js +1 -0
  135. package/build/types/rendering/wrap-skin.d.ts +14 -0
  136. package/build/types/rendering/wrap-skin.js +1 -0
  137. package/build/wrap-effects.js +5640 -0
  138. package/build/wrap-effects.js.map +7 -0
  139. package/package.json +105 -4
  140. package/src/deformation/cloth-surface.ts +223 -0
  141. package/src/deformation/fur-surface.ts +129 -0
  142. package/src/deformation/ik-constraints.ts +37 -0
  143. package/src/deformation/joints-json.ts +94 -0
  144. package/src/deformation/limits.ts +25 -0
  145. package/src/deformation/motion-settings.ts +9 -0
  146. package/src/deformation/pin-cloth.ts +149 -0
  147. package/src/deformation/pin-ik.ts +582 -0
  148. package/src/deformation/pin-types.ts +22 -0
  149. package/src/deformation/pin-wiggle.ts +119 -0
  150. package/src/deformation/pose-slots.ts +106 -0
  151. package/src/deformation/pose-timeline.ts +242 -0
  152. package/src/deformation/rig-drivers.ts +32 -0
  153. package/src/deformation/rig-extension.ts +87 -0
  154. package/src/deformation/rig-runtime.ts +416 -0
  155. package/src/deformation/wind.ts +36 -0
  156. package/src/impostor/impostor-metadata.js +137 -0
  157. package/src/impostor/impostor-node-material.js +1581 -0
  158. package/src/impostor/impostor-runtime-support.js +139 -0
  159. package/src/impostor/octahedral.js +280 -0
  160. package/src/pixel-impostor/pixel-impostor-display.js +794 -0
  161. package/src/pixel-impostor/pixel-impostor-metadata.js +74 -0
  162. package/src/pixel-impostor/pixel-impostor-runtime.js +78 -0
  163. package/src/public/deformation-runtime.ts +3 -0
  164. package/src/public/impostor-runtime-needle-engine.js +56 -0
  165. package/src/public/impostor-runtime.js +21 -0
  166. package/src/public/pixel-impostor-runtime.js +5 -0
  167. package/src/public/wrap-effects.js +21 -0
  168. package/src/rendering/skin-projection.js +113 -0
  169. package/src/rendering/surface-query.js +88 -0
  170. package/src/rendering/wireframe.js +115 -0
  171. package/src/rendering/wrap-preview-settings.js +123 -0
  172. package/src/rendering/wrap-preview.js +645 -0
  173. package/src/rendering/wrap-skin.js +109 -0
@@ -0,0 +1,119 @@
1
+ import { Quaternion, Vector3 } from 'three';
2
+ import { DEFAULT_FUR_DEPTH, type PinPose, type PinRecord } from './pin-types.js';
3
+ import type { PinParents } from './pin-types.js';
4
+ import { DEFAULT_MOTION, type MotionSettings } from './motion-settings.js';
5
+ import { ikChain } from './pin-ik.js';
6
+ import { windAcceleration } from './wind.js';
7
+
8
+ /** Disposable secondary motion. Never writes authored pins or history. */
9
+ export class PinWiggle {
10
+ private springs = new Map<string, { position: Vector3; velocity: Vector3; target:Vector3 }>();
11
+ private topology = '';
12
+ private lastPins: readonly PinRecord[] | null = null;
13
+ private lastParents: PinParents | null = null;
14
+ private awake = false;
15
+ private windTime = 0;
16
+ reset() { this.springs.clear(); this.topology = ''; this.lastPins = null; this.lastParents = null; this.awake = false; this.windTime = 0; }
17
+
18
+ step(pins: readonly PinRecord[], parents: PinParents, seconds: number, masses?:ReadonlyMap<string,number>, windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {
19
+ if (windStrength <= 0 && !this.awake && pins === this.lastPins && parents === this.lastParents) return {pins,active:false};
20
+ const topology = JSON.stringify(pins.map(p => [p.id,p.rest,p.rigidGroup,p.independent,p.guide,p.wiggle,p.fur,p.furDepth,p.motion,parents.get(p.id)]));
21
+ if (topology !== this.topology) { this.reset(); this.topology = topology; }
22
+ const groups = new Map<string, PinRecord[]>(), byId = new Map(pins.map(p => [p.id,p]));
23
+ const key = (p: PinRecord) => p.rigidGroup ?? p.id;
24
+ for (const pin of pins) { const group = groups.get(key(pin)) ?? []; group.push(pin); groups.set(key(pin),group); }
25
+ const settings = new Map<string,Readonly<MotionSettings>>();
26
+ const volumes=[...groups.values()].filter(group=>!group.every(p=>p.guide)).map(group=>Math.max(1e-9,masses?.get(group[0].id)??1)).sort((a,b)=>a-b);
27
+ const typicalVolume=volumes[Math.floor(volumes.length/2)]??1;
28
+ for (const pin of pins.filter(p=>p.wiggle && !p.guide)) {
29
+ const chain=ikChain(pins,parents,pin.id,masses);
30
+ for (const node of chain.length>1 ? chain.slice(1) : chain) if (!settings.has(key(node))) settings.set(key(node),pin.motion ?? DEFAULT_MOTION);
31
+ }
32
+ for (const pin of pins.filter(p=>p.wiggle && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);
33
+ // Fur belongs to the outer shell: unlike Wiggle it must not make the
34
+ // articulated core's ancestor chain into springs.
35
+ for (const pin of pins.filter(p=>p.fur && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);
36
+ const output = new Map<string, PinPose>(), visiting = new Set<string>();
37
+ let active = false;
38
+ // Exact underdamped spring integration, stable across variable frame times.
39
+ // Clamp background-tab gaps rather than simulating missed seconds.
40
+ const dt = Math.min(Math.max(seconds,0),.05);
41
+ this.windTime += dt;
42
+ const visit = (id: string) => {
43
+ const group = groups.get(id)!;
44
+ if (output.has(group[0].id)) return;
45
+ if (visiting.has(id)) { for (const pin of group) output.set(pin.id,pin.pose); return; }
46
+ visiting.add(id);
47
+ const parent = group.map(p => byId.get(parents.get(p.id) ?? '')).find(p => p && key(p) !== id);
48
+ if (parent) visit(key(parent));
49
+ const parentPose = parent ? output.get(parent.id)! : undefined;
50
+ const inherited = parent && parentPose ? new Quaternion().fromArray(parentPose.rotation).multiply(new Quaternion().fromArray(parent.pose.rotation).invert()) : new Quaternion();
51
+ const targets = group.map(pin => {
52
+ const position = new Vector3().fromArray(pin.pose.position);
53
+ if (!pin.ik && parent && parentPose) position.sub(new Vector3().fromArray(parent.pose.position)).applyQuaternion(inherited).add(new Vector3().fromArray(parentPose.position));
54
+ return { pin, position, rotation: (pin.ik ? new Quaternion() : inherited.clone()).multiply(new Quaternion().fromArray(pin.pose.rotation)) };
55
+ });
56
+ const center = targets.reduce((sum,p) => sum.add(p.position),new Vector3()).divideScalar(group.length);
57
+ let position = center, rotation = new Quaternion();
58
+ const motion=settings.get(id);
59
+ if (motion && !group.every(p=>p.guide) && !group.some(p=>p.ik)) {
60
+ const ratio=Math.max(.125,Math.min(8,(masses?.get(group[0].id)??typicalVolume)/typicalVolume));
61
+ const gain=motion.strength*Math.max(.25,Math.min(4,Math.pow(1/ratio,.5*motion.massInfluence)));
62
+ const frequency=motion.frequency*2*Math.PI, damping=Math.max(.05,Math.min(1,motion.damping*Math.pow(ratio,.25*motion.massInfluence)));
63
+ const decay = damping * frequency, oscillation = frequency * Math.sqrt(1-damping*damping);
64
+ const e = Math.exp(-decay*dt), c = Math.cos(oscillation*dt), s = oscillation > 1e-8 ? Math.sin(oscillation*dt)/oscillation : dt;
65
+ let spring = this.springs.get(id);
66
+ if (!spring) { spring = { position:center.clone(),velocity:new Vector3(),target:center.clone() }; this.springs.set(id,spring); }
67
+ spring.position.addScaledVector(center.clone().sub(spring.target),1-gain);spring.target.copy(center);
68
+ if(motion.strength===0){spring.position.copy(center);spring.velocity.set(0,0,0);}
69
+ else if (windStrength > 0) spring.velocity.addScaledVector(windAcceleration(this.windTime, windStrength,
70
+ parentPose ? Math.max(center.distanceTo(new Vector3().fromArray(parentPose.position)), 1e-3) : 1, center.toArray()), motion.strength * dt);
71
+ const offset = spring.position.clone().sub(center), velocity = spring.velocity.clone();
72
+ spring.position.copy(offset).multiplyScalar(c).addScaledVector(velocity.clone().addScaledVector(offset,decay),s).multiplyScalar(e).add(center);
73
+ spring.velocity.copy(velocity).multiplyScalar(c).sub(velocity.clone().multiplyScalar(decay).addScaledVector(offset,frequency*frequency).multiplyScalar(s)).multiplyScalar(e);
74
+ const fur = group.find(p=>p.fur), furDepth=fur?.furDepth??DEFAULT_FUR_DEPTH;
75
+ let radius = 1;
76
+ if (parentPose) {
77
+ const pivot = new Vector3().fromArray(parentPose.position), desired = center.clone().sub(pivot);
78
+ radius = desired.length();
79
+ const direction = spring.position.clone().sub(pivot);
80
+ if (radius > 1e-8) {
81
+ if (direction.lengthSq() < 1e-16) direction.copy(desired);
82
+ const length=direction.length();direction.divideScalar(length);
83
+ const coreRadius=radius*(1-furDepth),outerRadius=radius*(1+furDepth);
84
+ const projected=fur?Math.max(coreRadius,Math.min(outerRadius,length)):radius;
85
+ spring.position.copy(pivot).addScaledVector(direction,projected);
86
+ if(!fur||length<coreRadius||length>outerRadius)spring.velocity.addScaledVector(direction,-spring.velocity.dot(direction));
87
+ rotation.setFromUnitVectors(desired.normalize(),direction);
88
+ } else { spring.position.copy(center); spring.velocity.set(0,0,0); }
89
+ }
90
+ if (fur) {
91
+ const shell = Math.max(1e-4, radius) * furDepth;
92
+ if (shell === 0) { spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity(); }
93
+ const displacement = spring.position.clone().sub(center);
94
+ if (displacement.length() > shell) {
95
+ displacement.setLength(shell); spring.position.copy(center).add(displacement);
96
+ const outward=displacement.normalize();spring.velocity.addScaledVector(outward,-Math.max(0,spring.velocity.dot(outward)));
97
+ }
98
+ if(parentPose&&radius>1e-8){
99
+ const pivot=new Vector3().fromArray(parentPose.position),desired=center.clone().sub(pivot).normalize(),direction=spring.position.clone().sub(pivot).normalize();
100
+ rotation.setFromUnitVectors(desired,direction);
101
+ }
102
+ }
103
+ const epsilon = Math.max(radius,1e-3)*1e-5;
104
+ if (spring.position.distanceToSquared(center) < epsilon*epsilon && spring.velocity.lengthSq() < epsilon*epsilon*frequency*frequency) {
105
+ spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity();
106
+ } else active = true;
107
+ position = spring.position;
108
+ }
109
+ for (const target of targets) output.set(target.pin.id, {
110
+ position:target.position.sub(center).applyQuaternion(rotation).add(position).toArray(),
111
+ rotation:rotation.clone().multiply(target.rotation).normalize().toArray(),scale:target.pin.pose.scale,
112
+ });
113
+ visiting.delete(id);
114
+ };
115
+ for (const id of groups.keys()) visit(id);
116
+ this.lastPins = pins; this.lastParents = parents; this.awake = active;
117
+ return { pins: active ? pins.map(pin => ({...pin,pose:output.get(pin.id)!})) : pins, active };
118
+ }
119
+ }
@@ -0,0 +1,106 @@
1
+ import type { IKTarget, PinPose, PinRecord, Point, Rotation } from './pin-types.js';
2
+ import type { PinParents } from './pin-types.js';
3
+
4
+ export type StoredPose = { readonly id:string; readonly pose:PinPose; readonly ikTarget?:IKTarget; readonly authored?:boolean };
5
+ export type PoseSlot = { readonly slot:number; readonly poses:readonly StoredPose[] };
6
+ export const POSE_SLOTS=9;
7
+ /** Below any edit a hand can make, and far above the drift of composing one
8
+ * carried transform after another. */
9
+ const AUTHORED_EPSILON=1e-6;
10
+
11
+ export function capturePose(pins:readonly PinRecord[]):readonly StoredPose[]{
12
+ return pins.map(pin=>({id:pin.id,pose:pin.pose,...(pin.authored?{authored:true}:{}),...(pin.ikTarget?{ikTarget:pin.ikTarget}:{})}));
13
+ }
14
+
15
+ const restPoseOf=(rest:Point):PinPose=>({position:[rest[0],rest[1],rest[2]],rotation:[0,0,0,1],scale:[1,1,1]});
16
+
17
+ /** Where a pin lands when its parent carries it from rest. A parent's pose IS
18
+ * a similarity out of its own rest frame, so the child keeps its rest offset
19
+ * through that same rotation and scale — the transform hierarchy posing applies
20
+ * when a parent moves, written as one step from rest instead of accumulated. */
21
+ export function carriedPose(rest:Point,parentRest:Point,parent:PinPose):PinPose{
22
+ const [qx,qy,qz,qw]=parent.rotation;
23
+ const x=(rest[0]-parentRest[0])*parent.scale[0],y=(rest[1]-parentRest[1])*parent.scale[1],z=(rest[2]-parentRest[2])*parent.scale[2];
24
+ const tx=2*(qy*z-qz*y),ty=2*(qz*x-qx*z),tz=2*(qx*y-qy*x);
25
+ const position:Point=[parent.position[0]+x+qw*tx+(qy*tz-qz*ty),parent.position[1]+y+qw*ty+(qz*tx-qx*tz),parent.position[2]+z+qw*tz+(qx*ty-qy*tx)];
26
+ const rotation:Rotation=[qx,qy,qz,qw],scale:Point=[parent.scale[0],parent.scale[1],parent.scale[2]];
27
+ return {position,rotation,scale};
28
+ }
29
+
30
+ const samePose=(a:PinPose,b:PinPose)=>
31
+ a.position.every((v,i)=>Math.abs(v-b.position[i])<=AUTHORED_EPSILON)
32
+ && a.scale.every((v,i)=>Math.abs(v-b.scale[i])<=AUTHORED_EPSILON)
33
+ && a.rotation.every((v,i)=>Math.abs(v-b.rotation[i])<=AUTHORED_EPSILON);
34
+
35
+ /** What a slot would place a pin at if it said nothing about it. */
36
+ function inheritedPose(pin:PinRecord,parent:PinRecord|undefined,parentPose:PinPose|undefined):PinPose{
37
+ return parent&&parentPose?carriedPose(pin.rest,parent.rest,parentPose):restPoseOf(pin.rest);
38
+ }
39
+
40
+ /** Only the poses a slot actually authors. A pin the hierarchy already places
41
+ * is left out, so a point added while another pose was open keeps following its
42
+ * parent everywhere else until it is deliberately posed there. */
43
+ export function authoredPoses(pins:readonly PinRecord[],parents:PinParents=new Map()):readonly StoredPose[]{
44
+ const byId=new Map(pins.map(pin=>[pin.id,pin]));
45
+ return capturePose(pins).filter(stored=>{
46
+ const pin=byId.get(stored.id)!;
47
+ // Deliberate, or a goal, which is deliberate by definition.
48
+ if(pin.authored||pin.ikTarget)return true;
49
+ // Otherwise it is only kept because it could not be worked out again. A
50
+ // joint the IK solve swept along is not reproducible — the same goal
51
+ // reached from a different bend gives a different arm — so the value stays
52
+ // even though nobody posed it.
53
+ const parent=byId.get(parents.get(pin.id)??'');
54
+ return !samePose(pin.pose,inheritedPose(pin,parent,parent?.pose));
55
+ });
56
+ }
57
+
58
+ /** Active pins are the edit register. Inactive slots contain transforms only;
59
+ * topology, rest positions and settings remain shared and action-owned. A pin
60
+ * the slot does not mention inherits through the hierarchy rather than dropping
61
+ * to rest, which is what keeps a newly placed point attached to its parent in
62
+ * every other pose. */
63
+ export function resolvePose(pins:readonly PinRecord[],slot:PoseSlot,parents:PinParents=new Map()):readonly PinRecord[]{
64
+ const saved=new Map(slot.poses.map(p=>[p.id,p]));
65
+ const byId=new Map(pins.map(pin=>[pin.id,pin]));
66
+ const memo=new Map<string,PinPose>(),visiting=new Set<string>();
67
+ const poseOf=(pin:PinRecord):PinPose=>{
68
+ const cached=memo.get(pin.id);if(cached)return cached;
69
+ const stored=saved.get(pin.id);
70
+ let pose:PinPose;
71
+ if(stored)pose=stored.pose;
72
+ else{
73
+ const parentId=parents.get(pin.id);
74
+ // A parent already on the stack means a cycle in a derived hierarchy;
75
+ // rest is the only answer that terminates.
76
+ const parent=parentId&&!visiting.has(parentId)?byId.get(parentId):undefined;
77
+ if(!parent)pose=restPoseOf(pin.rest);
78
+ else{visiting.add(pin.id);pose=carriedPose(pin.rest,parent.rest,poseOf(parent));visiting.delete(pin.id);}
79
+ }
80
+ memo.set(pin.id,pose);return pose;
81
+ };
82
+ const resolved:PinRecord[]=pins.map(pin=>{
83
+ const stored=saved.get(pin.id),{ikTarget:_target,authored:_authored,...base}=pin;
84
+ return {...base,pose:poseOf(pin),...(stored?.authored?{authored:true}:{}),...(stored?.ikTarget?{ikTarget:stored.ikTarget}:{})};
85
+ });
86
+ // Group membership is shared. A group created after another pose was saved
87
+ // still has one rotation/uniform scale when that pose is opened. Positions
88
+ // stay authored; subsequent rigid edits preserve that arrangement.
89
+ return resolved.map(pin=>{
90
+ if(!pin.rigidGroup)return pin;const anchor=resolved.find(p=>p.rigidGroup===pin.rigidGroup)!;
91
+ return {...pin,pose:{...pin.pose,rotation:anchor.pose.rotation,scale:[anchor.pose.scale[0],anchor.pose.scale[0],anchor.pose.scale[0]]}};
92
+ });
93
+ }
94
+ export function definedPoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{
95
+ const slots=model.poseSlots.filter(p=>p.slot!==model.activePose);
96
+ return [...slots,...(model.activePose === 0 ? [] : [{slot:model.activePose,poses:capturePose(model.pins)}])].sort((a,b)=>a.slot-b.slot);
97
+ }
98
+
99
+ /** Pose 0 is derived from shared rest positions, never an editable pose slot. */
100
+ export function restPoseSlot(pins:readonly PinRecord[]):PoseSlot{
101
+ return {slot:0,poses:pins.map(pin=>({id:pin.id,pose:restPoseOf(pin.rest)}))};
102
+ }
103
+
104
+ export function playablePoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{
105
+ return [restPoseSlot(model.pins),...definedPoses(model)];
106
+ }
@@ -0,0 +1,242 @@
1
+ import type { PinPose, PinRecord, Point, Rotation } from './pin-types.js';
2
+ import type { PinParents } from './pin-types.js';
3
+
4
+ /** A pose slot's time controls its share of the loop around its own moment.
5
+ * The transition settles at each authored pose without holding a flat frame. */
6
+ export const DEFAULT_POSE_SECONDS = 0.7;
7
+ export const MIN_POSE_SECONDS = 0.05;
8
+ export const MAX_POSE_SECONDS = 60;
9
+ /** Travel kept below the longest pose so a slider dragged to the bottom can
10
+ * always be dragged further on the next pass, and shrinks back when shortened. */
11
+ export const POSE_TIME_HEADROOM = 0.5;
12
+
13
+ export type PoseTiming = { readonly slot: number; readonly seconds: number };
14
+ export type PoseTimeline = readonly PoseTiming[];
15
+
16
+ export function poseTimeScale(timeline: PoseTimeline): number {
17
+ return Math.max(DEFAULT_POSE_SECONDS, ...timeline.map(entry => entry.seconds)) + POSE_TIME_HEADROOM;
18
+ }
19
+
20
+ /** The strip reads downwards: zero at the top, the scale at the bottom, which
21
+ * is what makes "drag down" mean "stay longer". */
22
+ export function poseSecondsAt(offset: number, height: number, scale: number): number {
23
+ if (!(height > 0)) return MIN_POSE_SECONDS;
24
+ return Math.min(1, Math.max(0, offset / height)) * scale;
25
+ }
26
+
27
+ /** How far down the strip a time sits, as a percentage for the fill and handle. */
28
+ export function poseTimeOffset(seconds: number, scale: number): number {
29
+ if (!(scale > 0)) return 0;
30
+ return Math.min(100, Math.max(0, (seconds / scale) * 100));
31
+ }
32
+
33
+ export function poseLoopSeconds(timeline: PoseTimeline): number {
34
+ return timeline.reduce((total, entry) => total + Math.max(0, entry.seconds), 0);
35
+ }
36
+
37
+ /** The moment each pose is reached. Neighbours split the gap between them in
38
+ * proportion to their own times, which is what makes a time an ownership share
39
+ * rather than the length of one arc. */
40
+ export function poseKnots(timeline: PoseTimeline): number[] {
41
+ const knots = [0];
42
+ for (let i = 1; i < timeline.length; i++) {
43
+ knots.push(knots[i - 1] + (Math.max(0, timeline[i - 1].seconds) + Math.max(0, timeline[i].seconds)) / 2);
44
+ }
45
+ return knots;
46
+ }
47
+
48
+ /** How long one pass takes: the first pose's moment to the last one's.
49
+ * Looping playback adds the closing transition up to poseLoopSeconds. */
50
+ export function posePassSeconds(timeline: PoseTimeline): number {
51
+ const knots = poseKnots(timeline);
52
+ return knots.length ? knots[knots.length - 1] : 0;
53
+ }
54
+
55
+ export function poseTimeOf(timeline: PoseTimeline, slot: number): number {
56
+ const index = timeline.findIndex(entry => entry.slot === slot);
57
+ return index < 0 ? 0 : poseKnots(timeline)[index];
58
+ }
59
+
60
+ /** Septic: zero first, second AND third derivative at both ends, so a one-shot
61
+ * move away from rest and back to rest is G3 at the moment it starts and the
62
+ * moment it settles. A cubic smoothstep leaves a jerk step at both. */
63
+ export function smoothStep(t: number): number {
64
+ const x = Math.min(1, Math.max(0, t));
65
+ return x ** 4 * (35 + x * (-84 + x * (70 - 20 * x)));
66
+ }
67
+
68
+ export interface PoseSpline {
69
+ readonly slots: readonly number[];
70
+ readonly loop: number;
71
+ /** How much each pose owns of the frame at this moment; sums to one, and is
72
+ * one on a pose exactly at its own moment. */
73
+ weightsAt(time: number): number[];
74
+ }
75
+
76
+ /** A periodic C2 interpolant of the authored poses. Its weights are shared by
77
+ * rig playback, GLB clip mixing and trajectory sampling, so the visible path
78
+ * is the path the animation actually follows. */
79
+ export function preparePoseSpline(timeline: PoseTimeline): PoseSpline {
80
+ const n = timeline.length, slots = timeline.map(entry => entry.slot);
81
+ const loop = poseLoopSeconds(timeline), knots = poseKnots(timeline);
82
+ if (n < 2 || !(loop > 0)) {
83
+ const fixed = timeline.map((_, i) => (i === 0 ? 1 : 0));
84
+ return { slots, loop: Math.max(loop, 0), weightsAt: () => [...fixed] };
85
+ }
86
+ return { slots, loop, weightsAt: time => splineWeights(knots,loop,n,time) };
87
+ }
88
+
89
+ function splineWeights(knots: readonly number[], loop: number, n: number, time: number): number[] {
90
+ const cursor = ((time % loop) + loop) % loop, weights = new Array<number>(n).fill(0);
91
+ let k = n - 1; while (k > 0 && cursor < knots[k]) k--;
92
+ const start = knots[k], end = k + 1 < n ? knots[k + 1] : loop;
93
+ const h=end-start,t=h>0?(cursor-start)/h:0,next=(k+1)%n;
94
+ if(n<3||!(h>0)){weights[k]=1-smoothStep(t);weights[next]+=smoothStep(t);return weights;}
95
+ const coordinate=(i:number)=>i<0?knots[i+n]-loop:i>=n?knots[i-n]+loop:knots[i];
96
+ const unit=(i:number)=>{const result=new Array<number>(n).fill(0);result[(i+n)%n]=1;return result;};
97
+ const subtract=(a:readonly number[],b:readonly number[],scale:number)=>a.map((v,j)=>(v-b[j])/scale);
98
+ const derivatives=(i:number)=>{
99
+ const before=coordinate(i)-coordinate(i-1),after=coordinate(i+1)-coordinate(i);
100
+ const previous=subtract(unit(i),unit(i-1),Math.max(before,1e-8));
101
+ const following=subtract(unit(i+1),unit(i),Math.max(after,1e-8));
102
+ // Full centered tangents round a three-pose corner visibly. Reducing them
103
+ // to a quarter left a mathematically C2 but visibly triangular path.
104
+ return {velocity:previous.map((v,j)=>(v*after+following[j]*before)/(before+after)),
105
+ acceleration:previous.map((v,j)=>2*(following[j]-v)/(before+after))};
106
+ };
107
+ const a=derivatives(k),b=derivatives(k+1),p=unit(k),q=unit(k+1);
108
+ for(let j=0;j<n;j++){
109
+ const v0=h*a.velocity[j],v1=h*b.velocity[j],a0=h*h*a.acceleration[j],a1=h*h*b.acceleration[j];
110
+ const d=q[j]-p[j]-v0-a0/2,v=v1-v0-a0,acc=a1-a0;
111
+ weights[j]=p[j]+t*(v0+t*(a0/2+t*((10*d-4*v+acc/2)+t*((-15*d+7*v-acc)+t*(6*d-3*v+acc/2)))));
112
+ }
113
+ return weights;
114
+ }
115
+
116
+ const conjugate = (q: Rotation): Rotation => [-q[0], -q[1], -q[2], q[3]];
117
+ const multiply = (a: Rotation, b: Rotation): Rotation => [
118
+ a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
119
+ a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
120
+ a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
121
+ a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],
122
+ ];
123
+ function rotate(q: Rotation, v: Point): Point {
124
+ const tx = 2 * (q[1] * v[2] - q[2] * v[1]), ty = 2 * (q[2] * v[0] - q[0] * v[2]), tz = 2 * (q[0] * v[1] - q[1] * v[0]);
125
+ return [v[0] + q[3] * tx + (q[1] * tz - q[2] * ty), v[1] + q[3] * ty + (q[2] * tx - q[0] * tz), v[2] + q[3] * tz + (q[0] * ty - q[1] * tx)];
126
+ }
127
+ const safeScale = (v: number) => (Math.abs(v) > 1e-8 ? v : 1e-8);
128
+
129
+ /** A pose in its parent's frame. */
130
+ function localPose(pose: PinPose, parent: PinPose | undefined): PinPose {
131
+ if (!parent) return pose;
132
+ const inverse = conjugate(parent.rotation);
133
+ const offset = rotate(inverse, [pose.position[0] - parent.position[0], pose.position[1] - parent.position[1], pose.position[2] - parent.position[2]]);
134
+ return {
135
+ position: [offset[0] / safeScale(parent.scale[0]), offset[1] / safeScale(parent.scale[1]), offset[2] / safeScale(parent.scale[2])],
136
+ rotation: multiply(inverse, pose.rotation),
137
+ scale: [pose.scale[0] / safeScale(parent.scale[0]), pose.scale[1] / safeScale(parent.scale[1]), pose.scale[2] / safeScale(parent.scale[2])],
138
+ };
139
+ }
140
+
141
+ /** The inverse of localPose: a local transform read back out into the world. */
142
+ function worldPose(local: PinPose, parent: PinPose | undefined): PinPose {
143
+ if (!parent) return local;
144
+ const scaled: Point = [local.position[0] * parent.scale[0], local.position[1] * parent.scale[1], local.position[2] * parent.scale[2]];
145
+ const offset = rotate(parent.rotation, scaled);
146
+ return {
147
+ position: [parent.position[0] + offset[0], parent.position[1] + offset[1], parent.position[2] + offset[2]],
148
+ rotation: multiply(parent.rotation, local.rotation),
149
+ scale: [local.scale[0] * parent.scale[0], local.scale[1] * parent.scale[1], local.scale[2] * parent.scale[2]],
150
+ };
151
+ }
152
+
153
+ /** Parents before children, with any cycle in a derived hierarchy broken by
154
+ * treating the pin that closes it as a root. */
155
+ function hierarchyOrder(pins: readonly PinRecord[], parents: PinParents): { order: number[]; parentOf: (number | undefined)[] } {
156
+ const index = new Map(pins.map((pin, i) => [pin.id, i]));
157
+ const parentOf = pins.map(pin => { const p = index.get(parents.get(pin.id) ?? ''); return p === index.get(pin.id) ? undefined : p; });
158
+ const order: number[] = [], state = new Uint8Array(pins.length);
159
+ const visit = (i: number) => {
160
+ if (state[i]) { if (state[i] === 1) parentOf[i] = undefined; return; }
161
+ state[i] = 1;
162
+ const parent = parentOf[i];
163
+ if (parent !== undefined) visit(parent);
164
+ state[i] = 2; order.push(i);
165
+ };
166
+ for (let i = 0; i < pins.length; i++) visit(i);
167
+ return { order, parentOf };
168
+ }
169
+
170
+
171
+ /** The active pair shares one hemisphere, including the last-to-first seam. */
172
+ export function blendRotations(rotations: readonly Rotation[], weights: readonly number[]): Rotation {
173
+ let [x, y, z, w] = [0, 0, 0, 0];
174
+ const reference=rotations[weights.findIndex(weight=>weight>1e-12)]??rotations[0];
175
+ let dominant = reference, best = -Infinity;
176
+ for (let i = 0; i < rotations.length; i++) {
177
+ const q = rotations[i];
178
+ if(weights[i]===0)continue;
179
+ const aligned: Rotation = q[0] * reference[0] + q[1] * reference[1] + q[2] * reference[2] + q[3] * reference[3] < 0
180
+ ? [-q[0], -q[1], -q[2], -q[3]] : q;
181
+ if (weights[i] > best) { best = weights[i]; dominant = aligned; }
182
+ x += aligned[0] * weights[i]; y += aligned[1] * weights[i];
183
+ z += aligned[2] * weights[i]; w += aligned[3] * weights[i];
184
+ }
185
+ const length = Math.hypot(x, y, z, w);
186
+ // Opposed rotations at equal weight cancel and name no orientation at all.
187
+ return length > 1e-6 ? [x / length, y / length, z / length, w / length] : dominant;
188
+ }
189
+
190
+ /** Blends by id, so a pin missing from either side simply keeps its own pose —
191
+ * it appears on both sides of the blend and cannot move. Everything but the
192
+ * transform comes from the destination: ids, rest positions and flags are
193
+ * shared between slots and are not animated. */
194
+ export function blendPins(from: readonly PinRecord[], to: readonly PinRecord[], t: number, parents: PinParents = new Map()): readonly PinRecord[] {
195
+ if (t <= 0 && from.length === to.length && to.every((pin, i) => from[i]?.id === pin.id)) return from;
196
+ const aligned = to.map(pin => from.find(other => other.id === pin.id) ?? pin);
197
+ return blendPoses(to, [aligned, to], [1 - t, t], parents);
198
+ }
199
+
200
+ /** Every pose at once, by weight. `poses` are the same pins in the same order
201
+ * as `base` — they all come from resolving one document — so this walks them by
202
+ * index rather than searching per pin per frame.
203
+ *
204
+ * The blend happens in each pin's PARENT frame, never in world space. A chain
205
+ * posed two ways differs mostly in its joints' rotations, and averaging world
206
+ * positions cuts the chord between them: the limb shortens in the middle of
207
+ * every transition and lengthens again at each pose. In the parent's frame only
208
+ * the joint's own rotation and offset move, so the chain keeps its shape, and a
209
+ * pin's transform stays relative to whatever IK did to its parent — which is
210
+ * what makes moving an IK target interpolate as one arc rather than dragging
211
+ * every pin along a straight line of its own. */
212
+ export function blendPoses(base: readonly PinRecord[], poses: readonly (readonly PinRecord[])[], weights: readonly number[], parents: PinParents = new Map()): readonly PinRecord[] {
213
+ if (!poses.length || poses.some(pose => pose.length !== base.length)) return base;
214
+ const { order, parentOf } = hierarchyOrder(base, parents);
215
+ const world = new Array<PinPose>(base.length), blended = new Array<PinRecord>(base.length);
216
+ for (const i of order) {
217
+ const parent = parentOf[i], parentWorld = parent === undefined ? undefined : world[parent];
218
+ const locals = poses.map((pose, k) => localPose(pose[i].pose, parent === undefined ? undefined : poses[k][parent].pose));
219
+ world[i] = worldPose(weightedPose(locals, weights), parentWorld);
220
+ const pin: PinRecord = { ...base[i], pose: world[i] };
221
+ // A goal is an anchor in the world, not a point on its parent. A planted
222
+ // foot has the same goal in every pose, and must come out of the blend as
223
+ // that goal exactly however the body above it moves.
224
+ if (!poses.every(pose => pose[i].ikTarget)) { blended[i] = pin; continue; }
225
+ const targets = poses.map(pose => pose[i].ikTarget!);
226
+ blended[i] = { ...pin, ikTarget: {
227
+ position: [0, 1, 2].map(axis => targets.reduce((sum, target, k) => sum + target.position[axis] * weights[k], 0)) as unknown as Point,
228
+ rotation: blendRotations(targets.map(target => target.rotation), weights),
229
+ } };
230
+ }
231
+ return blended;
232
+ }
233
+
234
+ /** One pose out of many, by weight. */
235
+ function weightedPose(poses: readonly PinPose[], weights: readonly number[]): PinPose {
236
+ const position: [number, number, number] = [0, 0, 0], scale: [number, number, number] = [0, 0, 0];
237
+ for (let k = 0; k < poses.length; k++) for (let axis = 0; axis < 3; axis++) {
238
+ position[axis] += poses[k].position[axis] * weights[k];
239
+ scale[axis] += poses[k].scale[axis] * weights[k];
240
+ }
241
+ return { position, rotation: blendRotations(poses.map(pose => pose.rotation), weights), scale };
242
+ }
@@ -0,0 +1,32 @@
1
+ import { Matrix4, Quaternion, Vector3 } from 'three';
2
+ import type { PinPose, PinRecord } from './pin-types.js';
3
+ export interface BoneDriver { id:string; influences:readonly {id:string;weight:number}[] }
4
+ const matrix=(pose:PinPose)=>new Matrix4().compose(new Vector3().fromArray(pose.position),new Quaternion().fromArray(pose.rotation),new Vector3().fromArray(pose.scale));
5
+ /** Drivers reference actual fitted bones, never hidden authoring nodes. The
6
+ * driven bone's reference frame remains independently FK editable. */
7
+ export function driverDelta(driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]){
8
+ const affine=new Matrix4();affine.elements.fill(0);
9
+ const rotation=new Quaternion(0,0,0,0),scale=new Vector3();let hemisphere:Quaternion|undefined;
10
+ for(const influence of driver.influences){
11
+ const current=pins.find(p=>p.id===influence.id)!.pose,rest=reference.find(p=>p.id===influence.id)!.pose,w=influence.weight;
12
+ const delta=matrix(current).multiply(matrix(rest).invert()),q=new Quaternion().fromArray(current.rotation).multiply(new Quaternion().fromArray(rest.rotation).invert());
13
+ hemisphere??=q;const sign=hemisphere.dot(q)<0?-w:w;
14
+ delta.elements.forEach((value,i)=>affine.elements[i]+=value*w);
15
+ rotation.set(rotation.x+q.x*sign,rotation.y+q.y*sign,rotation.z+q.z*sign,rotation.w+q.w*sign);
16
+ scale.addScaledVector(new Vector3().fromArray(current.scale).divide(new Vector3().fromArray(rest.scale)),w);
17
+ }
18
+ if(!driver.influences.length){affine.identity();rotation.identity();scale.setScalar(1);}
19
+ return {affine,rotation:rotation.normalize(),scale};
20
+ }
21
+ export function drivenPose(pose:PinPose,driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]):PinPose{
22
+ const delta=driverDelta(driver,pins,reference);
23
+ return {position:new Vector3().fromArray(pose.position).applyMatrix4(delta.affine).toArray(),rotation:delta.rotation.multiply(new Quaternion().fromArray(pose.rotation)).normalize().toArray(),scale:delta.scale.multiply(new Vector3().fromArray(pose.scale)).toArray()};
24
+ }
25
+ export function referencePose(pose:PinPose,driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]):PinPose{
26
+ const delta=driverDelta(driver,pins,reference);
27
+ if(Math.abs(delta.affine.determinant())<1e-10)throw new Error('This blended bone frame is singular. Adjust its driving bones before editing its position.');
28
+ return {position:new Vector3().fromArray(pose.position).applyMatrix4(delta.affine.invert()).toArray(),rotation:delta.rotation.invert().multiply(new Quaternion().fromArray(pose.rotation)).normalize().toArray(),scale:new Vector3().fromArray(pose.scale).divide(delta.scale).toArray()};
29
+ }
30
+ export function driveRig(pins:readonly PinRecord[],reference:readonly PinRecord[],drivers:readonly BoneDriver[]){
31
+ return pins.map(pin=>{const driver=drivers.find(d=>d.id===pin.id);return driver?{...pin,pose:drivenPose(pin.pose,driver,pins,reference)}:pin;});
32
+ }
@@ -0,0 +1,87 @@
1
+ import { validateRig, type JointsRig } from './joints-json.js';
2
+ import { ikChain } from './pin-ik.js';
3
+ import {DEFAULT_MOTION} from './motion-settings.js';
4
+ import type { ClothCollider, ClothLink } from './pin-cloth.js';
5
+
6
+ export const NEEDLE_DEFORMATION_RIG = 'NEEDLE_deformation_rig';
7
+ export interface RigDescriptor extends JointsRig {
8
+ version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
9
+ joints: { node: number; parent: number | null; mass: number }[];
10
+ chains: { endpoint: number; joints: number[]; mode: 'ik' | 'secondary' | 'cloth' | 'fur' }[];
11
+ helpers?: { node: number; influences: { node: number; weight: number }[] }[];
12
+ cloth?: { links: ClothLink[]; colliders: ClothCollider[] };
13
+ furSurface?: { heightTexture: number; texCoord?: number };
14
+ }
15
+ /** Validate before allocating runtime objects or accepting node references. */
16
+ export function parseRigDescriptor(value: unknown, nodeCount: number, textureCount = Infinity): RigDescriptor {
17
+ if (!value || typeof value !== 'object') throw new Error('Invalid deformation rig.');
18
+ const raw = value as RigDescriptor;
19
+ if (raw.version !== 1 && raw.version !== 2 && raw.version !== 3 && raw.version !== 4 && raw.version !== 5 && raw.version !== 6 && raw.version !== 7 && raw.version !== 8 && raw.version !== 9) throw new Error('Unsupported NEEDLE_deformation_rig version.');
20
+ if (raw.furSurface?.texCoord !== undefined && (raw.version < 8 || !Number.isInteger(raw.furSurface.texCoord) || raw.furSurface.texCoord < 0 || raw.furSurface.texCoord > 1)) throw new Error('Invalid Fur height texture coordinates.');
21
+ if (raw.furSurface && (raw.version < 6 || !Number.isInteger(raw.furSurface.heightTexture) || raw.furSurface.heightTexture < 0 || raw.furSurface.heightTexture >= textureCount)) throw new Error('Invalid Fur height texture.');
22
+ if (raw.version < 5 && raw.windStrength !== undefined) throw new Error('Wind requires NEEDLE_deformation_rig version 5.');
23
+ if (raw.activePose === 0 && raw.version < 9) throw new Error('An unselected authored pose requires NEEDLE_deformation_rig version 9.');
24
+ const restSlot=raw.poseSlots?.find(slot=>slot.slot===0);
25
+ if(restSlot && raw.version<7)throw new Error('Pose 0 requires NEEDLE_deformation_rig version 7.');
26
+ const rig = validateRig({...raw,poseSlots:raw.poseSlots?.filter(slot=>slot.slot!==0)}, raw.version>=3?256:128);
27
+ if(restSlot){
28
+ if(raw.poseSlots.filter(slot=>slot.slot===0).length!==1 || !Array.isArray(restSlot.poses) || restSlot.poses.length!==rig.pins.length ||
29
+ new Set(restSlot.poses.map(p=>p.id)).size!==rig.pins.length || restSlot.poses.some(p=>!rig.pins.some(pin=>pin.id===p.id)))throw new Error('Invalid rest pose clip.');
30
+ validateRig({pins:rig.pins,activePose:1,poseSlots:[{slot:1,poses:restSlot.poses}],poseTimes:[]},raw.version>=3?256:128);
31
+ }
32
+ if (raw.version < 5 && rig.pins.some(pin=>pin.fur)) throw new Error('Fur requires NEEDLE_deformation_rig version 5.');
33
+ if (raw.furSurface && !rig.pins.some(pin => pin.fur)) throw new Error('Fur height requires a Fur rig.');
34
+ const node = (n: number) => Number.isInteger(n) && n >= 0 && n < nodeCount;
35
+ if (!Array.isArray(raw.joints) || raw.joints.length !== rig.pins.length) throw new Error('Invalid rig joint bindings.');
36
+ const indices = new Set<number>();
37
+ for (const joint of raw.joints) {
38
+ if (!joint || !node(joint.node) || indices.has(joint.node) || (joint.parent !== null && !node(joint.parent)) || !Number.isFinite(joint.mass) || joint.mass < 0) throw new Error('Invalid rig node or mass.');
39
+ indices.add(joint.node);
40
+ }
41
+ const parents = new Map(raw.joints.map(j => [j.node, j.parent]));
42
+ for (const joint of raw.joints) {
43
+ const seen = new Set<number>(); let cursor: number | null = joint.node;
44
+ while (cursor !== null) {
45
+ if (!indices.has(cursor) || seen.has(cursor)) throw new Error('Invalid or cyclic rig hierarchy.');
46
+ seen.add(cursor); cursor = parents.get(cursor)!;
47
+ }
48
+ }
49
+ if (!Array.isArray(raw.chains) || raw.chains.length > rig.pins.length) throw new Error('Invalid motion chains.');
50
+ const endpoints = new Set<number>();
51
+ for (const chain of raw.chains) {
52
+ if (!chain || !indices.has(chain.endpoint) || endpoints.has(chain.endpoint) || !['ik', 'secondary', 'cloth', 'fur'].includes(chain.mode) || !Array.isArray(chain.joints) || !chain.joints.length || chain.joints.length > rig.pins.length || chain.joints.at(-1) !== chain.endpoint || new Set(chain.joints).size !== chain.joints.length || chain.joints.some(n => !indices.has(n))) throw new Error('Invalid motion chain.');
53
+ endpoints.add(chain.endpoint);
54
+ }
55
+ const pinParents = new Map<string, string>(), masses = new Map<string, number>();
56
+ raw.joints.forEach((j, i) => { masses.set(rig.pins[i].id, j.mass); if (j.parent !== null) pinParents.set(rig.pins[i].id, rig.pins[raw.joints.findIndex(p => p.node === j.parent)].id); });
57
+ for (const [i, pin] of rig.pins.entries()) {
58
+ const chain = raw.chains.find(c => c.endpoint === raw.joints[i].node);
59
+ const mode = !pin.guide && (pin.ik ? 'ik' : pin.wiggle ? 'secondary' : pin.cloth ? 'cloth' : pin.fur ? 'fur' : null);
60
+ if (!mode && chain) throw new Error('Unexpected motion chain.');
61
+ if (!mode) continue;
62
+ const articulated=raw.version>=3?rig.pins.filter((_,i)=>!raw.helpers?.some(h=>h.node===raw.joints[i].node)):rig.pins;
63
+ const expected = ikChain(articulated.map(p=>p.id===pin.id?{...p,motion:{...(p.motion??DEFAULT_MOTION),reach:1}}:p), pinParents, pin.id, masses).map(p => raw.joints[rig.pins.findIndex(pin => pin.id === p.id)].node);
64
+ // Chains are derived caches, not authoritative authored topology. Older
65
+ // writers used discontinuous reach gates; accept any valid ancestor suffix
66
+ // and rebuild the current extent from the saved reach in the runtime.
67
+ if (!chain || chain.mode !== mode || chain.joints.length > expected.length || chain.joints.some((n, i) => n !== expected[expected.length - chain.joints.length + i])) throw new Error('Motion chain does not match its hierarchy and reach.');
68
+ }
69
+ if (raw.helpers !== undefined && (!Array.isArray(raw.helpers) || raw.helpers.length > 256)) throw new Error('Invalid helper bindings.');
70
+ const helpers = raw.helpers?.map(helper => {
71
+ if (!node(helper.node) || (raw.version<3&&indices.has(helper.node)) || (raw.version>=3&&!parents.has(helper.node)) || !Array.isArray(helper.influences) || helper.influences.length > rig.pins.length) throw new Error('Invalid helper node.');
72
+ const seen = new Set<number>(); let sum = 0;
73
+ for (const influence of helper.influences) {
74
+ if (!parents.has(influence.node) || (raw.version>=3&&raw.helpers?.some(h=>h.node===influence.node)) || seen.has(influence.node) || !Number.isFinite(influence.weight) || influence.weight <= 0) throw new Error('Invalid helper influence.');
75
+ seen.add(influence.node); sum += influence.weight;
76
+ }
77
+ if (helper.influences.length && Math.abs(sum - 1) > 1e-4) throw new Error('Helper weights must sum to one.');
78
+ indices.add(helper.node); return { node: helper.node, influences: helper.influences.map(i => ({ ...i })) };
79
+ });
80
+ if (raw.version >= 2 && !helpers) throw new Error('Rig requires helper bindings.');
81
+ if (helpers && new Set(helpers.map(h=>h.node)).size!==helpers.length) throw new Error('Duplicate helper bone.');
82
+ if ((raw.version < 4 && (raw.cloth !== undefined || rig.pins.some(p => p.cloth))) || (raw.version === 4 && !raw.cloth) || (rig.pins.some(p => p.cloth) && !raw.cloth) || (raw.cloth && (!Array.isArray(raw.cloth.links) || !Array.isArray(raw.cloth.colliders) || raw.cloth.links.length > 512 || raw.cloth.colliders.length > 4096))) throw new Error('Invalid cloth simulation data.');
83
+ const pinById = new Map(rig.pins.map(p => [p.id, p]));
84
+ for (const link of raw.cloth?.links ?? []) if (!link || !pinById.has(link.a) || !pinById.has(link.b) || link.a === link.b || !(pinById.get(link.a)?.cloth || pinById.get(link.b)?.cloth) || !Number.isFinite(link.length) || link.length < 0) throw new Error('Invalid cloth link.');
85
+ for (const collider of raw.cloth?.colliders ?? []) if (!collider || !Array.isArray(collider.position) || collider.position.length !== 3 || !collider.position.every(Number.isFinite) || !Number.isFinite(collider.radius) || collider.radius <= 0 || !collider.driver || !pinById.has(collider.driver) || pinById.get(collider.driver)?.cloth) throw new Error('Invalid cloth collider.');
86
+ return { ...rig,poseSlots:restSlot?[restSlot,...rig.poseSlots]:rig.poseSlots, version: raw.version, joints: raw.joints.map(j => ({ ...j })), chains: raw.chains.map(c => ({ ...c, joints: [...c.joints] })), ...(helpers ? { helpers } : {}), ...(raw.cloth ? { cloth: { links: raw.cloth.links.map(l => ({ ...l })), colliders: raw.cloth.colliders.map(c => ({ ...c, position: [...c.position] as [number,number,number] })) } } : {}), ...(raw.furSurface ? { furSurface: { ...raw.furSurface } } : {}) };
87
+ }