@needle-tools/three-mesh-effects 0.3.5 → 0.3.7

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 (63) hide show
  1. package/CHANGELOG.md +33 -28
  2. package/README.md +63 -231
  3. package/SKILL.md +11 -68
  4. package/build/box-impostor-runtime.js +652 -257
  5. package/build/box-impostor-runtime.js.map +4 -4
  6. package/build/deformation-runtime.js +1 -1
  7. package/build/deformation-runtime.js.map +1 -1
  8. package/build/hull-effects.js.map +1 -1
  9. package/build/impostor-runtime.js +2 -2
  10. package/build/impostor-runtime.js.map +2 -2
  11. package/build/index.js +2 -2
  12. package/build/index.js.map +2 -2
  13. package/build/internal/box-impostor/box-impostor-display.js +662 -265
  14. package/build/internal/box-impostor/box-impostor-display.js.map +4 -4
  15. package/build/internal/box-impostor/box-impostor-material.js +662 -265
  16. package/build/internal/box-impostor/box-impostor-material.js.map +4 -4
  17. package/build/internal/box-impostor/box-impostor-ray-bounds.js +369 -0
  18. package/build/internal/box-impostor/box-impostor-ray-bounds.js.map +7 -0
  19. package/build/internal/box-impostor/box-impostor-runtime.js +652 -257
  20. package/build/internal/box-impostor/box-impostor-runtime.js.map +4 -4
  21. package/build/internal/deformation/rig-runtime.js +1 -1
  22. package/build/internal/deformation/rig-runtime.js.map +1 -1
  23. package/build/internal/impostor/impostor-node-material.js +2 -2
  24. package/build/internal/impostor/impostor-node-material.js.map +2 -2
  25. package/build/internal/impostor/octahedral.js.map +1 -1
  26. package/build/internal/pixel-impostor/pixel-impostor-display.js +39 -16
  27. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +2 -2
  28. package/build/internal/pixel-impostor/pixel-impostor-metadata.js +61 -6
  29. package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +2 -2
  30. package/build/internal/pixel-impostor/pixel-impostor-runtime.js +980 -26
  31. package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +4 -4
  32. package/build/internal/rendering/hull-effect-runtime.js.map +1 -1
  33. package/build/internal/rendering/renderer-support.js.map +1 -1
  34. package/build/internal/rendering/skin-projection.js.map +1 -1
  35. package/build/internal/rendering/surface-query.js.map +1 -1
  36. package/build/internal/rendering/wrap-preview.js.map +1 -1
  37. package/build/internal/rendering/wrap-skin.js.map +1 -1
  38. package/build/pixel-impostor-runtime.js +362 -172
  39. package/build/pixel-impostor-runtime.js.map +4 -4
  40. package/build/types/box-impostor/box-impostor-material.d.ts +2 -1
  41. package/build/types/box-impostor/box-impostor-ray-bounds.d.ts +6 -0
  42. package/build/types/box-impostor/box-impostor-ray-bounds.js +1 -0
  43. package/build/types/deformation/rig-runtime.d.ts +1 -1
  44. package/build/types/impostor/octahedral.d.ts +1 -1
  45. package/build/types/pixel-impostor/pixel-impostor-display.d.ts +3 -3
  46. package/build/types/pixel-impostor/pixel-impostor-metadata.d.ts +76 -5
  47. package/build/types/pixel-impostor/pixel-impostor-runtime.d.ts +19 -7
  48. package/build/types/public/pixel-impostor-runtime.d.ts +1 -1
  49. package/build/types/rendering/renderer-support.d.ts +1 -1
  50. package/build/types/rendering/surface-query.d.ts +2 -2
  51. package/package.json +2 -2
  52. package/src/box-impostor/box-impostor-material.js +128 -90
  53. package/src/box-impostor/box-impostor-ray-bounds.js +452 -0
  54. package/src/deformation/rig-runtime.ts +1 -1
  55. package/src/impostor/impostor-node-material.js +2 -2
  56. package/src/impostor/octahedral.js +1 -1
  57. package/src/pixel-impostor/pixel-impostor-display.js +32 -18
  58. package/src/pixel-impostor/pixel-impostor-metadata.js +69 -9
  59. package/src/pixel-impostor/pixel-impostor-runtime.js +32 -9
  60. package/src/public/index.js +2 -2
  61. package/src/public/pixel-impostor-runtime.js +1 -1
  62. package/src/rendering/renderer-support.js +1 -1
  63. package/src/rendering/surface-query.js +2 -2
@@ -44,9 +44,9 @@ import {
44
44
  FrontSide
45
45
  } from "three/webgpu";
46
46
  import {
47
- Fn as Fn4,
48
- If as If3,
49
- Loop,
47
+ Fn as Fn5,
48
+ If as If4,
49
+ Loop as Loop2,
50
50
  Break,
51
51
  attribute as attribute3,
52
52
  varying,
@@ -56,22 +56,22 @@ import {
56
56
  cameraPosition,
57
57
  cameraWorldMatrix,
58
58
  cameraProjectionMatrix as cameraProjectionMatrix2,
59
- vec2 as vec23,
60
- vec3 as vec33,
61
- vec4 as vec44,
62
- float as float3,
63
- int as int3,
64
- uint,
59
+ vec2 as vec24,
60
+ vec3 as vec34,
61
+ vec4 as vec45,
62
+ float as float4,
63
+ int as int4,
64
+ uint as uint2,
65
65
  dot as dot3,
66
66
  abs as abs3,
67
- max as max3,
68
- min,
67
+ max as max4,
68
+ min as min2,
69
69
  sign as sign3,
70
70
  texture as texture3,
71
- textureLoad as textureLoad3,
72
- ivec2 as ivec23,
71
+ textureLoad as textureLoad4,
72
+ ivec2 as ivec24,
73
73
  normalize as normalize2,
74
- floor,
74
+ floor as floor2,
75
75
  fract,
76
76
  modelWorldMatrix as modelWorldMatrix3,
77
77
  cameraNear as cameraNear2,
@@ -103,12 +103,376 @@ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
103
103
  }
104
104
  };
105
105
 
