MTLLoader.js 10 KB

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