OBJLoader2Parser.js 29 KB

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