@needle-tools/three-mesh-effects 0.2.2 → 0.3.1

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