@needle-tools/three-mesh-effects 0.2.3 → 0.3.2

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 (113) hide show
  1. package/CHANGELOG.md +34 -8
  2. package/README.md +86 -3
  3. package/SKILL.md +14 -4
  4. package/build/box-impostor-runtime.js +1423 -0
  5. package/build/box-impostor-runtime.js.map +7 -0
  6. package/build/deformation-runtime.js +30 -19
  7. package/build/deformation-runtime.js.map +3 -3
  8. package/build/hull-effects.js +60 -28
  9. package/build/hull-effects.js.map +3 -3
  10. package/build/impostor-runtime.js +264 -133
  11. package/build/impostor-runtime.js.map +4 -4
  12. package/build/index.js +8 -0
  13. package/build/index.js.map +2 -2
  14. package/build/internal/box-impostor/box-impostor-display-settings.js +50 -0
  15. package/build/internal/box-impostor/box-impostor-display-settings.js.map +7 -0
  16. package/build/internal/box-impostor/box-impostor-display.js +1102 -0
  17. package/build/internal/box-impostor/box-impostor-display.js.map +7 -0
  18. package/build/internal/box-impostor/box-impostor-face-axes.js +15 -0
  19. package/build/internal/box-impostor/box-impostor-face-axes.js.map +7 -0
  20. package/build/internal/box-impostor/box-impostor-faces.js +125 -0
  21. package/build/internal/box-impostor/box-impostor-faces.js.map +7 -0
  22. package/build/internal/box-impostor/box-impostor-geometry.js +230 -0
  23. package/build/internal/box-impostor/box-impostor-geometry.js.map +7 -0
  24. package/build/internal/box-impostor/box-impostor-material.js +1056 -0
  25. package/build/internal/box-impostor/box-impostor-material.js.map +7 -0
  26. package/build/internal/box-impostor/box-impostor-metadata.js +108 -0
  27. package/build/internal/box-impostor/box-impostor-metadata.js.map +7 -0
  28. package/build/internal/box-impostor/box-impostor-projection.js +276 -0
  29. package/build/internal/box-impostor/box-impostor-projection.js.map +7 -0
  30. package/build/internal/box-impostor/box-impostor-runtime.js +1369 -0
  31. package/build/internal/box-impostor/box-impostor-runtime.js.map +7 -0
  32. package/build/internal/box-impostor/box-impostor-surface-search.js +21 -0
  33. package/build/internal/box-impostor/box-impostor-surface-search.js.map +7 -0
  34. package/build/internal/deformation/cloth-surface.js +23 -17
  35. package/build/internal/deformation/cloth-surface.js.map +3 -3
  36. package/build/internal/deformation/pin-cloth.js +7 -2
  37. package/build/internal/deformation/pin-cloth.js.map +2 -2
  38. package/build/internal/deformation/rig-runtime.js +30 -19
  39. package/build/internal/deformation/rig-runtime.js.map +3 -3
  40. package/build/internal/impostor/impostor-node-material.js +264 -133
  41. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  42. package/build/internal/pixel-impostor/pixel-impostor-display.js +84 -38
  43. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +4 -4
  44. package/build/internal/rendering/captured-surface-depth.js +35 -0
  45. package/build/internal/rendering/captured-surface-depth.js.map +7 -0
  46. package/build/internal/rendering/captured-surface-material.js +28 -0
  47. package/build/internal/rendering/captured-surface-material.js.map +7 -0
  48. package/build/internal/rendering/hull-effect-runtime.js +59 -27
  49. package/build/internal/rendering/hull-effect-runtime.js.map +3 -3
  50. package/build/internal/rendering/renderer-support.js +31 -0
  51. package/build/internal/rendering/renderer-support.js.map +7 -0
  52. package/build/internal/rendering/wireframe.js +41 -9
  53. package/build/internal/rendering/wireframe.js.map +2 -2
  54. package/build/internal/rendering/wrap-preview.js +59 -27
  55. package/build/internal/rendering/wrap-preview.js.map +3 -3
  56. package/build/pixel-impostor-runtime.js +84 -38
  57. package/build/pixel-impostor-runtime.js.map +4 -4
  58. package/build/types/box-impostor/box-impostor-display-settings.d.ts +30 -0
  59. package/build/types/box-impostor/box-impostor-display-settings.js +1 -0
  60. package/build/types/box-impostor/box-impostor-display.d.ts +13 -0
  61. package/build/types/box-impostor/box-impostor-display.js +1 -0
  62. package/build/types/box-impostor/box-impostor-face-axes.d.ts +5 -0
  63. package/build/types/box-impostor/box-impostor-face-axes.js +1 -0
  64. package/build/types/box-impostor/box-impostor-faces.d.ts +11 -0
  65. package/build/types/box-impostor/box-impostor-faces.js +1 -0
  66. package/build/types/box-impostor/box-impostor-geometry.d.ts +5 -0
  67. package/build/types/box-impostor/box-impostor-geometry.js +1 -0
  68. package/build/types/box-impostor/box-impostor-material.d.ts +14 -0
  69. package/build/types/box-impostor/box-impostor-material.js +1 -0
  70. package/build/types/box-impostor/box-impostor-metadata.d.ts +31 -0
  71. package/build/types/box-impostor/box-impostor-metadata.js +1 -0
  72. package/build/types/box-impostor/box-impostor-projection.d.ts +19 -0
  73. package/build/types/box-impostor/box-impostor-projection.js +1 -0
  74. package/build/types/box-impostor/box-impostor-runtime.d.ts +19 -0
  75. package/build/types/box-impostor/box-impostor-runtime.js +1 -0
  76. package/build/types/box-impostor/box-impostor-surface-search.d.ts +13 -0
  77. package/build/types/box-impostor/box-impostor-surface-search.js +1 -0
  78. package/build/types/deformation/cloth-surface.d.ts +1 -0
  79. package/build/types/deformation/pin-cloth.d.ts +1 -0
  80. package/build/types/impostor/impostor-node-material.d.ts +2 -15
  81. package/build/types/public/box-impostor-runtime.d.ts +6 -0
  82. package/build/types/public/box-impostor-runtime.js +1 -0
  83. package/build/types/public/hull-effects.d.ts +1 -0
  84. package/build/types/public/index.d.ts +1 -1
  85. package/build/types/rendering/captured-surface-depth.d.ts +5 -0
  86. package/build/types/rendering/captured-surface-depth.js +1 -0
  87. package/build/types/rendering/captured-surface-material.d.ts +8 -0
  88. package/build/types/rendering/captured-surface-material.js +1 -0
  89. package/build/types/rendering/renderer-support.d.ts +27 -0
  90. package/build/types/rendering/renderer-support.js +1 -0
  91. package/build/types/rendering/wireframe.d.ts +2 -2
  92. package/package.json +29 -8
  93. package/src/box-impostor/box-impostor-display-settings.js +54 -0
  94. package/src/box-impostor/box-impostor-display.js +50 -0
  95. package/src/box-impostor/box-impostor-face-axes.js +11 -0
  96. package/src/box-impostor/box-impostor-faces.js +118 -0
  97. package/src/box-impostor/box-impostor-geometry.js +140 -0
  98. package/src/box-impostor/box-impostor-material.js +771 -0
  99. package/src/box-impostor/box-impostor-metadata.js +122 -0
  100. package/src/box-impostor/box-impostor-projection.js +276 -0
  101. package/src/box-impostor/box-impostor-runtime.js +124 -0
  102. package/src/box-impostor/box-impostor-surface-search.js +11 -0
  103. package/src/deformation/cloth-surface.ts +28 -17
  104. package/src/deformation/pin-cloth.ts +9 -3
  105. package/src/impostor/impostor-node-material.js +188 -157
  106. package/src/pixel-impostor/pixel-impostor-display.js +5 -13
  107. package/src/public/box-impostor-runtime.js +14 -0
  108. package/src/public/hull-effects.js +1 -0
  109. package/src/public/index.js +10 -1
  110. package/src/rendering/captured-surface-depth.js +55 -0
  111. package/src/rendering/captured-surface-material.js +27 -0
  112. package/src/rendering/renderer-support.js +50 -0
  113. package/src/rendering/wireframe.js +51 -13
