@threenative/core 0.3.6 → 0.3.8

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 (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
@@ -0,0 +1,532 @@
1
+ import {
2
+ Box3,
3
+ type BufferAttribute,
4
+ type BufferGeometry,
5
+ DataTexture,
6
+ FloatType,
7
+ FrontSide,
8
+ type InterleavedBufferAttribute,
9
+ type Material,
10
+ Matrix3,
11
+ type Mesh,
12
+ NearestFilter,
13
+ type Object3D,
14
+ RGBAFormat,
15
+ Vector3,
16
+ } from "three";
17
+
18
+ /**
19
+ * The scene's static triangles, packed for a ray to walk on the GPU and, as the same walk, on the CPU.
20
+ *
21
+ * Why this exists beside `GPUSceneBVH`: that class hands three-mesh-bvh's WGSL ray query to the game, and
22
+ * the owned engine refuses that query by name (`three-native/src/addons/mesh-bvh-webgpu.ts`). This pack
23
+ * uses nothing but float textures and the TSL every engine runs, so one traversal serves the browser, the
24
+ * Wasm engine and the desktop player.
25
+ *
26
+ * Layout, RGBA32F, `TRACE_TEXTURE_WIDTH` texels per row, no filtering:
27
+ * nodes two texels per node, depth first (the left child is the next node):
28
+ * (low.xyz, skip) skip: the node after this subtree, or -1 at the end of the walk
29
+ * (high.xyz, leaf) leaf: -1 for an inner node, else `first * 16 + count`
30
+ * triangles six texels per triangle, in leaf order:
31
+ * (a.xyz, material) (b.xyz, side) (c.xyz, 0) then the three vertex normals
32
+ * side: 0 front faces only, 1 back faces only, 2 both, from the material's `side`
33
+ * materials two texels per material, in first-seen order:
34
+ * (colour.rgb, roughness) (emissive.rgb x intensity, metalness)
35
+ * Indices ride in the fourth channel as floats, exact below 2^24 (a scene under 2^20 triangles).
36
+ */
37
+ export const TRACE_TEXTURE_WIDTH = 2048;
38
+ export const NODE_TEXELS = 2;
39
+ export const TRIANGLE_TEXELS = 6;
40
+ export const MATERIAL_TEXELS = 2;
41
+ /** Triangles per leaf, at most; the leaf word keeps the count below 16. */
42
+ export const TRACE_LEAF_SIZE = 4;
43
+ const MAX_TRIANGLES = (1 << 20) - 1;
44
+ const SIDE_FRONT = 0;
45
+ const SIDE_BACK = 1;
46
+ const SIDE_BOTH = 2;
47
+ /** Three's `BackSide`. */
48
+ const BACK_SIDE = 1;
49
+ const EPSILON = 1e-9;
50
+ /**
51
+ * A ray this far outside a triangle's edge (barycentric units) still counts as inside. Float32 leaves hairline cracks
52
+ * between two triangles that share an edge, and a ray through one passes between both: a pinhole in a reflection, a
53
+ * leak of sun through a shadow. The tolerance is a hundredth of a millimetre on a metre-wide triangle.
54
+ */
55
+ export const EDGE_TOLERANCE = 1e-5;
56
+
57
+ export interface ITraceSceneOptions {
58
+ /** Which meshes join the pack. Default: every mesh under a visible parent chain. */
59
+ readonly include?: (mesh: Mesh) => boolean;
60
+ }
61
+
62
+ export interface ITraceSceneReport {
63
+ readonly triangles: number;
64
+ readonly nodes: number;
65
+ readonly materials: number;
66
+ /** Meshes left out because their triangles move (instanced, skinned, batched, morphing). */
67
+ readonly skippedMoving: number;
68
+ readonly milliseconds: number;
69
+ }
70
+
71
+ export interface ITraceHit {
72
+ readonly distance: number;
73
+ /** The triangle's index in leaf order. */
74
+ readonly triangle: number;
75
+ /** An index into `ITraceScene.materials`. */
76
+ readonly material: number;
77
+ readonly position: Vector3;
78
+ /** The interpolated vertex normal, flipped to face the ray. */
79
+ readonly normal: Vector3;
80
+ /** False when the ray reached the back of the surface. */
81
+ readonly front: boolean;
82
+ }
83
+
84
+ export interface ITraceScene {
85
+ readonly report: ITraceSceneReport;
86
+ readonly bounds: Box3;
87
+ /** The material of every id, for what the table cannot hold (a map, a node). */
88
+ readonly materials: readonly Material[];
89
+ readonly nodes: DataTexture;
90
+ readonly triangles: DataTexture;
91
+ readonly materialTable: DataTexture;
92
+ readonly nodeData: Float32Array;
93
+ readonly triangleData: Float32Array;
94
+ readonly materialData: Float32Array;
95
+ dispose(): void;
96
+ }
97
+
98
+ interface IFlatTriangles {
99
+ /** Per triangle, three corners of three. */
100
+ readonly corners: Float64Array;
101
+ /** Per triangle, three vertex normals of three. */
102
+ readonly normals: Float32Array;
103
+ readonly materialIds: Uint16Array;
104
+ readonly sides: Uint8Array;
105
+ readonly count: number;
106
+ }
107
+
108
+ function dataTexture(data: Float32Array, texels: number): DataTexture {
109
+ const height = Math.max(1, Math.ceil(texels / TRACE_TEXTURE_WIDTH));
110
+ const padded = new Float32Array(TRACE_TEXTURE_WIDTH * height * 4);
111
+ padded.set(data);
112
+ const result = new DataTexture(padded, TRACE_TEXTURE_WIDTH, height, RGBAFormat, FloatType);
113
+ result.minFilter = NearestFilter;
114
+ result.magFilter = NearestFilter;
115
+ result.generateMipmaps = false;
116
+ result.needsUpdate = true;
117
+ return result;
118
+ }
119
+
120
+ /** The material properties the trace reads, whichever material class carries them. */
121
+ interface IMaterialSlots {
122
+ color?: { r: number; g: number; b: number };
123
+ emissive?: { r: number; g: number; b: number };
124
+ emissiveIntensity?: unknown;
125
+ metalness?: unknown;
126
+ roughness?: unknown;
127
+ }
128
+
129
+ const sideOf = (material: Material): number =>
130
+ material.side === FrontSide ? SIDE_FRONT : material.side === BACK_SIDE ? SIDE_BACK : SIDE_BOTH;
131
+
132
+ /**
133
+ * A reader of component `c` of vertex `v`. Plain float data reads the attribute's own typed array, once per mesh:
134
+ * on the owned engine a method call per component crosses into the engine, and a scene has millions of them.
135
+ */
136
+ function reader(
137
+ attribute: BufferAttribute | InterleavedBufferAttribute,
138
+ ): (vertex: number, component: number) => number {
139
+ const raw = attribute as {
140
+ array?: ArrayLike<number>;
141
+ itemSize: number;
142
+ isInterleavedBufferAttribute?: boolean;
143
+ normalized?: boolean;
144
+ };
145
+ const array = raw.array;
146
+ if (raw.isInterleavedBufferAttribute !== true && raw.normalized !== true && array !== undefined) {
147
+ const stride = raw.itemSize;
148
+ return (vertex, component) => array[vertex * stride + component] ?? 0;
149
+ }
150
+ return (vertex, component) =>
151
+ component === 0
152
+ ? attribute.getX(vertex)
153
+ : component === 1
154
+ ? attribute.getY(vertex)
155
+ : attribute.getZ(vertex);
156
+ }
157
+
158
+ /** Every static mesh's triangles in world space, with vertex normals, material id and facing. */
159
+ function flatten(
160
+ root: Object3D,
161
+ include: (mesh: Mesh) => boolean,
162
+ materials: Material[],
163
+ ): { flat: IFlatTriangles; skippedMoving: number } {
164
+ root.updateMatrixWorld(true);
165
+ const meshes: Mesh[] = [];
166
+ let skippedMoving = 0;
167
+ root.traverseVisible((object) => {
168
+ const mesh = object as Mesh & Record<string, unknown>;
169
+ if (mesh.isMesh !== true || mesh.geometry === undefined || !include(mesh)) return;
170
+ const morphs = (mesh.morphTargetInfluences as unknown[] | undefined)?.length ?? 0;
171
+ if (
172
+ mesh.isInstancedMesh === true ||
173
+ mesh.isSkinnedMesh === true ||
174
+ mesh.isBatchedMesh === true ||
175
+ morphs > 0
176
+ ) {
177
+ skippedMoving += 1;
178
+ return;
179
+ }
180
+ meshes.push(mesh);
181
+ });
182
+ let count = 0;
183
+ for (const mesh of meshes) {
184
+ const geometry: BufferGeometry = mesh.geometry;
185
+ const position = geometry.attributes.position;
186
+ if (position !== undefined) count += Math.floor((geometry.index?.count ?? position.count) / 3);
187
+ }
188
+ if (count > MAX_TRIANGLES)
189
+ throw new RangeError(
190
+ `TN_TRACE_SCENE_TOO_LARGE: ${count} triangles; the pack holds at most ${MAX_TRIANGLES}`,
191
+ );
192
+ const corners = new Float64Array(count * 9);
193
+ const normals = new Float32Array(count * 9);
194
+ const materialIds = new Uint16Array(count);
195
+ const sides = new Uint8Array(count);
196
+ const ids = new Map<Material, number>();
197
+ const matrix3 = new Matrix3();
198
+ let filled = 0;
199
+ for (const mesh of meshes) {
200
+ const geometry = mesh.geometry;
201
+ const position = geometry.attributes.position;
202
+ if (position === undefined) continue;
203
+ const vertexNormal = geometry.attributes.normal;
204
+ const index = geometry.index;
205
+ const indexArray = index === null ? undefined : (index.array as ArrayLike<number>);
206
+ const readPosition = reader(position);
207
+ const readNormal = vertexNormal === undefined ? undefined : reader(vertexNormal);
208
+ // Elements of the world matrix and of its normal matrix, read once: 4 x 4 column-major and 3 x 3 column-major.
209
+ const m = [...mesh.matrixWorld.elements];
210
+ const n = [...matrix3.getNormalMatrix(mesh.matrixWorld).elements];
211
+ // A mirroring transform reverses the winding, so the face a ray calls front swaps with it.
212
+ const mirrored = mesh.matrixWorld.determinant() < 0;
213
+ const triangles = Math.floor((index?.count ?? position.count) / 3);
214
+ const list = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
215
+ for (let t = 0; t < triangles; t += 1) {
216
+ let slot = 0;
217
+ if (Array.isArray(mesh.material)) {
218
+ const first = t * 3;
219
+ slot =
220
+ geometry.groups.find((g) => first >= g.start && first < g.start + g.count)
221
+ ?.materialIndex ?? 0;
222
+ }
223
+ const material = list[slot] ?? list[0];
224
+ if (material === undefined) continue;
225
+ let id = ids.get(material);
226
+ if (id === undefined) {
227
+ id = materials.length;
228
+ ids.set(material, id);
229
+ materials.push(material);
230
+ }
231
+ for (let k = 0; k < 3; k += 1) {
232
+ const vertex = indexArray === undefined ? t * 3 + k : (indexArray[t * 3 + k] ?? 0);
233
+ const target = filled * 9 + (mirrored && k > 0 ? 3 - k : k) * 3;
234
+ const x = readPosition(vertex, 0);
235
+ const y = readPosition(vertex, 1);
236
+ const z = readPosition(vertex, 2);
237
+ corners[target] = (m[0] ?? 0) * x + (m[4] ?? 0) * y + (m[8] ?? 0) * z + (m[12] ?? 0);
238
+ corners[target + 1] = (m[1] ?? 0) * x + (m[5] ?? 0) * y + (m[9] ?? 0) * z + (m[13] ?? 0);
239
+ corners[target + 2] = (m[2] ?? 0) * x + (m[6] ?? 0) * y + (m[10] ?? 0) * z + (m[14] ?? 0);
240
+ const nx = readNormal === undefined ? 0 : readNormal(vertex, 0);
241
+ const ny = readNormal === undefined ? 1 : readNormal(vertex, 1);
242
+ const nz = readNormal === undefined ? 0 : readNormal(vertex, 2);
243
+ const wx = (n[0] ?? 0) * nx + (n[3] ?? 0) * ny + (n[6] ?? 0) * nz;
244
+ const wy = (n[1] ?? 0) * nx + (n[4] ?? 0) * ny + (n[7] ?? 0) * nz;
245
+ const wz = (n[2] ?? 0) * nx + (n[5] ?? 0) * ny + (n[8] ?? 0) * nz;
246
+ const length = Math.hypot(wx, wy, wz) || 1;
247
+ normals[target] = wx / length;
248
+ normals[target + 1] = wy / length;
249
+ normals[target + 2] = wz / length;
250
+ }
251
+ materialIds[filled] = id;
252
+ sides[filled] = sideOf(material);
253
+ filled += 1;
254
+ }
255
+ }
256
+ return {
257
+ flat: { corners, normals, materialIds, sides, count: filled },
258
+ skippedMoving,
259
+ };
260
+ }
261
+
262
+ interface IBuilt {
263
+ /** Leaf-order triangle ids. */
264
+ readonly order: Uint32Array;
265
+ /** Per node: low (3), skip, high (3), leaf. */
266
+ readonly nodes: Float32Array;
267
+ readonly nodeCount: number;
268
+ }
269
+
270
+ /**
271
+ * Median split on the longest axis of the centroids, `TRACE_LEAF_SIZE` triangles a leaf.
272
+ * ponytail: a sort per node (O(n log^2 n)); a binned SAH when scenes pass a few hundred thousand triangles.
273
+ */
274
+ function build(flat: IFlatTriangles): IBuilt {
275
+ const { corners, count } = flat;
276
+ const low = new Float32Array(count * 3);
277
+ const high = new Float32Array(count * 3);
278
+ const centroid = new Float32Array(count * 3);
279
+ for (let t = 0; t < count; t += 1)
280
+ for (let a = 0; a < 3; a += 1) {
281
+ const x = corners[t * 9 + a] ?? 0;
282
+ const y = corners[t * 9 + 3 + a] ?? 0;
283
+ const z = corners[t * 9 + 6 + a] ?? 0;
284
+ low[t * 3 + a] = Math.min(x, y, z);
285
+ high[t * 3 + a] = Math.max(x, y, z);
286
+ centroid[t * 3 + a] = (x + y + z) / 3;
287
+ }
288
+ const order = new Uint32Array(count);
289
+ for (let t = 0; t < count; t += 1) order[t] = t;
290
+ const words: number[] = [];
291
+ const visit = (start: number, end: number): void => {
292
+ const slot = words.length / 8;
293
+ const lo = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];
294
+ const hi = [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY];
295
+ const centre = [...lo];
296
+ const centreHigh = [...hi];
297
+ for (let i = start; i < end; i += 1) {
298
+ const t = order[i] ?? 0;
299
+ for (let a = 0; a < 3; a += 1) {
300
+ lo[a] = Math.min(lo[a] ?? 0, low[t * 3 + a] ?? 0);
301
+ hi[a] = Math.max(hi[a] ?? 0, high[t * 3 + a] ?? 0);
302
+ centre[a] = Math.min(centre[a] ?? 0, centroid[t * 3 + a] ?? 0);
303
+ centreHigh[a] = Math.max(centreHigh[a] ?? 0, centroid[t * 3 + a] ?? 0);
304
+ }
305
+ }
306
+ words.push(lo[0] ?? 0, lo[1] ?? 0, lo[2] ?? 0, -1, hi[0] ?? 0, hi[1] ?? 0, hi[2] ?? 0, -1);
307
+ if (end - start <= TRACE_LEAF_SIZE) {
308
+ words[slot * 8 + 7] = start * 16 + (end - start);
309
+ } else {
310
+ const span = centreHigh.map((v, a) => v - (centre[a] ?? 0));
311
+ const axis =
312
+ (span[0] ?? 0) >= (span[1] ?? 0) && (span[0] ?? 0) >= (span[2] ?? 0)
313
+ ? 0
314
+ : (span[1] ?? 0) >= (span[2] ?? 0)
315
+ ? 1
316
+ : 2;
317
+ const sorted = Array.from(order.subarray(start, end)).sort(
318
+ (p, q) => (centroid[p * 3 + axis] ?? 0) - (centroid[q * 3 + axis] ?? 0),
319
+ );
320
+ order.set(sorted, start);
321
+ const middle = (start + end) >> 1;
322
+ visit(start, middle);
323
+ visit(middle, end);
324
+ }
325
+ // Depth first: the next node outside this subtree is the one numbered next.
326
+ words[slot * 8 + 3] = words.length / 8;
327
+ };
328
+ if (count > 0) visit(0, count);
329
+ const nodeCount = words.length / 8;
330
+ for (let n = 0; n < nodeCount; n += 1)
331
+ if ((words[n * 8 + 3] ?? 0) >= nodeCount) words[n * 8 + 3] = -1;
332
+ return { order, nodes: new Float32Array(words), nodeCount };
333
+ }
334
+
335
+ /**
336
+ * Packs the static triangles under `root` (world space, now) into the textures a trace reads.
337
+ * The scene must not move afterwards: build again after a transform or geometry change.
338
+ */
339
+ export function packTraceScene(root: Object3D, options: ITraceSceneOptions = {}): ITraceScene {
340
+ const started = globalThis.performance?.now() ?? Date.now();
341
+ const materials: Material[] = [];
342
+ const { flat, skippedMoving } = flatten(root, options.include ?? (() => true), materials);
343
+ const built = build(flat);
344
+ const triangleData = new Float32Array(flat.count * TRIANGLE_TEXELS * 4);
345
+ const bounds = new Box3();
346
+ for (let slot = 0; slot < flat.count; slot += 1) {
347
+ const t = built.order[slot] ?? 0;
348
+ const o = slot * TRIANGLE_TEXELS * 4;
349
+ for (let k = 0; k < 3; k += 1) {
350
+ for (let a = 0; a < 3; a += 1) {
351
+ triangleData[o + k * 4 + a] = flat.corners[t * 9 + k * 3 + a] ?? 0;
352
+ triangleData[o + (3 + k) * 4 + a] = flat.normals[t * 9 + k * 3 + a] ?? 0;
353
+ }
354
+ bounds.expandByPoint(
355
+ new Vector3(
356
+ flat.corners[t * 9 + k * 3] ?? 0,
357
+ flat.corners[t * 9 + k * 3 + 1] ?? 0,
358
+ flat.corners[t * 9 + k * 3 + 2] ?? 0,
359
+ ),
360
+ );
361
+ }
362
+ triangleData[o + 3] = flat.materialIds[t] ?? 0;
363
+ triangleData[o + 7] = flat.sides[t] ?? SIDE_BOTH;
364
+ }
365
+ const materialData = new Float32Array(Math.max(1, materials.length) * MATERIAL_TEXELS * 4);
366
+ materials.forEach((material, id) => {
367
+ const slots = material as Material & IMaterialSlots;
368
+ const colour = slots.color;
369
+ const emissive = slots.emissive;
370
+ const number = (
371
+ key: "emissiveIntensity" | "metalness" | "roughness",
372
+ fallback: number,
373
+ ): number => {
374
+ const value = slots[key];
375
+ return typeof value === "number" ? value : fallback;
376
+ };
377
+ const o = id * MATERIAL_TEXELS * 4;
378
+ materialData.set([colour?.r ?? 1, colour?.g ?? 1, colour?.b ?? 1, number("roughness", 1)], o);
379
+ const glow = number("emissiveIntensity", 1);
380
+ materialData.set(
381
+ [
382
+ (emissive?.r ?? 0) * glow,
383
+ (emissive?.g ?? 0) * glow,
384
+ (emissive?.b ?? 0) * glow,
385
+ number("metalness", 0),
386
+ ],
387
+ o + 4,
388
+ );
389
+ });
390
+ const nodeTexture = dataTexture(built.nodes, built.nodeCount * NODE_TEXELS);
391
+ const triangleTexture = dataTexture(triangleData, flat.count * TRIANGLE_TEXELS);
392
+ const materialTexture = dataTexture(materialData, materials.length * MATERIAL_TEXELS);
393
+ return {
394
+ report: {
395
+ triangles: flat.count,
396
+ nodes: built.nodeCount,
397
+ materials: materials.length,
398
+ skippedMoving,
399
+ milliseconds: Math.round((globalThis.performance?.now() ?? Date.now()) - started),
400
+ },
401
+ bounds,
402
+ materials,
403
+ nodes: nodeTexture,
404
+ triangles: triangleTexture,
405
+ materialTable: materialTexture,
406
+ nodeData: built.nodes,
407
+ triangleData,
408
+ materialData,
409
+ dispose(): void {
410
+ nodeTexture.dispose();
411
+ triangleTexture.dispose();
412
+ materialTexture.dispose();
413
+ },
414
+ };
415
+ }
416
+
417
+ /**
418
+ * The walk the GPU kernel makes, in plain TypeScript: the reference the spec holds the pack to, and what a
419
+ * game may call to ask one question of the same data. Nearest hit within `far`, or undefined.
420
+ */
421
+ export function traceScene(
422
+ scene: Pick<ITraceScene, "nodeData" | "triangleData" | "report">,
423
+ origin: Vector3,
424
+ direction: Vector3,
425
+ far = Number.POSITIVE_INFINITY,
426
+ anyHit = false,
427
+ ): ITraceHit | undefined {
428
+ const { nodeData: nodes, triangleData: tri } = scene;
429
+ const dir = [direction.x, direction.y, direction.z].map((v) =>
430
+ Math.abs(v) < EPSILON ? (v < 0 ? -EPSILON : EPSILON) : v,
431
+ ) as [number, number, number];
432
+ const inv = dir.map((v) => 1 / v) as [number, number, number];
433
+ const o = [origin.x, origin.y, origin.z] as const;
434
+ let best = far;
435
+ let bestTriangle = -1;
436
+ let bestU = 0;
437
+ let bestV = 0;
438
+ let bestFront = true;
439
+ let node = scene.report.nodes > 0 ? 0 : -1;
440
+ while (node >= 0) {
441
+ const n = node * 8;
442
+ let tMin = 0;
443
+ let tMax = best;
444
+ for (let a = 0; a < 3; a += 1) {
445
+ const t0 = ((nodes[n + a] ?? 0) - (o[a] ?? 0)) * (inv[a] ?? 0);
446
+ const t1 = ((nodes[n + 4 + a] ?? 0) - (o[a] ?? 0)) * (inv[a] ?? 0);
447
+ tMin = Math.max(tMin, Math.min(t0, t1));
448
+ tMax = Math.min(tMax, Math.max(t0, t1));
449
+ }
450
+ if (tMax < tMin) {
451
+ node = nodes[n + 3] ?? -1;
452
+ continue;
453
+ }
454
+ const leaf = nodes[n + 7] ?? -1;
455
+ if (leaf < 0) {
456
+ node += 1;
457
+ continue;
458
+ }
459
+ const first = Math.floor(leaf / 16);
460
+ const count = leaf - first * 16;
461
+ for (let i = first; i < first + count; i += 1) {
462
+ const b = i * TRIANGLE_TEXELS * 4;
463
+ const ax = tri[b] ?? 0;
464
+ const ay = tri[b + 1] ?? 0;
465
+ const az = tri[b + 2] ?? 0;
466
+ const e1 = [(tri[b + 4] ?? 0) - ax, (tri[b + 5] ?? 0) - ay, (tri[b + 6] ?? 0) - az];
467
+ const e2 = [(tri[b + 8] ?? 0) - ax, (tri[b + 9] ?? 0) - ay, (tri[b + 10] ?? 0) - az];
468
+ // Moller-Trumbore. det > 0 is a hit on the front face (the ray opposes e1 x e2).
469
+ const p = [
470
+ dir[1] * (e2[2] ?? 0) - dir[2] * (e2[1] ?? 0),
471
+ dir[2] * (e2[0] ?? 0) - dir[0] * (e2[2] ?? 0),
472
+ dir[0] * (e2[1] ?? 0) - dir[1] * (e2[0] ?? 0),
473
+ ];
474
+ const det =
475
+ (e1[0] ?? 0) * (p[0] ?? 0) + (e1[1] ?? 0) * (p[1] ?? 0) + (e1[2] ?? 0) * (p[2] ?? 0);
476
+ const side = tri[b + 7] ?? SIDE_BOTH;
477
+ const facing =
478
+ side === SIDE_BOTH
479
+ ? Math.abs(det) > EPSILON
480
+ : side === SIDE_FRONT
481
+ ? det > EPSILON
482
+ : det < -EPSILON;
483
+ if (!facing) continue;
484
+ const s = [o[0] - ax, o[1] - ay, o[2] - az];
485
+ const u =
486
+ ((s[0] ?? 0) * (p[0] ?? 0) + (s[1] ?? 0) * (p[1] ?? 0) + (s[2] ?? 0) * (p[2] ?? 0)) / det;
487
+ if (u < -EDGE_TOLERANCE || u > 1 + EDGE_TOLERANCE) continue;
488
+ const q = [
489
+ (s[1] ?? 0) * (e1[2] ?? 0) - (s[2] ?? 0) * (e1[1] ?? 0),
490
+ (s[2] ?? 0) * (e1[0] ?? 0) - (s[0] ?? 0) * (e1[2] ?? 0),
491
+ (s[0] ?? 0) * (e1[1] ?? 0) - (s[1] ?? 0) * (e1[0] ?? 0),
492
+ ];
493
+ const v = (dir[0] * (q[0] ?? 0) + dir[1] * (q[1] ?? 0) + dir[2] * (q[2] ?? 0)) / det;
494
+ if (v < -EDGE_TOLERANCE || u + v > 1 + EDGE_TOLERANCE) continue;
495
+ const t =
496
+ ((e2[0] ?? 0) * (q[0] ?? 0) + (e2[1] ?? 0) * (q[1] ?? 0) + (e2[2] ?? 0) * (q[2] ?? 0)) /
497
+ det;
498
+ if (t > EPSILON && t < best) {
499
+ best = t;
500
+ bestTriangle = i;
501
+ bestU = u;
502
+ bestV = v;
503
+ bestFront = det > 0;
504
+ if (anyHit) node = -2;
505
+ }
506
+ }
507
+ node = node === -2 ? -1 : (nodes[n + 3] ?? -1);
508
+ }
509
+ if (bestTriangle < 0) return undefined;
510
+ const b = bestTriangle * TRIANGLE_TEXELS * 4;
511
+ const w = 1 - bestU - bestV;
512
+ const normal = new Vector3();
513
+ for (let a = 0; a < 3; a += 1)
514
+ normal.setComponent(
515
+ a,
516
+ w * (tri[b + 12 + a] ?? 0) + bestU * (tri[b + 16 + a] ?? 0) + bestV * (tri[b + 20 + a] ?? 0),
517
+ );
518
+ normal.normalize();
519
+ if (normal.x * direction.x + normal.y * direction.y + normal.z * direction.z > 0) normal.negate();
520
+ return {
521
+ distance: best,
522
+ triangle: bestTriangle,
523
+ material: tri[b + 3] ?? 0,
524
+ position: new Vector3(
525
+ origin.x + dir[0] * best,
526
+ origin.y + dir[1] * best,
527
+ origin.z + dir[2] * best,
528
+ ),
529
+ normal,
530
+ front: bestFront,
531
+ };
532
+ }