threedog 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +4 -4
  3. package/core/assets/Animator.js +66 -12
  4. package/core/assets/ik.js +144 -18
  5. package/core/assets/maskLayer.js +377 -0
  6. package/core/assets/rootMotion.js +148 -0
  7. package/core/audio/Audio.js +100 -4
  8. package/core/base/errorCodes.js +6 -369
  9. package/core/base/errorCodesModules.js +378 -0
  10. package/core/engine/Engine.js +8 -5
  11. package/core/engine/Loading.js +8 -4
  12. package/core/engine/copies.js +1 -1
  13. package/core/engine/headlessLoad.js +15 -4
  14. package/core/engine/lifecycle.js +1 -0
  15. package/core/engine/loop.js +23 -3
  16. package/core/engine/moduleSlots.js +3 -7
  17. package/core/engine/modules.js +30 -58
  18. package/core/engine/startup.js +3 -3
  19. package/core/input/Input.js +7 -3
  20. package/core/input/inputContext.js +3 -2
  21. package/core/input/inputSeat.js +1 -1
  22. package/core/inspect/DebugOverrides.js +1 -1
  23. package/core/inspect/Describe.js +7 -2
  24. package/core/inspect/describeRender.js +4 -1
  25. package/core/inspect/describeText.js +2 -2
  26. package/core/inspect/metadata.generated.js +380 -74
  27. package/core/inspect/pictureMenu.js +2 -0
  28. package/core/inspect/pictureWriters.js +4 -3
  29. package/core/ops/Ops.js +9 -3
  30. package/core/ops/actor.js +10 -0
  31. package/core/ops/control.js +17 -6
  32. package/core/ops/holds.js +1 -1
  33. package/core/ops/opsAtomic.js +6 -1
  34. package/core/ops/opsGuard.js +2 -2
  35. package/core/ops/owned.js +37 -11
  36. package/core/ops/sharedPoint.js +5 -1
  37. package/core/ops/stacks.js +30 -7
  38. package/core/saves/Saves.js +0 -2
  39. package/core/saves/saveApply.js +7 -7
  40. package/core/saves/session.js +6 -3
  41. package/core/saves/stateReplace.js +71 -41
  42. package/core/scene/Rays.js +74 -26
  43. package/core/scene/canvasBox.js +9 -0
  44. package/core/scene/gameLights.js +19 -11
  45. package/core/scene/sceneDelta.js +8 -4
  46. package/core/scene/sceneMethods.js +2 -1
  47. package/core/stream/chunkStream.js +21 -0
  48. package/core/stream/dirtyWatch.js +37 -0
  49. package/core/time/skip.js +9 -6
  50. package/core/time/time.js +72 -18
  51. package/docs/AI.md +22 -21
  52. package/docs/API.md +5 -4
  53. package/docs/CODEMAP.md +16 -10
  54. package/docs/COMMANDS.md +5 -5
  55. package/docs/CONVENTIONS.md +9 -25
  56. package/docs/api/ambience.md +1 -0
  57. package/docs/api/assets.md +10 -3
  58. package/docs/api/audio.md +5 -3
  59. package/docs/api/decals.md +16 -0
  60. package/docs/api/engine.md +1 -0
  61. package/docs/api/tools.md +3 -1
  62. package/docs/api/water.md +3 -0
  63. package/docs/recipes/09-materials-lights-models.md +15 -1
  64. package/docs/recipes/13-animation.md +51 -10
  65. package/docs/recipes/16-dev-bridge.md +4 -4
  66. package/docs/recipes/31-audio.md +15 -9
  67. package/docs/recipes/34-environment-lighting.md +11 -1
  68. package/docs/recipes/44-water-weather-hooks.md +1 -0
  69. package/examples/action/.threedog/content-index.json +1 -0
  70. package/examples/perf-island/.threedog/content-index.json +1 -0
  71. package/examples/plain-picture/.threedog/content-index.json +1 -0
  72. package/examples/rc2d/.threedog/content-index.json +1 -0
  73. package/examples/styletest/.threedog/content-index.json +1 -0
  74. package/examples/techniques/outlines-and-rim/main.js +1 -1
  75. package/examples/techniques/procedural-surface/main.js +1 -1
  76. package/examples/techniques/stylized-shading/main.js +1 -1
  77. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  78. package/examples/world/.threedog/content-index.json +1 -0
  79. package/index.d.ts +6 -2
  80. package/index.js +3 -2
  81. package/llms.txt +11 -10
  82. package/modules/ambience/Ambience.js +97 -15
  83. package/modules/camera/common.js +18 -12
  84. package/modules/characters/Character.js +30 -3
  85. package/modules/characters/NPC.js +2 -5
  86. package/modules/characters/astar.js +45 -14
  87. package/modules/characters/movers/rapier.js +53 -41
  88. package/modules/characters/movers/simple.js +37 -24
  89. package/modules/characters/npcView.js +2 -2
  90. package/modules/characters/pathAsync.js +3 -3
  91. package/modules/collision/contract.js +2 -2
  92. package/modules/content/index.js +3 -0
  93. package/modules/content/models.js +11 -4
  94. package/modules/content/templates.js +11 -11
  95. package/modules/debug/DebugPanel.js +1 -0
  96. package/modules/decals/Decals.js +393 -0
  97. package/modules/decals/index.js +1 -0
  98. package/modules/gameplay/Container.js +2 -0
  99. package/modules/gameplay/Containers.js +17 -3
  100. package/modules/gameplay/Dialogue.js +1 -1
  101. package/modules/gameplay/Interactions.js +7 -6
  102. package/modules/gameplay/Inventory.js +5 -1
  103. package/modules/gameplay/Quests.js +4 -3
  104. package/modules/gameplay/inventoryOps.js +2 -2
  105. package/modules/gameplay/pickups.js +32 -12
  106. package/modules/gameplay/questSave.js +2 -2
  107. package/modules/grid/index.js +8 -2
  108. package/modules/hud/index.js +1 -1
  109. package/modules/level/heightfield.js +1 -0
  110. package/modules/level/index.js +3 -2
  111. package/modules/level/nodes.js +2 -1
  112. package/modules/lights/index.js +27 -4
  113. package/modules/lights/slots.js +33 -16
  114. package/modules/nav/contract.js +4 -4
  115. package/modules/nav/index.js +6 -2
  116. package/modules/net/Client.js +24 -11
  117. package/modules/net/Host.js +73 -20
  118. package/modules/net/index.js +33 -21
  119. package/modules/net/sync.js +38 -8
  120. package/modules/net/transports.js +7 -3
  121. package/modules/particles/Particles.js +11 -4
  122. package/modules/particles/contract.js +6 -6
  123. package/modules/particles/effect.js +0 -1
  124. package/modules/rigid/RigidBodies.js +69 -57
  125. package/modules/rigid/Vehicles.js +8 -7
  126. package/modules/rigid/ragdoll.js +4 -6
  127. package/modules/rigid/rapierCompat.js +90 -0
  128. package/modules/rigid/sync.js +2 -5
  129. package/modules/settings/Settings.js +10 -4
  130. package/modules/sky/Sky.js +10 -2
  131. package/modules/sky/environment.js +29 -13
  132. package/modules/sky/frame.js +2 -2
  133. package/modules/sky/shader.js +5 -2
  134. package/modules/sky/skyModule.js +2 -2
  135. package/modules/swarm/Swarm.js +3 -2
  136. package/modules/swarm/grid.js +12 -7
  137. package/modules/terrain/ChunkManager.js +16 -26
  138. package/modules/triggers/index.js +5 -6
  139. package/modules/vegetation/draw.js +62 -26
  140. package/modules/vegetation/groundChunks.js +8 -22
  141. package/modules/water/Water.js +152 -24
  142. package/modules/water/surface.js +43 -20
  143. package/modules/weather/weatherDraw.js +4 -1
  144. package/modules/world/World.js +21 -2
  145. package/modules/world/index.js +5 -0
  146. package/modules/world/persist.js +1 -0
  147. package/modules/world/records.js +3 -1
  148. package/modules/world/sim.js +3 -2
  149. package/modules/world/simFar.js +4 -2
  150. package/modules/world/state.js +7 -1
  151. package/package.json +2 -2
  152. package/presets.js +30 -0
  153. package/render/PostFX.js +24 -17
  154. package/render/backend.js +72 -31
  155. package/render/cascades.js +25 -14
  156. package/render/cascades.tsl.js +32 -21
  157. package/render/fogLook.js +2 -1
  158. package/render/fx/detail.tsl.js +3 -0
  159. package/render/fx/library.tsl.js +1 -1
  160. package/render/fx/particles.tsl.js +4 -18
  161. package/render/fx/pcss.tsl.js +2 -2
  162. package/render/fx/postWebGPU.tsl.js +47 -25
  163. package/render/fx/sky.tsl.js +6 -18
  164. package/render/fx/uniforms.tsl.js +16 -0
  165. package/render/fx/water.tsl.js +24 -5
  166. package/render/fxNumbers.js +2 -0
  167. package/render/impostor.tsl.js +10 -6
  168. package/render/lights.js +6 -6
  169. package/render/occlusion.js +17 -6
  170. package/render/patches.js +40 -28
  171. package/render/postWebGL.js +6 -4
  172. package/render/reflectionProbes.js +302 -0
  173. package/render/shaderErrors.js +18 -8
  174. package/render/shadowCache.tsl.js +10 -5
  175. package/render/shadows.js +70 -49
  176. package/render/threeCompat.js +166 -0
  177. package/types/core.d.ts +33 -3
  178. package/types/gameplay.d.ts +80 -0
  179. package/types/generated/core/audio/Audio.d.ts +18 -1
  180. package/types/generated/core/ops/Ops.d.ts +2 -1
  181. package/types/generated/core/ops/control.d.ts +7 -3
  182. package/types/generated/core/saves/session.d.ts +4 -1
  183. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  184. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  185. package/types/generated/modules/grid/index.d.ts +27 -3
  186. package/types/generated/modules/net/index.d.ts +8 -3
  187. package/types/generated/modules/sky/Sky.d.ts +1 -0
  188. package/types/generated/modules/water/Water.d.ts +15 -0
  189. package/types/generated/modules/world/index.d.ts +5 -0
  190. package/types/generated/render/patches.d.ts +5 -0
  191. package/types/physics.d.ts +66 -9
  192. package/types/tsl.d.ts +2 -0
  193. package/types/world.d.ts +2 -0
  194. package/ui/Parts.js +3 -2
  195. package/docs/MIGRATING-0.7.md +0 -39
  196. package/docs/MIGRATING-0.8.md +0 -171
  197. package/modules/rigid/refresh.js +0 -10
