MTLLoader.js 10 KB

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