@threenative/core 0.3.12 → 0.3.13

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 (150) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +746 -32
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-4SRAQFTU.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-DIPIJICH.js} +1590 -375
  7. package/dist/{chunk-OKXUCASC.js → chunk-EEABDLUC.js} +3 -4
  8. package/dist/{chunk-5O73CDMR.js → chunk-EFWZWLPY.js} +62 -16
  9. package/dist/{chunk-N5LRP4BR.js → chunk-GYUZJQ7U.js} +63 -3
  10. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  11. package/dist/{chunk-2Z44XSI2.js → chunk-SV4QVUTQ.js} +3 -7
  12. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  13. package/dist/chunk-VP43GIWW.js +18 -0
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +289 -1034
  20. package/dist/index.js +3096 -1305
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BYqKGAwo.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +269 -15
  33. package/dist/world.js +1372 -628
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +105 -7
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/src/animation-batch.ts +193 -0
  39. package/src/animation-layers.ts +7 -3
  40. package/src/animation.ts +209 -29
  41. package/src/asset-cache.ts +3 -3
  42. package/src/asset-memo.ts +202 -0
  43. package/src/assets.ts +436 -131
  44. package/src/auto-batch.ts +190 -44
  45. package/src/compute-driven.ts +1 -1
  46. package/src/config.ts +8 -0
  47. package/src/debug.ts +103 -22
  48. package/src/dev-global.ts +54 -0
  49. package/src/engine-hooks.ts +37 -0
  50. package/src/frame-budget.ts +19 -3
  51. package/src/game-boot-phase.ts +269 -0
  52. package/src/game-dev-tools.ts +7 -14
  53. package/src/game-frame-loop.ts +45 -82
  54. package/src/game-startup.ts +145 -70
  55. package/src/game-ui.ts +84 -0
  56. package/src/game.ts +168 -552
  57. package/src/gamepad-mappings.ts +269 -0
  58. package/src/generated/console-markers.ts +13 -0
  59. package/src/geometry-capture.ts +28 -4
  60. package/src/gpu-readings.ts +98 -0
  61. package/src/gpu-scene-bvh.ts +149 -36
  62. package/src/hot.ts +4 -7
  63. package/src/index.ts +115 -8
  64. package/src/input.ts +237 -25
  65. package/src/instanced-batch-lod.ts +3 -8
  66. package/src/interpolation.ts +171 -40
  67. package/src/look/ao-admission.ts +4 -3
  68. package/src/look/auto-exposure.ts +5 -16
  69. package/src/look/default-tone-mapping.ts +41 -5
  70. package/src/look/local-exposure.ts +2 -7
  71. package/src/look/quad-pass.ts +21 -0
  72. package/src/look/quality.ts +4 -0
  73. package/src/look/unreal-bloom.ts +4 -13
  74. package/src/look/world-environment.ts +58 -115
  75. package/src/merge-parts.ts +20 -24
  76. package/src/model-lod.ts +97 -14
  77. package/src/particle-significance.ts +12 -0
  78. package/src/particles.ts +19 -10
  79. package/src/platform.ts +23 -4
  80. package/src/profiling/FrameStages.ts +5 -6
  81. package/src/profiling/Spans.ts +3 -17
  82. package/src/profiling/debug-telemetry.ts +2 -6
  83. package/src/profiling/render-list-validate.ts +6 -15
  84. package/src/projection-marker.ts +2 -1
  85. package/src/quiet-markers.ts +3 -10
  86. package/src/render/cpu-bvh.ts +100 -0
  87. package/src/render/depth-pyramid.ts +6 -14
  88. package/src/render/environment/environmentContribution.ts +202 -0
  89. package/src/render/environment/environmentRadiance.ts +44 -0
  90. package/src/render/environment/environmentSampleCache.ts +56 -0
  91. package/src/render/environment/environmentSampling.ts +201 -0
  92. package/src/render/environment/environmentSnapshot.ts +71 -0
  93. package/src/render/environment/gate.ts +57 -0
  94. package/src/render/mesh-pool.ts +3 -19
  95. package/src/render/probe-trace.ts +872 -0
  96. package/src/render/probe-volume.ts +780 -34
  97. package/src/render/radiance-cache.ts +17 -0
  98. package/src/render/virtual-shadow-partial.ts +13 -0
  99. package/src/render/virtual-shadow.ts +18 -16
  100. package/src/render/world-impostor-surface.ts +109 -6
  101. package/src/render/world-impostor.ts +5 -2
  102. package/src/render-camera-cull.ts +98 -3
  103. package/src/render-environment.ts +41 -0
  104. package/src/renderer-config.ts +36 -0
  105. package/src/renderer-facts.ts +37 -0
  106. package/src/renderer.ts +52 -28
  107. package/src/resolution-scaler.ts +3 -2
  108. package/src/scene-entry-inspectors.ts +61 -0
  109. package/src/snow-field.ts +1 -0
  110. package/src/startup-offscreen-bytes.ts +78 -0
  111. package/src/static-transform.ts +25 -19
  112. package/src/streamed-textures.ts +112 -0
  113. package/src/streaming.ts +68 -4
  114. package/src/texture-streaming.ts +331 -0
  115. package/src/version.ts +1 -1
  116. package/src/worker.ts +12 -2
  117. package/src/world-bundle-safety.ts +55 -10
  118. package/src/world-cell-batches.ts +162 -200
  119. package/src/world-cell-chunks.ts +3 -7
  120. package/src/world-cell-impostors.ts +20 -8
  121. package/src/world-cell-options.ts +2 -14
  122. package/src/world-cell-placements.ts +194 -90
  123. package/src/world-cell-prewarm.ts +39 -4
  124. package/src/world-cell-records.ts +401 -0
  125. package/src/world-cell-render-bundles.ts +2 -2
  126. package/src/world-cell-render-gpu-dress.ts +13 -17
  127. package/src/world-cell-render-main-cull.ts +73 -17
  128. package/src/world-cell-render-util.ts +17 -4
  129. package/src/world-cell-render.ts +13 -5
  130. package/src/world-cell-residency.ts +15 -6
  131. package/src/world-cell-stale.ts +238 -0
  132. package/src/world-cells.ts +22 -5
  133. package/src/world-gpu-flags.ts +18 -50
  134. package/src/world-gpu-reference.ts +22 -8
  135. package/src/world-gpu-scene.ts +44 -24
  136. package/src/world-gpu-shadow.ts +21 -8
  137. package/src/world-gpu-types.ts +41 -13
  138. package/src/world-load-limiter.ts +5 -0
  139. package/src/world-model-sections.ts +80 -0
  140. package/src/world-river-ribbon.ts +282 -0
  141. package/src/world-root-frame.ts +39 -0
  142. package/src/world-shore-field.ts +91 -0
  143. package/src/world-static-pose.ts +163 -0
  144. package/src/world-surface-sampler.ts +48 -0
  145. package/src/world-terrain-splat.ts +10 -18
  146. package/src/world-tile-budget.ts +4 -11
  147. package/src/world-tiles.ts +79 -12
  148. package/src/world-validate.ts +6 -14
  149. package/src/world-warm.ts +51 -0
  150. package/src/world.ts +13 -0
