MTLLoader.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. import {
  2. Color,
  3. ColorManagement,
  4. DefaultLoadingManager,
  5. FileLoader,
  6. FrontSide,
  7. Loader,
  8. LoaderUtils,
  9. MeshPhongMaterial,
  10. RepeatWrapping,
  11. TextureLoader,
  12. Vector2,
  13. SRGBColorSpace
  14. } from 'three';
  15. /**
  16. * Loads a Wavefront .mtl file specifying materials
  17. */
  18. class MTLLoader extends Loader {
  19. constructor( manager ) {
  20. super( manager );
  21. }
  22. /**
  23. * Loads and parses a MTL asset from a URL.
  24. *
  25. * @param {String} url - URL to the MTL file.
  26. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  27. * @param {Function} [onProgress] - Callback for download progress.
  28. * @param {Function} [onError] - Callback for download errors.
  29. *
  30. * @see setPath setResourcePath
  31. *
  32. * @note In order for relative texture references to resolve correctly
  33. * you must call setResourcePath() explicitly prior to load.
  34. */
  35. load( url, onLoad, onProgress, onError ) {
  36. const scope = this;
  37. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  38. const loader = new FileLoader( this.manager );
  39. loader.setPath( this.path );
  40. loader.setRequestHeader( this.requestHeader );
  41. loader.setWithCredentials( this.withCredentials );
  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( 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 {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( text, path ) {
  71. const lines = text.split( '\n' );
  72. let info = {};
  73. const delimiter_pattern = /\s+/;
  74. const materialsInfo = {};
  75. for ( let i = 0; i < lines.length; i ++ ) {
  76. let 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. const pos = line.indexOf( ' ' );
  83. let key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  84. key = key.toLowerCase();
  85. let 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. const 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. const materialCreator = new 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. class MaterialCreator {
  122. constructor( baseUrl = '', options = {} ) {
  123. this.baseUrl = baseUrl;
  124. this.options = options;
  125. this.materialsInfo = {};
  126. this.materials = {};
  127. this.materialsArray = [];
  128. this.nameLookup = {};
  129. this.crossOrigin = 'anonymous';
  130. this.side = ( this.options.side !== undefined ) ? this.options.side : FrontSide;
  131. this.wrap = ( this.options.wrap !== undefined ) ? this.options.wrap : RepeatWrapping;
  132. }
  133. setCrossOrigin( value ) {
  134. this.crossOrigin = value;
  135. return this;
  136. }
  137. setManager( value ) {
  138. this.manager = value;
  139. }
  140. setMaterials( materialsInfo ) {
  141. this.materialsInfo = this.convert( materialsInfo );
  142. this.materials = {};
  143. this.materialsArray = [];
  144. this.nameLookup = {};
  145. }
  146. convert( materialsInfo ) {
  147. if ( ! this.options ) return materialsInfo;
  148. const converted = {};
  149. for ( const mn in materialsInfo ) {
  150. // Convert materials info into normalized form based on options
  151. const mat = materialsInfo[ mn ];
  152. const covmat = {};
  153. converted[ mn ] = covmat;
  154. for ( const prop in mat ) {
  155. let save = true;
  156. let value = mat[ prop ];
  157. const 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() {
  184. for ( const mn in this.materialsInfo ) {
  185. this.create( mn );
  186. }
  187. }
  188. getIndex( materialName ) {
  189. return this.nameLookup[ materialName ];
  190. }
  191. getAsArray() {
  192. let index = 0;
  193. for ( const 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( materialName ) {
  201. if ( this.materials[ materialName ] === undefined ) {
  202. this.createMaterial_( materialName );
  203. }
  204. return this.materials[ materialName ];
  205. }
  206. createMaterial_( materialName ) {
  207. // Create material
  208. const scope = this;
  209. const mat = this.materialsInfo[ materialName ];
  210. const 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. const texParams = scope.getTextureParams( value, params );
  224. const 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. if ( mapType === 'map' || mapType === 'emissiveMap' ) {
  230. map.colorSpace = SRGBColorSpace;
  231. }
  232. params[ mapType ] = map;
  233. }
  234. for ( const prop in mat ) {
  235. const value = mat[ prop ];
  236. let n;
  237. if ( value === '' ) continue;
  238. switch ( prop.toLowerCase() ) {
  239. // Ns is material specular exponent
  240. case 'kd':
  241. // Diffuse color (color under white light) using RGB values
  242. params.color = ColorManagement.toWorkingColorSpace( new Color().fromArray( value ), SRGBColorSpace );
  243. break;
  244. case 'ks':
  245. // Specular color (color when light is reflected from shiny surface) using RGB values
  246. params.specular = ColorManagement.toWorkingColorSpace( new Color().fromArray( value ), SRGBColorSpace );
  247. break;
  248. case 'ke':
  249. // Emissive using RGB values
  250. params.emissive = ColorManagement.toWorkingColorSpace( new Color().fromArray( value ), SRGBColorSpace );
  251. break;
  252. case 'map_kd':
  253. // Diffuse texture map
  254. setMapForType( 'map', value );
  255. break;
  256. case 'map_ks':
  257. // Specular map
  258. setMapForType( 'specularMap', value );
  259. break;
  260. case 'map_ke':
  261. // Emissive map
  262. setMapForType( 'emissiveMap', value );
  263. break;
  264. case 'norm':
  265. setMapForType( 'normalMap', value );
  266. break;
  267. case 'map_bump':
  268. case 'bump':
  269. // Bump texture map
  270. setMapForType( 'bumpMap', value );
  271. break;
  272. case 'map_d':
  273. // Alpha map
  274. setMapForType( 'alphaMap', value );
  275. params.transparent = true;
  276. break;
  277. case 'ns':
  278. // The specular exponent (defines the focus of the specular highlight)
  279. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  280. params.shininess = parseFloat( value );
  281. break;
  282. case 'd':
  283. n = parseFloat( value );
  284. if ( n < 1 ) {
  285. params.opacity = n;
  286. params.transparent = true;
  287. }
  288. break;
  289. case 'tr':
  290. n = parseFloat( value );
  291. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  292. if ( n > 0 ) {
  293. params.opacity = 1 - n;
  294. params.transparent = true;
  295. }
  296. break;
  297. default:
  298. break;
  299. }
  300. }
  301. this.materials[ materialName ] = new MeshPhongMaterial( params );
  302. return this.materials[ materialName ];
  303. }
  304. getTextureParams( value, matParams ) {
  305. const texParams = {
  306. scale: new Vector2( 1, 1 ),
  307. offset: new Vector2( 0, 0 )
  308. };
  309. const items = value.split( /\s+/ );
  310. let pos;
  311. pos = items.indexOf( '-bm' );
  312. if ( pos >= 0 ) {
  313. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  314. items.splice( pos, 2 );
  315. }
  316. pos = items.indexOf( '-s' );
  317. if ( pos >= 0 ) {
  318. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  319. items.splice( pos, 4 ); // we expect 3 parameters here!
  320. }
  321. pos = items.indexOf( '-o' );
  322. if ( pos >= 0 ) {
  323. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  324. items.splice( pos, 4 ); // we expect 3 parameters here!
  325. }
  326. texParams.url = items.join( ' ' ).trim();
  327. return texParams;
  328. }
  329. loadTexture( url, mapping, onLoad, onProgress, onError ) {
  330. const manager = ( this.manager !== undefined ) ? this.manager : DefaultLoadingManager;
  331. let loader = manager.getHandler( url );
  332. if ( loader === null ) {
  333. loader = new TextureLoader( manager );
  334. }
  335. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  336. const texture = loader.load( url, onLoad, onProgress, onError );
  337. if ( mapping !== undefined ) texture.mapping = mapping;
  338. return texture;
  339. }
  340. }
  341. export { MTLLoader };