@vgai/engine 0.2.0 → 0.4.0-canary.20260715.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 (123) hide show
  1. package/README.md +3 -1
  2. package/package.json +24 -4
  3. package/schemas/engine-api.json +124 -0
  4. package/schemas/engine-api.md +53 -0
  5. package/schemas/engine-capabilities.json +124 -0
  6. package/schemas/inputmap.schema.json +314 -0
  7. package/schemas/mat.schema.json +286 -0
  8. package/schemas/prefab.schema.json +10148 -0
  9. package/schemas/scn2d.schema.json +475 -0
  10. package/schemas/vgai-game.schema.json +383 -0
  11. package/schemas/vscn.schema.json +11007 -0
  12. package/src/adapter/{world-kind.ts → adapter-surface.ts} +6 -6
  13. package/src/adapter/authoring.ts +77 -0
  14. package/src/adapter/first-party-systems.ts +23 -34
  15. package/src/adapter/game-adapter.ts +8 -8
  16. package/src/adapter/host-context.ts +2 -4
  17. package/src/adapter/index.ts +4 -4
  18. package/src/adapter/system-adapter.ts +88 -22
  19. package/src/adapter/vgai-scene-game-adapter.ts +244 -194
  20. package/src/animation/anim-graph-types.ts +12 -43
  21. package/src/animation/animation-clock.ts +479 -0
  22. package/src/animation/camera-ownership.ts +467 -0
  23. package/src/animation/cinematic-cues.ts +451 -0
  24. package/src/animation/clip-map.ts +41 -0
  25. package/src/animation/gsap-registration.ts +184 -0
  26. package/src/animation/theatre-clock-binding.ts +111 -0
  27. package/src/animation/theatre-director.ts +347 -0
  28. package/src/animation/theatre-object-binding.ts +661 -0
  29. package/src/animation/xstate-animation-binding.ts +436 -0
  30. package/src/animation/xstate-animation-meta.ts +319 -0
  31. package/src/audio/index.ts +39 -7
  32. package/src/audio/tone-clock-binding.ts +98 -0
  33. package/src/audio/tone-context.ts +129 -0
  34. package/src/audio/tone-offline-render.ts +167 -0
  35. package/src/audio/wav-encode.ts +119 -0
  36. package/src/character/cloth-sim.ts +533 -0
  37. package/src/character/spring-chain.ts +307 -0
  38. package/src/core/game-loop.ts +57 -2
  39. package/src/core/seeded-random.ts +161 -0
  40. package/src/core/system-runner.ts +20 -3
  41. package/src/core/types.ts +50 -0
  42. package/src/data/data-asset.ts +167 -0
  43. package/src/data/data-check-core.ts +242 -0
  44. package/src/data/data-ref.ts +145 -0
  45. package/src/data/vite-plugin-data.ts +290 -0
  46. package/src/dev/performance-profiler.ts +213 -0
  47. package/src/dev/webgl-gpu-timer.ts +53 -0
  48. package/src/ecs/component-manager.ts +45 -12
  49. package/src/ecs/game-component.ts +95 -11
  50. package/src/humanoid/bake.operation.ts +326 -0
  51. package/src/humanoid/body.ts +663 -0
  52. package/src/humanoid/clips.ts +149 -0
  53. package/src/humanoid/compose.ts +209 -0
  54. package/src/humanoid/generate.ts +189 -0
  55. package/src/humanoid/index.ts +36 -0
  56. package/src/humanoid/schema.ts +108 -0
  57. package/src/humanoid/skeleton.ts +345 -0
  58. package/src/index.ts +48 -0
  59. package/src/input/input-manager.ts +1886 -33
  60. package/src/input/input-types.ts +158 -3
  61. package/src/input/prompt-labels.ts +122 -0
  62. package/src/input/rebind-controller.ts +105 -0
  63. package/src/input/schema.ts +206 -52
  64. package/src/manifest/index.ts +5 -5
  65. package/src/manifest/load.ts +125 -72
  66. package/src/manifest/schema.ts +362 -255
  67. package/src/react/game-state.tsx +135 -32
  68. package/src/react/root-adapter.tsx +49 -0
  69. package/src/react/unmanaged-root-detector.ts +66 -0
  70. package/src/react/use-data.ts +124 -0
  71. package/src/react/use-selection.tsx +135 -0
  72. package/src/runtime/create-runtime.ts +112 -273
  73. package/src/runtime/debug-bridge.ts +483 -0
  74. package/src/runtime/debug-registry.ts +856 -0
  75. package/src/runtime/game.ts +342 -93
  76. package/src/runtime/gameplay-rng-trap.ts +134 -0
  77. package/src/runtime/input-router.ts +7 -7
  78. package/src/runtime/mount-game.ts +40 -38
  79. package/src/runtime/mount-manifest.ts +169 -37
  80. package/src/runtime/render-audio-control.ts +168 -0
  81. package/src/runtime/render-control.ts +522 -0
  82. package/src/runtime/render-seed.ts +79 -0
  83. package/src/runtime/state-bridge.ts +24 -10
  84. package/src/runtime/types.ts +110 -33
  85. package/src/scene/asset-loaders.ts +10 -36
  86. package/src/scene/asset-paths.ts +0 -2
  87. package/src/scene/asset-ref-check.ts +248 -0
  88. package/src/scene/asset-registry.ts +22 -0
  89. package/src/scene/component-registry.ts +14 -3
  90. package/src/scene/defaults.ts +1 -0
  91. package/src/scene/light-camera-factory.ts +11 -3
  92. package/src/scene/parse.ts +133 -0
  93. package/src/scene/scene-apply.ts +55 -4
  94. package/src/scene/scene-loader.ts +91 -123
  95. package/src/scene/scene-types.ts +0 -1
  96. package/src/scene/schema/animation.ts +30 -79
  97. package/src/scene/schema/entity.ts +20 -0
  98. package/src/scene/schema/index.ts +2 -46
  99. package/src/scene/schema/light.ts +16 -1
  100. package/src/scene/schema/material.ts +96 -91
  101. package/src/scene/schema/scene-file.ts +1 -7
  102. package/src/scene/user-data.ts +22 -10
  103. package/src/setup/setup-renderer.ts +10 -3
  104. package/src/tools/define-tool.ts +191 -0
  105. package/src/world2d/authoring-2d.ts +17 -1
  106. package/src/world2d/collision-2d.ts +1 -1
  107. package/src/world2d/pixi-game-adapter.ts +19 -17
  108. package/src/world2d/scene2d-loader.ts +1 -0
  109. package/src/world2d/types.ts +8 -2
  110. package/src/animation/anim-graph.ts +0 -406
  111. package/src/animation/anim-system.ts +0 -28
  112. package/src/animation/property-track.ts +0 -178
  113. package/src/animation/schema.ts +0 -204
  114. package/src/audio/ambient.ts +0 -300
  115. package/src/audio/impacts.ts +0 -212
  116. package/src/audio/movement.ts +0 -140
  117. package/src/audio/musical.ts +0 -200
  118. package/src/audio/ui-sounds.ts +0 -171
  119. package/src/audio/vehicle.ts +0 -235
  120. package/src/audio/weapons.ts +0 -152
  121. package/src/runtime/scene-ui-bridge.ts +0 -86
  122. package/src/runtime/scene-ui-data.ts +0 -119
  123. package/src/scene/schema/ui.ts +0 -602
