MTLLoader.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. params[ mapType ] = map;
  217. }
  218. for ( const prop in mat ) {
  219. const value = mat[ prop ];
  220. let n;
  221. if ( value === '' ) continue;
  222. switch ( prop.toLowerCase() ) {
  223. // Ns is material specular exponent
  224. case 'kd':
  225. // Diffuse color (color under white light) using RGB values
  226. params.color = new THREE.Color().fromArray( value );
  227. break;
  228. case 'ks':
  229. // Specular color (color when light is reflected from shiny surface) using RGB values
  230. params.specular = new THREE.Color().fromArray( value );
  231. break;
  232. case 'ke':
  233. // Emissive using RGB values
  234. params.emissive = new THREE.Color().fromArray( value );
  235. break;
  236. case 'map_kd':
  237. // Diffuse texture map
  238. setMapForType( 'map', value );
  239. break;
  240. case 'map_ks':
  241. // Specular map
  242. setMapForType( 'specularMap', value );
  243. break;
  244. case 'map_ke':
  245. // Emissive map
  246. setMapForType( 'emissiveMap', value );
  247. break;
  248. case 'norm':
  249. setMapForType( 'normalMap', value );
  250. break;
  251. case 'map_bump':
  252. case 'bump':
  253. // Bump texture map
  254. setMapForType( 'bumpMap', value );
  255. break;
  256. case 'map_d':
  257. // Alpha map
  258. setMapForType( 'alphaMap', value );
  259. params.transparent = true;
  260. break;
  261. case 'ns':
  262. // The specular exponent (defines the focus of the specular highlight)
  263. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  264. params.shininess = parseFloat( value );
  265. break;
  266. case 'd':
  267. n = parseFloat( value );
  268. if ( n < 1 ) {
  269. params.opacity = n;
  270. params.transparent = true;
  271. }
  272. break;
  273. case 'tr':
  274. n = parseFloat( value );
  275. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  276. if ( n > 0 ) {
  277. params.opacity = 1 - n;
  278. params.transparent = true;
  279. }
  280. break;
  281. default:
  282. break;
  283. }
  284. }
  285. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  286. return this.materials[ materialName ];
  287. }
  288. getTextureParams( value, matParams ) {
  289. const texParams = {
  290. scale: new THREE.Vector2( 1, 1 ),
  291. offset: new THREE.Vector2( 0, 0 )
  292. };
  293. const items = value.split( /\s+/ );
  294. let pos;
  295. pos = items.indexOf( '-bm' );
  296. if ( pos >= 0 ) {
  297. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  298. items.splice( pos, 2 );
  299. }
  300. pos = items.indexOf( '-s' );
  301. if ( pos >= 0 ) {
  302. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  303. items.splice( pos, 4 ); // we expect 3 parameters here!
  304. }
  305. pos = items.indexOf( '-o' );
  306. if ( pos >= 0 ) {
  307. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  308. items.splice( pos, 4 ); // we expect 3 parameters here!
  309. }
  310. texParams.url = items.join( ' ' ).trim();
  311. return texParams;
  312. }
  313. loadTexture( url, mapping, onLoad, onProgress, onError ) {
  314. const manager = this.manager !== undefined ? this.manager : THREE.DefaultLoadingManager;
  315. let loader = manager.getHandler( url );
  316. if ( loader === null ) {
  317. loader = new THREE.TextureLoader( manager );
  318. }
  319. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  320. const texture = loader.load( url, onLoad, onProgress, onError );
  321. if ( mapping !== undefined ) texture.mapping = mapping;
  322. return texture;
  323. }
  324. }
  325. THREE.MTLLoader = MTLLoader;
  326. } )();