MaterialXLoader.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. import {
  2. FileLoader,
  3. Loader,
  4. TextureLoader,
  5. RepeatWrapping
  6. } from 'three';
  7. import {
  8. MeshPhysicalNodeMaterial,
  9. float, bool, int, vec2, vec3, vec4, color, texture,
  10. positionLocal, positionWorld, uv, vertexColor,
  11. normalLocal, normalWorld, tangentLocal, tangentWorld,
  12. add, sub, mul, div, mod, abs, sign, floor, ceil, round, pow, sin, cos, tan,
  13. asin, acos, atan2, sqrt, exp, clamp, min, max, normalize, length, dot, cross, normalMap,
  14. remap, smoothstep, luminance, mx_rgbtohsv, mx_hsvtorgb,
  15. mix,
  16. mx_ramplr, mx_ramptb, mx_splitlr, mx_splittb,
  17. mx_fractal_noise_float, mx_noise_float, mx_cell_noise_float, mx_worley_noise_float,
  18. mx_transform_uv,
  19. mx_safepower, mx_contrast,
  20. mx_srgb_texture_to_lin_rec709,
  21. saturation
  22. } from '../nodes/Nodes.js';
  23. const colorSpaceLib = {
  24. mx_srgb_texture_to_lin_rec709
  25. };
  26. class MXElement {
  27. constructor( name, nodeFunc, params = null ) {
  28. this.name = name;
  29. this.nodeFunc = nodeFunc;
  30. this.params = params;
  31. }
  32. }
  33. // Ref: https://github.com/mrdoob/three.js/issues/24674
  34. const MXElements = [
  35. // << Math >>
  36. new MXElement( 'add', add, [ 'in1', 'in2' ] ),
  37. new MXElement( 'subtract', sub, [ 'in1', 'in2' ] ),
  38. new MXElement( 'multiply', mul, [ 'in1', 'in2' ] ),
  39. new MXElement( 'divide', div, [ 'in1', 'in2' ] ),
  40. new MXElement( 'modulo', mod, [ 'in1', 'in2' ] ),
  41. new MXElement( 'absval', abs, [ 'in1', 'in2' ] ),
  42. new MXElement( 'sign', sign, [ 'in1', 'in2' ] ),
  43. new MXElement( 'floor', floor, [ 'in1', 'in2' ] ),
  44. new MXElement( 'ceil', ceil, [ 'in1', 'in2' ] ),
  45. new MXElement( 'round', round, [ 'in1', 'in2' ] ),
  46. new MXElement( 'power', pow, [ 'in1', 'in2' ] ),
  47. new MXElement( 'sin', sin, [ 'in' ] ),
  48. new MXElement( 'cos', cos, [ 'in' ] ),
  49. new MXElement( 'tan', tan, [ 'in' ] ),
  50. new MXElement( 'asin', asin, [ 'in' ] ),
  51. new MXElement( 'acos', acos, [ 'in' ] ),
  52. new MXElement( 'atan2', atan2, [ 'in1', 'in2' ] ),
  53. new MXElement( 'sqrt', sqrt, [ 'in' ] ),
  54. //new MtlXElement( 'ln', ... ),
  55. new MXElement( 'exp', exp, [ 'in' ] ),
  56. new MXElement( 'clamp', clamp, [ 'in', 'low', 'high' ] ),
  57. new MXElement( 'min', min, [ 'in1', 'in2' ] ),
  58. new MXElement( 'max', max, [ 'in1', 'in2' ] ),
  59. new MXElement( 'normalize', normalize, [ 'in' ] ),
  60. new MXElement( 'magnitude', length, [ 'in1', 'in2' ] ),
  61. new MXElement( 'dotproduct', dot, [ 'in1', 'in2' ] ),
  62. new MXElement( 'crossproduct', cross, [ 'in' ] ),
  63. //new MtlXElement( 'transformpoint', ... ),
  64. //new MtlXElement( 'transformvector', ... ),
  65. //new MtlXElement( 'transformnormal', ... ),
  66. //new MtlXElement( 'transformmatrix', ... ),
  67. new MXElement( 'normalmap', normalMap, [ 'in', 'scale' ] ),
  68. //new MtlXElement( 'transpose', ... ),
  69. //new MtlXElement( 'determinant', ... ),
  70. //new MtlXElement( 'invertmatrix', ... ),
  71. //new MtlXElement( 'rotate2d', rotateUV, [ 'in', radians( 'amount' )** ] ),
  72. //new MtlXElement( 'rotate3d', ... ),
  73. //new MtlXElement( 'arrayappend', ... ),
  74. //new MtlXElement( 'dot', ... ),
  75. // << Adjustment >>
  76. new MXElement( 'remap', remap, [ 'in', 'inlow', 'inhigh', 'outlow', 'outhigh' ] ),
  77. new MXElement( 'smoothstep', smoothstep, [ 'in', 'low', 'high' ] ),
  78. //new MtlXElement( 'curveadjust', ... ),
  79. //new MtlXElement( 'curvelookup', ... ),
  80. new MXElement( 'luminance', luminance, [ 'in', 'lumacoeffs' ] ),
  81. new MXElement( 'rgbtohsv', mx_rgbtohsv, [ 'in' ] ),
  82. new MXElement( 'hsvtorgb', mx_hsvtorgb, [ 'in' ] ),
  83. // << Mix >>
  84. new MXElement( 'mix', mix, [ 'bg', 'fg', 'mix' ] ),
  85. // << Channel >>
  86. new MXElement( 'combine2', vec2, [ 'in1', 'in2' ] ),
  87. new MXElement( 'combine3', vec3, [ 'in1', 'in2', 'in3' ] ),
  88. new MXElement( 'combine4', vec4, [ 'in1', 'in2', 'in3', 'in4' ] ),
  89. // << Procedural >>
  90. new MXElement( 'ramplr', mx_ramplr, [ 'valuel', 'valuer', 'texcoord' ] ),
  91. new MXElement( 'ramptb', mx_ramptb, [ 'valuet', 'valueb', 'texcoord' ] ),
  92. new MXElement( 'splitlr', mx_splitlr, [ 'valuel', 'valuer', 'texcoord' ] ),
  93. new MXElement( 'splittb', mx_splittb, [ 'valuet', 'valueb', 'texcoord' ] ),
  94. new MXElement( 'noise2d', mx_noise_float, [ 'texcoord', 'amplitude', 'pivot' ] ),
  95. new MXElement( 'noise3d', mx_noise_float, [ 'texcoord', 'amplitude', 'pivot' ] ),
  96. new MXElement( 'fractal3d', mx_fractal_noise_float, [ 'position', 'octaves', 'lacunarity', 'diminish', 'amplitude' ] ),
  97. new MXElement( 'cellnoise2d', mx_cell_noise_float, [ 'texcoord' ] ),
  98. new MXElement( 'cellnoise3d', mx_cell_noise_float, [ 'texcoord' ] ),
  99. new MXElement( 'worleynoise2d', mx_worley_noise_float, [ 'texcoord', 'jitter' ] ),
  100. new MXElement( 'worleynoise3d', mx_worley_noise_float, [ 'texcoord', 'jitter' ] ),
  101. // << Supplemental >>
  102. //new MtlXElement( 'tiledimage', ... ),
  103. //new MtlXElement( 'triplanarprojection', triplanarTextures, [ 'filex', 'filey', 'filez' ] ),
  104. //new MtlXElement( 'ramp4', ... ),
  105. //new MtlXElement( 'place2d', mx_place2d, [ 'texcoord', 'pivot', 'scale', 'rotate', 'offset' ] ),
  106. new MXElement( 'safepower', mx_safepower, [ 'in1', 'in2' ] ),
  107. new MXElement( 'contrast', mx_contrast, [ 'in', 'amount', 'pivot' ] ),
  108. //new MtlXElement( 'hsvadjust', ... ),
  109. new MXElement( 'saturate', saturation, [ 'in', 'amount' ] ),
  110. //new MtlXElement( 'extract', ... ),
  111. //new MtlXElement( 'separate2', ... ),
  112. //new MtlXElement( 'separate3', ... ),
  113. //new MtlXElement( 'separate4', ... )
  114. ];
  115. const MtlXLibrary = {};
  116. MXElements.forEach( element => MtlXLibrary[ element.name ] = element );
  117. class MaterialXLoader extends Loader {
  118. constructor( manager ) {
  119. super( manager );
  120. }
  121. load( url, onLoad, onProgress, onError ) {
  122. const _onError = function ( e ) {
  123. if ( onError ) {
  124. onError( e );
  125. } else {
  126. console.error( e );
  127. }
  128. };
  129. new FileLoader( this.manager )
  130. .setPath( this.path )
  131. .load( url, async ( text ) => {
  132. try {
  133. onLoad( this.parse( text ) );
  134. } catch ( e ) {
  135. _onError( e );
  136. }
  137. }, onProgress, _onError );
  138. return this;
  139. }
  140. parse( text ) {
  141. return new MaterialX( this.manager, this.path ).parse( text );
  142. }
  143. }
  144. class MaterialXNode {
  145. constructor( materialX, nodeXML, nodePath = '' ) {
  146. this.materialX = materialX;
  147. this.nodeXML = nodeXML;
  148. this.nodePath = nodePath ? nodePath + '/' + this.name : this.name;
  149. this.parent = null;
  150. this.node = null;
  151. this.children = [];
  152. }
  153. get element() {
  154. return this.nodeXML.nodeName;
  155. }
  156. get nodeGraph() {
  157. return this.getAttribute( 'nodegraph' );
  158. }
  159. get nodeName() {
  160. return this.getAttribute( 'nodename' );
  161. }
  162. get interfaceName() {
  163. return this.getAttribute( 'interfacename' );
  164. }
  165. get output() {
  166. return this.getAttribute( 'output' );
  167. }
  168. get name() {
  169. return this.getAttribute( 'name' );
  170. }
  171. get type() {
  172. return this.getAttribute( 'type' );
  173. }
  174. get value() {
  175. return this.getAttribute( 'value' );
  176. }
  177. getNodeGraph() {
  178. let nodeX = this;
  179. while ( nodeX !== null ) {
  180. if ( nodeX.element === 'nodegraph' ) {
  181. break;
  182. }
  183. nodeX = nodeX.parent;
  184. }
  185. return nodeX;
  186. }
  187. getRoot() {
  188. let nodeX = this;
  189. while ( nodeX.parent !== null ) {
  190. nodeX = nodeX.parent;
  191. }
  192. return nodeX;
  193. }
  194. get referencePath() {
  195. let referencePath = null;
  196. if ( this.nodeGraph !== null && this.output !== null ) {
  197. referencePath = this.nodeGraph + '/' + this.output;
  198. } else if ( this.nodeName !== null || this.interfaceName !== null ) {
  199. referencePath = this.getNodeGraph().nodePath + '/' + ( this.nodeName || this.interfaceName );
  200. }
  201. return referencePath;
  202. }
  203. get hasReference() {
  204. return this.referencePath !== null;
  205. }
  206. get isConst() {
  207. return this.element === 'input' && this.value !== null && this.type !== 'filename';
  208. }
  209. getColorSpaceNode() {
  210. const csSource = this.getAttribute( 'colorspace' );
  211. const csTarget = this.getRoot().getAttribute( 'colorspace' );
  212. const nodeName = `mx_${ csSource }_to_${ csTarget }`;
  213. return colorSpaceLib[ nodeName ];
  214. }
  215. getTexture() {
  216. const filePrefix = this.getRecursiveAttribute( 'fileprefix' ) || '';
  217. let loader = this.materialX.textureLoader;
  218. const uri = filePrefix + this.value;
  219. if ( uri ) {
  220. const handler = this.materialX.manager.getHandler( uri );
  221. if ( handler !== null ) loader = handler;
  222. }
  223. const texture = loader.load( uri );
  224. texture.wrapS = texture.wrapT = RepeatWrapping;
  225. texture.flipY = false;
  226. return texture;
  227. }
  228. getClassFromType( type ) {
  229. let nodeClass = null;
  230. if ( type === 'integer' ) nodeClass = int;
  231. else if ( type === 'float' ) nodeClass = float;
  232. else if ( type === 'vector2' ) nodeClass = vec2;
  233. else if ( type === 'vector3' ) nodeClass = vec3;
  234. else if ( type === 'vector4' || type === 'color4' ) nodeClass = vec4;
  235. else if ( type === 'color3' ) nodeClass = color;
  236. else if ( type === 'boolean' ) nodeClass = bool;
  237. return nodeClass;
  238. }
  239. getNode() {
  240. let node = this.node;
  241. if ( node !== null ) {
  242. return node;
  243. }
  244. //
  245. const type = this.type;
  246. if ( this.isConst ) {
  247. const nodeClass = this.getClassFromType( type );
  248. node = nodeClass( ...this.getVector() );
  249. } else if ( this.hasReference ) {
  250. node = this.materialX.getMaterialXNode( this.referencePath ).getNode();
  251. } else {
  252. const element = this.element;
  253. if ( element === 'convert' ) {
  254. const nodeClass = this.getClassFromType( type );
  255. node = nodeClass( this.getNodeByName( 'in' ) );
  256. } else if ( element === 'constant' ) {
  257. node = this.getNodeByName( 'value' );
  258. } else if ( element === 'position' ) {
  259. const space = this.getAttribute( 'space' );
  260. node = space === 'world' ? positionWorld : positionLocal;
  261. } else if ( element === 'normal' ) {
  262. const space = this.getAttribute( 'space' );
  263. node = space === 'world' ? normalWorld : normalLocal;
  264. } else if ( element === 'tangent' ) {
  265. const space = this.getAttribute( 'space' );
  266. node = space === 'world' ? tangentWorld : tangentLocal;
  267. } else if ( element === 'texcoord' ) {
  268. const indexNode = this.getChildByName( 'index' );
  269. const index = indexNode ? parseInt( indexNode.value ) : 0;
  270. node = uv( index );
  271. } else if ( element === 'geomcolor' ) {
  272. const indexNode = this.getChildByName( 'index' );
  273. const index = indexNode ? parseInt( indexNode.value ) : 0;
  274. node = vertexColor( index );
  275. } else if ( element === 'tiledimage' ) {
  276. const file = this.getChildByName( 'file' );
  277. const textureFile = file.getTexture();
  278. const uvTiling = mx_transform_uv( ...this.getNodesByNames( [ 'uvtiling', 'uvoffset' ] ) );
  279. node = texture( textureFile, uvTiling );
  280. const colorSpaceNode = file.getColorSpaceNode();
  281. if ( colorSpaceNode ) {
  282. node = colorSpaceNode( node );
  283. }
  284. } else if ( element === 'image' ) {
  285. const file = this.getChildByName( 'file' );
  286. const uvNode = this.getNodeByName( 'texcoord' );
  287. const textureFile = file.getTexture();
  288. node = texture( textureFile, uvNode );
  289. const colorSpaceNode = file.getColorSpaceNode();
  290. if ( colorSpaceNode ) {
  291. node = colorSpaceNode( node );
  292. }
  293. } else if ( MtlXLibrary[ element ] !== undefined ) {
  294. const nodeElement = MtlXLibrary[ element ];
  295. node = nodeElement.nodeFunc( ...this.getNodesByNames( ...nodeElement.params ) );
  296. }
  297. }
  298. //
  299. if ( node === null ) {
  300. console.warn( `THREE.MaterialXLoader: Unexpected node ${ new XMLSerializer().serializeToString( this.nodeXML ) }.` );
  301. node = float( 0 );
  302. }
  303. //
  304. const nodeToTypeClass = this.getClassFromType( type );
  305. if ( nodeToTypeClass !== null ) {
  306. node = nodeToTypeClass( node );
  307. }
  308. node.name = this.name;
  309. this.node = node;
  310. return node;
  311. }
  312. getChildByName( name ) {
  313. for ( const input of this.children ) {
  314. if ( input.name === name ) {
  315. return input;
  316. }
  317. }
  318. }
  319. getNodes() {
  320. const nodes = {};
  321. for ( const input of this.children ) {
  322. const node = input.getNode();
  323. nodes[ node.name ] = node;
  324. }
  325. return nodes;
  326. }
  327. getNodeByName( name ) {
  328. const child = this.getChildByName( name );
  329. return child ? child.getNode() : undefined;
  330. }
  331. getNodesByNames( ...names ) {
  332. const nodes = [];
  333. for ( const name of names ) {
  334. const node = this.getNodeByName( name );
  335. if ( node ) nodes.push( node );
  336. }
  337. return nodes;
  338. }
  339. getValue() {
  340. return this.value.trim();
  341. }
  342. getVector() {
  343. const vector = [];
  344. for ( const val of this.getValue().split( /[,|\s]/ ) ) {
  345. if ( val !== '' ) {
  346. vector.push( Number( val.trim() ) );
  347. }
  348. }
  349. return vector;
  350. }
  351. getAttribute( name ) {
  352. return this.nodeXML.getAttribute( name );
  353. }
  354. getRecursiveAttribute( name ) {
  355. let attribute = this.nodeXML.getAttribute( name );
  356. if ( attribute === null && this.parent !== null ) {
  357. attribute = this.parent.getRecursiveAttribute( name );
  358. }
  359. return attribute;
  360. }
  361. setStandardSurfaceToGltfPBR( material ) {
  362. const inputs = this.getNodes();
  363. //
  364. let colorNode = null;
  365. if ( inputs.base && inputs.base_color ) colorNode = mul( inputs.base, inputs.base_color );
  366. else if ( inputs.base ) colorNode = inputs.base;
  367. else if ( inputs.base_color ) colorNode = inputs.base_color;
  368. //
  369. let roughnessNode = null;
  370. if ( inputs.specular_roughness ) roughnessNode = inputs.specular_roughness;
  371. //
  372. let metalnessNode = null;
  373. if ( inputs.metalness ) metalnessNode = inputs.metalness;
  374. //
  375. let clearcoatNode = null;
  376. let clearcoatRoughnessNode = null;
  377. if ( inputs.coat ) clearcoatNode = inputs.coat;
  378. if ( inputs.coat_roughness ) clearcoatRoughnessNode = inputs.coat_roughness;
  379. if ( inputs.coat_color ) {
  380. colorNode = colorNode ? mul( colorNode, inputs.coat_color ) : colorNode;
  381. }
  382. //
  383. let normalNode = null;
  384. if ( inputs.normal ) normalNode = inputs.normal;
  385. //
  386. let emissiveNode = null;
  387. if ( inputs.emission ) emissiveNode = inputs.emission;
  388. if ( inputs.emissionColor ) {
  389. emissiveNode = emissiveNode ? mul( emissiveNode, inputs.emissionColor ) : emissiveNode;
  390. }
  391. //
  392. material.colorNode = colorNode || color( 0.8, 0.8, 0.8 );
  393. material.roughnessNode = roughnessNode || float( 0.2 );
  394. material.metalnessNode = metalnessNode || float( 0 );
  395. material.clearcoatNode = clearcoatNode || float( 0 );
  396. material.clearcoatRoughnessNode = clearcoatRoughnessNode || float( 0 );
  397. if ( normalNode ) material.normalNode = normalNode;
  398. if ( emissiveNode ) material.emissiveNode = emissiveNode;
  399. }
  400. /*setGltfPBR( material ) {
  401. const inputs = this.getNodes();
  402. console.log( inputs );
  403. }*/
  404. setMaterial( material ) {
  405. const element = this.element;
  406. if ( element === 'gltf_pbr' ) {
  407. //this.setGltfPBR( material );
  408. } else if ( element === 'standard_surface' ) {
  409. this.setStandardSurfaceToGltfPBR( material );
  410. }
  411. }
  412. toMaterial() {
  413. const material = new MeshPhysicalNodeMaterial();
  414. material.name = this.name;
  415. for ( const nodeX of this.children ) {
  416. const shaderProperties = this.materialX.getMaterialXNode( nodeX.nodeName );
  417. shaderProperties.setMaterial( material );
  418. }
  419. return material;
  420. }
  421. toMaterials() {
  422. const materials = {};
  423. for ( const nodeX of this.children ) {
  424. if ( nodeX.element === 'surfacematerial' ) {
  425. const material = nodeX.toMaterial();
  426. materials[ material.name ] = material;
  427. }
  428. }
  429. return materials;
  430. }
  431. add( materialXNode ) {
  432. materialXNode.parent = this;
  433. this.children.push( materialXNode );
  434. }
  435. }
  436. class MaterialX {
  437. constructor( manager, path ) {
  438. this.manager = manager;
  439. this.path = path;
  440. this.resourcePath = '';
  441. this.nodesXLib = new Map();
  442. //this.nodesXRefLib = new WeakMap();
  443. this.textureLoader = new TextureLoader( manager );
  444. }
  445. addMaterialXNode( materialXNode ) {
  446. this.nodesXLib.set( materialXNode.nodePath, materialXNode );
  447. }
  448. /*getMaterialXNodeFromXML( xmlNode ) {
  449. return this.nodesXRefLib.get( xmlNode );
  450. }*/
  451. getMaterialXNode( ...names ) {
  452. return this.nodesXLib.get( names.join( '/' ) );
  453. }
  454. parseNode( nodeXML, nodePath = '' ) {
  455. const materialXNode = new MaterialXNode( this, nodeXML, nodePath );
  456. if ( materialXNode.nodePath ) this.addMaterialXNode( materialXNode );
  457. for ( const childNodeXML of nodeXML.children ) {
  458. const childMXNode = this.parseNode( childNodeXML, materialXNode.nodePath );
  459. materialXNode.add( childMXNode );
  460. }
  461. return materialXNode;
  462. }
  463. parse( text ) {
  464. const rootXML = new DOMParser().parseFromString( text, 'application/xml' ).documentElement;
  465. this.textureLoader.setPath( this.path );
  466. //
  467. const materials = this.parseNode( rootXML ).toMaterials();
  468. return { materials };
  469. }
  470. }
  471. export { MaterialXLoader };