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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  }
@@ -281,9 +281,9 @@ 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
289
  varying,
@@ -293,22 +293,22 @@ import {
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,
296
+ vec2 as vec24,
297
+ vec3 as vec34,
298
+ vec4 as vec45,
299
+ float as float4,
300
+ int as int4,
301
+ uint as uint2,
302
302
  dot as dot3,
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 textureLoad4,
309
+ ivec2 as ivec24,
310
310
  normalize as normalize2,
311
- floor,
311
+ floor as floor2,
312
312
  fract,
313
313
  modelWorldMatrix as modelWorldMatrix3,
314
314
  cameraNear as cameraNear2,
@@ -340,12 +340,364 @@ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
340
340
  }
341
341
  };
342
342
 
343
+ // src/box-impostor/box-impostor-ray-bounds.js
344
+ import { Matrix4, NodeUpdateType, StorageBufferAttribute, Vector3 } from "three/webgpu";
345
+ import {
346
+ Fn as Fn2,
347
+ If,
348
+ Loop,
349
+ atomicMin,
350
+ atomicStore,
351
+ clamp,
352
+ float,
353
+ floor,
354
+ instanceIndex,
355
+ int,
356
+ ivec2,
357
+ max,
358
+ min,
359
+ storage,
360
+ textureLoad,
361
+ uint,
362
+ vec2,
363
+ vec3,
364
+ vec4 as vec43
365
+ } from "three/tsl";
366
+ var MIN_TILE_SIZE = 3;
367
+ var MAX_CAPTURE_TILES = 512 * 1024;
368
+ var REFRESH_ANGLE_SQUARED = Math.tan(Math.PI / 360) ** 2;
369
+ var DEPTH_MAX = 65535;
370
+ var MAX_VIEW_BYTES = 16 * 1024 * 1024;
371
+ var MAX_CACHED_VIEW_BYTES = 64 * 1024 * 1024;
372
+ function buffer(length, components = 1, Type = Float32Array) {
373
+ return new StorageBufferAttribute(length, components, Type);
374
+ }
375
+ function captureTiles(descriptor) {
376
+ const faces = descriptor.boxes.flatMap(
377
+ (box, id) => BOX_FACE_AXES.map((axes, face) => {
378
+ const [, , width, height] = box.views[face];
379
+ const w = width - 2 * descriptor.padding, h = height - 2 * descriptor.padding;
380
+ const right = axes.right.findIndex(Boolean), up = axes.up.findIndex(Boolean);
381
+ const tolerance = 4 * Math.max(box.halfSize[right] / w, box.halfSize[up] / h) / box.halfSize[face >> 1] + 5 / DEPTH_MAX;
382
+ return { key: id * 6 + face, w, h, tolerance };
383
+ })
384
+ );
385
+ const countFor = (size2) => faces.reduce((n, f) => n + Math.ceil((f.w + 2) / size2) * Math.ceil((f.h + 2) / size2), 0);
386
+ let size = MIN_TILE_SIZE;
387
+ while (countFor(size) > MAX_CAPTURE_TILES) size *= 2;
388
+ const tiles = buffer(countFor(size), 4);
389
+ let offset = 0;
390
+ for (const { key, w, h, tolerance } of faces) {
391
+ for (let y = -1; y <= h; y += size) {
392
+ for (let x = -1; x <= w; x += size) {
393
+ tiles.array[offset] = key;
394
+ tiles.array[offset + 1] = x;
395
+ tiles.array[offset + 2] = y;
396
+ tiles.array[offset + 3] = tolerance;
397
+ offset += 4;
398
+ }
399
+ }
400
+ }
401
+ return { tiles, size };
402
+ }
403
+ function buildPatches(descriptor, maps, rects, tiles, size, output) {
404
+ const descriptions = storage(tiles, "vec4", tiles.count).toReadOnly();
405
+ const patches = storage(output, "vec4", output.count);
406
+ return Fn2(() => {
407
+ const meta = descriptions.element(instanceIndex).toVar();
408
+ const key = int(meta.x), face = key.mod(6), axis = face.div(2);
409
+ const rect = textureLoad(rects, ivec2(face, key.div(6))).mul(descriptor.atlasResolution).round().toVar();
410
+ const extent = ivec2(rect.zw.add(1).sub(meta.yz)).min(ivec2(size));
411
+ const origin = ivec2(rect.xy.add(meta.yz));
412
+ const near = float(1).toVar(), far = float(0).toVar();
413
+ function visit(process) {
414
+ Loop({ start: int(0), end: extent.y, type: "int", name: "row" }, ({ row }) => {
415
+ Loop({ start: int(0), end: extent.x, type: "int", name: "column" }, ({ column }) => {
416
+ const pixel = origin.add(ivec2(column, row));
417
+ If(textureLoad(maps.orm, pixel).a.greaterThan(0.5), () => {
418
+ const packed = textureLoad(maps.normalDepth, pixel);
419
+ const depth = packed.b.mul(65280).add(packed.a.mul(255)).div(DEPTH_MAX).toVar();
420
+ process(column, row, depth);
421
+ });
422
+ });
423
+ });
424
+ }
425
+ visit((x, y, depth) => {
426
+ near.assign(min(near, depth));
427
+ far.assign(max(far, depth));
428
+ });
429
+ const middle = near.add(far).mul(0.5).toVar();
430
+ const low = [vec3(2).toVar(), vec3(2).toVar()], high = [vec3(-2).toVar(), vec3(-2).toVar()];
431
+ visit((x, y, depth) => {
432
+ const uv2 = meta.yz.add(vec2(x, y)).div(rect.zw).mul(2).sub(1);
433
+ const lo = vec3(uv2.clamp(-1, 1), float(1).sub(depth.mul(2)).sub(meta.w).max(-1)).toVar();
434
+ const hi = vec3(
435
+ uv2.add(vec2(2).div(rect.zw)).clamp(-1, 1),
436
+ float(1).sub(depth.mul(2)).add(meta.w).min(1)
437
+ ).toVar();
438
+ lo.toStack();
439
+ hi.toStack();
440
+ const extend = (group) => {
441
+ low[group].assign(min(low[group], lo));
442
+ high[group].assign(max(high[group], hi));
443
+ };
444
+ If(depth.lessThanEqual(middle), () => {
445
+ extend(0);
446
+ }).Else(() => {
447
+ extend(1);
448
+ });
449
+ });
450
+ const facing = face.mod(2).equal(0).select(1, -1);
451
+ const right = axis.equal(0).select(vec3(0, 0, facing.negate()), axis.equal(1).select(vec3(1, 0, 0), vec3(facing, 0, 0)));
452
+ const up = axis.equal(1).select(vec3(0, 0, facing.negate()), vec3(0, 1, 0));
453
+ const normal = right.cross(up);
454
+ const rotate = (p) => right.mul(p.x).add(up.mul(p.y)).add(normal.mul(p.z));
455
+ for (let group = 0; group < 2; group++) {
456
+ const a = rotate(low[group]), b = rotate(high[group]), slot = instanceIndex.mul(4).add(group * 2);
457
+ const valid = low[group].x.lessThanEqual(high[group].x);
458
+ patches.element(slot).assign(vec43(min(a, b), valid.select(meta.x, -1)));
459
+ patches.element(slot.add(1)).assign(vec43(max(a, b), 0));
460
+ }
461
+ })().compute(tiles.count);
462
+ }
463
+ function makeViewPasses(patchBuffer, views, ranges, count, resolution) {
464
+ const table = storage(ranges, "uint", count).toAtomic();
465
+ const reset = Fn2(() => {
466
+ atomicStore(table.element(instanceIndex), uint(DEPTH_MAX));
467
+ })().compute(count);
468
+ const patches = storage(patchBuffer, "vec4", patchBuffer.count).toReadOnly();
469
+ const scatter = Fn2(() => {
470
+ const a = patches.element(instanceIndex.mul(2)).toVar(), b = patches.element(instanceIndex.mul(2).add(1)).toVar();
471
+ If(a.w.greaterThanEqual(0), () => {
472
+ const key = int(a.w), box = key.div(6);
473
+ const mapping = views.element(box.mul(2)), reference = views.element(box.mul(2).add(1));
474
+ If(reference.w.greaterThanEqual(0), () => {
475
+ const axis = int(reference.w).mod(3), x = axis.add(1).mod(3), y = axis.add(2).mod(3);
476
+ const e = vec2(reference.element(x), reference.element(y)), ez = reference.element(axis);
477
+ const za = a.element(axis), zb = b.element(axis);
478
+ const weight = reference.w.lessThan(3).select(1, 0).toVar();
479
+ const eyeSlope = e.div(ez).toVar(), inverseDistance = weight.div(ez).toVar();
480
+ const project = (v, z) => v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
481
+ const l = vec2(a.element(x), a.element(y)), h = vec2(b.element(x), b.element(y));
482
+ const cell = (v, bias) => ivec2(floor(v.sub(mapping.xy).mul(mapping.zw).add(bias)).clamp(0, resolution - 1));
483
+ const lo = cell(min(project(l, za), project(l, zb)), -5e-3);
484
+ const hi = cell(max(project(h, za), project(h, zb)), 5e-3);
485
+ const padding = vec2(0.506).div(mapping.zw).mul(inverseDistance.abs().add(1)).add(2e-6);
486
+ Loop({ start: lo.y, end: hi.y.add(1), type: "int", name: "row" }, ({ row }) => {
487
+ Loop({ start: lo.x, end: hi.x.add(1), type: "int", name: "column" }, ({ column }) => {
488
+ const uv2 = vec2(column, row).add(0.5).div(mapping.zw).add(mapping.xy);
489
+ const slope = eyeSlope.sub(uv2.mul(inverseDistance)).toVar();
490
+ const safe = slope.add(1e-30).sign().mul(slope.abs().max(1e-12));
491
+ const ta = l.sub(padding).sub(uv2).div(safe).toVar(), tb = h.add(padding).sub(uv2).div(safe).toVar();
492
+ 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)));
493
+ If(begin.lessThanEqual(end), () => {
494
+ const depths = floor(
495
+ vec2(begin.add(1), float(1).sub(end)).mul(DEPTH_MAX / 2).sub(0.02)
496
+ ).max(0);
497
+ const i = key.mul(resolution).add(row).mul(resolution).add(column).mul(2);
498
+ atomicMin(table.element(i), uint(depths.x));
499
+ atomicMin(table.element(i.add(1)), uint(depths.y));
500
+ });
501
+ });
502
+ });
503
+ });
504
+ });
505
+ })().compute(patchBuffer.count / 2);
506
+ return { reset, scatter, table };
507
+ }
508
+ function setProjection(data, descriptor, reference, orthographic, resolution) {
509
+ for (const [id, box] of descriptor.boxes.entries()) {
510
+ const p = box.axes.map(
511
+ (axis2, i) => axis2.reduce(
512
+ (sum, v, k) => sum + v * (orthographic ? reference[k] : reference[k] - box.center[k]),
513
+ 0
514
+ ) / box.halfSize[i]
515
+ );
516
+ const axis = p.map(Math.abs).indexOf(Math.max(...p.map(Math.abs)));
517
+ const ez = p[axis], offset = id * 8;
518
+ if (orthographic ? Math.abs(ez) < 1e-12 : Math.abs(ez) <= 1.01) {
519
+ data[offset + 7] = -1;
520
+ continue;
521
+ }
522
+ for (let j = 0; j < 2; j++) {
523
+ const e = p[(axis + 1 + j) % 3];
524
+ const project = (v, z) => orthographic ? v - z * e / ez : (v * ez - z * e) / (ez - z);
525
+ const low = Math.min(project(-1, -1), project(-1, 1));
526
+ const high = Math.max(project(1, -1), project(1, 1));
527
+ data[offset + j] = low;
528
+ data[offset + j + 2] = resolution / (high - low);
529
+ }
530
+ data.set(p, offset + 4);
531
+ data[offset + 7] = axis + (orthographic ? 3 : 0);
532
+ }
533
+ }
534
+ function createBoxRayBounds(descriptor, maps, rects, material) {
535
+ const boxes = descriptor.boxes.length;
536
+ const resolution = Math.min(128, Math.floor(Math.sqrt(MAX_VIEW_BYTES / (48 * boxes))));
537
+ if (resolution < 32 || descriptor.atlasResolution < 512 || [maps.normalDepth, maps.orm].some((map) => map.isRenderTargetTexture || map.isVideoTexture))
538
+ return null;
539
+ const count = boxes * 6 * resolution ** 2 * 2;
540
+ const maxViews = Math.max(1, Math.floor(MAX_CACHED_VIEW_BYTES / (count * 4 + boxes * 32)));
541
+ const inactiveView = buffer(boxes * 2, 4);
542
+ for (let i = 0; i < boxes; i++) inactiveView.array.set([0, 0, 1, 1, 2, 0, 0, -1], i * 8);
543
+ const inactiveRanges = buffer(1, 1, Uint32Array);
544
+ const views = storage(inactiveView, "vec4", boxes * 2).toReadOnly();
545
+ const ranges = storage(inactiveRanges, "uint").toReadOnly();
546
+ const inverse = new Matrix4(), eye = new Vector3(), center = new Vector3();
547
+ const states = /* @__PURE__ */ new Map();
548
+ let tiles, patches, reduce, passes;
549
+ function prepare({ renderer, camera, object }) {
550
+ views.value = inactiveView;
551
+ ranges.value = inactiveRanges;
552
+ if (!renderer.backend?.isWebGPUBackend || renderer.xr?.isPresenting || object.isInstancedMesh || !camera.isPerspectiveCamera && !camera.isOrthographicCamera || camera.isArrayCamera)
553
+ return;
554
+ inverse.copy(object.matrixWorld).invert();
555
+ const ortho = camera.isOrthographicCamera === true;
556
+ if (ortho) camera.getWorldDirection(eye).transformDirection(inverse);
557
+ else eye.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(inverse);
558
+ if (!Number.isFinite(eye.lengthSq())) return;
559
+ let state = states.get(renderer);
560
+ if (!state) {
561
+ state = { slots: [], initialized: false };
562
+ states.set(renderer, state);
563
+ }
564
+ if (!tiles) {
565
+ const capture = captureTiles(descriptor);
566
+ tiles = capture.tiles;
567
+ patches = buffer(tiles.count * 4, 4);
568
+ reduce = buildPatches(descriptor, maps, rects, tiles, capture.size, patches);
569
+ const computeViews = storage(inactiveView, "vec4", boxes * 2).toReadOnly();
570
+ passes = {
571
+ ...makeViewPasses(patches, computeViews, inactiveRanges, count, resolution),
572
+ views: computeViews
573
+ };
574
+ }
575
+ if (!state.initialized || state.depthVersion !== maps.normalDepth.version || state.coverageVersion !== maps.orm.version) {
576
+ renderer.compute(reduce);
577
+ for (const slot2 of state.slots) slot2.ready = false;
578
+ state.depthVersion = maps.normalDepth.version;
579
+ state.coverageVersion = maps.orm.version;
580
+ state.initialized = true;
581
+ }
582
+ const frame = renderer.info.render.calls;
583
+ const compatible = (v) => v.ready && v.ortho === ortho && v.eye.distanceToSquared(eye) <= v.radiusSq;
584
+ let slot = state.slots.find((v) => v.object.deref() === object && v.camera.deref() === camera);
585
+ if (!slot || !compatible(slot)) {
586
+ const shared = state.slots.find(compatible);
587
+ if (shared) {
588
+ shared.frame = frame;
589
+ views.value = shared.view;
590
+ ranges.value = shared.ranges;
591
+ return;
592
+ }
593
+ if (slot?.frame === frame) slot = void 0;
594
+ }
595
+ if (!slot) {
596
+ if (state.slots.length < maxViews) {
597
+ slot = { view: buffer(boxes * 2, 4), ranges: buffer(count, 1, Uint32Array), eye: new Vector3() };
598
+ state.slots.push(slot);
599
+ } else {
600
+ slot = state.slots.reduce((oldest, v) => v.frame < oldest.frame ? v : oldest);
601
+ if (slot.frame === frame) {
602
+ let nearest = Infinity;
603
+ for (const v of state.slots) {
604
+ if (!v.ready || v.ortho !== ortho) continue;
605
+ const distance = v.eye.distanceToSquared(eye);
606
+ if (distance < nearest) {
607
+ nearest = distance;
608
+ views.value = v.view;
609
+ ranges.value = v.ranges;
610
+ }
611
+ }
612
+ return;
613
+ }
614
+ }
615
+ slot.object = new WeakRef(object);
616
+ slot.camera = new WeakRef(camera);
617
+ slot.ready = false;
618
+ }
619
+ slot.frame = frame;
620
+ views.value = slot.view;
621
+ ranges.value = slot.ranges;
622
+ if (compatible(slot)) return;
623
+ setProjection(slot.view.array, descriptor, eye.toArray(), ortho, resolution);
624
+ slot.view.needsUpdate = true;
625
+ passes.views.value = slot.view;
626
+ passes.table.value = slot.ranges;
627
+ renderer.compute([passes.reset, passes.scatter]);
628
+ const distanceSquared = ortho ? 1 : Math.min(...descriptor.boxes.map((box) => eye.distanceToSquared(center.fromArray(box.center))));
629
+ slot.radiusSq = distanceSquared * REFRESH_ANGLE_SQUARED;
630
+ slot.eye.copy(eye);
631
+ slot.ortho = ortho;
632
+ slot.ready = true;
633
+ }
634
+ views.updateBeforeType = NodeUpdateType.OBJECT;
635
+ views.updateBefore = prepare;
636
+ material.addEventListener("dispose", () => {
637
+ for (const state of states.values()) {
638
+ for (const slot of state.slots) {
639
+ slot.view.dispose();
640
+ slot.ranges.dispose();
641
+ }
642
+ }
643
+ states.clear();
644
+ reduce?.dispose();
645
+ passes?.reset.dispose();
646
+ passes?.scatter.dispose();
647
+ tiles?.dispose();
648
+ patches?.dispose();
649
+ inactiveView.dispose();
650
+ inactiveRanges.dispose();
651
+ });
652
+ return (builder, id, o, r, enter, exit) => {
653
+ if (!builder.renderer.backend?.isWebGPUBackend) return null;
654
+ const mapping = views.element(id.mul(2)).toVar();
655
+ const ref = views.element(id.mul(2).add(1)).toVar();
656
+ const axis = int(max(ref.w, 0)).mod(3), x = axis.add(1).mod(3), y = axis.add(2).mod(3);
657
+ const rz = r.element(axis).toVar(), oz = o.element(axis).toVar();
658
+ const ez = ref.element(axis), e = vec2(ref.element(x), ref.element(y));
659
+ const eyeSlope = e.div(ez), inverseDistance = ref.w.lessThan(3).select(1, 0).div(ez);
660
+ const project = (t) => {
661
+ const point = o.add(r.mul(t)), v = vec2(point.element(x), point.element(y)), z = point.element(axis);
662
+ const p = v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
663
+ return p.sub(mapping.xy).mul(mapping.zw);
664
+ };
665
+ const a = project(enter).toVar(), b = project(exit).toVar();
666
+ const cellLo = ivec2(floor(min(a, b).sub(1e-3)).clamp(0, resolution - 1)).toVar();
667
+ const cellHi = ivec2(floor(max(a, b).add(1e-3)).clamp(0, resolution - 1)).toVar();
668
+ const valid = ref.w.greaterThanEqual(0).and(rz.abs().greaterThan(1e-12)).and(cellHi.sub(cellLo).lessThanEqual(ivec2(2)).all()).toVar();
669
+ return (face, enter2, exit2) => {
670
+ const start = enter2.toVar(), end = exit2.toVar();
671
+ If(valid, () => {
672
+ const base = id.mul(6).add(face).mul(resolution ** 2);
673
+ const at = (u, v) => base.add(v.mul(resolution)).add(u).mul(2);
674
+ const idx = at(cellLo.x, cellLo.y).toVar();
675
+ const lower = ranges.element(idx).toVar(), upper = ranges.element(idx.add(1)).toVar();
676
+ If(cellHi.notEqual(cellLo).any(), () => {
677
+ Loop({ start: cellLo.y, end: cellHi.y.add(1), type: "int", name: "by" }, ({ by }) => {
678
+ Loop({ start: cellLo.x, end: cellHi.x.add(1), type: "int", name: "bx" }, ({ bx }) => {
679
+ const p = at(bx, by);
680
+ lower.assign(min(lower, ranges.element(p)));
681
+ upper.assign(min(upper, ranges.element(p.add(1))));
682
+ });
683
+ });
684
+ });
685
+ const lo = float(lower).mul(2 / DEPTH_MAX).sub(1), hi = float(1).sub(float(upper).mul(2 / DEPTH_MAX));
686
+ const a2 = lo.sub(oz).div(rz), b2 = hi.sub(oz).div(rz);
687
+ start.assign(min(a2, b2));
688
+ end.assign(lo.lessThanEqual(hi).select(max(a2, b2), enter2.sub(1)));
689
+ });
690
+ return { start, end };
691
+ };
692
+ };
693
+ }
694
+
343
695
  // src/box-impostor/box-impostor-surface-search.js
