@needle-tools/three-mesh-effects 0.3.1 → 0.3.3

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 (50) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +22 -6
  3. package/SKILL.md +7 -5
  4. package/build/box-impostor-runtime.js +212 -87
  5. package/build/box-impostor-runtime.js.map +4 -4
  6. package/build/impostor-runtime.js +128 -48
  7. package/build/impostor-runtime.js.map +4 -4
  8. package/build/index.js +4 -0
  9. package/build/index.js.map +2 -2
  10. package/build/internal/box-impostor/box-impostor-display.js +178 -81
  11. package/build/internal/box-impostor/box-impostor-display.js.map +4 -4
  12. package/build/internal/box-impostor/box-impostor-material.js +163 -71
  13. package/build/internal/box-impostor/box-impostor-material.js.map +4 -4
  14. package/build/internal/box-impostor/box-impostor-projection.js +38 -18
  15. package/build/internal/box-impostor/box-impostor-projection.js.map +4 -4
  16. package/build/internal/box-impostor/box-impostor-runtime.js +193 -76
  17. package/build/internal/box-impostor/box-impostor-runtime.js.map +4 -4
  18. package/build/internal/impostor/impostor-node-material.js +128 -48
  19. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  20. package/build/internal/pixel-impostor/pixel-impostor-display.js +84 -38
  21. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +4 -4
  22. package/build/internal/rendering/captured-surface-depth.js +35 -0
  23. package/build/internal/rendering/captured-surface-depth.js.map +7 -0
  24. package/build/internal/rendering/captured-surface-material.js +28 -0
  25. package/build/internal/rendering/captured-surface-material.js.map +7 -0
  26. package/build/internal/rendering/renderer-support.js +31 -0
  27. package/build/internal/rendering/renderer-support.js.map +7 -0
  28. package/build/pixel-impostor-runtime.js +84 -38
  29. package/build/pixel-impostor-runtime.js.map +4 -4
  30. package/build/types/box-impostor/box-impostor-display.d.ts +9 -1
  31. package/build/types/box-impostor/box-impostor-material.d.ts +4 -0
  32. package/build/types/box-impostor/box-impostor-runtime.d.ts +5 -11
  33. package/build/types/impostor/impostor-node-material.d.ts +2 -15
  34. package/build/types/rendering/captured-surface-depth.d.ts +5 -0
  35. package/build/types/rendering/captured-surface-depth.js +1 -0
  36. package/build/types/rendering/captured-surface-material.d.ts +8 -0
  37. package/build/types/rendering/captured-surface-material.js +1 -0
  38. package/build/types/rendering/renderer-support.d.ts +27 -0
  39. package/build/types/rendering/renderer-support.js +1 -0
  40. package/package.json +3 -3
  41. package/src/box-impostor/box-impostor-display.js +23 -11
  42. package/src/box-impostor/box-impostor-material.js +94 -44
  43. package/src/box-impostor/box-impostor-projection.js +3 -14
  44. package/src/box-impostor/box-impostor-runtime.js +6 -4
  45. package/src/impostor/impostor-node-material.js +26 -43
  46. package/src/pixel-impostor/pixel-impostor-display.js +5 -13
  47. package/src/public/index.js +5 -0
  48. package/src/rendering/captured-surface-depth.js +55 -0
  49. package/src/rendering/captured-surface-material.js +27 -0
  50. package/src/rendering/renderer-support.js +50 -0
@@ -1,5 +1,6 @@
1
1
  // TSL's struct declarations erase members; GPU rendering tests cover this graph.
2
2
  // @ts-nocheck
