MTLLoader.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /**
  2. * Loads a Wavefront .mtl file specifying materials
  3. *
  4. * @author angelxuanchang
  5. */
  6. import {
  7. Color,
  8. DefaultLoadingManager,
  9. FileLoader,
  10. FrontSide,
  11. Loader,
  12. LoaderUtils,
  13. MeshPhongMaterial,
  14. RepeatWrapping,
  15. TextureLoader,
  16. Vector2
  17. } from "../../../build/three.module.js";
  18. var MTLLoader = function ( manager ) {
  19. Loader.call( this, manager );
  20. };
  21. MTLLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22. constructor: MTLLoader,
  23. /**
  24. * Loads and parses a MTL asset from a URL.
  25. *
  26. * @param {String} url - URL to the MTL file.
  27. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  28. * @param {Function} [onProgress] - Callback for download progress.
  29. * @param {Function} [onError] - Callback for download errors.
  30. *
  31. * @see setPath setResourcePath
  32. *
  33. * @note In order for relative texture references to resolve correctly
  34. * you must call setResourcePath() explicitly prior to load.
  35. */
  36. load: function ( url, onLoad, onProgress, onError ) {
  37. var scope = this;
  38. var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  39. var loader = new FileLoader( this.manager );
  40. loader.setPath( this.path );
  41. loader.setRequestHeader( this.requestHeader );
  42. loader.load( url, function ( text ) {
  43. try {
  44. onLoad( scope.parse( text, path ) );
  45. } catch ( e ) {
  46. if ( onError ) {
  47. onError( e );
  48. } else {
  49. console.error( e );
  50. }
  51. scope.manager.itemError( url );
  52. }
  53. }, onProgress, onError );
  54. },
  55. setMaterialOptions: function ( value ) {
  56. this.materialOptions = value;
  57. return this;
  58. },
  59. /**
  60. * Parses a MTL file.
  61. *
  62. * @param {String} text - Content of MTL file
  63. * @return {MTLLoader.MaterialCreator}
  64. *
  65. * @see setPath setResourcePath
  66. *
  67. * @note In order for relative texture references to resolve correctly
  68. * you must call setResourcePath() explicitly prior to parse.
  69. */
  70. parse: function ( text, path ) {
  71. var lines = text.split( '\n' );
  72. var info = {};
  73. var delimiter_pattern = /\s+/;
  74. var materialsInfo = {};
  75. for ( var i = 0; i < lines.length; i ++ ) {
  76. var line = lines[ i ];
  77. line = line.trim();
  78. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  79. // Blank line or comment ignore
  80. continue;
  81. }
  82. var pos = line.indexOf( ' ' );
  83. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  84. key = key.toLowerCase();
  85. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  86. value = value.trim();
  87. if ( key === 'newmtl' ) {
  88. // New material
  89. info = { name: value };
  90. materialsInfo[ value ] = info;
  91. } else {
  92. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  93. var ss = value.split( delimiter_pattern, 3 );
  94. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  95. } else {
  96. info[ key ] = value;
  97. }
  98. }
  99. }
  100. var materialCreator = new MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  101. materialCreator.setCrossOrigin( this.crossOrigin );
  102. materialCreator.setManager( this.manager );
  103. materialCreator.setMaterials( materialsInfo );
  104. return materialCreator;
  105. }
  106. } );
  107. /**
  108. * Create a new MTLLoader.MaterialCreator
  109. * @param baseUrl - Url relative to which textures are loaded
  110. * @param options - Set of options on how to construct the materials
  111. * side: Which side to apply the material
  112. * FrontSide (default), THREE.BackSide, THREE.DoubleSide
  113. * wrap: What type of wrapping to apply for textures
  114. * RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  115. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  116. * Default: false, assumed to be already normalized
  117. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  118. * Default: false
  119. * @constructor
  120. */
  121. MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  122. this.baseUrl = baseUrl || '';
  123. this.options = options;
  124. this.materialsInfo = {};
  125. this.materials = {};
  126. this.materialsArray = [];
  127. this.nameLookup = {};
  128. this.side = ( this.options && this.options.side ) ? this.options.side : FrontSide;
  129. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : RepeatWrapping;
  130. };
  131. MTLLoader.MaterialCreator.prototype = {
  132. constructor: MTLLoader.MaterialCreator,
  133. crossOrigin: 'anonymous',
  134. setCrossOrigin: function ( value ) {
  135. this.crossOrigin = value;
  136. return this;
  137. },
  138. setManager: function ( value ) {
  139. this.manager = value;
  140. },
  141. setMaterials: function ( materialsInfo ) {
  142. this.materialsInfo = this.convert( materialsInfo );
  143. this.materials = {};
  144. this.materialsArray = [];
  145. this.nameLookup = {};
  146. },
  147. convert: function ( materialsInfo ) {
  148. if ( ! this.options ) return materialsInfo;
  149. var converted = {};
  150. for ( var mn in materialsInfo ) {
  151. // Convert materials info into normalized form based on options
  152. var mat = materialsInfo[ mn ];
  153. var covmat = {};
  154. converted[ mn ] = covmat;
  155. for ( var prop in mat ) {
  156. var save = true;
  157. var value = mat[ prop ];
  158. var lprop = prop.toLowerCase();
  159. switch ( lprop ) {
  160. case 'kd':
  161. case 'ka':
  162. case 'ks':
  163. // Diffuse color (color under white light) using RGB values
  164. if ( this.options && this.options.normalizeRGB ) {
  165. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  166. }
  167. if ( this.options && this.options.ignoreZeroRGBs ) {
  168. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  169. // ignore
  170. save = false;
  171. }
  172. }
  173. break;
  174. default:
  175. break;
  176. }
  177. if ( save ) {
  178. covmat[ lprop ] = value;
  179. }
  180. }
  181. }
  182. return converted;
  183. },
  184. preload: function () {
  185. for ( var mn in this.materialsInfo ) {
  186. this.create( mn );
  187. }
  188. },
  189. getIndex: function ( materialName ) {
  190. return this.nameLookup[ materialName ];
  191. },
  192. getAsArray: function () {
  193. var index = 0;
  194. for ( var mn in this.materialsInfo ) {
  195. this.materialsArray[ index ] = this.create( mn );
  196. this.nameLookup[ mn ] = index;
  197. index ++;
  198. }
  199. return this.materialsArray;
  200. },
  201. create: function ( materialName ) {
  202. if ( this.materials[ materialName ] === undefined ) {
  203. this.createMaterial_( materialName );
  204. }
  205. return this.materials[ materialName ];
  206. },
  207. createMaterial_: function ( materialName ) {
  208. // Create material
  209. var scope = this;
  210. var mat = this.materialsInfo[ materialName ];
  211. var params = {
  212. name: materialName,
  213. side: this.side
  214. };
  215. function resolveURL( baseUrl, url ) {
  216. if ( typeof url !== 'string' || url === '' )
  217. return '';
  218. // Absolute URL
  219. if ( /^https?:\/\//i.test( url ) ) return url;
  220. return baseUrl + url;
  221. }
  222. function setMapForType( mapType, value ) {
  223. if ( params[ mapType ] ) return; // Keep the first encountered texture
  224. var texParams = scope.getTextureParams( value, params );
  225. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  226. map.repeat.copy( texParams.scale );
  227. map.offset.copy( texParams.offset );
  228. map.wrapS = scope.wrap;
  229. map.wrapT = scope.wrap;
  230. params[ mapType ] = map;
  231. }
  232. for ( var prop in mat ) {
  233. var value = mat[ prop ];
  234. var n;
  235. if ( value === '' ) continue;
  236. switch ( prop.toLowerCase() ) {
  237. // Ns is material specular exponent
  238. case 'kd':
  239. // Diffuse color (color under white light) using RGB values
  240. params.color = new Color().fromArray( value );
  241. break;
  242. case 'ks':
  243. // Specular color (color when light is reflected from shiny surface) using RGB values
  244. params.specular = new Color().fromArray( value );
  245. break;
  246. case 'ke':
  247. // Emissive using RGB values
  248. params.emissive = new Color().fromArray( value );
  249. break;
  250. case 'map_kd':
  251. // Diffuse texture map
  252. setMapForType( "map", value );
  253. break;
  254. case 'map_ks':
  255. // Specular map
  256. setMapForType( "specularMap", value );
  257. break;
  258. case 'map_ke':
  259. // Emissive map
  260. setMapForType( "emissiveMap", value );
  261. break;
  262. case 'norm':
  263. setMapForType( "normalMap", value );
  264. break;
  265. case 'map_bump':
  266. case 'bump':
  267. // Bump texture map
  268. setMapForType( "bumpMap", value );
  269. break;
  270. case 'map_d':
  271. // Alpha map
  272. setMapForType( "alphaMap", value );
  273. params.transparent = true;
  274. break;
  275. case 'ns':
  276. // The specular exponent (defines the focus of the specular highlight)
  277. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  278. params.shininess = parseFloat( value );
  279. break;
  280. case 'd':
  281. n = parseFloat( value );
  282. if ( n < 1 ) {
  283. params.opacity = n;
  284. params.transparent = true;
  285. }
  286. break;
  287. case 'tr':
  288. n = parseFloat( value );
  289. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  290. if ( n > 0 ) {
  291. params.opacity = 1 - n;
  292. params.transparent = true;
  293. }
  294. break;
  295. default:
  296. break;
  297. }
  298. }
  299. this.materials[ materialName ] = new MeshPhongMaterial( params );
  300. return this.materials[ materialName ];
  301. },
  302. getTextureParams: function ( value, matParams ) {
  303. var texParams = {
  304. scale: new Vector2( 1, 1 ),
  305. offset: new Vector2( 0, 0 )
  306. };
  307. var items = value.split( /\s+/ );
  308. var pos;
  309. pos = items.indexOf( '-bm' );
  310. if ( pos >= 0 ) {
  311. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  312. items.splice( pos, 2 );
  313. }
  314. pos = items.indexOf( '-s' );
  315. if ( pos >= 0 ) {
  316. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  317. items.splice( pos, 4 ); // we expect 3 parameters here!
  318. }
  319. pos = items.indexOf( '-o' );
  320. if ( pos >= 0 ) {
  321. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  322. items.splice( pos, 4 ); // we expect 3 parameters here!
  323. }
  324. texParams.url = items.join( ' ' ).trim();
  325. return texParams;
  326. },
  327. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  328. var texture;
  329. var manager = ( this.manager !== undefined ) ? this.manager : DefaultLoadingManager;
  330. var loader = manager.getHandler( url );
  331. if ( loader === null ) {
  332. loader = new TextureLoader( manager );
  333. }
  334. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  335. texture = loader.load( url, onLoad, onProgress, onError );
  336. if ( mapping !== undefined ) texture.mapping = mapping;
  337. return texture;
  338. }
  339. };
  340. export { MTLLoader };