OBJLoader2Parser.js 26 KB

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