3
+ import { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';
3
4
  import {
4
5
  DataTexture,
5
6
  FloatType,
@@ -8,8 +9,8 @@ import {
8
9
  UnsignedIntType,
9
10
  NearestFilter,
10
11
  LinearFilter,
11
- MeshStandardNodeMaterial,
12
12
  DoubleSide,
13
+ BackSide,
13
14
  FrontSide,
14
15
  } from "three/webgpu";
15
16
  import {
@@ -40,16 +41,14 @@ import {
40
41
  ivec2,
41
42
  normalize,
42
43
  floor,
43
- modelViewMatrix,
44
+ fract,
44
45
  modelWorldMatrix,
45
46
  cameraNear,
46
- cameraFar,
47
- viewZToPerspectiveDepth,
48
- viewZToOrthographicDepth,
49
47
  transformNormalToView,
50
48
  struct,
51
49
  uniform,
52
50
  } from "three/tsl";
51
+ import {CapturedSurfaceMaterial} from '../rendering/captured-surface-material.js';
53
52
  import {refineSurfaceCrossing} from './box-impostor-surface-search.js';
54
53
  import { applyBoxFaces } from "./box-impostor-faces.js";
55
54
  import { applyBoxProjection } from "./box-impostor-projection.js";
@@ -68,10 +67,52 @@ import {
68
67
  * @param {import('./box-impostor-metadata.js').BoxImpostorDescriptor} descriptor
69
68
  * @param {{baseColor:import('three').Texture,normalDepth:import('three').Texture,orm:import('three').Texture,emissive:import('three').Texture}} maps */
70
69
  export function createBoxImpostorMaterial(descriptor, maps) {
70
+ return createBoxImpostorMaterialVariant(descriptor, maps, {filtering:true});
71
+ }
72
+
73
+ /** Internal compile-time variants for matched quality and cost measurements. */
74
+ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering = false} = {}) {
71
75
  const settings = normalizeBoxImpostorDisplay(descriptor);
72
76
  const alphaCutoff = uniform(settings.alphaCutoff);
73
77
  const transparency = boxTransparency(descriptor, settings);
74
78
  const minimumAlpha = transparency === "cutout" ? alphaCutoff : float(1 / 255);
79
+ // Opaque/masked captures store geometric coverage in base alpha as well.
80
+ // This also supports older MRT captures whose unused ORM alpha was opaque.
81
+ const surfaceCoverage = (ormAlpha,baseAlpha) => filtering && descriptor.alphaMode !== 'blend' ? min(ormAlpha,baseAlpha) : ormAlpha;
82
+ const decodeNormal = encoded => {
83
+ const packed=encoded.mul(2).sub(1);
84
+ const normal=vec3(packed,float(1).sub(abs(packed.x)).sub(abs(packed.y))).toVar();
85
+ If(normal.z.lessThan(0),()=>{normal.xy.assign(vec2(1).sub(abs(normal.yx)).mul(sign(normal.xy.add(1e-20))));});
86
+ return normal.normalize();
87
+ };
88
+ const filteredNormal = (uv,depth,tolerance,nearest,alpha,sampled=texture(maps.normalDepth,uv).level(0),ormAlpha=texture(maps.orm,uv).level(0).a) => {
89
+ sampled=sampled.toVar();
90
+ const coverage=max(descriptor.alphaMode==='blend'?ormAlpha:alpha,1e-10);
91
+ const nearestNormal=decodeNormal(nearest.rg),result=decodeNormal(sampled.rg.div(coverage)).toVar();
92
+ const sampledDepth=sampled.b.mul(65280).add(sampled.a.mul(255)).div(65535);
93
+ const nearestDepth=nearest.b.mul(65280).add(nearest.a.mul(255)).div(65535);
94
+ // Bilinear oct coordinates suffice on smooth interiors. Decode individual
95
+ // taps only at a wrap, coverage edge or depth-layer discontinuity.
96
+ If(nearestNormal.z.lessThan(0).or(dot(result,nearestNormal).lessThan(.75)).or(coverage.lessThan(.9999)).or(abs(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)),()=>{
97
+ const p=uv.mul(descriptor.atlasResolution).sub(.5),lo=floor(p),f=fract(p);
98
+ const normal=vec3(0).toVar(),weights=float(0).toVar();
99
+ for(const [x,y] of [[0,0],[1,0],[0,1],[1,1]]) {
100
+ const texel=ivec2(lo.add(vec2(x,y)).clamp(0,descriptor.atlasResolution-1));
101
+ const packed=textureLoad(maps.normalDepth,texel).toVar();
102
+ const alpha=textureLoad(maps.baseColor,texel).a;
103
+ const coverage=descriptor.alphaMode==='blend'?textureLoad(maps.orm,texel).a:alpha;
104
+ const capturedDepth=packed.b.mul(65280).add(packed.a.mul(255)).div(65535);
105
+ const supported=coverage.greaterThan(1e-4).and(alpha.greaterThanEqual(minimumAlpha.mul(coverage))).and(abs(capturedDepth.sub(depth)).lessThanEqual(tolerance));
106
+ If(supported,()=>{
107
+ const weight=(x?f.x:float(1).sub(f.x)).mul(y?f.y:float(1).sub(f.y)).mul(coverage);
108
+ normal.addAssign(decodeNormal(packed.rg.div(max(coverage,1e-10))).mul(weight));weights.addAssign(weight);
109
+ });
110
+ }
111
+ // Decode before filtering: octahedral coordinates wrap at the back pole.
112
+ result.assign(weights.greaterThan(1e-10).select(normal.normalize(),nearestNormal));
113
+ });
114
+ return result;
115
+ };
75
116
  for (const map of Object.values(maps)) {
76
117
  if (map.minFilter !== LinearFilter || map.magFilter !== LinearFilter) {
77
118
  map.minFilter = map.magFilter = LinearFilter;
@@ -79,9 +120,9 @@ export function createBoxImpostorMaterial(descriptor, maps) {
79
120
  map.needsUpdate = true;
80
121
  }
81
122
  }
82
- const material = new MeshStandardNodeMaterial({
123
+ const material = new CapturedSurfaceMaterial({
83
124
  name: "Box impostor",
84
- side: descriptor.mode !== "fitted" ? DoubleSide : FrontSide,
125
+ side: descriptor.mode !== "fitted" ? DoubleSide : BackSide,
85
126
  alphaHash: transparency === "dithered",
86
127
  transparent: transparency === "blended",
87
128
  depthWrite: transparency !== "blended",
@@ -126,7 +167,8 @@ export function createBoxImpostorMaterial(descriptor, maps) {
126
167
  let proxy = positionLocal;
127
168
  if (descriptor.mode !== "fitted") {
128
169
  proxy = Fn((_, builder) => {
129
- const forward = perspective.select(normalize(eye.sub(center)), viewAxis);
170
+ const delta = eye.sub(center);
171
+ const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize(delta), viewAxis);
130
172
  const right = modelWorldMatrixInverse
131
173
  .mul(cameraWorldMatrix.mul(vec4(0, 1, 0, 0)))
132
174
  .xyz.cross(forward)
@@ -136,7 +178,8 @@ export function createBoxImpostorMaterial(descriptor, maps) {
136
178
  // conservative perspective bound, including views close to a thin box.
137
179
  const radius = half.length();
138
180
  const distance = dot(eye.sub(center), forward);
139
- const plane = center.add(forward.mul(radius));
181
+ const planeOffset = perspective.select(min(radius, distance.sub(cameraNear.mul(2))), radius);
182
+ const plane = center.add(forward.mul(planeOffset));
140
183
  const lo = vec2(1e20).toVar(),
141
184
  hi = vec2(-1e20).toVar();
142
185
  for (const x of [-1, 1])
@@ -144,7 +187,7 @@ export function createBoxImpostorMaterial(descriptor, maps) {
144
187
  for (const z of [-1, 1]) {
145
188
  const corner = fromBox(half.mul(vec3(x, y, z)));
146
189
  const scale = perspective.select(
147
- max(distance.sub(radius), 0.00001).div(
190
+ max(distance.sub(planeOffset), 0.00001).div(
148
191
  max(distance.sub(dot(corner, forward)), 0.00001),
149
192
  ),
150
193
  float(1),
@@ -165,7 +208,8 @@ export function createBoxImpostorMaterial(descriptor, maps) {
165
208
  boxDepthMode(descriptor, settings) === "projection" &&
166
209
  descriptor.mode === "fitted" &&
167
210
  settings.interpolation === "none"
168
- )
211
+ ) {
212
+ material.side = FrontSide;
169
213
  return applyBoxFaces({
170
214
  material,
171
215
  descriptor,
@@ -176,6 +220,7 @@ export function createBoxImpostorMaterial(descriptor, maps) {
176
220
  toBox,
177
221
  fromBox,
178
222
  });
223
+ }
179
224
  if (boxDepthMode(descriptor, settings) === "projection")
180
225
  return applyBoxProjection({
181
226
  material,
@@ -385,8 +430,9 @@ export function createBoxImpostorMaterial(descriptor, maps) {
385
430
  // jump beyond that footprint must not become a connecting wall.
386
431
  const texel = ivec2(uv.mul(descriptor.atlasResolution));
387
432
  const nearest = textureLoad(maps.normalDepth, texel);
388
- // Depth padding supplies filtering support, not geometry. A hit
389
- // still needs an occupied nearest texel, including at box entry.
433
+ // Depth padding supports filtering; every hit still requires an
434
+ // occupied nearest texel, including at box entry.
435
+ const capturedBase = texture(maps.baseColor,uv).level(0);
390
436
  const occupied = textureLoad(maps.orm, texel).a.greaterThan(0.5);
391
437
  const residual = abs(
392
438
  dot(point, n).sub(float(1).sub(decode(nearest).mul(2))),
@@ -403,9 +449,7 @@ export function createBoxImpostorMaterial(descriptor, maps) {
403
449
  .lessThanEqual(tolerance)
404
450
  .and(occupied)
405
451
  .and(
406
- texture(maps.baseColor, uv)
407
- .level(0)
408
- .a.greaterThanEqual(minimumAlpha),
452
+ capturedBase.a.greaterThanEqual(minimumAlpha),
409
453
  ),
410
454
  () => {
411
455
  valid.assign(1);
@@ -415,7 +459,7 @@ export function createBoxImpostorMaterial(descriptor, maps) {
415
459
  found.assign(1);
416
460
  const packed = texture(maps.normalDepth, uv)
417
461
  .level(0)
418
- .rg.div(max(texture(maps.orm, uv).level(0).a, 1e-10))
462
+ .rg.div(max(surfaceCoverage(texture(maps.orm, uv).level(0).a,capturedBase.a), 1e-10))
419
463
  .mul(2)
420
464
  .sub(1);
421
465
  const normal = vec3(
@@ -571,12 +615,13 @@ export function createBoxImpostorMaterial(descriptor, maps) {
571
615
  );
572
616
  });
573
617
  const hit = raycast().toVar("boxHit");
618
+ hit.toStack();
574
619
  const base = texture(maps.baseColor, hit.get("uv")).level(0),
575
620
  orm = texture(maps.orm, hit.get("uv")).level(0);
576
621
  // Capture backgrounds are zero in every map. Normalize all filtered surface
577
622
  // attributes by geometric coverage; an
578
623
  // empty neighbor must not turn a rough edge into a glossy highlight.
579
- const coverage = max(orm.a, 1e-10);
624
+ const coverage = max(surfaceCoverage(orm.a,base.a), 1e-10);
580
625
  let color = base.div(coverage),
581
626
  surfaceOrm = orm.rgb.div(coverage),
582
627
  emission = texture(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage),
@@ -647,32 +692,44 @@ export function createBoxImpostorMaterial(descriptor, maps) {
647
692
  ),
648
693
  () => {
649
694
  const angle = abs(look.element(axis));
650
- const weight =
695
+ const filtered = filtering ? texture(maps.normalDepth,uv).level(0).toVar() : captured;
696
+ let weight =
651
697
  settings.interpolation === "smooth" ? angle.mul(angle) : angle;
652
- const coverage = max(sampledOrm.a, 1e-10);
698
+ if (filtering) {
699
+ const error = abs(dot(point,n).sub(float(1).sub(
700
+ filtered.b.mul(65280).add(filtered.a.mul(255)).div(65535).mul(2)
701
+ )));
702
+ weight = weight.mul(float(1).sub(error.div(tolerance)).clamp(0,1));
703
+ }
704
+ const coverage = max(surfaceCoverage(sampledOrm.a,sampled.a), 1e-10);
653
705
  colors.addAssign(sampled.div(coverage).mul(weight));
654
706
  materials.addAssign(sampledOrm.rgb.div(coverage).mul(weight));
655
707
  emissions.addAssign(
656
708
  texture(maps.emissive, uv).level(0).rgb.div(coverage).mul(weight),
657
709
  );
658
- const packed = captured.rg.mul(2).sub(1);
659
- const decoded = vec3(
660
- packed,
661
- float(1).sub(abs(packed.x)).sub(abs(packed.y)),
662
- ).toVar();
663
- If(decoded.z.lessThan(0), () => {
664
- decoded.xy.assign(
665
- vec2(1)
666
- .sub(abs(decoded.yx))
667
- .mul(sign(decoded.xy.add(1e-20))),
668
- );
669
- });
710
+ let shadingNormal;
711
+ if (filtering) shadingNormal = filteredNormal(uv,float(1).sub(dot(point,n)).mul(.5),tolerance.mul(.5),captured,sampled.a,filtered,sampledOrm.a);
712
+ else {
713
+ const packed = captured.rg.mul(2).sub(1);
714
+ const decoded = vec3(
715
+ packed,
716
+ float(1).sub(abs(packed.x)).sub(abs(packed.y)),
717
+ ).toVar();
718
+ If(decoded.z.lessThan(0), () => {
719
+ decoded.xy.assign(
720
+ vec2(1)
721
+ .sub(abs(decoded.yx))
722
+ .mul(sign(decoded.xy.add(1e-20))),
723
+ );
724
+ });
725
+ shadingNormal = decoded;
726
+ }
670
727
  normals.addAssign(
671
728
  fromBox(
672
729
  right
673
- .mul(decoded.x)
674
- .add(up.mul(decoded.y))
675
- .add(n.mul(decoded.z)),
730
+ .mul(shadingNormal.x)
731
+ .add(up.mul(shadingNormal.y))
732
+ .add(n.mul(shadingNormal.z)),
676
733
  )
677
734
  .normalize()
678
735
  .mul(weight),
@@ -695,6 +752,7 @@ export function createBoxImpostorMaterial(descriptor, maps) {
695
752
  emission = blended.get("emission");
696
753
  normal = blended.get("normal");
697
754
  }
755
+ material.capturedPositionNode = hit.get("position");
698
756
  material.colorNode = color.rgb;
699
757
  material.normalNode = transformNormalToView(normal);
700
758
  material.roughnessNode = surfaceOrm.g;
@@ -704,15 +762,7 @@ export function createBoxImpostorMaterial(descriptor, maps) {
704
762
  if (transparency !== "cutout") material.opacityNode = color.a.clamp(0, 1);
705
763
  material.maskNode = hit.get("valid").greaterThan(0.5);
706
764
  material.maskShadowNode = material.maskNode;
707
- material.depthNode = Fn((_, builder) => {
708
- const z = modelViewMatrix
709
- .mul(vec4(hit.get("position"), 1))
710
- .z.toVar("boxHitDepthZ");
711
- return perspective.select(
712
- viewZToPerspectiveDepth(z, cameraNear, cameraFar),
713
- viewZToOrthographicDepth(z, cameraNear, cameraFar),
714
- );
715
- })();
765
+ material.depthNode = capturedSurfaceDepth(hit.get("position"));
716
766
  material.receivedShadowPositionNode = modelWorldMatrix.mul(
717
767
  vec4(hit.get("position"), 1),
718
768
  ).xyz;
@@ -1,5 +1,6 @@
1
1
  // TSL struct member types are verified by rendered GPU regressions.
2
2
  // @ts-nocheck
3
+ import { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';
3
4
  import { DataTexture, FloatType, RGBAFormat, NearestFilter } from 'three';
4
5
  import {
5
6
  Fn,
@@ -19,12 +20,7 @@ import {
19
20
  textureLoad,
20
21
  attribute,
21
22
  struct,
22
- modelViewMatrix,
23
23
  modelWorldMatrix,
24
- cameraNear,
25
- cameraFar,
26
- viewZToPerspectiveDepth,
27
- viewZToOrthographicDepth,
28
24
  transformNormalToView,
29
25
  } from 'three/tsl';
30
26
  import { BOX_FACE_AXES } from './box-impostor-metadata.js';
@@ -259,6 +255,7 @@ export function applyBoxProjection({
259
255
  positions,
260
256
  );
261
257
  })().toVar('boxProjectedSurface');
258
+ material.capturedPositionNode = surface.get('position');
262
259
  material.colorNode = surface.get('color');
263
260
  material.normalNode = transformNormalToView(surface.get('normal'));
264
261
  material.roughnessNode = surface.get('orm').g;
@@ -270,15 +267,7 @@ export function applyBoxProjection({
270
267
  .greaterThanEqual(transparency === 'cutout' ? alphaCutoff : float(1 / 255));
271
268
  material.maskShadowNode = material.maskNode;
272
269
  if (transparency !== 'cutout') material.opacityNode = surface.get('alpha');
273
- material.depthNode = Fn(() => {
274
- const z = modelViewMatrix
275
- .mul(vec4(surface.get('position'), 1))
276
- .z.toVar('boxProjectionDepthZ');
277
- return perspective.select(
278
- viewZToPerspectiveDepth(z, cameraNear, cameraFar),
279
- viewZToOrthographicDepth(z, cameraNear, cameraFar),
280
- );
281
- })();
270
+ material.depthNode = capturedSurfaceDepth(surface.get('position'));
282
271
  material.receivedShadowPositionNode = modelWorldMatrix.mul(
283
272
  vec4(surface.get('position'), 1),
284
273
  ).xyz;
@@ -10,12 +10,13 @@ import {
10
10
  NEEDLE_BOX_IMPOSTOR,
11
11
  parseBoxImpostorDescriptor,
12
12
  } from './box-impostor-metadata.js';
13
+ import { enableRendererNodeMaterials, rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';
13
14
  import { createBoxImpostorGeometry } from './box-impostor-geometry.js';
14
15
  import { createBoxImpostorMaterial } from './box-impostor-material.js';
15
16
 
16
17
  export class NeedleBoxImpostorLoaderPlugin {
17
18
  /** @param {import('three/addons/loaders/GLTFLoader.js').GLTFParser} parser
18
- * @param {{renderer?:{isWebGPURenderer?:boolean}}} [options] */
19
+ * @param {{renderer?:import('../rendering/renderer-support.js').ImpostorRenderer}} [options] */
19
20
  constructor(parser, options = {}) {
20
21
  this.name = NEEDLE_BOX_IMPOSTOR;
21
22
  this.parser = parser;
@@ -23,6 +24,7 @@ export class NeedleBoxImpostorLoaderPlugin {
23
24
  }
24
25
  /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
25
26
  async afterRoot(result) {
27
+ await enableRendererNodeMaterials(this.options.renderer);
26
28
  const seen = new Set();
27
29
  const geometries = new Set();
28
30
  const materials = new Set();
@@ -42,12 +44,12 @@ export class NeedleBoxImpostorLoaderPlugin {
42
44
  ?.extensions?.[NEEDLE_BOX_IMPOSTOR];
43
45
  if (raw === undefined) return;
44
46
  const descriptor = parseBoxImpostorDescriptor(raw);
45
- if (!this.options.renderer?.isWebGPURenderer) {
47
+ if (!rendererSupportsImpostorNodeMaterials(this.options.renderer)) {
46
48
  if (
47
49
  this.parser.json.extensionsRequired?.includes(NEEDLE_BOX_IMPOSTOR)
48
50
  )
49
51
  throw new Error(
50
- 'NEEDLE_box_impostor requires Three WebGPURenderer (WebGPU or WebGL2 backend).',
52
+ 'NEEDLE_box_impostor requires Three WebGPURenderer or a renderer with compatible node-material support.',
51
53
  );
52
54
  mesh.userData.boxImpostorFallback = true;
53
55
  return;
@@ -113,7 +115,7 @@ export class NeedleBoxImpostorLoaderPlugin {
113
115
  }
114
116
  }
115
117
  /** @template {import('three/addons/loaders/GLTFLoader.js').GLTFLoader} T
116
- * @param {T} loader @param {{renderer?:{isWebGPURenderer?:boolean}}} [options] @returns {T} */
118
+ * @param {T} loader @param {{renderer?:import('../rendering/renderer-support.js').ImpostorRenderer}} [options] @returns {T} */
117
119
  export function registerNeedleBoxImpostorLoader(loader, options = {}) {
118
120
  loader.register(
119
121
  (parser) => new NeedleBoxImpostorLoaderPlugin(parser, options),
@@ -4,6 +4,11 @@
4
4
  // their declared member layout.
5
5
  // @ts-nocheck
6
6
 
7
+ import { enableRendererNodeMaterials, rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';
8
+ export { rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';
9
+
10
+ import { CapturedSurfaceMaterial } from '../rendering/captured-surface-material.js';
11
+ import { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';
7
12
  import {
8
13
  ClampToEdgeWrapping,
9
14
  DoubleSide,
@@ -26,8 +31,6 @@ import {
26
31
  abs,
27
32
  any,
28
33
  bool,
29
- cameraFar,
30
- cameraNear,
31
34
  cameraPosition,
32
35
  cameraWorldMatrix,
33
36
  cross,
@@ -42,7 +45,6 @@ import {
42
45
  max,
43
46
  min,
44
47
  mix,
45
- modelViewMatrix,
46
48
  modelWorldMatrix,
47
49
  modelWorldMatrixInverse,
48
50
  positionGeometry,
@@ -55,8 +57,6 @@ import {
55
57
  vec2,
56
58
  vec3,
57
59
  vec4,
58
- viewZToOrthographicDepth,
59
- viewZToPerspectiveDepth,
60
60
  } from 'three/tsl';
61
61
  import { NEEDLE_MESH_IMPOSTOR } from './impostor-metadata.js';
62
62
  import { bindTextureSlot } from '../rendering/texture-slot.js';
@@ -73,13 +73,7 @@ const NAMED_STRUCT_FACTORY = Reflect.get(TSL, 'struct');
73
73
 
74
74
  /** @import { ImpostorDescriptor } from './impostor-metadata.js' */
75
75
 
76
- /**
77
- * @typedef {object} ImpostorRenderer
78
- * @property {boolean=} isWebGPURenderer
79
- * @property {boolean=} isWebGLRenderer
80
- * @property {(object & {supportsNodeMaterials?: boolean})=} capabilities
81
- */
82
-
76
+ /** @typedef {import('../rendering/renderer-support.js').ImpostorRenderer} ImpostorRenderer */
83
77
  /**
84
78
  * @typedef {object} ImpostorRuntimeFeatures
85
79
  * @property {boolean} interpolation
@@ -126,18 +120,6 @@ export const IMPOSTOR_RUNTIME_SAMPLE_LIMITS = Object.freeze({
126
120
  const IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS = 0.002;
127
121
  const HEMISPHERE_HORIZON_TRANSITION_SINE = Math.sin(Math.PI / 180);
128
122
 
129
- /**
130
- * Reports whether a renderer can compile Baker's TSL impostor material.
131
- * WebGPURenderer supports node materials directly. Classic WebGLRenderer
132
- * integrations must advertise that they installed a compatible nodes handler.
133
- *
134
- * @param {ImpostorRenderer | undefined} renderer
135
- */
136
- export function rendererSupportsImpostorNodeMaterials(renderer) {
137
- if (typeof NAMED_STRUCT_FACTORY !== 'function') return false;
138
- return renderer?.isWebGPURenderer === true
139
- || renderer?.capabilities?.supportsNodeMaterials === true;
140
- }
141
123
 
142
124
  /**
143
125
  * @param {ImpostorDescriptor} descriptor
@@ -375,6 +357,7 @@ export class NeedleImpostorLoaderPlugin {
375
357
 
376
358
  /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
377
359
  async afterRoot(result) {
360
+ await enableRendererNodeMaterials(this.options.renderer);
378
361
  const parser = /** @type {{
379
362
  * json: {meshes?: Array<{primitives: Array<{extensions?: Record<string, unknown>}>}>},
380
363
  * associations: Map<import('three').Object3D, {meshes?: number, primitives?: number}>,
@@ -942,14 +925,13 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
942
925
  .add(cameraUpLocal.mul(positionGeometry.y));
943
926
  const planeLocal = samplingBillboardPosition.toVarying('vImpostorPlaneLocal');
944
927
  const createFrameSampler = (withReprojection) => {
945
- const buildFrameSample = ([frame, planePosition, rayDirection]) => {
928
+ const buildFrameSample = ([frame, planePosition, rayDirection, bounds]) => {
946
929
  const frameDirection = singleView
947
930
  ? singleCaptureDirection
948
931
  : gridToDirection(frame.div(frames.sub(1)));
949
932
  const basis = frameBasis(frameDirection);
950
933
  const right = basisMember(basis, 'right');
951
934
  const up = basisMember(basis, 'up');
952
- const bounds = viewBounds.element(int(frame.y.mul(frames).add(frame.x)));
953
935
  // Every atlas frame is an orthographic capture whose image plane passes
954
936
  // through the object center. Start from the intersection of the current
955
937
  // perspective camera ray and that frame plane. Projecting `planePosition`
@@ -1309,7 +1291,20 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1309
1291
  footprint,
1310
1292
  );
1311
1293
  };
1312
- return Fn(buildFrameSample);
1294
+ // Share the expensive frame search across the three selected captures.
1295
+ // Resolve uniform-array bounds at the call site for both TSL backends.
1296
+ const sampleFrame = Fn(buildFrameSample).setLayout({
1297
+ name: withReprojection ? 'sampleReprojectedImpostorFrame' : 'samplePlanarImpostorFrame',
1298
+ type: 'ImpostorFrameSample',
1299
+ inputs: [
1300
+ { name: 'frame', type: 'vec2' },
1301
+ { name: 'planePosition', type: 'vec3' },
1302
+ { name: 'rayDirection', type: 'vec3' },
1303
+ { name: 'bounds', type: 'vec4' },
1304
+ ],
1305
+ });
1306
+ return (frame, planePosition, rayDirection) => sampleFrame(frame, planePosition, rayDirection,
1307
+ viewBounds.element(int(frame.y.mul(frames).add(frame.x))));
1313
1308
  };
1314
1309
  const samplePlanarFrame = createFrameSampler(false);
1315
1310
  const sampleReprojectedFrame = features.reprojection ? createFrameSampler(true) : null;
@@ -1586,21 +1581,7 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1586
1581
 
1587
1582
  const sample = blendImpostor().toVar('impostorSample');
1588
1583
  const reconstructedWorldPosition = modelWorldMatrix.mul(vec4(blendedMember(sample, 'positionLocal'), 1)).xyz;
1589
- const reconstructedDepth = Fn(([localPosition], builder) => {
1590
- const viewZ = modelViewMatrix.mul(vec4(localPosition, 1)).z;
1591
- const resolvedDepth = builder.camera.isPerspectiveCamera
1592
- ? viewZToPerspectiveDepth(viewZ, cameraNear, cameraFar)
1593
- : viewZToOrthographicDepth(viewZ, cameraNear, cameraFar);
1594
- // The light and view cameras reconstruct the surface from different atlas
1595
- // cells. Offset only the shadow-map writer so tiny cross-view depth
1596
- // disagreement cannot make an impostor shadow itself. Main-camera depth is
1597
- // left exact for intersections with surrounding geometry.
1598
- return builder.material.isShadowPassMaterial
1599
- ? min(1, resolvedDepth.add(IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS))
1600
- : resolvedDepth;
1601
- }, 'float');
1602
-
1603
- const material = new MeshStandardNodeMaterial({
1584
+ const material = new CapturedSurfaceMaterial({
1604
1585
  name: 'Needle PBR impostor TSL',
1605
1586
  side: DoubleSide,
1606
1587
  transparent: false,
@@ -1643,7 +1624,9 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1643
1624
  );
1644
1625
  material.maskShadowNode = distanceCoverage.mul(mappingVisibility).greaterThanEqual(0.5);
1645
1626
  material.alphaToCoverage = true;
1646
- material.depthNode = reconstructedDepth(blendedMember(sample, 'positionLocal'));
1627
+ material.capturedPositionNode = blendedMember(sample, 'positionLocal');
1628
+ // Offset only the shadow writer: different capture views can disagree slightly.
1629
+ material.depthNode = capturedSurfaceDepth(material.capturedPositionNode, IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS);
1647
1630
  material.receivedShadowPositionNode = reconstructedWorldPosition;
1648
1631
  material.toneMapped = true;
1649
1632
  material.userData.impostorShaderProfile = profile;
@@ -1,4 +1,6 @@
1
1
  // @ts-check
2
+ import { CapturedSurfaceMaterial } from '../rendering/captured-surface-material.js';
3
+ import { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';
2
4
  import * as THREE from 'three';
3
5
  import { MeshBasicNodeMaterial, MeshStandardNodeMaterial } from 'three/webgpu';
4
6
  import {
@@ -10,8 +12,6 @@ import {
10
12
  attribute,
11
13
  cameraProjectionMatrix,
12
14
  cameraProjectionMatrixInverse,
13
- cameraFar,
14
- cameraNear,
15
15
  cameraPosition,
16
16
  cameraWorldMatrix,
17
17
  ceil,
@@ -45,8 +45,6 @@ import {
45
45
  vec3,
46
46
  vec4,
47
47
  vertexColor,
48
- viewZToOrthographicDepth,
49
- viewZToPerspectiveDepth,
50
48
  } from 'three/tsl';
51
49
 
52
50
  /**
@@ -255,13 +253,6 @@ export function createPixelImpostorRaycastPreview(asset, bounds, descriptor) {
255
253
  const traceVolume = /** @type {(sampleOffset: import('three/webgpu').Node<'vec2'>) => import('three/webgpu').Node<'vec4'>} */ (
256
254
  /** @type {unknown} */ (traceVolumeNode)
257
255
  );
258
- // @ts-ignore -- TSL's Fn declaration erases tuple and builder member types.
259
- const reconstructedDepth = Fn(([localPosition], builder) => {
260
- const viewZ = modelViewMatrix.mul(vec4(localPosition, 1)).z;
261
- return builder.camera.isPerspectiveCamera
262
- ? viewZToPerspectiveDepth(viewZ, cameraNear, cameraFar)
263
- : viewZToOrthographicDepth(viewZ, cameraNear, cameraFar);
264
- }, 'float');
265
256
  const createRaycastMaterial = (
266
257
  /** @type {boolean} */ antialias,
267
258
  /** @type {boolean} */ pbr,
@@ -350,7 +341,7 @@ export function createPixelImpostorRaycastPreview(asset, bounds, descriptor) {
350
341
  .select(bakedNormal.negate(), bakedNormal);
351
342
  const shadingNormal = mix(geometricNormal, projectedNormal, projectedNormalMix).normalize();
352
343
  const materialName = `Pixel impostor · volume raycast · ${antialias ? 'AA' : 'fast'} · ${pbr ? 'PBR maps' : 'plain lit'}`;
353
- const material = new MeshStandardNodeMaterial({
344
+ const material = new CapturedSurfaceMaterial({
354
345
  name: materialName,
355
346
  side: THREE.FrontSide,
356
347
  depthTest: true,
@@ -371,7 +362,8 @@ export function createPixelImpostorRaycastPreview(asset, bounds, descriptor) {
371
362
  );
372
363
  material.maskShadowNode = antialias ? coverage.greaterThanEqual(0.5) : occupied;
373
364
  material.alphaToCoverage = antialias;
374
- material.depthNode = reconstructedDepth(hitPosition);
365
+ material.capturedPositionNode = hitPosition;
366
+ material.depthNode = capturedSurfaceDepth(hitPosition);
375
367
  material.toneMapped = true;
376
368
  material.userData.screenPixelSize = screenPixelSize;
377
369
  material.userData.pixelImpostorRaycastAntialias = antialias;
@@ -48,6 +48,11 @@ export function useLoader(loader, renderer, options = {}) {
48
48
  if (json.extensionsRequired?.includes(name)) throw new Error(`Required glTF extension ${name} is disabled in useLoader.`);
49
49
  return;
50
50
  }
51
+ if (renderer?.isWebGLRenderer && renderer.setNodesHandler &&
52
+ !renderer.capabilities?.supportsNodeMaterials) {
53
+ const {enableRendererNodeMaterials} = await import('@needle-tools/three-mesh-effects/internal/rendering/renderer-support');
54
+ await enableRendererNodeMaterials(renderer);
55
+ }
51
56
  await apply(parser, result, renderer);
52
57
  },
53
58
  };
@@ -0,0 +1,55 @@
1
+ // @ts-check
2
+ import {
3
+ Fn,
4
+ cameraFar,
5
+ cameraNear,
6
+ cameraProjectionMatrix,
7
+ modelViewMatrix,
8
+ vec4,
9
+ viewZToLogarithmicDepth,
10
+ viewZToOrthographicDepth,
11
+ viewZToPerspectiveDepth,
12
+ viewZToReversedOrthographicDepth,
13
+ viewZToReversedPerspectiveDepth,
14
+ } from 'three/tsl';
15
+
16
+ /** Match the renderer's depth convention after reconstructing a local hit.
17
+ * @param {import('three/webgpu').Node<'vec3'>} position
18
+ * @param {number} [shadowBias]
19
+ */
20
+ export function capturedSurfaceDepth(position, shadowBias = 0) {
21
+ return Fn(
22
+ (
23
+ /** @type {unknown} */ _,
24
+ /** @type {import('three/webgpu').NodeBuilder} */ builder,
25
+ ) => {
26
+ // Resolve the shared hit before either projection branch consumes it.
27
+ const z = modelViewMatrix
28
+ .mul(vec4(position, 1))
29
+ .z.toVar('capturedSurfaceViewZ');
30
+ const reversed = builder.renderer.reversedDepthBuffer === true;
31
+ // One material can alternate between a perspective view and orthographic
32
+ // shadow cameras without a new pipeline; select using the active projection.
33
+ const perspective = cameraProjectionMatrix
34
+ .mul(vec4(0, 0, 0, 1))
35
+ .w.equal(0);
36
+ const perspectiveDepth =
37
+ builder.renderer.logarithmicDepthBuffer === true
38
+ ? viewZToLogarithmicDepth(z, cameraNear, cameraFar)
39
+ : (reversed
40
+ ? viewZToReversedPerspectiveDepth
41
+ : viewZToPerspectiveDepth)(z, cameraNear, cameraFar);
42
+ const result = perspective.select(
43
+ perspectiveDepth,
44
+ (reversed
45
+ ? viewZToReversedOrthographicDepth
46
+ : viewZToOrthographicDepth)(z, cameraNear, cameraFar),
47
+ );
48
+ return shadowBias &&
49
+ 'isShadowPassMaterial' in builder.material &&
50
+ builder.material.isShadowPassMaterial
51
+ ? result.add(reversed ? -shadowBias : shadowBias).clamp(0, 1)
52
+ : result;
53
+ },
54
+ )();
55
+ }
@@ -0,0 +1,27 @@
1
+ // @ts-check
2
+ import { MeshStandardNodeMaterial } from 'three/webgpu';
3
+ import { context, modelViewMatrix, modelWorldMatrix, vec4 } from 'three/tsl';
4
+
5
+ /** Light reconstructed surfaces at their hit position, not the carrier face.
6
+ * View directions stay on the same ray; local lights also need the hit distance.
7
+ */
8
+ export class CapturedSurfaceMaterial extends MeshStandardNodeMaterial {
9
+ /** @type {import('three/webgpu').Node<'vec3'> | null} */
10
+ capturedPositionNode = null;
11
+
12
+ /**
13
+ * @override
14
+ * @param {import('three/webgpu').NodeBuilder} builder
15
+ */
16
+ setupLighting(builder) {
17
+ const lighting = super.setupLighting(builder);
18
+ if (!this.capturedPositionNode) return lighting;
19
+ const world = modelWorldMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;
20
+ const view = modelViewMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;
21
+ return context(lighting, {
22
+ positionView: view,
23
+ positionWorld: world,
24
+ shadowPositionWorld: world,
25
+ });
26
+ }
27
+ }