@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,721 @@
1
+ // TSL's struct declarations erase members; GPU rendering tests cover this graph.
2
+ // @ts-nocheck
3
+ import {
4
+ DataTexture,
5
+ FloatType,
6
+ RGBAFormat,
7
+ RedIntegerFormat,
8
+ UnsignedIntType,
9
+ NearestFilter,
10
+ LinearFilter,
11
+ MeshStandardNodeMaterial,
12
+ DoubleSide,
13
+ FrontSide,
14
+ } from "three/webgpu";
15
+ import {
16
+ Fn,
17
+ If,
18
+ Loop,
19
+ Break,
20
+ attribute,
21
+ varying,
22
+ positionLocal,
23
+ modelWorldMatrixInverse,
24
+ cameraPosition,
25
+ cameraWorldMatrix,
26
+ cameraProjectionMatrix,
27
+ vec2,
28
+ vec3,
29
+ vec4,
30
+ float,
31
+ int,
32
+ uint,
33
+ dot,
34
+ abs,
35
+ max,
36
+ min,
37
+ sign,
38
+ texture,
39
+ textureLoad,
40
+ ivec2,
41
+ normalize,
42
+ floor,
43
+ modelViewMatrix,
44
+ modelWorldMatrix,
45
+ cameraNear,
46
+ cameraFar,
47
+ viewZToPerspectiveDepth,
48
+ viewZToOrthographicDepth,
49
+ transformNormalToView,
50
+ struct,
51
+ uniform,
52
+ } from "three/tsl";
53
+ import {refineSurfaceCrossing} from './box-impostor-surface-search.js';
54
+ import { applyBoxFaces } from "./box-impostor-faces.js";
55
+ import { applyBoxProjection } from "./box-impostor-projection.js";
56
+ import {
57
+ normalizeBoxImpostorDisplay,
58
+ boxTransparency,
59
+ boxDepthMode,
60
+ } from "./box-impostor-display-settings.js";
61
+ import {
62
+ BOX_FACE_AXES,
63
+ BOX_OCCUPANCY_RESOLUTION,
64
+ } from "./box-impostor-metadata.js";
65
+
66
+ /** Six orthographic depth fields, one compiled ray budget and one shared PBR
67
+ * material. The same graph runs on native WebGPU and Three's WebGL2 backend.
68
+ * @param {import('./box-impostor-metadata.js').BoxImpostorDescriptor} descriptor
69
+ * @param {{baseColor:import('three').Texture,normalDepth:import('three').Texture,orm:import('three').Texture,emissive:import('three').Texture}} maps */
70
+ export function createBoxImpostorMaterial(descriptor, maps) {
71
+ const settings = normalizeBoxImpostorDisplay(descriptor);
72
+ const alphaCutoff = uniform(settings.alphaCutoff);
73
+ const transparency = boxTransparency(descriptor, settings);
74
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float(1 / 255);
75
+ for (const map of Object.values(maps)) {
76
+ if (map.minFilter !== LinearFilter || map.magFilter !== LinearFilter) {
77
+ map.minFilter = map.magFilter = LinearFilter;
78
+ map.generateMipmaps = false;
79
+ map.needsUpdate = true;
80
+ }
81
+ }
82
+ const material = new MeshStandardNodeMaterial({
83
+ name: "Box impostor",
84
+ side: descriptor.mode !== "fitted" ? DoubleSide : FrontSide,
85
+ alphaHash: transparency === "dithered",
86
+ transparent: transparency === "blended",
87
+ depthWrite: transparency !== "blended",
88
+ forceSinglePass: true,
89
+ });
90
+ const rectData = new Float32Array(descriptor.boxes.length * 6 * 4);
91
+ descriptor.boxes.forEach((b, i) =>
92
+ b.views.forEach((r, j) =>
93
+ rectData.set(
94
+ [
95
+ (r[0] + descriptor.padding) / descriptor.atlasResolution,
96
+ (r[1] + descriptor.padding) / descriptor.atlasResolution,
97
+ (r[2] - 2 * descriptor.padding) / descriptor.atlasResolution,
98
+ (r[3] - 2 * descriptor.padding) / descriptor.atlasResolution,
99
+ ],
100
+ (i * 6 + j) * 4,
101
+ ),
102
+ ),
103
+ );
104
+ const rects = new DataTexture(
105
+ rectData,
106
+ 6,
107
+ descriptor.boxes.length,
108
+ RGBAFormat,
109
+ FloatType,
110
+ );
111
+ rects.needsUpdate = true;
112
+ rects.magFilter = rects.minFilter = NearestFilter;
113
+ material.addEventListener("dispose", () => rects.dispose());
114
+ const center = attribute("boxCenter", "vec3"),
115
+ half = attribute("boxHalfSize", "vec3");
116
+ const ax = attribute("boxAxisX", "vec3"),
117
+ ay = attribute("boxAxisY", "vec3"),
118
+ az = attribute("boxAxisZ", "vec3");
119
+ const toBox = (p) => vec3(dot(p, ax), dot(p, ay), dot(p, az));
120
+ const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
121
+ const eye = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;
122
+ const viewAxis = modelWorldMatrixInverse
123
+ .mul(cameraWorldMatrix.mul(vec4(0, 0, 1, 0)))
124
+ .xyz.normalize();
125
+ const perspective = cameraProjectionMatrix.element(3).w.equal(0);
126
+ let proxy = positionLocal;
127
+ if (descriptor.mode !== "fitted") {
128
+ proxy = Fn((_, builder) => {
129
+ const forward = perspective.select(normalize(eye.sub(center)), viewAxis);
130
+ const right = modelWorldMatrixInverse
131
+ .mul(cameraWorldMatrix.mul(vec4(0, 1, 0, 0)))
132
+ .xyz.cross(forward)
133
+ .normalize();
134
+ const up = forward.cross(right).normalize();
135
+ // Project all box corners onto the nearest eye-facing plane. This is a
136
+ // conservative perspective bound, including views close to a thin box.
137
+ const radius = half.length();
138
+ const distance = dot(eye.sub(center), forward);
139
+ const plane = center.add(forward.mul(radius));
140
+ const lo = vec2(1e20).toVar(),
141
+ hi = vec2(-1e20).toVar();
142
+ for (const x of [-1, 1])
143
+ for (const y of [-1, 1])
144
+ for (const z of [-1, 1]) {
145
+ const corner = fromBox(half.mul(vec3(x, y, z)));
146
+ const scale = perspective.select(
147
+ max(distance.sub(radius), 0.00001).div(
148
+ max(distance.sub(dot(corner, forward)), 0.00001),
149
+ ),
150
+ float(1),
151
+ );
152
+ const p = vec2(dot(corner, right), dot(corner, up)).mul(scale);
153
+ lo.assign(min(lo, p));
154
+ hi.assign(max(hi, p));
155
+ }
156
+ const corner = attribute("cardCorner", "vec2").add(1).mul(0.5);
157
+ const xy = lo.add(hi.sub(lo).mul(corner));
158
+ return plane.add(right.mul(xy.x)).add(up.mul(xy.y));
159
+ })();
160
+ material.positionNode = proxy;
161
+ material.castShadowPositionNode = proxy;
162
+ }
163
+ const raster = varying(proxy, "boxRasterPosition");
164
+ if (
165
+ boxDepthMode(descriptor, settings) === "projection" &&
166
+ descriptor.mode === "fitted" &&
167
+ settings.interpolation === "none"
168
+ )
169
+ return applyBoxFaces({
170
+ material,
171
+ descriptor,
172
+ maps,
173
+ alphaCutoff,
174
+ transparency,
175
+ half,
176
+ toBox,
177
+ fromBox,
178
+ });
179
+ if (boxDepthMode(descriptor, settings) === "projection")
180
+ return applyBoxProjection({
181
+ material,
182
+ descriptor,
183
+ maps,
184
+ settings,
185
+ transparency,
186
+ alphaCutoff,
187
+ rects,
188
+ center,
189
+ half,
190
+ toBox,
191
+ fromBox,
192
+ eye,
193
+ viewAxis,
194
+ perspective,
195
+ raster,
196
+ });
197
+ const accelerated = descriptor.boxes.every((b) => b.depthBounds);
198
+ const gridSize = BOX_OCCUPANCY_RESOLUTION;
199
+ let occupancy;
200
+ if (
201
+ descriptor.boxes.every((b) => b.occupancy) &&
202
+ descriptor.boxes.some((b) =>
203
+ b.occupancy.some((word) => word !== 0xffffffff),
204
+ )
205
+ ) {
206
+ const wordsPerBox = gridSize ** 3 / 32;
207
+ const words = new Uint32Array(wordsPerBox * descriptor.boxes.length);
208
+ descriptor.boxes.forEach((box, index) =>
209
+ words.set(box.occupancy, index * wordsPerBox),
210
+ );
211
+ occupancy = new DataTexture(
212
+ words,
213
+ wordsPerBox,
214
+ descriptor.boxes.length,
215
+ RedIntegerFormat,
216
+ UnsignedIntType,
217
+ );
218
+ occupancy.needsUpdate = true;
219
+ material.addEventListener("dispose", () => occupancy.dispose());
220
+ }
221
+ const Result = struct(
222
+ { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
223
+ "BoxImpostorHit",
224
+ );
225
+ const raycast = Fn((_, builder) => {
226
+ const ray = perspective.select(
227
+ normalize(raster.sub(eye)),
228
+ viewAxis.negate(),
229
+ );
230
+ const origin = perspective.select(
231
+ eye,
232
+ raster.sub(ray.mul(half.length().mul(4))),
233
+ );
234
+ const o = toBox(origin.sub(center)).div(half),
235
+ r = toBox(ray).div(half);
236
+ const safe = sign(r.add(1e-20)).mul(max(abs(r), 1e-10));
237
+ const a = vec3(-1).sub(o).div(safe),
238
+ b = vec3(1).sub(o).div(safe);
239
+ const enter = max(max(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
240
+ const exit = min(min(max(a, b).x, max(a, b).y), max(a, b).z);
241
+ const occupiedStart = enter.toVar();
242
+ // This cover contains whole source voxel cubes. Only the empty space is
243
+ // skipped; the depth fields still determine the full-resolution surface.
244
+ if (occupancy) {
245
+ const gridOrigin = o.add(1).mul(gridSize / 2);
246
+ const gridRay = r.mul(gridSize / 2);
247
+ const step = sign(gridRay.add(1e-20));
248
+ const cell = floor(gridOrigin.add(gridRay.mul(enter)))
249
+ .clamp(0, gridSize - 1)
250
+ .toVar();
251
+ const inverse = vec3(1).div(safe.mul(gridSize / 2));
252
+ const delta = abs(inverse);
253
+ const next = cell
254
+ .add(step.add(1).mul(0.5))
255
+ .sub(gridOrigin)
256
+ .mul(inverse)
257
+ .toVar();
258
+ const t = enter.toVar();
259
+ occupiedStart.assign(exit.add(1));
260
+ Loop(gridSize * 3 + 1, () => {
261
+ If(t.greaterThan(exit), () => {
262
+ Break();
263
+ });
264
+ const cellIndex = uint(
265
+ cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2)),
266
+ ).toVar();
267
+ const word = textureLoad(
268
+ occupancy,
269
+ ivec2(int(cellIndex.shiftRight(5)), int(attribute("boxId", "float"))),
270
+ ).r;
271
+ const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
272
+ If(support.notEqual(uint(0)), () => {
273
+ occupiedStart.assign(t);
274
+ Break();
275
+ });
276
+ const edge = min(min(next.x, next.y), next.z).toVar();
277
+ const advance = vec3(
278
+ next.x.lessThanEqual(edge).select(1, 0),
279
+ next.y.lessThanEqual(edge).select(1, 0),
280
+ next.z.lessThanEqual(edge).select(1, 0),
281
+ );
282
+ cell.addAssign(advance.mul(step));
283
+ next.addAssign(advance.mul(delta));
284
+ t.assign(edge);
285
+ If(
286
+ cell.x
287
+ .lessThan(0)
288
+ .or(cell.x.greaterThan(gridSize - 1))
289
+ .or(cell.y.lessThan(0))
290
+ .or(cell.y.greaterThan(gridSize - 1))
291
+ .or(cell.z.lessThan(0))
292
+ .or(cell.z.greaterThan(gridSize - 1)),
293
+ () => {
294
+ Break();
295
+ },
296
+ );
297
+ });
298
+ }
299
+ const look = toBox(ray).negate();
300
+ const bestT = exit.add(1).toVar(),
301
+ bestUv = vec2(0).toVar(),
302
+ bestNormal = vec3(0, 0, 1).toVar(),
303
+ valid = float(0).toVar(),
304
+ found = float(0).toVar();
305
+ // A face-on capture can miss a nearer surface visible from another axis.
306
+ // Resolve each supported field and retain the closest validated surface.
307
+ const angles = abs(look).toVar();
308
+ const major = angles.x
309
+ .greaterThanEqual(angles.y)
310
+ .and(angles.x.greaterThanEqual(angles.z))
311
+ .select(
312
+ int(0),
313
+ angles.y.greaterThanEqual(angles.z).select(int(1), int(2)),
314
+ )
315
+ .toVar();
316
+ const nextAxis = major.add(1).mod(3),
317
+ lastAxis = major.add(2).mod(3);
318
+ const second = angles
319
+ .element(nextAxis)
320
+ .greaterThanEqual(angles.element(lastAxis))
321
+ .select(nextAxis, lastAxis)
322
+ .toVar();
323
+ const third = int(3).sub(major).sub(second).toVar();
324
+ Loop(
325
+ { start: 0, end: 6, type: "int", name: "viewIndex" },
326
+ ({ viewIndex: i }) => {
327
+ If(occupiedStart.greaterThan(exit), () => {
328
+ Break();
329
+ });
330
+ valid.assign(0);
331
+ const rank = i.mod(3);
332
+ const axis = rank
333
+ .equal(0)
334
+ .select(major, rank.equal(1).select(second, third))
335
+ .toVar();
336
+ const positive = i
337
+ .lessThan(3)
338
+ .select(
339
+ look.element(axis).greaterThanEqual(0),
340
+ look.element(axis).lessThan(0),
341
+ );
342
+ const face = axis.mul(2).add(positive.select(int(0), int(1)));
343
+ const facing = positive.select(1, -1);
344
+ const n = vec3(
345
+ axis.equal(0).select(facing, 0),
346
+ axis.equal(1).select(facing, 0),
347
+ axis.equal(2).select(facing, 0),
348
+ ).toVar();
349
+ const right = axis
350
+ .equal(0)
351
+ .select(
352
+ vec3(0, 0, facing.negate()),
353
+ axis.equal(1).select(vec3(1, 0, 0), vec3(facing, 0, 0)),
354
+ )
355
+ .toVar();
356
+ const up = axis
357
+ .equal(1)
358
+ .select(vec3(0, 0, facing.negate()), vec3(0, 1, 0))
359
+ .toVar();
360
+ const direction = i.lessThan(3).select(1, -1);
361
+ const rect = textureLoad(
362
+ rects,
363
+ ivec2(face, int(attribute("boxId", "float"))),
364
+ ).toVar();
365
+ const sampleUv = (p) =>
366
+ rect.xy.add(
367
+ vec2(dot(p, right), dot(p, up))
368
+ .mul(0.5)
369
+ .add(0.5)
370
+ .clamp(0, 1)
371
+ .mul(rect.zw),
372
+ );
373
+ const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
374
+ const depthAt = (uv) => decode(texture(maps.normalDepth, uv).level(0));
375
+ const distance = (t) => {
376
+ const p = o.add(r.mul(t));
377
+ return dot(p, n)
378
+ .sub(float(1).sub(depthAt(sampleUv(p)).mul(2)))
379
+ .mul(direction);
380
+ };
381
+ const acceptHit = (hitT) => {
382
+ const point = o.add(r.mul(hitT)),
383
+ uv = sampleUv(point);
384
+ // Filtering may move a hit within a texel footprint. A depth
385
+ // jump beyond that footprint must not become a connecting wall.
386
+ const texel = ivec2(uv.mul(descriptor.atlasResolution));
387
+ const nearest = textureLoad(maps.normalDepth, texel);
388
+ // Depth padding supplies filtering support, not geometry. A hit
389
+ // still needs an occupied nearest texel, including at box entry.
390
+ const occupied = textureLoad(maps.orm, texel).a.greaterThan(0.5);
391
+ const residual = abs(
392
+ dot(point, n).sub(float(1).sub(decode(nearest).mul(2))),
393
+ );
394
+ const tolerance = max(
395
+ dot(abs(right), half).div(rect.z.mul(descriptor.atlasResolution)),
396
+ dot(abs(up), half).div(rect.w.mul(descriptor.atlasResolution)),
397
+ )
398
+ .div(dot(abs(n), half))
399
+ .mul(4)
400
+ .add(4 / 65535);
401
+ If(
402
+ residual
403
+ .lessThanEqual(tolerance)
404
+ .and(occupied)
405
+ .and(
406
+ texture(maps.baseColor, uv)
407
+ .level(0)
408
+ .a.greaterThanEqual(minimumAlpha),
409
+ ),
410
+ () => {
411
+ valid.assign(1);
412
+ If(hitT.lessThan(bestT), () => {
413
+ bestT.assign(hitT);
414
+ bestUv.assign(uv);
415
+ found.assign(1);
416
+ const packed = texture(maps.normalDepth, uv)
417
+ .level(0)
418
+ .rg.div(max(texture(maps.orm, uv).level(0).a, 1e-10))
419
+ .mul(2)
420
+ .sub(1);
421
+ const normal = vec3(
422
+ packed.x,
423
+ packed.y,
424
+ float(1).sub(abs(packed.x)).sub(abs(packed.y)),
425
+ ).toVar();
426
+ If(normal.z.lessThan(0), () => {
427
+ normal.xy.assign(
428
+ vec2(1)
429
+ .sub(abs(normal.yx))
430
+ .mul(sign(normal.xy.add(1e-20))),
431
+ );
432
+ });
433
+ bestNormal.assign(
434
+ fromBox(
435
+ right
436
+ .mul(normal.x)
437
+ .add(up.mul(normal.y))
438
+ .add(n.mul(normal.z)),
439
+ ).normalize(),
440
+ );
441
+ bestNormal.mulAssign(
442
+ dot(bestNormal, ray).greaterThan(0).select(-1, 1),
443
+ );
444
+ });
445
+ },
446
+ );
447
+ };
448
+ const traceInterval = (
449
+ start,
450
+ end,
451
+ steps,
452
+ ) => {
453
+ // Sample every crossed texel; a fixed interval budget skips thin
454
+ // surfaces when an oblique ray spans hundreds of capture pixels.
455
+ const footprint = vec2(dot(r, right), dot(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
456
+ const samples = max(float(steps), max(footprint.x,footprint.y).mul(steps/8)).div(2).ceil().mul(2).toVar();
457
+ const step=end.sub(start).div(samples);
458
+ const previous = start.toVar(),
459
+ previousD = distance(start).toVar();
460
+ // At interval entry the refinement bracket has zero width. Resolve it
461
+ // once rather than resampling the same depth through every bisection.
462
+ If(previousD.lessThanEqual(0), () => {
463
+ acceptHit(start);
464
+ });
465
+ Loop({ start: int(0), end: int(samples.div(2)), type: "int" }, ({ i }) => {
466
+ If(valid.greaterThan(0.5), () => {
467
+ Break();
468
+ });
469
+ // Issue independent depth reads together, then resolve crossings in
470
+ // their original order before refining either crossing direction.
471
+ const samples = [1, 2].map((offset) => {
472
+ const t = start.add(step.mul(float(i.mul(2).add(offset)))).toVar();
473
+ return { t, d: distance(t).toVar() };
474
+ });
475
+ for (const { t, d } of samples) {
476
+ If(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
477
+ Break();
478
+ });
479
+ If(valid.lessThan(.5).and(d.mul(previousD).lessThanEqual(0)), () => {
480
+ const crossing=refineSurfaceCrossing({float,If,Loop},{lo:previous,hi:t,loValue:previousD,hiValue:d,height:distance,steps:3,secant:true});
481
+ acceptHit(crossing);
482
+ If(bestT.lessThanEqual(t), () => {
483
+ Break();
484
+ });
485
+ });
486
+ previous.assign(t);
487
+ previousD.assign(d);
488
+ }
489
+ });
490
+ };
491
+ If(
492
+ exit
493
+ .greaterThanEqual(enter)
494
+ .and(abs(look.element(axis)).greaterThan(0.001)),
495
+ () => {
496
+ if (!accelerated) {
497
+ traceInterval(enter, exit, descriptor.raySteps);
498
+ } else {
499
+ const depths = axis
500
+ .equal(0)
501
+ .select(
502
+ attribute("boxDepthX", "vec4"),
503
+ axis
504
+ .equal(1)
505
+ .select(
506
+ attribute("boxDepthY", "vec4"),
507
+ attribute("boxDepthZ", "vec4"),
508
+ ),
509
+ );
510
+ const interval = positive.select(depths.xy, depths.zw);
511
+ const initialDepth = float(1).sub(dot(o, n)).mul(0.5);
512
+ const depthSlope = dot(r, n).negate().mul(0.5);
513
+ const da = interval.x
514
+ .sub(2 / 65535)
515
+ .sub(initialDepth)
516
+ .div(depthSlope);
517
+ const db = interval.y
518
+ .add(2 / 65535)
519
+ .sub(initialDepth)
520
+ .div(depthSlope);
521
+ const start = max(occupiedStart, min(da, db));
522
+ const end = min(min(exit, bestT), max(da, db));
523
+ If(
524
+ interval.x
525
+ .lessThanEqual(interval.y)
526
+ .and(end.greaterThanEqual(start)),
527
+ () => {
528
+ const search = () =>
529
+ traceInterval(start, end, descriptor.raySteps);
530
+ const hasFlatView = descriptor.boxes.some((box) =>
531
+ [0, 2, 4, 6, 8, 10].some(
532
+ (i) =>
533
+ box.depthBounds[i + 1] >= box.depthBounds[i] &&
534
+ box.depthBounds[i + 1] - box.depthBounds[i] <= 1,
535
+ ),
536
+ );
537
+ if (hasFlatView) {
538
+ If(
539
+ interval.y.sub(interval.x).lessThanEqual(1 / 65535),
540
+ () => {
541
+ const t = interval.x
542
+ .add(interval.y)
543
+ .mul(0.5)
544
+ .sub(initialDepth)
545
+ .div(depthSlope);
546
+ If(
547
+ t
548
+ .greaterThanEqual(enter)
549
+ .and(t.lessThanEqual(min(exit, bestT))),
550
+ () => {
551
+ acceptHit(t);
552
+ },
553
+ );
554
+ },
555
+ ).Else(search);
556
+ } else search();
557
+ },
558
+ );
559
+ }
560
+ },
561
+ );
562
+ },
563
+ );
564
+ valid.assign(found);
565
+ const point = o.add(r.mul(bestT));
566
+ return Result(
567
+ bestUv,
568
+ center.add(fromBox(point.mul(half))),
569
+ bestNormal,
570
+ valid,
571
+ );
572
+ });
573
+ const hit = raycast().toVar("boxHit");
574
+ const base = texture(maps.baseColor, hit.get("uv")).level(0),
575
+ orm = texture(maps.orm, hit.get("uv")).level(0);
576
+ // Capture backgrounds are zero in every map. Normalize all filtered surface
577
+ // attributes by geometric coverage; an
578
+ // empty neighbor must not turn a rough edge into a glossy highlight.
579
+ const coverage = max(orm.a, 1e-10);
580
+ let color = base.div(coverage),
581
+ surfaceOrm = orm.rgb.div(coverage),
582
+ emission = texture(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage),
583
+ normal = hit.get("normal");
584
+ if (settings.interpolation !== "none") {
585
+ const fallbackColor = color,
586
+ fallbackOrm = surfaceOrm,
587
+ fallbackEmission = emission,
588
+ fallbackNormal = normal;
589
+ const Surface = struct(
590
+ { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
591
+ "BoxSurfaceBlend",
592
+ );
593
+ const blended = Fn(() => {
594
+ const point = toBox(hit.get("position").sub(center)).div(half);
595
+ const look = toBox(
596
+ perspective.select(normalize(eye.sub(hit.get("position"))), viewAxis),
597
+ );
598
+ const colors = vec4(0).toVar(),
599
+ materials = vec3(0).toVar(),
600
+ emissions = vec3(0).toVar(),
601
+ normals = vec3(0).toVar(),
602
+ weights = float(0).toVar();
603
+ for (let axis = 0; axis < 3; axis++) {
604
+ const positive = look.element(axis).greaterThanEqual(0);
605
+ const front = BOX_FACE_AXES[axis * 2],
606
+ back = BOX_FACE_AXES[axis * 2 + 1];
607
+ const n = positive.select(vec3(...front.normal), vec3(...back.normal));
608
+ const right = positive.select(
609
+ vec3(...front.right),
610
+ vec3(...back.right),
611
+ );
612
+ const up = positive.select(vec3(...front.up), vec3(...back.up));
613
+ const face = positive.select(int(axis * 2), int(axis * 2 + 1));
614
+ const rect = textureLoad(
615
+ rects,
616
+ ivec2(face, int(attribute("boxId", "float"))),
617
+ );
618
+ const uv = rect.xy.add(
619
+ vec2(dot(point, right), dot(point, up))
620
+ .mul(0.5)
621
+ .add(0.5)
622
+ .clamp(0, 1)
623
+ .mul(rect.zw),
624
+ );
625
+ const texel = ivec2(uv.mul(descriptor.atlasResolution));
626
+ const captured = textureLoad(maps.normalDepth, texel);
627
+ const sampled = texture(maps.baseColor, uv).level(0);
628
+ const sampledOrm = texture(maps.orm, uv).level(0);
629
+ const occupied = textureLoad(maps.orm, texel).a.greaterThan(0.5);
630
+ const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
631
+ const tolerance = max(
632
+ dot(abs(right), half).div(rect.z.mul(descriptor.atlasResolution)),
633
+ dot(abs(up), half).div(rect.w.mul(descriptor.atlasResolution)),
634
+ )
635
+ .div(dot(abs(n), half))
636
+ .mul(4)
637
+ .add(4 / 65535);
638
+ // Only blend captures that see this same surface. A hidden layer or
639
+ // background texel must not bleed across an occlusion boundary.
640
+ If(
641
+ occupied
642
+ .and(sampled.a.greaterThanEqual(minimumAlpha))
643
+ .and(
644
+ abs(dot(point, n).sub(float(1).sub(depth.mul(2)))).lessThanEqual(
645
+ tolerance,
646
+ ),
647
+ ),
648
+ () => {
649
+ const angle = abs(look.element(axis));
650
+ const weight =
651
+ settings.interpolation === "smooth" ? angle.mul(angle) : angle;
652
+ const coverage = max(sampledOrm.a, 1e-10);
653
+ colors.addAssign(sampled.div(coverage).mul(weight));
654
+ materials.addAssign(sampledOrm.rgb.div(coverage).mul(weight));
655
+ emissions.addAssign(
656
+ texture(maps.emissive, uv).level(0).rgb.div(coverage).mul(weight),
657
+ );
658
+ const packed = captured.rg.mul(2).sub(1);
659
+ const decoded = vec3(
660
+ packed,
661
+ float(1).sub(abs(packed.x)).sub(abs(packed.y)),
662
+ ).toVar();
663
+ If(decoded.z.lessThan(0), () => {
664
+ decoded.xy.assign(
665
+ vec2(1)
666
+ .sub(abs(decoded.yx))
667
+ .mul(sign(decoded.xy.add(1e-20))),
668
+ );
669
+ });
670
+ normals.addAssign(
671
+ fromBox(
672
+ right
673
+ .mul(decoded.x)
674
+ .add(up.mul(decoded.y))
675
+ .add(n.mul(decoded.z)),
676
+ )
677
+ .normalize()
678
+ .mul(weight),
679
+ );
680
+ weights.addAssign(weight);
681
+ },
682
+ );
683
+ }
684
+ const divisor = max(weights, 1e-10),
685
+ valid = weights.greaterThan(1e-10);
686
+ return Surface(
687
+ valid.select(colors.div(divisor), fallbackColor),
688
+ valid.select(materials.div(divisor), fallbackOrm),
689
+ valid.select(emissions.div(divisor), fallbackEmission),
690
+ valid.select(normals.normalize(), fallbackNormal),
691
+ );
692
+ })().toVar("boxBlendedSurface");
693
+ color = blended.get("color");
694
+ surfaceOrm = blended.get("orm");
695
+ emission = blended.get("emission");
696
+ normal = blended.get("normal");
697
+ }
698
+ material.colorNode = color.rgb;
699
+ material.normalNode = transformNormalToView(normal);
700
+ material.roughnessNode = surfaceOrm.g;
701
+ material.metalnessNode = surfaceOrm.b;
702
+ material.aoNode = surfaceOrm.r;
703
+ material.emissiveNode = emission;
704
+ if (transparency !== "cutout") material.opacityNode = color.a.clamp(0, 1);
705
+ material.maskNode = hit.get("valid").greaterThan(0.5);
706
+ material.maskShadowNode = material.maskNode;
707
+ material.depthNode = Fn((_, builder) => {
708
+ const z = modelViewMatrix
709
+ .mul(vec4(hit.get("position"), 1))
710
+ .z.toVar("boxHitDepthZ");
711
+ return perspective.select(
712
+ viewZToPerspectiveDepth(z, cameraNear, cameraFar),
713
+ viewZToOrthographicDepth(z, cameraNear, cameraFar),
714
+ );
715
+ })();
716
+ material.receivedShadowPositionNode = modelWorldMatrix.mul(
717
+ vec4(hit.get("position"), 1),
718
+ ).xyz;
719
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
720
+ return material;
721
+ }