OBJLoader2.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  1. /**
  2. * @author Kai Salmen / https://kaisalmen.de
  3. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  4. */
  5. 'use strict';
  6. if ( THREE.OBJLoader2 === undefined ) { THREE.OBJLoader2 = {} }
  7. /**
  8. * Use this class to load OBJ data from files or to parse OBJ data from an arraybuffer
  9. * @class
  10. *
  11. * @param {THREE.DefaultLoadingManager} [manager] The loadingManager for the loader to use. Default is {@link THREE.DefaultLoadingManager}
  12. */
  13. THREE.OBJLoader2 = (function () {
  14. var OBJLOADER2_VERSION = '2.0.0-dev';
  15. var Validator = THREE.LoaderSupport.Validator;
  16. var Commons = THREE.LoaderSupport.Commons;
  17. OBJLoader2.prototype = Object.create( THREE.LoaderSupport.Commons.prototype );
  18. OBJLoader2.prototype.constructor = OBJLoader2;
  19. function OBJLoader2( manager ) {
  20. THREE.LoaderSupport.Commons.call( this, manager );
  21. console.log( "Using THREE.OBJLoader2 version: " + OBJLOADER2_VERSION );
  22. this.materialPerSmoothingGroup = false;
  23. this.fileLoader = Validator.verifyInput( this.fileLoader, new THREE.FileLoader( this.manager ) );
  24. this.workerSupport = null;
  25. this.terminateWorkerOnLoad = true;
  26. };
  27. /**
  28. * Tells whether a material shall be created per smoothing group
  29. * @memberOf THREE.OBJLoader2
  30. *
  31. * @param {boolean} materialPerSmoothingGroup=false Default is false
  32. */
  33. OBJLoader2.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
  34. this.materialPerSmoothingGroup = materialPerSmoothingGroup === true;
  35. };
  36. /**
  37. * Sets debug mode for the parser
  38. * @memberOf THREE.OBJLoader2
  39. *
  40. * @param {boolean} enabled
  41. */
  42. OBJLoader2.prototype.setDebug = function ( enabled ) {
  43. THREE.LoaderSupport.Commons.prototype.setDebug.call( this, enabled );
  44. };
  45. /**
  46. * Use this convenient method to load an OBJ file at the given URL. Per default the fileLoader uses an arraybuffer
  47. * @memberOf THREE.OBJLoader2
  48. *
  49. * @param {string} url URL of the file to load
  50. * @param {callback} onLoad Called after loading was successfully completed
  51. * @param {callback} onProgress Called to report progress of loading. The argument will be the XMLHttpRequest instance, which contains {integer total} and {integer loaded} bytes.
  52. * @param {callback} onError Called after an error occurred during loading
  53. * @param {callback} onMeshAlter Called after a new mesh raw data becomes available
  54. * @param {boolean} useAsync Set this to use async loading
  55. */
  56. OBJLoader2.prototype.load = function ( url, onLoad, onProgress, onError, onMeshAlter, useAsync ) {
  57. var scope = this;
  58. if ( ! Validator.isValid( onProgress ) ) {
  59. var refPercentComplete = 0;
  60. var percentComplete = 0;
  61. onProgress = function ( event ) {
  62. if ( ! event.lengthComputable ) return;
  63. percentComplete = Math.round( event.loaded / event.total * 100 );
  64. if ( percentComplete > refPercentComplete ) {
  65. refPercentComplete = percentComplete;
  66. var output = 'Download of "' + url + '": ' + percentComplete + '%';
  67. console.log( output );
  68. scope.onProgress( output );
  69. }
  70. };
  71. }
  72. if ( ! Validator.isValid( onError ) ) {
  73. onError = function ( event ) {
  74. var output = 'Error occurred while downloading "' + url + '"';
  75. console.error( output + ': ' + event );
  76. scope.onProgress( output );
  77. };
  78. }
  79. this.fileLoader.setPath( this.path );
  80. this.fileLoader.setResponseType( 'arraybuffer' );
  81. this.fileLoader.load( url, function ( content ) {
  82. if ( useAsync ) {
  83. scope.parseAsync( content, onLoad );
  84. } else {
  85. scope._setCallbacks( null, onMeshAlter, null );
  86. onLoad( scope.parse( content ), scope.modelName, scope.instanceNo );
  87. }
  88. }, onProgress, onError );
  89. };
  90. /**
  91. * Run the loader according the provided instructions.
  92. * @memberOf THREE.OBJLoader2
  93. *
  94. * @param {THREE.LoaderSupport.PrepData} prepData All parameters and resources required for execution
  95. * @param {THREE.LoaderSupport.WorkerSupport} [workerSupportExternal] Use pre-existing WorkerSupport
  96. */
  97. OBJLoader2.prototype.run = function ( prepData, workerSupportExternal ) {
  98. this._applyPrepData( prepData );
  99. var available = this._checkFiles( prepData.resources );
  100. if ( Validator.isValid( workerSupportExternal ) ) {
  101. this.terminateWorkerOnLoad = false;
  102. this.workerSupport = workerSupportExternal;
  103. } else {
  104. this.terminateWorkerOnLoad = true;
  105. }
  106. var scope = this;
  107. var onMaterialsLoaded = function ( materials ) {
  108. scope.builder.setMaterials( materials );
  109. if ( Validator.isValid( available.obj.content ) ) {
  110. if ( prepData.useAsync ) {
  111. scope.parseAsync( available.obj.content, scope.callbacks.onLoad );
  112. } else {
  113. scope.parse( available.obj.content );
  114. }
  115. } else {
  116. scope.setPath( available.obj.path );
  117. scope.load( available.obj.name, scope.callbacks.onLoad, null, null, scope.callbacks.onMeshAlter, prepData.useAsync );
  118. }
  119. };
  120. this._loadMtl( available.mtl, onMaterialsLoaded, prepData.crossOrigin );
  121. };
  122. OBJLoader2.prototype._applyPrepData = function ( prepData ) {
  123. THREE.LoaderSupport.Commons.prototype._applyPrepData.call( this, prepData );
  124. if ( Validator.isValid( prepData ) ) {
  125. this.setMaterialPerSmoothingGroup( prepData.materialPerSmoothingGroup );
  126. }
  127. };
  128. /**
  129. * Parses OBJ content synchronously.
  130. * @memberOf THREE.OBJLoader2
  131. *
  132. * @param content
  133. */
  134. OBJLoader2.prototype.parse = function ( content ) {
  135. console.time( 'OBJLoader2 parse: ' + this.modelName );
  136. var parser = new Parser();
  137. parser.setMaterialPerSmoothingGroup( this.materialPerSmoothingGroup );
  138. parser.setUseIndices( this.useIndices );
  139. parser.setDisregardNormals( this.disregardNormals );
  140. parser.setMaterialNames( this.builder.materialNames );
  141. parser.setDebug( this.debug );
  142. var scope = this;
  143. var onMeshLoaded = function ( payload ) {
  144. var meshes = scope.builder.buildMeshes( payload );
  145. var mesh;
  146. for ( var i in meshes ) {
  147. mesh = meshes[ i ];
  148. scope.loaderRootNode.add( mesh );
  149. }
  150. };
  151. parser.setCallbackBuilder( onMeshLoaded );
  152. var onProgressScoped = function ( message ) {
  153. scope.onProgress( message );
  154. };
  155. parser.setCallbackProgress( onProgressScoped );
  156. if ( content instanceof ArrayBuffer || content instanceof Uint8Array ) {
  157. console.log( 'Parsing arrayBuffer...' );
  158. parser.parse( content );
  159. } else if ( typeof( content ) === 'string' || content instanceof String ) {
  160. console.log( 'Parsing text...' );
  161. parser.parseText( content );
  162. } else {
  163. throw 'Provided content was neither of type String nor Uint8Array! Aborting...';
  164. }
  165. console.timeEnd( 'OBJLoader2 parse: ' + this.modelName );
  166. return this.loaderRootNode;
  167. };
  168. /**
  169. * Parses OBJ content asynchronously.
  170. * @memberOf THREE.OBJLoader2
  171. *
  172. * @param {arraybuffer} content
  173. * @param {callback} onLoad
  174. */
  175. OBJLoader2.prototype.parseAsync = function ( content, onLoad ) {
  176. console.time( 'OBJLoader2 parseAsync: ' + this.modelName);
  177. var scope = this;
  178. var scopedOnLoad = function ( message ) {
  179. onLoad( scope.loaderRootNode, scope.modelName, scope.instanceNo, message );
  180. if ( scope.terminateWorkerOnLoad ) scope.workerSupport.terminateWorker();
  181. console.timeEnd( 'OBJLoader2 parseAsync: ' + scope.modelName );
  182. };
  183. var scopedOnMeshLoaded = function ( payload ) {
  184. var meshes = scope.builder.buildMeshes( payload );
  185. var mesh;
  186. for ( var i in meshes ) {
  187. mesh = meshes[ i ];
  188. scope.loaderRootNode.add( mesh );
  189. }
  190. };
  191. this.workerSupport = Validator.verifyInput( this.workerSupport, new THREE.LoaderSupport.WorkerSupport() );
  192. var buildCode = function ( funcBuildObject, funcBuildSingelton ) {
  193. var workerCode = '';
  194. workerCode += '/**\n';
  195. workerCode += ' * This code was constructed by OBJLoader2 buildWorkerCode.\n';
  196. workerCode += ' */\n\n';
  197. workerCode += funcBuildSingelton( 'Commons', 'Commons', Commons );
  198. workerCode += funcBuildObject( 'Consts', Consts );
  199. workerCode += funcBuildObject( 'Validator', Validator );
  200. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  201. workerCode += funcBuildSingelton( 'RawObject', 'RawObject', RawObject );
  202. workerCode += funcBuildSingelton( 'RawObjectDescription', 'RawObjectDescription', RawObjectDescription );
  203. return workerCode;
  204. };
  205. this.workerSupport.validate( buildCode, false );
  206. this.workerSupport.setCallbacks( scopedOnMeshLoaded, scopedOnLoad );
  207. this.workerSupport.run(
  208. {
  209. cmd: 'run',
  210. params: {
  211. debug: this.debug,
  212. materialPerSmoothingGroup: this.materialPerSmoothingGroup,
  213. useIndices: this.useIndices,
  214. disregardNormals: this.disregardNormals
  215. },
  216. materials: {
  217. materialNames: this.builder.materialNames
  218. },
  219. buffers: {
  220. input: content
  221. }
  222. },
  223. [ content.buffer ]
  224. );
  225. };
  226. /**
  227. * Constants used by THREE.OBJLoader2
  228. */
  229. var Consts = {
  230. CODE_LF: 10,
  231. CODE_CR: 13,
  232. CODE_SPACE: 32,
  233. CODE_SLASH: 47,
  234. STRING_LF: '\n',
  235. STRING_CR: '\r',
  236. STRING_SPACE: ' ',
  237. STRING_SLASH: '/',
  238. LINE_F: 'f',
  239. LINE_G: 'g',
  240. LINE_L: 'l',
  241. LINE_O: 'o',
  242. LINE_S: 's',
  243. LINE_V: 'v',
  244. LINE_VT: 'vt',
  245. LINE_VN: 'vn',
  246. LINE_MTLLIB: 'mtllib',
  247. LINE_USEMTL: 'usemtl'
  248. };
  249. /**
  250. * Parse OBJ data either from ArrayBuffer or string
  251. * @class
  252. */
  253. var Parser = (function () {
  254. function Parser() {
  255. this.callbackProgress = null;
  256. this.callbackBuilder = null;
  257. this.materialNames = [];
  258. this.debug = false;
  259. this.rawObject = null;
  260. this.materialPerSmoothingGroup = false;
  261. this.useIndices = false;
  262. this.disregardNormals = false;
  263. this.inputObjectCount = 1;
  264. this.outputObjectCount = 1;
  265. this.counts = {
  266. vertices: 0,
  267. faces: 0,
  268. doubleIndicesCount: 0
  269. };
  270. };
  271. Parser.prototype.setDebug = function ( debug ) {
  272. if ( debug === true || debug === false ) this.debug = debug;
  273. };
  274. Parser.prototype.configure = function () {
  275. this.rawObject = new RawObject( this.materialPerSmoothingGroup, this.useIndices, this.disregardNormals );
  276. var matNames = ( this.materialNames.length > 0 ) ? '\n\tmaterialNames:\n\t\t- ' + this.materialNames.join( '\n\t\t- ' ) : '\n\tmaterialNames: None';
  277. var printConfig = 'OBJLoader2.Parser configuration:'
  278. + '\n\tdebug: ' + this.debug
  279. + matNames
  280. + '\n\tmaterialPerSmoothingGroup: ' + this.materialPerSmoothingGroup
  281. + '\n\tuseIndices: ' + this.useIndices
  282. + '\n\tdisregardNormals: ' +this.disregardNormals;
  283. console.log( printConfig );
  284. };
  285. Parser.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
  286. this.materialPerSmoothingGroup = materialPerSmoothingGroup;
  287. };
  288. Parser.prototype.setUseIndices = function ( useIndices ) {
  289. this.useIndices = useIndices;
  290. };
  291. Parser.prototype.setDisregardNormals = function ( disregardNormals ) {
  292. this.disregardNormals = disregardNormals;
  293. };
  294. Parser.prototype.setMaterialNames = function ( materialNames ) {
  295. this.materialNames = Validator.verifyInput( materialNames, this.materialNames );
  296. this.materialNames = Validator.verifyInput( this.materialNames, [] );
  297. };
  298. Parser.prototype.setCallbackBuilder = function ( callbackBuilder ) {
  299. this.callbackBuilder = callbackBuilder;
  300. if ( ! Validator.isValid( this.callbackBuilder ) ) throw 'Unable to run as no "builder" callback is set.';
  301. };
  302. Parser.prototype.setCallbackProgress = function ( callbackProgress ) {
  303. this.callbackProgress = callbackProgress;
  304. };
  305. /**
  306. * Parse the provided arraybuffer
  307. * @memberOf Parser
  308. *
  309. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  310. */
  311. Parser.prototype.parse = function ( arrayBuffer ) {
  312. console.time( 'OBJLoader2.Parser.parse' );
  313. this.configure();
  314. var arrayBufferView = new Uint8Array( arrayBuffer );
  315. var length = arrayBufferView.byteLength;
  316. var buffer = new Array( 128 );
  317. var bufferPointer = 0;
  318. var slashesCount = 0;
  319. var reachedFaces = false;
  320. var code;
  321. var word = '';
  322. for ( var i = 0; i < length; i++ ) {
  323. code = arrayBufferView[ i ];
  324. switch ( code ) {
  325. case Consts.CODE_SPACE:
  326. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  327. word = '';
  328. break;
  329. case Consts.CODE_SLASH:
  330. slashesCount++;
  331. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  332. word = '';
  333. break;
  334. case Consts.CODE_LF:
  335. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  336. word = '';
  337. reachedFaces = this.processLine( buffer, bufferPointer, slashesCount, reachedFaces );
  338. bufferPointer = 0;
  339. slashesCount = 0;
  340. break;
  341. case Consts.CODE_CR:
  342. break;
  343. default:
  344. word += String.fromCharCode( code );
  345. break;
  346. }
  347. }
  348. this.finalize();
  349. console.timeEnd( 'OBJLoader2.Parser.parse' );
  350. };
  351. /**
  352. * Parse the provided text
  353. * @memberOf Parser
  354. *
  355. * @param {string} text OBJ data as string
  356. */
  357. Parser.prototype.parseText = function ( text ) {
  358. console.time( 'OBJLoader2.Parser.parseText' );
  359. this.configure();
  360. var length = text.length;
  361. var buffer = new Array( 128 );
  362. var bufferPointer = 0;
  363. var slashesCount = 0;
  364. var reachedFaces = false;
  365. var char;
  366. var word = '';
  367. for ( var i = 0; i < length; i++ ) {
  368. char = text[ i ];
  369. switch ( char ) {
  370. case Consts.STRING_SPACE:
  371. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  372. word = '';
  373. break;
  374. case Consts.STRING_SLASH:
  375. slashesCount++;
  376. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  377. word = '';
  378. break;
  379. case Consts.STRING_LF:
  380. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  381. word = '';
  382. reachedFaces = this.processLine( buffer, bufferPointer, slashesCount, reachedFaces );
  383. bufferPointer = 0;
  384. slashesCount = 0;
  385. break;
  386. case Consts.STRING_CR:
  387. break;
  388. default:
  389. word += char;
  390. }
  391. }
  392. this.finalize();
  393. console.timeEnd( 'OBJLoader2.Parser.parseText' );
  394. };
  395. Parser.prototype.processLine = function ( buffer, bufferPointer, slashesCount, reachedFaces ) {
  396. if ( bufferPointer < 1 ) return reachedFaces;
  397. var bufferLength = bufferPointer - 1;
  398. var concatBuffer;
  399. switch ( buffer[ 0 ] ) {
  400. case Consts.LINE_V:
  401. // object complete instance required if reached faces already (= reached next block of v)
  402. if ( reachedFaces ) {
  403. if ( this.rawObject.colors.length > 0 && this.rawObject.colors.length !== this.rawObject.vertices.length ) {
  404. throw 'Vertex Colors were detected, but vertex count and color count do not match!';
  405. }
  406. this.processCompletedObject( null, this.rawObject.groupName );
  407. reachedFaces = false;
  408. }
  409. if ( bufferLength === 3 ) {
  410. this.rawObject.pushVertex( buffer )
  411. } else {
  412. this.rawObject.pushVertexAndVertextColors( buffer );
  413. }
  414. break;
  415. case Consts.LINE_VT:
  416. this.rawObject.pushUv( buffer );
  417. break;
  418. case Consts.LINE_VN:
  419. this.rawObject.pushNormal( buffer );
  420. break;
  421. case Consts.LINE_F:
  422. reachedFaces = true;
  423. this.rawObject.processFaces( buffer, bufferPointer, slashesCount );
  424. break;
  425. case Consts.LINE_L:
  426. if ( bufferLength === slashesCount * 2 ) {
  427. this.rawObject.buildLineVvt( buffer );
  428. } else {
  429. this.rawObject.buildLineV( buffer );
  430. }
  431. break;
  432. case Consts.LINE_S:
  433. this.rawObject.pushSmoothingGroup( buffer[ 1 ] );
  434. this.flushStringBuffer( buffer, bufferPointer );
  435. break;
  436. case Consts.LINE_G:
  437. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  438. this.processCompletedGroup( concatBuffer );
  439. this.flushStringBuffer( buffer, bufferPointer );
  440. break;
  441. case Consts.LINE_O:
  442. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  443. if ( this.rawObject.vertices.length > 0 ) {
  444. this.processCompletedObject( concatBuffer, null );
  445. reachedFaces = false;
  446. } else {
  447. this.rawObject.pushObject( concatBuffer );
  448. }
  449. this.flushStringBuffer( buffer, bufferPointer );
  450. break;
  451. case Consts.LINE_MTLLIB:
  452. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  453. this.rawObject.pushMtllib( concatBuffer );
  454. this.flushStringBuffer( buffer, bufferPointer );
  455. break;
  456. case Consts.LINE_USEMTL:
  457. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  458. this.rawObject.pushUsemtl( concatBuffer );
  459. this.flushStringBuffer( buffer, bufferPointer );
  460. break;
  461. default:
  462. break;
  463. }
  464. return reachedFaces;
  465. };
  466. Parser.prototype.flushStringBuffer = function ( buffer, bufferLength ) {
  467. for ( var i = 0; i < bufferLength; i++ ) {
  468. buffer[ i ] = '';
  469. }
  470. };
  471. Parser.prototype.processCompletedObject = function ( objectName, groupName ) {
  472. var result = this.rawObject.finalize( this.debug );
  473. if ( Validator.isValid( result ) ) {
  474. this.inputObjectCount++;
  475. if ( this.debug ) this.rawObject.createReport( this.inputObjectCount, true );
  476. var message = this.buildMesh( result, this.inputObjectCount );
  477. this.onProgress( message );
  478. }
  479. this.rawObject = this.rawObject.newInstanceFromObject( objectName, groupName );
  480. };
  481. Parser.prototype.processCompletedGroup = function ( groupName ) {
  482. var result = this.rawObject.finalize();
  483. if ( Validator.isValid( result ) ) {
  484. this.inputObjectCount++;
  485. if ( this.debug ) this.rawObject.createReport( this.inputObjectCount, true );
  486. var message = this.buildMesh( result, this.inputObjectCount );
  487. this.onProgress( message );
  488. this.rawObject = this.rawObject.newInstanceFromGroup( groupName );
  489. } else {
  490. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  491. this.rawObject.pushGroup( groupName );
  492. }
  493. };
  494. Parser.prototype.finalize = function () {
  495. console.log( 'Global output object count: ' + this.outputObjectCount );
  496. var result = Validator.isValid( this.rawObject ) ? this.rawObject.finalize() : null;
  497. if ( Validator.isValid( result ) ) {
  498. this.inputObjectCount++;
  499. if ( this.debug ) this.rawObject.createReport( this.inputObjectCount, true );
  500. var message = this.buildMesh( result, this.inputObjectCount );
  501. console.log(
  502. 'Overall counts: ' +
  503. '\n\tVertices: ' + this.counts.vertices,
  504. '\n\tFaces: ' + this.counts.faces,
  505. '\n\tMultiple definitions: ' + this.counts.doubleIndicesCount
  506. );
  507. this.onProgress( message );
  508. }
  509. };
  510. Parser.prototype.onProgress = function ( text ) {
  511. if ( Validator.isValid( text ) && Validator.isValid( this.callbackProgress) ) this.callbackProgress( text );
  512. };
  513. /**
  514. * RawObjectDescriptions are transformed to too intermediate format that is forwarded to the Builder.
  515. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  516. *
  517. * @param result
  518. */
  519. Parser.prototype.buildMesh = function ( result ) {
  520. var rawObjectDescriptions = result.rawObjectDescriptions;
  521. var vertexFA = new Float32Array( result.absoluteVertexCount );
  522. this.counts.vertices += result.absoluteVertexCount / 3;
  523. this.counts.faces += result.faceCount;
  524. this.counts.doubleIndicesCount += result.doubleIndicesCount;
  525. var indexUA = ( result.absoluteIndexCount > 0 ) ? new Uint32Array( result.absoluteIndexCount ) : null;
  526. var colorFA = ( result.absoluteColorCount > 0 ) ? new Float32Array( result.absoluteColorCount ) : null;
  527. var normalFA = ( result.absoluteNormalCount > 0 ) ? new Float32Array( result.absoluteNormalCount ) : null;
  528. var uvFA = ( result.absoluteUvCount > 0 ) ? new Float32Array( result.absoluteUvCount ) : null;
  529. var rawObjectDescription;
  530. var materialDescription;
  531. var materialDescriptions = [];
  532. var createMultiMaterial = ( rawObjectDescriptions.length > 1 );
  533. var materialIndex = 0;
  534. var materialIndexMapping = [];
  535. var selectedMaterialIndex;
  536. var materialGroup;
  537. var materialGroups = [];
  538. var vertexFAOffset = 0;
  539. var indexUAOffset = 0;
  540. var colorFAOffset = 0;
  541. var normalFAOffset = 0;
  542. var uvFAOffset = 0;
  543. var materialGroupOffset = 0;
  544. var materialGroupLength = 0;
  545. for ( var oodIndex in rawObjectDescriptions ) {
  546. if ( ! rawObjectDescriptions.hasOwnProperty( oodIndex ) ) continue;
  547. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  548. materialDescription = {
  549. name: rawObjectDescription.materialName,
  550. flat: false,
  551. default: false
  552. };
  553. if ( this.materialNames[ materialDescription.name ] === null ) {
  554. materialDescription.default = true;
  555. console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName + '" was defined without material! Assigning "defaultMaterial".' );
  556. }
  557. // Attach '_flat' to materialName in case flat shading is needed due to smoothingGroup 0
  558. if ( rawObjectDescription.smoothingGroup === 0 ) materialDescription.flat = true;
  559. if ( createMultiMaterial ) {
  560. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  561. selectedMaterialIndex = materialIndexMapping[ materialDescription.name ];
  562. if ( ! selectedMaterialIndex ) {
  563. selectedMaterialIndex = materialIndex;
  564. materialIndexMapping[ materialDescription.name ] = materialIndex;
  565. materialDescriptions.push( materialDescription );
  566. materialIndex++;
  567. }
  568. materialGroupLength = this.useIndices ? rawObjectDescription.indices.length : rawObjectDescription.vertices.length / 3;
  569. materialGroup = {
  570. start: materialGroupOffset,
  571. count: materialGroupLength,
  572. index: selectedMaterialIndex
  573. };
  574. materialGroups.push( materialGroup );
  575. materialGroupOffset += materialGroupLength;
  576. } else {
  577. materialDescriptions.push( materialDescription );
  578. }
  579. vertexFA.set( rawObjectDescription.vertices, vertexFAOffset );
  580. vertexFAOffset += rawObjectDescription.vertices.length;
  581. if ( indexUA ) {
  582. indexUA.set( rawObjectDescription.indices, indexUAOffset );
  583. indexUAOffset += rawObjectDescription.indices.length;
  584. }
  585. if ( colorFA ) {
  586. colorFA.set( rawObjectDescription.colors, colorFAOffset );
  587. colorFAOffset += rawObjectDescription.colors.length;
  588. }
  589. if ( normalFA ) {
  590. normalFA.set( rawObjectDescription.normals, normalFAOffset );
  591. normalFAOffset += rawObjectDescription.normals.length;
  592. }
  593. if ( uvFA ) {
  594. uvFA.set( rawObjectDescription.uvs, uvFAOffset );
  595. uvFAOffset += rawObjectDescription.uvs.length;
  596. }
  597. if ( this.debug ) this.printReport( rawObjectDescription, selectedMaterialIndex );
  598. }
  599. this.outputObjectCount++;
  600. this.callbackBuilder(
  601. {
  602. cmd: 'meshData',
  603. params: {
  604. meshName: rawObjectDescription.groupName !== '' ? rawObjectDescription.groupName : rawObjectDescription.objectName
  605. },
  606. materials: {
  607. multiMaterial: createMultiMaterial,
  608. materialDescriptions: materialDescriptions,
  609. materialGroups: materialGroups
  610. },
  611. buffers: {
  612. vertices: vertexFA,
  613. indices: indexUA,
  614. colors: colorFA,
  615. normals: normalFA,
  616. uvs: uvFA
  617. }
  618. },
  619. [ vertexFA.buffer ],
  620. Validator.isValid( indexUA ) ? [ indexUA.buffer ] : null,
  621. Validator.isValid( colorFA ) ? [ colorFA.buffer ] : null,
  622. Validator.isValid( normalFA ) ? [ normalFA.buffer ] : null,
  623. Validator.isValid( uvFA ) ? [ uvFA.buffer ] : null
  624. );
  625. };
  626. Parser.prototype.printReport = function ( rawObjectDescription, selectedMaterialIndex ) {
  627. var materialIndexLine = Validator.isValid( selectedMaterialIndex ) ? '\n\tmaterialIndex: ' + selectedMaterialIndex : '';
  628. console.log(
  629. '\tOutput Object no.: ' + this.outputObjectCount +
  630. '\n\tobjectName: ' + rawObjectDescription.objectName +
  631. '\n\tgroupName: ' + rawObjectDescription.groupName +
  632. '\n\tmaterialName: ' + rawObjectDescription.materialName +
  633. materialIndexLine +
  634. '\n\tsmoothingGroup: ' + rawObjectDescription.smoothingGroup +
  635. '\n\t#vertices: ' + rawObjectDescription.vertices.length / 3 +
  636. '\n\t#indices: ' + rawObjectDescription.indices.length +
  637. '\n\t#colors: ' + rawObjectDescription.colors.length / 3 +
  638. '\n\t#uvs: ' + rawObjectDescription.uvs.length / 2 +
  639. '\n\t#normals: ' + rawObjectDescription.normals.length / 3
  640. );
  641. };
  642. return Parser;
  643. })();
  644. /**
  645. * {@link RawObject} is only used by {@link Parser}.
  646. * The user of OBJLoader2 does not need to care about this class.
  647. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  648. */
  649. var RawObject = (function () {
  650. function RawObject( materialPerSmoothingGroup, useIndices, disregardNormals, objectName, groupName, activeMtlName ) {
  651. this.globalVertexOffset = 1;
  652. this.globalUvOffset = 1;
  653. this.globalNormalOffset = 1;
  654. this.vertices = [];
  655. this.colors = [];
  656. this.normals = [];
  657. this.uvs = [];
  658. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  659. this.activeMtlName = Validator.verifyInput( activeMtlName, '' );
  660. this.objectName = Validator.verifyInput( objectName, '' );
  661. this.groupName = Validator.verifyInput( groupName, '' );
  662. this.mtllibName = '';
  663. this.smoothingGroup = {
  664. splitMaterials: materialPerSmoothingGroup === true,
  665. normalized: -1,
  666. real: -1
  667. };
  668. this.useIndices = useIndices === true;
  669. this.disregardNormals = disregardNormals === true;
  670. this.mtlCount = 0;
  671. this.smoothingGroupCount = 0;
  672. this.rawObjectDescriptions = [];
  673. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  674. this.pushSmoothingGroup( 1 );
  675. this.doubleIndicesCount = 0;
  676. this.faceCount = 0;
  677. }
  678. RawObject.prototype.newInstanceFromObject = function ( objectName, groupName ) {
  679. var newRawObject = new RawObject( this.smoothingGroup.splitMaterials, this.useIndices, this.disregardNormals, objectName, groupName, this.activeMtlName );
  680. // move indices forward
  681. newRawObject.globalVertexOffset = this.globalVertexOffset + this.vertices.length / 3;
  682. newRawObject.globalUvOffset = this.globalUvOffset + this.uvs.length / 2;
  683. newRawObject.globalNormalOffset = this.globalNormalOffset + this.normals.length / 3;
  684. return newRawObject;
  685. };
  686. RawObject.prototype.newInstanceFromGroup = function ( groupName ) {
  687. var newRawObject = new RawObject( this.smoothingGroup.splitMaterials, this.useIndices, this.disregardNormals, this.objectName, groupName, this.activeMtlName );
  688. // keep current buffers and indices forward
  689. newRawObject.vertices = this.vertices;
  690. newRawObject.colors = this.colors;
  691. newRawObject.uvs = this.uvs;
  692. newRawObject.normals = this.normals;
  693. newRawObject.globalVertexOffset = this.globalVertexOffset;
  694. newRawObject.globalUvOffset = this.globalUvOffset;
  695. newRawObject.globalNormalOffset = this.globalNormalOffset;
  696. return newRawObject;
  697. };
  698. RawObject.prototype.pushVertex = function ( buffer ) {
  699. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  700. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  701. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  702. };
  703. RawObject.prototype.pushVertexAndVertextColors = function ( buffer ) {
  704. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  705. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  706. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  707. this.colors.push( parseFloat( buffer[ 4 ] ) );
  708. this.colors.push( parseFloat( buffer[ 5 ] ) );
  709. this.colors.push( parseFloat( buffer[ 6 ] ) );
  710. };
  711. RawObject.prototype.pushUv = function ( buffer ) {
  712. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  713. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  714. };
  715. RawObject.prototype.pushNormal = function ( buffer ) {
  716. this.normals.push( parseFloat( buffer[ 1 ] ) );
  717. this.normals.push( parseFloat( buffer[ 2 ] ) );
  718. this.normals.push( parseFloat( buffer[ 3 ] ) );
  719. };
  720. RawObject.prototype.pushObject = function ( objectName ) {
  721. this.objectName = objectName;
  722. };
  723. RawObject.prototype.pushMtllib = function ( mtllibName ) {
  724. this.mtllibName = mtllibName;
  725. };
  726. RawObject.prototype.pushGroup = function ( groupName ) {
  727. this.groupName = groupName;
  728. };
  729. RawObject.prototype.pushUsemtl = function ( mtlName ) {
  730. if ( this.activeMtlName === mtlName || ! Validator.isValid( mtlName ) ) return;
  731. this.activeMtlName = mtlName;
  732. this.mtlCount++;
  733. this.verifyIndex();
  734. };
  735. RawObject.prototype.pushSmoothingGroup = function ( smoothingGroup ) {
  736. var smoothingGroupInt = parseInt( smoothingGroup );
  737. if ( isNaN( smoothingGroupInt ) ) {
  738. smoothingGroupInt = smoothingGroup === "off" ? 0 : 1;
  739. }
  740. var smoothCheck = this.smoothingGroup.normalized;
  741. this.smoothingGroup.normalized = this.smoothingGroup.splitMaterials ? smoothingGroupInt : ( smoothingGroupInt === 0 ) ? 0 : 1;
  742. this.smoothingGroup.real = smoothingGroupInt;
  743. if ( smoothCheck !== smoothingGroupInt ) {
  744. this.smoothingGroupCount++;
  745. this.verifyIndex();
  746. }
  747. };
  748. RawObject.prototype.verifyIndex = function () {
  749. var index = this.activeMtlName + '|' + this.smoothingGroup.normalized;
  750. this.rawObjectDescriptionInUse = this.rawObjectDescriptions[ index ];
  751. if ( ! Validator.isValid( this.rawObjectDescriptionInUse ) ) {
  752. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.smoothingGroup.normalized );
  753. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  754. }
  755. };
  756. RawObject.prototype.processFaces = function ( buffer, bufferPointer, slashesCount ) {
  757. var bufferLength = bufferPointer - 1;
  758. var i, length;
  759. // "f vertex ..."
  760. if ( slashesCount === 0 ) {
  761. for ( i = 2, length = bufferLength - 1; i < length; i ++ ) {
  762. this.buildFace( buffer[ 1 ] );
  763. this.buildFace( buffer[ i ] );
  764. this.buildFace( buffer[ i + 1 ] );
  765. }
  766. // "f vertex/uv ..."
  767. } else if ( bufferLength === slashesCount * 2 ) {
  768. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  769. this.buildFace( buffer[ 1 ], buffer[ 2 ] );
  770. this.buildFace( buffer[ i ], buffer[ i + 1 ] );
  771. this.buildFace( buffer[ i + 2 ], buffer[ i + 3 ] );
  772. }
  773. // "f vertex/uv/normal ..."
  774. } else if ( bufferLength * 2 === slashesCount * 3 ) {
  775. for ( i = 4, length = bufferLength - 3; i < length; i += 3 ) {
  776. this.buildFace( buffer[ 1 ], buffer[ 2 ], buffer[ 3 ] );
  777. this.buildFace( buffer[ i ], buffer[ i + 1 ], buffer[ i + 2 ] );
  778. this.buildFace( buffer[ i + 3 ], buffer[ i + 4 ], buffer[ i + 5 ] );
  779. }
  780. // "f vertex//normal ..."
  781. } else {
  782. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  783. this.buildFace( buffer[ 1 ], undefined, buffer[ 2 ] );
  784. this.buildFace( buffer[ i ], undefined, buffer[ i + 1 ] );
  785. this.buildFace( buffer[ i + 2 ], undefined, buffer[ i + 3 ] );
  786. }
  787. }
  788. };
  789. RawObject.prototype.buildFace = function ( faceIndexV, faceIndexU, faceIndexN ) {
  790. var rodiu = this.rawObjectDescriptionInUse;
  791. if ( this.disregardNormals ) faceIndexN = undefined;
  792. var scope = this;
  793. var updateRawObjectDescriptionInUse = function () {
  794. var indexPointerV = ( parseInt( faceIndexV ) - scope.globalVertexOffset ) * 3;
  795. var indexPointerC = scope.colors.length > 0 ? indexPointerV : undefined;
  796. var vertices = rodiu.vertices;
  797. vertices.push( scope.vertices[ indexPointerV++ ] );
  798. vertices.push( scope.vertices[ indexPointerV++ ] );
  799. vertices.push( scope.vertices[ indexPointerV ] );
  800. if ( indexPointerC ) {
  801. var colors = rodiu.colors;
  802. colors.push( scope.colors[ indexPointerC++ ] );
  803. colors.push( scope.colors[ indexPointerC++ ] );
  804. colors.push( scope.colors[ indexPointerC ] );
  805. }
  806. if ( faceIndexU ) {
  807. var indexPointerU = ( parseInt( faceIndexU ) - scope.globalUvOffset ) * 2;
  808. var uvs = rodiu.uvs;
  809. uvs.push( scope.uvs[ indexPointerU++ ] );
  810. uvs.push( scope.uvs[ indexPointerU ] );
  811. }
  812. if ( faceIndexN ) {
  813. var indexPointerN = ( parseInt( faceIndexN ) - scope.globalNormalOffset ) * 3;
  814. var normals = rodiu.normals;
  815. normals.push( scope.normals[ indexPointerN++ ] );
  816. normals.push( scope.normals[ indexPointerN++ ] );
  817. normals.push( scope.normals[ indexPointerN ] );
  818. }
  819. };
  820. if ( this.useIndices ) {
  821. var mappingName = faceIndexV + ( faceIndexU ? '_' + faceIndexU : '_n' ) + ( faceIndexN ? '_' + faceIndexN : '_n' );
  822. var indicesPointer = rodiu.indexMappings[ mappingName ];
  823. if ( Validator.isValid( indicesPointer ) ) {
  824. this.doubleIndicesCount++;
  825. } else {
  826. indicesPointer = rodiu.vertices.length / 3;
  827. updateRawObjectDescriptionInUse();
  828. rodiu.indexMappings[ mappingName ] = indicesPointer;
  829. rodiu.indexMappingsCount++;
  830. }
  831. rodiu.indices.push( indicesPointer );
  832. } else {
  833. updateRawObjectDescriptionInUse();
  834. }
  835. this.faceCount++;
  836. };
  837. /*
  838. * Support for lines with or without texture. First element in indexArray is the line identification
  839. * 0: "f vertex/uv vertex/uv ..."
  840. * 1: "f vertex vertex ..."
  841. */
  842. RawObject.prototype.buildLineVvt = function ( lineArray ) {
  843. for ( var i = 1, length = lineArray.length; i < length; i ++ ) {
  844. this.vertices.push( parseInt( lineArray[ i ] ) );
  845. this.uvs.push( parseInt( lineArray[ i ] ) );
  846. }
  847. };
  848. RawObject.prototype.buildLineV = function ( lineArray ) {
  849. for ( var i = 1, length = lineArray.length; i < length; i++ ) {
  850. this.vertices.push( parseInt( lineArray[ i ] ) );
  851. }
  852. };
  853. /**
  854. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  855. */
  856. RawObject.prototype.finalize = function () {
  857. var rawObjectDescriptionsTemp = [];
  858. var rawObjectDescription;
  859. var absoluteVertexCount = 0;
  860. var absoluteIndexMappingsCount = 0;
  861. var absoluteIndexCount = 0;
  862. var absoluteColorCount = 0;
  863. var absoluteNormalCount = 0;
  864. var absoluteUvCount = 0;
  865. var indices;
  866. for ( var name in this.rawObjectDescriptions ) {
  867. rawObjectDescription = this.rawObjectDescriptions[ name ];
  868. if ( rawObjectDescription.vertices.length > 0 ) {
  869. indices = rawObjectDescription.indices;
  870. if ( indices.length > 0 && absoluteIndexMappingsCount > 0 ) {
  871. for ( var i in indices ) indices[ i ] = indices[ i ] + absoluteIndexMappingsCount;
  872. }
  873. rawObjectDescriptionsTemp.push( rawObjectDescription );
  874. absoluteVertexCount += rawObjectDescription.vertices.length;
  875. absoluteIndexMappingsCount += rawObjectDescription.indexMappingsCount;
  876. absoluteIndexCount += rawObjectDescription.indices.length;
  877. absoluteColorCount += rawObjectDescription.colors.length;
  878. absoluteUvCount += rawObjectDescription.uvs.length;
  879. absoluteNormalCount += rawObjectDescription.normals.length;
  880. }
  881. }
  882. // do not continue if no result
  883. var result = null;
  884. if ( rawObjectDescriptionsTemp.length > 0 ) {
  885. result = {
  886. rawObjectDescriptions: rawObjectDescriptionsTemp,
  887. absoluteVertexCount: absoluteVertexCount,
  888. absoluteIndexCount: absoluteIndexCount,
  889. absoluteColorCount: absoluteColorCount,
  890. absoluteNormalCount: absoluteNormalCount,
  891. absoluteUvCount: absoluteUvCount,
  892. faceCount: this.faceCount,
  893. doubleIndicesCount: this.doubleIndicesCount
  894. };
  895. }
  896. return result;
  897. };
  898. RawObject.prototype.createReport = function ( inputObjectCount, printDirectly ) {
  899. var report = {
  900. name: this.objectName ? this.objectName : 'groups',
  901. mtllibName: this.mtllibName,
  902. vertexCount: this.vertices.length / 3,
  903. normalCount: this.normals.length / 3,
  904. uvCount: this.uvs.length / 2,
  905. smoothingGroupCount: this.smoothingGroupCount,
  906. mtlCount: this.mtlCount,
  907. rawObjectDescriptions: this.rawObjectDescriptions.length
  908. };
  909. if ( printDirectly ) {
  910. console.log( 'Input Object number: ' + inputObjectCount + ' Object name: ' + report.name +
  911. '\n Mtllib name: ' + report.mtllibName +
  912. '\n Vertex count: ' + report.vertexCount +
  913. '\n Normal count: ' + report.normalCount +
  914. '\n UV count: ' + report.uvCount +
  915. '\n SmoothingGroup count: ' + report.smoothingGroupCount +
  916. '\n Material count: ' + report.mtlCount +
  917. '\n Real RawObjectDescription count: ' + report.rawObjectDescriptions
  918. );
  919. }
  920. return report;
  921. };
  922. return RawObject;
  923. })();
  924. /**
  925. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  926. * @class
  927. *
  928. * @param {string} objectName Name of the mesh
  929. * @param {string} groupName Name of the group
  930. * @param {string} materialName Name of the material
  931. * @param {number} smoothingGroup Normalized smoothingGroup (0: flat shading, 1: smooth shading)
  932. */
  933. var RawObjectDescription = (function () {
  934. function RawObjectDescription( objectName, groupName, materialName, smoothingGroup ) {
  935. this.objectName = objectName;
  936. this.groupName = groupName;
  937. this.materialName = materialName;
  938. this.smoothingGroup = smoothingGroup;
  939. this.vertices = [];
  940. this.indexMappingsCount = 0;
  941. this.indexMappings = [];
  942. this.indices = [];
  943. this.colors = [];
  944. this.uvs = [];
  945. this.normals = [];
  946. }
  947. return RawObjectDescription;
  948. })();
  949. OBJLoader2.prototype._checkFiles = function ( resources ) {
  950. var resource;
  951. var result = {
  952. mtl: null,
  953. obj: null
  954. };
  955. for ( var index in resources ) {
  956. resource = resources[ index ];
  957. if ( ! Validator.isValid( resource.name ) ) continue;
  958. if ( Validator.isValid( resource.content ) ) {
  959. if ( resource.extension === 'OBJ' ) {
  960. // fast-fail on bad type
  961. if ( ! ( resource.content instanceof Uint8Array ) ) throw 'Provided content is not of type arraybuffer! Aborting...';
  962. result.obj = resource;
  963. } else if ( resource.extension === 'MTL' && Validator.isValid( resource.name ) ) {
  964. if ( ! ( typeof( resource.content ) === 'string' || resource.content instanceof String ) ) throw 'Provided content is not of type String! Aborting...';
  965. result.mtl = resource;
  966. } else if ( resource.extension === "ZIP" ) {
  967. // ignore
  968. } else {
  969. throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  970. }
  971. } else {
  972. // fast-fail on bad type
  973. if ( ! ( typeof( resource.name ) === 'string' || resource.name instanceof String ) ) throw 'Provided file is not properly defined! Aborting...';
  974. if ( resource.extension === 'OBJ' ) {
  975. result.obj = resource;
  976. } else if ( resource.extension === 'MTL' ) {
  977. result.mtl = resource;
  978. } else if ( resource.extension === "ZIP" ) {
  979. // ignore
  980. } else {
  981. throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  982. }
  983. }
  984. }
  985. return result;
  986. };
  987. /**
  988. * Utility method for loading an mtl file according resource description.
  989. * @memberOf THREE.OBJLoader2
  990. *
  991. * @param {string} url URL to the file
  992. * @param {string} name The name of the object
  993. * @param {Object} content The file content as arraybuffer or text
  994. * @param {function} callbackOnLoad
  995. * @param {string} [crossOrigin] CORS value
  996. */
  997. OBJLoader2.prototype.loadMtl = function ( url, name, content, callbackOnLoad, crossOrigin ) {
  998. var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'MTL' );
  999. resource.setContent( content );
  1000. this._loadMtl( resource, callbackOnLoad, crossOrigin );
  1001. };
  1002. /**
  1003. * Utility method for loading an mtl file according resource description.
  1004. * @memberOf THREE.OBJLoader2
  1005. *
  1006. * @param {THREE.LoaderSupport.ResourceDescriptor} resource
  1007. * @param {function} callbackOnLoad
  1008. * @param {string} [crossOrigin] CORS value
  1009. */
  1010. OBJLoader2.prototype._loadMtl = function ( resource, callbackOnLoad, crossOrigin ) {
  1011. if ( Validator.isValid( resource ) ) console.time( 'Loading MTL: ' + resource.name );
  1012. var materials = [];
  1013. var processMaterials = function ( materialCreator ) {
  1014. var materialCreatorMaterials = [];
  1015. if ( Validator.isValid( materialCreator ) ) {
  1016. materialCreator.preload();
  1017. materialCreatorMaterials = materialCreator.materials;
  1018. for ( var materialName in materialCreatorMaterials ) {
  1019. if ( materialCreatorMaterials.hasOwnProperty( materialName ) ) {
  1020. materials[ materialName ] = materialCreatorMaterials[ materialName ];
  1021. }
  1022. }
  1023. }
  1024. if ( Validator.isValid( resource ) ) console.timeEnd( 'Loading MTL: ' + resource.name );
  1025. callbackOnLoad( materials );
  1026. };
  1027. var mtlLoader = new THREE.MTLLoader();
  1028. crossOrigin = Validator.verifyInput( crossOrigin, 'anonymous' );
  1029. mtlLoader.setCrossOrigin( crossOrigin );
  1030. // fast-fail
  1031. if ( ! Validator.isValid( resource ) || ( ! Validator.isValid( resource.content ) && ! Validator.isValid( resource.url ) ) ) {
  1032. processMaterials();
  1033. } else {
  1034. mtlLoader.setPath( resource.path );
  1035. if ( Validator.isValid( resource.content ) ) {
  1036. processMaterials( Validator.isValid( resource.content ) ? mtlLoader.parse( resource.content ) : null );
  1037. } else if ( Validator.isValid( resource.url ) ) {
  1038. var onError = function ( event ) {
  1039. var output = 'Error occurred while downloading "' + resource.url + '"';
  1040. console.error( output + ': ' + event );
  1041. throw output;
  1042. };
  1043. mtlLoader.load( resource.name, processMaterials, undefined, onError );
  1044. }
  1045. }
  1046. };
  1047. return OBJLoader2;
  1048. })();