@needle-tools/three-mesh-effects 0.2.1 → 0.2.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.
@@ -0,0 +1,26 @@
1
+ // @ts-nocheck
2
+
3
+ // src/rendering/texture-slot.js
4
+ function bindTextureSlot(material, slot, initial, nodes, onChange) {
5
+ let current = initial;
6
+ Object.defineProperty(material, slot, {
7
+ configurable: true,
8
+ enumerable: true,
9
+ get: () => current,
10
+ set: (value) => {
11
+ value.channel = current.channel;
12
+ value.offset = current.offset;
13
+ value.repeat = current.repeat;
14
+ value.center = current.center;
15
+ value.rotation = current.rotation;
16
+ current = value;
17
+ for (const node of nodes) node.value = value;
18
+ onChange?.(value);
19
+ material.needsUpdate = true;
20
+ }
21
+ });
22
+ }
23
+ export {
24
+ bindTextureSlot
25
+ };
26
+ //# sourceMappingURL=texture-slot.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/rendering/texture-slot.js"],
4
+ "sourcesContent": ["// @ts-check\n\n/** Keep material-slot texture replacement connected to the shader nodes.\n * @param {import('three').Material} material\n * @param {string} slot\n * @param {import('three').Texture} initial\n * @param {{value: import('three').Texture}[]} nodes\n * @param {((value: import('three').Texture) => void)=} onChange\n */\nexport function bindTextureSlot(material, slot, initial, nodes, onChange) {\n let current = initial;\n Object.defineProperty(material, slot, {\n configurable: true, enumerable: true,\n get: () => current,\n set: (/** @type {import('three').Texture} */ value) => {\n value.channel = current.channel;\n value.offset = current.offset;\n value.repeat = current.repeat;\n value.center = current.center;\n value.rotation = current.rotation;\n current = value;\n for (const node of nodes) node.value = value;\n onChange?.(value);\n material.needsUpdate = true;\n },\n });\n}\n"],
5
+ "mappings": ";;;AASO,SAAS,gBAAgB,UAAU,MAAM,SAAS,OAAO,UAAU;AACxE,MAAI,UAAU;AACd,SAAO,eAAe,UAAU,MAAM;AAAA,IACpC,cAAc;AAAA,IAAM,YAAY;AAAA,IAChC,KAAK,MAAM;AAAA,IACX,KAAK,CAAwC,UAAU;AACrD,YAAM,UAAU,QAAQ;AACxB,YAAM,SAAS,QAAQ;AACvB,YAAM,SAAS,QAAQ;AACvB,YAAM,SAAS,QAAQ;AACvB,YAAM,WAAW,QAAQ;AACzB,gBAAU;AACV,iBAAW,QAAQ,MAAO,MAAK,QAAQ;AACvC,iBAAW,KAAK;AAChB,eAAS,cAAc;AAAA,IACzB;AAAA,EACF,CAAC;AACH;",
6
+ "names": []
7
+ }
@@ -0,0 +1,10 @@
1
+ /** Keep material-slot texture replacement connected to the shader nodes.
2
+ * @param {import('three').Material} material
3
+ * @param {string} slot
4
+ * @param {import('three').Texture} initial
5
+ * @param {{value: import('three').Texture}[]} nodes
6
+ * @param {((value: import('three').Texture) => void)=} onChange
7
+ */
8
+ export function bindTextureSlot(material: import("three").Material, slot: string, initial: import("three").Texture, nodes: {
9
+ value: import("three").Texture;
10
+ }[], onChange?: ((value: import("three").Texture) => void) | undefined): void;
@@ -0,0 +1 @@
1
+ export * from '../../../src/rendering/texture-slot.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needle-tools/three-mesh-effects",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Three.js loaders and TSL effects for Needle Mesh Baker outputs.",
5
5
  "keywords": [
6
6
  "three.js",
@@ -78,7 +78,7 @@
78
78
  },
79
79
  "./package.json": "./package.json"
80
80
  },
