OBJLoader2.js 42 KB

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