OBJLoader2Parser.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. /**
  2. * @author Kai Salmen / https://kaisalmen.de
  3. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  4. */
  5. /**
  6. * Parse OBJ data either from ArrayBuffer or string
  7. */
  8. const OBJLoader2Parser = function () {
  9. let scope = this;
  10. this.callbacks = {
  11. onProgress: function ( text ) {
  12. scope._onProgress( text )
  13. },
  14. onAssetAvailable: function ( payload ) {
  15. scope._onAssetAvailable( payload )
  16. },
  17. onError: function ( errorMessage ) {
  18. scope._onError( errorMessage )
  19. }
  20. };
  21. this.contentRef = null;
  22. this.legacyMode = false;
  23. this.materials = {};
  24. this.materialPerSmoothingGroup = false;
  25. this.useOAsMesh = false;
  26. this.useIndices = false;
  27. this.disregardNormals = false;
  28. this.vertices = [];
  29. this.colors = [];
  30. this.normals = [];
  31. this.uvs = [];
  32. this.rawMesh = {
  33. objectName: '',
  34. groupName: '',
  35. activeMtlName: '',
  36. mtllibName: '',
  37. // reset with new mesh
  38. faceType: - 1,
  39. subGroups: [],
  40. subGroupInUse: null,
  41. smoothingGroup: {
  42. splitMaterials: false,
  43. normalized: - 1,
  44. real: - 1
  45. },
  46. counts: {
  47. doubleIndicesCount: 0,
  48. faceCount: 0,
  49. mtlCount: 0,
  50. smoothingGroupCount: 0
  51. }
  52. };
  53. this.inputObjectCount = 1;
  54. this.outputObjectCount = 1;
  55. this.globalCounts = {
  56. vertices: 0,
  57. faces: 0,
  58. doubleIndicesCount: 0,
  59. lineByte: 0,
  60. currentByte: 0,
  61. totalBytes: 0
  62. };
  63. this.logging = {
  64. enabled: true,
  65. debug: false
  66. };
  67. };
  68. OBJLoader2Parser.prototype = {
  69. constructor: OBJLoader2Parser,
  70. _resetRawMesh: function () {
  71. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  72. this.rawMesh.subGroups = [];
  73. this.rawMesh.subGroupInUse = null;
  74. this.rawMesh.smoothingGroup.normalized = - 1;
  75. this.rawMesh.smoothingGroup.real = - 1;
  76. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  77. this._pushSmoothingGroup( 1 );
  78. this.rawMesh.counts.doubleIndicesCount = 0;
  79. this.rawMesh.counts.faceCount = 0;
  80. this.rawMesh.counts.mtlCount = 0;
  81. this.rawMesh.counts.smoothingGroupCount = 0;
  82. },
  83. /**
  84. * Tells whether a material shall be created per smoothing group.
  85. *
  86. * @param {boolean} materialPerSmoothingGroup=false
  87. * @return {OBJLoader2Parser}
  88. */
  89. setMaterialPerSmoothingGroup: function ( materialPerSmoothingGroup ) {
  90. this.materialPerSmoothingGroup = materialPerSmoothingGroup === true;
  91. return this;
  92. },
  93. /**
  94. * Usually 'o' is meta-information and does not result in creation of new meshes, but mesh creation on occurrence of "o" can be enforced.
  95. *
  96. * @param {boolean} useOAsMesh=false
  97. * @return {OBJLoader2Parser}
  98. */
  99. setUseOAsMesh: function ( useOAsMesh ) {
  100. this.useOAsMesh = useOAsMesh === true;
  101. return this;
  102. },
  103. /**
  104. * Instructs loaders to create indexed {@link BufferGeometry}.
  105. *
  106. * @param {boolean} useIndices=false
  107. * @return {OBJLoader2Parser}
  108. */
  109. setUseIndices: function ( useIndices ) {
  110. this.useIndices = useIndices === true;
  111. return this;
  112. },
  113. /**
  114. * Tells whether normals should be completely disregarded and regenerated.
  115. *
  116. * @param {boolean} disregardNormals=false
  117. * @return {OBJLoader2Parser}
  118. */
  119. setDisregardNormals: function ( disregardNormals ) {
  120. this.disregardNormals = disregardNormals === true;
  121. return this;
  122. },
  123. _setMaterials: function ( materials ) {
  124. if ( materials === undefined || materials === null ) return;
  125. for ( let materialName in materials ) {
  126. if ( materials.hasOwnProperty( materialName ) ) {
  127. this.materials[ materialName ] = materials[ materialName ];
  128. }
  129. }
  130. },
  131. /**
  132. * Register a function that is called once an asset (mesh/material) becomes available.
  133. *
  134. * @param onAssetAvailable
  135. * @return {OBJLoader2Parser}
  136. */
  137. setCallbackOnAssetAvailable: function ( onAssetAvailable ) {
  138. if ( onAssetAvailable !== null && onAssetAvailable !== undefined && onAssetAvailable instanceof Function ) {
  139. this.callbacks.onAssetAvailable = onAssetAvailable;
  140. }
  141. return this;
  142. },
  143. /**
  144. * Register a function that is used to report overall processing progress.
  145. *
  146. * @param {Function} onProgress
  147. * @return {OBJLoader2Parser}
  148. */
  149. setCallbackOnProgress: function ( onProgress ) {
  150. if ( onProgress !== null && onProgress !== undefined && onProgress instanceof Function ) {
  151. this.callbacks.onProgress = onProgress;
  152. }
  153. return this;
  154. },
  155. /**
  156. * Register an error handler function that is called if errors occur. It can decide to just log or to throw an exception.
  157. *
  158. * @param {Function} onError
  159. * @return {OBJLoader2Parser}
  160. */
  161. setCallbackOnError: function ( onError ) {
  162. if ( onError !== null && onError !== undefined && onError instanceof Function ) {
  163. this.callbacks.onError = onError;
  164. }
  165. return this;
  166. },
  167. /**
  168. * Announce parse progress feedback which is logged to the console.
  169. * @private
  170. *
  171. * @param {string} text Textual description of the event
  172. */
  173. _onProgress: function ( text ) {
  174. let message = text ? text : '';
  175. if ( this.logging.enabled && this.logging.debug ) {
  176. console.log( message );
  177. }
  178. },
  179. /**
  180. * Announce error feedback which is logged as error message.
  181. * @private
  182. *
  183. * @param {String} errorMessage The event containing the error
  184. */
  185. _onError: function ( errorMessage ) {
  186. if ( this.logging.enabled && this.logging.debug ) {
  187. console.error( errorMessage );
  188. }
  189. },
  190. _onAssetAvailable: function ( payload ) {
  191. let errorMessage = 'OBJLoader2Parser does not provide implementation for onAssetAvailable. Aborting...';
  192. this.callbacks.onError( errorMessage );
  193. throw errorMessage;
  194. },
  195. /**
  196. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  197. *
  198. * @param {boolean} enabled True or false.
  199. * @param {boolean} debug True or false.
  200. *
  201. * @return {OBJLoader2Parser}
  202. */
  203. setLogging: function ( enabled, debug ) {
  204. this.logging.enabled = enabled === true;
  205. this.logging.debug = debug === true;
  206. return this;
  207. },
  208. _configure: function () {
  209. this._pushSmoothingGroup( 1 );
  210. if ( this.logging.enabled ) {
  211. let matKeys = Object.keys( this.materials );
  212. let matNames = ( matKeys.length > 0 ) ? '\n\tmaterialNames:\n\t\t- ' + matKeys.join( '\n\t\t- ' ) : '\n\tmaterialNames: None';
  213. let printedConfig = 'OBJLoader.Parser configuration:'
  214. + matNames
  215. + '\n\tmaterialPerSmoothingGroup: ' + this.materialPerSmoothingGroup
  216. + '\n\tuseOAsMesh: ' + this.useOAsMesh
  217. + '\n\tuseIndices: ' + this.useIndices
  218. + '\n\tdisregardNormals: ' + this.disregardNormals;
  219. printedConfig += '\n\tcallbacks.onProgress: ' + this.callbacks.onProgress.name;
  220. printedConfig += '\n\tcallbacks.onAssetAvailable: ' + this.callbacks.onAssetAvailable.name;
  221. printedConfig += '\n\tcallbacks.onError: ' + this.callbacks.onError.name;
  222. console.info( printedConfig );
  223. }
  224. },
  225. /**
  226. * Parse the provided arraybuffer
  227. *
  228. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  229. */
  230. execute: function ( arrayBuffer ) {
  231. if ( this.logging.enabled ) console.time( 'OBJLoader2Parser.execute' );
  232. this._configure();
  233. let arrayBufferView = new Uint8Array( arrayBuffer );
  234. this.contentRef = arrayBufferView;
  235. let length = arrayBufferView.byteLength;
  236. this.globalCounts.totalBytes = length;
  237. let buffer = new Array( 128 );
  238. for ( let code, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i ++ ) {
  239. code = arrayBufferView[ i ];
  240. switch ( code ) {
  241. // space
  242. case 32:
  243. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  244. word = '';
  245. break;
  246. // slash
  247. case 47:
  248. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  249. slashesCount ++;
  250. word = '';
  251. break;
  252. // LF
  253. case 10:
  254. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  255. word = '';
  256. this.globalCounts.lineByte = this.globalCounts.currentByte;
  257. this.globalCounts.currentByte = i;
  258. this._processLine( buffer, bufferPointer, slashesCount );
  259. bufferPointer = 0;
  260. slashesCount = 0;
  261. break;
  262. // CR
  263. case 13:
  264. break;
  265. default:
  266. word += String.fromCharCode( code );
  267. break;
  268. }
  269. }
  270. this._finalizeParsing();
  271. if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2Parser.execute' );
  272. },
  273. /**
  274. * Parse the provided text
  275. *
  276. * @param {string} text OBJ data as string
  277. */
  278. executeLegacy: function ( text ) {
  279. if ( this.logging.enabled ) console.time( 'OBJLoader2Parser.executeLegacy' );
  280. this._configure();
  281. this.legacyMode = true;
  282. this.contentRef = text;
  283. let length = text.length;
  284. this.globalCounts.totalBytes = length;
  285. let buffer = new Array( 128 );
  286. for ( let char, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i ++ ) {
  287. char = text[ i ];
  288. switch ( char ) {
  289. case ' ':
  290. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  291. word = '';
  292. break;
  293. case '/':
  294. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  295. slashesCount ++;
  296. word = '';
  297. break;
  298. case '\n':
  299. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  300. word = '';
  301. this.globalCounts.lineByte = this.globalCounts.currentByte;
  302. this.globalCounts.currentByte = i;
  303. this._processLine( buffer, bufferPointer, slashesCount );
  304. bufferPointer = 0;
  305. slashesCount = 0;
  306. break;
  307. case '\r':
  308. break;
  309. default:
  310. word += char;
  311. }
  312. }
  313. this._finalizeParsing();
  314. if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2Parser.executeLegacy' );
  315. },
  316. _processLine: function ( buffer, bufferPointer, slashesCount ) {
  317. if ( bufferPointer < 1 ) return;
  318. let reconstructString = function ( content, legacyMode, start, stop ) {
  319. let line = '';
  320. if ( stop > start ) {
  321. let i;
  322. if ( legacyMode ) {
  323. for ( i = start; i < stop; i ++ ) line += content[ i ];
  324. } else {
  325. for ( i = start; i < stop; i ++ ) line += String.fromCharCode( content[ i ] );
  326. }
  327. line = line.trim();
  328. }
  329. return line;
  330. };
  331. let bufferLength, length, i, lineDesignation;
  332. lineDesignation = buffer[ 0 ];
  333. switch ( lineDesignation ) {
  334. case 'v':
  335. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  336. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  337. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  338. if ( bufferPointer > 4 ) {
  339. this.colors.push( parseFloat( buffer[ 4 ] ) );
  340. this.colors.push( parseFloat( buffer[ 5 ] ) );
  341. this.colors.push( parseFloat( buffer[ 6 ] ) );
  342. }
  343. break;
  344. case 'vt':
  345. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  346. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  347. break;
  348. case 'vn':
  349. this.normals.push( parseFloat( buffer[ 1 ] ) );
  350. this.normals.push( parseFloat( buffer[ 2 ] ) );
  351. this.normals.push( parseFloat( buffer[ 3 ] ) );
  352. break;
  353. case 'f':
  354. bufferLength = bufferPointer - 1;
  355. // "f vertex ..."
  356. if ( slashesCount === 0 ) {
  357. this._checkFaceType( 0 );
  358. for ( i = 2, length = bufferLength; i < length; i ++ ) {
  359. this._buildFace( buffer[ 1 ] );
  360. this._buildFace( buffer[ i ] );
  361. this._buildFace( buffer[ i + 1 ] );
  362. }
  363. // "f vertex/uv ..."
  364. } else if ( bufferLength === slashesCount * 2 ) {
  365. this._checkFaceType( 1 );
  366. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  367. this._buildFace( buffer[ 1 ], buffer[ 2 ] );
  368. this._buildFace( buffer[ i ], buffer[ i + 1 ] );
  369. this._buildFace( buffer[ i + 2 ], buffer[ i + 3 ] );
  370. }
  371. // "f vertex/uv/normal ..."
  372. } else if ( bufferLength * 2 === slashesCount * 3 ) {
  373. this._checkFaceType( 2 );
  374. for ( i = 4, length = bufferLength - 3; i < length; i += 3 ) {
  375. this._buildFace( buffer[ 1 ], buffer[ 2 ], buffer[ 3 ] );
  376. this._buildFace( buffer[ i ], buffer[ i + 1 ], buffer[ i + 2 ] );
  377. this._buildFace( buffer[ i + 3 ], buffer[ i + 4 ], buffer[ i + 5 ] );
  378. }
  379. // "f vertex//normal ..."
  380. } else {
  381. this._checkFaceType( 3 );
  382. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  383. this._buildFace( buffer[ 1 ], undefined, buffer[ 2 ] );
  384. this._buildFace( buffer[ i ], undefined, buffer[ i + 1 ] );
  385. this._buildFace( buffer[ i + 2 ], undefined, buffer[ i + 3 ] );
  386. }
  387. }
  388. break;
  389. case 'l':
  390. case 'p':
  391. bufferLength = bufferPointer - 1;
  392. if ( bufferLength === slashesCount * 2 ) {
  393. this._checkFaceType( 4 );
  394. for ( i = 1, length = bufferLength + 1; i < length; i += 2 ) this._buildFace( buffer[ i ], buffer[ i + 1 ] );
  395. } else {
  396. this._checkFaceType( ( lineDesignation === 'l' ) ? 5 : 6 );
  397. for ( i = 1, length = bufferLength + 1; i < length; i ++ ) this._buildFace( buffer[ i ] );
  398. }
  399. break;
  400. case 's':
  401. this._pushSmoothingGroup( buffer[ 1 ] );
  402. break;
  403. case 'g':
  404. // 'g' leads to creation of mesh if valid data (faces declaration was done before), otherwise only groupName gets set
  405. this._processCompletedMesh();
  406. this.rawMesh.groupName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 2, this.globalCounts.currentByte );
  407. break;
  408. case 'o':
  409. // 'o' is meta-information and usually does not result in creation of new meshes, but can be enforced with "useOAsMesh"
  410. if ( this.useOAsMesh ) this._processCompletedMesh();
  411. this.rawMesh.objectName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 2, this.globalCounts.currentByte );
  412. break;
  413. case 'mtllib':
  414. this.rawMesh.mtllibName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 7, this.globalCounts.currentByte );
  415. break;
  416. case 'usemtl':
  417. let mtlName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 7, this.globalCounts.currentByte );
  418. if ( mtlName !== '' && this.rawMesh.activeMtlName !== mtlName ) {
  419. this.rawMesh.activeMtlName = mtlName;
  420. this.rawMesh.counts.mtlCount ++;
  421. this._checkSubGroup();
  422. }
  423. break;
  424. default:
  425. break;
  426. }
  427. },
  428. _pushSmoothingGroup: function ( smoothingGroup ) {
  429. let smoothingGroupInt = parseInt( smoothingGroup );
  430. if ( isNaN( smoothingGroupInt ) ) {
  431. smoothingGroupInt = smoothingGroup === "off" ? 0 : 1;
  432. }
  433. let smoothCheck = this.rawMesh.smoothingGroup.normalized;
  434. this.rawMesh.smoothingGroup.normalized = this.rawMesh.smoothingGroup.splitMaterials ? smoothingGroupInt : ( smoothingGroupInt === 0 ) ? 0 : 1;
  435. this.rawMesh.smoothingGroup.real = smoothingGroupInt;
  436. if ( smoothCheck !== smoothingGroupInt ) {
  437. this.rawMesh.counts.smoothingGroupCount ++;
  438. this._checkSubGroup();
  439. }
  440. },
  441. /**
  442. * Expanded faceTypes include all four face types, both line types and the point type
  443. * faceType = 0: "f vertex ..."
  444. * faceType = 1: "f vertex/uv ..."
  445. * faceType = 2: "f vertex/uv/normal ..."
  446. * faceType = 3: "f vertex//normal ..."
  447. * faceType = 4: "l vertex/uv ..." or "l vertex ..."
  448. * faceType = 5: "l vertex ..."
  449. * faceType = 6: "p vertex ..."
  450. */
  451. _checkFaceType: function ( faceType ) {
  452. if ( this.rawMesh.faceType !== faceType ) {
  453. this._processCompletedMesh();
  454. this.rawMesh.faceType = faceType;
  455. this._checkSubGroup();
  456. }
  457. },
  458. _checkSubGroup: function () {
  459. let index = this.rawMesh.activeMtlName + '|' + this.rawMesh.smoothingGroup.normalized;
  460. this.rawMesh.subGroupInUse = this.rawMesh.subGroups[ index ];
  461. if ( this.rawMesh.subGroupInUse === undefined || this.rawMesh.subGroupInUse === null ) {
  462. this.rawMesh.subGroupInUse = {
  463. index: index,
  464. objectName: this.rawMesh.objectName,
  465. groupName: this.rawMesh.groupName,
  466. materialName: this.rawMesh.activeMtlName,
  467. smoothingGroup: this.rawMesh.smoothingGroup.normalized,
  468. vertices: [],
  469. indexMappingsCount: 0,
  470. indexMappings: [],
  471. indices: [],
  472. colors: [],
  473. uvs: [],
  474. normals: []
  475. };
  476. this.rawMesh.subGroups[ index ] = this.rawMesh.subGroupInUse;
  477. }
  478. },
  479. _buildFace: function ( faceIndexV, faceIndexU, faceIndexN ) {
  480. let subGroupInUse = this.rawMesh.subGroupInUse;
  481. let scope = this;
  482. let updateSubGroupInUse = function () {
  483. let faceIndexVi = parseInt( faceIndexV );
  484. let indexPointerV = 3 * ( faceIndexVi > 0 ? faceIndexVi - 1 : faceIndexVi + scope.vertices.length / 3 );
  485. let indexPointerC = scope.colors.length > 0 ? indexPointerV : null;
  486. let vertices = subGroupInUse.vertices;
  487. vertices.push( scope.vertices[ indexPointerV ++ ] );
  488. vertices.push( scope.vertices[ indexPointerV ++ ] );
  489. vertices.push( scope.vertices[ indexPointerV ] );
  490. if ( indexPointerC !== null ) {
  491. let colors = subGroupInUse.colors;
  492. colors.push( scope.colors[ indexPointerC ++ ] );
  493. colors.push( scope.colors[ indexPointerC ++ ] );
  494. colors.push( scope.colors[ indexPointerC ] );
  495. }
  496. if ( faceIndexU ) {
  497. let faceIndexUi = parseInt( faceIndexU );
  498. let indexPointerU = 2 * ( faceIndexUi > 0 ? faceIndexUi - 1 : faceIndexUi + scope.uvs.length / 2 );
  499. let uvs = subGroupInUse.uvs;
  500. uvs.push( scope.uvs[ indexPointerU ++ ] );
  501. uvs.push( scope.uvs[ indexPointerU ] );
  502. }
  503. if ( faceIndexN && ! scope.disregardNormals ) {
  504. let faceIndexNi = parseInt( faceIndexN );
  505. let indexPointerN = 3 * ( faceIndexNi > 0 ? faceIndexNi - 1 : faceIndexNi + scope.normals.length / 3 );
  506. let normals = subGroupInUse.normals;
  507. normals.push( scope.normals[ indexPointerN ++ ] );
  508. normals.push( scope.normals[ indexPointerN ++ ] );
  509. normals.push( scope.normals[ indexPointerN ] );
  510. }
  511. };
  512. if ( this.useIndices ) {
  513. if ( this.disregardNormals ) faceIndexN = undefined;
  514. let mappingName = faceIndexV + ( faceIndexU ? '_' + faceIndexU : '_n' ) + ( faceIndexN ? '_' + faceIndexN : '_n' );
  515. let indicesPointer = subGroupInUse.indexMappings[ mappingName ];
  516. if ( indicesPointer === undefined || indicesPointer === null ) {
  517. indicesPointer = this.rawMesh.subGroupInUse.vertices.length / 3;
  518. updateSubGroupInUse();
  519. subGroupInUse.indexMappings[ mappingName ] = indicesPointer;
  520. subGroupInUse.indexMappingsCount ++;
  521. } else {
  522. this.rawMesh.counts.doubleIndicesCount ++;
  523. }
  524. subGroupInUse.indices.push( indicesPointer );
  525. } else {
  526. updateSubGroupInUse();
  527. }
  528. this.rawMesh.counts.faceCount ++;
  529. },
  530. _createRawMeshReport: function ( inputObjectCount ) {
  531. return 'Input Object number: ' + inputObjectCount +
  532. '\n\tObject name: ' + this.rawMesh.objectName +
  533. '\n\tGroup name: ' + this.rawMesh.groupName +
  534. '\n\tMtllib name: ' + this.rawMesh.mtllibName +
  535. '\n\tVertex count: ' + this.vertices.length / 3 +
  536. '\n\tNormal count: ' + this.normals.length / 3 +
  537. '\n\tUV count: ' + this.uvs.length / 2 +
  538. '\n\tSmoothingGroup count: ' + this.rawMesh.counts.smoothingGroupCount +
  539. '\n\tMaterial count: ' + this.rawMesh.counts.mtlCount +
  540. '\n\tReal MeshOutputGroup count: ' + this.rawMesh.subGroups.length;
  541. },
  542. /**
  543. * Clear any empty subGroup and calculate absolute vertex, normal and uv counts
  544. */
  545. _finalizeRawMesh: function () {
  546. let meshOutputGroupTemp = [];
  547. let meshOutputGroup;
  548. let absoluteVertexCount = 0;
  549. let absoluteIndexMappingsCount = 0;
  550. let absoluteIndexCount = 0;
  551. let absoluteColorCount = 0;
  552. let absoluteNormalCount = 0;
  553. let absoluteUvCount = 0;
  554. let indices;
  555. for ( let name in this.rawMesh.subGroups ) {
  556. meshOutputGroup = this.rawMesh.subGroups[ name ];
  557. if ( meshOutputGroup.vertices.length > 0 ) {
  558. indices = meshOutputGroup.indices;
  559. if ( indices.length > 0 && absoluteIndexMappingsCount > 0 ) {
  560. for ( let i = 0; i < indices.length; i ++ ) {
  561. indices[ i ] = indices[ i ] + absoluteIndexMappingsCount;
  562. }
  563. }
  564. meshOutputGroupTemp.push( meshOutputGroup );
  565. absoluteVertexCount += meshOutputGroup.vertices.length;
  566. absoluteIndexMappingsCount += meshOutputGroup.indexMappingsCount;
  567. absoluteIndexCount += meshOutputGroup.indices.length;
  568. absoluteColorCount += meshOutputGroup.colors.length;
  569. absoluteUvCount += meshOutputGroup.uvs.length;
  570. absoluteNormalCount += meshOutputGroup.normals.length;
  571. }
  572. }
  573. // do not continue if no result
  574. let result = null;
  575. if ( meshOutputGroupTemp.length > 0 ) {
  576. result = {
  577. name: this.rawMesh.groupName !== '' ? this.rawMesh.groupName : this.rawMesh.objectName,
  578. subGroups: meshOutputGroupTemp,
  579. absoluteVertexCount: absoluteVertexCount,
  580. absoluteIndexCount: absoluteIndexCount,
  581. absoluteColorCount: absoluteColorCount,
  582. absoluteNormalCount: absoluteNormalCount,
  583. absoluteUvCount: absoluteUvCount,
  584. faceCount: this.rawMesh.counts.faceCount,
  585. doubleIndicesCount: this.rawMesh.counts.doubleIndicesCount
  586. };
  587. }
  588. return result;
  589. },
  590. _processCompletedMesh: function () {
  591. let result = this._finalizeRawMesh();
  592. let haveMesh = result !== null;
  593. if ( haveMesh ) {
  594. if ( this.colors.length > 0 && this.colors.length !== this.vertices.length ) {
  595. this.callbacks.onError( 'Vertex Colors were detected, but vertex count and color count do not match!' );
  596. }
  597. if ( this.logging.enabled && this.logging.debug ) console.debug( this._createRawMeshReport( this.inputObjectCount ) );
  598. this.inputObjectCount ++;
  599. this._buildMesh( result );
  600. let progressBytesPercent = this.globalCounts.currentByte / this.globalCounts.totalBytes;
  601. this._onProgress( 'Completed [o: ' + this.rawMesh.objectName + ' g:' + this.rawMesh.groupName + '' +
  602. '] Total progress: ' + ( progressBytesPercent * 100 ).toFixed( 2 ) + '%' );
  603. this._resetRawMesh();
  604. }
  605. return haveMesh;
  606. },
  607. /**
  608. * SubGroups are transformed to too intermediate format that is forwarded to the MeshReceiver.
  609. * It is ensured that SubGroups only contain objects with vertices (no need to check).
  610. *
  611. * @param result
  612. */
  613. _buildMesh: function ( result ) {
  614. let meshOutputGroups = result.subGroups;
  615. let vertexFA = new Float32Array( result.absoluteVertexCount );
  616. this.globalCounts.vertices += result.absoluteVertexCount / 3;
  617. this.globalCounts.faces += result.faceCount;
  618. this.globalCounts.doubleIndicesCount += result.doubleIndicesCount;
  619. let indexUA = ( result.absoluteIndexCount > 0 ) ? new Uint32Array( result.absoluteIndexCount ) : null;
  620. let colorFA = ( result.absoluteColorCount > 0 ) ? new Float32Array( result.absoluteColorCount ) : null;
  621. let normalFA = ( result.absoluteNormalCount > 0 ) ? new Float32Array( result.absoluteNormalCount ) : null;
  622. let uvFA = ( result.absoluteUvCount > 0 ) ? new Float32Array( result.absoluteUvCount ) : null;
  623. let haveVertexColors = colorFA !== null;
  624. let meshOutputGroup;
  625. let materialNames = [];
  626. let createMultiMaterial = ( meshOutputGroups.length > 1 );
  627. let materialIndex = 0;
  628. let materialIndexMapping = [];
  629. let selectedMaterialIndex;
  630. let materialGroup;
  631. let materialGroups = [];
  632. let vertexFAOffset = 0;
  633. let indexUAOffset = 0;
  634. let colorFAOffset = 0;
  635. let normalFAOffset = 0;
  636. let uvFAOffset = 0;
  637. let materialGroupOffset = 0;
  638. let materialGroupLength = 0;
  639. let materialOrg, material, materialName, materialNameOrg;
  640. // only one specific face type
  641. for ( let oodIndex in meshOutputGroups ) {
  642. if ( ! meshOutputGroups.hasOwnProperty( oodIndex ) ) continue;
  643. meshOutputGroup = meshOutputGroups[ oodIndex ];
  644. materialNameOrg = meshOutputGroup.materialName;
  645. if ( this.rawMesh.faceType < 4 ) {
  646. materialName = materialNameOrg + ( haveVertexColors ? '_vertexColor' : '' ) + ( meshOutputGroup.smoothingGroup === 0 ? '_flat' : '' );
  647. } else {
  648. materialName = this.rawMesh.faceType === 6 ? 'defaultPointMaterial' : 'defaultLineMaterial';
  649. }
  650. materialOrg = this.materials[ materialNameOrg ];
  651. material = this.materials[ materialName ];
  652. // both original and derived names do not lead to an existing material => need to use a default material
  653. if ( ( materialOrg === undefined || materialOrg === null ) && ( material === undefined || material === null ) ) {
  654. materialName = haveVertexColors ? 'defaultVertexColorMaterial' : 'defaultMaterial';
  655. material = this.materials[ materialName ];
  656. if ( this.logging.enabled ) {
  657. console.info( 'object_group "' + meshOutputGroup.objectName + '_' +
  658. meshOutputGroup.groupName + '" was defined with unresolvable material "' +
  659. materialNameOrg + '"! Assigning "' + materialName + '".' );
  660. }
  661. }
  662. if ( material === undefined || material === null ) {
  663. let materialCloneInstructions = {
  664. materialNameOrg: materialNameOrg,
  665. materialName: materialName,
  666. materialProperties: {
  667. vertexColors: haveVertexColors ? 2 : 0,
  668. flatShading: meshOutputGroup.smoothingGroup === 0
  669. }
  670. };
  671. let payload = {
  672. cmd: 'assetAvailable',
  673. type: 'material',
  674. materials: {
  675. materialCloneInstructions: materialCloneInstructions
  676. }
  677. };
  678. this.callbacks.onAssetAvailable( payload );
  679. // only set materials if they don't exist, yet
  680. let matCheck = this.materials[ materialName ];
  681. if ( matCheck === undefined || matCheck === null ) {
  682. this.materials[ materialName ] = materialCloneInstructions;
  683. }
  684. }
  685. if ( createMultiMaterial ) {
  686. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  687. selectedMaterialIndex = materialIndexMapping[ materialName ];
  688. if ( ! selectedMaterialIndex ) {
  689. selectedMaterialIndex = materialIndex;
  690. materialIndexMapping[ materialName ] = materialIndex;
  691. materialNames.push( materialName );
  692. materialIndex ++;
  693. }
  694. materialGroupLength = this.useIndices ? meshOutputGroup.indices.length : meshOutputGroup.vertices.length / 3;
  695. materialGroup = {
  696. start: materialGroupOffset,
  697. count: materialGroupLength,
  698. index: selectedMaterialIndex
  699. };
  700. materialGroups.push( materialGroup );
  701. materialGroupOffset += materialGroupLength;
  702. } else {
  703. materialNames.push( materialName );
  704. }
  705. vertexFA.set( meshOutputGroup.vertices, vertexFAOffset );
  706. vertexFAOffset += meshOutputGroup.vertices.length;
  707. if ( indexUA ) {
  708. indexUA.set( meshOutputGroup.indices, indexUAOffset );
  709. indexUAOffset += meshOutputGroup.indices.length;
  710. }
  711. if ( colorFA ) {
  712. colorFA.set( meshOutputGroup.colors, colorFAOffset );
  713. colorFAOffset += meshOutputGroup.colors.length;
  714. }
  715. if ( normalFA ) {
  716. normalFA.set( meshOutputGroup.normals, normalFAOffset );
  717. normalFAOffset += meshOutputGroup.normals.length;
  718. }
  719. if ( uvFA ) {
  720. uvFA.set( meshOutputGroup.uvs, uvFAOffset );
  721. uvFAOffset += meshOutputGroup.uvs.length;
  722. }
  723. if ( this.logging.enabled && this.logging.debug ) {
  724. let materialIndexLine = ( selectedMaterialIndex === undefined || selectedMaterialIndex === null ) ? '' : '\n\t\tmaterialIndex: ' + selectedMaterialIndex;
  725. let createdReport = '\tOutput Object no.: ' + this.outputObjectCount +
  726. '\n\t\tgroupName: ' + meshOutputGroup.groupName +
  727. '\n\t\tIndex: ' + meshOutputGroup.index +
  728. '\n\t\tfaceType: ' + this.rawMesh.faceType +
  729. '\n\t\tmaterialName: ' + meshOutputGroup.materialName +
  730. '\n\t\tsmoothingGroup: ' + meshOutputGroup.smoothingGroup +
  731. materialIndexLine +
  732. '\n\t\tobjectName: ' + meshOutputGroup.objectName +
  733. '\n\t\t#vertices: ' + meshOutputGroup.vertices.length / 3 +
  734. '\n\t\t#indices: ' + meshOutputGroup.indices.length +
  735. '\n\t\t#colors: ' + meshOutputGroup.colors.length / 3 +
  736. '\n\t\t#uvs: ' + meshOutputGroup.uvs.length / 2 +
  737. '\n\t\t#normals: ' + meshOutputGroup.normals.length / 3;
  738. console.debug( createdReport );
  739. }
  740. }
  741. this.outputObjectCount ++;
  742. this.callbacks.onAssetAvailable(
  743. {
  744. cmd: 'assetAvailable',
  745. type: 'mesh',
  746. progress: {
  747. numericalValue: this.globalCounts.currentByte / this.globalCounts.totalBytes
  748. },
  749. params: {
  750. meshName: result.name
  751. },
  752. materials: {
  753. multiMaterial: createMultiMaterial,
  754. materialNames: materialNames,
  755. materialGroups: materialGroups
  756. },
  757. buffers: {
  758. vertices: vertexFA,
  759. indices: indexUA,
  760. colors: colorFA,
  761. normals: normalFA,
  762. uvs: uvFA
  763. },
  764. // 0: mesh, 1: line, 2: point
  765. geometryType: this.rawMesh.faceType < 4 ? 0 : ( this.rawMesh.faceType === 6 ) ? 2 : 1
  766. },
  767. [ vertexFA.buffer ],
  768. indexUA !== null ? [ indexUA.buffer ] : null,
  769. colorFA !== null ? [ colorFA.buffer ] : null,
  770. normalFA !== null ? [ normalFA.buffer ] : null,
  771. uvFA !== null ? [ uvFA.buffer ] : null
  772. );
  773. },
  774. _finalizeParsing: function () {
  775. if ( this.logging.enabled ) console.info( 'Global output object count: ' + this.outputObjectCount );
  776. if ( this._processCompletedMesh() && this.logging.enabled ) {
  777. let parserFinalReport = 'Overall counts: ' +
  778. '\n\tVertices: ' + this.globalCounts.vertices +
  779. '\n\tFaces: ' + this.globalCounts.faces +
  780. '\n\tMultiple definitions: ' + this.globalCounts.doubleIndicesCount;
  781. console.info( parserFinalReport );
  782. }
  783. }
  784. };
  785. export { OBJLoader2Parser };