@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,1056 @@
1
+ // @ts-nocheck
2
+
3
+ // src/rendering/captured-surface-depth.js
4
+ import {
5
+ Fn,
6
+ cameraFar,
7
+ cameraNear,
8
+ cameraProjectionMatrix,
9
+ modelViewMatrix,
10
+ vec4,
11
+ viewZToLogarithmicDepth,
12
+ viewZToOrthographicDepth,
13
+ viewZToPerspectiveDepth,
14
+ viewZToReversedOrthographicDepth,
15
+ viewZToReversedPerspectiveDepth
16
+ } from "three/tsl";
17
+ function capturedSurfaceDepth(position, shadowBias = 0) {
18
+ return Fn(
19
+ (_, builder) => {
20
+ const z = modelViewMatrix.mul(vec4(position, 1)).z.toVar("capturedSurfaceViewZ");
21
+ const reversed = builder.renderer.reversedDepthBuffer === true;
22
+ const perspective = cameraProjectionMatrix.mul(vec4(0, 0, 0, 1)).w.equal(0);
23
+ const perspectiveDepth = builder.renderer.logarithmicDepthBuffer === true ? viewZToLogarithmicDepth(z, cameraNear, cameraFar) : (reversed ? viewZToReversedPerspectiveDepth : viewZToPerspectiveDepth)(z, cameraNear, cameraFar);
24
+ const result = perspective.select(
25
+ perspectiveDepth,
26
+ (reversed ? viewZToReversedOrthographicDepth : viewZToOrthographicDepth)(z, cameraNear, cameraFar)
27
+ );
28
+ return shadowBias && "isShadowPassMaterial" in builder.material && builder.material.isShadowPassMaterial ? result.add(reversed ? -shadowBias : shadowBias).clamp(0, 1) : result;
29
+ }
30
+ )();
31
+ }
32
+
33
+ // src/box-impostor/box-impostor-material.js
34
+ import {
35
+ DataTexture as DataTexture3,
36
+ FloatType as FloatType3,
37
+ RGBAFormat as RGBAFormat3,
38
+ RedIntegerFormat,
39
+ UnsignedIntType,
40
+ NearestFilter as NearestFilter3,
41
+ LinearFilter,
42
+ DoubleSide,
43
+ BackSide,
44
+ FrontSide
45
+ } from "three/webgpu";
46
+ import {
47
+ Fn as Fn4,
48
+ If as If3,
49
+ Loop,
50
+ Break,
51
+ attribute as attribute3,
52
+ varying,
53
+ positionLocal as positionLocal2,
54
+ modelWorldMatrixInverse,
55
+ cameraPosition,
56
+ cameraWorldMatrix,
57
+ cameraProjectionMatrix as cameraProjectionMatrix2,
58
+ vec2 as vec23,
59
+ vec3 as vec33,
60
+ vec4 as vec44,
61
+ float as float3,
62
+ int as int3,
63
+ uint,
64
+ dot as dot3,
65
+ abs as abs3,
66
+ max as max3,
67
+ min,
68
+ sign as sign3,
69
+ texture as texture3,
70
+ textureLoad as textureLoad3,
71
+ ivec2 as ivec23,
72
+ normalize as normalize2,
73
+ floor,
74
+ fract,
75
+ modelWorldMatrix as modelWorldMatrix3,
76
+ cameraNear as cameraNear2,
77
+ transformNormalToView as transformNormalToView3,
78
+ struct as struct2,
79
+ uniform
80
+ } from "three/tsl";
81
+
82
+ // src/rendering/captured-surface-material.js
83
+ import { MeshStandardNodeMaterial } from "three/webgpu";
84
+ import { context, modelViewMatrix as modelViewMatrix2, modelWorldMatrix, vec4 as vec42 } from "three/tsl";
85
+ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
86
+ /** @type {import('three/webgpu').Node<'vec3'> | null} */
87
+ capturedPositionNode = null;
88
+ /**
89
+ * @override
90
+ * @param {import('three/webgpu').NodeBuilder} builder
91
+ */
92
+ setupLighting(builder) {
93
+ const lighting = super.setupLighting(builder);
94
+ if (!this.capturedPositionNode) return lighting;
95
+ const world = modelWorldMatrix.mul(vec42(this.capturedPositionNode, 1)).xyz;
96
+ const view = modelViewMatrix2.mul(vec42(this.capturedPositionNode, 1)).xyz;
97
+ return context(lighting, {
98
+ positionView: view,
99
+ positionWorld: world,
100
+ shadowPositionWorld: world
101
+ });
102
+ }
103
+ };
104
+
105
+ // src/box-impostor/box-impostor-surface-search.js
106
+ function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
107
+ const a = lo.toVar(), b = hi.toVar(), fa = loValue.toVar(), fb = secant ? hiValue.toVar() : null;
108
+ Loop2(steps, () => {
109
+ const mid = a.add(b).mul(0.5).toVar(), d = height(mid).toVar();
110
+ If4(d.mul(fa).greaterThan(0), () => {
111
+ a.assign(mid);
112
+ if (secant) fa.assign(d);
113
+ }).Else(() => {
114
+ b.assign(mid);
115
+ if (secant) fb.assign(d);
116
+ });
117
+ });
118
+ 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);
119
+ }
120
+
121
+ // src/box-impostor/box-impostor-faces.js
122
+ import { DataTexture, FloatType, RGBAFormat, NearestFilter } from "three";
123
+ import {
124
+ Fn as Fn2,
125
+ If,
126
+ attribute,
127
+ positionLocal,
128
+ uv,
129
+ texture,
130
+ textureLoad,
131
+ ivec2,
132
+ vec2,
133
+ vec3,
134
+ float,
135
+ int,
136
+ dot,
137
+ abs,
138
+ max,
139
+ sign,
140
+ transformNormalToView
141
+ } from "three/tsl";
142
+
143
+ // src/box-impostor/box-impostor-display-settings.js
144
+ var DEFAULT_BOX_IMPOSTOR_DISPLAY = Object.freeze({
145
+ depthMode: (
146
+ /** @type {'auto'|'projection'|'depth'} */
147
+ "auto"
148
+ ),
149
+ raySteps: (
150
+ /** @type {8|16|32} */
151
+ 16
152
+ ),
153
+ alphaCutoff: 0.5,
154
+ interpolation: (
155
+ /** @type {'none'|'linear'|'smooth'} */
156
+ "none"
157
+ ),
158
+ transparency: (
159
+ /** @type {'auto'|'cutout'|'dithered'|'blended'} */
160
+ "auto"
161
+ )
162
+ });
163
+ function normalizeBoxImpostorDisplay(input = {}) {
164
+ const value = { ...DEFAULT_BOX_IMPOSTOR_DISPLAY, ...input };
165
+ 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))
166
+ throw new Error("Invalid box impostor display settings.");
167
+ return {
168
+ depthMode: value.depthMode,
169
+ raySteps: value.raySteps,
170
+ alphaCutoff: value.alphaCutoff,
171
+ interpolation: value.interpolation,
172
+ transparency: value.transparency
173
+ };
174
+ }
175
+ function boxTransparency(descriptor, settings) {
176
+ return settings.transparency === "auto" ? descriptor.alphaMode === "blend" ? "blended" : "cutout" : settings.transparency;
177
+ }
178
+ function boxDepthMode(descriptor, settings) {
179
+ if (settings.depthMode !== "auto") return settings.depthMode;
180
+ return descriptor.boxes.every(
181
+ (box) => box.planes?.length === 6 && box.planeErrors?.length === 6 && box.planeErrors.every((error) => error <= 2 / 255)
182
+ ) ? "projection" : "depth";
183
+ }
184
+
185
+ // src/box-impostor/box-impostor-face-axes.js
186
+ var BOX_FACE_AXES = Object.freeze([
187
+ { normal: [1, 0, 0], right: [0, 0, -1], up: [0, 1, 0] },
188
+ { normal: [-1, 0, 0], right: [0, 0, 1], up: [0, 1, 0] },
189
+ { normal: [0, 1, 0], right: [1, 0, 0], up: [0, 0, -1] },
190
+ { normal: [0, -1, 0], right: [1, 0, 0], up: [0, 0, 1] },
191
+ { normal: [0, 0, 1], right: [1, 0, 0], up: [0, 1, 0] },
192
+ { normal: [0, 0, -1], right: [-1, 0, 0], up: [0, 1, 0] }
193
+ ]);
194
+
195
+ // src/box-impostor/box-impostor-metadata.js
196
+ var BOX_OCCUPANCY_RESOLUTION = 8;
197
+ var BOX_OCCUPANCY_WORDS = BOX_OCCUPANCY_RESOLUTION ** 3 / 32;
198
+
199
+ // src/box-impostor/box-impostor-faces.js
200
+ function applyBoxFaces({
201
+ material,
202
+ descriptor,
203
+ maps,
204
+ alphaCutoff,
205
+ transparency,
206
+ half,
207
+ toBox,
208
+ fromBox
209
+ }) {
210
+ const values = new Float32Array(descriptor.boxes.length * 6 * 4);
211
+ descriptor.boxes.forEach((box, i) => {
212
+ for (let face2 = 0; face2 < 6; face2++)
213
+ values[(i * 6 + face2) * 4] = box.planes?.[face2] ?? 0.5;
214
+ });
215
+ const planes = new DataTexture(
216
+ values,
217
+ 6,
218
+ descriptor.boxes.length,
219
+ RGBAFormat,
220
+ FloatType
221
+ );
222
+ planes.minFilter = planes.magFilter = NearestFilter;
223
+ planes.needsUpdate = true;
224
+ material.addEventListener("dispose", () => planes.dispose());
225
+ const face = int(attribute("boxFace", "float"));
226
+ const n = attribute("normal", "vec3");
227
+ const depth = textureLoad(
228
+ planes,
229
+ ivec2(face, int(attribute("boxId", "float")))
230
+ ).r;
231
+ const proxy = positionLocal.sub(
232
+ n.mul(
233
+ dot(abs(toBox(n)), half).mul(depth).mul(2)
234
+ )
235
+ );
236
+ material.positionNode = proxy;
237
+ material.castShadowPositionNode = proxy;
238
+ const base = texture(maps.baseColor, uv()).level(0).toVar("boxFaceColor");
239
+ const orm = texture(maps.orm, uv()).level(0);
240
+ const coverage = max(orm.a, 1e-10);
241
+ const normal = Fn2(() => {
242
+ const packed = textureLoad(
243
+ maps.normalDepth,
244
+ ivec2(uv().mul(descriptor.atlasResolution))
245
+ ).rg.mul(2).sub(1);
246
+ const decoded = vec3(
247
+ packed,
248
+ float(1).sub(abs(packed.x)).sub(abs(packed.y))
249
+ ).toVar();
250
+ If(decoded.z.lessThan(0), () => {
251
+ decoded.xy.assign(
252
+ vec2(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
253
+ );
254
+ });
255
+ const result = vec3(0).toVar();
256
+ for (let f = 0; f < 6; f++) {
257
+ const a = BOX_FACE_AXES[f];
258
+ If(face.equal(f), () => {
259
+ result.assign(
260
+ fromBox(
261
+ vec3(...a.right).mul(decoded.x).add(vec3(...a.up).mul(decoded.y)).add(vec3(...a.normal).mul(decoded.z))
262
+ ).normalize()
263
+ );
264
+ });
265
+ }
266
+ return result;
267
+ })();
268
+ material.colorNode = base.rgb.div(coverage);
269
+ material.normalNode = transformNormalToView(normal);
270
+ material.roughnessNode = orm.g.div(coverage);
271
+ material.metalnessNode = orm.b.div(coverage);
272
+ material.aoNode = orm.r.div(coverage);
273
+ material.emissiveNode = texture(maps.emissive, uv()).level(0).rgb.div(coverage);
274
+ material.maskNode = base.a.greaterThanEqual(
275
+ transparency === "cutout" ? alphaCutoff : float(1 / 255)
276
+ );
277
+ material.maskShadowNode = material.maskNode;
278
+ if (transparency !== "cutout") material.opacityNode = base.a;
279
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
280
+ return material;
281
+ }
282
+
283
+ // src/box-impostor/box-impostor-projection.js
284
+ import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter as NearestFilter2 } from "three";
285
+ import {
286
+ Fn as Fn3,
287
+ If as If2,
288
+ vec2 as vec22,
289
+ vec3 as vec32,
290
+ vec4 as vec43,
291
+ float as float2,
292
+ int as int2,
293
+ ivec2 as ivec22,
294
+ dot as dot2,
295
+ abs as abs2,
296
+ max as max2,
297
+ sign as sign2,
298
+ normalize,
299
+ texture as texture2,
300
+ textureLoad as textureLoad2,
301
+ attribute as attribute2,
302
+ struct,
303
+ modelWorldMatrix as modelWorldMatrix2,
304
+ transformNormalToView as transformNormalToView2
305
+ } from "three/tsl";
306
+ function applyBoxProjection({
307
+ material,
308
+ descriptor,
309
+ maps,
310
+ settings,
311
+ transparency,
312
+ alphaCutoff,
313
+ rects,
314
+ center,
315
+ half,
316
+ toBox,
317
+ fromBox,
318
+ eye,
319
+ viewAxis,
320
+ perspective,
321
+ raster
322
+ }) {
323
+ const data = new Float32Array(descriptor.boxes.length * 24);
324
+ descriptor.boxes.forEach((box, i) => {
325
+ for (let face = 0; face < 6; face++)
326
+ data[(i * 6 + face) * 4] = box.planes?.[face] ?? 0.5;
327
+ });
328
+ const planes = new DataTexture2(
329
+ data,
330
+ 6,
331
+ descriptor.boxes.length,
332
+ RGBAFormat2,
333
+ FloatType2
334
+ );
335
+ planes.minFilter = planes.magFilter = NearestFilter2;
336
+ planes.needsUpdate = true;
337
+ material.addEventListener("dispose", () => planes.dispose());
338
+ const Surface = struct(
339
+ {
340
+ color: "vec3",
341
+ alpha: "float",
342
+ orm: "vec3",
343
+ emission: "vec3",
344
+ normal: "vec3",
345
+ position: "vec3"
346
+ },
347
+ "BoxProjectedSurface"
348
+ );
349
+ const readNormal = (uv2, right, up, n) => {
350
+ const packed = textureLoad2(
351
+ maps.normalDepth,
352
+ ivec22(uv2.mul(descriptor.atlasResolution))
353
+ ).rg.mul(2).sub(1);
354
+ const decoded = vec32(
355
+ packed,
356
+ float2(1).sub(abs2(packed.x)).sub(abs2(packed.y))
357
+ ).toVar();
358
+ If2(decoded.z.lessThan(0), () => {
359
+ decoded.xy.assign(
360
+ vec22(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
361
+ );
362
+ });
363
+ return fromBox(
364
+ right.mul(decoded.x).add(up.mul(decoded.y)).add(n.mul(decoded.z))
365
+ ).normalize();
366
+ };
367
+ const surface = Fn3(() => {
368
+ const ray = perspective.select(
369
+ normalize(raster.sub(eye)),
370
+ viewAxis.negate()
371
+ );
372
+ const origin = perspective.select(
373
+ eye,
374
+ raster.sub(ray.mul(half.length().mul(4)))
375
+ );
376
+ const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
377
+ const look = normalize(toBox(ray).negate()), angles = abs2(look);
378
+ const positions = vec32(0).toVar();
379
+ const selectedUv = vec22(0).toVar(), selectedRight = vec32(1, 0, 0).toVar(), selectedUp = vec32(0, 1, 0).toVar(), selectedNormal = vec32(0, 0, 1).toVar();
380
+ const nearest = float2(1e20).toVar("boxPlaneDistance");
381
+ const opacity = float2(0).toVar();
382
+ const candidates = [];
383
+ for (let axis = 0; axis < 3; axis++) {
384
+ const angle = angles.element(axis);
385
+ const positive = look.element(axis).greaterThanEqual(0), a = BOX_FACE_AXES[axis * 2], b = BOX_FACE_AXES[axis * 2 + 1];
386
+ 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));
387
+ const weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
388
+ const candidate = settings.interpolation === "none" ? null : {
389
+ uv: vec22(0).toVar(),
390
+ base: vec43(0).toVar(),
391
+ orm: vec43(0).toVar(),
392
+ t: float2(1e20).toVar(),
393
+ tolerance: float2(0).toVar(),
394
+ right,
395
+ up,
396
+ n,
397
+ weight
398
+ };
399
+ if (candidate) candidates.push(candidate);
400
+ If2(angle.greaterThan(1e-4), () => {
401
+ const face = positive.select(int2(axis * 2), int2(axis * 2 + 1)), id = int2(attribute2("boxId", "float"));
402
+ const plane = float2(1).sub(
403
+ textureLoad2(planes, ivec22(face, id)).r.mul(2)
404
+ );
405
+ const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max2(abs2(divisor2), 1e-10));
406
+ const t = plane.sub(dot2(o, n)).div(safe), point = o.add(r.mul(t));
407
+ const xy = vec22(dot2(point, right), dot2(point, up)).mul(0.5).add(0.5);
408
+ 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));
409
+ if (!candidate) supported = supported.and(t.lessThan(nearest));
410
+ If2(supported, () => {
411
+ const rect = textureLoad2(rects, ivec22(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
412
+ const base = texture2(maps.baseColor, uv2).level(0), orm = texture2(maps.orm, uv2).level(0);
413
+ const alpha2 = base.a.clamp(0, 1);
414
+ If2(
415
+ alpha2.greaterThanEqual(
416
+ transparency === "cutout" ? alphaCutoff : float2(1 / 255)
417
+ ).and(orm.a.greaterThan(0)),
418
+ () => {
419
+ If2(t.lessThan(nearest), () => {
420
+ nearest.assign(t);
421
+ selectedUv.assign(uv2);
422
+ opacity.assign(alpha2);
423
+ selectedRight.assign(right);
424
+ selectedUp.assign(up);
425
+ selectedNormal.assign(n);
426
+ positions.assign(center.add(fromBox(point.mul(half))));
427
+ });
428
+ if (candidate) {
429
+ candidate.uv.assign(uv2);
430
+ candidate.base.assign(base);
431
+ candidate.orm.assign(orm);
432
+ candidate.t.assign(t);
433
+ candidate.tolerance.assign(
434
+ max2(
435
+ dot2(abs2(right), half).div(
436
+ rect.z.mul(descriptor.atlasResolution)
437
+ ),
438
+ dot2(abs2(up), half).div(
439
+ rect.w.mul(descriptor.atlasResolution)
440
+ )
441
+ ).mul(4).div(max2(angle, 0.1))
442
+ );
443
+ }
444
+ }
445
+ );
446
+ });
447
+ });
448
+ }
449
+ if (settings.interpolation === "none") {
450
+ const base = texture2(maps.baseColor, selectedUv).level(0), orm = texture2(maps.orm, selectedUv).level(0);
451
+ const coverage = max2(orm.a, 1e-10);
452
+ return Surface(
453
+ base.rgb.div(coverage),
454
+ opacity,
455
+ orm.rgb.div(coverage),
456
+ texture2(maps.emissive, selectedUv).level(0).rgb.div(coverage),
457
+ readNormal(selectedUv, selectedRight, selectedUp, selectedNormal),
458
+ positions
459
+ );
460
+ }
461
+ const colors = vec32(0).toVar(), orms = vec32(0).toVar(), emissions = vec32(0).toVar(), normals = vec32(0).toVar();
462
+ const weights = float2(0).toVar(), support = float2(0).toVar(), alpha = float2(0).toVar();
463
+ for (const c of candidates) {
464
+ If2(
465
+ c.base.a.greaterThan(0).and(c.t.lessThanEqual(nearest.add(c.tolerance))),
466
+ () => {
467
+ const coverage = max2(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
468
+ weights.addAssign(c.weight.mul(coverage));
469
+ support.assign(max2(support, coverage));
470
+ colors.addAssign(c.base.rgb.div(coverage).mul(w));
471
+ orms.addAssign(c.orm.rgb.div(coverage).mul(w));
472
+ emissions.addAssign(
473
+ texture2(maps.emissive, c.uv).level(0).rgb.div(coverage).mul(w)
474
+ );
475
+ normals.addAssign(readNormal(c.uv, c.right, c.up, c.n).mul(w));
476
+ alpha.addAssign(w);
477
+ }
478
+ );
479
+ }
480
+ const divisor = max2(alpha, 1e-10);
481
+ return Surface(
482
+ colors.div(divisor),
483
+ alpha.div(max2(weights, 1e-10)).mul(support),
484
+ orms.div(divisor),
485
+ emissions.div(divisor),
486
+ normals.div(max2(normals.length(), 1e-10)),
487
+ positions
488
+ );
489
+ })().toVar("boxProjectedSurface");
490
+ material.capturedPositionNode = surface.get("position");
491
+ material.colorNode = surface.get("color");
492
+ material.normalNode = transformNormalToView2(surface.get("normal"));
493
+ material.roughnessNode = surface.get("orm").g;
494
+ material.metalnessNode = surface.get("orm").b;
495
+ material.aoNode = surface.get("orm").r;
496
+ material.emissiveNode = surface.get("emission");
497
+ material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float2(1 / 255));
498
+ material.maskShadowNode = material.maskNode;
499
+ if (transparency !== "cutout") material.opacityNode = surface.get("alpha");
500
+ material.depthNode = capturedSurfaceDepth(surface.get("position"));
501
+ material.receivedShadowPositionNode = modelWorldMatrix2.mul(
502
+ vec43(surface.get("position"), 1)
503
+ ).xyz;
504
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
505
+ return material;
506
+ }
507
+
508
+ // src/box-impostor/box-impostor-material.js
509
+ function createBoxImpostorMaterial(descriptor, maps) {
510
+ return createBoxImpostorMaterialVariant(descriptor, maps, { filtering: true });
511
+ }
512
+ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false } = {}) {
513
+ const settings = normalizeBoxImpostorDisplay(descriptor);
514
+ const alphaCutoff = uniform(settings.alphaCutoff);
515
+ const transparency = boxTransparency(descriptor, settings);
516
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float3(1 / 255);
517
+ const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min(ormAlpha, baseAlpha) : ormAlpha;
518
+ const decodeNormal = (encoded) => {
519
+ const packed = encoded.mul(2).sub(1);
520
+ const normal2 = vec33(packed, float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
521
+ If3(normal2.z.lessThan(0), () => {
522
+ normal2.xy.assign(vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
523
+ });
524
+ return normal2.normalize();
525
+ };
526
+ const filteredNormal = (uv2, depth, tolerance, nearest, alpha, sampled = texture3(maps.normalDepth, uv2).level(0), ormAlpha = texture3(maps.orm, uv2).level(0).a) => {
527
+ sampled = sampled.toVar();
528
+ const coverage2 = max3(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
529
+ const nearestNormal = decodeNormal(nearest.rg), result = decodeNormal(sampled.rg.div(coverage2)).toVar();
530
+ const sampledDepth = sampled.b.mul(65280).add(sampled.a.mul(255)).div(65535);
531
+ const nearestDepth = nearest.b.mul(65280).add(nearest.a.mul(255)).div(65535);
532
+ If3(nearestNormal.z.lessThan(0).or(dot3(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
533
+ const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor(p), f = fract(p);
534
+ const normal2 = vec33(0).toVar(), weights = float3(0).toVar();
535
+ for (const [x, y] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
536
+ const texel = ivec23(lo.add(vec23(x, y)).clamp(0, descriptor.atlasResolution - 1));
537
+ const packed = textureLoad3(maps.normalDepth, texel).toVar();
538
+ const alpha2 = textureLoad3(maps.baseColor, texel).a;
539
+ const coverage3 = descriptor.alphaMode === "blend" ? textureLoad3(maps.orm, texel).a : alpha2;
540
+ const capturedDepth = packed.b.mul(65280).add(packed.a.mul(255)).div(65535);
541
+ const supported = coverage3.greaterThan(1e-4).and(alpha2.greaterThanEqual(minimumAlpha.mul(coverage3))).and(abs3(capturedDepth.sub(depth)).lessThanEqual(tolerance));
542
+ If3(supported, () => {
543
+ const weight = (x ? f.x : float3(1).sub(f.x)).mul(y ? f.y : float3(1).sub(f.y)).mul(coverage3);
544
+ normal2.addAssign(decodeNormal(packed.rg.div(max3(coverage3, 1e-10))).mul(weight));
545
+ weights.addAssign(weight);
546
+ });
547
+ }
548
+ result.assign(weights.greaterThan(1e-10).select(normal2.normalize(), nearestNormal));
549
+ });
550
+ return result;
551
+ };
552
+ for (const map of Object.values(maps)) {
553
+ if (map.minFilter !== LinearFilter || map.magFilter !== LinearFilter) {
554
+ map.minFilter = map.magFilter = LinearFilter;
555
+ map.generateMipmaps = false;
556
+ map.needsUpdate = true;
557
+ }
558
+ }
559
+ const material = new CapturedSurfaceMaterial({
560
+ name: "Box impostor",
561
+ side: descriptor.mode !== "fitted" ? DoubleSide : BackSide,
562
+ alphaHash: transparency === "dithered",
563
+ transparent: transparency === "blended",
564
+ depthWrite: transparency !== "blended",
565
+ forceSinglePass: true
566
+ });
567
+ const rectData = new Float32Array(descriptor.boxes.length * 6 * 4);
568
+ descriptor.boxes.forEach(
569
+ (b, i) => b.views.forEach(
570
+ (r, j) => rectData.set(
571
+ [
572
+ (r[0] + descriptor.padding) / descriptor.atlasResolution,
573
+ (r[1] + descriptor.padding) / descriptor.atlasResolution,
574
+ (r[2] - 2 * descriptor.padding) / descriptor.atlasResolution,
575
+ (r[3] - 2 * descriptor.padding) / descriptor.atlasResolution
576
+ ],
577
+ (i * 6 + j) * 4
578
+ )
579
+ )
580
+ );
581
+ const rects = new DataTexture3(
582
+ rectData,
583
+ 6,
584
+ descriptor.boxes.length,
585
+ RGBAFormat3,
586
+ FloatType3
587
+ );
588
+ rects.needsUpdate = true;
589
+ rects.magFilter = rects.minFilter = NearestFilter3;
590
+ material.addEventListener("dispose", () => rects.dispose());
591
+ const center = attribute3("boxCenter", "vec3"), half = attribute3("boxHalfSize", "vec3");
592
+ const ax = attribute3("boxAxisX", "vec3"), ay = attribute3("boxAxisY", "vec3"), az = attribute3("boxAxisZ", "vec3");
593
+ const toBox = (p) => vec33(dot3(p, ax), dot3(p, ay), dot3(p, az));
594
+ const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
595
+ const eye = modelWorldMatrixInverse.mul(vec44(cameraPosition, 1)).xyz;
596
+ const viewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 0, 1, 0))).xyz.normalize();
597
+ const perspective = cameraProjectionMatrix2.element(3).w.equal(0);
598
+ let proxy = positionLocal2;
599
+ if (descriptor.mode !== "fitted") {
600
+ proxy = Fn4((_, builder) => {
601
+ const delta = eye.sub(center);
602
+ const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize2(delta), viewAxis);
603
+ const right = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 1, 0, 0))).xyz.cross(forward).normalize();
604
+ const up = forward.cross(right).normalize();
605
+ const radius = half.length();
606
+ const distance = dot3(eye.sub(center), forward);
607
+ const planeOffset = perspective.select(min(radius, distance.sub(cameraNear2.mul(2))), radius);
608
+ const plane = center.add(forward.mul(planeOffset));
609
+ const lo = vec23(1e20).toVar(), hi = vec23(-1e20).toVar();
610
+ for (const x of [-1, 1])
611
+ for (const y of [-1, 1])
612
+ for (const z of [-1, 1]) {
613
+ const corner2 = fromBox(half.mul(vec33(x, y, z)));
614
+ const scale = perspective.select(
615
+ max3(distance.sub(planeOffset), 1e-5).div(
616
+ max3(distance.sub(dot3(corner2, forward)), 1e-5)
617
+ ),
618
+ float3(1)
619
+ );
620
+ const p = vec23(dot3(corner2, right), dot3(corner2, up)).mul(scale);
621
+ lo.assign(min(lo, p));
622
+ hi.assign(max3(hi, p));
623
+ }
624
+ const corner = attribute3("cardCorner", "vec2").add(1).mul(0.5);
625
+ const xy = lo.add(hi.sub(lo).mul(corner));
626
+ return plane.add(right.mul(xy.x)).add(up.mul(xy.y));
627
+ })();
628
+ material.positionNode = proxy;
629
+ material.castShadowPositionNode = proxy;
630
+ }
631
+ const raster = varying(proxy, "boxRasterPosition");
632
+ if (boxDepthMode(descriptor, settings) === "projection" && descriptor.mode === "fitted" && settings.interpolation === "none") {
633
+ material.side = FrontSide;
634
+ return applyBoxFaces({
635
+ material,
636
+ descriptor,
637
+ maps,
638
+ alphaCutoff,
639
+ transparency,
640
+ half,
641
+ toBox,
642
+ fromBox
643
+ });
644
+ }
645
+ if (boxDepthMode(descriptor, settings) === "projection")
646
+ return applyBoxProjection({
647
+ material,
648
+ descriptor,
649
+ maps,
650
+ settings,
651
+ transparency,
652
+ alphaCutoff,
653
+ rects,
654
+ center,
655
+ half,
656
+ toBox,
657
+ fromBox,
658
+ eye,
659
+ viewAxis,
660
+ perspective,
661
+ raster
662
+ });
663
+ const accelerated = descriptor.boxes.every((b) => b.depthBounds);
664
+ const gridSize = BOX_OCCUPANCY_RESOLUTION;
665
+ let occupancy;
666
+ if (descriptor.boxes.every((b) => b.occupancy) && descriptor.boxes.some(
667
+ (b) => b.occupancy.some((word) => word !== 4294967295)
668
+ )) {
669
+ const wordsPerBox = gridSize ** 3 / 32;
670
+ const words = new Uint32Array(wordsPerBox * descriptor.boxes.length);
671
+ descriptor.boxes.forEach(
672
+ (box, index) => words.set(box.occupancy, index * wordsPerBox)
673
+ );
674
+ occupancy = new DataTexture3(
675
+ words,
676
+ wordsPerBox,
677
+ descriptor.boxes.length,
678
+ RedIntegerFormat,
679
+ UnsignedIntType
680
+ );
681
+ occupancy.needsUpdate = true;
682
+ material.addEventListener("dispose", () => occupancy.dispose());
683
+ }
684
+ const Result = struct2(
685
+ { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
686
+ "BoxImpostorHit"
687
+ );
688
+ const raycast = Fn4((_, builder) => {
689
+ const ray = perspective.select(
690
+ normalize2(raster.sub(eye)),
691
+ viewAxis.negate()
692
+ );
693
+ const origin = perspective.select(
694
+ eye,
695
+ raster.sub(ray.mul(half.length().mul(4)))
696
+ );
697
+ const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
698
+ const safe = sign3(r.add(1e-20)).mul(max3(abs3(r), 1e-10));
699
+ const a = vec33(-1).sub(o).div(safe), b = vec33(1).sub(o).div(safe);
700
+ const enter = max3(max3(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
701
+ const exit = min(min(max3(a, b).x, max3(a, b).y), max3(a, b).z);
702
+ const occupiedStart = enter.toVar();
703
+ if (occupancy) {
704
+ const gridOrigin = o.add(1).mul(gridSize / 2);
705
+ const gridRay = r.mul(gridSize / 2);
706
+ const step = sign3(gridRay.add(1e-20));
707
+ const cell = floor(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
708
+ const inverse = vec33(1).div(safe.mul(gridSize / 2));
709
+ const delta = abs3(inverse);
710
+ const next = cell.add(step.add(1).mul(0.5)).sub(gridOrigin).mul(inverse).toVar();
711
+ const t = enter.toVar();
712
+ occupiedStart.assign(exit.add(1));
713
+ Loop(gridSize * 3 + 1, () => {
714
+ If3(t.greaterThan(exit), () => {
715
+ Break();
716
+ });
717
+ const cellIndex = uint(
718
+ cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2))
719
+ ).toVar();
720
+ const word = textureLoad3(
721
+ occupancy,
722
+ ivec23(int3(cellIndex.shiftRight(5)), int3(attribute3("boxId", "float")))
723
+ ).r;
724
+ const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
725
+ If3(support.notEqual(uint(0)), () => {
726
+ occupiedStart.assign(t);
727
+ Break();
728
+ });
729
+ const edge = min(min(next.x, next.y), next.z).toVar();
730
+ const advance = vec33(
731
+ next.x.lessThanEqual(edge).select(1, 0),
732
+ next.y.lessThanEqual(edge).select(1, 0),
733
+ next.z.lessThanEqual(edge).select(1, 0)
734
+ );
735
+ cell.addAssign(advance.mul(step));
736
+ next.addAssign(advance.mul(delta));
737
+ t.assign(edge);
738
+ If3(
739
+ 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)),
740
+ () => {
741
+ Break();
742
+ }
743
+ );
744
+ });
745
+ }
746
+ const look = toBox(ray).negate();
747
+ const bestT = exit.add(1).toVar(), bestUv = vec23(0).toVar(), bestNormal = vec33(0, 0, 1).toVar(), valid = float3(0).toVar(), found = float3(0).toVar();
748
+ const angles = abs3(look).toVar();
749
+ const major = angles.x.greaterThanEqual(angles.y).and(angles.x.greaterThanEqual(angles.z)).select(
750
+ int3(0),
751
+ angles.y.greaterThanEqual(angles.z).select(int3(1), int3(2))
752
+ ).toVar();
753
+ const nextAxis = major.add(1).mod(3), lastAxis = major.add(2).mod(3);
754
+ const second = angles.element(nextAxis).greaterThanEqual(angles.element(lastAxis)).select(nextAxis, lastAxis).toVar();
755
+ const third = int3(3).sub(major).sub(second).toVar();
756
+ Loop(
757
+ { start: 0, end: 6, type: "int", name: "viewIndex" },
758
+ ({ viewIndex: i }) => {
759
+ If3(occupiedStart.greaterThan(exit), () => {
760
+ Break();
761
+ });
762
+ valid.assign(0);
763
+ const rank = i.mod(3);
764
+ const axis = rank.equal(0).select(major, rank.equal(1).select(second, third)).toVar();
765
+ const positive = i.lessThan(3).select(
766
+ look.element(axis).greaterThanEqual(0),
767
+ look.element(axis).lessThan(0)
768
+ );
769
+ const face = axis.mul(2).add(positive.select(int3(0), int3(1)));
770
+ const facing = positive.select(1, -1);
771
+ const n = vec33(
772
+ axis.equal(0).select(facing, 0),
773
+ axis.equal(1).select(facing, 0),
774
+ axis.equal(2).select(facing, 0)
775
+ ).toVar();
776
+ const right = axis.equal(0).select(
777
+ vec33(0, 0, facing.negate()),
778
+ axis.equal(1).select(vec33(1, 0, 0), vec33(facing, 0, 0))
779
+ ).toVar();
780
+ const up = axis.equal(1).select(vec33(0, 0, facing.negate()), vec33(0, 1, 0)).toVar();
781
+ const direction = i.lessThan(3).select(1, -1);
782
+ const rect = textureLoad3(
783
+ rects,
784
+ ivec23(face, int3(attribute3("boxId", "float")))
785
+ ).toVar();
786
+ const sampleUv = (p) => rect.xy.add(
787
+ vec23(dot3(p, right), dot3(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
788
+ );
789
+ const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
790
+ const depthAt = (uv2) => decode(texture3(maps.normalDepth, uv2).level(0));
791
+ const distance = (t) => {
792
+ const p = o.add(r.mul(t));
793
+ return dot3(p, n).sub(float3(1).sub(depthAt(sampleUv(p)).mul(2))).mul(direction);
794
+ };
795
+ const acceptHit = (hitT) => {
796
+ const point2 = o.add(r.mul(hitT)), uv2 = sampleUv(point2);
797
+ const texel = ivec23(uv2.mul(descriptor.atlasResolution));
798
+ const nearest = textureLoad3(maps.normalDepth, texel);
799
+ const capturedBase = texture3(maps.baseColor, uv2).level(0);
800
+ const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
801
+ const residual = abs3(
802
+ dot3(point2, n).sub(float3(1).sub(decode(nearest).mul(2)))
803
+ );
804
+ const tolerance = max3(
805
+ dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
806
+ dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
807
+ ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
808
+ If3(
809
+ residual.lessThanEqual(tolerance).and(occupied).and(
810
+ capturedBase.a.greaterThanEqual(minimumAlpha)
811
+ ),
812
+ () => {
813
+ valid.assign(1);
814
+ If3(hitT.lessThan(bestT), () => {
815
+ bestT.assign(hitT);
816
+ bestUv.assign(uv2);
817
+ found.assign(1);
818
+ 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);
819
+ const normal2 = vec33(
820
+ packed.x,
821
+ packed.y,
822
+ float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
823
+ ).toVar();
824
+ If3(normal2.z.lessThan(0), () => {
825
+ normal2.xy.assign(
826
+ vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20)))
827
+ );
828
+ });
829
+ bestNormal.assign(
830
+ fromBox(
831
+ right.mul(normal2.x).add(up.mul(normal2.y)).add(n.mul(normal2.z))
832
+ ).normalize()
833
+ );
834
+ bestNormal.mulAssign(
835
+ dot3(bestNormal, ray).greaterThan(0).select(-1, 1)
836
+ );
837
+ });
838
+ }
839
+ );
840
+ };
841
+ const traceInterval = (start, end, steps) => {
842
+ const footprint = vec23(dot3(r, right), dot3(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
843
+ const samples = max3(float3(steps), max3(footprint.x, footprint.y).mul(steps / 8)).div(2).ceil().mul(2).toVar();
844
+ const step = end.sub(start).div(samples);
845
+ const previous = start.toVar(), previousD = distance(start).toVar();
846
+ If3(previousD.lessThanEqual(0), () => {
847
+ acceptHit(start);
848
+ });
849
+ Loop({ start: int3(0), end: int3(samples.div(2)), type: "int" }, ({ i: i2 }) => {
850
+ If3(valid.greaterThan(0.5), () => {
851
+ Break();
852
+ });
853
+ const samples2 = [1, 2].map((offset) => {
854
+ const t = start.add(step.mul(float3(i2.mul(2).add(offset)))).toVar();
855
+ return { t, d: distance(t).toVar() };
856
+ });
857
+ for (const { t, d } of samples2) {
858
+ If3(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
859
+ Break();
860
+ });
861
+ If3(valid.lessThan(0.5).and(d.mul(previousD).lessThanEqual(0)), () => {
862
+ const crossing = refineSurfaceCrossing({ float: float3, If: If3, Loop }, { lo: previous, hi: t, loValue: previousD, hiValue: d, height: distance, steps: 3, secant: true });
863
+ acceptHit(crossing);
864
+ If3(bestT.lessThanEqual(t), () => {
865
+ Break();
866
+ });
867
+ });
868
+ previous.assign(t);
869
+ previousD.assign(d);
870
+ }
871
+ });
872
+ };
873
+ If3(
874
+ exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3)),
875
+ () => {
876
+ if (!accelerated) {
877
+ traceInterval(enter, exit, descriptor.raySteps);
878
+ } else {
879
+ const depths = axis.equal(0).select(
880
+ attribute3("boxDepthX", "vec4"),
881
+ axis.equal(1).select(
882
+ attribute3("boxDepthY", "vec4"),
883
+ attribute3("boxDepthZ", "vec4")
884
+ )
885
+ );
886
+ const interval = positive.select(depths.xy, depths.zw);
887
+ const initialDepth = float3(1).sub(dot3(o, n)).mul(0.5);
888
+ const depthSlope = dot3(r, n).negate().mul(0.5);
889
+ const da = interval.x.sub(2 / 65535).sub(initialDepth).div(depthSlope);
890
+ const db = interval.y.add(2 / 65535).sub(initialDepth).div(depthSlope);
891
+ const start = max3(occupiedStart, min(da, db));
892
+ const end = min(min(exit, bestT), max3(da, db));
893
+ If3(
894
+ interval.x.lessThanEqual(interval.y).and(end.greaterThanEqual(start)),
895
+ () => {
896
+ const search = () => traceInterval(start, end, descriptor.raySteps);
897
+ const hasFlatView = descriptor.boxes.some(
898
+ (box) => [0, 2, 4, 6, 8, 10].some(
899
+ (i2) => box.depthBounds[i2 + 1] >= box.depthBounds[i2] && box.depthBounds[i2 + 1] - box.depthBounds[i2] <= 1
900
+ )
901
+ );
902
+ if (hasFlatView) {
903
+ If3(
904
+ interval.y.sub(interval.x).lessThanEqual(1 / 65535),
905
+ () => {
906
+ const t = interval.x.add(interval.y).mul(0.5).sub(initialDepth).div(depthSlope);
907
+ If3(
908
+ t.greaterThanEqual(enter).and(t.lessThanEqual(min(exit, bestT))),
909
+ () => {
910
+ acceptHit(t);
911
+ }
912
+ );
913
+ }
914
+ ).Else(search);
915
+ } else search();
916
+ }
917
+ );
918
+ }
919
+ }
920
+ );
921
+ }
922
+ );
923
+ valid.assign(found);
924
+ const point = o.add(r.mul(bestT));
925
+ return Result(
926
+ bestUv,
927
+ center.add(fromBox(point.mul(half))),
928
+ bestNormal,
929
+ valid
930
+ );
931
+ });
932
+ const hit = raycast().toVar("boxHit");
933
+ hit.toStack();
934
+ const base = texture3(maps.baseColor, hit.get("uv")).level(0), orm = texture3(maps.orm, hit.get("uv")).level(0);
935
+ const coverage = max3(surfaceCoverage(orm.a, base.a), 1e-10);
936
+ 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");
937
+ if (settings.interpolation !== "none") {
938
+ const fallbackColor = color, fallbackOrm = surfaceOrm, fallbackEmission = emission, fallbackNormal = normal;
939
+ const Surface = struct2(
940
+ { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
941
+ "BoxSurfaceBlend"
942
+ );
943
+ const blended = Fn4(() => {
944
+ const point = toBox(hit.get("position").sub(center)).div(half);
945
+ const look = toBox(
946
+ perspective.select(normalize2(eye.sub(hit.get("position"))), viewAxis)
947
+ );
948
+ const colors = vec44(0).toVar(), materials = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar(), weights = float3(0).toVar();
949
+ for (let axis = 0; axis < 3; axis++) {
950
+ const positive = look.element(axis).greaterThanEqual(0);
951
+ const front = BOX_FACE_AXES[axis * 2], back = BOX_FACE_AXES[axis * 2 + 1];
952
+ const n = positive.select(vec33(...front.normal), vec33(...back.normal));
953
+ const right = positive.select(
954
+ vec33(...front.right),
955
+ vec33(...back.right)
956
+ );
957
+ const up = positive.select(vec33(...front.up), vec33(...back.up));
958
+ const face = positive.select(int3(axis * 2), int3(axis * 2 + 1));
959
+ const rect = textureLoad3(
960
+ rects,
961
+ ivec23(face, int3(attribute3("boxId", "float")))
962
+ );
963
+ const uv2 = rect.xy.add(
964
+ vec23(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
965
+ );
966
+ const texel = ivec23(uv2.mul(descriptor.atlasResolution));
967
+ const captured = textureLoad3(maps.normalDepth, texel);
968
+ const sampled = texture3(maps.baseColor, uv2).level(0);
969
+ const sampledOrm = texture3(maps.orm, uv2).level(0);
970
+ const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
971
+ const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
972
+ const tolerance = max3(
973
+ dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
974
+ dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
975
+ ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
976
+ If3(
977
+ occupied.and(sampled.a.greaterThanEqual(minimumAlpha)).and(
978
+ abs3(dot3(point, n).sub(float3(1).sub(depth.mul(2)))).lessThanEqual(
979
+ tolerance
980
+ )
981
+ ),
982
+ () => {
983
+ const angle = abs3(look.element(axis));
984
+ const filtered = filtering ? texture3(maps.normalDepth, uv2).level(0).toVar() : captured;
985
+ let weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
986
+ if (filtering) {
987
+ const error = abs3(dot3(point, n).sub(float3(1).sub(
988
+ filtered.b.mul(65280).add(filtered.a.mul(255)).div(65535).mul(2)
989
+ )));
990
+ weight = weight.mul(float3(1).sub(error.div(tolerance)).clamp(0, 1));
991
+ }
992
+ const coverage2 = max3(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
993
+ colors.addAssign(sampled.div(coverage2).mul(weight));
994
+ materials.addAssign(sampledOrm.rgb.div(coverage2).mul(weight));
995
+ emissions.addAssign(
996
+ texture3(maps.emissive, uv2).level(0).rgb.div(coverage2).mul(weight)
997
+ );
998
+ let shadingNormal;
999
+ if (filtering) shadingNormal = filteredNormal(uv2, float3(1).sub(dot3(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1000
+ else {
1001
+ const packed = captured.rg.mul(2).sub(1);
1002
+ const decoded = vec33(
1003
+ packed,
1004
+ float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1005
+ ).toVar();
1006
+ If3(decoded.z.lessThan(0), () => {
1007
+ decoded.xy.assign(
1008
+ vec23(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1009
+ );
1010
+ });
1011
+ shadingNormal = decoded;
1012
+ }
1013
+ normals.addAssign(
1014
+ fromBox(
1015
+ right.mul(shadingNormal.x).add(up.mul(shadingNormal.y)).add(n.mul(shadingNormal.z))
1016
+ ).normalize().mul(weight)
1017
+ );
1018
+ weights.addAssign(weight);
1019
+ }
1020
+ );
1021
+ }
1022
+ const divisor = max3(weights, 1e-10), valid = weights.greaterThan(1e-10);
1023
+ return Surface(
1024
+ valid.select(colors.div(divisor), fallbackColor),
1025
+ valid.select(materials.div(divisor), fallbackOrm),
1026
+ valid.select(emissions.div(divisor), fallbackEmission),
1027
+ valid.select(normals.normalize(), fallbackNormal)
1028
+ );
1029
+ })().toVar("boxBlendedSurface");
1030
+ color = blended.get("color");
1031
+ surfaceOrm = blended.get("orm");
1032
+ emission = blended.get("emission");
1033
+ normal = blended.get("normal");
1034
+ }
1035
+ material.capturedPositionNode = hit.get("position");
1036
+ material.colorNode = color.rgb;
1037
+ material.normalNode = transformNormalToView3(normal);
1038
+ material.roughnessNode = surfaceOrm.g;
1039
+ material.metalnessNode = surfaceOrm.b;
1040
+ material.aoNode = surfaceOrm.r;
1041
+ material.emissiveNode = emission;
1042
+ if (transparency !== "cutout") material.opacityNode = color.a.clamp(0, 1);
1043
+ material.maskNode = hit.get("valid").greaterThan(0.5);
1044
+ material.maskShadowNode = material.maskNode;
1045
+ material.depthNode = capturedSurfaceDepth(hit.get("position"));
1046
+ material.receivedShadowPositionNode = modelWorldMatrix3.mul(
1047
+ vec44(hit.get("position"), 1)
1048
+ ).xyz;
1049
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
1050
+ return material;
1051
+ }
1052
+ export {
1053
+ createBoxImpostorMaterial,
1054
+ createBoxImpostorMaterialVariant
1055
+ };
1056
+ //# sourceMappingURL=box-impostor-material.js.map