@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/auto-batch.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { type BufferGeometry, type Material, type Mesh, Object3D } from "three";
1
+ import { type BufferGeometry, type Layers, type Material, type Mesh, Object3D } from "three";
2
2
 
3
3
  import { isEngineRenderHook } from "./engine-render-hook.js";
4
4
  import type { Registry } from "./entities.js";
5
5
  import { mergeByMaterial } from "./merge-parts.js";
6
+ import { isStreamedGeometry } from "./model-lod.js";
6
7
  import { displacesVertices, hasMorphAttributes } from "./projection-plan.js";
7
8
  import { unbilled } from "./startup-offscreen-bytes.js";
8
9
 
@@ -25,6 +26,13 @@ import { unbilled } from "./startup-offscreen-bytes.js";
25
26
  * geometry, no render hook, no skin, morph, instancing or vertex displacement. Everything else keeps
26
27
  * its draw. The merged mesh keeps the game's own material and shadow, layer and render-order flags.
27
28
  *
29
+ * **The game never sees the merge.** A source is kept out of the draw without touching anything the game
30
+ * reads or copies: the engine's own `__tnBatchHidden` flag, or on plain three a `layers` view that answers
31
+ * the renderer's `test` with `false` and the game's `mask` with its own value. `visible` stays the game's,
32
+ * so a game that saves and restores visibility (a warm-up that shows everything to compile it) or clones a
33
+ * merged source gets back exactly what it authored. Hiding through `visible` let Midway's warm-up re-hide a
34
+ * given-back control stick for good, and a clone inherit the hide.
35
+ *
28
36
  * **Named overrides, both reported.** `userData.batch = "off"` on a mesh or any ancestor keeps that
29
37
  * subtree out. `autoBatch: false` in the game config switches the pass off.
30
38
  */
@@ -56,8 +64,10 @@ const ENGINE_GUARD_CHUNK = 2048;
56
64
  * compares it in place, so a lap of 8,000 sources fits the budget the JS slice spent on 200.
57
65
  */
58
66
  interface IEngineGuard {
59
- __tnGuardWatch(sources: readonly Mesh[]): number;
67
+ __tnGuardWatch(sources: readonly Mesh[], ancestors?: readonly Object3D[]): number;
60
68
  __tnGuardCheck(limit: number): ArrayLike<number>;
69
+ /** PRD-828: the sources' ancestors, checked whole in the engine; absent on an older engine. */
70
+ __tnGuardCheckAncestors?(): ArrayLike<number>;
61
71
  }
62
72
 