package/src/input.ts CHANGED
@@ -1,4 +1,10 @@
1
1
  import { Vector2 } from "three";
2
+ import {
3
+ type GamepadNormalizer,
4
+ type IStandardPad,
5
+ createStandardPad,
6
+ toStandardPad,
7
+ } from "./gamepad-mappings.js";
2
8
 
3
9
  /**
4
10
  * One action, read either as a button through `pressed`/`justPressed`, a 2D axis through
@@ -81,10 +87,27 @@ function mouseButtonMask(button: number): number {
81
87
  export interface IInputGamepad {
82
88
  readonly axes: ArrayLike<number>;
83
89
  readonly buttons: readonly { readonly pressed: boolean }[];
90
+ /** The browser's device name, which carries the vendor:product an unmapped pad is looked up by. */
91
+ readonly id?: string;
92
+ /**
93
+ * `"standard"` when the pad already uses the W3C standard layout, and `""` when the browser does
94
+ * not know the device. A source with no `mapping` at all is standard by construction: the owned
95
+ * native host builds standard pads, and so does a fixture.
96
+ */
97
+ readonly mapping?: string;
84
98
  }
85
99
 
86
100
  export type InputPlatformSource = () => readonly (IInputGamepad | null)[];
87
101
 
102
+ export interface IInputMapOptions {
103
+ /**
104
+ * Radial dead zone for both sticks, `0`..`1`. Default `0.2`, the stock Enhanced Input dead zone
105
+ * (`UInputModifierDeadZone`, `LowerThreshold = 0.2`, `EDeadZoneType::Radial`). A stick inside it
106
+ * reads zero, one outside it is rescaled so full tilt is still `1`. `0` publishes raw axes.
107
+ */
108
+ readonly gamepadDeadZone?: number;
109
+ }
110
+
88
111
  export interface IRawInputPointer {
89
112
  readonly id: number;
90
113
  buttons: number;
@@ -158,6 +181,41 @@ function pointerLockDocument(): PointerLockDocument | undefined {
158
181
  const browserGamepads: InputPlatformSource = () =>
159
182
  (globalThis.navigator as Navigator | undefined)?.getGamepads?.() ?? [];
160
183
 
184
+ const DEFAULT_GAMEPAD_DEAD_ZONE = 0.2;
185
+
186
+ /**
187
+ * How far past the dead zone a stick must travel to claim the input from another pad, on the
188
+ * rescaled axis: half travel. A worn stick jittering around the zone rescales to about `0.01` and
189
+ * never claims, while a deliberate move always does. A button press claims at any deflection.
190
+ */
191
+ const GAMEPAD_CLAIM_STICK = 0.5;
192
+
193
+ /** Stable names for pads a fixture reports with no `id`, so reporting allocates nothing per tick. */
194
+ const PAD_SLOT_KEYS: readonly string[] = Array.from({ length: 16 }, (_, index) => `slot-${index}`);
195
+
196
+ /**
197
+ * The radial dead zone, in place. A stick inside `deadZone` reads zero; one outside is rescaled by
198
+ * `(magnitude - deadZone) / (1 - deadZone)` so the edge of the zone is still `0` and full tilt is
199
+ * still `1`, which is what makes a 0.6 stick read 0.5 rather than 0.4.
200
+ */
201
+ function applyStickDeadZone(axes: number[], x: number, y: number, deadZone: number): void {
202
+ // `0` is the documented raw-axes override, so it must publish the stick untouched — the rescale
203
+ // below would still pull a corner in to the unit circle.
204
+ if (!(deadZone > 0)) return;
205
+ const zone = Math.min(deadZone, 1);
206
+ const stickX = axes[x] ?? 0;
207
+ const stickY = axes[y] ?? 0;
208
+ const magnitude = Math.sqrt(stickX * stickX + stickY * stickY);
209
+ if (magnitude <= zone || zone >= 1) {
210
+ axes[x] = 0;
211
+ axes[y] = 0;
212
+ return;
213
+ }
214
+ const scale = Math.min(1, (magnitude - zone) / (1 - zone)) / magnitude;
215
+ axes[x] = stickX * scale;
216
+ axes[y] = stickY * scale;
217
+ }
218
+
161
219
  /**
162
220
  * Ask the browser to lock the pointer to `target`, the capture every first-person mouse look needs.
163
221
  *
@@ -195,6 +253,20 @@ export class InputMap {
195
253
  #pinchSample = 0;
196
254
  #gamepadAxes: number[] = [];
197
255
  #gamepadButtons: boolean[] = [];
256
+ /** The pad every read goes through: one reused buffer, filled once per read and never allocated. */
257
+ #padScratch: IStandardPad = createStandardPad();
258
+ /** Which source slot the player last used. It stays active until another pad reports input. */
259
+ #activePadSlot = -1;
260
+ #padSeen = new Set<string>();
261
+ #padReports = new Map<string, GamepadNormalizer>();
262
+ /** Each slot's pressed-button mask and stick travel last tick: a pad takes the slot on a claim. */
263
+ #padButtonMask: number[] = [];
264
+ #padStick: number[] = [];
265
+ /** Whether the current pad took the slot by claiming it, rather than by being the only pad there. */
266
+ #activePadClaimed = false;
267
+ /** The `TN_GAMEPAD` key per slot, and the `id` it was built from, so a tick allocates no string. */
268
+ #padKeys: Array<string | undefined> = [];
269
+ #padKeyIds: Array<string | undefined> = [];
198
270
  #previousPressed = new Map<string, boolean>();
199
271
  #justPressed = new Set<string>();
200
272
  #justReleased = new Set<string>();
@@ -214,13 +286,28 @@ export class InputMap {
214
286
  #tracksPinch = false;
215
287
  #listeners: Array<[EventTarget, string, EventListener]> = [];
216
288
 
289
+ /**
290
+ * Radial dead zone for both sticks; `0` publishes the raw axes. Read on every tick, so a game may
291
+ * change it while running, and a value that is not a finite number from 0 through 1 reads as raw
292
+ * axes. `defineGame({ gamepadDeadZone })` sets the starting value and refuses one it cannot honour.
293
+ */
294
+ gamepadDeadZone: number;
295
+
217
296
  constructor(
218
297
  bindings: InputBindings = DEFAULT_BINDINGS,
219
298
  target: EventTarget = globalThis,
220
299
  pointerTarget: EventTarget = target,
221
300
  source: InputPlatformSource = browserGamepads,
222
301
  contextMenu: ContextMenuPolicy = "suppress",
302
+ options: IInputMapOptions = {},
223
303
  ) {
304
+ const deadZone = options.gamepadDeadZone ?? DEFAULT_GAMEPAD_DEAD_ZONE;
305
+ if (!Number.isFinite(deadZone) || deadZone < 0 || deadZone > 1) {
306
+ throw new RangeError(
307
+ `gamepadDeadZone must be a number from 0 through 1, received ${deadZone}.`,
308
+ );
309
+ }
310
+ this.gamepadDeadZone = deadZone;
224
311
  this.#bindings = { ...DEFAULT_BINDINGS, ...bindings };
225
312
  // Bindings are fixed at construction; freezing the key list keeps tick() from calling
226
313
  // Object.keys every step.
@@ -345,7 +432,11 @@ export class InputMap {
345
432
  return Math.max(-1, Math.min(1, value));
346
433
  }
347
434
 
348
- /** Request pointer capture explicitly from a named game gesture. Relative bindings request it on canvas click by default. */
435
+ /**
436
+ * Request pointer capture explicitly from a named game gesture. Relative bindings request it on
437
+ * canvas click by default. A refused lock — an unfocused window, an untrusted gesture — leaves
438
+ * `raw.pointer.captured` false and warns once as `TN_POINTER_LOCK_REFUSED:`, never a rejection.
439
+ */
349
440
  captureMouse(): void {
350
441
  if (this.raw.pointer.captured) return;
351
442
  const result = captureMouse(this.#pointerTarget);
@@ -357,7 +448,9 @@ export class InputMap {
357
448
  () => this.#syncCaptured(true),
358
449
  (error: unknown) => {
359
450
  this.raw.pointer.captured = false;
360
- throw error;
451
+ console.warn(
452
+ `TN_POINTER_LOCK_REFUSED: ${error instanceof Error ? error.message : String(error)}`,
453
+ );
361
454
  },
362
455
  );
363
456
  }
@@ -426,29 +519,7 @@ export class InputMap {
426
519
  this.#scrollSample = this.#clampAxis(this.#scrollDelta);
427
520
  this.#scrollDelta = 0;
428
521
  this.#samplePinch();
429
- const sources = this.#source();
430
- let gamepad: IInputGamepad | undefined;
431
- for (let index = 0; index < sources.length; index += 1) {
432
- const candidate = sources[index];
433
- if (candidate !== null) {
434
- gamepad = candidate;
435
- break;
436
- }
437
- }
438
- // Reused buffers: fresh arrays here were four allocations per update step, device or not.
439
- this.#gamepadAxes.length = 0;
440
- this.#gamepadButtons.length = 0;
441
- if (gamepad?.axes) {
442
- const axes = gamepad.axes;
443
- for (let axis = 0; axis < axes.length; axis += 1)
444
- this.#gamepadAxes.push(axes[axis] as number);
445
- }
446
- if (gamepad?.buttons) {
447
- for (let index = 0; index < gamepad.buttons.length; index += 1)
448
- this.#gamepadButtons.push(gamepad.buttons[index]?.pressed ?? false);
449
- }
450
- this.raw.gamepad.axes = this.#gamepadAxes;
451
- this.raw.gamepad.buttons = this.#gamepadButtons;
522
+ this.#sampleGamepad();
452
523
  this.#justPressed.clear();
453
524
  this.#justReleased.clear();
454
525
  for (let index = 0; index < this.#bindingNames.length; index += 1) {
@@ -486,6 +557,7 @@ export class InputMap {
486
557
  this.#pinchPair = undefined;
487
558
  this.#pinchDistance = 0;
488
559
  this.#pinchSample = 0;
560
+ this.#activePadSlot = -1;
489
561
  this.#previousPressed.clear();
490
562
  this.#justPressed.clear();
491
563
  this.#justReleased.clear();
@@ -505,6 +577,146 @@ export class InputMap {
505
577
  this.clear();
506
578
  }
507
579
 
580
+ /**
581
+ * Reads every pad once, normalizes each to the standard mapping, and publishes the one pad the
582
+ * player is holding. Reading the first non-null slot instead let a wheel or a paired-but-idle
583
+ * dongle at slot 0 swallow the pad in the player's hands.
584
+ */
585
+ #sampleGamepad(): void {
586
+ const sources = this.#source();
587
+ this.#padSeen.clear();
588
+ let claimSlot = -1;
589
+ let inputSlot = -1;
590
+ let firstMapped = -1;
591
+ let activeStillMapped = false;
592
+ for (let index = 0; index < sources.length; index += 1) {
593
+ const pad = sources[index];
594
+ if (pad === null || pad === undefined) {
595
+ this.#forgetPad(index);
596
+ continue;
597
+ }
598
+ if (this.#readPad(pad, index) === "unmapped") {
599
+ this.#forgetPad(index);
600
+ continue;
601
+ }
602
+ if (firstMapped < 0) firstMapped = index;
603
+ // A claim, not a level and not a pad-wide edge: a worn stick resting past the dead zone reports
604
+ // input on every tick, and one jittering across the zone produces an edge every few ticks, so
605
+ // either test would let a phantom pad take the slot in the middle of a real move — the bug this
606
+ // PRD exists to remove. A wedge either presses a button that was up, or travels past half a
607
+ // stick; a resting stick does neither, and a button press reclaims even while the player is
608
+ // already holding their stick still.
609
+ const mask = this.#padButtonMaskNow();
610
+ const stick = this.#padStickNow();
611
+ const pressedNewButton = (mask & ~(this.#padButtonMask[index] ?? 0)) !== 0;
612
+ const travelled =
613
+ stick >= GAMEPAD_CLAIM_STICK && (this.#padStick[index] ?? 0) < GAMEPAD_CLAIM_STICK;
614
+ if ((pressedNewButton || travelled) && claimSlot < 0) claimSlot = index;
615
+ this.#padButtonMask[index] = mask;
616
+ this.#padStick[index] = stick;
617
+ if (this.#padHasInput() && inputSlot < 0) inputSlot = index;
618
+ if (index === this.#activePadSlot) activeStillMapped = true;
619
+ }
620
+ // A source that shrinks never visits its old slots again, so they are forgotten here; otherwise a
621
+ // pad that later connects into one of them would inherit the previous pad's claim history.
622
+ for (let index = sources.length; index < this.#padButtonMask.length; index += 1)
623
+ this.#forgetPad(index);
624
+ for (const key of this.#padReports.keys())
625
+ if (!this.#padSeen.has(key)) this.#padReports.delete(key);
626
+ // The pad the player last claimed owns the input, and keeps it while idle so its releases are
627
+ // read. A pad that disappeared, or one the browser now reports unmapped, hands over to whichever
628
+ // pad is being held, then to the first pad there is. A slot nobody claimed — it merely held the
629
+ // input when nothing else did — is not owned, so a gentle tilt of the pad in the player's hands
630
+ // outranks it; that is what stops an idle dongle in slot 0 from needing a claim to get past.
631
+ let active: number;
632
+ let owned = false;
633
+ if (claimSlot >= 0) {
634
+ active = claimSlot;
635
+ owned = true;
636
+ } else if (activeStillMapped && this.#activePadClaimed && this.#activePadSlot >= 0) {
637
+ active = this.#activePadSlot;
638
+ owned = true;
639
+ } else if (inputSlot >= 0) {
640
+ active = inputSlot;
641
+ } else {
642
+ active = firstMapped;
643
+ }
644
+ this.#activePadSlot = active;
645
+ this.#activePadClaimed = owned;
646
+ // Reused buffers: fresh arrays here were four allocations per update step, device or not.
647
+ this.#gamepadAxes.length = 0;
648
+ this.#gamepadButtons.length = 0;
649
+ const pad = active < 0 ? undefined : sources[active];
650
+ if (pad === null || pad === undefined || this.#readPad(pad, active) === "unmapped") {
651
+ this.raw.gamepad.axes = this.#gamepadAxes;
652
+ this.raw.gamepad.buttons = this.#gamepadButtons;
653
+ return;
654
+ }
655
+ for (const axis of this.#padScratch.axes) this.#gamepadAxes.push(axis);
656
+ for (const button of this.#padScratch.buttons) this.#gamepadButtons.push(button.pressed);
657
+ this.raw.gamepad.axes = this.#gamepadAxes;
658
+ this.raw.gamepad.buttons = this.#gamepadButtons;
659
+ }
660
+
661
+ /** Normalizes one pad into the scratch buffer and reports it once per connect. */
662
+ #readPad(pad: IInputGamepad, index: number): GamepadNormalizer {
663
+ const normalizer = toStandardPad(pad, this.#padScratch);
664
+ // `index:id`: two identical pads are two pads, and a hotplug that moves a pad to another slot
665
+ // is a new reading of where it is rather than a silent re-use of the old line. Built once per
666
+ // slot:id, because a template literal allocates and this runs twice a tick for the active pad.
667
+ const id = pad.id;
668
+ let key = this.#padKeys[index];
669
+ if (key === undefined || this.#padKeyIds[index] !== id) {
670
+ key = `${index}:${id ?? (PAD_SLOT_KEYS[index] as string)}`;
671
+ this.#padKeys[index] = key;
672
+ this.#padKeyIds[index] = id;
673
+ }
674
+ this.#padSeen.add(key);
675
+ if (this.#padReports.get(key) !== normalizer) {
676
+ this.#padReports.set(key, normalizer);
677
+ console.info(
678
+ `TN_GAMEPAD ${JSON.stringify({
679
+ deadZone: this.gamepadDeadZone,
680
+ id: pad.id ?? (PAD_SLOT_KEYS[index] as string),
681
+ mapping: normalizer,
682
+ })}`,
683
+ );
684
+ }
685
+ applyStickDeadZone(this.#padScratch.axes, 0, 1, this.gamepadDeadZone);
686
+ applyStickDeadZone(this.#padScratch.axes, 2, 3, this.gamepadDeadZone);
687
+ return normalizer;
688
+ }
689
+
690
+ /** Clears one slot's claim history, so a pad that returns to it starts from rest. */
691
+ #forgetPad(index: number): void {
692
+ this.#padButtonMask[index] = 0;
693
+ this.#padStick[index] = 0;
694
+ }
695
+
696
+ /** The scratch pad's pressed buttons as a mask, so a new press is one integer compare. */
697
+ #padButtonMaskNow(): number {
698
+ let mask = 0;
699
+ const buttons = this.#padScratch.buttons;
700
+ for (let index = 0; index < buttons.length; index += 1)
701
+ if (buttons[index]?.pressed === true) mask |= 1 << index;
702
+ return mask;
703
+ }
704
+
705
+ /** The scratch pad's larger stick travel on the rescaled axes, which is what a claim compares. */
706
+ #padStickNow(): number {
707
+ const axes = this.#padScratch.axes;
708
+ const left = Math.sqrt((axes[0] ?? 0) ** 2 + (axes[1] ?? 0) ** 2);
709
+ const right = Math.sqrt((axes[2] ?? 0) ** 2 + (axes[3] ?? 0) ** 2);
710
+ return Math.max(left, right);
711
+ }
712
+
713
+ /** Whether the normalized pad in the scratch buffer has moved past its dead zone or pressed anything. */
714
+ #padHasInput(): boolean {
715
+ for (const axis of this.#padScratch.axes) if (axis !== 0) return true;
716
+ for (const button of this.#padScratch.buttons) if (button.pressed) return true;
717
+ return false;
718
+ }
719
+
508
720
  /** Was this action pressed at any point since the last tick, even if already released? */
509
721
  #latchedPressed(name: string): boolean {
510
722
  const binding = this.#bindings[name];
@@ -11,9 +11,9 @@ import {
11
11
  DISCRETE_LOD_DEFAULT_HYSTERESIS,
12
12
  type IModelLodController,
13
13
  biasedLodDistance,
14
- conservativeViewDepth,
15
14
  lodChainOf,
16
15
  registerModelLodController,
16
+ selectLodFor,
17
17
  selectLodLevel,
18
18
  } from "./model-lod.js";
19
19
 
@@ -201,12 +201,7 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
201
201
  mesh.getMatrixAt(index, matrix);
202
202
  world.multiplyMatrices(mesh.matrixWorld, matrix);
203
203
  sphere.copy(local).applyMatrix4(world);
204
- const view = conservativeViewDepth(
205
- camera,
206
- sphere.center,
207
- sphere.radius,
208
- (camera as Camera & { near?: number }).near ?? 0,
209
- );
204
+ const view = selectLodFor(camera, sphere, (camera as Camera & { near?: number }).near ?? 0);
210
205
  let level = 0;
211
206
  if (options.lods !== undefined) {
212
207
  const distance = biasedLodDistance(cameraPosition.distanceTo(sphere.center));
@@ -224,7 +219,7 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
224
219
  {
225
220
  camera,
226
221
  viewportHeight,
227
- depth: biasedLodDistance(view.depth),
222
+ depth: view.biased,
228
223
  degenerate: view.degenerate,
229
224
  },
230
225
  ],
@@ -1,4 +1,34 @@
1
- import { type Object3D, Quaternion, Vector3 } from "three";
1
+ import { type Object3D, type Object3D as Object3DType, Quaternion, Vector3 } from "three";
2
+
3
+ import { hasCopyMatrixWorldHook } from "./engine-hooks.js";
4
+ import { debugRequested, measureDebug } from "./profiling/debug-telemetry.js";
5
+
6
+ /**
7
+ * The five engine-internal methods the owned engine puts on an `Object3D` for the C++ pose history
8
+ * (PRD-877). Plain three.js has none of them, and the JavaScript loops below stay the path there.
9
+ * `runtime-native/src/engine/abi/bindings_scene.cpp` defines these names; a rename on either side
10
+ * takes every caller down the slow path, which the spec beside this one fails on.
11
+ */
12
+ interface IPoseOwner {
13
+ __tnPoseWatch(objects: Object3DType[]): number;
14
+ __tnPoseReset(objects: Object3DType[]): void;
15
+ __tnPoseTick(phase: number): void;
16
+ __tnPoseBlend(alpha: number): void;
17
+ __tnPoseRestore(): void;
18
+ }
19
+
20
+ type PoseOwnerCarrier = Object3DType & Partial<IPoseOwner>;
21
+
22
+ function poseOwnerOf(object: Object3DType): IPoseOwner | undefined {
23
+ const candidate = object as PoseOwnerCarrier;
24
+ return typeof candidate.__tnPoseTick === "function" &&
25
+ typeof candidate.__tnPoseBlend === "function" &&
26
+ typeof candidate.__tnPoseRestore === "function" &&
27
+ typeof candidate.__tnPoseWatch === "function" &&
28
+ typeof candidate.__tnPoseReset === "function"
29
+ ? (candidate as IPoseOwner)
30
+ : undefined;
31
+ }
2
32
 
3
33
  interface ITransformHistory {
4
34
  readonly object: Object3D;
@@ -21,9 +51,8 @@ interface ITransformHistory {
21
51
  * a node the walk will not compose.
22
52
  */
23
53
  function recompose(object: Object3D): void {
24
- const engine = object as Object3D & { __tnCopyMatrixWorld?: unknown };
25
- if (object.matrixAutoUpdate && engine.__tnCopyMatrixWorld !== undefined) {
26
- engine.matrixWorldNeedsUpdate = true;
54
+ if (object.matrixAutoUpdate && hasCopyMatrixWorldHook(object)) {
55
+ object.matrixWorldNeedsUpdate = true;
27
56
  return;
28
57
  }
29
58
  object.updateMatrix();
@@ -33,14 +62,69 @@ function recompose(object: Object3D): void {
33
62
  export class PhysicsInterpolation {
34
63
  readonly enabled: boolean;
35
64
  readonly overrideSource: "default" | "defineGame";
36
- readonly #objects = new Map<Object3D, ITransformHistory>();
65
+ readonly #objects = new Map<Object3DType, ITransformHistory>();
66
+ readonly #debug = debugRequested();
37
67
  #lastReport = "";
68
+ /** The engine object the C++ history lives on: created lazily, never added to a scene. */
69
+ #ownerInjected: IPoseOwner | null = null;
70
+ #ownerResolved: IPoseOwner | null | undefined;
71
+ /** Bumped whenever the tracked set changes, so the engine is told only when it must be. */
72
+ #membership = 0;
73
+ #watchedMembership = -1;
38
74
 
39
- constructor(enabled?: boolean) {
75
+ constructor(enabled?: boolean, poseOwner?: Object3DType) {
40
76
  if (enabled !== undefined && typeof enabled !== "boolean")
41
77
  throw new Error("physicsInterpolation must be a boolean.");
42
78
  this.enabled = enabled ?? true;
43
79
  this.overrideSource = enabled === undefined ? "default" : "defineGame";
80
+ if (poseOwner !== undefined) {
81
+ const owner = poseOwnerOf(poseOwner);
82
+ if (owner === undefined)
83
+ throw new Error("The pose owner must carry the engine's five pose methods.");
84
+ this.#ownerInjected = owner;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * The engine path, or null on plain three.js. Resolving it once and keeping the answer means a
90
+ * frame never probes for methods it already knows are absent.
91
+ */
92
+ get #owner(): IPoseOwner | null {
93
+ if (this.#ownerResolved === undefined) {
94
+ if (this.#ownerInjected !== null) this.#ownerResolved = this.#ownerInjected;
95
+ else {
96
+ // The tracked bodies are the objects the host demonstrably built: a game body carries the
97
+ // engine's methods when the host is the engine, and a detached `new Object3D()` created here
98
+ // may not be engine-backed at all. The first body that answers is the owner for all of them.
99
+ let found: IPoseOwner | null = null;
100
+ for (const object of this.#objects.keys()) {
101
+ const candidate = poseOwnerOf(object);
102
+ if (candidate !== undefined) {
103
+ found = candidate;
104
+ break;
105
+ }
106
+ }
107
+ this.#ownerResolved = found;
108
+ }
109
+ }
110
+ return this.#ownerResolved;
111
+ }
112
+
113
+ /** Which path this instance took, reported on every membership change. */
114
+ get path(): "engine" | "javascript" {
115
+ return this.#owner === null ? "javascript" : "engine";
116
+ }
117
+
118
+ /** Tells the engine the current tracked set, only when it changed since the last time. */
119
+ #watchIfDirty(owner: IPoseOwner): void {
120
+ if (this.#watchedMembership === this.#membership) return;
121
+ owner.__tnPoseWatch([...this.#objects.keys()]);
122
+ this.#watchedMembership = this.#membership;
123
+ }
124
+
125
+ /** One region of a frame step, timed only when this launch asked for debug telemetry. */
126
+ #measured<T>(name: string, caller: string, run: () => T): T {
127
+ return this.#debug ? measureDebug(name, "update", caller, run) : run();
44
128
  }
45
129
 
46
130
  track(object: Object3D): () => void {
@@ -58,6 +142,9 @@ export class PhysicsInterpolation {
58
142
  references: 0,
59
143
  };
60
144
  this.#objects.set(object, history);
145
+ this.#membership += 1;
146
+ // A body tracked after a plain one may be the first engine-backed object; ask again.
147
+ if (this.#ownerResolved === null) this.#ownerResolved = undefined;
61
148
  }
62
149
  history.references += 1;
63
150
  let active = true;
@@ -65,14 +152,17 @@ export class PhysicsInterpolation {
65
152
  if (!active) return;
66
153
  active = false;
67
154
  history.references -= 1;
68
- if (history.references === 0 && this.#objects.get(object) === history)
155
+ if (history.references === 0 && this.#objects.get(object) === history) {
69
156
  this.#objects.delete(object);
157
+ this.#membership += 1;
158
+ }
70
159
  };
71
160
  }
72
161
 
73
162
  reset(object: Object3D): void {
74
163
  const history = this.#objects.get(object);
75
164
  if (history === undefined) return;
165
+ this.#owner?.__tnPoseReset([object]);
76
166
  history.previousPosition.copy(object.position);
77
167
  history.previousRotation.copy(object.quaternion);
78
168
  history.currentPosition.copy(object.position);
@@ -81,28 +171,50 @@ export class PhysicsInterpolation {
81
171
 
82
172
  clear(): void {
83
173
  this.#objects.clear();
174
+ this.#membership += 1;
84
175
  }
85
176
 
86
177
  beginTick(): void {
87
- for (const history of this.#objects.values()) {
88
- history.previousPosition.copy(history.object.position);
89
- history.previousRotation.copy(history.object.quaternion);
178
+ const owner = this.#owner;
179
+ if (owner !== null) {
180
+ this.#watchIfDirty(owner);
181
+ this.#measured("interpolationTick", "PhysicsInterpolation.beginTick", () =>
182
+ owner.__tnPoseTick(0),
183
+ );
184
+ return;
90
185
  }
186
+ this.#measured("interpolationTick", "PhysicsInterpolation.beginTick", () => {
187
+ for (const history of this.#objects.values()) {
188
+ history.previousPosition.copy(history.object.position);
189
+ history.previousRotation.copy(history.object.quaternion);
190
+ }
191
+ });
91
192
  }
92
193
 
93
194
  endTick(): void {
94
- for (const history of this.#objects.values()) {
95
- history.currentPosition.copy(history.object.position);
96
- history.currentRotation.copy(history.object.quaternion);
195
+ const owner = this.#owner;
196
+ if (owner !== null) {
197
+ this.#measured("interpolationTick", "PhysicsInterpolation.endTick", () =>
198
+ owner.__tnPoseTick(1),
199
+ );
200
+ return;
97
201
  }
202
+ this.#measured("interpolationTick", "PhysicsInterpolation.endTick", () => {
203
+ for (const history of this.#objects.values()) {
204
+ history.currentPosition.copy(history.object.position);
205
+ history.currentRotation.copy(history.object.quaternion);
206
+ }
207
+ });
98
208
  }
99
209
 
100
210
  render<T>(alpha: number, draw: () => T): T {
101
211
  if (!Number.isFinite(alpha) || alpha < 0 || alpha > 1)
102
212
  throw new Error("Interpolation alpha must be in [0, 1].");
213
+ const owner = this.#owner;
103
214
  const report = JSON.stringify({
104
215
  enabled: this.enabled,
105
216
  overrideSource: this.overrideSource,
217
+ path: owner === null ? "javascript" : "engine",
106
218
  trackedObjects: this.#objects.size,
107
219
  });
108
220
  if (report !== this.#lastReport) {
@@ -110,38 +222,57 @@ export class PhysicsInterpolation {
110
222
  console.info(`TN_PHYSICS_INTERPOLATION:${report}`);
111
223
  }
112
224
  if (!this.enabled || alpha === 1) return draw();
225
+ if (owner !== null) {
226
+ // The reference counts, the early returns and the try/finally stay here; the poses move in C++.
227
+ // The watch crosses only when the tracked set changed since the engine last heard of it.
228
+ this.#watchIfDirty(owner);
229
+ this.#measured("interpolationBlend", "PhysicsInterpolation.render", () =>
230
+ owner.__tnPoseBlend(alpha),
231
+ );
232
+ try {
233
+ return draw();
234
+ } finally {
235
+ this.#measured("interpolationRestore", "PhysicsInterpolation.render", () =>
236
+ owner.__tnPoseRestore(),
237
+ );
238
+ }
239
+ }
113
240
  // Retain the exact participants even if Scene.render changes scenes or unregisters a body.
114
241
  const histories = [...this.#objects.values()];
115
242
  try {
116
- for (const history of histories) {
117
- const { object } = history;
118
- // An edit outside the fixed update is a discontinuity, never a new tick to blend across.
119
- if (
120
- !object.position.equals(history.currentPosition) ||
121
- !object.quaternion.equals(history.currentRotation)
122
- )
123
- this.reset(object);
124
- history.savedPosition.copy(object.position);
125
- history.savedRotation.copy(object.quaternion);
126
- object.position.lerpVectors(history.previousPosition, history.currentPosition, alpha);
127
- object.quaternion.slerpQuaternions(
128
- history.previousRotation,
129
- history.currentRotation,
130
- alpha,
131
- );
132
- }
243
+ this.#measured("interpolationBlend", "PhysicsInterpolation.render", () => {
244
+ for (const history of histories) {
245
+ const { object } = history;
246
+ // An edit outside the fixed update is a discontinuity, never a new tick to blend across.
247
+ if (
248
+ !object.position.equals(history.currentPosition) ||
249
+ !object.quaternion.equals(history.currentRotation)
250
+ )
251
+ this.reset(object);
252
+ history.savedPosition.copy(object.position);
253
+ history.savedRotation.copy(object.quaternion);
254
+ object.position.lerpVectors(history.previousPosition, history.currentPosition, alpha);
255
+ object.quaternion.slerpQuaternions(
256
+ history.previousRotation,
257
+ history.currentRotation,
258
+ alpha,
259
+ );
260
+ }
261
+ });
133
262
  return draw();
134
263
  } finally {
135
- for (const history of histories) {
136
- if (
137
- history.object.position.equals(history.savedPosition) &&
138
- history.object.quaternion.equals(history.savedRotation)
139
- )
140
- continue;
141
- history.object.position.copy(history.savedPosition);
142
- history.object.quaternion.copy(history.savedRotation);
143
- recompose(history.object);
144
- }
264
+ this.#measured("interpolationRestore", "PhysicsInterpolation.render", () => {
265
+ for (const history of histories) {
266
+ if (
267
+ history.object.position.equals(history.savedPosition) &&
268
+ history.object.quaternion.equals(history.savedRotation)
269
+ )
270
+ continue;
271
+ history.object.position.copy(history.savedPosition);
272
+ history.object.quaternion.copy(history.savedRotation);
273
+ recompose(history.object);
274
+ }
275
+ });
145
276
  }
146
277
  }
147
278
  }