@needle-tools/materialx 1.1.0 → 1.1.1-next.044ea68

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needle-tools/materialx",
3
- "version": "1.1.0",
3
+ "version": "1.1.1-next.044ea68",
4
4
  "type": "module",
5
5
  "main": "index.ts",
6
6
  "exports": {
@@ -42,4 +42,4 @@
42
42
  "mtlx",
43
43
  "rendering"
44
44
  ]
45
- }
45
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,13 @@
1
1
  export { ready, type MaterialXContext } from "./materialx.js";
2
2
  export { MaterialXMaterial } from "./materialx.material.js";
3
3
  export { MaterialXLoader } from "./loader/loader.three.js";
4
+
5
+
6
+ import { createMaterialXMaterial } from "./loader/loader.three.js";
7
+
8
+ const Experimental_API = {
9
+ createMaterialXMaterial
10
+ }
11
+
12
+
13
+ export { Experimental_API }
@@ -3,6 +3,7 @@ import { GLTFLoader, GLTFLoaderPlugin, GLTFParser } from "three/examples/jsm/loa
3
3
  import { ready, state, MaterialXContext } from "../materialx.js";
4
4
  import { debug } from "../utils.js";
5
5
  import { MaterialXMaterial } from "../materialx.material.js";
6
+ import { Callbacks as callbacks } from "../materialx.helper.js";
6
7
 
7
8
  // TypeScript interfaces matching the C# data structures
