@needle-tools/three-mesh-effects 0.3.6 → 0.4.0

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 (61) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +14 -1
  3. package/build/box-impostor-runtime.js +836 -315
  4. package/build/box-impostor-runtime.js.map +4 -4
  5. package/build/impostor-runtime.js +944 -202
  6. package/build/impostor-runtime.js.map +4 -4
  7. package/build/index.js +7 -7
  8. package/build/index.js.map +2 -2
  9. package/build/internal/box-impostor/box-impostor-display.js +844 -321
  10. package/build/internal/box-impostor/box-impostor-display.js.map +4 -4
  11. package/build/internal/box-impostor/box-impostor-faces.js +8 -6
  12. package/build/internal/box-impostor/box-impostor-faces.js.map +2 -2
  13. package/build/internal/box-impostor/box-impostor-material.js +844 -321
  14. package/build/internal/box-impostor/box-impostor-material.js.map +4 -4
  15. package/build/internal/box-impostor/box-impostor-projection.js +8 -5
  16. package/build/internal/box-impostor/box-impostor-projection.js.map +2 -2
  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 +836 -315
  20. package/build/internal/box-impostor/box-impostor-runtime.js.map +4 -4
  21. package/build/internal/impostor/adaptive-impostor-renderer.js +434 -0
  22. package/build/internal/impostor/adaptive-impostor-renderer.js.map +7 -0
  23. package/build/internal/impostor/impostor-node-material.js +944 -202
  24. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  25. package/build/internal/impostor/impostor-performance.js +136 -0
  26. package/build/internal/impostor/impostor-performance.js.map +7 -0
  27. package/build/internal/pixel-impostor/pixel-impostor-runtime.js +6 -1
  28. package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +2 -2
  29. package/build/internal/rendering/instance-space.js +110 -0
  30. package/build/internal/rendering/instance-space.js.map +7 -0
  31. package/build/internal/rendering/renderer-support.js +6 -1
  32. package/build/internal/rendering/renderer-support.js.map +2 -2
  33. package/build/pixel-impostor-runtime.js +6 -1
  34. package/build/pixel-impostor-runtime.js.map +2 -2
  35. package/build/types/box-impostor/box-impostor-faces.d.ts +3 -1
  36. package/build/types/box-impostor/box-impostor-material.d.ts +2 -1
  37. package/build/types/box-impostor/box-impostor-projection.d.ts +3 -1
  38. package/build/types/box-impostor/box-impostor-ray-bounds.d.ts +6 -0
  39. package/build/types/box-impostor/box-impostor-ray-bounds.js +1 -0
  40. package/build/types/impostor/adaptive-impostor-renderer.d.ts +74 -0
  41. package/build/types/impostor/adaptive-impostor-renderer.js +1 -0
  42. package/build/types/impostor/impostor-node-material.d.ts +5 -1
  43. package/build/types/impostor/impostor-performance.d.ts +90 -0
  44. package/build/types/impostor/impostor-performance.js +1 -0
  45. package/build/types/public/impostor-runtime.d.ts +2 -0
  46. package/build/types/public/index.d.ts +3 -0
  47. package/build/types/rendering/instance-space.d.ts +26 -0
  48. package/build/types/rendering/instance-space.js +1 -0
  49. package/build/types/rendering/renderer-support.d.ts +13 -0
  50. package/package.json +2 -2
  51. package/src/box-impostor/box-impostor-faces.js +7 -5
  52. package/src/box-impostor/box-impostor-material.js +162 -109
  53. package/src/box-impostor/box-impostor-projection.js +7 -4
  54. package/src/box-impostor/box-impostor-ray-bounds.js +452 -0
  55. package/src/impostor/adaptive-impostor-renderer.js +423 -0
  56. package/src/impostor/impostor-node-material.js +347 -157
  57. package/src/impostor/impostor-performance.js +152 -0
  58. package/src/public/impostor-runtime.js +2 -0
  59. package/src/public/index.js +12 -9
  60. package/src/rendering/instance-space.js +121 -0
  61. package/src/rendering/renderer-support.js +9 -0
