OBJLoader2.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  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. if ( THREE.LoaderSupport === undefined ) console.error( '"THREE.LoaderSupport" is not available. "THREE.OBJLoader2" requires it. Please include "LoaderSupport.js" in your HTML.' );
  8. /**
  9. * Use this class to load OBJ data from files or to parse OBJ data from an arraybuffer
  10. * @class
  11. *
  12. * @param {THREE.DefaultLoadingManager} [manager] The loadingManager for the loader to use. Default is {@link THREE.DefaultLoadingManager}
  13. */
  14. THREE.OBJLoader2 = (function () {
  15. var OBJLOADER2_VERSION = '2.4.2';
  16. var Validator = THREE.LoaderSupport.Validator;
  17. function OBJLoader2( manager ) {
  18. console.info( 'Using THREE.OBJLoader2 version: ' + OBJLOADER2_VERSION );
  19. this.manager = Validator.verifyInput( manager, THREE.DefaultLoadingManager );
  20. this.logging = {
  21. enabled: true,
  22. debug: false
  23. };
  24. this.modelName = '';
  25. this.instanceNo = 0;
  26. this.path = '';
  27. this.useIndices = false;
  28. this.disregardNormals = false;
  29. this.materialPerSmoothingGroup = false;
  30. this.useOAsMesh = false;
  31. this.loaderRootNode = new THREE.Group();
  32. this.meshBuilder = new THREE.LoaderSupport.MeshBuilder();
  33. this.callbacks = new THREE.LoaderSupport.Callbacks();
  34. this.workerSupport = new THREE.LoaderSupport.WorkerSupport();
  35. this.terminateWorkerOnLoad = true;
  36. }
  37. /**
  38. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  39. * @memberOf THREE.OBJLoader2
  40. *
  41. * @param {boolean} enabled True or false.
  42. * @param {boolean} debug True or false.
  43. */
  44. OBJLoader2.prototype.setLogging = function ( enabled, debug ) {
  45. this.logging.enabled = enabled === true;
  46. this.logging.debug = debug === true;
  47. this.meshBuilder.setLogging( this.logging.enabled, this.logging.debug );
  48. };
  49. /**
  50. * Set the name of the model.
  51. * @memberOf THREE.OBJLoader2
  52. *
  53. * @param {string} modelName
  54. */
  55. OBJLoader2.prototype.setModelName = function ( modelName ) {
  56. this.modelName = Validator.verifyInput( modelName, this.modelName );
  57. };
  58. /**
  59. * The URL of the base path.
  60. * @memberOf THREE.OBJLoader2
  61. *
  62. * @param {string} path URL
  63. */
  64. OBJLoader2.prototype.setPath = function ( path ) {
  65. this.path = Validator.verifyInput( path, this.path );
  66. };
  67. /**
  68. * Set the node where the loaded objects will be attached directly.
  69. * @memberOf THREE.OBJLoader2
  70. *
  71. * @param {THREE.Object3D} streamMeshesTo Object already attached to scenegraph where new meshes will be attached to
  72. */
  73. OBJLoader2.prototype.setStreamMeshesTo = function ( streamMeshesTo ) {
  74. this.loaderRootNode = Validator.verifyInput( streamMeshesTo, this.loaderRootNode );
  75. };
  76. /**
  77. * Set materials loaded by MTLLoader or any other supplier of an Array of {@link THREE.Material}.
  78. * @memberOf THREE.OBJLoader2
  79. *
  80. * @param {THREE.Material[]} materials Array of {@link THREE.Material}
  81. */
  82. OBJLoader2.prototype.setMaterials = function ( materials ) {
  83. this.meshBuilder.setMaterials( materials );
  84. };
  85. /**
  86. * Instructs loaders to create indexed {@link THREE.BufferGeometry}.
  87. * @memberOf THREE.OBJLoader2
  88. *
  89. * @param {boolean} useIndices=false
  90. */
  91. OBJLoader2.prototype.setUseIndices = function ( useIndices ) {
  92. this.useIndices = useIndices === true;
  93. };
  94. /**
  95. * Tells whether normals should be completely disregarded and regenerated.
  96. * @memberOf THREE.OBJLoader2
  97. *
  98. * @param {boolean} disregardNormals=false
  99. */
  100. OBJLoader2.prototype.setDisregardNormals = function ( disregardNormals ) {
  101. this.disregardNormals = disregardNormals === true;
  102. };
  103. /**
  104. * Tells whether a material shall be created per smoothing group.
  105. * @memberOf THREE.OBJLoader2
  106. *
  107. * @param {boolean} materialPerSmoothingGroup=false
  108. */
  109. OBJLoader2.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
  110. this.materialPerSmoothingGroup = materialPerSmoothingGroup === true;
  111. };
  112. /**
  113. * Usually 'o' is meta-information and does not result in creation of new meshes, but mesh creation on occurrence of "o" can be enforced.
  114. * @memberOf THREE.OBJLoader2
  115. *
  116. * @param {boolean} useOAsMesh=false
  117. */
  118. OBJLoader2.prototype.setUseOAsMesh = function ( useOAsMesh ) {
  119. this.useOAsMesh = useOAsMesh === true;
  120. };
  121. OBJLoader2.prototype._setCallbacks = function ( callbacks ) {
  122. if ( Validator.isValid( callbacks.onProgress ) ) this.callbacks.setCallbackOnProgress( callbacks.onProgress );
  123. if ( Validator.isValid( callbacks.onReportError ) ) this.callbacks.setCallbackOnReportError( callbacks.onReportError );
  124. if ( Validator.isValid( callbacks.onMeshAlter ) ) this.callbacks.setCallbackOnMeshAlter( callbacks.onMeshAlter );
  125. if ( Validator.isValid( callbacks.onLoad ) ) this.callbacks.setCallbackOnLoad( callbacks.onLoad );
  126. if ( Validator.isValid( callbacks.onLoadMaterials ) ) this.callbacks.setCallbackOnLoadMaterials( callbacks.onLoadMaterials );
  127. this.meshBuilder._setCallbacks( this.callbacks );
  128. };
  129. /**
  130. * Announce feedback which is give to the registered callbacks.
  131. * @memberOf THREE.OBJLoader2
  132. * @private
  133. *
  134. * @param {string} type The type of event
  135. * @param {string} text Textual description of the event
  136. * @param {number} numericalValue Numerical value describing the progress
  137. */
  138. OBJLoader2.prototype.onProgress = function ( type, text, numericalValue ) {
  139. var content = Validator.isValid( text ) ? text: '';
  140. var event = {
  141. detail: {
  142. type: type,
  143. modelName: this.modelName,
  144. instanceNo: this.instanceNo,
  145. text: content,
  146. numericalValue: numericalValue
  147. }
  148. };
  149. if ( Validator.isValid( this.callbacks.onProgress ) ) this.callbacks.onProgress( event );
  150. if ( this.logging.enabled && this.logging.debug ) console.debug( content );
  151. };
  152. OBJLoader2.prototype._onError = function ( event ) {
  153. var output = 'Error occurred while downloading!';
  154. if ( event.currentTarget && event.currentTarget.statusText !== null ) {
  155. output += '\nurl: ' + event.currentTarget.responseURL + '\nstatus: ' + event.currentTarget.statusText;
  156. }
  157. this.onProgress( 'error', output, -1 );
  158. this._throwError( output );
  159. };
  160. OBJLoader2.prototype._throwError = function ( errorMessage ) {
  161. if ( Validator.isValid( this.callbacks.onReportError ) ) {
  162. this.callbacks.onReportError( errorMessage );
  163. } else {
  164. throw errorMessage;
  165. }
  166. };
  167. /**
  168. * Use this convenient method to load a file at the given URL. By default the fileLoader uses an ArrayBuffer.
  169. * @memberOf THREE.OBJLoader2
  170. *
  171. * @param {string} url A string containing the path/URL of the file to be loaded.
  172. * @param {callback} onLoad A function to be called after loading is successfully completed. The function receives loaded Object3D as an argument.
  173. * @param {callback} [onProgress] A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and Integer bytes.
  174. * @param {callback} [onError] A function to be called if an error occurs during loading. The function receives the error as an argument.
  175. * @param {callback} [onMeshAlter] A function to be called after a new mesh raw data becomes available for alteration.
  176. * @param {boolean} [useAsync] If true, uses async loading with worker, if false loads data synchronously.
  177. */
  178. OBJLoader2.prototype.load = function ( url, onLoad, onProgress, onError, onMeshAlter, useAsync ) {
  179. var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'OBJ' );
  180. this._loadObj( resource, onLoad, onProgress, onError, onMeshAlter, useAsync );
  181. };
  182. OBJLoader2.prototype._loadObj = function ( resource, onLoad, onProgress, onError, onMeshAlter, useAsync ) {
  183. var scope = this;
  184. if ( ! Validator.isValid( onError ) ) {
  185. onError = function ( event ) {
  186. scope._onError( event );
  187. };
  188. }
  189. // fast-fail
  190. if ( ! Validator.isValid( resource ) ) onError( 'An invalid ResourceDescriptor was provided. Unable to continue!' );
  191. var fileLoaderOnLoad = function ( content ) {
  192. resource.content = content;
  193. if ( useAsync ) {
  194. scope.parseAsync( content, onLoad );
  195. } else {
  196. var callbacks = new THREE.LoaderSupport.Callbacks();
  197. callbacks.setCallbackOnMeshAlter( onMeshAlter );
  198. scope._setCallbacks( callbacks );
  199. onLoad(
  200. {
  201. detail: {
  202. loaderRootNode: scope.parse( content ),
  203. modelName: scope.modelName,
  204. instanceNo: scope.instanceNo
  205. }
  206. }
  207. );
  208. }
  209. };
  210. // fast-fail
  211. if ( ! Validator.isValid( resource.url ) || Validator.isValid( resource.content ) ) {
  212. fileLoaderOnLoad( Validator.isValid( resource.content ) ? resource.content : null );
  213. } else {
  214. if ( ! Validator.isValid( onProgress ) ) {
  215. var numericalValueRef = 0;
  216. var numericalValue = 0;
  217. onProgress = function ( event ) {
  218. if ( ! event.lengthComputable ) return;
  219. numericalValue = event.loaded / event.total;
  220. if ( numericalValue > numericalValueRef ) {
  221. numericalValueRef = numericalValue;
  222. var output = 'Download of "' + resource.url + '": ' + ( numericalValue * 100 ).toFixed( 2 ) + '%';
  223. scope.onProgress( 'progressLoad', output, numericalValue );
  224. }
  225. };
  226. }
  227. var fileLoader = new THREE.FileLoader( this.manager );
  228. fileLoader.setPath( this.path );
  229. fileLoader.setResponseType( 'arraybuffer' );
  230. fileLoader.load( resource.url, fileLoaderOnLoad, onProgress, onError );
  231. }
  232. };
  233. /**
  234. * Run the loader according the provided instructions.
  235. * @memberOf THREE.OBJLoader2
  236. *
  237. * @param {THREE.LoaderSupport.PrepData} prepData All parameters and resources required for execution
  238. * @param {THREE.LoaderSupport.WorkerSupport} [workerSupportExternal] Use pre-existing WorkerSupport
  239. */
  240. OBJLoader2.prototype.run = function ( prepData, workerSupportExternal ) {
  241. this._applyPrepData( prepData );
  242. var available = prepData.checkResourceDescriptorFiles( prepData.resources,
  243. [
  244. { ext: "obj", type: "ArrayBuffer", ignore: false },
  245. { ext: "mtl", type: "String", ignore: false },
  246. { ext: "zip", type: "String", ignore: true }
  247. ]
  248. );
  249. if ( Validator.isValid( workerSupportExternal ) ) {
  250. this.terminateWorkerOnLoad = false;
  251. this.workerSupport = workerSupportExternal;
  252. this.logging.enabled = this.workerSupport.logging.enabled;
  253. this.logging.debug = this.workerSupport.logging.debug;
  254. }
  255. var scope = this;
  256. var onMaterialsLoaded = function ( materials ) {
  257. if ( materials !== null ) scope.meshBuilder.setMaterials( materials );
  258. scope._loadObj( available.obj, scope.callbacks.onLoad, null, null, scope.callbacks.onMeshAlter, prepData.useAsync );
  259. };
  260. this._loadMtl( available.mtl, onMaterialsLoaded, null, null, prepData.crossOrigin, prepData.materialOptions );
  261. };
  262. OBJLoader2.prototype._applyPrepData = function ( prepData ) {
  263. if ( Validator.isValid( prepData ) ) {
  264. this.setLogging( prepData.logging.enabled, prepData.logging.debug );
  265. this.setModelName( prepData.modelName );
  266. this.setStreamMeshesTo( prepData.streamMeshesTo );
  267. this.meshBuilder.setMaterials( prepData.materials );
  268. this.setUseIndices( prepData.useIndices );
  269. this.setDisregardNormals( prepData.disregardNormals );
  270. this.setMaterialPerSmoothingGroup( prepData.materialPerSmoothingGroup );
  271. this.setUseOAsMesh( prepData.useOAsMesh );
  272. this._setCallbacks( prepData.getCallbacks() );
  273. }
  274. };
  275. /**
  276. * Parses OBJ data synchronously from arraybuffer or string.
  277. * @memberOf THREE.OBJLoader2
  278. *
  279. * @param {arraybuffer|string} content OBJ data as Uint8Array or String
  280. */
  281. OBJLoader2.prototype.parse = function ( content ) {
  282. // fast-fail in case of illegal data
  283. if ( ! Validator.isValid( content ) ) {
  284. console.warn( 'Provided content is not a valid ArrayBuffer or String.' );
  285. return this.loaderRootNode;
  286. }
  287. if ( this.logging.enabled ) console.time( 'OBJLoader2 parse: ' + this.modelName );
  288. this.meshBuilder.init();
  289. var parser = new Parser();
  290. parser.setLogging( this.logging.enabled, this.logging.debug );
  291. parser.setMaterialPerSmoothingGroup( this.materialPerSmoothingGroup );
  292. parser.setUseOAsMesh( this.useOAsMesh );
  293. parser.setUseIndices( this.useIndices );
  294. parser.setDisregardNormals( this.disregardNormals );
  295. // sync code works directly on the material references
  296. parser.setMaterials( this.meshBuilder.getMaterials() );
  297. var scope = this;
  298. var onMeshLoaded = function ( payload ) {
  299. var meshes = scope.meshBuilder.processPayload( payload );
  300. var mesh;
  301. for ( var i in meshes ) {
  302. mesh = meshes[ i ];
  303. scope.loaderRootNode.add( mesh );
  304. }
  305. };
  306. parser.setCallbackMeshBuilder( onMeshLoaded );
  307. var onProgressScoped = function ( text, numericalValue ) {
  308. scope.onProgress( 'progressParse', text, numericalValue );
  309. };
  310. parser.setCallbackProgress( onProgressScoped );
  311. if ( content instanceof ArrayBuffer || content instanceof Uint8Array ) {
  312. if ( this.logging.enabled ) console.info( 'Parsing arrayBuffer...' );
  313. parser.parse( content );
  314. } else if ( typeof( content ) === 'string' || content instanceof String ) {
  315. if ( this.logging.enabled ) console.info( 'Parsing text...' );
  316. parser.parseText( content );
  317. } else {
  318. this._throwError( 'Provided content was neither of type String nor Uint8Array! Aborting...' );
  319. }
  320. if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2 parse: ' + this.modelName );
  321. return this.loaderRootNode;
  322. };
  323. /**
  324. * Parses OBJ content asynchronously from arraybuffer.
  325. * @memberOf THREE.OBJLoader2
  326. *
  327. * @param {arraybuffer} content OBJ data as Uint8Array
  328. * @param {callback} onLoad Called after worker successfully completed loading
  329. */
  330. OBJLoader2.prototype.parseAsync = function ( content, onLoad ) {
  331. var scope = this;
  332. var measureTime = false;
  333. var scopedOnLoad = function () {
  334. onLoad(
  335. {
  336. detail: {
  337. loaderRootNode: scope.loaderRootNode,
  338. modelName: scope.modelName,
  339. instanceNo: scope.instanceNo
  340. }
  341. }
  342. );
  343. if ( measureTime && scope.logging.enabled ) console.timeEnd( 'OBJLoader2 parseAsync: ' + scope.modelName );
  344. };
  345. // fast-fail in case of illegal data
  346. if ( ! Validator.isValid( content ) ) {
  347. console.warn( 'Provided content is not a valid ArrayBuffer.' );
  348. scopedOnLoad();
  349. } else {
  350. measureTime = true;
  351. }
  352. if ( measureTime && this.logging.enabled ) console.time( 'OBJLoader2 parseAsync: ' + this.modelName );
  353. this.meshBuilder.init();
  354. var scopedOnMeshLoaded = function ( payload ) {
  355. var meshes = scope.meshBuilder.processPayload( payload );
  356. var mesh;
  357. for ( var i in meshes ) {
  358. mesh = meshes[ i ];
  359. scope.loaderRootNode.add( mesh );
  360. }
  361. };
  362. var buildCode = function ( funcBuildObject, funcBuildSingleton ) {
  363. var workerCode = '';
  364. workerCode += '/**\n';
  365. workerCode += ' * This code was constructed by OBJLoader2 buildCode.\n';
  366. workerCode += ' */\n\n';
  367. workerCode += 'THREE = { LoaderSupport: {} };\n\n';
  368. workerCode += funcBuildObject( 'THREE.LoaderSupport.Validator', Validator );
  369. workerCode += funcBuildSingleton( 'Parser', Parser );
  370. return workerCode;
  371. };
  372. this.workerSupport.validate( buildCode, 'Parser' );
  373. this.workerSupport.setCallbacks( scopedOnMeshLoaded, scopedOnLoad );
  374. if ( scope.terminateWorkerOnLoad ) this.workerSupport.setTerminateRequested( true );
  375. var materialNames = {};
  376. var materials = this.meshBuilder.getMaterials();
  377. for ( var materialName in materials ) {
  378. materialNames[ materialName ] = materialName;
  379. }
  380. this.workerSupport.run(
  381. {
  382. params: {
  383. useAsync: true,
  384. materialPerSmoothingGroup: this.materialPerSmoothingGroup,
  385. useOAsMesh: this.useOAsMesh,
  386. useIndices: this.useIndices,
  387. disregardNormals: this.disregardNormals
  388. },
  389. logging: {
  390. enabled: this.logging.enabled,
  391. debug: this.logging.debug
  392. },
  393. materials: {
  394. // in async case only material names are supplied to parser
  395. materials: materialNames
  396. },
  397. data: {
  398. input: content,
  399. options: null
  400. }
  401. }
  402. );
  403. };
  404. /**
  405. * Parse OBJ data either from ArrayBuffer or string
  406. * @class
  407. */
  408. var Parser = (function () {
  409. function Parser() {
  410. this.callbackProgress = null;
  411. this.callbackMeshBuilder = null;
  412. this.contentRef = null;
  413. this.legacyMode = false;
  414. this.materials = {};
  415. this.useAsync = false;
  416. this.materialPerSmoothingGroup = false;
  417. this.useOAsMesh = false;
  418. this.useIndices = false;
  419. this.disregardNormals = false;
  420. this.vertices = [];
  421. this.colors = [];
  422. this.normals = [];
  423. this.uvs = [];
  424. this.rawMesh = {
  425. objectName: '',
  426. groupName: '',
  427. activeMtlName: '',
  428. mtllibName: '',
  429. // reset with new mesh
  430. faceType: -1,
  431. subGroups: [],
  432. subGroupInUse: null,
  433. smoothingGroup: {
  434. splitMaterials: false,
  435. normalized: -1,
  436. real: -1
  437. },
  438. counts: {
  439. doubleIndicesCount: 0,
  440. faceCount: 0,
  441. mtlCount: 0,
  442. smoothingGroupCount: 0
  443. }
  444. };
  445. this.inputObjectCount = 1;
  446. this.outputObjectCount = 1;
  447. this.globalCounts = {
  448. vertices: 0,
  449. faces: 0,
  450. doubleIndicesCount: 0,
  451. lineByte: 0,
  452. currentByte: 0,
  453. totalBytes: 0
  454. };
  455. this.logging = {
  456. enabled: true,
  457. debug: false
  458. };
  459. }
  460. Parser.prototype.resetRawMesh = function () {
  461. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  462. this.rawMesh.subGroups = [];
  463. this.rawMesh.subGroupInUse = null;
  464. this.rawMesh.smoothingGroup.normalized = -1;
  465. this.rawMesh.smoothingGroup.real = -1;
  466. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  467. this.pushSmoothingGroup( 1 );
  468. this.rawMesh.counts.doubleIndicesCount = 0;
  469. this.rawMesh.counts.faceCount = 0;
  470. this.rawMesh.counts.mtlCount = 0;
  471. this.rawMesh.counts.smoothingGroupCount = 0;
  472. };
  473. Parser.prototype.setUseAsync = function ( useAsync ) {
  474. this.useAsync = useAsync;
  475. };
  476. Parser.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
  477. this.materialPerSmoothingGroup = materialPerSmoothingGroup;
  478. };
  479. Parser.prototype.setUseOAsMesh = function ( useOAsMesh ) {
  480. this.useOAsMesh = useOAsMesh;
  481. };
  482. Parser.prototype.setUseIndices = function ( useIndices ) {
  483. this.useIndices = useIndices;
  484. };
  485. Parser.prototype.setDisregardNormals = function ( disregardNormals ) {
  486. this.disregardNormals = disregardNormals;
  487. };
  488. Parser.prototype.setMaterials = function ( materials ) {
  489. this.materials = THREE.LoaderSupport.Validator.verifyInput( materials, this.materials );
  490. this.materials = THREE.LoaderSupport.Validator.verifyInput( this.materials, {} );
  491. };
  492. Parser.prototype.setCallbackMeshBuilder = function ( callbackMeshBuilder ) {
  493. if ( ! THREE.LoaderSupport.Validator.isValid( callbackMeshBuilder ) ) {
  494. this._throwError( 'Unable to run as no "MeshBuilder" callback is set.' );
  495. }
  496. this.callbackMeshBuilder = callbackMeshBuilder;
  497. };
  498. Parser.prototype.setCallbackProgress = function ( callbackProgress ) {
  499. this.callbackProgress = callbackProgress;
  500. };
  501. Parser.prototype.setLogging = function ( enabled, debug ) {
  502. this.logging.enabled = enabled === true;
  503. this.logging.debug = debug === true;
  504. };
  505. Parser.prototype.configure = function () {
  506. this.pushSmoothingGroup( 1 );
  507. if ( this.logging.enabled ) {
  508. var matKeys = Object.keys( this.materials );
  509. var matNames = ( matKeys.length > 0 ) ? '\n\tmaterialNames:\n\t\t- ' + matKeys.join( '\n\t\t- ' ) : '\n\tmaterialNames: None';
  510. var printedConfig = 'OBJLoader2.Parser configuration:'
  511. + matNames
  512. + '\n\tuseAsync: ' + this.useAsync
  513. + '\n\tmaterialPerSmoothingGroup: ' + this.materialPerSmoothingGroup
  514. + '\n\tuseOAsMesh: ' + this.useOAsMesh
  515. + '\n\tuseIndices: ' + this.useIndices
  516. + '\n\tdisregardNormals: ' + this.disregardNormals
  517. + '\n\tcallbackMeshBuilderName: ' + this.callbackMeshBuilder.name
  518. + '\n\tcallbackProgressName: ' + this.callbackProgress.name;
  519. console.info( printedConfig );
  520. }
  521. };
  522. /**
  523. * Parse the provided arraybuffer
  524. * @memberOf Parser
  525. *
  526. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  527. */
  528. Parser.prototype.parse = function ( arrayBuffer ) {
  529. if ( this.logging.enabled ) console.time( 'OBJLoader2.Parser.parse' );
  530. this.configure();
  531. var arrayBufferView = new Uint8Array( arrayBuffer );
  532. this.contentRef = arrayBufferView;
  533. var length = arrayBufferView.byteLength;
  534. this.globalCounts.totalBytes = length;
  535. var buffer = new Array( 128 );
  536. for ( var code, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i++ ) {
  537. code = arrayBufferView[ i ];
  538. switch ( code ) {
  539. // space
  540. case 32:
  541. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  542. word = '';
  543. break;
  544. // slash
  545. case 47:
  546. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  547. slashesCount++;
  548. word = '';
  549. break;
  550. // LF
  551. case 10:
  552. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  553. word = '';
  554. this.globalCounts.lineByte = this.globalCounts.currentByte;
  555. this.globalCounts.currentByte = i;
  556. this.processLine( buffer, bufferPointer, slashesCount );
  557. bufferPointer = 0;
  558. slashesCount = 0;
  559. break;
  560. // CR
  561. case 13:
  562. break;
  563. default:
  564. word += String.fromCharCode( code );
  565. break;
  566. }
  567. }
  568. this.finalizeParsing();
  569. if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2.Parser.parse' );
  570. };
  571. /**
  572. * Parse the provided text
  573. * @memberOf Parser
  574. *
  575. * @param {string} text OBJ data as string
  576. */
  577. Parser.prototype.parseText = function ( text ) {
  578. if ( this.logging.enabled ) console.time( 'OBJLoader2.Parser.parseText' );
  579. this.configure();
  580. this.legacyMode = true;
  581. this.contentRef = text;
  582. var length = text.length;
  583. this.globalCounts.totalBytes = length;
  584. var buffer = new Array( 128 );
  585. for ( var char, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i++ ) {
  586. char = text[ i ];
  587. switch ( char ) {
  588. case ' ':
  589. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  590. word = '';
  591. break;
  592. case '/':
  593. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  594. slashesCount++;
  595. word = '';
  596. break;
  597. case '\n':
  598. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  599. word = '';
  600. this.globalCounts.lineByte = this.globalCounts.currentByte;
  601. this.globalCounts.currentByte = i;
  602. this.processLine( buffer, bufferPointer, slashesCount );
  603. bufferPointer = 0;
  604. slashesCount = 0;
  605. break;
  606. case '\r':
  607. break;
  608. default:
  609. word += char;
  610. }
  611. }
  612. this.finalizeParsing();
  613. if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2.Parser.parseText' );
  614. };
  615. Parser.prototype.processLine = function ( buffer, bufferPointer, slashesCount ) {
  616. if ( bufferPointer < 1 ) return;
  617. var reconstructString = function ( content, legacyMode, start, stop ) {
  618. var line = '';
  619. if ( stop > start ) {
  620. var i;
  621. if ( legacyMode ) {
  622. for ( i = start; i < stop; i++ ) line += content[ i ];
  623. } else {
  624. for ( i = start; i < stop; i++ ) line += String.fromCharCode( content[ i ] );
  625. }
  626. line = line.trim();
  627. }
  628. return line;
  629. };
  630. var bufferLength, length, i, lineDesignation;
  631. lineDesignation = buffer [ 0 ];
  632. switch ( lineDesignation ) {
  633. case 'v':
  634. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  635. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  636. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  637. if ( bufferPointer > 4 ) {
  638. this.colors.push( parseFloat( buffer[ 4 ] ) );
  639. this.colors.push( parseFloat( buffer[ 5 ] ) );
  640. this.colors.push( parseFloat( buffer[ 6 ] ) );
  641. }
  642. break;
  643. case 'vt':
  644. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  645. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  646. break;
  647. case 'vn':
  648. this.normals.push( parseFloat( buffer[ 1 ] ) );
  649. this.normals.push( parseFloat( buffer[ 2 ] ) );
  650. this.normals.push( parseFloat( buffer[ 3 ] ) );
  651. break;
  652. case 'f':
  653. bufferLength = bufferPointer - 1;
  654. // "f vertex ..."
  655. if ( slashesCount === 0 ) {
  656. this.checkFaceType( 0 );
  657. for ( i = 2, length = bufferLength; i < length; i ++ ) {
  658. this.buildFace( buffer[ 1 ] );
  659. this.buildFace( buffer[ i ] );
  660. this.buildFace( buffer[ i + 1 ] );
  661. }
  662. // "f vertex/uv ..."
  663. } else if ( bufferLength === slashesCount * 2 ) {
  664. this.checkFaceType( 1 );
  665. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  666. this.buildFace( buffer[ 1 ], buffer[ 2 ] );
  667. this.buildFace( buffer[ i ], buffer[ i + 1 ] );
  668. this.buildFace( buffer[ i + 2 ], buffer[ i + 3 ] );
  669. }
  670. // "f vertex/uv/normal ..."
  671. } else if ( bufferLength * 2 === slashesCount * 3 ) {
  672. this.checkFaceType( 2 );
  673. for ( i = 4, length = bufferLength - 3; i < length; i += 3 ) {
  674. this.buildFace( buffer[ 1 ], buffer[ 2 ], buffer[ 3 ] );
  675. this.buildFace( buffer[ i ], buffer[ i + 1 ], buffer[ i + 2 ] );
  676. this.buildFace( buffer[ i + 3 ], buffer[ i + 4 ], buffer[ i + 5 ] );
  677. }
  678. // "f vertex//normal ..."
  679. } else {
  680. this.checkFaceType( 3 );
  681. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  682. this.buildFace( buffer[ 1 ], undefined, buffer[ 2 ] );
  683. this.buildFace( buffer[ i ], undefined, buffer[ i + 1 ] );
  684. this.buildFace( buffer[ i + 2 ], undefined, buffer[ i + 3 ] );
  685. }
  686. }
  687. break;
  688. case 'l':
  689. case 'p':
  690. bufferLength = bufferPointer - 1;
  691. if ( bufferLength === slashesCount * 2 ) {
  692. this.checkFaceType( 4 );
  693. for ( i = 1, length = bufferLength + 1; i < length; i += 2 ) this.buildFace( buffer[ i ], buffer[ i + 1 ] );
  694. } else {
  695. this.checkFaceType( ( lineDesignation === 'l' ) ? 5 : 6 );
  696. for ( i = 1, length = bufferLength + 1; i < length; i ++ ) this.buildFace( buffer[ i ] );
  697. }
  698. break;
  699. case 's':
  700. this.pushSmoothingGroup( buffer[ 1 ] );
  701. break;
  702. case 'g':
  703. // 'g' leads to creation of mesh if valid data (faces declaration was done before), otherwise only groupName gets set
  704. this.processCompletedMesh();
  705. this.rawMesh.groupName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 2, this.globalCounts.currentByte );
  706. break;
  707. case 'o':
  708. // 'o' is meta-information and usually does not result in creation of new meshes, but can be enforced with "useOAsMesh"
  709. if ( this.useOAsMesh ) this.processCompletedMesh();
  710. this.rawMesh.objectName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 2, this.globalCounts.currentByte );
  711. break;
  712. case 'mtllib':
  713. this.rawMesh.mtllibName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 7, this.globalCounts.currentByte );
  714. break;
  715. case 'usemtl':
  716. var mtlName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 7, this.globalCounts.currentByte );
  717. if ( mtlName !== '' && this.rawMesh.activeMtlName !== mtlName ) {
  718. this.rawMesh.activeMtlName = mtlName;
  719. this.rawMesh.counts.mtlCount++;
  720. this.checkSubGroup();
  721. }
  722. break;
  723. default:
  724. break;
  725. }
  726. };
  727. Parser.prototype.pushSmoothingGroup = function ( smoothingGroup ) {
  728. var smoothingGroupInt = parseInt( smoothingGroup );
  729. if ( isNaN( smoothingGroupInt ) ) {
  730. smoothingGroupInt = smoothingGroup === "off" ? 0 : 1;
  731. }
  732. var smoothCheck = this.rawMesh.smoothingGroup.normalized;
  733. this.rawMesh.smoothingGroup.normalized = this.rawMesh.smoothingGroup.splitMaterials ? smoothingGroupInt : ( smoothingGroupInt === 0 ) ? 0 : 1;
  734. this.rawMesh.smoothingGroup.real = smoothingGroupInt;
  735. if ( smoothCheck !== smoothingGroupInt ) {
  736. this.rawMesh.counts.smoothingGroupCount++;
  737. this.checkSubGroup();
  738. }
  739. };
  740. /**
  741. * Expanded faceTypes include all four face types, both line types and the point type
  742. * faceType = 0: "f vertex ..."
  743. * faceType = 1: "f vertex/uv ..."
  744. * faceType = 2: "f vertex/uv/normal ..."
  745. * faceType = 3: "f vertex//normal ..."
  746. * faceType = 4: "l vertex/uv ..." or "l vertex ..."
  747. * faceType = 5: "l vertex ..."
  748. * faceType = 6: "p vertex ..."
  749. */
  750. Parser.prototype.checkFaceType = function ( faceType ) {
  751. if ( this.rawMesh.faceType !== faceType ) {
  752. this.processCompletedMesh();
  753. this.rawMesh.faceType = faceType;
  754. this.checkSubGroup();
  755. }
  756. };
  757. Parser.prototype.checkSubGroup = function () {
  758. var index = this.rawMesh.activeMtlName + '|' + this.rawMesh.smoothingGroup.normalized;
  759. this.rawMesh.subGroupInUse = this.rawMesh.subGroups[ index ];
  760. if ( ! THREE.LoaderSupport.Validator.isValid( this.rawMesh.subGroupInUse ) ) {
  761. this.rawMesh.subGroupInUse = {
  762. index: index,
  763. objectName: this.rawMesh.objectName,
  764. groupName: this.rawMesh.groupName,
  765. materialName: this.rawMesh.activeMtlName,
  766. smoothingGroup: this.rawMesh.smoothingGroup.normalized,
  767. vertices: [],
  768. indexMappingsCount: 0,
  769. indexMappings: [],
  770. indices: [],
  771. colors: [],
  772. uvs: [],
  773. normals: []
  774. };
  775. this.rawMesh.subGroups[ index ] = this.rawMesh.subGroupInUse;
  776. }
  777. };
  778. Parser.prototype.buildFace = function ( faceIndexV, faceIndexU, faceIndexN ) {
  779. if ( this.disregardNormals ) faceIndexN = undefined;
  780. var scope = this;
  781. var updateSubGroupInUse = function () {
  782. var faceIndexVi = parseInt( faceIndexV );
  783. var indexPointerV = 3 * ( faceIndexVi > 0 ? faceIndexVi - 1 : faceIndexVi + scope.vertices.length / 3 );
  784. var vertices = scope.rawMesh.subGroupInUse.vertices;
  785. vertices.push( scope.vertices[ indexPointerV++ ] );
  786. vertices.push( scope.vertices[ indexPointerV++ ] );
  787. vertices.push( scope.vertices[ indexPointerV ] );
  788. var indexPointerC = scope.colors.length > 0 ? indexPointerV + 1 : null;
  789. if ( indexPointerC !== null ) {
  790. var colors = scope.rawMesh.subGroupInUse.colors;
  791. colors.push( scope.colors[ indexPointerC++ ] );
  792. colors.push( scope.colors[ indexPointerC++ ] );
  793. colors.push( scope.colors[ indexPointerC ] );
  794. }
  795. if ( faceIndexU ) {
  796. var faceIndexUi = parseInt( faceIndexU );
  797. var indexPointerU = 2 * ( faceIndexUi > 0 ? faceIndexUi - 1 : faceIndexUi + scope.uvs.length / 2 );
  798. var uvs = scope.rawMesh.subGroupInUse.uvs;
  799. uvs.push( scope.uvs[ indexPointerU++ ] );
  800. uvs.push( scope.uvs[ indexPointerU ] );
  801. }
  802. if ( faceIndexN ) {
  803. var faceIndexNi = parseInt( faceIndexN );
  804. var indexPointerN = 3 * ( faceIndexNi > 0 ? faceIndexNi - 1 : faceIndexNi + scope.normals.length / 3 );
  805. var normals = scope.rawMesh.subGroupInUse.normals;
  806. normals.push( scope.normals[ indexPointerN++ ] );
  807. normals.push( scope.normals[ indexPointerN++ ] );
  808. normals.push( scope.normals[ indexPointerN ] );
  809. }
  810. };
  811. if ( this.useIndices ) {
  812. var mappingName = faceIndexV + ( faceIndexU ? '_' + faceIndexU : '_n' ) + ( faceIndexN ? '_' + faceIndexN : '_n' );
  813. var indicesPointer = this.rawMesh.subGroupInUse.indexMappings[ mappingName ];
  814. if ( THREE.LoaderSupport.Validator.isValid( indicesPointer ) ) {
  815. this.rawMesh.counts.doubleIndicesCount++;
  816. } else {
  817. indicesPointer = this.rawMesh.subGroupInUse.vertices.length / 3;
  818. updateSubGroupInUse();
  819. this.rawMesh.subGroupInUse.indexMappings[ mappingName ] = indicesPointer;
  820. this.rawMesh.subGroupInUse.indexMappingsCount++;
  821. }
  822. this.rawMesh.subGroupInUse.indices.push( indicesPointer );
  823. } else {
  824. updateSubGroupInUse();
  825. }
  826. this.rawMesh.counts.faceCount++;
  827. };
  828. Parser.prototype.createRawMeshReport = function ( inputObjectCount ) {
  829. return 'Input Object number: ' + inputObjectCount +
  830. '\n\tObject name: ' + this.rawMesh.objectName +
  831. '\n\tGroup name: ' + this.rawMesh.groupName +
  832. '\n\tMtllib name: ' + this.rawMesh.mtllibName +
  833. '\n\tVertex count: ' + this.vertices.length / 3 +
  834. '\n\tNormal count: ' + this.normals.length / 3 +
  835. '\n\tUV count: ' + this.uvs.length / 2 +
  836. '\n\tSmoothingGroup count: ' + this.rawMesh.counts.smoothingGroupCount +
  837. '\n\tMaterial count: ' + this.rawMesh.counts.mtlCount +
  838. '\n\tReal MeshOutputGroup count: ' + this.rawMesh.subGroups.length;
  839. };
  840. /**
  841. * Clear any empty subGroup and calculate absolute vertex, normal and uv counts
  842. */
  843. Parser.prototype.finalizeRawMesh = function () {
  844. var meshOutputGroupTemp = [];
  845. var meshOutputGroup;
  846. var absoluteVertexCount = 0;
  847. var absoluteIndexMappingsCount = 0;
  848. var absoluteIndexCount = 0;
  849. var absoluteColorCount = 0;
  850. var absoluteNormalCount = 0;
  851. var absoluteUvCount = 0;
  852. var indices;
  853. for ( var name in this.rawMesh.subGroups ) {
  854. meshOutputGroup = this.rawMesh.subGroups[ name ];
  855. if ( meshOutputGroup.vertices.length > 0 ) {
  856. indices = meshOutputGroup.indices;
  857. if ( indices.length > 0 && absoluteIndexMappingsCount > 0 ) {
  858. for ( var i in indices ) indices[ i ] = indices[ i ] + absoluteIndexMappingsCount;
  859. }
  860. meshOutputGroupTemp.push( meshOutputGroup );
  861. absoluteVertexCount += meshOutputGroup.vertices.length;
  862. absoluteIndexMappingsCount += meshOutputGroup.indexMappingsCount;
  863. absoluteIndexCount += meshOutputGroup.indices.length;
  864. absoluteColorCount += meshOutputGroup.colors.length;
  865. absoluteUvCount += meshOutputGroup.uvs.length;
  866. absoluteNormalCount += meshOutputGroup.normals.length;
  867. }
  868. }
  869. // do not continue if no result
  870. var result = null;
  871. if ( meshOutputGroupTemp.length > 0 ) {
  872. result = {
  873. name: this.rawMesh.groupName !== '' ? this.rawMesh.groupName : this.rawMesh.objectName,
  874. subGroups: meshOutputGroupTemp,
  875. absoluteVertexCount: absoluteVertexCount,
  876. absoluteIndexCount: absoluteIndexCount,
  877. absoluteColorCount: absoluteColorCount,
  878. absoluteNormalCount: absoluteNormalCount,
  879. absoluteUvCount: absoluteUvCount,
  880. faceCount: this.rawMesh.counts.faceCount,
  881. doubleIndicesCount: this.rawMesh.counts.doubleIndicesCount
  882. };
  883. }
  884. return result;
  885. };
  886. Parser.prototype.processCompletedMesh = function () {
  887. var result = this.finalizeRawMesh();
  888. if ( THREE.LoaderSupport.Validator.isValid( result ) ) {
  889. if ( this.colors.length > 0 && this.colors.length !== this.vertices.length ) {
  890. this._throwError( 'Vertex Colors were detected, but vertex count and color count do not match!' );
  891. }
  892. if ( this.logging.enabled && this.logging.debug ) console.debug( this.createRawMeshReport( this.inputObjectCount ) );
  893. this.inputObjectCount++;
  894. this.buildMesh( result );
  895. var progressBytesPercent = this.globalCounts.currentByte / this.globalCounts.totalBytes;
  896. this.callbackProgress( 'Completed [o: ' + this.rawMesh.objectName + ' g:' + this.rawMesh.groupName + '] Total progress: ' + ( progressBytesPercent * 100 ).toFixed( 2 ) + '%', progressBytesPercent );
  897. this.resetRawMesh();
  898. return true;
  899. } else {
  900. return false;
  901. }
  902. };
  903. /**
  904. * SubGroups are transformed to too intermediate format that is forwarded to the MeshBuilder.
  905. * It is ensured that SubGroups only contain objects with vertices (no need to check).
  906. *
  907. * @param result
  908. */
  909. Parser.prototype.buildMesh = function ( result ) {
  910. var meshOutputGroups = result.subGroups;
  911. var vertexFA = new Float32Array( result.absoluteVertexCount );
  912. this.globalCounts.vertices += result.absoluteVertexCount / 3;
  913. this.globalCounts.faces += result.faceCount;
  914. this.globalCounts.doubleIndicesCount += result.doubleIndicesCount;
  915. var indexUA = ( result.absoluteIndexCount > 0 ) ? new Uint32Array( result.absoluteIndexCount ) : null;
  916. var colorFA = ( result.absoluteColorCount > 0 ) ? new Float32Array( result.absoluteColorCount ) : null;
  917. var normalFA = ( result.absoluteNormalCount > 0 ) ? new Float32Array( result.absoluteNormalCount ) : null;
  918. var uvFA = ( result.absoluteUvCount > 0 ) ? new Float32Array( result.absoluteUvCount ) : null;
  919. var haveVertexColors = THREE.LoaderSupport.Validator.isValid( colorFA );
  920. var meshOutputGroup;
  921. var materialNames = [];
  922. var createMultiMaterial = ( meshOutputGroups.length > 1 );
  923. var materialIndex = 0;
  924. var materialIndexMapping = [];
  925. var selectedMaterialIndex;
  926. var materialGroup;
  927. var materialGroups = [];
  928. var vertexFAOffset = 0;
  929. var indexUAOffset = 0;
  930. var colorFAOffset = 0;
  931. var normalFAOffset = 0;
  932. var uvFAOffset = 0;
  933. var materialGroupOffset = 0;
  934. var materialGroupLength = 0;
  935. var materialOrg, material, materialName, materialNameOrg;
  936. // only one specific face type
  937. for ( var oodIndex in meshOutputGroups ) {
  938. if ( ! meshOutputGroups.hasOwnProperty( oodIndex ) ) continue;
  939. meshOutputGroup = meshOutputGroups[ oodIndex ];
  940. materialNameOrg = meshOutputGroup.materialName;
  941. if ( this.rawMesh.faceType < 4 ) {
  942. materialName = materialNameOrg + ( haveVertexColors ? '_vertexColor' : '' ) + ( meshOutputGroup.smoothingGroup === 0 ? '_flat' : '' );
  943. } else {
  944. materialName = this.rawMesh.faceType === 6 ? 'defaultPointMaterial' : 'defaultLineMaterial';
  945. }
  946. materialOrg = this.materials[ materialNameOrg ];
  947. material = this.materials[ materialName ];
  948. // both original and derived names do not lead to an existing material => need to use a default material
  949. if ( ! THREE.LoaderSupport.Validator.isValid( materialOrg ) && ! THREE.LoaderSupport.Validator.isValid( material ) ) {
  950. var defaultMaterialName = haveVertexColors ? 'defaultVertexColorMaterial' : 'defaultMaterial';
  951. materialOrg = this.materials[ defaultMaterialName ];
  952. if ( this.logging.enabled ) console.warn( 'object_group "' + meshOutputGroup.objectName + '_' +
  953. meshOutputGroup.groupName + '" was defined with unresolvable material "' +
  954. materialNameOrg + '"! Assigning "' + defaultMaterialName + '".' );
  955. materialNameOrg = defaultMaterialName;
  956. // if names are identical then there is no need for later manipulation
  957. if ( materialNameOrg === materialName ) {
  958. material = materialOrg;
  959. materialName = defaultMaterialName;
  960. }
  961. }
  962. if ( ! THREE.LoaderSupport.Validator.isValid( material ) ) {
  963. var materialCloneInstructions = {
  964. materialNameOrg: materialNameOrg,
  965. materialName: materialName,
  966. materialProperties: {
  967. vertexColors: haveVertexColors ? 2 : 0,
  968. flatShading: meshOutputGroup.smoothingGroup === 0
  969. }
  970. };
  971. var payload = {
  972. cmd: 'materialData',
  973. materials: {
  974. materialCloneInstructions: materialCloneInstructions
  975. }
  976. };
  977. this.callbackMeshBuilder( payload );
  978. // fake entry for async; sync Parser always works on material references (Builder update directly visible here)
  979. if ( this.useAsync ) this.materials[ materialName ] = materialCloneInstructions;
  980. }
  981. if ( createMultiMaterial ) {
  982. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  983. selectedMaterialIndex = materialIndexMapping[ materialName ];
  984. if ( ! selectedMaterialIndex ) {
  985. selectedMaterialIndex = materialIndex;
  986. materialIndexMapping[ materialName ] = materialIndex;
  987. materialNames.push( materialName );
  988. materialIndex++;
  989. }
  990. materialGroupLength = this.useIndices ? meshOutputGroup.indices.length : meshOutputGroup.vertices.length / 3;
  991. materialGroup = {
  992. start: materialGroupOffset,
  993. count: materialGroupLength,
  994. index: selectedMaterialIndex
  995. };
  996. materialGroups.push( materialGroup );
  997. materialGroupOffset += materialGroupLength;
  998. } else {
  999. materialNames.push( materialName );
  1000. }
  1001. vertexFA.set( meshOutputGroup.vertices, vertexFAOffset );
  1002. vertexFAOffset += meshOutputGroup.vertices.length;
  1003. if ( indexUA ) {
  1004. indexUA.set( meshOutputGroup.indices, indexUAOffset );
  1005. indexUAOffset += meshOutputGroup.indices.length;
  1006. }
  1007. if ( colorFA ) {
  1008. colorFA.set( meshOutputGroup.colors, colorFAOffset );
  1009. colorFAOffset += meshOutputGroup.colors.length;
  1010. }
  1011. if ( normalFA ) {
  1012. normalFA.set( meshOutputGroup.normals, normalFAOffset );
  1013. normalFAOffset += meshOutputGroup.normals.length;
  1014. }
  1015. if ( uvFA ) {
  1016. uvFA.set( meshOutputGroup.uvs, uvFAOffset );
  1017. uvFAOffset += meshOutputGroup.uvs.length;
  1018. }
  1019. if ( this.logging.enabled && this.logging.debug ) {
  1020. var materialIndexLine = THREE.LoaderSupport.Validator.isValid( selectedMaterialIndex ) ? '\n\t\tmaterialIndex: ' + selectedMaterialIndex : '';
  1021. var createdReport = '\tOutput Object no.: ' + this.outputObjectCount +
  1022. '\n\t\tgroupName: ' + meshOutputGroup.groupName +
  1023. '\n\t\tIndex: ' + meshOutputGroup.index +
  1024. '\n\t\tfaceType: ' + this.rawMesh.faceType +
  1025. '\n\t\tmaterialName: ' + meshOutputGroup.materialName +
  1026. '\n\t\tsmoothingGroup: ' + meshOutputGroup.smoothingGroup +
  1027. materialIndexLine +
  1028. '\n\t\tobjectName: ' + meshOutputGroup.objectName +
  1029. '\n\t\t#vertices: ' + meshOutputGroup.vertices.length / 3 +
  1030. '\n\t\t#indices: ' + meshOutputGroup.indices.length +
  1031. '\n\t\t#colors: ' + meshOutputGroup.colors.length / 3 +
  1032. '\n\t\t#uvs: ' + meshOutputGroup.uvs.length / 2 +
  1033. '\n\t\t#normals: ' + meshOutputGroup.normals.length / 3;
  1034. console.debug( createdReport );
  1035. }
  1036. }
  1037. this.outputObjectCount++;
  1038. this.callbackMeshBuilder(
  1039. {
  1040. cmd: 'meshData',
  1041. progress: {
  1042. numericalValue: this.globalCounts.currentByte / this.globalCounts.totalBytes
  1043. },
  1044. params: {
  1045. meshName: result.name
  1046. },
  1047. materials: {
  1048. multiMaterial: createMultiMaterial,
  1049. materialNames: materialNames,
  1050. materialGroups: materialGroups
  1051. },
  1052. buffers: {
  1053. vertices: vertexFA,
  1054. indices: indexUA,
  1055. colors: colorFA,
  1056. normals: normalFA,
  1057. uvs: uvFA
  1058. },
  1059. // 0: mesh, 1: line, 2: point
  1060. geometryType: this.rawMesh.faceType < 4 ? 0 : ( this.rawMesh.faceType === 6 ) ? 2 : 1
  1061. },
  1062. [ vertexFA.buffer ],
  1063. THREE.LoaderSupport.Validator.isValid( indexUA ) ? [ indexUA.buffer ] : null,
  1064. THREE.LoaderSupport.Validator.isValid( colorFA ) ? [ colorFA.buffer ] : null,
  1065. THREE.LoaderSupport.Validator.isValid( normalFA ) ? [ normalFA.buffer ] : null,
  1066. THREE.LoaderSupport.Validator.isValid( uvFA ) ? [ uvFA.buffer ] : null
  1067. );
  1068. };
  1069. Parser.prototype.finalizeParsing = function () {
  1070. if ( this.logging.enabled ) console.info( 'Global output object count: ' + this.outputObjectCount );
  1071. if ( this.processCompletedMesh() && this.logging.enabled ) {
  1072. var parserFinalReport = 'Overall counts: ' +
  1073. '\n\tVertices: ' + this.globalCounts.vertices +
  1074. '\n\tFaces: ' + this.globalCounts.faces +
  1075. '\n\tMultiple definitions: ' + this.globalCounts.doubleIndicesCount;
  1076. console.info( parserFinalReport );
  1077. }
  1078. };
  1079. return Parser;
  1080. })();
  1081. /**
  1082. * Utility method for loading an mtl file according resource description. Provide url or content.
  1083. * @memberOf THREE.OBJLoader2
  1084. *
  1085. * @param {string} url URL to the file
  1086. * @param {Object} content The file content as arraybuffer or text
  1087. * @param {function} onLoad Callback to be called after successful load
  1088. * @param {callback} [onProgress] A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and Integer bytes.
  1089. * @param {callback} [onError] A function to be called if an error occurs during loading. The function receives the error as an argument.
  1090. * @param {string} [crossOrigin] CORS value
  1091. * @param {Object} [materialOptions] Set material loading options for MTLLoader
  1092. */
  1093. OBJLoader2.prototype.loadMtl = function ( url, content, onLoad, onProgress, onError, crossOrigin, materialOptions ) {
  1094. var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'MTL' );
  1095. resource.setContent( content );
  1096. this._loadMtl( resource, onLoad, onProgress, onError, crossOrigin, materialOptions );
  1097. };
  1098. OBJLoader2.prototype._loadMtl = function ( resource, onLoad, onProgress, onError, crossOrigin, materialOptions ) {
  1099. if ( THREE.MTLLoader === undefined ) console.error( '"THREE.MTLLoader" is not available. "THREE.OBJLoader2" requires it for loading MTL files.' );
  1100. if ( Validator.isValid( resource ) && this.logging.enabled ) console.time( 'Loading MTL: ' + resource.name );
  1101. var materials = [];
  1102. var scope = this;
  1103. var processMaterials = function ( materialCreator ) {
  1104. var materialCreatorMaterials = [];
  1105. if ( Validator.isValid( materialCreator ) ) {
  1106. materialCreator.preload();
  1107. materialCreatorMaterials = materialCreator.materials;
  1108. for ( var materialName in materialCreatorMaterials ) {
  1109. if ( materialCreatorMaterials.hasOwnProperty( materialName ) ) {
  1110. materials[ materialName ] = materialCreatorMaterials[ materialName ];
  1111. }
  1112. }
  1113. }
  1114. if ( Validator.isValid( resource ) && scope.logging.enabled ) console.timeEnd( 'Loading MTL: ' + resource.name );
  1115. onLoad( materials, materialCreator );
  1116. };
  1117. // fast-fail
  1118. if ( ! Validator.isValid( resource ) || ( ! Validator.isValid( resource.content ) && ! Validator.isValid( resource.url ) ) ) {
  1119. processMaterials();
  1120. } else {
  1121. var mtlLoader = new THREE.MTLLoader( this.manager );
  1122. crossOrigin = Validator.verifyInput( crossOrigin, 'anonymous' );
  1123. mtlLoader.setCrossOrigin( crossOrigin );
  1124. mtlLoader.setResourcePath( resource.path );
  1125. if ( Validator.isValid( materialOptions ) ) mtlLoader.setMaterialOptions( materialOptions );
  1126. var parseTextWithMtlLoader = function ( content ) {
  1127. var contentAsText = content;
  1128. if ( typeof( content ) !== 'string' && ! ( content instanceof String ) ) {
  1129. if ( content.length > 0 || content.byteLength > 0 ) {
  1130. contentAsText = THREE.LoaderUtils.decodeText( content );
  1131. } else {
  1132. this._throwError( 'Unable to parse mtl as it it seems to be neither a String, an Array or an ArrayBuffer!' );
  1133. }
  1134. }
  1135. processMaterials( mtlLoader.parse( contentAsText ) );
  1136. };
  1137. if ( Validator.isValid( resource.content ) ) {
  1138. parseTextWithMtlLoader( resource.content );
  1139. } else if ( Validator.isValid( resource.url ) ) {
  1140. var fileLoader = new THREE.FileLoader( this.manager );
  1141. if ( ! Validator.isValid( onError ) ) {
  1142. onError = function ( event ) {
  1143. scope._onError( event );
  1144. };
  1145. }
  1146. if ( ! Validator.isValid( onProgress ) ) {
  1147. var numericalValueRef = 0;
  1148. var numericalValue = 0;
  1149. onProgress = function ( event ) {
  1150. if ( ! event.lengthComputable ) return;
  1151. numericalValue = event.loaded / event.total;
  1152. if ( numericalValue > numericalValueRef ) {
  1153. numericalValueRef = numericalValue;
  1154. var output = 'Download of "' + resource.url + '": ' + ( numericalValue * 100 ).toFixed( 2 ) + '%';
  1155. scope.onProgress( 'progressLoad', output, numericalValue );
  1156. }
  1157. };
  1158. }
  1159. fileLoader.load( resource.url, parseTextWithMtlLoader, onProgress, onError );
  1160. }
  1161. }
  1162. };
  1163. return OBJLoader2;
  1164. })();