OBJLoader2.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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.4.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. var Validator = {
  160. /**
  161. * If given input is null or undefined, false is returned otherwise true.
  162. *
  163. * @param input Anything
  164. * @returns {boolean}
  165. */
  166. isValid: function( input ) {
  167. return ( input !== null && input !== undefined );
  168. },
  169. /**
  170. * If given input is null or undefined, the defaultValue is returned otherwise the given input.
  171. *
  172. * @param input Anything
  173. * @param defaultValue Anything
  174. * @returns {*}
  175. */
  176. verifyInput: function( input, defaultValue ) {
  177. return ( input === null || input === undefined ) ? defaultValue : input;
  178. }
  179. };
  180. OBJLoader2.prototype._getValidator = function () {
  181. return Validator;
  182. };
  183. /**
  184. * Parse OBJ data either from ArrayBuffer or string
  185. * @class
  186. */
  187. var Parser = (function () {
  188. function Parser( meshCreator ) {
  189. this.meshCreator = meshCreator;
  190. this.rawObject = null;
  191. this.inputObjectCount = 1;
  192. this.debug = false;
  193. }
  194. Parser.prototype.setDebug = function ( debug ) {
  195. if ( debug === true || debug === false ) this.debug = debug;
  196. };
  197. Parser.prototype.validate = function () {
  198. this.rawObject = new RawObject();
  199. this.inputObjectCount = 1;
  200. };
  201. /**
  202. * Parse the provided arraybuffer
  203. * @memberOf Parser
  204. *
  205. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  206. */
  207. Parser.prototype.parseArrayBuffer = function ( arrayBuffer ) {
  208. var arrayBufferView = new Uint8Array( arrayBuffer );
  209. var length = arrayBufferView.byteLength;
  210. var buffer = new Array( 128 );
  211. var bufferPointer = 0;
  212. var slashesCount = 0;
  213. var reachedFaces = false;
  214. var code;
  215. var word = '';
  216. for ( var i = 0; i < length; i++ ) {
  217. code = arrayBufferView[ i ];
  218. switch ( code ) {
  219. case Consts.CODE_SPACE:
  220. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  221. word = '';
  222. break;
  223. case Consts.CODE_SLASH:
  224. slashesCount++;
  225. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  226. word = '';
  227. break;
  228. case Consts.CODE_LF:
  229. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  230. word = '';
  231. reachedFaces = this.processLine( buffer, bufferPointer, slashesCount, reachedFaces );
  232. bufferPointer = 0;
  233. slashesCount = 0;
  234. break;
  235. case Consts.CODE_CR:
  236. break;
  237. default:
  238. word += String.fromCharCode( code );
  239. break;
  240. }
  241. }
  242. };
  243. /**
  244. * Parse the provided text
  245. * @memberOf Parser
  246. *
  247. * @param {string} text OBJ data as string
  248. */
  249. Parser.prototype.parseText = function ( text ) {
  250. var length = text.length;
  251. var buffer = new Array( 128 );
  252. var bufferPointer = 0;
  253. var slashesCount = 0;
  254. var reachedFaces = false;
  255. var char;
  256. var word = '';
  257. for ( var i = 0; i < length; i++ ) {
  258. char = text[ i ];
  259. switch ( char ) {
  260. case Consts.STRING_SPACE:
  261. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  262. word = '';
  263. break;
  264. case Consts.STRING_SLASH:
  265. slashesCount++;
  266. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  267. word = '';
  268. break;
  269. case Consts.STRING_LF:
  270. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  271. word = '';
  272. reachedFaces = this.processLine( buffer, bufferPointer, slashesCount, reachedFaces );
  273. bufferPointer = 0;
  274. slashesCount = 0;
  275. break;
  276. case Consts.STRING_CR:
  277. break;
  278. default:
  279. word += char;
  280. }
  281. }
  282. };
  283. Parser.prototype.processLine = function ( buffer, bufferPointer, slashesCount, reachedFaces ) {
  284. if ( bufferPointer < 1 ) return reachedFaces;
  285. var bufferLength = bufferPointer - 1;
  286. var concatBuffer;
  287. switch ( buffer[ 0 ] ) {
  288. case Consts.LINE_V:
  289. // object complete instance required if reached faces already (= reached next block of v)
  290. if ( reachedFaces ) {
  291. if ( this.rawObject.colors.length > 0 && this.rawObject.colors.length !== this.rawObject.vertices.length ) {
  292. throw 'Vertex Colors were detected, but vertex count and color count do not match!';
  293. }
  294. this.processCompletedObject( null, this.rawObject.groupName );
  295. reachedFaces = false;
  296. }
  297. if ( bufferLength === 3 ) {
  298. this.rawObject.pushVertex( buffer )
  299. } else {
  300. this.rawObject.pushVertexAndVertextColors( buffer );
  301. }
  302. break;
  303. case Consts.LINE_VT:
  304. this.rawObject.pushUv( buffer );
  305. break;
  306. case Consts.LINE_VN:
  307. this.rawObject.pushNormal( buffer );
  308. break;
  309. case Consts.LINE_F:
  310. reachedFaces = true;
  311. this.rawObject.processFaces( buffer, bufferPointer, slashesCount );
  312. break;
  313. case Consts.LINE_L:
  314. if ( bufferLength === slashesCount * 2 ) {
  315. this.rawObject.buildLineVvt( buffer );
  316. } else {
  317. this.rawObject.buildLineV( buffer );
  318. }
  319. break;
  320. case Consts.LINE_S:
  321. this.rawObject.pushSmoothingGroup( buffer[ 1 ] );
  322. this.flushStringBuffer( buffer, bufferPointer );
  323. break;
  324. case Consts.LINE_G:
  325. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  326. this.processCompletedGroup( concatBuffer );
  327. this.flushStringBuffer( buffer, bufferPointer );
  328. break;
  329. case Consts.LINE_O:
  330. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  331. if ( this.rawObject.vertices.length > 0 ) {
  332. this.processCompletedObject( concatBuffer, null );
  333. reachedFaces = false;
  334. } else {
  335. this.rawObject.pushObject( concatBuffer );
  336. }
  337. this.flushStringBuffer( buffer, bufferPointer );
  338. break;
  339. case Consts.LINE_MTLLIB:
  340. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  341. this.rawObject.pushMtllib( concatBuffer );
  342. this.flushStringBuffer( buffer, bufferPointer );
  343. break;
  344. case Consts.LINE_USEMTL:
  345. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  346. this.rawObject.pushUsemtl( concatBuffer );
  347. this.flushStringBuffer( buffer, bufferPointer );
  348. break;
  349. default:
  350. break;
  351. }
  352. return reachedFaces;
  353. };
  354. Parser.prototype.flushStringBuffer = function ( buffer, bufferLength ) {
  355. for ( var i = 0; i < bufferLength; i++ ) {
  356. buffer[ i ] = '';
  357. }
  358. };
  359. Parser.prototype.processCompletedObject = function ( objectName, groupName ) {
  360. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  361. this.inputObjectCount++;
  362. this.rawObject = this.rawObject.newInstanceFromObject( objectName, groupName );
  363. };
  364. Parser.prototype.processCompletedGroup = function ( groupName ) {
  365. var notEmpty = this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  366. if ( notEmpty ) {
  367. this.inputObjectCount ++;
  368. this.rawObject = this.rawObject.newInstanceFromGroup( groupName );
  369. } else {
  370. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  371. this.rawObject.pushGroup( groupName );
  372. }
  373. };
  374. Parser.prototype.finalize = function () {
  375. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  376. this.inputObjectCount++;
  377. };
  378. return Parser;
  379. })();
  380. /**
  381. * {@link RawObject} is only used by {@link Parser}.
  382. * The user of OBJLoader2 does not need to care about this class.
  383. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  384. */
  385. var RawObject = (function () {
  386. function RawObject( objectName, groupName, activeMtlName ) {
  387. this.globalVertexOffset = 1;
  388. this.globalUvOffset = 1;
  389. this.globalNormalOffset = 1;
  390. this.vertices = [];
  391. this.colors = [];
  392. this.normals = [];
  393. this.uvs = [];
  394. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  395. this.activeMtlName = Validator.verifyInput( activeMtlName, '' );
  396. this.objectName = Validator.verifyInput( objectName, '' );
  397. this.groupName = Validator.verifyInput( groupName, '' );
  398. this.activeSmoothingGroup = 1;
  399. this.mtlCount = 0;
  400. this.smoothingGroupCount = 0;
  401. this.rawObjectDescriptions = [];
  402. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  403. var index = this.buildIndex( this.activeMtlName, this.activeSmoothingGroup );
  404. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  405. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  406. }
  407. RawObject.prototype.buildIndex = function ( materialName, smoothingGroup) {
  408. return materialName + '|' + smoothingGroup;
  409. };
  410. RawObject.prototype.newInstanceFromObject = function ( objectName, groupName ) {
  411. var newRawObject = new RawObject( objectName, groupName, this.activeMtlName );
  412. // move indices forward
  413. newRawObject.globalVertexOffset = this.globalVertexOffset + this.vertices.length / 3;
  414. newRawObject.globalUvOffset = this.globalUvOffset + this.uvs.length / 2;
  415. newRawObject.globalNormalOffset = this.globalNormalOffset + this.normals.length / 3;
  416. return newRawObject;
  417. };
  418. RawObject.prototype.newInstanceFromGroup = function ( groupName ) {
  419. var newRawObject = new RawObject( this.objectName, groupName, this.activeMtlName );
  420. // keep current buffers and indices forward
  421. newRawObject.vertices = this.vertices;
  422. newRawObject.colors = this.colors;
  423. newRawObject.uvs = this.uvs;
  424. newRawObject.normals = this.normals;
  425. newRawObject.globalVertexOffset = this.globalVertexOffset;
  426. newRawObject.globalUvOffset = this.globalUvOffset;
  427. newRawObject.globalNormalOffset = this.globalNormalOffset;
  428. return newRawObject;
  429. };
  430. RawObject.prototype.pushVertex = function ( buffer ) {
  431. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  432. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  433. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  434. };
  435. RawObject.prototype.pushVertexAndVertextColors = function ( buffer ) {
  436. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  437. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  438. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  439. this.colors.push( parseFloat( buffer[ 4 ] ) );
  440. this.colors.push( parseFloat( buffer[ 5 ] ) );
  441. this.colors.push( parseFloat( buffer[ 6 ] ) );
  442. };
  443. RawObject.prototype.pushUv = function ( buffer ) {
  444. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  445. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  446. };
  447. RawObject.prototype.pushNormal = function ( buffer ) {
  448. this.normals.push( parseFloat( buffer[ 1 ] ) );
  449. this.normals.push( parseFloat( buffer[ 2 ] ) );
  450. this.normals.push( parseFloat( buffer[ 3 ] ) );
  451. };
  452. RawObject.prototype.pushObject = function ( objectName ) {
  453. this.objectName = objectName;
  454. };
  455. RawObject.prototype.pushMtllib = function ( mtllibName ) {
  456. this.mtllibName = mtllibName;
  457. };
  458. RawObject.prototype.pushGroup = function ( groupName ) {
  459. this.groupName = groupName;
  460. this.verifyIndex();
  461. };
  462. RawObject.prototype.pushUsemtl = function ( mtlName ) {
  463. if ( this.activeMtlName === mtlName || ! Validator.isValid( mtlName ) ) return;
  464. this.activeMtlName = mtlName;
  465. this.mtlCount++;
  466. this.verifyIndex();
  467. };
  468. RawObject.prototype.pushSmoothingGroup = function ( activeSmoothingGroup ) {
  469. var normalized = parseInt( activeSmoothingGroup );
  470. if ( isNaN( normalized ) ) {
  471. normalized = activeSmoothingGroup === "off" ? 0 : 1;
  472. }
  473. if ( this.activeSmoothingGroup === normalized ) return;
  474. this.activeSmoothingGroup = normalized;
  475. this.smoothingGroupCount++;
  476. this.verifyIndex();
  477. };
  478. RawObject.prototype.verifyIndex = function () {
  479. var index = this.buildIndex( this.activeMtlName, ( this.activeSmoothingGroup === 0 ) ? 0 : 1 );
  480. this.rawObjectDescriptionInUse = this.rawObjectDescriptions[ index ];
  481. if ( ! Validator.isValid( this.rawObjectDescriptionInUse ) ) {
  482. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  483. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  484. }
  485. };
  486. RawObject.prototype.processFaces = function ( buffer, bufferPointer, slashesCount ) {
  487. var bufferLength = bufferPointer - 1;
  488. var i;
  489. // "f vertex ..."
  490. if ( slashesCount === 0 ) {
  491. for ( i = 2; i < bufferLength - 1; i ++ ) {
  492. this.attachFace( buffer[ 1 ] );
  493. this.attachFace( buffer[ i ] );
  494. this.attachFace( buffer[ i + 1 ] );
  495. }
  496. // "f vertex/uv ..."
  497. } else if ( bufferLength === slashesCount * 2 ) {
  498. for ( i = 3; i < bufferLength - 2; i += 2 ) {
  499. this.attachFace( buffer[ 1 ], buffer[ 2 ] );
  500. this.attachFace( buffer[ i ], buffer[ i + 1 ] );
  501. this.attachFace( buffer[ i + 2 ], buffer[ i + 3 ] );
  502. }
  503. // "f vertex/uv/normal ..."
  504. } else if ( bufferLength * 2 === slashesCount * 3 ) {
  505. for ( i = 4; i < bufferLength - 3; i += 3 ) {
  506. this.attachFace( buffer[ 1 ], buffer[ 2 ], buffer[ 3 ] );
  507. this.attachFace( buffer[ i ], buffer[ i + 1 ], buffer[ i + 2 ] );
  508. this.attachFace( buffer[ i + 3 ], buffer[ i + 4 ], buffer[ i + 5 ] );
  509. }
  510. // "f vertex//normal ..."
  511. } else {
  512. for ( i = 3; i < bufferLength - 2; i += 2 ) {
  513. this.attachFace( buffer[ 1 ], undefined, buffer[ 2 ] );
  514. this.attachFace( buffer[ i ], undefined, buffer[ i + 1 ] );
  515. this.attachFace( buffer[ i + 2 ], undefined, buffer[ i + 3 ] );
  516. }
  517. }
  518. };
  519. RawObject.prototype.attachFace = function ( faceIndexV, faceIndexU, faceIndexN ) {
  520. var indexV = ( parseInt( faceIndexV ) - this.globalVertexOffset ) * 3;
  521. var vertices = this.rawObjectDescriptionInUse.vertices;
  522. vertices.push( this.vertices[ indexV ++ ] );
  523. vertices.push( this.vertices[ indexV ++ ] );
  524. vertices.push( this.vertices[ indexV ] );
  525. if ( this.colors.length > 0 ) {
  526. indexV -= 2;
  527. var colors = this.rawObjectDescriptionInUse.colors;
  528. colors.push( this.colors[ indexV ++ ] );
  529. colors.push( this.colors[ indexV ++ ] );
  530. colors.push( this.colors[ indexV ] );
  531. }
  532. if ( faceIndexU ) {
  533. var indexU = ( parseInt( faceIndexU ) - this.globalUvOffset ) * 2;
  534. var uvs = this.rawObjectDescriptionInUse.uvs;
  535. uvs.push( this.uvs[ indexU ++ ] );
  536. uvs.push( this.uvs[ indexU ] );
  537. }
  538. if ( faceIndexN ) {
  539. var indexN = ( parseInt( faceIndexN ) - this.globalNormalOffset ) * 3;
  540. var normals = this.rawObjectDescriptionInUse.normals;
  541. normals.push( this.normals[ indexN ++ ] );
  542. normals.push( this.normals[ indexN ++ ] );
  543. normals.push( this.normals[ indexN ] );
  544. }
  545. };
  546. /*
  547. * Support for lines with or without texture. irst element in indexArray is the line identification
  548. * 0: "f vertex/uv vertex/uv ..."
  549. * 1: "f vertex vertex ..."
  550. */
  551. RawObject.prototype.buildLineVvt = function ( lineArray ) {
  552. var length = lineArray.length;
  553. for ( var i = 1; i < length; i ++ ) {
  554. this.vertices.push( parseInt( lineArray[ i ] ) );
  555. this.uvs.push( parseInt( lineArray[ i ] ) );
  556. }
  557. };
  558. RawObject.prototype.buildLineV = function ( lineArray ) {
  559. var length = lineArray.length;
  560. for ( var i = 1; i < length; i++ ) {
  561. this.vertices.push( parseInt( lineArray[ i ] ) );
  562. }
  563. };
  564. /**
  565. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  566. */
  567. RawObject.prototype.finalize = function ( meshCreator, inputObjectCount, debug ) {
  568. var temp = [];
  569. var rawObjectDescription;
  570. var index = 0;
  571. var absoluteVertexCount = 0;
  572. var absoluteColorCount = 0;
  573. var absoluteNormalCount = 0;
  574. var absoluteUvCount = 0;
  575. for ( var name in this.rawObjectDescriptions ) {
  576. rawObjectDescription = this.rawObjectDescriptions[ name ];
  577. if ( rawObjectDescription.vertices.length > 0 ) {
  578. temp[ index++ ] = rawObjectDescription;
  579. absoluteVertexCount += rawObjectDescription.vertices.length;
  580. absoluteColorCount += rawObjectDescription.colors.length;
  581. absoluteUvCount += rawObjectDescription.uvs.length;
  582. absoluteNormalCount += rawObjectDescription.normals.length;
  583. }
  584. }
  585. // don not continue if no result
  586. var notEmpty = false;
  587. if ( index > 0 ) {
  588. if ( debug ) this.createReport( inputObjectCount, true );
  589. meshCreator.buildMesh(
  590. temp,
  591. inputObjectCount,
  592. absoluteVertexCount,
  593. absoluteColorCount,
  594. absoluteNormalCount,
  595. absoluteUvCount
  596. );
  597. notEmpty = true;
  598. }
  599. return notEmpty;
  600. };
  601. RawObject.prototype.createReport = function ( inputObjectCount, printDirectly ) {
  602. var report = {
  603. name: this.objectName ? this.objectName : 'groups',
  604. mtllibName: this.mtllibName,
  605. vertexCount: this.vertices.length / 3,
  606. normalCount: this.normals.length / 3,
  607. uvCount: this.uvs.length / 2,
  608. smoothingGroupCount: this.smoothingGroupCount,
  609. mtlCount: this.mtlCount,
  610. rawObjectDescriptions: this.rawObjectDescriptions.length
  611. };
  612. if ( printDirectly ) {
  613. console.log( 'Input Object number: ' + inputObjectCount + ' Object name: ' + report.name );
  614. console.log( 'Mtllib name: ' + report.mtllibName );
  615. console.log( 'Vertex count: ' + report.vertexCount );
  616. console.log( 'Normal count: ' + report.normalCount );
  617. console.log( 'UV count: ' + report.uvCount );
  618. console.log( 'SmoothingGroup count: ' + report.smoothingGroupCount );
  619. console.log( 'Material count: ' + report.mtlCount );
  620. console.log( 'Real RawObjectDescription count: ' + report.rawObjectDescriptions );
  621. console.log( '' );
  622. }
  623. return report;
  624. };
  625. return RawObject;
  626. })();
  627. /**
  628. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  629. * @class
  630. *
  631. * @param {string} objectName Name of the mesh
  632. * @param {string} groupName Name of the group
  633. * @param {string} materialName Name of the material
  634. * @param {number} smoothingGroup Normalized smoothingGroup (0: flat shading, 1: smooth shading)
  635. */
  636. var RawObjectDescription = (function () {
  637. function RawObjectDescription( objectName, groupName, materialName, smoothingGroup ) {
  638. this.objectName = objectName;
  639. this.groupName = groupName;
  640. this.materialName = materialName;
  641. this.smoothingGroup = smoothingGroup;
  642. this.vertices = [];
  643. this.colors = [];
  644. this.uvs = [];
  645. this.normals = [];
  646. }
  647. return RawObjectDescription;
  648. })();
  649. /**
  650. * MeshCreator is used to transform RawObjectDescriptions to THREE.Mesh
  651. *
  652. * @class
  653. */
  654. var MeshCreator = (function () {
  655. function MeshCreator() {
  656. this.sceneGraphBaseNode = null;
  657. this.materials = null;
  658. this.debug = false;
  659. this.globalObjectCount = 1;
  660. this.validated = false;
  661. }
  662. MeshCreator.prototype.setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  663. this.sceneGraphBaseNode = Validator.verifyInput( sceneGraphBaseNode, this.sceneGraphBaseNode );
  664. this.sceneGraphBaseNode = Validator.verifyInput( this.sceneGraphBaseNode, new THREE.Group() );
  665. };
  666. MeshCreator.prototype.setMaterials = function ( materials ) {
  667. this.materials = Validator.verifyInput( materials, this.materials );
  668. this.materials = Validator.verifyInput( this.materials, { materials: [] } );
  669. var defaultMaterial = this.materials[ 'defaultMaterial' ];
  670. if ( ! defaultMaterial ) {
  671. defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  672. defaultMaterial.name = 'defaultMaterial';
  673. this.materials[ 'defaultMaterial' ] = defaultMaterial;
  674. }
  675. var vertexColorMaterial = this.materials[ 'vertexColorMaterial' ];
  676. if ( ! vertexColorMaterial ) {
  677. vertexColorMaterial = new THREE.MeshBasicMaterial( { color: 0xDCF1FF } );
  678. vertexColorMaterial.name = 'vertexColorMaterial';
  679. vertexColorMaterial.vertexColors = THREE.VertexColors;
  680. this.materials[ 'vertexColorMaterial' ] = vertexColorMaterial;
  681. }
  682. };
  683. MeshCreator.prototype.setDebug = function ( debug ) {
  684. if ( debug === true || debug === false ) this.debug = debug;
  685. };
  686. MeshCreator.prototype.validate = function () {
  687. if ( this.validated ) return;
  688. this.setSceneGraphBaseNode( null );
  689. this.setMaterials( null );
  690. this.setDebug( null );
  691. this.globalObjectCount = 1;
  692. };
  693. MeshCreator.prototype.finalize = function () {
  694. this.sceneGraphBaseNode = null;
  695. this.materials = null;
  696. this.validated = false;
  697. };
  698. /**
  699. * This is an internal function, but due to its importance to Parser it is documented.
  700. * RawObjectDescriptions are transformed to THREE.Mesh.
  701. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  702. * This method shall be overridden by the web worker implementation
  703. *
  704. * @param {RawObjectDescription[]} rawObjectDescriptions Array of descriptive information and data (vertices, normals, uvs) about the parsed object(s)
  705. * @param {number} inputObjectCount Number of objects already retrieved from OBJ
  706. * @param {number} absoluteVertexCount Sum of all vertices of all rawObjectDescriptions
  707. * @param {number} absoluteColorCount Sum of all vertex colors of all rawObjectDescriptions
  708. * @param {number} absoluteNormalCount Sum of all normals of all rawObjectDescriptions
  709. * @param {number} absoluteUvCount Sum of all uvs of all rawObjectDescriptions
  710. */
  711. MeshCreator.prototype.buildMesh = function ( rawObjectDescriptions, inputObjectCount, absoluteVertexCount,
  712. absoluteColorCount, absoluteNormalCount, absoluteUvCount ) {
  713. if ( this.debug ) console.log( 'MeshCreator.buildRawMeshData:\nInput object no.: ' + inputObjectCount );
  714. var bufferGeometry = new THREE.BufferGeometry();
  715. var vertexBA = new THREE.BufferAttribute( new Float32Array( absoluteVertexCount ), 3 );
  716. bufferGeometry.addAttribute( 'position', vertexBA );
  717. var colorBA;
  718. if ( absoluteColorCount > 0 ) {
  719. colorBA = new THREE.BufferAttribute( new Float32Array( absoluteColorCount ), 3 );
  720. bufferGeometry.addAttribute( 'color', colorBA );
  721. }
  722. var normalBA;
  723. if ( absoluteNormalCount > 0 ) {
  724. normalBA = new THREE.BufferAttribute( new Float32Array( absoluteNormalCount ), 3 );
  725. bufferGeometry.addAttribute( 'normal', normalBA );
  726. }
  727. var uvBA;
  728. if ( absoluteUvCount > 0 ) {
  729. uvBA = new THREE.BufferAttribute( new Float32Array( absoluteUvCount ), 2 );
  730. bufferGeometry.addAttribute( 'uv', uvBA );
  731. }
  732. var rawObjectDescription;
  733. var material;
  734. var materialName;
  735. var createMultiMaterial = rawObjectDescriptions.length > 1;
  736. var materials = [];
  737. var materialIndex = 0;
  738. var materialIndexMapping = [];
  739. var selectedMaterialIndex;
  740. var vertexBAOffset = 0;
  741. var vertexGroupOffset = 0;
  742. var vertexLength;
  743. var colorBAOffset = 0;
  744. var normalBAOffset = 0;
  745. var uvBAOffset = 0;
  746. if ( this.debug ) {
  747. console.log( createMultiMaterial ? 'Creating Multi-Material' : 'Creating Material' + ' for object no.: ' + this.globalObjectCount );
  748. }
  749. for ( var oodIndex in rawObjectDescriptions ) {
  750. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  751. materialName = rawObjectDescription.materialName;
  752. material = colorBA ? this.materials[ 'vertexColorMaterial' ] : this.materials[ materialName ];
  753. if ( ! material ) {
  754. material = this.materials[ 'defaultMaterial' ];
  755. if ( ! material ) console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName +
  756. '" was defined without material! Assigning "defaultMaterial".' );
  757. }
  758. // clone material in case flat shading is needed due to smoothingGroup 0
  759. if ( rawObjectDescription.smoothingGroup === 0 ) {
  760. materialName = material.name + '_flat';
  761. var materialClone = this.materials[ materialName ];
  762. if ( ! materialClone ) {
  763. materialClone = material.clone();
  764. materialClone.name = materialName;
  765. materialClone.flatShading = true;
  766. this.materials[ materialName ] = name;
  767. }
  768. }
  769. vertexLength = rawObjectDescription.vertices.length;
  770. if ( createMultiMaterial ) {
  771. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  772. selectedMaterialIndex = materialIndexMapping[ materialName ];
  773. if ( ! selectedMaterialIndex ) {
  774. selectedMaterialIndex = materialIndex;
  775. materialIndexMapping[ materialName ] = materialIndex;
  776. materials.push( material );
  777. materialIndex++;
  778. }
  779. bufferGeometry.addGroup( vertexGroupOffset, vertexLength / 3, selectedMaterialIndex );
  780. vertexGroupOffset += vertexLength / 3;
  781. }
  782. vertexBA.set( rawObjectDescription.vertices, vertexBAOffset );
  783. vertexBAOffset += vertexLength;
  784. if ( colorBA ) {
  785. colorBA.set( rawObjectDescription.colors, colorBAOffset );
  786. colorBAOffset += rawObjectDescription.colors.length;
  787. }
  788. if ( normalBA ) {
  789. normalBA.set( rawObjectDescription.normals, normalBAOffset );
  790. normalBAOffset += rawObjectDescription.normals.length;
  791. }
  792. if ( uvBA ) {
  793. uvBA.set( rawObjectDescription.uvs, uvBAOffset );
  794. uvBAOffset += rawObjectDescription.uvs.length;
  795. }
  796. if ( this.debug ) this.printReport( rawObjectDescription, selectedMaterialIndex );
  797. }
  798. if ( ! normalBA ) bufferGeometry.computeVertexNormals();
  799. if ( createMultiMaterial ) material = materials;
  800. var mesh = new THREE.Mesh( bufferGeometry, material );
  801. mesh.name = rawObjectDescription.groupName !== '' ? rawObjectDescription.groupName : rawObjectDescription.objectName;
  802. this.sceneGraphBaseNode.add( mesh );
  803. this.globalObjectCount++;
  804. };
  805. MeshCreator.prototype.printReport = function ( rawObjectDescription, selectedMaterialIndex ) {
  806. var materialIndexLine = Validator.isValid( selectedMaterialIndex ) ? '\n materialIndex: ' + selectedMaterialIndex : '';
  807. console.log(
  808. ' Output Object no.: ' + this.globalObjectCount +
  809. '\n objectName: ' + rawObjectDescription.objectName +
  810. '\n groupName: ' + rawObjectDescription.groupName +
  811. '\n materialName: ' + rawObjectDescription.materialName +
  812. materialIndexLine +
  813. '\n smoothingGroup: ' + rawObjectDescription.smoothingGroup +
  814. '\n #vertices: ' + rawObjectDescription.vertices.length / 3 +
  815. '\n #colors: ' + rawObjectDescription.colors.length / 3 +
  816. '\n #uvs: ' + rawObjectDescription.uvs.length / 2 +
  817. '\n #normals: ' + rawObjectDescription.normals.length / 3
  818. );
  819. };
  820. return MeshCreator;
  821. })();
  822. OBJLoader2.prototype._buildWebWorkerCode = function ( funcBuildObject, funcBuildSingelton ) {
  823. var workerCode = '';
  824. workerCode += funcBuildObject( 'Consts', Consts );
  825. workerCode += funcBuildObject( 'Validator', Validator );
  826. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  827. workerCode += funcBuildSingelton( 'RawObject', 'RawObject', RawObject );
  828. workerCode += funcBuildSingelton( 'RawObjectDescription', 'RawObjectDescription', RawObjectDescription );
  829. return workerCode;
  830. };
  831. return OBJLoader2;
  832. })();