@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
@@ -0,0 +1,401 @@
1
+ import type { Box3, InstancedBufferAttribute, Matrix4 } from "three";
2
+
3
+ /**
4
+ * The instance records of the world's shared batches, written by one engine call a frame.
5
+ *
6
+ * A shared batch used to write, zero, move and regroup its records in a JS copy of each instance
7
+ * buffer and push every change through `needsUpdate`, which on the owned engine is a bridge crossing
8
+ * per range and per attribute: the 2 km forest walk spent 4.2 ms a frame in the admission drain, 63%
9
+ * of it in the bridge glue around those writes. Now a batch only decides where records go. What
10
+ * happens to the bytes is queued here as ops, and `flush` hands the whole frame to the engine in
11
+ * one `InstancedBufferAttribute.__tnRecords` call, which writes the engine's own buffers and their
12
+ * upload ranges: the batch never reads or holds the bytes. The record boxes the batch publishes as
13
+ * mesh bounds come back from the same call, measured from the bytes as written.
14
+ *
15
+ * Upstream three (`engine: "threejs"`) has no engine to call, so the same ops run on each
16
+ * attribute's own array in {@link applyRecords}, the twin of `bindings_geometry.cpp`'s
17
+ * `applyRecords`.
18
+ *
19
+ * Every op starts with its code and the attribute's index in the call's attribute list; element
20
+ * offsets and counts are in floats of that attribute's array:
21
+ * - `WRITE at count payloadAt`: `count` floats of the payload at `at`.
22
+ * - `FILL at count`: zeros.
23
+ * - `MOVE from to count`: `copyWithin(to, from, from + count)`.
24
+ * - `COPY source count`: the first `count` floats of attribute `source` (a grown buffer's old one).
25
+ * - `GATHER stride blocks [from count]...`: the blocks (in records) laid out from record 0 in order.
26
+ * - `UPLOAD from count`: the range the next render uploads; `count` 0 uploads the whole array.
27
+ * - `BOX from count payloadAt`: answers the AABB and largest basis scale of records
28
+ * `[from, from + count)` of a matrix buffer, for a local box whose centre and half size are the
29
+ * six payload floats at `payloadAt`: seven numbers per op, in op order.
30
+ * - `LANES stride lanes values...`: the first `lanes` floats of every record set to `values`.
31
+ */
32
+ export const RECORD_OP = {
33
+ write: 1,
34
+ fill: 2,
35
+ move: 3,
36
+ copy: 4,
37
+ gather: 5,
38
+ upload: 6,
39
+ box: 7,
40
+ lanes: 8,
41
+ } as const;
42
+
43
+ /** Numbers each `BOX` op answers: min x y z, max x y z, largest basis scale. */
44
+ export const RECORD_BOX_SIZE = 7;
45
+
46
+ /** What a queued batch does around a flush: name its upload ranges, then read its boxes back. */
47
+ export interface IRecordWriter {
48
+ uploadRecords(): void;
49
+ settleRecords(boxes: ArrayLike<number>): void;
50
+ }
51
+
52
+ type IRecordsCall = (
53
+ attributes: InstancedBufferAttribute[],
54
+ ops: Float64Array,
55
+ payload: Float32Array,
56
+ ) => ArrayLike<number>;
57
+
58
+ /** The engine's own applier, present only on the owned engine. */
59
+ interface IRecordsEngine {
60
+ __tnRecords?: IRecordsCall;
61
+ }
62
+
63
+ function grown<T extends Float64Array | Float32Array>(array: T, needed: number): T {
64
+ if (needed <= array.length) return array;
65
+ const next = new (array.constructor as new (length: number) => T)(
66
+ Math.max(needed, array.length * 2),
67
+ );
68
+ next.set(array);
69
+ return next;
70
+ }
71
+
72
+ export class RecordQueue {
73
+ #attributes: InstancedBufferAttribute[] = [];
74
+ readonly #slots = new Map<InstancedBufferAttribute, number>();
75
+ #ops = new Float64Array(1024);
76
+ #opAt = 0;
77
+ #payload = new Float32Array(16384);
78
+ #payloadAt = 0;
79
+ #boxes = 0;
80
+ readonly #writers = new Set<IRecordWriter>();
81
+
82
+ /** The payload buffer; read it after {@link reserve}, which may replace it. */
83
+ get payload(): Float32Array {
84
+ return this.#payload;
85
+ }
86
+
87
+ /** Room for `floats` payload floats at a record-aligned offset, which is returned. */
88
+ reserve(floats: number): number {
89
+ const at = Math.ceil(this.#payloadAt / 16) * 16;
90
+ this.#payload = grown(this.#payload, at + floats);
91
+ this.#payloadAt = at + floats;
92
+ return at;
93
+ }
94
+
95
+ write(attribute: InstancedBufferAttribute, at: number, count: number, payloadAt: number): void {
96
+ if (count > 0) this.#op(RECORD_OP.write, attribute, at, count, payloadAt);
97
+ }
98
+
99
+ fill(attribute: InstancedBufferAttribute, at: number, count: number): void {
100
+ if (count > 0) this.#op(RECORD_OP.fill, attribute, at, count);
101
+ }
102
+
103
+ move(attribute: InstancedBufferAttribute, from: number, to: number, count: number): void {
104
+ if (count > 0 && from !== to) this.#op(RECORD_OP.move, attribute, from, to, count);
105
+ }
106
+
107
+ copy(target: InstancedBufferAttribute, source: InstancedBufferAttribute, count: number): void {
108
+ if (count > 0) this.#op(RECORD_OP.copy, target, this.#slot(source), count);
109
+ }
110
+
111
+ /** `blocks` holds `[fromRecord, records]` pairs, laid out from record 0 in order. */
112
+ gather(attribute: InstancedBufferAttribute, stride: number, blocks: readonly number[]): void {
113
+ if (blocks.length === 0) return;
114
+ this.#op(RECORD_OP.gather, attribute, stride, blocks.length / 2, ...blocks);
115
+ }
116
+
117
+ upload(attribute: InstancedBufferAttribute, from: number, count: number): void {
118
+ this.#op(RECORD_OP.upload, attribute, from, count);
119
+ }
120
+
121
+ /** Queues a box; the returned index is where its seven numbers start in the flush's answer. */
122
+ box(
123
+ attribute: InstancedBufferAttribute,
124
+ from: number,
125
+ count: number,
126
+ center: { x: number; y: number; z: number },
127
+ half: { x: number; y: number; z: number },
128
+ ): number {
129
+ const at = this.reserve(6);
130
+ this.#payload.set([center.x, center.y, center.z, half.x, half.y, half.z], at);
131
+ this.#op(RECORD_OP.box, attribute, from, count, at);
132
+ const index = this.#boxes;
133
+ this.#boxes += RECORD_BOX_SIZE;
134
+ return index;
135
+ }
136
+
137
+ lanes(attribute: InstancedBufferAttribute, stride: number, values: readonly number[]): void {
138
+ this.#op(RECORD_OP.lanes, attribute, stride, values.length, ...values);
139
+ }
140
+
141
+ /** `writer` names its upload ranges at the next flush and reads its boxes back after it. */
142
+ touch(writer: IRecordWriter): void {
143
+ this.#writers.add(writer);
144
+ }
145
+
146
+ /**
147
+ * Hands the frame's ops to the engine in one call (or to {@link applyRecords} on upstream three),
148
+ * then tells each writer what its boxes measured. A frame that queued nothing calls nothing.
149
+ */
150
+ flush(): void {
151
+ if (this.#writers.size === 0 && this.#opAt === 0) return;
152
+ const writers = [...this.#writers];
153
+ this.#writers.clear();
154
+ for (const writer of writers) writer.uploadRecords();
155
+ const attributes = this.#attributes;
156
+ const ops = this.#ops.subarray(0, this.#opAt);
157
+ const payload = this.#payload.subarray(0, this.#payloadAt);
158
+ this.#attributes = [];
159
+ this.#slots.clear();
160
+ this.#opAt = 0;
161
+ this.#payloadAt = 0;
162
+ this.#boxes = 0;
163
+ const first = attributes[0] as (InstancedBufferAttribute & IRecordsEngine) | undefined;
164
+ let boxes: ArrayLike<number> = [];
165
+ if (first !== undefined) {
166
+ const engine = first.__tnRecords;
167
+ boxes =
168
+ typeof engine === "function"
169
+ ? engine.call(first, attributes, ops, payload)
170
+ : applyRecords(attributes, ops, payload);
171
+ }
172
+ for (const writer of writers) writer.settleRecords(boxes);
173
+ }
174
+
175
+ #slot(attribute: InstancedBufferAttribute): number {
176
+ let slot = this.#slots.get(attribute);
177
+ if (slot === undefined) {
178
+ slot = this.#attributes.length;
179
+ this.#attributes.push(attribute);
180
+ this.#slots.set(attribute, slot);
181
+ }
182
+ return slot;
183
+ }
184
+
185
+ #op(code: number, attribute: InstancedBufferAttribute, ...args: number[]): void {
186
+ const slot = this.#slot(attribute);
187
+ this.#ops = grown(this.#ops, this.#opAt + 2 + args.length);
188
+ this.#ops[this.#opAt] = code;
189
+ this.#ops[this.#opAt + 1] = slot;
190
+ this.#ops.set(args, this.#opAt + 2);
191
+ this.#opAt += 2 + args.length;
192
+ }
193
+ }
194
+
195
+ /** The one queue every shared batch writes into, flushed at the end of `WorldCells.update`. */
196
+ export const batchRecords = new RecordQueue();
197
+
198
+ function span(array: ArrayLike<number>, at: number, count: number, what: string): void {
199
+ if (
200
+ !(
201
+ Number.isInteger(at) &&
202
+ Number.isInteger(count) &&
203
+ at >= 0 &&
204
+ count >= 0 &&
205
+ at + count <= array.length
206
+ )
207
+ )
208
+ throw new RangeError(
209
+ `TN_WORLD_RECORDS: ${what} [${String(at)}, ${String(at + count)}) is outside ${String(array.length)} floats`,
210
+ );
211
+ }
212
+
213
+ /** `GATHER stride blocks [from count]...` on one array, read whole before it is written. */
214
+ function gather(array: Float32Array, ops: Float64Array, at: number): void {
215
+ const stride = ops[at + 2] as number;
216
+ const blocks = ops[at + 3] as number;
217
+ let total = 0;
218
+ for (let block = 0; block < blocks; block += 1) total += ops[at + 5 + block * 2] as number;
219
+ const scratch = new Float32Array(total * stride);
220
+ let written = 0;
221
+ for (let block = 0; block < blocks; block += 1) {
222
+ const from = (ops[at + 4 + block * 2] as number) * stride;
223
+ const count = (ops[at + 5 + block * 2] as number) * stride;
224
+ span(array, from, count, "gather");
225
+ scratch.set(array.subarray(from, from + count), written);
226
+ written += count;
227
+ }
228
+ span(array, 0, written, "gather target");
229
+ array.set(scratch);
230
+ }
231
+
232
+ /** `LANES stride lanes values...`: the first `lanes` floats of every record. */
233
+ function lanes(array: Float32Array, ops: Float64Array, at: number): void {
234
+ const stride = ops[at + 2] as number;
235
+ const count = ops[at + 3] as number;
236
+ if (!(count <= stride)) throw new RangeError("TN_WORLD_RECORDS: lanes wider than the record");
237
+ for (let record = 0; record + stride <= array.length; record += stride)
238
+ for (let lane = 0; lane < count; lane += 1) array[record + lane] = ops[at + 4 + lane] as number;
239
+ }
240
+
241
+ /**
242
+ * The ops of one flush on each attribute's own array: the upstream-three twin of the engine's
243
+ * `__tnRecords`, with the same checks. Answers the `BOX` ops' numbers in order.
244
+ */
245
+ export function applyRecords(
246
+ attributes: readonly InstancedBufferAttribute[],
247
+ ops: Float64Array,
248
+ payload: Float32Array,
249
+ ): number[] {
250
+ const boxes: number[] = [];
251
+ for (let at = 0; at < ops.length; ) at = applyOp(attributes, ops, at, payload, boxes);
252
+ return boxes;
253
+ }
254
+
255
+ /** One op of {@link applyRecords}; answers where the next op starts. */
256
+ function applyOp(
257
+ attributes: readonly InstancedBufferAttribute[],
258
+ ops: Float64Array,
259
+ at: number,
260
+ payload: Float32Array,
261
+ boxes: number[],
262
+ ): number {
263
+ const attribute = attributes[ops[at + 1] as number];
264
+ if (attribute === undefined) throw new RangeError("TN_WORLD_RECORDS: an op names no attribute");
265
+ const array = attribute.array as Float32Array;
266
+ const a = ops[at + 2] as number;
267
+ const b = ops[at + 3] as number;
268
+ const c = ops[at + 4] as number;
269
+ switch (ops[at]) {
270
+ case RECORD_OP.write:
271
+ span(array, a, b, "write");
272
+ span(payload, c, b, "payload");
273
+ array.set(payload.subarray(c, c + b), a);
274
+ return at + 5;
275
+ case RECORD_OP.fill:
276
+ span(array, a, b, "fill");
277
+ array.fill(0, a, a + b);
278
+ return at + 4;
279
+ case RECORD_OP.move:
280
+ span(array, a, c, "move source");
281
+ span(array, b, c, "move target");
282
+ array.copyWithin(b, a, a + c);
283
+ return at + 5;
284
+ case RECORD_OP.copy: {
285
+ const source = attributes[a]?.array as Float32Array | undefined;
286
+ if (source === undefined) throw new RangeError("TN_WORLD_RECORDS: copy names no source");
287
+ span(array, 0, b, "copy target");
288
+ span(source, 0, b, "copy source");
289
+ array.set(source.subarray(0, b));
290
+ return at + 4;
291
+ }
292
+ case RECORD_OP.gather:
293
+ gather(array, ops, at);
294
+ return at + 4 + b * 2;
295
+ case RECORD_OP.upload:
296
+ span(array, a, b, "upload");
297
+ attribute.clearUpdateRanges();
298
+ if (b > 0) attribute.addUpdateRange(a, b);
299
+ attribute.needsUpdate = true;
300
+ return at + 4;
301
+ case RECORD_OP.box:
302
+ span(array, a * 16, b * 16, "box");
303
+ span(payload, c, 6, "box payload");
304
+ boxes.push(...boxOf(array, a, b, payload, c));
305
+ return at + 5;
306
+ case RECORD_OP.lanes:
307
+ lanes(array, ops, at);
308
+ return at + 4 + b;
309
+ default:
310
+ throw new RangeError(`TN_WORLD_RECORDS: unknown op ${String(ops[at])}`);
311
+ }
312
+ }
313
+
314
+ /**
315
+ * The AABB of records `[from, from + count)`: each record's local box centre moved by its matrix,
316
+ * with half extents `|basis| * half`, which is the box a rotated or stretched instance actually
317
+ * covers. The seventh number is the largest basis column, the scale a fern or a trunk is drawn at.
318
+ */
319
+ function boxOf(
320
+ array: Float32Array,
321
+ from: number,
322
+ count: number,
323
+ local: Float32Array,
324
+ at: number,
325
+ ): number[] {
326
+ const cx = local[at] as number;
327
+ const cy = local[at + 1] as number;
328
+ const cz = local[at + 2] as number;
329
+ const hx = local[at + 3] as number;
330
+ const hy = local[at + 4] as number;
331
+ const hz = local[at + 5] as number;
332
+ let minX = Number.POSITIVE_INFINITY;
333
+ let minY = Number.POSITIVE_INFINITY;
334
+ let minZ = Number.POSITIVE_INFINITY;
335
+ let maxX = Number.NEGATIVE_INFINITY;
336
+ let maxY = Number.NEGATIVE_INFINITY;
337
+ let maxZ = Number.NEGATIVE_INFINITY;
338
+ let scale = 0;
339
+ for (let index = from; index < from + count; index += 1) {
340
+ const m = index * 16;
341
+ const m0 = array[m] as number;
342
+ const m1 = array[m + 1] as number;
343
+ const m2 = array[m + 2] as number;
344
+ const m4 = array[m + 4] as number;
345
+ const m5 = array[m + 5] as number;
346
+ const m6 = array[m + 6] as number;
347
+ const m8 = array[m + 8] as number;
348
+ const m9 = array[m + 9] as number;
349
+ const m10 = array[m + 10] as number;
350
+ const px = m0 * cx + m4 * cy + m8 * cz + (array[m + 12] as number);
351
+ const py = m1 * cx + m5 * cy + m9 * cz + (array[m + 13] as number);
352
+ const pz = m2 * cx + m6 * cy + m10 * cz + (array[m + 14] as number);
353
+ const ex = Math.abs(m0) * hx + Math.abs(m4) * hy + Math.abs(m8) * hz;
354
+ const ey = Math.abs(m1) * hx + Math.abs(m5) * hy + Math.abs(m9) * hz;
355
+ const ez = Math.abs(m2) * hx + Math.abs(m6) * hy + Math.abs(m10) * hz;
356
+ if (px - ex < minX) minX = px - ex;
357
+ if (py - ey < minY) minY = py - ey;
358
+ if (pz - ez < minZ) minZ = pz - ez;
359
+ if (px + ex > maxX) maxX = px + ex;
360
+ if (py + ey > maxY) maxY = py + ey;
361
+ if (pz + ez > maxZ) maxZ = pz + ez;
362
+ const basis = Math.max(Math.hypot(m0, m1, m2), Math.hypot(m4, m5, m6), Math.hypot(m8, m9, m10));
363
+ if (basis > scale) scale = basis;
364
+ }
365
+ return [minX, minY, minZ, maxX, maxY, maxZ, scale];
366
+ }
367
+
368
+ /**
369
+ * The AABB a local box covers under `matrix`, measured as the engine's `BOX` op measures a record: the
370
+ * centre moved by the matrix, half extents `|basis| * half`. Equal to `Box3.applyMatrix4`'s eight
371
+ * corners for an affine matrix, in twelve multiply-adds; a placement's box was the drain's largest
372
+ * per-record cost on the forest walk (0.12 ms a frame), measured twice per placement. An empty local
373
+ * box is left as authored, as three leaves it.
374
+ */
375
+ export function placedBox(
376
+ target: Box3,
377
+ min: readonly number[],
378
+ max: readonly number[],
379
+ matrix: Matrix4,
380
+ ): Box3 {
381
+ target.min.fromArray(min);
382
+ target.max.fromArray(max);
383
+ if (target.isEmpty()) return target;
384
+ const e = matrix.elements;
385
+ const cx = ((min[0] as number) + (max[0] as number)) / 2;
386
+ const cy = ((min[1] as number) + (max[1] as number)) / 2;
387
+ const cz = ((min[2] as number) + (max[2] as number)) / 2;
388
+ const hx = ((max[0] as number) - (min[0] as number)) / 2;
389
+ const hy = ((max[1] as number) - (min[1] as number)) / 2;
390
+ const hz = ((max[2] as number) - (min[2] as number)) / 2;
391
+ for (let axis = 0; axis < 3; axis += 1) {
392
+ const a = e[axis] as number;
393
+ const b = e[axis + 4] as number;
394
+ const c = e[axis + 8] as number;
395
+ const centre = a * cx + b * cy + c * cz + (e[axis + 12] as number);
396
+ const half = Math.abs(a) * hx + Math.abs(b) * hy + Math.abs(c) * hz;
397
+ target.min.setComponent(axis, centre - half);
398
+ target.max.setComponent(axis, centre + half);
399
+ }
400
+ return target;
401
+ }
@@ -2,6 +2,7 @@ import type { Object3D } from "three";
2
2
  import type { Material } from "three";
3
3
  import { BundleGroup } from "three/webgpu";
4
4
  import { lodChainOf } from "./model-lod.js";
5
+ import { rendererFacts } from "./renderer-facts.js";
5
6
  import type { IRendererLike } from "./renderer.js";
6
7
  import { markStatic } from "./static-transform.js";
7
8
  import { BundleSurfaceSafety, bundleSafe, ownHook } from "./world-bundle-safety.js";
@@ -209,8 +210,7 @@ export class CellBundles {
209
210
  if (this.#ownsBundles !== undefined) return this.#ownsBundles;
210
211
  const renderer = this.#host.renderer();
211
212
  if (renderer === undefined) return false;
212
- const info = (renderer.raw as { info?: object } | undefined)?.info;
213
- this.#ownsBundles = info !== undefined && "engine" in info;
213
+ this.#ownsBundles = rendererFacts(renderer).ownedEngine;
214
214
  return this.#ownsBundles;
215
215
  }
216
216
 
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  type Box3,
3
3
  type Camera,
4
- Frustum,
5
4
  type InstancedMesh,
6
5
  type Material,
7
6
  Matrix4,
@@ -48,6 +47,8 @@ import {
48
47
  type WorldGpuScene,
49
48
  liveKeyInstances,
50
49
  } from "./world-gpu-scene.js";
50
+ import { frustumPlanes } from "./world-gpu-types.js";
51
+ import { localClip, localPoint } from "./world-root-frame.js";
51
52
 
52
53
  /**
53
54
  * The mesh a key draws: its shape, its level's material, and the dress that points it at the GPU
@@ -74,6 +75,8 @@ export interface ICellGpuDressHost {
74
75
  carryPrewarm(old: ICasterScaleMesh, next: ICasterScaleMesh): void;
75
76
  isBundleHome(shared: SharedBatch): boolean;
76
77
  renderer(): IRendererLike | undefined;
78
+ /** The world root's own `matrixWorld`: the frame its placements are recorded in. */
79
+ root(): Matrix4;
77
80
 
78
81
  // The batches, the scene and the state the dress shares with the rest of the renderer.
79
82
  shared(): Map<string, SharedBatch>;
@@ -105,7 +108,6 @@ export interface ICellGpuDressHost {
105
108
 
106
109
  /** The scratch a draw's own planes are built in, reused per frame. */
107
110
  const _gpuEye = new Vector3();
108
- const _cullFrustum = new Frustum();
109
111
  const _cullProjScreen = new Matrix4();
110
112
 
111
113
  export class CellGpuDress {
@@ -194,11 +196,12 @@ export class CellGpuDress {
194
196
  : { geometry: own.geometry, material: own.material };
195
197
  return {
196
198
  ...shape,
197
- material: this.#lodSurface(entry.asset, level, entry.part, shape.material),
199
+ material: this.lodSurface(entry.asset, level, entry.part, shape.material),
198
200
  };
199
201
  }
200
202
 
201
- #lodSurface(assetId: string, level: number, partIndex: number, source: Material): Material {
203
+ /** The material a batch of this level and part draws: `source` with the LOD gate's mask, when the asset has one. */
204
+ lodSurface(assetId: string, level: number, partIndex: number, source: Material): Material {
202
205
  assertSlotFree(source, assetId);
203
206
  const asset = this.#host.asset(assetId);
204
207
  const part = asset?.levels[level]?.[partIndex];
@@ -254,7 +257,7 @@ export class CellGpuDress {
254
257
  const partIndex = Number(partText?.split("@")[0]);
255
258
  const part = asset.levels[level]?.[partIndex];
256
259
  if (part !== undefined) {
257
- const material = this.#lodSurface(asset.id, level, partIndex, part.material);
260
+ const material = this.lodSurface(asset.id, level, partIndex, part.material);
258
261
  if (
259
262
  material.userData.tnPublishedLodRange === true &&
260
263
  shared.mesh.geometry.getAttribute("tnPublishedLodRange") === undefined &&
@@ -630,19 +633,12 @@ export class CellGpuDress {
630
633
  const lives = this.liveGates();
631
634
  if (lives.size === 0) return [];
632
635
  // The dispatch's own camera, its own planes: this is asked for inside the dispatch that is
633
- // running, so the eye and the six planes are the ones the kernel is reading now.
636
+ // running, so the eye and the six planes are the ones the kernel is reading now — and, like the
637
+ // dispatch's, in the root's frame, because that is the frame the placements are recorded in.
638
+ const root = this.#host.root();
634
639
  const planes = this.#gpuPlanes;
635
- _cullFrustum.setFromProjectionMatrix(
636
- _cullProjScreen.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse),
637
- );
638
- for (const [index, plane] of _cullFrustum.planes.entries()) {
639
- const at = index * 4;
640
- planes[at] = plane.normal.x;
641
- planes[at + 1] = plane.normal.y;
642
- planes[at + 2] = plane.normal.z;
643
- planes[at + 3] = plane.constant;
644
- }
645
- _gpuEye.setFromMatrixPosition(camera.matrixWorld);
640
+ frustumPlanes(localClip(_cullProjScreen, camera, root), planes);
641
+ localPoint(_gpuEye.setFromMatrixPosition(camera.matrixWorld), root);
646
642
  const expected = liveKeyInstances(
647
643
  this.#host.gpuScene().placements,
648
644
  (slot) => {
@@ -14,6 +14,7 @@ import type {
14
14
  } from "./world-cell-data.js";
15
15
  import { clusterOf } from "./world-cell-data.js";
16
16
  import { PLACEMENT_RECORD_FLOATS } from "./world-cell-impostors.js";
17
+ import { placedBox } from "./world-cell-records.js";
17
18
  import {
18
19
  GPU_KEY_SUFFIX,
19
20
  MAIN_CULL_MARKER_MS,
@@ -27,6 +28,7 @@ import {
27
28
  type IWorldPackage,
28
29
  cellPlacements,
29
30
  } from "./world-package.js";
31
+ import { localClip } from "./world-root-frame.js";
30
32
 
31
33
  /**
32
34
  * The main pass's coarse cull: one volume per resident visibility cell, one frustum a frame, and the
@@ -69,6 +71,27 @@ export interface ICellMainCullSettings {
69
71
  /** The two scratch objects a cull builds its frustum in. */
70
72
  const _cullFrustum = new Frustum();
71
73
  const _cullProjScreen = new Matrix4();
74
+ const _cullBox = new Box3();
75
+
76
+ /** The owned engine's whole-set test (PRD-879): the indices of the packed boxes the frustum holds. */
77
+ type IBoxesInFrustum = (this: Frustum, boxes: Float64Array) => ArrayLike<number>;
78
+
79
+ /**
80
+ * Every packed box (min xyz, max xyz) the frustum intersects, by index. The owned engine answers the
81
+ * set in one call; upstream three, the `engine: "threejs"` arm, has no such method and tests each box.
82
+ */
83
+ function boxesInFrustum(frustum: Frustum, boxes: Float64Array): ArrayLike<number> {
84
+ const engine = (frustum as Frustum & { __tnIntersectsBoxes?: IBoxesInFrustum })
85
+ .__tnIntersectsBoxes;
86
+ if (typeof engine === "function") return engine.call(frustum, boxes);
87
+ const hits: number[] = [];
88
+ for (let at = 0; at < boxes.length; at += 6) {
89
+ _cullBox.min.fromArray(boxes, at);
90
+ _cullBox.max.fromArray(boxes, at + 3);
91
+ if (frustum.intersectsBox(_cullBox)) hits.push(at / 6);
92
+ }
93
+ return hits;
94
+ }
72
95
 
73
96
  export class CellMainCull {
74
97
  readonly #host: ICellMainCullHost;
@@ -118,6 +141,16 @@ export class CellMainCull {
118
141
  */
119
142
  readonly #cullCells = new Map<string, { cells: number; box: Box3 }>();
120
143
 
144
+ /**
145
+ * The non-empty volumes of `#cullCells` packed for the frame's one frustum test, and their names
146
+ * by index. Repacked only after a volume was admitted, widened or dropped, so a frame reads no box.
147
+ */
148
+ #cullBoxes = new Float64Array(0);
149
+
150
+ #cullNames: string[] = [];
151
+
152
+ #cullPacked = false;
153
+
121
154
  /** The visibility cells the last cull kept and the frame's set, trading places; see `#cullMainPass`. */
122
155
  #visibleSquares: Set<string> = new Set();
123
156
 
@@ -169,19 +202,18 @@ export class CellMainCull {
169
202
  if (camera === undefined || (camera as ICamera).isOrthographicCamera === true) return;
170
203
  this.#host.beginBundleFrame();
171
204
  this.#mainCullFrustums += 1;
172
- const frustum = _cullFrustum.setFromProjectionMatrix(
173
- _cullProjScreen.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse),
174
- );
205
+ // The volumes this tests and the records it narrows are the root's own, so the frustum is taken
206
+ // in the root's frame: a game that moves its world draws the squares that are over the camera.
207
+ const root = this.#host.render().root();
208
+ const frustum = _cullFrustum.setFromProjectionMatrix(localClip(_cullProjScreen, camera, root));
175
209
  // The visible visibility cells, for the whole pass, into a set that is reused and compared
176
210
  // rather than allocated: two sets trading places, so a settled camera allocates nothing at all.
177
211
  const next = this.#cullScratch;
178
212
  next.clear();
179
- for (const [cell, entry] of this.#cullCells) {
180
- // An occupied cell whose placements have not been decoded yet holds nothing to draw, and its
181
- // Y range is still empty — a volume that cannot be tested against ±Infinity is not one this
182
- // frame's answer may rest on.
183
- if (entry.box.isEmpty() === false && frustum.intersectsBox(entry.box)) next.add(cell);
184
- }
213
+ if (!this.#cullPacked) this.#packCullBoxes();
214
+ const hits = boxesInFrustum(frustum, this.#cullBoxes);
215
+ for (let at = 0; at < hits.length; at += 1)
216
+ next.add(this.#cullNames[hits[at] as number] as string);
185
217
  if (!sameSquares(next, this.#visibleSquares)) {
186
218
  this.#visibleEpoch += 1;
187
219
  const was = this.#visibleSquares;
@@ -250,14 +282,31 @@ export class CellMainCull {
250
282
  // After the coarse gate, and only for the main camera: an orthographic one — every shadow
251
283
  // level's own — returned at the top, so a level's render never dispatches over the main pass's
252
284
  // compaction.
253
- if (gpu.on) gpu.dispatch(this.#host.render().renderer() as IRendererLike, camera);
285
+ if (gpu.on) gpu.dispatch(this.#host.render().renderer() as IRendererLike, camera, root);
286
+ }
287
+
288
+ /**
289
+ * An occupied cell whose placements have not been decoded yet holds nothing to draw, and its Y
290
+ * range is still empty — a volume that cannot be tested against ±Infinity is not one a frame's
291
+ * answer may rest on, so it is not packed.
292
+ */
293
+ #packCullBoxes(): void {
294
+ this.#cullNames.length = 0;
295
+ this.#cullBoxes = new Float64Array(this.#cullCells.size * 6);
296
+ for (const [cell, { box }] of this.#cullCells) {
297
+ if (box.isEmpty()) continue;
298
+ const at = this.#cullNames.length * 6;
299
+ box.min.toArray(this.#cullBoxes, at);
300
+ box.max.toArray(this.#cullBoxes, at + 3);
301
+ this.#cullNames.push(cell);
302
+ }
303
+ this.#cullBoxes = this.#cullBoxes.subarray(0, this.#cullNames.length * 6);
304
+ this.#cullPacked = true;
254
305
  }
255
306
 
256
307
  /** Borrowed scratch box: consume its transformed volume before the next bounds query. */
257
308
  #boundsAt(bounds: IWorldAsset["bounds"], matrix: Matrix4): Box3 {
258
- this.#recordBounds.min.fromArray(bounds.min);
259
- this.#recordBounds.max.fromArray(bounds.max);
260
- return this.#recordBounds.applyMatrix4(matrix);
309
+ return placedBox(this.#recordBounds, bounds.min, bounds.max, matrix);
261
310
  }
262
311
 
263
312
  /**
@@ -305,6 +354,7 @@ export class CellMainCull {
305
354
  this.#cullCells.set(name, entry);
306
355
  }
307
356
  entry.cells += 1;
357
+ this.#cullPacked = false;
308
358
  const box = entry.box;
309
359
  for (const run of cell.runs) {
310
360
  const bounds = this.#manifest.assets[this.#host.render().canonical(run.asset)]?.bounds;
@@ -341,7 +391,10 @@ export class CellMainCull {
341
391
  const entry = this.#cullCells.get(name);
342
392
  if (entry === undefined) return;
343
393
  entry.cells -= 1;
344
- if (entry.cells <= 0) this.#cullCells.delete(name);
394
+ if (entry.cells <= 0) {
395
+ this.#cullCells.delete(name);
396
+ this.#cullPacked = false;
397
+ }
345
398
  }
346
399
 
347
400
  /**
@@ -472,9 +525,12 @@ export class CellMainCull {
472
525
  return _cullFrustum.intersectsObject(mesh);
473
526
  }
474
527
 
475
- /** The volume each resident visibility cell covers, which the chunk bounds widen on admission. */
476
- cells(): Map<string, { cells: number; box: Box3 }> {
477
- return this.#cullCells;
528
+ /** Widen a resident visibility cell's volume by a chunk's bounds; an unknown cell is left alone. */
529
+ widenCell(name: string, box: Box3): void {
530
+ const entry = this.#cullCells.get(name);
531
+ if (entry === undefined) return;
532
+ entry.box.union(box);
533
+ this.#cullPacked = false;
478
534
  }
479
535
 
480
536
  /** The visibility cells the last cull kept, which the GPU dress's coarse gate reads. */