OBJLoader2.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. /**
  2. * @author Kai Salmen / https://kaisalmen.de
  3. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  4. */
  5. 'use strict';
  6. if ( THREE.OBJLoader2 === undefined ) { THREE.OBJLoader2 = {} }
  7. THREE.OBJLoader2.version = '1.0.6';
  8. /**
  9. * Use this class to load OBJ data from files or to parse OBJ data from arraybuffer or text
  10. * @class
  11. *
  12. * @param {THREE.DefaultLoadingManager} [manager] Extension of {@link THREE.DefaultLoadingManager}
  13. */
  14. THREE.OBJLoader2 = (function () {
  15. function OBJLoader2( manager ) {
  16. this.manager = ( manager == null ) ? THREE.DefaultLoadingManager : manager;
  17. this.path = '';
  18. this.fileLoader = new THREE.FileLoader( this.manager );
  19. this.meshCreator = new MeshCreator();
  20. this.parser = new Parser( this.meshCreator );
  21. this.validated = false;
  22. }
  23. /**
  24. * Base path to use
  25. * @memberOf THREE.OBJLoader2
  26. *
  27. * @param {string} path The basepath
  28. */
  29. OBJLoader2.prototype.setPath = function ( path ) {
  30. this.path = ( path == null ) ? this.path : path;
  31. };
  32. /**
  33. * Set the node where the loaded objects will be attached
  34. * @memberOf THREE.OBJLoader2
  35. *
  36. * @param {THREE.Object3D} sceneGraphBaseNode Scenegraph object where meshes will be attached
  37. */
  38. OBJLoader2.prototype.setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  39. this.meshCreator._setSceneGraphBaseNode( sceneGraphBaseNode );
  40. };
  41. /**
  42. * Set materials loaded by MTLLoader
  43. * @memberOf THREE.OBJLoader2
  44. *
  45. * @param {THREE.MTLLoader.MaterialCreator.materials[]} materials {@link THREE.MTLLoader.MaterialCreator.materials}
  46. */
  47. OBJLoader2.prototype.setMaterials = function ( materials ) {
  48. this.meshCreator._setMaterials( materials );
  49. };
  50. /**
  51. * Allows to set debug mode for the parser and the meshCreator
  52. * @memberOf THREE.OBJLoader2
  53. *
  54. * @param {boolean} parserDebug {@link Parser} will produce debug output
  55. * @param {boolean} meshCreatorDebug {@link THREE.OBJLoader2.MeshCreator} will produce debug output
  56. */
  57. OBJLoader2.prototype.setDebug = function ( parserDebug, meshCreatorDebug ) {
  58. this.parser._setDebug( parserDebug );
  59. this.meshCreator._setDebug( meshCreatorDebug );
  60. };
  61. /**
  62. * Use this convenient method to load an OBJ file at the given URL. Per default the fileLoader uses an arraybuffer
  63. * @memberOf THREE.OBJLoader2
  64. *
  65. * @param {string} url URL of the file to load
  66. * @param {callback} onLoad Called after loading was successfully completed
  67. * @param {callback} onProgress Called to report progress of loading
  68. * @param {callback} onError Called after an error occurred during loading
  69. * @param {boolean} [useArrayBuffer=true] Set this to false to force string based parsing
  70. */
  71. OBJLoader2.prototype.load = function ( url, onLoad, onProgress, onError, useArrayBuffer ) {
  72. this._validate();
  73. this.fileLoader.setPath( this.path );
  74. this.fileLoader.setResponseType( ( useArrayBuffer || useArrayBuffer == null ) ? 'arraybuffer' : 'text' );
  75. var scope = this;
  76. scope.fileLoader.load( url, function ( content ) {
  77. // only use parseText if useArrayBuffer is explicitly set to false
  78. onLoad( ( useArrayBuffer || useArrayBuffer == null ) ? scope.parse( content ) : scope.parseText( content ) );
  79. }, onProgress, onError );
  80. };
  81. /**
  82. * Default parse function: Parses OBJ file content stored in arrayBuffer and returns the sceneGraphBaseNode
  83. * @memberOf THREE.OBJLoader2
  84. *
  85. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  86. */
  87. OBJLoader2.prototype.parse = function ( arrayBuffer ) {
  88. // fast-fail on bad type
  89. if ( ! ( arrayBuffer instanceof ArrayBuffer || arrayBuffer instanceof Uint8Array ) ) {
  90. throw 'Provided input is not of type arraybuffer! Aborting...';
  91. }
  92. console.log( 'Parsing arrayBuffer...' );
  93. console.time( 'parseArrayBuffer' );
  94. this._validate();
  95. this.parser.parseArrayBuffer( arrayBuffer );
  96. var sceneGraphAttach = this._finalize();
  97. console.timeEnd( 'parseArrayBuffer' );
  98. return sceneGraphAttach;
  99. };
  100. /**
  101. * Legacy parse function: Parses OBJ file content stored in string and returns the sceneGraphBaseNode
  102. * @memberOf THREE.OBJLoader2
  103. *
  104. * @param {string} text OBJ data as string
  105. */
  106. OBJLoader2.prototype.parseText = function ( text ) {
  107. // fast-fail on bad type
  108. if ( ! ( typeof( text ) === 'string' || text instanceof String ) ) {
  109. throw 'Provided input is not of type String! Aborting...';
  110. }
  111. console.log( 'Parsing text...' );
  112. console.time( 'parseText' );
  113. this._validate();
  114. this.parser.parseText( text );
  115. var sceneGraphBaseNode = this._finalize();
  116. console.timeEnd( 'parseText' );
  117. return sceneGraphBaseNode;
  118. };
  119. OBJLoader2.prototype._validate = function () {
  120. if ( this.validated ) return;
  121. this.fileLoader = ( this.fileLoader == null ) ? new THREE.FileLoader( this.manager ) : this.fileLoader;
  122. this.setPath();
  123. this.parser._validate();
  124. this.meshCreator._validate();
  125. this.validated = true;
  126. };
  127. OBJLoader2.prototype._finalize = function () {
  128. console.log( 'Global output object count: ' + this.meshCreator.globalObjectCount );
  129. this.parser._finalize();
  130. this.fileLoader = null;
  131. var sceneGraphBaseNode = this.meshCreator.sceneGraphBaseNode;
  132. this.meshCreator._finalize();
  133. this.validated = false;
  134. return sceneGraphBaseNode;
  135. };
  136. /**
  137. * Constants used by THREE.OBJLoader2
  138. */
  139. var Consts = {
  140. CODE_LF: 10,
  141. CODE_CR: 13,
  142. CODE_SPACE: 32,
  143. CODE_SLASH: 47,
  144. STRING_LF: '\n',
  145. STRING_CR: '\r',
  146. STRING_SPACE: ' ',
  147. STRING_SLASH: '/',
  148. LINE_F: 'f',
  149. LINE_G: 'g',
  150. LINE_L: 'l',
  151. LINE_O: 'o',
  152. LINE_S: 's',
  153. LINE_V: 'v',
  154. LINE_VT: 'vt',
  155. LINE_VN: 'vn',
  156. LINE_MTLLIB: 'mtllib',
  157. LINE_USEMTL: 'usemtl',
  158. /*
  159. * Build Face/Quad: first element in indexArray is the line identification, therefore offset of one needs to be taken into account
  160. * N-Gons are not supported
  161. * Quad Faces: FaceA: 0, 1, 2 FaceB: 2, 3, 0
  162. *
  163. * 0: "f vertex/uv/normal vertex/uv/normal vertex/uv/normal (vertex/uv/normal)"
  164. * 1: "f vertex/uv vertex/uv vertex/uv (vertex/uv )"
  165. * 2: "f vertex//normal vertex//normal vertex//normal (vertex//normal )"
  166. * 3: "f vertex vertex vertex (vertex )"
  167. *
  168. * @param indexArray
  169. * @param faceType
  170. */
  171. QUAD_INDICES_1: [ 1, 2, 3, 3, 4, 1 ],
  172. QUAD_INDICES_2: [ 1, 3, 5, 5, 7, 1 ],
  173. QUAD_INDICES_3: [ 1, 4, 7, 7, 10, 1 ]
  174. };
  175. /**
  176. * Parse OBJ data either from ArrayBuffer or string
  177. * @class
  178. */
  179. var Parser = (function () {
  180. function Parser( meshCreator ) {
  181. this.meshCreator = meshCreator;
  182. this.rawObject = null;
  183. this.inputObjectCount = 1;
  184. this.debug = false;
  185. }
  186. Parser.prototype._setDebug = function ( debug ) {
  187. this.debug = ( debug == null ) ? this.debug : debug;
  188. };
  189. Parser.prototype._validate = function () {
  190. this.rawObject = new RawObject();
  191. this.inputObjectCount = 1;
  192. };
  193. /**
  194. * Parse the provided arraybuffer
  195. * @memberOf Parser
  196. *
  197. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  198. */
  199. Parser.prototype.parseArrayBuffer = function ( arrayBuffer ) {
  200. var arrayBufferView = new Uint8Array( arrayBuffer );
  201. var length = arrayBufferView.byteLength;
  202. var buffer = new Array( 32 );
  203. var bufferPointer = 0;
  204. var slashes = new Array( 32 );
  205. var slashesPointer = 0;
  206. var reachedFaces = false;
  207. var code;
  208. var word = '';
  209. for ( var i = 0; i < length; i++ ) {
  210. code = arrayBufferView[ i ];
  211. switch ( code ) {
  212. case Consts.CODE_SPACE:
  213. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  214. word = '';
  215. break;
  216. case Consts.CODE_SLASH:
  217. slashes[ slashesPointer++ ] = i;
  218. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  219. word = '';
  220. break;
  221. case Consts.CODE_LF:
  222. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  223. word = '';
  224. reachedFaces = this._processLine( buffer, bufferPointer, slashes, slashesPointer, reachedFaces );
  225. slashesPointer = 0;
  226. bufferPointer = 0;
  227. break;
  228. case Consts.CODE_CR:
  229. break;
  230. default:
  231. word += String.fromCharCode( code );
  232. break;
  233. }
  234. }
  235. };
  236. /**
  237. * Parse the provided text
  238. * @memberOf Parser
  239. *
  240. * @param {string} text OBJ data as string
  241. */
  242. Parser.prototype.parseText = function ( text ) {
  243. var length = text.length;
  244. var buffer = new Array( 32 );
  245. var bufferPointer = 0;
  246. var slashes = new Array( 32 );
  247. var slashesPointer = 0;
  248. var reachedFaces = false;
  249. var char;
  250. var word = '';
  251. for ( var i = 0; i < length; i++ ) {
  252. char = text[ i ];
  253. switch ( char ) {
  254. case Consts.STRING_SPACE:
  255. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  256. word = '';
  257. break;
  258. case Consts.STRING_SLASH:
  259. slashes[ slashesPointer++ ] = i;
  260. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  261. word = '';
  262. break;
  263. case Consts.STRING_LF:
  264. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  265. word = '';
  266. reachedFaces = this._processLine( buffer, bufferPointer, slashes, slashesPointer, reachedFaces );
  267. slashesPointer = 0;
  268. bufferPointer = 0;
  269. break;
  270. case Consts.STRING_CR:
  271. break;
  272. default:
  273. word += char;
  274. }
  275. }
  276. };
  277. Parser.prototype._processLine = function ( buffer, bufferPointer, slashes, slashesPointer, reachedFaces ) {
  278. if ( bufferPointer < 1 ) return reachedFaces;
  279. var bufferLength = bufferPointer - 1;
  280. switch ( buffer[ 0 ] ) {
  281. case Consts.LINE_V:
  282. // object complete instance required if reached faces already (= reached next block of v)
  283. if ( reachedFaces ) {
  284. this._processCompletedObject( null, this.rawObject.groupName );
  285. reachedFaces = false;
  286. }
  287. this.rawObject._pushVertex( buffer );
  288. break;
  289. case Consts.LINE_VT:
  290. this.rawObject._pushUv( buffer );
  291. break;
  292. case Consts.LINE_VN:
  293. this.rawObject._pushNormal( buffer );
  294. break;
  295. case Consts.LINE_F:
  296. reachedFaces = true;
  297. /*
  298. * 0: "f vertex/uv/normal ..."
  299. * 1: "f vertex/uv ..."
  300. * 2: "f vertex//normal ..."
  301. * 3: "f vertex ..."
  302. */
  303. var haveQuad = bufferLength % 4 === 0;
  304. if ( slashesPointer > 1 && ( slashes[ 1 ] - slashes[ 0 ] ) === 1 ) {
  305. if ( haveQuad ) {
  306. this.rawObject._buildQuadVVn( buffer );
  307. } else {
  308. this.rawObject._buildFaceVVn( buffer );
  309. }
  310. } else if ( bufferLength === slashesPointer * 2 ) {
  311. if ( haveQuad ) {
  312. this.rawObject._buildQuadVVt( buffer );
  313. } else {
  314. this.rawObject._buildFaceVVt( buffer );
  315. }
  316. } else if ( bufferLength * 2 === slashesPointer * 3 ) {
  317. if ( haveQuad ) {
  318. this.rawObject._buildQuadVVtVn( buffer );
  319. } else {
  320. this.rawObject._buildFaceVVtVn( buffer );
  321. }
  322. } else {
  323. if ( haveQuad ) {
  324. this.rawObject._buildQuadV( buffer );
  325. } else {
  326. this.rawObject._buildFaceV( buffer );
  327. }
  328. }
  329. break;
  330. case Consts.LINE_L:
  331. if ( bufferLength === slashesPointer * 2 ) {
  332. this.rawObject._buildLineVvt( buffer );
  333. } else {
  334. this.rawObject._buildLineV( buffer );
  335. }
  336. break;
  337. case Consts.LINE_S:
  338. this.rawObject._pushSmoothingGroup( buffer[ 1 ] );
  339. break;
  340. case Consts.LINE_G:
  341. this._processCompletedGroup( buffer[ 1 ] );
  342. break;
  343. case Consts.LINE_O:
  344. if ( this.rawObject.vertices.length > 0 ) {
  345. this._processCompletedObject( buffer[ 1 ], null );
  346. reachedFaces = false;
  347. } else {
  348. this.rawObject._pushObject( buffer[ 1 ] );
  349. }
  350. break;
  351. case Consts.LINE_MTLLIB:
  352. this.rawObject._pushMtllib( buffer[ 1 ] );
  353. break;
  354. case Consts.LINE_USEMTL:
  355. this.rawObject._pushUsemtl( buffer[ 1 ] );
  356. break;
  357. default:
  358. break;
  359. }
  360. return reachedFaces;
  361. };
  362. Parser.prototype._processCompletedObject = function ( objectName, groupName ) {
  363. this.rawObject._finalize( this.meshCreator, this.inputObjectCount, this.debug );
  364. this.inputObjectCount++;
  365. this.rawObject = this.rawObject._newInstanceFromObject( objectName, groupName );
  366. };
  367. Parser.prototype._processCompletedGroup = function ( groupName ) {
  368. var notEmpty = this.rawObject._finalize( this.meshCreator, this.inputObjectCount, this.debug );
  369. if ( notEmpty ) {
  370. this.inputObjectCount ++;
  371. this.rawObject = this.rawObject._newInstanceFromGroup( groupName );
  372. } else {
  373. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  374. this.rawObject._pushGroup( groupName );
  375. }
  376. };
  377. Parser.prototype._finalize = function () {
  378. this.rawObject._finalize( this.meshCreator, this.inputObjectCount, this.debug );
  379. this.inputObjectCount++;
  380. };
  381. return Parser;
  382. })();
  383. /**
  384. * {@link RawObject} is only used by {@link Parser}.
  385. * The user of OBJLoader2 does not need to care about this class.
  386. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  387. */
  388. var RawObject = (function () {
  389. function RawObject( objectName, groupName, mtllibName ) {
  390. this.globalVertexOffset = 1;
  391. this.globalUvOffset = 1;
  392. this.globalNormalOffset = 1;
  393. this.vertices = [];
  394. this.normals = [];
  395. this.uvs = [];
  396. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  397. this.mtllibName = ( mtllibName != null ) ? mtllibName : 'none';
  398. this.objectName = ( objectName != null ) ? objectName : 'none';
  399. this.groupName = ( groupName != null ) ? groupName : 'none';
  400. this.activeMtlName = 'none';
  401. this.activeSmoothingGroup = 1;
  402. this.mtlCount = 0;
  403. this.smoothingGroupCount = 0;
  404. this.rawObjectDescriptions = [];
  405. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  406. var index = this._buildIndex( this.activeMtlName, this.activeSmoothingGroup );
  407. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  408. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  409. }
  410. RawObject.prototype._buildIndex = function ( materialName, smoothingGroup) {
  411. return materialName + '|' + smoothingGroup;
  412. };
  413. RawObject.prototype._newInstanceFromObject = function ( objectName, groupName ) {
  414. var newRawObject = new RawObject( objectName, groupName, this.mtllibName );
  415. // move indices forward
  416. newRawObject.globalVertexOffset = this.globalVertexOffset + this.vertices.length / 3;
  417. newRawObject.globalUvOffset = this.globalUvOffset + this.uvs.length / 2;
  418. newRawObject.globalNormalOffset = this.globalNormalOffset + this.normals.length / 3;
  419. return newRawObject;
  420. };
  421. RawObject.prototype._newInstanceFromGroup = function ( groupName ) {
  422. var newRawObject = new RawObject( this.objectName, groupName, this.mtllibName );
  423. // keep current buffers and indices forward
  424. newRawObject.vertices = this.vertices;
  425. newRawObject.uvs = this.uvs;
  426. newRawObject.normals = this.normals;
  427. newRawObject.globalVertexOffset = this.globalVertexOffset;
  428. newRawObject.globalUvOffset = this.globalUvOffset;
  429. newRawObject.globalNormalOffset = this.globalNormalOffset;
  430. return newRawObject;
  431. };
  432. RawObject.prototype._pushVertex = function ( buffer ) {
  433. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  434. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  435. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  436. };
  437. RawObject.prototype._pushUv = function ( buffer ) {
  438. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  439. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  440. };
  441. RawObject.prototype._pushNormal = function ( buffer ) {
  442. this.normals.push( parseFloat( buffer[ 1 ] ) );
  443. this.normals.push( parseFloat( buffer[ 2 ] ) );
  444. this.normals.push( parseFloat( buffer[ 3 ] ) );
  445. };
  446. RawObject.prototype._pushObject = function ( objectName ) {
  447. this.objectName = objectName;
  448. };
  449. RawObject.prototype._pushMtllib = function ( mtllibName ) {
  450. this.mtllibName = mtllibName;
  451. };
  452. RawObject.prototype._pushGroup = function ( groupName ) {
  453. this.groupName = groupName;
  454. this._verifyIndex();
  455. };
  456. RawObject.prototype._pushUsemtl = function ( mtlName ) {
  457. if ( this.activeMtlName === mtlName || mtlName == null ) return;
  458. this.activeMtlName = mtlName;
  459. this.mtlCount++;
  460. this._verifyIndex();
  461. };
  462. RawObject.prototype._pushSmoothingGroup = function ( activeSmoothingGroup ) {
  463. var normalized = activeSmoothingGroup === 'off' ? 0 : activeSmoothingGroup;
  464. if ( this.activeSmoothingGroup === normalized ) return;
  465. this.activeSmoothingGroup = normalized;
  466. this.smoothingGroupCount++;
  467. this._verifyIndex();
  468. };
  469. RawObject.prototype._verifyIndex = function () {
  470. var index = this._buildIndex( this.activeMtlName, ( this.activeSmoothingGroup === 0 ) ? 0 : 1 );
  471. if ( this.rawObjectDescriptions[ index ] == null ) {
  472. this.rawObjectDescriptionInUse = this.rawObjectDescriptions[ index ] =
  473. new RawObjectDescription(
  474. this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup
  475. );
  476. } else {
  477. this.rawObjectDescriptionInUse = this.rawObjectDescriptions[ index ];
  478. }
  479. };
  480. RawObject.prototype._buildQuadVVtVn = function ( indexArray ) {
  481. for ( var i = 0; i < 6; i ++ ) {
  482. this._attachFaceV_( indexArray[ Consts.QUAD_INDICES_3[ i ] ] );
  483. this._attachFaceVt( indexArray[ Consts.QUAD_INDICES_3[ i ] + 1 ] );
  484. this._attachFaceVn( indexArray[ Consts.QUAD_INDICES_3[ i ] + 2 ] );
  485. }
  486. };
  487. RawObject.prototype._buildQuadVVt = function ( indexArray ) {
  488. for ( var i = 0; i < 6; i ++ ) {
  489. this._attachFaceV_( indexArray[ Consts.QUAD_INDICES_2[ i ] ] );
  490. this._attachFaceVt( indexArray[ Consts.QUAD_INDICES_2[ i ] + 1 ] );
  491. }
  492. };
  493. RawObject.prototype._buildQuadVVn = function ( indexArray ) {
  494. for ( var i = 0; i < 6; i ++ ) {
  495. this._attachFaceV_( indexArray[ Consts.QUAD_INDICES_2[ i ] ] );
  496. this._attachFaceVn( indexArray[ Consts.QUAD_INDICES_2[ i ] + 1 ] );
  497. }
  498. };
  499. RawObject.prototype._buildQuadV = function ( indexArray ) {
  500. for ( var i = 0; i < 6; i ++ ) {
  501. this._attachFaceV_( indexArray[ Consts.QUAD_INDICES_1[ i ] ] );
  502. }
  503. };
  504. RawObject.prototype._buildFaceVVtVn = function ( indexArray ) {
  505. for ( var i = 1; i < 10; i += 3 ) {
  506. this._attachFaceV_( indexArray[ i ] );
  507. this._attachFaceVt( indexArray[ i + 1 ] );
  508. this._attachFaceVn( indexArray[ i + 2 ] );
  509. }
  510. };
  511. RawObject.prototype._buildFaceVVt = function ( indexArray ) {
  512. for ( var i = 1; i < 7; i += 2 ) {
  513. this._attachFaceV_( indexArray[ i ] );
  514. this._attachFaceVt( indexArray[ i + 1 ] );
  515. }
  516. };
  517. RawObject.prototype._buildFaceVVn = function ( indexArray ) {
  518. for ( var i = 1; i < 7; i += 2 ) {
  519. this._attachFaceV_( indexArray[ i ] );
  520. this._attachFaceVn( indexArray[ i + 1 ] );
  521. }
  522. };
  523. RawObject.prototype._buildFaceV = function ( indexArray ) {
  524. for ( var i = 1; i < 4; i ++ ) {
  525. this._attachFaceV_( indexArray[ i ] );
  526. }
  527. };
  528. RawObject.prototype._attachFaceV_ = function ( faceIndex ) {
  529. var faceIndexInt = parseInt( faceIndex );
  530. var index = ( faceIndexInt - this.globalVertexOffset ) * 3;
  531. var rodiu = this.rawObjectDescriptionInUse;
  532. rodiu.vertices.push( this.vertices[ index++ ] );
  533. rodiu.vertices.push( this.vertices[ index++ ] );
  534. rodiu.vertices.push( this.vertices[ index ] );
  535. };
  536. RawObject.prototype._attachFaceVt = function ( faceIndex ) {
  537. var faceIndexInt = parseInt( faceIndex );
  538. var index = ( faceIndexInt - this.globalUvOffset ) * 2;
  539. var rodiu = this.rawObjectDescriptionInUse;
  540. rodiu.uvs.push( this.uvs[ index++ ] );
  541. rodiu.uvs.push( this.uvs[ index ] );
  542. };
  543. RawObject.prototype._attachFaceVn = function ( faceIndex ) {
  544. var faceIndexInt = parseInt( faceIndex );
  545. var index = ( faceIndexInt - this.globalNormalOffset ) * 3;
  546. var rodiu = this.rawObjectDescriptionInUse;
  547. rodiu.normals.push( this.normals[ index++ ] );
  548. rodiu.normals.push( this.normals[ index++ ] );
  549. rodiu.normals.push( this.normals[ index ] );
  550. };
  551. /*
  552. * Support for lines with or without texture. irst element in indexArray is the line identification
  553. * 0: "f vertex/uv vertex/uv ..."
  554. * 1: "f vertex vertex ..."
  555. */
  556. RawObject.prototype._buildLineVvt = function ( lineArray ) {
  557. var length = lineArray.length;
  558. for ( var i = 1; i < length; i ++ ) {
  559. this.vertices.push( parseInt( lineArray[ i ] ) );
  560. this.uvs.push( parseInt( lineArray[ i ] ) );
  561. }
  562. };
  563. RawObject.prototype._buildLineV = function ( lineArray ) {
  564. var length = lineArray.length;
  565. for ( var i = 1; i < length; i++ ) {
  566. this.vertices.push( parseInt( lineArray[ i ] ) );
  567. }
  568. };
  569. /**
  570. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  571. */
  572. RawObject.prototype._finalize = function ( meshCreator, inputObjectCount, debug ) {
  573. var temp = this.rawObjectDescriptions;
  574. this.rawObjectDescriptions = [];
  575. var rawObjectDescription;
  576. var index = 0;
  577. var absoluteVertexCount = 0;
  578. var absoluteNormalCount = 0;
  579. var absoluteUvCount = 0;
  580. for ( var name in temp ) {
  581. rawObjectDescription = temp[ name ];
  582. if ( rawObjectDescription.vertices.length > 0 ) {
  583. if ( rawObjectDescription.objectName === 'none' ) rawObjectDescription.objectName = rawObjectDescription.groupName;
  584. this.rawObjectDescriptions[ index++ ] = rawObjectDescription;
  585. absoluteVertexCount += rawObjectDescription.vertices.length;
  586. absoluteUvCount += rawObjectDescription.uvs.length;
  587. absoluteNormalCount += rawObjectDescription.normals.length;
  588. }
  589. }
  590. // don not continue if no result
  591. var notEmpty = false;
  592. if ( index > 0 ) {
  593. if ( debug ) this._createReport( inputObjectCount, true );
  594. meshCreator._buildMesh(
  595. this.rawObjectDescriptions,
  596. inputObjectCount,
  597. absoluteVertexCount,
  598. absoluteNormalCount,
  599. absoluteUvCount
  600. );
  601. notEmpty = true;
  602. }
  603. return notEmpty;
  604. };
  605. RawObject.prototype._createReport = function ( inputObjectCount, printDirectly ) {
  606. var report = {
  607. name: this.objectName ? this.objectName : 'groups',
  608. mtllibName: this.mtllibName,
  609. vertexCount: this.vertices.length / 3,
  610. normalCount: this.normals.length / 3,
  611. uvCount: this.uvs.length / 2,
  612. smoothingGroupCount: this.smoothingGroupCount,
  613. mtlCount: this.mtlCount,
  614. rawObjectDescriptions: this.rawObjectDescriptions.length
  615. };
  616. if ( printDirectly ) {
  617. console.log( 'Input Object number: ' + inputObjectCount + ' Object name: ' + report.name );
  618. console.log( 'Mtllib name: ' + report.mtllibName );
  619. console.log( 'Vertex count: ' + report.vertexCount );
  620. console.log( 'Normal count: ' + report.normalCount );
  621. console.log( 'UV count: ' + report.uvCount );
  622. console.log( 'SmoothingGroup count: ' + report.smoothingGroupCount );
  623. console.log( 'Material count: ' + report.mtlCount );
  624. console.log( 'Real RawObjectDescription count: ' + report.rawObjectDescriptions );
  625. console.log( '' );
  626. }
  627. return report;
  628. };
  629. return RawObject;
  630. })();
  631. /**
  632. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  633. * @class
  634. *
  635. * @param {string} objectName Name of the mesh
  636. * @param {string} groupName Name of the group
  637. * @param {string} materialName Name of the material
  638. * @param {number} smoothingGroup Normalized smoothingGroup (0: THREE.FlatShading, 1: THREE.SmoothShading)
  639. */
  640. var RawObjectDescription = (function () {
  641. function RawObjectDescription( objectName, groupName, materialName, smoothingGroup ) {
  642. this.objectName = objectName;
  643. this.groupName = groupName;
  644. this.materialName = materialName;
  645. this.smoothingGroup = smoothingGroup;
  646. this.vertices = [];
  647. this.uvs = [];
  648. this.normals = [];
  649. }
  650. return RawObjectDescription;
  651. })();
  652. /**
  653. * MeshCreator is used to transform RawObjectDescriptions to THREE.Mesh
  654. *
  655. * @class
  656. */
  657. var MeshCreator = (function () {
  658. function MeshCreator() {
  659. this.sceneGraphBaseNode = null;
  660. this.materials = null;
  661. this.debug = false;
  662. this.globalObjectCount = 1;
  663. this.validated = false;
  664. }
  665. MeshCreator.prototype._setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  666. this.sceneGraphBaseNode = ( sceneGraphBaseNode == null ) ? ( this.sceneGraphBaseNode == null ? new THREE.Group() : this.sceneGraphBaseNode ) : sceneGraphBaseNode;
  667. };
  668. MeshCreator.prototype._setMaterials = function ( materials ) {
  669. this.materials = ( materials == null ) ? ( this.materials == null ? { materials: [] } : this.materials ) : materials;
  670. };
  671. MeshCreator.prototype._setDebug = function ( debug ) {
  672. this.debug = ( debug == null ) ? this.debug : debug;
  673. };
  674. MeshCreator.prototype._validate = function () {
  675. if ( this.validated ) return;
  676. this._setSceneGraphBaseNode( null );
  677. this._setMaterials( null );
  678. this._setDebug( null );
  679. this.globalObjectCount = 1;
  680. };
  681. MeshCreator.prototype._finalize = function () {
  682. this.sceneGraphBaseNode = null;
  683. this.materials = null;
  684. this.validated = false;
  685. };
  686. /**
  687. * This is an internal function, but due to its importance to Parser it is documented.
  688. * RawObjectDescriptions are transformed to THREE.Mesh.
  689. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  690. * This method shall be overridden by the web worker implementation
  691. *
  692. * @param {RawObjectDescription[]} rawObjectDescriptions Array of descriptive information and data (vertices, normals, uvs) about the parsed object(s)
  693. * @param {number} inputObjectCount Number of objects already retrieved from OBJ
  694. * @param {number} absoluteVertexCount Sum of all vertices of all rawObjectDescriptions
  695. * @param {number} absoluteNormalCount Sum of all normals of all rawObjectDescriptions
  696. * @param {number} absoluteUvCount Sum of all uvs of all rawObjectDescriptions
  697. */
  698. MeshCreator.prototype._buildMesh = function ( rawObjectDescriptions, inputObjectCount, absoluteVertexCount, absoluteNormalCount, absoluteUvCount ) {
  699. if ( this.debug ) console.log( 'MeshCreator.buildRawMeshData:\nInput object no.: ' + inputObjectCount );
  700. var bufferGeometry = new THREE.BufferGeometry();
  701. var vertexBA = new THREE.BufferAttribute( new Float32Array( absoluteVertexCount ), 3 );
  702. bufferGeometry.addAttribute( 'position', vertexBA );
  703. var normalBA;
  704. if ( absoluteNormalCount > 0 ) {
  705. normalBA = new THREE.BufferAttribute( new Float32Array( absoluteNormalCount ), 3 );
  706. bufferGeometry.addAttribute( 'normal', normalBA );
  707. }
  708. var uvBA;
  709. if ( absoluteUvCount > 0 ) {
  710. uvBA = new THREE.BufferAttribute( new Float32Array( absoluteUvCount ), 2 );
  711. bufferGeometry.addAttribute( 'uv', uvBA );
  712. }
  713. if ( this.debug ) console.log( 'Creating Multi-Material for object no.: ' + this.globalObjectCount );
  714. var rawObjectDescription;
  715. var material;
  716. var materialName;
  717. var createMultiMaterial = rawObjectDescriptions.length > 1;
  718. var materials = [];
  719. var materialIndex = 0;
  720. var materialIndexMapping = [];
  721. var selectedMaterialIndex;
  722. var vertexBAOffset = 0;
  723. var vertexGroupOffset = 0;
  724. var vertexLength;
  725. var normalOffset = 0;
  726. var uvOffset = 0;
  727. for ( var oodIndex in rawObjectDescriptions ) {
  728. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  729. materialName = rawObjectDescription.materialName;
  730. material = this.materials[ materialName ];
  731. if ( ! material ) {
  732. material = this.materials[ 'defaultMaterial' ];
  733. if ( ! material ) {
  734. material = new THREE.MeshStandardMaterial( { color: 0xDCF1FF} );
  735. material.name = 'defaultMaterial';
  736. this.materials[ 'defaultMaterial' ] = material;
  737. }
  738. console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName + '" was defined without material! Assigning "defaultMaterial".' );
  739. }
  740. // clone material in case flat shading is needed due to smoothingGroup 0
  741. if ( rawObjectDescription.smoothingGroup === 0 ) {
  742. materialName = material.name + '_flat';
  743. var materialClone = this.materials[ materialName ];
  744. if ( ! materialClone ) {
  745. materialClone = material.clone();
  746. materialClone.name = materialName;
  747. materialClone.shading = THREE.FlatShading;
  748. this.materials[ materialName ] = name;
  749. }
  750. }
  751. vertexLength = rawObjectDescription.vertices.length;
  752. if ( createMultiMaterial ) {
  753. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  754. selectedMaterialIndex = materialIndexMapping[ materialName ];
  755. if ( ! selectedMaterialIndex ) {
  756. selectedMaterialIndex = materialIndex;
  757. materialIndexMapping[ materialName ] = materialIndex;
  758. materials.push( material );
  759. materialIndex++;
  760. }
  761. bufferGeometry.addGroup( vertexGroupOffset, vertexLength / 3, selectedMaterialIndex );
  762. vertexGroupOffset += vertexLength / 3;
  763. }
  764. vertexBA.set( rawObjectDescription.vertices, vertexBAOffset );
  765. vertexBAOffset += vertexLength;
  766. if ( normalBA ) {
  767. normalBA.set( rawObjectDescription.normals, normalOffset );
  768. normalOffset += rawObjectDescription.normals.length;
  769. }
  770. if ( uvBA ) {
  771. uvBA.set( rawObjectDescription.uvs, uvOffset );
  772. uvOffset += rawObjectDescription.uvs.length;
  773. }
  774. if ( this.debug ) this._printReport( rawObjectDescription, selectedMaterialIndex );
  775. }
  776. if ( ! normalBA ) bufferGeometry.computeVertexNormals();
  777. if ( createMultiMaterial ) material = new THREE.MultiMaterial( materials );
  778. var mesh = new THREE.Mesh( bufferGeometry, material );
  779. this.sceneGraphBaseNode.add( mesh );
  780. this.globalObjectCount++;
  781. };
  782. MeshCreator.prototype._printReport = function ( rawObjectDescription, selectedMaterialIndex ) {
  783. console.log(
  784. ' Output Object no.: ' + this.globalObjectCount +
  785. '\n objectName: ' + rawObjectDescription.objectName +
  786. '\n groupName: ' + rawObjectDescription.groupName +
  787. '\n materialName: ' + rawObjectDescription.materialName +
  788. '\n materialIndex: ' + selectedMaterialIndex +
  789. '\n smoothingGroup: ' + rawObjectDescription.smoothingGroup +
  790. '\n #vertices: ' + rawObjectDescription.vertices.length / 3 +
  791. '\n #uvs: ' + rawObjectDescription.uvs.length / 2 +
  792. '\n #normals: ' + rawObjectDescription.normals.length / 3
  793. );
  794. };
  795. return MeshCreator;
  796. })();
  797. OBJLoader2.prototype._buildWebWorkerCode = function ( funcBuildObject, funcBuildSingelton ) {
  798. var workerCode = '';
  799. workerCode += funcBuildObject( 'Consts', Consts );
  800. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  801. workerCode += funcBuildSingelton( 'RawObject', 'RawObject', RawObject );
  802. workerCode += funcBuildSingelton( 'RawObjectDescription', 'RawObjectDescription', RawObjectDescription );
  803. return workerCode;
  804. };
  805. return OBJLoader2;
  806. })();