@needle-tools/three-mesh-effects 0.3.3 → 0.3.5

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 (47) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +3 -2
  3. package/build/box-impostor-runtime.js +27 -2
  4. package/build/box-impostor-runtime.js.map +3 -3
  5. package/build/deformation-runtime.js +11 -9
  6. package/build/deformation-runtime.js.map +2 -2
  7. package/build/impostor-runtime.js +41 -19
  8. package/build/impostor-runtime.js.map +3 -3
  9. package/build/internal/box-impostor/box-impostor-display.js +10 -2
  10. package/build/internal/box-impostor/box-impostor-display.js.map +2 -2
  11. package/build/internal/box-impostor/box-impostor-faces.js.map +1 -1
  12. package/build/internal/box-impostor/box-impostor-geometry.js +4 -0
  13. package/build/internal/box-impostor/box-impostor-geometry.js.map +2 -2
  14. package/build/internal/box-impostor/box-impostor-material.js +10 -2
  15. package/build/internal/box-impostor/box-impostor-material.js.map +2 -2
  16. package/build/internal/box-impostor/box-impostor-metadata.js +4 -0
  17. package/build/internal/box-impostor/box-impostor-metadata.js.map +2 -2
  18. package/build/internal/box-impostor/box-impostor-projection.js.map +1 -1
  19. package/build/internal/box-impostor/box-impostor-runtime.js +27 -2
  20. package/build/internal/box-impostor/box-impostor-runtime.js.map +3 -3
  21. package/build/internal/deformation/pin-ik.js +11 -9
  22. package/build/internal/deformation/pin-ik.js.map +2 -2
  23. package/build/internal/deformation/pin-wiggle.js.map +1 -1
  24. package/build/internal/deformation/rig-extension.js.map +1 -1
  25. package/build/internal/deformation/rig-runtime.js +11 -9
  26. package/build/internal/deformation/rig-runtime.js.map +2 -2
  27. package/build/internal/impostor/impostor-node-material.js +41 -19
  28. package/build/internal/impostor/impostor-node-material.js.map +3 -3
  29. package/build/internal/pixel-impostor/pixel-impostor-display.js +9 -7
  30. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +2 -2
  31. package/build/internal/rendering/classic-webgl-support.js +12 -0
  32. package/build/internal/rendering/classic-webgl-support.js.map +7 -0
  33. package/build/internal/rendering/renderer-support.js +13 -0
  34. package/build/internal/rendering/renderer-support.js.map +3 -3
  35. package/build/pixel-impostor-runtime.js +9 -7
  36. package/build/pixel-impostor-runtime.js.map +2 -2
  37. package/build/types/box-impostor/box-impostor-metadata.d.ts +3 -1
  38. package/build/types/rendering/classic-webgl-support.d.ts +9 -0
  39. package/build/types/rendering/classic-webgl-support.js +1 -0
  40. package/package.json +2 -2
  41. package/src/box-impostor/box-impostor-material.js +10 -2
  42. package/src/box-impostor/box-impostor-metadata.js +5 -1
  43. package/src/deformation/pin-ik.ts +13 -9
  44. package/src/impostor/impostor-node-material.js +31 -15
  45. package/src/pixel-impostor/pixel-impostor-display.js +18 -7
  46. package/src/rendering/classic-webgl-support.js +15 -0
  47. package/src/rendering/renderer-support.js +5 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/deformation/pin-types.ts", "../../../src/deformation/limits.ts", "../../../src/deformation/motion-settings.ts", "../../../src/deformation/ik-constraints.ts", "../../../src/deformation/pose-slots.ts", "../../../src/deformation/pose-timeline.ts", "../../../src/deformation/wind.ts", "../../../src/deformation/joints-json.ts", "../../../src/deformation/pin-ik.ts", "../../../src/deformation/rig-extension.ts"],