81
- "files": ["build/", "src/", "README.md", "CHANGELOG.md", "LICENSE"],
81
+ "files": ["build/", "src/", "README.md", "CHANGELOG.md", "SKILL.md", "LICENSE"],
82
82
  "scripts": {
83
83
  "build": "node scripts/build.mjs",
84
84
  "test": "npm run build && node --test tests/use-loader.test.js",
@@ -1,6 +1,7 @@
1
- import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';
1
+ import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, Vector2, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';
2
2
  import { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, type Node } from 'three/webgpu';
3
3
  import { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from 'three/tsl';
4
+ import { bindTextureSlot } from '../rendering/texture-slot.js';
4
5
  import type { RigDescriptor } from './rig-extension.js';
5
6
 
6
7
  interface Surface { mesh: SkinnedMesh; geometry: BufferGeometry; modified: BufferGeometry; material: Material | Material[]; variants: MeshStandardNodeMaterial[] }
@@ -79,10 +80,18 @@ export class FurSurface {
79
80
  if (!signal) return material;
80
81
  const depth = attribute('furDepth', 'float' as const).mul(5).clamp(0, 1);
81
82
  const skinnedDelta = varying(positionLocal.sub(attribute('position', 'vec3' as const)), 'furSkinDelta') as Node<'vec3'>;
82
- const dimensions = signal.image as { width?: number; height?: number } | undefined;
83
- const pixel = vec2(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
83
+ const signalSlot = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap'].find(slot => Reflect.get(source, slot) === signal) ?? 'furHeightMap';
84
+ const pixel = uniform(new Vector2());
85
+ const updatePixel = (map: Texture) => {
86
+ const dimensions = map.image as { width?: number; height?: number } | undefined;
87
+ pixel.value.set(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
88
+ };
89
+ updatePixel(signal);
84
90
  const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));
85
- const height = this.height ? texture(this.height, uv(this.height.channel)).r : float(.5);
91
+ const heightNode = this.height ? texture(this.height, uv(this.height.channel)) : null;
92
+ if (heightNode && this.height) bindTextureSlot(material, 'furHeightMap', this.height,
93
+ [heightNode], value => { this.height = value; if (signalSlot === 'furHeightMap') updatePixel(value); });
94
+ const height = heightNode ? heightNode.r : float(.5);
86
95
  const raised = mix(.65, 1.35, height);
87
96
  const phase = coordinates.dot(vec2(31, 43)).add(height.sub(.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));
88
97
  const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(.65));
@@ -91,20 +100,21 @@ export class FurSurface {
91
100
  // with wind; height modulates movement rather than drawing synthetic hair.
92
101
  const shift = movement.add(gust).mul(depth).mul(raised)
93
102
  .clamp(pixel.mul(-2), pixel.mul(2)).toVar('furTextureShift');
94
- const sample = (map: Texture) => {
103
+ const sample = (map: Texture, slot: string) => {
95
104
  const node = texture(map, uv(map.channel).add(shift));
96
105
  node.updateMatrix = true;
106
+ bindTextureSlot(material, slot, map, [node], value => { Reflect.set(source, slot, value); if (signalSlot === slot) updatePixel(value); });
97
107
  return node;
98
108
  };
99
- const base = source.map ? sample(source.map) : vec4(1);
109
+ const base = source.map ? sample(source.map, 'map') : vec4(1);
100
110
  material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));
101
- if (source.alphaMap) material.opacityNode = sample(source.alphaMap).g;
102
- if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap).xyz,
111
+ if (source.alphaMap) material.opacityNode = sample(source.alphaMap, 'alphaMap').g;
112
+ if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap, 'normalMap').xyz,
103
113
  vec2(source.normalScale.x, source.normalScale.y));
104
- material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap).g.mul(source.roughness) : float(source.roughness);
105
- material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap).b.mul(source.metalness) : float(source.metalness);
106
- if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap).r).mul(source.aoMapIntensity));
107
- if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap).rgb.mul(vec3(
114
+ material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap, 'roughnessMap').g.mul(source.roughness) : float(source.roughness);
115
+ material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap, 'metalnessMap').b.mul(source.metalness) : float(source.metalness);
116
+ if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap, 'aoMap').r).mul(source.aoMapIntensity));
117
+ if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap, 'emissiveMap').rgb.mul(vec3(
108
118
  source.emissive.r * source.emissiveIntensity,
109
119
  source.emissive.g * source.emissiveIntensity,
110
120
  source.emissive.b * source.emissiveIntensity));
