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