106
+ // src/box-impostor/box-impostor-ray-bounds.js
107
+ import { Matrix4, NodeUpdateType, StorageBufferAttribute, Vector3 } from "three/webgpu";
108
+ import {
109
+ Fn as Fn2,
110
+ If,
111
+ Loop,
112
+ atomicMin,
113
+ atomicStore,
114
+ clamp,
115
+ float,
116
+ floor,
117
+ instanceIndex,
118
+ int,
119
+ ivec2,
120
+ max,
121
+ min,
122
+ storage,
123
+ textureLoad,
124
+ uint,
125
+ vec2,
126
+ vec3,
127
+ vec4 as vec43
128
+ } from "three/tsl";
129
+
130
+ // src/box-impostor/box-impostor-face-axes.js
131
+ var BOX_FACE_AXES = Object.freeze([
132
+ { normal: [1, 0, 0], right: [0, 0, -1], up: [0, 1, 0] },
133
+ { normal: [-1, 0, 0], right: [0, 0, 1], up: [0, 1, 0] },
134
+ { normal: [0, 1, 0], right: [1, 0, 0], up: [0, 0, -1] },
135
+ { normal: [0, -1, 0], right: [1, 0, 0], up: [0, 0, 1] },
136
+ { normal: [0, 0, 1], right: [1, 0, 0], up: [0, 1, 0] },
137
+ { normal: [0, 0, -1], right: [-1, 0, 0], up: [0, 1, 0] }
138
+ ]);
139
+
140
+ // src/box-impostor/box-impostor-ray-bounds.js
141
+ var MIN_TILE_SIZE = 3;
142
+ var MAX_CAPTURE_TILES = 512 * 1024;
143
+ var REFRESH_ANGLE_SQUARED = Math.tan(Math.PI / 360) ** 2;
144
+ var DEPTH_MAX = 65535;
145
+ var MAX_VIEW_BYTES = 16 * 1024 * 1024;
146
+ var MAX_CACHED_VIEW_BYTES = 64 * 1024 * 1024;
147
+ function buffer(length, components = 1, Type = Float32Array) {
148
+ return new StorageBufferAttribute(length, components, Type);
149
+ }
150
+ function captureTiles(descriptor) {
151
+ const faces = descriptor.boxes.flatMap(
152
+ (box, id) => BOX_FACE_AXES.map((axes, face) => {
153
+ const [, , width, height] = box.views[face];
154
+ const w = width - 2 * descriptor.padding, h = height - 2 * descriptor.padding;
155
+ const right = axes.right.findIndex(Boolean), up = axes.up.findIndex(Boolean);
156
+ const tolerance = 4 * Math.max(box.halfSize[right] / w, box.halfSize[up] / h) / box.halfSize[face >> 1] + 5 / DEPTH_MAX;
157
+ return { key: id * 6 + face, w, h, tolerance };
158
+ })
159
+ );
160
+ const countFor = (size2) => faces.reduce((n, f) => n + Math.ceil((f.w + 2) / size2) * Math.ceil((f.h + 2) / size2), 0);
161
+ let size = MIN_TILE_SIZE;
162
+ while (countFor(size) > MAX_CAPTURE_TILES) size *= 2;
163
+ const tiles = buffer(countFor(size), 4);
164
+ let offset = 0;
165
+ for (const { key, w, h, tolerance } of faces) {
166
+ for (let y = -1; y <= h; y += size) {
167
+ for (let x = -1; x <= w; x += size) {
168
+ tiles.array[offset] = key;
169
+ tiles.array[offset + 1] = x;
170
+ tiles.array[offset + 2] = y;
171
+ tiles.array[offset + 3] = tolerance;
172
+ offset += 4;
173
+ }
174
+ }
175
+ }
176
+ return { tiles, size };
177
+ }
178
+ function buildPatches(descriptor, maps, rects, tiles, size, output) {
179
+ const descriptions = storage(tiles, "vec4", tiles.count).toReadOnly();
180
+ const patches = storage(output, "vec4", output.count);
181
+ return Fn2(() => {
182
+ const meta = descriptions.element(instanceIndex).toVar();
183
+ const key = int(meta.x), face = key.mod(6), axis = face.div(2);
184
+ const rect = textureLoad(rects, ivec2(face, key.div(6))).mul(descriptor.atlasResolution).round().toVar();
185
+ const extent = ivec2(rect.zw.add(1).sub(meta.yz)).min(ivec2(size));
186
+ const origin = ivec2(rect.xy.add(meta.yz));
187
+ const near = float(1).toVar(), far = float(0).toVar();
188
+ function visit(process) {
189
+ Loop({ start: int(0), end: extent.y, type: "int", name: "row" }, ({ row }) => {
190
+ Loop({ start: int(0), end: extent.x, type: "int", name: "column" }, ({ column }) => {
191
+ const pixel = origin.add(ivec2(column, row));
192
+ If(textureLoad(maps.orm, pixel).a.greaterThan(0.5), () => {
193
+ const packed = textureLoad(maps.normalDepth, pixel);
194
+ const depth = packed.b.mul(65280).add(packed.a.mul(255)).div(DEPTH_MAX).toVar();
195
+ process(column, row, depth);
196
+ });
197
+ });
198
+ });
199
+ }
200
+ visit((x, y, depth) => {
201
+ near.assign(min(near, depth));
202
+ far.assign(max(far, depth));
203
+ });
204
+ const middle = near.add(far).mul(0.5).toVar();
205
+ const low = [vec3(2).toVar(), vec3(2).toVar()], high = [vec3(-2).toVar(), vec3(-2).toVar()];
206
+ visit((x, y, depth) => {
207
+ const uv2 = meta.yz.add(vec2(x, y)).div(rect.zw).mul(2).sub(1);
208
+ const lo = vec3(uv2.clamp(-1, 1), float(1).sub(depth.mul(2)).sub(meta.w).max(-1)).toVar();
209
+ const hi = vec3(
210
+ uv2.add(vec2(2).div(rect.zw)).clamp(-1, 1),
211
+ float(1).sub(depth.mul(2)).add(meta.w).min(1)
212
+ ).toVar();
213
+ lo.toStack();
214
+ hi.toStack();
215
+ const extend = (group) => {
216
+ low[group].assign(min(low[group], lo));
217
+ high[group].assign(max(high[group], hi));
218
+ };
219
+ If(depth.lessThanEqual(middle), () => {
220
+ extend(0);
221
+ }).Else(() => {
222
+ extend(1);
223
+ });
224
+ });
225
+ const facing = face.mod(2).equal(0).select(1, -1);
226
+ const right = axis.equal(0).select(vec3(0, 0, facing.negate()), axis.equal(1).select(vec3(1, 0, 0), vec3(facing, 0, 0)));
227
+ const up = axis.equal(1).select(vec3(0, 0, facing.negate()), vec3(0, 1, 0));
228
+ const normal = right.cross(up);
229
+ const rotate = (p) => right.mul(p.x).add(up.mul(p.y)).add(normal.mul(p.z));
230
+ for (let group = 0; group < 2; group++) {
231
+ const a = rotate(low[group]), b = rotate(high[group]), slot = instanceIndex.mul(4).add(group * 2);
232
+ const valid = low[group].x.lessThanEqual(high[group].x);
233
+ patches.element(slot).assign(vec43(min(a, b), valid.select(meta.x, -1)));
234
+ patches.element(slot.add(1)).assign(vec43(max(a, b), 0));
235
+ }
236
+ })().compute(tiles.count);
237
+ }
238
+ function makeViewPasses(patchBuffer, views, ranges, count, resolution) {
239
+ const table = storage(ranges, "uint", count).toAtomic();
240
+ const reset = Fn2(() => {
241
+ atomicStore(table.element(instanceIndex), uint(DEPTH_MAX));
242
+ })().compute(count);
243
+ const patches = storage(patchBuffer, "vec4", patchBuffer.count).toReadOnly();
244
+ const scatter = Fn2(() => {
245
+ const a = patches.element(instanceIndex.mul(2)).toVar(), b = patches.element(instanceIndex.mul(2).add(1)).toVar();
246
+ If(a.w.greaterThanEqual(0), () => {
247
+ const key = int(a.w), box = key.div(6);
248
+ const mapping = views.element(box.mul(2)), reference = views.element(box.mul(2).add(1));
249
+ If(reference.w.greaterThanEqual(0), () => {
250
+ const axis = int(reference.w).mod(3), x = axis.add(1).mod(3), y = axis.add(2).mod(3);
251
+ const e = vec2(reference.element(x), reference.element(y)), ez = reference.element(axis);
252
+ const za = a.element(axis), zb = b.element(axis);
253
+ const weight = reference.w.lessThan(3).select(1, 0).toVar();
254
+ const eyeSlope = e.div(ez).toVar(), inverseDistance = weight.div(ez).toVar();
255
+ const project = (v, z) => v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
256
+ const l = vec2(a.element(x), a.element(y)), h = vec2(b.element(x), b.element(y));
257
+ const cell = (v, bias) => ivec2(floor(v.sub(mapping.xy).mul(mapping.zw).add(bias)).clamp(0, resolution - 1));
258
+ const lo = cell(min(project(l, za), project(l, zb)), -5e-3);
259
+ const hi = cell(max(project(h, za), project(h, zb)), 5e-3);
260
+ const padding = vec2(0.506).div(mapping.zw).mul(inverseDistance.abs().add(1)).add(2e-6);
261
+ Loop({ start: lo.y, end: hi.y.add(1), type: "int", name: "row" }, ({ row }) => {
262
+ Loop({ start: lo.x, end: hi.x.add(1), type: "int", name: "column" }, ({ column }) => {
263
+ const uv2 = vec2(column, row).add(0.5).div(mapping.zw).add(mapping.xy);
264
+ const slope = eyeSlope.sub(uv2.mul(inverseDistance)).toVar();
265
+ const safe = slope.add(1e-30).sign().mul(slope.abs().max(1e-12));
266
+ const ta = l.sub(padding).sub(uv2).div(safe).toVar(), tb = h.add(padding).sub(uv2).div(safe).toVar();
267
+ const begin = max(za, max(min(ta.x, tb.x), min(ta.y, tb.y))), end = min(zb, min(max(ta.x, tb.x), max(ta.y, tb.y)));
268
+ If(begin.lessThanEqual(end), () => {
269
+ const depths = floor(
270
+ vec2(begin.add(1), float(1).sub(end)).mul(DEPTH_MAX / 2).sub(0.02)
271
+ ).max(0);
272
+ const i = key.mul(resolution).add(row).mul(resolution).add(column).mul(2);
273
+ atomicMin(table.element(i), uint(depths.x));
274
+ atomicMin(table.element(i.add(1)), uint(depths.y));
275
+ });
276
+ });
277
+ });
278
+ });
279
+ });
280
+ })().compute(patchBuffer.count / 2);
281
+ return { reset, scatter, table };
282
+ }
283
+ function setProjection(data, descriptor, reference, orthographic, resolution) {
284
+ for (const [id, box] of descriptor.boxes.entries()) {
285
+ const p = box.axes.map(
286
+ (axis2, i) => axis2.reduce(
287
+ (sum, v, k) => sum + v * (orthographic ? reference[k] : reference[k] - box.center[k]),
288
+ 0
289
+ ) / box.halfSize[i]
290
+ );
291
+ const axis = p.map(Math.abs).indexOf(Math.max(...p.map(Math.abs)));
292
+ const ez = p[axis], offset = id * 8;
293
+ if (orthographic ? Math.abs(ez) < 1e-12 : Math.abs(ez) <= 1.01) {
294
+ data[offset + 7] = -1;
295
+ continue;
296
+ }
297
+ for (let j = 0; j < 2; j++) {
298
+ const e = p[(axis + 1 + j) % 3];
299
+ const project = (v, z) => orthographic ? v - z * e / ez : (v * ez - z * e) / (ez - z);
300
+ const low = Math.min(project(-1, -1), project(-1, 1));
301
+ const high = Math.max(project(1, -1), project(1, 1));
302
+ data[offset + j] = low;
303
+ data[offset + j + 2] = resolution / (high - low);
304
+ }
305
+ data.set(p, offset + 4);
306
+ data[offset + 7] = axis + (orthographic ? 3 : 0);
307
+ }
308
+ }
309
+ function createBoxRayBounds(descriptor, maps, rects, material) {
310
+ const boxes = descriptor.boxes.length;
311
+ const resolution = Math.min(128, Math.floor(Math.sqrt(MAX_VIEW_BYTES / (48 * boxes))));
312
+ if (resolution < 32 || descriptor.atlasResolution < 512 || [maps.normalDepth, maps.orm].some((map) => map.isRenderTargetTexture || map.isVideoTexture))
313
+ return null;
314
+ const count = boxes * 6 * resolution ** 2 * 2;
315
+ const maxViews = Math.max(1, Math.floor(MAX_CACHED_VIEW_BYTES / (count * 4 + boxes * 32)));
316
+ const inactiveView = buffer(boxes * 2, 4);
317
+ for (let i = 0; i < boxes; i++) inactiveView.array.set([0, 0, 1, 1, 2, 0, 0, -1], i * 8);
318
+ const inactiveRanges = buffer(1, 1, Uint32Array);
319
+ const views = storage(inactiveView, "vec4", boxes * 2).toReadOnly();
320
+ const ranges = storage(inactiveRanges, "uint").toReadOnly();
321
+ const inverse = new Matrix4(), eye = new Vector3(), center = new Vector3();
322
+ const states = /* @__PURE__ */ new Map();
323
+ let tiles, patches, reduce, passes;
324
+ function prepare({ renderer, camera, object }) {
325
+ views.value = inactiveView;
326
+ ranges.value = inactiveRanges;
327
+ if (!renderer.backend?.isWebGPUBackend || renderer.xr?.isPresenting || object.isInstancedMesh || !camera.isPerspectiveCamera && !camera.isOrthographicCamera || camera.isArrayCamera)
328
+ return;
329
+ inverse.copy(object.matrixWorld).invert();
330
+ const ortho = camera.isOrthographicCamera === true;
331
+ if (ortho) camera.getWorldDirection(eye).transformDirection(inverse);
332
+ else eye.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(inverse);
333
+ if (!Number.isFinite(eye.lengthSq())) return;
334
+ let state = states.get(renderer);
335
+ if (!state) {
336
+ state = { slots: [], initialized: false };
337
+ states.set(renderer, state);
338
+ }
339
+ if (!tiles) {
340
+ const capture = captureTiles(descriptor);
341
+ tiles = capture.tiles;
342
+ patches = buffer(tiles.count * 4, 4);
343
+ reduce = buildPatches(descriptor, maps, rects, tiles, capture.size, patches);
344
+ const computeViews = storage(inactiveView, "vec4", boxes * 2).toReadOnly();
345
+ passes = {
346
+ ...makeViewPasses(patches, computeViews, inactiveRanges, count, resolution),
347
+ views: computeViews
348
+ };
349
+ }
350
+ if (!state.initialized || state.depthVersion !== maps.normalDepth.version || state.coverageVersion !== maps.orm.version) {
351
+ renderer.compute(reduce);
352
+ for (const slot2 of state.slots) slot2.ready = false;
353
+ state.depthVersion = maps.normalDepth.version;
354
+ state.coverageVersion = maps.orm.version;
355
+ state.initialized = true;
356
+ }
357
+ const frame = renderer.info.render.calls;
358
+ const compatible = (v) => v.ready && v.ortho === ortho && v.eye.distanceToSquared(eye) <= v.radiusSq;
359
+ let slot = state.slots.find((v) => v.object.deref() === object && v.camera.deref() === camera);
360
+ if (!slot || !compatible(slot)) {
361
+ const shared = state.slots.find(compatible);
362
+ if (shared) {
363
+ shared.frame = frame;
364
+ views.value = shared.view;
365
+ ranges.value = shared.ranges;
366
+ return;
367
+ }
368
+ if (slot?.frame === frame) slot = void 0;
369
+ }
370
+ if (!slot) {
371
+ if (state.slots.length < maxViews) {
372
+ slot = { view: buffer(boxes * 2, 4), ranges: buffer(count, 1, Uint32Array), eye: new Vector3() };
373
+ state.slots.push(slot);
374
+ } else {
375
+ slot = state.slots.reduce((oldest, v) => v.frame < oldest.frame ? v : oldest);
376
+ if (slot.frame === frame) {
377
+ let nearest = Infinity;
378
+ for (const v of state.slots) {
379
+ if (!v.ready || v.ortho !== ortho) continue;
380
+ const distance = v.eye.distanceToSquared(eye);
381
+ if (distance < nearest) {
382
+ nearest = distance;
383
+ views.value = v.view;
384
+ ranges.value = v.ranges;
385
+ }
386
+ }
387
+ return;
388
+ }
389
+ }
390
+ slot.object = new WeakRef(object);
391
+ slot.camera = new WeakRef(camera);
392
+ slot.ready = false;
393
+ }
394
+ slot.frame = frame;
395
+ views.value = slot.view;
396
+ ranges.value = slot.ranges;
397
+ if (compatible(slot)) return;
398
+ setProjection(slot.view.array, descriptor, eye.toArray(), ortho, resolution);
399
+ slot.view.needsUpdate = true;
400
+ passes.views.value = slot.view;
401
+ passes.table.value = slot.ranges;
402
+ renderer.compute([passes.reset, passes.scatter]);
403
+ const distanceSquared = ortho ? 1 : Math.min(...descriptor.boxes.map((box) => eye.distanceToSquared(center.fromArray(box.center))));
404
+ slot.radiusSq = distanceSquared * REFRESH_ANGLE_SQUARED;
405
+ slot.eye.copy(eye);
406
+ slot.ortho = ortho;
407
+ slot.ready = true;
408
+ }
409
+ views.updateBeforeType = NodeUpdateType.OBJECT;
410
+ views.updateBefore = prepare;
411
+ material.addEventListener("dispose", () => {
412
+ for (const state of states.values()) {
413
+ for (const slot of state.slots) {
414
+ slot.view.dispose();
415
+ slot.ranges.dispose();
416
+ }
417
+ }
418
+ states.clear();
419
+ reduce?.dispose();
420
+ passes?.reset.dispose();
421
+ passes?.scatter.dispose();
422
+ tiles?.dispose();
423
+ patches?.dispose();
424
+ inactiveView.dispose();
425
+ inactiveRanges.dispose();
426
+ });
427
+ return (builder, id, o, r, enter, exit) => {
428
+ if (!builder.renderer.backend?.isWebGPUBackend) return null;
429
+ const mapping = views.element(id.mul(2)).toVar();
430
+ const ref = views.element(id.mul(2).add(1)).toVar();
431
+ const axis = int(max(ref.w, 0)).mod(3), x = axis.add(1).mod(3), y = axis.add(2).mod(3);
432
+ const rz = r.element(axis).toVar(), oz = o.element(axis).toVar();
433
+ const ez = ref.element(axis), e = vec2(ref.element(x), ref.element(y));
434
+ const eyeSlope = e.div(ez), inverseDistance = ref.w.lessThan(3).select(1, 0).div(ez);
435
+ const project = (t) => {
436
+ const point = o.add(r.mul(t)), v = vec2(point.element(x), point.element(y)), z = point.element(axis);
437
+ const p = v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
438
+ return p.sub(mapping.xy).mul(mapping.zw);
439
+ };
440
+ const a = project(enter).toVar(), b = project(exit).toVar();
441
+ const cellLo = ivec2(floor(min(a, b).sub(1e-3)).clamp(0, resolution - 1)).toVar();
442
+ const cellHi = ivec2(floor(max(a, b).add(1e-3)).clamp(0, resolution - 1)).toVar();
443
+ const valid = ref.w.greaterThanEqual(0).and(rz.abs().greaterThan(1e-12)).and(cellHi.sub(cellLo).lessThanEqual(ivec2(2)).all()).toVar();
444
+ return (face, enter2, exit2) => {
445
+ const start = enter2.toVar(), end = exit2.toVar();
446
+ If(valid, () => {
447
+ const base = id.mul(6).add(face).mul(resolution ** 2);
448
+ const at = (u, v) => base.add(v.mul(resolution)).add(u).mul(2);
449
+ const idx = at(cellLo.x, cellLo.y).toVar();
450
+ const lower = ranges.element(idx).toVar(), upper = ranges.element(idx.add(1)).toVar();
451
+ If(cellHi.notEqual(cellLo).any(), () => {
452
+ Loop({ start: cellLo.y, end: cellHi.y.add(1), type: "int", name: "by" }, ({ by }) => {
453
+ Loop({ start: cellLo.x, end: cellHi.x.add(1), type: "int", name: "bx" }, ({ bx }) => {
454
+ const p = at(bx, by);
455
+ lower.assign(min(lower, ranges.element(p)));
456
+ upper.assign(min(upper, ranges.element(p.add(1))));
457
+ });
458
+ });
459
+ });
460
+ const lo = float(lower).mul(2 / DEPTH_MAX).sub(1), hi = float(1).sub(float(upper).mul(2 / DEPTH_MAX));
461
+ const a2 = lo.sub(oz).div(rz), b2 = hi.sub(oz).div(rz);
462
+ start.assign(min(a2, b2));
463
+ end.assign(lo.lessThanEqual(hi).select(max(a2, b2), enter2.sub(1)));
464
+ });
465
+ return { start, end };
466
+ };
467
+ };
468
+ }
469
+
106
470
  // src/box-impostor/box-impostor-surface-search.js