4
- "sourcesContent": ["import type { IKConstraint } from './ik-constraints.js';\nimport type { MotionSettings } from './motion-settings.js';\n\n/** Shared data contract; deliberately independent of editor history and GPU types. */\nexport type Point = readonly [number, number, number];\nexport type Rotation = readonly [number, number, number, number];\nexport type PinPose = { readonly position: Point; readonly rotation: Rotation; readonly scale: Point };\nexport type PinParents = ReadonlyMap<string, string>;\nexport type HierarchyEdge = {from:string;to:string;cost:number;geodesic?:number};\nexport type PinMotion = 'none' | 'ik' | 'wiggle' | 'cloth' | 'fur';\nexport const DEFAULT_FUR_DEPTH = .1;\nexport const MAX_FUR_DEPTH = .5;\nexport type IKTarget = { readonly position: Point; readonly rotation: Rotation };\nexport const IK_CHAIN_KINDS = ['leg','arm','head','tail','wing','fin','tentacle','spine'] as const;\nexport type IKChainRole = { readonly kind: typeof IK_CHAIN_KINDS[number]; readonly side: 'center'|'left'|'right'; readonly position?: 'front'|'hind' };\nexport type PinRecord = { readonly id: string; readonly rest: Point; readonly pose: PinPose; readonly rigidGroup: string | null; readonly independent: boolean;\n /** This pose was set on purpose in the slot now open, rather than reached by\n * being carried by a parent or swept along by an IK solve. A slot still\n * stores an unauthored pose it could not otherwise reproduce \u2014 an IK chain\n * does not come back the same way twice \u2014 but only an authored one is shown\n * as deliberate and only an authored one can be released. */\n readonly authored?: boolean; readonly guide?: boolean; readonly ik?: boolean; readonly wiggle?: boolean; readonly cloth?: boolean; readonly fur?: boolean; readonly furDepth?: number; readonly motion?: MotionSettings; readonly ikTarget?: IKTarget; readonly ikConstraint?: IKConstraint; readonly chainRole?: IKChainRole };\n", "/** Shared document, import, UI and GPU capacity. Pin records are 64 bytes. */\nexport const MAX_DEFORMATION_PINS = 128;\n/** What one sweep of the Suggested pins slider will place. Well short of the\n * document cap: past this the slider stops placing body anchors and starts\n * splitting fine branches, which is hand work rather than a slider's job. */\nexport const MAX_SUGGESTED_PINS = 64;\n\n/** Cells along the longest axis of the solver lattice.\n *\n * The lattice is N by N by N over the model's bounds, and everything the solver\n * measures \u2014 how thick a part is, how far a contact reaches, how much an\n * element is strained \u2014 is in units of those cells. What a grid can represent\n * is what it can resolve: on a posed arm a finger is 2.7 cells across at 32 and\n * 3.5 at 40, which is a rod three nodes thick.\n *\n * The ceiling is a memory bound rather than a speed one. Node buffers are 16\n * bytes each and there are about ten of them, so 64 costs roughly 42 MB of\n * those; the harmonic weights are the one that hurts, at four bytes per node\n * per pin slot, which for a full 128 pins is 268 MB at 64 against 67 MB at 40. */\nexport const MIN_DEFORMATION_RESOLUTION = 16;\nexport const MAX_DEFORMATION_RESOLUTION = 64;\n\n/** Bones the skeleton solver turns on its own: every part of the body no pin\n * drives, cut along the curve skeleton. 132 bytes of GPU state each. */\nexport const MAX_SKELETON_BONES = 2048;\n", "export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };\nexport const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };\nexport function validateMotionSettings(value: MotionSettings) {\n if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1\n || !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8\n || !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1\n || !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2\n || !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');\n}\n", "import { Quaternion, Vector3 } from 'three';\nexport type IKConstraint = { mode:'free'|'cone'|'hinge'|'locked'; axis:'auto'|'x'|'y'|'z'; min:number; max:number; orientation?:[number,number,number,number]; maxY?:number };\nexport const DEFAULT_IK_CONSTRAINT:Readonly<IKConstraint> = {mode:'free',axis:'auto',min:-120,max:120};\nexport function validateIKConstraint(value:IKConstraint) {\n if(value?.maxY!==undefined && (!Number.isFinite(value.maxY)||value.maxY<0||value.maxY>180))throw new Error('Invalid IK cone aperture.');\n if(value?.orientation!==undefined && (!Array.isArray(value.orientation)||value.orientation.length!==4||!value.orientation.every(Number.isFinite)||Math.abs(Math.hypot(...value.orientation)-1)>1e-4))throw new Error('Invalid IK cone orientation.');\n if (!value || !['free','cone','hinge','locked'].includes(value.mode) || !['auto','x','y','z'].includes(value.axis)\n || !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || (value.mode==='cone' && value.max<0)) throw new Error('Invalid IK joint constraint.');\n}\n/** Stable parent-local cone frame. Z follows the rest bone; X/Y are aperture axes. */\nexport function coneFrame(axis:Vector3,constraint:Readonly<IKConstraint>){\n return new Quaternion().fromArray(constraint.orientation??[0,0,0,1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis.clone().normalize()));\n}\n/** Angular ellipse (also valid beyond 90 degrees), rather than a tangent-plane box. */\nexport function coneAngle(constraint:Readonly<IKConstraint>,azimuth:number){\n const x=(constraint.mode==='cone'?constraint.max:90)*Math.PI/180,y=(constraint.mode==='cone'?(constraint.maxY??constraint.max):90)*Math.PI/180;\n const c=Math.cos(azimuth),s=Math.sin(azimuth);\n if((x===0&&Math.abs(c)>1e-8)||(y===0&&Math.abs(s)>1e-8))return 0;\n return 1/Math.sqrt((Math.abs(c)<1e-8?0:c/Math.max(x,1e-12))**2+(Math.abs(s)<1e-8?0:s/Math.max(y,1e-12))**2);\n}\nexport function constrainCone(rotation:Quaternion,axis:Vector3,constraint:Readonly<IKConstraint>,movingAxis:Vector3=axis){\n const frame=coneFrame(axis,constraint),direction=movingAxis.clone().normalize().applyQuaternion(rotation);\n const local=direction.clone().applyQuaternion(frame.clone().invert()),azimuth=Math.atan2(local.y,local.x);\n const angle=Math.atan2(Math.hypot(local.x,local.y),local.z),limit=coneAngle(constraint,azimuth);\n if(angle<=limit+1e-8)return rotation.clone();\n const target=new Vector3(Math.sin(limit)*Math.cos(azimuth),Math.sin(limit)*Math.sin(azimuth),Math.cos(limit)).applyQuaternion(frame);\n return new Quaternion().setFromUnitVectors(direction,target).multiply(rotation).normalize();\n}\n/** Circular swing cone, not an Euler-angle box. Twist remains free. */\nexport function constrainSwing(rotation: Quaternion, axis: Vector3, degrees: number) {\n const direction=axis.clone().normalize(), rotated=direction.clone().applyQuaternion(rotation);\n const angle=direction.angleTo(rotated), limit=degrees*Math.PI/180;\n if(angle<=limit+1e-8)return rotation.clone();\n const normal=new Vector3().crossVectors(direction,rotated);\n if(normal.lengthSq()<1e-12)normal.crossVectors(direction,Math.abs(direction.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0));\n return new Quaternion().setFromAxisAngle(normal.normalize(),limit-angle).multiply(rotation).normalize();\n}\n", "import type { IKTarget, PinPose, PinRecord, Point, Rotation } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\n\nexport type StoredPose = { readonly id:string; readonly pose:PinPose; readonly ikTarget?:IKTarget; readonly authored?:boolean };\nexport type PoseSlot = { readonly slot:number; readonly poses:readonly StoredPose[] };\nexport const POSE_SLOTS=9;\n/** Below any edit a hand can make, and far above the drift of composing one\n * carried transform after another. */\nconst AUTHORED_EPSILON=1e-6;\n\nexport function capturePose(pins:readonly PinRecord[]):readonly StoredPose[]{\n return pins.map(pin=>({id:pin.id,pose:pin.pose,...(pin.authored?{authored:true}:{}),...(pin.ikTarget?{ikTarget:pin.ikTarget}:{})}));\n}\n\nconst restPoseOf=(rest:Point):PinPose=>({position:[rest[0],rest[1],rest[2]],rotation:[0,0,0,1],scale:[1,1,1]});\n\n/** Where a pin lands when its parent carries it from rest. A parent's pose IS\n * a similarity out of its own rest frame, so the child keeps its rest offset\n * through that same rotation and scale \u2014 the transform hierarchy posing applies\n * when a parent moves, written as one step from rest instead of accumulated. */\nexport function carriedPose(rest:Point,parentRest:Point,parent:PinPose):PinPose{\n const [qx,qy,qz,qw]=parent.rotation;\n 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];\n const tx=2*(qy*z-qz*y),ty=2*(qz*x-qx*z),tz=2*(qx*y-qy*x);\n 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)];\n const rotation:Rotation=[qx,qy,qz,qw],scale:Point=[parent.scale[0],parent.scale[1],parent.scale[2]];\n return {position,rotation,scale};\n}\n\nconst samePose=(a:PinPose,b:PinPose)=>\n a.position.every((v,i)=>Math.abs(v-b.position[i])<=AUTHORED_EPSILON)\n && a.scale.every((v,i)=>Math.abs(v-b.scale[i])<=AUTHORED_EPSILON)\n && a.rotation.every((v,i)=>Math.abs(v-b.rotation[i])<=AUTHORED_EPSILON);\n\n/** What a slot would place a pin at if it said nothing about it. */\nfunction inheritedPose(pin:PinRecord,parent:PinRecord|undefined,parentPose:PinPose|undefined):PinPose{\n return parent&&parentPose?carriedPose(pin.rest,parent.rest,parentPose):restPoseOf(pin.rest);\n}\n\n/** Only the poses a slot actually authors. A pin the hierarchy already places\n * is left out, so a point added while another pose was open keeps following its\n * parent everywhere else until it is deliberately posed there. */\nexport function authoredPoses(pins:readonly PinRecord[],parents:PinParents=new Map()):readonly StoredPose[]{\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\n return capturePose(pins).filter(stored=>{\n const pin=byId.get(stored.id)!;\n // Deliberate, or a goal, which is deliberate by definition.\n if(pin.authored||pin.ikTarget)return true;\n // Otherwise it is only kept because it could not be worked out again. A\n // joint the IK solve swept along is not reproducible \u2014 the same goal\n // reached from a different bend gives a different arm \u2014 so the value stays\n // even though nobody posed it.\n const parent=byId.get(parents.get(pin.id)??'');\n return !samePose(pin.pose,inheritedPose(pin,parent,parent?.pose));\n });\n}\n\n/** Active pins are the edit register. Inactive slots contain transforms only;\n * topology, rest positions and settings remain shared and action-owned. A pin\n * the slot does not mention inherits through the hierarchy rather than dropping\n * to rest, which is what keeps a newly placed point attached to its parent in\n * every other pose. */\nexport function resolvePose(pins:readonly PinRecord[],slot:PoseSlot,parents:PinParents=new Map()):readonly PinRecord[]{\n const saved=new Map(slot.poses.map(p=>[p.id,p]));\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\n const memo=new Map<string,PinPose>(),visiting=new Set<string>();\n const poseOf=(pin:PinRecord):PinPose=>{\n const cached=memo.get(pin.id);if(cached)return cached;\n const stored=saved.get(pin.id);\n let pose:PinPose;\n if(stored)pose=stored.pose;\n else{\n const parentId=parents.get(pin.id);\n // A parent already on the stack means a cycle in a derived hierarchy;\n // rest is the only answer that terminates.\n const parent=parentId&&!visiting.has(parentId)?byId.get(parentId):undefined;\n if(!parent)pose=restPoseOf(pin.rest);\n else{visiting.add(pin.id);pose=carriedPose(pin.rest,parent.rest,poseOf(parent));visiting.delete(pin.id);}\n }\n memo.set(pin.id,pose);return pose;\n };\n const resolved:PinRecord[]=pins.map(pin=>{\n const stored=saved.get(pin.id),{ikTarget:_target,authored:_authored,...base}=pin;\n return {...base,pose:poseOf(pin),...(stored?.authored?{authored:true}:{}),...(stored?.ikTarget?{ikTarget:stored.ikTarget}:{})};\n });\n // Group membership is shared. A group created after another pose was saved\n // still has one rotation/uniform scale when that pose is opened. Positions\n // stay authored; subsequent rigid edits preserve that arrangement.\n return resolved.map(pin=>{\n if(!pin.rigidGroup)return pin;const anchor=resolved.find(p=>p.rigidGroup===pin.rigidGroup)!;\n return {...pin,pose:{...pin.pose,rotation:anchor.pose.rotation,scale:[anchor.pose.scale[0],anchor.pose.scale[0],anchor.pose.scale[0]]}};\n });\n}\nexport function definedPoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\n const slots=model.poseSlots.filter(p=>p.slot!==model.activePose);\n return [...slots,...(model.activePose === 0 ? [] : [{slot:model.activePose,poses:capturePose(model.pins)}])].sort((a,b)=>a.slot-b.slot);\n}\n\n/** Pose 0 is derived from shared rest positions, never an editable pose slot. */\nexport function restPoseSlot(pins:readonly PinRecord[]):PoseSlot{\n return {slot:0,poses:pins.map(pin=>({id:pin.id,pose:restPoseOf(pin.rest)}))};\n}\n\nexport function playablePoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\n return [restPoseSlot(model.pins),...definedPoses(model)];\n}\n", "import type { PinPose, PinRecord, Point, Rotation } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\n\n/** A pose slot's time controls its share of the loop around its own moment.\n * The transition settles at each authored pose without holding a flat frame. */\nexport const DEFAULT_POSE_SECONDS = 0.7;\nexport const MIN_POSE_SECONDS = 0.05;\nexport const MAX_POSE_SECONDS = 60;\n/** Travel kept below the longest pose so a slider dragged to the bottom can\n * always be dragged further on the next pass, and shrinks back when shortened. */\nexport const POSE_TIME_HEADROOM = 0.5;\n\nexport type PoseTiming = { readonly slot: number; readonly seconds: number };\nexport type PoseTimeline = readonly PoseTiming[];\n\nexport function poseTimeScale(timeline: PoseTimeline): number {\n return Math.max(DEFAULT_POSE_SECONDS, ...timeline.map(entry => entry.seconds)) + POSE_TIME_HEADROOM;\n}\n\n/** The strip reads downwards: zero at the top, the scale at the bottom, which\n * is what makes \"drag down\" mean \"stay longer\". */\nexport function poseSecondsAt(offset: number, height: number, scale: number): number {\n if (!(height > 0)) return MIN_POSE_SECONDS;\n return Math.min(1, Math.max(0, offset / height)) * scale;\n}\n\n/** How far down the strip a time sits, as a percentage for the fill and handle. */\nexport function poseTimeOffset(seconds: number, scale: number): number {\n if (!(scale > 0)) return 0;\n return Math.min(100, Math.max(0, (seconds / scale) * 100));\n}\n\nexport function poseLoopSeconds(timeline: PoseTimeline): number {\n return timeline.reduce((total, entry) => total + Math.max(0, entry.seconds), 0);\n}\n\n/** The moment each pose is reached. Neighbours split the gap between them in\n * proportion to their own times, which is what makes a time an ownership share\n * rather than the length of one arc. */\nexport function poseKnots(timeline: PoseTimeline): number[] {\n const knots = [0];\n for (let i = 1; i < timeline.length; i++) {\n knots.push(knots[i - 1] + (Math.max(0, timeline[i - 1].seconds) + Math.max(0, timeline[i].seconds)) / 2);\n }\n return knots;\n}\n\n/** How long one pass takes: the first pose's moment to the last one's.\n * Looping playback adds the closing transition up to poseLoopSeconds. */\nexport function posePassSeconds(timeline: PoseTimeline): number {\n const knots = poseKnots(timeline);\n return knots.length ? knots[knots.length - 1] : 0;\n}\n\nexport function poseTimeOf(timeline: PoseTimeline, slot: number): number {\n const index = timeline.findIndex(entry => entry.slot === slot);\n return index < 0 ? 0 : poseKnots(timeline)[index];\n}\n\n/** Septic: zero first, second AND third derivative at both ends, so a one-shot\n * move away from rest and back to rest is G3 at the moment it starts and the\n * moment it settles. A cubic smoothstep leaves a jerk step at both. */\nexport function smoothStep(t: number): number {\n const x = Math.min(1, Math.max(0, t));\n return x ** 4 * (35 + x * (-84 + x * (70 - 20 * x)));\n}\n\nexport interface PoseSpline {\n readonly slots: readonly number[];\n readonly loop: number;\n /** How much each pose owns of the frame at this moment; sums to one, and is\n * one on a pose exactly at its own moment. */\n weightsAt(time: number): number[];\n}\n\n/** A periodic C2 interpolant of the authored poses. Its weights are shared by\n * rig playback, GLB clip mixing and trajectory sampling, so the visible path\n * is the path the animation actually follows. */\nexport function preparePoseSpline(timeline: PoseTimeline): PoseSpline {\n const n = timeline.length, slots = timeline.map(entry => entry.slot);\n const loop = poseLoopSeconds(timeline), knots = poseKnots(timeline);\n if (n < 2 || !(loop > 0)) {\n const fixed = timeline.map((_, i) => (i === 0 ? 1 : 0));\n return { slots, loop: Math.max(loop, 0), weightsAt: () => [...fixed] };\n }\n return { slots, loop, weightsAt: time => splineWeights(knots,loop,n,time) };\n}\n\nfunction splineWeights(knots: readonly number[], loop: number, n: number, time: number): number[] {\n const cursor = ((time % loop) + loop) % loop, weights = new Array<number>(n).fill(0);\n let k = n - 1; while (k > 0 && cursor < knots[k]) k--;\n const start = knots[k], end = k + 1 < n ? knots[k + 1] : loop;\n const h=end-start,t=h>0?(cursor-start)/h:0,next=(k+1)%n;\n if(n<3||!(h>0)){weights[k]=1-smoothStep(t);weights[next]+=smoothStep(t);return weights;}\n const coordinate=(i:number)=>i<0?knots[i+n]-loop:i>=n?knots[i-n]+loop:knots[i];\n const unit=(i:number)=>{const result=new Array<number>(n).fill(0);result[(i+n)%n]=1;return result;};\n const subtract=(a:readonly number[],b:readonly number[],scale:number)=>a.map((v,j)=>(v-b[j])/scale);\n const derivatives=(i:number)=>{\n const before=coordinate(i)-coordinate(i-1),after=coordinate(i+1)-coordinate(i);\n const previous=subtract(unit(i),unit(i-1),Math.max(before,1e-8));\n const following=subtract(unit(i+1),unit(i),Math.max(after,1e-8));\n // Full centered tangents round a three-pose corner visibly. Reducing them\n // to a quarter left a mathematically C2 but visibly triangular path.\n return {velocity:previous.map((v,j)=>(v*after+following[j]*before)/(before+after)),\n acceleration:previous.map((v,j)=>2*(following[j]-v)/(before+after))};\n };\n const a=derivatives(k),b=derivatives(k+1),p=unit(k),q=unit(k+1);\n for(let j=0;j<n;j++){\n const v0=h*a.velocity[j],v1=h*b.velocity[j],a0=h*h*a.acceleration[j],a1=h*h*b.acceleration[j];\n const d=q[j]-p[j]-v0-a0/2,v=v1-v0-a0,acc=a1-a0;\n 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)))));\n }\n return weights;\n}\n\nconst conjugate = (q: Rotation): Rotation => [-q[0], -q[1], -q[2], q[3]];\nconst multiply = (a: Rotation, b: Rotation): Rotation => [\n a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],\n a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],\n a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],\n a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],\n];\nfunction rotate(q: Rotation, v: Point): Point {\n 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]);\n 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)];\n}\nconst safeScale = (v: number) => (Math.abs(v) > 1e-8 ? v : 1e-8);\n\n/** A pose in its parent's frame. */\nfunction localPose(pose: PinPose, parent: PinPose | undefined): PinPose {\n if (!parent) return pose;\n const inverse = conjugate(parent.rotation);\n const offset = rotate(inverse, [pose.position[0] - parent.position[0], pose.position[1] - parent.position[1], pose.position[2] - parent.position[2]]);\n return {\n position: [offset[0] / safeScale(parent.scale[0]), offset[1] / safeScale(parent.scale[1]), offset[2] / safeScale(parent.scale[2])],\n rotation: multiply(inverse, pose.rotation),\n scale: [pose.scale[0] / safeScale(parent.scale[0]), pose.scale[1] / safeScale(parent.scale[1]), pose.scale[2] / safeScale(parent.scale[2])],\n };\n}\n\n/** The inverse of localPose: a local transform read back out into the world. */\nfunction worldPose(local: PinPose, parent: PinPose | undefined): PinPose {\n if (!parent) return local;\n const scaled: Point = [local.position[0] * parent.scale[0], local.position[1] * parent.scale[1], local.position[2] * parent.scale[2]];\n const offset = rotate(parent.rotation, scaled);\n return {\n position: [parent.position[0] + offset[0], parent.position[1] + offset[1], parent.position[2] + offset[2]],\n rotation: multiply(parent.rotation, local.rotation),\n scale: [local.scale[0] * parent.scale[0], local.scale[1] * parent.scale[1], local.scale[2] * parent.scale[2]],\n };\n}\n\n/** Parents before children, with any cycle in a derived hierarchy broken by\n * treating the pin that closes it as a root. */\nfunction hierarchyOrder(pins: readonly PinRecord[], parents: PinParents): { order: number[]; parentOf: (number | undefined)[] } {\n const index = new Map(pins.map((pin, i) => [pin.id, i]));\n const parentOf = pins.map(pin => { const p = index.get(parents.get(pin.id) ?? ''); return p === index.get(pin.id) ? undefined : p; });\n const order: number[] = [], state = new Uint8Array(pins.length);\n const visit = (i: number) => {\n if (state[i]) { if (state[i] === 1) parentOf[i] = undefined; return; }\n state[i] = 1;\n const parent = parentOf[i];\n if (parent !== undefined) visit(parent);\n state[i] = 2; order.push(i);\n };\n for (let i = 0; i < pins.length; i++) visit(i);\n return { order, parentOf };\n}\n\n\n/** The active pair shares one hemisphere, including the last-to-first seam. */\nexport function blendRotations(rotations: readonly Rotation[], weights: readonly number[]): Rotation {\n let [x, y, z, w] = [0, 0, 0, 0];\n const reference=rotations[weights.findIndex(weight=>weight>1e-12)]??rotations[0];\n let dominant = reference, best = -Infinity;\n for (let i = 0; i < rotations.length; i++) {\n const q = rotations[i];\n if(weights[i]===0)continue;\n const aligned: Rotation = q[0] * reference[0] + q[1] * reference[1] + q[2] * reference[2] + q[3] * reference[3] < 0\n ? [-q[0], -q[1], -q[2], -q[3]] : q;\n if (weights[i] > best) { best = weights[i]; dominant = aligned; }\n x += aligned[0] * weights[i]; y += aligned[1] * weights[i];\n z += aligned[2] * weights[i]; w += aligned[3] * weights[i];\n }\n const length = Math.hypot(x, y, z, w);\n // Opposed rotations at equal weight cancel and name no orientation at all.\n return length > 1e-6 ? [x / length, y / length, z / length, w / length] : dominant;\n}\n\n/** Blends by id, so a pin missing from either side simply keeps its own pose \u2014\n * it appears on both sides of the blend and cannot move. Everything but the\n * transform comes from the destination: ids, rest positions and flags are\n * shared between slots and are not animated. */\nexport function blendPins(from: readonly PinRecord[], to: readonly PinRecord[], t: number, parents: PinParents = new Map()): readonly PinRecord[] {\n if (t <= 0 && from.length === to.length && to.every((pin, i) => from[i]?.id === pin.id)) return from;\n const aligned = to.map(pin => from.find(other => other.id === pin.id) ?? pin);\n return blendPoses(to, [aligned, to], [1 - t, t], parents);\n}\n\n/** Every pose at once, by weight. `poses` are the same pins in the same order\n * as `base` \u2014 they all come from resolving one document \u2014 so this walks them by\n * index rather than searching per pin per frame.\n *\n * The blend happens in each pin's PARENT frame, never in world space. A chain\n * posed two ways differs mostly in its joints' rotations, and averaging world\n * positions cuts the chord between them: the limb shortens in the middle of\n * every transition and lengthens again at each pose. In the parent's frame only\n * the joint's own rotation and offset move, so the chain keeps its shape, and a\n * pin's transform stays relative to whatever IK did to its parent \u2014 which is\n * what makes moving an IK target interpolate as one arc rather than dragging\n * every pin along a straight line of its own. */\nexport function blendPoses(base: readonly PinRecord[], poses: readonly (readonly PinRecord[])[], weights: readonly number[], parents: PinParents = new Map()): readonly PinRecord[] {\n if (!poses.length || poses.some(pose => pose.length !== base.length)) return base;\n const { order, parentOf } = hierarchyOrder(base, parents);\n const world = new Array<PinPose>(base.length), blended = new Array<PinRecord>(base.length);\n for (const i of order) {\n const parent = parentOf[i], parentWorld = parent === undefined ? undefined : world[parent];\n const locals = poses.map((pose, k) => localPose(pose[i].pose, parent === undefined ? undefined : poses[k][parent].pose));\n world[i] = worldPose(weightedPose(locals, weights), parentWorld);\n const pin: PinRecord = { ...base[i], pose: world[i] };\n // A goal is an anchor in the world, not a point on its parent. A planted\n // foot has the same goal in every pose, and must come out of the blend as\n // that goal exactly however the body above it moves.\n if (!poses.every(pose => pose[i].ikTarget)) { blended[i] = pin; continue; }\n const targets = poses.map(pose => pose[i].ikTarget!);\n blended[i] = { ...pin, ikTarget: {\n position: [0, 1, 2].map(axis => targets.reduce((sum, target, k) => sum + target.position[axis] * weights[k], 0)) as unknown as Point,\n rotation: blendRotations(targets.map(target => target.rotation), weights),\n } };\n }\n return blended;\n}\n\n/** One pose out of many, by weight. */\nfunction weightedPose(poses: readonly PinPose[], weights: readonly number[]): PinPose {\n const position: [number, number, number] = [0, 0, 0], scale: [number, number, number] = [0, 0, 0];\n for (let k = 0; k < poses.length; k++) for (let axis = 0; axis < 3; axis++) {\n position[axis] += poses[k].position[axis] * weights[k];\n scale[axis] += poses[k].scale[axis] * weights[k];\n }\n return { position, rotation: blendRotations(poses.map(pose => pose.rotation), weights), scale };\n}\n", "import { Vector3 } from 'three';\n\nexport const MAX_WIND_STRENGTH = 4;\n\n/** A single weather control drives pin motion and surface pressure. Sparse pin\n * loads stay bounded; fabric pressure has room to grow through a storm. */\nexport function windProfile(strength: number) {\n const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));\n const label = level === 0 ? 'Off' : level < .75 ? 'Breeze' : level < 1.5 ? 'Windy' : level < 2.5 ? 'Strong wind' : level < 3.3 ? 'Gale' : 'Storm';\n return {\n label,\n load: 30 * level * level / (.8 + level * level),\n surfaceLoad: 4 * level * level,\n gust: .14 + .12 * level,\n crosswind: .05 + .07 * level,\n gustRate: .42 + .12 * level,\n };\n}\n\n/** Deterministic scene-local prevailing wind with slow gusts and spatially\n * varying eddies. Force is an acceleration scaled to the model's size, so a\n * tiny prop and a large character respond comparably at the same setting. */\nexport function windAcceleration(seconds: number, strength: number, scale: number, position: readonly number[]) {\n if (strength <= 0) return new Vector3();\n const size = Math.max(1e-4, scale);\n const profile = windProfile(strength);\n // Advect the gust bands along +X. Nearby controls see related wind, while\n // their phase delay keeps a large sheet or branch hierarchy from moving as\n // one perfectly synchronized rigid object.\n const along = position[0] / size, lateral = (position[1] * .67 + position[2] * .33) / size;\n const slow = seconds * profile.gustRate - along * .55;\n const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * .4;\n const gust = Math.max(.2, 1 + profile.gust * (.7 * Math.sin(slow) + .3 * Math.sin(fast + 1.3)));\n const cross = profile.crosswind * (.65 * Math.sin(fast + lateral) + .35 * Math.sin(slow * .73 - lateral * .6));\n return new Vector3(1, cross * .35, cross).normalize().multiplyScalar(profile.load * size * gust);\n}\n", "import { IK_CHAIN_KINDS, MAX_FUR_DEPTH, type IKChainRole, type PinRecord, type Point, type Rotation } from './pin-types.js';\nimport { MAX_DEFORMATION_PINS } from './limits.js';\nimport { DEFAULT_MOTION, validateMotionSettings } from './motion-settings.js';\nimport { validateIKConstraint, type IKConstraint } from './ik-constraints.js';\nimport { capturePose, POSE_SLOTS, resolvePose, type PoseSlot } from './pose-slots.js';\nimport type { PinParents } from './pin-types.js';\nimport { MAX_POSE_SECONDS, MIN_POSE_SECONDS, type PoseTiming } from './pose-timeline.js';\nimport { MAX_WIND_STRENGTH } from './wind.js';\n\nfunction record(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid joints JSON object.');\n return value as Record<string, unknown>;\n}\nfunction numbers(value: unknown, length: number): number[] {\n if (!Array.isArray(value) || value.length !== length || !value.every(v => typeof v === 'number' && Number.isFinite(v))) throw new Error('Invalid joint coordinates.');\n return [...value];\n}\nfunction point(value: unknown): Point { const v = numbers(value, 3); return [v[0], v[1], v[2]]; }\nfunction quaternion(value: unknown): Rotation { const v = numbers(value, 4); return [v[0], v[1], v[2], v[3]]; }\nexport function validateJoints(value: unknown, maximum = MAX_DEFORMATION_PINS): readonly PinRecord[] {\n if (!Array.isArray(value) || value.length > maximum) throw new Error(`Joints JSON must contain at most ${maximum} joints.`);\n const ids = new Set<string>();\n const pins = value.map(item => {\n const pin = record(item), pose = record(pin.pose);\n if (typeof pin.id !== 'string' || !pin.id || ids.has(pin.id)) throw new Error('Joint IDs must be unique non-empty strings.');\n ids.add(pin.id);\n if (typeof pin.independent !== 'boolean' || (pin.rigidGroup !== null && (typeof pin.rigidGroup !== 'string' || !pin.rigidGroup))) throw new Error('Invalid joint membership.');\n if (pin.guide !== undefined && typeof pin.guide !== 'boolean') throw new Error('Invalid guide flag.');\n if (pin.authored !== undefined && typeof pin.authored !== 'boolean') throw new Error('Invalid authored flag.');\n if (pin.ik !== undefined && typeof pin.ik !== 'boolean') throw new Error('Invalid IK flag.');\n if (pin.wiggle !== undefined && typeof pin.wiggle !== 'boolean') throw new Error('Invalid Wiggle flag.');\n if (pin.cloth !== undefined && typeof pin.cloth !== 'boolean') throw new Error('Invalid Cloth flag.');\n if (pin.fur !== undefined && typeof pin.fur !== 'boolean') throw new Error('Invalid Fur flag.');\n if (pin.furDepth !== undefined && (typeof pin.furDepth !== 'number' || !Number.isFinite(pin.furDepth) || pin.furDepth < 0 || pin.furDepth > MAX_FUR_DEPTH)) throw new Error('Invalid Fur depth.');\n const chainRole=pin.chainRole===undefined?undefined:(()=>{\n const value=record(pin.chainRole);\n if(!IK_CHAIN_KINDS.includes(value.kind as IKChainRole['kind'])||!['center','left','right'].includes(value.side as string)||\n (value.position!==undefined&&!['front','hind'].includes(value.position as string)))throw new Error('Invalid IK chain role.');\n return {kind:value.kind as IKChainRole['kind'],side:value.side as IKChainRole['side'],...(value.position?{position:value.position as 'front'|'hind'}:{})};\n })();\n if (Number(Boolean(pin.ik)) + Number(Boolean(pin.wiggle)) + Number(Boolean(pin.cloth)) + Number(Boolean(pin.fur)) > 1) throw new Error('Choose IK, Wiggle, Cloth or Fur.');\n const motion = pin.motion === undefined ? undefined : (()=>{\n const raw=record(pin.motion), result={reach:Number(raw.reach),frequency:Number(raw.frequency),damping:Number(raw.damping),massInfluence:raw.massInfluence===undefined?DEFAULT_MOTION.massInfluence:Number(raw.massInfluence),strength:raw.strength===undefined?DEFAULT_MOTION.strength:Number(raw.strength)};\n for(const key of ['massInfluence','strength']) if(raw[key]!==undefined && typeof raw[key]!=='number') throw new Error('Invalid motion settings.');\n if (typeof raw.reach!=='number' || typeof raw.frequency!=='number' || typeof raw.damping!=='number') throw new Error('Invalid motion settings.');\n validateMotionSettings(result); return result;\n })();\n const ikConstraint=pin.ikConstraint===undefined?undefined:(()=>{const raw=record(pin.ikConstraint);const value={mode:raw.mode,axis:raw.axis,min:raw.min,max:raw.max,...(raw.orientation!==undefined?{orientation:quaternion(raw.orientation)}:{}),...(raw.maxY!==undefined?{maxY:raw.maxY}:{})} as IKConstraint;validateIKConstraint(value);return value;})();\n const ikTarget=pin.ikTarget === undefined ? undefined : (()=>{\n const raw=record(pin.ikTarget),rotation=quaternion(raw.rotation);\n if (Math.abs(Math.hypot(...rotation)-1)>1e-4) throw new Error('Invalid IK target rotation.');\n return {position:point(raw.position),rotation};\n })();\n if (pin.guide && (pin.rigidGroup || pin.independent)) throw new Error('Guides cannot be rigid members or roots.');\n const scale = point(pose.scale), rotation = quaternion(pose.rotation);\n if (scale.some(v => v < 0.01 || v > 100) || Math.abs(Math.hypot(...rotation) - 1) > 1e-4) throw new Error('Invalid joint rotation or scale.');\n return { id: pin.id, independent: pin.independent, rigidGroup: pin.rigidGroup, ...(pin.authored === true ? { authored: true } : {}), ...(typeof pin.guide === 'boolean' ? { guide: pin.guide } : {}), ...(typeof pin.ik === 'boolean' ? { ik: pin.ik } : {}),\n ...(ikConstraint?{ikConstraint}:{}),...(chainRole?{chainRole}:{}),...(motion ? {motion}:{}),...(ikTarget ? {ikTarget}:{}),...(typeof pin.wiggle === 'boolean' ? {wiggle:pin.wiggle} : {}),...(typeof pin.cloth === 'boolean' ? {cloth:pin.cloth} : {}),...(typeof pin.fur === 'boolean' ? {fur:pin.fur} : {}),...(pin.furDepth !== undefined ? {furDepth:pin.furDepth as number} : {}), rest: point(pin.rest), pose: { position: point(pose.position), rotation, scale } };\n });\n for (const pin of pins) if (pin.rigidGroup) {\n const anchor = pins.find(other => other.rigidGroup === pin.rigidGroup)!;\n const dot = pin.pose.rotation.reduce((sum, v, i) => sum + v * anchor.pose.rotation[i], 0);\n if (pin.pose.scale.some(v => Math.abs(v - anchor.pose.scale[0]) > 1e-5) || 1 - Math.abs(dot) > 1e-5) throw new Error('Rigid joints must share rotation and uniform scale.');\n }\n return pins;\n}\nexport interface JointsRig { pins:readonly PinRecord[];activePose:number;poseSlots:readonly PoseSlot[];poseTimes:readonly PoseTiming[];windStrength?:number }\nfunction validatePoseTimes(value:unknown):readonly PoseTiming[]{\n if(!Array.isArray(value)||value.length>POSE_SLOTS)throw new Error('Invalid pose times.');\n const slots=new Set<number>();\n return value.map(item=>{\n const entry=record(item);\n if(!Number.isInteger(entry.slot)||(entry.slot as number)<0||(entry.slot as number)>POSE_SLOTS||slots.has(entry.slot as number))throw new Error('Invalid pose time slot.');\n slots.add(entry.slot as number);\n if(typeof entry.seconds!=='number'||!Number.isFinite(entry.seconds)||entry.seconds<MIN_POSE_SECONDS||entry.seconds>MAX_POSE_SECONDS)throw new Error('Invalid pose time.');\n return {slot:entry.slot as number,seconds:entry.seconds};\n }).sort((a,b)=>a.slot-b.slot);\n}\n/** Slots are written out in full. A pin the hierarchy places is left unsaid in\n * the editor so it keeps following its parent, but a file has no voxel field to\n * rebuild that hierarchy from and older readers would drop it to rest, so the\n * inherited pose is resolved here and stored. */\nexport function validateRig(value:JointsRig, maximum = MAX_DEFORMATION_PINS, parents:PinParents = new Map()):JointsRig{\n const pins=validateJoints(value.pins,maximum);\n if (value.windStrength !== undefined && (!Number.isFinite(value.windStrength) || value.windStrength < 0 || value.windStrength > MAX_WIND_STRENGTH)) throw new Error('Invalid wind strength.');\n if(!Number.isInteger(value.activePose)||value.activePose<0||value.activePose>POSE_SLOTS||!Array.isArray(value.poseSlots)||value.poseSlots.length>POSE_SLOTS)throw new Error('Invalid pose slots.');\n const slots=new Set<number>(),ids=new Set(pins.map(p=>p.id));\n const poseSlots=value.poseSlots.map(slot=>{\n if(!slot||!Number.isInteger(slot.slot)||slot.slot<1||slot.slot>POSE_SLOTS||slots.has(slot.slot)||!Array.isArray(slot.poses))throw new Error('Invalid pose slot.');slots.add(slot.slot);\n const pinIds=new Set<string>();for(const p of slot.poses){if(!p||!ids.has(p.id)||pinIds.has(p.id))throw new Error('Invalid pose pin.');pinIds.add(p.id);}\n return {slot:slot.slot,poses:capturePose(validateJoints(resolvePose(pins,slot,parents),maximum))};\n }).filter(slot=>slot.slot!==value.activePose);\n return {pins,activePose:value.activePose,poseSlots,poseTimes:validatePoseTimes(value.poseTimes??[]),...(value.windStrength !== undefined ? {windStrength:value.windStrength} : {})};\n}\n", "import { Goal, Joint, Link, Solver } from 'closed-chain-ik/core';\nimport { Euler, Matrix4, Quaternion, Vector3 } from 'three';\nimport type { PinRecord, PinPose, Point, Rotation } from './pin-types.js';\nimport { DEFAULT_MOTION } from './motion-settings.js';\nimport type { PinParents } from './pin-types.js';\nimport { DEFAULT_IK_CONSTRAINT, constrainCone } from './ik-constraints.js';\n\nconst POSE_CONTINUITY_WEIGHT=1e-4;\n\n/** A routing guide is not a limb. Only guides leading to real joints create\n * an articulated branch; dangling guidance must not lock an IK pivot. */\nfunction articulatedNodes(pins: readonly PinRecord[], parents: PinParents) {\n const nodes = new Set<string>();\n for (const pin of pins) if (!pin.guide) {\n let id: string | undefined = pin.id;\n while (id && !nodes.has(id)) { nodes.add(id); id = parents.get(id); }\n }\n return nodes;\n}\n\n/** IDs are derived each time; no stale authored chain survives topology edits. */\nexport function ikChain(pins: readonly PinRecord[], parents: PinParents, id: string, mass: ReadonlyMap<string, number> = new Map()): PinRecord[] {\n const byId = new Map(pins.map(pin => [pin.id, pin]));\n const element = (pin: PinRecord) => pin.rigidGroup ?? pin.id;\n const articulated = articulatedNodes(pins, parents);\n const children = new Map<string, Set<string>>();\n const supportLength=new Map<string,number>();\n for (const pin of pins) {\n if (!articulated.has(pin.id)) continue;\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (!parent) continue;\n const length=Math.hypot(...pin.rest.map((x,i)=>x-parent.rest[i]))*.5;\n supportLength.set(pin.id,(supportLength.get(pin.id)??0)+length);\n supportLength.set(parent.id,(supportLength.get(parent.id)??0)+length);\n const set = children.get(element(parent)) ?? new Set<string>(); set.add(element(pin)); children.set(element(parent), set);\n }\n const chain: PinRecord[] = [], seen = new Set<string>();\n let pin = byId.get(id);\n const reach = pin?.motion?.reach ?? DEFAULT_MOTION.reach;\n let automatic:string|undefined;\n // Mass per supported rest length approximates cross-section, unlike raw\n // per-pin mass which shrinks simply because a limb gained more joints.\n const density=(p:PinRecord)=>mass.has(p.id)?mass.get(p.id)!/Math.max(supportLength.get(p.id)??0,1e-12):undefined;\n while (pin && !seen.has(element(pin))) {\n chain.unshift(pin); seen.add(element(pin));\n if (pin.independent) break;\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (!parent) break;\n // Keep the body/other limbs stationary. An immediate parent is still\n // needed as the pivot for a single-link chain.\n if (!automatic && ((children.get(element(parent))?.size ?? 0) > 1\n || (!pin.guide && !parent.guide && (density(parent) ?? 0) > 8 * Math.max(density(pin) ?? Infinity, 1e-12)))) automatic=parent.id;\n pin = parent;\n }\n if(chain.length<2)return chain;\n const distance=new Float64Array(chain.length);\n for(let i=chain.length-2;i>=0;i--)distance[i]=distance[i+1]+Math.hypot(...chain[i].rest.map((x,k)=>x-chain[i+1].rest[k]));\n const boundary=automatic?chain.findIndex(p=>p.id===automatic):-1;\n const automaticDistance=distance[Math.max(0,boundary)];\n // Reach measures REST arc length, not node count or posed/chord distance.\n // Zero starts at the endpoint (clamped to one link); subdivision must not\n // move the slider's origin by changing that first link's length.\n const budget=reach<=.5?automaticDistance*reach*2:automaticDistance+(distance[0]-automaticDistance)*(reach-.5)*2;\n const first=reach<=.5&&boundary>=0?Math.min(boundary+1,chain.length-2):0;\n let start=chain.length-2;\n for(let i=start-1;i>=first;i--)if(Math.abs(distance[i]-budget)<Math.abs(distance[start]-budget))start=i;\n if(reach===1)start=0;\n return chain.slice(start);\n}\n\nexport function solvePinIK(pins: readonly PinRecord[], parents: PinParents, id: string, target: Point,\n mass?: ReadonlyMap<string, number>, targetRotation?: Rotation): { id: string; pose: PinPose }[] {\n const pin=pins.find(p=>p.id===id)!;\n return solvePinIKGoals(pins,parents,[{id,position:target,rotation:targetRotation ?? pin.ikTarget?.rotation ?? pin.pose.rotation}],mass);\n}\n\nexport type IKGoal = {id:string;position:Point;rotation:Rotation};\n\n/** Endpoint editing is local. Shared body frames and sibling branches retain\n * their authored poses; root/body edits use the separate multi-goal solve. */\nexport function solveLocalPinIK(pins:readonly PinRecord[],parents:PinParents,goal:IKGoal,mass?:ReadonlyMap<string,number>,floor=-Infinity){\n const chain=ikChain(pins,parents,goal.id,mass),key=(p:PinRecord)=>p.rigidGroup??p.id;\n const keys=new Set(chain.map(key)),byId=new Map(pins.map(p=>[p.id,p]));\n const articulated = articulatedNodes(pins, parents);\n let boundary=-1;\n // Children below the endpoint are followers, never competing side branches.\n for(let i=0;i<chain.length-1;i++)if(chain[i].independent || pins.some(p=>{\n if (!articulated.has(p.id)) return false;\n const parent=byId.get(parents.get(p.id)??'');return parent&&key(parent)===key(chain[i])&&!keys.has(key(p));\n }))boundary=i;\n const shared=boundary>=0&&pins.some(p=>{\n if(!articulated.has(p.id))return false;\n const parent=byId.get(parents.get(p.id)??'');\n return parent&&key(parent)===key(chain[boundary])&&!keys.has(key(p));\n });\n // A shared attachment fixes the body. The outgoing limb gets a separate\n // zero-length branch pivot in the solver, so the first link can still swing.\n // A lone independent root has no sibling to disturb and retains the exact\n // two-link analytic solve through its temporary root rotation.\n const fixed=new Set(chain.slice(0,shared?boundary+1:Math.max(0,boundary)).flatMap(p=>pins.filter(q=>key(q)===key(p)).map(q=>q.id)));\n const moving=new Set(chain.slice(boundary+1).map(key));\n for(let added=true;added;){added=false;for(const p of pins){const parent=byId.get(parents.get(p.id)??'');if(parent&&moving.has(key(parent))&&!moving.has(key(p))){moving.add(key(p));added=true;}}}\n const retained=new Set(boundary>=0?[key(chain[boundary])]:[]);\n return solvePinIKGoals(pins,parents,[goal],mass,fixed,retained,floor).filter(p=>moving.has(key(byId.get(p.id)!)));\n}\n\n/** Solve separate planted limbs against the same body pose. Their temporary\n * attachment rotations must not become rotations of the shared torso frame. */\nexport function solvePlantedPinIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass?:ReadonlyMap<string,number>,fixed:ReadonlySet<string>=new Set(),floor=-Infinity){\n if(!goals.length)return [];\n const edits=new Map<string,{id:string;pose:PinPose}>();\n let independent=true;\n for(const goal of goals){\n const limb=solveLocalPinIK(pins,parents,goal,mass,floor);\n for(const edit of limb){\n if(fixed.has(edit.id)||edits.has(edit.id)){independent=false;break;}\n edits.set(edit.id,edit);\n }\n if(!independent)break;\n }\n return independent?[...edits.values()]:solvePinIKGoals(pins,parents,goals,mass,fixed,new Set(),floor);\n}\n\n/** Body motion and imported-pose reconstruction use the same full-chain solve.\n * Shared attachment frames are held; each limb gets its own branch pivot. */\nexport function solveBodyIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass:ReadonlyMap<string,number>,fixed:ReadonlySet<string>,floor=-Infinity){\n const poleChains=new Map(goals.map(goal=>[goal.id,ikChain(pins,parents,goal.id,mass)]));\n const full=pins.map(pin=>pin.ik?{...pin,motion:{...DEFAULT_MOTION,...pin.motion,reach:1}}:pin);\n const uses=new Map<string,number>();\n for(const goal of goals)for(const pin of ikChain(full,parents,goal.id,mass))uses.set(pin.id,(uses.get(pin.id)??0)+1);\n const anchors=new Set([...fixed,...[...uses].filter(([,count])=>count>1).map(([id])=>id)]);\n return solvePinIKGoals(full,parents,goals,mass,anchors,new Set(),floor,poleChains);\n}\n\n/** One articulated forest, one joint solve. Shared joints are never overwritten\n * by a later endpoint, and every child offset retains its authored length. */\nexport function solvePinIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass?:ReadonlyMap<string,number>,fixed:ReadonlySet<string>=new Set(),retained:ReadonlySet<string>=new Set(),floor=-Infinity,poleChains:ReadonlyMap<string,readonly PinRecord[]> = new Map()):{id:string;pose:PinPose}[] {\n if (!goals.length) return [];\n const byId=new Map(pins.map(p=>[p.id,p])),key=(p:PinRecord)=>p.rigidGroup ?? p.id;\n const groups=new Map<string,PinRecord[]>();\n for(const pin of pins){const group=groups.get(key(pin)) ?? [];group.push(pin);groups.set(key(pin),group);}\n const active=new Set<string>(), roots=new Set<string>();\n const bendSeeds=new Map<string,Vector3>();\n let size=0;\n for(const goal of goals){\n const chain=ikChain(pins,parents,goal.id,mass);\n if(chain.length<2) throw new Error('IK needs a parent chain. Add a parent pin or remove Independent from this endpoint.');\n for(const p of chain) active.add(key(p));\n roots.add(key(chain[0]));\n // Only a straight, contracting chain needs a perturbation: at full\n // extension its positional Jacobian cannot discover a bend. Seeding an\n // already bent chain injects rotation on every drag sample and accumulates\n // drift despite a nearly stationary target.\n const start=new Vector3().fromArray(chain[0].pose.position),direction=new Vector3().fromArray(chain.at(-1)!.pose.position).sub(start);\n const span=direction.length();\n if(span>1e-8 && new Vector3().fromArray(goal.position).distanceTo(start)<span*(1-1e-6)){\n direction.divideScalar(span);\n const straight=chain.every(p=>new Vector3().fromArray(p.pose.position).sub(start).cross(direction).lengthSq()<span*span*1e-12);\n const candidate=straight?chain.slice(1,-1).find(p=>!groups.get(key(p))!.some(q=>fixed.has(q.id)) && ['free','cone'].includes((p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode)):undefined;\n if(candidate){\n // Bend in the plane the goal is actually in: perpendicular to both the\n // chain and the way it has to reach. Seeding off the chain's smallest\n // world component instead picks a plane with no relation to the goal,\n // and a straight arm pulled sideways swings out of the screen on its\n // way there \u2014 deterministic, but not a bend anyone asked for.\n const axis=new Vector3().crossVectors(direction,new Vector3().fromArray(goal.position).sub(start));\n if(axis.lengthSq()<1e-12){\n // The goal lies along the chain, so no plane is implied by it; any\n // axis across the chain will do, chosen the same way every time.\n const components=direction.toArray().map(Math.abs);\n axis.setComponent(components.indexOf(Math.min(...components)),1).addScaledVector(direction,-axis.dot(direction));\n }\n bendSeeds.set(key(candidate),axis.normalize());\n }\n }\n size=Math.max(size,chain.slice(1).reduce((sum,p,i)=>sum+new Vector3().fromArray(p.pose.position).distanceTo(new Vector3().fromArray(chain[i].pose.position)),0));\n }\n if(size<1e-8) throw new Error('IK chain has no length. Separate its rest pins first.');\n const parentGroup=new Map<string,string>();\n for(const [id,members] of groups){\n const parent=members.map(p=>byId.get(parents.get(p.id) ?? '')).find(p=>p && key(p)!==id);\n if(parent) parentGroup.set(id,key(parent));\n }\n // Include followers in the graph so branch attachments keep their lengths too.\n const affected=new Set(active);\n for(let changed=true;changed;){changed=false;for(const [id,parent] of parentGroup) if(affected.has(parent)&&!affected.has(id)){affected.add(id);changed=true;}}\n const unchanged=goals.every(g=>{const p=byId.get(g.id)!;return new Vector3().fromArray(g.position).distanceToSquared(new Vector3().fromArray(p.pose.position))<1e-20 && new Quaternion().fromArray(g.rotation).angleTo(new Quaternion().fromArray(p.pose.rotation))<1e-10;});\n if(unchanged && !pins.some(p=>p.ikConstraint && p.ikConstraint.mode!=='free')) return pins.filter(p=>affected.has(key(p))).map(p=>({id:p.id,pose:p.pose}));\n const origin=new Vector3().fromArray(byId.get(goals[0].id)!.pose.position);\n const frames=new Map<string,Link>(), forest:Link[]=[], building=new Set<string>();\n const coneJoints=new Map<string,Joint>();\n const freeJoints=new Map<string,Joint>();\n const branchJoints=new Map<string,{joint:Joint;frame:Link}>();\n const build=(id:string):Link=>{\n const cached=frames.get(id);if(cached) return cached;\n if(building.has(id)) throw new Error('Cyclic IK hierarchy.');building.add(id);\n const pin=groups.get(id)![0],parentId=parentGroup.get(id),parent=parentId ? groups.get(parentId)![0] : undefined;\n const parentFrame=parentId ? build(parentId) : new Link();\n let attachment=parentFrame;\n if(parentId&&active.has(id)&&!groups.get(id)!.some(p=>fixed.has(p.id))&&groups.get(parentId)!.some(p=>fixed.has(p.id))){\n const pivot=new Joint();pivot.setDoF(3,4,5);pivot.setDoFValues(0,0,0);pivot.setRestPoseValues(0,0,0);\n parentFrame.addChild(pivot);attachment=new Link();pivot.addChild(attachment);\n branchJoints.set(id,{joint:pivot,frame:attachment});\n }\n const parentRotation=parent ? new Quaternion().fromArray(parent.pose.rotation) : new Quaternion();\n const position=new Vector3().fromArray(pin.pose.position).sub(parent ? new Vector3().fromArray(parent.pose.position):origin).applyQuaternion(parentRotation.clone().invert()).divideScalar(size);\n const relative=parentRotation.clone().invert().multiply(new Quaternion().fromArray(pin.pose.rotation)).normalize();\n const joint=new Joint();joint.setPosition(position.x,position.y,position.z);attachment.addChild(joint);\n const link=new Link(),constraint=pin.ikConstraint ?? DEFAULT_IK_CONSTRAINT;\n const movable=active.has(id)&&!groups.get(id)!.some(p=>fixed.has(p.id));\n if(!movable || constraint.mode==='locked') joint.setQuaternion(...relative.toArray());\n else if(constraint.mode==='hinge') {\n let axis=new Vector3();\n if(constraint.axis!=='auto') axis.setComponent(['x','y','z'].indexOf(constraint.axis),1);\n else {\n const child=pins.find(p=>parents.get(p.id)===pin.id && active.has(key(p)));\n if(parent&&child) axis.crossVectors(new Vector3().fromArray(pin.rest).sub(new Vector3().fromArray(parent.rest)),new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)));\n if(axis.lengthSq()<1e-10) {const direction=child ? new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)).normalize():new Vector3(0,1,0);axis.crossVectors(direction,Math.abs(direction.z)<.9 ? new Vector3(0,0,1):new Vector3(1,0,0));}\n axis.normalize();\n }\n const basis=new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis);\n joint.setQuaternion(...basis.toArray());link.setQuaternion(...basis.clone().invert().toArray());\n joint.setDoF(5);joint.setMinLimits(constraint.min*Math.PI/180);joint.setMaxLimits(constraint.max*Math.PI/180);\n const twist=2*Math.atan2(new Vector3(relative.x,relative.y,relative.z).dot(axis),relative.w);\n joint.setDoFValues(Math.atan2(Math.sin(twist),Math.cos(twist)));joint.setRestPoseValues(0);\n } else {\n if(constraint.mode==='cone')coneJoints.set(id,joint);\n else freeJoints.set(id,joint);\n joint.setDoF(3,4,5);\n const euler=new Euler().setFromQuaternion(relative,'ZYX');joint.setDoFValues(euler.x,euler.y,euler.z);joint.setRestPoseValues(euler.x,euler.y,euler.z);\n const seed=bendSeeds.get(id);\n if(seed && !roots.has(id) && !goals.some(g=>key(byId.get(g.id)!)===id)){\n const axis=seed.clone().applyQuaternion(parentRotation.clone().invert());\n const seeded=new Euler().setFromQuaternion(new Quaternion().setFromAxisAngle(axis,.03).multiply(relative),'ZYX');\n joint.setDoFValues(seeded.x,seeded.y,seeded.z);\n }\n }\n joint.addChild(link);frames.set(id,link);building.delete(id);if(!parentId) forest.push(parentFrame);return link;\n };\n for(const id of groups.keys()) build(id);\n // Limits describe the visible segment in the committed parent's frame, not\n // a shared attachment's temporary solver rotation or a stale inserted frame.\n const limitRotation=(id:string,rotation:Quaternion,parentRotation:Quaternion)=>{\n const pin=groups.get(id)![0];if(pin.ikConstraint?.mode!=='cone')return rotation;\n const parentId=parentGroup.get(id),parent=parentId?groups.get(parentId)![0]:undefined;\n const child=pins.find(p=>parents.get(p.id)===pin.id);\n if(retained.has(id)&&child&&!active.has(key(child)))return rotation;\n const axis=child?new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)):parent?new Vector3().fromArray(pin.rest).sub(new Vector3().fromArray(parent.rest)):new Vector3(0,1,0);\n if(axis.lengthSq()<1e-12)axis.set(0,1,0);\n const movingAxis=child?new Vector3().fromArray(child.pose.position).sub(new Vector3().fromArray(pin.pose.position)).applyQuaternion(new Quaternion().fromArray(pin.pose.rotation).invert()):axis;\n if(movingAxis.lengthSq()<1e-12)movingAxis.copy(axis);\n const reference=parentId&&retained.has(parentId)?new Quaternion().fromArray(parent!.pose.rotation):parentRotation;\n const relative=reference.clone().invert().multiply(parentRotation).multiply(rotation);\n return parentRotation.clone().invert().multiply(reference).multiply(constrainCone(relative,axis,pin.ikConstraint,movingAxis));\n };\n // Continuity refers to the pose on screen, before analytic initialization\n // or cone projection chooses a candidate. Include temporary body pivots.\n const priorRotations=new Map([...frames.values(),...[...branchJoints.values()].map(branch=>branch.frame)].map(frame=>{\n frame.updateMatrixWorld();return [frame,new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld))] as const;\n }));\n const closures:Goal[]=[];\n for(const target of goals){\n const pin=byId.get(target.id)!,anchor=groups.get(key(pin))![0];\n const offset=new Vector3().fromArray(pin.pose.position).sub(new Vector3().fromArray(anchor.pose.position)).applyQuaternion(new Quaternion().fromArray(anchor.pose.rotation).invert()).divideScalar(size);\n const attachment=new Joint();attachment.setPosition(...offset.toArray());frames.get(key(pin))!.addChild(attachment);\n const tip=new Link();attachment.addChild(tip);\n const goal=new Goal();\n const freeEndpoint=groups.get(key(pin))!.length===1 && (!pin.ikConstraint || pin.ikConstraint.mode==='free');\n if(freeEndpoint) goal.setGoalDoF(0,1,2);else goal.setGoalDoF(0,1,2,3,4,5);\n goal.makeClosure(tip);\n const requested=new Vector3().fromArray(target.position);\n if(goals.length===1 && freeEndpoint){\n const chain=ikChain(pins,parents,target.id,mass);\n const first=chain.findIndex(p=>!groups.get(key(p))!.some(q=>fixed.has(q.id)) && (p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode!=='locked');\n const moving=first<0?[]:chain.slice(branchJoints.has(key(chain[first]))?Math.max(0,first-1):first);\n // For an unconstrained ball-joint chain its link lengths define a\n // reachable spherical shell. Solve against that shell, not an impossible\n // residual which can stall the iterative solver away from the closest\n // pose. The authored world target is deliberately left unchanged.\n if(moving.length>1 && moving.every((p,i)=>(i===0&&branchJoints.has(key(moving[1])))||(!fixed.has(p.id) && groups.get(key(p))!.length===1 && (p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode==='free'))){\n const pivot=new Vector3().fromArray(moving[0].pose.position);\n const lengths=moving.slice(1).map((p,i)=>new Vector3().fromArray(p.pose.position).distanceTo(new Vector3().fromArray(moving[i].pose.position)));\n const outer=lengths.reduce((a,b)=>a+b,0),inner=Math.max(0,2*Math.max(...lengths)-outer),delta=requested.clone().sub(pivot),distance=delta.length();\n if(distance<inner || distance>outer){\n if(distance<1e-12)delta.fromArray(moving.at(-1)!.pose.position).sub(pivot);\n if(delta.lengthSq()>1e-24)requested.copy(pivot).add(delta.setLength(Math.max(inner,Math.min(outer,distance))));\n }\n if(moving.length===2){\n // One free link has a closed-form minimum-rotation solution. Its\n // positional Jacobian is rank deficient (twist is unobservable), so\n // initialize it analytically instead of relying on an arbitrary seed.\n const before=new Vector3().fromArray(moving[1].pose.position).sub(pivot),after=requested.clone().sub(pivot);\n if(before.lengthSq()>1e-24 && after.lengthSq()>1e-24){\n const branch=branchJoints.get(key(moving[1])),parent=branch?moving[0]:byId.get(parents.get(moving[0].id)??'');\n const local=parent?new Quaternion().fromArray(parent.pose.rotation).invert():new Quaternion();\n local.multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().fromArray(moving[0].pose.rotation));\n const euler=new Euler().setFromQuaternion(local,'ZYX');(branch?.joint??freeJoints.get(key(moving[0])))!.setDoFValues(euler.x,euler.y,euler.z);\n }\n }\n }\n }\n goal.setPosition(...requested.sub(origin).divideScalar(size).toArray());goal.setQuaternion(...target.rotation);\n closures.push(goal);\n }\n // Two-link limbs have an exact positional solution. Keep their existing bend\n // plane and transport each frame by the minimum swing: an Euler/SVD solve can\n // choose a different elbow branch or arbitrary axial twist near singularity.\n // Cone projection + constrained refinement below still enforce authored limits.\n let analytic=false;\n if(goals.length===1){\n const goal=goals[0],chain=ikChain(pins,parents,goal.id,mass);\n const first=chain.findIndex((p,i)=>coneJoints.has(key(p))||freeJoints.has(key(p))||(i+1<chain.length&&branchJoints.has(key(chain[i+1]))));\n const limb=first<0?[]:chain.slice(first),tipPin=byId.get(goal.id)!;\n if(limb.length===3&&limb.every(p=>groups.get(key(p))!.length===1)\n &&limb.slice(0,2).every((p,i)=>coneJoints.has(key(p))||freeJoints.has(key(p))||branchJoints.has(key(limb[i+1])))\n &&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\n const world=(p:PinRecord)=>{const frame=frames.get(key(p))!;frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const matrices=limb.map(world),points=matrices.map(m=>new Vector3().setFromMatrixPosition(m));\n const [base,knee,tip]=points,a=base.distanceTo(knee),b=knee.distanceTo(tip);\n const direction=new Vector3().fromArray(closures[0].position).sub(base);\n if(a>1e-10&&b>1e-10&&direction.lengthSq()>1e-20){\n const distance=Math.max(Math.abs(a-b)+1e-9,Math.min(a+b-1e-9,direction.length()));direction.normalize();\n const oldAxis=tip.clone().sub(base).normalize();\n const bend=knee.clone().sub(base).addScaledVector(oldAxis,-knee.clone().sub(base).dot(oldAxis));\n // Transport the previous pole with the target, instead of projecting it\n // against the new axis (which can flip the knee on a large target move).\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(oldAxis,direction));\n if(bend.lengthSq()<1e-16){\n bend.fromArray(limb[1].rest).sub(new Vector3().fromArray(limb[0].rest));\n const restAxis=new Vector3().fromArray(limb[2].rest).sub(new Vector3().fromArray(limb[0].rest)).normalize();\n bend.addScaledVector(restAxis,-bend.dot(restAxis)).applyQuaternion(new Quaternion().setFromRotationMatrix(matrices[0]));\n bend.addScaledVector(direction,-bend.dot(direction));\n }\n if(bend.lengthSq()<1e-16){bend.set(Math.abs(direction.x)<.8?1:0,Math.abs(direction.x)<.8?0:1,0);bend.addScaledVector(direction,-bend.dot(direction));}\n const along=(a*a-b*b+distance*distance)/(2*distance);\n const desiredKnee=base.clone().addScaledVector(direction,along).addScaledVector(bend.normalize(),Math.sqrt(Math.max(0,a*a-along*along)));\n const desiredTip=base.clone().addScaledVector(direction,distance);\n for(const [i,end] of [desiredKnee,desiredTip].entries()){\n const pin=limb[i],branch=branchJoints.get(key(limb[i+1])),frame=branch?.frame??frames.get(key(pin))!;\n frame.updateMatrixWorld();\n const matrix=new Matrix4().fromArray(frame.matrixWorld),pivot=new Vector3().setFromMatrixPosition(matrix);\n const before=new Vector3().setFromMatrixPosition(world(limb[i+1])).sub(pivot),after=end.clone().sub(pivot);\n const parentId=parentGroup.get(key(pin)),parentFrame=branch?frames.get(key(pin)):branchJoints.get(key(pin))?.frame??(parentId?frames.get(parentId):undefined);parentFrame?.updateMatrixWorld();\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\n const rotation=parentRotation.invert().multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n const euler=new Euler().setFromQuaternion(rotation,'ZYX');(branch?.joint??coneJoints.get(key(pin))??freeJoints.get(key(pin)))!.setDoFValues(euler.x,euler.y,euler.z);\n }\n analytic=true;\n }\n }\n }\n const positionOnlyGoal=goals.length===1&&groups.get(key(byId.get(goals[0].id)!))!.length===1\n &&(!byId.get(goals[0].id)!.ikConstraint||byId.get(goals[0].id)!.ikConstraint!.mode==='free');\n const positionOnlyGoals=goals.every(goal=>groups.get(key(byId.get(goal.id)!))!.length===1\n &&(!byId.get(goal.id)!.ikConstraint||byId.get(goal.id)!.ikConstraint!.mode==='free'));\n // A lone planted foot has a prior bend in the current frame. Starting a\n // global SVD solve there can choose another elbow branch on a tiny edit;\n // the constrained descent below instead continues that bend.\n if(!analytic&&!positionOnlyGoal&&!positionOnlyGoals){\n const solver=new Solver([...forest,...closures]);solver.useSVD=true;solver.maxIterations=48;solver.restPoseFactor=.001;\n solver.translationConvergeThreshold=1e-6;solver.rotationConvergeThreshold=1e-6;solver.translationErrorClamp=.2;\n solver.solve();\n }\n // Project oriented elliptical swing limits in parent-to-child order. Updating the joint\n // frame carries descendants rigidly, so limiting a cone never stretches links.\n const projectCones=()=>{for(const [id,joint] of coneJoints){\n const parentId=parentGroup.get(id), frame=frames.get(id)!;\n frame.updateMatrixWorld();\n const parentFrame=branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\n const relative=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld)));\n const limited=limitRotation(id,relative,parentRotation),euler=new Euler().setFromQuaternion(limited,'ZYX');\n joint.setDoFValues(euler.x,euler.y,euler.z);frame.updateMatrixWorld();\n }\n };\n if(goals.length===1||!positionOnlyGoals)projectCones();\n if(goals.length>1&&positionOnlyGoals){\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const tips=goals.map(goal=>({goal,frame:frames.get(key(byId.get(goal.id)!))!,desired:new Vector3().fromArray(closures[goals.indexOf(goal)].position),chain:ikChain(pins,parents,goal.id,mass).slice(0,-1).reverse()}));\n const poles=tips.flatMap(tip=>{\n const chain=poleChains.get(tip.goal.id);\n if(!chain||chain.length<3)return [];\n const base=chain[0],knee=chain[Math.floor((chain.length-1)/2)],end=chain.at(-1)!;\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest));\n const restBend=new Vector3().fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\n if(restAxis.lengthSq()<1e-16)return [];\n restBend.addScaledVector(restAxis,-restBend.dot(restAxis)/restAxis.lengthSq());\n if(restBend.length()<restAxis.length()*.02)return [];\n const minBend=Math.min(.03,restBend.length()/size*.5);\n return [{base,knee,chain,tip,minBend,restAxis:restAxis.normalize(),restPole:restBend.normalize()}];\n });\n const poleState=(pole:typeof poles[number])=>{\n const base=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.base))!));\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\n const axis=pole.tip.desired.clone().sub(base).normalize();\n const preferred=pole.restPole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.restAxis,axis));\n preferred.addScaledVector(axis,-preferred.dot(axis)).normalize();\n const bend=knee.sub(base);bend.addScaledVector(axis,-bend.dot(axis));\n return {base,axis,preferred,bend};\n };\n const initial=[...new Set(tips.flatMap(tip=>tip.chain.flatMap(pin=>[frames.get(key(pin)),branchJoints.get(key(pin))?.frame]).filter((frame):frame is Link=>Boolean(frame))))]\n .map(frame=>({frame,rotation:new Quaternion().setFromRotationMatrix(world(frame))}));\n const cost=()=>tips.reduce((sum,tip)=>sum+new Vector3().setFromMatrixPosition(world(tip.frame)).distanceToSquared(tip.desired),0)\n +POSE_CONTINUITY_WEIGHT*initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0)\n +10*poles.reduce((sum,pole)=>{const {preferred,bend}=poleState(pole);\n return sum+Math.max(0,pole.minBend-bend.dot(preferred))**2;},0);\n for(let sweep=0;sweep<96;sweep++){\n if(cost()<1e-12)break;\n let largestChange=0;\n for(const tip of tips)for(const pin of tip.chain){\n const id=key(pin),joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\n for(const [index,joint] of joints.entries()){\n if(!joint)continue;\n const branch=index===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix),end=new Vector3().setFromMatrixPosition(world(tip.frame));\n const a=end.sub(pivot),b=tip.desired.clone().sub(pivot);\n if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\n const parentId=parentGroup.get(id),localParent=branch?(parentId?frames.get(parentId):undefined):branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n for(let fraction=1;fraction>=1/32;fraction/=2){\n const attempt=old.clone().slerp(rotation,fraction);set(attempt);\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\n set(old);\n }\n }\n }\n for(const pole of poles){\n const {base,preferred,bend}=poleState(pole),along=bend.dot(preferred);\n if(along>=pole.minBend)continue;\n const baseId=key(pole.base),nextId=key(pole.chain[1]);\n const branch=branchJoints.get(nextId),joint=branch?.joint??coneJoints.get(baseId)??freeJoints.get(baseId);\n const frame=branch?.frame??frames.get(baseId);\n if(!joint||!frame)continue;\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\n const arm=knee.sub(base),aim=arm.clone().addScaledVector(preferred,Math.min(.01,pole.minBend-along));\n if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\n const parentId=branch?baseId:parentGroup.get(baseId),parentFrame=parentId?frames.get(parentId):undefined;\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(world(parentFrame)):new Quaternion();\n const matrix=world(frame),old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let proposal=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)proposal=limitRotation(baseId,proposal,parentRotation);\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n for(let fraction=1;fraction>=1/32;fraction/=2){\n const attempt=old.clone().slerp(proposal,fraction);set(attempt);\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\n set(old);\n }\n }\n if(largestChange<1e-5)break;\n }\n }\n // Projecting cones only AFTER the unconstrained solve leaves the endpoint\n // stranded, even when another joint could reach it. Finish positional chains\n // with constrained coordinate descent: every accepted step obeys its cone\n // and reduces the residual. Siblings/fixed roots never enter this joint list.\n if(goals.length===1){\n const target=goals[0],tipPin=byId.get(target.id)!;\n if(groups.get(key(tipPin))!.length===1&&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\n const tip=frames.get(key(tipPin))!,desired=new Vector3().fromArray(closures[0].position);\n const ordered=ikChain(pins,parents,target.id,mass),chain=ordered.slice(0,-1).reverse();\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const ground=tipPin.chainRole?.kind==='leg'&&Number.isFinite(floor)?(floor-origin.y)/size:-Infinity;\n const point=(pin:PinRecord)=>new Vector3().setFromMatrixPosition(world(frames.get(key(pin))!));\n const initial=[...new Set(chain.flatMap(pin=>[frames.get(key(pin))!,branchJoints.get(key(pin))?.frame].filter((frame):frame is Link=>Boolean(frame))))].map(frame=>({frame,rotation:priorRotations.get(frame)!}));\n // Endpoint distance has mirrored solutions. Carry each visible bend's\n // pole into the new chord frame instead of letting descent change sides.\n const poles=ordered.slice(1,-1).flatMap((knee,i)=>{\n const base=ordered[i],end=ordered[i+2];\n const chord=new Vector3().fromArray(end.pose.position).sub(new Vector3().fromArray(base.pose.position)),span=chord.length(),axis=chord.normalize();\n const bend=new Vector3().fromArray(knee.pose.position).sub(new Vector3().fromArray(base.pose.position));\n bend.addScaledVector(axis,-bend.dot(axis));\n // Near extension the positional pole is numerical noise; the rest\n // bend carried by the current base frame still defines its side.\n if(bend.length()<span*.02){\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest)).normalize();\n bend.fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\n bend.addScaledVector(restAxis,-bend.dot(restAxis));\n const rotation=new Quaternion().fromArray(base.pose.rotation);\n bend.applyQuaternion(rotation);\n restAxis.applyQuaternion(rotation);\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(restAxis,axis));\n }\n return bend.length()<span*.02?[]:[{base,knee,end,axis,pole:bend.normalize()}];\n });\n const poleCost=()=>poles.reduce((sum,pole)=>{\n const base=point(pole.base),axis=point(pole.end).sub(base).normalize();\n const preferred=pole.pole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.axis,axis));\n const bend=point(pole.knee).sub(base);bend.addScaledVector(axis,-bend.dot(axis));\n return sum+Math.max(0,-bend.dot(preferred))**2;\n },0);\n // Position alone does not determine every joint frame. Keep the nearest\n // solution to the pose on screen when a controller moves a tiny amount.\n const cost=()=>{\n const error=new Vector3().setFromMatrixPosition(world(tip)).distanceToSquared(desired);\n let penetration=0;\n if(Number.isFinite(ground))for(const pin of ordered.slice(1,-1))penetration+=Math.max(0,ground-point(pin).y)**2;\n const drift=initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0);\n return error+16*penetration+100*poleCost()+POSE_CONTINUITY_WEIGHT*drift;\n };\n // Near a tight cone the last few sweeps are small but visible. Stop only\n // once the pose itself has settled, not merely when the goal is close.\n for(let sweep=0;sweep<128;sweep++){\n if(cost()<1e-12)break;\n let largestChange=0;\n for(const pin of chain){\n const id=key(pin);\n const joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\n for(const [jointIndex,joint] of joints.entries()){\n if(!joint)continue;\n const branch=jointIndex===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix);\n const end=new Vector3().setFromMatrixPosition(world(tip)),before=cost();\n const a=end.clone().sub(pivot),b=desired.clone().sub(pivot);if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\n const parentId=parentGroup.get(id),localParent=branch?parentId?frames.get(parentId):undefined:branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\n const set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n let accepted=false;\n for(let fraction=1;fraction>=1/32;fraction/=2){\n let attempt=old.clone().slerp(rotation,fraction);\n if(!branch)attempt=limitRotation(id,attempt,parentRotation);\n set(attempt);\n if(cost()<=before+1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));accepted=true;break;}\n }\n if(!accepted)set(old);\n if(Number.isFinite(ground))for(const descendant of ordered.slice(ordered.indexOf(pin)+1,-1)){\n const lower=point(descendant);if(lower.y>=ground)continue;\n const current=point(pin),arm=lower.clone().sub(current),raised=lower.clone();raised.y=ground;\n const aim=raised.sub(current);if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\n const parentNow=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const previous=parentNow.clone().invert().multiply(new Quaternion().setFromRotationMatrix(world(frame)));\n let proposal=parentNow.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(world(frame)));\n if(!branch)proposal=limitRotation(id,proposal,parentNow);\n const start=cost();\n for(let fraction=1;fraction>=1/16;fraction/=2){\n const attempt=previous.clone().slerp(proposal,fraction);set(attempt);\n if(cost()<start-1e-14){largestChange=Math.max(largestChange,previous.angleTo(attempt));break;}\n set(previous);\n }\n }\n }\n }\n if(largestChange<1e-5)break;\n }\n }\n }\n // Ancestor refinement must not leave a cone outside its committed frame.\n if(goals.length===1||!positionOnlyGoals)projectCones();\n // A free goal's orientation is independent of its position, including when\n // extra toe/follower joints are added below it. Carry those followers through\n // the frame, rather than only overwriting the endpoint's returned quaternion.\n for(const goal of goals){\n const id=key(byId.get(goal.id)!),joint=freeJoints.get(id);if(!joint||groups.get(id)!.length!==1)continue;\n const parentId=parentGroup.get(id),parent=parentId?frames.get(parentId):undefined;parent?.updateMatrixWorld();\n const rotation=parent?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parent.matrixWorld)).invert():new Quaternion();\n rotation.multiply(new Quaternion().fromArray(goal.rotation));\n const e=new Euler().setFromQuaternion(rotation,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frames.get(id)!.updateMatrixWorld();\n }\n const result=pins.filter(p=>affected.has(key(p))).map(pin=>{\n if(fixed.has(pin.id)) return {id:pin.id,pose:pin.pose};\n const anchor=groups.get(key(pin))![0],frame=frames.get(key(pin))!;frame.updateMatrixWorld();\n const matrix=new Matrix4().fromArray(frame.matrixWorld),rotation=new Quaternion().setFromRotationMatrix(matrix).normalize();\n const position=new Vector3().setFromMatrixPosition(matrix).multiplyScalar(size).add(origin);\n const delta=rotation.clone().multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\n const goal=goals.find(g=>key(byId.get(g.id)!)===key(pin));\n const terminal=![...parentGroup.values()].includes(key(pin));\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) rotation.fromArray(goal.rotation);\n const offset=new Vector3().fromArray(pin.pose.position).sub(new Vector3().fromArray(anchor.pose.position));\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) delta.copy(rotation).multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\n position.add(offset.applyQuaternion(delta));\n if(!parentGroup.has(key(pin)) && pin.id===anchor.id) position.fromArray(pin.pose.position);\n if(![...position.toArray(),...rotation.toArray()].every(Number.isFinite)) throw new Error('IK produced an invalid pose.');\n return {id:pin.id,pose:{position:position.toArray(),rotation:rotation.toArray(),scale:pin.pose.scale}};\n });\n return result;\n}\n", "import { validateRig, type JointsRig } from './joints-json.js';\nimport { ikChain } from './pin-ik.js';\nimport {DEFAULT_MOTION} from './motion-settings.js';\nimport type { ClothCollider, ClothLink } from './pin-cloth.js';\n\nexport const NEEDLE_DEFORMATION_RIG = 'NEEDLE_deformation_rig';\nexport interface RigDescriptor extends JointsRig {\n version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;\n joints: { node: number; parent: number | null; mass: number }[];\n chains: { endpoint: number; joints: number[]; mode: 'ik' | 'secondary' | 'cloth' | 'fur' }[];\n helpers?: { node: number; influences: { node: number; weight: number }[] }[];\n cloth?: { links: ClothLink[]; colliders: ClothCollider[] };\n furSurface?: { heightTexture: number; texCoord?: number };\n}\n/** Validate before allocating runtime objects or accepting node references. */\nexport function parseRigDescriptor(value: unknown, nodeCount: number, textureCount = Infinity): RigDescriptor {\n if (!value || typeof value !== 'object') throw new Error('Invalid deformation rig.');\n const raw = value as RigDescriptor;\n 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.');\n 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.');\n 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.');\n if (raw.version < 5 && raw.windStrength !== undefined) throw new Error('Wind requires NEEDLE_deformation_rig version 5.');\n if (raw.activePose === 0 && raw.version < 9) throw new Error('An unselected authored pose requires NEEDLE_deformation_rig version 9.');\n const restSlot=raw.poseSlots?.find(slot=>slot.slot===0);\n if(restSlot && raw.version<7)throw new Error('Pose 0 requires NEEDLE_deformation_rig version 7.');\n const rig = validateRig({...raw,poseSlots:raw.poseSlots?.filter(slot=>slot.slot!==0)}, raw.version>=3?256:128);\n if(restSlot){\n if(raw.poseSlots.filter(slot=>slot.slot===0).length!==1 || !Array.isArray(restSlot.poses) || restSlot.poses.length!==rig.pins.length ||\n 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.');\n validateRig({pins:rig.pins,activePose:1,poseSlots:[{slot:1,poses:restSlot.poses}],poseTimes:[]},raw.version>=3?256:128);\n }\n if (raw.version < 5 && rig.pins.some(pin=>pin.fur)) throw new Error('Fur requires NEEDLE_deformation_rig version 5.');\n if (raw.furSurface && !rig.pins.some(pin => pin.fur)) throw new Error('Fur height requires a Fur rig.');\n const node = (n: number) => Number.isInteger(n) && n >= 0 && n < nodeCount;\n if (!Array.isArray(raw.joints) || raw.joints.length !== rig.pins.length) throw new Error('Invalid rig joint bindings.');\n const indices = new Set<number>();\n for (const joint of raw.joints) {\n 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.');\n indices.add(joint.node);\n }\n const parents = new Map(raw.joints.map(j => [j.node, j.parent]));\n for (const joint of raw.joints) {\n const seen = new Set<number>(); let cursor: number | null = joint.node;\n while (cursor !== null) {\n if (!indices.has(cursor) || seen.has(cursor)) throw new Error('Invalid or cyclic rig hierarchy.');\n seen.add(cursor); cursor = parents.get(cursor)!;\n }\n }\n if (!Array.isArray(raw.chains) || raw.chains.length > rig.pins.length) throw new Error('Invalid motion chains.');\n const endpoints = new Set<number>();\n for (const chain of raw.chains) {\n 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.');\n endpoints.add(chain.endpoint);\n }\n const pinParents = new Map<string, string>(), masses = new Map<string, number>();\n 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); });\n for (const [i, pin] of rig.pins.entries()) {\n const chain = raw.chains.find(c => c.endpoint === raw.joints[i].node);\n const mode = !pin.guide && (pin.ik ? 'ik' : pin.wiggle ? 'secondary' : pin.cloth ? 'cloth' : pin.fur ? 'fur' : null);\n if (!mode && chain) throw new Error('Unexpected motion chain.');\n if (!mode) continue;\n const articulated=raw.version>=3?rig.pins.filter((_,i)=>!raw.helpers?.some(h=>h.node===raw.joints[i].node)):rig.pins;\n 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);\n // Chains are derived caches, not authoritative authored topology. Older\n // writers used discontinuous reach gates; accept any valid ancestor suffix\n // and rebuild the current extent from the saved reach in the runtime.\n 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.');\n }\n if (raw.helpers !== undefined && (!Array.isArray(raw.helpers) || raw.helpers.length > 256)) throw new Error('Invalid helper bindings.');\n const helpers = raw.helpers?.map(helper => {\n 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.');\n const seen = new Set<number>(); let sum = 0;\n for (const influence of helper.influences) {\n 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.');\n seen.add(influence.node); sum += influence.weight;\n }\n if (helper.influences.length && Math.abs(sum - 1) > 1e-4) throw new Error('Helper weights must sum to one.');\n indices.add(helper.node); return { node: helper.node, influences: helper.influences.map(i => ({ ...i })) };\n });\n if (raw.version >= 2 && !helpers) throw new Error('Rig requires helper bindings.');\n if (helpers && new Set(helpers.map(h=>h.node)).size!==helpers.length) throw new Error('Duplicate helper bone.');\n 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.');\n const pinById = new Map(rig.pins.map(p => [p.id, p]));\n 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.');\n 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.');\n 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 } } : {}) };\n}\n"],
4
+ "sourcesContent": ["import type { IKConstraint } from './ik-constraints.js';\nimport type { MotionSettings } from './motion-settings.js';\n\n/** Shared data contract; deliberately independent of editor history and GPU types. */\nexport type Point = readonly [number, number, number];\nexport type Rotation = readonly [number, number, number, number];\nexport type PinPose = { readonly position: Point; readonly rotation: Rotation; readonly scale: Point };\nexport type PinParents = ReadonlyMap<string, string>;\nexport type HierarchyEdge = {from:string;to:string;cost:number;geodesic?:number};\nexport type PinMotion = 'none' | 'ik' | 'wiggle' | 'cloth' | 'fur';\nexport const DEFAULT_FUR_DEPTH = .1;\nexport const MAX_FUR_DEPTH = .5;\nexport type IKTarget = { readonly position: Point; readonly rotation: Rotation };\nexport const IK_CHAIN_KINDS = ['leg','arm','head','tail','wing','fin','tentacle','spine'] as const;\nexport type IKChainRole = { readonly kind: typeof IK_CHAIN_KINDS[number]; readonly side: 'center'|'left'|'right'; readonly position?: 'front'|'hind' };\nexport type PinRecord = { readonly id: string; readonly rest: Point; readonly pose: PinPose; readonly rigidGroup: string | null; readonly independent: boolean;\n /** This pose was set on purpose in the slot now open, rather than reached by\n * being carried by a parent or swept along by an IK solve. A slot still\n * stores an unauthored pose it could not otherwise reproduce \u2014 an IK chain\n * does not come back the same way twice \u2014 but only an authored one is shown\n * as deliberate and only an authored one can be released. */\n readonly authored?: boolean; readonly guide?: boolean; readonly ik?: boolean; readonly wiggle?: boolean; readonly cloth?: boolean; readonly fur?: boolean; readonly furDepth?: number; readonly motion?: MotionSettings; readonly ikTarget?: IKTarget; readonly ikConstraint?: IKConstraint; readonly chainRole?: IKChainRole };\n", "/** Shared document, import, UI and GPU capacity. Pin records are 64 bytes. */\nexport const MAX_DEFORMATION_PINS = 128;\n/** What one sweep of the Suggested pins slider will place. Well short of the\n * document cap: past this the slider stops placing body anchors and starts\n * splitting fine branches, which is hand work rather than a slider's job. */\nexport const MAX_SUGGESTED_PINS = 64;\n\n/** Cells along the longest axis of the solver lattice.\n *\n * The lattice is N by N by N over the model's bounds, and everything the solver\n * measures \u2014 how thick a part is, how far a contact reaches, how much an\n * element is strained \u2014 is in units of those cells. What a grid can represent\n * is what it can resolve: on a posed arm a finger is 2.7 cells across at 32 and\n * 3.5 at 40, which is a rod three nodes thick.\n *\n * The ceiling is a memory bound rather than a speed one. Node buffers are 16\n * bytes each and there are about ten of them, so 64 costs roughly 42 MB of\n * those; the harmonic weights are the one that hurts, at four bytes per node\n * per pin slot, which for a full 128 pins is 268 MB at 64 against 67 MB at 40. */\nexport const MIN_DEFORMATION_RESOLUTION = 16;\nexport const MAX_DEFORMATION_RESOLUTION = 64;\n\n/** Bones the skeleton solver turns on its own: every part of the body no pin\n * drives, cut along the curve skeleton. 132 bytes of GPU state each. */\nexport const MAX_SKELETON_BONES = 2048;\n", "export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };\nexport const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };\nexport function validateMotionSettings(value: MotionSettings) {\n if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1\n || !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8\n || !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1\n || !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2\n || !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');\n}\n", "import { Quaternion, Vector3 } from 'three';\nexport type IKConstraint = { mode:'free'|'cone'|'hinge'|'locked'; axis:'auto'|'x'|'y'|'z'; min:number; max:number; orientation?:[number,number,number,number]; maxY?:number };\nexport const DEFAULT_IK_CONSTRAINT:Readonly<IKConstraint> = {mode:'free',axis:'auto',min:-120,max:120};\nexport function validateIKConstraint(value:IKConstraint) {\n if(value?.maxY!==undefined && (!Number.isFinite(value.maxY)||value.maxY<0||value.maxY>180))throw new Error('Invalid IK cone aperture.');\n if(value?.orientation!==undefined && (!Array.isArray(value.orientation)||value.orientation.length!==4||!value.orientation.every(Number.isFinite)||Math.abs(Math.hypot(...value.orientation)-1)>1e-4))throw new Error('Invalid IK cone orientation.');\n if (!value || !['free','cone','hinge','locked'].includes(value.mode) || !['auto','x','y','z'].includes(value.axis)\n || !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || (value.mode==='cone' && value.max<0)) throw new Error('Invalid IK joint constraint.');\n}\n/** Stable parent-local cone frame. Z follows the rest bone; X/Y are aperture axes. */\nexport function coneFrame(axis:Vector3,constraint:Readonly<IKConstraint>){\n return new Quaternion().fromArray(constraint.orientation??[0,0,0,1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis.clone().normalize()));\n}\n/** Angular ellipse (also valid beyond 90 degrees), rather than a tangent-plane box. */\nexport function coneAngle(constraint:Readonly<IKConstraint>,azimuth:number){\n const x=(constraint.mode==='cone'?constraint.max:90)*Math.PI/180,y=(constraint.mode==='cone'?(constraint.maxY??constraint.max):90)*Math.PI/180;\n const c=Math.cos(azimuth),s=Math.sin(azimuth);\n if((x===0&&Math.abs(c)>1e-8)||(y===0&&Math.abs(s)>1e-8))return 0;\n return 1/Math.sqrt((Math.abs(c)<1e-8?0:c/Math.max(x,1e-12))**2+(Math.abs(s)<1e-8?0:s/Math.max(y,1e-12))**2);\n}\nexport function constrainCone(rotation:Quaternion,axis:Vector3,constraint:Readonly<IKConstraint>,movingAxis:Vector3=axis){\n const frame=coneFrame(axis,constraint),direction=movingAxis.clone().normalize().applyQuaternion(rotation);\n const local=direction.clone().applyQuaternion(frame.clone().invert()),azimuth=Math.atan2(local.y,local.x);\n const angle=Math.atan2(Math.hypot(local.x,local.y),local.z),limit=coneAngle(constraint,azimuth);\n if(angle<=limit+1e-8)return rotation.clone();\n const target=new Vector3(Math.sin(limit)*Math.cos(azimuth),Math.sin(limit)*Math.sin(azimuth),Math.cos(limit)).applyQuaternion(frame);\n return new Quaternion().setFromUnitVectors(direction,target).multiply(rotation).normalize();\n}\n/** Circular swing cone, not an Euler-angle box. Twist remains free. */\nexport function constrainSwing(rotation: Quaternion, axis: Vector3, degrees: number) {\n const direction=axis.clone().normalize(), rotated=direction.clone().applyQuaternion(rotation);\n const angle=direction.angleTo(rotated), limit=degrees*Math.PI/180;\n if(angle<=limit+1e-8)return rotation.clone();\n const normal=new Vector3().crossVectors(direction,rotated);\n if(normal.lengthSq()<1e-12)normal.crossVectors(direction,Math.abs(direction.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0));\n return new Quaternion().setFromAxisAngle(normal.normalize(),limit-angle).multiply(rotation).normalize();\n}\n", "import type { IKTarget, PinPose, PinRecord, Point, Rotation } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\n\nexport type StoredPose = { readonly id:string; readonly pose:PinPose; readonly ikTarget?:IKTarget; readonly authored?:boolean };\nexport type PoseSlot = { readonly slot:number; readonly poses:readonly StoredPose[] };\nexport const POSE_SLOTS=9;\n/** Below any edit a hand can make, and far above the drift of composing one\n * carried transform after another. */\nconst AUTHORED_EPSILON=1e-6;\n\nexport function capturePose(pins:readonly PinRecord[]):readonly StoredPose[]{\n return pins.map(pin=>({id:pin.id,pose:pin.pose,...(pin.authored?{authored:true}:{}),...(pin.ikTarget?{ikTarget:pin.ikTarget}:{})}));\n}\n\nconst restPoseOf=(rest:Point):PinPose=>({position:[rest[0],rest[1],rest[2]],rotation:[0,0,0,1],scale:[1,1,1]});\n\n/** Where a pin lands when its parent carries it from rest. A parent's pose IS\n * a similarity out of its own rest frame, so the child keeps its rest offset\n * through that same rotation and scale \u2014 the transform hierarchy posing applies\n * when a parent moves, written as one step from rest instead of accumulated. */\nexport function carriedPose(rest:Point,parentRest:Point,parent:PinPose):PinPose{\n const [qx,qy,qz,qw]=parent.rotation;\n 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];\n const tx=2*(qy*z-qz*y),ty=2*(qz*x-qx*z),tz=2*(qx*y-qy*x);\n 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)];\n const rotation:Rotation=[qx,qy,qz,qw],scale:Point=[parent.scale[0],parent.scale[1],parent.scale[2]];\n return {position,rotation,scale};\n}\n\nconst samePose=(a:PinPose,b:PinPose)=>\n a.position.every((v,i)=>Math.abs(v-b.position[i])<=AUTHORED_EPSILON)\n && a.scale.every((v,i)=>Math.abs(v-b.scale[i])<=AUTHORED_EPSILON)\n && a.rotation.every((v,i)=>Math.abs(v-b.rotation[i])<=AUTHORED_EPSILON);\n\n/** What a slot would place a pin at if it said nothing about it. */\nfunction inheritedPose(pin:PinRecord,parent:PinRecord|undefined,parentPose:PinPose|undefined):PinPose{\n return parent&&parentPose?carriedPose(pin.rest,parent.rest,parentPose):restPoseOf(pin.rest);\n}\n\n/** Only the poses a slot actually authors. A pin the hierarchy already places\n * is left out, so a point added while another pose was open keeps following its\n * parent everywhere else until it is deliberately posed there. */\nexport function authoredPoses(pins:readonly PinRecord[],parents:PinParents=new Map()):readonly StoredPose[]{\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\n return capturePose(pins).filter(stored=>{\n const pin=byId.get(stored.id)!;\n // Deliberate, or a goal, which is deliberate by definition.\n if(pin.authored||pin.ikTarget)return true;\n // Otherwise it is only kept because it could not be worked out again. A\n // joint the IK solve swept along is not reproducible \u2014 the same goal\n // reached from a different bend gives a different arm \u2014 so the value stays\n // even though nobody posed it.\n const parent=byId.get(parents.get(pin.id)??'');\n return !samePose(pin.pose,inheritedPose(pin,parent,parent?.pose));\n });\n}\n\n/** Active pins are the edit register. Inactive slots contain transforms only;\n * topology, rest positions and settings remain shared and action-owned. A pin\n * the slot does not mention inherits through the hierarchy rather than dropping\n * to rest, which is what keeps a newly placed point attached to its parent in\n * every other pose. */\nexport function resolvePose(pins:readonly PinRecord[],slot:PoseSlot,parents:PinParents=new Map()):readonly PinRecord[]{\n const saved=new Map(slot.poses.map(p=>[p.id,p]));\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\n const memo=new Map<string,PinPose>(),visiting=new Set<string>();\n const poseOf=(pin:PinRecord):PinPose=>{\n const cached=memo.get(pin.id);if(cached)return cached;\n const stored=saved.get(pin.id);\n let pose:PinPose;\n if(stored)pose=stored.pose;\n else{\n const parentId=parents.get(pin.id);\n // A parent already on the stack means a cycle in a derived hierarchy;\n // rest is the only answer that terminates.\n const parent=parentId&&!visiting.has(parentId)?byId.get(parentId):undefined;\n if(!parent)pose=restPoseOf(pin.rest);\n else{visiting.add(pin.id);pose=carriedPose(pin.rest,parent.rest,poseOf(parent));visiting.delete(pin.id);}\n }\n memo.set(pin.id,pose);return pose;\n };\n const resolved:PinRecord[]=pins.map(pin=>{\n const stored=saved.get(pin.id),{ikTarget:_target,authored:_authored,...base}=pin;\n return {...base,pose:poseOf(pin),...(stored?.authored?{authored:true}:{}),...(stored?.ikTarget?{ikTarget:stored.ikTarget}:{})};\n });\n // Group membership is shared. A group created after another pose was saved\n // still has one rotation/uniform scale when that pose is opened. Positions\n // stay authored; subsequent rigid edits preserve that arrangement.\n return resolved.map(pin=>{\n if(!pin.rigidGroup)return pin;const anchor=resolved.find(p=>p.rigidGroup===pin.rigidGroup)!;\n return {...pin,pose:{...pin.pose,rotation:anchor.pose.rotation,scale:[anchor.pose.scale[0],anchor.pose.scale[0],anchor.pose.scale[0]]}};\n });\n}\nexport function definedPoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\n const slots=model.poseSlots.filter(p=>p.slot!==model.activePose);\n return [...slots,...(model.activePose === 0 ? [] : [{slot:model.activePose,poses:capturePose(model.pins)}])].sort((a,b)=>a.slot-b.slot);\n}\n\n/** Pose 0 is derived from shared rest positions, never an editable pose slot. */\nexport function restPoseSlot(pins:readonly PinRecord[]):PoseSlot{\n return {slot:0,poses:pins.map(pin=>({id:pin.id,pose:restPoseOf(pin.rest)}))};\n}\n\nexport function playablePoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\n return [restPoseSlot(model.pins),...definedPoses(model)];\n}\n", "import type { PinPose, PinRecord, Point, Rotation } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\n\n/** A pose slot's time controls its share of the loop around its own moment.\n * The transition settles at each authored pose without holding a flat frame. */\nexport const DEFAULT_POSE_SECONDS = 0.7;\nexport const MIN_POSE_SECONDS = 0.05;\nexport const MAX_POSE_SECONDS = 60;\n/** Travel kept below the longest pose so a slider dragged to the bottom can\n * always be dragged further on the next pass, and shrinks back when shortened. */\nexport const POSE_TIME_HEADROOM = 0.5;\n\nexport type PoseTiming = { readonly slot: number; readonly seconds: number };\nexport type PoseTimeline = readonly PoseTiming[];\n\nexport function poseTimeScale(timeline: PoseTimeline): number {\n return Math.max(DEFAULT_POSE_SECONDS, ...timeline.map(entry => entry.seconds)) + POSE_TIME_HEADROOM;\n}\n\n/** The strip reads downwards: zero at the top, the scale at the bottom, which\n * is what makes \"drag down\" mean \"stay longer\". */\nexport function poseSecondsAt(offset: number, height: number, scale: number): number {\n if (!(height > 0)) return MIN_POSE_SECONDS;\n return Math.min(1, Math.max(0, offset / height)) * scale;\n}\n\n/** How far down the strip a time sits, as a percentage for the fill and handle. */\nexport function poseTimeOffset(seconds: number, scale: number): number {\n if (!(scale > 0)) return 0;\n return Math.min(100, Math.max(0, (seconds / scale) * 100));\n}\n\nexport function poseLoopSeconds(timeline: PoseTimeline): number {\n return timeline.reduce((total, entry) => total + Math.max(0, entry.seconds), 0);\n}\n\n/** The moment each pose is reached. Neighbours split the gap between them in\n * proportion to their own times, which is what makes a time an ownership share\n * rather than the length of one arc. */\nexport function poseKnots(timeline: PoseTimeline): number[] {\n const knots = [0];\n for (let i = 1; i < timeline.length; i++) {\n knots.push(knots[i - 1] + (Math.max(0, timeline[i - 1].seconds) + Math.max(0, timeline[i].seconds)) / 2);\n }\n return knots;\n}\n\n/** How long one pass takes: the first pose's moment to the last one's.\n * Looping playback adds the closing transition up to poseLoopSeconds. */\nexport function posePassSeconds(timeline: PoseTimeline): number {\n const knots = poseKnots(timeline);\n return knots.length ? knots[knots.length - 1] : 0;\n}\n\nexport function poseTimeOf(timeline: PoseTimeline, slot: number): number {\n const index = timeline.findIndex(entry => entry.slot === slot);\n return index < 0 ? 0 : poseKnots(timeline)[index];\n}\n\n/** Septic: zero first, second AND third derivative at both ends, so a one-shot\n * move away from rest and back to rest is G3 at the moment it starts and the\n * moment it settles. A cubic smoothstep leaves a jerk step at both. */\nexport function smoothStep(t: number): number {\n const x = Math.min(1, Math.max(0, t));\n return x ** 4 * (35 + x * (-84 + x * (70 - 20 * x)));\n}\n\nexport interface PoseSpline {\n readonly slots: readonly number[];\n readonly loop: number;\n /** How much each pose owns of the frame at this moment; sums to one, and is\n * one on a pose exactly at its own moment. */\n weightsAt(time: number): number[];\n}\n\n/** A periodic C2 interpolant of the authored poses. Its weights are shared by\n * rig playback, GLB clip mixing and trajectory sampling, so the visible path\n * is the path the animation actually follows. */\nexport function preparePoseSpline(timeline: PoseTimeline): PoseSpline {\n const n = timeline.length, slots = timeline.map(entry => entry.slot);\n const loop = poseLoopSeconds(timeline), knots = poseKnots(timeline);\n if (n < 2 || !(loop > 0)) {\n const fixed = timeline.map((_, i) => (i === 0 ? 1 : 0));\n return { slots, loop: Math.max(loop, 0), weightsAt: () => [...fixed] };\n }\n return { slots, loop, weightsAt: time => splineWeights(knots,loop,n,time) };\n}\n\nfunction splineWeights(knots: readonly number[], loop: number, n: number, time: number): number[] {\n const cursor = ((time % loop) + loop) % loop, weights = new Array<number>(n).fill(0);\n let k = n - 1; while (k > 0 && cursor < knots[k]) k--;\n const start = knots[k], end = k + 1 < n ? knots[k + 1] : loop;\n const h=end-start,t=h>0?(cursor-start)/h:0,next=(k+1)%n;\n if(n<3||!(h>0)){weights[k]=1-smoothStep(t);weights[next]+=smoothStep(t);return weights;}\n const coordinate=(i:number)=>i<0?knots[i+n]-loop:i>=n?knots[i-n]+loop:knots[i];\n const unit=(i:number)=>{const result=new Array<number>(n).fill(0);result[(i+n)%n]=1;return result;};\n const subtract=(a:readonly number[],b:readonly number[],scale:number)=>a.map((v,j)=>(v-b[j])/scale);\n const derivatives=(i:number)=>{\n const before=coordinate(i)-coordinate(i-1),after=coordinate(i+1)-coordinate(i);\n const previous=subtract(unit(i),unit(i-1),Math.max(before,1e-8));\n const following=subtract(unit(i+1),unit(i),Math.max(after,1e-8));\n // Full centered tangents round a three-pose corner visibly. Reducing them\n // to a quarter left a mathematically C2 but visibly triangular path.\n return {velocity:previous.map((v,j)=>(v*after+following[j]*before)/(before+after)),\n acceleration:previous.map((v,j)=>2*(following[j]-v)/(before+after))};\n };\n const a=derivatives(k),b=derivatives(k+1),p=unit(k),q=unit(k+1);\n for(let j=0;j<n;j++){\n const v0=h*a.velocity[j],v1=h*b.velocity[j],a0=h*h*a.acceleration[j],a1=h*h*b.acceleration[j];\n const d=q[j]-p[j]-v0-a0/2,v=v1-v0-a0,acc=a1-a0;\n 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)))));\n }\n return weights;\n}\n\nconst conjugate = (q: Rotation): Rotation => [-q[0], -q[1], -q[2], q[3]];\nconst multiply = (a: Rotation, b: Rotation): Rotation => [\n a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],\n a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],\n a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],\n a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],\n];\nfunction rotate(q: Rotation, v: Point): Point {\n 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]);\n 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)];\n}\nconst safeScale = (v: number) => (Math.abs(v) > 1e-8 ? v : 1e-8);\n\n/** A pose in its parent's frame. */\nfunction localPose(pose: PinPose, parent: PinPose | undefined): PinPose {\n if (!parent) return pose;\n const inverse = conjugate(parent.rotation);\n const offset = rotate(inverse, [pose.position[0] - parent.position[0], pose.position[1] - parent.position[1], pose.position[2] - parent.position[2]]);\n return {\n position: [offset[0] / safeScale(parent.scale[0]), offset[1] / safeScale(parent.scale[1]), offset[2] / safeScale(parent.scale[2])],\n rotation: multiply(inverse, pose.rotation),\n scale: [pose.scale[0] / safeScale(parent.scale[0]), pose.scale[1] / safeScale(parent.scale[1]), pose.scale[2] / safeScale(parent.scale[2])],\n };\n}\n\n/** The inverse of localPose: a local transform read back out into the world. */\nfunction worldPose(local: PinPose, parent: PinPose | undefined): PinPose {\n if (!parent) return local;\n const scaled: Point = [local.position[0] * parent.scale[0], local.position[1] * parent.scale[1], local.position[2] * parent.scale[2]];\n const offset = rotate(parent.rotation, scaled);\n return {\n position: [parent.position[0] + offset[0], parent.position[1] + offset[1], parent.position[2] + offset[2]],\n rotation: multiply(parent.rotation, local.rotation),\n scale: [local.scale[0] * parent.scale[0], local.scale[1] * parent.scale[1], local.scale[2] * parent.scale[2]],\n };\n}\n\n/** Parents before children, with any cycle in a derived hierarchy broken by\n * treating the pin that closes it as a root. */\nfunction hierarchyOrder(pins: readonly PinRecord[], parents: PinParents): { order: number[]; parentOf: (number | undefined)[] } {\n const index = new Map(pins.map((pin, i) => [pin.id, i]));\n const parentOf = pins.map(pin => { const p = index.get(parents.get(pin.id) ?? ''); return p === index.get(pin.id) ? undefined : p; });\n const order: number[] = [], state = new Uint8Array(pins.length);\n const visit = (i: number) => {\n if (state[i]) { if (state[i] === 1) parentOf[i] = undefined; return; }\n state[i] = 1;\n const parent = parentOf[i];\n if (parent !== undefined) visit(parent);\n state[i] = 2; order.push(i);\n };\n for (let i = 0; i < pins.length; i++) visit(i);\n return { order, parentOf };\n}\n\n\n/** The active pair shares one hemisphere, including the last-to-first seam. */\nexport function blendRotations(rotations: readonly Rotation[], weights: readonly number[]): Rotation {\n let [x, y, z, w] = [0, 0, 0, 0];\n const reference=rotations[weights.findIndex(weight=>weight>1e-12)]??rotations[0];\n let dominant = reference, best = -Infinity;\n for (let i = 0; i < rotations.length; i++) {\n const q = rotations[i];\n if(weights[i]===0)continue;\n const aligned: Rotation = q[0] * reference[0] + q[1] * reference[1] + q[2] * reference[2] + q[3] * reference[3] < 0\n ? [-q[0], -q[1], -q[2], -q[3]] : q;\n if (weights[i] > best) { best = weights[i]; dominant = aligned; }\n x += aligned[0] * weights[i]; y += aligned[1] * weights[i];\n z += aligned[2] * weights[i]; w += aligned[3] * weights[i];\n }\n const length = Math.hypot(x, y, z, w);\n // Opposed rotations at equal weight cancel and name no orientation at all.\n return length > 1e-6 ? [x / length, y / length, z / length, w / length] : dominant;\n}\n\n/** Blends by id, so a pin missing from either side simply keeps its own pose \u2014\n * it appears on both sides of the blend and cannot move. Everything but the\n * transform comes from the destination: ids, rest positions and flags are\n * shared between slots and are not animated. */\nexport function blendPins(from: readonly PinRecord[], to: readonly PinRecord[], t: number, parents: PinParents = new Map()): readonly PinRecord[] {\n if (t <= 0 && from.length === to.length && to.every((pin, i) => from[i]?.id === pin.id)) return from;\n const aligned = to.map(pin => from.find(other => other.id === pin.id) ?? pin);\n return blendPoses(to, [aligned, to], [1 - t, t], parents);\n}\n\n/** Every pose at once, by weight. `poses` are the same pins in the same order\n * as `base` \u2014 they all come from resolving one document \u2014 so this walks them by\n * index rather than searching per pin per frame.\n *\n * The blend happens in each pin's PARENT frame, never in world space. A chain\n * posed two ways differs mostly in its joints' rotations, and averaging world\n * positions cuts the chord between them: the limb shortens in the middle of\n * every transition and lengthens again at each pose. In the parent's frame only\n * the joint's own rotation and offset move, so the chain keeps its shape, and a\n * pin's transform stays relative to whatever IK did to its parent \u2014 which is\n * what makes moving an IK target interpolate as one arc rather than dragging\n * every pin along a straight line of its own. */\nexport function blendPoses(base: readonly PinRecord[], poses: readonly (readonly PinRecord[])[], weights: readonly number[], parents: PinParents = new Map()): readonly PinRecord[] {\n if (!poses.length || poses.some(pose => pose.length !== base.length)) return base;\n const { order, parentOf } = hierarchyOrder(base, parents);\n const world = new Array<PinPose>(base.length), blended = new Array<PinRecord>(base.length);\n for (const i of order) {\n const parent = parentOf[i], parentWorld = parent === undefined ? undefined : world[parent];\n const locals = poses.map((pose, k) => localPose(pose[i].pose, parent === undefined ? undefined : poses[k][parent].pose));\n world[i] = worldPose(weightedPose(locals, weights), parentWorld);\n const pin: PinRecord = { ...base[i], pose: world[i] };\n // A goal is an anchor in the world, not a point on its parent. A planted\n // foot has the same goal in every pose, and must come out of the blend as\n // that goal exactly however the body above it moves.\n if (!poses.every(pose => pose[i].ikTarget)) { blended[i] = pin; continue; }\n const targets = poses.map(pose => pose[i].ikTarget!);\n blended[i] = { ...pin, ikTarget: {\n position: [0, 1, 2].map(axis => targets.reduce((sum, target, k) => sum + target.position[axis] * weights[k], 0)) as unknown as Point,\n rotation: blendRotations(targets.map(target => target.rotation), weights),\n } };\n }\n return blended;\n}\n\n/** One pose out of many, by weight. */\nfunction weightedPose(poses: readonly PinPose[], weights: readonly number[]): PinPose {\n const position: [number, number, number] = [0, 0, 0], scale: [number, number, number] = [0, 0, 0];\n for (let k = 0; k < poses.length; k++) for (let axis = 0; axis < 3; axis++) {\n position[axis] += poses[k].position[axis] * weights[k];\n scale[axis] += poses[k].scale[axis] * weights[k];\n }\n return { position, rotation: blendRotations(poses.map(pose => pose.rotation), weights), scale };\n}\n", "import { Vector3 } from 'three';\n\nexport const MAX_WIND_STRENGTH = 4;\n\n/** A single weather control drives pin motion and surface pressure. Sparse pin\n * loads stay bounded; fabric pressure has room to grow through a storm. */\nexport function windProfile(strength: number) {\n const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));\n const label = level === 0 ? 'Off' : level < .75 ? 'Breeze' : level < 1.5 ? 'Windy' : level < 2.5 ? 'Strong wind' : level < 3.3 ? 'Gale' : 'Storm';\n return {\n label,\n load: 30 * level * level / (.8 + level * level),\n surfaceLoad: 4 * level * level,\n gust: .14 + .12 * level,\n crosswind: .05 + .07 * level,\n gustRate: .42 + .12 * level,\n };\n}\n\n/** Deterministic scene-local prevailing wind with slow gusts and spatially\n * varying eddies. Force is an acceleration scaled to the model's size, so a\n * tiny prop and a large character respond comparably at the same setting. */\nexport function windAcceleration(seconds: number, strength: number, scale: number, position: readonly number[]) {\n if (strength <= 0) return new Vector3();\n const size = Math.max(1e-4, scale);\n const profile = windProfile(strength);\n // Advect the gust bands along +X. Nearby controls see related wind, while\n // their phase delay keeps a large sheet or branch hierarchy from moving as\n // one perfectly synchronized rigid object.\n const along = position[0] / size, lateral = (position[1] * .67 + position[2] * .33) / size;\n const slow = seconds * profile.gustRate - along * .55;\n const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * .4;\n const gust = Math.max(.2, 1 + profile.gust * (.7 * Math.sin(slow) + .3 * Math.sin(fast + 1.3)));\n const cross = profile.crosswind * (.65 * Math.sin(fast + lateral) + .35 * Math.sin(slow * .73 - lateral * .6));\n return new Vector3(1, cross * .35, cross).normalize().multiplyScalar(profile.load * size * gust);\n}\n", "import { IK_CHAIN_KINDS, MAX_FUR_DEPTH, type IKChainRole, type PinRecord, type Point, type Rotation } from './pin-types.js';\nimport { MAX_DEFORMATION_PINS } from './limits.js';\nimport { DEFAULT_MOTION, validateMotionSettings } from './motion-settings.js';\nimport { validateIKConstraint, type IKConstraint } from './ik-constraints.js';\nimport { capturePose, POSE_SLOTS, resolvePose, type PoseSlot } from './pose-slots.js';\nimport type { PinParents } from './pin-types.js';\nimport { MAX_POSE_SECONDS, MIN_POSE_SECONDS, type PoseTiming } from './pose-timeline.js';\nimport { MAX_WIND_STRENGTH } from './wind.js';\n\nfunction record(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid joints JSON object.');\n return value as Record<string, unknown>;\n}\nfunction numbers(value: unknown, length: number): number[] {\n if (!Array.isArray(value) || value.length !== length || !value.every(v => typeof v === 'number' && Number.isFinite(v))) throw new Error('Invalid joint coordinates.');\n return [...value];\n}\nfunction point(value: unknown): Point { const v = numbers(value, 3); return [v[0], v[1], v[2]]; }\nfunction quaternion(value: unknown): Rotation { const v = numbers(value, 4); return [v[0], v[1], v[2], v[3]]; }\nexport function validateJoints(value: unknown, maximum = MAX_DEFORMATION_PINS): readonly PinRecord[] {\n if (!Array.isArray(value) || value.length > maximum) throw new Error(`Joints JSON must contain at most ${maximum} joints.`);\n const ids = new Set<string>();\n const pins = value.map(item => {\n const pin = record(item), pose = record(pin.pose);\n if (typeof pin.id !== 'string' || !pin.id || ids.has(pin.id)) throw new Error('Joint IDs must be unique non-empty strings.');\n ids.add(pin.id);\n if (typeof pin.independent !== 'boolean' || (pin.rigidGroup !== null && (typeof pin.rigidGroup !== 'string' || !pin.rigidGroup))) throw new Error('Invalid joint membership.');\n if (pin.guide !== undefined && typeof pin.guide !== 'boolean') throw new Error('Invalid guide flag.');\n if (pin.authored !== undefined && typeof pin.authored !== 'boolean') throw new Error('Invalid authored flag.');\n if (pin.ik !== undefined && typeof pin.ik !== 'boolean') throw new Error('Invalid IK flag.');\n if (pin.wiggle !== undefined && typeof pin.wiggle !== 'boolean') throw new Error('Invalid Wiggle flag.');\n if (pin.cloth !== undefined && typeof pin.cloth !== 'boolean') throw new Error('Invalid Cloth flag.');\n if (pin.fur !== undefined && typeof pin.fur !== 'boolean') throw new Error('Invalid Fur flag.');\n if (pin.furDepth !== undefined && (typeof pin.furDepth !== 'number' || !Number.isFinite(pin.furDepth) || pin.furDepth < 0 || pin.furDepth > MAX_FUR_DEPTH)) throw new Error('Invalid Fur depth.');\n const chainRole=pin.chainRole===undefined?undefined:(()=>{\n const value=record(pin.chainRole);\n if(!IK_CHAIN_KINDS.includes(value.kind as IKChainRole['kind'])||!['center','left','right'].includes(value.side as string)||\n (value.position!==undefined&&!['front','hind'].includes(value.position as string)))throw new Error('Invalid IK chain role.');\n return {kind:value.kind as IKChainRole['kind'],side:value.side as IKChainRole['side'],...(value.position?{position:value.position as 'front'|'hind'}:{})};\n })();\n if (Number(Boolean(pin.ik)) + Number(Boolean(pin.wiggle)) + Number(Boolean(pin.cloth)) + Number(Boolean(pin.fur)) > 1) throw new Error('Choose IK, Wiggle, Cloth or Fur.');\n const motion = pin.motion === undefined ? undefined : (()=>{\n const raw=record(pin.motion), result={reach:Number(raw.reach),frequency:Number(raw.frequency),damping:Number(raw.damping),massInfluence:raw.massInfluence===undefined?DEFAULT_MOTION.massInfluence:Number(raw.massInfluence),strength:raw.strength===undefined?DEFAULT_MOTION.strength:Number(raw.strength)};\n for(const key of ['massInfluence','strength']) if(raw[key]!==undefined && typeof raw[key]!=='number') throw new Error('Invalid motion settings.');\n if (typeof raw.reach!=='number' || typeof raw.frequency!=='number' || typeof raw.damping!=='number') throw new Error('Invalid motion settings.');\n validateMotionSettings(result); return result;\n })();\n const ikConstraint=pin.ikConstraint===undefined?undefined:(()=>{const raw=record(pin.ikConstraint);const value={mode:raw.mode,axis:raw.axis,min:raw.min,max:raw.max,...(raw.orientation!==undefined?{orientation:quaternion(raw.orientation)}:{}),...(raw.maxY!==undefined?{maxY:raw.maxY}:{})} as IKConstraint;validateIKConstraint(value);return value;})();\n const ikTarget=pin.ikTarget === undefined ? undefined : (()=>{\n const raw=record(pin.ikTarget),rotation=quaternion(raw.rotation);\n if (Math.abs(Math.hypot(...rotation)-1)>1e-4) throw new Error('Invalid IK target rotation.');\n return {position:point(raw.position),rotation};\n })();\n if (pin.guide && (pin.rigidGroup || pin.independent)) throw new Error('Guides cannot be rigid members or roots.');\n const scale = point(pose.scale), rotation = quaternion(pose.rotation);\n if (scale.some(v => v < 0.01 || v > 100) || Math.abs(Math.hypot(...rotation) - 1) > 1e-4) throw new Error('Invalid joint rotation or scale.');\n return { id: pin.id, independent: pin.independent, rigidGroup: pin.rigidGroup, ...(pin.authored === true ? { authored: true } : {}), ...(typeof pin.guide === 'boolean' ? { guide: pin.guide } : {}), ...(typeof pin.ik === 'boolean' ? { ik: pin.ik } : {}),\n ...(ikConstraint?{ikConstraint}:{}),...(chainRole?{chainRole}:{}),...(motion ? {motion}:{}),...(ikTarget ? {ikTarget}:{}),...(typeof pin.wiggle === 'boolean' ? {wiggle:pin.wiggle} : {}),...(typeof pin.cloth === 'boolean' ? {cloth:pin.cloth} : {}),...(typeof pin.fur === 'boolean' ? {fur:pin.fur} : {}),...(pin.furDepth !== undefined ? {furDepth:pin.furDepth as number} : {}), rest: point(pin.rest), pose: { position: point(pose.position), rotation, scale } };\n });\n for (const pin of pins) if (pin.rigidGroup) {\n const anchor = pins.find(other => other.rigidGroup === pin.rigidGroup)!;\n const dot = pin.pose.rotation.reduce((sum, v, i) => sum + v * anchor.pose.rotation[i], 0);\n if (pin.pose.scale.some(v => Math.abs(v - anchor.pose.scale[0]) > 1e-5) || 1 - Math.abs(dot) > 1e-5) throw new Error('Rigid joints must share rotation and uniform scale.');\n }\n return pins;\n}\nexport interface JointsRig { pins:readonly PinRecord[];activePose:number;poseSlots:readonly PoseSlot[];poseTimes:readonly PoseTiming[];windStrength?:number }\nfunction validatePoseTimes(value:unknown):readonly PoseTiming[]{\n if(!Array.isArray(value)||value.length>POSE_SLOTS)throw new Error('Invalid pose times.');\n const slots=new Set<number>();\n return value.map(item=>{\n const entry=record(item);\n if(!Number.isInteger(entry.slot)||(entry.slot as number)<0||(entry.slot as number)>POSE_SLOTS||slots.has(entry.slot as number))throw new Error('Invalid pose time slot.');\n slots.add(entry.slot as number);\n if(typeof entry.seconds!=='number'||!Number.isFinite(entry.seconds)||entry.seconds<MIN_POSE_SECONDS||entry.seconds>MAX_POSE_SECONDS)throw new Error('Invalid pose time.');\n return {slot:entry.slot as number,seconds:entry.seconds};\n }).sort((a,b)=>a.slot-b.slot);\n}\n/** Slots are written out in full. A pin the hierarchy places is left unsaid in\n * the editor so it keeps following its parent, but a file has no voxel field to\n * rebuild that hierarchy from and older readers would drop it to rest, so the\n * inherited pose is resolved here and stored. */\nexport function validateRig(value:JointsRig, maximum = MAX_DEFORMATION_PINS, parents:PinParents = new Map()):JointsRig{\n const pins=validateJoints(value.pins,maximum);\n if (value.windStrength !== undefined && (!Number.isFinite(value.windStrength) || value.windStrength < 0 || value.windStrength > MAX_WIND_STRENGTH)) throw new Error('Invalid wind strength.');\n if(!Number.isInteger(value.activePose)||value.activePose<0||value.activePose>POSE_SLOTS||!Array.isArray(value.poseSlots)||value.poseSlots.length>POSE_SLOTS)throw new Error('Invalid pose slots.');\n const slots=new Set<number>(),ids=new Set(pins.map(p=>p.id));\n const poseSlots=value.poseSlots.map(slot=>{\n if(!slot||!Number.isInteger(slot.slot)||slot.slot<1||slot.slot>POSE_SLOTS||slots.has(slot.slot)||!Array.isArray(slot.poses))throw new Error('Invalid pose slot.');slots.add(slot.slot);\n const pinIds=new Set<string>();for(const p of slot.poses){if(!p||!ids.has(p.id)||pinIds.has(p.id))throw new Error('Invalid pose pin.');pinIds.add(p.id);}\n return {slot:slot.slot,poses:capturePose(validateJoints(resolvePose(pins,slot,parents),maximum))};\n }).filter(slot=>slot.slot!==value.activePose);\n return {pins,activePose:value.activePose,poseSlots,poseTimes:validatePoseTimes(value.poseTimes??[]),...(value.windStrength !== undefined ? {windStrength:value.windStrength} : {})};\n}\n", "import { Goal, Joint, Link, Solver } from 'closed-chain-ik/core';\nimport { Euler, Matrix4, Quaternion, Vector3 } from 'three';\nimport type { PinRecord, PinPose, Point, Rotation } from './pin-types.js';\nimport { DEFAULT_MOTION } from './motion-settings.js';\nimport type { PinParents } from './pin-types.js';\nimport { DEFAULT_IK_CONSTRAINT, constrainCone } from './ik-constraints.js';\n\nconst POSE_CONTINUITY_WEIGHT=1e-4;\n\n/** A routing guide is not a limb. Only guides leading to real joints create\n * an articulated branch; dangling guidance must not lock an IK pivot. */\nfunction articulatedNodes(pins: readonly PinRecord[], parents: PinParents) {\n const nodes = new Set<string>();\n for (const pin of pins) if (!pin.guide) {\n let id: string | undefined = pin.id;\n while (id && !nodes.has(id)) { nodes.add(id); id = parents.get(id); }\n }\n return nodes;\n}\n\n/** IDs are derived each time; no stale authored chain survives topology edits. */\nexport function ikChain(pins: readonly PinRecord[], parents: PinParents, id: string, mass: ReadonlyMap<string, number> = new Map()): PinRecord[] {\n const byId = new Map(pins.map(pin => [pin.id, pin]));\n const element = (pin: PinRecord) => pin.rigidGroup ?? pin.id;\n const articulated = articulatedNodes(pins, parents);\n const children = new Map<string, Set<string>>();\n const supportLength=new Map<string,number>();\n for (const pin of pins) {\n if (!articulated.has(pin.id)) continue;\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (!parent) continue;\n const length=Math.hypot(...pin.rest.map((x,i)=>x-parent.rest[i]))*.5;\n supportLength.set(pin.id,(supportLength.get(pin.id)??0)+length);\n supportLength.set(parent.id,(supportLength.get(parent.id)??0)+length);\n const set = children.get(element(parent)) ?? new Set<string>(); set.add(element(pin)); children.set(element(parent), set);\n }\n const chain: PinRecord[] = [], seen = new Set<string>();\n let pin = byId.get(id);\n const reach = pin?.motion?.reach ?? DEFAULT_MOTION.reach;\n let automatic:string|undefined;\n // Mass per supported rest length approximates cross-section, unlike raw\n // per-pin mass which shrinks simply because a limb gained more joints.\n const density=(p:PinRecord)=>mass.has(p.id)?mass.get(p.id)!/Math.max(supportLength.get(p.id)??0,1e-12):undefined;\n while (pin && !seen.has(element(pin))) {\n chain.unshift(pin); seen.add(element(pin));\n if (pin.independent) break;\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (!parent) break;\n // Keep the body/other limbs stationary. An immediate parent is still\n // needed as the pivot for a single-link chain.\n if (!automatic && ((children.get(element(parent))?.size ?? 0) > 1\n || (!pin.guide && !parent.guide && (density(parent) ?? 0) > 8 * Math.max(density(pin) ?? Infinity, 1e-12)))) automatic=parent.id;\n pin = parent;\n }\n if(chain.length<2)return chain;\n const distance=new Float64Array(chain.length);\n for(let i=chain.length-2;i>=0;i--)distance[i]=distance[i+1]+Math.hypot(...chain[i].rest.map((x,k)=>x-chain[i+1].rest[k]));\n const boundary=automatic?chain.findIndex(p=>p.id===automatic):-1;\n const automaticDistance=distance[Math.max(0,boundary)];\n // Reach measures REST arc length, not node count or posed/chord distance.\n // Zero starts at the endpoint (clamped to one link); subdivision must not\n // move the slider's origin by changing that first link's length.\n const budget=reach<=.5?automaticDistance*reach*2:automaticDistance+(distance[0]-automaticDistance)*(reach-.5)*2;\n const first=reach<=.5&&boundary>=0?Math.min(boundary+1,chain.length-2):0;\n let start=chain.length-2;\n for(let i=start-1;i>=first;i--)if(Math.abs(distance[i]-budget)<Math.abs(distance[start]-budget))start=i;\n if(reach===1)start=0;\n return chain.slice(start);\n}\n\nexport function solvePinIK(pins: readonly PinRecord[], parents: PinParents, id: string, target: Point,\n mass?: ReadonlyMap<string, number>, targetRotation?: Rotation): { id: string; pose: PinPose }[] {\n const pin=pins.find(p=>p.id===id)!;\n return solvePinIKGoals(pins,parents,[{id,position:target,rotation:targetRotation ?? pin.ikTarget?.rotation ?? pin.pose.rotation}],mass);\n}\n\nexport type IKGoal = {id:string;position:Point;rotation:Rotation};\n\n/** Endpoint editing is local. Shared body frames and sibling branches retain\n * their authored poses; root/body edits use the separate multi-goal solve. */\nexport function solveLocalPinIK(pins:readonly PinRecord[],parents:PinParents,goal:IKGoal,mass?:ReadonlyMap<string,number>,floor=-Infinity){\n const chain=ikChain(pins,parents,goal.id,mass),key=(p:PinRecord)=>p.rigidGroup??p.id;\n const keys=new Set(chain.map(key)),byId=new Map(pins.map(p=>[p.id,p]));\n const articulated = articulatedNodes(pins, parents);\n let boundary=-1;\n // Children below the endpoint are followers, never competing side branches.\n for(let i=0;i<chain.length-1;i++)if(chain[i].independent || pins.some(p=>{\n if (!articulated.has(p.id)) return false;\n const parent=byId.get(parents.get(p.id)??'');return parent&&key(parent)===key(chain[i])&&!keys.has(key(p));\n }))boundary=i;\n const shared=boundary>=0&&pins.some(p=>{\n if(!articulated.has(p.id))return false;\n const parent=byId.get(parents.get(p.id)??'');\n return parent&&key(parent)===key(chain[boundary])&&!keys.has(key(p));\n });\n // A shared attachment fixes the body. The outgoing limb gets a separate\n // zero-length branch pivot in the solver, so the first link can still swing.\n // A lone independent root has no sibling to disturb and retains the exact\n // two-link analytic solve through its temporary root rotation.\n const fixed=new Set(chain.slice(0,shared?boundary+1:Math.max(0,boundary)).flatMap(p=>pins.filter(q=>key(q)===key(p)).map(q=>q.id)));\n const moving=new Set(chain.slice(boundary+1).map(key));\n for(let added=true;added;){added=false;for(const p of pins){const parent=byId.get(parents.get(p.id)??'');if(parent&&moving.has(key(parent))&&!moving.has(key(p))){moving.add(key(p));added=true;}}}\n const retained=new Set(boundary>=0?[key(chain[boundary])]:[]);\n return solvePinIKGoals(pins,parents,[goal],mass,fixed,retained,floor).filter(p=>moving.has(key(byId.get(p.id)!)));\n}\n\n/** Solve separate planted limbs against the same body pose. Their temporary\n * attachment rotations must not become rotations of the shared torso frame. */\nexport function solvePlantedPinIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass?:ReadonlyMap<string,number>,fixed:ReadonlySet<string>=new Set(),floor=-Infinity){\n if(!goals.length)return [];\n const edits=new Map<string,{id:string;pose:PinPose}>();\n let independent=true;\n for(const goal of goals){\n const limb=solveLocalPinIK(pins,parents,goal,mass,floor);\n for(const edit of limb){\n if(fixed.has(edit.id)||edits.has(edit.id)){independent=false;break;}\n edits.set(edit.id,edit);\n }\n if(!independent)break;\n }\n return independent?[...edits.values()]:solvePinIKGoals(pins,parents,goals,mass,fixed,new Set(),floor);\n}\n\n/** Body motion and imported-pose reconstruction use the same full-chain solve.\n * Shared attachment frames are held; each limb gets its own branch pivot. */\nexport function solveBodyIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass:ReadonlyMap<string,number>,fixed:ReadonlySet<string>,floor=-Infinity){\n const poleChains=new Map(goals.map(goal=>[goal.id,ikChain(pins,parents,goal.id,mass)]));\n const full=pins.map(pin=>pin.ik?{...pin,motion:{...DEFAULT_MOTION,...pin.motion,reach:1}}:pin);\n const uses=new Map<string,number>();\n for(const goal of goals)for(const pin of ikChain(full,parents,goal.id,mass))uses.set(pin.id,(uses.get(pin.id)??0)+1);\n const anchors=new Set([...fixed,...[...uses].filter(([,count])=>count>1).map(([id])=>id)]);\n return solvePinIKGoals(full,parents,goals,mass,anchors,new Set(),floor,poleChains);\n}\n\n/** One articulated forest, one joint solve. Shared joints are never overwritten\n * by a later endpoint, and every child offset retains its authored length. */\nexport function solvePinIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass?:ReadonlyMap<string,number>,fixed:ReadonlySet<string>=new Set(),retained:ReadonlySet<string>=new Set(),floor=-Infinity,poleChains:ReadonlyMap<string,readonly PinRecord[]> = new Map()):{id:string;pose:PinPose}[] {\n if (!goals.length) return [];\n const byId=new Map(pins.map(p=>[p.id,p])),key=(p:PinRecord)=>p.rigidGroup ?? p.id;\n const groups=new Map<string,PinRecord[]>();\n for(const pin of pins){const group=groups.get(key(pin)) ?? [];group.push(pin);groups.set(key(pin),group);}\n const parentGroup=new Map<string,string>();\n for(const [id,members] of groups){\n const parent=members.map(p=>byId.get(parents.get(p.id) ?? '')).find(p=>p && key(p)!==id);\n if(parent) parentGroup.set(id,key(parent));\n }\n // A joint carries every pin below it, so a joint above a fixed pin holds\n // still too; otherwise the fixed pin would swing about that ancestor.\n const holding=new Set<string>();\n for(const [id,members] of groups) if(members.some(p=>fixed.has(p.id))) for(let at:string|undefined=id;at&&!holding.has(at);at=parentGroup.get(at)) holding.add(at);\n const active=new Set<string>(), roots=new Set<string>();\n const bendSeeds=new Map<string,Vector3>();\n let size=0;\n for(const goal of goals){\n const chain=ikChain(pins,parents,goal.id,mass);\n if(chain.length<2) throw new Error('IK needs a parent chain. Add a parent pin or remove Independent from this endpoint.');\n for(const p of chain) active.add(key(p));\n roots.add(key(chain[0]));\n // Only a straight, contracting chain needs a perturbation: at full\n // extension its positional Jacobian cannot discover a bend. Seeding an\n // already bent chain injects rotation on every drag sample and accumulates\n // drift despite a nearly stationary target.\n const start=new Vector3().fromArray(chain[0].pose.position),direction=new Vector3().fromArray(chain.at(-1)!.pose.position).sub(start);\n const span=direction.length();\n if(span>1e-8 && new Vector3().fromArray(goal.position).distanceTo(start)<span*(1-1e-6)){\n direction.divideScalar(span);\n const straight=chain.every(p=>new Vector3().fromArray(p.pose.position).sub(start).cross(direction).lengthSq()<span*span*1e-12);\n const candidate=straight?chain.slice(1,-1).find(p=>!holding.has(key(p)) && ['free','cone'].includes((p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode)):undefined;\n if(candidate){\n // Bend in the plane the goal is actually in: perpendicular to both the\n // chain and the way it has to reach. Seeding off the chain's smallest\n // world component instead picks a plane with no relation to the goal,\n // and a straight arm pulled sideways swings out of the screen on its\n // way there \u2014 deterministic, but not a bend anyone asked for.\n const axis=new Vector3().crossVectors(direction,new Vector3().fromArray(goal.position).sub(start));\n if(axis.lengthSq()<1e-12){\n // The goal lies along the chain, so no plane is implied by it; any\n // axis across the chain will do, chosen the same way every time.\n const components=direction.toArray().map(Math.abs);\n axis.setComponent(components.indexOf(Math.min(...components)),1).addScaledVector(direction,-axis.dot(direction));\n }\n bendSeeds.set(key(candidate),axis.normalize());\n }\n }\n size=Math.max(size,chain.slice(1).reduce((sum,p,i)=>sum+new Vector3().fromArray(p.pose.position).distanceTo(new Vector3().fromArray(chain[i].pose.position)),0));\n }\n if(size<1e-8) throw new Error('IK chain has no length. Separate its rest pins first.');\n // Include followers in the graph so branch attachments keep their lengths too.\n const affected=new Set(active);\n for(let changed=true;changed;){changed=false;for(const [id,parent] of parentGroup) if(affected.has(parent)&&!affected.has(id)){affected.add(id);changed=true;}}\n const unchanged=goals.every(g=>{const p=byId.get(g.id)!;return new Vector3().fromArray(g.position).distanceToSquared(new Vector3().fromArray(p.pose.position))<1e-20 && new Quaternion().fromArray(g.rotation).angleTo(new Quaternion().fromArray(p.pose.rotation))<1e-10;});\n if(unchanged && !pins.some(p=>p.ikConstraint && p.ikConstraint.mode!=='free')) return pins.filter(p=>affected.has(key(p))).map(p=>({id:p.id,pose:p.pose}));\n const origin=new Vector3().fromArray(byId.get(goals[0].id)!.pose.position);\n const frames=new Map<string,Link>(), forest:Link[]=[], building=new Set<string>();\n const coneJoints=new Map<string,Joint>();\n const freeJoints=new Map<string,Joint>();\n const branchJoints=new Map<string,{joint:Joint;frame:Link}>();\n const build=(id:string):Link=>{\n const cached=frames.get(id);if(cached) return cached;\n if(building.has(id)) throw new Error('Cyclic IK hierarchy.');building.add(id);\n const pin=groups.get(id)![0],parentId=parentGroup.get(id),parent=parentId ? groups.get(parentId)![0] : undefined;\n const parentFrame=parentId ? build(parentId) : new Link();\n let attachment=parentFrame;\n if(parentId&&active.has(id)&&!holding.has(id)&&holding.has(parentId)){\n const pivot=new Joint();pivot.setDoF(3,4,5);pivot.setDoFValues(0,0,0);pivot.setRestPoseValues(0,0,0);\n parentFrame.addChild(pivot);attachment=new Link();pivot.addChild(attachment);\n branchJoints.set(id,{joint:pivot,frame:attachment});\n }\n const parentRotation=parent ? new Quaternion().fromArray(parent.pose.rotation) : new Quaternion();\n const position=new Vector3().fromArray(pin.pose.position).sub(parent ? new Vector3().fromArray(parent.pose.position):origin).applyQuaternion(parentRotation.clone().invert()).divideScalar(size);\n const relative=parentRotation.clone().invert().multiply(new Quaternion().fromArray(pin.pose.rotation)).normalize();\n const joint=new Joint();joint.setPosition(position.x,position.y,position.z);attachment.addChild(joint);\n const link=new Link(),constraint=pin.ikConstraint ?? DEFAULT_IK_CONSTRAINT;\n const movable=active.has(id)&&!holding.has(id);\n if(!movable || constraint.mode==='locked') joint.setQuaternion(...relative.toArray());\n else if(constraint.mode==='hinge') {\n let axis=new Vector3();\n if(constraint.axis!=='auto') axis.setComponent(['x','y','z'].indexOf(constraint.axis),1);\n else {\n const child=pins.find(p=>parents.get(p.id)===pin.id && active.has(key(p)));\n if(parent&&child) axis.crossVectors(new Vector3().fromArray(pin.rest).sub(new Vector3().fromArray(parent.rest)),new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)));\n if(axis.lengthSq()<1e-10) {const direction=child ? new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)).normalize():new Vector3(0,1,0);axis.crossVectors(direction,Math.abs(direction.z)<.9 ? new Vector3(0,0,1):new Vector3(1,0,0));}\n axis.normalize();\n }\n const basis=new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis);\n joint.setQuaternion(...basis.toArray());link.setQuaternion(...basis.clone().invert().toArray());\n joint.setDoF(5);joint.setMinLimits(constraint.min*Math.PI/180);joint.setMaxLimits(constraint.max*Math.PI/180);\n const twist=2*Math.atan2(new Vector3(relative.x,relative.y,relative.z).dot(axis),relative.w);\n joint.setDoFValues(Math.atan2(Math.sin(twist),Math.cos(twist)));joint.setRestPoseValues(0);\n } else {\n if(constraint.mode==='cone')coneJoints.set(id,joint);\n else freeJoints.set(id,joint);\n joint.setDoF(3,4,5);\n const euler=new Euler().setFromQuaternion(relative,'ZYX');joint.setDoFValues(euler.x,euler.y,euler.z);joint.setRestPoseValues(euler.x,euler.y,euler.z);\n const seed=bendSeeds.get(id);\n if(seed && !roots.has(id) && !goals.some(g=>key(byId.get(g.id)!)===id)){\n const axis=seed.clone().applyQuaternion(parentRotation.clone().invert());\n const seeded=new Euler().setFromQuaternion(new Quaternion().setFromAxisAngle(axis,.03).multiply(relative),'ZYX');\n joint.setDoFValues(seeded.x,seeded.y,seeded.z);\n }\n }\n joint.addChild(link);frames.set(id,link);building.delete(id);if(!parentId) forest.push(parentFrame);return link;\n };\n for(const id of groups.keys()) build(id);\n // Limits describe the visible segment in the committed parent's frame, not\n // a shared attachment's temporary solver rotation or a stale inserted frame.\n const limitRotation=(id:string,rotation:Quaternion,parentRotation:Quaternion)=>{\n const pin=groups.get(id)![0];if(pin.ikConstraint?.mode!=='cone')return rotation;\n const parentId=parentGroup.get(id),parent=parentId?groups.get(parentId)![0]:undefined;\n const child=pins.find(p=>parents.get(p.id)===pin.id);\n if(retained.has(id)&&child&&!active.has(key(child)))return rotation;\n const axis=child?new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)):parent?new Vector3().fromArray(pin.rest).sub(new Vector3().fromArray(parent.rest)):new Vector3(0,1,0);\n if(axis.lengthSq()<1e-12)axis.set(0,1,0);\n const movingAxis=child?new Vector3().fromArray(child.pose.position).sub(new Vector3().fromArray(pin.pose.position)).applyQuaternion(new Quaternion().fromArray(pin.pose.rotation).invert()):axis;\n if(movingAxis.lengthSq()<1e-12)movingAxis.copy(axis);\n const reference=parentId&&retained.has(parentId)?new Quaternion().fromArray(parent!.pose.rotation):parentRotation;\n const relative=reference.clone().invert().multiply(parentRotation).multiply(rotation);\n return parentRotation.clone().invert().multiply(reference).multiply(constrainCone(relative,axis,pin.ikConstraint,movingAxis));\n };\n // Continuity refers to the pose on screen, before analytic initialization\n // or cone projection chooses a candidate. Include temporary body pivots.\n const priorRotations=new Map([...frames.values(),...[...branchJoints.values()].map(branch=>branch.frame)].map(frame=>{\n frame.updateMatrixWorld();return [frame,new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld))] as const;\n }));\n const closures:Goal[]=[];\n for(const target of goals){\n const pin=byId.get(target.id)!,anchor=groups.get(key(pin))![0];\n const offset=new Vector3().fromArray(pin.pose.position).sub(new Vector3().fromArray(anchor.pose.position)).applyQuaternion(new Quaternion().fromArray(anchor.pose.rotation).invert()).divideScalar(size);\n const attachment=new Joint();attachment.setPosition(...offset.toArray());frames.get(key(pin))!.addChild(attachment);\n const tip=new Link();attachment.addChild(tip);\n const goal=new Goal();\n const freeEndpoint=groups.get(key(pin))!.length===1 && (!pin.ikConstraint || pin.ikConstraint.mode==='free');\n if(freeEndpoint) goal.setGoalDoF(0,1,2);else goal.setGoalDoF(0,1,2,3,4,5);\n goal.makeClosure(tip);\n const requested=new Vector3().fromArray(target.position);\n if(goals.length===1 && freeEndpoint){\n const chain=ikChain(pins,parents,target.id,mass);\n const first=chain.findIndex(p=>!holding.has(key(p)) && (p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode!=='locked');\n const moving=first<0?[]:chain.slice(branchJoints.has(key(chain[first]))?Math.max(0,first-1):first);\n // For an unconstrained ball-joint chain its link lengths define a\n // reachable spherical shell. Solve against that shell, not an impossible\n // residual which can stall the iterative solver away from the closest\n // pose. The authored world target is deliberately left unchanged.\n if(moving.length>1 && moving.every((p,i)=>(i===0&&branchJoints.has(key(moving[1])))||(!fixed.has(p.id) && groups.get(key(p))!.length===1 && (p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode==='free'))){\n const pivot=new Vector3().fromArray(moving[0].pose.position);\n const lengths=moving.slice(1).map((p,i)=>new Vector3().fromArray(p.pose.position).distanceTo(new Vector3().fromArray(moving[i].pose.position)));\n const outer=lengths.reduce((a,b)=>a+b,0),inner=Math.max(0,2*Math.max(...lengths)-outer),delta=requested.clone().sub(pivot),distance=delta.length();\n if(distance<inner || distance>outer){\n if(distance<1e-12)delta.fromArray(moving.at(-1)!.pose.position).sub(pivot);\n if(delta.lengthSq()>1e-24)requested.copy(pivot).add(delta.setLength(Math.max(inner,Math.min(outer,distance))));\n }\n if(moving.length===2){\n // One free link has a closed-form minimum-rotation solution. Its\n // positional Jacobian is rank deficient (twist is unobservable), so\n // initialize it analytically instead of relying on an arbitrary seed.\n const before=new Vector3().fromArray(moving[1].pose.position).sub(pivot),after=requested.clone().sub(pivot);\n if(before.lengthSq()>1e-24 && after.lengthSq()>1e-24){\n const branch=branchJoints.get(key(moving[1])),parent=branch?moving[0]:byId.get(parents.get(moving[0].id)??'');\n const local=parent?new Quaternion().fromArray(parent.pose.rotation).invert():new Quaternion();\n local.multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().fromArray(moving[0].pose.rotation));\n const euler=new Euler().setFromQuaternion(local,'ZYX');(branch?.joint??freeJoints.get(key(moving[0])))!.setDoFValues(euler.x,euler.y,euler.z);\n }\n }\n }\n }\n goal.setPosition(...requested.sub(origin).divideScalar(size).toArray());goal.setQuaternion(...target.rotation);\n closures.push(goal);\n }\n // Two-link limbs have an exact positional solution. Keep their existing bend\n // plane and transport each frame by the minimum swing: an Euler/SVD solve can\n // choose a different elbow branch or arbitrary axial twist near singularity.\n // Cone projection + constrained refinement below still enforce authored limits.\n let analytic=false;\n if(goals.length===1){\n const goal=goals[0],chain=ikChain(pins,parents,goal.id,mass);\n const first=chain.findIndex((p,i)=>coneJoints.has(key(p))||freeJoints.has(key(p))||(i+1<chain.length&&branchJoints.has(key(chain[i+1]))));\n const limb=first<0?[]:chain.slice(first),tipPin=byId.get(goal.id)!;\n if(limb.length===3&&limb.every(p=>groups.get(key(p))!.length===1)\n &&limb.slice(0,2).every((p,i)=>coneJoints.has(key(p))||freeJoints.has(key(p))||branchJoints.has(key(limb[i+1])))\n &&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\n const world=(p:PinRecord)=>{const frame=frames.get(key(p))!;frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const matrices=limb.map(world),points=matrices.map(m=>new Vector3().setFromMatrixPosition(m));\n const [base,knee,tip]=points,a=base.distanceTo(knee),b=knee.distanceTo(tip);\n const direction=new Vector3().fromArray(closures[0].position).sub(base);\n if(a>1e-10&&b>1e-10&&direction.lengthSq()>1e-20){\n const distance=Math.max(Math.abs(a-b)+1e-9,Math.min(a+b-1e-9,direction.length()));direction.normalize();\n const oldAxis=tip.clone().sub(base).normalize();\n const bend=knee.clone().sub(base).addScaledVector(oldAxis,-knee.clone().sub(base).dot(oldAxis));\n // Transport the previous pole with the target, instead of projecting it\n // against the new axis (which can flip the knee on a large target move).\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(oldAxis,direction));\n if(bend.lengthSq()<1e-16){\n bend.fromArray(limb[1].rest).sub(new Vector3().fromArray(limb[0].rest));\n const restAxis=new Vector3().fromArray(limb[2].rest).sub(new Vector3().fromArray(limb[0].rest)).normalize();\n bend.addScaledVector(restAxis,-bend.dot(restAxis)).applyQuaternion(new Quaternion().setFromRotationMatrix(matrices[0]));\n bend.addScaledVector(direction,-bend.dot(direction));\n }\n if(bend.lengthSq()<1e-16){bend.set(Math.abs(direction.x)<.8?1:0,Math.abs(direction.x)<.8?0:1,0);bend.addScaledVector(direction,-bend.dot(direction));}\n const along=(a*a-b*b+distance*distance)/(2*distance);\n const desiredKnee=base.clone().addScaledVector(direction,along).addScaledVector(bend.normalize(),Math.sqrt(Math.max(0,a*a-along*along)));\n const desiredTip=base.clone().addScaledVector(direction,distance);\n for(const [i,end] of [desiredKnee,desiredTip].entries()){\n const pin=limb[i],branch=branchJoints.get(key(limb[i+1])),frame=branch?.frame??frames.get(key(pin))!;\n frame.updateMatrixWorld();\n const matrix=new Matrix4().fromArray(frame.matrixWorld),pivot=new Vector3().setFromMatrixPosition(matrix);\n const before=new Vector3().setFromMatrixPosition(world(limb[i+1])).sub(pivot),after=end.clone().sub(pivot);\n const parentId=parentGroup.get(key(pin)),parentFrame=branch?frames.get(key(pin)):branchJoints.get(key(pin))?.frame??(parentId?frames.get(parentId):undefined);parentFrame?.updateMatrixWorld();\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\n const rotation=parentRotation.invert().multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n const euler=new Euler().setFromQuaternion(rotation,'ZYX');(branch?.joint??coneJoints.get(key(pin))??freeJoints.get(key(pin)))!.setDoFValues(euler.x,euler.y,euler.z);\n }\n analytic=true;\n }\n }\n }\n const positionOnlyGoal=goals.length===1&&groups.get(key(byId.get(goals[0].id)!))!.length===1\n &&(!byId.get(goals[0].id)!.ikConstraint||byId.get(goals[0].id)!.ikConstraint!.mode==='free');\n const positionOnlyGoals=goals.every(goal=>groups.get(key(byId.get(goal.id)!))!.length===1\n &&(!byId.get(goal.id)!.ikConstraint||byId.get(goal.id)!.ikConstraint!.mode==='free'));\n // A lone planted foot has a prior bend in the current frame. Starting a\n // global SVD solve there can choose another elbow branch on a tiny edit;\n // the constrained descent below instead continues that bend.\n if(!analytic&&!positionOnlyGoal&&!positionOnlyGoals){\n const solver=new Solver([...forest,...closures]);solver.useSVD=true;solver.maxIterations=48;solver.restPoseFactor=.001;\n solver.translationConvergeThreshold=1e-6;solver.rotationConvergeThreshold=1e-6;solver.translationErrorClamp=.2;\n solver.solve();\n }\n // Project oriented elliptical swing limits in parent-to-child order. Updating the joint\n // frame carries descendants rigidly, so limiting a cone never stretches links.\n const projectCones=()=>{for(const [id,joint] of coneJoints){\n const parentId=parentGroup.get(id), frame=frames.get(id)!;\n frame.updateMatrixWorld();\n const parentFrame=branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\n const relative=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld)));\n const limited=limitRotation(id,relative,parentRotation),euler=new Euler().setFromQuaternion(limited,'ZYX');\n joint.setDoFValues(euler.x,euler.y,euler.z);frame.updateMatrixWorld();\n }\n };\n if(goals.length===1||!positionOnlyGoals)projectCones();\n if(goals.length>1&&positionOnlyGoals){\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const tips=goals.map(goal=>({goal,frame:frames.get(key(byId.get(goal.id)!))!,desired:new Vector3().fromArray(closures[goals.indexOf(goal)].position),chain:ikChain(pins,parents,goal.id,mass).slice(0,-1).reverse()}));\n const poles=tips.flatMap(tip=>{\n const chain=poleChains.get(tip.goal.id);\n if(!chain||chain.length<3)return [];\n const base=chain[0],knee=chain[Math.floor((chain.length-1)/2)],end=chain.at(-1)!;\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest));\n const restBend=new Vector3().fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\n if(restAxis.lengthSq()<1e-16)return [];\n restBend.addScaledVector(restAxis,-restBend.dot(restAxis)/restAxis.lengthSq());\n if(restBend.length()<restAxis.length()*.02)return [];\n const minBend=Math.min(.03,restBend.length()/size*.5);\n return [{base,knee,chain,tip,minBend,restAxis:restAxis.normalize(),restPole:restBend.normalize()}];\n });\n const poleState=(pole:typeof poles[number])=>{\n const base=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.base))!));\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\n const axis=pole.tip.desired.clone().sub(base).normalize();\n const preferred=pole.restPole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.restAxis,axis));\n preferred.addScaledVector(axis,-preferred.dot(axis)).normalize();\n const bend=knee.sub(base);bend.addScaledVector(axis,-bend.dot(axis));\n return {base,axis,preferred,bend};\n };\n const initial=[...new Set(tips.flatMap(tip=>tip.chain.flatMap(pin=>[frames.get(key(pin)),branchJoints.get(key(pin))?.frame]).filter((frame):frame is Link=>Boolean(frame))))]\n .map(frame=>({frame,rotation:new Quaternion().setFromRotationMatrix(world(frame))}));\n const cost=()=>tips.reduce((sum,tip)=>sum+new Vector3().setFromMatrixPosition(world(tip.frame)).distanceToSquared(tip.desired),0)\n +POSE_CONTINUITY_WEIGHT*initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0)\n +10*poles.reduce((sum,pole)=>{const {preferred,bend}=poleState(pole);\n return sum+Math.max(0,pole.minBend-bend.dot(preferred))**2;},0);\n for(let sweep=0;sweep<96;sweep++){\n if(cost()<1e-12)break;\n let largestChange=0;\n for(const tip of tips)for(const pin of tip.chain){\n const id=key(pin),joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\n for(const [index,joint] of joints.entries()){\n if(!joint)continue;\n const branch=index===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix),end=new Vector3().setFromMatrixPosition(world(tip.frame));\n const a=end.sub(pivot),b=tip.desired.clone().sub(pivot);\n if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\n const parentId=parentGroup.get(id),localParent=branch?(parentId?frames.get(parentId):undefined):branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n for(let fraction=1;fraction>=1/32;fraction/=2){\n const attempt=old.clone().slerp(rotation,fraction);set(attempt);\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\n set(old);\n }\n }\n }\n for(const pole of poles){\n const {base,preferred,bend}=poleState(pole),along=bend.dot(preferred);\n if(along>=pole.minBend)continue;\n const baseId=key(pole.base),nextId=key(pole.chain[1]);\n const branch=branchJoints.get(nextId),joint=branch?.joint??coneJoints.get(baseId)??freeJoints.get(baseId);\n const frame=branch?.frame??frames.get(baseId);\n if(!joint||!frame)continue;\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\n const arm=knee.sub(base),aim=arm.clone().addScaledVector(preferred,Math.min(.01,pole.minBend-along));\n if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\n const parentId=branch?baseId:parentGroup.get(baseId),parentFrame=parentId?frames.get(parentId):undefined;\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(world(parentFrame)):new Quaternion();\n const matrix=world(frame),old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let proposal=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)proposal=limitRotation(baseId,proposal,parentRotation);\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n for(let fraction=1;fraction>=1/32;fraction/=2){\n const attempt=old.clone().slerp(proposal,fraction);set(attempt);\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\n set(old);\n }\n }\n if(largestChange<1e-5)break;\n }\n }\n // Projecting cones only AFTER the unconstrained solve leaves the endpoint\n // stranded, even when another joint could reach it. Finish positional chains\n // with constrained coordinate descent: every accepted step obeys its cone\n // and reduces the residual. Siblings/fixed roots never enter this joint list.\n if(goals.length===1){\n const target=goals[0],tipPin=byId.get(target.id)!;\n if(groups.get(key(tipPin))!.length===1&&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\n const tip=frames.get(key(tipPin))!,desired=new Vector3().fromArray(closures[0].position);\n const ordered=ikChain(pins,parents,target.id,mass),chain=ordered.slice(0,-1).reverse();\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const ground=tipPin.chainRole?.kind==='leg'&&Number.isFinite(floor)?(floor-origin.y)/size:-Infinity;\n const point=(pin:PinRecord)=>new Vector3().setFromMatrixPosition(world(frames.get(key(pin))!));\n const initial=[...new Set(chain.flatMap(pin=>[frames.get(key(pin))!,branchJoints.get(key(pin))?.frame].filter((frame):frame is Link=>Boolean(frame))))].map(frame=>({frame,rotation:priorRotations.get(frame)!}));\n // Endpoint distance has mirrored solutions. Carry each visible bend's\n // pole into the new chord frame instead of letting descent change sides.\n const poles=ordered.slice(1,-1).flatMap((knee,i)=>{\n const base=ordered[i],end=ordered[i+2];\n const chord=new Vector3().fromArray(end.pose.position).sub(new Vector3().fromArray(base.pose.position)),span=chord.length(),axis=chord.normalize();\n const bend=new Vector3().fromArray(knee.pose.position).sub(new Vector3().fromArray(base.pose.position));\n bend.addScaledVector(axis,-bend.dot(axis));\n // Near extension the positional pole is numerical noise; the rest\n // bend carried by the current base frame still defines its side.\n if(bend.length()<span*.02){\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest)).normalize();\n bend.fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\n bend.addScaledVector(restAxis,-bend.dot(restAxis));\n const rotation=new Quaternion().fromArray(base.pose.rotation);\n bend.applyQuaternion(rotation);\n restAxis.applyQuaternion(rotation);\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(restAxis,axis));\n }\n return bend.length()<span*.02?[]:[{base,knee,end,axis,pole:bend.normalize()}];\n });\n const poleCost=()=>poles.reduce((sum,pole)=>{\n const base=point(pole.base),axis=point(pole.end).sub(base).normalize();\n const preferred=pole.pole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.axis,axis));\n const bend=point(pole.knee).sub(base);bend.addScaledVector(axis,-bend.dot(axis));\n return sum+Math.max(0,-bend.dot(preferred))**2;\n },0);\n // Position alone does not determine every joint frame. Keep the nearest\n // solution to the pose on screen when a controller moves a tiny amount.\n const cost=()=>{\n const error=new Vector3().setFromMatrixPosition(world(tip)).distanceToSquared(desired);\n let penetration=0;\n if(Number.isFinite(ground))for(const pin of ordered.slice(1,-1))penetration+=Math.max(0,ground-point(pin).y)**2;\n const drift=initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0);\n return error+16*penetration+100*poleCost()+POSE_CONTINUITY_WEIGHT*drift;\n };\n // Near a tight cone the last few sweeps are small but visible. Stop only\n // once the pose itself has settled, not merely when the goal is close.\n for(let sweep=0;sweep<128;sweep++){\n if(cost()<1e-12)break;\n let largestChange=0;\n for(const pin of chain){\n const id=key(pin);\n const joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\n for(const [jointIndex,joint] of joints.entries()){\n if(!joint)continue;\n const branch=jointIndex===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix);\n const end=new Vector3().setFromMatrixPosition(world(tip)),before=cost();\n const a=end.clone().sub(pivot),b=desired.clone().sub(pivot);if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\n const parentId=parentGroup.get(id),localParent=branch?parentId?frames.get(parentId):undefined:branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\n const set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n let accepted=false;\n for(let fraction=1;fraction>=1/32;fraction/=2){\n let attempt=old.clone().slerp(rotation,fraction);\n if(!branch)attempt=limitRotation(id,attempt,parentRotation);\n set(attempt);\n if(cost()<=before+1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));accepted=true;break;}\n }\n if(!accepted)set(old);\n if(Number.isFinite(ground))for(const descendant of ordered.slice(ordered.indexOf(pin)+1,-1)){\n const lower=point(descendant);if(lower.y>=ground)continue;\n const current=point(pin),arm=lower.clone().sub(current),raised=lower.clone();raised.y=ground;\n const aim=raised.sub(current);if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\n const parentNow=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const previous=parentNow.clone().invert().multiply(new Quaternion().setFromRotationMatrix(world(frame)));\n let proposal=parentNow.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(world(frame)));\n if(!branch)proposal=limitRotation(id,proposal,parentNow);\n const start=cost();\n for(let fraction=1;fraction>=1/16;fraction/=2){\n const attempt=previous.clone().slerp(proposal,fraction);set(attempt);\n if(cost()<start-1e-14){largestChange=Math.max(largestChange,previous.angleTo(attempt));break;}\n set(previous);\n }\n }\n }\n }\n if(largestChange<1e-5)break;\n }\n }\n }\n // Ancestor refinement must not leave a cone outside its committed frame.\n if(goals.length===1||!positionOnlyGoals)projectCones();\n // A free goal's orientation is independent of its position, including when\n // extra toe/follower joints are added below it. Carry those followers through\n // the frame, rather than only overwriting the endpoint's returned quaternion.\n for(const goal of goals){\n const id=key(byId.get(goal.id)!),joint=freeJoints.get(id);if(!joint||groups.get(id)!.length!==1)continue;\n const parentId=parentGroup.get(id),parent=parentId?frames.get(parentId):undefined;parent?.updateMatrixWorld();\n const rotation=parent?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parent.matrixWorld)).invert():new Quaternion();\n rotation.multiply(new Quaternion().fromArray(goal.rotation));\n const e=new Euler().setFromQuaternion(rotation,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frames.get(id)!.updateMatrixWorld();\n }\n const result=pins.filter(p=>affected.has(key(p))).map(pin=>{\n if(fixed.has(pin.id)) return {id:pin.id,pose:pin.pose};\n const anchor=groups.get(key(pin))![0],frame=frames.get(key(pin))!;frame.updateMatrixWorld();\n const matrix=new Matrix4().fromArray(frame.matrixWorld),rotation=new Quaternion().setFromRotationMatrix(matrix).normalize();\n const position=new Vector3().setFromMatrixPosition(matrix).multiplyScalar(size).add(origin);\n const delta=rotation.clone().multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\n const goal=goals.find(g=>key(byId.get(g.id)!)===key(pin));\n const terminal=![...parentGroup.values()].includes(key(pin));\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) rotation.fromArray(goal.rotation);\n const offset=new Vector3().fromArray(pin.pose.position).sub(new Vector3().fromArray(anchor.pose.position));\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) delta.copy(rotation).multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\n position.add(offset.applyQuaternion(delta));\n if(!parentGroup.has(key(pin)) && pin.id===anchor.id) position.fromArray(pin.pose.position);\n if(![...position.toArray(),...rotation.toArray()].every(Number.isFinite)) throw new Error('IK produced an invalid pose.');\n return {id:pin.id,pose:{position:position.toArray(),rotation:rotation.toArray(),scale:pin.pose.scale}};\n });\n return result;\n}\n", "import { validateRig, type JointsRig } from './joints-json.js';\nimport { ikChain } from './pin-ik.js';\nimport {DEFAULT_MOTION} from './motion-settings.js';\nimport type { ClothCollider, ClothLink } from './pin-cloth.js';\n\nexport const NEEDLE_DEFORMATION_RIG = 'NEEDLE_deformation_rig';\nexport interface RigDescriptor extends JointsRig {\n version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;\n joints: { node: number; parent: number | null; mass: number }[];\n chains: { endpoint: number; joints: number[]; mode: 'ik' | 'secondary' | 'cloth' | 'fur' }[];\n helpers?: { node: number; influences: { node: number; weight: number }[] }[];\n cloth?: { links: ClothLink[]; colliders: ClothCollider[] };\n furSurface?: { heightTexture: number; texCoord?: number };\n}\n/** Validate before allocating runtime objects or accepting node references. */\nexport function parseRigDescriptor(value: unknown, nodeCount: number, textureCount = Infinity): RigDescriptor {\n if (!value || typeof value !== 'object') throw new Error('Invalid deformation rig.');\n const raw = value as RigDescriptor;\n 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.');\n 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.');\n 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.');\n if (raw.version < 5 && raw.windStrength !== undefined) throw new Error('Wind requires NEEDLE_deformation_rig version 5.');\n if (raw.activePose === 0 && raw.version < 9) throw new Error('An unselected authored pose requires NEEDLE_deformation_rig version 9.');\n const restSlot=raw.poseSlots?.find(slot=>slot.slot===0);\n if(restSlot && raw.version<7)throw new Error('Pose 0 requires NEEDLE_deformation_rig version 7.');\n const rig = validateRig({...raw,poseSlots:raw.poseSlots?.filter(slot=>slot.slot!==0)}, raw.version>=3?256:128);\n if(restSlot){\n if(raw.poseSlots.filter(slot=>slot.slot===0).length!==1 || !Array.isArray(restSlot.poses) || restSlot.poses.length!==rig.pins.length ||\n 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.');\n validateRig({pins:rig.pins,activePose:1,poseSlots:[{slot:1,poses:restSlot.poses}],poseTimes:[]},raw.version>=3?256:128);\n }\n if (raw.version < 5 && rig.pins.some(pin=>pin.fur)) throw new Error('Fur requires NEEDLE_deformation_rig version 5.');\n if (raw.furSurface && !rig.pins.some(pin => pin.fur)) throw new Error('Fur height requires a Fur rig.');\n const node = (n: number) => Number.isInteger(n) && n >= 0 && n < nodeCount;\n if (!Array.isArray(raw.joints) || raw.joints.length !== rig.pins.length) throw new Error('Invalid rig joint bindings.');\n const indices = new Set<number>();\n for (const joint of raw.joints) {\n 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.');\n indices.add(joint.node);\n }\n const parents = new Map(raw.joints.map(j => [j.node, j.parent]));\n for (const joint of raw.joints) {\n const seen = new Set<number>(); let cursor: number | null = joint.node;\n while (cursor !== null) {\n if (!indices.has(cursor) || seen.has(cursor)) throw new Error('Invalid or cyclic rig hierarchy.');\n seen.add(cursor); cursor = parents.get(cursor)!;\n }\n }\n if (!Array.isArray(raw.chains) || raw.chains.length > rig.pins.length) throw new Error('Invalid motion chains.');\n const endpoints = new Set<number>();\n for (const chain of raw.chains) {\n 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.');\n endpoints.add(chain.endpoint);\n }\n const pinParents = new Map<string, string>(), masses = new Map<string, number>();\n 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); });\n for (const [i, pin] of rig.pins.entries()) {\n const chain = raw.chains.find(c => c.endpoint === raw.joints[i].node);\n const mode = !pin.guide && (pin.ik ? 'ik' : pin.wiggle ? 'secondary' : pin.cloth ? 'cloth' : pin.fur ? 'fur' : null);\n if (!mode && chain) throw new Error('Unexpected motion chain.');\n if (!mode) continue;\n const articulated=raw.version>=3?rig.pins.filter((_,i)=>!raw.helpers?.some(h=>h.node===raw.joints[i].node)):rig.pins;\n 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);\n // Chains are derived caches, not authoritative authored topology. Older\n // writers used discontinuous reach gates; accept any valid ancestor suffix\n // and rebuild the current extent from the saved reach in the runtime.\n 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.');\n }\n if (raw.helpers !== undefined && (!Array.isArray(raw.helpers) || raw.helpers.length > 256)) throw new Error('Invalid helper bindings.');\n const helpers = raw.helpers?.map(helper => {\n 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.');\n const seen = new Set<number>(); let sum = 0;\n for (const influence of helper.influences) {\n 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.');\n seen.add(influence.node); sum += influence.weight;\n }\n if (helper.influences.length && Math.abs(sum - 1) > 1e-4) throw new Error('Helper weights must sum to one.');\n indices.add(helper.node); return { node: helper.node, influences: helper.influences.map(i => ({ ...i })) };\n });\n if (raw.version >= 2 && !helpers) throw new Error('Rig requires helper bindings.');\n if (helpers && new Set(helpers.map(h=>h.node)).size!==helpers.length) throw new Error('Duplicate helper bone.');\n 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.');\n const pinById = new Map(rig.pins.map(p => [p.id, p]));\n 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.');\n 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.');\n 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 } } : {}) };\n}\n"],
5
5
  "mappings": ";;;AAWO,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB,CAAC,OAAM,OAAM,QAAO,QAAO,QAAO,OAAM,YAAW,OAAO;;;ACZjF,IAAM,uBAAuB;;;ACA7B,IAAM,iBAA2C,EAAE,OAAO,KAAI,WAAW,MAAM,IAAE,KAAK,KAAK,SAAS,MAAK,eAAc,GAAE,UAAS,EAAE;AACpI,SAAS,uBAAuB,OAAuB;AAC5D,MAAI,CAAC,SAAS,CAAC,OAAO,SAAS,MAAM,KAAK,KAAK,MAAM,QAAQ,KAAK,MAAM,QAAQ,KAC3E,CAAC,OAAO,SAAS,MAAM,SAAS,KAAK,MAAM,YAAY,QAAO,MAAM,YAAY,KAChF,CAAC,OAAO,SAAS,MAAM,OAAO,KAAK,MAAM,UAAU,QAAO,MAAM,UAAU,KAC1E,CAAC,OAAO,SAAS,MAAM,aAAa,KAAK,MAAM,gBAAc,KAAK,MAAM,gBAAc,KACtF,CAAC,OAAO,SAAS,MAAM,QAAQ,KAAK,MAAM,WAAS,KAAK,MAAM,WAAS,EAAG,OAAM,IAAI,MAAM,0BAA0B;AAC3H;;;ACRA,SAAS,YAAY,eAAe;AAG7B,SAAS,qBAAqB,OAAoB;AACvD,M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CAAC,SAAS,UAAU,CAAC,QAAQ,IAAI,SAAS,MAAM,KAAK,QAAQ,IAAI,SAAS,MAAM,GAAG,MAAO,OAAM,IAAI,MAAM,yBAAyB;AACxX,SAAO,EAAE,GAAG,KAAI,WAAU,WAAS,CAAC,UAAS,GAAG,IAAI,SAAS,IAAE,IAAI,WAAW,SAAS,IAAI,SAAS,QAAQ,IAAI,OAAO,IAAI,QAAM,EAAE,GAAG,EAAE,EAAE,GAAG,QAAQ,IAAI,OAAO,IAAI,QAAM,EAAE,GAAG,GAAG,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,GAAG,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC,GAAI,GAAI,IAAI,QAAQ,EAAE,OAAO,EAAE,OAAO,IAAI,MAAM,MAAM,IAAI,QAAM,EAAE,GAAG,EAAE,EAAE,GAAG,WAAW,IAAI,MAAM,UAAU,IAAI,QAAM,EAAE,GAAG,GAAG,UAAU,CAAC,GAAG,EAAE,QAAQ,EAA4B,EAAE,EAAE,EAAE,IAAI,CAAC,GAAI,GAAI,IAAI,aAAa,EAAE,YAAY,EAAE,GAAG,IAAI,WAAW,EAAE,IAAI,CAAC,EAAG;AAC7e;",
