@threenative/core 0.3.4 → 0.3.6

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +57 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2408 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +574 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +850 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
package/src/scene.ts ADDED
@@ -0,0 +1,239 @@
1
+ import type { Camera, Intersection, Object3D, Scene as ThreeScene } from "three";
2
+ import type { IAssetLoader } from "./assets.js";
3
+ import type { CanvasLayer } from "./canvas-layer.js";
4
+ import type { Registry } from "./entities.js";
5
+ import type { InputMap } from "./input.js";
6
+ import type { AfterPhysicsCallback } from "./loop.js";
7
+ import type { IRaycastOptions } from "./picking.js";
8
+ import type { IPointerEvents3D } from "./pointer-events.js";
9
+ import type { IRandom } from "./random.js";
10
+ import type { IRendererLike } from "./renderer.js";
11
+ import type { ITweenOptions, ScheduleHandle } from "./schedule.js";
12
+ import type { GameStore } from "./state.js";
13
+ import type { Viewport } from "./viewport.js";
14
+ import type { IWarmUpObservation, WarmUpObservationStatus } from "./warmup.js";
15
+
16
+ export abstract class Scene<
17
+ TState extends Record<string, unknown> = Record<string, unknown>,
18
+ TPhysics = undefined,
19
+ > {
20
+ static readonly initialState: Record<string, unknown> | undefined = undefined;
21
+
22
+ load(_ctx: ICtx<TState, TPhysics>): void | Promise<void> {}
23
+
24
+ enter(_ctx: ICtx<TState, TPhysics>): SceneEnterResult<TState, TPhysics> {
25
+ return undefined;
26
+ }
27
+
28
+ exit(_ctx: ICtx<TState, TPhysics>): void {}
29
+
30
+ update(_ctx: ICtx<TState, TPhysics>, _dt: number): void {}
31
+
32
+ render(_ctx: ICtx<TState, TPhysics>): void {}
33
+ }
34
+
35
+ export type SceneConstructor<
36
+ TState extends Record<string, unknown> = Record<string, unknown>,
37
+ TPhysics = undefined,
38
+ > = new () => Scene<TState, TPhysics>;
39
+
40
+ export type SceneFrame<
41
+ TState extends Record<string, unknown> = Record<string, unknown>,
42
+ TPhysics = undefined,
43
+ > = (ctx: ICtx<TState, TPhysics>, dt: number) => void;
44
+
45
+ export type SceneEnterResult<
46
+ TState extends Record<string, unknown> = Record<string, unknown>,
47
+ TPhysics = undefined,
48
+ > = // biome-ignore lint/suspicious/noConfusingVoidType: void preserves existing Scene.enter overrides.
49
+ void | SceneFrame<TState, TPhysics>;
50
+
51
+ /**
52
+ * When the framework's startup milestones happened, in milliseconds on the host's monotonic
53
+ * clock (`performance.now()`: since navigation on the web, since process start on native).
54
+ *
55
+ * Absent members have not happened yet. Published to the playtest bridge so a scenario asserts
56
+ * startup time as an observation rather than reading it off a console log.
57
+ */
58
+ export interface IStartupTimeline {
59
+ /** The start scene's `load()` began. */
60
+ readonly loadStartedMs?: number;
61
+ /** The start scene's `enter()` returned: the world is built and the loop can move. */
62
+ readonly enteredMs?: number;
63
+ /** First-use compilation settled or its budget expired. */
64
+ readonly compileSettledMs?: number;
65
+ /**
66
+ * The framework's own launch work finished: compilation settled and the frame window held.
67
+ *
68
+ * Equal to `readyMs` unless the game registered a `startup.hold()`. Kept separate so that making
69
+ * `readyMs` honest about the player's wait does not delete the only measurement of the
70
+ * framework's own cost — a game with a slow asset tier would otherwise hide a framework
71
+ * regression inside its own loading time.
72
+ */
73
+ readonly frameworkReadyMs?: number;
74
+ /**
75
+ * `whenReady()` resolved: the world is safe to show, including anything the game held for.
76
+ *
77
+ * This is the number to compare against what a player experiences. It used to be the
78
+ * framework's own readiness and nothing else, which reported 1.5 s on a valley that took 8.8 s
79
+ * to appear — and `assert.startup`'s `maxReadyMs` passed on it.
80
+ */
81
+ readonly readyMs?: number;
82
+ }
83
+
84
+ export interface IStartupStatus {
85
+ /** The most recent warm-up accounting, when a warm-up has run. */
86
+ readonly warmup?: {
87
+ readonly attempted?: number;
88
+ readonly candidates?: number;
89
+ readonly observed?: IWarmUpObservation;
90
+ readonly status: WarmUpObservationStatus;
91
+ };
92
+ /**
93
+ * True once first-use compilation has settled — earlier than `phase === "ready"`, which also
94
+ * waits for a sustained in-budget frame window.
95
+ *
96
+ * This is the signal a game wants when something must not run during the launch. `phase` cannot
97
+ * express it: it is binary, and on a software rasteriser the frame window can only ever expire
98
+ * rather than be met, so a game gated on `phase` alone does nothing for tens of seconds there.
99
+ * Measured as a chase route of length `0.000000` against a required `6`, because the scenario
100
+ * ended before the window did.
101
+ */
102
+ readonly compileSettled: boolean;
103
+ /**
104
+ * `collapsing` until first-use work and a sustained in-budget frame window complete, `ready`
105
+ * once the world is safe to show.
106
+ */
107
+ readonly phase: "observing" | "collapsing" | "ready";
108
+ /**
109
+ * 0 to 1, monotonic and honest: the loader's settled/requested ratio carries the first 0.7
110
+ * while the start scene loads, 0.8 once the world is entered, 0.9 once first-use compilation
111
+ * settled, 1 when `whenReady()` resolves.
112
+ *
113
+ * Monotonic is enforced, not assumed: this is a high-water mark over the measured load state,
114
+ * because that state can fall — requesting an asset after an earlier one settled shrinks the
115
+ * ratio, and a bar that jumps backwards reads to a player as the load restarting.
116
+ */
117
+ readonly progress: number;
118
+ /** When each milestone happened; members appear as they are reached. */
119
+ readonly timeline: IStartupTimeline;
120
+ /** Resolves after first-use work, the sustained frame window, and every game `hold()`. */
121
+ whenReady(): Promise<void>;
122
+ /**
123
+ * Resolves after first-use work and the sustained frame window, and **before** any `hold()`.
124
+ *
125
+ * This is what a game should sequence its own launch work off. `whenReady()` cannot be used for
126
+ * that once the game holds startup: the hold makes readiness wait for the game's work, so work
127
+ * *started* from `whenReady()` waits for a gate that is waiting for it. The cycle is only broken
128
+ * by the hold's budget expiring, which looks exactly like a very slow asset load — measured as a
129
+ * valley revealing its critical tier after a 45 s stall with `trees=1`.
130
+ *
131
+ * Use this when the reason to wait is the framework's launch cost — not competing with first-use
132
+ * compilation, not stealing frames from the stable-frame window — which is the usual reason.
133
+ *
134
+ * @situation start the game's own asset streaming after the framework's launch work, without deadlocking the readiness gate
135
+ */
136
+ whenFrameworkReady(): Promise<void>;
137
+ /**
138
+ * Add the game's own launch work to the readiness gate, so every framework-owned observation of
139
+ * startup describes the moment the player actually reached the world.
140
+ *
141
+ * For a game that streams a second asset tier after the framework is done. Without it the only
142
+ * options are to show a half-built world or to hold a curtain past `whenReady()`, and the second
143
+ * leaves `progress`, `phase`, `timeline.readyMs` and the playtest bridge's `assert.startup` all
144
+ * describing a moment nobody experienced.
145
+ *
146
+ * Fails open twice: a hold that rejects counts as settled, and `budgetMs` bounds how long it may
147
+ * delay the world (45 s by default). A launch slower than it could be is a disappointment; a
148
+ * launch that never finishes because one asset 404'd is a bug.
149
+ *
150
+ * Throws on an empty or duplicate label, and on a hold registered after startup already
151
+ * resolved — each means the caller believes it is gating something it is not.
152
+ *
153
+ * `progress` optionally observes monotonically completed work units (textures, placements or
154
+ * cells), so a fixed display percentage cannot falsely report a stall. Use completed work,
155
+ * never time or frame counts. Regressing/invalid values receive no credit, settlement freezes
156
+ * the count, and the hold's original deadline still applies.
157
+ * `work` may instead be a predicate, polled once per rendered frame until it returns true, for a
158
+ * readiness the game measures rather than awaits (spawn cells loaded). It needs no simulation
159
+ * step, so it also settles under a playtest's deterministic clock, which advances no fixed step
160
+ * while startup is held. A throwing predicate counts as settled.
161
+ *
162
+ * @situation hold the loading screen until the game's own asset tier has landed
163
+ */
164
+ hold(
165
+ label: string,
166
+ work: Promise<unknown> | (() => boolean),
167
+ budgetMs?: number,
168
+ progress?: () => number,
169
+ ): void;
170
+ }
171
+
172
+ export interface ICtx<
173
+ TState extends Record<string, unknown> = Record<string, unknown>,
174
+ TPhysics = undefined,
175
+ > {
176
+ /** Fraction of the next simulation tick accumulated for the presented frame, in [0, 1). */
177
+ readonly alpha: number;
178
+ /** The current frame callback timestamp in milliseconds, shared by web and native. */
179
+ readonly frameTime: number;
180
+ /** Opt a transform into draw-only fixed-step interpolation; returns scene-owned removal. */
181
+ readonly interpolate: (object: Object3D) => () => void;
182
+ /** Reset history after a game-driven teleport. */
183
+ readonly resetInterpolation: (object: Object3D) => void;
184
+ readonly fps: number;
185
+ readonly renderer: IRendererLike;
186
+ readonly viewport: Viewport;
187
+ readonly scene: ThreeScene;
188
+ readonly camera: Camera;
189
+ readonly canvasLayer: CanvasLayer;
190
+ readonly entities: Registry;
191
+ /**
192
+ * Adds a node to the scene and hands it straight back, with its own type intact.
193
+ *
194
+ * Generic rather than `Object3D` because a game writes `const sea = ctx.add(new SpectralOcean())`
195
+ * and then calls a method on it. Erasing the type here makes every typed node in every scene need
196
+ * a cast back to what it already was, and that cast is where a game stops noticing it is holding
197
+ * something else.
198
+ */
199
+ readonly add: <T extends Object3D>(object: T) => T;
200
+ readonly input: InputMap;
201
+ readonly pointer: IPointerEvents3D;
202
+ readonly assets: IAssetLoader;
203
+ readonly after: (delay: number, callback: () => void) => ScheduleHandle;
204
+ /** Register a callback for the engine-owned phase after physics writes solved transforms. */
205
+ readonly afterPhysics: (callback: AfterPhysicsCallback) => () => void;
206
+ /**
207
+ * Register work that runs once per actual world render, after the frame's last fixed update and
208
+ * before the projection reconciles and the renderer draws. A held, loader-only frame has no world
209
+ * draw and therefore dispatches nothing.
210
+ */
211
+ readonly beforeRender: (callback: () => void) => () => void;
212
+ readonly every: (callback: (dt: number) => void) => ScheduleHandle;
213
+ readonly state: GameStore<TState>;
214
+ readonly tween: <T extends object>(
215
+ target: T,
216
+ properties: { [K in keyof T]?: number },
217
+ duration: number,
218
+ options?: ITweenOptions,
219
+ ) => Promise<void>;
220
+ readonly random: IRandom;
221
+ readonly raycast: (options?: IRaycastOptions) => Intersection | undefined;
222
+ readonly raycastAll: (
223
+ options?: IRaycastOptions,
224
+ target?: Intersection[],
225
+ ) => readonly Intersection[];
226
+ /**
227
+ * The framework's own startup work — what a loading screen waits on.
228
+ *
229
+ * A shader may compile the first time something using it is drawn, and the render projection may
230
+ * do its first build in that same frame. Both costs are real and belong before the world is shown.
231
+ *
232
+ * Keeping the world hidden until `whenReady()` resolves does more than hide the mess: the
233
+ * shaders that would have been compiled for geometry the projection then discards are never
234
+ * compiled at all, so waiting is *faster* than not waiting.
235
+ */
236
+ readonly startup: IStartupStatus;
237
+ readonly goto: (name: string) => Promise<void>;
238
+ physics: TPhysics;
239
+ }
@@ -0,0 +1,155 @@
1
+ export type ScheduleHandle = (() => void) & {
2
+ cancel(): void;
3
+ readonly active: boolean;
4
+ };
5
+
6
+ type TweenProperties<T extends object> = { [K in keyof T]?: number };
7
+
8
+ export interface ITweenOptions {
9
+ readonly ease?: (t: number) => number;
10
+ }
11
+
12
+ interface IScheduleEntry {
13
+ active: boolean;
14
+ cancel(): void;
15
+ /** Monotonic registration order; entries added during a tick carry the tick's cutoff. */
16
+ order: number;
17
+ tick(dt: number): void;
18
+ }
19
+
20
+ function createHandle(cancel: () => void, active: () => boolean): ScheduleHandle {
21
+ const handle = (() => cancel()) as ScheduleHandle;
22
+ handle.cancel = handle;
23
+ Object.defineProperty(handle, "active", { get: active });
24
+ return handle;
25
+ }
26
+
27
+ export class Scheduler {
28
+ readonly #entries = new Set<IScheduleEntry>();
29
+ /** Monotonic registration order, so a tick can tell pre-tick entries from mid-tick ones. */
30
+ #nextOrder = 0;
31
+
32
+ get size(): number {
33
+ return this.#entries.size;
34
+ }
35
+
36
+ after(delay: number, callback: () => void): ScheduleHandle {
37
+ assertDelay(delay, "delay");
38
+ let elapsed = 0;
39
+ const entry = this.#add((dt) => {
40
+ elapsed += dt;
41
+ if (elapsed + Number.EPSILON < delay) return;
42
+ entry.cancel();
43
+ callback();
44
+ });
45
+ return entry.handle;
46
+ }
47
+
48
+ every(callback: (dt: number) => void): ScheduleHandle {
49
+ const entry = this.#add(callback);
50
+ return entry.handle;
51
+ }
52
+
53
+ tween<T extends object>(
54
+ target: T,
55
+ properties: TweenProperties<T>,
56
+ duration: number,
57
+ options?: ITweenOptions,
58
+ ): Promise<void> {
59
+ assertDelay(duration, "duration");
60
+ const ease = options?.ease;
61
+ const values = Object.entries(properties).map(([key, end]) => {
62
+ if (typeof end !== "number" || !Number.isFinite(end)) {
63
+ throw new TypeError(`Tween property '${key}' must be a finite number.`);
64
+ }
65
+ const start = (target as Record<string, unknown>)[key];
66
+ if (typeof start !== "number" || !Number.isFinite(start)) {
67
+ throw new TypeError(`Tween property '${key}' must start as a finite number.`);
68
+ }
69
+ return { end, key, start };
70
+ });
71
+
72
+ if (duration === 0) {
73
+ for (const { end, key } of values) (target as Record<string, unknown>)[key] = end;
74
+ return Promise.resolve();
75
+ }
76
+
77
+ let elapsed = 0;
78
+ let settled = false;
79
+ const settle = () => {
80
+ if (settled) return;
81
+ settled = true;
82
+ resolve();
83
+ };
84
+ let resolve!: () => void;
85
+ const promise = new Promise<void>((finish) => {
86
+ resolve = finish;
87
+ });
88
+ const entry = this.#add((dt) => {
89
+ elapsed = Math.min(duration, elapsed + dt);
90
+ const progress = elapsed / duration;
91
+ const easedProgress = ease === undefined ? progress : ease(progress);
92
+ if (progress >= 1) {
93
+ for (const { end, key } of values) (target as Record<string, unknown>)[key] = end;
94
+ entry.cancel();
95
+ settle();
96
+ return;
97
+ }
98
+ for (const { end, key, start } of values) {
99
+ (target as Record<string, unknown>)[key] = start + (end - start) * easedProgress;
100
+ }
101
+ }, settle);
102
+ return promise;
103
+ }
104
+
105
+ tick(dt: number): void {
106
+ if (!Number.isFinite(dt) || dt < 0)
107
+ throw new TypeError("Tick duration must be finite and non-negative.");
108
+ // Bounded direct iteration instead of a copy per tick. The bound alone is not enough: a
109
+ // mid-tick cancellation deletes from the Set and shifts later entries down a visit, which
110
+ // used to let an entry appended during this very tick fire inside this tick. The order
111
+ // guard closes that hole without paying for a per-tick snapshot copy.
112
+ const bound = this.#entries.size;
113
+ const addedBeforeTick = this.#nextOrder;
114
+ let visited = 0;
115
+ for (const entry of this.#entries) {
116
+ if (visited >= bound) break;
117
+ visited += 1;
118
+ if (!entry.active) continue;
119
+ if (entry.order >= addedBeforeTick) continue;
120
+ entry.tick(dt);
121
+ }
122
+ }
123
+
124
+ clear(): void {
125
+ for (const entry of [...this.#entries]) entry.cancel();
126
+ }
127
+
128
+ #add(
129
+ tick: (dt: number) => void,
130
+ onCancel?: () => void,
131
+ ): IScheduleEntry & { handle: ScheduleHandle } {
132
+ const entry: IScheduleEntry & { handle: ScheduleHandle } = {
133
+ active: true,
134
+ cancel: () => {
135
+ if (!entry.active) return;
136
+ entry.active = false;
137
+ this.#entries.delete(entry);
138
+ onCancel?.();
139
+ },
140
+ handle: undefined as never,
141
+ order: this.#nextOrder,
142
+ tick,
143
+ };
144
+ this.#nextOrder += 1;
145
+ entry.handle = createHandle(entry.cancel, () => entry.active);
146
+ this.#entries.add(entry);
147
+ return entry;
148
+ }
149
+ }
150
+
151
+ function assertDelay(value: number, label: string): void {
152
+ if (!Number.isFinite(value) || value < 0) {
153
+ throw new TypeError(`${label} must be finite and non-negative.`);
154
+ }
155
+ }
@@ -0,0 +1,61 @@
1
+ import type { AnimationClip, Object3D } from "three";
2
+ import { clone as cloneSkeleton } from "three/addons/utils/SkeletonUtils.js";
3
+ import { AnimationPlayer } from "./animation.js";
4
+ import { rigPreparation } from "./rig-preparation.js";
5
+ import { type INormaliseToMetresOptions, normaliseToMetres } from "./scale.js";
6
+
7
+ export interface ISkeletalMesh3DOptions {
8
+ readonly source: Object3D;
9
+ readonly clips?: readonly AnimationClip[];
10
+ readonly requiredClips?: readonly string[] | Readonly<Record<string, string>>;
11
+ readonly size?: INormaliseToMetresOptions;
12
+ readonly strideRoot?: Object3D;
13
+ readonly strideSync?: boolean;
14
+ }
15
+
16
+ export class SkeletalMesh3D extends AnimationPlayer {
17
+ constructor(options: ISkeletalMesh3DOptions) {
18
+ if (!options?.source) throw new Error("SkeletalMesh3D requires a source Object3D.");
19
+ const root = cloneSkeleton(options.source);
20
+ const clips = options.clips ?? [];
21
+ super({
22
+ clips,
23
+ requiredClips: options.requiredClips,
24
+ root,
25
+ strideRoot: options.strideRoot ?? root,
26
+ strideSync: options.strideSync,
27
+ preparation: rigPreparation(options.source),
28
+ });
29
+ if (options.size !== undefined) {
30
+ normaliseToMetres(root, mapSizeToClone(options.source, root, options.size));
31
+ }
32
+ }
33
+ }
34
+
35
+ function mapSizeToClone(
36
+ source: Object3D,
37
+ clone: Object3D,
38
+ size: INormaliseToMetresOptions,
39
+ ): INormaliseToMetresOptions {
40
+ const requestedTop = size.top;
41
+ if (requestedTop === undefined || typeof requestedTop === "string") return size;
42
+
43
+ const path: number[] = [];
44
+ let current: Object3D = requestedTop;
45
+ while (current !== source) {
46
+ const parent = current.parent;
47
+ if (parent === null) return size;
48
+ const index = parent.children.indexOf(current);
49
+ if (index < 0) return size;
50
+ path.push(index);
51
+ current = parent;
52
+ }
53
+
54
+ let mappedTop = clone;
55
+ for (const index of path.reverse()) {
56
+ const child = mappedTop.children[index];
57
+ if (child === undefined) return size;
58
+ mappedTop = child;
59
+ }
60
+ return { ...size, top: mappedTop };
61
+ }
@@ -0,0 +1,100 @@
1
+ import { type Bone, Box3, type Object3D, Vector3 } from "three";
2
+ import { type ThreePoseVector, measureThreePose } from "./pose-measure.js";
3
+
4
+ function isBone(object: Object3D): object is Bone {
5
+ return (object as Bone).isBone === true;
6
+ }
7
+
8
+ /** Every bone under `root` in traversal order. Internal: `skeletonBones` is the public surface. */
9
+ export function bonesIn(root: Object3D): Bone[] {
10
+ const bones: Bone[] = [];
11
+ root.traverse((object) => {
12
+ if (isBone(object)) bones.push(object);
13
+ });
14
+ return bones;
15
+ }
16
+
17
+ function requireBone(root: Object3D, boneName: string): Bone {
18
+ const bones = bonesIn(root);
19
+ const bone = bones.find((candidate) => candidate.name === boneName);
20
+ if (bone === undefined) {
21
+ const available =
22
+ bones.map((candidate) => candidate.name || "(unnamed)").join(", ") || "(none)";
23
+ throw new Error(`Bone '${boneName}' not found. Available bones: ${available}.`);
24
+ }
25
+ return bone;
26
+ }
27
+
28
+ function preserveScale(value: number, attachedScale: number, localScale: number): number {
29
+ return attachedScale === 0 ? 1 : (localScale * value) / attachedScale;
30
+ }
31
+
32
+ /** Names of every bone in traversal order. Empty for an unskinned model. */
33
+ export function skeletonBones(root: Object3D): readonly string[] {
34
+ return bonesIn(root).map((bone) => bone.name);
35
+ }
36
+
37
+ /** Parent a child to a named bone while preserving the child's authored world scale. */
38
+ export function attachToBone(root: Object3D, boneName: string, child: Object3D): Object3D {
39
+ const bone = requireBone(root, boneName);
40
+
41
+ const childScale = new Vector3();
42
+ child.getWorldScale(childScale);
43
+ bone.add(child);
44
+ const attachedScale = new Vector3();
45
+ child.getWorldScale(attachedScale);
46
+ const localScale = child.scale.clone();
47
+ child.scale.set(
48
+ preserveScale(childScale.x, attachedScale.x, localScale.x),
49
+ preserveScale(childScale.y, attachedScale.y, localScale.y),
50
+ preserveScale(childScale.z, attachedScale.z, localScale.z),
51
+ );
52
+ return child;
53
+ }
54
+
55
+ /** How far a bone sits from the object it is supposed to be touching. */
56
+ export interface IBoneContactReport {
57
+ readonly bone: string;
58
+ readonly target: string;
59
+ /** Metres from the bone to the nearest point of the target's world bounds. Zero when inside. */
60
+ readonly distance: number;
61
+ readonly inside: boolean;
62
+ readonly bonePosition: ThreePoseVector;
63
+ readonly targetPoint: ThreePoseVector;
64
+ }
65
+
66
+ /**
67
+ * Measure whether a named bone reaches a game object, in metres.
68
+ *
69
+ * This turns "his hands are on the keyboard" and "he is sitting on the chair" into numbers a
70
+ * scenario can assert. It walks the target's vertices through `measureThreePose`, so call it on
71
+ * a check or a debug sample rather than every frame.
72
+ */
73
+ export function boneContact(
74
+ root: Object3D,
75
+ boneName: string,
76
+ target: Object3D,
77
+ ): IBoneContactReport {
78
+ const bone = requireBone(root, boneName);
79
+ const bonePose = measureThreePose(bone, { bounds: false });
80
+ const targetPose = measureThreePose(target);
81
+ if (targetPose.bounds === null) {
82
+ throw new Error(`boneContact could not measure '${target.name || target.type}'.`);
83
+ }
84
+
85
+ const position = new Vector3(...bonePose.position);
86
+ const bounds = new Box3(
87
+ new Vector3(...targetPose.bounds.min),
88
+ new Vector3(...targetPose.bounds.max),
89
+ );
90
+ const nearest = bounds.clampPoint(position, new Vector3());
91
+ const distance = nearest.distanceTo(position);
92
+ return {
93
+ bone: bone.name,
94
+ target: target.name || target.type,
95
+ distance,
96
+ inside: distance === 0,
97
+ bonePosition: bonePose.position,
98
+ targetPoint: [nearest.x, nearest.y, nearest.z],
99
+ };
100
+ }