@@ -89,8 +89,8 @@ function parseBoxImpostorDescriptor(raw) {
89
89
  fail();
90
90
  for (let i = 0; i < 3; i++)
91
91
  for (let j = 0; j < 3; j++) {
92
- const dot4 = b.axes[i].reduce((s, v, k) => s + v * b.axes[j][k], 0);
93
- if (Math.abs(dot4 - (i === j ? 1 : 0)) > 1e-4) fail();
92
+ const dot5 = b.axes[i].reduce((s, v, k) => s + v * b.axes[j][k], 0);
93
+ if (Math.abs(dot5 - (i === j ? 1 : 0)) > 1e-4) fail();
94
94
  }
95
95
  const [x, y, z] = b.axes;
96
96
  if ((x[1] * y[2] - x[2] * y[1]) * z[0] + (x[2] * y[0] - x[0] * y[2]) * z[1] + (x[0] * y[1] - x[1] * y[0]) * z[2] < 0.999)
@@ -211,7 +211,7 @@ function createBoxImpostorGeometry(input) {
211
211
  (sum, name) => sum + geometry.getAttribute(name).itemSize,
212
212
  0
213
213
  );
214
- const data = new Float32Array(centers.length / 3 * stride), buffer = new InterleavedBuffer(data, stride);
214
+ const data = new Float32Array(centers.length / 3 * stride), buffer2 = new InterleavedBuffer(data, stride);
215
215
  let offset = 0;
216
216
  for (const name of names) {
217
217
  const attribute4 = geometry.getAttribute(name);
@@ -223,7 +223,7 @@ function createBoxImpostorGeometry(input) {
223
223
  );
224
224
  geometry.setAttribute(
225
225
  name,
226
- new InterleavedBufferAttribute(buffer, attribute4.itemSize, offset)
226
+ new InterleavedBufferAttribute(buffer2, attribute4.itemSize, offset)
227
227
  );
228
228
  offset += attribute4.itemSize;
229
229
  }
@@ -269,9 +269,9 @@ function capturedSurfaceDepth(position, shadowBias = 0) {
269
269
 
270
270
  // src/box-impostor/box-impostor-material.js
271
271
  import {
272
- DataTexture as DataTexture3,
273
- FloatType as FloatType3,
274
- RGBAFormat as RGBAFormat3,
272
+ DataTexture as DataTexture4,
273
+ FloatType as FloatType4,
274
+ RGBAFormat as RGBAFormat4,
275
275
  RedIntegerFormat,
276
276
  UnsignedIntType,
277
277
  NearestFilter as NearestFilter3,
@@ -281,34 +281,34 @@ import {
281
281
  FrontSide
282
282
  } from "three/webgpu";
283
283
  import {
284
- Fn as Fn4,
285
- If as If3,
286
- Loop,
284
+ Fn as Fn5,
285
+ If as If4,
286
+ Loop as Loop2,
287
287
  Break,
288
288
  attribute as attribute3,
289
- varying,
290
- positionLocal as positionLocal2,
289
+ varying as varying2,
290
+ positionGeometry as positionGeometry2,
291
291
  positionViewDirection,
292
292
  modelWorldMatrixInverse,
293
293
  cameraPosition,
294
294
  cameraWorldMatrix,
295
295
  cameraProjectionMatrix as cameraProjectionMatrix2,
296
- vec2 as vec23,
297
- vec3 as vec33,
298
- vec4 as vec44,
299
- float as float3,
300
- int as int3,
301
- uint,
302
- dot as dot3,
296
+ vec2 as vec24,
297
+ vec3 as vec35,
298
+ vec4 as vec46,
299
+ float as float4,
300
+ int as int5,
301
+ uint as uint2,
302
+ dot as dot4,
303
303
  abs as abs3,
304
- max as max3,
305
- min,
304
+ max as max4,
305
+ min as min2,
306
306
  sign as sign3,
307
307
  texture as texture3,
308
- textureLoad as textureLoad3,
309
- ivec2 as ivec23,
308
+ textureLoad as textureLoad5,
309
+ ivec2 as ivec25,
310
310
  normalize as normalize2,
311
- floor,
311
+ floor as floor2,
312
312
  fract,
313
313
  modelWorldMatrix as modelWorldMatrix3,
314
314
  cameraNear as cameraNear2,
@@ -317,9 +317,114 @@ import {
317
317
  uniform
318
318
  } from "three/tsl";
319
319
 
320
+ // src/rendering/instance-space.js
321
+ import { DataTexture, DynamicDrawUsage, FloatType, InstancedInterleavedBuffer, InterpolationSamplingType, NodeUpdateType, RGBAFormat } from "three/webgpu";
322
+ import { cross, dot, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, ivec2, textureLoad, varying, vec3, vec4 as vec42 } from "three/tsl";
323
+ var spaces = /* @__PURE__ */ new WeakMap();
324
+ var webglSpaces = /* @__PURE__ */ new WeakMap();
325
+ function instanceColumns(object, matrix, useTexture) {
326
+ const columns = [0, 1, 2, 3];
327
+ if (useTexture) {
328
+ const rowSize = Math.ceil(Math.sqrt(matrix.count) / 2);
329
+ const rows = Math.ceil(matrix.count / rowSize);
330
+ const data = new Float32Array(rowSize * rows * 16);
331
+ const texture4 = new DataTexture(data, rowSize * 4, rows, RGBAFormat, FloatType);
332
+ const upload = () => {
333
+ data.set(matrix.array);
334
+ texture4.needsUpdate = true;
335
+ };
336
+ upload();
337
+ const release = () => {
338
+ object.removeEventListener("dispose", release);
339
+ texture4.dispose();
340
+ webglSpaces.delete(matrix);
341
+ };
342
+ object.addEventListener("dispose", release);
343
+ const x = instanceIndex.mod(rowSize).mul(4);
344
+ const y = instanceIndex.div(rowSize);
345
+ return { nodes: columns.map((column) => textureLoad(texture4, ivec2(int(x.add(column)), int(y)))), upload };
346
+ }
347
+ const interleaved = new InstancedInterleavedBuffer(matrix.array, 16, 1);
348
+ const read = matrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
349
+ return {
350
+ nodes: columns.map((column) => read(
351
+ interleaved,
352
+ /** @type {const} */
353
+ "vec4",
354
+ 16,
355
+ column * 4
356
+ )),
357
+ upload: () => {
358
+ interleaved.needsUpdate = true;
359
+ }
360
+ };
361
+ }
362
+ function instanceSpace(builder) {
363
+ const object = (
364
+ /** @type {InstancedMesh} */
365
+ builder.object
366
+ );
367
+ const matrix = object?.isInstancedMesh ? object.instanceMatrix : null;
368
+ if (!matrix) return null;
369
+ const backend = (
370
+ /** @type {{isWebGPUBackend?: boolean} | undefined} */
371
+ builder.renderer.backend
372
+ );
373
+ const useTexture = !backend?.isWebGPUBackend && matrix.count * 64 > (builder.getUniformBufferLimit?.() ?? 16384);
374
+ const cache = useTexture ? webglSpaces : spaces;
375
+ const cached = cache.get(matrix);
376
+ if (cached) return cached;
377
+ const { nodes, upload } = instanceColumns(object, matrix, useTexture);
378
+ let version = matrix.version;
379
+ nodes[0].updateBeforeType = NodeUpdateType.OBJECT;
380
+ nodes[0].updateBefore = () => {
381
+ if (matrix.version !== version) {
382
+ version = matrix.version;
383
+ upload();
384
+ }
385
+ return void 0;
386
+ };
387
+ const [a, b, c, d] = nodes.map((node) => node.xyz);
388
+ const determinant = dot(a, cross(b, c));
389
+ const rows = [cross(b, c), cross(c, a), cross(a, b)].map((row) => row.div(determinant));
390
+ const toLocalDirection = (v) => vec3(dot(rows[0], v), dot(rows[1], v), dot(rows[2], v));
391
+ const toMeshDirection = (v) => a.mul(v.x).add(b.mul(v.y)).add(c.mul(v.z));
392
+ const translation = [d.x, d.y, d.z];
393
+ const packed = [a, b, c].map(
394
+ (column, k) => varying(vec42(column, translation[k]), `instanceSpace${k}`).setInterpolation(InterpolationSamplingType.FLAT)
395
+ );
396
+ const [fa, fb, fc] = packed.map((column) => column.xyz);
397
+ const cofactors = () => [cross(fb, fc), cross(fc, fa), cross(fa, fb)];
398
+ const space = {
399
+ toLocalPoint: (p) => toLocalDirection(p.sub(d)),
400
+ toLocalDirection,
401
+ toMeshPoint: (p) => toMeshDirection(p).add(d),
402
+ toMeshDirection,
403
+ fragment: {
404
+ toMeshPoint: (p) => fa.mul(p.x).add(fb.mul(p.y)).add(fc.mul(p.z)).add(vec3(packed[0].w, packed[1].w, packed[2].w)),
405
+ toMeshDirection: (v) => fa.mul(v.x).add(fb.mul(v.y)).add(fc.mul(v.z)),
406
+ toMeshNormal: (n) => {
407
+ const [x, y, z] = cofactors();
408
+ return x.mul(n.x).add(y.mul(n.y)).add(z.mul(n.z)).mul(dot(fa, x).sign()).normalize();
409
+ },
410
+ toLocalDirection: (v) => {
411
+ const [x, y, z] = cofactors();
412
+ return vec3(dot(x, v), dot(y, v), dot(z, v)).div(dot(fa, x));
413
+ },
414
+ toLocalPoint: (p) => {
415
+ const [x, y, z] = cofactors();
416
+ const v = p.sub(vec3(packed[0].w, packed[1].w, packed[2].w));
417
+ return vec3(dot(x, v), dot(y, v), dot(z, v)).div(dot(fa, x));
418
+ }
419
+ }
420
+ };
421
+ cache.set(matrix, space);
422
+ return space;
423
+ }
424
+
320
425
  // src/rendering/captured-surface-material.js
321
426
  import { MeshStandardNodeMaterial } from "three/webgpu";
322
- import { context, modelViewMatrix as modelViewMatrix2, modelWorldMatrix, vec4 as vec42 } from "three/tsl";
427
+ import { context, modelViewMatrix as modelViewMatrix2, modelWorldMatrix, vec4 as vec43 } from "three/tsl";
323
428
  var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
324
429
  /** @type {import('three/webgpu').Node<'vec3'> | null} */
325
430
  capturedPositionNode = null;
@@ -330,8 +435,8 @@ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
330
435
  setupLighting(builder) {
331
436
  const lighting = super.setupLighting(builder);
332
437
  if (!this.capturedPositionNode) return lighting;
333
- const world = modelWorldMatrix.mul(vec42(this.capturedPositionNode, 1)).xyz;
334
- const view = modelViewMatrix2.mul(vec42(this.capturedPositionNode, 1)).xyz;
438
+ const world = modelWorldMatrix.mul(vec43(this.capturedPositionNode, 1)).xyz;
439
+ const view = modelViewMatrix2.mul(vec43(this.capturedPositionNode, 1)).xyz;
335
440
  return context(lighting, {
336
441
  positionView: view,
337
442
  positionWorld: world,
@@ -340,12 +445,364 @@ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
340
445
  }
341
446
  };
342
447
 
448
+ // src/box-impostor/box-impostor-ray-bounds.js
449
+ import { Matrix4, NodeUpdateType as NodeUpdateType2, StorageBufferAttribute, Vector3 } from "three/webgpu";
450
+ import {
451
+ Fn as Fn2,
452
+ If,
453
+ Loop,
454
+ atomicMin,
455
+ atomicStore,
456
+ clamp,
457
+ float,
458
+ floor,
459
+ instanceIndex as instanceIndex2,
460
+ int as int2,
461
+ ivec2 as ivec22,
462
+ max,
463
+ min,
464
+ storage,
465
+ textureLoad as textureLoad2,
466
+ uint,
467
+ vec2,
468
+ vec3 as vec32,
469
+ vec4 as vec44
470
+ } from "three/tsl";
471
+ var MIN_TILE_SIZE = 3;
472
+ var MAX_CAPTURE_TILES = 512 * 1024;
473
+ var REFRESH_ANGLE_SQUARED = Math.tan(Math.PI / 360) ** 2;
474
+ var DEPTH_MAX = 65535;
475
+ var MAX_VIEW_BYTES = 16 * 1024 * 1024;
476
+ var MAX_CACHED_VIEW_BYTES = 64 * 1024 * 1024;
477
+ function buffer(length, components = 1, Type = Float32Array) {
478
+ return new StorageBufferAttribute(length, components, Type);
479
+ }
480
+ function captureTiles(descriptor) {
481
+ const faces = descriptor.boxes.flatMap(
482
+ (box, id) => BOX_FACE_AXES.map((axes, face) => {
483
+ const [, , width, height] = box.views[face];
484
+ const w = width - 2 * descriptor.padding, h = height - 2 * descriptor.padding;
485
+ const right = axes.right.findIndex(Boolean), up = axes.up.findIndex(Boolean);
486
+ const tolerance = 4 * Math.max(box.halfSize[right] / w, box.halfSize[up] / h) / box.halfSize[face >> 1] + 5 / DEPTH_MAX;
487
+ return { key: id * 6 + face, w, h, tolerance };
488
+ })
489
+ );
490
+ const countFor = (size2) => faces.reduce((n, f) => n + Math.ceil((f.w + 2) / size2) * Math.ceil((f.h + 2) / size2), 0);
491
+ let size = MIN_TILE_SIZE;
492
+ while (countFor(size) > MAX_CAPTURE_TILES) size *= 2;
493
+ const tiles = buffer(countFor(size), 4);
494
+ let offset = 0;
495
+ for (const { key, w, h, tolerance } of faces) {
496
+ for (let y = -1; y <= h; y += size) {
497
+ for (let x = -1; x <= w; x += size) {
498
+ tiles.array[offset] = key;
499
+ tiles.array[offset + 1] = x;
500
+ tiles.array[offset + 2] = y;
501
+ tiles.array[offset + 3] = tolerance;
502
+ offset += 4;
503
+ }
504
+ }
505
+ }
506
+ return { tiles, size };
507
+ }
508
+ function buildPatches(descriptor, maps, rects, tiles, size, output) {
509
+ const descriptions = storage(tiles, "vec4", tiles.count).toReadOnly();
510
+ const patches = storage(output, "vec4", output.count);
511
+ return Fn2(() => {
512
+ const meta = descriptions.element(instanceIndex2).toVar();
513
+ const key = int2(meta.x), face = key.mod(6), axis = face.div(2);
514
+ const rect = textureLoad2(rects, ivec22(face, key.div(6))).mul(descriptor.atlasResolution).round().toVar();
515
+ const extent = ivec22(rect.zw.add(1).sub(meta.yz)).min(ivec22(size));
516
+ const origin = ivec22(rect.xy.add(meta.yz));
517
+ const near = float(1).toVar(), far = float(0).toVar();
518
+ function visit(process) {
519
+ Loop({ start: int2(0), end: extent.y, type: "int", name: "row" }, ({ row }) => {
520
+ Loop({ start: int2(0), end: extent.x, type: "int", name: "column" }, ({ column }) => {
521
+ const pixel = origin.add(ivec22(column, row));
522
+ If(textureLoad2(maps.orm, pixel).a.greaterThan(0.5), () => {
523
+ const packed = textureLoad2(maps.normalDepth, pixel);
524
+ const depth = packed.b.mul(65280).add(packed.a.mul(255)).div(DEPTH_MAX).toVar();
525
+ process(column, row, depth);
526
+ });
527
+ });
528
+ });
529
+ }
530
+ visit((x, y, depth) => {
531
+ near.assign(min(near, depth));
532
+ far.assign(max(far, depth));
533
+ });
534
+ const middle = near.add(far).mul(0.5).toVar();
535
+ const low = [vec32(2).toVar(), vec32(2).toVar()], high = [vec32(-2).toVar(), vec32(-2).toVar()];
536
+ visit((x, y, depth) => {
537
+ const uv2 = meta.yz.add(vec2(x, y)).div(rect.zw).mul(2).sub(1);
538
+ const lo = vec32(uv2.clamp(-1, 1), float(1).sub(depth.mul(2)).sub(meta.w).max(-1)).toVar();
539
+ const hi = vec32(
540
+ uv2.add(vec2(2).div(rect.zw)).clamp(-1, 1),
541
+ float(1).sub(depth.mul(2)).add(meta.w).min(1)
542
+ ).toVar();
543
+ lo.toStack();
544
+ hi.toStack();
545
+ const extend = (group) => {
546
+ low[group].assign(min(low[group], lo));
547
+ high[group].assign(max(high[group], hi));
548
+ };
549
+ If(depth.lessThanEqual(middle), () => {
550
+ extend(0);
551
+ }).Else(() => {
552
+ extend(1);
553
+ });
554
+ });
555
+ const facing = face.mod(2).equal(0).select(1, -1);
556
+ const right = axis.equal(0).select(vec32(0, 0, facing.negate()), axis.equal(1).select(vec32(1, 0, 0), vec32(facing, 0, 0)));
557
+ const up = axis.equal(1).select(vec32(0, 0, facing.negate()), vec32(0, 1, 0));
558
+ const normal = right.cross(up);
559
+ const rotate = (p) => right.mul(p.x).add(up.mul(p.y)).add(normal.mul(p.z));
560
+ for (let group = 0; group < 2; group++) {
561
+ const a = rotate(low[group]), b = rotate(high[group]), slot = instanceIndex2.mul(4).add(group * 2);
562
+ const valid = low[group].x.lessThanEqual(high[group].x);
563
+ patches.element(slot).assign(vec44(min(a, b), valid.select(meta.x, -1)));
564
+ patches.element(slot.add(1)).assign(vec44(max(a, b), 0));
565
+ }
566
+ })().compute(tiles.count);
567
+ }
568
+ function makeViewPasses(patchBuffer, views, ranges, count, resolution) {
569
+ const table = storage(ranges, "uint", count).toAtomic();
570
+ const reset = Fn2(() => {
571
+ atomicStore(table.element(instanceIndex2), uint(DEPTH_MAX));
572
+ })().compute(count);
573
+ const patches = storage(patchBuffer, "vec4", patchBuffer.count).toReadOnly();
574
+ const scatter = Fn2(() => {
575
+ const a = patches.element(instanceIndex2.mul(2)).toVar(), b = patches.element(instanceIndex2.mul(2).add(1)).toVar();
576
+ If(a.w.greaterThanEqual(0), () => {
577
+ const key = int2(a.w), box = key.div(6);
578
+ const mapping = views.element(box.mul(2)), reference = views.element(box.mul(2).add(1));
579
+ If(reference.w.greaterThanEqual(0), () => {
580
+ const axis = int2(reference.w).mod(3), x = axis.add(1).mod(3), y = axis.add(2).mod(3);
581
+ const e = vec2(reference.element(x), reference.element(y)), ez = reference.element(axis);
582
+ const za = a.element(axis), zb = b.element(axis);
583
+ const weight = reference.w.lessThan(3).select(1, 0).toVar();
584
+ const eyeSlope = e.div(ez).toVar(), inverseDistance = weight.div(ez).toVar();
585
+ const project = (v, z) => v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
586
+ const l = vec2(a.element(x), a.element(y)), h = vec2(b.element(x), b.element(y));
587
+ const cell = (v, bias) => ivec22(floor(v.sub(mapping.xy).mul(mapping.zw).add(bias)).clamp(0, resolution - 1));
588
+ const lo = cell(min(project(l, za), project(l, zb)), -5e-3);
589
+ const hi = cell(max(project(h, za), project(h, zb)), 5e-3);
590
+ const padding = vec2(0.506).div(mapping.zw).mul(inverseDistance.abs().add(1)).add(2e-6);
591
+ Loop({ start: lo.y, end: hi.y.add(1), type: "int", name: "row" }, ({ row }) => {
592
+ Loop({ start: lo.x, end: hi.x.add(1), type: "int", name: "column" }, ({ column }) => {
593
+ const uv2 = vec2(column, row).add(0.5).div(mapping.zw).add(mapping.xy);
594
+ const slope = eyeSlope.sub(uv2.mul(inverseDistance)).toVar();
595
+ const safe = slope.add(1e-30).sign().mul(slope.abs().max(1e-12));
596
+ const ta = l.sub(padding).sub(uv2).div(safe).toVar(), tb = h.add(padding).sub(uv2).div(safe).toVar();
597
+ 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)));
598
+ If(begin.lessThanEqual(end), () => {
599
+ const depths = floor(
600
+ vec2(begin.add(1), float(1).sub(end)).mul(DEPTH_MAX / 2).sub(0.02)
601
+ ).max(0);
602
+ const i = key.mul(resolution).add(row).mul(resolution).add(column).mul(2);
603
+ atomicMin(table.element(i), uint(depths.x));
604
+ atomicMin(table.element(i.add(1)), uint(depths.y));
605
+ });
606
+ });
607
+ });
608
+ });
609
+ });
610
+ })().compute(patchBuffer.count / 2);
611
+ return { reset, scatter, table };
612
+ }
613
+ function setProjection(data, descriptor, reference, orthographic, resolution) {
614
+ for (const [id, box] of descriptor.boxes.entries()) {
615
+ const p = box.axes.map(
616
+ (axis2, i) => axis2.reduce(
617
+ (sum, v, k) => sum + v * (orthographic ? reference[k] : reference[k] - box.center[k]),
618
+ 0
619
+ ) / box.halfSize[i]
620
+ );
621
+ const axis = p.map(Math.abs).indexOf(Math.max(...p.map(Math.abs)));
622
+ const ez = p[axis], offset = id * 8;
623
+ if (orthographic ? Math.abs(ez) < 1e-12 : Math.abs(ez) <= 1.01) {
624
+ data[offset + 7] = -1;
625
+ continue;
626
+ }
627
+ for (let j = 0; j < 2; j++) {
628
+ const e = p[(axis + 1 + j) % 3];
629
+ const project = (v, z) => orthographic ? v - z * e / ez : (v * ez - z * e) / (ez - z);
630
+ const low = Math.min(project(-1, -1), project(-1, 1));
631
+ const high = Math.max(project(1, -1), project(1, 1));
632
+ data[offset + j] = low;
633
+ data[offset + j + 2] = resolution / (high - low);
634
+ }
635
+ data.set(p, offset + 4);
636
+ data[offset + 7] = axis + (orthographic ? 3 : 0);
637
+ }
638
+ }
639
+ function createBoxRayBounds(descriptor, maps, rects, material) {
640
+ const boxes = descriptor.boxes.length;
641
+ const resolution = Math.min(128, Math.floor(Math.sqrt(MAX_VIEW_BYTES / (48 * boxes))));
642
+ if (resolution < 32 || descriptor.atlasResolution < 512 || [maps.normalDepth, maps.orm].some((map) => map.isRenderTargetTexture || map.isVideoTexture))
643
+ return null;
644
+ const count = boxes * 6 * resolution ** 2 * 2;
645
+ const maxViews = Math.max(1, Math.floor(MAX_CACHED_VIEW_BYTES / (count * 4 + boxes * 32)));
646
+ const inactiveView = buffer(boxes * 2, 4);
647
+ for (let i = 0; i < boxes; i++) inactiveView.array.set([0, 0, 1, 1, 2, 0, 0, -1], i * 8);
648
+ const inactiveRanges = buffer(1, 1, Uint32Array);
649
+ const views = storage(inactiveView, "vec4", boxes * 2).toReadOnly();
650
+ const ranges = storage(inactiveRanges, "uint").toReadOnly();
651
+ const inverse = new Matrix4(), eye = new Vector3(), center = new Vector3();
652
+ const states = /* @__PURE__ */ new Map();
653
+ let tiles, patches, reduce, passes;
654
+ function prepare({ renderer, camera, object }) {
655
+ views.value = inactiveView;
656
+ ranges.value = inactiveRanges;
657
+ if (!renderer.backend?.isWebGPUBackend || renderer.xr?.isPresenting || object.isInstancedMesh || !camera.isPerspectiveCamera && !camera.isOrthographicCamera || camera.isArrayCamera)
658
+ return;
659
+ inverse.copy(object.matrixWorld).invert();
660
+ const ortho = camera.isOrthographicCamera === true;
661
+ if (ortho) camera.getWorldDirection(eye).transformDirection(inverse);
662
+ else eye.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(inverse);
663
+ if (!Number.isFinite(eye.lengthSq())) return;
664
+ let state = states.get(renderer);
665
+ if (!state) {
666
+ state = { slots: [], initialized: false };
667
+ states.set(renderer, state);
668
+ }
669
+ if (!tiles) {
670
+ const capture = captureTiles(descriptor);
671
+ tiles = capture.tiles;
672
+ patches = buffer(tiles.count * 4, 4);
673
+ reduce = buildPatches(descriptor, maps, rects, tiles, capture.size, patches);
674
+ const computeViews = storage(inactiveView, "vec4", boxes * 2).toReadOnly();
675
+ passes = {
676
+ ...makeViewPasses(patches, computeViews, inactiveRanges, count, resolution),
677
+ views: computeViews
678
+ };
679
+ }
680
+ if (!state.initialized || state.depthVersion !== maps.normalDepth.version || state.coverageVersion !== maps.orm.version) {
681
+ renderer.compute(reduce);
682
+ for (const slot2 of state.slots) slot2.ready = false;
683
+ state.depthVersion = maps.normalDepth.version;
684
+ state.coverageVersion = maps.orm.version;
685
+ state.initialized = true;
686
+ }
687
+ const frame = renderer.info.render.calls;
688
+ const compatible = (v) => v.ready && v.ortho === ortho && v.eye.distanceToSquared(eye) <= v.radiusSq;
689
+ let slot = state.slots.find((v) => v.object.deref() === object && v.camera.deref() === camera);
690
+ if (!slot || !compatible(slot)) {
691
+ const shared = state.slots.find(compatible);
692
+ if (shared) {
693
+ shared.frame = frame;
694
+ views.value = shared.view;
695
+ ranges.value = shared.ranges;
696
+ return;
697
+ }
698
+ if (slot?.frame === frame) slot = void 0;
699
+ }
700
+ if (!slot) {
701
+ if (state.slots.length < maxViews) {
702
+ slot = { view: buffer(boxes * 2, 4), ranges: buffer(count, 1, Uint32Array), eye: new Vector3() };
703
+ state.slots.push(slot);
704
+ } else {
705
+ slot = state.slots.reduce((oldest, v) => v.frame < oldest.frame ? v : oldest);
706
+ if (slot.frame === frame) {
707
+ let nearest = Infinity;
708
+ for (const v of state.slots) {
709
+ if (!v.ready || v.ortho !== ortho) continue;
710
+ const distance = v.eye.distanceToSquared(eye);
711
+ if (distance < nearest) {
712
+ nearest = distance;
713
+ views.value = v.view;
714
+ ranges.value = v.ranges;
715
+ }
716
+ }
717
+ return;
718
+ }
719
+ }
720
+ slot.object = new WeakRef(object);
721
+ slot.camera = new WeakRef(camera);
722
+ slot.ready = false;
723
+ }
724
+ slot.frame = frame;
725
+ views.value = slot.view;
726
+ ranges.value = slot.ranges;
727
+ if (compatible(slot)) return;
728
+ setProjection(slot.view.array, descriptor, eye.toArray(), ortho, resolution);
729
+ slot.view.needsUpdate = true;
730
+ passes.views.value = slot.view;
731
+ passes.table.value = slot.ranges;
732
+ renderer.compute([passes.reset, passes.scatter]);
733
+ const distanceSquared = ortho ? 1 : Math.min(...descriptor.boxes.map((box) => eye.distanceToSquared(center.fromArray(box.center))));
734
+ slot.radiusSq = distanceSquared * REFRESH_ANGLE_SQUARED;
735
+ slot.eye.copy(eye);
736
+ slot.ortho = ortho;
737
+ slot.ready = true;
738
+ }
739
+ views.updateBeforeType = NodeUpdateType2.OBJECT;
740
+ views.updateBefore = prepare;
741
+ material.addEventListener("dispose", () => {
742
+ for (const state of states.values()) {
743
+ for (const slot of state.slots) {
744
+ slot.view.dispose();
745
+ slot.ranges.dispose();
746
+ }
747
+ }
748
+ states.clear();
749
+ reduce?.dispose();
750
+ passes?.reset.dispose();
751
+ passes?.scatter.dispose();
752
+ tiles?.dispose();
753
+ patches?.dispose();
754
+ inactiveView.dispose();
755
+ inactiveRanges.dispose();
756
+ });
757
+ return (builder, id, o, r, enter, exit) => {
758
+ if (!builder.renderer.backend?.isWebGPUBackend) return null;
759
+ const mapping = views.element(id.mul(2)).toVar();
760
+ const ref = views.element(id.mul(2).add(1)).toVar();
761
+ const axis = int2(max(ref.w, 0)).mod(3), x = axis.add(1).mod(3), y = axis.add(2).mod(3);
762
+ const rz = r.element(axis).toVar(), oz = o.element(axis).toVar();
763
+ const ez = ref.element(axis), e = vec2(ref.element(x), ref.element(y));
764
+ const eyeSlope = e.div(ez), inverseDistance = ref.w.lessThan(3).select(1, 0).div(ez);
765
+ const project = (t) => {
766
+ const point = o.add(r.mul(t)), v = vec2(point.element(x), point.element(y)), z = point.element(axis);
767
+ const p = v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
768
+ return p.sub(mapping.xy).mul(mapping.zw);
769
+ };
770
+ const a = project(enter).toVar(), b = project(exit).toVar();
771
+ const cellLo = ivec22(floor(min(a, b).sub(1e-3)).clamp(0, resolution - 1)).toVar();
772
+ const cellHi = ivec22(floor(max(a, b).add(1e-3)).clamp(0, resolution - 1)).toVar();
773
+ const valid = ref.w.greaterThanEqual(0).and(rz.abs().greaterThan(1e-12)).and(cellHi.sub(cellLo).lessThanEqual(ivec22(2)).all()).toVar();
774
+ return (face, enter2, exit2) => {
775
+ const start = enter2.toVar(), end = exit2.toVar();
776
+ If(valid, () => {
777
+ const base = id.mul(6).add(face).mul(resolution ** 2);
778
+ const at = (u, v) => base.add(v.mul(resolution)).add(u).mul(2);
779
+ const idx = at(cellLo.x, cellLo.y).toVar();
780
+ const lower = ranges.element(idx).toVar(), upper = ranges.element(idx.add(1)).toVar();
781
+ If(cellHi.notEqual(cellLo).any(), () => {
782
+ Loop({ start: cellLo.y, end: cellHi.y.add(1), type: "int", name: "by" }, ({ by }) => {
783
+ Loop({ start: cellLo.x, end: cellHi.x.add(1), type: "int", name: "bx" }, ({ bx }) => {
784
+ const p = at(bx, by);
785
+ lower.assign(min(lower, ranges.element(p)));
786
+ upper.assign(min(upper, ranges.element(p.add(1))));
787
+ });
788
+ });
789
+ });
790
+ const lo = float(lower).mul(2 / DEPTH_MAX).sub(1), hi = float(1).sub(float(upper).mul(2 / DEPTH_MAX));
791
+ const a2 = lo.sub(oz).div(rz), b2 = hi.sub(oz).div(rz);
792
+ start.assign(min(a2, b2));
793
+ end.assign(lo.lessThanEqual(hi).select(max(a2, b2), enter2.sub(1)));
794
+ });
795
+ return { start, end };
796
+ };
797
+ };
798
+ }
799
+
343
800
  // src/box-impostor/box-impostor-surface-search.js
344
- function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
801
+ function refineSurfaceCrossing({ float: float5, If: If5, Loop: Loop3 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
345
802
  const a = lo.toVar(), b = hi.toVar(), fa = loValue.toVar(), fb = secant ? hiValue.toVar() : null;
346
- Loop2(steps, () => {
803
+ Loop3(steps, () => {
347
804
  const mid = a.add(b).mul(0.5).toVar(), d = height(mid).toVar();
348
- If4(d.mul(fa).greaterThan(0), () => {
805
+ If5(d.mul(fa).greaterThan(0), () => {
349
806
  a.assign(mid);
350
807
  if (secant) fa.assign(d);
351
808
  }).Else(() => {
@@ -357,23 +814,23 @@ function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi
357
814
  }
358
815
 
359
816
  // src/box-impostor/box-impostor-faces.js
360
- import { DataTexture, FloatType, RGBAFormat, NearestFilter } from "three";
817
+ import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter } from "three";
361
818
  import {
362
- Fn as Fn2,
363
- If,
819
+ Fn as Fn3,
820
+ If as If2,
364
821
  attribute,
365
- positionLocal,
822
+ positionGeometry,
366
823
  uv,
367
824
  texture,
368
- textureLoad,
369
- ivec2,
370
- vec2,
371
- vec3,
372
- float,
373
- int,
374
- dot,
825
+ textureLoad as textureLoad3,
826
+ ivec2 as ivec23,
827
+ vec2 as vec22,
828
+ vec3 as vec33,
829
+ float as float2,
830
+ int as int3,
831
+ dot as dot2,
375
832
  abs,
376
- max,
833
+ max as max2,
377
834
  sign,
378
835
  transformNormalToView
379
836
  } from "three/tsl";
@@ -385,60 +842,62 @@ function applyBoxFaces({
385
842
  transparency,
386
843
  half,
387
844
  toBox,
388
- fromBox
845
+ fromBox,
846
+ meshVertex,
847
+ meshNormal
389
848
  }) {
390
849
  const values = new Float32Array(descriptor.boxes.length * 6 * 4);
391
850
  descriptor.boxes.forEach((box, i) => {
392
851
  for (let face2 = 0; face2 < 6; face2++)
393
852
  values[(i * 6 + face2) * 4] = box.planes?.[face2] ?? 0.5;
394
853
  });
395
- const planes = new DataTexture(
854
+ const planes = new DataTexture2(
396
855
  values,
397
856
  6,
398
857
  descriptor.boxes.length,
399
- RGBAFormat,
400
- FloatType
858
+ RGBAFormat2,
859
+ FloatType2
401
860
  );
402
861
  planes.minFilter = planes.magFilter = NearestFilter;
403
862
  planes.needsUpdate = true;
404
863
  material.addEventListener("dispose", () => planes.dispose());
405
- const face = int(attribute("boxFace", "float"));
864
+ const face = int3(attribute("boxFace", "float"));
406
865
  const n = attribute("normal", "vec3");
407
- const depth = textureLoad(
866
+ const depth = textureLoad3(
408
867
  planes,
409
- ivec2(face, int(attribute("boxId", "float")))
868
+ ivec23(face, int3(attribute("boxId", "float")))
410
869
  ).r;
411
- const proxy = positionLocal.sub(
870
+ const proxy = positionGeometry.sub(
412
871
  n.mul(
413
- dot(abs(toBox(n)), half).mul(depth).mul(2)
872
+ dot2(abs(toBox(n)), half).mul(depth).mul(2)
414
873
  )
415
874
  );
416
- material.positionNode = proxy;
417
- material.castShadowPositionNode = proxy;
875
+ material.positionNode = meshVertex(proxy);
876
+ material.castShadowPositionNode = material.positionNode;
418
877
  const base = texture(maps.baseColor, uv()).level(0).toVar("boxFaceColor");
419
878
  const orm = texture(maps.orm, uv()).level(0);
420
- const coverage = max(orm.a, 1e-10);
421
- const normal = Fn2(() => {
422
- const packed = textureLoad(
879
+ const coverage = max2(orm.a, 1e-10);
880
+ const normal = Fn3(() => {
881
+ const packed = textureLoad3(
423
882
  maps.normalDepth,
424
- ivec2(uv().mul(descriptor.atlasResolution))
883
+ ivec23(uv().mul(descriptor.atlasResolution))
425
884
  ).rg.mul(2).sub(1);
426
- const decoded = vec3(
885
+ const decoded = vec33(
427
886
  packed,
428
- float(1).sub(abs(packed.x)).sub(abs(packed.y))
887
+ float2(1).sub(abs(packed.x)).sub(abs(packed.y))
429
888
  ).toVar();
430
- If(decoded.z.lessThan(0), () => {
889
+ If2(decoded.z.lessThan(0), () => {
431
890
  decoded.xy.assign(
432
- vec2(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
891
+ vec22(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
433
892
  );
434
893
  });
435
- const result = vec3(0).toVar();
894
+ const result = vec33(0).toVar();
436
895
  for (let f = 0; f < 6; f++) {
437
896
  const a = BOX_FACE_AXES[f];
438
- If(face.equal(f), () => {
897
+ If2(face.equal(f), () => {
439
898
  result.assign(
440
899
  fromBox(
441
- vec3(...a.right).mul(decoded.x).add(vec3(...a.up).mul(decoded.y)).add(vec3(...a.normal).mul(decoded.z))
900
+ vec33(...a.right).mul(decoded.x).add(vec33(...a.up).mul(decoded.y)).add(vec33(...a.normal).mul(decoded.z))
442
901
  ).normalize()
443
902
  );
444
903
  });
@@ -446,13 +905,13 @@ function applyBoxFaces({
446
905
  return result;
447
906
  })();
448
907
  material.colorNode = base.rgb.div(coverage);
449
- material.normalNode = transformNormalToView(normal);
908
+ material.normalNode = transformNormalToView(meshNormal(normal));
450
909
  material.roughnessNode = orm.g.div(coverage);
451
910
  material.metalnessNode = orm.b.div(coverage);
452
911
  material.aoNode = orm.r.div(coverage);
453
912
  material.emissiveNode = texture(maps.emissive, uv()).level(0).rgb.div(coverage);
454
913
  material.maskNode = base.a.greaterThanEqual(
455
- transparency === "cutout" ? alphaCutoff : float(1 / 255)
914
+ transparency === "cutout" ? alphaCutoff : float2(1 / 255)
456
915
  );
457
916
  material.maskShadowNode = material.maskNode;
458
917
  if (transparency !== "cutout") material.opacityNode = base.a;
@@ -461,23 +920,23 @@ function applyBoxFaces({
461
920
  }
462
921
 
463
922
  // src/box-impostor/box-impostor-projection.js
464
- import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter as NearestFilter2 } from "three";
923
+ import { DataTexture as DataTexture3, FloatType as FloatType3, RGBAFormat as RGBAFormat3, NearestFilter as NearestFilter2 } from "three";
465
924
  import {
466
- Fn as Fn3,
467
- If as If2,
468
- vec2 as vec22,
469
- vec3 as vec32,
470
- vec4 as vec43,
471
- float as float2,
472
- int as int2,
473
- ivec2 as ivec22,
474
- dot as dot2,
925
+ Fn as Fn4,
926
+ If as If3,
927
+ vec2 as vec23,
928
+ vec3 as vec34,
929
+ vec4 as vec45,
930
+ float as float3,
931
+ int as int4,
932
+ ivec2 as ivec24,
933
+ dot as dot3,
475
934
  abs as abs2,
476
- max as max2,
935
+ max as max3,
477
936
  sign as sign2,
478
937
  normalize,
479
938
  texture as texture2,
480
- textureLoad as textureLoad2,
939
+ textureLoad as textureLoad4,
481
940
  attribute as attribute2,
482
941
  struct,
483
942
  modelWorldMatrix as modelWorldMatrix2,
@@ -498,19 +957,21 @@ function applyBoxProjection({
498
957
  eye,
499
958
  viewAxis,
500
959
  perspective,
501
- raster
960
+ raster,
961
+ meshPoint,
962
+ meshNormal
502
963
  }) {
503
964
  const data = new Float32Array(descriptor.boxes.length * 24);
504
965
  descriptor.boxes.forEach((box, i) => {
505
966
  for (let face = 0; face < 6; face++)
506
967
  data[(i * 6 + face) * 4] = box.planes?.[face] ?? 0.5;
507
968
  });
508
- const planes = new DataTexture2(
969
+ const planes = new DataTexture3(
509
970
  data,
510
971
  6,
511
972
  descriptor.boxes.length,
512
- RGBAFormat2,
513
- FloatType2
973
+ RGBAFormat3,
974
+ FloatType3
514
975
  );
515
976
  planes.minFilter = planes.magFilter = NearestFilter2;
516
977
  planes.needsUpdate = true;
@@ -527,24 +988,24 @@ function applyBoxProjection({
527
988
  "BoxProjectedSurface"
528
989
  );
529
990
  const readNormal = (uv2, right, up, n) => {
530
- const packed = textureLoad2(
991
+ const packed = textureLoad4(
531
992
  maps.normalDepth,
532
- ivec22(uv2.mul(descriptor.atlasResolution))
993
+ ivec24(uv2.mul(descriptor.atlasResolution))
533
994
  ).rg.mul(2).sub(1);
534
- const decoded = vec32(
995
+ const decoded = vec34(
535
996
  packed,
536
- float2(1).sub(abs2(packed.x)).sub(abs2(packed.y))
997
+ float3(1).sub(abs2(packed.x)).sub(abs2(packed.y))
537
998
  ).toVar();
538
- If2(decoded.z.lessThan(0), () => {
999
+ If3(decoded.z.lessThan(0), () => {
539
1000
  decoded.xy.assign(
540
- vec22(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
1001
+ vec23(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
541
1002
  );
542
1003
  });
543
1004
  return fromBox(
544
1005
  right.mul(decoded.x).add(up.mul(decoded.y)).add(n.mul(decoded.z))
545
1006
  ).normalize();
546
1007
  };
547
- const surface = Fn3(() => {
1008
+ const surface = Fn4(() => {
548
1009
  const ray = perspective.select(
549
1010
  normalize(raster.sub(eye)),
550
1011
  viewAxis.negate()
@@ -555,48 +1016,48 @@ function applyBoxProjection({
555
1016
  );
556
1017
  const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
557
1018
  const look = normalize(toBox(ray).negate()), angles = abs2(look);
558
- const positions = vec32(0).toVar();
559
- const selectedUv = vec22(0).toVar(), selectedRight = vec32(1, 0, 0).toVar(), selectedUp = vec32(0, 1, 0).toVar(), selectedNormal = vec32(0, 0, 1).toVar();
560
- const nearest = float2(1e20).toVar("boxPlaneDistance");
561
- const opacity = float2(0).toVar();
1019
+ const positions = vec34(0).toVar();
1020
+ const selectedUv = vec23(0).toVar(), selectedRight = vec34(1, 0, 0).toVar(), selectedUp = vec34(0, 1, 0).toVar(), selectedNormal = vec34(0, 0, 1).toVar();
1021
+ const nearest = float3(1e20).toVar("boxPlaneDistance");
1022
+ const opacity = float3(0).toVar();
562
1023
  const candidates = [];
563
1024
  for (let axis = 0; axis < 3; axis++) {
564
1025
  const angle = angles.element(axis);
565
1026
  const positive = look.element(axis).greaterThanEqual(0), a = BOX_FACE_AXES[axis * 2], b = BOX_FACE_AXES[axis * 2 + 1];
566
- 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));
1027
+ const n = positive.select(vec34(...a.normal), vec34(...b.normal)), right = positive.select(vec34(...a.right), vec34(...b.right)), up = positive.select(vec34(...a.up), vec34(...b.up));
567
1028
  const weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
568
1029
  const candidate = settings.interpolation === "none" ? null : {
569
- uv: vec22(0).toVar(),
570
- base: vec43(0).toVar(),
571
- orm: vec43(0).toVar(),
572
- t: float2(1e20).toVar(),
573
- tolerance: float2(0).toVar(),
1030
+ uv: vec23(0).toVar(),
1031
+ base: vec45(0).toVar(),
1032
+ orm: vec45(0).toVar(),
1033
+ t: float3(1e20).toVar(),
1034
+ tolerance: float3(0).toVar(),
574
1035
  right,
575
1036
  up,
576
1037
  n,
577
1038
  weight
578
1039
  };
579
1040
  if (candidate) candidates.push(candidate);
580
- If2(angle.greaterThan(1e-4), () => {
581
- const face = positive.select(int2(axis * 2), int2(axis * 2 + 1)), id = int2(attribute2("boxId", "float"));
582
- const plane = float2(1).sub(
583
- textureLoad2(planes, ivec22(face, id)).r.mul(2)
1041
+ If3(angle.greaterThan(1e-4), () => {
1042
+ const face = positive.select(int4(axis * 2), int4(axis * 2 + 1)), id = int4(attribute2("boxId", "float"));
1043
+ const plane = float3(1).sub(
1044
+ textureLoad4(planes, ivec24(face, id)).r.mul(2)
584
1045
  );
585
- const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max2(abs2(divisor2), 1e-10));
586
- const t = plane.sub(dot2(o, n)).div(safe), point = o.add(r.mul(t));
587
- const xy = vec22(dot2(point, right), dot2(point, up)).mul(0.5).add(0.5);
1046
+ const divisor2 = dot3(r, n), safe = sign2(divisor2.add(1e-20)).mul(max3(abs2(divisor2), 1e-10));
1047
+ const t = plane.sub(dot3(o, n)).div(safe), point = o.add(r.mul(t));
1048
+ const xy = vec23(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5);
588
1049
  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));
589
1050
  if (!candidate) supported = supported.and(t.lessThan(nearest));
590
- If2(supported, () => {
591
- const rect = textureLoad2(rects, ivec22(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
1051
+ If3(supported, () => {
1052
+ const rect = textureLoad4(rects, ivec24(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
592
1053
  const base = texture2(maps.baseColor, uv2).level(0), orm = texture2(maps.orm, uv2).level(0);
593
1054
  const alpha2 = base.a.clamp(0, 1);
594
- If2(
1055
+ If3(
595
1056
  alpha2.greaterThanEqual(
596
- transparency === "cutout" ? alphaCutoff : float2(1 / 255)
1057
+ transparency === "cutout" ? alphaCutoff : float3(1 / 255)
597
1058
  ).and(orm.a.greaterThan(0)),
598
1059
  () => {
599
- If2(t.lessThan(nearest), () => {
1060
+ If3(t.lessThan(nearest), () => {
600
1061
  nearest.assign(t);
601
1062
  selectedUv.assign(uv2);
602
1063
  opacity.assign(alpha2);
@@ -611,14 +1072,14 @@ function applyBoxProjection({
611
1072
  candidate.orm.assign(orm);
612
1073
  candidate.t.assign(t);
613
1074
  candidate.tolerance.assign(
614
- max2(
615
- dot2(abs2(right), half).div(
1075
+ max3(
1076
+ dot3(abs2(right), half).div(
616
1077
  rect.z.mul(descriptor.atlasResolution)
617
1078
  ),
618
- dot2(abs2(up), half).div(
1079
+ dot3(abs2(up), half).div(
619
1080
  rect.w.mul(descriptor.atlasResolution)
620
1081
  )
621
- ).mul(4).div(max2(angle, 0.1))
1082
+ ).mul(4).div(max3(angle, 0.1))
622
1083
  );
623
1084
  }
624
1085
  }
@@ -628,7 +1089,7 @@ function applyBoxProjection({
628
1089
  }
629
1090
  if (settings.interpolation === "none") {
630
1091
  const base = texture2(maps.baseColor, selectedUv).level(0), orm = texture2(maps.orm, selectedUv).level(0);
631
- const coverage = max2(orm.a, 1e-10);
1092
+ const coverage = max3(orm.a, 1e-10);
632
1093
  return Surface(
633
1094
  base.rgb.div(coverage),
634
1095
  opacity,
@@ -638,15 +1099,15 @@ function applyBoxProjection({
638
1099
  positions
639
1100
  );
640
1101
  }
641
- const colors = vec32(0).toVar(), orms = vec32(0).toVar(), emissions = vec32(0).toVar(), normals = vec32(0).toVar();
642
- const weights = float2(0).toVar(), support = float2(0).toVar(), alpha = float2(0).toVar();
1102
+ const colors = vec34(0).toVar(), orms = vec34(0).toVar(), emissions = vec34(0).toVar(), normals = vec34(0).toVar();
1103
+ const weights = float3(0).toVar(), support = float3(0).toVar(), alpha = float3(0).toVar();
643
1104
  for (const c of candidates) {
644
- If2(
1105
+ If3(
645
1106
  c.base.a.greaterThan(0).and(c.t.lessThanEqual(nearest.add(c.tolerance))),
646
1107
  () => {
647
- const coverage = max2(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
1108
+ const coverage = max3(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
648
1109
  weights.addAssign(c.weight.mul(coverage));
649
- support.assign(max2(support, coverage));
1110
+ support.assign(max3(support, coverage));
650
1111
  colors.addAssign(c.base.rgb.div(coverage).mul(w));
651
1112
  orms.addAssign(c.orm.rgb.div(coverage).mul(w));
652
1113
  emissions.addAssign(
@@ -657,29 +1118,30 @@ function applyBoxProjection({
657
1118
  }
658
1119
  );
659
1120
  }
660
- const divisor = max2(alpha, 1e-10);
1121
+ const divisor = max3(alpha, 1e-10);
661
1122
  return Surface(
662
1123
  colors.div(divisor),
663
- alpha.div(max2(weights, 1e-10)).mul(support),
1124
+ alpha.div(max3(weights, 1e-10)).mul(support),
664
1125
  orms.div(divisor),
665
1126
  emissions.div(divisor),
666
- normals.div(max2(normals.length(), 1e-10)),
1127
+ normals.div(max3(normals.length(), 1e-10)),
667
1128
  positions
668
1129
  );
669
1130
  })().toVar("boxProjectedSurface");
670
- material.capturedPositionNode = surface.get("position");
1131
+ const position = meshPoint(surface.get("position")).toVar("boxProjectedMeshPosition");
1132
+ material.capturedPositionNode = position;
671
1133
  material.colorNode = surface.get("color");
672
- material.normalNode = transformNormalToView2(surface.get("normal"));
1134
+ material.normalNode = transformNormalToView2(meshNormal(surface.get("normal")));
673
1135
  material.roughnessNode = surface.get("orm").g;
674
1136
  material.metalnessNode = surface.get("orm").b;
675
1137
  material.aoNode = surface.get("orm").r;
676
1138
  material.emissiveNode = surface.get("emission");
677
- material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float2(1 / 255));
1139
+ material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float3(1 / 255));
678
1140
  material.maskShadowNode = material.maskNode;
679
1141
  if (transparency !== "cutout") material.opacityNode = surface.get("alpha");
680
- material.depthNode = capturedSurfaceDepth(surface.get("position"));
1142
+ material.depthNode = capturedSurfaceDepth(position);
681
1143
  material.receivedShadowPositionNode = modelWorldMatrix2.mul(
682
- vec43(surface.get("position"), 1)
1144
+ vec45(position, 1)
683
1145
  ).xyz;
684
1146
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
685
1147
  return material;
@@ -689,39 +1151,40 @@ function applyBoxProjection({
689
1151
  function createBoxImpostorMaterial(descriptor, maps) {
690
1152
  return createBoxImpostorMaterialVariant(descriptor, maps, { filtering: true });
691
1153
  }
692
- function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false } = {}) {
1154
+ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false, boundSearch = true } = {}) {
693
1155
  const settings = normalizeBoxImpostorDisplay(descriptor);
694
1156
  const alphaCutoff = uniform(settings.alphaCutoff);
695
1157
  const transparency = boxTransparency(descriptor, settings);
696
- const minimumAlpha = transparency === "cutout" ? alphaCutoff : float3(1 / 255);
697
- const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min(ormAlpha, baseAlpha) : ormAlpha;
698
- const decodeNormal = (encoded) => {
1158
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float4(1 / 255);
1159
+ const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min2(ormAlpha, baseAlpha) : ormAlpha;
1160
+ const unpackNormal = (encoded) => {
699
1161
  const packed = encoded.mul(2).sub(1);
700
- const normal2 = vec33(packed, float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
701
- If3(normal2.z.lessThan(0), () => {
702
- normal2.xy.assign(vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
1162
+ const normal2 = vec35(packed, float4(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
1163
+ If4(normal2.z.lessThan(0), () => {
1164
+ normal2.xy.assign(vec24(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
703
1165
  });
704
- return normal2.normalize();
1166
+ return normal2;
705
1167
  };
1168
+ const decodeNormal = (encoded) => unpackNormal(encoded).normalize();
706
1169
  const filteredNormal = (uv2, depth, tolerance, nearest, alpha, sampled = texture3(maps.normalDepth, uv2).level(0), ormAlpha = texture3(maps.orm, uv2).level(0).a) => {
707
1170
  sampled = sampled.toVar();
708
- const coverage2 = max3(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
1171
+ const coverage2 = max4(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
709
1172
  const nearestNormal = decodeNormal(nearest.rg), result = decodeNormal(sampled.rg.div(coverage2)).toVar();
710
1173
  const sampledDepth = sampled.b.mul(65280).add(sampled.a.mul(255)).div(65535);
711
1174
  const nearestDepth = nearest.b.mul(65280).add(nearest.a.mul(255)).div(65535);
712
- If3(nearestNormal.z.lessThan(0).or(dot3(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
713
- const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor(p), f = fract(p);
714
- const normal2 = vec33(0).toVar(), weights = float3(0).toVar();
1175
+ If4(nearestNormal.z.lessThan(0).or(dot4(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
1176
+ const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor2(p), f = fract(p);
1177
+ const normal2 = vec35(0).toVar(), weights = float4(0).toVar();
715
1178
  for (const [x, y] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
716
- const texel = ivec23(lo.add(vec23(x, y)).clamp(0, descriptor.atlasResolution - 1));
717
- const packed = textureLoad3(maps.normalDepth, texel).toVar();
718
- const alpha2 = textureLoad3(maps.baseColor, texel).a;
719
- const coverage3 = descriptor.alphaMode === "blend" ? textureLoad3(maps.orm, texel).a : alpha2;
1179
+ const texel = ivec25(lo.add(vec24(x, y)).clamp(0, descriptor.atlasResolution - 1));
1180
+ const packed = textureLoad5(maps.normalDepth, texel).toVar();
1181
+ const alpha2 = textureLoad5(maps.baseColor, texel).a;
1182
+ const coverage3 = descriptor.alphaMode === "blend" ? textureLoad5(maps.orm, texel).a : alpha2;
720
1183
  const capturedDepth = packed.b.mul(65280).add(packed.a.mul(255)).div(65535);
721
1184
  const supported = coverage3.greaterThan(1e-4).and(alpha2.greaterThanEqual(minimumAlpha.mul(coverage3))).and(abs3(capturedDepth.sub(depth)).lessThanEqual(tolerance));
722
- If3(supported, () => {
723
- const weight = (x ? f.x : float3(1).sub(f.x)).mul(y ? f.y : float3(1).sub(f.y)).mul(coverage3);
724
- normal2.addAssign(decodeNormal(packed.rg.div(max3(coverage3, 1e-10))).mul(weight));
1185
+ If4(supported, () => {
1186
+ const weight = (x ? f.x : float4(1).sub(f.x)).mul(y ? f.y : float4(1).sub(f.y)).mul(coverage3);
1187
+ normal2.addAssign(decodeNormal(packed.rg.div(max4(coverage3, 1e-10))).mul(weight));
725
1188
  weights.addAssign(weight);
726
1189
  });
727
1190
  }
@@ -758,57 +1221,68 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
758
1221
  )
759
1222
  )
760
1223
  );
761
- const rects = new DataTexture3(
1224
+ const rects = new DataTexture4(
762
1225
  rectData,
763
1226
  6,
764
1227
  descriptor.boxes.length,
765
- RGBAFormat3,
766
- FloatType3
1228
+ RGBAFormat4,
1229
+ FloatType4
767
1230
  );
768
1231
  rects.needsUpdate = true;
769
1232
  rects.magFilter = rects.minFilter = NearestFilter3;
770
1233
  material.addEventListener("dispose", () => rects.dispose());
771
1234
  const center = attribute3("boxCenter", "vec3"), half = attribute3("boxHalfSize", "vec3");
772
1235
  const ax = attribute3("boxAxisX", "vec3"), ay = attribute3("boxAxisY", "vec3"), az = attribute3("boxAxisZ", "vec3");
773
- const toBox = (p) => vec33(dot3(p, ax), dot3(p, ay), dot3(p, az));
1236
+ const toBox = (p) => vec35(dot4(p, ax), dot4(p, ay), dot4(p, az));
774
1237
  const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
775
- const eye = modelWorldMatrixInverse.mul(vec44(cameraPosition, 1)).xyz;
776
- const viewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 0, 1, 0))).xyz.normalize();
1238
+ const meshVertex = (p) => Fn5((_, builder) => instanceSpace(builder)?.toMeshPoint(p) ?? p)();
1239
+ const meshPoint = (p) => Fn5((_, builder) => instanceSpace(builder)?.fragment.toMeshPoint(p) ?? p)();
1240
+ const meshNormal = (n) => Fn5((_, builder) => instanceSpace(builder)?.fragment.toMeshNormal(n) ?? n)();
1241
+ const meshEye = modelWorldMatrixInverse.mul(vec46(cameraPosition, 1)).xyz;
1242
+ const meshViewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec46(0, 0, 1, 0))).xyz;
1243
+ const eye = Fn5((_, builder) => instanceSpace(builder)?.fragment.toLocalPoint(meshEye) ?? meshEye)();
1244
+ const viewAxis = Fn5((_, builder) => instanceSpace(builder)?.fragment.toLocalDirection(meshViewAxis) ?? meshViewAxis)().normalize();
1245
+ const vertexEye = Fn5((_, builder) => instanceSpace(builder)?.toLocalPoint(meshEye) ?? meshEye)();
1246
+ const vertexViewAxis = Fn5((_, builder) => instanceSpace(builder)?.toLocalDirection(meshViewAxis) ?? meshViewAxis)().normalize();
1247
+ const cameraUp = Fn5((_, builder) => {
1248
+ const up = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec46(0, 1, 0, 0))).xyz;
1249
+ return instanceSpace(builder)?.toLocalDirection(up) ?? up;
1250
+ })();
777
1251
  const perspective = cameraProjectionMatrix2.element(3).w.equal(0);
778
- let proxy = positionLocal2;
1252
+ let proxy = positionGeometry2;
779
1253
  if (descriptor.mode !== "fitted") {
780
- proxy = Fn4((_, builder) => {
781
- const delta = eye.sub(center);
782
- const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize2(delta), viewAxis);
783
- const right = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 1, 0, 0))).xyz.cross(forward).normalize();
1254
+ proxy = Fn5((_, builder) => {
1255
+ const delta = vertexEye.sub(center);
1256
+ const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize2(delta), vertexViewAxis);
1257
+ const right = cameraUp.cross(forward).normalize();
784
1258
  const up = forward.cross(right).normalize();
785
1259
  const radius = half.length();
786
- const distance = dot3(eye.sub(center), forward);
787
- const planeOffset = perspective.select(min(radius, distance.sub(cameraNear2.mul(2))), radius);
1260
+ const distance = dot4(vertexEye.sub(center), forward);
1261
+ const planeOffset = perspective.select(min2(radius, distance.sub(cameraNear2.mul(2))), radius);
788
1262
  const plane = center.add(forward.mul(planeOffset));
789
- const lo = vec23(1e20).toVar(), hi = vec23(-1e20).toVar();
1263
+ const lo = vec24(1e20).toVar(), hi = vec24(-1e20).toVar();
790
1264
  for (const x of [-1, 1])
791
1265
  for (const y of [-1, 1])
792
1266
  for (const z of [-1, 1]) {
793
- const corner2 = fromBox(half.mul(vec33(x, y, z)));
1267
+ const corner2 = fromBox(half.mul(vec35(x, y, z)));
794
1268
  const scale = perspective.select(
795
- max3(distance.sub(planeOffset), 1e-5).div(
796
- max3(distance.sub(dot3(corner2, forward)), 1e-5)
1269
+ max4(distance.sub(planeOffset), 1e-5).div(
1270
+ max4(distance.sub(dot4(corner2, forward)), 1e-5)
797
1271
  ),
798
- float3(1)
1272
+ float4(1)
799
1273
  );
800
- const p = vec23(dot3(corner2, right), dot3(corner2, up)).mul(scale);
801
- lo.assign(min(lo, p));
802
- hi.assign(max3(hi, p));
1274
+ const p = vec24(dot4(corner2, right), dot4(corner2, up)).mul(scale);
1275
+ lo.assign(min2(lo, p));
1276
+ hi.assign(max4(hi, p));
803
1277
  }
804
1278
  const corner = attribute3("cardCorner", "vec2").add(1).mul(0.5);
805
1279
  const xy = lo.add(hi.sub(lo).mul(corner));
806
1280
  return plane.add(right.mul(xy.x)).add(up.mul(xy.y));
807
1281
  })();
808
- material.positionNode = proxy;
809
- material.castShadowPositionNode = proxy;
1282
+ material.positionNode = meshVertex(proxy);
1283
+ material.castShadowPositionNode = material.positionNode;
810
1284
  }
811
- const raster = varying(proxy, "boxRasterPosition");
1285
+ const raster = varying2(proxy, "boxRasterPosition");
812
1286
  if (boxDepthMode(descriptor, settings) === "projection" && descriptor.mode === "fitted" && settings.interpolation === "none") {
813
1287
  material.side = FrontSide;
814
1288
  return applyBoxFaces({
@@ -819,7 +1293,9 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
819
1293
  transparency,
820
1294
  half,
821
1295
  toBox,
822
- fromBox
1296
+ fromBox,
1297
+ meshVertex,
1298
+ meshNormal
823
1299
  });
824
1300
  }
825
1301
  if (boxDepthMode(descriptor, settings) === "projection")
@@ -838,7 +1314,9 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
838
1314
  eye,
839
1315
  viewAxis,
840
1316
  perspective,
841
- raster
1317
+ raster,
1318
+ meshPoint,
1319
+ meshNormal
842
1320
  });
843
1321
  const accelerated = descriptor.boxes.every((b) => b.depthBounds);
844
1322
  const gridSize = BOX_OCCUPANCY_RESOLUTION;
@@ -851,7 +1329,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
851
1329
  descriptor.boxes.forEach(
852
1330
  (box, index) => words.set(box.occupancy, index * wordsPerBox)
853
1331
  );
854
- occupancy = new DataTexture3(
1332
+ occupancy = new DataTexture4(
855
1333
  words,
856
1334
  wordsPerBox,
857
1335
  descriptor.boxes.length,
@@ -861,53 +1339,66 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
861
1339
  occupancy.needsUpdate = true;
862
1340
  material.addEventListener("dispose", () => occupancy.dispose());
863
1341
  }
1342
+ const preferFacingCapture = filtering && descriptor.alphaMode === "opaque" && settings.interpolation === "none";
1343
+ const viewBounds = boundSearch ? createBoxRayBounds(descriptor, maps, rects, material) : null;
864
1344
  const Result = struct2(
865
- { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
1345
+ { uv: "vec2", position: "vec3", face: "int", valid: "float" },
866
1346
  "BoxImpostorHit"
867
1347
  );
868
- const raycast = Fn4((_, builder) => {
869
- const ray = perspective.select(
870
- normalize2(raster.sub(eye)),
871
- viewAxis.negate()
872
- );
1348
+ const faceBasis = (axis, facing) => {
1349
+ const n = vec35(
1350
+ axis.equal(0).select(facing, 0),
1351
+ axis.equal(1).select(facing, 0),
1352
+ axis.equal(2).select(facing, 0)
1353
+ ).toVar();
1354
+ const right = axis.equal(0).select(
1355
+ vec35(0, 0, facing.negate()),
1356
+ axis.equal(1).select(vec35(1, 0, 0), vec35(facing, 0, 0))
1357
+ ).toVar();
1358
+ const up = axis.equal(1).select(vec35(0, 0, facing.negate()), vec35(0, 1, 0)).toVar();
1359
+ return { n, right, up };
1360
+ };
1361
+ const ray = perspective.select(normalize2(raster.sub(eye)), viewAxis.negate());
1362
+ const raycast = Fn5((_, builder) => {
873
1363
  const origin = perspective.select(
874
1364
  eye,
875
1365
  raster.sub(ray.mul(half.length().mul(4)))
876
1366
  );
877
1367
  const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
878
- const safe = sign3(r.add(1e-20)).mul(max3(abs3(r), 1e-10));
879
- const a = vec33(-1).sub(o).div(safe), b = vec33(1).sub(o).div(safe);
880
- const enter = max3(max3(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
881
- const exit = min(min(max3(a, b).x, max3(a, b).y), max3(a, b).z);
1368
+ const safe = sign3(r.add(1e-20)).mul(max4(abs3(r), 1e-10));
1369
+ const a = vec35(-1).sub(o).div(safe), b = vec35(1).sub(o).div(safe);
1370
+ const enter = max4(max4(min2(a, b).x, min2(a, b).y), min2(a, b).z).max(0);
1371
+ const exit = min2(min2(max4(a, b).x, max4(a, b).y), max4(a, b).z);
1372
+ const rayBounds = viewBounds?.(builder, int5(attribute3("boxId", "float")), o, r, enter, exit);
882
1373
  const occupiedStart = enter.toVar();
883
1374
  if (occupancy) {
884
1375
  const gridOrigin = o.add(1).mul(gridSize / 2);
885
1376
  const gridRay = r.mul(gridSize / 2);
886
1377
  const step = sign3(gridRay.add(1e-20));
887
- const cell = floor(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
888
- const inverse = vec33(1).div(safe.mul(gridSize / 2));
1378
+ const cell = floor2(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
1379
+ const inverse = vec35(1).div(safe.mul(gridSize / 2));
889
1380
  const delta = abs3(inverse);
890
1381
  const next = cell.add(step.add(1).mul(0.5)).sub(gridOrigin).mul(inverse).toVar();
891
1382
  const t = enter.toVar();
892
1383
  occupiedStart.assign(exit.add(1));
893
- Loop(gridSize * 3 + 1, () => {
894
- If3(t.greaterThan(exit), () => {
1384
+ Loop2(gridSize * 3 + 1, () => {
1385
+ If4(t.greaterThan(exit), () => {
895
1386
  Break();
896
1387
  });
897
- const cellIndex = uint(
1388
+ const cellIndex = uint2(
898
1389
  cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2))
899
1390
  ).toVar();
900
- const word = textureLoad3(
1391
+ const word = textureLoad5(
901
1392
  occupancy,
902
- ivec23(int3(cellIndex.shiftRight(5)), int3(attribute3("boxId", "float")))
1393
+ ivec25(int5(cellIndex.shiftRight(5)), int5(attribute3("boxId", "float")))
903
1394
  ).r;
904
1395
  const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
905
- If3(support.notEqual(uint(0)), () => {
1396
+ If4(support.notEqual(uint2(0)), () => {
906
1397
  occupiedStart.assign(t);
907
1398
  Break();
908
1399
  });
909
- const edge = min(min(next.x, next.y), next.z).toVar();
910
- const advance = vec33(
1400
+ const edge = min2(min2(next.x, next.y), next.z).toVar();
1401
+ const advance = vec35(
911
1402
  next.x.lessThanEqual(edge).select(1, 0),
912
1403
  next.y.lessThanEqual(edge).select(1, 0),
913
1404
  next.z.lessThanEqual(edge).select(1, 0)
@@ -915,7 +1406,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
915
1406
  cell.addAssign(advance.mul(step));
916
1407
  next.addAssign(advance.mul(delta));
917
1408
  t.assign(edge);
918
- If3(
1409
+ If4(
919
1410
  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)),
920
1411
  () => {
921
1412
  Break();
@@ -924,19 +1415,19 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
924
1415
  });
925
1416
  }
926
1417
  const look = toBox(ray).negate();
927
- const bestT = exit.add(1).toVar(), bestUv = vec23(0).toVar(), bestNormal = vec33(0, 0, 1).toVar(), valid = float3(0).toVar(), found = float3(0).toVar();
1418
+ const bestT = exit.add(1).toVar(), bestUv = vec24(0).toVar(), bestFace = int5(0).toVar(), appearanceNear = preferFacingCapture ? float4(0).toVar() : null, valid = float4(0).toVar(), found = float4(0).toVar();
928
1419
  const angles = abs3(look).toVar();
929
1420
  const major = angles.x.greaterThanEqual(angles.y).and(angles.x.greaterThanEqual(angles.z)).select(
930
- int3(0),
931
- angles.y.greaterThanEqual(angles.z).select(int3(1), int3(2))
1421
+ int5(0),
1422
+ angles.y.greaterThanEqual(angles.z).select(int5(1), int5(2))
932
1423
  ).toVar();
933
1424
  const nextAxis = major.add(1).mod(3), lastAxis = major.add(2).mod(3);
934
1425
  const second = angles.element(nextAxis).greaterThanEqual(angles.element(lastAxis)).select(nextAxis, lastAxis).toVar();
935
- const third = int3(3).sub(major).sub(second).toVar();
936
- Loop(
1426
+ const third = int5(3).sub(major).sub(second).toVar();
1427
+ Loop2(
937
1428
  { start: 0, end: 6, type: "int", name: "viewIndex" },
938
1429
  ({ viewIndex: i }) => {
939
- If3(occupiedStart.greaterThan(exit), () => {
1430
+ If4(occupiedStart.greaterThan(exit), () => {
940
1431
  Break();
941
1432
  });
942
1433
  valid.assign(0);
@@ -946,112 +1437,133 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
946
1437
  look.element(axis).greaterThanEqual(0),
947
1438
  look.element(axis).lessThan(0)
948
1439
  );
949
- const face = axis.mul(2).add(positive.select(int3(0), int3(1)));
1440
+ const face = axis.mul(2).add(positive.select(int5(0), int5(1)));
1441
+ const bounds = rayBounds?.(face, enter, exit);
950
1442
  const facing = positive.select(1, -1);
951
- const n = vec33(
952
- axis.equal(0).select(facing, 0),
953
- axis.equal(1).select(facing, 0),
954
- axis.equal(2).select(facing, 0)
955
- ).toVar();
956
- const right = axis.equal(0).select(
957
- vec33(0, 0, facing.negate()),
958
- axis.equal(1).select(vec33(1, 0, 0), vec33(facing, 0, 0))
959
- ).toVar();
960
- const up = axis.equal(1).select(vec33(0, 0, facing.negate()), vec33(0, 1, 0)).toVar();
1443
+ const { n, right, up } = faceBasis(axis, facing);
961
1444
  const direction = i.lessThan(3).select(1, -1);
962
- const rect = textureLoad3(
1445
+ const rect = textureLoad5(
963
1446
  rects,
964
- ivec23(face, int3(attribute3("boxId", "float")))
1447
+ ivec25(face, int5(attribute3("boxId", "float")))
965
1448
  ).toVar();
966
1449
  const sampleUv = (p) => rect.xy.add(
967
- vec23(dot3(p, right), dot3(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1450
+ vec24(dot4(p, right), dot4(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
968
1451
  );
969
1452
  const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
970
1453
  const depthAt = (uv2) => decode(texture3(maps.normalDepth, uv2).level(0));
1454
+ const projectedOrigin = vec24(dot4(o, right), dot4(o, up)).toVar();
1455
+ const projectedRay = vec24(dot4(r, right), dot4(r, up)).toVar();
1456
+ const axialOrigin = dot4(o, n).toVar();
1457
+ const axialRay = dot4(r, n).toVar();
971
1458
  const distance = (t) => {
972
- const p = o.add(r.mul(t));
973
- return dot3(p, n).sub(float3(1).sub(depthAt(sampleUv(p)).mul(2))).mul(direction);
1459
+ const uv2 = rect.xy.add(
1460
+ projectedOrigin.add(projectedRay.mul(t)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1461
+ );
1462
+ return axialOrigin.add(axialRay.mul(t)).sub(float4(1).sub(depthAt(uv2).mul(2))).mul(direction);
974
1463
  };
975
1464
  const acceptHit = (hitT) => {
976
1465
  const point2 = o.add(r.mul(hitT)), uv2 = sampleUv(point2);
977
- const texel = ivec23(uv2.mul(descriptor.atlasResolution));
978
- const nearest = textureLoad3(maps.normalDepth, texel);
1466
+ const texel = ivec25(uv2.mul(descriptor.atlasResolution));
1467
+ const nearest = textureLoad5(maps.normalDepth, texel);
979
1468
  const capturedBase = texture3(maps.baseColor, uv2).level(0);
980
- const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1469
+ const occupied = textureLoad5(maps.orm, texel).a.greaterThan(0.5);
981
1470
  const residual = abs3(
982
- dot3(point2, n).sub(float3(1).sub(decode(nearest).mul(2)))
1471
+ dot4(point2, n).sub(float4(1).sub(decode(nearest).mul(2)))
983
1472
  );
984
- const tolerance = max3(
985
- dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
986
- dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
987
- ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
988
- If3(
1473
+ const tolerance = max4(
1474
+ dot4(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
1475
+ dot4(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
1476
+ ).div(dot4(abs3(n), half)).mul(4).add(4 / 65535);
1477
+ If4(
989
1478
  residual.lessThanEqual(tolerance).and(occupied).and(
990
1479
  capturedBase.a.greaterThanEqual(minimumAlpha)
991
1480
  ),
992
1481
  () => {
993
1482
  valid.assign(1);
994
- If3(hitT.lessThan(bestT), () => {
1483
+ If4(hitT.lessThan(bestT), () => {
995
1484
  bestT.assign(hitT);
996
- bestUv.assign(uv2);
997
- found.assign(1);
998
- 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);
999
- const normal2 = vec33(
1000
- packed.x,
1001
- packed.y,
1002
- float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1003
- ).toVar();
1004
- If3(normal2.z.lessThan(0), () => {
1005
- normal2.xy.assign(
1006
- vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20)))
1485
+ const useAppearance = () => {
1486
+ bestUv.assign(uv2);
1487
+ bestFace.assign(face);
1488
+ };
1489
+ if (preferFacingCapture) {
1490
+ const texel2 = max4(
1491
+ dot4(abs3(right), half).div(rect.z),
1492
+ dot4(abs3(up), half).div(rect.w)
1493
+ ).div(descriptor.atlasResolution);
1494
+ const uncertainty = min2(
1495
+ texel2,
1496
+ residual.add(2 / 65535).div(abs3(axialRay).max(1e-10))
1007
1497
  );
1008
- });
1009
- bestNormal.assign(
1010
- fromBox(
1011
- right.mul(normal2.x).add(up.mul(normal2.y)).add(n.mul(normal2.z))
1012
- ).normalize()
1013
- );
1014
- bestNormal.mulAssign(
1015
- dot3(bestNormal, ray).greaterThan(0).select(-1, 1)
1016
- );
1498
+ If4(found.lessThan(0.5).or(hitT.add(uncertainty).lessThan(appearanceNear)), () => {
1499
+ appearanceNear.assign(hitT.sub(uncertainty));
1500
+ useAppearance();
1501
+ });
1502
+ } else useAppearance();
1503
+ found.assign(1);
1017
1504
  });
1018
1505
  }
1019
1506
  );
1020
1507
  };
1021
1508
  const traceInterval = (start, end, steps) => {
1022
- const footprint = vec23(dot3(r, right), dot3(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
1023
- const samples = max3(float3(steps), max3(footprint.x, footprint.y).mul(steps / 8)).div(2).ceil().mul(2).toVar();
1024
- const step = end.sub(start).div(samples);
1025
- const previous = start.toVar(), previousD = distance(start).toVar();
1026
- If3(previousD.lessThanEqual(0), () => {
1509
+ const footprint = vec24(dot4(r, right), dot4(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
1510
+ let density = steps / 8;
1511
+ if (descriptor.alphaMode === "blend" && transparency === "blended" && steps < 32) {
1512
+ density = i.equal(0).select(steps / 16, steps / 32);
1513
+ } else if (descriptor.alphaMode === "opaque" && steps === 16) {
1514
+ density = found.greaterThan(0.5).select(1, 2);
1515
+ }
1516
+ const samples = max4(float4(steps), max4(footprint.x, footprint.y).mul(density)).div(2).ceil().mul(2).toVar();
1517
+ const step = end.sub(start).div(samples).toVar();
1518
+ const pairs = int5(samples.div(2));
1519
+ const pairAt = (t) => t.sub(start).div(max4(step.mul(2), 1e-15));
1520
+ const firstPair = bounds ? int5(floor2(pairAt(bounds.start))).clamp(0, pairs).toVar() : int5(0);
1521
+ const lastPair = bounds ? int5(pairAt(bounds.end).ceil()).clamp(0, pairs).toVar() : pairs;
1522
+ const previous = start.toVar();
1523
+ if (bounds) If4(firstPair.greaterThan(0), () => {
1524
+ previous.assign(start.add(step.mul(float4(firstPair.mul(2)))));
1525
+ });
1526
+ const previousD = distance(previous).toVar();
1527
+ const atEntry = bounds ? firstPair.equal(0).and(start.greaterThanEqual(bounds.start)).and(start.lessThanEqual(bounds.end)) : null;
1528
+ If4(atEntry ? atEntry.and(previousD.lessThanEqual(0)) : previousD.lessThanEqual(0), () => {
1027
1529
  acceptHit(start);
1028
1530
  });
1029
- Loop({ start: int3(0), end: int3(samples.div(2)), type: "int" }, ({ i: i2 }) => {
1030
- If3(valid.greaterThan(0.5), () => {
1531
+ Loop2({ start: firstPair, end: lastPair, type: "int" }, ({ i: i2 }) => {
1532
+ If4(valid.greaterThan(0.5).or(previous.greaterThan(bestT)), () => {
1031
1533
  Break();
1032
1534
  });
1033
- const samples2 = [1, 2].map((offset) => {
1034
- const t = start.add(step.mul(float3(i2.mul(2).add(offset)))).toVar();
1535
+ const [first, second2] = [1, 2].map((offset) => {
1536
+ const t = start.add(step.mul(float4(i2.mul(2).add(offset)))).toVar();
1035
1537
  return { t, d: distance(t).toVar() };
1036
1538
  });
1037
- for (const { t, d } of samples2) {
1038
- If3(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
1039
- Break();
1040
- });
1041
- If3(valid.lessThan(0.5).and(d.mul(previousD).lessThanEqual(0)), () => {
1042
- const crossing = refineSurfaceCrossing({ float: float3, If: If3, Loop }, { lo: previous, hi: t, loValue: previousD, hiValue: d, height: distance, steps: 3, secant: true });
1043
- acceptHit(crossing);
1044
- If3(bestT.lessThanEqual(t), () => {
1045
- Break();
1539
+ const crossesFirst = first.d.mul(previousD).lessThanEqual(0);
1540
+ const crossesSecond = second2.d.mul(first.d).lessThanEqual(0);
1541
+ If4(crossesFirst.or(crossesSecond), () => {
1542
+ for (const [{ t, d }, crosses] of [[first, crossesFirst], [second2, crossesSecond]]) {
1543
+ If4(crosses.and(valid.lessThan(0.5)).and(previous.lessThanEqual(bestT)), () => {
1544
+ const crossing = refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, {
1545
+ lo: previous,
1546
+ hi: t,
1547
+ loValue: previousD,
1548
+ hiValue: d,
1549
+ height: distance,
1550
+ steps: 3,
1551
+ secant: true
1552
+ });
1553
+ acceptHit(crossing);
1046
1554
  });
1047
- });
1048
- previous.assign(t);
1049
- previousD.assign(d);
1050
- }
1555
+ previous.assign(t);
1556
+ previousD.assign(d);
1557
+ }
1558
+ }).Else(() => {
1559
+ previous.assign(second2.t);
1560
+ previousD.assign(second2.d);
1561
+ });
1051
1562
  });
1052
1563
  };
1053
- If3(
1054
- exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3)),
1564
+ const supported = exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3));
1565
+ If4(
1566
+ bounds ? supported.and(bounds.start.lessThanEqual(bestT)).and(bounds.end.greaterThanEqual(occupiedStart)) : supported,
1055
1567
  () => {
1056
1568
  if (!accelerated) {
1057
1569
  traceInterval(enter, exit, descriptor.raySteps);
@@ -1064,13 +1576,13 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1064
1576
  )
1065
1577
  );
1066
1578
  const interval = positive.select(depths.xy, depths.zw);
1067
- const initialDepth = float3(1).sub(dot3(o, n)).mul(0.5);
1068
- const depthSlope = dot3(r, n).negate().mul(0.5);
1579
+ const initialDepth = float4(1).sub(dot4(o, n)).mul(0.5);
1580
+ const depthSlope = dot4(r, n).negate().mul(0.5);
1069
1581
  const da = interval.x.sub(2 / 65535).sub(initialDepth).div(depthSlope);
1070
1582
  const db = interval.y.add(2 / 65535).sub(initialDepth).div(depthSlope);
1071
- const start = max3(occupiedStart, min(da, db));
1072
- const end = min(min(exit, bestT), max3(da, db));
1073
- If3(
1583
+ const start = max4(occupiedStart, min2(da, db));
1584
+ const end = min2(min2(exit, bestT), max4(da, db));
1585
+ If4(
1074
1586
  interval.x.lessThanEqual(interval.y).and(end.greaterThanEqual(start)),
1075
1587
  () => {
1076
1588
  const search = () => traceInterval(start, end, descriptor.raySteps);
@@ -1080,12 +1592,12 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1080
1592
  )
1081
1593
  );
1082
1594
  if (hasFlatView) {
1083
- If3(
1595
+ If4(
1084
1596
  interval.y.sub(interval.x).lessThanEqual(1 / 65535),
1085
1597
  () => {
1086
1598
  const t = interval.x.add(interval.y).mul(0.5).sub(initialDepth).div(depthSlope);
1087
- If3(
1088
- t.greaterThanEqual(enter).and(t.lessThanEqual(min(exit, bestT))),
1599
+ If4(
1600
+ t.greaterThanEqual(enter).and(t.lessThanEqual(min2(exit, bestT))),
1089
1601
  () => {
1090
1602
  acceptHit(t);
1091
1603
  }
@@ -1105,57 +1617,65 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1105
1617
  return Result(
1106
1618
  bestUv,
1107
1619
  center.add(fromBox(point.mul(half))),
1108
- bestNormal,
1620
+ bestFace,
1109
1621
  valid
1110
1622
  );
1111
1623
  });
1112
1624
  const hit = raycast().toVar("boxHit");
1113
1625
  hit.toStack();
1114
1626
  const base = texture3(maps.baseColor, hit.get("uv")).level(0), orm = texture3(maps.orm, hit.get("uv")).level(0);
1115
- const coverage = max3(surfaceCoverage(orm.a, base.a), 1e-10);
1116
- 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");
1627
+ const coverage = max4(surfaceCoverage(orm.a, base.a), 1e-10);
1628
+ const hitNormal = Fn5(() => {
1629
+ const face = hit.get("face");
1630
+ const { n, right, up } = faceBasis(face.div(2), face.mod(2).equal(0).select(1, -1));
1631
+ const sampled = texture3(maps.normalDepth, hit.get("uv")).level(0);
1632
+ const local = unpackNormal(sampled.rg.div(coverage));
1633
+ const direction = fromBox(right.mul(local.x).add(up.mul(local.y)).add(n.mul(local.z))).normalize().toVar();
1634
+ return direction.mul(dot4(direction, ray).greaterThan(0).select(-1, 1));
1635
+ })();
1636
+ let color = base.div(coverage), surfaceOrm = orm.rgb.div(coverage), emission = texture3(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage), normal = hitNormal;
1117
1637
  if (settings.interpolation !== "none") {
1118
1638
  const fallbackColor = color, fallbackOrm = surfaceOrm, fallbackEmission = emission, fallbackNormal = normal;
1119
1639
  const Surface = struct2(
1120
1640
  { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
1121
1641
  "BoxSurfaceBlend"
1122
1642
  );
1123
- const blended = Fn4(() => {
1643
+ const blended = Fn5(() => {
1124
1644
  const point = toBox(hit.get("position").sub(center)).div(half);
1125
1645
  const look = toBox(
1126
1646
  perspective.select(normalize2(eye.sub(hit.get("position"))), viewAxis)
1127
1647
  );
1128
- const colors = vec44(0).toVar(), materials = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar(), weights = float3(0).toVar();
1648
+ const colors = vec46(0).toVar(), materials = vec35(0).toVar(), emissions = vec35(0).toVar(), normals = vec35(0).toVar(), weights = float4(0).toVar();
1129
1649
  for (let axis = 0; axis < 3; axis++) {
1130
1650
  const positive = look.element(axis).greaterThanEqual(0);
1131
1651
  const front = BOX_FACE_AXES[axis * 2], back = BOX_FACE_AXES[axis * 2 + 1];
1132
- const n = positive.select(vec33(...front.normal), vec33(...back.normal));
1652
+ const n = positive.select(vec35(...front.normal), vec35(...back.normal));
1133
1653
  const right = positive.select(
1134
- vec33(...front.right),
1135
- vec33(...back.right)
1654
+ vec35(...front.right),
1655
+ vec35(...back.right)
1136
1656
  );
1137
- const up = positive.select(vec33(...front.up), vec33(...back.up));
1138
- const face = positive.select(int3(axis * 2), int3(axis * 2 + 1));
1139
- const rect = textureLoad3(
1657
+ const up = positive.select(vec35(...front.up), vec35(...back.up));
1658
+ const face = positive.select(int5(axis * 2), int5(axis * 2 + 1));
1659
+ const rect = textureLoad5(
1140
1660
  rects,
1141
- ivec23(face, int3(attribute3("boxId", "float")))
1661
+ ivec25(face, int5(attribute3("boxId", "float")))
1142
1662
  );
1143
1663
  const uv2 = rect.xy.add(
1144
- vec23(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1664
+ vec24(dot4(point, right), dot4(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1145
1665
  );
1146
- const texel = ivec23(uv2.mul(descriptor.atlasResolution));
1147
- const captured = textureLoad3(maps.normalDepth, texel);
1666
+ const texel = ivec25(uv2.mul(descriptor.atlasResolution));
1667
+ const captured = textureLoad5(maps.normalDepth, texel);
1148
1668
  const sampled = texture3(maps.baseColor, uv2).level(0);
1149
1669
  const sampledOrm = texture3(maps.orm, uv2).level(0);
1150
- const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1670
+ const occupied = textureLoad5(maps.orm, texel).a.greaterThan(0.5);
1151
1671
  const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
1152
- const tolerance = max3(
1153
- dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
1154
- dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
1155
- ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
1156
- If3(
1672
+ const tolerance = max4(
1673
+ dot4(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
1674
+ dot4(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
1675
+ ).div(dot4(abs3(n), half)).mul(4).add(4 / 65535);
1676
+ If4(
1157
1677
  occupied.and(sampled.a.greaterThanEqual(minimumAlpha)).and(
1158
- abs3(dot3(point, n).sub(float3(1).sub(depth.mul(2)))).lessThanEqual(
1678
+ abs3(dot4(point, n).sub(float4(1).sub(depth.mul(2)))).lessThanEqual(
1159
1679
  tolerance
1160
1680
  )
1161
1681
  ),
@@ -1164,28 +1684,28 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1164
1684
  const filtered = filtering ? texture3(maps.normalDepth, uv2).level(0).toVar() : captured;
1165
1685
  let weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
1166
1686
  if (filtering) {
1167
- const error = abs3(dot3(point, n).sub(float3(1).sub(
1687
+ const error = abs3(dot4(point, n).sub(float4(1).sub(
1168
1688
  filtered.b.mul(65280).add(filtered.a.mul(255)).div(65535).mul(2)
1169
1689
  )));
1170
- weight = weight.mul(float3(1).sub(error.div(tolerance)).clamp(0, 1));
1690
+ weight = weight.mul(float4(1).sub(error.div(tolerance)).clamp(0, 1));
1171
1691
  }
1172
- const coverage2 = max3(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
1692
+ const coverage2 = max4(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
1173
1693
  colors.addAssign(sampled.div(coverage2).mul(weight));
1174
1694
  materials.addAssign(sampledOrm.rgb.div(coverage2).mul(weight));
1175
1695
  emissions.addAssign(
1176
1696
  texture3(maps.emissive, uv2).level(0).rgb.div(coverage2).mul(weight)
1177
1697
  );
1178
1698
  let shadingNormal;
1179
- if (filtering) shadingNormal = filteredNormal(uv2, float3(1).sub(dot3(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1699
+ if (filtering) shadingNormal = filteredNormal(uv2, float4(1).sub(dot4(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1180
1700
  else {
1181
1701
  const packed = captured.rg.mul(2).sub(1);
1182
- const decoded = vec33(
1702
+ const decoded = vec35(
1183
1703
  packed,
1184
- float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1704
+ float4(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1185
1705
  ).toVar();
1186
- If3(decoded.z.lessThan(0), () => {
1706
+ If4(decoded.z.lessThan(0), () => {
1187
1707
  decoded.xy.assign(
1188
- vec23(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1708
+ vec24(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1189
1709
  );
1190
1710
  });
1191
1711
  shadingNormal = decoded;
@@ -1199,7 +1719,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1199
1719
  }
1200
1720
  );
1201
1721
  }
1202
- const divisor = max3(weights, 1e-10), valid = weights.greaterThan(1e-10);
1722
+ const divisor = max4(weights, 1e-10), valid = weights.greaterThan(1e-10);
1203
1723
  return Surface(
1204
1724
  valid.select(colors.div(divisor), fallbackColor),
1205
1725
  valid.select(materials.div(divisor), fallbackOrm),
@@ -1212,9 +1732,10 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1212
1732
  emission = blended.get("emission");
1213
1733
  normal = blended.get("normal");
1214
1734
  }
1215
- material.capturedPositionNode = hit.get("position");
1735
+ const position = meshPoint(hit.get("position")).toVar("boxHitMeshPosition");
1736
+ material.capturedPositionNode = position;
1216
1737
  material.colorNode = color.rgb;
1217
- material.normalNode = transformNormalToView3(normal);
1738
+ material.normalNode = transformNormalToView3(meshNormal(normal));
1218
1739
  material.roughnessNode = surfaceOrm.g;
1219
1740
  material.metalnessNode = surfaceOrm.b;
1220
1741
  material.aoNode = surfaceOrm.r;
@@ -1229,9 +1750,9 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1229
1750
  }
1230
1751
  material.maskNode = hit.get("valid").greaterThan(0.5);
1231
1752
  material.maskShadowNode = material.maskNode;
1232
- material.depthNode = capturedSurfaceDepth(hit.get("position"));
1753
+ material.depthNode = capturedSurfaceDepth(position);
1233
1754
  material.receivedShadowPositionNode = modelWorldMatrix3.mul(
1234
- vec44(hit.get("position"), 1)
1755
+ vec46(position, 1)
1235
1756
  ).xyz;
1236
1757
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
1237
1758
  return material;