MTLLoader.js 9.8 KB

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