@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.
@@ -9,6 +9,7 @@ export function createBoxImpostorMaterial(descriptor: import("./box-impostor-met
9
9
  emissive: import("three").Texture;
10
10
  }): any;
11
11
  /** Internal compile-time variants for matched quality and cost measurements. */
12
- export function createBoxImpostorMaterialVariant(descriptor: any, maps: any, { filtering }?: {
12
+ export function createBoxImpostorMaterialVariant(descriptor: any, maps: any, { filtering, boundSearch }?: {
13
13
  filtering?: boolean | undefined;
14
+ boundSearch?: boolean | undefined;
14
15
  }): any;
@@ -0,0 +1,6 @@
1
+ /** Restrict the existing full-resolution search to intervals containing supported
2
+ * capture texels. All preparation stays on the GPU, including for compressed maps. */
3
+ export function createBoxRayBounds(descriptor: any, maps: any, rects: any, material: any): ((builder: any, id: any, o: any, r: any, enter: any, exit: any) => ((face: any, enter: any, exit: any) => {
4
+ start: any;
5
+ end: any;
6
+ }) | null) | null;
@@ -0,0 +1 @@
1
+ export * from '../../../src/box-impostor/box-impostor-ray-bounds.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needle-tools/three-mesh-effects",
3
- "version": "0.3.6",
3
+ "version": "0.3.7",
4
4
  "description": "Three.js loaders and TSL materials for glTF impostors, hull effects, and deformation rigs.",
5
5
  "keywords": [
6
6
  "three.js",
@@ -50,6 +50,7 @@ import {
50
50
  uniform,
51
51
  } from "three/tsl";
52
52
  import {CapturedSurfaceMaterial} from '../rendering/captured-surface-material.js';
53
+ import {createBoxRayBounds} from './box-impostor-ray-bounds.js';
53
54
  import {refineSurfaceCrossing} from './box-impostor-surface-search.js';
54
55
  import { applyBoxFaces } from "./box-impostor-faces.js";
55
56
  import { applyBoxProjection } from "./box-impostor-projection.js";
@@ -72,7 +73,7 @@ export function createBoxImpostorMaterial(descriptor, maps) {
72
73
  }
73
74
 
74
75
  /** Internal compile-time variants for matched quality and cost measurements. */
75
- export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering = false} = {}) {
76
+ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering = false, boundSearch = true} = {}) {
76
77
  const settings = normalizeBoxImpostorDisplay(descriptor);
77
78
  const alphaCutoff = uniform(settings.alphaCutoff);
78
79
  const transparency = boxTransparency(descriptor, settings);
@@ -80,12 +81,13 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
80
81
  // Opaque/masked captures store geometric coverage in base alpha as well.
81
82
  // This also supports older MRT captures whose unused ORM alpha was opaque.
82
83
  const surfaceCoverage = (ormAlpha,baseAlpha) => filtering && descriptor.alphaMode !== 'blend' ? min(ormAlpha,baseAlpha) : ormAlpha;
83
- const decodeNormal = encoded => {
84
+ const unpackNormal = encoded => {
84
85
  const packed=encoded.mul(2).sub(1);
85
86
  const normal=vec3(packed,float(1).sub(abs(packed.x)).sub(abs(packed.y))).toVar();
86
87
  If(normal.z.lessThan(0),()=>{normal.xy.assign(vec2(1).sub(abs(normal.yx)).mul(sign(normal.xy.add(1e-20))));});
87
- return normal.normalize();
88
+ return normal;
88
89
  };
90
+ const decodeNormal = encoded => unpackNormal(encoded).normalize();
89
91
  const filteredNormal = (uv,depth,tolerance,nearest,alpha,sampled=texture(maps.normalDepth,uv).level(0),ormAlpha=texture(maps.orm,uv).level(0).a) => {
90
92
  sampled=sampled.toVar();
91
93
  const coverage=max(descriptor.alphaMode==='blend'?ormAlpha:alpha,1e-10);
@@ -264,15 +266,33 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
264
266
  occupancy.needsUpdate = true;
265
267
  material.addEventListener("dispose", () => occupancy.dispose());
266
268
  }
269
+ const preferFacingCapture = filtering && descriptor.alphaMode === "opaque" && settings.interpolation === "none";
270
+ const viewBounds = boundSearch ? createBoxRayBounds(descriptor, maps, rects, material) : null;
267
271
  const Result = struct(
268
- { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
272
+ { uv: "vec2", position: "vec3", face: "int", valid: "float" },
269
273
  "BoxImpostorHit",
270
274
  );
275
+ const faceBasis = (axis, facing) => {
276
+ const n = vec3(
277
+ axis.equal(0).select(facing, 0),
278
+ axis.equal(1).select(facing, 0),
279
+ axis.equal(2).select(facing, 0),
280
+ ).toVar();
281
+ const right = axis
282
+ .equal(0)
283
+ .select(
284
+ vec3(0, 0, facing.negate()),
285
+ axis.equal(1).select(vec3(1, 0, 0), vec3(facing, 0, 0)),
286
+ )
287
+ .toVar();
288
+ const up = axis
289
+ .equal(1)
290
+ .select(vec3(0, 0, facing.negate()), vec3(0, 1, 0))
291
+ .toVar();
292
+ return { n, right, up };
293
+ };
294
+ const ray = perspective.select(normalize(raster.sub(eye)), viewAxis.negate());
271
295
  const raycast = Fn((_, builder) => {
272
- const ray = perspective.select(
273
- normalize(raster.sub(eye)),
274
- viewAxis.negate(),
275
- );
276
296
  const origin = perspective.select(
277
297
  eye,
278
298
  raster.sub(ray.mul(half.length().mul(4))),
@@ -284,6 +304,7 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
284
304
  b = vec3(1).sub(o).div(safe);
285
305
  const enter = max(max(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
286
306
  const exit = min(min(max(a, b).x, max(a, b).y), max(a, b).z);
307
+ const rayBounds = viewBounds?.(builder, int(attribute("boxId", "float")), o, r, enter, exit);
287
308
  const occupiedStart = enter.toVar();
288
309
  // This cover contains whole source voxel cubes. Only the empty space is
289
310
  // skipped; the depth fields still determine the full-resolution surface.
@@ -345,7 +366,8 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
345
366
  const look = toBox(ray).negate();
346
367
  const bestT = exit.add(1).toVar(),
347
368
  bestUv = vec2(0).toVar(),
348
- bestNormal = vec3(0, 0, 1).toVar(),
369
+ bestFace = int(0).toVar(),
370
+ appearanceNear = preferFacingCapture ? float(0).toVar() : null,
349
371
  valid = float(0).toVar(),
350
372
  found = float(0).toVar();
351
373
  // A face-on capture can miss a nearer surface visible from another axis.
@@ -386,23 +408,9 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
386
408
  look.element(axis).lessThan(0),
387
409
  );
388
410
  const face = axis.mul(2).add(positive.select(int(0), int(1)));
411
+ const bounds = rayBounds?.(face, enter, exit);
389
412
  const facing = positive.select(1, -1);
390
- const n = vec3(
391
- axis.equal(0).select(facing, 0),
392
- axis.equal(1).select(facing, 0),
393
- axis.equal(2).select(facing, 0),
394
- ).toVar();
395
- const right = axis
396
- .equal(0)
397
- .select(
398
- vec3(0, 0, facing.negate()),
399
- axis.equal(1).select(vec3(1, 0, 0), vec3(facing, 0, 0)),
400
- )
401
- .toVar();
402
- const up = axis
403
- .equal(1)
404
- .select(vec3(0, 0, facing.negate()), vec3(0, 1, 0))
405
- .toVar();
413
+ const { n, right, up } = faceBasis(axis, facing);
406
414
  const direction = i.lessThan(3).select(1, -1);
407
415
  const rect = textureLoad(
408
416
  rects,
@@ -418,10 +426,19 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
418
426
  );
419
427
  const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
420
428
  const depthAt = (uv) => decode(texture(maps.normalDepth, uv).level(0));
429
+ // A capture sees an affine ray. Project it once per face so stepping
430
+ // and refinement only need its position along that ray.
431
+ const projectedOrigin = vec2(dot(o, right), dot(o, up)).toVar();
432
+ const projectedRay = vec2(dot(r, right), dot(r, up)).toVar();
433
+ const axialOrigin = dot(o, n).toVar();
434
+ const axialRay = dot(r, n).toVar();
421
435
  const distance = (t) => {
422
- const p = o.add(r.mul(t));
423
- return dot(p, n)
424
- .sub(float(1).sub(depthAt(sampleUv(p)).mul(2)))
436
+ const uv = rect.xy.add(
437
+ projectedOrigin.add(projectedRay.mul(t)).mul(0.5).add(0.5)
438
+ .clamp(0, 1).mul(rect.zw),
439
+ );
440
+ return axialOrigin.add(axialRay.mul(t))
441
+ .sub(float(1).sub(depthAt(uv).mul(2)))
425
442
  .mul(direction);
426
443
  };
427
444
  const acceptHit = (hitT) => {
@@ -456,36 +473,27 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
456
473
  valid.assign(1);
457
474
  If(hitT.lessThan(bestT), () => {
458
475
  bestT.assign(hitT);
459
- bestUv.assign(uv);
460
- found.assign(1);
461
- const packed = texture(maps.normalDepth, uv)
462
- .level(0)
463
- .rg.div(max(surfaceCoverage(texture(maps.orm, uv).level(0).a,capturedBase.a), 1e-10))
464
- .mul(2)
465
- .sub(1);
466
- const normal = vec3(
467
- packed.x,
468
- packed.y,
469
- float(1).sub(abs(packed.x)).sub(abs(packed.y)),
470
- ).toVar();
471
- If(normal.z.lessThan(0), () => {
472
- normal.xy.assign(
473
- vec2(1)
474
- .sub(abs(normal.yx))
475
- .mul(sign(normal.xy.add(1e-20))),
476
+ const useAppearance = () => {
477
+ bestUv.assign(uv);
478
+ bestFace.assign(face);
479
+ };
480
+ if (preferFacingCapture) {
481
+ // The more face-on capture was visited first. Keep it only
482
+ // while the two depth estimates overlap within one texel.
483
+ const texel = max(
484
+ dot(abs(right), half).div(rect.z),
485
+ dot(abs(up), half).div(rect.w),
486
+ ).div(descriptor.atlasResolution);
487
+ const uncertainty = min(
488
+ texel,
489
+ residual.add(2 / 65535).div(abs(axialRay).max(1e-10)),
476
490
  );
477
- });
478
- bestNormal.assign(
479
- fromBox(
480
- right
481
- .mul(normal.x)
482
- .add(up.mul(normal.y))
483
- .add(n.mul(normal.z)),
484
- ).normalize(),
485
- );
486
- bestNormal.mulAssign(
487
- dot(bestNormal, ray).greaterThan(0).select(-1, 1),
488
- );
491
+ If(found.lessThan(0.5).or(hitT.add(uncertainty).lessThan(appearanceNear)), () => {
492
+ appearanceNear.assign(hitT.sub(uncertainty));
493
+ useAppearance();
494
+ });
495
+ } else useAppearance();
496
+ found.assign(1);
489
497
  });
490
498
  },
491
499
  );
@@ -495,48 +503,68 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
495
503
  end,
496
504
  steps,
497
505
  ) => {
498
- // Sample every crossed texel; a fixed interval budget skips thin
499
- // surfaces when an oblique ray spans hundreds of capture pixels.
500
- const footprint = vec2(dot(r, right), dot(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
501
- const samples = max(float(steps), max(footprint.x,footprint.y).mul(steps/8)).div(2).ceil().mul(2).toVar();
502
- const step=end.sub(start).div(samples);
503
- const previous = start.toVar(),
504
- previousD = distance(start).toVar();
505
- // At interval entry the refinement bracket has zero width. Resolve it
506
- // once rather than resampling the same depth through every bisection.
507
- If(previousD.lessThanEqual(0), () => {
506
+ const footprint = vec2(dot(r, right), dot(r, up)).abs()
507
+ .mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
508
+ let density = steps / 8;
509
+ if (descriptor.alphaMode === "blend" && transparency === "blended" && steps < 32) {
510
+ // Overlapping blended carriers each trace their dominant capture more densely.
511
+ density = i.equal(0).select(steps / 16, steps / 32);
512
+ } else if (descriptor.alphaMode === "opaque" && steps === 16) {
513
+ // Use the full density until the silhouette is established. Later
514
+ // captures look for closer occluders at one sample per crossed texel.
515
+ density = found.greaterThan(0.5).select(1, 2);
516
+ }
517
+ const samples = max(float(steps), max(footprint.x, footprint.y).mul(density))
518
+ .div(2).ceil().mul(2).toVar();
519
+ const step = end.sub(start).div(samples).toVar();
520
+ const pairs = int(samples.div(2));
521
+ // Keep the original bracket indices. Restarting at a clipped bound
522
+ // moves the samples and can lose thin surfaces between them.
523
+ const pairAt = t => t.sub(start).div(max(step.mul(2), 1e-15));
524
+ const firstPair = bounds ? int(floor(pairAt(bounds.start))).clamp(0, pairs).toVar() : int(0);
525
+ const lastPair = bounds ? int(pairAt(bounds.end).ceil()).clamp(0, pairs).toVar() : pairs;
526
+ const previous = start.toVar();
527
+ if (bounds) If(firstPair.greaterThan(0), () => {
528
+ previous.assign(start.add(step.mul(float(firstPair.mul(2)))));
529
+ });
530
+ const previousD = distance(previous).toVar();
531
+ const atEntry = bounds ? firstPair.equal(0).and(start.greaterThanEqual(bounds.start)).and(start.lessThanEqual(bounds.end)) : null;
532
+ If(atEntry ? atEntry.and(previousD.lessThanEqual(0)) : previousD.lessThanEqual(0), () => {
508
533
  acceptHit(start);
509
534
  });
510
- Loop({ start: int(0), end: int(samples.div(2)), type: "int" }, ({ i }) => {
511
- If(valid.greaterThan(0.5), () => {
535
+ Loop({ start: firstPair, end: lastPair, type: "int" }, ({ i }) => {
536
+ If(valid.greaterThan(0.5).or(previous.greaterThan(bestT)), () => {
512
537
  Break();
513
538
  });
514
- // Issue independent depth reads together, then resolve crossings in
515
- // their original order before refining either crossing direction.
516
- const samples = [1, 2].map((offset) => {
539
+ const [first, second] = [1, 2].map((offset) => {
517
540
  const t = start.add(step.mul(float(i.mul(2).add(offset)))).toVar();
518
541
  return { t, d: distance(t).toVar() };
519
542
  });
520
- for (const { t, d } of samples) {
521
- If(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
522
- Break();
523
- });
524
- If(valid.lessThan(.5).and(d.mul(previousD).lessThanEqual(0)), () => {
525
- const crossing=refineSurfaceCrossing({float,If,Loop},{lo:previous,hi:t,loValue:previousD,hiValue:d,height:distance,steps:3,secant:true});
526
- acceptHit(crossing);
527
- If(bestT.lessThanEqual(t), () => {
528
- Break();
543
+ const crossesFirst = first.d.mul(previousD).lessThanEqual(0);
544
+ const crossesSecond = second.d.mul(first.d).lessThanEqual(0);
545
+ // Most pairs have no crossing. Skip the per-bracket work together,
546
+ // while retaining both brackets for thin surfaces and reversals.
547
+ If(crossesFirst.or(crossesSecond), () => {
548
+ for (const [{ t, d }, crosses] of [[first, crossesFirst], [second, crossesSecond]]) {
549
+ If(crosses.and(valid.lessThan(0.5)).and(previous.lessThanEqual(bestT)), () => {
550
+ const crossing = refineSurfaceCrossing({ float, If, Loop }, {
551
+ lo: previous, hi: t, loValue: previousD, hiValue: d,
552
+ height: distance, steps: 3, secant: true,
553
+ });
554
+ acceptHit(crossing);
529
555
  });
530
- });
531
- previous.assign(t);
532
- previousD.assign(d);
533
- }
556
+ previous.assign(t);
557
+ previousD.assign(d);
558
+ }
559
+ }).Else(() => {
560
+ previous.assign(second.t);
561
+ previousD.assign(second.d);
562
+ });
534
563
  });
535
564
  };
565
+ const supported = exit.greaterThanEqual(enter).and(abs(look.element(axis)).greaterThan(0.001));
536
566
  If(
537
- exit
538
- .greaterThanEqual(enter)
539
- .and(abs(look.element(axis)).greaterThan(0.001)),
567
+ bounds ? supported.and(bounds.start.lessThanEqual(bestT)).and(bounds.end.greaterThanEqual(occupiedStart)) : supported,
540
568
  () => {
541
569
  if (!accelerated) {
542
570
  traceInterval(enter, exit, descriptor.raySteps);
@@ -611,7 +639,7 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
611
639
  return Result(
612
640
  bestUv,
613
641
  center.add(fromBox(point.mul(half))),
614
- bestNormal,
642
+ bestFace,
615
643
  valid,
616
644
  );
617
645
  });
@@ -623,10 +651,20 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
623
651
  // attributes by geometric coverage; an
624
652
  // empty neighbor must not turn a rough edge into a glossy highlight.
625
653
  const coverage = max(surfaceCoverage(orm.a,base.a), 1e-10);
654
+ // Decode only the winning capture. Visibility and depth passes need just
655
+ // the hit, and shaded passes already fetch its base color and coverage.
656
+ const hitNormal = Fn(() => {
657
+ const face = hit.get("face");
658
+ const { n, right, up } = faceBasis(face.div(2), face.mod(2).equal(0).select(1, -1));
659
+ const sampled = texture(maps.normalDepth, hit.get("uv")).level(0);
660
+ const local = unpackNormal(sampled.rg.div(coverage));
661
+ const direction = fromBox(right.mul(local.x).add(up.mul(local.y)).add(n.mul(local.z))).normalize().toVar();
662
+ return direction.mul(dot(direction, ray).greaterThan(0).select(-1, 1));
663
+ })();
626
664
  let color = base.div(coverage),
627
665
  surfaceOrm = orm.rgb.div(coverage),
628
666
  emission = texture(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage),
629
- normal = hit.get("normal");
667
+ normal = hitNormal;
630
668
  if (settings.interpolation !== "none") {
631
669
  const fallbackColor = color,
632
670
  fallbackOrm = surfaceOrm,