OBJLoader2.js 32 KB

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