MaterialXLoader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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. let loader = this.materialX.textureLoader;
  217. const uri = filePrefix + this.value;
  218. if ( uri ) {
  219. const handler = this.materialX.manager.getHandler( uri );
  220. if ( handler !== null ) loader = handler;
  221. }
  222. const texture = loader.load( uri );
  223. texture.wrapS = texture.wrapT = RepeatWrapping;
  224. texture.flipY = false;
  225. return texture;
  226. }
  227. getClassFromType( type ) {
  228. let nodeClass = null;
  229. if ( type === 'integer' ) nodeClass = int;
  230. else if ( type === 'float' ) nodeClass = float;
  231. else if ( type === 'vector2' ) nodeClass = vec2;
  232. else if ( type === 'vector3' ) nodeClass = vec3;
  233. else if ( type === 'vector4' || type === 'color4' ) nodeClass = vec4;
  234. else if ( type === 'color3' ) nodeClass = color;
  235. else if ( type === 'boolean' ) nodeClass = bool;
  236. return nodeClass;
  237. }
  238. getNode() {
  239. let node = this.node;
  240. if ( node !== null ) {
  241. return node;
  242. }
  243. //
  244. const type = this.type;
  245. if ( this.isConst ) {
  246. const nodeClass = this.getClassFromType( type );
  247. node = nodeClass( ...this.getVector() );
  248. } else if ( this.hasReference ) {
  249. node = this.materialX.getMaterialXNode( this.referencePath ).getNode();
  250. } else {
  251. const element = this.element;
  252. if ( element === 'convert' ) {
  253. const nodeClass = this.getClassFromType( type );
  254. node = nodeClass( this.getNodeByName( 'in' ) );
  255. } else if ( element === 'constant' ) {
  256. node = this.getNodeByName( 'value' );
  257. } else if ( element === 'position' ) {
  258. node = positionLocal;
  259. } else if ( element === 'tiledimage' ) {
  260. const file = this.getChildByName( 'file' );
  261. const textureFile = file.getTexture();
  262. const uvTiling = mx_transform_uv( ...this.getNodesByNames( [ 'uvtiling', 'uvoffset' ] ) );
  263. node = texture( textureFile, uvTiling );
  264. const colorSpaceNode = file.getColorSpaceNode();
  265. if ( colorSpaceNode ) {
  266. node = colorSpaceNode( node );
  267. }
  268. } else if ( element === 'image' ) {
  269. const file = this.getChildByName( 'file' );
  270. const uvNode = this.getNodeByName( 'texcoord' );
  271. const textureFile = file.getTexture();
  272. node = texture( textureFile, uvNode );
  273. const colorSpaceNode = file.getColorSpaceNode();
  274. if ( colorSpaceNode ) {
  275. node = colorSpaceNode( node );
  276. }
  277. } else if ( MtlXLibrary[ element ] !== undefined ) {
  278. const nodeElement = MtlXLibrary[ element ];
  279. node = nodeElement.nodeFunc( ...this.getNodesByNames( ...nodeElement.params ) );
  280. }
  281. }
  282. //
  283. if ( node === null ) {
  284. console.warn( `THREE.MaterialXLoader: Unexpected node ${ new XMLSerializer().serializeToString( this.nodeXML ) }.` );
  285. node = float( 0 );
  286. }
  287. //
  288. const nodeToTypeClass = this.getClassFromType( type );
  289. if ( nodeToTypeClass !== null ) {
  290. node = nodeToTypeClass( node );
  291. }
  292. node.name = this.name;
  293. this.node = node;
  294. return node;
  295. }
  296. getChildByName( name ) {
  297. for ( const input of this.children ) {
  298. if ( input.name === name ) {
  299. return input;
  300. }
  301. }
  302. }
  303. getNodes() {
  304. const nodes = {};
  305. for ( const input of this.children ) {
  306. const node = input.getNode();
  307. nodes[ node.name ] = node;
  308. }
  309. return nodes;
  310. }
  311. getNodeByName( name ) {
  312. const child = this.getChildByName( name );
  313. return child ? child.getNode() : undefined;
  314. }
  315. getNodesByNames( ...names ) {
  316. const nodes = [];
  317. for ( const name of names ) {
  318. const node = this.getNodeByName( name );
  319. if ( node ) nodes.push( node );
  320. }
  321. return nodes;
  322. }
  323. getValue() {
  324. return this.value.trim();
  325. }
  326. getVector() {
  327. const vector = [];
  328. for ( const val of this.getValue().split( /[,|\s]/ ) ) {
  329. if ( val !== '' ) {
  330. vector.push( Number( val.trim() ) );
  331. }
  332. }
  333. return vector;
  334. }
  335. getAttribute( name ) {
  336. return this.nodeXML.getAttribute( name );
  337. }
  338. getRecursiveAttribute( name ) {
  339. let attribute = this.nodeXML.getAttribute( name );
  340. if ( attribute === null && this.parent !== null ) {
  341. attribute = this.parent.getRecursiveAttribute( name );
  342. }
  343. return attribute;
  344. }
  345. setStandardSurfaceToGltfPBR( material ) {
  346. const inputs = this.getNodes();
  347. //
  348. let colorNode = null;
  349. if ( inputs.base && inputs.base_color ) colorNode = mul( inputs.base, inputs.base_color );
  350. else if ( inputs.base ) colorNode = inputs.base;
  351. else if ( inputs.base_color ) colorNode = inputs.base_color;
  352. //
  353. let roughnessNode = null;
  354. if ( inputs.specular_roughness ) roughnessNode = inputs.specular_roughness;
  355. //
  356. let metalnessNode = null;
  357. if ( inputs.metalness ) metalnessNode = inputs.metalness;
  358. //
  359. let clearcoatNode = null;
  360. let clearcoatRoughnessNode = null;
  361. if ( inputs.coat ) clearcoatNode = inputs.coat;
  362. if ( inputs.coat_roughness ) clearcoatRoughnessNode = inputs.coat_roughness;
  363. if ( inputs.coat_color ) {
  364. colorNode = colorNode ? mul( colorNode, inputs.coat_color ) : colorNode;
  365. }
  366. //
  367. let normalNode = null;
  368. if ( inputs.normal ) normalNode = inputs.normal;
  369. //
  370. let emissiveNode = null;
  371. if ( inputs.emission ) emissiveNode = inputs.emission;
  372. if ( inputs.emissionColor ) {
  373. emissiveNode = emissiveNode ? mul( emissiveNode, inputs.emissionColor ) : emissiveNode;
  374. }
  375. //
  376. material.colorNode = colorNode || color( 0.8, 0.8, 0.8 );
  377. material.roughnessNode = roughnessNode || float( 0.2 );
  378. material.metalnessNode = metalnessNode || float( 0 );
  379. material.clearcoatNode = clearcoatNode || float( 0 );
  380. material.clearcoatRoughnessNode = clearcoatRoughnessNode || float( 0 );
  381. if ( normalNode ) material.normalNode = normalNode;
  382. if ( emissiveNode ) material.emissiveNode = emissiveNode;
  383. }
  384. /*setGltfPBR( material ) {
  385. const inputs = this.getNodes();
  386. console.log( inputs );
  387. }*/
  388. setMaterial( material ) {
  389. const element = this.element;
  390. if ( element === 'gltf_pbr' ) {
  391. //this.setGltfPBR( material );
  392. } else if ( element === 'standard_surface' ) {
  393. this.setStandardSurfaceToGltfPBR( material );
  394. }
  395. }
  396. toMaterial() {
  397. const material = new MeshPhysicalNodeMaterial();
  398. material.name = this.name;
  399. for ( const nodeX of this.children ) {
  400. const shaderProperties = this.materialX.getMaterialXNode( nodeX.nodeName );
  401. shaderProperties.setMaterial( material );
  402. }
  403. return material;
  404. }
  405. toMaterials() {
  406. const materials = {};
  407. for ( const nodeX of this.children ) {
  408. if ( nodeX.element === 'surfacematerial' ) {
  409. const material = nodeX.toMaterial();
  410. materials[ material.name ] = material;
  411. }
  412. }
  413. return materials;
  414. }
  415. add( materialXNode ) {
  416. materialXNode.parent = this;
  417. this.children.push( materialXNode );
  418. }
  419. }
  420. class MaterialX {
  421. constructor( manager, path ) {
  422. this.manager = manager;
  423. this.path = path;
  424. this.resourcePath = '';
  425. this.nodesXLib = new Map();
  426. //this.nodesXRefLib = new WeakMap();
  427. this.textureLoader = new TextureLoader( manager );
  428. }
  429. addMaterialXNode( materialXNode ) {
  430. this.nodesXLib.set( materialXNode.nodePath, materialXNode );
  431. }
  432. /*getMaterialXNodeFromXML( xmlNode ) {
  433. return this.nodesXRefLib.get( xmlNode );
  434. }*/
  435. getMaterialXNode( ...names ) {
  436. return this.nodesXLib.get( names.join( '/' ) );
  437. }
  438. parseNode( nodeXML, nodePath = '' ) {
  439. const materialXNode = new MaterialXNode( this, nodeXML, nodePath );
  440. if ( materialXNode.nodePath ) this.addMaterialXNode( materialXNode );
  441. for ( const childNodeXML of nodeXML.children ) {
  442. const childMXNode = this.parseNode( childNodeXML, materialXNode.nodePath );
  443. materialXNode.add( childMXNode );
  444. }
  445. return materialXNode;
  446. }
  447. parse( text ) {
  448. const rootXML = new DOMParser().parseFromString( text, 'application/xml' ).documentElement;
  449. this.textureLoader.setPath( this.path );
  450. //
  451. const materials = this.parseNode( rootXML ).toMaterials();
  452. return { materials };
  453. }
  454. }
  455. export { MaterialXLoader };