OBJLoader2.js 44 KB

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