107
- function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
471
+ function refineSurfaceCrossing({ float: float5, If: If5, Loop: Loop3 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
108
472
  const a = lo.toVar(), b = hi.toVar(), fa = loValue.toVar(), fb = secant ? hiValue.toVar() : null;
109
- Loop2(steps, () => {
473
+ Loop3(steps, () => {
110
474
  const mid = a.add(b).mul(0.5).toVar(), d = height(mid).toVar();
111
- If4(d.mul(fa).greaterThan(0), () => {
475
+ If5(d.mul(fa).greaterThan(0), () => {
112
476
  a.assign(mid);
113
477
  if (secant) fa.assign(d);
114
478
  }).Else(() => {
@@ -122,21 +486,21 @@ function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi
122
486
  // src/box-impostor/box-impostor-faces.js
123
487
  import { DataTexture, FloatType, RGBAFormat, NearestFilter } from "three";
124
488
  import {
125
- Fn as Fn2,
126
- If,
489
+ Fn as Fn3,
490
+ If as If2,
127
491
  attribute,
128
492
  positionLocal,
129
493
  uv,
130
494
  texture,
131
- textureLoad,
132
- ivec2,
133
- vec2,
134
- vec3,
135
- float,
136
- int,
495
+ textureLoad as textureLoad2,
496
+ ivec2 as ivec22,
497
+ vec2 as vec22,
498
+ vec3 as vec32,
499
+ float as float2,
500
+ int as int2,
137
501
  dot,
138
502
  abs,
139
- max,
503
+ max as max2,
140
504
  sign,
141
505
  transformNormalToView
142
506
  } from "three/tsl";
@@ -183,16 +547,6 @@ function boxDepthMode(descriptor, settings) {
183
547
  ) ? "projection" : "depth";
184
548
  }
185
549
 
186
- // src/box-impostor/box-impostor-face-axes.js
187
- var BOX_FACE_AXES = Object.freeze([
188
- { normal: [1, 0, 0], right: [0, 0, -1], up: [0, 1, 0] },
189
- { normal: [-1, 0, 0], right: [0, 0, 1], up: [0, 1, 0] },
190
- { normal: [0, 1, 0], right: [1, 0, 0], up: [0, 0, -1] },
191
- { normal: [0, -1, 0], right: [1, 0, 0], up: [0, 0, 1] },
192
- { normal: [0, 0, 1], right: [1, 0, 0], up: [0, 1, 0] },
193
- { normal: [0, 0, -1], right: [-1, 0, 0], up: [0, 1, 0] }
194
- ]);
195
-
196
550
  // src/box-impostor/box-impostor-metadata.js
197
551
  var BOX_OCCUPANCY_RESOLUTION = 8;
198
552
  var BOX_OCCUPANCY_WORDS = BOX_OCCUPANCY_RESOLUTION ** 3 / 32;
@@ -223,11 +577,11 @@ function applyBoxFaces({
223
577
  planes.minFilter = planes.magFilter = NearestFilter;
224
578
  planes.needsUpdate = true;
225
579
  material.addEventListener("dispose", () => planes.dispose());
226
- const face = int(attribute("boxFace", "float"));
580
+ const face = int2(attribute("boxFace", "float"));
227
581
  const n = attribute("normal", "vec3");
228
- const depth = textureLoad(
582
+ const depth = textureLoad2(
229
583
  planes,
230
- ivec2(face, int(attribute("boxId", "float")))
584
+ ivec22(face, int2(attribute("boxId", "float")))
231
585
  ).r;
232
586
  const proxy = positionLocal.sub(
233
587
  n.mul(
@@ -238,28 +592,28 @@ function applyBoxFaces({
238
592
  material.castShadowPositionNode = proxy;
239
593
  const base = texture(maps.baseColor, uv()).level(0).toVar("boxFaceColor");
240
594
  const orm = texture(maps.orm, uv()).level(0);
241
- const coverage = max(orm.a, 1e-10);
242
- const normal = Fn2(() => {
243
- const packed = textureLoad(
595
+ const coverage = max2(orm.a, 1e-10);
596
+ const normal = Fn3(() => {
597
+ const packed = textureLoad2(
244
598
  maps.normalDepth,
245
- ivec2(uv().mul(descriptor.atlasResolution))
599
+ ivec22(uv().mul(descriptor.atlasResolution))
246
600
  ).rg.mul(2).sub(1);
247
- const decoded = vec3(
601
+ const decoded = vec32(
248
602
  packed,
249
- float(1).sub(abs(packed.x)).sub(abs(packed.y))
603
+ float2(1).sub(abs(packed.x)).sub(abs(packed.y))
250
604
  ).toVar();
251
- If(decoded.z.lessThan(0), () => {
605
+ If2(decoded.z.lessThan(0), () => {
252
606
  decoded.xy.assign(
253
- vec2(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
607
+ vec22(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
254
608
  );
255
609
  });
256
- const result = vec3(0).toVar();
610
+ const result = vec32(0).toVar();
257
611
  for (let f = 0; f < 6; f++) {
258
612
  const a = BOX_FACE_AXES[f];
259
- If(face.equal(f), () => {
613
+ If2(face.equal(f), () => {
260
614
  result.assign(
261
615
  fromBox(
262
- vec3(...a.right).mul(decoded.x).add(vec3(...a.up).mul(decoded.y)).add(vec3(...a.normal).mul(decoded.z))
616
+ vec32(...a.right).mul(decoded.x).add(vec32(...a.up).mul(decoded.y)).add(vec32(...a.normal).mul(decoded.z))
263
617
  ).normalize()
264
618
  );
265
619
  });
@@ -273,7 +627,7 @@ function applyBoxFaces({
273
627
  material.aoNode = orm.r.div(coverage);
274
628
  material.emissiveNode = texture(maps.emissive, uv()).level(0).rgb.div(coverage);
275
629
  material.maskNode = base.a.greaterThanEqual(
276
- transparency === "cutout" ? alphaCutoff : float(1 / 255)
630
+ transparency === "cutout" ? alphaCutoff : float2(1 / 255)
277
631
  );
278
632
  material.maskShadowNode = material.maskNode;
279
633
  if (transparency !== "cutout") material.opacityNode = base.a;
@@ -284,21 +638,21 @@ function applyBoxFaces({
284
638
  // src/box-impostor/box-impostor-projection.js
285
639
  import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter as NearestFilter2 } from "three";
286
640
  import {
287
- Fn as Fn3,
288
- If as If2,
289
- vec2 as vec22,
290
- vec3 as vec32,
291
- vec4 as vec43,
292
- float as float2,
293
- int as int2,
294
- ivec2 as ivec22,
641
+ Fn as Fn4,
642
+ If as If3,
643
+ vec2 as vec23,
644
+ vec3 as vec33,
645
+ vec4 as vec44,
646
+ float as float3,
647
+ int as int3,
648
+ ivec2 as ivec23,
295
649
  dot as dot2,
296
650
  abs as abs2,
297
- max as max2,
651
+ max as max3,
298
652
  sign as sign2,
299
653
  normalize,
300
654
  texture as texture2,
301
- textureLoad as textureLoad2,
655
+ textureLoad as textureLoad3,
302
656
  attribute as attribute2,
303
657
  struct,
304
658
  modelWorldMatrix as modelWorldMatrix2,
@@ -348,24 +702,24 @@ function applyBoxProjection({
348
702
  "BoxProjectedSurface"
349
703
  );
350
704
  const readNormal = (uv2, right, up, n) => {
351
- const packed = textureLoad2(
705
+ const packed = textureLoad3(
352
706
  maps.normalDepth,
353
- ivec22(uv2.mul(descriptor.atlasResolution))
707
+ ivec23(uv2.mul(descriptor.atlasResolution))
354
708
  ).rg.mul(2).sub(1);
355
- const decoded = vec32(
709
+ const decoded = vec33(
356
710
  packed,
357
- float2(1).sub(abs2(packed.x)).sub(abs2(packed.y))
711
+ float3(1).sub(abs2(packed.x)).sub(abs2(packed.y))
358
712
  ).toVar();
359
- If2(decoded.z.lessThan(0), () => {
713
+ If3(decoded.z.lessThan(0), () => {
360
714
  decoded.xy.assign(
361
- vec22(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
715
+ vec23(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
362
716
  );
363
717
  });
364
718
  return fromBox(
365
719
  right.mul(decoded.x).add(up.mul(decoded.y)).add(n.mul(decoded.z))
366
720
  ).normalize();
367
721
  };
368
- const surface = Fn3(() => {
722
+ const surface = Fn4(() => {
369
723
  const ray = perspective.select(
370
724
  normalize(raster.sub(eye)),
371
725
  viewAxis.negate()
@@ -376,48 +730,48 @@ function applyBoxProjection({
376
730
  );
377
731
  const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
378
732
  const look = normalize(toBox(ray).negate()), angles = abs2(look);
379
- const positions = vec32(0).toVar();
380
- const selectedUv = vec22(0).toVar(), selectedRight = vec32(1, 0, 0).toVar(), selectedUp = vec32(0, 1, 0).toVar(), selectedNormal = vec32(0, 0, 1).toVar();
381
- const nearest = float2(1e20).toVar("boxPlaneDistance");
382
- const opacity = float2(0).toVar();
733
+ const positions = vec33(0).toVar();
734
+ const selectedUv = vec23(0).toVar(), selectedRight = vec33(1, 0, 0).toVar(), selectedUp = vec33(0, 1, 0).toVar(), selectedNormal = vec33(0, 0, 1).toVar();
735
+ const nearest = float3(1e20).toVar("boxPlaneDistance");
736
+ const opacity = float3(0).toVar();
383
737
  const candidates = [];
384
738
  for (let axis = 0; axis < 3; axis++) {
385
739
  const angle = angles.element(axis);
386
740
  const positive = look.element(axis).greaterThanEqual(0), a = BOX_FACE_AXES[axis * 2], b = BOX_FACE_AXES[axis * 2 + 1];
387
- 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));
741
+ const n = positive.select(vec33(...a.normal), vec33(...b.normal)), right = positive.select(vec33(...a.right), vec33(...b.right)), up = positive.select(vec33(...a.up), vec33(...b.up));
388
742
  const weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
389
743
  const candidate = settings.interpolation === "none" ? null : {
390
- uv: vec22(0).toVar(),
391
- base: vec43(0).toVar(),
392
- orm: vec43(0).toVar(),
393
- t: float2(1e20).toVar(),
394
- tolerance: float2(0).toVar(),
744
+ uv: vec23(0).toVar(),
745
+ base: vec44(0).toVar(),
746
+ orm: vec44(0).toVar(),
747
+ t: float3(1e20).toVar(),
748
+ tolerance: float3(0).toVar(),
395
749
  right,
396
750
  up,
397
751
  n,
398
752
  weight
399
753
  };
400
754
  if (candidate) candidates.push(candidate);
401
- If2(angle.greaterThan(1e-4), () => {
402
- const face = positive.select(int2(axis * 2), int2(axis * 2 + 1)), id = int2(attribute2("boxId", "float"));
403
- const plane = float2(1).sub(
404
- textureLoad2(planes, ivec22(face, id)).r.mul(2)
755
+ If3(angle.greaterThan(1e-4), () => {
756
+ const face = positive.select(int3(axis * 2), int3(axis * 2 + 1)), id = int3(attribute2("boxId", "float"));
757
+ const plane = float3(1).sub(
758
+ textureLoad3(planes, ivec23(face, id)).r.mul(2)
405
759
  );
406
- const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max2(abs2(divisor2), 1e-10));
760
+ const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max3(abs2(divisor2), 1e-10));
407
761
  const t = plane.sub(dot2(o, n)).div(safe), point = o.add(r.mul(t));
408
- const xy = vec22(dot2(point, right), dot2(point, up)).mul(0.5).add(0.5);
762
+ const xy = vec23(dot2(point, right), dot2(point, up)).mul(0.5).add(0.5);
409
763
  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));
410
764
  if (!candidate) supported = supported.and(t.lessThan(nearest));
411
- If2(supported, () => {
412
- const rect = textureLoad2(rects, ivec22(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
765
+ If3(supported, () => {
766
+ const rect = textureLoad3(rects, ivec23(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
413
767
  const base = texture2(maps.baseColor, uv2).level(0), orm = texture2(maps.orm, uv2).level(0);
414
768
  const alpha2 = base.a.clamp(0, 1);
415
- If2(
769
+ If3(
416
770
  alpha2.greaterThanEqual(
417
- transparency === "cutout" ? alphaCutoff : float2(1 / 255)
771
+ transparency === "cutout" ? alphaCutoff : float3(1 / 255)
418
772
  ).and(orm.a.greaterThan(0)),
419
773
  () => {
420
- If2(t.lessThan(nearest), () => {
774
+ If3(t.lessThan(nearest), () => {
421
775
  nearest.assign(t);
422
776
  selectedUv.assign(uv2);
423
777
  opacity.assign(alpha2);
@@ -432,14 +786,14 @@ function applyBoxProjection({
432
786
  candidate.orm.assign(orm);
433
787
  candidate.t.assign(t);
434
788
  candidate.tolerance.assign(
435
- max2(
789
+ max3(
436
790
  dot2(abs2(right), half).div(
437
791
  rect.z.mul(descriptor.atlasResolution)
438
792
  ),
439
793
  dot2(abs2(up), half).div(
440
794
  rect.w.mul(descriptor.atlasResolution)
441
795
  )
442
- ).mul(4).div(max2(angle, 0.1))
796
+ ).mul(4).div(max3(angle, 0.1))
443
797
  );
444
798
  }
445
799
  }
@@ -449,7 +803,7 @@ function applyBoxProjection({
449
803
  }
450
804
  if (settings.interpolation === "none") {
451
805
  const base = texture2(maps.baseColor, selectedUv).level(0), orm = texture2(maps.orm, selectedUv).level(0);
452
- const coverage = max2(orm.a, 1e-10);
806
+ const coverage = max3(orm.a, 1e-10);
453
807
  return Surface(
454
808
  base.rgb.div(coverage),
455
809
  opacity,
@@ -459,15 +813,15 @@ function applyBoxProjection({
459
813
  positions
460
814
  );
461
815
  }
462
- const colors = vec32(0).toVar(), orms = vec32(0).toVar(), emissions = vec32(0).toVar(), normals = vec32(0).toVar();
463
- const weights = float2(0).toVar(), support = float2(0).toVar(), alpha = float2(0).toVar();
816
+ const colors = vec33(0).toVar(), orms = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar();
817
+ const weights = float3(0).toVar(), support = float3(0).toVar(), alpha = float3(0).toVar();
464
818
  for (const c of candidates) {
465
- If2(
819
+ If3(
466
820
  c.base.a.greaterThan(0).and(c.t.lessThanEqual(nearest.add(c.tolerance))),
467
821
  () => {
468
- const coverage = max2(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
822
+ const coverage = max3(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
469
823
  weights.addAssign(c.weight.mul(coverage));
470
- support.assign(max2(support, coverage));
824
+ support.assign(max3(support, coverage));
471
825
  colors.addAssign(c.base.rgb.div(coverage).mul(w));
472
826
  orms.addAssign(c.orm.rgb.div(coverage).mul(w));
473
827
  emissions.addAssign(
@@ -478,13 +832,13 @@ function applyBoxProjection({
478
832
  }
479
833
  );
480
834
  }
481
- const divisor = max2(alpha, 1e-10);
835
+ const divisor = max3(alpha, 1e-10);
482
836
  return Surface(
483
837
  colors.div(divisor),
484
- alpha.div(max2(weights, 1e-10)).mul(support),
838
+ alpha.div(max3(weights, 1e-10)).mul(support),
485
839
  orms.div(divisor),
486
840
  emissions.div(divisor),
487
- normals.div(max2(normals.length(), 1e-10)),
841
+ normals.div(max3(normals.length(), 1e-10)),
488
842
  positions
489
843
  );
490
844
  })().toVar("boxProjectedSurface");
@@ -495,12 +849,12 @@ function applyBoxProjection({
495
849
  material.metalnessNode = surface.get("orm").b;
496
850
  material.aoNode = surface.get("orm").r;
497
851
  material.emissiveNode = surface.get("emission");
498
- material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float2(1 / 255));
852
+ material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float3(1 / 255));
499
853
  material.maskShadowNode = material.maskNode;
500
854
  if (transparency !== "cutout") material.opacityNode = surface.get("alpha");
501
855
  material.depthNode = capturedSurfaceDepth(surface.get("position"));
502
856
  material.receivedShadowPositionNode = modelWorldMatrix2.mul(
503
- vec43(surface.get("position"), 1)
857
+ vec44(surface.get("position"), 1)
504
858
  ).xyz;
505
859
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
506
860
  return material;
@@ -510,39 +864,40 @@ function applyBoxProjection({
510
864
  function createBoxImpostorMaterial(descriptor, maps) {
511
865
  return createBoxImpostorMaterialVariant(descriptor, maps, { filtering: true });
512
866
  }
513
- function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false } = {}) {
867
+ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false, boundSearch = true } = {}) {
514
868
  const settings = normalizeBoxImpostorDisplay(descriptor);
515
869
  const alphaCutoff = uniform(settings.alphaCutoff);
516
870
  const transparency = boxTransparency(descriptor, settings);
517
- const minimumAlpha = transparency === "cutout" ? alphaCutoff : float3(1 / 255);
518
- const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min(ormAlpha, baseAlpha) : ormAlpha;
519
- const decodeNormal = (encoded) => {
871
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float4(1 / 255);
872
+ const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min2(ormAlpha, baseAlpha) : ormAlpha;
873
+ const unpackNormal = (encoded) => {
520
874
  const packed = encoded.mul(2).sub(1);
521
- const normal2 = vec33(packed, float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
522
- If3(normal2.z.lessThan(0), () => {
523
- normal2.xy.assign(vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
875
+ const normal2 = vec34(packed, float4(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
876
+ If4(normal2.z.lessThan(0), () => {
877
+ normal2.xy.assign(vec24(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
524
878
  });
525
- return normal2.normalize();
879
+ return normal2;
526
880
  };
881
+ const decodeNormal = (encoded) => unpackNormal(encoded).normalize();
527
882
  const filteredNormal = (uv2, depth, tolerance, nearest, alpha, sampled = texture3(maps.normalDepth, uv2).level(0), ormAlpha = texture3(maps.orm, uv2).level(0).a) => {
528
883
  sampled = sampled.toVar();
529
- const coverage2 = max3(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
884
+ const coverage2 = max4(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
530
885
  const nearestNormal = decodeNormal(nearest.rg), result = decodeNormal(sampled.rg.div(coverage2)).toVar();
531
886
  const sampledDepth = sampled.b.mul(65280).add(sampled.a.mul(255)).div(65535);
532
887
  const nearestDepth = nearest.b.mul(65280).add(nearest.a.mul(255)).div(65535);
533
- If3(nearestNormal.z.lessThan(0).or(dot3(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
534
- const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor(p), f = fract(p);
535
- const normal2 = vec33(0).toVar(), weights = float3(0).toVar();
888
+ If4(nearestNormal.z.lessThan(0).or(dot3(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
889
+ const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor2(p), f = fract(p);
890
+ const normal2 = vec34(0).toVar(), weights = float4(0).toVar();
536
891
  for (const [x, y] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
537
- const texel = ivec23(lo.add(vec23(x, y)).clamp(0, descriptor.atlasResolution - 1));
538
- const packed = textureLoad3(maps.normalDepth, texel).toVar();
539
- const alpha2 = textureLoad3(maps.baseColor, texel).a;
540
- const coverage3 = descriptor.alphaMode === "blend" ? textureLoad3(maps.orm, texel).a : alpha2;
892
+ const texel = ivec24(lo.add(vec24(x, y)).clamp(0, descriptor.atlasResolution - 1));
893
+ const packed = textureLoad4(maps.normalDepth, texel).toVar();
894
+ const alpha2 = textureLoad4(maps.baseColor, texel).a;
895
+ const coverage3 = descriptor.alphaMode === "blend" ? textureLoad4(maps.orm, texel).a : alpha2;
541
896
  const capturedDepth = packed.b.mul(65280).add(packed.a.mul(255)).div(65535);
542
897
  const supported = coverage3.greaterThan(1e-4).and(alpha2.greaterThanEqual(minimumAlpha.mul(coverage3))).and(abs3(capturedDepth.sub(depth)).lessThanEqual(tolerance));
543
- If3(supported, () => {
544
- const weight = (x ? f.x : float3(1).sub(f.x)).mul(y ? f.y : float3(1).sub(f.y)).mul(coverage3);
545
- normal2.addAssign(decodeNormal(packed.rg.div(max3(coverage3, 1e-10))).mul(weight));
898
+ If4(supported, () => {
899
+ const weight = (x ? f.x : float4(1).sub(f.x)).mul(y ? f.y : float4(1).sub(f.y)).mul(coverage3);
900
+ normal2.addAssign(decodeNormal(packed.rg.div(max4(coverage3, 1e-10))).mul(weight));
546
901
  weights.addAssign(weight);
547
902
  });
548
903
  }
@@ -591,36 +946,36 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
591
946
  material.addEventListener("dispose", () => rects.dispose());
592
947
  const center = attribute3("boxCenter", "vec3"), half = attribute3("boxHalfSize", "vec3");
593
948
  const ax = attribute3("boxAxisX", "vec3"), ay = attribute3("boxAxisY", "vec3"), az = attribute3("boxAxisZ", "vec3");
594
- const toBox = (p) => vec33(dot3(p, ax), dot3(p, ay), dot3(p, az));
949
+ const toBox = (p) => vec34(dot3(p, ax), dot3(p, ay), dot3(p, az));
595
950
  const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
596
- const eye = modelWorldMatrixInverse.mul(vec44(cameraPosition, 1)).xyz;
597
- const viewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 0, 1, 0))).xyz.normalize();
951
+ const eye = modelWorldMatrixInverse.mul(vec45(cameraPosition, 1)).xyz;
952
+ const viewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec45(0, 0, 1, 0))).xyz.normalize();
598
953
  const perspective = cameraProjectionMatrix2.element(3).w.equal(0);
599
954
  let proxy = positionLocal2;
600
955
  if (descriptor.mode !== "fitted") {
601
- proxy = Fn4((_, builder) => {
956
+ proxy = Fn5((_, builder) => {
602
957
  const delta = eye.sub(center);
603
958
  const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize2(delta), viewAxis);
604
- const right = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 1, 0, 0))).xyz.cross(forward).normalize();
959
+ const right = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec45(0, 1, 0, 0))).xyz.cross(forward).normalize();
605
960
  const up = forward.cross(right).normalize();
606
961
  const radius = half.length();
607
962
  const distance = dot3(eye.sub(center), forward);
608
- const planeOffset = perspective.select(min(radius, distance.sub(cameraNear2.mul(2))), radius);
963
+ const planeOffset = perspective.select(min2(radius, distance.sub(cameraNear2.mul(2))), radius);
609
964
  const plane = center.add(forward.mul(planeOffset));
610
- const lo = vec23(1e20).toVar(), hi = vec23(-1e20).toVar();
965
+ const lo = vec24(1e20).toVar(), hi = vec24(-1e20).toVar();
611
966
  for (const x of [-1, 1])
612
967
  for (const y of [-1, 1])
613
968
  for (const z of [-1, 1]) {
614
- const corner2 = fromBox(half.mul(vec33(x, y, z)));
969
+ const corner2 = fromBox(half.mul(vec34(x, y, z)));
615
970
  const scale = perspective.select(
616
- max3(distance.sub(planeOffset), 1e-5).div(
617
- max3(distance.sub(dot3(corner2, forward)), 1e-5)
971
+ max4(distance.sub(planeOffset), 1e-5).div(
972
+ max4(distance.sub(dot3(corner2, forward)), 1e-5)
618
973
  ),
619
- float3(1)
974
+ float4(1)
620
975
  );
621
- const p = vec23(dot3(corner2, right), dot3(corner2, up)).mul(scale);
622
- lo.assign(min(lo, p));
623
- hi.assign(max3(hi, p));
976
+ const p = vec24(dot3(corner2, right), dot3(corner2, up)).mul(scale);
977
+ lo.assign(min2(lo, p));
978
+ hi.assign(max4(hi, p));
624
979
  }
625
980
  const corner = attribute3("cardCorner", "vec2").add(1).mul(0.5);
626
981
  const xy = lo.add(hi.sub(lo).mul(corner));
@@ -682,53 +1037,66 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
682
1037
  occupancy.needsUpdate = true;
683
1038
  material.addEventListener("dispose", () => occupancy.dispose());
684
1039
  }
1040
+ const preferFacingCapture = filtering && descriptor.alphaMode === "opaque" && settings.interpolation === "none";
1041
+ const viewBounds = boundSearch ? createBoxRayBounds(descriptor, maps, rects, material) : null;
685
1042
  const Result = struct2(
686
- { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
1043
+ { uv: "vec2", position: "vec3", face: "int", valid: "float" },
687
1044
  "BoxImpostorHit"
688
1045
  );
689
- const raycast = Fn4((_, builder) => {
690
- const ray = perspective.select(
691
- normalize2(raster.sub(eye)),
692
- viewAxis.negate()
693
- );
1046
+ const faceBasis = (axis, facing) => {
1047
+ const n = vec34(
1048
+ axis.equal(0).select(facing, 0),
1049
+ axis.equal(1).select(facing, 0),
1050
+ axis.equal(2).select(facing, 0)
1051
+ ).toVar();
1052
+ const right = axis.equal(0).select(
1053
+ vec34(0, 0, facing.negate()),
1054
+ axis.equal(1).select(vec34(1, 0, 0), vec34(facing, 0, 0))
1055
+ ).toVar();
1056
+ const up = axis.equal(1).select(vec34(0, 0, facing.negate()), vec34(0, 1, 0)).toVar();
1057
+ return { n, right, up };
1058
+ };
1059
+ const ray = perspective.select(normalize2(raster.sub(eye)), viewAxis.negate());
1060
+ const raycast = Fn5((_, builder) => {
694
1061
  const origin = perspective.select(
695
1062
  eye,
696
1063
  raster.sub(ray.mul(half.length().mul(4)))
697
1064
  );
698
1065
  const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
699
- const safe = sign3(r.add(1e-20)).mul(max3(abs3(r), 1e-10));
700
- const a = vec33(-1).sub(o).div(safe), b = vec33(1).sub(o).div(safe);
701
- const enter = max3(max3(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
702
- const exit = min(min(max3(a, b).x, max3(a, b).y), max3(a, b).z);
1066
+ const safe = sign3(r.add(1e-20)).mul(max4(abs3(r), 1e-10));
1067
+ const a = vec34(-1).sub(o).div(safe), b = vec34(1).sub(o).div(safe);
1068
+ const enter = max4(max4(min2(a, b).x, min2(a, b).y), min2(a, b).z).max(0);
1069
+ const exit = min2(min2(max4(a, b).x, max4(a, b).y), max4(a, b).z);
1070
+ const rayBounds = viewBounds?.(builder, int4(attribute3("boxId", "float")), o, r, enter, exit);
703
1071
  const occupiedStart = enter.toVar();
704
1072
  if (occupancy) {
705
1073
  const gridOrigin = o.add(1).mul(gridSize / 2);
706
1074
  const gridRay = r.mul(gridSize / 2);
707
1075
  const step = sign3(gridRay.add(1e-20));
708
- const cell = floor(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
709
- const inverse = vec33(1).div(safe.mul(gridSize / 2));
1076
+ const cell = floor2(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
1077
+ const inverse = vec34(1).div(safe.mul(gridSize / 2));
710
1078
  const delta = abs3(inverse);
711
1079
  const next = cell.add(step.add(1).mul(0.5)).sub(gridOrigin).mul(inverse).toVar();
712
1080
  const t = enter.toVar();
713
1081
  occupiedStart.assign(exit.add(1));
714
- Loop(gridSize * 3 + 1, () => {
715
- If3(t.greaterThan(exit), () => {
1082
+ Loop2(gridSize * 3 + 1, () => {
1083
+ If4(t.greaterThan(exit), () => {
716
1084
  Break();
717
1085
  });
718
- const cellIndex = uint(
1086
+ const cellIndex = uint2(
719
1087
  cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2))
720
1088
  ).toVar();
721
- const word = textureLoad3(
1089
+ const word = textureLoad4(
722
1090
  occupancy,
723
- ivec23(int3(cellIndex.shiftRight(5)), int3(attribute3("boxId", "float")))
1091
+ ivec24(int4(cellIndex.shiftRight(5)), int4(attribute3("boxId", "float")))
724
1092
  ).r;
725
1093
  const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
726
- If3(support.notEqual(uint(0)), () => {
1094
+ If4(support.notEqual(uint2(0)), () => {
727
1095
  occupiedStart.assign(t);
728
1096
  Break();
729
1097
  });
730
- const edge = min(min(next.x, next.y), next.z).toVar();
731
- const advance = vec33(
1098
+ const edge = min2(min2(next.x, next.y), next.z).toVar();
1099
+ const advance = vec34(
732
1100
  next.x.lessThanEqual(edge).select(1, 0),
733
1101
  next.y.lessThanEqual(edge).select(1, 0),
734
1102
  next.z.lessThanEqual(edge).select(1, 0)
@@ -736,7 +1104,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
736
1104
  cell.addAssign(advance.mul(step));
737
1105
  next.addAssign(advance.mul(delta));
738
1106
  t.assign(edge);
739
- If3(
1107
+ If4(
740
1108
  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)),
741
1109
  () => {
742
1110
  Break();
@@ -745,19 +1113,19 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
745
1113
  });
746
1114
  }
747
1115
  const look = toBox(ray).negate();
748
- const bestT = exit.add(1).toVar(), bestUv = vec23(0).toVar(), bestNormal = vec33(0, 0, 1).toVar(), valid = float3(0).toVar(), found = float3(0).toVar();
1116
+ const bestT = exit.add(1).toVar(), bestUv = vec24(0).toVar(), bestFace = int4(0).toVar(), appearanceNear = preferFacingCapture ? float4(0).toVar() : null, valid = float4(0).toVar(), found = float4(0).toVar();
749
1117
  const angles = abs3(look).toVar();
750
1118
  const major = angles.x.greaterThanEqual(angles.y).and(angles.x.greaterThanEqual(angles.z)).select(
751
- int3(0),
752
- angles.y.greaterThanEqual(angles.z).select(int3(1), int3(2))
1119
+ int4(0),
1120
+ angles.y.greaterThanEqual(angles.z).select(int4(1), int4(2))
753
1121
  ).toVar();
754
1122
  const nextAxis = major.add(1).mod(3), lastAxis = major.add(2).mod(3);
755
1123
  const second = angles.element(nextAxis).greaterThanEqual(angles.element(lastAxis)).select(nextAxis, lastAxis).toVar();
756
- const third = int3(3).sub(major).sub(second).toVar();
757
- Loop(
1124
+ const third = int4(3).sub(major).sub(second).toVar();
1125
+ Loop2(
758
1126
  { start: 0, end: 6, type: "int", name: "viewIndex" },
759
1127
  ({ viewIndex: i }) => {
760
- If3(occupiedStart.greaterThan(exit), () => {
1128
+ If4(occupiedStart.greaterThan(exit), () => {
761
1129
  Break();
762
1130
  });
763
1131
  valid.assign(0);
@@ -767,112 +1135,133 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
767
1135
  look.element(axis).greaterThanEqual(0),
768
1136
  look.element(axis).lessThan(0)
769
1137
  );
770
- const face = axis.mul(2).add(positive.select(int3(0), int3(1)));
1138
+ const face = axis.mul(2).add(positive.select(int4(0), int4(1)));
1139
+ const bounds = rayBounds?.(face, enter, exit);
771
1140
  const facing = positive.select(1, -1);
772
- const n = vec33(
773
- axis.equal(0).select(facing, 0),
774
- axis.equal(1).select(facing, 0),
775
- axis.equal(2).select(facing, 0)
776
- ).toVar();
777
- const right = axis.equal(0).select(
778
- vec33(0, 0, facing.negate()),
779
- axis.equal(1).select(vec33(1, 0, 0), vec33(facing, 0, 0))
780
- ).toVar();
781
- const up = axis.equal(1).select(vec33(0, 0, facing.negate()), vec33(0, 1, 0)).toVar();
1141
+ const { n, right, up } = faceBasis(axis, facing);
782
1142
  const direction = i.lessThan(3).select(1, -1);
783
- const rect = textureLoad3(
1143
+ const rect = textureLoad4(
784
1144
  rects,
785
- ivec23(face, int3(attribute3("boxId", "float")))
1145
+ ivec24(face, int4(attribute3("boxId", "float")))
786
1146
  ).toVar();
787
1147
  const sampleUv = (p) => rect.xy.add(
788
- vec23(dot3(p, right), dot3(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1148
+ vec24(dot3(p, right), dot3(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
789
1149
  );
790
1150
  const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
791
1151
  const depthAt = (uv2) => decode(texture3(maps.normalDepth, uv2).level(0));
1152
+ const projectedOrigin = vec24(dot3(o, right), dot3(o, up)).toVar();
1153
+ const projectedRay = vec24(dot3(r, right), dot3(r, up)).toVar();
1154
+ const axialOrigin = dot3(o, n).toVar();
1155
+ const axialRay = dot3(r, n).toVar();
792
1156
  const distance = (t) => {
793
- const p = o.add(r.mul(t));
794
- return dot3(p, n).sub(float3(1).sub(depthAt(sampleUv(p)).mul(2))).mul(direction);
1157
+ const uv2 = rect.xy.add(
1158
+ projectedOrigin.add(projectedRay.mul(t)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1159
+ );
1160
+ return axialOrigin.add(axialRay.mul(t)).sub(float4(1).sub(depthAt(uv2).mul(2))).mul(direction);
795
1161
  };
796
1162
  const acceptHit = (hitT) => {
797
1163
  const point2 = o.add(r.mul(hitT)), uv2 = sampleUv(point2);
798
- const texel = ivec23(uv2.mul(descriptor.atlasResolution));
799
- const nearest = textureLoad3(maps.normalDepth, texel);
1164
+ const texel = ivec24(uv2.mul(descriptor.atlasResolution));
1165
+ const nearest = textureLoad4(maps.normalDepth, texel);
800
1166
  const capturedBase = texture3(maps.baseColor, uv2).level(0);
801
- const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1167
+ const occupied = textureLoad4(maps.orm, texel).a.greaterThan(0.5);
802
1168
  const residual = abs3(
803
- dot3(point2, n).sub(float3(1).sub(decode(nearest).mul(2)))
1169
+ dot3(point2, n).sub(float4(1).sub(decode(nearest).mul(2)))
804
1170
  );
805
- const tolerance = max3(
1171
+ const tolerance = max4(
806
1172
  dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
807
1173
  dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
808
1174
  ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
809
- If3(
1175
+ If4(
810
1176
  residual.lessThanEqual(tolerance).and(occupied).and(
811
1177
  capturedBase.a.greaterThanEqual(minimumAlpha)
812
1178
  ),
813
1179
  () => {
814
1180
  valid.assign(1);
815
- If3(hitT.lessThan(bestT), () => {
1181
+ If4(hitT.lessThan(bestT), () => {
816
1182
  bestT.assign(hitT);
817
- bestUv.assign(uv2);
818
- found.assign(1);
819
- 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);
820
- const normal2 = vec33(
821
- packed.x,
822
- packed.y,
823
- float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
824
- ).toVar();
825
- If3(normal2.z.lessThan(0), () => {
826
- normal2.xy.assign(
827
- vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20)))
1183
+ const useAppearance = () => {
1184
+ bestUv.assign(uv2);
1185
+ bestFace.assign(face);
1186
+ };
1187
+ if (preferFacingCapture) {
1188
+ const texel2 = max4(
1189
+ dot3(abs3(right), half).div(rect.z),
1190
+ dot3(abs3(up), half).div(rect.w)
1191
+ ).div(descriptor.atlasResolution);
1192
+ const uncertainty = min2(
1193
+ texel2,
1194
+ residual.add(2 / 65535).div(abs3(axialRay).max(1e-10))
828
1195
  );
829
- });
830
- bestNormal.assign(
831
- fromBox(
832
- right.mul(normal2.x).add(up.mul(normal2.y)).add(n.mul(normal2.z))
833
- ).normalize()
834
- );
835
- bestNormal.mulAssign(
836
- dot3(bestNormal, ray).greaterThan(0).select(-1, 1)
837
- );
1196
+ If4(found.lessThan(0.5).or(hitT.add(uncertainty).lessThan(appearanceNear)), () => {
1197
+ appearanceNear.assign(hitT.sub(uncertainty));
1198
+ useAppearance();
1199
+ });
1200
+ } else useAppearance();
1201
+ found.assign(1);
838
1202
  });
839
1203
  }
840
1204
  );
841
1205
  };
842
1206
  const traceInterval = (start, end, steps) => {
843
- const footprint = vec23(dot3(r, right), dot3(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
844
- const samples = max3(float3(steps), max3(footprint.x, footprint.y).mul(steps / 8)).div(2).ceil().mul(2).toVar();
845
- const step = end.sub(start).div(samples);
846
- const previous = start.toVar(), previousD = distance(start).toVar();
847
- If3(previousD.lessThanEqual(0), () => {
1207
+ const footprint = vec24(dot3(r, right), dot3(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
1208
+ let density = steps / 8;
1209
+ if (descriptor.alphaMode === "blend" && transparency === "blended" && steps < 32) {
1210
+ density = i.equal(0).select(steps / 16, steps / 32);
1211
+ } else if (descriptor.alphaMode === "opaque" && steps === 16) {
1212
+ density = found.greaterThan(0.5).select(1, 2);
1213
+ }
1214
+ const samples = max4(float4(steps), max4(footprint.x, footprint.y).mul(density)).div(2).ceil().mul(2).toVar();
1215
+ const step = end.sub(start).div(samples).toVar();
1216
+ const pairs = int4(samples.div(2));
1217
+ const pairAt = (t) => t.sub(start).div(max4(step.mul(2), 1e-15));
1218
+ const firstPair = bounds ? int4(floor2(pairAt(bounds.start))).clamp(0, pairs).toVar() : int4(0);
1219
+ const lastPair = bounds ? int4(pairAt(bounds.end).ceil()).clamp(0, pairs).toVar() : pairs;
1220
+ const previous = start.toVar();
1221
+ if (bounds) If4(firstPair.greaterThan(0), () => {
1222
+ previous.assign(start.add(step.mul(float4(firstPair.mul(2)))));
1223
+ });
1224
+ const previousD = distance(previous).toVar();
1225
+ const atEntry = bounds ? firstPair.equal(0).and(start.greaterThanEqual(bounds.start)).and(start.lessThanEqual(bounds.end)) : null;
1226
+ If4(atEntry ? atEntry.and(previousD.lessThanEqual(0)) : previousD.lessThanEqual(0), () => {
848
1227
  acceptHit(start);
849
1228
  });
850
- Loop({ start: int3(0), end: int3(samples.div(2)), type: "int" }, ({ i: i2 }) => {
851
- If3(valid.greaterThan(0.5), () => {
1229
+ Loop2({ start: firstPair, end: lastPair, type: "int" }, ({ i: i2 }) => {
1230
+ If4(valid.greaterThan(0.5).or(previous.greaterThan(bestT)), () => {
852
1231
  Break();
853
1232
  });
854
- const samples2 = [1, 2].map((offset) => {
855
- const t = start.add(step.mul(float3(i2.mul(2).add(offset)))).toVar();
1233
+ const [first, second2] = [1, 2].map((offset) => {
1234
+ const t = start.add(step.mul(float4(i2.mul(2).add(offset)))).toVar();
856
1235
  return { t, d: distance(t).toVar() };
857
1236
  });
858
- for (const { t, d } of samples2) {
859
- If3(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
860
- Break();
861
- });
862
- If3(valid.lessThan(0.5).and(d.mul(previousD).lessThanEqual(0)), () => {
863
- const crossing = refineSurfaceCrossing({ float: float3, If: If3, Loop }, { lo: previous, hi: t, loValue: previousD, hiValue: d, height: distance, steps: 3, secant: true });
864
- acceptHit(crossing);
865
- If3(bestT.lessThanEqual(t), () => {
866
- Break();
1237
+ const crossesFirst = first.d.mul(previousD).lessThanEqual(0);
1238
+ const crossesSecond = second2.d.mul(first.d).lessThanEqual(0);
1239
+ If4(crossesFirst.or(crossesSecond), () => {
1240
+ for (const [{ t, d }, crosses] of [[first, crossesFirst], [second2, crossesSecond]]) {
1241
+ If4(crosses.and(valid.lessThan(0.5)).and(previous.lessThanEqual(bestT)), () => {
1242
+ const crossing = refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, {
1243
+ lo: previous,
1244
+ hi: t,
1245
+ loValue: previousD,
1246
+ hiValue: d,
1247
+ height: distance,
1248
+ steps: 3,
1249
+ secant: true
1250
+ });
1251
+ acceptHit(crossing);
867
1252
  });
868
- });
869
- previous.assign(t);
870
- previousD.assign(d);
871
- }
1253
+ previous.assign(t);
1254
+ previousD.assign(d);
1255
+ }
1256
+ }).Else(() => {
1257
+ previous.assign(second2.t);
1258
+ previousD.assign(second2.d);
1259
+ });
872
1260
  });
873
1261
  };
874
- If3(
875
- exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3)),
1262
+ const supported = exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3));
1263
+ If4(
1264
+ bounds ? supported.and(bounds.start.lessThanEqual(bestT)).and(bounds.end.greaterThanEqual(occupiedStart)) : supported,
876
1265
  () => {
877
1266
  if (!accelerated) {
878
1267
  traceInterval(enter, exit, descriptor.raySteps);
@@ -885,13 +1274,13 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
885
1274
  )
886
1275
  );
887
1276
  const interval = positive.select(depths.xy, depths.zw);
888
- const initialDepth = float3(1).sub(dot3(o, n)).mul(0.5);
1277
+ const initialDepth = float4(1).sub(dot3(o, n)).mul(0.5);
889
1278
  const depthSlope = dot3(r, n).negate().mul(0.5);
890
1279
  const da = interval.x.sub(2 / 65535).sub(initialDepth).div(depthSlope);
891
1280
  const db = interval.y.add(2 / 65535).sub(initialDepth).div(depthSlope);
892
- const start = max3(occupiedStart, min(da, db));
893
- const end = min(min(exit, bestT), max3(da, db));
894
- If3(
1281
+ const start = max4(occupiedStart, min2(da, db));
1282
+ const end = min2(min2(exit, bestT), max4(da, db));
1283
+ If4(
895
1284
  interval.x.lessThanEqual(interval.y).and(end.greaterThanEqual(start)),
896
1285
  () => {
897
1286
  const search = () => traceInterval(start, end, descriptor.raySteps);
@@ -901,12 +1290,12 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
901
1290
  )
902
1291
  );
903
1292
  if (hasFlatView) {
904
- If3(
1293
+ If4(
905
1294
  interval.y.sub(interval.x).lessThanEqual(1 / 65535),
906
1295
  () => {
907
1296
  const t = interval.x.add(interval.y).mul(0.5).sub(initialDepth).div(depthSlope);
908
- If3(
909
- t.greaterThanEqual(enter).and(t.lessThanEqual(min(exit, bestT))),
1297
+ If4(
1298
+ t.greaterThanEqual(enter).and(t.lessThanEqual(min2(exit, bestT))),
910
1299
  () => {
911
1300
  acceptHit(t);
912
1301
  }
@@ -926,57 +1315,65 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
926
1315
  return Result(
927
1316
  bestUv,
928
1317
  center.add(fromBox(point.mul(half))),
929
- bestNormal,
1318
+ bestFace,
930
1319
  valid
931
1320
  );
932
1321
  });
933
1322
  const hit = raycast().toVar("boxHit");
934
1323
  hit.toStack();
935
1324
  const base = texture3(maps.baseColor, hit.get("uv")).level(0), orm = texture3(maps.orm, hit.get("uv")).level(0);
936
- const coverage = max3(surfaceCoverage(orm.a, base.a), 1e-10);
937
- 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");
1325
+ const coverage = max4(surfaceCoverage(orm.a, base.a), 1e-10);
1326
+ const hitNormal = Fn5(() => {
1327
+ const face = hit.get("face");
1328
+ const { n, right, up } = faceBasis(face.div(2), face.mod(2).equal(0).select(1, -1));
1329
+ const sampled = texture3(maps.normalDepth, hit.get("uv")).level(0);
1330
+ const local = unpackNormal(sampled.rg.div(coverage));
1331
+ const direction = fromBox(right.mul(local.x).add(up.mul(local.y)).add(n.mul(local.z))).normalize().toVar();
1332
+ return direction.mul(dot3(direction, ray).greaterThan(0).select(-1, 1));
1333
+ })();
1334
+ let color = base.div(coverage), surfaceOrm = orm.rgb.div(coverage), emission = texture3(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage), normal = hitNormal;
938
1335
  if (settings.interpolation !== "none") {
939
1336
  const fallbackColor = color, fallbackOrm = surfaceOrm, fallbackEmission = emission, fallbackNormal = normal;
940
1337
  const Surface = struct2(
941
1338
  { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
942
1339
  "BoxSurfaceBlend"
943
1340
  );
944
- const blended = Fn4(() => {
1341
+ const blended = Fn5(() => {
945
1342
  const point = toBox(hit.get("position").sub(center)).div(half);
946
1343
  const look = toBox(
947
1344
  perspective.select(normalize2(eye.sub(hit.get("position"))), viewAxis)
948
1345
  );
949
- const colors = vec44(0).toVar(), materials = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar(), weights = float3(0).toVar();
1346
+ const colors = vec45(0).toVar(), materials = vec34(0).toVar(), emissions = vec34(0).toVar(), normals = vec34(0).toVar(), weights = float4(0).toVar();
950
1347
  for (let axis = 0; axis < 3; axis++) {
951
1348
  const positive = look.element(axis).greaterThanEqual(0);
952
1349
  const front = BOX_FACE_AXES[axis * 2], back = BOX_FACE_AXES[axis * 2 + 1];
953
- const n = positive.select(vec33(...front.normal), vec33(...back.normal));
1350
+ const n = positive.select(vec34(...front.normal), vec34(...back.normal));
954
1351
  const right = positive.select(
955
- vec33(...front.right),
956
- vec33(...back.right)
1352
+ vec34(...front.right),
1353
+ vec34(...back.right)
957
1354
  );
958
- const up = positive.select(vec33(...front.up), vec33(...back.up));
959
- const face = positive.select(int3(axis * 2), int3(axis * 2 + 1));
960
- const rect = textureLoad3(
1355
+ const up = positive.select(vec34(...front.up), vec34(...back.up));
1356
+ const face = positive.select(int4(axis * 2), int4(axis * 2 + 1));
1357
+ const rect = textureLoad4(
961
1358
  rects,
962
- ivec23(face, int3(attribute3("boxId", "float")))
1359
+ ivec24(face, int4(attribute3("boxId", "float")))
963
1360
  );
964
1361
  const uv2 = rect.xy.add(
965
- vec23(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1362
+ vec24(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
966
1363
  );
967
- const texel = ivec23(uv2.mul(descriptor.atlasResolution));
968
- const captured = textureLoad3(maps.normalDepth, texel);
1364
+ const texel = ivec24(uv2.mul(descriptor.atlasResolution));
1365
+ const captured = textureLoad4(maps.normalDepth, texel);
969
1366
  const sampled = texture3(maps.baseColor, uv2).level(0);
970
1367
  const sampledOrm = texture3(maps.orm, uv2).level(0);
971
- const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1368
+ const occupied = textureLoad4(maps.orm, texel).a.greaterThan(0.5);
972
1369
  const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
973
- const tolerance = max3(
1370
+ const tolerance = max4(
974
1371
  dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
975
1372
  dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
976
1373
  ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
977
- If3(
1374
+ If4(
978
1375
  occupied.and(sampled.a.greaterThanEqual(minimumAlpha)).and(
979
- abs3(dot3(point, n).sub(float3(1).sub(depth.mul(2)))).lessThanEqual(
1376
+ abs3(dot3(point, n).sub(float4(1).sub(depth.mul(2)))).lessThanEqual(
980
1377
  tolerance
981
1378
  )
982
1379
  ),
@@ -985,28 +1382,28 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
985
1382
  const filtered = filtering ? texture3(maps.normalDepth, uv2).level(0).toVar() : captured;
986
1383
  let weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
987
1384
  if (filtering) {
988
- const error = abs3(dot3(point, n).sub(float3(1).sub(
1385
+ const error = abs3(dot3(point, n).sub(float4(1).sub(
989
1386
  filtered.b.mul(65280).add(filtered.a.mul(255)).div(65535).mul(2)
990
1387
  )));
991
- weight = weight.mul(float3(1).sub(error.div(tolerance)).clamp(0, 1));
1388
+ weight = weight.mul(float4(1).sub(error.div(tolerance)).clamp(0, 1));
992
1389
  }
993
- const coverage2 = max3(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
1390
+ const coverage2 = max4(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
994
1391
  colors.addAssign(sampled.div(coverage2).mul(weight));
995
1392
  materials.addAssign(sampledOrm.rgb.div(coverage2).mul(weight));
996
1393
  emissions.addAssign(
997
1394
  texture3(maps.emissive, uv2).level(0).rgb.div(coverage2).mul(weight)
998
1395
  );
999
1396
  let shadingNormal;
1000
- if (filtering) shadingNormal = filteredNormal(uv2, float3(1).sub(dot3(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1397
+ if (filtering) shadingNormal = filteredNormal(uv2, float4(1).sub(dot3(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1001
1398
  else {
1002
1399
  const packed = captured.rg.mul(2).sub(1);
1003
- const decoded = vec33(
1400
+ const decoded = vec34(
1004
1401
  packed,
1005
- float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1402
+ float4(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1006
1403
  ).toVar();
1007
- If3(decoded.z.lessThan(0), () => {
1404
+ If4(decoded.z.lessThan(0), () => {
1008
1405
  decoded.xy.assign(
1009
- vec23(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1406
+ vec24(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1010
1407
  );
1011
1408
  });
1012
1409
  shadingNormal = decoded;
@@ -1020,7 +1417,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1020
1417
  }
1021
1418
  );
1022
1419
  }
1023
- const divisor = max3(weights, 1e-10), valid = weights.greaterThan(1e-10);
1420
+ const divisor = max4(weights, 1e-10), valid = weights.greaterThan(1e-10);
1024
1421
  return Surface(
1025
1422
  valid.select(colors.div(divisor), fallbackColor),
1026
1423
  valid.select(materials.div(divisor), fallbackOrm),
@@ -1052,7 +1449,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1052
1449
  material.maskShadowNode = material.maskNode;
1053
1450
  material.depthNode = capturedSurfaceDepth(hit.get("position"));
1054
1451
  material.receivedShadowPositionNode = modelWorldMatrix3.mul(
1055
- vec44(hit.get("position"), 1)
1452
+ vec45(hit.get("position"), 1)
1056
1453
  ).xyz;
1057
1454
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
1058
1455
  return material;