MaterialXLoader.js 15 KB

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