MTLLoader.js 10 KB

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