MTLLoader.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. * A loader for the MTL format.
  17. *
  18. * The Material Template Library format (MTL) or .MTL File Format is a companion file format
  19. * to OBJ that describes surface shading (material) properties of objects within one or more
  20. * OBJ files.
  21. *
  22. * ```js
  23. * const loader = new MTLLoader();
  24. * const materials = await loader.loadAsync( 'models/obj/male02/male02.mtl' );
  25. *
  26. * const objLoader = new OBJLoader();
  27. * objLoader.setMaterials( materials );
  28. * ```
  29. *
  30. * @augments Loader
  31. */
  32. class MTLLoader extends Loader {
  33. constructor( manager ) {
  34. super( manager );
  35. }
  36. /**
  37. * Starts loading from the given URL and passes the loaded MTL asset
  38. * to the `onLoad()` callback.
  39. *
  40. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  41. * @param {function(MaterialCreator)} onLoad - Executed when the loading process has been finished.
  42. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  43. * @param {onErrorCallback} onError - Executed when errors occur.
  44. */
  45. load( url, onLoad, onProgress, onError ) {
  46. const scope = this;
  47. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  48. const loader = new FileLoader( this.manager );
  49. loader.setPath( this.path );
  50. loader.setRequestHeader( this.requestHeader );
  51. loader.setWithCredentials( this.withCredentials );
  52. loader.load( url, function ( text ) {
  53. try {
  54. onLoad( scope.parse( text, path ) );
  55. } catch ( e ) {
  56. if ( onError ) {
  57. onError( e );
  58. } else {
  59. console.error( e );
  60. }
  61. scope.manager.itemError( url );
  62. }
  63. }, onProgress, onError );
  64. }
  65. /**
  66. * Sets the material options.
  67. *
  68. * @param {MTLLoader~MaterialOptions} value - The material options.
  69. * @return {MTLLoader} A reference to this loader.
  70. */
  71. setMaterialOptions( value ) {
  72. this.materialOptions = value;
  73. return this;
  74. }
  75. /**
  76. * Parses the given MTL data and returns the resulting material creator.
  77. *
  78. * @param {string} text - The raw MTL data as a string.
  79. * @param {string} path - The URL base path.
  80. * @return {MaterialCreator} The material creator.
  81. */
  82. parse( text, path ) {
  83. const lines = text.split( '\n' );
  84. let info = {};
  85. const delimiter_pattern = /\s+/;
  86. const materialsInfo = {};
  87. for ( let i = 0; i < lines.length; i ++ ) {
  88. let line = lines[ i ];
  89. line = line.trim();
  90. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  91. // Blank line or comment ignore
  92. continue;
  93. }
  94. const pos = line.indexOf( ' ' );
  95. let key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  96. key = key.toLowerCase();
  97. let value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  98. value = value.trim();
  99. if ( key === 'newmtl' ) {
  100. // New material
  101. info = { name: value };
  102. materialsInfo[ value ] = info;
  103. } else {
  104. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  105. const ss = value.split( delimiter_pattern, 3 );
  106. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  107. } else {
  108. info[ key ] = value;
  109. }
  110. }
  111. }
  112. const materialCreator = new MaterialCreator( this.resourcePath || path, this.materialOptions );
  113. materialCreator.setCrossOrigin( this.crossOrigin );
  114. materialCreator.setManager( this.manager );
  115. materialCreator.setMaterials( materialsInfo );
  116. return materialCreator;
  117. }
  118. }
  119. /**
  120. * Material options of `MTLLoader`.
  121. *
  122. * @typedef {Object} MTLLoader~MaterialOptions
  123. * @property {(FrontSide|BackSide|DoubleSide)} [side=FrontSide] - Which side to apply the material.
  124. * @property {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)} [wrap=RepeatWrapping] - What type of wrapping to apply for textures.
  125. * @property {boolean} [normalizeRGB=false] - Whether RGB colors should be normalized to `0-1` from `0-255`.
  126. * @property {boolean} [ignoreZeroRGBs=false] - Ignore values of RGBs (Ka,Kd,Ks) that are all 0's.
  127. */
  128. class MaterialCreator {
  129. constructor( baseUrl = '', options = {} ) {
  130. this.baseUrl = baseUrl;
  131. this.options = options;
  132. this.materialsInfo = {};
  133. this.materials = {};
  134. this.materialsArray = [];
  135. this.nameLookup = {};
  136. this.crossOrigin = 'anonymous';
  137. this.side = ( this.options.side !== undefined ) ? this.options.side : FrontSide;
  138. this.wrap = ( this.options.wrap !== undefined ) ? this.options.wrap : RepeatWrapping;
  139. }
  140. setCrossOrigin( value ) {
  141. this.crossOrigin = value;
  142. return this;
  143. }
  144. setManager( value ) {
  145. this.manager = value;
  146. }
  147. setMaterials( materialsInfo ) {
  148. this.materialsInfo = this.convert( materialsInfo );
  149. this.materials = {};
  150. this.materialsArray = [];
  151. this.nameLookup = {};
  152. }
  153. convert( materialsInfo ) {
  154. if ( ! this.options ) return materialsInfo;
  155. const converted = {};
  156. for ( const mn in materialsInfo ) {
  157. // Convert materials info into normalized form based on options
  158. const mat = materialsInfo[ mn ];
  159. const covmat = {};
  160. converted[ mn ] = covmat;
  161. for ( const prop in mat ) {
  162. let save = true;
  163. let value = mat[ prop ];
  164. const lprop = prop.toLowerCase();
  165. switch ( lprop ) {
  166. case 'kd':
  167. case 'ka':
  168. case 'ks':
  169. // Diffuse color (color under white light) using RGB values
  170. if ( this.options && this.options.normalizeRGB ) {
  171. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  172. }
  173. if ( this.options && this.options.ignoreZeroRGBs ) {
  174. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  175. // ignore
  176. save = false;
  177. }
  178. }
  179. break;
  180. default:
  181. break;
  182. }
  183. if ( save ) {
  184. covmat[ lprop ] = value;
  185. }
  186. }
  187. }
  188. return converted;
  189. }
  190. preload() {
  191. for ( const mn in this.materialsInfo ) {
  192. this.create( mn );
  193. }
  194. }
  195. getIndex( materialName ) {
  196. return this.nameLookup[ materialName ];
  197. }
  198. getAsArray() {
  199. let index = 0;
  200. for ( const mn in this.materialsInfo ) {
  201. this.materialsArray[ index ] = this.create( mn );
  202. this.nameLookup[ mn ] = index;
  203. index ++;
  204. }
  205. return this.materialsArray;
  206. }
  207. create( materialName ) {
  208. if ( this.materials[ materialName ] === undefined ) {
  209. this.createMaterial_( materialName );
  210. }
  211. return this.materials[ materialName ];
  212. }
  213. createMaterial_( materialName ) {
  214. // Create material
  215. const scope = this;
  216. const mat = this.materialsInfo[ materialName ];
  217. const params = {
  218. name: materialName,
  219. side: this.side
  220. };
  221. function resolveURL( baseUrl, url ) {
  222. if ( typeof url !== 'string' || url === '' )
  223. return '';
  224. // Absolute URL
  225. if ( /^https?:\/\//i.test( url ) ) return url;
  226. return baseUrl + url;
  227. }
  228. function setMapForType( mapType, value ) {
  229. if ( params[ mapType ] ) return; // Keep the first encountered texture
  230. const texParams = scope.getTextureParams( value, params );
  231. const map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  232. map.repeat.copy( texParams.scale );
  233. map.offset.copy( texParams.offset );
  234. map.wrapS = scope.wrap;
  235. map.wrapT = scope.wrap;
  236. if ( mapType === 'map' || mapType === 'emissiveMap' ) {
  237. map.colorSpace = SRGBColorSpace;
  238. }
  239. params[ mapType ] = map;
  240. }
  241. for ( const prop in mat ) {
  242. const value = mat[ prop ];
  243. let n;
  244. if ( value === '' ) continue;
  245. switch ( prop.toLowerCase() ) {
  246. // Ns is material specular exponent
  247. case 'kd':
  248. // Diffuse color (color under white light) using RGB values
  249. params.color = ColorManagement.toWorkingColorSpace( new Color().fromArray( value ), SRGBColorSpace );
  250. break;
  251. case 'ks':
  252. // Specular color (color when light is reflected from shiny surface) using RGB values
  253. params.specular = ColorManagement.toWorkingColorSpace( new Color().fromArray( value ), SRGBColorSpace );
  254. break;
  255. case 'ke':
  256. // Emissive using RGB values
  257. params.emissive = ColorManagement.toWorkingColorSpace( new Color().fromArray( value ), SRGBColorSpace );
  258. break;
  259. case 'map_kd':
  260. // Diffuse texture map
  261. setMapForType( 'map', value );
  262. break;
  263. case 'map_ks':
  264. // Specular map
  265. setMapForType( 'specularMap', value );
  266. break;
  267. case 'map_ke':
  268. // Emissive map
  269. setMapForType( 'emissiveMap', value );
  270. break;
  271. case 'norm':
  272. setMapForType( 'normalMap', value );
  273. break;
  274. case 'map_bump':
  275. case 'bump':
  276. // Bump texture map
  277. setMapForType( 'bumpMap', value );
  278. break;
  279. case 'disp':
  280. // Displacement texture map
  281. setMapForType( 'displacementMap', value );
  282. break;
  283. case 'map_d':
  284. // Alpha map
  285. setMapForType( 'alphaMap', value );
  286. params.transparent = true;
  287. break;
  288. case 'ns':
  289. // The specular exponent (defines the focus of the specular highlight)
  290. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  291. params.shininess = parseFloat( value );
  292. break;
  293. case 'd':
  294. n = parseFloat( value );
  295. if ( n < 1 ) {
  296. params.opacity = n;
  297. params.transparent = true;
  298. }
  299. break;
  300. case 'tr':
  301. n = parseFloat( value );
  302. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  303. if ( n > 0 ) {
  304. params.opacity = 1 - n;
  305. params.transparent = true;
  306. }
  307. break;
  308. default:
  309. break;
  310. }
  311. }
  312. this.materials[ materialName ] = new MeshPhongMaterial( params );
  313. return this.materials[ materialName ];
  314. }
  315. getTextureParams( value, matParams ) {
  316. const texParams = {
  317. scale: new Vector2( 1, 1 ),
  318. offset: new Vector2( 0, 0 )
  319. };
  320. const items = value.split( /\s+/ );
  321. let pos;
  322. pos = items.indexOf( '-bm' );
  323. if ( pos >= 0 ) {
  324. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  325. items.splice( pos, 2 );
  326. }
  327. pos = items.indexOf( '-mm' );
  328. if ( pos >= 0 ) {
  329. matParams.displacementBias = parseFloat( items[ pos + 1 ] );
  330. matParams.displacementScale = parseFloat( items[ pos + 2 ] );
  331. items.splice( pos, 3 );
  332. }
  333. pos = items.indexOf( '-s' );
  334. if ( pos >= 0 ) {
  335. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  336. items.splice( pos, 4 ); // we expect 3 parameters here!
  337. }
  338. pos = items.indexOf( '-o' );
  339. if ( pos >= 0 ) {
  340. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  341. items.splice( pos, 4 ); // we expect 3 parameters here!
  342. }
  343. texParams.url = items.join( ' ' ).trim();
  344. return texParams;
  345. }
  346. loadTexture( url, mapping, onLoad, onProgress, onError ) {
  347. const manager = ( this.manager !== undefined ) ? this.manager : DefaultLoadingManager;
  348. let loader = manager.getHandler( url );
  349. if ( loader === null ) {
  350. loader = new TextureLoader( manager );
  351. }
  352. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  353. const texture = loader.load( url, onLoad, onProgress, onError );
  354. if ( mapping !== undefined ) texture.mapping = mapping;
  355. return texture;
  356. }
  357. }
  358. export { MTLLoader };
粤ICP备19079148号