OBJLoader2.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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.0';
  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. break;
  372. case Consts.LINE_G:
  373. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  374. this.processCompletedGroup( concatBuffer );
  375. break;
  376. case Consts.LINE_O:
  377. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  378. if ( this.rawObject.vertices.length > 0 ) {
  379. this.processCompletedObject( concatBuffer, null );
  380. reachedFaces = false;
  381. } else {
  382. this.rawObject.pushObject( concatBuffer );
  383. }
  384. break;
  385. case Consts.LINE_MTLLIB:
  386. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  387. this.rawObject.pushMtllib( concatBuffer );
  388. break;
  389. case Consts.LINE_USEMTL:
  390. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  391. this.rawObject.pushUsemtl( concatBuffer );
  392. break;
  393. default:
  394. break;
  395. }
  396. return reachedFaces;
  397. };
  398. Parser.prototype.processCompletedObject = function ( objectName, groupName ) {
  399. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  400. this.inputObjectCount++;
  401. this.rawObject = this.rawObject.newInstanceFromObject( objectName, groupName );
  402. };
  403. Parser.prototype.processCompletedGroup = function ( groupName ) {
  404. var notEmpty = this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  405. if ( notEmpty ) {
  406. this.inputObjectCount ++;
  407. this.rawObject = this.rawObject.newInstanceFromGroup( groupName );
  408. } else {
  409. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  410. this.rawObject.pushGroup( groupName );
  411. }
  412. };
  413. Parser.prototype.finalize = function () {
  414. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  415. this.inputObjectCount++;
  416. };
  417. return Parser;
  418. })();
  419. /**
  420. * {@link RawObject} is only used by {@link Parser}.
  421. * The user of OBJLoader2 does not need to care about this class.
  422. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  423. */
  424. var RawObject = (function () {
  425. function RawObject( objectName, groupName, mtllibName ) {
  426. this.globalVertexOffset = 1;
  427. this.globalUvOffset = 1;
  428. this.globalNormalOffset = 1;
  429. this.vertices = [];
  430. this.colors = [];
  431. this.normals = [];
  432. this.uvs = [];
  433. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  434. this.mtllibName = Validator.verifyInput( mtllibName, '' );
  435. this.objectName = Validator.verifyInput( objectName, '' );
  436. this.groupName = Validator.verifyInput( groupName, '' );
  437. this.activeMtlName = '';
  438. this.activeSmoothingGroup = 1;
  439. this.mtlCount = 0;
  440. this.smoothingGroupCount = 0;
  441. this.rawObjectDescriptions = [];
  442. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  443. var index = this.buildIndex( this.activeMtlName, this.activeSmoothingGroup );
  444. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  445. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  446. }
  447. RawObject.prototype.buildIndex = function ( materialName, smoothingGroup) {
  448. return materialName + '|' + smoothingGroup;
  449. };
  450. RawObject.prototype.newInstanceFromObject = function ( objectName, groupName ) {
  451. var newRawObject = new RawObject( objectName, groupName, this.mtllibName );
  452. // move indices forward
  453. newRawObject.globalVertexOffset = this.globalVertexOffset + this.vertices.length / 3;
  454. newRawObject.globalUvOffset = this.globalUvOffset + this.uvs.length / 2;
  455. newRawObject.globalNormalOffset = this.globalNormalOffset + this.normals.length / 3;
  456. return newRawObject;
  457. };
  458. RawObject.prototype.newInstanceFromGroup = function ( groupName ) {
  459. var newRawObject = new RawObject( this.objectName, groupName, this.mtllibName );
  460. // keep current buffers and indices forward
  461. newRawObject.vertices = this.vertices;
  462. newRawObject.colors = this.colors;
  463. newRawObject.uvs = this.uvs;
  464. newRawObject.normals = this.normals;
  465. newRawObject.globalVertexOffset = this.globalVertexOffset;
  466. newRawObject.globalUvOffset = this.globalUvOffset;
  467. newRawObject.globalNormalOffset = this.globalNormalOffset;
  468. return newRawObject;
  469. };
  470. RawObject.prototype.pushVertex = function ( buffer ) {
  471. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  472. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  473. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  474. };
  475. RawObject.prototype.pushVertexAndVertextColors = function ( buffer ) {
  476. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  477. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  478. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  479. this.colors.push( parseFloat( buffer[ 4 ] ) );
  480. this.colors.push( parseFloat( buffer[ 5 ] ) );
  481. this.colors.push( parseFloat( buffer[ 6 ] ) );
  482. };
  483. RawObject.prototype.pushUv = function ( buffer ) {
  484. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  485. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  486. };
  487. RawObject.prototype.pushNormal = function ( buffer ) {
  488. this.normals.push( parseFloat( buffer[ 1 ] ) );
  489. this.normals.push( parseFloat( buffer[ 2 ] ) );
  490. this.normals.push( parseFloat( buffer[ 3 ] ) );
  491. };
  492. RawObject.prototype.pushObject = function ( objectName ) {
  493. this.objectName = objectName;
  494. };
  495. RawObject.prototype.pushMtllib = function ( mtllibName ) {
  496. this.mtllibName = mtllibName;
  497. };
  498. RawObject.prototype.pushGroup = function ( groupName ) {
  499. this.groupName = groupName;
  500. this.verifyIndex();
  501. };
  502. RawObject.prototype.pushUsemtl = function ( mtlName ) {
  503. if ( this.activeMtlName === mtlName || ! Validator.isValid( mtlName ) ) return;
  504. this.activeMtlName = mtlName;
  505. this.mtlCount++;
  506. this.verifyIndex();
  507. };
  508. RawObject.prototype.pushSmoothingGroup = function ( activeSmoothingGroup ) {
  509. var normalized = parseInt( activeSmoothingGroup );
  510. if ( isNaN( normalized ) ) {
  511. normalized = activeSmoothingGroup === "off" ? 0 : 1;
  512. }
  513. if ( this.activeSmoothingGroup === normalized ) return;
  514. this.activeSmoothingGroup = normalized;
  515. this.smoothingGroupCount++;
  516. this.verifyIndex();
  517. };
  518. RawObject.prototype.verifyIndex = function () {
  519. var index = this.buildIndex( this.activeMtlName, ( this.activeSmoothingGroup === 0 ) ? 0 : 1 );
  520. this.rawObjectDescriptionInUse = this.rawObjectDescriptions[ index ];
  521. if ( ! Validator.isValid( this.rawObjectDescriptionInUse ) ) {
  522. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  523. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  524. }
  525. };
  526. RawObject.prototype.buildQuadVVtVn = function ( indexArray ) {
  527. for ( var i = 0; i < 6; i ++ ) {
  528. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_3[ i ] ] );
  529. this.attachFaceVt( indexArray[ Consts.QUAD_INDICES_3[ i ] + 1 ] );
  530. this.attachFaceVn( indexArray[ Consts.QUAD_INDICES_3[ i ] + 2 ] );
  531. }
  532. };
  533. RawObject.prototype.buildQuadVVt = function ( indexArray ) {
  534. for ( var i = 0; i < 6; i ++ ) {
  535. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_2[ i ] ] );
  536. this.attachFaceVt( indexArray[ Consts.QUAD_INDICES_2[ i ] + 1 ] );
  537. }
  538. };
  539. RawObject.prototype.buildQuadVVn = function ( indexArray ) {
  540. for ( var i = 0; i < 6; i ++ ) {
  541. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_2[ i ] ] );
  542. this.attachFaceVn( indexArray[ Consts.QUAD_INDICES_2[ i ] + 1 ] );
  543. }
  544. };
  545. RawObject.prototype.buildQuadV = function ( indexArray ) {
  546. for ( var i = 0; i < 6; i ++ ) {
  547. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_1[ i ] ] );
  548. }
  549. };
  550. RawObject.prototype.buildFaceVVtVn = function ( indexArray ) {
  551. for ( var i = 1; i < 10; i += 3 ) {
  552. this.attachFaceV_( indexArray[ i ] );
  553. this.attachFaceVt( indexArray[ i + 1 ] );
  554. this.attachFaceVn( indexArray[ i + 2 ] );
  555. }
  556. };
  557. RawObject.prototype.buildFaceVVt = function ( indexArray ) {
  558. for ( var i = 1; i < 7; i += 2 ) {
  559. this.attachFaceV_( indexArray[ i ] );
  560. this.attachFaceVt( indexArray[ i + 1 ] );
  561. }
  562. };
  563. RawObject.prototype.buildFaceVVn = function ( indexArray ) {
  564. for ( var i = 1; i < 7; i += 2 ) {
  565. this.attachFaceV_( indexArray[ i ] );
  566. this.attachFaceVn( indexArray[ i + 1 ] );
  567. }
  568. };
  569. RawObject.prototype.buildFaceV = function ( indexArray ) {
  570. for ( var i = 1; i < 4; i ++ ) {
  571. this.attachFaceV_( indexArray[ i ] );
  572. }
  573. };
  574. RawObject.prototype.attachFaceV_ = function ( faceIndex ) {
  575. var faceIndexInt = parseInt( faceIndex );
  576. var index = ( faceIndexInt - this.globalVertexOffset ) * 3;
  577. var rodiu = this.rawObjectDescriptionInUse;
  578. rodiu.vertices.push( this.vertices[ index++ ] );
  579. rodiu.vertices.push( this.vertices[ index++ ] );
  580. rodiu.vertices.push( this.vertices[ index ] );
  581. if ( this.colors.length > 0 ) {
  582. index -= 2;
  583. rodiu.colors.push( this.colors[ index++ ] );
  584. rodiu.colors.push( this.colors[ index++ ] );
  585. rodiu.colors.push( this.colors[ index ] );
  586. }
  587. };
  588. RawObject.prototype.attachFaceVt = function ( faceIndex ) {
  589. var faceIndexInt = parseInt( faceIndex );
  590. var index = ( faceIndexInt - this.globalUvOffset ) * 2;
  591. var rodiu = this.rawObjectDescriptionInUse;
  592. rodiu.uvs.push( this.uvs[ index++ ] );
  593. rodiu.uvs.push( this.uvs[ index ] );
  594. };
  595. RawObject.prototype.attachFaceVn = function ( faceIndex ) {
  596. var faceIndexInt = parseInt( faceIndex );
  597. var index = ( faceIndexInt - this.globalNormalOffset ) * 3;
  598. var rodiu = this.rawObjectDescriptionInUse;
  599. rodiu.normals.push( this.normals[ index++ ] );
  600. rodiu.normals.push( this.normals[ index++ ] );
  601. rodiu.normals.push( this.normals[ index ] );
  602. };
  603. /*
  604. * Support for lines with or without texture. irst element in indexArray is the line identification
  605. * 0: "f vertex/uv vertex/uv ..."
  606. * 1: "f vertex vertex ..."
  607. */
  608. RawObject.prototype.buildLineVvt = function ( lineArray ) {
  609. var length = lineArray.length;
  610. for ( var i = 1; i < length; i ++ ) {
  611. this.vertices.push( parseInt( lineArray[ i ] ) );
  612. this.uvs.push( parseInt( lineArray[ i ] ) );
  613. }
  614. };
  615. RawObject.prototype.buildLineV = function ( lineArray ) {
  616. var length = lineArray.length;
  617. for ( var i = 1; i < length; i++ ) {
  618. this.vertices.push( parseInt( lineArray[ i ] ) );
  619. }
  620. };
  621. /**
  622. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  623. */
  624. RawObject.prototype.finalize = function ( meshCreator, inputObjectCount, debug ) {
  625. var temp = this.rawObjectDescriptions;
  626. this.rawObjectDescriptions = [];
  627. var rawObjectDescription;
  628. var index = 0;
  629. var absoluteVertexCount = 0;
  630. var absoluteColorCount = 0;
  631. var absoluteNormalCount = 0;
  632. var absoluteUvCount = 0;
  633. for ( var name in temp ) {
  634. rawObjectDescription = temp[ name ];
  635. if ( rawObjectDescription.vertices.length > 0 ) {
  636. this.rawObjectDescriptions[ index++ ] = rawObjectDescription;
  637. absoluteVertexCount += rawObjectDescription.vertices.length;
  638. absoluteColorCount += rawObjectDescription.colors.length;
  639. absoluteUvCount += rawObjectDescription.uvs.length;
  640. absoluteNormalCount += rawObjectDescription.normals.length;
  641. }
  642. }
  643. // don not continue if no result
  644. var notEmpty = false;
  645. if ( index > 0 ) {
  646. if ( debug ) this.createReport( inputObjectCount, true );
  647. meshCreator.buildMesh(
  648. this.rawObjectDescriptions,
  649. inputObjectCount,
  650. absoluteVertexCount,
  651. absoluteColorCount,
  652. absoluteNormalCount,
  653. absoluteUvCount
  654. );
  655. notEmpty = true;
  656. }
  657. return notEmpty;
  658. };
  659. RawObject.prototype.createReport = function ( inputObjectCount, printDirectly ) {
  660. var report = {
  661. name: this.objectName ? this.objectName : 'groups',
  662. mtllibName: this.mtllibName,
  663. vertexCount: this.vertices.length / 3,
  664. normalCount: this.normals.length / 3,
  665. uvCount: this.uvs.length / 2,
  666. smoothingGroupCount: this.smoothingGroupCount,
  667. mtlCount: this.mtlCount,
  668. rawObjectDescriptions: this.rawObjectDescriptions.length
  669. };
  670. if ( printDirectly ) {
  671. console.log( 'Input Object number: ' + inputObjectCount + ' Object name: ' + report.name );
  672. console.log( 'Mtllib name: ' + report.mtllibName );
  673. console.log( 'Vertex count: ' + report.vertexCount );
  674. console.log( 'Normal count: ' + report.normalCount );
  675. console.log( 'UV count: ' + report.uvCount );
  676. console.log( 'SmoothingGroup count: ' + report.smoothingGroupCount );
  677. console.log( 'Material count: ' + report.mtlCount );
  678. console.log( 'Real RawObjectDescription count: ' + report.rawObjectDescriptions );
  679. console.log( '' );
  680. }
  681. return report;
  682. };
  683. return RawObject;
  684. })();
  685. /**
  686. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  687. * @class
  688. *
  689. * @param {string} objectName Name of the mesh
  690. * @param {string} groupName Name of the group
  691. * @param {string} materialName Name of the material
  692. * @param {number} smoothingGroup Normalized smoothingGroup (0: flat shading, 1: smooth shading)
  693. */
  694. var RawObjectDescription = (function () {
  695. function RawObjectDescription( objectName, groupName, materialName, smoothingGroup ) {
  696. this.objectName = objectName;
  697. this.groupName = groupName;
  698. this.materialName = materialName;
  699. this.smoothingGroup = smoothingGroup;
  700. this.vertices = [];
  701. this.colors = [];
  702. this.uvs = [];
  703. this.normals = [];
  704. }
  705. return RawObjectDescription;
  706. })();
  707. /**
  708. * MeshCreator is used to transform RawObjectDescriptions to THREE.Mesh
  709. *
  710. * @class
  711. */
  712. var MeshCreator = (function () {
  713. function MeshCreator() {
  714. this.sceneGraphBaseNode = null;
  715. this.materials = null;
  716. this.debug = false;
  717. this.globalObjectCount = 1;
  718. this.validated = false;
  719. }
  720. MeshCreator.prototype.setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  721. this.sceneGraphBaseNode = Validator.verifyInput( sceneGraphBaseNode, this.sceneGraphBaseNode );
  722. this.sceneGraphBaseNode = Validator.verifyInput( this.sceneGraphBaseNode, new THREE.Group() );
  723. };
  724. MeshCreator.prototype.setMaterials = function ( materials ) {
  725. this.materials = Validator.verifyInput( materials, this.materials );
  726. this.materials = Validator.verifyInput( this.materials, { materials: [] } );
  727. var defaultMaterial = this.materials[ 'defaultMaterial' ];
  728. if ( ! defaultMaterial ) {
  729. defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  730. defaultMaterial.name = 'defaultMaterial';
  731. this.materials[ 'defaultMaterial' ] = defaultMaterial;
  732. }
  733. var vertexColorMaterial = this.materials[ 'vertexColorMaterial' ];
  734. if ( ! vertexColorMaterial ) {
  735. vertexColorMaterial = new THREE.MeshBasicMaterial( { color: 0xDCF1FF } );
  736. vertexColorMaterial.name = 'vertexColorMaterial';
  737. vertexColorMaterial.vertexColors = THREE.VertexColors;
  738. this.materials[ 'vertexColorMaterial' ] = vertexColorMaterial;
  739. }
  740. };
  741. MeshCreator.prototype.setDebug = function ( debug ) {
  742. if ( debug === true || debug === false ) this.debug = debug;
  743. };
  744. MeshCreator.prototype.validate = function () {
  745. if ( this.validated ) return;
  746. this.setSceneGraphBaseNode( null );
  747. this.setMaterials( null );
  748. this.setDebug( null );
  749. this.globalObjectCount = 1;
  750. };
  751. MeshCreator.prototype.finalize = function () {
  752. this.sceneGraphBaseNode = null;
  753. this.materials = null;
  754. this.validated = false;
  755. };
  756. /**
  757. * This is an internal function, but due to its importance to Parser it is documented.
  758. * RawObjectDescriptions are transformed to THREE.Mesh.
  759. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  760. * This method shall be overridden by the web worker implementation
  761. *
  762. * @param {RawObjectDescription[]} rawObjectDescriptions Array of descriptive information and data (vertices, normals, uvs) about the parsed object(s)
  763. * @param {number} inputObjectCount Number of objects already retrieved from OBJ
  764. * @param {number} absoluteVertexCount Sum of all vertices of all rawObjectDescriptions
  765. * @param {number} absoluteColorCount Sum of all vertex colors of all rawObjectDescriptions
  766. * @param {number} absoluteNormalCount Sum of all normals of all rawObjectDescriptions
  767. * @param {number} absoluteUvCount Sum of all uvs of all rawObjectDescriptions
  768. */
  769. MeshCreator.prototype.buildMesh = function ( rawObjectDescriptions, inputObjectCount, absoluteVertexCount,
  770. absoluteColorCount, absoluteNormalCount, absoluteUvCount ) {
  771. if ( this.debug ) console.log( 'MeshCreator.buildRawMeshData:\nInput object no.: ' + inputObjectCount );
  772. var bufferGeometry = new THREE.BufferGeometry();
  773. var vertexBA = new THREE.BufferAttribute( new Float32Array( absoluteVertexCount ), 3 );
  774. bufferGeometry.addAttribute( 'position', vertexBA );
  775. var colorBA;
  776. if ( absoluteColorCount > 0 ) {
  777. colorBA = new THREE.BufferAttribute( new Float32Array( absoluteColorCount ), 3 );
  778. bufferGeometry.addAttribute( 'color', colorBA );
  779. }
  780. var normalBA;
  781. if ( absoluteNormalCount > 0 ) {
  782. normalBA = new THREE.BufferAttribute( new Float32Array( absoluteNormalCount ), 3 );
  783. bufferGeometry.addAttribute( 'normal', normalBA );
  784. }
  785. var uvBA;
  786. if ( absoluteUvCount > 0 ) {
  787. uvBA = new THREE.BufferAttribute( new Float32Array( absoluteUvCount ), 2 );
  788. bufferGeometry.addAttribute( 'uv', uvBA );
  789. }
  790. var rawObjectDescription;
  791. var material;
  792. var materialName;
  793. var createMultiMaterial = rawObjectDescriptions.length > 1;
  794. var materials = [];
  795. var materialIndex = 0;
  796. var materialIndexMapping = [];
  797. var selectedMaterialIndex;
  798. var vertexBAOffset = 0;
  799. var vertexGroupOffset = 0;
  800. var vertexLength;
  801. var colorBAOffset = 0;
  802. var normalBAOffset = 0;
  803. var uvBAOffset = 0;
  804. if ( this.debug ) {
  805. console.log( createMultiMaterial ? 'Creating Multi-Material' : 'Creating Material' + ' for object no.: ' + this.globalObjectCount );
  806. }
  807. for ( var oodIndex in rawObjectDescriptions ) {
  808. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  809. materialName = rawObjectDescription.materialName;
  810. material = colorBA ? this.materials[ 'vertexColorMaterial' ] : this.materials[ materialName ];
  811. if ( ! material ) {
  812. material = this.materials[ 'defaultMaterial' ];
  813. if ( ! material ) console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName +
  814. '" was defined without material! Assigning "defaultMaterial".' );
  815. }
  816. // clone material in case flat shading is needed due to smoothingGroup 0
  817. if ( rawObjectDescription.smoothingGroup === 0 ) {
  818. materialName = material.name + '_flat';
  819. var materialClone = this.materials[ materialName ];
  820. if ( ! materialClone ) {
  821. materialClone = material.clone();
  822. materialClone.name = materialName;
  823. materialClone.flatShading = true;
  824. this.materials[ materialName ] = name;
  825. }
  826. }
  827. vertexLength = rawObjectDescription.vertices.length;
  828. if ( createMultiMaterial ) {
  829. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  830. selectedMaterialIndex = materialIndexMapping[ materialName ];
  831. if ( ! selectedMaterialIndex ) {
  832. selectedMaterialIndex = materialIndex;
  833. materialIndexMapping[ materialName ] = materialIndex;
  834. materials.push( material );
  835. materialIndex++;
  836. }
  837. bufferGeometry.addGroup( vertexGroupOffset, vertexLength / 3, selectedMaterialIndex );
  838. vertexGroupOffset += vertexLength / 3;
  839. }
  840. vertexBA.set( rawObjectDescription.vertices, vertexBAOffset );
  841. vertexBAOffset += vertexLength;
  842. if ( colorBA ) {
  843. colorBA.set( rawObjectDescription.colors, colorBAOffset );
  844. colorBAOffset += rawObjectDescription.colors.length;
  845. }
  846. if ( normalBA ) {
  847. normalBA.set( rawObjectDescription.normals, normalBAOffset );
  848. normalBAOffset += rawObjectDescription.normals.length;
  849. }
  850. if ( uvBA ) {
  851. uvBA.set( rawObjectDescription.uvs, uvBAOffset );
  852. uvBAOffset += rawObjectDescription.uvs.length;
  853. }
  854. if ( this.debug ) this.printReport( rawObjectDescription, selectedMaterialIndex );
  855. }
  856. if ( ! normalBA ) bufferGeometry.computeVertexNormals();
  857. if ( createMultiMaterial ) material = materials;
  858. var mesh = new THREE.Mesh( bufferGeometry, material );
  859. mesh.name = rawObjectDescription.groupName !== '' ? rawObjectDescription.groupName : rawObjectDescription.objectName;
  860. this.sceneGraphBaseNode.add( mesh );
  861. this.globalObjectCount++;
  862. };
  863. MeshCreator.prototype.printReport = function ( rawObjectDescription, selectedMaterialIndex ) {
  864. var materialIndexLine = Validator.isValid( selectedMaterialIndex ) ? '\n materialIndex: ' + selectedMaterialIndex : '';
  865. console.log(
  866. ' Output Object no.: ' + this.globalObjectCount +
  867. '\n objectName: ' + rawObjectDescription.objectName +
  868. '\n groupName: ' + rawObjectDescription.groupName +
  869. '\n materialName: ' + rawObjectDescription.materialName +
  870. materialIndexLine +
  871. '\n smoothingGroup: ' + rawObjectDescription.smoothingGroup +
  872. '\n #vertices: ' + rawObjectDescription.vertices.length / 3 +
  873. '\n #colors: ' + rawObjectDescription.colors.length / 3 +
  874. '\n #uvs: ' + rawObjectDescription.uvs.length / 2 +
  875. '\n #normals: ' + rawObjectDescription.normals.length / 3
  876. );
  877. };
  878. return MeshCreator;
  879. })();
  880. OBJLoader2.prototype._buildWebWorkerCode = function ( funcBuildObject, funcBuildSingelton ) {
  881. var workerCode = '';
  882. workerCode += funcBuildObject( 'Consts', Consts );
  883. workerCode += funcBuildObject( 'Validator', Validator );
  884. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  885. workerCode += funcBuildSingelton( 'RawObject', 'RawObject', RawObject );
  886. workerCode += funcBuildSingelton( 'RawObjectDescription', 'RawObjectDescription', RawObjectDescription );
  887. return workerCode;
  888. };
  889. return OBJLoader2;
  890. })();