MTLLoader.js 11 KB

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