63
73
  function engineGuardOf(scene: Object3D): IEngineGuard | undefined {
@@ -254,6 +264,57 @@ function stampMatches(object: Object3D, stamp: Float64Array): boolean {
254
264
  return true;
255
265
  }
256
266
 
267
+ /** Each plain-three source's own `Layers`, kept while a view stands in for it. */
268
+ const ownLayers = new WeakMap<Object3D, Layers>();
269
+
270
+ /** Nonzero while core draws the world; only then does a plain-three source's view fail the layer test. */
271
+ let drawingWorld = 0;
272
+
273
+ /**
274
+ * Runs core's world draw. On plain three a merged source is out of the renderer's layer test only in
275
+ * here, so a game's own raycast or `layers.test` still finds it, as it did before the merge.
276
+ */
277
+ export function drawWorld<T>(draw: () => T): T {
278
+ drawingWorld += 1;
279
+ try {
280
+ return draw();
281
+ } finally {
282
+ drawingWorld -= 1;
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Takes a merged source out of the draw, or puts it back, leaving every property the game reads as it was.
288
+ * The engine hides it natively; on plain three, the renderer and shadow passes ask `layers.test(camera)`,
289
+ * and a view whose `test` fails inside {@link drawWorld} and whose `mask` reads and writes the source's own
290
+ * `Layers` hides it from that draw alone. A clone copies `mask`, so it copies the game's layers, not the hide.
291
+ */
292
+ function setBatchHidden(mesh: Mesh, hidden: boolean): void {
293
+ const engine = mesh as Mesh & { __tnBatchHidden?: boolean };
294
+ if ("__tnBatchHidden" in engine) {
295
+ engine.__tnBatchHidden = hidden;
296
+ return;
297
+ }
298
+ if (!hidden) {
299
+ const own = ownLayers.get(mesh);
300
+ if (own !== undefined) mesh.layers = own;
301
+ ownLayers.delete(mesh);
302
+ return;
303
+ }
304
+ if (ownLayers.has(mesh)) return;
305
+ const own = mesh.layers;
306
+ ownLayers.set(mesh, own);
307
+ mesh.layers = Object.create(Object.getPrototypeOf(own) as object, {
308
+ mask: {
309
+ get: () => own.mask,
310
+ set: (mask: number) => {
311
+ own.mask = mask;
312
+ },
313
+ },
314
+ test: { value: (layers: Layers) => drawingWorld === 0 && own.test(layers) },
315
+ }) as Layers;
316
+ }
317
+
257
318
  function isMesh(object: Object3D): object is Mesh {
258
319
  return (object as Mesh).isMesh === true;
259
320
  }
@@ -290,9 +351,17 @@ function bakeable(geometry: BufferGeometry): boolean {
290
351
  return true;
291
352
  }
292
353
 
293
- /** Whether merging this mesh leaves the frame looking the same. */
354
+ /**
355
+ * Whether merging this mesh leaves the frame looking the same. A streamed coarse model stays out:
356
+ * its full file replaces the geometry in place, and a merged copy would keep the coarse vertices.
357
+ */
294
358
  function mergeable(mesh: Mesh): boolean {
295
- return plainDraw(mesh) && bakeable(mesh.geometry) && mesh.matrixWorld.determinant() > 0;
359
+ return (
360
+ plainDraw(mesh) &&
361
+ bakeable(mesh.geometry) &&
362
+ !isStreamedGeometry(mesh.geometry) &&
363
+ mesh.matrixWorld.determinant() > 0
364
+ );
296
365
  }
297
366
 
298
367
  /** Meshes with equal keys can share a merged mesh without changing how any of them draws. */
@@ -340,6 +409,8 @@ export class AutoBatch {
340
409
  readonly #excluded = new WeakSet<Object3D>();
341
410
  #records: IRecord[] = [];
342
411
  readonly #ancestors = new Map<Object3D, IAncestor>();
412
+ /** The ancestors in the order the engine's guard watches them, so its indices name them. */
413
+ #watchedAncestors: Object3D[] = [];
343
414
  #watched = new Map<Mesh, Float64Array>();
344
415
  #state: State = "idle";
345
416
  #known = Number.NaN;
@@ -366,12 +437,24 @@ export class AutoBatch {
366
437
  readonly #levelOne = new Set<Object3D>();
367
438
  /** Children added to or removed from the scene since the last frame, to start or stop counting. */
368
439
  #arrived: Object3D[] = [];
369
- readonly #onTopChild = (event: { child: Object3D }): void => {
440
+ /**
441
+ * The subtrees a scan walks: what was added at the top two levels since the last finished scan, plus what an
442
+ * earlier scan could not merge yet (a hidden subtree, a mesh that moved while watched, a mesh with no partner).
443
+ * A scan costs what arrived and what still waits, never the scene: ten thrown objects a second re-walked the
444
+ * stress lab's 5,000 nodes after every add and every remove, 4.1 ms of a 9.8 ms frame.
445
+ * ponytail: a mesh with no partner is walked by every scan; index those by material when a scene holds thousands.
446
+ */
447
+ #pending = new Set<Object3D>();
448
+ /** What the scan in progress met and left for the next one: hidden subtrees. */
449
+ #later = new Set<Object3D>();
450
+ readonly #onTopChild = (event: { type: string; child: Object3D }): void => {
370
451
  this.#shapeChanges += 1;
371
452
  this.#arrived.push(event.child);
453
+ if (event.type === "childadded") this.#pending.add(event.child);
372
454
  };
373
- readonly #onChild = (): void => {
455
+ readonly #onChild = (event: { type: string; child: Object3D }): void => {
374
456
  this.#shapeChanges += 1;
457
+ if (event.type === "childadded") this.#pending.add(event.child);
375
458
  };
376
459
 
377
460
  constructor(scene: Object3D, options: IAutoBatchOptions = {}) {
@@ -386,6 +469,7 @@ export class AutoBatch {
386
469
  scene.addEventListener("childadded", this.#onTopChild);
387
470
  scene.addEventListener("childremoved", this.#onTopChild);
388
471
  this.#arrived = [...scene.children];
472
+ this.#pending = new Set(this.#arrived);
389
473
  }
390
474
 
391
475
  get census(): IAutoBatchCensus {
@@ -435,6 +519,7 @@ export class AutoBatch {
435
519
  this.#frames = 0;
436
520
  if (this.#watched.size < 2) {
437
521
  // Nothing here can share a draw: the pass is finished until the scene's shape changes.
522
+ this.#finish(this.#watched);
438
523
  this.#known = shape;
439
524
  this.#state = "idle";
440
525
  }
@@ -452,6 +537,7 @@ export class AutoBatch {
452
537
  if (!this.#enabled) return;
453
538
  const meshes = this.#snapshot();
454
539
  if (meshes.size >= 2) this.#merge([...meshes.keys()]);
540
+ this.#finish(meshes);
455
541
  this.#watchEngine();
456
542
  this.#known = this.#shape();
457
543
  this.#state = "idle";
@@ -461,11 +547,13 @@ export class AutoBatch {
461
547
  reset(): void {
462
548
  for (const record of this.#records) if (!record.out) this.#giveBack(record);
463
549
  this.#records = [];
464
- this.#watchEngine();
465
550
  this.#ancestors.clear();
551
+ this.#watchEngine();
466
552
  this.#watched.clear();
467
553
  this.#state = "idle";
468
554
  this.#known = Number.NaN;
555
+ // The next scene's content arrives through the events; what stays under the scene is scanned once more.
556
+ this.#pending = new Set(this.#scene.children);
469
557
  }
470
558
 
471
559
  /**
@@ -491,50 +579,83 @@ export class AutoBatch {
491
579
  }
492
580
 
493
581
  /**
494
- * Eligible meshes with the world matrix they were drawn at. Runs only while the scene settles, so
495
- * its reads are no game's steady cost and the bridge census leaves them out.
582
+ * Eligible meshes under the pending subtrees, with the world matrix they were drawn at. Runs only while
583
+ * the scene settles, so its reads are no game's steady cost and the bridge census leaves them out.
496
584
  */
497
585
  #snapshot(): Map<Mesh, Float64Array> {
498
586
  return unbilled(() => {
499
- this.#scene.updateMatrixWorld(true);
500
587
  const found = new Map<Mesh, Float64Array>();
501
588
  this.#optedOut = 0;
502
589
  this.#held = 0;
590
+ this.#later = new Set();
503
591
  const held = heldObjects(this.#entities);
504
- this.#walk(this.#scene, false, held, (mesh) => {
592
+ const visit = (mesh: Mesh): void => {
505
593
  found.set(mesh, Float64Array.from(mesh.matrixWorld.elements));
506
- });
594
+ };
595
+ for (const root of [...this.#pending]) {
596
+ const off = this.#hangs(root, held);
597
+ if (off === "gone") this.#pending.delete(root);
598
+ else if (off === "wait") this.#later.add(root);
599
+ else {
600
+ root.updateWorldMatrix(true, true);
601
+ this.#visit(root, off, held, visit);
602
+ }
603
+ }
507
604
  return found;
508
605
  });
509
606
  }
510
607
 
511
- #walk(
512
- object: Object3D,
608
+ /**
609
+ * How a pending subtree hangs under the scene. `gone`: it left the scene, or a pending ancestor walks it.
610
+ * `wait`: an ancestor is hidden, held or an LOD, which the game can change. Else whether an ancestor opted it out.
611
+ */
612
+ #hangs(root: Object3D, held: ReadonlySet<Object3D>): boolean | "gone" | "wait" {
613
+ let off = false;
614
+ let wait = false;
615
+ for (let node = root.parent; node !== this.#scene; node = node.parent) {
616
+ if (node === null || this.#excluded.has(node) || this.#pending.has(node)) return "gone";
617
+ wait ||= !node.visible || (node as { isLOD?: boolean }).isLOD === true || held.has(node);
618
+ off ||= node.userData.batch === "off";
619
+ }
620
+ return wait ? "wait" : off;
621
+ }
622
+
623
+ /**
624
+ * Ends a scan: the next one walks what this one left (`#later`) and each mesh it found that no merge took.
625
+ * A mesh that moved can come to rest, and a mesh with no partner can get one.
626
+ */
627
+ #finish(found: ReadonlyMap<Mesh, Float64Array>): void {
628
+ this.#pending = this.#later;
629
+ this.#later = new Set();
630
+ for (const mesh of found.keys()) if (!sourceGroups.has(mesh)) this.#pending.add(mesh);
631
+ }
632
+
633
+ #visit(
634
+ child: Object3D,
513
635
  off: boolean,
514
636
  held: ReadonlySet<Object3D>,
515
637
  visit: (mesh: Mesh) => void,
516
638
  ): void {
517
- for (const child of object.children) {
518
- if (
519
- !child.visible ||
520
- this.#excluded.has(child) ||
521
- (child as { isLOD?: boolean }).isLOD === true
522
- )
523
- continue;
524
- if (held.has(child)) {
525
- const parts = countMeshes(child);
526
- if (parts <= HELD_SUBTREE_MAX_MESHES) {
527
- this.#held += parts;
528
- continue;
529
- }
530
- }
531
- const skip = off || child.userData.batch === "off";
532
- if (isMesh(child) && mergeable(child)) {
533
- if (skip) this.#optedOut += 1;
534
- else visit(child);
639
+ if (!child.visible) {
640
+ // Hidden now; the game can show it, so the next scan asks again.
641
+ this.#later.add(child);
642
+ return;
643
+ }
644
+ if (this.#excluded.has(child) || (child as { isLOD?: boolean }).isLOD === true) return;
645
+ if (held.has(child)) {
646
+ const parts = countMeshes(child);
647
+ if (parts <= HELD_SUBTREE_MAX_MESHES) {
648
+ this.#held += parts;
649
+ return;
535
650
  }
536
- this.#walk(child, skip, held, visit);
537
651
  }
652
+ const skip = off || child.userData.batch === "off";
653
+ // A source already drawn by a merge is not walked into a second one: its `visible` stays true.
654
+ if (isMesh(child) && !sourceGroups.has(child) && mergeable(child)) {
655
+ if (skip) this.#optedOut += 1;
656
+ else visit(child);
657
+ }
658
+ for (const part of child.children) this.#visit(part, skip, held, visit);
538
659
  }
539
660
 
540
661
  #settle(): void {
@@ -551,6 +672,7 @@ export class AutoBatch {
551
672
  this.#unsettled = moved;
552
673
  this.#watched = new Map();
553
674
  this.#merge([...stable.keys()]);
675
+ this.#finish(now);
554
676
  this.#watchEngine();
555
677
  this.#known = this.#shape();
556
678
  this.#state = "idle";
@@ -629,8 +751,8 @@ export class AutoBatch {
629
751
  };
630
752
  vertexStart += vertexCount;
631
753
  // The source stays where the game put it, so rays, `userData` and world matrices keep working.
632
- // Only the renderer is told not to draw it.
633
- mesh.visible = false;
754
+ // Only the renderer is told not to draw it; `visible` stays the game's.
755
+ setBatchHidden(mesh, true);
634
756
  writeStamp(mesh, record.stamp);
635
757
  group.sources.push(record);
636
758
  sourceGroups.set(mesh, group);
@@ -674,15 +796,33 @@ export class AutoBatch {
674
796
  /** Every frame, because there are few ancestors and one moved parent changes thousands of sources. */
675
797
  #checkAncestors(): number {
676
798
  let given = 0;
799
+ const engine = this.#engine;
800
+ if (engine?.__tnGuardCheckAncestors !== undefined) {
801
+ const changed = engine.__tnGuardCheckAncestors();
802
+ for (let at = 0; at < changed.length; at += 1) {
803
+ const node = this.#watchedAncestors[changed[at] as number];
804
+ if (node !== undefined) given += this.#giveBackUnder(node);
805
+ }
806
+ return given;
807
+ }
677
808
  for (const [node, entry] of this.#ancestors) {
678
809
  if (node.parent === entry.parent && stampMatches(node, entry.stamp)) continue;
679
- this.#excluded.add(node);
680
- this.#ancestors.delete(node);
681
- for (const record of entry.records) {
682
- if (record.out) continue;
683
- this.#giveBack(record);
684
- given += 1;
685
- }
810
+ given += this.#giveBackUnder(node);
811
+ }
812
+ return given;
813
+ }
814
+
815
+ /** An ancestor moved: it never merges again, and every source under it goes back to the game. */
816
+ #giveBackUnder(node: Object3D): number {
817
+ const entry = this.#ancestors.get(node);
818
+ if (entry === undefined) return 0;
819
+ let given = 0;
820
+ this.#excluded.add(node);
821
+ this.#ancestors.delete(node);
822
+ for (const record of entry.records) {
823
+ if (record.out) continue;
824
+ this.#giveBack(record);
825
+ given += 1;
686
826
  }
687
827
  return given;
688
828
  }
@@ -692,7 +832,12 @@ export class AutoBatch {
692
832
  * and each give-back, so no game code runs between the state merged and the state watched.
693
833
  */
694
834
  #watchEngine(): void {
695
- this.#engine?.__tnGuardWatch(this.#records.map((record) => record.mesh));
835
+ if (this.#engine === undefined) return;
836
+ this.#watchedAncestors = [...this.#ancestors.keys()];
837
+ this.#engine.__tnGuardWatch(
838
+ this.#records.map((record) => record.mesh),
839
+ this.#watchedAncestors,
840
+ );
696
841
  }
697
842
 
698
843
  /** A slice of the sources bounded by {@link GUARD_BUDGET_MS}, or all of them under `everyFrame`. */
@@ -764,7 +909,8 @@ export class AutoBatch {
764
909
  this.#excluded.add(record.mesh);
765
910
  this.#restored += 1;
766
911
  this.#meshes -= 1;
767
- record.mesh.visible = true;
912
+ // Drawn on its own again, as the game now has it: a source the game hid stays hidden.
913
+ setBatchHidden(record.mesh, false);
768
914
  const { group } = record;
769
915
  group.live -= 1;
770
916
  if (group.live > 0) this.#collapse(record);
@@ -113,7 +113,7 @@ export class ComputeDrivenRegistry {
113
113
  ): void {
114
114
  const simulatedSeconds =
115
115
  simulation === undefined ? undefined : simulation.tick() * simulation.step;
116
- if (camera !== undefined) {
116
+ if (camera !== undefined && !this.#significance.idle) {
117
117
  const candidates: IBudgetCandidate[] = [];
118
118
  for (const { object, driven } of this.#entries.values()) {
119
119
  if (
package/src/config.ts CHANGED
@@ -336,6 +336,14 @@ export interface IThreeNativeConfig {
336
336
  readonly orientation?: ThreeNativeOrientation;
337
337
  readonly fullscreen?: boolean;
338
338
  readonly keepScreenOn?: boolean;
339
+ /**
340
+ * CPU priority of a shipped native game (PRD-859). `"game"`, the default, raises the game, render
341
+ * and present threads above other programs and lowers the game's own background work (shader
342
+ * compiles, workers, the HUD processes), through the route each OS allows without admin rights.
343
+ * `"normal"` keeps the OS default. The player reports what the OS applied on its
344
+ * `TN_PROCESS_PRIORITY` line. The browser owns scheduling, so a web build ignores it.
345
+ */
346
+ readonly priority?: "game" | "normal";
339
347
  /**
340
348
  * Maximum native presentation rate in frames per second. Left out, it follows the display's own
341
349
  * refresh rate capped at 120 on desktop and web, and stays 60 on mobile where the ceiling is
package/src/debug.ts CHANGED
@@ -3,18 +3,112 @@
3
3
  *
4
4
  * Two questions an agent answers differently in every game, both of which cost a rewrite: how do I
5
5
  * turn this on for one run without changing the code, and how does a capture script reach the object
6
- * it wants to look at. The answers here are one function each, and neither decides how anything
7
- * looks.
6
+ * it wants to look at. The answers here are one function each, neither decides how anything looks.
8
7
  */
9
8
 
10
- /** The shared global the engine's dev surfaces and `exposeDebug` both publish under. */
11
- const HOST_KEY = "__THREENATIVE__";
9
+ import { devGlobal, publishDevGlobal } from "./dev-global.js";
12
10
 
13
11
  /** `freeCam` → `FREE_CAM`. A name a developer typed becomes a name a shell can set. */
14
12
  function envName(name: string): string {
15
13
  return `TN_DEBUG_${name.replace(/([a-z0-9])([A-Z])/gu, "$1_$2").toUpperCase()}`;
16
14
  }
17
15
 
16
+ /**
17
+ * The three seams a launch has, named once. A native host sets the environment variable, a browser
18
+ * page asks with the query parameter, and a test or capture harness sets the global before boot.
19
+ */
20
+ export interface ILaunchFlagSpec {
21
+ /** Environment variable a native host sets, e.g. `TN_TERRAIN_VALIDATE`. */
22
+ readonly environment: string;
23
+ /** Query parameter a browser asks with, e.g. `tnTerrainValidate`. */
24
+ readonly query: string;
25
+ /** Global a test or harness sets before the game boots, e.g. `__tnTerrainValidate`. */
26
+ readonly global?: string;
27
+ }
28
+
29
+ /**
30
+ * Every seam that named `flag`, in the order they are read: environment, query string, global.
31
+ *
32
+ * An empty environment variable is skipped — a shell that exports a name with no value did not ask
33
+ * for anything — while an empty value on any other seam means the seam named the flag and had no
34
+ * value to give, which is a URL's way of saying yes.
35
+ */
36
+ function readLaunchSeams(spec: ILaunchFlagSpec, search?: string): readonly string[] {
37
+ const values: string[] = [];
38
+ if (spec.environment.length > 0) {
39
+ const env = envValue(spec.environment);
40
+ if (env !== undefined && env !== "") values.push(env);
41
+ }
42
+ const query = search ?? globalThis.location?.search;
43
+ if (typeof query === "string") {
44
+ const fromQuery = new URLSearchParams(query).get(spec.query);
45
+ if (fromQuery !== null) values.push(fromQuery);
46
+ }
47
+ if (spec.global !== undefined) {
48
+ const fromGlobal: unknown = (globalThis as Record<string, unknown>)[spec.global];
49
+ if (typeof fromGlobal === "string") values.push(fromGlobal);
50
+ else if (typeof fromGlobal === "number") values.push(String(fromGlobal));
51
+ else if (typeof fromGlobal === "boolean") values.push(fromGlobal ? "true" : "false");
52
+ }
53
+ return values;
54
+ }
55
+
56
+ /** `0` and `false` are the only two spellings of off; a named-but-empty value is on. */
57
+ function isOff(value: string): boolean {
58
+ return value === "0" || value === "false";
59
+ }
60
+
61
+ /**
62
+ * Whether this launch asked for a flag, on one rule for every subsystem.
63
+ *
64
+ * `askedFor` says which answer the caller cares about: an opt-in switch (`"on"`, the default) is off
65
+ * when no seam asked for it, and an opt-out switch (`"off"`) is on unless some seam asked it off.
66
+ * Every seam that names the flag is heard, so a global a test sets is not lost behind an environment
67
+ * variable that happens to disagree; what changes from the sixteen hand-written readers this
68
+ * replaces is the vocabulary, not the seams: `0` and `false` are off and everything else is on.
69
+ *
70
+ * `search` is the query string to read, for a caller that already read the URL once at setup.
71
+ *
72
+ * @situation read one of the engine's launch switches the same way every subsystem does
73
+ * @example const validate = readLaunchFlag({ environment: "TN_TERRAIN_VALIDATE", query: "tnTerrainValidate" });
74
+ * @constraint `0` and `false` are off; a named-but-empty value is on; an empty variable is unset
75
+ */
76
+ export function readLaunchFlag(
77
+ spec: ILaunchFlagSpec,
78
+ askedFor: "on" | "off" = "on",
79
+ search?: string,
80
+ ): boolean {
81
+ const values = readLaunchSeams(spec, search);
82
+ return askedFor === "off"
83
+ ? values.some((value) => isOff(value))
84
+ : values.some((value) => !isOff(value));
85
+ }
86
+
87
+ /**
88
+ * The text this launch gave a flag, or `undefined` when no seam named it.
89
+ *
90
+ * For switches whose value is not a yes or no — an occlusion mode, a numeric override — the caller
91
+ * parses. An empty string means a seam named the flag with no value.
92
+ *
93
+ * @situation read a launch override whose value is not a boolean
94
+ * @example const mode = readLaunchValue({ environment: "TN_OCCLUSION", query: "tnOcclusion" });
95
+ */
96
+ export function readLaunchValue(spec: ILaunchFlagSpec): string | undefined {
97
+ return readLaunchSeams(spec)[0];
98
+ }
99
+
100
+ /**
101
+ * Every value this launch gave a flag, one per seam that named it, in the order they are read.
102
+ *
103
+ * For the switches whose answer is not a yes or a no — a tri-state, a table of spellings — the
104
+ * caller classifies the whole set rather than only the first seam's answer.
105
+ *
106
+ * @situation classify every value a launch gave one switch
107
+ */
108
+ export function readLaunchValues(spec: ILaunchFlagSpec): readonly string[] {
109
+ return readLaunchSeams(spec);
110
+ }
111
+
18
112
  /**
19
113
  * `process.env` on a host that installed one, narrowed rather than asserted exactly as
20
114
  * `isDevLaunch` does in `game.ts`: it exists on the native runtime and not in a browser bundle.
@@ -31,15 +125,10 @@ function envValue(name: string): string | undefined {
31
125
  return typeof value === "string" ? value : undefined;
32
126
  }
33
127
 
34
- /** Not one of the two spellings of off. */
35
- function isOn(value: string): boolean {
36
- return value !== "0" && value !== "false";
37
- }
38
-
39
128
  /**
40
129
  * A debug switch read from the URL, or from the environment on a native launch.
41
130
  *
42
- * @situation read a debug toggle from the URL or an environment variable
131
+ * @situation read a debug toggle from the URL, an environment variable or a harness global
43
132
  *
44
133
  * A browser asks with the query string — `?freeCam`, or `?freeCam=0` to force it off — and a native
45
134
  * launch asks with `TN_DEBUG_FREE_CAM`, because a query string is not something a developer sets on
@@ -47,14 +136,7 @@ function isOn(value: string): boolean {
47
136
  * "off" rather than quietly turning it back on.
48
137
  */
49
138
  export function debugFlag(name: string): boolean {
50
- // An exported-but-empty variable is off, as `DEV_MODE=` is to the engine's own reader; a bare
51
- // `?freeCam` is on, because the query string has no other way to say it.
52
- const env = envValue(envName(name));
53
- if (env !== undefined && env !== "" && isOn(env)) return true;
54
- const search: unknown = globalThis.location?.search;
55
- if (typeof search !== "string") return false;
56
- const value = new URLSearchParams(search).get(name);
57
- return value !== null && isOn(value);
139
+ return readLaunchFlag({ environment: envName(name), query: name });
58
140
  }
59
141
 
60
142
  /**
@@ -74,9 +156,8 @@ export function exposeDebug(name: string, value: unknown): void {
74
156
  const isDev =
75
157
  (import.meta as ImportMeta & { env?: Record<"DEV", boolean | undefined> }).env?.DEV === true;
76
158
  if (!isDev) return;
77
- const tools = (Reflect.get(globalThis, HOST_KEY) ?? {}) as { debug?: Record<string, unknown> };
78
- const debug = tools.debug ?? {};
159
+ const tools = devGlobal(globalThis) ?? {};
160
+ const debug = (tools.debug as Record<string, unknown> | undefined) ?? {};
79
161
  debug[name] = value;
80
- tools.debug = debug;
81
- Reflect.set(globalThis, HOST_KEY, tools);
162
+ publishDevGlobal("debug", debug, globalThis);
82
163
  }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The one owner of `__THREENATIVE__`, the object every dev surface publishes under.
3
+ *
4
+ * Five places used to spell the key itself — the debug flag, hot reload, the game's dev tools, the
5
+ * UI overlay and the engine's export — so the global's name and its shape were written twice at
6
+ * least. The worker keeps its own mirror list: that list is a typed tuple its mirror machinery is
7
+ * built from, and moving it here changed what the worker host forwarded.
8
+ *
9
+ * Nothing here decides how anything looks: it is the seam a capture script, the console and the dev
10
+ * overlay reach the running game through.
11
+ */
12
+
13
+ /** The property name a dev surface publishes under, on the window and on a worker's global. */
14
+ export const DEV_GLOBAL_KEY = "__THREENATIVE__";
15
+
16
+ /** What the game's own dev tools publish: a snapshot, and an armed geometry capture. */
17
+ export interface IDevTools {
18
+ snapshot(): import("./entities.js").EntitySnapshot;
19
+ /**
20
+ * Arms one per-object geometry capture for a development overlay. Absent until the game has a
21
+ * render loop; the overlay treats that as "not ready", never as an empty scene.
22
+ */
23
+ geometry?(
24
+ request?: import("./geometry-capture.js").IGeometryCaptureRequest,
25
+ ): Promise<import("./geometry-capture.js").IGeometryCaptureReport>;
26
+ }
27
+
28
+ /** What a dev surface may publish under {@link DEV_GLOBAL_KEY}. */
29
+ export type DevGlobal = Partial<IDevTools> & Record<string, unknown>;
30
+
31
+ /**
32
+ * The global a host installed, or `undefined` outside a dev launch.
33
+ *
34
+ * `scope` is required on purpose: a default of `globalThis` would make an explicit `undefined` read
35
+ * the page's global, which is exactly the worker case a caller is asking about.
36
+ */
37
+ export function devGlobal(scope: unknown): DevGlobal | undefined {
38
+ const value = (scope as Record<string, unknown> | undefined)?.[DEV_GLOBAL_KEY];
39
+ return typeof value === "object" && value !== null ? (value as DevGlobal) : undefined;
40
+ }
41
+
42
+ /** Adds one member to the global, keeping whatever another surface already published. */
43
+ export function publishDevGlobal(name: string, value: unknown, scope: unknown): void {
44
+ const host = scope as Record<string, unknown> | undefined;
45
+ if (host === undefined) return;
46
+ // In place: a surface that published earlier keeps its identity, which is what lets a disposer
47
+ // check `devGlobal(host) === mine` and leave another surface's members alone.
48
+ const current = devGlobal(scope);
49
+ if (current !== undefined) {
50
+ current[name] = value;
51
+ return;
52
+ }
53
+ host[DEV_GLOBAL_KEY] = { [name]: value };
54
+ }
@@ -0,0 +1,37 @@
1
+ import type { Matrix4, Object3D } from "three";
2
+
3
+ /**
4
+ * The method the owned engine puts on every `Object3D` to copy its world matrix into a caller's
5
+ * `Matrix4`. Plain three.js has no such method and reads `matrixWorld` instead.
6
+ *
7
+ * The engine defines this name in `runtime-native/src/engine/abi/bindings_scene.cpp` and probes it in
8
+ * `adapters/v8/math/entry.js`. `__tests__/engine-hooks.spec.ts` holds those two copies to this one,
9
+ * so a rename on either side fails a spec instead of silently taking every caller down the slow path.
10
+ */
11
+ export const COPY_MATRIX_WORLD_HOOK = "__tnCopyMatrixWorld";
12
+
13
+ type CopyMatrixWorld = (target: Matrix4) => void;
14
+
15
+ /** An `Object3D` that may carry the engine's hook; the property is absent on plain three.js. */
16
+ type HookCarrier = Object3D & { readonly [COPY_MATRIX_WORLD_HOOK]?: unknown };
17
+
18
+ function hookOf(object: Object3D): CopyMatrixWorld | undefined {
19
+ const hook = (object as HookCarrier)[COPY_MATRIX_WORLD_HOOK];
20
+ return typeof hook === "function" ? (hook as CopyMatrixWorld) : undefined;
21
+ }
22
+
23
+ /** Whether `object` belongs to the owned engine, which copies world matrices out instead of aliasing them. */
24
+ export function hasCopyMatrixWorldHook(object: Object3D): boolean {
25
+ return hookOf(object) !== undefined;
26
+ }
27
+
28
+ /**
29
+ * Copy `object`'s current world matrix into `target` through the engine's hook.
30
+ * @returns false when the object has no hook, so the caller reads `object.matrixWorld` itself
31
+ */
32
+ export function copyMatrixWorld(object: Object3D, target: Matrix4): boolean {
33
+ const hook = hookOf(object);
34
+ if (hook === undefined) return false;
35
+ hook.call(object, target);
36
+ return true;
37
+ }