@@ -0,0 +1,1369 @@
1
+ // @ts-nocheck
2
+
3
+ // src/box-impostor/box-impostor-runtime.js
4
+ import {
5
+ ClampToEdgeWrapping,
6
+ LinearFilter as LinearFilter2,
7
+ NearestFilter as NearestFilter4,
8
+ NoColorSpace,
9
+ SRGBColorSpace
10
+ } from "three";
11
+
12
+ // src/box-impostor/box-impostor-display-settings.js
13
+ var DEFAULT_BOX_IMPOSTOR_DISPLAY = Object.freeze({
14
+ depthMode: (
15
+ /** @type {'auto'|'projection'|'depth'} */
16
+ "auto"
17
+ ),
18
+ raySteps: (
19
+ /** @type {8|16|32} */
20
+ 16
21
+ ),
22
+ alphaCutoff: 0.5,
23
+ interpolation: (
24
+ /** @type {'none'|'linear'|'smooth'} */
25
+ "none"
26
+ ),
27
+ transparency: (
28
+ /** @type {'auto'|'cutout'|'dithered'|'blended'} */
29
+ "auto"
30
+ )
31
+ });
32
+ function normalizeBoxImpostorDisplay(input = {}) {
33
+ const value = { ...DEFAULT_BOX_IMPOSTOR_DISPLAY, ...input };
34
+ if (!["auto", "projection", "depth"].includes(value.depthMode) || ![8, 16, 32].includes(value.raySteps) || !Number.isFinite(value.alphaCutoff) || value.alphaCutoff <= 0 || value.alphaCutoff >= 1 || !["none", "linear", "smooth"].includes(value.interpolation) || !["auto", "cutout", "dithered", "blended"].includes(value.transparency))
35
+ throw new Error("Invalid box impostor display settings.");
36
+ return {
37
+ depthMode: value.depthMode,
38
+ raySteps: value.raySteps,
39
+ alphaCutoff: value.alphaCutoff,
40
+ interpolation: value.interpolation,
41
+ transparency: value.transparency
42
+ };
43
+ }
44
+ function boxTransparency(descriptor, settings) {
45
+ return settings.transparency === "auto" ? descriptor.alphaMode === "blend" ? "blended" : "cutout" : settings.transparency;
46
+ }
47
+ function boxDepthMode(descriptor, settings) {
48
+ if (settings.depthMode !== "auto") return settings.depthMode;
49
+ return descriptor.boxes.every(
50
+ (box) => box.planes?.length === 6 && box.planeErrors?.length === 6 && box.planeErrors.every((error) => error <= 2 / 255)
51
+ ) ? "projection" : "depth";
52
+ }
53
+
54
+ // src/box-impostor/box-impostor-face-axes.js
55
+ var BOX_FACE_AXES = Object.freeze([
56
+ { normal: [1, 0, 0], right: [0, 0, -1], up: [0, 1, 0] },
57
+ { normal: [-1, 0, 0], right: [0, 0, 1], up: [0, 1, 0] },
58
+ { normal: [0, 1, 0], right: [1, 0, 0], up: [0, 0, -1] },
59
+ { normal: [0, -1, 0], right: [1, 0, 0], up: [0, 0, 1] },
60
+ { normal: [0, 0, 1], right: [1, 0, 0], up: [0, 1, 0] },
61
+ { normal: [0, 0, -1], right: [-1, 0, 0], up: [0, 1, 0] }
62
+ ]);
63
+
64
+ // src/box-impostor/box-impostor-metadata.js
65
+ var NEEDLE_BOX_IMPOSTOR = "NEEDLE_box_impostor";
66
+ var BOX_OCCUPANCY_RESOLUTION = 8;
67
+ var BOX_OCCUPANCY_WORDS = BOX_OCCUPANCY_RESOLUTION ** 3 / 32;
68
+ function parseBoxImpostorDescriptor(raw) {
69
+ const d = (
70
+ /** @type {BoxImpostorDescriptor} */
71
+ raw
72
+ );
73
+ const fail = () => {
74
+ throw new Error("Invalid NEEDLE_box_impostor descriptor.");
75
+ };
76
+ const vector = (v) => Array.isArray(v) && v.length === 3 && v.every(Number.isFinite);
77
+ if (!d || d.version !== 1 || !["basic", "cards", "fitted"].includes(d.mode) || ![8, 16, 32].includes(d.raySteps) || !Number.isInteger(d.atlasResolution) || d.atlasResolution < 32 || d.atlasResolution > 8192 || !Number.isInteger(d.padding) || d.padding < 1 || d.padding > 16 || !Number.isFinite(d.alphaCutoff) || d.alphaCutoff <= 0 || d.alphaCutoff >= 1 || !Array.isArray(d.boxes) || !d.boxes.length || d.boxes.length > 64)
78
+ fail();
79
+ if (d.alphaMode !== void 0 && !["opaque", "mask", "blend"].includes(d.alphaMode))
80
+ fail();
81
+ if (d.mode === "basic" && d.boxes.length !== 1) fail();
82
+ for (const b of d.boxes) {
83
+ if (b.occupancy !== void 0 && (!Array.isArray(b.occupancy) || b.occupancy.length !== BOX_OCCUPANCY_WORDS || !b.occupancy.every(
84
+ (v) => Number.isInteger(v) && v >= 0 && v <= 4294967295
85
+ )))
86
+ fail();
87
+ if (b.depthBounds !== void 0 && (!Array.isArray(b.depthBounds) || b.depthBounds.length !== 12 || !b.depthBounds.every(
88
+ (v) => Number.isInteger(v) && v >= 0 && v <= 65535
89
+ )))
90
+ fail();
91
+ if (b.planeErrors !== void 0 && (!Array.isArray(b.planeErrors) || b.planeErrors.length !== 6 || !b.planeErrors.every((v) => Number.isFinite(v) && v >= 0 && v <= 1)))
92
+ fail();
93
+ if (b.planes !== void 0 && (!Array.isArray(b.planes) || b.planes.length !== 6 || !b.planes.every((v) => Number.isFinite(v) && v >= 0 && v <= 1)))
94
+ fail();
95
+ if (!vector(b.center) || !vector(b.halfSize) || b.halfSize.some((v) => v <= 0) || !Array.isArray(b.axes) || b.axes.length !== 3 || !b.axes.every(vector) || !Array.isArray(b.views) || b.views.length !== 6)
96
+ fail();
97
+ for (let i = 0; i < 3; i++)
98
+ for (let j = 0; j < 3; j++) {
99
+ const dot4 = b.axes[i].reduce((s, v, k) => s + v * b.axes[j][k], 0);
100
+ if (Math.abs(dot4 - (i === j ? 1 : 0)) > 1e-4) fail();
101
+ }
102
+ const [x, y, z] = b.axes;
103
+ if ((x[1] * y[2] - x[2] * y[1]) * z[0] + (x[2] * y[0] - x[0] * y[2]) * z[1] + (x[0] * y[1] - x[1] * y[0]) * z[2] < 0.999)
104
+ fail();
105
+ for (const r of b.views)
106
+ if (!Array.isArray(r) || r.length !== 4 || !r.every(Number.isInteger) || r[0] < 0 || r[1] < 0 || r[2] <= d.padding * 2 || r[3] <= d.padding * 2 || r[0] + r[2] > d.atlasResolution || r[1] + r[3] > d.atlasResolution)
107
+ fail();
108
+ }
109
+ return {
110
+ version: d.version,
111
+ mode: d.mode,
112
+ atlasResolution: d.atlasResolution,
113
+ padding: d.padding,
114
+ boxes: d.boxes,
115
+ ...d.alphaMode ? { alphaMode: d.alphaMode } : {},
116
+ ...normalizeBoxImpostorDisplay(d)
117
+ };
118
+ }
119
+
120
+ // src/rendering/renderer-support.js
121
+ import * as TSL from "three/tsl";
122
+ function rendererSupportsImpostorNodeMaterials(renderer) {
123
+ if (typeof Reflect.get(TSL, "struct") !== "function") return false;
124
+ return renderer?.isWebGPURenderer === true || renderer?.capabilities?.supportsNodeMaterials === true;
125
+ }
126
+ var pending = /* @__PURE__ */ new WeakMap();
127
+ async function enableRendererNodeMaterials(renderer) {
128
+ if (rendererSupportsImpostorNodeMaterials(renderer) || !renderer?.isWebGLRenderer || !renderer.setNodesHandler || typeof Reflect.get(TSL, "struct") !== "function") return;
129
+ let setup = pending.get(renderer);
130
+ if (!setup) {
131
+ setup = import("three/addons/tsl/WebGLNodesHandler.js").then(({ WebGLNodesHandler }) => {
132
+ if (rendererSupportsImpostorNodeMaterials(renderer)) return;
133
+ renderer.setNodesHandler?.(new WebGLNodesHandler());
134
+ renderer.capabilities ??= {};
135
+ renderer.capabilities.supportsNodeMaterials = true;
136
+ }).catch((error) => {
137
+ pending.delete(renderer);
138
+ throw error;
139
+ });
140
+ pending.set(renderer, setup);
141
+ }
142
+ await setup;
143
+ }
144
+
145
+ // src/box-impostor/box-impostor-geometry.js
146
+ import {
147
+ BufferGeometry,
148
+ Float32BufferAttribute,
149
+ InterleavedBuffer,
150
+ InterleavedBufferAttribute
151
+ } from "three";
152
+ function createBoxImpostorGeometry(input) {
153
+ const d = parseBoxImpostorDescriptor(input);
154
+ const depths = (
155
+ /** @type {number[][]} */
156
+ [[], [], []]
157
+ );
158
+ const positions = [], normals = [], uvs = [], indices = [], centers = [], halves = [], axisX = [], axisY = [], axisZ = [], boxIds = [], faces = [], corners = [];
159
+ for (const [id, b] of d.boxes.entries())
160
+ for (const f of d.mode !== "fitted" ? [4] : [0, 1, 2, 3, 4, 5]) {
161
+ const face = BOX_FACE_AXES[f], base = positions.length / 3, r = b.views[f], p = d.padding;
162
+ for (const [x, y] of [
163
+ [-1, -1],
164
+ [1, -1],
165
+ [1, 1],
166
+ [-1, 1]
167
+ ]) {
168
+ const local = face.normal.map(
169
+ (n, a) => (n + face.right[a] * x + face.up[a] * y) * b.halfSize[a]
170
+ );
171
+ positions.push(
172
+ ...b.center.map(
173
+ (c, a) => c + local.reduce((s, v, i) => s + v * b.axes[i][a], 0)
174
+ )
175
+ );
176
+ normals.push(
177
+ ...[0, 1, 2].map(
178
+ (a) => face.normal.reduce((s, v, i) => s + v * b.axes[i][a], 0)
179
+ )
180
+ );
181
+ uvs.push(
182
+ (r[0] + p + (x + 1) * 0.5 * (r[2] - 2 * p)) / d.atlasResolution,
183
+ (r[1] + p + (y + 1) * 0.5 * (r[3] - 2 * p)) / d.atlasResolution
184
+ );
185
+ centers.push(...b.center);
186
+ halves.push(...b.halfSize);
187
+ axisX.push(...b.axes[0]);
188
+ axisY.push(...b.axes[1]);
189
+ axisZ.push(...b.axes[2]);
190
+ for (let axis = 0; axis < 3; axis++)
191
+ depths[axis].push(
192
+ ...(b.depthBounds?.slice(axis * 4, axis * 4 + 4) ?? [
193
+ 0,
194
+ 65535,
195
+ 0,
196
+ 65535
197
+ ]).map((v) => v / 65535)
198
+ );
199
+ boxIds.push(id);
200
+ faces.push(f);
201
+ corners.push(x, y);
202
+ }
203
+ indices.push(base, base + 1, base + 2, base, base + 2, base + 3);
204
+ }
205
+ const geometry = new BufferGeometry();
206
+ for (
207
+ const [name, data2, size] of
208
+ /** @type {[string,number[],number][]} */
209
+ [
210
+ ["position", positions, 3],
211
+ ["normal", normals, 3],
212
+ ["uv", uvs, 2],
213
+ ["boxCenter", centers, 3],
214
+ ["boxHalfSize", halves, 3],
215
+ ["boxAxisX", axisX, 3],
216
+ ["boxAxisY", axisY, 3],
217
+ ["boxAxisZ", axisZ, 3],
218
+ ["boxDepthX", depths[0], 4],
219
+ ["boxDepthY", depths[1], 4],
220
+ ["boxDepthZ", depths[2], 4],
221
+ ["boxId", boxIds, 1],
222
+ ["boxFace", faces, 1],
223
+ ["cardCorner", corners, 2]
224
+ ]
225
+ )
226
+ geometry.setAttribute(name, new Float32BufferAttribute(data2, size));
227
+ const names = [
228
+ "boxCenter",
229
+ "boxHalfSize",
230
+ "boxAxisX",
231
+ "boxAxisY",
232
+ "boxAxisZ",
233
+ "boxDepthX",
234
+ "boxDepthY",
235
+ "boxDepthZ",
236
+ "boxId",
237
+ "boxFace",
238
+ "cardCorner"
239
+ ];
240
+ const stride = names.reduce(
241
+ (sum, name) => sum + geometry.getAttribute(name).itemSize,
242
+ 0
243
+ );
244
+ const data = new Float32Array(centers.length / 3 * stride), buffer = new InterleavedBuffer(data, stride);
245
+ let offset = 0;
246
+ for (const name of names) {
247
+ const attribute4 = geometry.getAttribute(name);
248
+ for (let vertex = 0; vertex < attribute4.count; vertex++)
249
+ for (let component = 0; component < attribute4.itemSize; component++)
250
+ data[vertex * stride + offset + component] = attribute4.getComponent(
251
+ vertex,
252
+ component
253
+ );
254
+ geometry.setAttribute(
255
+ name,
256
+ new InterleavedBufferAttribute(buffer, attribute4.itemSize, offset)
257
+ );
258
+ offset += attribute4.itemSize;
259
+ }
260
+ geometry.userData.previewWireframeEdgeMasks = Float32Array.from(
261
+ { length: indices.length },
262
+ (_, i) => [1, 0, 1, 1, 1, 0][i % 6]
263
+ );
264
+ geometry.setIndex(indices);
265
+ geometry.computeBoundingBox();
266
+ geometry.computeBoundingSphere();
267
+ return geometry;
268
+ }
269
+
270
+ // src/rendering/captured-surface-depth.js
271
+ import {
272
+ Fn,
273
+ cameraFar,
274
+ cameraNear,
275
+ cameraProjectionMatrix,
276
+ modelViewMatrix,
277
+ vec4,
278
+ viewZToLogarithmicDepth,
279
+ viewZToOrthographicDepth,
280
+ viewZToPerspectiveDepth,
281
+ viewZToReversedOrthographicDepth,
282
+ viewZToReversedPerspectiveDepth
283
+ } from "three/tsl";
284
+ function capturedSurfaceDepth(position, shadowBias = 0) {
285
+ return Fn(
286
+ (_, builder) => {
287
+ const z = modelViewMatrix.mul(vec4(position, 1)).z.toVar("capturedSurfaceViewZ");
288
+ const reversed = builder.renderer.reversedDepthBuffer === true;
289
+ const perspective = cameraProjectionMatrix.mul(vec4(0, 0, 0, 1)).w.equal(0);
290
+ const perspectiveDepth = builder.renderer.logarithmicDepthBuffer === true ? viewZToLogarithmicDepth(z, cameraNear, cameraFar) : (reversed ? viewZToReversedPerspectiveDepth : viewZToPerspectiveDepth)(z, cameraNear, cameraFar);
291
+ const result = perspective.select(
292
+ perspectiveDepth,
293
+ (reversed ? viewZToReversedOrthographicDepth : viewZToOrthographicDepth)(z, cameraNear, cameraFar)
294
+ );
295
+ return shadowBias && "isShadowPassMaterial" in builder.material && builder.material.isShadowPassMaterial ? result.add(reversed ? -shadowBias : shadowBias).clamp(0, 1) : result;
296
+ }
297
+ )();
298
+ }
299
+
300
+ // src/box-impostor/box-impostor-material.js
301
+ import {
302
+ DataTexture as DataTexture3,
303
+ FloatType as FloatType3,
304
+ RGBAFormat as RGBAFormat3,
305
+ RedIntegerFormat,
306
+ UnsignedIntType,
307
+ NearestFilter as NearestFilter3,
308
+ LinearFilter,
309
+ DoubleSide,
310
+ BackSide,
311
+ FrontSide
312
+ } from "three/webgpu";
313
+ import {
314
+ Fn as Fn4,
315
+ If as If3,
316
+ Loop,
317
+ Break,
318
+ attribute as attribute3,
319
+ varying,
320
+ positionLocal as positionLocal2,
321
+ modelWorldMatrixInverse,
322
+ cameraPosition,
323
+ cameraWorldMatrix,
324
+ cameraProjectionMatrix as cameraProjectionMatrix2,
325
+ vec2 as vec23,
326
+ vec3 as vec33,
327
+ vec4 as vec44,
328
+ float as float3,
329
+ int as int3,
330
+ uint,
331
+ dot as dot3,
332
+ abs as abs3,
333
+ max as max3,
334
+ min,
335
+ sign as sign3,
336
+ texture as texture3,
337
+ textureLoad as textureLoad3,
338
+ ivec2 as ivec23,
339
+ normalize as normalize2,
340
+ floor,
341
+ fract,
342
+ modelWorldMatrix as modelWorldMatrix3,
343
+ cameraNear as cameraNear2,
344
+ transformNormalToView as transformNormalToView3,
345
+ struct as struct2,
346
+ uniform
347
+ } from "three/tsl";
348
+
349
+ // src/rendering/captured-surface-material.js
350
+ import { MeshStandardNodeMaterial } from "three/webgpu";
351
+ import { context, modelViewMatrix as modelViewMatrix2, modelWorldMatrix, vec4 as vec42 } from "three/tsl";
352
+ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
353
+ /** @type {import('three/webgpu').Node<'vec3'> | null} */
354
+ capturedPositionNode = null;
355
+ /**
356
+ * @override
357
+ * @param {import('three/webgpu').NodeBuilder} builder
358
+ */
359
+ setupLighting(builder) {
360
+ const lighting = super.setupLighting(builder);
361
+ if (!this.capturedPositionNode) return lighting;
362
+ const world = modelWorldMatrix.mul(vec42(this.capturedPositionNode, 1)).xyz;
363
+ const view = modelViewMatrix2.mul(vec42(this.capturedPositionNode, 1)).xyz;
364
+ return context(lighting, {
365
+ positionView: view,
366
+ positionWorld: world,
367
+ shadowPositionWorld: world
368
+ });
369
+ }
370
+ };
371
+
372
+ // src/box-impostor/box-impostor-surface-search.js
373
+ function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
374
+ const a = lo.toVar(), b = hi.toVar(), fa = loValue.toVar(), fb = secant ? hiValue.toVar() : null;
375
+ Loop2(steps, () => {
376
+ const mid = a.add(b).mul(0.5).toVar(), d = height(mid).toVar();
377
+ If4(d.mul(fa).greaterThan(0), () => {
378
+ a.assign(mid);
379
+ if (secant) fa.assign(d);
380
+ }).Else(() => {
381
+ b.assign(mid);
382
+ if (secant) fb.assign(d);
383
+ });
384
+ });
385
+ return secant ? a.add(b.sub(a).mul(fa.abs().div(fa.abs().add(fb.abs()).max(1e-20)).clamp(0, 1))) : a.add(b).mul(0.5);
386
+ }
387
+
388
+ // src/box-impostor/box-impostor-faces.js
389
+ import { DataTexture, FloatType, RGBAFormat, NearestFilter } from "three";
390
+ import {
391
+ Fn as Fn2,
392
+ If,
393
+ attribute,
394
+ positionLocal,
395
+ uv,
396
+ texture,
397
+ textureLoad,
398
+ ivec2,
399
+ vec2,
400
+ vec3,
401
+ float,
402
+ int,
403
+ dot,
404
+ abs,
405
+ max,
406
+ sign,
407
+ transformNormalToView
408
+ } from "three/tsl";
409
+ function applyBoxFaces({
410
+ material,
411
+ descriptor,
412
+ maps,
413
+ alphaCutoff,
414
+ transparency,
415
+ half,
416
+ toBox,
417
+ fromBox
418
+ }) {
419
+ const values = new Float32Array(descriptor.boxes.length * 6 * 4);
420
+ descriptor.boxes.forEach((box, i) => {
421
+ for (let face2 = 0; face2 < 6; face2++)
422
+ values[(i * 6 + face2) * 4] = box.planes?.[face2] ?? 0.5;
423
+ });
424
+ const planes = new DataTexture(
425
+ values,
426
+ 6,
427
+ descriptor.boxes.length,
428
+ RGBAFormat,
429
+ FloatType
430
+ );
431
+ planes.minFilter = planes.magFilter = NearestFilter;
432
+ planes.needsUpdate = true;
433
+ material.addEventListener("dispose", () => planes.dispose());
434
+ const face = int(attribute("boxFace", "float"));
435
+ const n = attribute("normal", "vec3");
436
+ const depth = textureLoad(
437
+ planes,
438
+ ivec2(face, int(attribute("boxId", "float")))
439
+ ).r;
440
+ const proxy = positionLocal.sub(
441
+ n.mul(
442
+ dot(abs(toBox(n)), half).mul(depth).mul(2)
443
+ )
444
+ );
445
+ material.positionNode = proxy;
446
+ material.castShadowPositionNode = proxy;
447
+ const base = texture(maps.baseColor, uv()).level(0).toVar("boxFaceColor");
448
+ const orm = texture(maps.orm, uv()).level(0);
449
+ const coverage = max(orm.a, 1e-10);
450
+ const normal = Fn2(() => {
451
+ const packed = textureLoad(
452
+ maps.normalDepth,
453
+ ivec2(uv().mul(descriptor.atlasResolution))
454
+ ).rg.mul(2).sub(1);
455
+ const decoded = vec3(
456
+ packed,
457
+ float(1).sub(abs(packed.x)).sub(abs(packed.y))
458
+ ).toVar();
459
+ If(decoded.z.lessThan(0), () => {
460
+ decoded.xy.assign(
461
+ vec2(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
462
+ );
463
+ });
464
+ const result = vec3(0).toVar();
465
+ for (let f = 0; f < 6; f++) {
466
+ const a = BOX_FACE_AXES[f];
467
+ If(face.equal(f), () => {
468
+ result.assign(
469
+ fromBox(
470
+ vec3(...a.right).mul(decoded.x).add(vec3(...a.up).mul(decoded.y)).add(vec3(...a.normal).mul(decoded.z))
471
+ ).normalize()
472
+ );
473
+ });
474
+ }
475
+ return result;
476
+ })();
477
+ material.colorNode = base.rgb.div(coverage);
478
+ material.normalNode = transformNormalToView(normal);
479
+ material.roughnessNode = orm.g.div(coverage);
480
+ material.metalnessNode = orm.b.div(coverage);
481
+ material.aoNode = orm.r.div(coverage);
482
+ material.emissiveNode = texture(maps.emissive, uv()).level(0).rgb.div(coverage);
483
+ material.maskNode = base.a.greaterThanEqual(
484
+ transparency === "cutout" ? alphaCutoff : float(1 / 255)
485
+ );
486
+ material.maskShadowNode = material.maskNode;
487
+ if (transparency !== "cutout") material.opacityNode = base.a;
488
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
489
+ return material;
490
+ }
491
+
492
+ // src/box-impostor/box-impostor-projection.js
493
+ import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter as NearestFilter2 } from "three";
494
+ import {
495
+ Fn as Fn3,
496
+ If as If2,
497
+ vec2 as vec22,
498
+ vec3 as vec32,
499
+ vec4 as vec43,
500
+ float as float2,
501
+ int as int2,
502
+ ivec2 as ivec22,
503
+ dot as dot2,
504
+ abs as abs2,
505
+ max as max2,
506
+ sign as sign2,
507
+ normalize,
508
+ texture as texture2,
509
+ textureLoad as textureLoad2,
510
+ attribute as attribute2,
511
+ struct,
512
+ modelWorldMatrix as modelWorldMatrix2,
513
+ transformNormalToView as transformNormalToView2
514
+ } from "three/tsl";
515
+ function applyBoxProjection({
516
+ material,
517
+ descriptor,
518
+ maps,
519
+ settings,
520
+ transparency,
521
+ alphaCutoff,
522
+ rects,
523
+ center,
524
+ half,
525
+ toBox,
526
+ fromBox,
527
+ eye,
528
+ viewAxis,
529
+ perspective,
530
+ raster
531
+ }) {
532
+ const data = new Float32Array(descriptor.boxes.length * 24);
533
+ descriptor.boxes.forEach((box, i) => {
534
+ for (let face = 0; face < 6; face++)
535
+ data[(i * 6 + face) * 4] = box.planes?.[face] ?? 0.5;
536
+ });
537
+ const planes = new DataTexture2(
538
+ data,
539
+ 6,
540
+ descriptor.boxes.length,
541
+ RGBAFormat2,
542
+ FloatType2
543
+ );
544
+ planes.minFilter = planes.magFilter = NearestFilter2;
545
+ planes.needsUpdate = true;
546
+ material.addEventListener("dispose", () => planes.dispose());
547
+ const Surface = struct(
548
+ {
549
+ color: "vec3",
550
+ alpha: "float",
551
+ orm: "vec3",
552
+ emission: "vec3",
553
+ normal: "vec3",
554
+ position: "vec3"
555
+ },
556
+ "BoxProjectedSurface"
557
+ );
558
+ const readNormal = (uv2, right, up, n) => {
559
+ const packed = textureLoad2(
560
+ maps.normalDepth,
561
+ ivec22(uv2.mul(descriptor.atlasResolution))
562
+ ).rg.mul(2).sub(1);
563
+ const decoded = vec32(
564
+ packed,
565
+ float2(1).sub(abs2(packed.x)).sub(abs2(packed.y))
566
+ ).toVar();
567
+ If2(decoded.z.lessThan(0), () => {
568
+ decoded.xy.assign(
569
+ vec22(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
570
+ );
571
+ });
572
+ return fromBox(
573
+ right.mul(decoded.x).add(up.mul(decoded.y)).add(n.mul(decoded.z))
574
+ ).normalize();
575
+ };
576
+ const surface = Fn3(() => {
577
+ const ray = perspective.select(
578
+ normalize(raster.sub(eye)),
579
+ viewAxis.negate()
580
+ );
581
+ const origin = perspective.select(
582
+ eye,
583
+ raster.sub(ray.mul(half.length().mul(4)))
584
+ );
585
+ const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
586
+ const look = normalize(toBox(ray).negate()), angles = abs2(look);
587
+ const positions = vec32(0).toVar();
588
+ const selectedUv = vec22(0).toVar(), selectedRight = vec32(1, 0, 0).toVar(), selectedUp = vec32(0, 1, 0).toVar(), selectedNormal = vec32(0, 0, 1).toVar();
589
+ const nearest = float2(1e20).toVar("boxPlaneDistance");
590
+ const opacity = float2(0).toVar();
591
+ const candidates = [];
592
+ for (let axis = 0; axis < 3; axis++) {
593
+ const angle = angles.element(axis);
594
+ const positive = look.element(axis).greaterThanEqual(0), a = BOX_FACE_AXES[axis * 2], b = BOX_FACE_AXES[axis * 2 + 1];
595
+ const n = positive.select(vec32(...a.normal), vec32(...b.normal)), right = positive.select(vec32(...a.right), vec32(...b.right)), up = positive.select(vec32(...a.up), vec32(...b.up));
596
+ const weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
597
+ const candidate = settings.interpolation === "none" ? null : {
598
+ uv: vec22(0).toVar(),
599
+ base: vec43(0).toVar(),
600
+ orm: vec43(0).toVar(),
601
+ t: float2(1e20).toVar(),
602
+ tolerance: float2(0).toVar(),
603
+ right,
604
+ up,
605
+ n,
606
+ weight
607
+ };
608
+ if (candidate) candidates.push(candidate);
609
+ If2(angle.greaterThan(1e-4), () => {
610
+ const face = positive.select(int2(axis * 2), int2(axis * 2 + 1)), id = int2(attribute2("boxId", "float"));
611
+ const plane = float2(1).sub(
612
+ textureLoad2(planes, ivec22(face, id)).r.mul(2)
613
+ );
614
+ const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max2(abs2(divisor2), 1e-10));
615
+ const t = plane.sub(dot2(o, n)).div(safe), point = o.add(r.mul(t));
616
+ const xy = vec22(dot2(point, right), dot2(point, up)).mul(0.5).add(0.5);
617
+ let supported = t.greaterThanEqual(0).and(xy.x.greaterThanEqual(0)).and(xy.y.greaterThanEqual(0)).and(xy.x.lessThanEqual(1)).and(xy.y.lessThanEqual(1));
618
+ if (!candidate) supported = supported.and(t.lessThan(nearest));
619
+ If2(supported, () => {
620
+ const rect = textureLoad2(rects, ivec22(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
621
+ const base = texture2(maps.baseColor, uv2).level(0), orm = texture2(maps.orm, uv2).level(0);
622
+ const alpha2 = base.a.clamp(0, 1);
623
+ If2(
624
+ alpha2.greaterThanEqual(
625
+ transparency === "cutout" ? alphaCutoff : float2(1 / 255)
626
+ ).and(orm.a.greaterThan(0)),
627
+ () => {
628
+ If2(t.lessThan(nearest), () => {
629
+ nearest.assign(t);
630
+ selectedUv.assign(uv2);
631
+ opacity.assign(alpha2);
632
+ selectedRight.assign(right);
633
+ selectedUp.assign(up);
634
+ selectedNormal.assign(n);
635
+ positions.assign(center.add(fromBox(point.mul(half))));
636
+ });
637
+ if (candidate) {
638
+ candidate.uv.assign(uv2);
639
+ candidate.base.assign(base);
640
+ candidate.orm.assign(orm);
641
+ candidate.t.assign(t);
642
+ candidate.tolerance.assign(
643
+ max2(
644
+ dot2(abs2(right), half).div(
645
+ rect.z.mul(descriptor.atlasResolution)
646
+ ),
647
+ dot2(abs2(up), half).div(
648
+ rect.w.mul(descriptor.atlasResolution)
649
+ )
650
+ ).mul(4).div(max2(angle, 0.1))
651
+ );
652
+ }
653
+ }
654
+ );
655
+ });
656
+ });
657
+ }
658
+ if (settings.interpolation === "none") {
659
+ const base = texture2(maps.baseColor, selectedUv).level(0), orm = texture2(maps.orm, selectedUv).level(0);
660
+ const coverage = max2(orm.a, 1e-10);
661
+ return Surface(
662
+ base.rgb.div(coverage),
663
+ opacity,
664
+ orm.rgb.div(coverage),
665
+ texture2(maps.emissive, selectedUv).level(0).rgb.div(coverage),
666
+ readNormal(selectedUv, selectedRight, selectedUp, selectedNormal),
667
+ positions
668
+ );
669
+ }
670
+ const colors = vec32(0).toVar(), orms = vec32(0).toVar(), emissions = vec32(0).toVar(), normals = vec32(0).toVar();
671
+ const weights = float2(0).toVar(), support = float2(0).toVar(), alpha = float2(0).toVar();
672
+ for (const c of candidates) {
673
+ If2(
674
+ c.base.a.greaterThan(0).and(c.t.lessThanEqual(nearest.add(c.tolerance))),
675
+ () => {
676
+ const coverage = max2(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
677
+ weights.addAssign(c.weight.mul(coverage));
678
+ support.assign(max2(support, coverage));
679
+ colors.addAssign(c.base.rgb.div(coverage).mul(w));
680
+ orms.addAssign(c.orm.rgb.div(coverage).mul(w));
681
+ emissions.addAssign(
682
+ texture2(maps.emissive, c.uv).level(0).rgb.div(coverage).mul(w)
683
+ );
684
+ normals.addAssign(readNormal(c.uv, c.right, c.up, c.n).mul(w));
685
+ alpha.addAssign(w);
686
+ }
687
+ );
688
+ }
689
+ const divisor = max2(alpha, 1e-10);
690
+ return Surface(
691
+ colors.div(divisor),
692
+ alpha.div(max2(weights, 1e-10)).mul(support),
693
+ orms.div(divisor),
694
+ emissions.div(divisor),
695
+ normals.div(max2(normals.length(), 1e-10)),
696
+ positions
697
+ );
698
+ })().toVar("boxProjectedSurface");
699
+ material.capturedPositionNode = surface.get("position");
700
+ material.colorNode = surface.get("color");
701
+ material.normalNode = transformNormalToView2(surface.get("normal"));
702
+ material.roughnessNode = surface.get("orm").g;
703
+ material.metalnessNode = surface.get("orm").b;
704
+ material.aoNode = surface.get("orm").r;
705
+ material.emissiveNode = surface.get("emission");
706
+ material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float2(1 / 255));
707
+ material.maskShadowNode = material.maskNode;
708
+ if (transparency !== "cutout") material.opacityNode = surface.get("alpha");
709
+ material.depthNode = capturedSurfaceDepth(surface.get("position"));
710
+ material.receivedShadowPositionNode = modelWorldMatrix2.mul(
711
+ vec43(surface.get("position"), 1)
712
+ ).xyz;
713
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
714
+ return material;
715
+ }
716
+
717
+ // src/box-impostor/box-impostor-material.js
718
+ function createBoxImpostorMaterial(descriptor, maps) {
719
+ return createBoxImpostorMaterialVariant(descriptor, maps, { filtering: true });
720
+ }
721
+ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false } = {}) {
722
+ const settings = normalizeBoxImpostorDisplay(descriptor);
723
+ const alphaCutoff = uniform(settings.alphaCutoff);
724
+ const transparency = boxTransparency(descriptor, settings);
725
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float3(1 / 255);
726
+ const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min(ormAlpha, baseAlpha) : ormAlpha;
727
+ const decodeNormal = (encoded) => {
728
+ const packed = encoded.mul(2).sub(1);
729
+ const normal2 = vec33(packed, float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
730
+ If3(normal2.z.lessThan(0), () => {
731
+ normal2.xy.assign(vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
732
+ });
733
+ return normal2.normalize();
734
+ };
735
+ const filteredNormal = (uv2, depth, tolerance, nearest, alpha, sampled = texture3(maps.normalDepth, uv2).level(0), ormAlpha = texture3(maps.orm, uv2).level(0).a) => {
736
+ sampled = sampled.toVar();
737
+ const coverage2 = max3(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
738
+ const nearestNormal = decodeNormal(nearest.rg), result = decodeNormal(sampled.rg.div(coverage2)).toVar();
739
+ const sampledDepth = sampled.b.mul(65280).add(sampled.a.mul(255)).div(65535);
740
+ const nearestDepth = nearest.b.mul(65280).add(nearest.a.mul(255)).div(65535);
741
+ If3(nearestNormal.z.lessThan(0).or(dot3(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
742
+ const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor(p), f = fract(p);
743
+ const normal2 = vec33(0).toVar(), weights = float3(0).toVar();
744
+ for (const [x, y] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
745
+ const texel = ivec23(lo.add(vec23(x, y)).clamp(0, descriptor.atlasResolution - 1));
746
+ const packed = textureLoad3(maps.normalDepth, texel).toVar();
747
+ const alpha2 = textureLoad3(maps.baseColor, texel).a;
748
+ const coverage3 = descriptor.alphaMode === "blend" ? textureLoad3(maps.orm, texel).a : alpha2;
749
+ const capturedDepth = packed.b.mul(65280).add(packed.a.mul(255)).div(65535);
750
+ const supported = coverage3.greaterThan(1e-4).and(alpha2.greaterThanEqual(minimumAlpha.mul(coverage3))).and(abs3(capturedDepth.sub(depth)).lessThanEqual(tolerance));
751
+ If3(supported, () => {
752
+ const weight = (x ? f.x : float3(1).sub(f.x)).mul(y ? f.y : float3(1).sub(f.y)).mul(coverage3);
753
+ normal2.addAssign(decodeNormal(packed.rg.div(max3(coverage3, 1e-10))).mul(weight));
754
+ weights.addAssign(weight);
755
+ });
756
+ }
757
+ result.assign(weights.greaterThan(1e-10).select(normal2.normalize(), nearestNormal));
758
+ });
759
+ return result;
760
+ };
761
+ for (const map of Object.values(maps)) {
762
+ if (map.minFilter !== LinearFilter || map.magFilter !== LinearFilter) {
763
+ map.minFilter = map.magFilter = LinearFilter;
764
+ map.generateMipmaps = false;
765
+ map.needsUpdate = true;
766
+ }
767
+ }
768
+ const material = new CapturedSurfaceMaterial({
769
+ name: "Box impostor",
770
+ side: descriptor.mode !== "fitted" ? DoubleSide : BackSide,
771
+ alphaHash: transparency === "dithered",
772
+ transparent: transparency === "blended",
773
+ depthWrite: transparency !== "blended",
774
+ forceSinglePass: true
775
+ });
776
+ const rectData = new Float32Array(descriptor.boxes.length * 6 * 4);
777
+ descriptor.boxes.forEach(
778
+ (b, i) => b.views.forEach(
779
+ (r, j) => rectData.set(
780
+ [
781
+ (r[0] + descriptor.padding) / descriptor.atlasResolution,
782
+ (r[1] + descriptor.padding) / descriptor.atlasResolution,
783
+ (r[2] - 2 * descriptor.padding) / descriptor.atlasResolution,
784
+ (r[3] - 2 * descriptor.padding) / descriptor.atlasResolution
785
+ ],
786
+ (i * 6 + j) * 4
787
+ )
788
+ )
789
+ );
790
+ const rects = new DataTexture3(
791
+ rectData,
792
+ 6,
793
+ descriptor.boxes.length,
794
+ RGBAFormat3,
795
+ FloatType3
796
+ );
797
+ rects.needsUpdate = true;
798
+ rects.magFilter = rects.minFilter = NearestFilter3;
799
+ material.addEventListener("dispose", () => rects.dispose());
800
+ const center = attribute3("boxCenter", "vec3"), half = attribute3("boxHalfSize", "vec3");
801
+ const ax = attribute3("boxAxisX", "vec3"), ay = attribute3("boxAxisY", "vec3"), az = attribute3("boxAxisZ", "vec3");
802
+ const toBox = (p) => vec33(dot3(p, ax), dot3(p, ay), dot3(p, az));
803
+ const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
804
+ const eye = modelWorldMatrixInverse.mul(vec44(cameraPosition, 1)).xyz;
805
+ const viewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 0, 1, 0))).xyz.normalize();
806
+ const perspective = cameraProjectionMatrix2.element(3).w.equal(0);
807
+ let proxy = positionLocal2;
808
+ if (descriptor.mode !== "fitted") {
809
+ proxy = Fn4((_, builder) => {
810
+ const delta = eye.sub(center);
811
+ const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize2(delta), viewAxis);
812
+ const right = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 1, 0, 0))).xyz.cross(forward).normalize();
813
+ const up = forward.cross(right).normalize();
814
+ const radius = half.length();
815
+ const distance = dot3(eye.sub(center), forward);
816
+ const planeOffset = perspective.select(min(radius, distance.sub(cameraNear2.mul(2))), radius);
817
+ const plane = center.add(forward.mul(planeOffset));
818
+ const lo = vec23(1e20).toVar(), hi = vec23(-1e20).toVar();
819
+ for (const x of [-1, 1])
820
+ for (const y of [-1, 1])
821
+ for (const z of [-1, 1]) {
822
+ const corner2 = fromBox(half.mul(vec33(x, y, z)));
823
+ const scale = perspective.select(
824
+ max3(distance.sub(planeOffset), 1e-5).div(
825
+ max3(distance.sub(dot3(corner2, forward)), 1e-5)
826
+ ),
827
+ float3(1)
828
+ );
829
+ const p = vec23(dot3(corner2, right), dot3(corner2, up)).mul(scale);
830
+ lo.assign(min(lo, p));
831
+ hi.assign(max3(hi, p));
832
+ }
833
+ const corner = attribute3("cardCorner", "vec2").add(1).mul(0.5);
834
+ const xy = lo.add(hi.sub(lo).mul(corner));
835
+ return plane.add(right.mul(xy.x)).add(up.mul(xy.y));
836
+ })();
837
+ material.positionNode = proxy;
838
+ material.castShadowPositionNode = proxy;
839
+ }
840
+ const raster = varying(proxy, "boxRasterPosition");
841
+ if (boxDepthMode(descriptor, settings) === "projection" && descriptor.mode === "fitted" && settings.interpolation === "none") {
842
+ material.side = FrontSide;
843
+ return applyBoxFaces({
844
+ material,
845
+ descriptor,
846
+ maps,
847
+ alphaCutoff,
848
+ transparency,
849
+ half,
850
+ toBox,
851
+ fromBox
852
+ });
853
+ }
854
+ if (boxDepthMode(descriptor, settings) === "projection")
855
+ return applyBoxProjection({
856
+ material,
857
+ descriptor,
858
+ maps,
859
+ settings,
860
+ transparency,
861
+ alphaCutoff,
862
+ rects,
863
+ center,
864
+ half,
865
+ toBox,
866
+ fromBox,
867
+ eye,
868
+ viewAxis,
869
+ perspective,
870
+ raster
871
+ });
872
+ const accelerated = descriptor.boxes.every((b) => b.depthBounds);
873
+ const gridSize = BOX_OCCUPANCY_RESOLUTION;
874
+ let occupancy;
875
+ if (descriptor.boxes.every((b) => b.occupancy) && descriptor.boxes.some(
876
+ (b) => b.occupancy.some((word) => word !== 4294967295)
877
+ )) {
878
+ const wordsPerBox = gridSize ** 3 / 32;
879
+ const words = new Uint32Array(wordsPerBox * descriptor.boxes.length);
880
+ descriptor.boxes.forEach(
881
+ (box, index) => words.set(box.occupancy, index * wordsPerBox)
882
+ );
883
+ occupancy = new DataTexture3(
884
+ words,
885
+ wordsPerBox,
886
+ descriptor.boxes.length,
887
+ RedIntegerFormat,
888
+ UnsignedIntType
889
+ );
890
+ occupancy.needsUpdate = true;
891
+ material.addEventListener("dispose", () => occupancy.dispose());
892
+ }
893
+ const Result = struct2(
894
+ { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
895
+ "BoxImpostorHit"
896
+ );
897
+ const raycast = Fn4((_, builder) => {
898
+ const ray = perspective.select(
899
+ normalize2(raster.sub(eye)),
900
+ viewAxis.negate()
901
+ );
902
+ const origin = perspective.select(
903
+ eye,
904
+ raster.sub(ray.mul(half.length().mul(4)))
905
+ );
906
+ const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
907
+ const safe = sign3(r.add(1e-20)).mul(max3(abs3(r), 1e-10));
908
+ const a = vec33(-1).sub(o).div(safe), b = vec33(1).sub(o).div(safe);
909
+ const enter = max3(max3(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
910
+ const exit = min(min(max3(a, b).x, max3(a, b).y), max3(a, b).z);
911
+ const occupiedStart = enter.toVar();
912
+ if (occupancy) {
913
+ const gridOrigin = o.add(1).mul(gridSize / 2);
914
+ const gridRay = r.mul(gridSize / 2);
915
+ const step = sign3(gridRay.add(1e-20));
916
+ const cell = floor(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
917
+ const inverse = vec33(1).div(safe.mul(gridSize / 2));
918
+ const delta = abs3(inverse);
919
+ const next = cell.add(step.add(1).mul(0.5)).sub(gridOrigin).mul(inverse).toVar();
920
+ const t = enter.toVar();
921
+ occupiedStart.assign(exit.add(1));
922
+ Loop(gridSize * 3 + 1, () => {
923
+ If3(t.greaterThan(exit), () => {
924
+ Break();
925
+ });
926
+ const cellIndex = uint(
927
+ cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2))
928
+ ).toVar();
929
+ const word = textureLoad3(
930
+ occupancy,
931
+ ivec23(int3(cellIndex.shiftRight(5)), int3(attribute3("boxId", "float")))
932
+ ).r;
933
+ const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
934
+ If3(support.notEqual(uint(0)), () => {
935
+ occupiedStart.assign(t);
936
+ Break();
937
+ });
938
+ const edge = min(min(next.x, next.y), next.z).toVar();
939
+ const advance = vec33(
940
+ next.x.lessThanEqual(edge).select(1, 0),
941
+ next.y.lessThanEqual(edge).select(1, 0),
942
+ next.z.lessThanEqual(edge).select(1, 0)
943
+ );
944
+ cell.addAssign(advance.mul(step));
945
+ next.addAssign(advance.mul(delta));
946
+ t.assign(edge);
947
+ If3(
948
+ cell.x.lessThan(0).or(cell.x.greaterThan(gridSize - 1)).or(cell.y.lessThan(0)).or(cell.y.greaterThan(gridSize - 1)).or(cell.z.lessThan(0)).or(cell.z.greaterThan(gridSize - 1)),
949
+ () => {
950
+ Break();
951
+ }
952
+ );
953
+ });
954
+ }
955
+ const look = toBox(ray).negate();
956
+ const bestT = exit.add(1).toVar(), bestUv = vec23(0).toVar(), bestNormal = vec33(0, 0, 1).toVar(), valid = float3(0).toVar(), found = float3(0).toVar();
957
+ const angles = abs3(look).toVar();
958
+ const major = angles.x.greaterThanEqual(angles.y).and(angles.x.greaterThanEqual(angles.z)).select(
959
+ int3(0),
960
+ angles.y.greaterThanEqual(angles.z).select(int3(1), int3(2))
961
+ ).toVar();
962
+ const nextAxis = major.add(1).mod(3), lastAxis = major.add(2).mod(3);
963
+ const second = angles.element(nextAxis).greaterThanEqual(angles.element(lastAxis)).select(nextAxis, lastAxis).toVar();
964
+ const third = int3(3).sub(major).sub(second).toVar();
965
+ Loop(
966
+ { start: 0, end: 6, type: "int", name: "viewIndex" },
967
+ ({ viewIndex: i }) => {
968
+ If3(occupiedStart.greaterThan(exit), () => {
969
+ Break();
970
+ });
971
+ valid.assign(0);
972
+ const rank = i.mod(3);
973
+ const axis = rank.equal(0).select(major, rank.equal(1).select(second, third)).toVar();
974
+ const positive = i.lessThan(3).select(
975
+ look.element(axis).greaterThanEqual(0),
976
+ look.element(axis).lessThan(0)
977
+ );
978
+ const face = axis.mul(2).add(positive.select(int3(0), int3(1)));
979
+ const facing = positive.select(1, -1);
980
+ const n = vec33(
981
+ axis.equal(0).select(facing, 0),
982
+ axis.equal(1).select(facing, 0),
983
+ axis.equal(2).select(facing, 0)
984
+ ).toVar();
985
+ const right = axis.equal(0).select(
986
+ vec33(0, 0, facing.negate()),
987
+ axis.equal(1).select(vec33(1, 0, 0), vec33(facing, 0, 0))
988
+ ).toVar();
989
+ const up = axis.equal(1).select(vec33(0, 0, facing.negate()), vec33(0, 1, 0)).toVar();
990
+ const direction = i.lessThan(3).select(1, -1);
991
+ const rect = textureLoad3(
992
+ rects,
993
+ ivec23(face, int3(attribute3("boxId", "float")))
994
+ ).toVar();
995
+ const sampleUv = (p) => rect.xy.add(
996
+ vec23(dot3(p, right), dot3(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
997
+ );
998
+ const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
999
+ const depthAt = (uv2) => decode(texture3(maps.normalDepth, uv2).level(0));
1000
+ const distance = (t) => {
1001
+ const p = o.add(r.mul(t));
1002
+ return dot3(p, n).sub(float3(1).sub(depthAt(sampleUv(p)).mul(2))).mul(direction);
1003
+ };
1004
+ const acceptHit = (hitT) => {
1005
+ const point2 = o.add(r.mul(hitT)), uv2 = sampleUv(point2);
1006
+ const texel = ivec23(uv2.mul(descriptor.atlasResolution));
1007
+ const nearest = textureLoad3(maps.normalDepth, texel);
1008
+ const capturedBase = texture3(maps.baseColor, uv2).level(0);
1009
+ const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1010
+ const residual = abs3(
1011
+ dot3(point2, n).sub(float3(1).sub(decode(nearest).mul(2)))
1012
+ );
1013
+ const tolerance = max3(
1014
+ dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
1015
+ dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
1016
+ ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
1017
+ If3(
1018
+ residual.lessThanEqual(tolerance).and(occupied).and(
1019
+ capturedBase.a.greaterThanEqual(minimumAlpha)
1020
+ ),
1021
+ () => {
1022
+ valid.assign(1);
1023
+ If3(hitT.lessThan(bestT), () => {
1024
+ bestT.assign(hitT);
1025
+ bestUv.assign(uv2);
1026
+ found.assign(1);
1027
+ const packed = texture3(maps.normalDepth, uv2).level(0).rg.div(max3(surfaceCoverage(texture3(maps.orm, uv2).level(0).a, capturedBase.a), 1e-10)).mul(2).sub(1);
1028
+ const normal2 = vec33(
1029
+ packed.x,
1030
+ packed.y,
1031
+ float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1032
+ ).toVar();
1033
+ If3(normal2.z.lessThan(0), () => {
1034
+ normal2.xy.assign(
1035
+ vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20)))
1036
+ );
1037
+ });
1038
+ bestNormal.assign(
1039
+ fromBox(
1040
+ right.mul(normal2.x).add(up.mul(normal2.y)).add(n.mul(normal2.z))
1041
+ ).normalize()
1042
+ );
1043
+ bestNormal.mulAssign(
1044
+ dot3(bestNormal, ray).greaterThan(0).select(-1, 1)
1045
+ );
1046
+ });
1047
+ }
1048
+ );
1049
+ };
1050
+ const traceInterval = (start, end, steps) => {
1051
+ const footprint = vec23(dot3(r, right), dot3(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
1052
+ const samples = max3(float3(steps), max3(footprint.x, footprint.y).mul(steps / 8)).div(2).ceil().mul(2).toVar();
1053
+ const step = end.sub(start).div(samples);
1054
+ const previous = start.toVar(), previousD = distance(start).toVar();
1055
+ If3(previousD.lessThanEqual(0), () => {
1056
+ acceptHit(start);
1057
+ });
1058
+ Loop({ start: int3(0), end: int3(samples.div(2)), type: "int" }, ({ i: i2 }) => {
1059
+ If3(valid.greaterThan(0.5), () => {
1060
+ Break();
1061
+ });
1062
+ const samples2 = [1, 2].map((offset) => {
1063
+ const t = start.add(step.mul(float3(i2.mul(2).add(offset)))).toVar();
1064
+ return { t, d: distance(t).toVar() };
1065
+ });
1066
+ for (const { t, d } of samples2) {
1067
+ If3(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
1068
+ Break();
1069
+ });
1070
+ If3(valid.lessThan(0.5).and(d.mul(previousD).lessThanEqual(0)), () => {
1071
+ const crossing = refineSurfaceCrossing({ float: float3, If: If3, Loop }, { lo: previous, hi: t, loValue: previousD, hiValue: d, height: distance, steps: 3, secant: true });
1072
+ acceptHit(crossing);
1073
+ If3(bestT.lessThanEqual(t), () => {
1074
+ Break();
1075
+ });
1076
+ });
1077
+ previous.assign(t);
1078
+ previousD.assign(d);
1079
+ }
1080
+ });
1081
+ };
1082
+ If3(
1083
+ exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3)),
1084
+ () => {
1085
+ if (!accelerated) {
1086
+ traceInterval(enter, exit, descriptor.raySteps);
1087
+ } else {
1088
+ const depths = axis.equal(0).select(
1089
+ attribute3("boxDepthX", "vec4"),
1090
+ axis.equal(1).select(
1091
+ attribute3("boxDepthY", "vec4"),
1092
+ attribute3("boxDepthZ", "vec4")
1093
+ )
1094
+ );
1095
+ const interval = positive.select(depths.xy, depths.zw);
1096
+ const initialDepth = float3(1).sub(dot3(o, n)).mul(0.5);
1097
+ const depthSlope = dot3(r, n).negate().mul(0.5);
1098
+ const da = interval.x.sub(2 / 65535).sub(initialDepth).div(depthSlope);
1099
+ const db = interval.y.add(2 / 65535).sub(initialDepth).div(depthSlope);
1100
+ const start = max3(occupiedStart, min(da, db));
1101
+ const end = min(min(exit, bestT), max3(da, db));
1102
+ If3(
1103
+ interval.x.lessThanEqual(interval.y).and(end.greaterThanEqual(start)),
1104
+ () => {
1105
+ const search = () => traceInterval(start, end, descriptor.raySteps);
1106
+ const hasFlatView = descriptor.boxes.some(
1107
+ (box) => [0, 2, 4, 6, 8, 10].some(
1108
+ (i2) => box.depthBounds[i2 + 1] >= box.depthBounds[i2] && box.depthBounds[i2 + 1] - box.depthBounds[i2] <= 1
1109
+ )
1110
+ );
1111
+ if (hasFlatView) {
1112
+ If3(
1113
+ interval.y.sub(interval.x).lessThanEqual(1 / 65535),
1114
+ () => {
1115
+ const t = interval.x.add(interval.y).mul(0.5).sub(initialDepth).div(depthSlope);
1116
+ If3(
1117
+ t.greaterThanEqual(enter).and(t.lessThanEqual(min(exit, bestT))),
1118
+ () => {
1119
+ acceptHit(t);
1120
+ }
1121
+ );
1122
+ }
1123
+ ).Else(search);
1124
+ } else search();
1125
+ }
1126
+ );
1127
+ }
1128
+ }
1129
+ );
1130
+ }
1131
+ );
1132
+ valid.assign(found);
1133
+ const point = o.add(r.mul(bestT));
1134
+ return Result(
1135
+ bestUv,
1136
+ center.add(fromBox(point.mul(half))),
1137
+ bestNormal,
1138
+ valid
1139
+ );
1140
+ });
1141
+ const hit = raycast().toVar("boxHit");
1142
+ hit.toStack();
1143
+ const base = texture3(maps.baseColor, hit.get("uv")).level(0), orm = texture3(maps.orm, hit.get("uv")).level(0);
1144
+ const coverage = max3(surfaceCoverage(orm.a, base.a), 1e-10);
1145
+ let color = base.div(coverage), surfaceOrm = orm.rgb.div(coverage), emission = texture3(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage), normal = hit.get("normal");
1146
+ if (settings.interpolation !== "none") {
1147
+ const fallbackColor = color, fallbackOrm = surfaceOrm, fallbackEmission = emission, fallbackNormal = normal;
1148
+ const Surface = struct2(
1149
+ { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
1150
+ "BoxSurfaceBlend"
1151
+ );
1152
+ const blended = Fn4(() => {
1153
+ const point = toBox(hit.get("position").sub(center)).div(half);
1154
+ const look = toBox(
1155
+ perspective.select(normalize2(eye.sub(hit.get("position"))), viewAxis)
1156
+ );
1157
+ const colors = vec44(0).toVar(), materials = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar(), weights = float3(0).toVar();
1158
+ for (let axis = 0; axis < 3; axis++) {
1159
+ const positive = look.element(axis).greaterThanEqual(0);
1160
+ const front = BOX_FACE_AXES[axis * 2], back = BOX_FACE_AXES[axis * 2 + 1];
1161
+ const n = positive.select(vec33(...front.normal), vec33(...back.normal));
1162
+ const right = positive.select(
1163
+ vec33(...front.right),
1164
+ vec33(...back.right)
1165
+ );
1166
+ const up = positive.select(vec33(...front.up), vec33(...back.up));
1167
+ const face = positive.select(int3(axis * 2), int3(axis * 2 + 1));
1168
+ const rect = textureLoad3(
1169
+ rects,
1170
+ ivec23(face, int3(attribute3("boxId", "float")))
1171
+ );
1172
+ const uv2 = rect.xy.add(
1173
+ vec23(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1174
+ );
1175
+ const texel = ivec23(uv2.mul(descriptor.atlasResolution));
1176
+ const captured = textureLoad3(maps.normalDepth, texel);
1177
+ const sampled = texture3(maps.baseColor, uv2).level(0);
1178
+ const sampledOrm = texture3(maps.orm, uv2).level(0);
1179
+ const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1180
+ const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
1181
+ const tolerance = max3(
1182
+ dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
1183
+ dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
1184
+ ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
1185
+ If3(
1186
+ occupied.and(sampled.a.greaterThanEqual(minimumAlpha)).and(
1187
+ abs3(dot3(point, n).sub(float3(1).sub(depth.mul(2)))).lessThanEqual(
1188
+ tolerance
1189
+ )
1190
+ ),
1191
+ () => {
1192
+ const angle = abs3(look.element(axis));
1193
+ const filtered = filtering ? texture3(maps.normalDepth, uv2).level(0).toVar() : captured;
1194
+ let weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
1195
+ if (filtering) {
1196
+ const error = abs3(dot3(point, n).sub(float3(1).sub(
1197
+ filtered.b.mul(65280).add(filtered.a.mul(255)).div(65535).mul(2)
1198
+ )));
1199
+ weight = weight.mul(float3(1).sub(error.div(tolerance)).clamp(0, 1));
1200
+ }
1201
+ const coverage2 = max3(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
1202
+ colors.addAssign(sampled.div(coverage2).mul(weight));
1203
+ materials.addAssign(sampledOrm.rgb.div(coverage2).mul(weight));
1204
+ emissions.addAssign(
1205
+ texture3(maps.emissive, uv2).level(0).rgb.div(coverage2).mul(weight)
1206
+ );
1207
+ let shadingNormal;
1208
+ if (filtering) shadingNormal = filteredNormal(uv2, float3(1).sub(dot3(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1209
+ else {
1210
+ const packed = captured.rg.mul(2).sub(1);
1211
+ const decoded = vec33(
1212
+ packed,
1213
+ float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1214
+ ).toVar();
1215
+ If3(decoded.z.lessThan(0), () => {
1216
+ decoded.xy.assign(
1217
+ vec23(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1218
+ );
1219
+ });
1220
+ shadingNormal = decoded;
1221
+ }
1222
+ normals.addAssign(
1223
+ fromBox(
1224
+ right.mul(shadingNormal.x).add(up.mul(shadingNormal.y)).add(n.mul(shadingNormal.z))
1225
+ ).normalize().mul(weight)
1226
+ );
1227
+ weights.addAssign(weight);
1228
+ }
1229
+ );
1230
+ }
1231
+ const divisor = max3(weights, 1e-10), valid = weights.greaterThan(1e-10);
1232
+ return Surface(
1233
+ valid.select(colors.div(divisor), fallbackColor),
1234
+ valid.select(materials.div(divisor), fallbackOrm),
1235
+ valid.select(emissions.div(divisor), fallbackEmission),
1236
+ valid.select(normals.normalize(), fallbackNormal)
1237
+ );
1238
+ })().toVar("boxBlendedSurface");
1239
+ color = blended.get("color");
1240
+ surfaceOrm = blended.get("orm");
1241
+ emission = blended.get("emission");
1242
+ normal = blended.get("normal");
1243
+ }
1244
+ material.capturedPositionNode = hit.get("position");
1245
+ material.colorNode = color.rgb;
1246
+ material.normalNode = transformNormalToView3(normal);
1247
+ material.roughnessNode = surfaceOrm.g;
1248
+ material.metalnessNode = surfaceOrm.b;
1249
+ material.aoNode = surfaceOrm.r;
1250
+ material.emissiveNode = emission;
1251
+ if (transparency !== "cutout") material.opacityNode = color.a.clamp(0, 1);
1252
+ material.maskNode = hit.get("valid").greaterThan(0.5);
1253
+ material.maskShadowNode = material.maskNode;
1254
+ material.depthNode = capturedSurfaceDepth(hit.get("position"));
1255
+ material.receivedShadowPositionNode = modelWorldMatrix3.mul(
1256
+ vec44(hit.get("position"), 1)
1257
+ ).xyz;
1258
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
1259
+ return material;
1260
+ }
1261
+
1262
+ // src/box-impostor/box-impostor-runtime.js
1263
+ var NeedleBoxImpostorLoaderPlugin = class {
1264
+ /** @param {import('three/addons/loaders/GLTFLoader.js').GLTFParser} parser
1265
+ * @param {{renderer?:import('../rendering/renderer-support.js').ImpostorRenderer}} [options] */
1266
+ constructor(parser, options = {}) {
1267
+ this.name = NEEDLE_BOX_IMPOSTOR;
1268
+ this.parser = parser;
1269
+ this.options = options;
1270
+ }
1271
+ /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
1272
+ async afterRoot(result) {
1273
+ await enableRendererNodeMaterials(this.options.renderer);
1274
+ const seen = /* @__PURE__ */ new Set();
1275
+ const geometries = /* @__PURE__ */ new Set();
1276
+ const materials = /* @__PURE__ */ new Set();
1277
+ const scenes = result.scenes ?? [result.scene];
1278
+ const pending2 = (
1279
+ /** @type {Promise<void>[]} */
1280
+ []
1281
+ );
1282
+ for (const scene of scenes)
1283
+ scene?.traverse((object) => {
1284
+ const mesh = (
1285
+ /** @type {import('three').Mesh} */
1286
+ object
1287
+ );
1288
+ if (!mesh.isMesh || seen.has(mesh)) return;
1289
+ seen.add(mesh);
1290
+ const a = (
1291
+ /** @type {{meshes?:number,primitives?:number}|undefined} */
1292
+ this.parser.associations.get(mesh)
1293
+ );
1294
+ if (a?.meshes === void 0 || a.primitives === void 0) return;
1295
+ const raw = this.parser.json.meshes?.[a.meshes]?.primitives[a.primitives]?.extensions?.[NEEDLE_BOX_IMPOSTOR];
1296
+ if (raw === void 0) return;
1297
+ const descriptor = parseBoxImpostorDescriptor(raw);
1298
+ if (!rendererSupportsImpostorNodeMaterials(this.options.renderer)) {
1299
+ if (this.parser.json.extensionsRequired?.includes(NEEDLE_BOX_IMPOSTOR))
1300
+ throw new Error(
1301
+ "NEEDLE_box_impostor requires Three WebGPURenderer or a renderer with compatible node-material support."
1302
+ );
1303
+ mesh.userData.boxImpostorFallback = true;
1304
+ return;
1305
+ }
1306
+ pending2.push(
1307
+ (async () => {
1308
+ const entries = await Promise.all(
1309
+ ["baseColor", "normalDepth", "orm", "emissive"].map(
1310
+ async (role) => {
1311
+ const index = raw.textures?.[role]?.index;
1312
+ if (!Number.isInteger(index) || index < 0)
1313
+ throw new Error(
1314
+ `NEEDLE_box_impostor has no valid ${role} texture.`
1315
+ );
1316
+ const texture4 = await this.parser.getDependency(
1317
+ "texture",
1318
+ index
1319
+ );
1320
+ texture4.colorSpace = role === "baseColor" || role === "emissive" ? SRGBColorSpace : NoColorSpace;
1321
+ texture4.magFilter = texture4.minFilter = role === "normalDepth" ? NearestFilter4 : LinearFilter2;
1322
+ texture4.wrapS = texture4.wrapT = ClampToEdgeWrapping;
1323
+ texture4.generateMipmaps = false;
1324
+ texture4.needsUpdate = true;
1325
+ return [role, texture4];
1326
+ }
1327
+ )
1328
+ );
1329
+ const maps = (
1330
+ /** @type {Parameters<typeof createBoxImpostorMaterial>[1]} */
1331
+ Object.fromEntries(entries)
1332
+ );
1333
+ geometries.add(mesh.geometry);
1334
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material])
1335
+ materials.add(material);
1336
+ mesh.geometry = createBoxImpostorGeometry(descriptor);
1337
+ mesh.material = createBoxImpostorMaterial(descriptor, maps);
1338
+ mesh.userData.boxImpostor = { descriptor, maps };
1339
+ mesh.frustumCulled = descriptor.mode === "fitted";
1340
+ })()
1341
+ );
1342
+ });
1343
+ await Promise.all(pending2);
1344
+ for (const scene of scenes)
1345
+ scene?.traverse((object) => {
1346
+ const mesh = (
1347
+ /** @type {import('three').Mesh} */
1348
+ object
1349
+ );
1350
+ if (!mesh.isMesh) return;
1351
+ geometries.delete(mesh.geometry);
1352
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material])
1353
+ materials.delete(material);
1354
+ });
1355
+ for (const geometry of geometries) geometry.dispose();
1356
+ for (const material of materials) material.dispose();
1357
+ }
1358
+ };
1359
+ function registerNeedleBoxImpostorLoader(loader, options = {}) {
1360
+ loader.register(
1361
+ (parser) => new NeedleBoxImpostorLoaderPlugin(parser, options)
1362
+ );
1363
+ return loader;
1364
+ }
1365
+ export {
1366
+ NeedleBoxImpostorLoaderPlugin,
1367
+ registerNeedleBoxImpostorLoader
1368
+ };
1369
+ //# sourceMappingURL=box-impostor-runtime.js.map