@threenative/core 0.3.4 → 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/capabilities.json +1505 -79
- package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
- package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
- package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
- package/dist/hot.d.ts +4 -4
- package/dist/index.d.ts +712 -118
- package/dist/index.js +12423 -4955
- package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
- package/dist/playtest.d.ts +6 -10
- package/dist/playtest.js +47 -24
- package/dist/react-css.d.ts +62 -0
- package/dist/react-css.js +591 -0
- package/dist/react.d.ts +2 -2
- package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
- package/dist/terrain-jobs-worker.d.ts +2 -0
- package/dist/terrain-jobs-worker.js +130 -0
- package/dist/ui-layer.js +59 -8
- package/dist/world.d.ts +766 -73
- package/dist/world.js +9307 -3543
- package/gpl/recipes/export_world.py +18 -1
- package/mcp/blender-server.mjs +7 -4
- package/mcp/blender.mjs +3 -4
- package/mcp/engine-server.mjs +2 -2
- package/mcp/servers.mjs +4 -4
- package/package.json +15 -9
- package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
- package/patches/three@0.185.1.patch +6594 -700
- package/scripts/apply-three-patch.mjs +62 -4
- package/src/animation-blend.ts +264 -0
- package/src/animation-composition.ts +362 -0
- package/src/animation-layers.ts +260 -0
- package/src/animation-root-motion.ts +283 -0
- package/src/animation.ts +896 -0
- package/src/assets.ts +1303 -0
- package/src/atmosphere/index.ts +335 -0
- package/src/atmosphere/luts.ts +298 -0
- package/src/atmosphere/params.ts +323 -0
- package/src/audio.ts +912 -0
- package/src/billboard.ts +124 -0
- package/src/bone-lengths.ts +157 -0
- package/src/camera-shake.ts +116 -0
- package/src/canvas-layer.ts +47 -0
- package/src/clip-audit.ts +401 -0
- package/src/clustered-batch.ts +492 -0
- package/src/clustered-mesh.ts +638 -0
- package/src/compute-driven.ts +176 -0
- package/src/compute-timing.ts +318 -0
- package/src/config.ts +593 -0
- package/src/debug.ts +82 -0
- package/src/engine-render-hook.ts +25 -0
- package/src/entities.ts +79 -0
- package/src/entity-snapshot.ts +53 -0
- package/src/flight.ts +683 -0
- package/src/fluid-field.ts +748 -0
- package/src/fluid-particles.ts +1253 -0
- package/src/frame-budget.ts +1368 -0
- package/src/game.ts +2390 -0
- package/src/geometry-capture.ts +1098 -0
- package/src/gpu-class.ts +160 -0
- package/src/gpu-frame-observation.ts +424 -0
- package/src/gpu-readback.ts +143 -0
- package/src/gpu-scene-bvh.ts +464 -0
- package/src/grounding.ts +100 -0
- package/src/hot.ts +161 -0
- package/src/import-meta.d.ts +13 -0
- package/src/index.ts +1536 -0
- package/src/input.ts +690 -0
- package/src/instanced-batch-lod.ts +283 -0
- package/src/instanced-batch.ts +274 -0
- package/src/interpolation.ts +129 -0
- package/src/launch-diagnostics.ts +161 -0
- package/src/loop.ts +564 -0
- package/src/matrix-world.ts +245 -0
- package/src/merge-parts.ts +812 -0
- package/src/model-lod.ts +1315 -0
- package/src/net-protocol.ts +333 -0
- package/src/net-session.ts +477 -0
- package/src/net.ts +80 -0
- package/src/ocean/fft.ts +72 -0
- package/src/ocean/spectral.ts +728 -0
- package/src/particle-significance.ts +102 -0
- package/src/particles.ts +648 -0
- package/src/path-follow.ts +175 -0
- package/src/picking.ts +250 -0
- package/src/pipeline-census.ts +1566 -0
- package/src/platform.ts +210 -0
- package/src/playtest.ts +839 -0
- package/src/pointer-events.ts +411 -0
- package/src/pose-measure.ts +435 -0
- package/src/profiling/FrameCounters.ts +231 -0
- package/src/profiling/Spans.ts +548 -0
- package/src/profiling/opacity-convention.ts +21 -0
- package/src/profiling/render-list-validate.ts +175 -0
- package/src/profiling/render-trap-audit.ts +84 -0
- package/src/profiling/scene-warning.ts +190 -0
- package/src/profiling/span-probes.ts +191 -0
- package/src/profiling/unlit-foliage-warning.ts +149 -0
- package/src/projection-apply.ts +1529 -0
- package/src/projection-marker.ts +142 -0
- package/src/projection-plan.ts +1258 -0
- package/src/projection-skinned.ts +419 -0
- package/src/projection-stability.ts +409 -0
- package/src/projection-uniform.ts +328 -0
- package/src/random.ts +41 -0
- package/src/react-css.ts +604 -0
- package/src/react-glyphs.ts +114 -0
- package/src/react-host.ts +576 -0
- package/src/react-layout.ts +265 -0
- package/src/react.ts +60 -0
- package/src/render/alpha-antialiasing.ts +159 -0
- package/src/render/batched-velocity.ts +126 -0
- package/src/render/chain.ts +1021 -0
- package/src/render/daylight.ts +189 -0
- package/src/render/depth-pyramid.ts +596 -0
- package/src/render/foliage-alpha.ts +166 -0
- package/src/render/material-key.ts +60 -0
- package/src/render/mesh-pool.ts +144 -0
- package/src/render/probe-volume.ts +1668 -0
- package/src/render/resolution-subrect.ts +253 -0
- package/src/render/velocity.ts +442 -0
- package/src/render/virtual-shadow-pages.ts +827 -0
- package/src/render/virtual-shadow-partial.ts +174 -0
- package/src/render/virtual-shadow.ts +3330 -0
- package/src/render/world-impostor-surface.ts +722 -0
- package/src/render/world-impostor.ts +558 -0
- package/src/render-camera-cull.ts +441 -0
- package/src/render-pass-budget.ts +501 -0
- package/src/renderProjection.ts +758 -0
- package/src/renderer-config.ts +127 -0
- package/src/renderer.ts +1847 -0
- package/src/replay-protocol.ts +85 -0
- package/src/replay.ts +205 -0
- package/src/resolution-scaler.ts +819 -0
- package/src/rig-preparation.ts +271 -0
- package/src/ripple-field.ts +432 -0
- package/src/scale.ts +109 -0
- package/src/scene.ts +239 -0
- package/src/schedule.ts +155 -0
- package/src/skeletal-mesh.ts +61 -0
- package/src/skeleton.ts +100 -0
- package/src/snow-field.ts +744 -0
- package/src/softbody-topology.ts +269 -0
- package/src/softbody.ts +516 -0
- package/src/sprite-animator.ts +222 -0
- package/src/startup-readiness.ts +386 -0
- package/src/state.ts +66 -0
- package/src/static-transform.ts +274 -0
- package/src/storage-buffer.ts +253 -0
- package/src/streaming.ts +308 -0
- package/src/target-fps.ts +92 -0
- package/src/terrain-jobs-worker.ts +17 -0
- package/src/terrain-jobs.ts +353 -0
- package/src/textures.ts +39 -0
- package/src/tracers.ts +237 -0
- package/src/ui-bridge.ts +368 -0
- package/src/ui-hit-regions.ts +380 -0
- package/src/ui-layer.ts +83 -0
- package/src/ui-state.ts +220 -0
- package/src/version.ts +2 -0
- package/src/viewport.ts +253 -0
- package/src/warmup.ts +1357 -0
- package/src/water-surface.ts +384 -0
- package/src/wave-field.ts +524 -0
- package/src/world-capabilities.ts +131 -0
- package/src/world-cell-proxy.ts +392 -0
- package/src/world-cells.ts +10564 -0
- package/src/world-gpu-scene.ts +3354 -0
- package/src/world-heightmap.ts +82 -0
- package/src/world-package.ts +469 -0
- package/src/world-passes.ts +582 -0
- package/src/world-region.ts +17 -0
- package/src/world-terrain-splat.ts +564 -0
- package/src/world-tiles.ts +3826 -0
- package/src/world-topology.ts +370 -0
- package/src/world-validate.ts +48 -0
- package/src/world.ts +805 -0
package/src/animation.ts
ADDED
|
@@ -0,0 +1,896 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AnimationAction,
|
|
3
|
+
type AnimationClip,
|
|
4
|
+
AnimationMixer,
|
|
5
|
+
LoopOnce,
|
|
6
|
+
LoopRepeat,
|
|
7
|
+
Matrix4,
|
|
8
|
+
type Object3D,
|
|
9
|
+
Vector3,
|
|
10
|
+
type VectorKeyframeTrack,
|
|
11
|
+
} from "three";
|
|
12
|
+
import { clipTrackBindings } from "./clip-audit.js";
|
|
13
|
+
import { type ISharedStride, type RigPreparation, uniformYawScale } from "./rig-preparation.js";
|
|
14
|
+
|
|
15
|
+
export interface IAnimationPlayerOptions {
|
|
16
|
+
readonly clips: readonly AnimationClip[];
|
|
17
|
+
readonly root: Object3D;
|
|
18
|
+
readonly requiredClips?: readonly string[] | Readonly<Record<string, string>>;
|
|
19
|
+
/**
|
|
20
|
+
* Shared preparation for clones of one source rig. Set by `SkeletalMesh3D`; a standalone
|
|
21
|
+
* player leaves it undefined and keeps the per-instance binding audit and stride sample.
|
|
22
|
+
*/
|
|
23
|
+
readonly preparation?: RigPreparation;
|
|
24
|
+
/**
|
|
25
|
+
* Match a travelling clip's playback rate to the ground the body actually covers.
|
|
26
|
+
*
|
|
27
|
+
* On by default, because a model whose feet do not agree with its motion is the single most
|
|
28
|
+
* common thing wrong with a character in a game built here, and every game solves it the same
|
|
29
|
+
* way. Set `false` to keep the authored rate; the measurement below stays live either way and
|
|
30
|
+
* says that it was overridden. The convention re-times locomotion only: a `"once"` clip — a
|
|
31
|
+
* death, a flinch — always plays at its authored rate.
|
|
32
|
+
*/
|
|
33
|
+
readonly strideSync?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* The object whose travel counts as ground covered. Defaults to `root`.
|
|
36
|
+
*
|
|
37
|
+
* Name the body a game moves when the rig is a child of it, which is the usual shape: the clip
|
|
38
|
+
* writes the model's own root track, so measuring the same object the mixer writes would read
|
|
39
|
+
* the clip's motion back as if it were the body's.
|
|
40
|
+
*/
|
|
41
|
+
readonly strideRoot?: Object3D;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* What the feet are doing against what the body is doing.
|
|
46
|
+
*
|
|
47
|
+
* Reported whether or not the convention is applied: turning a convention off must not turn its
|
|
48
|
+
* measurement off, or a game that opted out has no way to know what it cost.
|
|
49
|
+
*/
|
|
50
|
+
export interface IStrideReport {
|
|
51
|
+
/** Metres of ground the current clip carries per clip-second, at rate 1. Zero if it travels none. */
|
|
52
|
+
readonly clipGroundSpeed: number;
|
|
53
|
+
/** Metres per second the root has actually covered, smoothed over the last update. */
|
|
54
|
+
readonly groundSpeed: number;
|
|
55
|
+
/** The playback rate those two imply, clamped to `limits`. */
|
|
56
|
+
readonly rate: number;
|
|
57
|
+
/** True when that rate is being applied to the action. */
|
|
58
|
+
readonly synced: boolean;
|
|
59
|
+
/** True when a rate was measured and deliberately not applied. */
|
|
60
|
+
readonly overridden: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* True when the clip carries no root motion and its stride was read off the feet instead.
|
|
63
|
+
*
|
|
64
|
+
* `synced: false, overridden: false` is what an idle reports, so without this a game whose walk
|
|
65
|
+
* cycle is silently going unmatched cannot tell itself apart from one with nothing to match. An
|
|
66
|
+
* in-place clip that also yields no foot plant reports `inPlace: true` with a zero
|
|
67
|
+
* `clipGroundSpeed`, which names the asset as the thing to fix.
|
|
68
|
+
*/
|
|
69
|
+
readonly inPlace: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The band a measured rate is held inside.
|
|
74
|
+
*
|
|
75
|
+
* A rig with one walk cycle cannot honestly represent a sprint or a crawl. Above the ceiling the
|
|
76
|
+
* clip reads as a cartoon; at zero it freezes mid-stride while the body drifts, which is worse
|
|
77
|
+
* than a slow cycle. Both ends are a property of the clip set, so both are the game's to move.
|
|
78
|
+
*/
|
|
79
|
+
const STRIDE_RATE_MIN = 0.15;
|
|
80
|
+
const STRIDE_RATE_MAX = 3;
|
|
81
|
+
/** Below this the body is standing, and a measured rate would be noise. */
|
|
82
|
+
const STRIDE_SPEED_FLOOR = 1e-4;
|
|
83
|
+
/** A clip carrying less ground than this per second is not locomotion. */
|
|
84
|
+
const CLIP_GROUND_FLOOR = 1e-3;
|
|
85
|
+
/** Poses taken across one cycle when reading an in-place clip's stride off its feet. */
|
|
86
|
+
const PLANT_SAMPLES = 64;
|
|
87
|
+
/** A contact bone is one that reaches this near the lowest point the rig visits. */
|
|
88
|
+
const CONTACT_BAND = 0.15;
|
|
89
|
+
/** Of a contact bone's own vertical arc, the bottom slice counts as planted. */
|
|
90
|
+
const PLANT_BAND = 0.3;
|
|
91
|
+
|
|
92
|
+
/** What one clip's own locomotion measured out at, cached per clip name. */
|
|
93
|
+
interface IClipStride {
|
|
94
|
+
/** Metres of ground the clip carries per clip-second at rate 1. */
|
|
95
|
+
readonly groundSpeed: number;
|
|
96
|
+
/** True when no root track travelled and the number came from the feet — or from nothing. */
|
|
97
|
+
readonly inPlace: boolean;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The ground a clip's root track carries, per clip-second, in the track's own units.
|
|
102
|
+
*
|
|
103
|
+
* **Net** displacement, not distance walked. Summing every step's magnitude is what made a
|
|
104
|
+
* swinging thigh outscore a still root: a limb that ends the cycle where it began has covered no
|
|
105
|
+
* ground however far it waved, while a travelling root ends the cycle somewhere else — that is
|
|
106
|
+
* what root motion *is*. Measured in `sandbox/wildwood`: `ANIM_DeerStag_Walk` scored 0.1287 under
|
|
107
|
+
* the old sum (from `STAG_-R-Thigh`) and scores 0 under this one, which is the truth.
|
|
108
|
+
*/
|
|
109
|
+
function clipRootMotionSpeed(clip: AnimationClip): number {
|
|
110
|
+
let best = 0;
|
|
111
|
+
for (const track of clip.tracks) {
|
|
112
|
+
if (!track.name.endsWith(".position")) continue;
|
|
113
|
+
const values = (track as VectorKeyframeTrack).values;
|
|
114
|
+
if (values.length < 6) continue;
|
|
115
|
+
const dx = (values[values.length - 3] ?? 0) - (values[0] ?? 0);
|
|
116
|
+
const dz = (values[values.length - 1] ?? 0) - (values[2] ?? 0);
|
|
117
|
+
best = Math.max(best, Math.hypot(dx, dz) / clip.duration);
|
|
118
|
+
}
|
|
119
|
+
return best;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The ground an in-place clip was authored for, read off the feet, in world metres per clip-second.
|
|
124
|
+
*
|
|
125
|
+
* A planted foot sweeps backward relative to the body at exactly the speed the body is meant to be
|
|
126
|
+
* travelling — that is what "planted" means — so the stance phase of a cycle states the clip's
|
|
127
|
+
* speed even though nothing in it translates. Contact bones are found by where they go rather than
|
|
128
|
+
* by what they are called: whatever reaches the bottom of the rig's arc is a foot, in any rig and
|
|
129
|
+
* any language. The median over stance frames rejects the toe-off and heel-strike ends of the
|
|
130
|
+
* sweep, and the median over feet rejects a limb that never plants.
|
|
131
|
+
*
|
|
132
|
+
* The rig is driven and then restored to the transforms it arrived with, once per clip.
|
|
133
|
+
*/
|
|
134
|
+
function footPlantSpeed(root: Object3D, clip: AnimationClip): number {
|
|
135
|
+
const objects: Object3D[] = [];
|
|
136
|
+
root.traverse((object) => objects.push(object));
|
|
137
|
+
|
|
138
|
+
// The root belongs to the game, which turns it with `rotation.y +=`. A quaternion restore
|
|
139
|
+
// rewrites `rotation` as the equivalent Euler, so a yaw of PI comes back as (PI, 0, PI) and the
|
|
140
|
+
// next increment turns the figure the mirrored way. Bones keep the exact quaternion: a round trip
|
|
141
|
+
// through Euler would lose precision on every joint.
|
|
142
|
+
const rootRotation = root.rotation.clone();
|
|
143
|
+
|
|
144
|
+
const mixer = new AnimationMixer(root);
|
|
145
|
+
const action = mixer.clipAction(clip);
|
|
146
|
+
action.play();
|
|
147
|
+
const paths = objects.map(() => [] as { x: number; y: number; z: number }[]);
|
|
148
|
+
const step = clip.duration / PLANT_SAMPLES;
|
|
149
|
+
// The mixer animates only the rig, so its ancestors need one refresh, not one per sample.
|
|
150
|
+
root.parent?.updateWorldMatrix(true, false);
|
|
151
|
+
try {
|
|
152
|
+
for (let frame = 0; frame <= PLANT_SAMPLES; frame += 1) {
|
|
153
|
+
mixer.setTime(frame * step);
|
|
154
|
+
root.updateMatrixWorld(true);
|
|
155
|
+
for (let index = 0; index < objects.length; index += 1) {
|
|
156
|
+
// The frame's updateMatrixWorld already holds every bone; getWorldPosition re-walks ancestors.
|
|
157
|
+
const object = objects[index] as Object3D & {
|
|
158
|
+
__tnCopyMatrixWorld?: (target: Matrix4) => void;
|
|
159
|
+
};
|
|
160
|
+
if (object.__tnCopyMatrixWorld !== undefined) {
|
|
161
|
+
object.__tnCopyMatrixWorld(scratchMatrixWorld);
|
|
162
|
+
scratchWorld.setFromMatrixPosition(scratchMatrixWorld);
|
|
163
|
+
} else scratchWorld.setFromMatrixPosition(object.matrixWorld);
|
|
164
|
+
(paths[index] as { x: number; y: number; z: number }[]).push({
|
|
165
|
+
x: scratchWorld.x,
|
|
166
|
+
y: scratchWorld.y,
|
|
167
|
+
z: scratchWorld.z,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
} finally {
|
|
172
|
+
// Stopping restores every animated binding saved by this isolated mixer when it played.
|
|
173
|
+
action.stop();
|
|
174
|
+
mixer.uncacheClip(clip);
|
|
175
|
+
root.rotation.copy(rootRotation);
|
|
176
|
+
root.updateMatrixWorld(true);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const rootPath = paths[0];
|
|
180
|
+
if (rootPath === undefined) return 0;
|
|
181
|
+
let lowest = Number.POSITIVE_INFINITY;
|
|
182
|
+
let highest = Number.NEGATIVE_INFINITY;
|
|
183
|
+
for (const path of paths)
|
|
184
|
+
for (const point of path) {
|
|
185
|
+
lowest = Math.min(lowest, point.y);
|
|
186
|
+
highest = Math.max(highest, point.y);
|
|
187
|
+
}
|
|
188
|
+
const height = highest - lowest;
|
|
189
|
+
if (!(height > 0)) return 0;
|
|
190
|
+
|
|
191
|
+
const speeds: number[] = [];
|
|
192
|
+
for (const path of paths) {
|
|
193
|
+
let low = Number.POSITIVE_INFINITY;
|
|
194
|
+
let high = Number.NEGATIVE_INFINITY;
|
|
195
|
+
for (const point of path) {
|
|
196
|
+
low = Math.min(low, point.y);
|
|
197
|
+
high = Math.max(high, point.y);
|
|
198
|
+
}
|
|
199
|
+
// A contact bone visits the floor and lifts off it again. One that never descends is not a
|
|
200
|
+
// foot, and one that never rises is a stationary prop rather than a cycling limb.
|
|
201
|
+
if (low > lowest + height * CONTACT_BAND) continue;
|
|
202
|
+
const arc = high - low;
|
|
203
|
+
if (!(arc > height * CLIP_GROUND_FLOOR)) continue;
|
|
204
|
+
const planted = low + arc * PLANT_BAND;
|
|
205
|
+
const rates: number[] = [];
|
|
206
|
+
for (let frame = 1; frame < path.length; frame += 1) {
|
|
207
|
+
const previous = path[frame - 1] as { x: number; y: number; z: number };
|
|
208
|
+
const current = path[frame] as { x: number; y: number; z: number };
|
|
209
|
+
if (current.y > planted || previous.y > planted) continue;
|
|
210
|
+
const anchor = rootPath[frame] as { x: number; y: number; z: number };
|
|
211
|
+
const before = rootPath[frame - 1] as { x: number; y: number; z: number };
|
|
212
|
+
const dx = current.x - anchor.x - (previous.x - before.x);
|
|
213
|
+
const dz = current.z - anchor.z - (previous.z - before.z);
|
|
214
|
+
rates.push(Math.hypot(dx, dz) / step);
|
|
215
|
+
}
|
|
216
|
+
if (rates.length < 4) continue;
|
|
217
|
+
rates.sort((first, second) => first - second);
|
|
218
|
+
speeds.push(rates[Math.floor(rates.length / 2)] as number);
|
|
219
|
+
}
|
|
220
|
+
if (speeds.length === 0) return 0;
|
|
221
|
+
speeds.sort((first, second) => first - second);
|
|
222
|
+
return speeds[Math.floor(speeds.length / 2)] as number;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export interface IAnimationPlayOptions {
|
|
226
|
+
readonly fade?: number;
|
|
227
|
+
/**
|
|
228
|
+
* `"loop"` (default) repeats; `"once"` plays through and holds the last frame. A `"once"` clip
|
|
229
|
+
* also keeps its authored rate — stride sync re-times locomotion, not events.
|
|
230
|
+
*/
|
|
231
|
+
readonly mode?: "loop" | "once";
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
type AnimationMode = "loop" | "once";
|
|
235
|
+
|
|
236
|
+
export class AnimationPlayer {
|
|
237
|
+
readonly mixer: AnimationMixer;
|
|
238
|
+
readonly root: Object3D;
|
|
239
|
+
#actions = new Map<string, AnimationAction>();
|
|
240
|
+
#current: string | undefined;
|
|
241
|
+
#mode: AnimationMode = "loop";
|
|
242
|
+
#advancedFrames = 0;
|
|
243
|
+
#finished = false;
|
|
244
|
+
#posed = false;
|
|
245
|
+
#fadeOut: { action: AnimationAction; from: number }[] = [];
|
|
246
|
+
#fadeElapsed = 0;
|
|
247
|
+
#fadeDuration = 0;
|
|
248
|
+
#fadeInFrom = 0;
|
|
249
|
+
#clips = new Map<string, AnimationClip>();
|
|
250
|
+
#clipGroundSpeed = new Map<string, IClipStride>();
|
|
251
|
+
/** Weights `playWeighted` is heading towards. Undefined whenever single-clip `play` owns the rig. */
|
|
252
|
+
#blendTargets: Map<string, number> | undefined;
|
|
253
|
+
#blendDuration = 0;
|
|
254
|
+
#blendElapsed = 0;
|
|
255
|
+
#blendStarts = new Map<string, number>();
|
|
256
|
+
#preparation: RigPreparation | undefined;
|
|
257
|
+
#strideSync: boolean;
|
|
258
|
+
#strideRoot: Object3D;
|
|
259
|
+
#lastRootPosition = new Vector3();
|
|
260
|
+
#hasLastRootPosition = false;
|
|
261
|
+
// The last update's numbers, kept as scalars so a frame that never reads `.stride` builds no
|
|
262
|
+
// report. A read materializes a fresh snapshot, so a retained report never changes under it.
|
|
263
|
+
#strideGroundSpeed = 0;
|
|
264
|
+
#strideRate = 1;
|
|
265
|
+
#strideSynced = false;
|
|
266
|
+
#strideOverridden = false;
|
|
267
|
+
#strideInPlace = false;
|
|
268
|
+
readonly #onFinished = ({ action }: { action: AnimationAction }) => {
|
|
269
|
+
if (action === this.#actions.get(this.#current ?? "")) this.#finished = true;
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
constructor(options: IAnimationPlayerOptions) {
|
|
273
|
+
const owner = new.target.name || "AnimationPlayer";
|
|
274
|
+
this.root = options.root;
|
|
275
|
+
this.mixer = new AnimationMixer(options.root);
|
|
276
|
+
this.#preparation = options.preparation;
|
|
277
|
+
this.#strideSync = options.strideSync ?? true;
|
|
278
|
+
this.#strideRoot = options.strideRoot ?? options.root;
|
|
279
|
+
for (const clip of options.clips) {
|
|
280
|
+
if (this.#actions.has(clip.name))
|
|
281
|
+
// Two clip sources on one rig is the normal way to assemble a character's vocabulary, and
|
|
282
|
+
// stock libraries all ship a bind pose under the same name. Failing closed is right — a
|
|
283
|
+
// silently dropped clip is a pose bug nobody thinks to look for — but the message says
|
|
284
|
+
// what to do about it, because every game that loads two `.glb` files hits this.
|
|
285
|
+
throw new Error(
|
|
286
|
+
`Duplicate animation clip '${clip.name}'. Two clip sources define it; keep one per name before constructing the player.`,
|
|
287
|
+
);
|
|
288
|
+
const action = this.mixer.clipAction(clip);
|
|
289
|
+
if (action === null)
|
|
290
|
+
throw new Error(`Animation clip '${clip.name}' could not create an action.`);
|
|
291
|
+
this.#actions.set(clip.name, action);
|
|
292
|
+
this.#clips.set(clip.name, clip);
|
|
293
|
+
}
|
|
294
|
+
for (const name of requiredClipNames(options.requiredClips)) {
|
|
295
|
+
const clip = this.#clips.get(name);
|
|
296
|
+
if (clip === undefined)
|
|
297
|
+
throw new Error(
|
|
298
|
+
`${owner}: missing required clip '${name}'. Available clips: ${options.clips.map((item) => `'${item.name}'`).join(", ") || "(none)"}.`,
|
|
299
|
+
);
|
|
300
|
+
let bound = this.#preparation?.boundCount(options.root, clip);
|
|
301
|
+
if (bound === undefined) {
|
|
302
|
+
bound = clipTrackBindings(options.root, clip).bound;
|
|
303
|
+
this.#preparation?.rememberBound(options.root, clip, bound);
|
|
304
|
+
}
|
|
305
|
+
if (bound === 0)
|
|
306
|
+
throw new Error(
|
|
307
|
+
`${owner}: clip '${name}' binds 0 tracks to '${options.root.name || options.root.type}'.`,
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
this.mixer.addEventListener("finished", this.#onFinished);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
get current(): string | undefined {
|
|
314
|
+
return this.#current;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
get advancedFrames(): number {
|
|
318
|
+
return this.#advancedFrames;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** True when a `"once"` clip has reached its end and is holding. */
|
|
322
|
+
get finished(): boolean {
|
|
323
|
+
return this.#finished;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* What the feet are doing against what the body is doing, as of the last `update`.
|
|
328
|
+
*
|
|
329
|
+
* Live whether or not the convention is applied. A game that set `strideSync: false` reads
|
|
330
|
+
* `overridden: true` here next to the rate it declined, which is the only way an override can
|
|
331
|
+
* be honest about what it turned off.
|
|
332
|
+
*/
|
|
333
|
+
get stride(): IStrideReport {
|
|
334
|
+
const name = this.#current;
|
|
335
|
+
const measured = name === undefined ? undefined : this.#measureOf(name);
|
|
336
|
+
// A fresh snapshot each read: what the last update stored, with the clip's own ground speed
|
|
337
|
+
// derived so it is answerable the moment it is played, before any frame has advanced.
|
|
338
|
+
return {
|
|
339
|
+
clipGroundSpeed: measured?.groundSpeed ?? 0,
|
|
340
|
+
groundSpeed: this.#strideGroundSpeed,
|
|
341
|
+
inPlace: measured?.inPlace ?? this.#strideInPlace,
|
|
342
|
+
overridden: this.#strideOverridden,
|
|
343
|
+
rate: this.#strideRate,
|
|
344
|
+
synced: this.#strideSynced,
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** The clip behind a name, for a game that wants the action or the raw `AnimationClip`. */
|
|
349
|
+
clip(name: string): AnimationClip {
|
|
350
|
+
const clip = this.#clips.get(name);
|
|
351
|
+
if (clip === undefined) throw new Error(`Unknown animation clip '${name}'.`);
|
|
352
|
+
return clip;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* How much ground a clip carries per clip-second, in the world's metres.
|
|
357
|
+
*
|
|
358
|
+
* Horizontal only: a jump's vertical arc is not stride. Measured once per clip and cached,
|
|
359
|
+
* because it is a property of the asset and cannot change between frames.
|
|
360
|
+
*
|
|
361
|
+
* Root motion first, feet second. Most game locomotion is authored **in place** — every ActorX
|
|
362
|
+
* and Unreal export, every Mixamo "in place" clip, every stock animal pack — and a convention
|
|
363
|
+
* that only works on the travelling minority is a convention that does not work.
|
|
364
|
+
*/
|
|
365
|
+
#measureOf(name: string): IClipStride {
|
|
366
|
+
const cached = this.#clipGroundSpeed.get(name);
|
|
367
|
+
if (cached !== undefined) return cached;
|
|
368
|
+
const clip = this.#clips.get(name);
|
|
369
|
+
let measured: IClipStride = { groundSpeed: 0, inPlace: true };
|
|
370
|
+
if (clip !== undefined && clip.duration > 0) {
|
|
371
|
+
const shared = this.#sharedStride(clip);
|
|
372
|
+
if (shared !== undefined) {
|
|
373
|
+
measured = {
|
|
374
|
+
groundSpeed: shared.groundSpeed * this.#trackScale(),
|
|
375
|
+
inPlace: shared.inPlace,
|
|
376
|
+
};
|
|
377
|
+
} else {
|
|
378
|
+
const rootMotion = clipRootMotionSpeed(clip);
|
|
379
|
+
measured =
|
|
380
|
+
rootMotion >= CLIP_GROUND_FLOOR
|
|
381
|
+
? { groundSpeed: rootMotion * this.#trackScale(), inPlace: false }
|
|
382
|
+
: {
|
|
383
|
+
groundSpeed: footPlantSpeed(this.mixer.getRoot() as Object3D, clip),
|
|
384
|
+
inPlace: true,
|
|
385
|
+
};
|
|
386
|
+
this.#rememberSharedStride(clip, measured);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
this.#clipGroundSpeed.set(name, measured);
|
|
390
|
+
return measured;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* A stride already measured for an equivalent clone, rescaled into this clone's world.
|
|
395
|
+
*
|
|
396
|
+
* Only a yaw-only, uniformly scaled rig is eligible: the sampled value normalizes for scale and
|
|
397
|
+
* translation, so a tilted, mirrored or non-uniformly scaled instance keeps its own sample.
|
|
398
|
+
*/
|
|
399
|
+
#sharedStride(clip: AnimationClip): ISharedStride | undefined {
|
|
400
|
+
if (this.#preparation === undefined) return undefined;
|
|
401
|
+
if (this.#uniformWorldScale() === undefined) return undefined;
|
|
402
|
+
return this.#preparation.stride(this.mixer.getRoot() as Object3D, clip);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
#rememberSharedStride(clip: AnimationClip, measured: IClipStride): void {
|
|
406
|
+
if (this.#preparation === undefined) return;
|
|
407
|
+
const scale = this.#uniformWorldScale();
|
|
408
|
+
if (scale === undefined) return;
|
|
409
|
+
this.#preparation.rememberStride(this.mixer.getRoot() as Object3D, clip, {
|
|
410
|
+
groundSpeed: measured.groundSpeed / scale,
|
|
411
|
+
inPlace: measured.inPlace,
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
#uniformWorldScale(): number | undefined {
|
|
416
|
+
const root = this.mixer.getRoot() as Object3D;
|
|
417
|
+
const owner = (root.parent ?? root) as Object3D & {
|
|
418
|
+
__tnCopyMatrixWorld?: (target: Matrix4) => void;
|
|
419
|
+
};
|
|
420
|
+
owner.updateWorldMatrix(true, false);
|
|
421
|
+
if (owner.__tnCopyMatrixWorld !== undefined) {
|
|
422
|
+
// Native copies into owned storage so this read cannot escape the live transform alias.
|
|
423
|
+
owner.__tnCopyMatrixWorld(scratchMatrixWorld);
|
|
424
|
+
return uniformYawScale(scratchMatrixWorld);
|
|
425
|
+
}
|
|
426
|
+
return uniformYawScale(owner.matrixWorld);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* What one unit of a root track is worth in world metres.
|
|
431
|
+
*
|
|
432
|
+
* A clip's translation values are in the animated node's **parent** space, while the ground the
|
|
433
|
+
* body covers is measured in world metres. `normaliseToMetres` — the framework's own convention
|
|
434
|
+
* for sizing an import — all but guarantees the two differ, and a half-scale rig compared
|
|
435
|
+
* without this reads its own stride at twice the speed. The foot-plant path below needs no such
|
|
436
|
+
* conversion: it reads world positions, which already carry every ancestor's scale.
|
|
437
|
+
*/
|
|
438
|
+
#trackScale(): number {
|
|
439
|
+
const root = this.mixer.getRoot() as Object3D;
|
|
440
|
+
(root.parent ?? root).getWorldScale(scratchScale);
|
|
441
|
+
return (Math.abs(scratchScale.x) + Math.abs(scratchScale.z)) / 2;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Hold the current clip's playback rate against the ground the body just covered.
|
|
446
|
+
*
|
|
447
|
+
* Called after `mixer.update`, from the root's world position, so it reads the movement a game
|
|
448
|
+
* already applied this frame rather than asking the game to report it. A game that drives the
|
|
449
|
+
* same object from the clip's own root motion has the two ends of this loop joined and should
|
|
450
|
+
* turn the convention off; that is what the option is for.
|
|
451
|
+
*/
|
|
452
|
+
#syncStride(dt: number): void {
|
|
453
|
+
const name = this.#current;
|
|
454
|
+
const action = name === undefined ? undefined : this.#actions.get(name);
|
|
455
|
+
this.#strideRoot.getWorldPosition(scratchWorld);
|
|
456
|
+
const previous = this.#lastRootPosition;
|
|
457
|
+
const moved = this.#hasLastRootPosition
|
|
458
|
+
? Math.hypot(scratchWorld.x - previous.x, scratchWorld.z - previous.z)
|
|
459
|
+
: 0;
|
|
460
|
+
this.#lastRootPosition.copy(scratchWorld);
|
|
461
|
+
this.#hasLastRootPosition = true;
|
|
462
|
+
if (name === undefined || action === undefined || dt <= 0) return;
|
|
463
|
+
const measured = this.#measureOf(name);
|
|
464
|
+
const clipGroundSpeed = measured.groundSpeed;
|
|
465
|
+
const groundSpeed = moved / dt;
|
|
466
|
+
// A dominant idle must not leave a contributing walk at its authored speed.
|
|
467
|
+
if (this.#blendTargets !== undefined && this.#strideSync && this.#mode === "loop")
|
|
468
|
+
this.#syncBlendParticipants(groundSpeed);
|
|
469
|
+
if (clipGroundSpeed < CLIP_GROUND_FLOOR) {
|
|
470
|
+
// Not locomotion. An idle, a reload or a death is authored at the rate it is authored at,
|
|
471
|
+
// and warping it by how fast the body happens to be sliding is a bug, not a convention.
|
|
472
|
+
if (action.getEffectiveTimeScale() !== 1) action.setEffectiveTimeScale(1);
|
|
473
|
+
this.#strideGroundSpeed = groundSpeed;
|
|
474
|
+
this.#strideRate = 1;
|
|
475
|
+
this.#strideSynced = false;
|
|
476
|
+
this.#strideOverridden = false;
|
|
477
|
+
this.#strideInPlace = measured.inPlace;
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
const wanted =
|
|
481
|
+
groundSpeed < STRIDE_SPEED_FLOOR ? STRIDE_RATE_MIN : groundSpeed / clipGroundSpeed;
|
|
482
|
+
const rate = Math.min(STRIDE_RATE_MAX, Math.max(STRIDE_RATE_MIN, wanted));
|
|
483
|
+
// A `"once"` clip is an event — a death, a flinch, a reload — and plays at the rate the
|
|
484
|
+
// event happens at, however still the body stands: its own root motion is the movement, so
|
|
485
|
+
// re-timing it against a stationary body only slows the event down. A travelling death clip
|
|
486
|
+
// clamped to the rate floor held a corpse upright through its whole death in the sandbox.
|
|
487
|
+
const applies = this.#strideSync && this.#mode === "loop";
|
|
488
|
+
if (applies) action.setEffectiveTimeScale(rate);
|
|
489
|
+
this.#strideGroundSpeed = groundSpeed;
|
|
490
|
+
this.#strideRate = rate;
|
|
491
|
+
this.#strideSynced = applies;
|
|
492
|
+
this.#strideOverridden = !this.#strideSync;
|
|
493
|
+
this.#strideInPlace = measured.inPlace;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Hold every contributing locomotion clip of a blend against the ground the body covered.
|
|
498
|
+
*
|
|
499
|
+
* One body covers one ground speed, and each clip carries its own distance per clip-second, so
|
|
500
|
+
* each participant gets the rate its own stride implies. Without this the minority clip of a
|
|
501
|
+
* blend slides: it plays at its authored rate against a body moving at another clip's speed.
|
|
502
|
+
*/
|
|
503
|
+
#syncBlendParticipants(groundSpeed: number): void {
|
|
504
|
+
for (const [name, action] of this.#actions) {
|
|
505
|
+
if (!action.isScheduled() || action.getEffectiveWeight() <= 0) continue;
|
|
506
|
+
const ground = this.#measureOf(name).groundSpeed;
|
|
507
|
+
if (ground < CLIP_GROUND_FLOOR) continue;
|
|
508
|
+
const wanted = groundSpeed < STRIDE_SPEED_FLOOR ? STRIDE_RATE_MIN : groundSpeed / ground;
|
|
509
|
+
action.setEffectiveTimeScale(Math.min(STRIDE_RATE_MAX, Math.max(STRIDE_RATE_MIN, wanted)));
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
#playAction(action: AnimationAction, mode: AnimationMode, weight: number): void {
|
|
514
|
+
const once = mode === "once";
|
|
515
|
+
action
|
|
516
|
+
.reset()
|
|
517
|
+
.setLoop(once ? LoopOnce : LoopRepeat, once ? 1 : Number.POSITIVE_INFINITY)
|
|
518
|
+
.setEffectiveWeight(weight)
|
|
519
|
+
.play();
|
|
520
|
+
action.clampWhenFinished = once;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
#replayCurrent(action: AnimationAction, mode: AnimationMode): void {
|
|
524
|
+
for (const entry of this.#fadeOut) entry.action.stop();
|
|
525
|
+
this.#fadeOut = [];
|
|
526
|
+
for (const other of this.#actions.values()) {
|
|
527
|
+
if (other !== action) other.setEffectiveWeight(0).stop();
|
|
528
|
+
}
|
|
529
|
+
this.#playAction(action, mode, 1);
|
|
530
|
+
this.#mode = mode;
|
|
531
|
+
this.#finished = false;
|
|
532
|
+
this.#advancedFrames = 0;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
#playCurrent(action: AnimationAction, requestedMode: AnimationMode | undefined): void {
|
|
536
|
+
const mode = requestedMode ?? "loop";
|
|
537
|
+
if (!this.#finished && mode === this.#mode) return;
|
|
538
|
+
this.#replayCurrent(action, mode);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
#playNext(name: string, next: AnimationAction, options: IAnimationPlayOptions): void {
|
|
542
|
+
const fade = Math.max(0, options.fade ?? 0);
|
|
543
|
+
const once = options.mode === "once";
|
|
544
|
+
const from = fade > 0 && next.isScheduled() ? next.getEffectiveWeight() : 0;
|
|
545
|
+
// A loop that is still visible keeps its gait; explicit one-shots and mode changes replay.
|
|
546
|
+
const time = from > 0 && !once && next.loop === LoopRepeat ? next.time : 0;
|
|
547
|
+
|
|
548
|
+
// Every clip still contributing ramps out together, from the weight it currently holds.
|
|
549
|
+
//
|
|
550
|
+
// This used to hard-stop anything that was not `previous` and force `previous` to weight 1.
|
|
551
|
+
// Interrupting a blend therefore dropped the older clip's contribution in a single frame
|
|
552
|
+
// and snapped the outgoing clip up to full — a visible pop, and one that appeared only when
|
|
553
|
+
// transitions came faster than the fade, which is exactly when a character is reacting.
|
|
554
|
+
const outgoing: { action: AnimationAction; from: number }[] = [];
|
|
555
|
+
for (const action of this.#actions.values()) {
|
|
556
|
+
if (action === next) continue;
|
|
557
|
+
const weight = action.getEffectiveWeight();
|
|
558
|
+
if (action.isScheduled() && weight > 0) outgoing.push({ action, from: weight });
|
|
559
|
+
else action.setEffectiveWeight(0).stop();
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
this.#playAction(next, once ? "once" : "loop", fade > 0 && outgoing.length > 0 ? from : 1);
|
|
563
|
+
next.time = time;
|
|
564
|
+
if (outgoing.length === 0 || fade === 0) {
|
|
565
|
+
for (const entry of outgoing) entry.action.setEffectiveWeight(0).stop();
|
|
566
|
+
this.#fadeOut = [];
|
|
567
|
+
} else {
|
|
568
|
+
for (const entry of outgoing) entry.action.play();
|
|
569
|
+
this.#fadeOut = outgoing;
|
|
570
|
+
this.#fadeElapsed = 0;
|
|
571
|
+
this.#fadeDuration = fade;
|
|
572
|
+
this.#fadeInFrom = from;
|
|
573
|
+
}
|
|
574
|
+
this.#current = name;
|
|
575
|
+
this.#mode = once ? "once" : "loop";
|
|
576
|
+
this.#finished = false;
|
|
577
|
+
this.#advancedFrames = 0;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
play(name: string, options: IAnimationPlayOptions = {}): void {
|
|
581
|
+
this.#start(name, options);
|
|
582
|
+
this.#poseAtStart();
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Whether a clip has posed the skeleton. False until the first `play` or `playWeighted`, so a
|
|
587
|
+
* rig that never plays a clip stays observably in its bind pose.
|
|
588
|
+
*/
|
|
589
|
+
get posed(): boolean {
|
|
590
|
+
return this.#posed;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* Pose the skeleton from the clip that just started, before any `update`. `play` only schedules
|
|
595
|
+
* an action, and three applies a pose only inside `mixer.update`, so a character added to the
|
|
596
|
+
* scene on the frame it starts would otherwise render once in its bind pose (a T-pose) and snap
|
|
597
|
+
* to its clip on the next tick. A zero step applies the pose and advances nothing.
|
|
598
|
+
*/
|
|
599
|
+
#poseAtStart(): void {
|
|
600
|
+
if (this.#posed) return;
|
|
601
|
+
this.mixer.update(0);
|
|
602
|
+
this.#posed = true;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
#start(name: string, options: IAnimationPlayOptions): void {
|
|
606
|
+
const next = this.#actions.get(name);
|
|
607
|
+
if (next === undefined) throw new Error(`Unknown animation clip '${name}'.`);
|
|
608
|
+
// One owner at a time. A single-clip request takes the rig back from a weighted blend, exactly
|
|
609
|
+
// as it took it back from a crossfade.
|
|
610
|
+
const weighted = this.#blendTargets !== undefined;
|
|
611
|
+
this.#blendTargets = undefined;
|
|
612
|
+
this.#blendDuration = 0;
|
|
613
|
+
this.#blendStarts.clear();
|
|
614
|
+
if (this.#current === name) {
|
|
615
|
+
if (weighted) {
|
|
616
|
+
const time = next.time;
|
|
617
|
+
const keepPhase = this.#mode === "loop" && options.mode !== "once";
|
|
618
|
+
this.#playNext(name, next, options);
|
|
619
|
+
if (keepPhase) next.time = time;
|
|
620
|
+
} else this.#playCurrent(next, options.mode);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
this.#playNext(name, next, options);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Play several clips at once, at weights the game computed — the plumbing half of a locomotion
|
|
628
|
+
* blend space. The samples, the thresholds and the interpolation domain stay the game's: this
|
|
629
|
+
* takes the answer (`{ clip, weight }[]`) and owns what happens to the actions.
|
|
630
|
+
*
|
|
631
|
+
* What it guarantees, because every blend space needs the same four things:
|
|
632
|
+
*
|
|
633
|
+
* - **One mixer, one updater, one action per clip.** Nothing here creates an `AnimationMixer`.
|
|
634
|
+
* - **A still-contributing clip keeps its phase.** Returning to a walk mid-cycle does not
|
|
635
|
+
* restart it — the same convention `play` follows.
|
|
636
|
+
* - **An entering clip joins the gait.** Its normalized time is set to the dominant
|
|
637
|
+
* contributor's, so a walk→run change does not cross the feet mid-stride. Pass
|
|
638
|
+
* `phaseSync: false` for authored cycles that are deliberately out of phase with each other.
|
|
639
|
+
* - **Weights stay finite, non-negative and summing to 1.** Malformed input throws rather than
|
|
640
|
+
* producing a pose nobody can explain.
|
|
641
|
+
*
|
|
642
|
+
* `transition` is the bounded authored transition: weights move linearly towards the request
|
|
643
|
+
* over that many seconds, so a large instantaneous intent change cannot pop the pose, and `0`
|
|
644
|
+
* snaps them on the call. A clip that drops out of the request fades to zero and is then
|
|
645
|
+
* stopped, so repeated blends release their actions.
|
|
646
|
+
*
|
|
647
|
+
* Entries are played as loops. Events — a hit, a death, a reload — are `play`'s job.
|
|
648
|
+
*/
|
|
649
|
+
playWeighted(
|
|
650
|
+
entries: readonly { readonly clip: string; readonly weight: number }[],
|
|
651
|
+
options: { readonly transition?: number; readonly phaseSync?: boolean } = {},
|
|
652
|
+
): void {
|
|
653
|
+
const transition = options.transition ?? 0;
|
|
654
|
+
if (!Number.isFinite(transition) || transition < 0)
|
|
655
|
+
throw new Error("AnimationPlayer.playWeighted requires a finite non-negative transition.");
|
|
656
|
+
const targets = blendTargets(this.#actions, entries);
|
|
657
|
+
const phaseSync = options.phaseSync ?? true;
|
|
658
|
+
// Per-frame evaluators may repeat their answer; retain the original fade deadline.
|
|
659
|
+
if (
|
|
660
|
+
this.#blendTargets !== undefined &&
|
|
661
|
+
this.#blendDuration === transition &&
|
|
662
|
+
this.#blendTargets.size === targets.size &&
|
|
663
|
+
[...targets].every(([name, weight]) => this.#blendTargets?.get(name) === weight)
|
|
664
|
+
)
|
|
665
|
+
return;
|
|
666
|
+
// Any crossfade in flight stops owning the rig; its outgoing actions join the blend ramp below
|
|
667
|
+
// as participants with a target of zero, so they leave the same bounded way they arrived.
|
|
668
|
+
this.#fadeOut = [];
|
|
669
|
+
const phase = this.#dominantPhase();
|
|
670
|
+
let current = "";
|
|
671
|
+
let heaviest = -1;
|
|
672
|
+
for (const [name, action] of this.#actions) {
|
|
673
|
+
const target = targets.get(name);
|
|
674
|
+
if (target === undefined) continue;
|
|
675
|
+
if (target > heaviest) {
|
|
676
|
+
heaviest = target;
|
|
677
|
+
current = name;
|
|
678
|
+
}
|
|
679
|
+
this.#startBlendParticipant(action, phase, phaseSync);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
this.#blendStarts.clear();
|
|
683
|
+
let initialWeight = 0;
|
|
684
|
+
for (const [name, action] of this.#actions) {
|
|
685
|
+
if (!action.isScheduled()) continue;
|
|
686
|
+
const weight = action.getEffectiveWeight();
|
|
687
|
+
this.#blendStarts.set(name, weight);
|
|
688
|
+
initialWeight += weight;
|
|
689
|
+
}
|
|
690
|
+
this.#blendTargets = targets;
|
|
691
|
+
// With no contributing pose there is nothing to fade from: start at the requested blend.
|
|
692
|
+
this.#blendDuration = initialWeight > 0 ? transition : 0;
|
|
693
|
+
this.#blendElapsed = 0;
|
|
694
|
+
this.#current = current;
|
|
695
|
+
this.#mode = "loop";
|
|
696
|
+
this.#finished = false;
|
|
697
|
+
this.#advancedFrames = 0;
|
|
698
|
+
// A zero transition is the caller's request for these weights right now, not on the next
|
|
699
|
+
// frame; a positive one leaves them where the previous request left them and ramps from there.
|
|
700
|
+
this.#advanceBlend(0);
|
|
701
|
+
this.#poseAtStart();
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/**
|
|
705
|
+
* The normalized gait phase an entering clip joins: the dominant contributor's own.
|
|
706
|
+
*
|
|
707
|
+
* A returning action is deliberately left alone — its phase is the continuity the reversal
|
|
708
|
+
* repair exists to protect, and re-deriving it here would restart a walk the player is watching.
|
|
709
|
+
*/
|
|
710
|
+
#dominantPhase(): number {
|
|
711
|
+
let phase = 0;
|
|
712
|
+
let dominant = 0;
|
|
713
|
+
for (const action of this.#actions.values()) {
|
|
714
|
+
if (!action.isScheduled()) continue;
|
|
715
|
+
const weight = action.getEffectiveWeight();
|
|
716
|
+
if (weight > dominant) {
|
|
717
|
+
dominant = weight;
|
|
718
|
+
const duration = action.getClip().duration;
|
|
719
|
+
phase = duration > 0 ? action.time / duration : 0;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
return phase;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
#startBlendParticipant(action: AnimationAction, phase: number, phaseSync: boolean): void {
|
|
726
|
+
const weight = action.isScheduled() ? action.getEffectiveWeight() : 0;
|
|
727
|
+
const returning = action.isScheduled() && action.loop === LoopRepeat && !action.paused;
|
|
728
|
+
if (!returning) action.reset();
|
|
729
|
+
action.setLoop(LoopRepeat, Number.POSITIVE_INFINITY).setEffectiveWeight(weight);
|
|
730
|
+
action.clampWhenFinished = false;
|
|
731
|
+
action.play();
|
|
732
|
+
if (returning) return;
|
|
733
|
+
const duration = action.getClip().duration;
|
|
734
|
+
action.time = phaseSync && duration > 0 ? phase * duration : 0;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Move every contributing action one step towards its requested weight.
|
|
739
|
+
*
|
|
740
|
+
* `dt` is the frame's own time, so the ramp is linear in real time whatever the frame rate is.
|
|
741
|
+
*/
|
|
742
|
+
#advanceBlend(dt: number): void {
|
|
743
|
+
const targets = this.#blendTargets;
|
|
744
|
+
if (targets === undefined) return;
|
|
745
|
+
this.#blendElapsed = Math.min(this.#blendDuration, this.#blendElapsed + dt);
|
|
746
|
+
const progress = this.#blendDuration > 0 ? this.#blendElapsed / this.#blendDuration : 1;
|
|
747
|
+
let total = 0;
|
|
748
|
+
for (const [name, action] of this.#actions) {
|
|
749
|
+
if (!action.isScheduled()) continue;
|
|
750
|
+
const target = targets.get(name) ?? 0;
|
|
751
|
+
const from = this.#blendStarts.get(name) ?? 0;
|
|
752
|
+
const next = progress === 1 ? target : from + (target - from) * progress;
|
|
753
|
+
action.setEffectiveWeight(next);
|
|
754
|
+
total += next;
|
|
755
|
+
}
|
|
756
|
+
this.#settleBlend(targets, total);
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* Release every action the request no longer includes, then restore the sum-to-one invariant.
|
|
761
|
+
*
|
|
762
|
+
* The renormalization is what keeps the sum at 1 while a blend swaps one clip for another: the
|
|
763
|
+
* arriving clip grows from zero at the same rate the departing one shrinks, so without it the
|
|
764
|
+
* rig under-weights toward the bind pose for the length of the transition.
|
|
765
|
+
*/
|
|
766
|
+
#settleBlend(targets: ReadonlyMap<string, number>, total: number): void {
|
|
767
|
+
const scale = total > 0 && total !== 1 ? 1 / total : 1;
|
|
768
|
+
for (const [name, action] of this.#actions) {
|
|
769
|
+
if (!action.isScheduled()) continue;
|
|
770
|
+
if ((targets.get(name) ?? 0) === 0 && action.getEffectiveWeight() === 0) action.stop();
|
|
771
|
+
else if (scale !== 1) action.setEffectiveWeight(action.getEffectiveWeight() * scale);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
update(dt: number): void {
|
|
776
|
+
if (!Number.isFinite(dt) || dt < 0)
|
|
777
|
+
throw new Error("AnimationPlayer.update requires a finite non-negative dt.");
|
|
778
|
+
// Read before mixer.update(): the "finished" listener fires inside it for a completing
|
|
779
|
+
// once-clip, and that final frame still counts as advancement.
|
|
780
|
+
const wasFinished = this.#finished;
|
|
781
|
+
const before = this.mixer.time;
|
|
782
|
+
this.mixer.update(dt);
|
|
783
|
+
if (this.#fadeOut.length > 0) {
|
|
784
|
+
this.#fadeElapsed = Math.min(this.#fadeDuration, this.#fadeElapsed + dt);
|
|
785
|
+
const linear = this.#fadeDuration === 0 ? 1 : this.#fadeElapsed / this.#fadeDuration;
|
|
786
|
+
// Smoothstep rather than linear. A linear weight ramp changes the pose's velocity
|
|
787
|
+
// instantly at both ends, which reads as a corner on the character even when the fade
|
|
788
|
+
// duration is right.
|
|
789
|
+
const progress = linear * linear * (3 - 2 * linear);
|
|
790
|
+
for (const entry of this.#fadeOut) {
|
|
791
|
+
entry.action.setEffectiveWeight(entry.from * (1 - progress));
|
|
792
|
+
}
|
|
793
|
+
this.#actions
|
|
794
|
+
.get(this.#current ?? "")
|
|
795
|
+
?.setEffectiveWeight(this.#fadeInFrom + (1 - this.#fadeInFrom) * progress);
|
|
796
|
+
if (linear >= 1) {
|
|
797
|
+
for (const entry of this.#fadeOut) entry.action.setEffectiveWeight(0).stop();
|
|
798
|
+
this.#fadeOut = [];
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
// three advances mixer.time unconditionally, finished or not: past a held last frame the
|
|
802
|
+
// pose is frozen, so counting there would report idle frames as animation progress.
|
|
803
|
+
if (this.#current !== undefined && !wasFinished && this.mixer.time !== before)
|
|
804
|
+
this.#advancedFrames += 1;
|
|
805
|
+
this.#advanceBlend(dt);
|
|
806
|
+
this.#syncStride(dt);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
stop(): void {
|
|
810
|
+
this.mixer.stopAllAction();
|
|
811
|
+
this.#current = undefined;
|
|
812
|
+
this.#mode = "loop";
|
|
813
|
+
this.#finished = false;
|
|
814
|
+
this.#advancedFrames = 0;
|
|
815
|
+
this.#fadeOut = [];
|
|
816
|
+
this.#blendTargets = undefined;
|
|
817
|
+
this.#blendDuration = 0;
|
|
818
|
+
this.#blendElapsed = 0;
|
|
819
|
+
this.#blendStarts.clear();
|
|
820
|
+
this.#resetStride();
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
#resetStride(): void {
|
|
824
|
+
this.#hasLastRootPosition = false;
|
|
825
|
+
this.#strideGroundSpeed = 0;
|
|
826
|
+
this.#strideRate = 1;
|
|
827
|
+
this.#strideSynced = false;
|
|
828
|
+
this.#strideOverridden = false;
|
|
829
|
+
this.#strideInPlace = false;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
dispose(): void {
|
|
833
|
+
this.stop();
|
|
834
|
+
this.mixer.uncacheRoot(this.mixer.getRoot());
|
|
835
|
+
this.mixer.removeEventListener("finished", this.#onFinished);
|
|
836
|
+
this.#actions.clear();
|
|
837
|
+
this.#clips.clear();
|
|
838
|
+
this.#clipGroundSpeed.clear();
|
|
839
|
+
this.#preparation = undefined;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** Reused so a per-frame stride read costs no allocation. See PRD-189. */
|
|
844
|
+
const scratchWorld = new Vector3();
|
|
845
|
+
const scratchScale = new Vector3();
|
|
846
|
+
const scratchMatrixWorld = new Matrix4();
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* Validate one weighted request into normalized, non-zero target weights.
|
|
850
|
+
*
|
|
851
|
+
* Fail closed on everything malformed — an unknown clip, a non-finite or negative weight, a clip
|
|
852
|
+
* listed twice, a request with nothing in it — because a blend that silently drops a sample reads
|
|
853
|
+
* as a rig problem long after the request that caused it. Zero weights are dropped rather than
|
|
854
|
+
* rejected: an evaluation over a grid naturally reports every cell it did not pick, and those
|
|
855
|
+
* clips simply leave the blend. The remaining weights are scaled to sum to 1, so the engine holds
|
|
856
|
+
* the invariant the caller does not have to.
|
|
857
|
+
*/
|
|
858
|
+
function blendTargets(
|
|
859
|
+
actions: ReadonlyMap<string, AnimationAction>,
|
|
860
|
+
entries: readonly { readonly clip: string; readonly weight: number }[],
|
|
861
|
+
): Map<string, number> {
|
|
862
|
+
if (entries.length === 0)
|
|
863
|
+
throw new Error("AnimationPlayer.playWeighted requires at least one clip.");
|
|
864
|
+
const targets = new Map<string, number>();
|
|
865
|
+
const seen = new Set<string>();
|
|
866
|
+
let largest = 0;
|
|
867
|
+
for (const entry of entries) {
|
|
868
|
+
if (!actions.has(entry.clip)) throw new Error(`Unknown animation clip '${entry.clip}'.`);
|
|
869
|
+
if (!Number.isFinite(entry.weight) || entry.weight < 0)
|
|
870
|
+
throw new Error(
|
|
871
|
+
`AnimationPlayer.playWeighted: '${entry.clip}' has weight ${entry.weight}; weights must be finite and non-negative.`,
|
|
872
|
+
);
|
|
873
|
+
if (seen.has(entry.clip))
|
|
874
|
+
throw new Error(
|
|
875
|
+
`AnimationPlayer.playWeighted: '${entry.clip}' is listed twice; give each clip one weight.`,
|
|
876
|
+
);
|
|
877
|
+
seen.add(entry.clip);
|
|
878
|
+
if (entry.weight === 0) continue;
|
|
879
|
+
targets.set(entry.clip, entry.weight);
|
|
880
|
+
largest = Math.max(largest, entry.weight);
|
|
881
|
+
}
|
|
882
|
+
if (!(largest > 0))
|
|
883
|
+
throw new Error("AnimationPlayer.playWeighted requires at least one clip above weight zero.");
|
|
884
|
+
let total = 0;
|
|
885
|
+
for (const weight of targets.values()) total += weight / largest;
|
|
886
|
+
for (const [name, weight] of targets) targets.set(name, weight / largest / total);
|
|
887
|
+
return targets;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
function requiredClipNames(value: IAnimationPlayerOptions["requiredClips"]): readonly string[] {
|
|
891
|
+
if (value === undefined) return [];
|
|
892
|
+
const names = Array.isArray(value) ? value : Object.values(value);
|
|
893
|
+
if (!names.every((name): name is string => typeof name === "string" && name.length > 0))
|
|
894
|
+
throw new Error("AnimationPlayer: requiredClips must contain non-empty strings.");
|
|
895
|
+
return names;
|
|
896
|
+
}
|