OBJLoader2.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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 an arraybuffer
  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 = '2.0.1';
  15. var Commons = THREE.LoaderSupport.Commons;
  16. var Validator = THREE.LoaderSupport.Validator;
  17. var ConsoleLogger = THREE.LoaderSupport.ConsoleLogger;
  18. OBJLoader2.prototype = Object.create( THREE.LoaderSupport.Commons.prototype );
  19. OBJLoader2.prototype.constructor = OBJLoader2;
  20. function OBJLoader2( logger, manager ) {
  21. THREE.LoaderSupport.Commons.call( this, logger, manager );
  22. this.logger.logInfo( 'Using THREE.OBJLoader2 version: ' + OBJLOADER2_VERSION );
  23. this.materialPerSmoothingGroup = false;
  24. this.fileLoader = Validator.verifyInput( this.fileLoader, new THREE.FileLoader( this.manager ) );
  25. this.workerSupport = null;
  26. this.terminateWorkerOnLoad = true;
  27. };
  28. /**
  29. * Tells whether a material shall be created per smoothing group.
  30. * @memberOf THREE.OBJLoader2
  31. *
  32. * @param {boolean} materialPerSmoothingGroup=false
  33. */
  34. OBJLoader2.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
  35. this.materialPerSmoothingGroup = materialPerSmoothingGroup === true;
  36. };
  37. /**
  38. * Use this convenient method to load an OBJ file at the given URL. Per default the fileLoader uses an arraybuffer.
  39. * @memberOf THREE.OBJLoader2
  40. *
  41. * @param {string} url URL of the file to load
  42. * @param {callback} onLoad Called after loading was successfully completed
  43. * @param {callback} onProgress Called to report progress of loading. The argument will be the XMLHttpRequest instance, which contains {integer total} and {integer loaded} bytes.
  44. * @param {callback} onError Called after an error occurred during loading
  45. * @param {callback} onMeshAlter Called after a new mesh raw data becomes available to allow alteration
  46. * @param {boolean} useAsync If true uses async loading with worker, if false loads data synchronously
  47. */
  48. OBJLoader2.prototype.load = function ( url, onLoad, onProgress, onError, onMeshAlter, useAsync ) {
  49. var scope = this;
  50. if ( ! Validator.isValid( onProgress ) ) {
  51. var numericalValueRef = 0;
  52. var numericalValue = 0;
  53. onProgress = function ( event ) {
  54. if ( ! event.lengthComputable ) return;
  55. numericalValue = event.loaded / event.total;
  56. if ( numericalValue > numericalValueRef ) {
  57. numericalValueRef = numericalValue;
  58. var output = 'Download of "' + url + '": ' + ( numericalValue * 100 ).toFixed( 2 ) + '%';
  59. scope.onProgress( 'progressLoad', output, numericalValue );
  60. }
  61. };
  62. }
  63. if ( ! Validator.isValid( onError ) ) {
  64. onError = function ( event ) {
  65. var output = 'Error occurred while downloading "' + url + '"';
  66. scope.logger.logError( output + ': ' + event );
  67. scope.onProgress( 'error', output, -1 );
  68. };
  69. }
  70. this.fileLoader.setPath( this.path );
  71. this.fileLoader.setResponseType( 'arraybuffer' );
  72. this.fileLoader.load( url, function ( content ) {
  73. if ( useAsync ) {
  74. scope.parseAsync( content, onLoad );
  75. } else {
  76. scope._setCallbacks( null, onMeshAlter, null );
  77. onLoad(
  78. {
  79. detail: {
  80. loaderRootNode: scope.parse( content ),
  81. modelName: scope.modelName,
  82. instanceNo: scope.instanceNo
  83. }
  84. }
  85. );
  86. }
  87. }, onProgress, onError );
  88. };
  89. /**
  90. * Run the loader according the provided instructions.
  91. * @memberOf THREE.OBJLoader2
  92. *
  93. * @param {THREE.LoaderSupport.PrepData} prepData All parameters and resources required for execution
  94. * @param {THREE.LoaderSupport.WorkerSupport} [workerSupportExternal] Use pre-existing WorkerSupport
  95. */
  96. OBJLoader2.prototype.run = function ( prepData, workerSupportExternal ) {
  97. this._applyPrepData( prepData );
  98. var available = this._checkFiles( prepData.resources );
  99. if ( Validator.isValid( workerSupportExternal ) ) {
  100. this.terminateWorkerOnLoad = false;
  101. this.workerSupport = workerSupportExternal;
  102. this.logger = workerSupportExternal.logger;
  103. } else {
  104. this.terminateWorkerOnLoad = true;
  105. }
  106. var scope = this;
  107. var onMaterialsLoaded = function ( materials ) {
  108. scope.builder.setMaterials( materials );
  109. if ( Validator.isValid( available.obj.content ) ) {
  110. if ( prepData.useAsync ) {
  111. scope.parseAsync( available.obj.content, scope.callbacks.onLoad );
  112. } else {
  113. scope.parse( available.obj.content );
  114. }
  115. } else {
  116. scope.setPath( available.obj.path );
  117. scope.load( available.obj.name, scope.callbacks.onLoad, null, null, scope.callbacks.onMeshAlter, prepData.useAsync );
  118. }
  119. };
  120. this._loadMtl( available.mtl, onMaterialsLoaded, prepData.crossOrigin );
  121. };
  122. OBJLoader2.prototype._applyPrepData = function ( prepData ) {
  123. THREE.LoaderSupport.Commons.prototype._applyPrepData.call( this, prepData );
  124. if ( Validator.isValid( prepData ) ) {
  125. this.setMaterialPerSmoothingGroup( prepData.materialPerSmoothingGroup );
  126. }
  127. };
  128. /**
  129. * Parses OBJ data synchronously from arraybuffer or string.
  130. * @memberOf THREE.OBJLoader2
  131. *
  132. * @param {arraybuffer|string} content OBJ data as Uint8Array or String
  133. */
  134. OBJLoader2.prototype.parse = function ( content ) {
  135. this.logger.logTimeStart( 'OBJLoader2 parse: ' + this.modelName );
  136. var parser = new Parser( this.logger );
  137. parser.setMaterialPerSmoothingGroup( this.materialPerSmoothingGroup );
  138. parser.setUseIndices( this.useIndices );
  139. parser.setDisregardNormals( this.disregardNormals );
  140. parser.setMaterialNames( this.builder.materialNames );
  141. var scope = this;
  142. var onMeshLoaded = function ( payload ) {
  143. var meshes = scope.builder.buildMeshes( payload );
  144. var mesh;
  145. for ( var i in meshes ) {
  146. mesh = meshes[ i ];
  147. scope.loaderRootNode.add( mesh );
  148. }
  149. };
  150. parser.setCallbackBuilder( onMeshLoaded );
  151. var onProgressScoped = function ( text, numericalValue ) {
  152. scope.onProgress( 'progressParse', text, numericalValue );
  153. };
  154. parser.setCallbackProgress( onProgressScoped );
  155. if ( content instanceof ArrayBuffer || content instanceof Uint8Array ) {
  156. this.logger.logInfo( 'Parsing arrayBuffer...' );
  157. parser.parse( content );
  158. } else if ( typeof( content ) === 'string' || content instanceof String ) {
  159. this.logger.logInfo( 'Parsing text...' );
  160. parser.parseText( content );
  161. } else {
  162. throw 'Provided content was neither of type String nor Uint8Array! Aborting...';
  163. }
  164. this.logger.logTimeEnd( 'OBJLoader2 parse: ' + this.modelName );
  165. return this.loaderRootNode;
  166. };
  167. /**
  168. * Parses OBJ content asynchronously from arraybuffer.
  169. * @memberOf THREE.OBJLoader2
  170. *
  171. * @param {arraybuffer} content OBJ data as Uint8Array
  172. * @param {callback} onLoad Called after worker successfully completed loading
  173. */
  174. OBJLoader2.prototype.parseAsync = function ( content, onLoad ) {
  175. this.logger.logTimeStart( 'OBJLoader2 parseAsync: ' + this.modelName );
  176. var scope = this;
  177. var scopedOnLoad = function () {
  178. onLoad(
  179. {
  180. detail: {
  181. loaderRootNode: scope.loaderRootNode,
  182. modelName: scope.modelName,
  183. instanceNo: scope.instanceNo
  184. }
  185. }
  186. );
  187. if ( scope.terminateWorkerOnLoad ) scope.workerSupport.terminateWorker();
  188. scope.logger.logTimeEnd( 'OBJLoader2 parseAsync: ' + scope.modelName );
  189. };
  190. var scopedOnMeshLoaded = function ( payload ) {
  191. var meshes = scope.builder.buildMeshes( payload );
  192. var mesh;
  193. for ( var i in meshes ) {
  194. mesh = meshes[ i ];
  195. scope.loaderRootNode.add( mesh );
  196. }
  197. };
  198. this.workerSupport = Validator.verifyInput( this.workerSupport, new THREE.LoaderSupport.WorkerSupport( this.logger ) );
  199. var buildCode = function ( funcBuildObject, funcBuildSingelton ) {
  200. var workerCode = '';
  201. workerCode += '/**\n';
  202. workerCode += ' * This code was constructed by OBJLoader2 buildWorkerCode.\n';
  203. workerCode += ' */\n\n';
  204. workerCode += funcBuildSingelton( 'Commons', 'Commons', Commons );
  205. workerCode += funcBuildObject( 'Consts', Consts );
  206. workerCode += funcBuildObject( 'Validator', Validator );
  207. workerCode += funcBuildSingelton( 'ConsoleLogger', 'ConsoleLogger', ConsoleLogger );
  208. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  209. workerCode += funcBuildSingelton( 'RawMesh', 'RawMesh', RawMesh );
  210. workerCode += funcBuildSingelton( 'RawMeshSubGroup', 'RawMeshSubGroup', RawMeshSubGroup );
  211. return workerCode;
  212. };
  213. this.workerSupport.validate( buildCode, false );
  214. this.workerSupport.setCallbacks( scopedOnMeshLoaded, scopedOnLoad );
  215. this.workerSupport.run(
  216. {
  217. cmd: 'run',
  218. params: {
  219. materialPerSmoothingGroup: this.materialPerSmoothingGroup,
  220. useIndices: this.useIndices,
  221. disregardNormals: this.disregardNormals
  222. },
  223. logger: {
  224. debug: this.logger.debug,
  225. enabled: this.logger.enabled
  226. },
  227. materials: {
  228. materialNames: this.builder.materialNames
  229. },
  230. buffers: {
  231. input: content
  232. }
  233. },
  234. [ content.buffer ]
  235. );
  236. };
  237. /**
  238. * Constants used by THREE.OBJLoader2
  239. */
  240. var Consts = {
  241. CODE_LF: 10,
  242. CODE_CR: 13,
  243. CODE_SPACE: 32,
  244. CODE_SLASH: 47,
  245. STRING_LF: '\n',
  246. STRING_CR: '\r',
  247. STRING_SPACE: ' ',
  248. STRING_SLASH: '/',
  249. LINE_F: 'f',
  250. LINE_G: 'g',
  251. LINE_L: 'l',
  252. LINE_O: 'o',
  253. LINE_S: 's',
  254. LINE_V: 'v',
  255. LINE_VT: 'vt',
  256. LINE_VN: 'vn',
  257. LINE_MTLLIB: 'mtllib',
  258. LINE_USEMTL: 'usemtl'
  259. };
  260. /**
  261. * Parse OBJ data either from ArrayBuffer or string
  262. * @class
  263. */
  264. var Parser = (function () {
  265. function Parser( logger ) {
  266. this.callbackProgress = null;
  267. this.callbackBuilder = null;
  268. this.materialNames = [];
  269. this.rawMesh = null;
  270. this.materialPerSmoothingGroup = false;
  271. this.useIndices = false;
  272. this.disregardNormals = false;
  273. this.inputObjectCount = 1;
  274. this.outputObjectCount = 1;
  275. this.counts = {
  276. vertices: 0,
  277. faces: 0,
  278. doubleIndicesCount: 0
  279. };
  280. this.logger = logger;
  281. this.totalBytes = 0;
  282. };
  283. Parser.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
  284. this.materialPerSmoothingGroup = materialPerSmoothingGroup;
  285. };
  286. Parser.prototype.setUseIndices = function ( useIndices ) {
  287. this.useIndices = useIndices;
  288. };
  289. Parser.prototype.setDisregardNormals = function ( disregardNormals ) {
  290. this.disregardNormals = disregardNormals;
  291. };
  292. Parser.prototype.setMaterialNames = function ( materialNames ) {
  293. this.materialNames = Validator.verifyInput( materialNames, this.materialNames );
  294. this.materialNames = Validator.verifyInput( this.materialNames, [] );
  295. };
  296. Parser.prototype.setCallbackBuilder = function ( callbackBuilder ) {
  297. this.callbackBuilder = callbackBuilder;
  298. if ( ! Validator.isValid( this.callbackBuilder ) ) throw 'Unable to run as no "builder" callback is set.';
  299. };
  300. Parser.prototype.setCallbackProgress = function ( callbackProgress ) {
  301. this.callbackProgress = callbackProgress;
  302. };
  303. Parser.prototype.configure = function () {
  304. this.rawMesh = new RawMesh( this.materialPerSmoothingGroup, this.useIndices, this.disregardNormals );
  305. if ( this.logger.isEnabled() ) {
  306. var matNames = ( this.materialNames.length > 0 ) ? '\n\tmaterialNames:\n\t\t- ' + this.materialNames.join( '\n\t\t- ' ) : '\n\tmaterialNames: None';
  307. var printedConfig = 'OBJLoader2.Parser configuration:'
  308. + matNames
  309. + '\n\tmaterialPerSmoothingGroup: ' + this.materialPerSmoothingGroup
  310. + '\n\tuseIndices: ' + this.useIndices
  311. + '\n\tdisregardNormals: ' + this.disregardNormals
  312. + '\n\tcallbackBuilderName: ' + this.callbackBuilder.name
  313. + '\n\tcallbackProgressName: ' + this.callbackProgress.name;
  314. this.logger.logInfo( printedConfig );
  315. }
  316. };
  317. /**
  318. * Parse the provided arraybuffer
  319. * @memberOf Parser
  320. *
  321. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  322. */
  323. Parser.prototype.parse = function ( arrayBuffer ) {
  324. this.logger.logTimeStart( 'OBJLoader2.Parser.parse' );
  325. this.configure();
  326. var arrayBufferView = new Uint8Array( arrayBuffer );
  327. var length = arrayBufferView.byteLength;
  328. this.totalBytes = length;
  329. var buffer = new Array( 128 );
  330. var bufferPointer = 0;
  331. var slashSpacePattern = new Array( 16 );
  332. var slashSpacePatternPointer = 0;
  333. var reachedFaces = false;
  334. var code;
  335. var word = '';
  336. var i = 0;
  337. for ( ; i < length; i++ ) {
  338. code = arrayBufferView[ i ];
  339. switch ( code ) {
  340. case Consts.CODE_SPACE:
  341. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  342. slashSpacePattern[ slashSpacePatternPointer++ ] = 0;
  343. word = '';
  344. break;
  345. case Consts.CODE_SLASH:
  346. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  347. slashSpacePattern[ slashSpacePatternPointer++ ] = 1;
  348. word = '';
  349. break;
  350. case Consts.CODE_LF:
  351. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  352. word = '';
  353. reachedFaces = this.processLine( buffer, bufferPointer, slashSpacePattern, slashSpacePatternPointer, reachedFaces, i );
  354. bufferPointer = 0;
  355. slashSpacePatternPointer = 0;
  356. break;
  357. case Consts.CODE_CR:
  358. break;
  359. default:
  360. word += String.fromCharCode( code );
  361. break;
  362. }
  363. }
  364. this.finalize( i );
  365. this.logger.logTimeEnd( 'OBJLoader2.Parser.parse' );
  366. };
  367. /**
  368. * Parse the provided text
  369. * @memberOf Parser
  370. *
  371. * @param {string} text OBJ data as string
  372. */
  373. Parser.prototype.parseText = function ( text ) {
  374. this.logger.logTimeStart( 'OBJLoader2.Parser.parseText' );
  375. this.configure();
  376. var length = text.length;
  377. this.totalBytes = length;
  378. var buffer = new Array( 128 );
  379. var bufferPointer = 0;
  380. var slashSpacePattern = new Array( 16 );
  381. var slashSpacePatternPointer = 0;
  382. var reachedFaces = false;
  383. var char;
  384. var word = '';
  385. var i = 0;
  386. for ( ; i < length; i++ ) {
  387. char = text[ i ];
  388. switch ( char ) {
  389. case Consts.STRING_SPACE:
  390. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  391. slashSpacePattern[ slashSpacePatternPointer++ ] = 0;
  392. word = '';
  393. break;
  394. case Consts.STRING_SLASH:
  395. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  396. slashSpacePattern[ slashSpacePatternPointer++ ] = 1;
  397. word = '';
  398. break;
  399. case Consts.STRING_LF:
  400. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  401. word = '';
  402. reachedFaces = this.processLine( buffer, bufferPointer, slashSpacePattern, slashSpacePatternPointer, reachedFaces, i );
  403. bufferPointer = 0;
  404. slashSpacePatternPointer = 0;
  405. break;
  406. case Consts.STRING_CR:
  407. break;
  408. default:
  409. word += char;
  410. }
  411. }
  412. this.finalize( i );
  413. this.logger.logTimeEnd( 'OBJLoader2.Parser.parseText' );
  414. };
  415. Parser.prototype.processLine = function ( buffer, bufferPointer, slashSpacePattern, slashSpacePatternPointer, reachedFaces, currentByte ) {
  416. if ( bufferPointer < 1 ) return reachedFaces;
  417. var countSlashes = function ( slashSpacePattern, slashSpacePatternPointer ) {
  418. var slashesCount = 0;
  419. for ( var i = 0; i < slashSpacePatternPointer; i++ ) {
  420. slashesCount += slashSpacePattern[ i ];
  421. }
  422. return slashesCount;
  423. };
  424. var concatStringBuffer = function ( buffer, bufferPointer, slashSpacePattern ) {
  425. var concatBuffer = '';
  426. if ( bufferPointer === 2 ) {
  427. concatBuffer = buffer[ 1 ];
  428. } else {
  429. var bufferLength = bufferPointer - 1;
  430. for ( var i = 1; i < bufferLength; i++ ) {
  431. concatBuffer += buffer[ i ] + ( slashSpacePattern[ i ] === 0 ? ' ' : '/' );
  432. }
  433. concatBuffer += buffer[ bufferLength ];
  434. }
  435. return concatBuffer;
  436. };
  437. var flushStringBuffer = function ( buffer, bufferPointer ) {
  438. for ( var i = 0; i < bufferPointer; i++ ) {
  439. buffer[ i ] = '';
  440. }
  441. };
  442. switch ( buffer[ 0 ] ) {
  443. case Consts.LINE_V:
  444. // object complete instance required if reached faces already (= reached next block of v)
  445. if ( reachedFaces ) {
  446. if ( this.rawMesh.colors.length > 0 && this.rawMesh.colors.length !== this.rawMesh.vertices.length ) {
  447. throw 'Vertex Colors were detected, but vertex count and color count do not match!';
  448. }
  449. this.processCompletedObject( null, this.rawMesh.groupName, currentByte );
  450. reachedFaces = false;
  451. }
  452. if ( bufferPointer === 4 ) {
  453. this.rawMesh.pushVertex( buffer )
  454. } else {
  455. this.rawMesh.pushVertexAndVertextColors( buffer );
  456. }
  457. break;
  458. case Consts.LINE_VT:
  459. this.rawMesh.pushUv( buffer );
  460. break;
  461. case Consts.LINE_VN:
  462. this.rawMesh.pushNormal( buffer );
  463. break;
  464. case Consts.LINE_F:
  465. reachedFaces = true;
  466. this.rawMesh.processFaces( buffer, bufferPointer, countSlashes( slashSpacePattern, slashSpacePatternPointer ) );
  467. break;
  468. case Consts.LINE_L:
  469. this.rawMesh.processLines( buffer, bufferPointer, countSlashes( slashSpacePattern, slashSpacePatternPointer ) );
  470. break;
  471. case Consts.LINE_S:
  472. this.rawMesh.pushSmoothingGroup( buffer[ 1 ] );
  473. flushStringBuffer( buffer, bufferPointer );
  474. break;
  475. case Consts.LINE_G:
  476. this.processCompletedGroup( concatStringBuffer( buffer, bufferPointer, slashSpacePattern ), currentByte );
  477. flushStringBuffer( buffer, bufferPointer );
  478. break;
  479. case Consts.LINE_O:
  480. if ( this.rawMesh.vertices.length > 0 ) {
  481. this.processCompletedObject( concatStringBuffer( buffer, bufferPointer, slashSpacePattern ), null, currentByte );
  482. reachedFaces = false;
  483. } else {
  484. this.rawMesh.pushObject( concatStringBuffer( buffer, bufferPointer, slashSpacePattern ) );
  485. }
  486. flushStringBuffer( buffer, bufferPointer );
  487. break;
  488. case Consts.LINE_MTLLIB:
  489. this.rawMesh.pushMtllib( concatStringBuffer( buffer, bufferPointer, slashSpacePattern ) );
  490. flushStringBuffer( buffer, bufferPointer );
  491. break;
  492. case Consts.LINE_USEMTL:
  493. this.rawMesh.pushUsemtl( concatStringBuffer( buffer, bufferPointer, slashSpacePattern ) );
  494. flushStringBuffer( buffer, bufferPointer );
  495. break;
  496. default:
  497. break;
  498. }
  499. return reachedFaces;
  500. };
  501. Parser.prototype.createRawMeshReport = function ( rawMesh , inputObjectCount ) {
  502. var report = rawMesh.createReport( inputObjectCount );
  503. return 'Input Object number: ' + inputObjectCount +
  504. '\n\tObject name: ' + report.objectName +
  505. '\n\tGroup name: ' + report.groupName +
  506. '\n\tMtllib name: ' + report.mtllibName +
  507. '\n\tVertex count: ' + report.vertexCount +
  508. '\n\tNormal count: ' + report.normalCount +
  509. '\n\tUV count: ' + report.uvCount +
  510. '\n\tSmoothingGroup count: ' + report.smoothingGroupCount +
  511. '\n\tMaterial count: ' + report.mtlCount +
  512. '\n\tReal RawMeshSubGroup count: ' + report.subGroups;
  513. };
  514. Parser.prototype.processCompletedObject = function ( objectName, groupName, currentByte ) {
  515. var result = this.rawMesh.finalize();
  516. if ( Validator.isValid( result ) ) {
  517. this.inputObjectCount++;
  518. if ( this.logger.isDebug() ) this.logger.logDebug( this.createRawMeshReport( this.rawMesh, this.inputObjectCount ) );
  519. this.buildMesh( result, currentByte );
  520. var progressBytesPercent = currentByte / this.totalBytes;
  521. this.callbackProgress( 'Completed object: ' + objectName + ' Total progress: ' + ( progressBytesPercent * 100 ).toFixed( 2 ) + '%', progressBytesPercent );
  522. }
  523. this.rawMesh = this.rawMesh.newInstanceFromObject( objectName, groupName );
  524. };
  525. Parser.prototype.processCompletedGroup = function ( groupName, currentByte ) {
  526. var result = this.rawMesh.finalize();
  527. if ( Validator.isValid( result ) ) {
  528. this.inputObjectCount++;
  529. if ( this.logger.isDebug() ) this.logger.logDebug( this.createRawMeshReport( this.rawMesh, this.inputObjectCount ) );
  530. this.buildMesh( result, currentByte );
  531. var progressBytesPercent = currentByte / this.totalBytes;
  532. this.callbackProgress( 'Completed group: ' + groupName + ' Total progress: ' + ( progressBytesPercent * 100 ).toFixed( 2 ) + '%', progressBytesPercent );
  533. this.rawMesh = this.rawMesh.newInstanceFromGroup( groupName );
  534. } else {
  535. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  536. this.rawMesh.pushGroup( groupName );
  537. }
  538. };
  539. Parser.prototype.finalize = function ( currentByte ) {
  540. this.logger.logInfo( 'Global output object count: ' + this.outputObjectCount );
  541. var result = Validator.isValid( this.rawMesh ) ? this.rawMesh.finalize() : null;
  542. if ( Validator.isValid( result ) ) {
  543. this.inputObjectCount++;
  544. if ( this.logger.isDebug() ) this.logger.logDebug( this.createRawMeshReport( this.rawMesh, this.inputObjectCount ) );
  545. this.buildMesh( result, currentByte );
  546. if ( this.logger.isEnabled() ) {
  547. var parserFinalReport = 'Overall counts: ' +
  548. '\n\tVertices: ' + this.counts.vertices +
  549. '\n\tFaces: ' + this.counts.faces +
  550. '\n\tMultiple definitions: ' + this.counts.doubleIndicesCount;
  551. this.logger.logInfo( parserFinalReport );
  552. }
  553. var progressBytesPercent = currentByte / this.totalBytes;
  554. this.callbackProgress( 'Completed Parsing: 100.00%', progressBytesPercent );
  555. }
  556. };
  557. /**
  558. * RawObjectDescriptions are transformed to too intermediate format that is forwarded to the Builder.
  559. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  560. *
  561. * @param result
  562. */
  563. Parser.prototype.buildMesh = function ( result, currentByte ) {
  564. var rawObjectDescriptions = result.subGroups;
  565. var vertexFA = new Float32Array( result.absoluteVertexCount );
  566. this.counts.vertices += result.absoluteVertexCount / 3;
  567. this.counts.faces += result.faceCount;
  568. this.counts.doubleIndicesCount += result.doubleIndicesCount;
  569. var indexUA = ( result.absoluteIndexCount > 0 ) ? new Uint32Array( result.absoluteIndexCount ) : null;
  570. var colorFA = ( result.absoluteColorCount > 0 ) ? new Float32Array( result.absoluteColorCount ) : null;
  571. var normalFA = ( result.absoluteNormalCount > 0 ) ? new Float32Array( result.absoluteNormalCount ) : null;
  572. var uvFA = ( result.absoluteUvCount > 0 ) ? new Float32Array( result.absoluteUvCount ) : null;
  573. var rawObjectDescription;
  574. var materialDescription;
  575. var materialDescriptions = [];
  576. var createMultiMaterial = ( rawObjectDescriptions.length > 1 );
  577. var materialIndex = 0;
  578. var materialIndexMapping = [];
  579. var selectedMaterialIndex;
  580. var materialGroup;
  581. var materialGroups = [];
  582. var vertexFAOffset = 0;
  583. var indexUAOffset = 0;
  584. var colorFAOffset = 0;
  585. var normalFAOffset = 0;
  586. var uvFAOffset = 0;
  587. var materialGroupOffset = 0;
  588. var materialGroupLength = 0;
  589. for ( var oodIndex in rawObjectDescriptions ) {
  590. if ( ! rawObjectDescriptions.hasOwnProperty( oodIndex ) ) continue;
  591. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  592. materialDescription = {
  593. name: rawObjectDescription.materialName,
  594. flat: false,
  595. default: false
  596. };
  597. if ( this.materialNames[ materialDescription.name ] === null ) {
  598. materialDescription.default = true;
  599. this.logger.logWarn( 'object_group "' + rawObjectDescription.objectName + '_' +
  600. rawObjectDescription.groupName +
  601. '" was defined without material! Assigning "defaultMaterial".' );
  602. }
  603. // Attach '_flat' to materialName in case flat shading is needed due to smoothingGroup 0
  604. if ( rawObjectDescription.smoothingGroup === 0 ) materialDescription.flat = true;
  605. if ( createMultiMaterial ) {
  606. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  607. selectedMaterialIndex = materialIndexMapping[ materialDescription.name ];
  608. if ( ! selectedMaterialIndex ) {
  609. selectedMaterialIndex = materialIndex;
  610. materialIndexMapping[ materialDescription.name ] = materialIndex;
  611. materialDescriptions.push( materialDescription );
  612. materialIndex++;
  613. }
  614. materialGroupLength = this.useIndices ? rawObjectDescription.indices.length : rawObjectDescription.vertices.length / 3;
  615. materialGroup = {
  616. start: materialGroupOffset,
  617. count: materialGroupLength,
  618. index: selectedMaterialIndex
  619. };
  620. materialGroups.push( materialGroup );
  621. materialGroupOffset += materialGroupLength;
  622. } else {
  623. materialDescriptions.push( materialDescription );
  624. }
  625. vertexFA.set( rawObjectDescription.vertices, vertexFAOffset );
  626. vertexFAOffset += rawObjectDescription.vertices.length;
  627. if ( indexUA ) {
  628. indexUA.set( rawObjectDescription.indices, indexUAOffset );
  629. indexUAOffset += rawObjectDescription.indices.length;
  630. }
  631. if ( colorFA ) {
  632. colorFA.set( rawObjectDescription.colors, colorFAOffset );
  633. colorFAOffset += rawObjectDescription.colors.length;
  634. }
  635. if ( normalFA ) {
  636. normalFA.set( rawObjectDescription.normals, normalFAOffset );
  637. normalFAOffset += rawObjectDescription.normals.length;
  638. }
  639. if ( uvFA ) {
  640. uvFA.set( rawObjectDescription.uvs, uvFAOffset );
  641. uvFAOffset += rawObjectDescription.uvs.length;
  642. }
  643. if ( this.logger.isDebug() ) {
  644. var materialIndexLine = Validator.isValid( selectedMaterialIndex ) ? '\n\t\tmaterialIndex: ' + selectedMaterialIndex : '';
  645. var createdReport = 'Output Object no.: ' + this.outputObjectCount +
  646. '\n\t\tobjectName: ' + rawObjectDescription.objectName +
  647. '\n\t\tgroupName: ' + rawObjectDescription.groupName +
  648. '\n\t\tmaterialName: ' + rawObjectDescription.materialName +
  649. materialIndexLine +
  650. '\n\t\tsmoothingGroup: ' + rawObjectDescription.smoothingGroup +
  651. '\n\t\t#vertices: ' + rawObjectDescription.vertices.length / 3 +
  652. '\n\t\t#indices: ' + rawObjectDescription.indices.length +
  653. '\n\t\t#colors: ' + rawObjectDescription.colors.length / 3 +
  654. '\n\t\t#uvs: ' + rawObjectDescription.uvs.length / 2 +
  655. '\n\t\t#normals: ' + rawObjectDescription.normals.length / 3;
  656. this.logger.logDebug( createdReport );
  657. }
  658. }
  659. this.outputObjectCount++;
  660. this.callbackBuilder(
  661. {
  662. cmd: 'meshData',
  663. progress: {
  664. numericalValue: currentByte / this.totalBytes
  665. },
  666. params: {
  667. meshName: result.name
  668. },
  669. materials: {
  670. multiMaterial: createMultiMaterial,
  671. materialDescriptions: materialDescriptions,
  672. materialGroups: materialGroups
  673. },
  674. buffers: {
  675. vertices: vertexFA,
  676. indices: indexUA,
  677. colors: colorFA,
  678. normals: normalFA,
  679. uvs: uvFA
  680. }
  681. },
  682. [ vertexFA.buffer ],
  683. Validator.isValid( indexUA ) ? [ indexUA.buffer ] : null,
  684. Validator.isValid( colorFA ) ? [ colorFA.buffer ] : null,
  685. Validator.isValid( normalFA ) ? [ normalFA.buffer ] : null,
  686. Validator.isValid( uvFA ) ? [ uvFA.buffer ] : null
  687. );
  688. };
  689. return Parser;
  690. })();
  691. /**
  692. * {@link RawMesh} is only used by {@link Parser}.
  693. * The user of OBJLoader2 does not need to care about this class.
  694. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  695. */
  696. var RawMesh = (function () {
  697. function RawMesh( materialPerSmoothingGroup, useIndices, disregardNormals, objectName, groupName, activeMtlName ) {
  698. this.globalVertexOffset = 1;
  699. this.globalUvOffset = 1;
  700. this.globalNormalOffset = 1;
  701. this.vertices = [];
  702. this.colors = [];
  703. this.normals = [];
  704. this.uvs = [];
  705. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  706. this.activeMtlName = Validator.verifyInput( activeMtlName, '' );
  707. this.objectName = Validator.verifyInput( objectName, '' );
  708. this.groupName = Validator.verifyInput( groupName, '' );
  709. this.mtllibName = '';
  710. this.smoothingGroup = {
  711. splitMaterials: materialPerSmoothingGroup === true,
  712. normalized: -1,
  713. real: -1
  714. };
  715. this.useIndices = useIndices === true;
  716. this.disregardNormals = disregardNormals === true;
  717. this.mtlCount = 0;
  718. this.smoothingGroupCount = 0;
  719. this.subGroups = [];
  720. this.subGroupInUse = null;
  721. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  722. this.pushSmoothingGroup( 1 );
  723. this.doubleIndicesCount = 0;
  724. this.faceCount = 0;
  725. }
  726. RawMesh.prototype.newInstanceFromObject = function ( objectName, groupName ) {
  727. var newRawObject = new RawMesh( this.smoothingGroup.splitMaterials, this.useIndices, this.disregardNormals, objectName, groupName, this.activeMtlName );
  728. // move indices forward
  729. newRawObject.globalVertexOffset = this.globalVertexOffset + this.vertices.length / 3;
  730. newRawObject.globalUvOffset = this.globalUvOffset + this.uvs.length / 2;
  731. newRawObject.globalNormalOffset = this.globalNormalOffset + this.normals.length / 3;
  732. return newRawObject;
  733. };
  734. RawMesh.prototype.newInstanceFromGroup = function ( groupName ) {
  735. var newRawObject = new RawMesh( this.smoothingGroup.splitMaterials, this.useIndices, this.disregardNormals, this.objectName, groupName, this.activeMtlName );
  736. // keep current buffers and indices forward
  737. newRawObject.vertices = this.vertices;
  738. newRawObject.colors = this.colors;
  739. newRawObject.uvs = this.uvs;
  740. newRawObject.normals = this.normals;
  741. newRawObject.globalVertexOffset = this.globalVertexOffset;
  742. newRawObject.globalUvOffset = this.globalUvOffset;
  743. newRawObject.globalNormalOffset = this.globalNormalOffset;
  744. return newRawObject;
  745. };
  746. RawMesh.prototype.pushVertex = function ( buffer ) {
  747. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  748. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  749. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  750. };
  751. RawMesh.prototype.pushVertexAndVertextColors = function ( buffer ) {
  752. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  753. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  754. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  755. this.colors.push( parseFloat( buffer[ 4 ] ) );
  756. this.colors.push( parseFloat( buffer[ 5 ] ) );
  757. this.colors.push( parseFloat( buffer[ 6 ] ) );
  758. };
  759. RawMesh.prototype.pushUv = function ( buffer ) {
  760. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  761. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  762. };
  763. RawMesh.prototype.pushNormal = function ( buffer ) {
  764. this.normals.push( parseFloat( buffer[ 1 ] ) );
  765. this.normals.push( parseFloat( buffer[ 2 ] ) );
  766. this.normals.push( parseFloat( buffer[ 3 ] ) );
  767. };
  768. RawMesh.prototype.pushObject = function ( objectName ) {
  769. this.objectName = Validator.verifyInput( objectName, '' );
  770. };
  771. RawMesh.prototype.pushMtllib = function ( mtllibName ) {
  772. this.mtllibName = Validator.verifyInput( mtllibName, '' );
  773. };
  774. RawMesh.prototype.pushGroup = function ( groupName ) {
  775. this.groupName = Validator.verifyInput( groupName, '' );
  776. };
  777. RawMesh.prototype.pushUsemtl = function ( mtlName ) {
  778. if ( this.activeMtlName === mtlName || ! Validator.isValid( mtlName ) ) return;
  779. this.activeMtlName = mtlName;
  780. this.mtlCount++;
  781. this.verifyIndex();
  782. };
  783. RawMesh.prototype.pushSmoothingGroup = function ( smoothingGroup ) {
  784. var smoothingGroupInt = parseInt( smoothingGroup );
  785. if ( isNaN( smoothingGroupInt ) ) {
  786. smoothingGroupInt = smoothingGroup === "off" ? 0 : 1;
  787. }
  788. var smoothCheck = this.smoothingGroup.normalized;
  789. this.smoothingGroup.normalized = this.smoothingGroup.splitMaterials ? smoothingGroupInt : ( smoothingGroupInt === 0 ) ? 0 : 1;
  790. this.smoothingGroup.real = smoothingGroupInt;
  791. if ( smoothCheck !== smoothingGroupInt ) {
  792. this.smoothingGroupCount++;
  793. this.verifyIndex();
  794. }
  795. };
  796. RawMesh.prototype.verifyIndex = function () {
  797. var index = this.activeMtlName + '|' + this.smoothingGroup.normalized;
  798. this.subGroupInUse = this.subGroups[ index ];
  799. if ( ! Validator.isValid( this.subGroupInUse ) ) {
  800. this.subGroupInUse = new RawMeshSubGroup( this.objectName, this.groupName, this.activeMtlName, this.smoothingGroup.normalized );
  801. this.subGroups[ index ] = this.subGroupInUse;
  802. }
  803. };
  804. RawMesh.prototype.processFaces = function ( buffer, bufferPointer, slashesCount ) {
  805. var bufferLength = bufferPointer - 1;
  806. var i, length;
  807. // "f vertex ..."
  808. if ( slashesCount === 0 ) {
  809. for ( i = 2, length = bufferLength - 1; i < length; i ++ ) {
  810. this.buildFace( buffer[ 1 ] );
  811. this.buildFace( buffer[ i ] );
  812. this.buildFace( buffer[ i + 1 ] );
  813. }
  814. // "f vertex/uv ..."
  815. } else if ( bufferLength === slashesCount * 2 ) {
  816. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  817. this.buildFace( buffer[ 1 ], buffer[ 2 ] );
  818. this.buildFace( buffer[ i ], buffer[ i + 1 ] );
  819. this.buildFace( buffer[ i + 2 ], buffer[ i + 3 ] );
  820. }
  821. // "f vertex/uv/normal ..."
  822. } else if ( bufferLength * 2 === slashesCount * 3 ) {
  823. for ( i = 4, length = bufferLength - 3; i < length; i += 3 ) {
  824. this.buildFace( buffer[ 1 ], buffer[ 2 ], buffer[ 3 ] );
  825. this.buildFace( buffer[ i ], buffer[ i + 1 ], buffer[ i + 2 ] );
  826. this.buildFace( buffer[ i + 3 ], buffer[ i + 4 ], buffer[ i + 5 ] );
  827. }
  828. // "f vertex//normal ..."
  829. } else {
  830. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  831. this.buildFace( buffer[ 1 ], undefined, buffer[ 2 ] );
  832. this.buildFace( buffer[ i ], undefined, buffer[ i + 1 ] );
  833. this.buildFace( buffer[ i + 2 ], undefined, buffer[ i + 3 ] );
  834. }
  835. }
  836. };
  837. RawMesh.prototype.buildFace = function ( faceIndexV, faceIndexU, faceIndexN ) {
  838. var sgiu = this.subGroupInUse;
  839. if ( this.disregardNormals ) faceIndexN = undefined;
  840. var scope = this;
  841. var updateRawObjectDescriptionInUse = function () {
  842. var indexPointerV = ( parseInt( faceIndexV ) - scope.globalVertexOffset ) * 3;
  843. var indexPointerC = scope.colors.length > 0 ? indexPointerV : null;
  844. var vertices = sgiu.vertices;
  845. vertices.push( scope.vertices[ indexPointerV++ ] );
  846. vertices.push( scope.vertices[ indexPointerV++ ] );
  847. vertices.push( scope.vertices[ indexPointerV ] );
  848. if ( indexPointerC !== null ) {
  849. var colors = sgiu.colors;
  850. colors.push( scope.colors[ indexPointerC++ ] );
  851. colors.push( scope.colors[ indexPointerC++ ] );
  852. colors.push( scope.colors[ indexPointerC ] );
  853. }
  854. if ( faceIndexU ) {
  855. var indexPointerU = ( parseInt( faceIndexU ) - scope.globalUvOffset ) * 2;
  856. var uvs = sgiu.uvs;
  857. uvs.push( scope.uvs[ indexPointerU++ ] );
  858. uvs.push( scope.uvs[ indexPointerU ] );
  859. }
  860. if ( faceIndexN ) {
  861. var indexPointerN = ( parseInt( faceIndexN ) - scope.globalNormalOffset ) * 3;
  862. var normals = sgiu.normals;
  863. normals.push( scope.normals[ indexPointerN++ ] );
  864. normals.push( scope.normals[ indexPointerN++ ] );
  865. normals.push( scope.normals[ indexPointerN ] );
  866. }
  867. };
  868. if ( this.useIndices ) {
  869. var mappingName = faceIndexV + ( faceIndexU ? '_' + faceIndexU : '_n' ) + ( faceIndexN ? '_' + faceIndexN : '_n' );
  870. var indicesPointer = sgiu.indexMappings[ mappingName ];
  871. if ( Validator.isValid( indicesPointer ) ) {
  872. this.doubleIndicesCount++;
  873. } else {
  874. indicesPointer = sgiu.vertices.length / 3;
  875. updateRawObjectDescriptionInUse();
  876. sgiu.indexMappings[ mappingName ] = indicesPointer;
  877. sgiu.indexMappingsCount++;
  878. }
  879. sgiu.indices.push( indicesPointer );
  880. } else {
  881. updateRawObjectDescriptionInUse();
  882. }
  883. this.faceCount++;
  884. };
  885. /*
  886. * Support for lines with or without texture. First element in indexArray is the line identification
  887. * 0: "f vertex/uv vertex/uv ..."
  888. * 1: "f vertex vertex ..."
  889. */
  890. RawMesh.prototype.processLines = function ( buffer, bufferPointer, slashCount ) {
  891. var i = 1;
  892. var length;
  893. var bufferLength = bufferPointer - 1;
  894. if ( bufferLength === slashCount * 2 ) {
  895. for ( length = bufferLength - 2; i < length; i += 2 ) {
  896. this.vertices.push( parseInt( buffer[ i ] ) );
  897. this.uvs.push( parseInt( buffer[ i + 1 ] ) );
  898. }
  899. } else {
  900. for ( length = bufferLength - 1; i < length; i ++ ) {
  901. this.vertices.push( parseInt( buffer[ i ] ) );
  902. }
  903. }
  904. };
  905. /**
  906. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  907. */
  908. RawMesh.prototype.finalize = function () {
  909. var rawObjectDescriptionsTemp = [];
  910. var rawObjectDescription;
  911. var absoluteVertexCount = 0;
  912. var absoluteIndexMappingsCount = 0;
  913. var absoluteIndexCount = 0;
  914. var absoluteColorCount = 0;
  915. var absoluteNormalCount = 0;
  916. var absoluteUvCount = 0;
  917. var indices;
  918. for ( var name in this.subGroups ) {
  919. rawObjectDescription = this.subGroups[ name ];
  920. if ( rawObjectDescription.vertices.length > 0 ) {
  921. indices = rawObjectDescription.indices;
  922. if ( indices.length > 0 && absoluteIndexMappingsCount > 0 ) {
  923. for ( var i in indices ) indices[ i ] = indices[ i ] + absoluteIndexMappingsCount;
  924. }
  925. rawObjectDescriptionsTemp.push( rawObjectDescription );
  926. absoluteVertexCount += rawObjectDescription.vertices.length;
  927. absoluteIndexMappingsCount += rawObjectDescription.indexMappingsCount;
  928. absoluteIndexCount += rawObjectDescription.indices.length;
  929. absoluteColorCount += rawObjectDescription.colors.length;
  930. absoluteUvCount += rawObjectDescription.uvs.length;
  931. absoluteNormalCount += rawObjectDescription.normals.length;
  932. }
  933. }
  934. // do not continue if no result
  935. var result = null;
  936. if ( rawObjectDescriptionsTemp.length > 0 ) {
  937. result = {
  938. name: this.groupName !== '' ? this.groupName : this.objectName,
  939. subGroups: rawObjectDescriptionsTemp,
  940. absoluteVertexCount: absoluteVertexCount,
  941. absoluteIndexCount: absoluteIndexCount,
  942. absoluteColorCount: absoluteColorCount,
  943. absoluteNormalCount: absoluteNormalCount,
  944. absoluteUvCount: absoluteUvCount,
  945. faceCount: this.faceCount,
  946. doubleIndicesCount: this.doubleIndicesCount
  947. };
  948. }
  949. return result;
  950. };
  951. RawMesh.prototype.createReport = function () {
  952. var report = {
  953. objectName: this.objectName,
  954. groupName: this.groupName,
  955. mtllibName: this.mtllibName,
  956. vertexCount: this.vertices.length / 3,
  957. normalCount: this.normals.length / 3,
  958. uvCount: this.uvs.length / 2,
  959. smoothingGroupCount: this.smoothingGroupCount,
  960. mtlCount: this.mtlCount,
  961. subGroups: this.subGroups.length
  962. };
  963. return report;
  964. };
  965. return RawMesh;
  966. })();
  967. /**
  968. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  969. * @class
  970. *
  971. * @param {string} objectName Name of the mesh
  972. * @param {string} groupName Name of the group
  973. * @param {string} materialName Name of the material
  974. * @param {number} smoothingGroup Normalized smoothingGroup (0: flat shading, 1: smooth shading)
  975. */
  976. var RawMeshSubGroup = (function () {
  977. function RawMeshSubGroup( objectName, groupName, materialName, smoothingGroup ) {
  978. this.objectName = objectName;
  979. this.groupName = groupName;
  980. this.materialName = materialName;
  981. this.smoothingGroup = smoothingGroup;
  982. this.vertices = [];
  983. this.indexMappingsCount = 0;
  984. this.indexMappings = [];
  985. this.indices = [];
  986. this.colors = [];
  987. this.uvs = [];
  988. this.normals = [];
  989. }
  990. return RawMeshSubGroup;
  991. })();
  992. OBJLoader2.prototype._checkFiles = function ( resources ) {
  993. var resource;
  994. var result = {
  995. mtl: null,
  996. obj: null
  997. };
  998. for ( var index in resources ) {
  999. resource = resources[ index ];
  1000. if ( ! Validator.isValid( resource.name ) ) continue;
  1001. if ( Validator.isValid( resource.content ) ) {
  1002. if ( resource.extension === 'OBJ' ) {
  1003. // fast-fail on bad type
  1004. if ( ! ( resource.content instanceof Uint8Array ) ) throw 'Provided content is not of type arraybuffer! Aborting...';
  1005. result.obj = resource;
  1006. } else if ( resource.extension === 'MTL' && Validator.isValid( resource.name ) ) {
  1007. if ( ! ( typeof( resource.content ) === 'string' || resource.content instanceof String ) ) throw 'Provided content is not of type String! Aborting...';
  1008. result.mtl = resource;
  1009. } else if ( resource.extension === "ZIP" ) {
  1010. // ignore
  1011. } else {
  1012. throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  1013. }
  1014. } else {
  1015. // fast-fail on bad type
  1016. if ( ! ( typeof( resource.name ) === 'string' || resource.name instanceof String ) ) throw 'Provided file is not properly defined! Aborting...';
  1017. if ( resource.extension === 'OBJ' ) {
  1018. result.obj = resource;
  1019. } else if ( resource.extension === 'MTL' ) {
  1020. result.mtl = resource;
  1021. } else if ( resource.extension === "ZIP" ) {
  1022. // ignore
  1023. } else {
  1024. throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  1025. }
  1026. }
  1027. }
  1028. return result;
  1029. };
  1030. /**
  1031. * Utility method for loading an mtl file according resource description.
  1032. * @memberOf THREE.OBJLoader2
  1033. *
  1034. * @param {string} url URL to the file
  1035. * @param {string} name The name of the object
  1036. * @param {Object} content The file content as arraybuffer or text
  1037. * @param {function} callbackOnLoad
  1038. * @param {string} [crossOrigin] CORS value
  1039. */
  1040. OBJLoader2.prototype.loadMtl = function ( url, name, content, callbackOnLoad, crossOrigin ) {
  1041. var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'MTL' );
  1042. resource.setContent( content );
  1043. this._loadMtl( resource, callbackOnLoad, crossOrigin );
  1044. };
  1045. /**
  1046. * Utility method for loading an mtl file according resource description.
  1047. * @memberOf THREE.OBJLoader2
  1048. *
  1049. * @param {THREE.LoaderSupport.ResourceDescriptor} resource
  1050. * @param {function} callbackOnLoad
  1051. * @param {string} [crossOrigin] CORS value
  1052. */
  1053. OBJLoader2.prototype._loadMtl = function ( resource, callbackOnLoad, crossOrigin ) {
  1054. if ( Validator.isValid( resource ) ) this.logger.logTimeStart( 'Loading MTL: ' + resource.name );
  1055. var materials = [];
  1056. var scope = this;
  1057. var processMaterials = function ( materialCreator ) {
  1058. var materialCreatorMaterials = [];
  1059. if ( Validator.isValid( materialCreator ) ) {
  1060. materialCreator.preload();
  1061. materialCreatorMaterials = materialCreator.materials;
  1062. for ( var materialName in materialCreatorMaterials ) {
  1063. if ( materialCreatorMaterials.hasOwnProperty( materialName ) ) {
  1064. materials[ materialName ] = materialCreatorMaterials[ materialName ];
  1065. }
  1066. }
  1067. }
  1068. if ( Validator.isValid( resource ) ) scope.logger.logTimeEnd( 'Loading MTL: ' + resource.name );
  1069. callbackOnLoad( materials );
  1070. };
  1071. var mtlLoader = new THREE.MTLLoader();
  1072. crossOrigin = Validator.verifyInput( crossOrigin, 'anonymous' );
  1073. mtlLoader.setCrossOrigin( crossOrigin );
  1074. // fast-fail
  1075. if ( ! Validator.isValid( resource ) || ( ! Validator.isValid( resource.content ) && ! Validator.isValid( resource.url ) ) ) {
  1076. processMaterials();
  1077. } else {
  1078. mtlLoader.setPath( resource.path );
  1079. if ( Validator.isValid( resource.content ) ) {
  1080. processMaterials( Validator.isValid( resource.content ) ? mtlLoader.parse( resource.content ) : null );
  1081. } else if ( Validator.isValid( resource.url ) ) {
  1082. var onError = function ( event ) {
  1083. var output = 'Error occurred while downloading "' + resource.url + '"';
  1084. this.logger.logError( output + ': ' + event );
  1085. throw output;
  1086. };
  1087. mtlLoader.load( resource.name, processMaterials, undefined, onError );
  1088. }
  1089. }
  1090. };
  1091. return OBJLoader2;
  1092. })();