OBJLoader2.js 46 KB

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