@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.
- package/CHANGELOG.md +9 -0
- package/README.md +3 -2
- package/build/box-impostor-runtime.js +27 -2
- package/build/box-impostor-runtime.js.map +3 -3
- package/build/deformation-runtime.js +11 -9
- package/build/deformation-runtime.js.map +2 -2
- package/build/impostor-runtime.js +41 -19
- package/build/impostor-runtime.js.map +3 -3
- package/build/internal/box-impostor/box-impostor-display.js +10 -2
- package/build/internal/box-impostor/box-impostor-display.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-faces.js.map +1 -1
- package/build/internal/box-impostor/box-impostor-geometry.js +4 -0
- package/build/internal/box-impostor/box-impostor-geometry.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-material.js +10 -2
- package/build/internal/box-impostor/box-impostor-material.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-metadata.js +4 -0
- package/build/internal/box-impostor/box-impostor-metadata.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-projection.js.map +1 -1
- package/build/internal/box-impostor/box-impostor-runtime.js +27 -2
- package/build/internal/box-impostor/box-impostor-runtime.js.map +3 -3
- package/build/internal/deformation/pin-ik.js +11 -9
- package/build/internal/deformation/pin-ik.js.map +2 -2
- package/build/internal/deformation/pin-wiggle.js.map +1 -1
- package/build/internal/deformation/rig-extension.js.map +1 -1
- package/build/internal/deformation/rig-runtime.js +11 -9
- package/build/internal/deformation/rig-runtime.js.map +2 -2
- package/build/internal/impostor/impostor-node-material.js +41 -19
- package/build/internal/impostor/impostor-node-material.js.map +3 -3
- package/build/internal/pixel-impostor/pixel-impostor-display.js +9 -7
- package/build/internal/pixel-impostor/pixel-impostor-display.js.map +2 -2
- package/build/internal/rendering/classic-webgl-support.js +12 -0
- package/build/internal/rendering/classic-webgl-support.js.map +7 -0
- package/build/internal/rendering/renderer-support.js +13 -0
- package/build/internal/rendering/renderer-support.js.map +3 -3
- package/build/pixel-impostor-runtime.js +9 -7
- package/build/pixel-impostor-runtime.js.map +2 -2
- package/build/types/box-impostor/box-impostor-metadata.d.ts +3 -1
- package/build/types/rendering/classic-webgl-support.d.ts +9 -0
- package/build/types/rendering/classic-webgl-support.js +1 -0
- package/package.json +2 -2
- package/src/box-impostor/box-impostor-material.js +10 -2
- package/src/box-impostor/box-impostor-metadata.js +5 -1
- package/src/deformation/pin-ik.ts +13 -9
- package/src/impostor/impostor-node-material.js +31 -15
- package/src/pixel-impostor/pixel-impostor-display.js +18 -7
- package/src/rendering/classic-webgl-support.js +15 -0
- package/src/rendering/renderer-support.js +5 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/deformation/pin-wiggle.ts", "../../../src/deformation/pin-types.ts", "../../../src/deformation/motion-settings.ts", "../../../src/deformation/pin-ik.ts", "../../../src/deformation/wind.ts"],
|
|
4
|
-
"sourcesContent": ["import { Quaternion, Vector3 } from 'three';\nimport { DEFAULT_FUR_DEPTH, type PinPose, type PinRecord } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\nimport { DEFAULT_MOTION, type MotionSettings } from './motion-settings.js';\nimport { ikChain } from './pin-ik.js';\nimport { windAcceleration } from './wind.js';\n\n/** Disposable secondary motion. Never writes authored pins or history. */\nexport class PinWiggle {\n private springs = new Map<string, { position: Vector3; velocity: Vector3; target:Vector3 }>();\n private topology = '';\n private lastPins: readonly PinRecord[] | null = null;\n private lastParents: PinParents | null = null;\n private awake = false;\n private windTime = 0;\n reset() { this.springs.clear(); this.topology = ''; this.lastPins = null; this.lastParents = null; this.awake = false; this.windTime = 0; }\n\n step(pins: readonly PinRecord[], parents: PinParents, seconds: number, masses?:ReadonlyMap<string,number>, windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {\n if (windStrength <= 0 && !this.awake && pins === this.lastPins && parents === this.lastParents) return {pins,active:false};\n const topology = JSON.stringify(pins.map(p => [p.id,p.rest,p.rigidGroup,p.independent,p.guide,p.wiggle,p.fur,p.furDepth,p.motion,parents.get(p.id)]));\n if (topology !== this.topology) { this.reset(); this.topology = topology; }\n const groups = new Map<string, PinRecord[]>(), byId = new Map(pins.map(p => [p.id,p]));\n const key = (p: PinRecord) => p.rigidGroup ?? p.id;\n for (const pin of pins) { const group = groups.get(key(pin)) ?? []; group.push(pin); groups.set(key(pin),group); }\n const settings = new Map<string,Readonly<MotionSettings>>();\n const volumes=[...groups.values()].filter(group=>!group.every(p=>p.guide)).map(group=>Math.max(1e-9,masses?.get(group[0].id)??1)).sort((a,b)=>a-b);\n const typicalVolume=volumes[Math.floor(volumes.length/2)]??1;\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) {\n const chain=ikChain(pins,parents,pin.id,masses);\n for (const node of chain.length>1 ? chain.slice(1) : chain) if (!settings.has(key(node))) settings.set(key(node),pin.motion ?? DEFAULT_MOTION);\n }\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\n // Fur belongs to the outer shell: unlike Wiggle it must not make the\n // articulated core's ancestor chain into springs.\n for (const pin of pins.filter(p=>p.fur && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\n const output = new Map<string, PinPose>(), visiting = new Set<string>();\n let active = false;\n // Exact underdamped spring integration, stable across variable frame times.\n // Clamp background-tab gaps rather than simulating missed seconds.\n const dt = Math.min(Math.max(seconds,0),.05);\n this.windTime += dt;\n const visit = (id: string) => {\n const group = groups.get(id)!;\n if (output.has(group[0].id)) return;\n if (visiting.has(id)) { for (const pin of group) output.set(pin.id,pin.pose); return; }\n visiting.add(id);\n const parent = group.map(p => byId.get(parents.get(p.id) ?? '')).find(p => p && key(p) !== id);\n if (parent) visit(key(parent));\n const parentPose = parent ? output.get(parent.id)! : undefined;\n const inherited = parent && parentPose ? new Quaternion().fromArray(parentPose.rotation).multiply(new Quaternion().fromArray(parent.pose.rotation).invert()) : new Quaternion();\n const targets = group.map(pin => {\n const position = new Vector3().fromArray(pin.pose.position);\n if (!pin.ik && parent && parentPose) position.sub(new Vector3().fromArray(parent.pose.position)).applyQuaternion(inherited).add(new Vector3().fromArray(parentPose.position));\n return { pin, position, rotation: (pin.ik ? new Quaternion() : inherited.clone()).multiply(new Quaternion().fromArray(pin.pose.rotation)) };\n });\n const center = targets.reduce((sum,p) => sum.add(p.position),new Vector3()).divideScalar(group.length);\n let position = center, rotation = new Quaternion();\n const motion=settings.get(id);\n if (motion && !group.every(p=>p.guide) && !group.some(p=>p.ik)) {\n const ratio=Math.max(.125,Math.min(8,(masses?.get(group[0].id)??typicalVolume)/typicalVolume));\n const gain=motion.strength*Math.max(.25,Math.min(4,Math.pow(1/ratio,.5*motion.massInfluence)));\n const frequency=motion.frequency*2*Math.PI, damping=Math.max(.05,Math.min(1,motion.damping*Math.pow(ratio,.25*motion.massInfluence)));\n const decay = damping * frequency, oscillation = frequency * Math.sqrt(1-damping*damping);\n const e = Math.exp(-decay*dt), c = Math.cos(oscillation*dt), s = oscillation > 1e-8 ? Math.sin(oscillation*dt)/oscillation : dt;\n let spring = this.springs.get(id);\n if (!spring) { spring = { position:center.clone(),velocity:new Vector3(),target:center.clone() }; this.springs.set(id,spring); }\n spring.position.addScaledVector(center.clone().sub(spring.target),1-gain);spring.target.copy(center);\n if(motion.strength===0){spring.position.copy(center);spring.velocity.set(0,0,0);}\n else if (windStrength > 0) spring.velocity.addScaledVector(windAcceleration(this.windTime, windStrength,\n parentPose ? Math.max(center.distanceTo(new Vector3().fromArray(parentPose.position)), 1e-3) : 1, center.toArray()), motion.strength * dt);\n const offset = spring.position.clone().sub(center), velocity = spring.velocity.clone();\n spring.position.copy(offset).multiplyScalar(c).addScaledVector(velocity.clone().addScaledVector(offset,decay),s).multiplyScalar(e).add(center);\n spring.velocity.copy(velocity).multiplyScalar(c).sub(velocity.clone().multiplyScalar(decay).addScaledVector(offset,frequency*frequency).multiplyScalar(s)).multiplyScalar(e);\n const fur = group.find(p=>p.fur), furDepth=fur?.furDepth??DEFAULT_FUR_DEPTH;\n let radius = 1;\n if (parentPose) {\n const pivot = new Vector3().fromArray(parentPose.position), desired = center.clone().sub(pivot);\n radius = desired.length();\n const direction = spring.position.clone().sub(pivot);\n if (radius > 1e-8) {\n if (direction.lengthSq() < 1e-16) direction.copy(desired);\n const length=direction.length();direction.divideScalar(length);\n const coreRadius=radius*(1-furDepth),outerRadius=radius*(1+furDepth);\n const projected=fur?Math.max(coreRadius,Math.min(outerRadius,length)):radius;\n spring.position.copy(pivot).addScaledVector(direction,projected);\n if(!fur||length<coreRadius||length>outerRadius)spring.velocity.addScaledVector(direction,-spring.velocity.dot(direction));\n rotation.setFromUnitVectors(desired.normalize(),direction);\n } else { spring.position.copy(center); spring.velocity.set(0,0,0); }\n }\n if (fur) {\n const shell = Math.max(1e-4, radius) * furDepth;\n if (shell === 0) { spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity(); }\n const displacement = spring.position.clone().sub(center);\n if (displacement.length() > shell) {\n displacement.setLength(shell); spring.position.copy(center).add(displacement);\n const outward=displacement.normalize();spring.velocity.addScaledVector(outward,-Math.max(0,spring.velocity.dot(outward)));\n }\n if(parentPose&&radius>1e-8){\n const pivot=new Vector3().fromArray(parentPose.position),desired=center.clone().sub(pivot).normalize(),direction=spring.position.clone().sub(pivot).normalize();\n rotation.setFromUnitVectors(desired,direction);\n }\n }\n const epsilon = Math.max(radius,1e-3)*1e-5;\n if (spring.position.distanceToSquared(center) < epsilon*epsilon && spring.velocity.lengthSq() < epsilon*epsilon*frequency*frequency) {\n spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity();\n } else active = true;\n position = spring.position;\n }\n for (const target of targets) output.set(target.pin.id, {\n position:target.position.sub(center).applyQuaternion(rotation).add(position).toArray(),\n rotation:rotation.clone().multiply(target.rotation).normalize().toArray(),scale:target.pin.pose.scale,\n });\n visiting.delete(id);\n };\n for (const id of groups.keys()) visit(id);\n this.lastPins = pins; this.lastParents = parents; this.awake = active;\n return { pins: active ? pins.map(pin => ({...pin,pose:output.get(pin.id)!})) : pins, active };\n }\n}\n", "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", "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 { 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 { 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"],
|
|
4
|
+
"sourcesContent": ["import { Quaternion, Vector3 } from 'three';\nimport { DEFAULT_FUR_DEPTH, type PinPose, type PinRecord } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\nimport { DEFAULT_MOTION, type MotionSettings } from './motion-settings.js';\nimport { ikChain } from './pin-ik.js';\nimport { windAcceleration } from './wind.js';\n\n/** Disposable secondary motion. Never writes authored pins or history. */\nexport class PinWiggle {\n private springs = new Map<string, { position: Vector3; velocity: Vector3; target:Vector3 }>();\n private topology = '';\n private lastPins: readonly PinRecord[] | null = null;\n private lastParents: PinParents | null = null;\n private awake = false;\n private windTime = 0;\n reset() { this.springs.clear(); this.topology = ''; this.lastPins = null; this.lastParents = null; this.awake = false; this.windTime = 0; }\n\n step(pins: readonly PinRecord[], parents: PinParents, seconds: number, masses?:ReadonlyMap<string,number>, windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {\n if (windStrength <= 0 && !this.awake && pins === this.lastPins && parents === this.lastParents) return {pins,active:false};\n const topology = JSON.stringify(pins.map(p => [p.id,p.rest,p.rigidGroup,p.independent,p.guide,p.wiggle,p.fur,p.furDepth,p.motion,parents.get(p.id)]));\n if (topology !== this.topology) { this.reset(); this.topology = topology; }\n const groups = new Map<string, PinRecord[]>(), byId = new Map(pins.map(p => [p.id,p]));\n const key = (p: PinRecord) => p.rigidGroup ?? p.id;\n for (const pin of pins) { const group = groups.get(key(pin)) ?? []; group.push(pin); groups.set(key(pin),group); }\n const settings = new Map<string,Readonly<MotionSettings>>();\n const volumes=[...groups.values()].filter(group=>!group.every(p=>p.guide)).map(group=>Math.max(1e-9,masses?.get(group[0].id)??1)).sort((a,b)=>a-b);\n const typicalVolume=volumes[Math.floor(volumes.length/2)]??1;\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) {\n const chain=ikChain(pins,parents,pin.id,masses);\n for (const node of chain.length>1 ? chain.slice(1) : chain) if (!settings.has(key(node))) settings.set(key(node),pin.motion ?? DEFAULT_MOTION);\n }\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\n // Fur belongs to the outer shell: unlike Wiggle it must not make the\n // articulated core's ancestor chain into springs.\n for (const pin of pins.filter(p=>p.fur && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\n const output = new Map<string, PinPose>(), visiting = new Set<string>();\n let active = false;\n // Exact underdamped spring integration, stable across variable frame times.\n // Clamp background-tab gaps rather than simulating missed seconds.\n const dt = Math.min(Math.max(seconds,0),.05);\n this.windTime += dt;\n const visit = (id: string) => {\n const group = groups.get(id)!;\n if (output.has(group[0].id)) return;\n if (visiting.has(id)) { for (const pin of group) output.set(pin.id,pin.pose); return; }\n visiting.add(id);\n const parent = group.map(p => byId.get(parents.get(p.id) ?? '')).find(p => p && key(p) !== id);\n if (parent) visit(key(parent));\n const parentPose = parent ? output.get(parent.id)! : undefined;\n const inherited = parent && parentPose ? new Quaternion().fromArray(parentPose.rotation).multiply(new Quaternion().fromArray(parent.pose.rotation).invert()) : new Quaternion();\n const targets = group.map(pin => {\n const position = new Vector3().fromArray(pin.pose.position);\n if (!pin.ik && parent && parentPose) position.sub(new Vector3().fromArray(parent.pose.position)).applyQuaternion(inherited).add(new Vector3().fromArray(parentPose.position));\n return { pin, position, rotation: (pin.ik ? new Quaternion() : inherited.clone()).multiply(new Quaternion().fromArray(pin.pose.rotation)) };\n });\n const center = targets.reduce((sum,p) => sum.add(p.position),new Vector3()).divideScalar(group.length);\n let position = center, rotation = new Quaternion();\n const motion=settings.get(id);\n if (motion && !group.every(p=>p.guide) && !group.some(p=>p.ik)) {\n const ratio=Math.max(.125,Math.min(8,(masses?.get(group[0].id)??typicalVolume)/typicalVolume));\n const gain=motion.strength*Math.max(.25,Math.min(4,Math.pow(1/ratio,.5*motion.massInfluence)));\n const frequency=motion.frequency*2*Math.PI, damping=Math.max(.05,Math.min(1,motion.damping*Math.pow(ratio,.25*motion.massInfluence)));\n const decay = damping * frequency, oscillation = frequency * Math.sqrt(1-damping*damping);\n const e = Math.exp(-decay*dt), c = Math.cos(oscillation*dt), s = oscillation > 1e-8 ? Math.sin(oscillation*dt)/oscillation : dt;\n let spring = this.springs.get(id);\n if (!spring) { spring = { position:center.clone(),velocity:new Vector3(),target:center.clone() }; this.springs.set(id,spring); }\n spring.position.addScaledVector(center.clone().sub(spring.target),1-gain);spring.target.copy(center);\n if(motion.strength===0){spring.position.copy(center);spring.velocity.set(0,0,0);}\n else if (windStrength > 0) spring.velocity.addScaledVector(windAcceleration(this.windTime, windStrength,\n parentPose ? Math.max(center.distanceTo(new Vector3().fromArray(parentPose.position)), 1e-3) : 1, center.toArray()), motion.strength * dt);\n const offset = spring.position.clone().sub(center), velocity = spring.velocity.clone();\n spring.position.copy(offset).multiplyScalar(c).addScaledVector(velocity.clone().addScaledVector(offset,decay),s).multiplyScalar(e).add(center);\n spring.velocity.copy(velocity).multiplyScalar(c).sub(velocity.clone().multiplyScalar(decay).addScaledVector(offset,frequency*frequency).multiplyScalar(s)).multiplyScalar(e);\n const fur = group.find(p=>p.fur), furDepth=fur?.furDepth??DEFAULT_FUR_DEPTH;\n let radius = 1;\n if (parentPose) {\n const pivot = new Vector3().fromArray(parentPose.position), desired = center.clone().sub(pivot);\n radius = desired.length();\n const direction = spring.position.clone().sub(pivot);\n if (radius > 1e-8) {\n if (direction.lengthSq() < 1e-16) direction.copy(desired);\n const length=direction.length();direction.divideScalar(length);\n const coreRadius=radius*(1-furDepth),outerRadius=radius*(1+furDepth);\n const projected=fur?Math.max(coreRadius,Math.min(outerRadius,length)):radius;\n spring.position.copy(pivot).addScaledVector(direction,projected);\n if(!fur||length<coreRadius||length>outerRadius)spring.velocity.addScaledVector(direction,-spring.velocity.dot(direction));\n rotation.setFromUnitVectors(desired.normalize(),direction);\n } else { spring.position.copy(center); spring.velocity.set(0,0,0); }\n }\n if (fur) {\n const shell = Math.max(1e-4, radius) * furDepth;\n if (shell === 0) { spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity(); }\n const displacement = spring.position.clone().sub(center);\n if (displacement.length() > shell) {\n displacement.setLength(shell); spring.position.copy(center).add(displacement);\n const outward=displacement.normalize();spring.velocity.addScaledVector(outward,-Math.max(0,spring.velocity.dot(outward)));\n }\n if(parentPose&&radius>1e-8){\n const pivot=new Vector3().fromArray(parentPose.position),desired=center.clone().sub(pivot).normalize(),direction=spring.position.clone().sub(pivot).normalize();\n rotation.setFromUnitVectors(desired,direction);\n }\n }\n const epsilon = Math.max(radius,1e-3)*1e-5;\n if (spring.position.distanceToSquared(center) < epsilon*epsilon && spring.velocity.lengthSq() < epsilon*epsilon*frequency*frequency) {\n spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity();\n } else active = true;\n position = spring.position;\n }\n for (const target of targets) output.set(target.pin.id, {\n position:target.position.sub(center).applyQuaternion(rotation).add(position).toArray(),\n rotation:rotation.clone().multiply(target.rotation).normalize().toArray(),scale:target.pin.pose.scale,\n });\n visiting.delete(id);\n };\n for (const id of groups.keys()) visit(id);\n this.lastPins = pins; this.lastParents = parents; this.awake = active;\n return { pins: active ? pins.map(pin => ({...pin,pose:output.get(pin.id)!})) : pins, active };\n }\n}\n", "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", "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 { 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 { 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"],
|
|
5
5
|
"mappings": ";;;AAAA,SAAS,cAAAA,aAAY,WAAAC,gBAAe;;;ACU7B,IAAM,oBAAoB;;;ACT1B,IAAM,iBAA2C,EAAE,OAAO,KAAI,WAAW,MAAM,IAAE,KAAK,KAAK,SAAS,MAAK,eAAc,GAAE,UAAS,EAAE;;;ACD3I,SAA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