MTLLoader.js 10 KB

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