@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
@@ -233,17 +233,13 @@ type NormalElements = readonly [
233
233
  * Positions of one part, placed, written into `values` at `at`.
234
234
  *
235
235
  * The expression is three's `Vector3.applyMatrix4` term for term over the same elements in the same
236
- * order, including its homogeneous divide, so a merged buffer holds the values it held before. The
237
- * second half of it is what `setXYZ` wrote back into the part's own typed array before the
238
- * de-quantizing copy read it again: `normalize` rounds into the channel's own range — the scratch
239
- * store keeps a value outside that range wrapping exactly as three's store did — and `denormalize`
240
- * reads it back as a float.
236
+ * order, including its homogeneous divide. A placed position leaves a quantized channel's range, so
237
+ * it goes straight to float and never back into the channel's own type.
241
238
  */
242
239
  function writePosition(
243
240
  channel: IChannel,
244
241
  indices: Uint16Array | Uint32Array | null,
245
242
  elements: PlacementElements | null,
246
- scratch: IScratch | null,
247
243
  values: Float32Array,
248
244
  at: number,
249
245
  ): void {
@@ -271,14 +267,6 @@ function writePosition(
271
267
  pz = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
272
268
  }
273
269
  const out = at + vertex * 3;
274
- if (scratch !== null) {
275
- scratch[0] = Math.round(px * scale);
276
- scratch[1] = Math.round(py * scale);
277
- scratch[2] = Math.round(pz * scale);
278
- px = Math.max((scratch[0] as number) / scale, -1);
279
- py = Math.max((scratch[1] as number) / scale, -1);
280
- pz = Math.max((scratch[2] as number) / scale, -1);
281
- }
282
270
  values[out] = px;
283
271
  values[out + 1] = py;
284
272
  values[out + 2] = pz;
@@ -399,6 +387,15 @@ function scratchOf(array: IRawNumbers): IScratch | null {
399
387
  return null;
400
388
  }
401
389
 
390
+ /** A channel as plain float, read through its own accessors so normalization and interleaving resolve. */
391
+ function floatCopy(attribute: BufferAttribute | InterleavedBufferAttribute): BufferAttribute {
392
+ const values = new Float32Array(attribute.count * attribute.itemSize);
393
+ for (let index = 0; index < attribute.count; index += 1)
394
+ for (let component = 0; component < attribute.itemSize; component += 1)
395
+ values[index * attribute.itemSize + component] = attribute.getComponent(index, component);
396
+ return new BufferAttribute(values, attribute.itemSize);
397
+ }
398
+
402
399
  function flatten(
403
400
  part: IMergePart,
404
401
  paint: boolean,
@@ -406,6 +403,10 @@ function flatten(
406
403
  deindex: boolean,
407
404
  ): BufferGeometry {
408
405
  const placed = part.geometry.clone();
406
+ // Placed before it is float, a quantized position is stored back into its own range and clamps.
407
+ const position = placed.getAttribute("position");
408
+ if (position !== undefined && (!(position.array instanceof Float32Array) || position.normalized))
409
+ placed.setAttribute("position", floatCopy(position));
409
410
  const matrix = placementMatrix(part);
410
411
  if (matrix !== undefined) placed.applyMatrix4(matrix);
411
412
  const flat = deindex && placed.index !== null ? placed.toNonIndexed() : placed;
@@ -428,17 +429,13 @@ function flatten(
428
429
  !("isInterleavedBufferAttribute" in attribute)
429
430
  )
430
431
  continue;
431
- const values = new Float32Array(attribute.count * attribute.itemSize);
432
- for (let index = 0; index < attribute.count; index += 1)
433
- for (let component = 0; component < attribute.itemSize; component += 1)
434
- values[index * attribute.itemSize + component] = attribute.getComponent(index, component);
435
- flat.setAttribute(name, new BufferAttribute(values, attribute.itemSize));
432
+ flat.setAttribute(name, floatCopy(attribute));
436
433
  }
437
- const position = flat.getAttribute("position");
438
- if (!paint || position === undefined) return flat;
434
+ const flatPosition = flat.getAttribute("position");
435
+ if (!paint || flatPosition === undefined) return flat;
439
436
  const tone = new Color(part.color);
440
- const painted = new Float32Array(position.count * 3);
441
- for (let vertex = 0; vertex < position.count; vertex += 1) {
437
+ const painted = new Float32Array(flatPosition.count * 3);
438
+ for (let vertex = 0; vertex < flatPosition.count; vertex += 1) {
442
439
  painted[vertex * 3] = tone.r;
443
440
  painted[vertex * 3 + 1] = tone.g;
444
441
  painted[vertex * 3 + 2] = tone.b;
@@ -602,7 +599,6 @@ function writeChannel(
602
599
  indices,
603
600
  // quality-allow: Matrix4.elements is number[] in three's types and always 16 long.
604
601
  matrix === undefined ? null : (matrix.elements as unknown as PlacementElements),
605
- scratchOf(channel.array),
606
602
  values,
607
603
  at,
608
604
  );
package/src/model-lod.ts CHANGED
@@ -130,6 +130,16 @@ export function biasedLodDistance(distance: number): number {
130
130
 
131
131
  const nearest = new Vector3();
132
132
 
133
+ /**
134
+ * The near plane a caller with no camera `near` uses for the degenerate test.
135
+ *
136
+ * `degenerate` is whether the sphere's nearest surface reaches the camera plane (`depth <= near`).
137
+ * Two callers used `0.1` and the rest `0`, so a camera with no `near` answered two different
138
+ * questions; this is the one value, and it is `0` because the test is about the surface reaching the
139
+ * camera, not the surface being close to it.
140
+ */
141
+ export const LOD_NEAR_PLANE = 0;
142
+
133
143
  /**
134
144
  * The conservative nearest view-space depth of a world-space bounding sphere.
135
145
  *
@@ -148,6 +158,29 @@ export function conservativeViewDepth(
148
158
  return { depth, degenerate: depth <= nearPlane };
149
159
  }
150
160
 
161
+ /**
162
+ * The LOD recipe every caller repeats: the sphere in the camera's view, how far its nearest surface
163
+ * is, and that distance biased for the level table.
164
+ *
165
+ * `depth` is the raw conservative view depth, which a reporter projects an error from; `biased` is
166
+ * the same distance with {@link biasedLodDistance} applied, which a level selection compares. The
167
+ * two are returned together because the six callers each want one of them and each used to spell the
168
+ * step itself — one of them with a near plane of its own.
169
+ */
170
+ export function selectLodFor(
171
+ camera: Camera,
172
+ sphere: Sphere,
173
+ nearPlane: number,
174
+ ): { readonly depth: number; readonly degenerate: boolean; readonly biased: number } {
175
+ const { depth, degenerate } = conservativeViewDepth(
176
+ camera,
177
+ sphere.center,
178
+ sphere.radius,
179
+ nearPlane,
180
+ );
181
+ return { biased: biasedLodDistance(depth), degenerate, depth };
182
+ }
183
+
151
184
  /** The world-space bounding sphere of a cached local sphere under a node's world matrix. */
152
185
  export function worldSphere(
153
186
  local: Sphere,
@@ -315,10 +348,21 @@ export interface ILodChain {
315
348
  readonly sphere: Sphere;
316
349
  }
317
350
 
318
- /** Triangles one level of a chain submits. */
319
- function drawTriangles(geometry: BufferGeometry): number {
320
- const drawn = geometry.index?.count ?? geometry.getAttribute("position")?.count ?? 0;
321
- return Math.floor(drawn / 3);
351
+ const levelTriangles = new WeakMap<BufferGeometry, number>();
352
+
353
+ /**
354
+ * Triangles one level of a chain submits, read once: a level is an index view nothing edits, and on
355
+ * the owned engine each `geometry.index` read is a bridge crossing (Midway's fleet read it 528 times
356
+ * a frame, `TN_BRIDGE_WARNING`).
357
+ */
358
+ export function drawTriangles(geometry: BufferGeometry): number {
359
+ let triangles = levelTriangles.get(geometry);
360
+ if (triangles === undefined) {
361
+ const drawn = geometry.index?.count ?? geometry.getAttribute("position")?.count ?? 0;
362
+ triangles = Math.floor(drawn / 3);
363
+ levelTriangles.set(geometry, triangles);
364
+ }
365
+ return triangles;
322
366
  }
323
367
 
324
368
  /**
@@ -375,16 +419,15 @@ class ModelLod {
375
419
  return;
376
420
  }
377
421
  const world = worldSphere(this.#chain.sphere, this.#mesh, undefined, this.#mesh.matrixWorld);
378
- const { depth, degenerate } = conservativeViewDepth(
422
+ const { biased, degenerate } = selectLodFor(
379
423
  camera,
380
- world.center,
381
- world.radius,
424
+ world,
382
425
  (camera as ILodCameraLike).near ?? 0,
383
426
  );
384
427
  const view: ILodView = {
385
428
  camera,
386
429
  degenerate,
387
- depth: biasedLodDistance(depth),
430
+ depth: biased,
388
431
  viewportHeight,
389
432
  };
390
433
  const index = selectLodLevel(
@@ -412,10 +455,9 @@ class ModelLod {
412
455
  const container = this.#container;
413
456
  if (container === null) return;
414
457
  const world = worldSphere(rung.sphere, container, undefined, container.matrixWorld);
415
- const { depth, degenerate } = conservativeViewDepth(
458
+ const { biased, degenerate } = selectLodFor(
416
459
  camera,
417
- world.center,
418
- world.radius,
460
+ world,
419
461
  (camera as ILodCameraLike).near ?? 0,
420
462
  );
421
463
  const errors = [...this.#chain.errors, rung.error];
@@ -423,7 +465,7 @@ class ModelLod {
423
465
  const view: ILodView = {
424
466
  camera,
425
467
  degenerate,
426
- depth: biasedLodDistance(depth),
468
+ depth: biased,
427
469
  viewportHeight,
428
470
  };
429
471
  const index = selectLodLevel(
@@ -876,7 +918,47 @@ export function registerModelLodController(mesh: Mesh, controller: IModelLodCont
876
918
  function isChained(object: object): boolean {
877
919
  const mesh = object as Partial<Mesh>;
878
920
  const geometry = mesh.geometry;
879
- return mesh.isMesh === true && geometry !== undefined && chains.has(geometry);
921
+ return (
922
+ mesh.isMesh === true &&
923
+ geometry !== undefined &&
924
+ (chains.has(geometry) || streaming.has(geometry))
925
+ );
926
+ }
927
+
928
+ /**
929
+ * Coarse geometries of streamed models (PRD-860) whose full model is still downloading. They are
930
+ * tracked like a chained mesh, so on the frame the full model lands every mesh over them, a game's
931
+ * clones included, picks its chain up.
932
+ */
933
+ const streaming = new WeakSet<BufferGeometry>();
934
+
935
+ /** A coarse companion's geometry, drawn until {@link upgradeStreamedGeometry} gives it the full model. */
936
+ export function markStreamedGeometry(coarse: BufferGeometry): void {
937
+ streaming.add(coarse);
938
+ }
939
+
940
+ /** True while a geometry is a streamed coarse companion the full model has not replaced yet. */
941
+ export function isStreamedGeometry(geometry: BufferGeometry): boolean {
942
+ return streaming.has(geometry);
943
+ }
944
+
945
+ /**
946
+ * The full model landed: the coarse geometry takes the full base's index and attributes in place,
947
+ * so every mesh holding it (a game's clones, a projection mirror) draws the full model with no
948
+ * object swapped under the game, and it adopts the full chain.
949
+ */
950
+ export function upgradeStreamedGeometry(coarse: BufferGeometry, full: BufferGeometry): void {
951
+ const attributes = full.attributes as Record<string, BufferAttribute>;
952
+ for (const name of Object.keys(coarse.attributes))
953
+ if (attributes[name] === undefined) coarse.deleteAttribute(name);
954
+ for (const [name, attribute] of Object.entries(attributes)) coarse.setAttribute(name, attribute);
955
+ coarse.setIndex(full.index);
956
+ coarse.computeBoundingBox();
957
+ coarse.computeBoundingSphere();
958
+ levelTriangles.delete(coarse);
959
+ const registered = chains.get(full);
960
+ if (registered !== undefined) chains.set(coarse, registered);
961
+ streaming.delete(coarse);
880
962
  }
881
963
 
882
964
  /**
@@ -1357,7 +1439,8 @@ export function updateModelLods(
1357
1439
  for (const mesh of tracking.items) {
1358
1440
  const entry = controllerFor(mesh);
1359
1441
  if (entry === undefined) {
1360
- tracking.items.delete(mesh);
1442
+ // A streamed coarse mesh stays tracked until its full model lands and brings the chain.
1443
+ if (!streaming.has(mesh.geometry)) tracking.items.delete(mesh);
1361
1444
  continue;
1362
1445
  }
1363
1446
  entry.update(camera, viewportHeight);
@@ -31,6 +31,8 @@ export interface IParticleSignificanceOptions {
31
31
  */
32
32
  export class ParticleSignificance {
33
33
  #shed = 0;
34
+ /** Candidates this pass has yielded and not yet resumed. */
35
+ #yielded = 0;
34
36
  readonly #decayPerSecond: number;
35
37
  readonly #graceSeconds: number;
36
38
  readonly #states = new WeakMap<IBudgetCandidate, { yielded: boolean; changedAt: number }>();
@@ -78,7 +80,16 @@ export class ParticleSignificance {
78
80
  return this.#shed;
79
81
  }
80
82
 
83
+ /**
84
+ * Nothing to shed and nothing yielded: {@link apply} would change nothing, so the caller can skip
85
+ * asking each candidate its significance (an engine crossing per emitter on the owned engine, PRD-828).
86
+ */
87
+ get idle(): boolean {
88
+ return this.#shed === 0 && this.#yielded === 0;
89
+ }
90
+
81
91
  apply(candidates: Iterable<IBudgetCandidate>, camera: Camera, nowSeconds: number): void {
92
+ if (this.idle) return;
82
93
  const ranked: { candidate: IBudgetCandidate; significance: number }[] = [];
83
94
  for (const candidate of candidates) {
84
95
  const significance = candidate.significance(camera);
@@ -95,6 +106,7 @@ export class ParticleSignificance {
95
106
  const yielded = index < count;
96
107
  if (state.yielded === yielded || nowSeconds - state.changedAt < this.#graceSeconds) continue;
97
108
  candidate.yield(yielded);
109
+ this.#yielded += yielded ? 1 : -1;
98
110
  state.yielded = yielded;
99
111
  state.changedAt = nowSeconds;
100
112
  }
package/src/particles.ts CHANGED
@@ -492,17 +492,26 @@ export class GPUParticles3D extends Sprite implements IComputeDriven {
492
492
  if (camera !== undefined && !this.castShadow && this.#authoredVisible) {
493
493
  const bounds = this.measuredBounds;
494
494
  if (bounds !== undefined && this.#graceSeconds !== Number.POSITIVE_INFINITY) {
495
- if (camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
496
- this.updateWorldMatrix(true, false);
497
- viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
498
- frustum.setFromProjectionMatrix(
499
- viewProjection,
500
- camera.coordinateSystem,
501
- camera.reversedDepth,
502
- );
503
- worldBox.copy(bounds).applyMatrix4(this.matrixWorld).expandByScalar(this.#worldPadding);
495
+ // The native engine folds the same test in one call (PRD-828); a NaN padding asks for the default.
496
+ const engine = (this as { __boundsInView?: (c: Camera, b: Box3, p: number) => boolean })
497
+ .__boundsInView;
498
+ let inView: boolean;
499
+ if (typeof engine === "function")
500
+ inView = engine.call(this, camera, bounds, this.#padding ?? Number.NaN);
501
+ else {
502
+ if (camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
503
+ this.updateWorldMatrix(true, false);
504
+ viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
505
+ frustum.setFromProjectionMatrix(
506
+ viewProjection,
507
+ camera.coordinateSystem,
508
+ camera.reversedDepth,
509
+ );
510
+ worldBox.copy(bounds).applyMatrix4(this.matrixWorld).expandByScalar(this.#worldPadding);
511
+ inView = frustum.intersectsBox(worldBox);
512
+ }
504
513
  // ponytail: bounds lag by boundsEveryFrames; grace delays culling and paused clouds do not move.
505
- if (frustum.intersectsBox(worldBox)) this.#outsideSince = undefined;
514
+ if (inView) this.#outsideSince = undefined;
506
515
  else {
507
516
  // Wall time is only for callers without a loop clock.
508
517
  const now = simulatedSeconds ?? performance.now() / 1000;
package/src/platform.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export type PlatformRuntime = "web" | "native";
2
- export type PlatformOS = "android" | "ios" | "linux" | "macos" | "windows" | "unknown";
3
- export type PlatformFormFactor = "mobile" | "desktop" | "unknown";
2
+ export type PlatformOS = "android" | "ios" | "linux" | "macos" | "windows" | "ps4" | "unknown";
3
+ export type PlatformFormFactor = "mobile" | "desktop" | "console" | "unknown";
4
4
 
5
5
  export interface IPlatformInfo {
6
6
  readonly runtime: PlatformRuntime;
@@ -22,6 +22,7 @@ interface IUserAgentData {
22
22
 
23
23
  const DESKTOP_OS = new Set<PlatformOS>(["linux", "macos", "windows"]);
24
24
  const MOBILE_OS = new Set<PlatformOS>(["android", "ios"]);
25
+ const CONSOLE_OS = new Set<PlatformOS>(["ps4"]);
25
26
 
26
27
  function isRecord(value: unknown): value is Record<string, unknown> {
27
28
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -51,11 +52,17 @@ function nativePlatform(source: unknown): Readonly<IPlatformInfo> {
51
52
  os !== "linux" &&
52
53
  os !== "macos" &&
53
54
  os !== "windows" &&
55
+ os !== "ps4" &&
54
56
  os !== "unknown"
55
57
  ) {
56
58
  invalidNativePlatform("os is unknown");
57
59
  }
58
- if (formFactor !== "mobile" && formFactor !== "desktop" && formFactor !== "unknown") {
60
+ if (
61
+ formFactor !== "mobile" &&
62
+ formFactor !== "desktop" &&
63
+ formFactor !== "console" &&
64
+ formFactor !== "unknown"
65
+ ) {
59
66
  invalidNativePlatform("formFactor is unknown");
60
67
  }
61
68
  if (!Number.isInteger(maxTouchPoints) || (maxTouchPoints as number) < 0) {
@@ -66,7 +73,9 @@ function nativePlatform(source: unknown): Readonly<IPlatformInfo> {
66
73
  ? "mobile"
67
74
  : DESKTOP_OS.has(os as PlatformOS)
68
75
  ? "desktop"
69
- : "unknown";
76
+ : CONSOLE_OS.has(os as PlatformOS)
77
+ ? "console"
78
+ : "unknown";
70
79
  if (formFactor !== expectedFormFactor) {
71
80
  invalidNativePlatform("os and formFactor disagree");
72
81
  }
@@ -209,6 +218,16 @@ export function isMobile(): boolean {
209
218
  return getPlatform().formFactor === "mobile";
210
219
  }
211
220
 
221
+ /** A games console (PS4): a pad is the input, there is no keyboard, mouse or touchscreen. */
222
+ export function isConsole(): boolean {
223
+ return getPlatform().formFactor === "console";
224
+ }
225
+
226
+ /** A PlayStation 4: the pad is a DualShock 4, so its buttons are ✕ ○ □ △ and OPTIONS. */
227
+ export function isPs4(): boolean {
228
+ return getPlatform().os === "ps4";
229
+ }
230
+
212
231
  export function isTouchscreenAvailable(): boolean {
213
232
  return getPlatform().maxTouchPoints > 0;
214
233
  }
@@ -16,6 +16,7 @@
16
16
  * stages (`wasmRendererGap` is what `Renderer::render` spends outside its plan and encode halves) so the unlocated time is a number and never a quiet category. On an engine that publishes no
17
17
  * stage totals (upstream three), the whole call is `engineJs`.
18
18
  */
19
+ import { readLaunchFlag } from "../debug.js";
19
20
 
20
21
  import type { IFrameCounters } from "./FrameCounters.js";
21
22
 
@@ -217,12 +218,10 @@ export function createStageReader(
217
218
  * `stages`: the paired A/B that prices the meters runs one build with this switch alone.
218
219
  */
219
220
  export function stageMetersRequested(): boolean {
220
- const host = globalThis as { process?: { env?: Record<string, unknown> }; __tnStages?: unknown };
221
- const fromEnv = host.process?.env?.TN_STAGES;
222
- if (fromEnv === "0" || fromEnv === "false") return false;
223
- const query = globalThis.location?.search;
224
- if (typeof query === "string" && /[?&]tnStages=(?:0|false)(?:&|$)/u.test(query)) return false;
225
- return host.__tnStages !== false;
221
+ return !readLaunchFlag(
222
+ { environment: "TN_STAGES", global: "__tnStages", query: "tnStages" },
223
+ "off",
224
+ );
226
225
  }
227
226
 
228
227
  interface IEngineWorkHost {
@@ -23,6 +23,7 @@
23
23
  * The ids are integers on the hot path — a span call must not allocate a string to be cheap enough
24
24
  * to put around a per-draw call — and the names exist only in the report.
25
25
  */
26
+ import { readLaunchFlag } from "../debug.js";
26
27
 
27
28
  /** Marker printed once per report window when spans are installed. */
28
29
  import { countDebug, debugRequested } from "./debug-telemetry.js";
@@ -535,24 +536,9 @@ export function addSpan(id: SpanId, ms: number): void {
535
536
  * `globalThis.__tnFrameSpans` before the game boots.
536
537
  */
537
538
  export function spansRequested(): boolean {
538
- if (debugRequested()) return true;
539
- const host = globalThis as {
540
- process?: { env?: Record<string, unknown> };
541
- __tnFrameSpans?: unknown;
542
- };
543
- const fromEnv = host.process?.env?.[SPANS_FLAG];
544
- if (typeof fromEnv === "string" && fromEnv !== "" && fromEnv !== "0" && fromEnv !== "false")
545
- return true;
546
- const query = globalThis.location?.search;
547
- if (typeof query === "string" && /[?&]tnFrameSpans=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query))
548
- return true;
549
- const fromGlobal = host.__tnFrameSpans;
550
539
  return (
551
- fromGlobal === true ||
552
- (typeof fromGlobal === "string" &&
553
- fromGlobal !== "" &&
554
- fromGlobal !== "0" &&
555
- fromGlobal !== "false")
540
+ debugRequested() ||
541
+ readLaunchFlag({ environment: SPANS_FLAG, global: "__tnFrameSpans", query: "tnFrameSpans" })
556
542
  );
557
543
  }
558
544
 
@@ -1,3 +1,4 @@
1
+ import { readLaunchFlag } from "../debug.js";
1
2
  import type { IFrameBudgetWindow } from "../frame-budget.js";
2
3
 
3
4
  export interface IDebugSource {
@@ -34,12 +35,7 @@ export function isContentScaled(name: string): boolean {
34
35
  const DEBUG_GLOBAL = "__THREENATIVE_DEBUG__";
35
36
 
36
37
  export function debugRequested(): boolean {
37
- const host = globalThis as IDebugHost;
38
- return (
39
- host.process?.env?.TN_DEBUG === "1" ||
40
- (globalThis as Record<string, unknown>)[DEBUG_GLOBAL] === true ||
41
- /[?&]tnDebug=1(?:&|$)/u.test(globalThis.location?.search ?? "")
42
- );
38
+ return readLaunchFlag({ environment: "TN_DEBUG", global: DEBUG_GLOBAL, query: "tnDebug" });
43
39
  }
44
40
 
45
41
  /** Debug-only producers call this; the existing engine-cost reader owns the per-frame difference. */
@@ -13,6 +13,7 @@
13
13
  *
14
14
  * Off by default and expensive by construction — it does the work it is checking, twice.
15
15
  */
16
+ import { readLaunchFlag } from "../debug.js";
16
17
 
17
18
  import { Matrix4, type Object3D } from "three";
18
19
  import { composeSilencedByFreeze, worldSilencedByFreeze } from "../static-transform.js";
@@ -34,21 +35,11 @@ const TOLERANCE = 1e-6;
34
35
 
35
36
  /** Whether `TN_RENDERLIST_VALIDATE` asks for validation on this launch. */
36
37
  export function renderListValidationRequested(): boolean {
37
- const host = globalThis as {
38
- process?: { env?: Record<string, unknown> };
39
- __tnRenderListValidate?: unknown;
40
- };
41
- const fromEnv = host.process?.env?.[RENDERLIST_VALIDATE_FLAG];
42
- if (typeof fromEnv === "string" && fromEnv !== "" && fromEnv !== "0" && fromEnv !== "false")
43
- return true;
44
- const query = globalThis.location?.search;
45
- if (
46
- typeof query === "string" &&
47
- /[?&]tnRenderListValidate=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query)
48
- )
49
- return true;
50
- const fromGlobal = host.__tnRenderListValidate;
51
- return fromGlobal === true || fromGlobal === "1";
38
+ return readLaunchFlag({
39
+ environment: RENDERLIST_VALIDATE_FLAG,
40
+ global: "__tnRenderListValidate",
41
+ query: "tnRenderListValidate",
42
+ });
52
43
  }
53
44
 
54
45
  /** What one frame's check found. */
@@ -1,3 +1,4 @@
1
+ import { CONSOLE_MARKER } from "./generated/console-markers.js";
1
2
  import type { IMatrixWorldReport } from "./matrix-world.js";
2
3
  import type { IRenderCameraCullReport } from "./render-camera-cull.js";
3
4
  import type {
@@ -15,7 +16,7 @@ import type {
15
16
  * produces a series rather than a single sentence, and it carries the one thing the projection
16
17
  * cannot know on its own: how many draws the renderer was actually handed.
17
18
  */
18
- export const PROJECTION_MARKER = "TN_PROJECTION";
19
+ export const PROJECTION_MARKER = CONSOLE_MARKER.projection;
19
20
 
20
21
  export interface IProjectionWindowJson {
21
22
  /**
@@ -9,24 +9,17 @@
9
9
  * Only a real browser page installs it: the native host stubs `document.location` but sets no
10
10
  * `globalThis.location`, so a native game keeps its console as the host prints it.
11
11
  */
12
+ import { readLaunchFlag } from "./debug.js";
13
+
12
14
  const LOG_FLAG = "TN_LOG";
13
15
  const BROWSER_PROTOCOLS = new Set(["http:", "https:", "file:"]);
14
16
 
15
17
  type ConsoleMethod = (...args: unknown[]) => void;
16
18
  let restore: { log: ConsoleMethod; info: ConsoleMethod } | undefined;
17
19
 
18
- const isOn = (value: unknown): boolean =>
19
- value === true ||
20
- (typeof value === "string" && value !== "" && value !== "0" && value !== "false");
21
-
22
20
  /** Whether `TN_LOG` asks for markers at their own console level on this launch. */
23
21
  export function markerLogRequested(): boolean {
24
- const host = globalThis as { process?: { env?: Record<string, unknown> } };
25
- if (isOn(host.process?.env?.[LOG_FLAG])) return true;
26
- const query = globalThis.location?.search;
27
- if (typeof query === "string" && /[?&]tnLog=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query))
28
- return true;
29
- return isOn((globalThis as Record<string, unknown>).__THREENATIVE_LOG__);
22
+ return readLaunchFlag({ environment: LOG_FLAG, global: "__THREENATIVE_LOG__", query: "tnLog" });
30
23
  }
31
24
 
32
25
  /** Re-routes `TN_` log/info lines to `console.debug`; a second call is a no-op. */
@@ -0,0 +1,100 @@
1
+ /**
2
+ * A CPU bounding-volume hierarchy for the probe trace, in the node layout the trace threads
3
+ * (`threadBvh`): 8 words a node, bounds as 6 floats, then a leaf offset and `0xffff0000 | count`, or the
4
+ * right child's distance in nodes and an axis. The left child of node `i` is node `i + 1`.
5
+ *
6
+ * It exists because the owned engine's `MeshBVH` builds no tree (`TN_NATIVE_MESH_BVH_OPTIONS_UNSUPPORTED`),
7
+ * so `GPUSceneBVH` cannot take its nodes there. A median split along the longest centroid axis is
8
+ * slower to trace than a surface-area split. It builds in O(n log^2 n) and is correct on any engine.
9
+ */
10
+ const LEAF_FLAG = 0xffff0000;
11
+ export const CPU_BVH_LEAF_SIZE = 8;
12
+
13
+ export interface ICpuBvh {
14
+ /** 8 words a node, depth-first, left child first. */
15
+ readonly nodes: Uint32Array;
16
+ /** `order[slot]` is the source triangle held at leaf slot `slot`. */
17
+ readonly order: Uint32Array;
18
+ }
19
+
20
+ /** `positions` are tight xyz triples and `indices` three vertex indices a triangle. */
21
+ export function buildCpuBvh(positions: Float32Array, indices: Uint32Array): ICpuBvh {
22
+ const count = Math.floor(indices.length / 3);
23
+ const order = Uint32Array.from({ length: count }, (_, i) => i);
24
+ if (count === 0) return { nodes: new Uint32Array(8), order };
25
+ const low = new Float32Array(count * 3);
26
+ const high = new Float32Array(count * 3);
27
+ const centre = new Float32Array(count * 3);
28
+ for (let t = 0; t < count; t += 1) {
29
+ for (let axis = 0; axis < 3; axis += 1) {
30
+ let lo = Number.POSITIVE_INFINITY;
31
+ let hi = Number.NEGATIVE_INFINITY;
32
+ for (let corner = 0; corner < 3; corner += 1) {
33
+ const value = positions[(indices[t * 3 + corner] as number) * 3 + axis] as number;
34
+ lo = Math.min(lo, value);
35
+ hi = Math.max(hi, value);
36
+ }
37
+ low[t * 3 + axis] = lo;
38
+ high[t * 3 + axis] = hi;
39
+ centre[t * 3 + axis] = (lo + hi) / 2;
40
+ }
41
+ }
42
+ const words: number[] = [];
43
+ const floats = new Float32Array(1);
44
+ const bits = new Uint32Array(floats.buffer);
45
+ const bitsOf = (value: number): number => {
46
+ floats[0] = value;
47
+ return bits[0] as number;
48
+ };
49
+ const build = (start: number, end: number): number => {
50
+ const node = words.length / 8;
51
+ words.push(0, 0, 0, 0, 0, 0, 0, 0);
52
+ const box = [
53
+ Number.POSITIVE_INFINITY,
54
+ Number.POSITIVE_INFINITY,
55
+ Number.POSITIVE_INFINITY,
56
+ Number.NEGATIVE_INFINITY,
57
+ Number.NEGATIVE_INFINITY,
58
+ Number.NEGATIVE_INFINITY,
59
+ ];
60
+ const middle = [
61
+ Number.POSITIVE_INFINITY,
62
+ Number.POSITIVE_INFINITY,
63
+ Number.POSITIVE_INFINITY,
64
+ Number.NEGATIVE_INFINITY,
65
+ Number.NEGATIVE_INFINITY,
66
+ Number.NEGATIVE_INFINITY,
67
+ ];
68
+ for (let slot = start; slot < end; slot += 1) {
69
+ const t = order[slot] as number;
70
+ for (let axis = 0; axis < 3; axis += 1) {
71
+ box[axis] = Math.min(box[axis] as number, low[t * 3 + axis] as number);
72
+ box[axis + 3] = Math.max(box[axis + 3] as number, high[t * 3 + axis] as number);
73
+ middle[axis] = Math.min(middle[axis] as number, centre[t * 3 + axis] as number);
74
+ middle[axis + 3] = Math.max(middle[axis + 3] as number, centre[t * 3 + axis] as number);
75
+ }
76
+ }
77
+ for (let i = 0; i < 6; i += 1) words[node * 8 + i] = bitsOf(box[i] as number);
78
+ const spread = (a: number) => (middle[a + 3] as number) - (middle[a] as number);
79
+ let axis = 0;
80
+ if (spread(1) > spread(axis)) axis = 1;
81
+ if (spread(2) > spread(axis)) axis = 2;
82
+ if (end - start <= CPU_BVH_LEAF_SIZE || spread(axis) <= 0) {
83
+ words[node * 8 + 6] = start;
84
+ words[node * 8 + 7] = (LEAF_FLAG | (end - start)) >>> 0;
85
+ return node;
86
+ }
87
+ const slice = Array.from(order.subarray(start, end)).sort(
88
+ (a, b) => (centre[a * 3 + axis] as number) - (centre[b * 3 + axis] as number),
89
+ );
90
+ order.set(slice, start);
91
+ const half = start + ((end - start) >> 1);
92
+ build(start, half);
93
+ const right = build(half, end);
94
+ words[node * 8 + 6] = right - node;
95
+ words[node * 8 + 7] = axis;
96
+ return node;
97
+ };
98
+ build(0, count);
99
+ return { nodes: Uint32Array.from(words), order };
100
+ }