OBJLoader2.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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. /**
  8. * Use this class to load OBJ data from files or to parse OBJ data from arraybuffer or text
  9. * @class
  10. *
  11. * @param {THREE.DefaultLoadingManager} [manager] The loadingManager for the loader to use. Default is {@link THREE.DefaultLoadingManager}
  12. */
  13. THREE.OBJLoader2 = (function () {
  14. var OBJLOADER2_VERSION = '1.3.1';
  15. function OBJLoader2( manager ) {
  16. console.log( "Using THREE.OBJLoader2 version: " + OBJLOADER2_VERSION );
  17. this.manager = Validator.verifyInput( manager, THREE.DefaultLoadingManager );
  18. this.path = '';
  19. this.fileLoader = new THREE.FileLoader( this.manager );
  20. this.meshCreator = new MeshCreator();
  21. this.parser = new Parser( this.meshCreator );
  22. this.validated = false;
  23. }
  24. /**
  25. * Base path to use.
  26. * @memberOf THREE.OBJLoader2
  27. *
  28. * @param {string} path The basepath
  29. */
  30. OBJLoader2.prototype.setPath = function ( path ) {
  31. this.path = Validator.verifyInput( path, this.path );
  32. };
  33. /**
  34. * Set the node where the loaded objects will be attached.
  35. * @memberOf THREE.OBJLoader2
  36. *
  37. * @param {THREE.Object3D} sceneGraphBaseNode Scenegraph object where meshes will be attached
  38. */
  39. OBJLoader2.prototype.setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  40. this.meshCreator.setSceneGraphBaseNode( sceneGraphBaseNode );
  41. };
  42. /**
  43. * Set materials loaded by MTLLoader or any other supplier of an Array of {@link THREE.Material}.
  44. * @memberOf THREE.OBJLoader2
  45. *
  46. * @param {THREE.Material[]} materials Array of {@link THREE.Material} from MTLLoader
  47. */
  48. OBJLoader2.prototype.setMaterials = function ( materials ) {
  49. this.meshCreator.setMaterials( materials );
  50. };
  51. /**
  52. * Allows to set debug mode for the parser and the meshCreator.
  53. * @memberOf THREE.OBJLoader2
  54. *
  55. * @param {boolean} parserDebug Internal Parser will produce debug output
  56. * @param {boolean} meshCreatorDebug Internal MeshCreator will produce debug output
  57. */
  58. OBJLoader2.prototype.setDebug = function ( parserDebug, meshCreatorDebug ) {
  59. this.parser.setDebug( parserDebug );
  60. this.meshCreator.setDebug( meshCreatorDebug );
  61. };
  62. /**
  63. * Use this convenient method to load an OBJ file at the given URL. Per default the fileLoader uses an arraybuffer
  64. * @memberOf THREE.OBJLoader2
  65. *
  66. * @param {string} url URL of the file to load
  67. * @param {callback} onLoad Called after loading was successfully completed
  68. * @param {callback} onProgress Called to report progress of loading. The argument will be the XMLHttpRequest instance, which contains {integer total} and {integer loaded} bytes.
  69. * @param {callback} onError Called after an error occurred during loading
  70. * @param {boolean} [useArrayBuffer=true] Set this to false to force string based parsing
  71. */
  72. OBJLoader2.prototype.load = function ( url, onLoad, onProgress, onError, useArrayBuffer ) {
  73. this._validate();
  74. this.fileLoader.setPath( this.path );
  75. this.fileLoader.setResponseType( useArrayBuffer !== false ? 'arraybuffer' : 'text' );
  76. var scope = this;
  77. scope.fileLoader.load( url, function ( content ) {
  78. // only use parseText if useArrayBuffer is explicitly set to false
  79. onLoad( useArrayBuffer !== false ? scope.parse( content ) : scope.parseText( content ) );
  80. }, onProgress, onError );
  81. };
  82. /**
  83. * Default parse function: Parses OBJ file content stored in arrayBuffer and returns the sceneGraphBaseNode
  84. * @memberOf THREE.OBJLoader2
  85. *
  86. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  87. */
  88. OBJLoader2.prototype.parse = function ( arrayBuffer ) {
  89. // fast-fail on bad type
  90. if ( ! ( arrayBuffer instanceof ArrayBuffer || arrayBuffer instanceof Uint8Array ) ) {
  91. throw 'Provided input is not of type arraybuffer! Aborting...';
  92. }
  93. console.log( 'Parsing arrayBuffer...' );
  94. console.time( 'parseArrayBuffer' );
  95. this._validate();
  96. this.parser.parseArrayBuffer( arrayBuffer );
  97. var sceneGraphAttach = this._finalize();
  98. console.timeEnd( 'parseArrayBuffer' );
  99. return sceneGraphAttach;
  100. };
  101. /**
  102. * Legacy parse function: Parses OBJ file content stored in string and returns the sceneGraphBaseNode
  103. * @memberOf THREE.OBJLoader2
  104. *
  105. * @param {string} text OBJ data as string
  106. */
  107. OBJLoader2.prototype.parseText = function ( text ) {
  108. // fast-fail on bad type
  109. if ( ! ( typeof( text ) === 'string' || text instanceof String ) ) {
  110. throw 'Provided input is not of type String! Aborting...';
  111. }
  112. console.log( 'Parsing text...' );
  113. console.time( 'parseText' );
  114. this._validate();
  115. this.parser.parseText( text );
  116. var sceneGraphBaseNode = this._finalize();
  117. console.timeEnd( 'parseText' );
  118. return sceneGraphBaseNode;
  119. };
  120. OBJLoader2.prototype._validate = function () {
  121. if ( this.validated ) return;
  122. this.fileLoader = Validator.verifyInput( this.fileLoader, new THREE.FileLoader( this.manager ) );
  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. var Validator = {
  176. /**
  177. * If given input is null or undefined, false is returned otherwise true.
  178. *
  179. * @param input Anything
  180. * @returns {boolean}
  181. */
  182. isValid: function( input ) {
  183. return ( input !== null && input !== undefined );
  184. },
  185. /**
  186. * If given input is null or undefined, the defaultValue is returned otherwise the given input.
  187. *
  188. * @param input Anything
  189. * @param defaultValue Anything
  190. * @returns {*}
  191. */
  192. verifyInput: function( input, defaultValue ) {
  193. return ( input === null || input === undefined ) ? defaultValue : input;
  194. }
  195. };
  196. OBJLoader2.prototype._getValidator = function () {
  197. return Validator;
  198. };
  199. /**
  200. * Parse OBJ data either from ArrayBuffer or string
  201. * @class
  202. */
  203. var Parser = (function () {
  204. function Parser( meshCreator ) {
  205. this.meshCreator = meshCreator;
  206. this.rawObject = null;
  207. this.inputObjectCount = 1;
  208. this.debug = false;
  209. }
  210. Parser.prototype.setDebug = function ( debug ) {
  211. if ( debug === true || debug === false ) this.debug = debug;
  212. };
  213. Parser.prototype.validate = function () {
  214. this.rawObject = new RawObject();
  215. this.inputObjectCount = 1;
  216. };
  217. /**
  218. * Parse the provided arraybuffer
  219. * @memberOf Parser
  220. *
  221. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  222. */
  223. Parser.prototype.parseArrayBuffer = function ( arrayBuffer ) {
  224. var arrayBufferView = new Uint8Array( arrayBuffer );
  225. var length = arrayBufferView.byteLength;
  226. var buffer = new Array( 32 );
  227. var bufferPointer = 0;
  228. var slashes = new Array( 32 );
  229. var slashesPointer = 0;
  230. var reachedFaces = false;
  231. var code;
  232. var word = '';
  233. for ( var i = 0; i < length; i++ ) {
  234. code = arrayBufferView[ i ];
  235. switch ( code ) {
  236. case Consts.CODE_SPACE:
  237. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  238. word = '';
  239. break;
  240. case Consts.CODE_SLASH:
  241. slashes[ slashesPointer++ ] = i;
  242. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  243. word = '';
  244. break;
  245. case Consts.CODE_LF:
  246. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  247. word = '';
  248. reachedFaces = this.processLine( buffer, bufferPointer, slashes, slashesPointer, reachedFaces );
  249. slashesPointer = 0;
  250. bufferPointer = 0;
  251. break;
  252. case Consts.CODE_CR:
  253. break;
  254. default:
  255. word += String.fromCharCode( code );
  256. break;
  257. }
  258. }
  259. };
  260. /**
  261. * Parse the provided text
  262. * @memberOf Parser
  263. *
  264. * @param {string} text OBJ data as string
  265. */
  266. Parser.prototype.parseText = function ( text ) {
  267. var length = text.length;
  268. var buffer = new Array( 32 );
  269. var bufferPointer = 0;
  270. var slashes = new Array( 32 );
  271. var slashesPointer = 0;
  272. var reachedFaces = false;
  273. var char;
  274. var word = '';
  275. for ( var i = 0; i < length; i++ ) {
  276. char = text[ i ];
  277. switch ( char ) {
  278. case Consts.STRING_SPACE:
  279. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  280. word = '';
  281. break;
  282. case Consts.STRING_SLASH:
  283. slashes[ slashesPointer++ ] = i;
  284. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  285. word = '';
  286. break;
  287. case Consts.STRING_LF:
  288. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  289. word = '';
  290. reachedFaces = this.processLine( buffer, bufferPointer, slashes, slashesPointer, reachedFaces );
  291. slashesPointer = 0;
  292. bufferPointer = 0;
  293. break;
  294. case Consts.STRING_CR:
  295. break;
  296. default:
  297. word += char;
  298. }
  299. }
  300. };
  301. Parser.prototype.processLine = function ( buffer, bufferPointer, slashes, slashesPointer, reachedFaces ) {
  302. if ( bufferPointer < 1 ) return reachedFaces;
  303. var bufferLength = bufferPointer - 1;
  304. var concatBuffer;
  305. switch ( buffer[ 0 ] ) {
  306. case Consts.LINE_V:
  307. // object complete instance required if reached faces already (= reached next block of v)
  308. if ( reachedFaces ) {
  309. if ( this.rawObject.colors.length > 0 && this.rawObject.colors.length !== this.rawObject.vertices.length ) {
  310. throw 'Vertex Colors were detected, but vertex count and color count do not match!';
  311. }
  312. this.processCompletedObject( null, this.rawObject.groupName );
  313. reachedFaces = false;
  314. }
  315. if ( bufferLength === 3 ) {
  316. this.rawObject.pushVertex( buffer )
  317. } else {
  318. this.rawObject.pushVertexAndVertextColors( buffer );
  319. }
  320. break;
  321. case Consts.LINE_VT:
  322. this.rawObject.pushUv( buffer );
  323. break;
  324. case Consts.LINE_VN:
  325. this.rawObject.pushNormal( buffer );
  326. break;
  327. case Consts.LINE_F:
  328. reachedFaces = true;
  329. /*
  330. * 0: "f vertex/uv/normal ..."
  331. * 1: "f vertex/uv ..."
  332. * 2: "f vertex//normal ..."
  333. * 3: "f vertex ..."
  334. */
  335. var haveQuad = bufferLength % 4 === 0;
  336. if ( slashesPointer > 1 && ( slashes[ 1 ] - slashes[ 0 ] ) === 1 ) {
  337. if ( haveQuad ) {
  338. this.rawObject.buildQuadVVn( buffer );
  339. } else {
  340. this.rawObject.buildFaceVVn( buffer );
  341. }
  342. } else if ( bufferLength === slashesPointer * 2 ) {
  343. if ( haveQuad ) {
  344. this.rawObject.buildQuadVVt( buffer );
  345. } else {
  346. this.rawObject.buildFaceVVt( buffer );
  347. }
  348. } else if ( bufferLength * 2 === slashesPointer * 3 ) {
  349. if ( haveQuad ) {
  350. this.rawObject.buildQuadVVtVn( buffer );
  351. } else {
  352. this.rawObject.buildFaceVVtVn( buffer );
  353. }
  354. } else {
  355. if ( haveQuad ) {
  356. this.rawObject.buildQuadV( buffer );
  357. } else {
  358. this.rawObject.buildFaceV( buffer );
  359. }
  360. }
  361. break;
  362. case Consts.LINE_L:
  363. if ( bufferLength === slashesPointer * 2 ) {
  364. this.rawObject.buildLineVvt( buffer );
  365. } else {
  366. this.rawObject.buildLineV( buffer );
  367. }
  368. break;
  369. case Consts.LINE_S:
  370. this.rawObject.pushSmoothingGroup( buffer[ 1 ] );
  371. this.flushStringBuffer( buffer, bufferPointer );
  372. break;
  373. case Consts.LINE_G:
  374. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  375. this.processCompletedGroup( concatBuffer );
  376. this.flushStringBuffer( buffer, bufferPointer );
  377. break;
  378. case Consts.LINE_O:
  379. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  380. if ( this.rawObject.vertices.length > 0 ) {
  381. this.processCompletedObject( concatBuffer, null );
  382. reachedFaces = false;
  383. } else {
  384. this.rawObject.pushObject( concatBuffer );
  385. }
  386. this.flushStringBuffer( buffer, bufferPointer );
  387. break;
  388. case Consts.LINE_MTLLIB:
  389. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  390. this.rawObject.pushMtllib( concatBuffer );
  391. this.flushStringBuffer( buffer, bufferPointer );
  392. break;
  393. case Consts.LINE_USEMTL:
  394. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  395. this.rawObject.pushUsemtl( concatBuffer );
  396. this.flushStringBuffer( buffer, bufferPointer );
  397. break;
  398. default:
  399. break;
  400. }
  401. return reachedFaces;
  402. };
  403. Parser.prototype.flushStringBuffer = function ( buffer, bufferLength ) {
  404. for ( var i = 0; i < bufferLength; i++ ) {
  405. buffer[ i ] = '';
  406. }
  407. };
  408. Parser.prototype.processCompletedObject = function ( objectName, groupName ) {
  409. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  410. this.inputObjectCount++;
  411. this.rawObject = this.rawObject.newInstanceFromObject( objectName, groupName );
  412. };
  413. Parser.prototype.processCompletedGroup = function ( groupName ) {
  414. var notEmpty = this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  415. if ( notEmpty ) {
  416. this.inputObjectCount ++;
  417. this.rawObject = this.rawObject.newInstanceFromGroup( groupName );
  418. } else {
  419. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  420. this.rawObject.pushGroup( groupName );
  421. }
  422. };
  423. Parser.prototype.finalize = function () {
  424. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  425. this.inputObjectCount++;
  426. };
  427. return Parser;
  428. })();
  429. /**
  430. * {@link RawObject} is only used by {@link Parser}.
  431. * The user of OBJLoader2 does not need to care about this class.
  432. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  433. */
  434. var RawObject = (function () {
  435. function RawObject( objectName, groupName, mtllibName ) {
  436. this.globalVertexOffset = 1;
  437. this.globalUvOffset = 1;
  438. this.globalNormalOffset = 1;
  439. this.vertices = [];
  440. this.colors = [];
  441. this.normals = [];
  442. this.uvs = [];
  443. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  444. this.mtllibName = Validator.verifyInput( mtllibName, '' );
  445. this.objectName = Validator.verifyInput( objectName, '' );
  446. this.groupName = Validator.verifyInput( groupName, '' );
  447. this.activeMtlName = '';
  448. this.activeSmoothingGroup = 1;
  449. this.mtlCount = 0;
  450. this.smoothingGroupCount = 0;
  451. this.rawObjectDescriptions = [];
  452. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  453. var index = this.buildIndex( this.activeMtlName, this.activeSmoothingGroup );
  454. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  455. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  456. }
  457. RawObject.prototype.buildIndex = function ( materialName, smoothingGroup) {
  458. return materialName + '|' + smoothingGroup;
  459. };
  460. RawObject.prototype.newInstanceFromObject = function ( objectName, groupName ) {
  461. var newRawObject = new RawObject( objectName, groupName, this.mtllibName );
  462. // move indices forward
  463. newRawObject.globalVertexOffset = this.globalVertexOffset + this.vertices.length / 3;
  464. newRawObject.globalUvOffset = this.globalUvOffset + this.uvs.length / 2;
  465. newRawObject.globalNormalOffset = this.globalNormalOffset + this.normals.length / 3;
  466. return newRawObject;
  467. };
  468. RawObject.prototype.newInstanceFromGroup = function ( groupName ) {
  469. var newRawObject = new RawObject( this.objectName, groupName, this.mtllibName );
  470. // keep current buffers and indices forward
  471. newRawObject.vertices = this.vertices;
  472. newRawObject.colors = this.colors;
  473. newRawObject.uvs = this.uvs;
  474. newRawObject.normals = this.normals;
  475. newRawObject.globalVertexOffset = this.globalVertexOffset;
  476. newRawObject.globalUvOffset = this.globalUvOffset;
  477. newRawObject.globalNormalOffset = this.globalNormalOffset;
  478. return newRawObject;
  479. };
  480. RawObject.prototype.pushVertex = function ( buffer ) {
  481. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  482. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  483. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  484. };
  485. RawObject.prototype.pushVertexAndVertextColors = function ( buffer ) {
  486. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  487. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  488. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  489. this.colors.push( parseFloat( buffer[ 4 ] ) );
  490. this.colors.push( parseFloat( buffer[ 5 ] ) );
  491. this.colors.push( parseFloat( buffer[ 6 ] ) );
  492. };
  493. RawObject.prototype.pushUv = function ( buffer ) {
  494. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  495. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  496. };
  497. RawObject.prototype.pushNormal = function ( buffer ) {
  498. this.normals.push( parseFloat( buffer[ 1 ] ) );
  499. this.normals.push( parseFloat( buffer[ 2 ] ) );
  500. this.normals.push( parseFloat( buffer[ 3 ] ) );
  501. };
  502. RawObject.prototype.pushObject = function ( objectName ) {
  503. this.objectName = objectName;
  504. };
  505. RawObject.prototype.pushMtllib = function ( mtllibName ) {
  506. this.mtllibName = mtllibName;
  507. };
  508. RawObject.prototype.pushGroup = function ( groupName ) {
  509. this.groupName = groupName;
  510. this.verifyIndex();
  511. };
  512. RawObject.prototype.pushUsemtl = function ( mtlName ) {
  513. if ( this.activeMtlName === mtlName || ! Validator.isValid( mtlName ) ) return;
  514. this.activeMtlName = mtlName;
  515. this.mtlCount++;
  516. this.verifyIndex();
  517. };
  518. RawObject.prototype.pushSmoothingGroup = function ( activeSmoothingGroup ) {
  519. var normalized = parseInt( activeSmoothingGroup );
  520. if ( isNaN( normalized ) ) {
  521. normalized = activeSmoothingGroup === "off" ? 0 : 1;
  522. }
  523. if ( this.activeSmoothingGroup === normalized ) return;
  524. this.activeSmoothingGroup = normalized;
  525. this.smoothingGroupCount++;
  526. this.verifyIndex();
  527. };
  528. RawObject.prototype.verifyIndex = function () {
  529. var index = this.buildIndex( this.activeMtlName, ( this.activeSmoothingGroup === 0 ) ? 0 : 1 );
  530. this.rawObjectDescriptionInUse = this.rawObjectDescriptions[ index ];
  531. if ( ! Validator.isValid( this.rawObjectDescriptionInUse ) ) {
  532. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  533. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  534. }
  535. };
  536. RawObject.prototype.buildQuadVVtVn = function ( indexArray ) {
  537. for ( var i = 0; i < 6; i ++ ) {
  538. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_3[ i ] ] );
  539. this.attachFaceVt( indexArray[ Consts.QUAD_INDICES_3[ i ] + 1 ] );
  540. this.attachFaceVn( indexArray[ Consts.QUAD_INDICES_3[ i ] + 2 ] );
  541. }
  542. };
  543. RawObject.prototype.buildQuadVVt = function ( indexArray ) {
  544. for ( var i = 0; i < 6; i ++ ) {
  545. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_2[ i ] ] );
  546. this.attachFaceVt( indexArray[ Consts.QUAD_INDICES_2[ i ] + 1 ] );
  547. }
  548. };
  549. RawObject.prototype.buildQuadVVn = function ( indexArray ) {
  550. for ( var i = 0; i < 6; i ++ ) {
  551. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_2[ i ] ] );
  552. this.attachFaceVn( indexArray[ Consts.QUAD_INDICES_2[ i ] + 1 ] );
  553. }
  554. };
  555. RawObject.prototype.buildQuadV = function ( indexArray ) {
  556. for ( var i = 0; i < 6; i ++ ) {
  557. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_1[ i ] ] );
  558. }
  559. };
  560. RawObject.prototype.buildFaceVVtVn = function ( indexArray ) {
  561. for ( var i = 1; i < 10; i += 3 ) {
  562. this.attachFaceV_( indexArray[ i ] );
  563. this.attachFaceVt( indexArray[ i + 1 ] );
  564. this.attachFaceVn( indexArray[ i + 2 ] );
  565. }
  566. };
  567. RawObject.prototype.buildFaceVVt = function ( indexArray ) {
  568. for ( var i = 1; i < 7; i += 2 ) {
  569. this.attachFaceV_( indexArray[ i ] );
  570. this.attachFaceVt( indexArray[ i + 1 ] );
  571. }
  572. };
  573. RawObject.prototype.buildFaceVVn = function ( indexArray ) {
  574. for ( var i = 1; i < 7; i += 2 ) {
  575. this.attachFaceV_( indexArray[ i ] );
  576. this.attachFaceVn( indexArray[ i + 1 ] );
  577. }
  578. };
  579. RawObject.prototype.buildFaceV = function ( indexArray ) {
  580. for ( var i = 1; i < 4; i ++ ) {
  581. this.attachFaceV_( indexArray[ i ] );
  582. }
  583. };
  584. RawObject.prototype.attachFaceV_ = function ( faceIndex ) {
  585. var faceIndexInt = parseInt( faceIndex );
  586. var index = ( faceIndexInt - this.globalVertexOffset ) * 3;
  587. var rodiu = this.rawObjectDescriptionInUse;
  588. rodiu.vertices.push( this.vertices[ index++ ] );
  589. rodiu.vertices.push( this.vertices[ index++ ] );
  590. rodiu.vertices.push( this.vertices[ index ] );
  591. if ( this.colors.length > 0 ) {
  592. index -= 2;
  593. rodiu.colors.push( this.colors[ index++ ] );
  594. rodiu.colors.push( this.colors[ index++ ] );
  595. rodiu.colors.push( this.colors[ index ] );
  596. }
  597. };
  598. RawObject.prototype.attachFaceVt = function ( faceIndex ) {
  599. var faceIndexInt = parseInt( faceIndex );
  600. var index = ( faceIndexInt - this.globalUvOffset ) * 2;
  601. var rodiu = this.rawObjectDescriptionInUse;
  602. rodiu.uvs.push( this.uvs[ index++ ] );
  603. rodiu.uvs.push( this.uvs[ index ] );
  604. };
  605. RawObject.prototype.attachFaceVn = function ( faceIndex ) {
  606. var faceIndexInt = parseInt( faceIndex );
  607. var index = ( faceIndexInt - this.globalNormalOffset ) * 3;
  608. var rodiu = this.rawObjectDescriptionInUse;
  609. rodiu.normals.push( this.normals[ index++ ] );
  610. rodiu.normals.push( this.normals[ index++ ] );
  611. rodiu.normals.push( this.normals[ index ] );
  612. };
  613. /*
  614. * Support for lines with or without texture. irst element in indexArray is the line identification
  615. * 0: "f vertex/uv vertex/uv ..."
  616. * 1: "f vertex vertex ..."
  617. */
  618. RawObject.prototype.buildLineVvt = function ( lineArray ) {
  619. var length = lineArray.length;
  620. for ( var i = 1; i < length; i ++ ) {
  621. this.vertices.push( parseInt( lineArray[ i ] ) );
  622. this.uvs.push( parseInt( lineArray[ i ] ) );
  623. }
  624. };
  625. RawObject.prototype.buildLineV = function ( lineArray ) {
  626. var length = lineArray.length;
  627. for ( var i = 1; i < length; i++ ) {
  628. this.vertices.push( parseInt( lineArray[ i ] ) );
  629. }
  630. };
  631. /**
  632. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  633. */
  634. RawObject.prototype.finalize = function ( meshCreator, inputObjectCount, debug ) {
  635. var temp = this.rawObjectDescriptions;
  636. this.rawObjectDescriptions = [];
  637. var rawObjectDescription;
  638. var index = 0;
  639. var absoluteVertexCount = 0;
  640. var absoluteColorCount = 0;
  641. var absoluteNormalCount = 0;
  642. var absoluteUvCount = 0;
  643. for ( var name in temp ) {
  644. rawObjectDescription = temp[ name ];
  645. if ( rawObjectDescription.vertices.length > 0 ) {
  646. this.rawObjectDescriptions[ index++ ] = rawObjectDescription;
  647. absoluteVertexCount += rawObjectDescription.vertices.length;
  648. absoluteColorCount += rawObjectDescription.colors.length;
  649. absoluteUvCount += rawObjectDescription.uvs.length;
  650. absoluteNormalCount += rawObjectDescription.normals.length;
  651. }
  652. }
  653. // don not continue if no result
  654. var notEmpty = false;
  655. if ( index > 0 ) {
  656. if ( debug ) this.createReport( inputObjectCount, true );
  657. meshCreator.buildMesh(
  658. this.rawObjectDescriptions,
  659. inputObjectCount,
  660. absoluteVertexCount,
  661. absoluteColorCount,
  662. absoluteNormalCount,
  663. absoluteUvCount
  664. );
  665. notEmpty = true;
  666. }
  667. return notEmpty;
  668. };
  669. RawObject.prototype.createReport = function ( inputObjectCount, printDirectly ) {
  670. var report = {
  671. name: this.objectName ? this.objectName : 'groups',
  672. mtllibName: this.mtllibName,
  673. vertexCount: this.vertices.length / 3,
  674. normalCount: this.normals.length / 3,
  675. uvCount: this.uvs.length / 2,
  676. smoothingGroupCount: this.smoothingGroupCount,
  677. mtlCount: this.mtlCount,
  678. rawObjectDescriptions: this.rawObjectDescriptions.length
  679. };
  680. if ( printDirectly ) {
  681. console.log( 'Input Object number: ' + inputObjectCount + ' Object name: ' + report.name );
  682. console.log( 'Mtllib name: ' + report.mtllibName );
  683. console.log( 'Vertex count: ' + report.vertexCount );
  684. console.log( 'Normal count: ' + report.normalCount );
  685. console.log( 'UV count: ' + report.uvCount );
  686. console.log( 'SmoothingGroup count: ' + report.smoothingGroupCount );
  687. console.log( 'Material count: ' + report.mtlCount );
  688. console.log( 'Real RawObjectDescription count: ' + report.rawObjectDescriptions );
  689. console.log( '' );
  690. }
  691. return report;
  692. };
  693. return RawObject;
  694. })();
  695. /**
  696. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  697. * @class
  698. *
  699. * @param {string} objectName Name of the mesh
  700. * @param {string} groupName Name of the group
  701. * @param {string} materialName Name of the material
  702. * @param {number} smoothingGroup Normalized smoothingGroup (0: flat shading, 1: smooth shading)
  703. */
  704. var RawObjectDescription = (function () {
  705. function RawObjectDescription( objectName, groupName, materialName, smoothingGroup ) {
  706. this.objectName = objectName;
  707. this.groupName = groupName;
  708. this.materialName = materialName;
  709. this.smoothingGroup = smoothingGroup;
  710. this.vertices = [];
  711. this.colors = [];
  712. this.uvs = [];
  713. this.normals = [];
  714. }
  715. return RawObjectDescription;
  716. })();
  717. /**
  718. * MeshCreator is used to transform RawObjectDescriptions to THREE.Mesh
  719. *
  720. * @class
  721. */
  722. var MeshCreator = (function () {
  723. function MeshCreator() {
  724. this.sceneGraphBaseNode = null;
  725. this.materials = null;
  726. this.debug = false;
  727. this.globalObjectCount = 1;
  728. this.validated = false;
  729. }
  730. MeshCreator.prototype.setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  731. this.sceneGraphBaseNode = Validator.verifyInput( sceneGraphBaseNode, this.sceneGraphBaseNode );
  732. this.sceneGraphBaseNode = Validator.verifyInput( this.sceneGraphBaseNode, new THREE.Group() );
  733. };
  734. MeshCreator.prototype.setMaterials = function ( materials ) {
  735. this.materials = Validator.verifyInput( materials, this.materials );
  736. this.materials = Validator.verifyInput( this.materials, { materials: [] } );
  737. var defaultMaterial = this.materials[ 'defaultMaterial' ];
  738. if ( ! defaultMaterial ) {
  739. defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  740. defaultMaterial.name = 'defaultMaterial';
  741. this.materials[ 'defaultMaterial' ] = defaultMaterial;
  742. }
  743. var vertexColorMaterial = this.materials[ 'vertexColorMaterial' ];
  744. if ( ! vertexColorMaterial ) {
  745. vertexColorMaterial = new THREE.MeshBasicMaterial( { color: 0xDCF1FF } );
  746. vertexColorMaterial.name = 'vertexColorMaterial';
  747. vertexColorMaterial.vertexColors = THREE.VertexColors;
  748. this.materials[ 'vertexColorMaterial' ] = vertexColorMaterial;
  749. }
  750. };
  751. MeshCreator.prototype.setDebug = function ( debug ) {
  752. if ( debug === true || debug === false ) this.debug = debug;
  753. };
  754. MeshCreator.prototype.validate = function () {
  755. if ( this.validated ) return;
  756. this.setSceneGraphBaseNode( null );
  757. this.setMaterials( null );
  758. this.setDebug( null );
  759. this.globalObjectCount = 1;
  760. };
  761. MeshCreator.prototype.finalize = function () {
  762. this.sceneGraphBaseNode = null;
  763. this.materials = null;
  764. this.validated = false;
  765. };
  766. /**
  767. * This is an internal function, but due to its importance to Parser it is documented.
  768. * RawObjectDescriptions are transformed to THREE.Mesh.
  769. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  770. * This method shall be overridden by the web worker implementation
  771. *
  772. * @param {RawObjectDescription[]} rawObjectDescriptions Array of descriptive information and data (vertices, normals, uvs) about the parsed object(s)
  773. * @param {number} inputObjectCount Number of objects already retrieved from OBJ
  774. * @param {number} absoluteVertexCount Sum of all vertices of all rawObjectDescriptions
  775. * @param {number} absoluteColorCount Sum of all vertex colors of all rawObjectDescriptions
  776. * @param {number} absoluteNormalCount Sum of all normals of all rawObjectDescriptions
  777. * @param {number} absoluteUvCount Sum of all uvs of all rawObjectDescriptions
  778. */
  779. MeshCreator.prototype.buildMesh = function ( rawObjectDescriptions, inputObjectCount, absoluteVertexCount,
  780. absoluteColorCount, absoluteNormalCount, absoluteUvCount ) {
  781. if ( this.debug ) console.log( 'MeshCreator.buildRawMeshData:\nInput object no.: ' + inputObjectCount );
  782. var bufferGeometry = new THREE.BufferGeometry();
  783. var vertexBA = new THREE.BufferAttribute( new Float32Array( absoluteVertexCount ), 3 );
  784. bufferGeometry.addAttribute( 'position', vertexBA );
  785. var colorBA;
  786. if ( absoluteColorCount > 0 ) {
  787. colorBA = new THREE.BufferAttribute( new Float32Array( absoluteColorCount ), 3 );
  788. bufferGeometry.addAttribute( 'color', colorBA );
  789. }
  790. var normalBA;
  791. if ( absoluteNormalCount > 0 ) {
  792. normalBA = new THREE.BufferAttribute( new Float32Array( absoluteNormalCount ), 3 );
  793. bufferGeometry.addAttribute( 'normal', normalBA );
  794. }
  795. var uvBA;
  796. if ( absoluteUvCount > 0 ) {
  797. uvBA = new THREE.BufferAttribute( new Float32Array( absoluteUvCount ), 2 );
  798. bufferGeometry.addAttribute( 'uv', uvBA );
  799. }
  800. var rawObjectDescription;
  801. var material;
  802. var materialName;
  803. var createMultiMaterial = rawObjectDescriptions.length > 1;
  804. var materials = [];
  805. var materialIndex = 0;
  806. var materialIndexMapping = [];
  807. var selectedMaterialIndex;
  808. var vertexBAOffset = 0;
  809. var vertexGroupOffset = 0;
  810. var vertexLength;
  811. var colorBAOffset = 0;
  812. var normalBAOffset = 0;
  813. var uvBAOffset = 0;
  814. if ( this.debug ) {
  815. console.log( createMultiMaterial ? 'Creating Multi-Material' : 'Creating Material' + ' for object no.: ' + this.globalObjectCount );
  816. }
  817. for ( var oodIndex in rawObjectDescriptions ) {
  818. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  819. materialName = rawObjectDescription.materialName;
  820. material = colorBA ? this.materials[ 'vertexColorMaterial' ] : this.materials[ materialName ];
  821. if ( ! material ) {
  822. material = this.materials[ 'defaultMaterial' ];
  823. if ( ! material ) console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName +
  824. '" was defined without material! Assigning "defaultMaterial".' );
  825. }
  826. // clone material in case flat shading is needed due to smoothingGroup 0
  827. if ( rawObjectDescription.smoothingGroup === 0 ) {
  828. materialName = material.name + '_flat';
  829. var materialClone = this.materials[ materialName ];
  830. if ( ! materialClone ) {
  831. materialClone = material.clone();
  832. materialClone.name = materialName;
  833. materialClone.flatShading = true;
  834. this.materials[ materialName ] = name;
  835. }
  836. }
  837. vertexLength = rawObjectDescription.vertices.length;
  838. if ( createMultiMaterial ) {
  839. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  840. selectedMaterialIndex = materialIndexMapping[ materialName ];
  841. if ( ! selectedMaterialIndex ) {
  842. selectedMaterialIndex = materialIndex;
  843. materialIndexMapping[ materialName ] = materialIndex;
  844. materials.push( material );
  845. materialIndex++;
  846. }
  847. bufferGeometry.addGroup( vertexGroupOffset, vertexLength / 3, selectedMaterialIndex );
  848. vertexGroupOffset += vertexLength / 3;
  849. }
  850. vertexBA.set( rawObjectDescription.vertices, vertexBAOffset );
  851. vertexBAOffset += vertexLength;
  852. if ( colorBA ) {
  853. colorBA.set( rawObjectDescription.colors, colorBAOffset );
  854. colorBAOffset += rawObjectDescription.colors.length;
  855. }
  856. if ( normalBA ) {
  857. normalBA.set( rawObjectDescription.normals, normalBAOffset );
  858. normalBAOffset += rawObjectDescription.normals.length;
  859. }
  860. if ( uvBA ) {
  861. uvBA.set( rawObjectDescription.uvs, uvBAOffset );
  862. uvBAOffset += rawObjectDescription.uvs.length;
  863. }
  864. if ( this.debug ) this.printReport( rawObjectDescription, selectedMaterialIndex );
  865. }
  866. if ( ! normalBA ) bufferGeometry.computeVertexNormals();
  867. if ( createMultiMaterial ) material = materials;
  868. var mesh = new THREE.Mesh( bufferGeometry, material );
  869. mesh.name = rawObjectDescription.groupName !== '' ? rawObjectDescription.groupName : rawObjectDescription.objectName;
  870. this.sceneGraphBaseNode.add( mesh );
  871. this.globalObjectCount++;
  872. };
  873. MeshCreator.prototype.printReport = function ( rawObjectDescription, selectedMaterialIndex ) {
  874. var materialIndexLine = Validator.isValid( selectedMaterialIndex ) ? '\n materialIndex: ' + selectedMaterialIndex : '';
  875. console.log(
  876. ' Output Object no.: ' + this.globalObjectCount +
  877. '\n objectName: ' + rawObjectDescription.objectName +
  878. '\n groupName: ' + rawObjectDescription.groupName +
  879. '\n materialName: ' + rawObjectDescription.materialName +
  880. materialIndexLine +
  881. '\n smoothingGroup: ' + rawObjectDescription.smoothingGroup +
  882. '\n #vertices: ' + rawObjectDescription.vertices.length / 3 +
  883. '\n #colors: ' + rawObjectDescription.colors.length / 3 +
  884. '\n #uvs: ' + rawObjectDescription.uvs.length / 2 +
  885. '\n #normals: ' + rawObjectDescription.normals.length / 3
  886. );
  887. };
  888. return MeshCreator;
  889. })();
  890. OBJLoader2.prototype._buildWebWorkerCode = function ( funcBuildObject, funcBuildSingelton ) {
  891. var workerCode = '';
  892. workerCode += funcBuildObject( 'Consts', Consts );
  893. workerCode += funcBuildObject( 'Validator', Validator );
  894. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  895. workerCode += funcBuildSingelton( 'RawObject', 'RawObject', RawObject );
  896. workerCode += funcBuildSingelton( 'RawObjectDescription', 'RawObjectDescription', RawObjectDescription );
  897. return workerCode;
  898. };
  899. return OBJLoader2;
  900. })();