@@ -0,0 +1,377 @@
1
+ // Bone-mask animation layers (anim.addLayer) and 2D directional blend spaces (blend2d on AnimatorState).
2
+ // Why a separate mixer per masked layer: three's AnimationMixer blends competing tracks on one mixer by weight sum, which dilutes lower-body
3
+ // locomotion when a full-body attack clip plays. Filtering a layer's clips down to tracks targeting the masked bones and slerping those bones
4
+ // over the base mixer's pose keeps the unmasked skeleton 100% on base locomotion and crossfades the masked subtree cleanly in and out.
5
+ import * as THREE from 'three';
6
+ import { readParams, keysSchema } from '../base/params.js';
7
+ import { codedError } from '../base/errorHints.js';
8
+ import { warnMissing } from '../base/validate.js';
9
+
10
+ const LAYER_KEYS = ['name', 'mask', 'states', 'transitions', 'weight', 'fade'];
11
+ const SET_KEYS = ['weight', 'fade'];
12
+ const GO_KEYS = ['fade'];
13
+
14
+ const UPPER_ROOT = /spine|chest|torso|upper.?body|abdomen|bust/i;
15
+ const ARM_NECK = /clavicle|collar|shoulder|arm|hand|finger|thumb|wrist|neck|head|jaw|eye/i;
16
+ const LOWER_ROOT = /thigh|up.?leg|upper.?leg|leg|hip.?[lr]|^[lr].?hip/i;
17
+ const PELVIS_SKIP = /hips|pelvis|root|armature/i;
18
+
19
+ /** Parse the target node name out of a three.js track name ('Armature|Spine1.quaternion' -> 'Spine1') */
20
+ function trackBoneName(trackName) {
21
+ const dot = trackName.lastIndexOf('.');
22
+ const path = dot >= 0 ? trackName.slice(0, dot) : trackName;
23
+ const slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('|'));
24
+ return slash >= 0 ? path.slice(slash + 1) : path;
25
+ }
26
+
27
+ function addSubtree(node, set, excluded) {
28
+ if (!node || excluded.has(node)) return;
29
+ if (node.isBone) set.add(node);
30
+ for (const c of node.children) addSubtree(c, set, excluded);
31
+ }
32
+
33
+ function findBone(root, name) {
34
+ return root.getObjectByName(name) ?? root.getObjectByName(THREE.PropertyBinding.sanitizeNodeName(name)) ?? null;
35
+ }
36
+
37
+ /** Resolve mask ('upper' | 'lower' | bone name(s) | { include, exclude, subtree }) into an ordered array of Bone objects */
38
+ function resolveBoneMask(root, mask, where = 'anim.addLayer()') {
39
+ const allBones = [];
40
+ root.traverse(o => { if (o.isBone) allBones.push(o); });
41
+ if (!allBones.length) throw codedError('engine-misuse', `${where}: model has no Bone nodes to mask`);
42
+
43
+ const set = new Set(), excluded = new Set();
44
+ if (mask === 'upper') {
45
+ // Exclude leg subtrees first so a spine parented strangely never pulls legs in
46
+ for (const b of allBones) if (LOWER_ROOT.test(b.name) && !UPPER_ROOT.test(b.name)) addSubtree(b, excluded, new Set());
47
+ for (const b of allBones) {
48
+ if (excluded.has(b) || PELVIS_SKIP.test(b.name)) continue;
49
+ if (UPPER_ROOT.test(b.name) || ARM_NECK.test(b.name)) addSubtree(b, set, excluded);
50
+ }
51
+ } else if (mask === 'lower') {
52
+ for (const b of allBones) if (LOWER_ROOT.test(b.name) && !PELVIS_SKIP.test(b.name)) addSubtree(b, set, excluded);
53
+ } else {
54
+ const spec = typeof mask === 'string' || Array.isArray(mask) ? { include: mask, subtree: true } : mask;
55
+ if (!spec || typeof spec !== 'object' || !spec.include) {
56
+ throw codedError('engine-misuse', `${where}: mask must be 'upper', 'lower', a bone name / array of names, or { include, exclude?, subtree? }`);
57
+ }
58
+ const inc = [spec.include].flat().filter(Boolean);
59
+ const exc = [spec.exclude ?? []].flat().filter(Boolean);
60
+ const sub = spec.subtree !== false;
61
+ for (const n of exc) {
62
+ const b = findBone(root, n);
63
+ if (b) { if (sub) addSubtree(b, excluded, new Set()); else excluded.add(b); }
64
+ }
65
+ for (const n of inc) {
66
+ const b = findBone(root, n);
67
+ if (!b) throw codedError('engine-misuse', `${where}: bone '${n}' not found in skeleton (${allBones.map(x => x.name).join(', ')})`);
68
+ if (sub) addSubtree(b, set, excluded);
69
+ else if (!excluded.has(b)) set.add(b);
70
+ }
71
+ }
72
+ const list = allBones.filter(b => set.has(b));
73
+ if (!list.length) {
74
+ throw codedError('engine-misuse', `${where}: mask ${JSON.stringify(mask)} matched 0 bones (skeleton bones: ${allBones.map(x => x.name).join(', ')})`);
75
+ }
76
+ return list;
77
+ }
78
+
79
+ /**
80
+ * 2D Gradient Band Interpolation (Johansen 2009, polar-aware for directional strafe rings).
81
+ * Writes normalized weights into a cached Float64Array on `def` (zero per-frame allocation).
82
+ */
83
+ export function computeBlend2D(def, params) {
84
+ const pts = def.blend2d, n = pts.length;
85
+ const pNames = def.params ?? ['moveX', 'moveZ'];
86
+ const qx = params[pNames[0]] ?? 0, qz = params[pNames[1]] ?? 0;
87
+ const out = (def._b2w && def._b2w.length === n) ? def._b2w : (def._b2w = new Float64Array(n));
88
+ if (n === 0) return out;
89
+ if (n === 1) { out[0] = 1; return out; }
90
+
91
+ let sum = 0;
92
+ for (let i = 0; i < n; i++) {
93
+ const [ix, iz] = pts[i].at;
94
+ const dxQ = qx - ix, dzQ = qz - iz;
95
+ if (dxQ * dxQ + dzQ * dzQ < 1e-10) {
96
+ out.fill(0); out[i] = 1;
97
+ return out;
98
+ }
99
+ let hi = 1;
100
+ const iLen = Math.hypot(ix, iz);
101
+ for (let j = 0; j < n; j++) {
102
+ if (j === i) continue;
103
+ const [jx, jz] = pts[j].at;
104
+ const jLen = Math.hypot(jx, jz);
105
+ let v;
106
+ // Polar directional band when both samples sit off the origin: prevents opposite strafe leakage and keeps circular speed rings smooth
107
+ if (iLen > 1e-4 && jLen > 1e-4) {
108
+ const avgR = (iLen + jLen) * 0.5, qLen = Math.hypot(qx, qz);
109
+ const drIJ = (jLen - iLen) / avgR, drIQ = (qLen - iLen) / avgR;
110
+ const angIJ = Math.atan2(ix * jz - iz * jx, ix * jx + iz * jz);
111
+ const angIQ = qLen > 1e-5 ? Math.atan2(ix * qz - iz * qx, ix * qx + iz * qz) : 0;
112
+ const denom = drIJ * drIJ + angIJ * angIJ;
113
+ v = denom > 1e-8 ? 1 - (drIQ * drIJ + angIQ * angIJ) / denom : 1;
114
+ } else {
115
+ const gx = jx - ix, gz = jz - iz;
116
+ const denom = gx * gx + gz * gz;
117
+ v = denom > 1e-8 ? 1 - (dxQ * gx + dzQ * gz) / denom : 1;
118
+ }
119
+ if (v <= 0) { hi = 0; break; }
120
+ if (v < hi) hi = v;
121
+ }
122
+ out[i] = hi;
123
+ sum += hi;
124
+ }
125
+ if (sum > 1e-8) { for (let i = 0; i < n; i++) out[i] /= sum; }
126
+ else out[0] = 1;
127
+ return out;
128
+ }
129
+
130
+ /** Create a masked animation layer attached to `anim` */
131
+ export function createMaskLayer(anim, findClip, opts = {}) {
132
+ const o = readParams('anim.addLayer()', keysSchema(LAYER_KEYS), opts);
133
+ anim._layerSeq = (anim._layerSeq ?? 0) + 1;
134
+ const name = o.name ?? (typeof o.mask === 'string' ? o.mask : `layer#${anim._layerSeq}`);
135
+ const bones = resolveBoneMask(anim.root, o.mask ?? 'upper', `anim.addLayer('${name}')`);
136
+ const boneNames = new Set(bones.map(b => b.name));
137
+ for (const b of bones) boneNames.add(THREE.PropertyBinding.sanitizeNodeName(b.name));
138
+
139
+ const baseQ = bones.map(() => new THREE.Quaternion());
140
+ const baseP = bones.map(() => new THREE.Vector3());
141
+ const mixer = new THREE.AnimationMixer(anim.root);
142
+ const filteredClips = new Map();
143
+ const actions = new Map();
144
+
145
+ const statesOf = st => o.states?.[st] ?? anim.states[st];
146
+ const fadeFor = (from, to, f) => {
147
+ const tr = o.transitions ?? anim.transitions;
148
+ return f ?? tr[`${from}>${to}`] ?? tr[`*>${to}`] ?? tr[`${from}>*`] ?? o.fade ?? anim.fade;
149
+ };
150
+
151
+ function maskedAction(clipName) {
152
+ if (actions.has(clipName)) return actions.get(clipName);
153
+ const src = findClip(anim.clips, clipName);
154
+ if (!src) return null;
155
+ let sub = filteredClips.get(src);
156
+ if (!sub) {
157
+ const tracks = src.tracks.filter(t => boneNames.has(trackBoneName(t.name)));
158
+ sub = new THREE.AnimationClip(`${src.name}__mask_${name}`, src.duration, tracks);
159
+ filteredClips.set(src, sub);
160
+ }
161
+ const act = mixer.clipAction(sub);
162
+ actions.set(clipName, act);
163
+ return act;
164
+ }
165
+
166
+ const st = {
167
+ name, bones, mixer,
168
+ weight: o.weight !== undefined ? Math.max(0, Math.min(1, o.weight)) : 1,
169
+ fade: o.fade ?? anim.fade,
170
+ state: null,
171
+ layers: [],
172
+ returnTo: null,
173
+ driven: null,
174
+ t: 0,
175
+ dead: false,
176
+ };
177
+
178
+ const heldElsewhere = (a, cur) => st.layers.some(l => l !== cur && !(l.w === 0 && l.target === 0) && l.actions.some(x => x.a === a));
179
+
180
+ function syncWeights() {
181
+ let sum = 0;
182
+ for (const l of st.layers) { sum += l.w; for (const x of l.actions) x.a.setEffectiveWeight(0); }
183
+ if (sum <= 0) return;
184
+ for (const l of st.layers) {
185
+ const lw = l.w / sum;
186
+ const bw = l.def.blend2d ? computeBlend2D(l.def, anim.params) : l.def.blend ? anim._blend(l.def) : [1];
187
+ let dur = 0, moveShare = 0;
188
+ for (let i = 0; i < l.actions.length; i++) {
189
+ const pt = l.def.blend2d?.[i];
190
+ if (pt && pt.at[0] === 0 && pt.at[1] === 0) continue;
191
+ dur += bw[i] * l.actions[i].a.getClip().duration;
192
+ moveShare += bw[i];
193
+ }
194
+ const meanDur = moveShare > 1e-4 ? dur / moveShare : 0;
195
+ for (let i = 0; i < l.actions.length; i++) {
196
+ const { a } = l.actions[i];
197
+ a.setEffectiveWeight(a.weight + lw * bw[i]);
198
+ const pt = l.def.blend2d?.[i];
199
+ const isIdleCenter = pt && pt.at[0] === 0 && pt.at[1] === 0;
200
+ if ((l.def.blend || l.def.blend2d) && l.def.sync !== false && meanDur > 0 && !isIdleCenter) {
201
+ a.setEffectiveTimeScale(a.getClip().duration / meanDur);
202
+ }
203
+ }
204
+ }
205
+ }
206
+
207
+ function enter(stateName, fadeOverride) {
208
+ if (!anim.hasClips) return null;
209
+ if (stateName == null) {
210
+ const f = fadeOverride ?? st.fade, rate = f > 0 ? 1 / f : 1e9;
211
+ for (const l of st.layers) { l.target = 0; l.rate = rate; }
212
+ st.state = null; st.returnTo = null;
213
+ return null;
214
+ }
215
+ const def = statesOf(stateName);
216
+ if (!def) {
217
+ const known = [...new Set([...Object.keys(anim.states), ...Object.keys(o.states ?? {})])];
218
+ warnMissing('animState', stateName, known);
219
+ return null;
220
+ }
221
+ const clipList = def.blend2d ? def.blend2d.map(b => b.clip) : def.blend ? def.blend.map(b => b.clip) : [def.clip];
222
+ const acts = clipList.map(clip => ({ a: maskedAction(clip), clip }));
223
+ if (acts.some(x => !x.a)) return null;
224
+ const f = fadeFor(st.state, stateName, fadeOverride), rate = f > 0 ? 1 / f : 1e9;
225
+ for (const l of st.layers) { l.target = 0; l.rate = rate; }
226
+ let layer = st.layers.find(l => l.name === stateName);
227
+ if (!layer) {
228
+ layer = { name: stateName, def, w: f === 0 ? 1 : 0, actions: acts };
229
+ st.layers.push(layer);
230
+ for (const { a } of acts) {
231
+ if (!heldElsewhere(a, layer)) a.reset().setEffectiveTimeScale(1).setEffectiveWeight(0);
232
+ if (def.loop === false) { a.setLoop(THREE.LoopOnce, 1); a.clampWhenFinished = true; } else a.setLoop(THREE.LoopRepeat, Infinity);
233
+ a.play();
234
+ }
235
+ } else if (def.loop === false) {
236
+ for (const { a } of acts) a.reset().play();
237
+ }
238
+ Object.assign(layer, { target: 1, rate, done: false, once: false, driven: false });
239
+ for (const { a } of acts) a.paused = false;
240
+ st.state = stateName;
241
+ syncWeights();
242
+ return acts[0].a;
243
+ }
244
+
245
+ mixer.addEventListener('finished', ev => {
246
+ const layer = st.layers.find(l => l.name === st.state);
247
+ if (!layer || layer.driven || !layer.actions.some(x => x.a === ev.action)) return;
248
+ layer.done = true;
249
+ anim.engine.events.emit('anim:end', { root: anim.root, state: layer.name, layer: st.name });
250
+ const next = layer.def.then ?? st.returnTo ?? null;
251
+ st.returnTo = null;
252
+ enter(next);
253
+ });
254
+
255
+ st.saved = false;
256
+ st.restore = () => {
257
+ if (!st.saved) return;
258
+ for (let i = 0; i < bones.length; i++) {
259
+ bones[i].quaternion.copy(baseQ[i]);
260
+ bones[i].position.copy(baseP[i]);
261
+ }
262
+ st.saved = false;
263
+ };
264
+ st.step = dt => {
265
+ if (!st.layers.length) return;
266
+ let j = 0, activeSum = 0;
267
+ for (const l of st.layers) {
268
+ if (l.w < l.target) l.w = Math.min(l.target, l.w + dt * l.rate);
269
+ else if (l.w > l.target) l.w = Math.max(l.target, l.w - dt * l.rate);
270
+ if (l.w === 0 && l.target === 0) {
271
+ for (const { a } of l.actions) if (!heldElsewhere(a, l)) a.setEffectiveWeight(0).stop();
272
+ continue;
273
+ }
274
+ activeSum += l.w;
275
+ st.layers[j++] = l;
276
+ }
277
+ st.layers.length = j;
278
+ const blendAlpha = Math.min(1, activeSum) * st.weight;
279
+ if (blendAlpha <= 0) return;
280
+ for (let i = 0; i < bones.length; i++) {
281
+ baseQ[i].copy(bones[i].quaternion);
282
+ baseP[i].copy(bones[i].position);
283
+ }
284
+ st.saved = true;
285
+ syncWeights();
286
+ mixer.update(dt);
287
+ if (blendAlpha < 1) {
288
+ for (let i = 0; i < bones.length; i++) {
289
+ bones[i].quaternion.slerpQuaternions(baseQ[i], bones[i].quaternion, blendAlpha);
290
+ bones[i].position.lerpVectors(baseP[i], bones[i].position, blendAlpha);
291
+ }
292
+ }
293
+ };
294
+
295
+ const handle = {
296
+ get name() { return st.name; },
297
+ get state() { return st.state; },
298
+ go(stateName, goOpts) {
299
+ if (st.dead) return null;
300
+ const fade = goOpts === undefined ? undefined : readParams('layer.go()', keysSchema(GO_KEYS), goOpts).fade;
301
+ if (st.driven) return st.layers.find(l => l.name === st.driven)?.actions[0].a ?? null;
302
+ if (stateName == null) return enter(null, fade);
303
+ const cur = st.layers.find(l => l.name === st.state && l.target === 1);
304
+ if (cur && stateName === st.state && !cur.done) return cur.actions[0].a;
305
+ if ((cur?.def.lock || cur?.once) && !cur.done) return cur.actions[0].a;
306
+ return enter(stateName, fade);
307
+ },
308
+ action(actName, actOpts) {
309
+ if (st.dead) return null;
310
+ const prev = st.state;
311
+ let def = statesOf(actName);
312
+ if (!def) {
313
+ if (!findClip(anim.clips, actName)) return null;
314
+ (o.states ??= {})[actName] = def = { clip: actName, loop: false, lock: true };
315
+ }
316
+ const a = handle.go(actName, actOpts);
317
+ if (a && st.state === actName) {
318
+ if (def.loop === false) st.layers.find(l => l.name === actName).once = true;
319
+ if (!def.then && prev !== actName) st.returnTo = prev;
320
+ }
321
+ return a;
322
+ },
323
+ sync(stateName, t = 0) {
324
+ if (st.dead) return null;
325
+ if (stateName == null) {
326
+ const l = st.driven && st.layers.find(x => x.name === st.driven);
327
+ if (l) { l.driven = false; l.done = true; for (const { a } of l.actions) a.paused = false; }
328
+ st.driven = null;
329
+ enter(null, 0);
330
+ return null;
331
+ }
332
+ if (st.driven !== stateName || !st.layers.some(l => l.name === stateName && l.target === 1)) {
333
+ st.driven = null;
334
+ if (!enter(stateName, 0)) return null;
335
+ const l = st.layers.find(x => x.name === stateName);
336
+ l.driven = true; st.driven = stateName;
337
+ for (const { a } of l.actions) { a.paused = true; a.enabled = true; }
338
+ }
339
+ st.t = t;
340
+ const def = statesOf(stateName), l = st.layers.find(x => x.name === stateName);
341
+ for (const { a } of l.actions) a.time = anim._clipTime(def, a.getClip().duration, t);
342
+ return l.actions[0].a;
343
+ },
344
+ set(patch = {}) {
345
+ if (st.dead) return handle;
346
+ const s = readParams('layer.set()', keysSchema(SET_KEYS), patch);
347
+ if (s.weight !== undefined) st.weight = Math.max(0, Math.min(1, s.weight));
348
+ if (s.fade !== undefined && s.fade >= 0) st.fade = s.fade;
349
+ return handle;
350
+ },
351
+ describe() {
352
+ const activeSum = st.layers.reduce((s, l) => s + l.w, 0);
353
+ return {
354
+ name: st.name, state: st.state,
355
+ weight: Math.round(Math.min(1, activeSum) * st.weight * 1000) / 1000,
356
+ bones: bones.length,
357
+ };
358
+ },
359
+ remove() {
360
+ if (st.dead) return;
361
+ st.dead = true;
362
+ const idx = anim._maskLayers.indexOf(st);
363
+ if (idx >= 0) anim._maskLayers.splice(idx, 1);
364
+ if (!anim._held) st.restore();
365
+ mixer.stopAllAction();
366
+ mixer.uncacheRoot(anim.root);
367
+ actions.clear();
368
+ filteredClips.clear();
369
+ st.layers.length = 0;
370
+ if (!anim._maskLayers.length && !anim._ik.length && !anim.hasClips) anim._dropHook();
371
+ },
372
+ };
373
+ st.handle = handle;
374
+ anim._maskLayers.push(st);
375
+ anim._needHook();
376
+ return handle;
377
+ }
@@ -0,0 +1,148 @@
1
+ // Deterministic skeletal Root Motion: analytical sampling of VectorKeyframeTrack position keyframes (independent of mixer.update / render frames)
2
+ // and per-frame pinning of the root / hips bone back to its initial bind position so the visual mesh never drifts out of the collision capsule.
3
+ import * as THREE from 'three';
4
+
5
+ const ROOT_BONE = /(?:^|[:._|/])(root|hips|pelvis)$/i;
6
+ const _p0 = { x: 0, y: 0, z: 0 }, _p1 = { x: 0, y: 0, z: 0 }, _acc = { x: 0, y: 0, z: 0 };
7
+
8
+ function normalize(raw) {
9
+ if (!raw) return null;
10
+ if (raw === true) return { bone: null, y: false };
11
+ if (typeof raw === 'string') return { bone: raw, y: false };
12
+ return typeof raw === 'object' ? { bone: typeof raw.bone === 'string' ? raw.bone : null, y: !!raw.y } : null;
13
+ }
14
+
15
+ function resolveBone(root, boneName) {
16
+ if (boneName) return root.getObjectByName(boneName) ?? root.getObjectByName(THREE.PropertyBinding.sanitizeNodeName(boneName)) ?? null;
17
+ let named = null, firstRoot = null;
18
+ root.traverse(o => { if (o.isBone) { if (!named && ROOT_BONE.test(o.name)) named = o; if (!firstRoot && !o.parent?.isBone) firstRoot = o; } });
19
+ return named ?? firstRoot ?? null;
20
+ }
21
+
22
+ const ensureStore = anim => anim._rm ?? (anim._rm = { bones: new Map(), tracks: new WeakMap() });
23
+
24
+ function boneEntry(anim, boneName) {
25
+ const store = ensureStore(anim), key = boneName ?? '';
26
+ if (store.bones.has(key)) return store.bones.get(key);
27
+ const bone = resolveBone(anim.root, boneName), entry = bone ? { bone, bind: bone.position.clone() } : null;
28
+ store.bones.set(key, entry);
29
+ return entry;
30
+ }
31
+
32
+ function findTrack(anim, clip, boneName) {
33
+ const store = ensureStore(anim), key = boneName ?? '';
34
+ let byKey = store.tracks.get(clip);
35
+ if (!byKey) store.tracks.set(clip, byKey = new Map());
36
+ if (byKey.has(key)) return byKey.get(key);
37
+ const posTracks = clip.tracks.filter(tr => tr.name.endsWith('.position') && tr.getValueSize() === 3);
38
+ const want = boneName ?? boneEntry(anim, null)?.bone.name ?? null, wantSan = want ? THREE.PropertyBinding.sanitizeNodeName(want) : null;
39
+ let hit = want ? (posTracks.find(tr => { const n = THREE.PropertyBinding.parseTrackName(tr.name).nodeName; return n === want || THREE.PropertyBinding.sanitizeNodeName(n) === wantSan; }) ?? null) : null;
40
+ if (!hit && !boneName) hit = posTracks.find(tr => ROOT_BONE.test(THREE.PropertyBinding.parseTrackName(tr.name).nodeName)) ?? posTracks[0] ?? null;
41
+ byKey.set(key, hit);
42
+ return hit;
43
+ }
44
+
45
+ function sampleTrack(track, t, out) {
46
+ const times = track.times, vals = track.values, n = times.length;
47
+ if (!n) { out.x = out.y = out.z = 0; return out; }
48
+ const stride = vals.length / n, off = stride === 9 ? 3 : 0;
49
+ if (n === 1 || t <= times[0]) { out.x = vals[off]; out.y = vals[off + 1]; out.z = vals[off + 2]; return out; }
50
+ if (t >= times[n - 1]) { const b = (n - 1) * stride + off; out.x = vals[b]; out.y = vals[b + 1]; out.z = vals[b + 2]; return out; }
51
+ let lo = 0, hi = n - 1;
52
+ while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (times[mid] <= t) lo = mid; else hi = mid; }
53
+ const span = times[hi] - times[lo], a = span > 0 ? (t - times[lo]) / span : 0, b0 = lo * stride + off, b1 = hi * stride + off;
54
+ if (track.getInterpolation?.() === THREE.InterpolateDiscrete) {
55
+ out.x = vals[b0]; out.y = vals[b0 + 1]; out.z = vals[b0 + 2];
56
+ } else if (stride === 9) {
57
+ const a2 = a * a, a3 = a2 * a, h00 = 2 * a3 - 3 * a2 + 1, h10 = a3 - 2 * a2 + a, h01 = -2 * a3 + 3 * a2, h11 = a3 - a2;
58
+ const m0 = lo * 9 + 6, m1 = hi * 9;
59
+ out.x = h00 * vals[b0] + h10 * span * vals[m0] + h01 * vals[b1] + h11 * span * vals[m1];
60
+ out.y = h00 * vals[b0 + 1] + h10 * span * vals[m0 + 1] + h01 * vals[b1 + 1] + h11 * span * vals[m1 + 1];
61
+ out.z = h00 * vals[b0 + 2] + h10 * span * vals[m0 + 2] + h01 * vals[b1 + 2] + h11 * span * vals[m1 + 2];
62
+ } else {
63
+ out.x = vals[b0] + (vals[b1] - vals[b0]) * a; out.y = vals[b0 + 1] + (vals[b1 + 1] - vals[b0 + 1]) * a; out.z = vals[b0 + 2] + (vals[b1 + 2] - vals[b0 + 2]) * a;
64
+ }
65
+ return out;
66
+ }
67
+
68
+ function rawClipTime(def, dur, t) {
69
+ const k = def.timing;
70
+ if (typeof k === 'number') return k > 0 ? (t / k) * dur : 0;
71
+ if (Array.isArray(k) && k.length) {
72
+ if (t <= k[0][0]) return k[0][1];
73
+ for (let i = 1; i < k.length; i++) if (t < k[i][0]) { const [t0, c0] = k[i - 1], [t1, c1] = k[i]; return c0 + (c1 - c0) * (t - t0) / (t1 - t0); }
74
+ return k[k.length - 1][1];
75
+ }
76
+ return t;
77
+ }
78
+
79
+ function clipDelta(clip, def, track, fromT, toT, out) {
80
+ out.x = out.y = out.z = 0;
81
+ const dur = clip?.duration ?? 0;
82
+ if (!(dur > 0) || !track) return out;
83
+ const c0 = rawClipTime(def, dur, fromT), c1 = rawClipTime(def, dur, toT);
84
+ if (def.loop === false) {
85
+ sampleTrack(track, Math.min(Math.max(c0, 0), dur), _p0);
86
+ sampleTrack(track, Math.min(Math.max(c1, 0), dur), _p1);
87
+ out.x = _p1.x - _p0.x; out.y = _p1.y - _p0.y; out.z = _p1.z - _p0.z;
88
+ return out;
89
+ }
90
+ const k0 = Math.floor(c0 / dur), k1 = Math.floor(c1 / dur), loops = k1 - k0;
91
+ sampleTrack(track, c0 - k0 * dur, _p0); sampleTrack(track, c1 - k1 * dur, _p1);
92
+ out.x = _p1.x - _p0.x; out.y = _p1.y - _p0.y; out.z = _p1.z - _p0.z;
93
+ if (loops !== 0) {
94
+ sampleTrack(track, 0, _p0); sampleTrack(track, dur, _p1);
95
+ out.x += loops * (_p1.x - _p0.x); out.y += loops * (_p1.y - _p0.y); out.z += loops * (_p1.z - _p0.z);
96
+ }
97
+ return out;
98
+ }
99
+
100
+ /** @internal Capture initial bind positions of root-motion bones before any mixer.update runs */
101
+ export function initRootMotion(anim) {
102
+ let any = false;
103
+ const g = normalize(anim.rootMotion);
104
+ if (g) { any = true; boneEntry(anim, g.bone); }
105
+ for (const def of Object.values(anim.states)) { const s = normalize(def?.rootMotion); if (s) { any = true; boneEntry(anim, s.bone); } }
106
+ if (!any) anim._rm = null;
107
+ }
108
+
109
+ /** @internal Pin enabled root-motion bones back to their initial local X/Z (and Y when y: true) after mixer.update */
110
+ export function pinRootBone(anim) {
111
+ for (let i = 0; i < anim._layers.length; i++) {
112
+ const l = anim._layers[i];
113
+ if (!(l.w > 0)) continue;
114
+ const cfg = normalize(l.def.rootMotion !== undefined ? l.def.rootMotion : anim.rootMotion), ent = cfg && boneEntry(anim, cfg.bone);
115
+ if (!ent) continue;
116
+ ent.bone.position.x = ent.bind.x; ent.bone.position.z = ent.bind.z;
117
+ if (cfg.y) ent.bone.position.y = ent.bind.y;
118
+ }
119
+ }
120
+
121
+ /** @internal Deterministic analytical root displacement over gameplay interval [fromT, toT] */
122
+ export function rootDelta(anim, findClip, state, fromT, toT, opts) {
123
+ const out = opts?.out ?? { x: 0, y: 0, z: 0 };
124
+ out.x = 0; out.y = 0; out.z = 0;
125
+ const def = anim.states[state];
126
+ if (!def) return out;
127
+ const raw = def.rootMotion !== undefined ? def.rootMotion : anim.rootMotion;
128
+ if (raw === false) return out;
129
+ const cfg = normalize(raw === undefined ? true : raw), includeY = opts?.y !== undefined ? !!opts.y : cfg.y;
130
+ let dx = 0, dy = 0, dz = 0;
131
+ if (def.blend) {
132
+ const bw = anim._blend(def);
133
+ for (let i = 0; i < def.blend.length; i++) {
134
+ const w = bw[i], clip = w > 0 ? findClip(anim.clips, def.blend[i].clip) : null;
135
+ if (!clip) continue;
136
+ clipDelta(clip, def, findTrack(anim, clip, cfg.bone), fromT, toT, _acc);
137
+ dx += _acc.x * w; dy += _acc.y * w; dz += _acc.z * w;
138
+ }
139
+ } else if (def.clip) {
140
+ const clip = findClip(anim.clips, def.clip);
141
+ if (clip) { clipDelta(clip, def, findTrack(anim, clip, cfg.bone), fromT, toT, _acc); dx = _acc.x; dy = _acc.y; dz = _acc.z; }
142
+ }
143
+ if (!includeY) dy = 0;
144
+ if (opts?.local) { out.x = dx; out.y = dy; out.z = dz; return out; }
145
+ const yaw = opts?.yaw ?? anim.root.rotation.y, c = Math.cos(yaw), s = Math.sin(yaw);
146
+ out.x = dx * c + dz * s; out.y = dy; out.z = -dx * s + dz * c;
147
+ return out;
148
+ }