MTLLoader.js 11 KB

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