6
6
  "names": ["Vector3", "value", "rotation", "Quaternion", "Vector3", "pin", "i", "pin"]
7
7
  }
@@ -357,6 +357,13 @@ function solvePinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new
357
357
  group.push(pin);
358
358
  groups.set(key(pin), group);
359
359
  }
360
+ const parentGroup = /* @__PURE__ */ new Map();
361
+ for (const [id, members] of groups) {
362
+ const parent = members.map((p) => byId.get(parents.get(p.id) ?? "")).find((p) => p && key(p) !== id);
363
+ if (parent) parentGroup.set(id, key(parent));
364
+ }
365
+ const holding = /* @__PURE__ */ new Set();
366
+ for (const [id, members] of groups) if (members.some((p) => fixed.has(p.id))) for (let at = id; at && !holding.has(at); at = parentGroup.get(at)) holding.add(at);
360
367
  const active = /* @__PURE__ */ new Set(), roots = /* @__PURE__ */ new Set();
361
368
  const bendSeeds = /* @__PURE__ */ new Map();
362
369
  let size = 0;
@@ -370,7 +377,7 @@ function solvePinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new
370
377
  if (span > 1e-8 && new Vector33().fromArray(goal.position).distanceTo(start) < span * (1 - 1e-6)) {
371
378
  direction.divideScalar(span);
372
379
  const straight = chain.every((p) => new Vector33().fromArray(p.pose.position).sub(start).cross(direction).lengthSq() < span * span * 1e-12);
373
- const candidate = straight ? chain.slice(1, -1).find((p) => !groups.get(key(p)).some((q) => fixed.has(q.id)) && ["free", "cone"].includes((p.ikConstraint ?? DEFAULT_IK_CONSTRAINT).mode)) : void 0;
380
+ const candidate = straight ? chain.slice(1, -1).find((p) => !holding.has(key(p)) && ["free", "cone"].includes((p.ikConstraint ?? DEFAULT_IK_CONSTRAINT).mode)) : void 0;
374
381
  if (candidate) {
375
382
  const axis = new Vector33().crossVectors(direction, new Vector33().fromArray(goal.position).sub(start));
376
383
  if (axis.lengthSq() < 1e-12) {
@@ -383,11 +390,6 @@ function solvePinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new
383
390
  size = Math.max(size, chain.slice(1).reduce((sum, p, i) => sum + new Vector33().fromArray(p.pose.position).distanceTo(new Vector33().fromArray(chain[i].pose.position)), 0));
384
391
  }
385
392
  if (size < 1e-8) throw new Error("IK chain has no length. Separate its rest pins first.");
386
- const parentGroup = /* @__PURE__ */ new Map();
387
- for (const [id, members] of groups) {
388
- const parent = members.map((p) => byId.get(parents.get(p.id) ?? "")).find((p) => p && key(p) !== id);
389
- if (parent) parentGroup.set(id, key(parent));
390
- }
391
393
  const affected = new Set(active);
392
394
  for (let changed = true; changed; ) {
393
395
  changed = false;
@@ -414,7 +416,7 @@ function solvePinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new
414
416
  const pin = groups.get(id)[0], parentId = parentGroup.get(id), parent = parentId ? groups.get(parentId)[0] : void 0;
415
417
  const parentFrame = parentId ? build(parentId) : new Link();
416
418
  let attachment = parentFrame;
417
- if (parentId && active.has(id) && !groups.get(id).some((p) => fixed.has(p.id)) && groups.get(parentId).some((p) => fixed.has(p.id))) {
419
+ if (parentId && active.has(id) && !holding.has(id) && holding.has(parentId)) {
418
420
  const pivot = new Joint();
419
421
  pivot.setDoF(3, 4, 5);
420
422
  pivot.setDoFValues(0, 0, 0);
@@ -431,7 +433,7 @@ function solvePinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new
431
433
  joint.setPosition(position.x, position.y, position.z);
432
434
  attachment.addChild(joint);
433
435
  const link = new Link(), constraint = pin.ikConstraint ?? DEFAULT_IK_CONSTRAINT;
434
- const movable = active.has(id) && !groups.get(id).some((p) => fixed.has(p.id));
436
+ const movable = active.has(id) && !holding.has(id);
435
437
  if (!movable || constraint.mode === "locked") joint.setQuaternion(...relative.toArray());
436
438
  else if (constraint.mode === "hinge") {
437
439
  let axis = new Vector33();
@@ -510,7 +512,7 @@ function solvePinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new
510
512
  const requested = new Vector33().fromArray(target.position);
511
513
  if (goals.length === 1 && freeEndpoint) {
512
514
  const chain = ikChain(pins, parents, target.id, mass);
513
- const first = chain.findIndex((p) => !groups.get(key(p)).some((q) => fixed.has(q.id)) && (p.ikConstraint ?? DEFAULT_IK_CONSTRAINT).mode !== "locked");
515
+ const first = chain.findIndex((p) => !holding.has(key(p)) && (p.ikConstraint ?? DEFAULT_IK_CONSTRAINT).mode !== "locked");
514
516
  const moving = first < 0 ? [] : chain.slice(branchJoints.has(key(chain[first])) ? Math.max(0, first - 1) : first);
515
517
  if (moving.length > 1 && moving.every((p, i) => i === 0 && branchJoints.has(key(moving[1])) || !fixed.has(p.id) && groups.get(key(p)).length === 1 && (p.ikConstraint ?? DEFAULT_IK_CONSTRAINT).mode === "free")) {
516
518
  const pivot = new Vector33().fromArray(moving[0].pose.position);