@@ -1,406 +0,0 @@
1
- import * as THREE from 'three';
2
- import type {
3
- AnimGraphFile,
4
- AnimLayer,
5
- AnimState,
6
- AnimTransition,
7
- TransitionCondition,
8
- } from './anim-graph-types';
9
- import { evaluateBlendTree } from './blend-node';
10
-
11
- /**
12
- * Runtime animation graph for a single entity.
13
- *
14
- * This is the core custom code that Three.js doesn't provide.
15
- * Three.js AnimationMixer handles clip playback and crossfading.
16
- * This adds: state machines, parameter-driven transitions, blend trees.
17
- *
18
- * Weight management: all AnimationActions are pre-played at creation with
19
- * weight 0. Weights are set explicitly every frame — we never use Three.js's
20
- * fadeIn/fadeOut, which can cause total weight to dip below 1.0 and flash
21
- * the bind pose (T-pose).
22
- *
23
- * Usage:
24
- * const graph = new AnimGraph(mixer, graphData, clips);
25
- * graph.setParameter('speed', 5.0);
26
- * graph.update(dt); // call each frame
27
- */
28
- export class AnimGraph {
29
- private mixer: THREE.AnimationMixer;
30
- private layers: LayerRuntime[] = [];
31
- private parameters = new Map<string, number | boolean>();
32
- private triggers = new Set<string>();
33
-
34
- constructor(
35
- mixer: THREE.AnimationMixer,
36
- data: AnimGraphFile,
37
- clips: Map<string, THREE.AnimationClip>,
38
- ) {
39
- this.mixer = mixer;
40
-
41
- // Initialize parameters with defaults
42
- for (const [name, param] of Object.entries(data.parameters)) {
43
- this.parameters.set(name, param.default);
44
- }
45
-
46
- // Create runtime for each layer
47
- for (const layerDef of data.layers) {
48
- this.layers.push(new LayerRuntime(mixer, layerDef, clips));
49
- }
50
- }
51
-
52
- /** The names of all declared parameters (for the AnimationAdapter to enumerate). */
53
- parameterNames(): string[] {
54
- return [...this.parameters.keys()];
55
- }
56
-
57
- /** Set a float/int/bool parameter */
58
- setParameter(name: string, value: number | boolean) {
59
- this.parameters.set(name, value);
60
- }
61
-
62
- /** Get a parameter value */
63
- getParameter(name: string): number | boolean | undefined {
64
- return this.parameters.get(name);
65
- }
66
-
67
- /** Fire a trigger (auto-resets after consumed by a transition) */
68
- trigger(name: string) {
69
- this.triggers.add(name);
70
- }
71
-
72
- /** Get the current state name for a layer (default: first layer) */
73
- getCurrentState(layerIndex = 0): string {
74
- return this.layers[layerIndex]?.currentState ?? '';
75
- }
76
-
77
- /** Update the animation graph. Call once per frame. */
78
- update(dt: number) {
79
- // Triggers persist until a transition actually consumes them — we do NOT
80
- // clear every frame. A trigger fired mid-crossfade (when no transition can
81
- // fire) survives until the layer is ready to act on it.
82
- const consumed = new Set<string>();
83
- for (const layer of this.layers) {
84
- layer.update(dt, this.parameters, this.triggers, consumed);
85
- }
86
-
87
- // Clear only triggers that were consumed by a transition this frame.
88
- for (const name of consumed) {
89
- this.triggers.delete(name);
90
- }
91
-
92
- // Advance the mixer
93
- this.mixer.update(dt);
94
- }
95
- }
96
-
97
- /**
98
- * Runtime state for a single animation layer.
99
- */
100
- class LayerRuntime {
101
- private mixer: THREE.AnimationMixer;
102
- private states: Map<string, AnimState>;
103
- private transitions: AnimTransition[];
104
- private actionMap = new Map<string, THREE.AnimationAction>();
105
- currentState: string;
106
- private previousState = '';
107
- private stateTime = 0;
108
- private stateDuration = 0;
109
- private transitioning = false;
110
- private transitionElapsed = 0;
111
- private transitionDuration = 0;
112
-
113
- constructor(
114
- mixer: THREE.AnimationMixer,
115
- layerDef: AnimLayer,
116
- clips: Map<string, THREE.AnimationClip>,
117
- ) {
118
- this.mixer = mixer;
119
- this.states = new Map(Object.entries(layerDef.states));
120
- this.transitions = layerDef.transitions;
121
- this.currentState = layerDef.defaultState;
122
-
123
- // Collect the (loop, speed) config each clip name is played with. A clip
124
- // name is a key into a single shared THREE.AnimationAction (ensureAction
125
- // dedupes by name), so two states — or a state and a blend-tree child —
126
- // that reference the same clip with different loop/speed would silently
127
- // let whichever state was processed first win, and the other's config
128
- // would be dropped with no signal. Per-state clip config is deferred
129
- // (no real need for it yet) — the correct behavior for now is a loud
130
- // error at graph load, not silent last-write-wins.
131
- const clipConfigs = new Map<string, { loop: boolean; speed: number; state: string }>();
132
- for (const [stateName, state] of this.states) {
133
- if (state.clip) {
134
- this.registerClipConfig(
135
- clipConfigs,
136
- state.clip,
137
- state.loop ?? true,
138
- state.speed ?? 1,
139
- stateName,
140
- );
141
- }
142
- if (state.blendTree) {
143
- for (const child of state.blendTree.children) {
144
- this.registerClipConfig(clipConfigs, child.clip, true, 1, stateName);
145
- }
146
- }
147
- }
148
-
149
- // Create AnimationActions for all referenced clips.
150
- // All actions are played immediately at weight 0 — they stay active in the
151
- // mixer but contribute nothing visually until we raise their weight.
152
- for (const [clipName, config] of clipConfigs) {
153
- this.ensureAction(clipName, clips, config.loop, config.speed);
154
- }
155
-
156
- // Start default state
157
- this.enterState(this.currentState, new Map());
158
- }
159
-
160
- /** Record a clip's (loop, speed) config, throwing if a prior state disagrees. */
161
- private registerClipConfig(
162
- configs: Map<string, { loop: boolean; speed: number; state: string }>,
163
- clipName: string,
164
- loop: boolean,
165
- speed: number,
166
- stateName: string,
167
- ) {
168
- const existing = configs.get(clipName);
169
- if (existing && (existing.loop !== loop || existing.speed !== speed)) {
170
- throw new Error(
171
- `AnimGraph: clip "${clipName}" is configured inconsistently across states — ` +
172
- `state "${existing.state}" uses loop=${existing.loop}/speed=${existing.speed}, ` +
173
- `but state "${stateName}" uses loop=${loop}/speed=${speed}. ` +
174
- `Per-state clip config is not supported: every state (and blend-tree child) that ` +
175
- `plays a given clip must agree on its loop/speed.`,
176
- );
177
- }
178
- if (!existing) configs.set(clipName, { loop, speed, state: stateName });
179
- }
180
-
181
- private ensureAction(
182
- clipName: string,
183
- clips: Map<string, THREE.AnimationClip>,
184
- loop: boolean,
185
- speed: number,
186
- ) {
187
- if (this.actionMap.has(clipName)) return;
188
- const clip = clips.get(clipName);
189
- if (!clip) return;
190
-
191
- const action = this.mixer.clipAction(clip);
192
- action.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, Infinity);
193
- action.clampWhenFinished = !loop;
194
- action.timeScale = speed;
195
- action.setEffectiveWeight(0);
196
- action.play();
197
- this.actionMap.set(clipName, action);
198
- }
199
-
200
- private enterState(stateName: string, parameters: Map<string, number | boolean>) {
201
- const state = this.states.get(stateName);
202
- if (!state) return;
203
-
204
- this.currentState = stateName;
205
- this.stateTime = 0;
206
- this.transitioning = false;
207
-
208
- // Zero all, then set the entering state to full weight
209
- this.zeroAllWeights();
210
-
211
- if (state.clip) {
212
- const action = this.actionMap.get(state.clip);
213
- if (action) {
214
- action.reset();
215
- action.setEffectiveWeight(1);
216
- action.play();
217
- this.stateDuration = action.getClip().duration;
218
- }
219
- }
220
-
221
- if (state.blendTree) {
222
- const weights = evaluateBlendTree(state.blendTree, parameters);
223
- this.setWeights(weights, 1);
224
- const heaviest = weights.reduce((a, b) => (b.weight > a.weight ? b : a), weights[0]!);
225
- const action = this.actionMap.get(heaviest.clip);
226
- this.stateDuration = action?.getClip().duration ?? 1;
227
- }
228
- }
229
-
230
- /** Zero all action weights. */
231
- private zeroAllWeights() {
232
- for (const action of this.actionMap.values()) {
233
- action.setEffectiveWeight(0);
234
- }
235
- }
236
-
237
- /** Set weights for a list of clip/weight pairs, multiplied by a scale factor. */
238
- private setWeights(weights: { clip: string; weight: number }[], scale: number) {
239
- for (const { clip, weight } of weights) {
240
- const action = this.actionMap.get(clip);
241
- if (action) {
242
- action.setEffectiveWeight(weight * scale);
243
- }
244
- }
245
- }
246
-
247
- /** Get the weight list for a state (single clip at weight 1, or blend tree evaluated). */
248
- private getStateWeights(
249
- stateName: string,
250
- parameters: Map<string, number | boolean>,
251
- ): { clip: string; weight: number }[] {
252
- const state = this.states.get(stateName);
253
- if (!state) return [];
254
- if (state.clip) return [{ clip: state.clip, weight: 1 }];
255
- if (state.blendTree) return evaluateBlendTree(state.blendTree, parameters);
256
- return [];
257
- }
258
-
259
- update(
260
- dt: number,
261
- parameters: Map<string, number | boolean>,
262
- triggers: Set<string>,
263
- consumed: Set<string>,
264
- ) {
265
- this.stateTime += dt;
266
- const normalizedTime = this.stateDuration > 0 ? this.stateTime / this.stateDuration : 1;
267
-
268
- // Zero all weights, then set them based on current (and previous) state.
269
- // This guarantees total weight = 1.0 every frame — no bind-pose bleed.
270
- this.zeroAllWeights();
271
-
272
- if (this.transitioning) {
273
- this.transitionElapsed += dt;
274
- const alpha = Math.min(this.transitionElapsed / this.transitionDuration, 1);
275
-
276
- // Crossfade: outgoing * (1 - alpha) + incoming * alpha — sums to exactly 1.0
277
- this.setWeights(this.getStateWeights(this.previousState, parameters), 1 - alpha);
278
- this.setWeights(this.getStateWeights(this.currentState, parameters), alpha);
279
-
280
- if (alpha >= 1) {
281
- this.transitioning = false;
282
- }
283
- return;
284
- }
285
-
286
- // Not transitioning — current state at full weight
287
- this.setWeights(this.getStateWeights(this.currentState, parameters), 1);
288
-
289
- // Check transitions
290
- for (const transition of this.transitions) {
291
- // Match: exact state or wildcard
292
- if (transition.from !== '*' && transition.from !== this.currentState) continue;
293
- // A wildcard transition must never re-enter the state we're already in —
294
- // otherwise a wildcard whose condition stays true fires every single
295
- // frame (performTransition resets the action to time 0 each time), so
296
- // the state is "entered" over and over and its animation never advances
297
- // past frame 0. An explicit from:X→to:X self-transition is a deliberate
298
- // restart and is allowed to fire.
299
- if (transition.from === '*' && transition.to === this.currentState) continue;
300
-
301
- // Check exit time
302
- if (transition.exitTime !== undefined && normalizedTime < transition.exitTime) continue;
303
-
304
- // Check conditions
305
- if (
306
- transition.conditions &&
307
- !this.checkConditions(transition.conditions, parameters, triggers)
308
- ) {
309
- continue;
310
- }
311
-
312
- // Transition! Mark any trigger conditions as consumed so the graph
313
- // clears them after all layers have had a chance to react this frame.
314
- if (transition.conditions) {
315
- for (const cond of transition.conditions) {
316
- if (cond.op === 'trigger') consumed.add(cond.param);
317
- }
318
- }
319
- this.performTransition(transition, parameters);
320
- return;
321
- }
322
- }
323
-
324
- private checkConditions(
325
- conditions: TransitionCondition[],
326
- parameters: Map<string, number | boolean>,
327
- triggers: Set<string>,
328
- ): boolean {
329
- for (const cond of conditions) {
330
- if (cond.op === 'trigger') {
331
- if (!triggers.has(cond.param)) return false;
332
- continue;
333
- }
334
-
335
- const paramVal = parameters.get(cond.param);
336
- if (paramVal === undefined) return false;
337
-
338
- const a = Number(paramVal);
339
- const b = Number(cond.value ?? 0);
340
-
341
- switch (cond.op) {
342
- case '>':
343
- if (!(a > b)) return false;
344
- break;
345
- case '<':
346
- if (!(a < b)) return false;
347
- break;
348
- case '>=':
349
- if (!(a >= b)) return false;
350
- break;
351
- case '<=':
352
- if (!(a <= b)) return false;
353
- break;
354
- case '==':
355
- if (paramVal !== cond.value && a !== b) return false;
356
- break;
357
- case '!=':
358
- if (paramVal === cond.value || a === b) return false;
359
- break;
360
- }
361
- }
362
- return true;
363
- }
364
-
365
- private performTransition(transition: AnimTransition, parameters: Map<string, number | boolean>) {
366
- const toState = this.states.get(transition.to);
367
- if (!toState) return;
368
-
369
- this.previousState = this.currentState;
370
- this.currentState = transition.to;
371
- this.stateTime = 0;
372
- this.transitioning = true;
373
- this.transitionElapsed = 0;
374
- this.transitionDuration = transition.duration;
375
-
376
- // Reset incoming actions to time=0 so they start fresh.
377
- // No fadeIn/fadeOut — weights are managed explicitly in update().
378
- if (toState.clip) {
379
- const action = this.actionMap.get(toState.clip);
380
- if (action) {
381
- action.reset();
382
- action.play();
383
- }
384
- }
385
- if (toState.blendTree) {
386
- for (const child of toState.blendTree.children) {
387
- const action = this.actionMap.get(child.clip);
388
- if (action) {
389
- action.reset();
390
- action.play();
391
- }
392
- }
393
- }
394
-
395
- // Estimate state duration for exitTime calculations
396
- if (toState.clip) {
397
- const action = this.actionMap.get(toState.clip);
398
- this.stateDuration = action?.getClip().duration ?? 1;
399
- } else if (toState.blendTree) {
400
- const weights = evaluateBlendTree(toState.blendTree, parameters);
401
- const heaviest = weights.reduce((a, b) => (b.weight > a.weight ? b : a), weights[0]!);
402
- const action = this.actionMap.get(heaviest.clip);
403
- this.stateDuration = action?.getClip().duration ?? 1;
404
- }
405
- }
406
- }
@@ -1,28 +0,0 @@
1
- import type * as THREE from 'three';
2
- import type { AnimGraph } from './anim-graph';
3
-
4
- /**
5
- * Registry of active animation graphs, keyed by Object3D (the entity).
6
- *
7
- * AnimGraph wraps a THREE.AnimationMixer (a class instance), so it can't live in
8
- * a flat data store — we keep a simple Map<Object3D, AnimGraph> and update each
9
- * one every frame. Each runtime owns its own map (see createGameRuntime) so that
10
- * multiple concurrent runtimes never cross-contaminate each other's graphs.
11
- *
12
- * Usage:
13
- * const animGraphs: AnimGraphMap = new Map();
14
- * animGraphs.set(playerObject3D, new AnimGraph(mixer, data, clips));
15
- * // In system runner:
16
- * systems.add('animation', (dt) => animationSystem(animGraphs, dt));
17
- */
18
- export type AnimGraphMap = Map<THREE.Object3D, AnimGraph>;
19
-
20
- /**
21
- * Updates all active animation graphs.
22
- * Call this in the ANIMATION phase.
23
- */
24
- export function animationSystem(graphs: AnimGraphMap, dt: number) {
25
- for (const graph of graphs.values()) {
26
- graph.update(dt);
27
- }
28
- }
@@ -1,178 +0,0 @@
1
- /**
2
- * F5 — Declarative property tracks (deterministic timeline).
3
- * docs/VSCN-STRUCTURAL-GAPS-DESIGN.md
4
- *
5
- * A property track is DATA: a pure function of time (keyframes + named
6
- * easing), never behavior. `samplePropertyTrack` is the pure sampler (time →
7
- * value) the unit test asserts determinism against directly.
8
- * `PropertyTrackRunner` is a thin stateful shell that accumulates elapsed
9
- * time from the fixed-step `dt` already threaded through the scene tick (the
10
- * SAME `dt` the AnimationMixers get — see scene-loader.ts's `tickFns`) and
11
- * writes the sampled value onto the target Object3D property each frame. It
12
- * introduces NO new clock: a paused frame passes `dt = 0`, and time simply
13
- * does not advance — pause/timeScale are honored for free.
14
- *
15
- * Anything state-dependent ("move WHEN the player steps on it") stays a
16
- * GameComponent, which may start/stop/seek a track. This module only adds the
17
- * time→value data + a deterministic evaluator (G1 — data, not behavior).
18
- */
19
- import type * as THREE from 'three';
20
- import { log } from '../dev/logger';
21
- import type { PropertyTrack, PropertyTrackKeyframe } from '../scene/schema/animation';
22
- import type { UIEasing } from '../scene/schema/ui';
23
-
24
- // ---------------------------------------------------------------------------
25
- // Easing — mirrors packages/scene-ui/src/animation.ts's `ease` (same enum,
26
- // same semantics). NOT imported from there: scene-ui depends on the engine,
27
- // so importing it back here would be circular. A ~10-line parallel
28
- // implementation over the shared UIEasingSchema enum is the correct fix.
29
- // ---------------------------------------------------------------------------
30
-
31
- function ease(t: number, kind: UIEasing | undefined): number {
32
- const x = Math.max(0, Math.min(1, t));
33
- switch (kind) {
34
- case 'ease-in':
35
- return x * x;
36
- case 'ease-out':
37
- return 1 - (1 - x) * (1 - x);
38
- case 'ease-in-out':
39
- return x < 0.5 ? 2 * x * x : 1 - (-2 * x + 2) ** 2 / 2;
40
- case 'step':
41
- return x < 1 ? 0 : 1; // hold the previous value until the next keyframe
42
- default:
43
- return x; // linear
44
- }
45
- }
46
-
47
- /**
48
- * Sample a track at `time` seconds from track start. `time` is assumed
49
- * already wrapped/clamped by the caller (see {@link PropertyTrackRunner});
50
- * this function is a pure, side-effect-free keyframe interpolation and is
51
- * safe to call directly from tests.
52
- */
53
- export function samplePropertyTrack(track: PropertyTrack, time: number): number {
54
- const kfs = track.keyframes;
55
- if (kfs.length === 0) return 0;
56
- const first = kfs[0] as PropertyTrackKeyframe;
57
- if (time <= first.time) return first.value;
58
- const last = kfs[kfs.length - 1] as PropertyTrackKeyframe;
59
- if (time >= last.time) return last.value;
60
- for (let i = 0; i < kfs.length - 1; i++) {
61
- const k0 = kfs[i] as PropertyTrackKeyframe;
62
- const k1 = kfs[i + 1] as PropertyTrackKeyframe;
63
- if (time >= k0.time && time <= k1.time) {
64
- const span = k1.time - k0.time || 1;
65
- const raw = (time - k0.time) / span;
66
- const t = ease(raw, k0.easing);
67
- return k0.value + (k1.value - k0.value) * t;
68
- }
69
- }
70
- return last.value;
71
- }
72
-
73
- /** Wrap/clamp elapsed time against a track's `duration`/`loop`. */
74
- function resolveTrackTime(track: PropertyTrack, elapsed: number): number {
75
- if (track.duration <= 0) return elapsed;
76
- if (track.loop) return elapsed % track.duration;
77
- return Math.min(elapsed, track.duration);
78
- }
79
-
80
- type TargetSetter = (object3D: THREE.Object3D, value: number, warnOnce: () => void) => void;
81
-
82
- // Allowlisted target → setter. Keys are exactly PropertyTrackTargetSchema's
83
- // enum values — the allowlist IS the schema; no arbitrary path resolution.
84
- const TARGET_SETTERS: Record<string, TargetSetter> = {
85
- 'position.x': (o, v) => {
86
- o.position.x = v;
87
- },
88
- 'position.y': (o, v) => {
89
- o.position.y = v;
90
- },
91
- 'position.z': (o, v) => {
92
- o.position.z = v;
93
- },
94
- 'rotation.x': (o, v) => {
95
- o.rotation.x = v;
96
- },
97
- 'rotation.y': (o, v) => {
98
- o.rotation.y = v;
99
- },
100
- 'rotation.z': (o, v) => {
101
- o.rotation.z = v;
102
- },
103
- 'scale.x': (o, v) => {
104
- o.scale.x = v;
105
- },
106
- 'scale.y': (o, v) => {
107
- o.scale.y = v;
108
- },
109
- 'scale.z': (o, v) => {
110
- o.scale.z = v;
111
- },
112
- 'material.opacity': (o, v, warnOnce) => {
113
- const mesh = o as THREE.Mesh;
114
- const material = mesh.material as THREE.Material | THREE.Material[] | undefined;
115
- if (!material) {
116
- warnOnce();
117
- return;
118
- }
119
- for (const mat of Array.isArray(material) ? material : [material]) {
120
- mat.transparent = true;
121
- mat.opacity = v;
122
- mat.needsUpdate = true;
123
- }
124
- },
125
- 'light.intensity': (o, v, warnOnce) => {
126
- const light = o as THREE.Light;
127
- if (!light.isLight) {
128
- warnOnce();
129
- return;
130
- }
131
- light.intensity = v;
132
- },
133
- };
134
-
135
- /**
136
- * Drives 1..N property tracks against a single Object3D. Constructed once per
137
- * entity that declares `animation.tracks`; `update(dt)` is registered in the
138
- * SAME tickFns list AnimationMixers use (scene-loader.ts), so it runs in the
139
- * animation phase on the same deterministic clock.
140
- */
141
- export class PropertyTrackRunner {
142
- private readonly object3D: THREE.Object3D;
143
- private readonly tracks: PropertyTrack[];
144
- private elapsed: number[];
145
- private readonly warned = new Set<string>();
146
-
147
- constructor(object3D: THREE.Object3D, tracks: PropertyTrack[]) {
148
- this.object3D = object3D;
149
- this.tracks = tracks;
150
- this.elapsed = tracks.map(() => 0);
151
- }
152
-
153
- /** Advance every track by `dt` seconds and write the sampled value. A paused
154
- * frame (`dt = 0`) leaves every track's value unchanged — no wall-clock, no
155
- * new clock; determinism follows directly from the caller's `dt`. */
156
- update(dt: number): void {
157
- for (let i = 0; i < this.tracks.length; i++) {
158
- const track = this.tracks[i] as PropertyTrack;
159
- this.elapsed[i] = (this.elapsed[i] ?? 0) + dt;
160
- const time = resolveTrackTime(track, this.elapsed[i] ?? 0);
161
- const value = samplePropertyTrack(track, time);
162
- const setter = TARGET_SETTERS[track.target];
163
- // Unreachable when `target` was parsed through PropertyTrackTargetSchema
164
- // (the allowlist enum) — guarded defensively since TARGET_SETTERS is a
165
- // separate table that must stay in sync with the schema.
166
- if (!setter) continue;
167
- setter(this.object3D, value, () => {
168
- if (this.warned.has(track.target)) return;
169
- this.warned.add(track.target);
170
- log.scene.warn(
171
- `Property track target "${track.target}" has no effect on entity "${this.object3D.name}" ` +
172
- '(no material / not a light) — no-op.',
173
- { entityName: this.object3D.name, target: track.target },
174
- );
175
- });
176
- }
177
- }
178
- }