344
- function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
696
+ function refineSurfaceCrossing({ float: float5, If: If5, Loop: Loop3 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
345
697
  const a = lo.toVar(), b = hi.toVar(), fa = loValue.toVar(), fb = secant ? hiValue.toVar() : null;
346
- Loop2(steps, () => {
698
+ Loop3(steps, () => {
347
699
  const mid = a.add(b).mul(0.5).toVar(), d = height(mid).toVar();
348
- If4(d.mul(fa).greaterThan(0), () => {
700
+ If5(d.mul(fa).greaterThan(0), () => {
349
701
  a.assign(mid);
350
702
  if (secant) fa.assign(d);
351
703
  }).Else(() => {
@@ -359,21 +711,21 @@ function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi
359
711
  // src/box-impostor/box-impostor-faces.js
360
712
  import { DataTexture, FloatType, RGBAFormat, NearestFilter } from "three";
361
713
  import {
362
- Fn as Fn2,
363
- If,
714
+ Fn as Fn3,
715
+ If as If2,
364
716
  attribute,
365
717
  positionLocal,
366
718
  uv,
367
719
  texture,
368
- textureLoad,
369
- ivec2,
370
- vec2,
371
- vec3,
372
- float,
373
- int,
720
+ textureLoad as textureLoad2,
721
+ ivec2 as ivec22,
722
+ vec2 as vec22,
723
+ vec3 as vec32,
724
+ float as float2,
725
+ int as int2,
374
726
  dot,
375
727
  abs,
376
- max,
728
+ max as max2,
377
729
  sign,
378
730
  transformNormalToView
379
731
  } from "three/tsl";
@@ -402,11 +754,11 @@ function applyBoxFaces({
402
754
  planes.minFilter = planes.magFilter = NearestFilter;
403
755
  planes.needsUpdate = true;
404
756
  material.addEventListener("dispose", () => planes.dispose());
405
- const face = int(attribute("boxFace", "float"));
757
+ const face = int2(attribute("boxFace", "float"));
406
758
  const n = attribute("normal", "vec3");
407
- const depth = textureLoad(
759
+ const depth = textureLoad2(
408
760
  planes,
409
- ivec2(face, int(attribute("boxId", "float")))
761
+ ivec22(face, int2(attribute("boxId", "float")))
410
762
  ).r;
411
763
  const proxy = positionLocal.sub(
412
764
  n.mul(
@@ -417,28 +769,28 @@ function applyBoxFaces({
417
769
  material.castShadowPositionNode = proxy;
418
770
  const base = texture(maps.baseColor, uv()).level(0).toVar("boxFaceColor");
419
771
  const orm = texture(maps.orm, uv()).level(0);
420
- const coverage = max(orm.a, 1e-10);
421
- const normal = Fn2(() => {
422
- const packed = textureLoad(
772
+ const coverage = max2(orm.a, 1e-10);
773
+ const normal = Fn3(() => {
774
+ const packed = textureLoad2(
423
775
  maps.normalDepth,
424
- ivec2(uv().mul(descriptor.atlasResolution))
776
+ ivec22(uv().mul(descriptor.atlasResolution))
425
777
  ).rg.mul(2).sub(1);
426
- const decoded = vec3(
778
+ const decoded = vec32(
427
779
  packed,
428
- float(1).sub(abs(packed.x)).sub(abs(packed.y))
780
+ float2(1).sub(abs(packed.x)).sub(abs(packed.y))
429
781
  ).toVar();
430
- If(decoded.z.lessThan(0), () => {
782
+ If2(decoded.z.lessThan(0), () => {
431
783
  decoded.xy.assign(
432
- vec2(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
784
+ vec22(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
433
785
  );
434
786
  });
435
- const result = vec3(0).toVar();
787
+ const result = vec32(0).toVar();
436
788
  for (let f = 0; f < 6; f++) {
437
789
  const a = BOX_FACE_AXES[f];
438
- If(face.equal(f), () => {
790
+ If2(face.equal(f), () => {
439
791
  result.assign(
440
792
  fromBox(
441
- vec3(...a.right).mul(decoded.x).add(vec3(...a.up).mul(decoded.y)).add(vec3(...a.normal).mul(decoded.z))
793
+ vec32(...a.right).mul(decoded.x).add(vec32(...a.up).mul(decoded.y)).add(vec32(...a.normal).mul(decoded.z))
442
794
  ).normalize()
443
795
  );
444
796
  });
@@ -452,7 +804,7 @@ function applyBoxFaces({
452
804
  material.aoNode = orm.r.div(coverage);
453
805
  material.emissiveNode = texture(maps.emissive, uv()).level(0).rgb.div(coverage);
454
806
  material.maskNode = base.a.greaterThanEqual(
455
- transparency === "cutout" ? alphaCutoff : float(1 / 255)
807
+ transparency === "cutout" ? alphaCutoff : float2(1 / 255)
456
808
  );
457
809
  material.maskShadowNode = material.maskNode;
458
810
  if (transparency !== "cutout") material.opacityNode = base.a;
@@ -463,21 +815,21 @@ function applyBoxFaces({
463
815
  // src/box-impostor/box-impostor-projection.js
464
816
  import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter as NearestFilter2 } from "three";
465
817
  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,
818
+ Fn as Fn4,
819
+ If as If3,
820
+ vec2 as vec23,
821
+ vec3 as vec33,
822
+ vec4 as vec44,
823
+ float as float3,
824
+ int as int3,
825
+ ivec2 as ivec23,
474
826
  dot as dot2,
475
827
  abs as abs2,
476
- max as max2,
828
+ max as max3,
477
829
  sign as sign2,
478
830
  normalize,
479
831
  texture as texture2,
480
- textureLoad as textureLoad2,
832
+ textureLoad as textureLoad3,
481
833
  attribute as attribute2,
482
834
  struct,
483
835
  modelWorldMatrix as modelWorldMatrix2,
@@ -527,24 +879,24 @@ function applyBoxProjection({
527
879
  "BoxProjectedSurface"
528
880
  );
529
881
  const readNormal = (uv2, right, up, n) => {
530
- const packed = textureLoad2(
882
+ const packed = textureLoad3(
531
883
  maps.normalDepth,
532
- ivec22(uv2.mul(descriptor.atlasResolution))
884
+ ivec23(uv2.mul(descriptor.atlasResolution))
533
885
  ).rg.mul(2).sub(1);
534
- const decoded = vec32(
886
+ const decoded = vec33(
535
887
  packed,
536
- float2(1).sub(abs2(packed.x)).sub(abs2(packed.y))
888
+ float3(1).sub(abs2(packed.x)).sub(abs2(packed.y))
537
889
  ).toVar();
538
- If2(decoded.z.lessThan(0), () => {
890
+ If3(decoded.z.lessThan(0), () => {
539
891
  decoded.xy.assign(
540
- vec22(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
892
+ vec23(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
541
893
  );
542
894
  });
543
895
  return fromBox(
544
896
  right.mul(decoded.x).add(up.mul(decoded.y)).add(n.mul(decoded.z))
545
897
  ).normalize();
546
898
  };
547
- const surface = Fn3(() => {
899
+ const surface = Fn4(() => {
548
900
  const ray = perspective.select(
549
901
  normalize(raster.sub(eye)),
550
902
  viewAxis.negate()
@@ -555,48 +907,48 @@ function applyBoxProjection({
555
907
  );
556
908
  const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
557
909
  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();
910
+ const positions = vec33(0).toVar();
911
+ const selectedUv = vec23(0).toVar(), selectedRight = vec33(1, 0, 0).toVar(), selectedUp = vec33(0, 1, 0).toVar(), selectedNormal = vec33(0, 0, 1).toVar();
912
+ const nearest = float3(1e20).toVar("boxPlaneDistance");
913
+ const opacity = float3(0).toVar();
562
914
  const candidates = [];
563
915
  for (let axis = 0; axis < 3; axis++) {
564
916
  const angle = angles.element(axis);
565
917
  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));
918
+ const n = positive.select(vec33(...a.normal), vec33(...b.normal)), right = positive.select(vec33(...a.right), vec33(...b.right)), up = positive.select(vec33(...a.up), vec33(...b.up));
567
919
  const weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
568
920
  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(),
921
+ uv: vec23(0).toVar(),
922
+ base: vec44(0).toVar(),
923
+ orm: vec44(0).toVar(),
924
+ t: float3(1e20).toVar(),
925
+ tolerance: float3(0).toVar(),
574
926
  right,
575
927
  up,
576
928
  n,
577
929
  weight
578
930
  };
579
931
  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)
932
+ If3(angle.greaterThan(1e-4), () => {
933
+ const face = positive.select(int3(axis * 2), int3(axis * 2 + 1)), id = int3(attribute2("boxId", "float"));
934
+ const plane = float3(1).sub(
935
+ textureLoad3(planes, ivec23(face, id)).r.mul(2)
584
936
  );
585
- const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max2(abs2(divisor2), 1e-10));
937
+ const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max3(abs2(divisor2), 1e-10));
586
938
  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);
939
+ const xy = vec23(dot2(point, right), dot2(point, up)).mul(0.5).add(0.5);
588
940
  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
941
  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));
942
+ If3(supported, () => {
943
+ const rect = textureLoad3(rects, ivec23(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
592
944
  const base = texture2(maps.baseColor, uv2).level(0), orm = texture2(maps.orm, uv2).level(0);
593
945
  const alpha2 = base.a.clamp(0, 1);
594
- If2(
946
+ If3(
595
947
  alpha2.greaterThanEqual(
596
- transparency === "cutout" ? alphaCutoff : float2(1 / 255)
948
+ transparency === "cutout" ? alphaCutoff : float3(1 / 255)
597
949
  ).and(orm.a.greaterThan(0)),
598
950
  () => {
599
- If2(t.lessThan(nearest), () => {
951
+ If3(t.lessThan(nearest), () => {
600
952
  nearest.assign(t);
601
953
  selectedUv.assign(uv2);
602
954
  opacity.assign(alpha2);
@@ -611,14 +963,14 @@ function applyBoxProjection({
611
963
  candidate.orm.assign(orm);
612
964
  candidate.t.assign(t);
613
965
  candidate.tolerance.assign(
614
- max2(
966
+ max3(
615
967
  dot2(abs2(right), half).div(
616
968
  rect.z.mul(descriptor.atlasResolution)
617
969
  ),
618
970
  dot2(abs2(up), half).div(
619
971
  rect.w.mul(descriptor.atlasResolution)
620
972
  )
621
- ).mul(4).div(max2(angle, 0.1))
973
+ ).mul(4).div(max3(angle, 0.1))
622
974
  );
623
975
  }
624
976
  }
@@ -628,7 +980,7 @@ function applyBoxProjection({
628
980
  }
629
981
  if (settings.interpolation === "none") {
630
982
  const base = texture2(maps.baseColor, selectedUv).level(0), orm = texture2(maps.orm, selectedUv).level(0);
631
- const coverage = max2(orm.a, 1e-10);
983
+ const coverage = max3(orm.a, 1e-10);
632
984
  return Surface(
633
985
  base.rgb.div(coverage),
634
986
  opacity,
@@ -638,15 +990,15 @@ function applyBoxProjection({
638
990
  positions
639
991
  );
640
992
  }
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();
993
+ const colors = vec33(0).toVar(), orms = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar();
994
+ const weights = float3(0).toVar(), support = float3(0).toVar(), alpha = float3(0).toVar();
643
995
  for (const c of candidates) {
644
- If2(
996
+ If3(
645
997
  c.base.a.greaterThan(0).and(c.t.lessThanEqual(nearest.add(c.tolerance))),
646
998
  () => {
647
- const coverage = max2(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
999
+ const coverage = max3(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
648
1000
  weights.addAssign(c.weight.mul(coverage));
649
- support.assign(max2(support, coverage));
1001
+ support.assign(max3(support, coverage));
650
1002
  colors.addAssign(c.base.rgb.div(coverage).mul(w));
651
1003
  orms.addAssign(c.orm.rgb.div(coverage).mul(w));
652
1004
  emissions.addAssign(
@@ -657,13 +1009,13 @@ function applyBoxProjection({
657
1009
  }
658
1010
  );
659
1011
  }
660
- const divisor = max2(alpha, 1e-10);
1012
+ const divisor = max3(alpha, 1e-10);
661
1013
  return Surface(
662
1014
  colors.div(divisor),
663
- alpha.div(max2(weights, 1e-10)).mul(support),
1015
+ alpha.div(max3(weights, 1e-10)).mul(support),
664
1016
  orms.div(divisor),
665
1017
  emissions.div(divisor),
666
- normals.div(max2(normals.length(), 1e-10)),
1018
+ normals.div(max3(normals.length(), 1e-10)),
667
1019
  positions
668
1020
  );
669
1021
  })().toVar("boxProjectedSurface");
@@ -674,12 +1026,12 @@ function applyBoxProjection({
674
1026
  material.metalnessNode = surface.get("orm").b;
675
1027
  material.aoNode = surface.get("orm").r;
676
1028
  material.emissiveNode = surface.get("emission");
677
- material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float2(1 / 255));
1029
+ material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float3(1 / 255));
678
1030
  material.maskShadowNode = material.maskNode;
679
1031
  if (transparency !== "cutout") material.opacityNode = surface.get("alpha");
680
1032
  material.depthNode = capturedSurfaceDepth(surface.get("position"));
681
1033
  material.receivedShadowPositionNode = modelWorldMatrix2.mul(
682
- vec43(surface.get("position"), 1)
1034
+ vec44(surface.get("position"), 1)
683
1035
  ).xyz;
684
1036
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
685
1037
  return material;
@@ -689,39 +1041,40 @@ function applyBoxProjection({
689
1041
  function createBoxImpostorMaterial(descriptor, maps) {
690
1042
  return createBoxImpostorMaterialVariant(descriptor, maps, { filtering: true });
691
1043
  }
692
- function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false } = {}) {
1044
+ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false, boundSearch = true } = {}) {
693
1045
  const settings = normalizeBoxImpostorDisplay(descriptor);
694
1046
  const alphaCutoff = uniform(settings.alphaCutoff);
695
1047
  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) => {
1048
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float4(1 / 255);
1049
+ const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min2(ormAlpha, baseAlpha) : ormAlpha;
1050
+ const unpackNormal = (encoded) => {
699
1051
  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))));
1052
+ const normal2 = vec34(packed, float4(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
1053
+ If4(normal2.z.lessThan(0), () => {
1054
+ normal2.xy.assign(vec24(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
703
1055
  });
704
- return normal2.normalize();
1056
+ return normal2;
705
1057
  };
1058
+ const decodeNormal = (encoded) => unpackNormal(encoded).normalize();
706
1059
  const filteredNormal = (uv2, depth, tolerance, nearest, alpha, sampled = texture3(maps.normalDepth, uv2).level(0), ormAlpha = texture3(maps.orm, uv2).level(0).a) => {
707
1060
  sampled = sampled.toVar();
708
- const coverage2 = max3(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
1061
+ const coverage2 = max4(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
709
1062
  const nearestNormal = decodeNormal(nearest.rg), result = decodeNormal(sampled.rg.div(coverage2)).toVar();
710
1063
  const sampledDepth = sampled.b.mul(65280).add(sampled.a.mul(255)).div(65535);
711
1064
  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();
1065
+ If4(nearestNormal.z.lessThan(0).or(dot3(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
1066
+ const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor2(p), f = fract(p);
1067
+ const normal2 = vec34(0).toVar(), weights = float4(0).toVar();
715
1068
  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;
1069
+ const texel = ivec24(lo.add(vec24(x, y)).clamp(0, descriptor.atlasResolution - 1));
1070
+ const packed = textureLoad4(maps.normalDepth, texel).toVar();
1071
+ const alpha2 = textureLoad4(maps.baseColor, texel).a;
1072
+ const coverage3 = descriptor.alphaMode === "blend" ? textureLoad4(maps.orm, texel).a : alpha2;
720
1073
  const capturedDepth = packed.b.mul(65280).add(packed.a.mul(255)).div(65535);
721
1074
  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));
1075
+ If4(supported, () => {
1076
+ const weight = (x ? f.x : float4(1).sub(f.x)).mul(y ? f.y : float4(1).sub(f.y)).mul(coverage3);
1077
+ normal2.addAssign(decodeNormal(packed.rg.div(max4(coverage3, 1e-10))).mul(weight));
725
1078
  weights.addAssign(weight);
726
1079
  });
727
1080
  }
@@ -770,36 +1123,36 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
770
1123
  material.addEventListener("dispose", () => rects.dispose());
771
1124
  const center = attribute3("boxCenter", "vec3"), half = attribute3("boxHalfSize", "vec3");
772
1125
  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));
1126
+ const toBox = (p) => vec34(dot3(p, ax), dot3(p, ay), dot3(p, az));
774
1127
  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();
1128
+ const eye = modelWorldMatrixInverse.mul(vec45(cameraPosition, 1)).xyz;
1129
+ const viewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec45(0, 0, 1, 0))).xyz.normalize();
777
1130
  const perspective = cameraProjectionMatrix2.element(3).w.equal(0);
778
1131
  let proxy = positionLocal2;
779
1132
  if (descriptor.mode !== "fitted") {
780
- proxy = Fn4((_, builder) => {
1133
+ proxy = Fn5((_, builder) => {
781
1134
  const delta = eye.sub(center);
782
1135
  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();
1136
+ const right = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec45(0, 1, 0, 0))).xyz.cross(forward).normalize();
784
1137
  const up = forward.cross(right).normalize();
785
1138
  const radius = half.length();
786
1139
  const distance = dot3(eye.sub(center), forward);
787
- const planeOffset = perspective.select(min(radius, distance.sub(cameraNear2.mul(2))), radius);
1140
+ const planeOffset = perspective.select(min2(radius, distance.sub(cameraNear2.mul(2))), radius);
788
1141
  const plane = center.add(forward.mul(planeOffset));
789
- const lo = vec23(1e20).toVar(), hi = vec23(-1e20).toVar();
1142
+ const lo = vec24(1e20).toVar(), hi = vec24(-1e20).toVar();
790
1143
  for (const x of [-1, 1])
791
1144
  for (const y of [-1, 1])
792
1145
  for (const z of [-1, 1]) {
793
- const corner2 = fromBox(half.mul(vec33(x, y, z)));
1146
+ const corner2 = fromBox(half.mul(vec34(x, y, z)));
794
1147
  const scale = perspective.select(
795
- max3(distance.sub(planeOffset), 1e-5).div(
796
- max3(distance.sub(dot3(corner2, forward)), 1e-5)
1148
+ max4(distance.sub(planeOffset), 1e-5).div(
1149
+ max4(distance.sub(dot3(corner2, forward)), 1e-5)
797
1150
  ),
798
- float3(1)
1151
+ float4(1)
799
1152
  );
800
- const p = vec23(dot3(corner2, right), dot3(corner2, up)).mul(scale);
801
- lo.assign(min(lo, p));
802
- hi.assign(max3(hi, p));
1153
+ const p = vec24(dot3(corner2, right), dot3(corner2, up)).mul(scale);
1154
+ lo.assign(min2(lo, p));
1155
+ hi.assign(max4(hi, p));
803
1156
  }
804
1157
  const corner = attribute3("cardCorner", "vec2").add(1).mul(0.5);
805
1158
  const xy = lo.add(hi.sub(lo).mul(corner));
@@ -861,53 +1214,66 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
861
1214
  occupancy.needsUpdate = true;
862
1215
  material.addEventListener("dispose", () => occupancy.dispose());
863
1216
  }
1217
+ const preferFacingCapture = filtering && descriptor.alphaMode === "opaque" && settings.interpolation === "none";
1218
+ const viewBounds = boundSearch ? createBoxRayBounds(descriptor, maps, rects, material) : null;
864
1219
  const Result = struct2(
865
- { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
1220
+ { uv: "vec2", position: "vec3", face: "int", valid: "float" },
866
1221
  "BoxImpostorHit"
867
1222
  );
868
- const raycast = Fn4((_, builder) => {
869
- const ray = perspective.select(
870
- normalize2(raster.sub(eye)),
871
- viewAxis.negate()
872
- );
1223
+ const faceBasis = (axis, facing) => {
1224
+ const n = vec34(
1225
+ axis.equal(0).select(facing, 0),
1226
+ axis.equal(1).select(facing, 0),
1227
+ axis.equal(2).select(facing, 0)
1228
+ ).toVar();
1229
+ const right = axis.equal(0).select(
1230
+ vec34(0, 0, facing.negate()),
1231
+ axis.equal(1).select(vec34(1, 0, 0), vec34(facing, 0, 0))
1232
+ ).toVar();
1233
+ const up = axis.equal(1).select(vec34(0, 0, facing.negate()), vec34(0, 1, 0)).toVar();
1234
+ return { n, right, up };
1235
+ };
1236
+ const ray = perspective.select(normalize2(raster.sub(eye)), viewAxis.negate());
1237
+ const raycast = Fn5((_, builder) => {
873
1238
  const origin = perspective.select(
874
1239
  eye,
875
1240
  raster.sub(ray.mul(half.length().mul(4)))
876
1241
  );
877
1242
  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);
1243
+ const safe = sign3(r.add(1e-20)).mul(max4(abs3(r), 1e-10));
1244
+ const a = vec34(-1).sub(o).div(safe), b = vec34(1).sub(o).div(safe);
1245
+ const enter = max4(max4(min2(a, b).x, min2(a, b).y), min2(a, b).z).max(0);
1246
+ const exit = min2(min2(max4(a, b).x, max4(a, b).y), max4(a, b).z);
1247
+ const rayBounds = viewBounds?.(builder, int4(attribute3("boxId", "float")), o, r, enter, exit);
882
1248
  const occupiedStart = enter.toVar();
883
1249
  if (occupancy) {
884
1250
  const gridOrigin = o.add(1).mul(gridSize / 2);
885
1251
  const gridRay = r.mul(gridSize / 2);
886
1252
  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));
1253
+ const cell = floor2(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
1254
+ const inverse = vec34(1).div(safe.mul(gridSize / 2));
889
1255
  const delta = abs3(inverse);
890
1256
  const next = cell.add(step.add(1).mul(0.5)).sub(gridOrigin).mul(inverse).toVar();
891
1257
  const t = enter.toVar();
892
1258
  occupiedStart.assign(exit.add(1));
893
- Loop(gridSize * 3 + 1, () => {
894
- If3(t.greaterThan(exit), () => {
1259
+ Loop2(gridSize * 3 + 1, () => {
1260
+ If4(t.greaterThan(exit), () => {
895
1261
  Break();
896
1262
  });
897
- const cellIndex = uint(
1263
+ const cellIndex = uint2(
898
1264
  cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2))
899
1265
  ).toVar();
900
- const word = textureLoad3(
1266
+ const word = textureLoad4(
901
1267
  occupancy,
902
- ivec23(int3(cellIndex.shiftRight(5)), int3(attribute3("boxId", "float")))
1268
+ ivec24(int4(cellIndex.shiftRight(5)), int4(attribute3("boxId", "float")))
903
1269
  ).r;
904
1270
  const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
905
- If3(support.notEqual(uint(0)), () => {
1271
+ If4(support.notEqual(uint2(0)), () => {
906
1272
  occupiedStart.assign(t);
907
1273
  Break();
908
1274
  });
909
- const edge = min(min(next.x, next.y), next.z).toVar();
910
- const advance = vec33(
1275
+ const edge = min2(min2(next.x, next.y), next.z).toVar();
1276
+ const advance = vec34(
911
1277
  next.x.lessThanEqual(edge).select(1, 0),
912
1278
  next.y.lessThanEqual(edge).select(1, 0),
913
1279
  next.z.lessThanEqual(edge).select(1, 0)
@@ -915,7 +1281,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
915
1281
  cell.addAssign(advance.mul(step));
916
1282
  next.addAssign(advance.mul(delta));
917
1283
  t.assign(edge);
918
- If3(
1284
+ If4(
919
1285
  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
1286
  () => {
921
1287
  Break();
@@ -924,19 +1290,19 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
924
1290
  });
925
1291
  }
926
1292
  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();
1293
+ const bestT = exit.add(1).toVar(), bestUv = vec24(0).toVar(), bestFace = int4(0).toVar(), appearanceNear = preferFacingCapture ? float4(0).toVar() : null, valid = float4(0).toVar(), found = float4(0).toVar();
928
1294
  const angles = abs3(look).toVar();
929
1295
  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))
1296
+ int4(0),
1297
+ angles.y.greaterThanEqual(angles.z).select(int4(1), int4(2))
932
1298
  ).toVar();
933
1299
  const nextAxis = major.add(1).mod(3), lastAxis = major.add(2).mod(3);
934
1300
  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(
1301
+ const third = int4(3).sub(major).sub(second).toVar();
1302
+ Loop2(
937
1303
  { start: 0, end: 6, type: "int", name: "viewIndex" },
938
1304
  ({ viewIndex: i }) => {
939
- If3(occupiedStart.greaterThan(exit), () => {
1305
+ If4(occupiedStart.greaterThan(exit), () => {
940
1306
  Break();
941
1307
  });
942
1308
  valid.assign(0);
@@ -946,112 +1312,133 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
946
1312
  look.element(axis).greaterThanEqual(0),
947
1313
  look.element(axis).lessThan(0)
948
1314
  );
949
- const face = axis.mul(2).add(positive.select(int3(0), int3(1)));
1315
+ const face = axis.mul(2).add(positive.select(int4(0), int4(1)));
1316
+ const bounds = rayBounds?.(face, enter, exit);
950
1317
  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();
1318
+ const { n, right, up } = faceBasis(axis, facing);
961
1319
  const direction = i.lessThan(3).select(1, -1);
962
- const rect = textureLoad3(
1320
+ const rect = textureLoad4(
963
1321
  rects,
964
- ivec23(face, int3(attribute3("boxId", "float")))
1322
+ ivec24(face, int4(attribute3("boxId", "float")))
965
1323
  ).toVar();
966
1324
  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)
1325
+ vec24(dot3(p, right), dot3(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
968
1326
  );
969
1327
  const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
970
1328
  const depthAt = (uv2) => decode(texture3(maps.normalDepth, uv2).level(0));
1329
+ const projectedOrigin = vec24(dot3(o, right), dot3(o, up)).toVar();
1330
+ const projectedRay = vec24(dot3(r, right), dot3(r, up)).toVar();
1331
+ const axialOrigin = dot3(o, n).toVar();
1332
+ const axialRay = dot3(r, n).toVar();
971
1333
  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);
1334
+ const uv2 = rect.xy.add(
1335
+ projectedOrigin.add(projectedRay.mul(t)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1336
+ );
1337
+ return axialOrigin.add(axialRay.mul(t)).sub(float4(1).sub(depthAt(uv2).mul(2))).mul(direction);
974
1338
  };
975
1339
  const acceptHit = (hitT) => {
976
1340
  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);
1341
+ const texel = ivec24(uv2.mul(descriptor.atlasResolution));
1342
+ const nearest = textureLoad4(maps.normalDepth, texel);
979
1343
  const capturedBase = texture3(maps.baseColor, uv2).level(0);
980
- const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1344
+ const occupied = textureLoad4(maps.orm, texel).a.greaterThan(0.5);
981
1345
  const residual = abs3(
982
- dot3(point2, n).sub(float3(1).sub(decode(nearest).mul(2)))
1346
+ dot3(point2, n).sub(float4(1).sub(decode(nearest).mul(2)))
983
1347
  );
984
- const tolerance = max3(
1348
+ const tolerance = max4(
985
1349
  dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
986
1350
  dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
987
1351
  ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
988
- If3(
1352
+ If4(
989
1353
  residual.lessThanEqual(tolerance).and(occupied).and(
990
1354
  capturedBase.a.greaterThanEqual(minimumAlpha)
991
1355
  ),
992
1356
  () => {
993
1357
  valid.assign(1);
994
- If3(hitT.lessThan(bestT), () => {
1358
+ If4(hitT.lessThan(bestT), () => {
995
1359
  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)))
1360
+ const useAppearance = () => {
1361
+ bestUv.assign(uv2);
1362
+ bestFace.assign(face);
1363
+ };
1364
+ if (preferFacingCapture) {
1365
+ const texel2 = max4(
1366
+ dot3(abs3(right), half).div(rect.z),
1367
+ dot3(abs3(up), half).div(rect.w)
1368
+ ).div(descriptor.atlasResolution);
1369
+ const uncertainty = min2(
1370
+ texel2,
1371
+ residual.add(2 / 65535).div(abs3(axialRay).max(1e-10))
1007
1372
  );
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
- );
1373
+ If4(found.lessThan(0.5).or(hitT.add(uncertainty).lessThan(appearanceNear)), () => {
1374
+ appearanceNear.assign(hitT.sub(uncertainty));
1375
+ useAppearance();
1376
+ });
1377
+ } else useAppearance();
1378
+ found.assign(1);
1017
1379
  });
1018
1380
  }
1019
1381
  );
1020
1382
  };
1021
1383
  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), () => {
1384
+ const footprint = vec24(dot3(r, right), dot3(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
1385
+ let density = steps / 8;
1386
+ if (descriptor.alphaMode === "blend" && transparency === "blended" && steps < 32) {
1387
+ density = i.equal(0).select(steps / 16, steps / 32);
1388
+ } else if (descriptor.alphaMode === "opaque" && steps === 16) {
1389
+ density = found.greaterThan(0.5).select(1, 2);
1390
+ }
1391
+ const samples = max4(float4(steps), max4(footprint.x, footprint.y).mul(density)).div(2).ceil().mul(2).toVar();
1392
+ const step = end.sub(start).div(samples).toVar();
1393
+ const pairs = int4(samples.div(2));
1394
+ const pairAt = (t) => t.sub(start).div(max4(step.mul(2), 1e-15));
1395
+ const firstPair = bounds ? int4(floor2(pairAt(bounds.start))).clamp(0, pairs).toVar() : int4(0);
1396
+ const lastPair = bounds ? int4(pairAt(bounds.end).ceil()).clamp(0, pairs).toVar() : pairs;
1397
+ const previous = start.toVar();
1398
+ if (bounds) If4(firstPair.greaterThan(0), () => {
1399
+ previous.assign(start.add(step.mul(float4(firstPair.mul(2)))));
1400
+ });
1401
+ const previousD = distance(previous).toVar();
1402
+ const atEntry = bounds ? firstPair.equal(0).and(start.greaterThanEqual(bounds.start)).and(start.lessThanEqual(bounds.end)) : null;
1403
+ If4(atEntry ? atEntry.and(previousD.lessThanEqual(0)) : previousD.lessThanEqual(0), () => {
1027
1404
  acceptHit(start);
1028
1405
  });
1029
- Loop({ start: int3(0), end: int3(samples.div(2)), type: "int" }, ({ i: i2 }) => {
1030
- If3(valid.greaterThan(0.5), () => {
1406
+ Loop2({ start: firstPair, end: lastPair, type: "int" }, ({ i: i2 }) => {
1407
+ If4(valid.greaterThan(0.5).or(previous.greaterThan(bestT)), () => {
1031
1408
  Break();
1032
1409
  });
1033
- const samples2 = [1, 2].map((offset) => {
1034
- const t = start.add(step.mul(float3(i2.mul(2).add(offset)))).toVar();
1410
+ const [first, second2] = [1, 2].map((offset) => {
1411
+ const t = start.add(step.mul(float4(i2.mul(2).add(offset)))).toVar();
1035
1412
  return { t, d: distance(t).toVar() };
1036
1413
  });
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();
1414
+ const crossesFirst = first.d.mul(previousD).lessThanEqual(0);
1415
+ const crossesSecond = second2.d.mul(first.d).lessThanEqual(0);
1416
+ If4(crossesFirst.or(crossesSecond), () => {
1417
+ for (const [{ t, d }, crosses] of [[first, crossesFirst], [second2, crossesSecond]]) {
1418
+ If4(crosses.and(valid.lessThan(0.5)).and(previous.lessThanEqual(bestT)), () => {
1419
+ const crossing = refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, {
1420
+ lo: previous,
1421
+ hi: t,
1422
+ loValue: previousD,
1423
+ hiValue: d,
1424
+ height: distance,
1425
+ steps: 3,
1426
+ secant: true
1427
+ });
1428
+ acceptHit(crossing);
1046
1429
  });
1047
- });
1048
- previous.assign(t);
1049
- previousD.assign(d);
1050
- }
1430
+ previous.assign(t);
1431
+ previousD.assign(d);
1432
+ }
1433
+ }).Else(() => {
1434
+ previous.assign(second2.t);
1435
+ previousD.assign(second2.d);
1436
+ });
1051
1437
  });
1052
1438
  };
1053
- If3(
1054
- exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3)),
1439
+ const supported = exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3));
1440
+ If4(
1441
+ bounds ? supported.and(bounds.start.lessThanEqual(bestT)).and(bounds.end.greaterThanEqual(occupiedStart)) : supported,
1055
1442
  () => {
1056
1443
  if (!accelerated) {
1057
1444
  traceInterval(enter, exit, descriptor.raySteps);
@@ -1064,13 +1451,13 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1064
1451
  )
1065
1452
  );
1066
1453
  const interval = positive.select(depths.xy, depths.zw);
1067
- const initialDepth = float3(1).sub(dot3(o, n)).mul(0.5);
1454
+ const initialDepth = float4(1).sub(dot3(o, n)).mul(0.5);
1068
1455
  const depthSlope = dot3(r, n).negate().mul(0.5);
1069
1456
  const da = interval.x.sub(2 / 65535).sub(initialDepth).div(depthSlope);
1070
1457
  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(
1458
+ const start = max4(occupiedStart, min2(da, db));
1459
+ const end = min2(min2(exit, bestT), max4(da, db));
1460
+ If4(
1074
1461
  interval.x.lessThanEqual(interval.y).and(end.greaterThanEqual(start)),
1075
1462
  () => {
1076
1463
  const search = () => traceInterval(start, end, descriptor.raySteps);
@@ -1080,12 +1467,12 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1080
1467
  )
1081
1468
  );
1082
1469
  if (hasFlatView) {
1083
- If3(
1470
+ If4(
1084
1471
  interval.y.sub(interval.x).lessThanEqual(1 / 65535),
1085
1472
  () => {
1086
1473
  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))),
1474
+ If4(
1475
+ t.greaterThanEqual(enter).and(t.lessThanEqual(min2(exit, bestT))),
1089
1476
  () => {
1090
1477
  acceptHit(t);
1091
1478
  }
@@ -1105,57 +1492,65 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1105
1492
  return Result(
1106
1493
  bestUv,
1107
1494
  center.add(fromBox(point.mul(half))),
1108
- bestNormal,
1495
+ bestFace,
1109
1496
  valid
1110
1497
  );
1111
1498
  });
1112
1499
  const hit = raycast().toVar("boxHit");
1113
1500
  hit.toStack();
1114
1501
  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");
1502
+ const coverage = max4(surfaceCoverage(orm.a, base.a), 1e-10);
1503
+ const hitNormal = Fn5(() => {
1504
+ const face = hit.get("face");
1505
+ const { n, right, up } = faceBasis(face.div(2), face.mod(2).equal(0).select(1, -1));
1506
+ const sampled = texture3(maps.normalDepth, hit.get("uv")).level(0);
1507
+ const local = unpackNormal(sampled.rg.div(coverage));
1508
+ const direction = fromBox(right.mul(local.x).add(up.mul(local.y)).add(n.mul(local.z))).normalize().toVar();
1509
+ return direction.mul(dot3(direction, ray).greaterThan(0).select(-1, 1));
1510
+ })();
1511
+ 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
1512
  if (settings.interpolation !== "none") {
1118
1513
  const fallbackColor = color, fallbackOrm = surfaceOrm, fallbackEmission = emission, fallbackNormal = normal;
1119
1514
  const Surface = struct2(
1120
1515
  { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
1121
1516
  "BoxSurfaceBlend"
1122
1517
  );
1123
- const blended = Fn4(() => {
1518
+ const blended = Fn5(() => {
1124
1519
  const point = toBox(hit.get("position").sub(center)).div(half);
1125
1520
  const look = toBox(
1126
1521
  perspective.select(normalize2(eye.sub(hit.get("position"))), viewAxis)
1127
1522
  );
1128
- const colors = vec44(0).toVar(), materials = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar(), weights = float3(0).toVar();
1523
+ const colors = vec45(0).toVar(), materials = vec34(0).toVar(), emissions = vec34(0).toVar(), normals = vec34(0).toVar(), weights = float4(0).toVar();
1129
1524
  for (let axis = 0; axis < 3; axis++) {
1130
1525
  const positive = look.element(axis).greaterThanEqual(0);
1131
1526
  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));
1527
+ const n = positive.select(vec34(...front.normal), vec34(...back.normal));
1133
1528
  const right = positive.select(
1134
- vec33(...front.right),
1135
- vec33(...back.right)
1529
+ vec34(...front.right),
1530
+ vec34(...back.right)
1136
1531
  );
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(
1532
+ const up = positive.select(vec34(...front.up), vec34(...back.up));
1533
+ const face = positive.select(int4(axis * 2), int4(axis * 2 + 1));
1534
+ const rect = textureLoad4(
1140
1535
  rects,
1141
- ivec23(face, int3(attribute3("boxId", "float")))
1536
+ ivec24(face, int4(attribute3("boxId", "float")))
1142
1537
  );
1143
1538
  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)
1539
+ vec24(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1145
1540
  );
1146
- const texel = ivec23(uv2.mul(descriptor.atlasResolution));
1147
- const captured = textureLoad3(maps.normalDepth, texel);
1541
+ const texel = ivec24(uv2.mul(descriptor.atlasResolution));
1542
+ const captured = textureLoad4(maps.normalDepth, texel);
1148
1543
  const sampled = texture3(maps.baseColor, uv2).level(0);
1149
1544
  const sampledOrm = texture3(maps.orm, uv2).level(0);
1150
- const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1545
+ const occupied = textureLoad4(maps.orm, texel).a.greaterThan(0.5);
1151
1546
  const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
1152
- const tolerance = max3(
1547
+ const tolerance = max4(
1153
1548
  dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
1154
1549
  dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
1155
1550
  ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
1156
- If3(
1551
+ If4(
1157
1552
  occupied.and(sampled.a.greaterThanEqual(minimumAlpha)).and(
1158
- abs3(dot3(point, n).sub(float3(1).sub(depth.mul(2)))).lessThanEqual(
1553
+ abs3(dot3(point, n).sub(float4(1).sub(depth.mul(2)))).lessThanEqual(
1159
1554
  tolerance
1160
1555
  )
1161
1556
  ),
@@ -1164,28 +1559,28 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1164
1559
  const filtered = filtering ? texture3(maps.normalDepth, uv2).level(0).toVar() : captured;
1165
1560
  let weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
1166
1561
  if (filtering) {
1167
- const error = abs3(dot3(point, n).sub(float3(1).sub(
1562
+ const error = abs3(dot3(point, n).sub(float4(1).sub(
1168
1563
  filtered.b.mul(65280).add(filtered.a.mul(255)).div(65535).mul(2)
1169
1564
  )));
1170
- weight = weight.mul(float3(1).sub(error.div(tolerance)).clamp(0, 1));
1565
+ weight = weight.mul(float4(1).sub(error.div(tolerance)).clamp(0, 1));
1171
1566
  }
1172
- const coverage2 = max3(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
1567
+ const coverage2 = max4(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
1173
1568
  colors.addAssign(sampled.div(coverage2).mul(weight));
1174
1569
  materials.addAssign(sampledOrm.rgb.div(coverage2).mul(weight));
1175
1570
  emissions.addAssign(
1176
1571
  texture3(maps.emissive, uv2).level(0).rgb.div(coverage2).mul(weight)
1177
1572
  );
1178
1573
  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);
1574
+ if (filtering) shadingNormal = filteredNormal(uv2, float4(1).sub(dot3(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1180
1575
  else {
1181
1576
  const packed = captured.rg.mul(2).sub(1);
1182
- const decoded = vec33(
1577
+ const decoded = vec34(
1183
1578
  packed,
1184
- float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1579
+ float4(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1185
1580
  ).toVar();
1186
- If3(decoded.z.lessThan(0), () => {
1581
+ If4(decoded.z.lessThan(0), () => {
1187
1582
  decoded.xy.assign(
1188
- vec23(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1583
+ vec24(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1189
1584
  );
1190
1585
  });
1191
1586
  shadingNormal = decoded;
@@ -1199,7 +1594,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1199
1594
  }
1200
1595
  );
1201
1596
  }
1202
- const divisor = max3(weights, 1e-10), valid = weights.greaterThan(1e-10);
1597
+ const divisor = max4(weights, 1e-10), valid = weights.greaterThan(1e-10);
1203
1598
  return Surface(
1204
1599
  valid.select(colors.div(divisor), fallbackColor),
1205
1600
  valid.select(materials.div(divisor), fallbackOrm),
@@ -1231,7 +1626,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1231
1626
  material.maskShadowNode = material.maskNode;
1232
1627
  material.depthNode = capturedSurfaceDepth(hit.get("position"));
1233
1628
  material.receivedShadowPositionNode = modelWorldMatrix3.mul(
1234
- vec44(hit.get("position"), 1)
1629
+ vec45(hit.get("position"), 1)
1235
1630
  ).xyz;
1236
1631
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
1237
1632
  return material;