@@ -48,6 +48,7 @@ import {
48
48
  smoothstep,
49
49
  texture,
50
50
  textureLoad,
51
+ textureSize,
51
52
  transformNormalToView,
52
53
  uniformArray,
53
54
  vec2,
@@ -57,6 +58,7 @@ import {
57
58
  viewZToPerspectiveDepth,
58
59
  } from 'three/tsl';
59
60
  import { NEEDLE_MESH_IMPOSTOR } from './impostor-metadata.js';
61
+ import { bindTextureSlot } from '../rendering/texture-slot.js';
60
62
  import { PERSPECTIVE_RAY_PLANE_SIGN } from './octahedral.js';
61
63
  import {
62
64
  REPROJECTION_CONFIDENCE_INNER_TEXELS,
@@ -560,6 +562,21 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
560
562
  float halfTexel = 0.5001 / frameResolution;
561
563
  return (frame + clamp(insideCell, vec2(halfTexel), vec2(1.0 - halfTexel))) / frames;
562
564
  }
565
+ vec4 sampleColorAtlas(vec2 coordinates) {
566
+ vec2 size = vec2(textureSize(baseColorAtlas, 0));
567
+ vec2 grid = vec2(frames);
568
+ #if COMPACT_COLOR && COMPACT_EMISSIVE
569
+ grid.x *= 2.0;
570
+ #endif
571
+ vec2 pixels = coordinates * size;
572
+ float footprint = max(length(dFdx(pixels)), length(dFdy(pixels)));
573
+ float gutter = padding * size.y / (frames * frameResolution);
574
+ float lod = clamp(log2(max(footprint, 1.0)), 0.0, floor(log2(max(gutter, 1.0))));
575
+ vec2 cell = floor(clamp(coordinates * grid, vec2(0.0), grid - 0.00001));
576
+ vec2 guard = vec2(0.5001 * exp2(lod)) / size;
577
+ vec2 safe = clamp(coordinates, cell / grid + guard, (cell + 1.0) / grid - guard);
578
+ return textureLod(baseColorAtlas, safe, lod);
579
+ }
563
580
  void main() {
564
581
  vec3 cameraLocal = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;
565
582
  vec3 cameraDirection = normalize(cameraLocal);
@@ -594,7 +611,7 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
594
611
  #if COMPACT_COLOR
595
612
  colorUv.x *= COMPACT_EMISSIVE == 1 ? 0.5 : 1.0;
596
613
  #endif
597
- vec4 base = texture(baseColorAtlas, colorUv);
614
+ vec4 base = sampleColorAtlas(colorUv);
598
615
  vec4 geometry = texture(geometryAtlas, atlas);
599
616
  float contour = base.a;
600
617
  float depthValue;
@@ -690,14 +707,30 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
690
707
  uvNode.y,
691
708
  )
692
709
  : uvNode;
710
+ const mapLod = (atlas, coordinates) => {
711
+ const size = vec2(textureSize(atlas));
712
+ const pixels = coordinates.mul(size);
713
+ const footprint = max(pixels.dFdx().length(), pixels.dFdy().length());
714
+ const gutter = padding.mul(size.y).div(frames.mul(frameResolution));
715
+ return max(footprint, 1).log2().clamp(0, max(gutter, 1).log2().floor());
716
+ };
717
+ const sampleAtlas = (atlas, coordinates, lod = float(0), columns = frames) => {
718
+ const size = vec2(textureSize(atlas));
719
+ const grid = vec2(columns, frames);
720
+ const cell = coordinates.mul(grid).clamp(0, grid.sub(0.00001)).floor();
721
+ const guard = float(0.5001).mul(float(2).pow(lod)).div(size);
722
+ const safe = coordinates.clamp(cell.div(grid).add(guard), cell.add(1).div(grid).sub(guard));
723
+ return texture(atlas, safe).level(lod);
724
+ };
725
+ const colorColumns = frames.mul(compactLayout && compactEmissive ? 2 : 1);
693
726
  const sampleCapturedAlpha = (uvNode) => compressedGeometry
694
- ? texture(baseColorAtlas, colorAtlasUv(uvNode)).level(0).a
695
- : texture(baseColorAtlas, uvNode).level(0).a;
727
+ ? sampleAtlas(baseColorAtlas, colorAtlasUv(uvNode), float(0), colorColumns).a
728
+ : sampleAtlas(baseColorAtlas, uvNode).a;
696
729
  const sampleContour = (uvNode) => compressedGeometry
697
730
  ? texture(geometryAtlas, uvNode).level(0).a
698
731
  : descriptor.coverageEncoding === 'sdf-base-alpha'
699
- ? texture(baseColorAtlas, uvNode).level(0).a
700
- : texture(ormAtlas, uvNode).level(0).a;
732
+ ? sampleAtlas(baseColorAtlas, uvNode).a
733
+ : sampleAtlas(ormAtlas, uvNode).a;
701
734
  const viewBounds = uniformArray(
702
735
  Array.from({ length: descriptor.frames * descriptor.frames }, (_, index) => new Vector4(
703
736
  descriptor.viewBounds[index * 4],
@@ -708,12 +741,6 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
708
741
  'vec4',
709
742
  );
710
743
  const atlasResolution = float(descriptor.frames * descriptor.frameResolution);
711
- const materialAtlasResolution = float(
712
- descriptor.frames * (descriptor.compression?.materialFrameResolution ?? descriptor.frameResolution),
713
- );
714
- // Stop before the atlas gutter becomes sub-texel, otherwise adjacent views
715
- // bleed into one another in the generated mip chain.
716
- const maximumSafeAtlasLod = float(Math.max(0, Math.floor(Math.log2(Math.max(1, descriptor.padding)))));
717
744
 
718
745
  const FrameBasis = NAMED_STRUCT_FACTORY(
719
746
  { right: 'vec3', up: 'vec3' },
@@ -801,22 +828,6 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
801
828
  const halfTexel = float(0.5001).div(frameResolution);
802
829
  return frame.add(insideCell.clamp(halfTexel, float(1).sub(halfTexel))).div(frames);
803
830
  }, 'vec2');
804
- const atlasLod = Fn(([uvNode]) => {
805
- const texelCoordinate = uvNode.mul(atlasResolution);
806
- const footprint = max(
807
- texelCoordinate.dFdx().length(),
808
- texelCoordinate.dFdy().length(),
809
- );
810
- return max(footprint, 1).log2().clamp(0, maximumSafeAtlasLod);
811
- }, 'float');
812
- const materialAtlasLod = Fn(([uvNode]) => {
813
- const texelCoordinate = uvNode.mul(materialAtlasResolution);
814
- const footprint = max(
815
- texelCoordinate.dFdx().length(),
816
- texelCoordinate.dFdy().length(),
817
- );
818
- return max(footprint, 1).log2().clamp(0, maximumSafeAtlasLod);
819
- }, 'float');
820
831
  const decodeDepth16 = Fn(([packed]) => {
821
832
  if (descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba') {
822
833
  const bytes = floor(packed.rg.mul(255).add(0.5));
@@ -1137,8 +1148,6 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1137
1148
  });
1138
1149
  }
1139
1150
  const uvNode = atlasUv(frame, frameUv);
1140
- const lod = atlasLod(uvNode);
1141
- const materialLod = compactLayout ? materialAtlasLod(uvNode) : lod;
1142
1151
  reconstructed.assign(reconstructPosition(
1143
1152
  frameUv,
1144
1153
  bounds,
@@ -1147,7 +1156,7 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1147
1156
  up,
1148
1157
  sampleDepth16(uvNode),
1149
1158
  ));
1150
- const shadingSample = texture(normalDepthAtlas, uvNode).level(materialLod);
1159
+ const shadingSample = sampleAtlas(normalDepthAtlas, uvNode, mapLod(normalDepthAtlas, uvNode));
1151
1160
  const geometrySample = compressedGeometry
1152
1161
  ? texture(geometryAtlas, uvNode).level(0)
1153
1162
  : null;
@@ -1202,12 +1211,13 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1202
1211
  ? alignedConfidence.mul(strictRootSolved)
1203
1212
  : float(1),
1204
1213
  );
1205
- const baseColor = texture(baseColorAtlas, colorAtlasUv(uvNode)).level(materialLod);
1214
+ const colorUv = colorAtlasUv(uvNode);
1215
+ const baseColor = sampleAtlas(baseColorAtlas, colorUv, mapLod(baseColorAtlas, colorUv), colorColumns);
1206
1216
  const capturedAlpha = sampleCapturedAlpha(uvNode);
1207
1217
  const orm = compactLayout
1208
1218
  ? vec4(geometrySample.b, shadingSample.b, shadingSample.a, 1)
1209
1219
  : ormAtlas
1210
- ? texture(ormAtlas, uvNode).level(lod)
1220
+ ? sampleAtlas(ormAtlas, uvNode, mapLod(ormAtlas, uvNode))
1211
1221
  : vec4(
1212
1222
  descriptor.material.occlusion,
1213
1223
  descriptor.material.roughness,
@@ -1230,7 +1240,7 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1230
1240
  reconstructed,
1231
1241
  orm.rgb,
1232
1242
  emissiveAtlas
1233
- ? texture(emissiveAtlas, colorAtlasUv(uvNode, true)).level(materialLod).rgb
1243
+ ? sampleAtlas(emissiveAtlas, colorAtlasUv(uvNode, true), mapLod(emissiveAtlas, colorAtlasUv(uvNode, true)), colorColumns).rgb
1234
1244
  : vec3(0),
1235
1245
  coverage,
1236
1246
  resolvedValidity,
@@ -1577,5 +1587,23 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1577
1587
  material.receivedShadowPositionNode = reconstructedWorldPosition;
1578
1588
  material.toneMapped = true;
1579
1589
  material.userData.impostorShaderProfile = profile;
1590
+ bindTextureSlot(material, 'baseColorAtlas', maps.baseColor, [baseColorAtlas, ...(compactLayout && compactEmissive && emissiveAtlas ? [emissiveAtlas] : [])], value => {
1591
+ maps.baseColor = value;
1592
+ if (compactLayout && compactEmissive) maps.emissive = value;
1593
+ if (material.userData.impostor) {
1594
+ material.userData.impostor.atlases.baseColor = value;
1595
+ if (compactLayout && compactEmissive) material.userData.impostor.atlases.emissive = value;
1596
+ }
1597
+ });
1598
+ bindTextureSlot(material, 'normalDepthAtlas', maps.normalDepth, [normalDepthAtlas, ...(compactLayout && ormAtlas ? [ormAtlas] : []), ...(!compressedGeometry ? [geometryAtlas] : [])], value => {
1599
+ maps.normalDepth = value;
1600
+ if (compactLayout) maps.orm = value;
1601
+ if (material.userData.impostor) {
1602
+ material.userData.impostor.atlases.normalDepth = value;
1603
+ if (compactLayout) material.userData.impostor.atlases.orm = value;
1604
+ }
1605
+ });
1606
+ if (!compactLayout && maps.orm && ormAtlas) bindTextureSlot(material, 'ormAtlas', maps.orm, [ormAtlas], value => { maps.orm = value; });
1607
+ if (!compactLayout && maps.emissive && emissiveAtlas) bindTextureSlot(material, 'emissiveAtlas', maps.emissive, [emissiveAtlas], value => { maps.emissive = value; });
1580
1608
  return material;
1581
1609
  }
@@ -0,0 +1,27 @@
1
+ // @ts-check
2
+
3
+ /** Keep material-slot texture replacement connected to the shader nodes.
4
+ * @param {import('three').Material} material
5
+ * @param {string} slot
6
+ * @param {import('three').Texture} initial
7
+ * @param {{value: import('three').Texture}[]} nodes
8
+ * @param {((value: import('three').Texture) => void)=} onChange
9
+ */
10
+ export function bindTextureSlot(material, slot, initial, nodes, onChange) {
11
+ let current = initial;
12
+ Object.defineProperty(material, slot, {
13
+ configurable: true, enumerable: true,
14
+ get: () => current,
15
+ set: (/** @type {import('three').Texture} */ value) => {
16
+ value.channel = current.channel;
17
+ value.offset = current.offset;
18
+ value.repeat = current.repeat;
19
+ value.center = current.center;
20
+ value.rotation = current.rotation;
21
+ current = value;
22
+ for (const node of nodes) node.value = value;
23
+ onChange?.(value);
24
+ material.needsUpdate = true;
25
+ },
26
+ });
27
+ }