MTLLoader.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /**
  2. * Loads a Wavefront .mtl file specifying materials
  3. *
  4. * @author angelxuanchang
  5. */
  6. THREE.MTLLoader = function( baseUrl, options, crossOrigin ) {
  7. this.baseUrl = baseUrl;
  8. this.options = options;
  9. this.crossOrigin = crossOrigin;
  10. };
  11. THREE.MTLLoader.prototype = {
  12. constructor: THREE.MTLLoader,
  13. load: function ( url, onLoad, onProgress, onError ) {
  14. var scope = this;
  15. var loader = new THREE.XHRLoader();
  16. loader.setCrossOrigin( this.crossOrigin );
  17. loader.load( url, function ( text ) {
  18. onLoad( scope.parse( text ) );
  19. }, onProgress, onError );
  20. },
  21. /**
  22. * Parses loaded MTL file
  23. * @param text - Content of MTL file
  24. * @return {THREE.MTLLoader.MaterialCreator}
  25. */
  26. parse: function ( text ) {
  27. var lines = text.split( "\n" );
  28. var info = {};
  29. var delimiter_pattern = /\s+/;
  30. var materialsInfo = {};
  31. for ( var i = 0; i < lines.length; i ++ ) {
  32. var line = lines[ i ];
  33. line = line.trim();
  34. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  35. // Blank line or comment ignore
  36. continue;
  37. }
  38. var pos = line.indexOf( ' ' );
  39. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  40. key = key.toLowerCase();
  41. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : "";
  42. value = value.trim();
  43. if ( key === "newmtl" ) {
  44. // New material
  45. info = { name: value };
  46. materialsInfo[ value ] = info;
  47. } else if ( info ) {
  48. if ( key === "ka" || key === "kd" || key === "ks" ) {
  49. var ss = value.split( delimiter_pattern, 3 );
  50. info[ key ] = [ parseFloat( ss[0] ), parseFloat( ss[1] ), parseFloat( ss[2] ) ];
  51. } else {
  52. info[ key ] = value;
  53. }
  54. }
  55. }
  56. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.baseUrl, this.options );
  57. materialCreator.crossOrigin = this.crossOrigin
  58. materialCreator.setMaterials( materialsInfo );
  59. return materialCreator;
  60. }
  61. };
  62. /**
  63. * Create a new THREE-MTLLoader.MaterialCreator
  64. * @param baseUrl - Url relative to which textures are loaded
  65. * @param options - Set of options on how to construct the materials
  66. * side: Which side to apply the material
  67. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  68. * wrap: What type of wrapping to apply for textures
  69. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  70. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  71. * Default: false, assumed to be already normalized
  72. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  73. * Default: false
  74. * invertTransparency: If transparency need to be inverted (inversion is needed if d = 0 is fully opaque)
  75. * Default: false (d = 1 is fully opaque)
  76. * @constructor
  77. */
  78. THREE.MTLLoader.MaterialCreator = function( baseUrl, options ) {
  79. this.baseUrl = baseUrl;
  80. this.options = options;
  81. this.materialsInfo = {};
  82. this.materials = {};
  83. this.materialsArray = [];
  84. this.nameLookup = {};
  85. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  86. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  87. };
  88. THREE.MTLLoader.MaterialCreator.prototype = {
  89. constructor: THREE.MTLLoader.MaterialCreator,
  90. setMaterials: function( materialsInfo ) {
  91. this.materialsInfo = this.convert( materialsInfo );
  92. this.materials = {};
  93. this.materialsArray = [];
  94. this.nameLookup = {};
  95. },
  96. convert: function( materialsInfo ) {
  97. if ( !this.options ) return materialsInfo;
  98. var converted = {};
  99. for ( var mn in materialsInfo ) {
  100. // Convert materials info into normalized form based on options
  101. var mat = materialsInfo[ mn ];
  102. var covmat = {};
  103. converted[ mn ] = covmat;
  104. for ( var prop in mat ) {
  105. var save = true;
  106. var value = mat[ prop ];
  107. var lprop = prop.toLowerCase();
  108. switch ( lprop ) {
  109. case 'kd':
  110. case 'ka':
  111. case 'ks':
  112. // Diffuse color (color under white light) using RGB values
  113. if ( this.options && this.options.normalizeRGB ) {
  114. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  115. }
  116. if ( this.options && this.options.ignoreZeroRGBs ) {
  117. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 1 ] === 0 ) {
  118. // ignore
  119. save = false;
  120. }
  121. }
  122. break;
  123. case 'd':
  124. // According to MTL format (http://paulbourke.net/dataformats/mtl/):
  125. // d is dissolve for current material
  126. // factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent)
  127. if ( this.options && this.options.invertTransparency ) {
  128. value = 1 - value;
  129. }
  130. break;
  131. default:
  132. break;
  133. }
  134. if ( save ) {
  135. covmat[ lprop ] = value;
  136. }
  137. }
  138. }
  139. return converted;
  140. },
  141. preload: function () {
  142. for ( var mn in this.materialsInfo ) {
  143. this.create( mn );
  144. }
  145. },
  146. getIndex: function( materialName ) {
  147. return this.nameLookup[ materialName ];
  148. },
  149. getAsArray: function() {
  150. var index = 0;
  151. for ( var mn in this.materialsInfo ) {
  152. this.materialsArray[ index ] = this.create( mn );
  153. this.nameLookup[ mn ] = index;
  154. index ++;
  155. }
  156. return this.materialsArray;
  157. },
  158. create: function ( materialName ) {
  159. if ( this.materials[ materialName ] === undefined ) {
  160. this.createMaterial_( materialName );
  161. }
  162. return this.materials[ materialName ];
  163. },
  164. createMaterial_: function ( materialName ) {
  165. // Create material
  166. var mat = this.materialsInfo[ materialName ];
  167. var params = {
  168. name: materialName,
  169. side: this.side
  170. };
  171. for ( var prop in mat ) {
  172. var value = mat[ prop ];
  173. switch ( prop.toLowerCase() ) {
  174. // Ns is material specular exponent
  175. case 'kd':
  176. // Diffuse color (color under white light) using RGB values
  177. params[ 'diffuse' ] = new THREE.Color().fromArray( value );
  178. break;
  179. case 'ka':
  180. // Ambient color (color under shadow) using RGB values
  181. break;
  182. case 'ks':
  183. // Specular color (color when light is reflected from shiny surface) using RGB values
  184. params[ 'specular' ] = new THREE.Color().fromArray( value );
  185. break;
  186. case 'map_kd':
  187. // Diffuse texture map
  188. params[ 'map' ] = this.loadTexture( this.baseUrl + value );
  189. params[ 'map' ].wrapS = this.wrap;
  190. params[ 'map' ].wrapT = this.wrap;
  191. break;
  192. case 'ns':
  193. // The specular exponent (defines the focus of the specular highlight)
  194. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  195. params['shininess'] = value;
  196. break;
  197. case 'd':
  198. // According to MTL format (http://paulbourke.net/dataformats/mtl/):
  199. // d is dissolve for current material
  200. // factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent)
  201. if ( value < 1 ) {
  202. params['transparent'] = true;
  203. params['opacity'] = value;
  204. }
  205. break;
  206. case 'map_bump':
  207. case 'bump':
  208. // Bump texture map
  209. if ( params[ 'bumpMap' ] ) break; // Avoid loading twice.
  210. params[ 'bumpMap' ] = this.loadTexture( this.baseUrl + value );
  211. params[ 'bumpMap' ].wrapS = this.wrap;
  212. params[ 'bumpMap' ].wrapT = this.wrap;
  213. break;
  214. default:
  215. break;
  216. }
  217. }
  218. if ( params[ 'diffuse' ] ) {
  219. params[ 'color' ] = params[ 'diffuse' ];
  220. }
  221. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  222. return this.materials[ materialName ];
  223. },
  224. loadTexture: function ( url, mapping, onLoad, onError ) {
  225. var texture;
  226. var loader = THREE.Loader.Handlers.get( url );
  227. if ( loader !== null ) {
  228. texture = loader.load( url, onLoad );
  229. } else {
  230. texture = new THREE.Texture();
  231. loader = new THREE.ImageLoader();
  232. loader.crossOrigin = this.crossOrigin;
  233. loader.load( url, function ( image ) {
  234. texture.image = THREE.MTLLoader.ensurePowerOfTwo_( image );
  235. texture.needsUpdate = true;
  236. if ( onLoad ) onLoad( texture );
  237. } );
  238. }
  239. if ( mapping !== undefined ) texture.mapping = mapping;
  240. return texture;
  241. }
  242. };
  243. THREE.MTLLoader.ensurePowerOfTwo_ = function ( image ) {
  244. if ( ! THREE.Math.isPowerOfTwo( image.width ) || ! THREE.Math.isPowerOfTwo( image.height ) ) {
  245. var canvas = document.createElement( "canvas" );
  246. canvas.width = THREE.MTLLoader.nextHighestPowerOfTwo_( image.width );
  247. canvas.height = THREE.MTLLoader.nextHighestPowerOfTwo_( image.height );
  248. var ctx = canvas.getContext("2d");
  249. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  250. return canvas;
  251. }
  252. return image;
  253. };
  254. THREE.MTLLoader.nextHighestPowerOfTwo_ = function( x ) {
  255. -- x;
  256. for ( var i = 1; i < 32; i <<= 1 ) {
  257. x = x | x >> i;
  258. }
  259. return x + 1;
  260. };
  261. THREE.EventDispatcher.prototype.apply( THREE.MTLLoader.prototype );