8
9
  export type MaterialX_root_extension = {
@@ -14,10 +15,19 @@ export type MaterialX_root_extension = {
14
15
  mtlx: string;
15
16
  /** MaterialX texture pointers */
16
17
  textures: Array<{ name: string, pointer: string }>;
18
+ shaders?: Array<{
19
+ /** The materialx node name */
20
+ name: string,
21
+ /** The original name of the shader */
22
+ originalName: string,
23
+ }>,
17
24
  }
18
25
 
19
26
  export type MaterialX_material_extension = {
20
- name: string; // Material name reference
27
+ /** The MaterialX material name */
28
+ name: string;
29
+ /** The index of the shader in the shaders array of the root extension. */
30
+ shader?: number;
21
31
  }
22
32
 
23
33
  type MaterialDefinition = {
@@ -81,36 +91,6 @@ export class MaterialXLoader implements GLTFLoaderPlugin {
81
91
  return this._loadMaterialAsync(materialIndex);
82
92
  }
83
93
 
84
- // Parse the MaterialX document once and cache it
85
- private async _materialXDocumentReady(): Promise<any> {
86
- if (this._documentReadyPromise) {
87
- return this._documentReadyPromise;
88
- }
89
- return this._documentReadyPromise = (async () => {
90
- if (debug) console.log("[MaterialX] Parsing MaterialX root document...");
91
-
92
- // Ensure MaterialX is initialized
93
- await ready();
94
-
95
- if (!state.materialXModule) {
96
- throw new Error("[MaterialX] module failed to initialize");
97
- }
98
-
99
- // Create MaterialX document and parse ALL the XML data from root
100
- const doc = state.materialXModule.createDocument();
101
- doc.setDataLibrary(state.materialXStdLib);
102
-
103
- // Parse all MaterialX XML strings from the root data
104
- const root = this.materialX_root_data
105
- if (root) {
106
- if (debug) console.log(`[MaterialX] Parsing XML for: ${root.name}`);
107
- await state.materialXModule.readFromXmlString(doc, root.mtlx, "");
108
- }
109
-
110
- if (debug) console.log("[MaterialX] root document parsed successfully");
111
- return doc;
112
- })();
113
- }
114
94
 
115
95
  private async _loadMaterialAsync(materialIndex: number): Promise<Material> {
116
96
 
@@ -120,8 +100,61 @@ export class MaterialXLoader implements GLTFLoaderPlugin {
120
100
  // Handle different types of MaterialX data
121
101
  const ext = materialDef.extensions?.[this.name] as MaterialX_material_extension;
122
102
 
123
- if (ext) {
124
- return this._createMaterialXMaterial(materialDef, ext);
103
+ const mtlx = this.materialX_root_data?.mtlx;
104
+
105
+ if (ext && mtlx) {
106
+
107
+ const materialOptions: MaterialXMaterialOptions = {
108
+ ...this.options,
109
+ }
110
+
111
+ if (!materialOptions.parameters) materialOptions.parameters = {};
112
+
113
+ if (materialOptions.parameters?.side === undefined && materialDef.doubleSided !== undefined) {
114
+ materialOptions.parameters.side = materialDef.doubleSided ? DoubleSide : FrontSide;
115
+ }
116
+
117
+ return createMaterialXMaterial(mtlx, ext.name, {
118
+ cacheKey: this.options.cacheKey || "",
119
+ getTexture: async url => {
120
+ // Find the index of the texture in the parser
121
+ const filenameWithoutExt = url.split('/').pop()?.split('.').shift() || '';
122
+
123
+ // Resolve the texture from the MaterialX root extension
124
+ if (this.materialX_root_data) {
125
+ const textures = this.materialX_root_data.textures || [];
126
+ let index = -1;
127
+ for (const texture of textures) {
128
+ // Find the texture by name and use the pointer string to get the index
129
+ if (texture.name === filenameWithoutExt) {
130
+ const ptr = texture.pointer;
131
+ const indexStr = ptr.substring("/textures/".length);
132
+ index = parseInt(indexStr);
133
+
134
+ if (isNaN(index) || index < 0) {
135
+ console.error("[MaterialX] Invalid texture index in pointer:", ptr);
136
+ return;
137
+ }
138
+ else {
139
+ if (debug) console.log("[MaterialX] Texture index found:", index, "for", filenameWithoutExt);
140
+ }
141
+ }
142
+ }
143
+
144
+ if (index < 0) {
145
+ console.error("[MaterialX] Texture not found in parser:", filenameWithoutExt, this.parser.json);
146
+ return;
147
+ }
148
+ return this.parser.getDependency("texture", index);
149
+ }
150
+ return null;
151
+ }
152
+ }, materialOptions, this.context)
153
+ // Cache and return the generated material
154
+ .then(mat => {
155
+ if (mat instanceof MaterialXMaterial) this._generatedMaterials.push(mat);
156
+ return mat;
157
+ })
125
158
  }
126
159
 
127
160
  // Return fallback material instead of null
@@ -130,190 +163,179 @@ export class MaterialXLoader implements GLTFLoaderPlugin {
130
163
  return fallbackMaterial;
131
164
  }
132
165
 
133
- private async _createMaterialXMaterial(material_def: MaterialDefinition, material_extension: MaterialX_material_extension): Promise<Material> {
134
- try {
135
- if (debug) console.log(`Creating MaterialX material: ${material_extension.name}`);
166
+ }
136
167
 
137
- const doc = await this._materialXDocumentReady();
138
168
 
139
- if (!state.materialXModule || !state.materialXGenerator || !state.materialXGenContext) {
140
- console.warn("[MaterialX] WASM module not ready, returning fallback material");
141
- const fallbackMaterial = new MeshStandardMaterial();
142
- fallbackMaterial.userData.materialX = material_extension;
143
- fallbackMaterial.name = `MaterialX_Fallback_${material_extension.name}`;
144
- return fallbackMaterial;
145
- }
169
+ type MaterialXMaterialOptions = {
170
+ parameters?: MaterialParameters;
171
+ }
146
172
 
147
- // Find the renderable element following MaterialX example pattern exactly
148
- let renderableElement: any = null;
149
- let foundRenderable = false;
150
-
151
- if (debug) console.log("[MaterialX] document", doc);
152
-
153
- // Search for material nodes first (following the reference pattern)
154
- const materialNodes = doc.getMaterialNodes();
155
- if (debug) console.log(`[MaterialX] Found ${materialNodes.length} material nodes in document`, materialNodes);
156
-
157
- // Handle both array and vector-like APIs
158
- const materialNodesLength = materialNodes.length;
159
- for (let i = 0; i < materialNodesLength; ++i) {
160
- const materialNode = materialNodes[i];
161
- if (materialNode) {
162
- const materialName = materialNode.getNamePath();
163
- if (debug) console.log('[MaterialX] Scan material: ', i, materialName);
164
-
165
- // Find the matching material
166
- if (materialName == material_extension.name) {
167
- renderableElement = materialNode;
168
- foundRenderable = true;
169
- if (debug) console.log('[MaterialX] -- add material: ', materialName);
170
- break;
171
- }
173
+ /**
174
+ * Add the MaterialXLoader to the GLTFLoader instance.
175
+ */
176
+ export function useNeedleMaterialX(loader: GLTFLoader, options?: MaterialXLoaderOptions, context?: MaterialXContext) {
177
+ loader.register(p => {
178
+ const loader = new MaterialXLoader(p, options || {}, context || {});
179
+ return loader;
180
+ });
181
+ }
182
+
183
+
184
+
185
+
186
+ // Parse the MaterialX document once and cache it
187
+ async function load(mtlx: string): Promise<any> {
188
+ // Ensure MaterialX is initialized
189
+ await ready();
190
+ if (!state.materialXModule) {
191
+ throw new Error("[MaterialX] module failed to initialize");
192
+ }
193
+ // Create MaterialX document and parse ALL the XML data from root
194
+ const doc = state.materialXModule.createDocument();
195
+ doc.setDataLibrary(state.materialXStdLib);
196
+ // Parse all MaterialX XML strings from the root data
197
+ await state.materialXModule.readFromXmlString(doc, mtlx, "");
198
+ if (debug) console.log("[MaterialX] root document parsed successfully");
199
+ return doc;
200
+ }
201
+
202
+ export async function createMaterialXMaterial(mtlx: string, materialNodeName: string, loaders: callbacks, options?: MaterialXLoaderOptions, context?: MaterialXContext): Promise<Material> {
203
+ try {
204
+ if (debug) console.log(`Creating MaterialX material: ${materialNodeName}`);
205
+
206
+ const doc = await load(mtlx);
207
+
208
+ if (!state.materialXModule || !state.materialXGenerator || !state.materialXGenContext) {
209
+ console.warn("[MaterialX] WASM module not ready, returning fallback material");
210
+ const fallbackMaterial = new MeshStandardMaterial();
211
+ fallbackMaterial.name = `MaterialX_Fallback_${materialNodeName}`;
212
+ return fallbackMaterial;
213
+ }
214
+
215
+ // Find the renderable element following MaterialX example pattern exactly
216
+ let renderableElement: any = null;
217
+ let foundRenderable = false;
218
+
219
+ if (debug) console.log("[MaterialX] document", doc);
220
+
221
+ // Search for material nodes first (following the reference pattern)
222
+ const materialNodes = doc.getMaterialNodes();
223
+ if (debug) console.log(`[MaterialX] Found ${materialNodes.length} material nodes in document`, materialNodes);
224
+
225
+ // Handle both array and vector-like APIs
226
+ for (let i = 0; i < materialNodes.length; ++i) {
227
+ const materialNode = materialNodes[i];
228
+ if (materialNode) {
229
+ const name = materialNode.getNamePath();
230
+ if (debug) console.log(`[MaterialX] Scan material[${i}]: ${name}`);
231
+
232
+ // Find the matching material
233
+ if (materialNodes.length === 1 || name == materialNodeName) {
234
+ materialNodeName = name;
235
+ renderableElement = materialNode;
236
+ foundRenderable = true;
237
+ if (debug) console.log(`[MaterialX] Use material node: '${name}'`);
238
+ break;
172
239
  }
173
240
  }
241
+ }
174
242
 
175
- /*
176
- // If no material nodes found, search nodeGraphs
177
- if (!foundRenderable) {
178
- const nodeGraphs = doc.getNodeGraphs();
179
- console.log(`Found ${nodeGraphs.length} node graphs in document`);
180
- const nodeGraphsLength = nodeGraphs.length;
181
- for (let i = 0; i < nodeGraphsLength; ++i) {
182
- const nodeGraph = nodeGraphs[i];
183
- if (nodeGraph) {
184
- // Skip any nodegraph that has nodedef or sourceUri
185
- if ((nodeGraph as any).hasAttribute('nodedef') || (nodeGraph as any).hasSourceUri()) {
186
- continue;
187
- }
188
- // Skip any nodegraph that is connected to something downstream
189
- if ((nodeGraph as any).getDownstreamPorts().length > 0) {
190
- continue;
191
- }
192
- const outputs = (nodeGraph as any).getOutputs();
193
- for (let j = 0; j < outputs.length; ++j) {
194
- const output = outputs[j];
195
- if (output && !foundRenderable) {
196
- renderableElement = output;
197
- foundRenderable = true;
198
- break;
199
- }
243
+ /*
244
+ // If no material nodes found, search nodeGraphs
245
+ if (!foundRenderable) {
246
+ const nodeGraphs = doc.getNodeGraphs();
247
+ console.log(`Found ${nodeGraphs.length} node graphs in document`);
248
+ const nodeGraphsLength = nodeGraphs.length;
249
+ for (let i = 0; i < nodeGraphsLength; ++i) {
250
+ const nodeGraph = nodeGraphs[i];
251
+ if (nodeGraph) {
252
+ // Skip any nodegraph that has nodedef or sourceUri
253
+ if ((nodeGraph as any).hasAttribute('nodedef') || (nodeGraph as any).hasSourceUri()) {
254
+ continue;
255
+ }
256
+ // Skip any nodegraph that is connected to something downstream
257
+ if ((nodeGraph as any).getDownstreamPorts().length > 0) {
258
+ continue;
259
+ }
260
+ const outputs = (nodeGraph as any).getOutputs();
261
+ for (let j = 0; j < outputs.length; ++j) {
262
+ const output = outputs[j];
263
+ if (output && !foundRenderable) {
264
+ renderableElement = output;
265
+ foundRenderable = true;
266
+ break;
200
267
  }
201
- if (foundRenderable) break;
202
268
  }
269
+ if (foundRenderable) break;
203
270
  }
204
271
  }
205
-
206
- // If still no element found, search document outputs
207
- if (!foundRenderable) {
208
- const outputs = doc.getOutputs();
209
- console.log(`Found ${outputs.length} output nodes in document`);
210
- const outputsLength = outputs.length;
211
- for (let i = 0; i < outputsLength; ++i) {
212
- const output = outputs[i];
213
- if (output && !foundRenderable) {
214
- renderableElement = output;
215
- foundRenderable = true;
216
- break;
217
- }
272
+ }
273
+
274
+ // If still no element found, search document outputs
275
+ if (!foundRenderable) {
276
+ const outputs = doc.getOutputs();
277
+ console.log(`Found ${outputs.length} output nodes in document`);
278
+ const outputsLength = outputs.length;
279
+ for (let i = 0; i < outputsLength; ++i) {
280
+ const output = outputs[i];
281
+ if (output && !foundRenderable) {
282
+ renderableElement = output;
283
+ foundRenderable = true;
284
+ break;
218
285
  }
219
286
  }
220
- */
221
-
222
- if (!renderableElement) {
223
- console.warn(`[MaterialX] No renderable element found in MaterialX document (${material_extension.name})`);
224
- const fallbackMaterial = new MeshStandardMaterial();
225
- fallbackMaterial.color.set(0xff00ff);
226
- fallbackMaterial.userData.materialX = material_extension;
227
- fallbackMaterial.name = `MaterialX_NoRenderable_${material_extension.name}`;
228
- return fallbackMaterial;
229
- }
230
-
231
- if (debug) console.log("[MaterialX] Using renderable element for shader generation");
232
-
233
- // Check transparency and set context options like the reference
234
- const isTransparent = state.materialXModule.isTransparentSurface(renderableElement, state.materialXGenerator.getTarget());
235
- state.materialXGenContext.getOptions().hwTransparency = isTransparent;
236
-
237
- // Generate shaders using the element's name path
238
- if (debug) console.log("[MaterialX] Generating MaterialX shaders...");
239
- const elementName = (renderableElement as any).getNamePath ? (renderableElement as any).getNamePath() : (renderableElement as any).getName();
240
-
241
- const shader = state.materialXGenerator.generate(elementName, renderableElement, state.materialXGenContext);
242
- const shaderMaterial = new MaterialXMaterial({
243
- name: material_extension.name,
244
- shader,
245
- transparent: isTransparent,
246
- side: material_def.doubleSided ? DoubleSide : FrontSide,
247
- context: this.context,
248
- precision: this.options.parameters?.precision,
249
- loaders: {
250
- cacheKey: this.options.cacheKey || "",
251
- getTexture: async url => {
252
- // Find the index of the texture in the parser
253
- const filenameWithoutExt = url.split('/').pop()?.split('.').shift() || '';
254
-
255
- // Resolve the texture from the MaterialX root extension
256
- const ext = this.materialX_root_data;
257
- if (ext) {
258
- const textures = ext.textures || [];
259
- let index = -1;
260
- for (const texture of textures) {
261
- // Find the texture by name and use the pointer string to get the index
262
- if (texture.name === filenameWithoutExt) {
263
- const ptr = texture.pointer;
264
- const indexStr = ptr.substring("/textures/".length);
265
- index = parseInt(indexStr);
266
-
267
- if (isNaN(index) || index < 0) {
268
- console.error("[MaterialX] Invalid texture index in pointer:", ptr);
269
- return;
270
- }
271
- else {
272
- if (debug) console.log("[MaterialX] Texture index found:", index, "for", filenameWithoutExt);
273
- }
274
- }
275
- }
287
+ }
288
+ */
276
289
 
277
- if (index < 0) {
278
- console.error("[MaterialX] Texture not found in parser:", filenameWithoutExt, this.parser.json);
279
- return;
280
- }
281
- return this.parser.getDependency("texture", index).then(tex => {
282
- if (debug) console.log("[MaterialX] Texture loaded:" + tex.name, tex);
283
- return tex;
284
- });
285
- }
286
- return null;
287
- }
288
- }
289
- });
290
- // Track this material for later lighting updates
291
- this._generatedMaterials.push(shaderMaterial);
292
-
293
- // Add debugging to see if the material compiles correctly
294
- if (debug) console.log("[MaterialX] material created:", shaderMaterial.name);
295
- return shaderMaterial;
296
-
297
- } catch (error) {
298
- // This is a wasm error (an int) that we need to resolve
299
- console.error(`[MaterialX] Error creating MaterialX material (${material_extension.name}):`, error);
300
- // Return a fallback material with stored MaterialX data
290
+ if (!renderableElement) {
291
+ console.warn(`[MaterialX] No renderable element found in MaterialX document (${name})`);
301
292
  const fallbackMaterial = new MeshStandardMaterial();
302
293
  fallbackMaterial.color.set(0xff00ff);
303
- fallbackMaterial.userData.materialX = material_extension;
304
- fallbackMaterial.name = `MaterialX_Error_${material_extension.name}`;
294
+ fallbackMaterial.name = `MaterialX_NoRenderable_${name}`;
305
295
  return fallbackMaterial;
306
296
  }
307
- }
308
- }
309
297
 
298
+ if (debug) console.log("[MaterialX] Using renderable element for shader generation");
310
299
 
311
- /**
312
- * Add the MaterialXLoader to the GLTFLoader instance.
313
- */
314
- export function useNeedleMaterialX(loader: GLTFLoader, options?: MaterialXLoaderOptions, context?: MaterialXContext) {
315
- loader.register(p => {
316
- const loader = new MaterialXLoader(p, options || {}, context || {});
317
- return loader;
318
- });
300
+ // Check transparency and set context options like the reference
301
+ const isTransparent = state.materialXModule.isTransparentSurface(renderableElement, state.materialXGenerator.getTarget());
302
+ state.materialXGenContext.getOptions().hwTransparency = isTransparent;
303
+
304
+ // Generate shaders using the element's name path
305
+ if (debug) console.log("[MaterialX] Generating MaterialX shaders...");
306
+ const elementName = (renderableElement as any).getNamePath ? (renderableElement as any).getNamePath() : (renderableElement as any).getName();
307
+
308
+ const shader = state.materialXGenerator.generate(elementName, renderableElement, state.materialXGenContext);
309
+
310
+ // const rootExtension = this.materialX_root_data;
311
+
312
+ // const shaderInfo = rootExtension && material_extension.shader !== undefined && material_extension.shader >= 0
313
+ // ? rootExtension.shaders?.[material_extension.shader]
314
+ // : null;
315
+
316
+ const shaderMaterial = new MaterialXMaterial({
317
+ name: materialNodeName,
318
+ shaderName: null, //shaderInfo?.originalName || shaderInfo?.name || null,
319
+ shader,
320
+ context: context || {},
321
+ parameters: {
322
+ transparent: isTransparent,
323
+ ...options?.parameters,
324
+ },
325
+ loaders: loaders,
326
+ });
327
+
328
+ // Add debugging to see if the material compiles correctly
329
+ if (debug) console.log("[MaterialX] material created:", shaderMaterial.name);
330
+ return shaderMaterial;
331
+
332
+ } catch (error) {
333
+ // This is a wasm error (an int) that we need to resolve
334
+ console.error(`[MaterialX] Error creating MaterialX material (${name}):`, error);
335
+ // Return a fallback material with stored MaterialX data
336
+ const fallbackMaterial = new MeshStandardMaterial();
337
+ fallbackMaterial.color.set(0xff00ff);
338
+ fallbackMaterial.name = `MaterialX_Error_${name}`;
339
+ return fallbackMaterial;
340
+ }
319
341
  }
@@ -70,17 +70,17 @@ function fromMatrix(matrix: MaterialX.Matrix, dimension: MaterialX.Matrix["size"
70
70
  }
71
71
 
72
72
 
73
- export type Loaders = {
73
+ export type Callbacks = {
74
74
  /**
75
75
  * Cache key for the loaders, used to identify and reuse textures
76
76
  */
77
- readonly cacheKey: string;
77
+ readonly cacheKey?: string;
78
78
  /**
79
79
  * Get a texture by path
80
80
  * @param {string} path - The path to the texture
81
81
  * @return {Promise<THREE.Texture>} - A promise that resolves to the texture
82
82
  */
83
- readonly getTexture: (path: string) => Promise<THREE.Texture>;
83
+ readonly getTexture: (path: string) => Promise<THREE.Texture | null | void>;
84
84
  }
85
85
 
86
86
  const defaultTexture = new THREE.Texture();
@@ -119,7 +119,7 @@ function addToCache(key: string, value: any): void {
119
119
  /**
120
120
  * Get Three uniform from MaterialX value
121
121
  */
122
- function toThreeUniform(uniforms: any, type: string, value: any, name: string, loaders: Loaders, searchPath: string): THREE.Uniform {
122
+ function toThreeUniform(uniforms: any, type: string, value: any, name: string, loaders: Callbacks, searchPath: string): THREE.Uniform {
123
123
 
124
124
  const uniform = new THREE.Uniform<any>(null);
125
125
 
@@ -165,7 +165,7 @@ function toThreeUniform(uniforms: any, type: string, value: any, name: string, l
165
165
  checkCache = true;
166
166
  }
167
167
 
168
- const cacheKey = `${loaders.cacheKey}-${texturePath}`;
168
+ const cacheKey = loaders.cacheKey?.length ? `${loaders.cacheKey}-${texturePath}` : texturePath;
169
169
  const cacheValue = checkCache ? tryGetFromCache(cacheKey) : null;
170
170
  if (cacheValue) {
171
171
  if (debug) console.log('[MaterialX] Use cached texture: ', cacheKey, cacheValue);
@@ -180,27 +180,29 @@ function toThreeUniform(uniforms: any, type: string, value: any, name: string, l
180
180
  }
181
181
  }
182
182
  else {
183
- if (name.toLowerCase().includes("normal")) {
184
- uniform.value = defaultNormalTexture;
185
- }
186
- else {
187
- uniform.value = defaultTexture;
188
- }
189
-
190
183
  if (debug) console.log('[MaterialX] Load texture:', texturePath);
184
+
185
+ if (name.toLowerCase().includes("normal")) uniform.value = defaultNormalTexture;
186
+ else uniform.value = defaultTexture;
187
+ const defaultValue = uniform.value;
191
188
  // Save the loading promise in the cache
192
- const promise = loaders.getTexture(texturePath).then(res => {
193
- if (res) {
194
- res = res.clone(); // we need to clone the texture once to avoid colorSpace issues with other materials
195
- res.colorSpace = THREE.LinearSRGBColorSpace;
196
- setTextureParameters(res, name, uniforms);
197
- }
198
- return res;
199
- });
200
- if (checkCache) {
201
- addToCache(cacheKey, promise);
202
- }
203
- promise.then(res => {
189
+ const promise = loaders.getTexture(texturePath)
190
+ ?.then(res => {
191
+ if (res) {
192
+ res = res.clone(); // we need to clone the texture once to avoid colorSpace issues with other materials
193
+ res.colorSpace = THREE.LinearSRGBColorSpace;
194
+ setTextureParameters(res, name, uniforms);
195
+ }
196
+ return res;
197
+ })
198
+ .catch(err => {
199
+ console.error(`[MaterialX] Failed to load texture ${name} '${texturePath}'`, err);
200
+ return defaultValue;
201
+ });
202
+
203
+ if (checkCache) addToCache(cacheKey, promise);
204
+
205
+ promise?.then(res => {
204
206
  if (res) uniform.value = res;
205
207
  else console.warn(`[MaterialX] Failed to load texture ${name} '${texturePath}'`);
206
208
  });
@@ -454,7 +456,7 @@ export function getLightData(lights: Array<THREE.Light>, genContext: any): { lig
454
456
  /**
455
457
  * Get uniform values for a shader
456
458
  */
457
- export function getUniformValues(shaderStage: MaterialX.ShaderStage, loaders: Loaders, searchPath: string) {
459
+ export function getUniformValues(shaderStage: MaterialX.ShaderStage, loaders: Callbacks, searchPath: string) {
458
460
  const threeUniforms = {};
459
461
 
460
462
  const uniformBlocks = shaderStage.getUniformBlocks()
@@ -466,12 +468,62 @@ export function getUniformValues(shaderStage: MaterialX.ShaderStage, loaders: Lo
466
468
  for (let i = 0; i < uniforms.size(); ++i) {
467
469
  const variable = uniforms.get(i);
468
470
  const value = variable.getValue()?.getData();
469
- const name = variable.getVariable();
470
- if (debug) console.log("Adding uniform", { path: variable.getPath(), name: name, value: value, type: variable.getType().getName() });
471
- threeUniforms[name] = toThreeUniform(uniforms, variable.getType().getName(), value, name, loaders, searchPath);
471
+ const uniformName = variable.getVariable();
472
+ const type = variable.getType().getName();
473
+ threeUniforms[uniformName] = toThreeUniform(uniforms, type, value, uniformName, loaders, searchPath);
474
+ if (debug) console.log("Adding uniform", { path: variable.getPath(), type: type, name: uniformName, value: threeUniforms[uniformName], },);
472
475
  }
473
476
  }
474
477
  }
475
478
 
476
479
  return threeUniforms;
477
480
  }
481
+
482
+ export function generateMaterialPropertiesForUniforms(material: THREE.ShaderMaterial, shaderStage: MaterialX.ShaderStage) {
483
+
484
+ const uniformBlocks = shaderStage.getUniformBlocks()
485
+ for (const [blockName, uniforms] of Object.entries(uniformBlocks)) {
486
+ // Seems struct uniforms (like in LightData) end up here as well, we should filter those out.
487
+ if (blockName === "LightData") continue;
488
+
489
+ if (!uniforms.empty()) {
490
+ for (let i = 0; i < uniforms.size(); ++i) {
491
+ const variable = uniforms.get(i);
492
+ const uniformName = variable.getVariable();
493
+ let key = variable.getPath().split('/').pop();
494
+ switch (key) {
495
+ case "_Color":
496
+ key = "color";
497
+ break;
498
+ case "_Roughness":
499
+ key = "roughness";
500
+ break;
501
+ case "_Metallic":
502
+ key = "metalness";
503
+ break;
504
+ }
505
+ if (key) {
506
+ if (material.hasOwnProperty(key)) {
507
+ if (debug) console.warn(`[MaterialX] Uniform ${uniformName} already exists in material as property ${key}, skipping.`);
508
+ }
509
+ else {
510
+ Object.defineProperty(material, key, {
511
+ get: function () {
512
+ return this.uniforms?.[uniformName].value
513
+ },
514
+ set: function (v) {
515
+ const uniforms = this.uniforms;
516
+ if (!uniforms || !uniforms[uniformName]) {
517
+ console.warn(`[MaterialX] Uniform ${uniformName} not found in ${this.name} uniforms`);
518
+ return;
519
+ }
520
+ this.uniforms[uniformName].value = v;
521
+ this.uniformsNeedUpdate = true;
522
+ }
523
+ });
524
+ }
525
+ }
526
+ }
527
+ }
528
+ }
529
+ }
@@ -1,7 +1,8 @@
1
1
  import { BufferGeometry, Camera, FrontSide, GLSL3, Group, IUniform, MaterialParameters, Matrix3, Matrix4, Object3D, Scene, ShaderMaterial, Texture, Vector3, WebGLRenderer } from "three";
2
2
  import { debug, getFrame, getTime } from "./utils.js";
3
3
  import { MaterialXContext, MaterialXEnvironment } from "./materialx.js";
4
- import { getUniformValues, Loaders } from "./materialx.helper.js";
4
+ import { generateMaterialPropertiesForUniforms, getUniformValues, Callbacks } from "./materialx.helper.js";
5
+ import { cloneUniforms, cloneUniformsGroups } from "three/src/renderers/shaders/UniformsUtils.js";
5
6
 
6
7
 
7
8
  // Add helper matrices for uniform updates (similar to MaterialX example)
@@ -10,13 +11,13 @@ const worldViewPos = new Vector3();
10
11
 
11
12
  declare type MaterialXMaterialInitParameters = {
12
13
  name: string,
14
+ shaderName?: string | null, // Optional name of the shader
13
15
  shader: any,
14
- loaders: Loaders,
16
+ loaders: Callbacks,
15
17
  context: MaterialXContext,
16
18
  // Optional parameters
17
- transparent?: boolean,
18
- side?: MaterialParameters['side'],
19
- precision?: MaterialParameters['precision'],
19
+ parameters?: MaterialParameters,
20
+ debug?: boolean,
20
21
  }
21
22
 
22
23
  type Uniforms = Record<string, IUniform & { needsUpdate?: boolean }>;
@@ -24,13 +25,26 @@ type Precision = "highp" | "mediump" | "lowp";
24
25
 
25
26
  export class MaterialXMaterial extends ShaderMaterial {
26
27
 
28
+ /** The original name of the shader */
29
+ readonly shaderName: string | null = null;
30
+
27
31
  copy(source: MaterialXMaterial): this {
28
32
  super.copy(source);
29
33
  this._context = source._context;
34
+ this._shader = source._shader;
35
+ this.uniforms = cloneUniforms(source.uniforms) as Uniforms;
36
+ this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups);
37
+ this.envMapIntensity = source.envMapIntensity;
38
+ this.envMap = source.envMap;
39
+ generateMaterialPropertiesForUniforms(this, this._shader.getStage('pixel'));
40
+ generateMaterialPropertiesForUniforms(this, this._shader.getStage('vertex'));
41
+ this.needsUpdate = true;
30
42
  return this;
31
43
  }
32
44
 
33
45
  private _context: MaterialXContext | null = null;
46
+ private _shader: any;
47
+ private _needsTangents: boolean = false;
34
48
 
35
49
  constructor(init?: MaterialXMaterialInitParameters) {
36
50
 
@@ -63,7 +77,8 @@ export class MaterialXMaterial extends ShaderMaterial {
63
77
  vertexShader = vertexShader.replace(/\bi_color_0\b/g, 'color');
64
78
 
65
79
  // Patch fragmentShader
66
- const precision = init.precision || "highp" as Precision;
80
+ const precision: Precision = init.parameters?.precision || "highp" as Precision;
81
+ vertexShader = vertexShader.replace(/precision mediump float;/g, `precision ${precision} float;`);
67
82
  fragmentShader = fragmentShader.replace(/precision mediump float;/g, `precision ${precision} float;`);
68
83
  fragmentShader = fragmentShader.replace(/#define M_FLOAT_EPS 1e-8/g, precision === "highp" ? `#define M_FLOAT_EPS 1e-8` : `#define M_FLOAT_EPS 1e-3`);
69
84
 
@@ -76,9 +91,16 @@ export class MaterialXMaterial extends ShaderMaterial {
76
91
  fragmentShader = fragmentShader.replace(/\bi_tangent\b/g, 'tangent');
77
92
  fragmentShader = fragmentShader.replace(/\bi_color_0\b/g, 'color');
78
93
 
94
+ // Capture some vertex shader properties
95
+ const uv_is_vec2 = vertexShader.includes('in vec2 uv;'); // check if uv is vec2; e.g. https://matlib.gpuopen.com/main/materials/all?material=da6ec531-f5c1-4790-ac14-8a5c51d0314e
96
+ const uv1_is_vec2 = vertexShader.includes('in vec2 uv1;');
97
+ const uv2_is_vec2 = vertexShader.includes('in vec2 uv2;');
98
+ const uv3_is_vec2 = vertexShader.includes('in vec2 uv3;');
99
+
79
100
  // Remove `in vec3 position;` and so on since they're already declared by ShaderMaterial
80
101
  vertexShader = vertexShader.replace(/in\s+vec3\s+position;/g, '');
81
102
  vertexShader = vertexShader.replace(/in\s+vec3\s+normal;/g, '');
103
+ vertexShader = vertexShader.replace(/in\s+vec2\s+uv;/g, '');
82
104
  vertexShader = vertexShader.replace(/in\s+vec3\s+uv;/g, '');
83
105
  var hasUv1 = vertexShader.includes('in vec3 uv1;');
84
106
  vertexShader = vertexShader.replace(/in\s+vec3\s+uv1;/g, '');
@@ -93,10 +115,10 @@ export class MaterialXMaterial extends ShaderMaterial {
93
115
 
94
116
  // Patch uv 2-component to 3-component (`texcoord_0 = uv;` needs to be replaced with `texcoord_0 = vec3(uv, 0.0);`)
95
117
  // TODO what if we actually have a 3-component UV? Not sure what three.js does then
96
- vertexShader = vertexShader.replace(/texcoord_0 = uv;/g, 'texcoord_0 = vec3(uv, 0.0);');
97
- vertexShader = vertexShader.replace(/texcoord_1 = uv1;/g, 'texcoord_1 = vec3(uv1, 0.0);');
98
- vertexShader = vertexShader.replace(/texcoord_2 = uv2;/g, 'texcoord_2 = vec3(uv2, 0.0);');
99
- vertexShader = vertexShader.replace(/texcoord_3 = uv3;/g, 'texcoord_3 = vec3(uv3, 0.0);');
118
+ if (!uv_is_vec2) vertexShader = vertexShader.replace(/texcoord_0 = uv;/g, 'texcoord_0 = vec3(uv, 0.0);');
119
+ if (!uv1_is_vec2) vertexShader = vertexShader.replace(/texcoord_1 = uv1;/g, 'texcoord_1 = vec3(uv1, 0.0);');
120
+ if (!uv2_is_vec2) vertexShader = vertexShader.replace(/texcoord_2 = uv2;/g, 'texcoord_2 = vec3(uv2, 0.0);');
121
+ if (!uv3_is_vec2) vertexShader = vertexShader.replace(/texcoord_3 = uv3;/g, 'texcoord_3 = vec3(uv3, 0.0);');
100
122
 
101
123
  // Patch units – seems MaterialX uses different units and we end up with wrong light values?
102
124
  // result.direction = light.position - position;
@@ -124,19 +146,22 @@ export class MaterialXMaterial extends ShaderMaterial {
124
146
  if (hasColor) defines['USE_COLOR'] = '';
125
147
 
126
148
  const searchPath = ""; // Could be derived from the asset path if needed
127
- const isTransparent = init.transparent ?? false;
149
+ const isTransparent = init.parameters?.transparent ?? false;
128
150
  super({
129
151
  name: init.name,
130
152
  uniforms: {},
131
153
  vertexShader: vertexShader,
132
154
  fragmentShader: fragmentShader,
133
155
  glslVersion: GLSL3,
134
- transparent: isTransparent,
135
- side: init.side ? init.side : FrontSide,
136
156
  depthTest: true,
137
157
  depthWrite: !isTransparent,
138
158
  defines: defines,
159
+ ...init.parameters, // Spread any additional parameters passed to the material
139
160
  });
161
+ this.shaderName = init.shaderName || null;
162
+ this._context = init.context;
163
+ this._shader = init.shader;
164
+ this._needsTangents = vertexShader.includes('in vec4 tangent;') || vertexShader.includes('in vec3 tangent;');
140
165
 
141
166
  Object.assign(this.uniforms, {
142
167
  ...getUniformValues(init.shader.getStage('vertex'), init.loaders, searchPath),
@@ -147,6 +172,9 @@ export class MaterialXMaterial extends ShaderMaterial {
147
172
  u_viewPosition: { value: new Vector3() },
148
173
  u_worldInverseTransposeMatrix: { value: new Matrix4() },
149
174
 
175
+ // u_shadowMatrix: { value: new Matrix4() },
176
+ // u_shadowMap: { value: null, type: 't' }, // Shadow map
177
+
150
178
  u_envMatrix: { value: new Matrix4() },
151
179
  u_envRadiance: { value: null, type: 't' },
152
180
  u_envRadianceMips: { value: 8, type: 'i' },
@@ -158,9 +186,11 @@ export class MaterialXMaterial extends ShaderMaterial {
158
186
  u_lightData: { value: [], needsUpdate: false }, // Array of light data. We need to set needsUpdate to false until we actually update it
159
187
  });
160
188
 
161
- this._context = init.context;
189
+ generateMaterialPropertiesForUniforms(this, init.shader.getStage('pixel'));
190
+ generateMaterialPropertiesForUniforms(this, init.shader.getStage('vertex'));
162
191
 
163
- if (debug) {
192
+
193
+ if (debug || init.debug) {
164
194
  // Get lighting and environment data from MaterialX environment
165
195
  console.group("[MaterialX]: ", this.name);
166
196
  console.log(`Vertex shader length: ${vertexShader.length}\n`, vertexShader);
@@ -169,20 +199,28 @@ export class MaterialXMaterial extends ShaderMaterial {
169
199
  }
170
200
  }
171
201
 
172
- onBeforeRender(_renderer: WebGLRenderer, _scene: Scene, camera: Camera, _geometry: BufferGeometry, object: Object3D, _group: Group): void {
202
+ private _missingTangentsWarned: boolean = false;
203
+ onBeforeRender(renderer: WebGLRenderer, _scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D, _group: Group): void {
204
+ if (this._needsTangents && !geometry.attributes.tangent) {
205
+ if (!this._missingTangentsWarned) {
206
+ this._missingTangentsWarned = true;
207
+ console.warn(`[MaterialX] Tangents are required for this material (${this.name}) but not present in the geometry.`);
208
+ // TODO: can we compute tangents here?
209
+ }
210
+ }
173
211
  const time = this._context?.getTime?.() || getTime();
174
212
  const frame = this._context?.getFrame?.() || getFrame();
175
213
  const env = MaterialXEnvironment.get(_scene);
176
214
  if (env) {
177
- env.update(frame, _scene, _renderer);
178
- this.updateUniforms(env, object, camera, time, frame);
215
+ env.update(frame, _scene, renderer);
216
+ this.updateUniforms(env, renderer, object, camera, time, frame);
179
217
  }
180
218
  }
181
219
 
182
220
 
183
221
  envMapIntensity: number = 1.0; // Default intensity for environment map
184
222
  envMap: Texture | null = null; // Environment map texture, can be set externally
185
- updateUniforms = (environment: MaterialXEnvironment, object: Object3D, camera: Camera, time?: number, frame?: number) => {
223
+ updateUniforms = (environment: MaterialXEnvironment, renderer: WebGLRenderer, object: Object3D, camera: Camera, time?: number, frame?: number) => {
186
224
 
187
225
  const uniforms = this.uniforms as Uniforms;
188
226
 
@@ -197,15 +235,23 @@ export class MaterialXMaterial extends ShaderMaterial {
197
235
  uniforms.u_viewProjectionMatrix.needsUpdate = true;
198
236
  }
199
237
 
238
+ if (uniforms.u_worldInverseTransposeMatrix) {
239
+ uniforms.u_worldInverseTransposeMatrix.value.setFromMatrix3(normalMat.getNormalMatrix(object.matrixWorld));
240
+ uniforms.u_worldInverseTransposeMatrix.needsUpdate = true;
241
+ }
242
+
200
243
  if (uniforms.u_viewPosition) {
201
244
  uniforms.u_viewPosition.value.copy(camera.getWorldPosition(worldViewPos));
202
245
  uniforms.u_viewPosition.needsUpdate = true;
203
246
  }
204
247
 
205
- if (uniforms.u_worldInverseTransposeMatrix) {
206
- uniforms.u_worldInverseTransposeMatrix.value.setFromMatrix3(normalMat.getNormalMatrix(object.matrixWorld));
207
- uniforms.u_worldInverseTransposeMatrix.needsUpdate = true;
208
- }
248
+ // if (uniforms.u_shadowMap) {
249
+ // const light = environment.lights?.[2] || null;
250
+ // uniforms.u_shadowMatrix.value = light?.shadow?.matrix.clone().premultiply(object.matrixWorld.clone()).invert();
251
+ // uniforms.u_shadowMap.value = light.shadow?.map || null;
252
+ // uniforms.u_shadowMap.needsUpdate = true;
253
+ // console.log("[MaterialX] Renderer shadow map updated", light);
254
+ // }
209
255
 
210
256
  // Update time uniforms
211
257
  if (uniforms.u_time) {
@@ -216,7 +262,7 @@ export class MaterialXMaterial extends ShaderMaterial {
216
262
  if (frame === undefined) frame = getFrame();
217
263
  uniforms.u_frame.value = frame;
218
264
  }
219
-
265
+
220
266
  // Update light uniforms
221
267
  this.updateEnvironmentUniforms(environment);
222
268
 
package/src/materialx.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { MaterialX as MX } from "./materialx.types.js";
2
2
  import MaterialX from "../bin/JsMaterialXGenShader.js";
3
3
  import { debug } from "./utils.js";
4
- import { renderPMREMToEquirect } from "./textureHelper.js";
4
+ import { renderPMREMToEquirect } from "./utils.texture.js";
5
5
  import { Light, Mesh, MeshBasicMaterial, Object3D, PlaneGeometry, PMREMGenerator, Scene, Texture, WebGLRenderer } from "three";
6
6
  import { registerLights, getLightData, LightData } from "./materialx.helper.js";
7
7
  import type { MaterialXMaterial } from "./materialx.material.js";
@@ -95,6 +95,8 @@ export async function ready(): Promise<void> {
95
95
  // Set a reasonable default for max active lights
96
96
  state.materialXGenContext.getOptions().hwMaxActiveLightSources = 4;
97
97
 
98
+ // state.materialXGenContext.getOptions().hwShadowMap = true;
99
+
98
100
  // This prewarms the shader generation context to have all light types
99
101
  await registerLights(state.materialXModule, state.materialXGenContext);
100
102
 
@@ -179,13 +181,15 @@ export class MaterialXEnvironment {
179
181
  const radianceCube = new Mesh(planeGeometry, radianceMat);
180
182
  const irradianceMat = unlitMat.clone();
181
183
  irradianceMat.map = textures.irradianceTexture;
182
- const irradianceCube = new Mesh(planeGeometry, radianceMat);
184
+ const irradianceCube = new Mesh(planeGeometry, irradianceMat);
183
185
  scene.add(radianceCube);
184
186
  scene.add(irradianceCube);
185
187
  radianceCube.name = "MaterialXRadianceCube";
186
- radianceCube.position.set(.6, 1, 0);
188
+ radianceCube.position.set(.8, 1, .01);
189
+ radianceCube.scale.set(1.5, 1, 1);
187
190
  irradianceCube.name = "MaterialXIrradianceCube";
188
- irradianceCube.position.set(-.6, 1, 0);
191
+ irradianceCube.position.set(-.8, 1, -.01);
192
+ irradianceCube.scale.set(1.5, 0.98, 1);
189
193
  console.log("[MaterialX] environment initialized from Needle context", { textures, radianceCube, irradianceCube });
190
194
  }
191
195
  }
@@ -209,6 +213,9 @@ export class MaterialXEnvironment {
209
213
  this._texturesCache.clear();
210
214
  }
211
215
 
216
+ get lights() {
217
+ return this._lights;
218
+ }
212
219
  get lightData() {
213
220
  return this._lightData;
214
221
  }
package/src/utils.ts CHANGED
@@ -1,3 +1,7 @@
1
+ // import { BufferGeometry } from 'three';
2
+ // import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';
3
+
4
+
1
5
  export function getParam(name: string) {
2
6
  const urlParams = new URLSearchParams(window.location.search);
3
7
  const param = urlParams.get(name);
File without changes