OBJLoader2Parser.js 26 KB

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