LoaderSupport.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. /**
  2. * @author Kai Salmen / https://kaisalmen.de
  3. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  4. */
  5. 'use strict';
  6. if ( THREE.LoaderSupport === undefined ) { THREE.LoaderSupport = {} }
  7. /**
  8. * Validation functions.
  9. * @class
  10. */
  11. THREE.LoaderSupport.Validator = {
  12. /**
  13. * If given input is null or undefined, false is returned otherwise true.
  14. *
  15. * @param input Can be anything
  16. * @returns {boolean}
  17. */
  18. isValid: function( input ) {
  19. return ( input !== null && input !== undefined );
  20. },
  21. /**
  22. * If given input is null or undefined, the defaultValue is returned otherwise the given input.
  23. *
  24. * @param input Can be anything
  25. * @param defaultValue Can be anything
  26. * @returns {*}
  27. */
  28. verifyInput: function( input, defaultValue ) {
  29. return ( input === null || input === undefined ) ? defaultValue : input;
  30. }
  31. };
  32. /**
  33. * Callbacks utilized by loaders and builders.
  34. * @class
  35. */
  36. THREE.LoaderSupport.Callbacks = function () {
  37. this.onProgress = null;
  38. this.onReportError = null;
  39. this.onMeshAlter = null;
  40. this.onLoad = null;
  41. this.onLoadMaterials = null;
  42. };
  43. THREE.LoaderSupport.Callbacks.prototype = {
  44. constructor: THREE.LoaderSupport.Callbacks,
  45. /**
  46. * Register callback function that is invoked by internal function "announceProgress" to print feedback.
  47. *
  48. * @param {callback} callbackOnProgress Callback function for described functionality
  49. */
  50. setCallbackOnProgress: function ( callbackOnProgress ) {
  51. this.onProgress = THREE.LoaderSupport.Validator.verifyInput( callbackOnProgress, this.onProgress );
  52. },
  53. /**
  54. * Register callback function that is invoked when an error is reported.
  55. *
  56. * @param {callback} callbackOnReportError Callback function for described functionality
  57. */
  58. setCallbackOnReportError: function ( callbackOnReportError ) {
  59. this.onReportError = THREE.LoaderSupport.Validator.verifyInput( callbackOnReportError, this.onReportError );
  60. },
  61. /**
  62. * Register callback function that is called every time a mesh was loaded.
  63. * Use {@link THREE.LoaderSupport.LoadedMeshUserOverride} for alteration instructions (geometry, material or disregard mesh).
  64. *
  65. * @param {callback} callbackOnMeshAlter Callback function for described functionality
  66. */
  67. setCallbackOnMeshAlter: function ( callbackOnMeshAlter ) {
  68. this.onMeshAlter = THREE.LoaderSupport.Validator.verifyInput( callbackOnMeshAlter, this.onMeshAlter );
  69. },
  70. /**
  71. * Register callback function that is called once loading of the complete OBJ file is completed.
  72. *
  73. * @param {callback} callbackOnLoad Callback function for described functionality
  74. */
  75. setCallbackOnLoad: function ( callbackOnLoad ) {
  76. this.onLoad = THREE.LoaderSupport.Validator.verifyInput( callbackOnLoad, this.onLoad );
  77. },
  78. /**
  79. * Register callback function that is called when materials have been loaded.
  80. *
  81. * @param {callback} callbackOnLoadMaterials Callback function for described functionality
  82. */
  83. setCallbackOnLoadMaterials: function ( callbackOnLoadMaterials ) {
  84. this.onLoadMaterials = THREE.LoaderSupport.Validator.verifyInput( callbackOnLoadMaterials, this.onLoadMaterials );
  85. }
  86. };
  87. /**
  88. * Object to return by callback onMeshAlter. Used to disregard a certain mesh or to return one to many meshes.
  89. * @class
  90. *
  91. * @param {boolean} disregardMesh=false Tell implementation to completely disregard this mesh
  92. * @param {boolean} disregardMesh=false Tell implementation that mesh(es) have been altered or added
  93. */
  94. THREE.LoaderSupport.LoadedMeshUserOverride = function( disregardMesh, alteredMesh ) {
  95. this.disregardMesh = disregardMesh === true;
  96. this.alteredMesh = alteredMesh === true;
  97. this.meshes = [];
  98. };
  99. THREE.LoaderSupport.LoadedMeshUserOverride.prototype = {
  100. constructor: THREE.LoaderSupport.LoadedMeshUserOverride,
  101. /**
  102. * Add a mesh created within callback.
  103. *
  104. * @param {THREE.Mesh} mesh
  105. */
  106. addMesh: function ( mesh ) {
  107. this.meshes.push( mesh );
  108. this.alteredMesh = true;
  109. },
  110. /**
  111. * Answers if mesh shall be disregarded completely.
  112. *
  113. * @returns {boolean}
  114. */
  115. isDisregardMesh: function () {
  116. return this.disregardMesh;
  117. },
  118. /**
  119. * Answers if new mesh(es) were created.
  120. *
  121. * @returns {boolean}
  122. */
  123. providesAlteredMeshes: function () {
  124. return this.alteredMesh;
  125. }
  126. };
  127. /**
  128. * A resource description used by {@link THREE.LoaderSupport.PrepData} and others.
  129. * @class
  130. *
  131. * @param {string} url URL to the file
  132. * @param {string} extension The file extension (type)
  133. */
  134. THREE.LoaderSupport.ResourceDescriptor = function ( url, extension ) {
  135. var urlParts = url.split( '/' );
  136. this.path;
  137. this.resourcePath;
  138. this.name = url;
  139. this.url = url;
  140. if ( urlParts.length >= 2 ) {
  141. this.path = THREE.LoaderSupport.Validator.verifyInput( urlParts.slice( 0, urlParts.length - 1).join( '/' ) + '/', this.path );
  142. this.name = urlParts[ urlParts.length - 1 ];
  143. this.url = url;
  144. }
  145. this.name = THREE.LoaderSupport.Validator.verifyInput( this.name, 'Unnamed_Resource' );
  146. this.extension = THREE.LoaderSupport.Validator.verifyInput( extension, 'default' );
  147. this.extension = this.extension.trim();
  148. this.content = null;
  149. };
  150. THREE.LoaderSupport.ResourceDescriptor.prototype = {
  151. constructor: THREE.LoaderSupport.ResourceDescriptor,
  152. /**
  153. * Set the content of this resource
  154. *
  155. * @param {Object} content The file content as arraybuffer or text
  156. */
  157. setContent: function ( content ) {
  158. this.content = THREE.LoaderSupport.Validator.verifyInput( content, null );
  159. },
  160. /**
  161. * Allows to specify resourcePath for dependencies of specified resource.
  162. * @param {string} resourcePath
  163. */
  164. setResourcePath: function ( resourcePath ) {
  165. this.resourcePath = THREE.LoaderSupport.Validator.verifyInput( resourcePath, this.resourcePath );
  166. }
  167. };
  168. /**
  169. * Configuration instructions to be used by run method.
  170. * @class
  171. */
  172. THREE.LoaderSupport.PrepData = function ( modelName ) {
  173. this.logging = {
  174. enabled: true,
  175. debug: false
  176. };
  177. this.modelName = THREE.LoaderSupport.Validator.verifyInput( modelName, '' );
  178. this.resources = [];
  179. this.callbacks = new THREE.LoaderSupport.Callbacks();
  180. };
  181. THREE.LoaderSupport.PrepData.prototype = {
  182. constructor: THREE.LoaderSupport.PrepData,
  183. /**
  184. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  185. *
  186. * @param {boolean} enabled True or false.
  187. * @param {boolean} debug True or false.
  188. */
  189. setLogging: function ( enabled, debug ) {
  190. this.logging.enabled = enabled === true;
  191. this.logging.debug = debug === true;
  192. },
  193. /**
  194. * Returns all callbacks as {@link THREE.LoaderSupport.Callbacks}
  195. *
  196. * @returns {THREE.LoaderSupport.Callbacks}
  197. */
  198. getCallbacks: function () {
  199. return this.callbacks;
  200. },
  201. /**
  202. * Add a resource description.
  203. *
  204. * @param {THREE.LoaderSupport.ResourceDescriptor} Adds a {@link THREE.LoaderSupport.ResourceDescriptor}
  205. */
  206. addResource: function ( resource ) {
  207. this.resources.push( resource );
  208. },
  209. /**
  210. * Clones this object and returns it afterwards. Callbacks and resources are not cloned deep (references!).
  211. *
  212. * @returns {@link THREE.LoaderSupport.PrepData}
  213. */
  214. clone: function () {
  215. var clone = new THREE.LoaderSupport.PrepData( this.modelName );
  216. clone.logging.enabled = this.logging.enabled;
  217. clone.logging.debug = this.logging.debug;
  218. clone.resources = this.resources;
  219. clone.callbacks = this.callbacks;
  220. var property, value;
  221. for ( property in this ) {
  222. value = this[ property ];
  223. if ( ! clone.hasOwnProperty( property ) && typeof this[ property ] !== 'function' ) {
  224. clone[ property ] = value;
  225. }
  226. }
  227. return clone;
  228. },
  229. /**
  230. * Identify files or content of interest from an Array of {@link THREE.LoaderSupport.ResourceDescriptor}.
  231. *
  232. * @param {THREE.LoaderSupport.ResourceDescriptor[]} resources Array of {@link THREE.LoaderSupport.ResourceDescriptor}
  233. * @param Object fileDesc Object describing which resources are of interest (ext, type (string or UInt8Array) and ignore (boolean))
  234. * @returns {{}} Object with each "ext" and the corresponding {@link THREE.LoaderSupport.ResourceDescriptor}
  235. */
  236. checkResourceDescriptorFiles: function ( resources, fileDesc ) {
  237. var resource, triple, i, found;
  238. var result = {};
  239. for ( var index in resources ) {
  240. resource = resources[ index ];
  241. found = false;
  242. if ( ! THREE.LoaderSupport.Validator.isValid( resource.name ) ) continue;
  243. if ( THREE.LoaderSupport.Validator.isValid( resource.content ) ) {
  244. for ( i = 0; i < fileDesc.length && !found; i++ ) {
  245. triple = fileDesc[ i ];
  246. if ( resource.extension.toLowerCase() === triple.ext.toLowerCase() ) {
  247. if ( triple.ignore ) {
  248. found = true;
  249. } else if ( triple.type === "ArrayBuffer" ) {
  250. // fast-fail on bad type
  251. if ( ! ( resource.content instanceof ArrayBuffer || resource.content instanceof Uint8Array ) ) throw 'Provided content is not of type ArrayBuffer! Aborting...';
  252. result[ triple.ext ] = resource;
  253. found = true;
  254. } else if ( triple.type === "String" ) {
  255. if ( ! ( typeof( resource.content ) === 'string' || resource.content instanceof String) ) throw 'Provided content is not of type String! Aborting...';
  256. result[ triple.ext ] = resource;
  257. found = true;
  258. }
  259. }
  260. }
  261. if ( !found ) throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  262. } else {
  263. // fast-fail on bad type
  264. if ( ! ( typeof( resource.name ) === 'string' || resource.name instanceof String ) ) throw 'Provided file is not properly defined! Aborting...';
  265. for ( i = 0; i < fileDesc.length && !found; i++ ) {
  266. triple = fileDesc[ i ];
  267. if ( resource.extension.toLowerCase() === triple.ext.toLowerCase() ) {
  268. if ( ! triple.ignore ) result[ triple.ext ] = resource;
  269. found = true;
  270. }
  271. }
  272. if ( !found ) throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  273. }
  274. }
  275. return result;
  276. }
  277. };
  278. /**
  279. * Builds one or many THREE.Mesh from one raw set of Arraybuffers, materialGroup descriptions and further parameters.
  280. * Supports vertex, vertexColor, normal, uv and index buffers.
  281. * @class
  282. */
  283. THREE.LoaderSupport.MeshBuilder = function() {
  284. console.info( 'Using THREE.LoaderSupport.MeshBuilder version: ' + THREE.LoaderSupport.MeshBuilder.LOADER_MESH_BUILDER_VERSION );
  285. this.validator = THREE.LoaderSupport.Validator;
  286. this.logging = {
  287. enabled: true,
  288. debug: false
  289. };
  290. this.callbacks = new THREE.LoaderSupport.Callbacks();
  291. this.materials = [];
  292. };
  293. THREE.LoaderSupport.MeshBuilder.LOADER_MESH_BUILDER_VERSION = '1.3.0';
  294. THREE.LoaderSupport.MeshBuilder.prototype = {
  295. constructor: THREE.LoaderSupport.MeshBuilder,
  296. /**
  297. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  298. *
  299. * @param {boolean} enabled True or false.
  300. * @param {boolean} debug True or false.
  301. */
  302. setLogging: function ( enabled, debug ) {
  303. this.logging.enabled = enabled === true;
  304. this.logging.debug = debug === true;
  305. },
  306. /**
  307. * Initializes the MeshBuilder (currently only default material initialisation).
  308. *
  309. */
  310. init: function () {
  311. var defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  312. defaultMaterial.name = 'defaultMaterial';
  313. var defaultVertexColorMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  314. defaultVertexColorMaterial.name = 'defaultVertexColorMaterial';
  315. defaultVertexColorMaterial.vertexColors = THREE.VertexColors;
  316. var defaultLineMaterial = new THREE.LineBasicMaterial();
  317. defaultLineMaterial.name = 'defaultLineMaterial';
  318. var defaultPointMaterial = new THREE.PointsMaterial( { size: 1 } );
  319. defaultPointMaterial.name = 'defaultPointMaterial';
  320. var runtimeMaterials = {};
  321. runtimeMaterials[ defaultMaterial.name ] = defaultMaterial;
  322. runtimeMaterials[ defaultVertexColorMaterial.name ] = defaultVertexColorMaterial;
  323. runtimeMaterials[ defaultLineMaterial.name ] = defaultLineMaterial;
  324. runtimeMaterials[ defaultPointMaterial.name ] = defaultPointMaterial;
  325. this.updateMaterials(
  326. {
  327. cmd: 'materialData',
  328. materials: {
  329. materialCloneInstructions: null,
  330. serializedMaterials: null,
  331. runtimeMaterials: runtimeMaterials
  332. }
  333. }
  334. );
  335. },
  336. /**
  337. * Set materials loaded by any supplier of an Array of {@link THREE.Material}.
  338. *
  339. * @param {THREE.Material[]} materials Array of {@link THREE.Material}
  340. */
  341. setMaterials: function ( materials ) {
  342. var payload = {
  343. cmd: 'materialData',
  344. materials: {
  345. materialCloneInstructions: null,
  346. serializedMaterials: null,
  347. runtimeMaterials: this.validator.isValid( this.callbacks.onLoadMaterials ) ? this.callbacks.onLoadMaterials( materials ) : materials
  348. }
  349. };
  350. this.updateMaterials( payload );
  351. },
  352. _setCallbacks: function ( callbacks ) {
  353. if ( this.validator.isValid( callbacks.onProgress ) ) this.callbacks.setCallbackOnProgress( callbacks.onProgress );
  354. if ( this.validator.isValid( callbacks.onReportError ) ) this.callbacks.setCallbackOnReportError( callbacks.onReportError );
  355. if ( this.validator.isValid( callbacks.onMeshAlter ) ) this.callbacks.setCallbackOnMeshAlter( callbacks.onMeshAlter );
  356. if ( this.validator.isValid( callbacks.onLoad ) ) this.callbacks.setCallbackOnLoad( callbacks.onLoad );
  357. if ( this.validator.isValid( callbacks.onLoadMaterials ) ) this.callbacks.setCallbackOnLoadMaterials( callbacks.onLoadMaterials );
  358. },
  359. /**
  360. * Delegates processing of the payload (mesh building or material update) to the corresponding functions (BW-compatibility).
  361. *
  362. * @param {Object} payload Raw Mesh or Material descriptions.
  363. * @returns {THREE.Mesh[]} mesh Array of {@link THREE.Mesh} or null in case of material update
  364. */
  365. processPayload: function ( payload ) {
  366. if ( payload.cmd === 'meshData' ) {
  367. return this.buildMeshes( payload );
  368. } else if ( payload.cmd === 'materialData' ) {
  369. this.updateMaterials( payload );
  370. return null;
  371. }
  372. },
  373. /**
  374. * Builds one or multiple meshes from the data described in the payload (buffers, params, material info).
  375. *
  376. * @param {Object} meshPayload Raw mesh description (buffers, params, materials) used to build one to many meshes.
  377. * @returns {THREE.Mesh[]} mesh Array of {@link THREE.Mesh}
  378. */
  379. buildMeshes: function ( meshPayload ) {
  380. var meshName = meshPayload.params.meshName;
  381. var bufferGeometry = new THREE.BufferGeometry();
  382. bufferGeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.vertices ), 3 ) );
  383. if ( this.validator.isValid( meshPayload.buffers.indices ) ) {
  384. bufferGeometry.setIndex( new THREE.BufferAttribute( new Uint32Array( meshPayload.buffers.indices ), 1 ));
  385. }
  386. var haveVertexColors = this.validator.isValid( meshPayload.buffers.colors );
  387. if ( haveVertexColors ) {
  388. bufferGeometry.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.colors ), 3 ) );
  389. }
  390. if ( this.validator.isValid( meshPayload.buffers.normals ) ) {
  391. bufferGeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.normals ), 3 ) );
  392. } else {
  393. bufferGeometry.computeVertexNormals();
  394. }
  395. if ( this.validator.isValid( meshPayload.buffers.uvs ) ) {
  396. bufferGeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.uvs ), 2 ) );
  397. }
  398. var material, materialName, key;
  399. var materialNames = meshPayload.materials.materialNames;
  400. var createMultiMaterial = meshPayload.materials.multiMaterial;
  401. var multiMaterials = [];
  402. for ( key in materialNames ) {
  403. materialName = materialNames[ key ];
  404. material = this.materials[ materialName ];
  405. if ( createMultiMaterial ) multiMaterials.push( material );
  406. }
  407. if ( createMultiMaterial ) {
  408. material = multiMaterials;
  409. var materialGroups = meshPayload.materials.materialGroups;
  410. var materialGroup;
  411. for ( key in materialGroups ) {
  412. materialGroup = materialGroups[ key ];
  413. bufferGeometry.addGroup( materialGroup.start, materialGroup.count, materialGroup.index );
  414. }
  415. }
  416. var meshes = [];
  417. var mesh;
  418. var callbackOnMeshAlter = this.callbacks.onMeshAlter;
  419. var callbackOnMeshAlterResult;
  420. var useOrgMesh = true;
  421. var geometryType = this.validator.verifyInput( meshPayload.geometryType, 0 );
  422. if ( this.validator.isValid( callbackOnMeshAlter ) ) {
  423. callbackOnMeshAlterResult = callbackOnMeshAlter(
  424. {
  425. detail: {
  426. meshName: meshName,
  427. bufferGeometry: bufferGeometry,
  428. material: material,
  429. geometryType: geometryType
  430. }
  431. }
  432. );
  433. if ( this.validator.isValid( callbackOnMeshAlterResult ) ) {
  434. if ( callbackOnMeshAlterResult.isDisregardMesh() ) {
  435. useOrgMesh = false;
  436. } else if ( callbackOnMeshAlterResult.providesAlteredMeshes() ) {
  437. for ( var i in callbackOnMeshAlterResult.meshes ) {
  438. meshes.push( callbackOnMeshAlterResult.meshes[ i ] );
  439. }
  440. useOrgMesh = false;
  441. }
  442. }
  443. }
  444. if ( useOrgMesh ) {
  445. if ( meshPayload.computeBoundingSphere ) bufferGeometry.computeBoundingSphere();
  446. if ( geometryType === 0 ) {
  447. mesh = new THREE.Mesh( bufferGeometry, material );
  448. } else if ( geometryType === 1) {
  449. mesh = new THREE.LineSegments( bufferGeometry, material );
  450. } else {
  451. mesh = new THREE.Points( bufferGeometry, material );
  452. }
  453. mesh.name = meshName;
  454. meshes.push( mesh );
  455. }
  456. var progressMessage;
  457. if ( this.validator.isValid( meshes ) && meshes.length > 0 ) {
  458. var meshNames = [];
  459. for ( var i in meshes ) {
  460. mesh = meshes[ i ];
  461. meshNames[ i ] = mesh.name;
  462. }
  463. progressMessage = 'Adding mesh(es) (' + meshNames.length + ': ' + meshNames + ') from input mesh: ' + meshName;
  464. progressMessage += ' (' + ( meshPayload.progress.numericalValue * 100 ).toFixed( 2 ) + '%)';
  465. } else {
  466. progressMessage = 'Not adding mesh: ' + meshName;
  467. progressMessage += ' (' + ( meshPayload.progress.numericalValue * 100 ).toFixed( 2 ) + '%)';
  468. }
  469. var callbackOnProgress = this.callbacks.onProgress;
  470. if ( this.validator.isValid( callbackOnProgress ) ) {
  471. var event = new CustomEvent( 'MeshBuilderEvent', {
  472. detail: {
  473. type: 'progress',
  474. modelName: meshPayload.params.meshName,
  475. text: progressMessage,
  476. numericalValue: meshPayload.progress.numericalValue
  477. }
  478. } );
  479. callbackOnProgress( event );
  480. }
  481. return meshes;
  482. },
  483. /**
  484. * Updates the materials with contained material objects (sync) or from alteration instructions (async).
  485. *
  486. * @param {Object} materialPayload Material update instructions
  487. */
  488. updateMaterials: function ( materialPayload ) {
  489. var material, materialName;
  490. var materialCloneInstructions = materialPayload.materials.materialCloneInstructions;
  491. if ( this.validator.isValid( materialCloneInstructions ) ) {
  492. var materialNameOrg = materialCloneInstructions.materialNameOrg;
  493. var materialOrg = this.materials[ materialNameOrg ];
  494. if ( this.validator.isValid( materialNameOrg ) ) {
  495. material = materialOrg.clone();
  496. materialName = materialCloneInstructions.materialName;
  497. material.name = materialName;
  498. var materialProperties = materialCloneInstructions.materialProperties;
  499. for ( var key in materialProperties ) {
  500. if ( material.hasOwnProperty( key ) && materialProperties.hasOwnProperty( key ) ) material[ key ] = materialProperties[ key ];
  501. }
  502. this.materials[ materialName ] = material;
  503. } else {
  504. console.warn( 'Requested material "' + materialNameOrg + '" is not available!' );
  505. }
  506. }
  507. var materials = materialPayload.materials.serializedMaterials;
  508. if ( this.validator.isValid( materials ) && Object.keys( materials ).length > 0 ) {
  509. var loader = new THREE.MaterialLoader();
  510. var materialJson;
  511. for ( materialName in materials ) {
  512. materialJson = materials[ materialName ];
  513. if ( this.validator.isValid( materialJson ) ) {
  514. material = loader.parse( materialJson );
  515. if ( this.logging.enabled ) console.info( 'De-serialized material with name "' + materialName + '" will be added.' );
  516. this.materials[ materialName ] = material;
  517. }
  518. }
  519. }
  520. materials = materialPayload.materials.runtimeMaterials;
  521. if ( this.validator.isValid( materials ) && Object.keys( materials ).length > 0 ) {
  522. for ( materialName in materials ) {
  523. material = materials[ materialName ];
  524. if ( this.logging.enabled ) console.info( 'Material with name "' + materialName + '" will be added.' );
  525. this.materials[ materialName ] = material;
  526. }
  527. }
  528. },
  529. /**
  530. * Returns the mapping object of material name and corresponding jsonified material.
  531. *
  532. * @returns {Object} Map of Materials in JSON representation
  533. */
  534. getMaterialsJSON: function () {
  535. var materialsJSON = {};
  536. var material;
  537. for ( var materialName in this.materials ) {
  538. material = this.materials[ materialName ];
  539. materialsJSON[ materialName ] = material.toJSON();
  540. }
  541. return materialsJSON;
  542. },
  543. /**
  544. * Returns the mapping object of material name and corresponding material.
  545. *
  546. * @returns {Object} Map of {@link THREE.Material}
  547. */
  548. getMaterials: function () {
  549. return this.materials;
  550. }
  551. };
  552. /**
  553. * This class provides means to transform existing parser code into a web worker. It defines a simple communication protocol
  554. * which allows to configure the worker and receive raw mesh data during execution.
  555. * @class
  556. */
  557. THREE.LoaderSupport.WorkerSupport = function () {
  558. console.info( 'Using THREE.LoaderSupport.WorkerSupport version: ' + THREE.LoaderSupport.WorkerSupport.WORKER_SUPPORT_VERSION );
  559. this.logging = {
  560. enabled: true,
  561. debug: false
  562. };
  563. //Choose implementation of worker based on environment
  564. this.loaderWorker = typeof window !== "undefined" ? new THREE.LoaderSupport.WorkerSupport.LoaderWorker() : new THREE.LoaderSupport.WorkerSupport.NodeLoaderWorker();
  565. };
  566. THREE.LoaderSupport.WorkerSupport.WORKER_SUPPORT_VERSION = '2.3.0';
  567. THREE.LoaderSupport.WorkerSupport.prototype = {
  568. constructor: THREE.LoaderSupport.WorkerSupport,
  569. /**
  570. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  571. *
  572. * @param {boolean} enabled True or false.
  573. * @param {boolean} debug True or false.
  574. */
  575. setLogging: function ( enabled, debug ) {
  576. this.logging.enabled = enabled === true;
  577. this.logging.debug = debug === true;
  578. this.loaderWorker.setLogging( this.logging.enabled, this.logging.debug );
  579. },
  580. /**
  581. * Forces all ArrayBuffers to be transferred to worker to be copied.
  582. *
  583. * @param {boolean} forceWorkerDataCopy True or false.
  584. */
  585. setForceWorkerDataCopy: function ( forceWorkerDataCopy ) {
  586. this.loaderWorker.setForceCopy( forceWorkerDataCopy );
  587. },
  588. /**
  589. * Validate the status of worker code and the derived worker.
  590. *
  591. * @param {Function} functionCodeBuilder Function that is invoked with funcBuildObject and funcBuildSingleton that allows stringification of objects and singletons.
  592. * @param {String} parserName Name of the Parser object
  593. * @param {String[]} libLocations URL of libraries that shall be added to worker code relative to libPath
  594. * @param {String} libPath Base path used for loading libraries
  595. * @param {THREE.LoaderSupport.WorkerRunnerRefImpl} runnerImpl The default worker parser wrapper implementation (communication and execution). An extended class could be passed here.
  596. */
  597. validate: function ( functionCodeBuilder, parserName, libLocations, libPath, runnerImpl ) {
  598. if ( THREE.LoaderSupport.Validator.isValid( this.loaderWorker.worker ) ) return;
  599. if ( this.logging.enabled ) {
  600. console.info( 'WorkerSupport: Building worker code...' );
  601. console.time( 'buildWebWorkerCode' );
  602. }
  603. if ( THREE.LoaderSupport.Validator.isValid( runnerImpl ) ) {
  604. if ( this.logging.enabled ) console.info( 'WorkerSupport: Using "' + runnerImpl.runnerName + '" as Runner class for worker.' );
  605. // Browser implementation
  606. } else if ( typeof window !== "undefined" ) {
  607. runnerImpl = THREE.LoaderSupport.WorkerRunnerRefImpl;
  608. if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.WorkerRunnerRefImpl" as Runner class for worker.' );
  609. // NodeJS implementation
  610. } else {
  611. runnerImpl = THREE.LoaderSupport.NodeWorkerRunnerRefImpl;
  612. if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.NodeWorkerRunnerRefImpl" as Runner class for worker.' );
  613. }
  614. var userWorkerCode = functionCodeBuilder( THREE.LoaderSupport.WorkerSupport.CodeSerializer );
  615. userWorkerCode += 'var Parser = '+ parserName + ';\n\n';
  616. userWorkerCode += THREE.LoaderSupport.WorkerSupport.CodeSerializer.serializeClass( runnerImpl.runnerName, runnerImpl );
  617. userWorkerCode += 'new ' + runnerImpl.runnerName + '();\n\n';
  618. var scope = this;
  619. if ( THREE.LoaderSupport.Validator.isValid( libLocations ) && libLocations.length > 0 ) {
  620. var libsContent = '';
  621. var loadAllLibraries = function ( path, locations ) {
  622. if ( locations.length === 0 ) {
  623. scope.loaderWorker.initWorker( libsContent + userWorkerCode, runnerImpl.runnerName );
  624. if ( scope.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' );
  625. } else {
  626. var loadedLib = function ( contentAsString ) {
  627. libsContent += contentAsString;
  628. loadAllLibraries( path, locations );
  629. };
  630. var fileLoader = new THREE.FileLoader();
  631. fileLoader.setPath( path );
  632. fileLoader.setResponseType( 'text' );
  633. fileLoader.load( locations[ 0 ], loadedLib );
  634. locations.shift();
  635. }
  636. };
  637. loadAllLibraries( libPath, libLocations );
  638. } else {
  639. this.loaderWorker.initWorker( userWorkerCode, runnerImpl.runnerName );
  640. if ( this.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' );
  641. }
  642. },
  643. /**
  644. * Specify functions that should be build when new raw mesh data becomes available and when the parser is finished.
  645. *
  646. * @param {Function} meshBuilder The mesh builder function. Default is {@link THREE.LoaderSupport.MeshBuilder}.
  647. * @param {Function} onLoad The function that is called when parsing is complete.
  648. */
  649. setCallbacks: function ( meshBuilder, onLoad ) {
  650. this.loaderWorker.setCallbacks( meshBuilder, onLoad );
  651. },
  652. /**
  653. * Runs the parser with the provided configuration.
  654. *
  655. * @param {Object} payload Raw mesh description (buffers, params, materials) used to build one to many meshes.
  656. */
  657. run: function ( payload ) {
  658. this.loaderWorker.run( payload );
  659. },
  660. /**
  661. * Request termination of worker once parser is finished.
  662. *
  663. * @param {boolean} terminateRequested True or false.
  664. */
  665. setTerminateRequested: function ( terminateRequested ) {
  666. this.loaderWorker.setTerminateRequested( terminateRequested );
  667. }
  668. };
  669. THREE.LoaderSupport.WorkerSupport.LoaderWorker = function () {
  670. this._reset();
  671. };
  672. THREE.LoaderSupport.WorkerSupport.LoaderWorker.prototype = {
  673. constructor: THREE.LoaderSupport.WorkerSupport.LoaderWorker,
  674. _reset: function () {
  675. this.logging = {
  676. enabled: true,
  677. debug: false
  678. };
  679. this.worker = null;
  680. this.runnerImplName = null;
  681. this.callbacks = {
  682. meshBuilder: null,
  683. onLoad: null
  684. };
  685. this.terminateRequested = false;
  686. this.queuedMessage = null;
  687. this.started = false;
  688. this.forceCopy = false;
  689. },
  690. /**
  691. * Check support for Workers and other necessary features returning
  692. * reason if the environment is unsupported
  693. *
  694. * @returns {string|undefined} Returns undefined if supported, or
  695. * string with error if not supported
  696. */
  697. checkSupport: function() {
  698. if ( window.Worker === undefined ) return "This browser does not support web workers!";
  699. if ( window.Blob === undefined ) return "This browser does not support Blob!";
  700. if ( typeof window.URL.createObjectURL !== 'function' ) return "This browser does not support Object creation from URL!";
  701. },
  702. setLogging: function ( enabled, debug ) {
  703. this.logging.enabled = enabled === true;
  704. this.logging.debug = debug === true;
  705. },
  706. setForceCopy: function ( forceCopy ) {
  707. this.forceCopy = forceCopy === true;
  708. },
  709. initWorker: function ( code, runnerImplName ) {
  710. var supportError = this.checkSupport();
  711. if ( supportError ) {
  712. throw supportError;
  713. }
  714. this.runnerImplName = runnerImplName;
  715. var blob = new Blob( [ code ], { type: 'application/javascript' } );
  716. this.worker = new Worker( window.URL.createObjectURL( blob ) );
  717. this.worker.onmessage = this._receiveWorkerMessage;
  718. // set referemce to this, then processing in worker scope within "_receiveWorkerMessage" can access members
  719. this.worker.runtimeRef = this;
  720. // process stored queuedMessage
  721. this._postMessage();
  722. },
  723. /**
  724. * Executed in worker scope
  725. */
  726. _receiveWorkerMessage: function ( e ) {
  727. var payload = e.data;
  728. switch ( payload.cmd ) {
  729. case 'meshData':
  730. case 'materialData':
  731. case 'imageData':
  732. this.runtimeRef.callbacks.meshBuilder( payload );
  733. break;
  734. case 'complete':
  735. this.runtimeRef.queuedMessage = null;
  736. this.started = false;
  737. this.runtimeRef.callbacks.onLoad( payload.msg );
  738. if ( this.runtimeRef.terminateRequested ) {
  739. if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run is complete. Terminating application on request!' );
  740. this.runtimeRef._terminate();
  741. }
  742. break;
  743. case 'error':
  744. console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Reported error: ' + payload.msg );
  745. this.runtimeRef.queuedMessage = null;
  746. this.started = false;
  747. this.runtimeRef.callbacks.onLoad( payload.msg );
  748. if ( this.runtimeRef.terminateRequested ) {
  749. if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run reported error. Terminating application on request!' );
  750. this.runtimeRef._terminate();
  751. }
  752. break;
  753. default:
  754. console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Received unknown command: ' + payload.cmd );
  755. break;
  756. }
  757. },
  758. setCallbacks: function ( meshBuilder, onLoad ) {
  759. this.callbacks.meshBuilder = THREE.LoaderSupport.Validator.verifyInput( meshBuilder, this.callbacks.meshBuilder );
  760. this.callbacks.onLoad = THREE.LoaderSupport.Validator.verifyInput( onLoad, this.callbacks.onLoad );
  761. },
  762. run: function( payload ) {
  763. if ( THREE.LoaderSupport.Validator.isValid( this.queuedMessage ) ) {
  764. console.warn( 'Already processing message. Rejecting new run instruction' );
  765. return;
  766. } else {
  767. this.queuedMessage = payload;
  768. this.started = true;
  769. }
  770. if ( ! THREE.LoaderSupport.Validator.isValid( this.callbacks.meshBuilder ) ) throw 'Unable to run as no "MeshBuilder" callback is set.';
  771. if ( ! THREE.LoaderSupport.Validator.isValid( this.callbacks.onLoad ) ) throw 'Unable to run as no "onLoad" callback is set.';
  772. if ( payload.cmd !== 'run' ) payload.cmd = 'run';
  773. if ( THREE.LoaderSupport.Validator.isValid( payload.logging ) ) {
  774. payload.logging.enabled = payload.logging.enabled === true;
  775. payload.logging.debug = payload.logging.debug === true;
  776. } else {
  777. payload.logging = {
  778. enabled: true,
  779. debug: false
  780. }
  781. }
  782. this._postMessage();
  783. },
  784. _postMessage: function () {
  785. if ( THREE.LoaderSupport.Validator.isValid( this.queuedMessage ) && THREE.LoaderSupport.Validator.isValid( this.worker ) ) {
  786. if ( this.queuedMessage.data.input instanceof ArrayBuffer ) {
  787. var content;
  788. if ( this.forceCopy ) {
  789. content = this.queuedMessage.data.input.slice( 0 );
  790. } else {
  791. content = this.queuedMessage.data.input;
  792. }
  793. this.worker.postMessage( this.queuedMessage, [ content ] );
  794. } else {
  795. this.worker.postMessage( this.queuedMessage );
  796. }
  797. }
  798. },
  799. setTerminateRequested: function ( terminateRequested ) {
  800. this.terminateRequested = terminateRequested === true;
  801. if ( this.terminateRequested && THREE.LoaderSupport.Validator.isValid( this.worker ) && ! THREE.LoaderSupport.Validator.isValid( this.queuedMessage ) && this.started ) {
  802. if ( this.logging.enabled ) console.info( 'Worker is terminated immediately as it is not running!' );
  803. this._terminate();
  804. }
  805. },
  806. _terminate: function () {
  807. this.worker.terminate();
  808. this._reset();
  809. }
  810. };
  811. THREE.LoaderSupport.WorkerSupport.CodeSerializer = {
  812. /**
  813. *
  814. * @param fullName
  815. * @param object
  816. * @returns {string}
  817. */
  818. serializeObject: function ( fullName, object ) {
  819. var objectString = fullName + ' = {\n\n';
  820. var part;
  821. for ( var name in object ) {
  822. part = object[ name ];
  823. if ( typeof( part ) === 'string' || part instanceof String ) {
  824. part = part.replace( '\n', '\\n' );
  825. part = part.replace( '\r', '\\r' );
  826. objectString += '\t' + name + ': "' + part + '",\n';
  827. } else if ( part instanceof Array ) {
  828. objectString += '\t' + name + ': [' + part + '],\n';
  829. } else if ( typeof part === 'object' ) {
  830. // TODO: Short-cut for now. Recursion required?
  831. objectString += '\t' + name + ': {},\n';
  832. } else {
  833. objectString += '\t' + name + ': ' + part + ',\n';
  834. }
  835. }
  836. objectString += '}\n\n';
  837. return objectString;
  838. },
  839. /**
  840. *
  841. * @param fullName
  842. * @param object
  843. * @param basePrototypeName
  844. * @param ignoreFunctions
  845. * @returns {string}
  846. */
  847. serializeClass: function ( fullName, object, constructorName, basePrototypeName, ignoreFunctions, includeFunctions, overrideFunctions ) {
  848. var valueString, objectPart, constructorString, i, funcOverride;
  849. var prototypeFunctions = [];
  850. var objectProperties = [];
  851. var objectFunctions = [];
  852. var isExtended = ( basePrototypeName !== null && basePrototypeName !== undefined );
  853. if ( ! Array.isArray( ignoreFunctions ) ) ignoreFunctions = [];
  854. if ( ! Array.isArray( includeFunctions ) ) includeFunctions = null;
  855. if ( ! Array.isArray( overrideFunctions ) ) overrideFunctions = [];
  856. for ( var name in object.prototype ) {
  857. objectPart = object.prototype[ name ];
  858. valueString = objectPart.toString();
  859. if ( name === 'constructor' ) {
  860. constructorString = fullName + ' = ' + valueString + ';\n\n';
  861. } else if ( typeof objectPart === 'function' ) {
  862. if ( ignoreFunctions.indexOf( name ) < 0 && ( includeFunctions === null || includeFunctions.indexOf( name ) >= 0 ) ) {
  863. funcOverride = overrideFunctions[ name ];
  864. if ( funcOverride && funcOverride.fullName === fullName + '.prototype.' + name ) {
  865. valueString = funcOverride.code;
  866. }
  867. if ( isExtended ) {
  868. prototypeFunctions.push( fullName + '.prototype.' + name + ' = ' + valueString + ';\n\n' );
  869. } else {
  870. prototypeFunctions.push( '\t' + name + ': ' + valueString + ',\n\n' );
  871. }
  872. }
  873. }
  874. }
  875. for ( var name in object ) {
  876. objectPart = object[ name ];
  877. if ( typeof objectPart === 'function' ) {
  878. if ( ignoreFunctions.indexOf( name ) < 0 && ( includeFunctions === null || includeFunctions.indexOf( name ) >= 0 ) ) {
  879. funcOverride = overrideFunctions[ name ];
  880. if ( funcOverride && funcOverride.fullName === fullName + '.' + name ) {
  881. valueString = funcOverride.code;
  882. } else {
  883. valueString = objectPart.toString();
  884. }
  885. objectFunctions.push( fullName + '.' + name + ' = ' + valueString + ';\n\n' );
  886. }
  887. } else {
  888. if ( typeof( objectPart ) === 'string' || objectPart instanceof String) {
  889. valueString = '\"' + objectPart.toString() + '\"';
  890. } else if ( typeof objectPart === 'object' ) {
  891. // TODO: Short-cut for now. Recursion required?
  892. valueString = "{}";
  893. } else {
  894. valueString = objectPart;
  895. }
  896. objectProperties.push( fullName + '.' + name + ' = ' + valueString + ';\n' );
  897. }
  898. }
  899. if ( ( constructorString === undefined || constructorString === null ) && typeof object.prototype.constructor === 'function' ) {
  900. constructorString = fullName + ' = ' + object.prototype.constructor.toString().replace( constructorName, '' );
  901. }
  902. var objectString = constructorString + '\n\n';
  903. if ( isExtended ) {
  904. objectString += fullName + '.prototype = Object.create( ' + basePrototypeName + '.prototype );\n';
  905. }
  906. objectString += fullName + '.prototype.constructor = ' + fullName + ';\n';
  907. objectString += '\n\n';
  908. for ( i = 0; i < objectProperties.length; i ++ ) objectString += objectProperties[ i ];
  909. objectString += '\n\n';
  910. for ( i = 0; i < objectFunctions.length; i ++ ) objectString += objectFunctions[ i ];
  911. objectString += '\n\n';
  912. if ( isExtended ) {
  913. for ( i = 0; i < prototypeFunctions.length; i ++ ) objectString += prototypeFunctions[ i ];
  914. } else {
  915. objectString += fullName + '.prototype = {\n\n';
  916. for ( i = 0; i < prototypeFunctions.length; i ++ ) objectString += prototypeFunctions[ i ];
  917. objectString += '\n};';
  918. }
  919. objectString += '\n\n';
  920. return objectString;
  921. },
  922. };
  923. /**
  924. * Default implementation of the WorkerRunner responsible for creation and configuration of the parser within the worker.
  925. *
  926. * @class
  927. */
  928. THREE.LoaderSupport.WorkerRunnerRefImpl = function () {
  929. var scopedRunner = function( event ) {
  930. this.processMessage( event.data );
  931. };
  932. this.getParentScope().addEventListener( 'message', scopedRunner.bind( this ) );
  933. };
  934. THREE.LoaderSupport.WorkerRunnerRefImpl.runnerName = 'THREE.LoaderSupport.WorkerRunnerRefImpl';
  935. THREE.LoaderSupport.WorkerRunnerRefImpl.prototype = {
  936. constructor: THREE.LoaderSupport.WorkerRunnerRefImpl,
  937. /**
  938. * Returns the parent scope that this worker was spawned in.
  939. *
  940. * @returns {WorkerGlobalScope|Object} Returns a references
  941. * to the parent global scope or compatible type.
  942. */
  943. getParentScope: function () {
  944. return self;
  945. },
  946. /**
  947. * Applies values from parameter object via set functions or via direct assignment.
  948. *
  949. * @param {Object} parser The parser instance
  950. * @param {Object} params The parameter object
  951. */
  952. applyProperties: function ( parser, params ) {
  953. var property, funcName, values;
  954. for ( property in params ) {
  955. funcName = 'set' + property.substring( 0, 1 ).toLocaleUpperCase() + property.substring( 1 );
  956. values = params[ property ];
  957. if ( typeof parser[ funcName ] === 'function' ) {
  958. parser[ funcName ]( values );
  959. } else if ( parser.hasOwnProperty( property ) ) {
  960. parser[ property ] = values;
  961. }
  962. }
  963. },
  964. /**
  965. * Configures the Parser implementation according the supplied configuration object.
  966. *
  967. * @param {Object} payload Raw mesh description (buffers, params, materials) used to build one to many meshes.
  968. */
  969. processMessage: function ( payload ) {
  970. if ( payload.cmd === 'run' ) {
  971. var self = this.getParentScope();
  972. var callbacks = {
  973. callbackMeshBuilder: function ( payload ) {
  974. self.postMessage( payload );
  975. },
  976. callbackProgress: function ( text ) {
  977. if ( payload.logging.enabled && payload.logging.debug ) console.debug( 'WorkerRunner: progress: ' + text );
  978. }
  979. };
  980. // Parser is expected to be named as such
  981. var parser = new Parser();
  982. if ( typeof parser[ 'setLogging' ] === 'function' ) parser.setLogging( payload.logging.enabled, payload.logging.debug );
  983. this.applyProperties( parser, payload.params );
  984. this.applyProperties( parser, payload.materials );
  985. this.applyProperties( parser, callbacks );
  986. parser.workerScope = self;
  987. parser.parse( payload.data.input, payload.data.options );
  988. if ( payload.logging.enabled ) console.log( 'WorkerRunner: Run complete!' );
  989. callbacks.callbackMeshBuilder( {
  990. cmd: 'complete',
  991. msg: 'WorkerRunner completed run.'
  992. } );
  993. } else {
  994. console.error( 'WorkerRunner: Received unknown command: ' + payload.cmd );
  995. }
  996. }
  997. };
  998. /**
  999. * This class provides the NodeJS implementation of the WorkerRunnerRefImpl
  1000. * @class
  1001. * @extends THREE.LoaderSupport.WorkerRunnerRefImpl
  1002. */
  1003. THREE.LoaderSupport.NodeWorkerRunnerRefImpl = function () {
  1004. this.runnerName = 'THREE.LoaderSupport.NodeWorkerRunnerRefImpl';
  1005. // No call to super because super class only binds to processMessage
  1006. // In NodeJS, there is no addEventListener so use onmessage.
  1007. // Also, the message object can be passed directly to
  1008. // processMessage() as it isn't an `Event`, but a plain object
  1009. // with the data
  1010. this.getParentScope().onmessage = this.processMessage.bind( this );
  1011. };
  1012. THREE.LoaderSupport.NodeWorkerRunnerRefImpl.prototype = Object.create( THREE.LoaderSupport.WorkerRunnerRefImpl.prototype );
  1013. THREE.LoaderSupport.NodeWorkerRunnerRefImpl.prototype.constructor = THREE.LoaderSupport.NodeWorkerRunnerRefImpl;
  1014. THREE.LoaderSupport.NodeWorkerRunnerRefImpl.runnerName = 'THREE.LoaderSupport.NodeWorkerRunnerRefImpl';
  1015. THREE.LoaderSupport.NodeWorkerRunnerRefImpl.prototype = {
  1016. getParentScope: function(){
  1017. // Work around webpack builds failing with NodeJS requires
  1018. // (placing it outside this function will fail because
  1019. // this class is passed to the worker as a string!)
  1020. var _require = eval( 'require' );
  1021. return _require( 'worker_threads' ).parentPort;
  1022. }
  1023. };
  1024. /**
  1025. * This class provides the NodeJS implementation of LoaderWorker
  1026. * @class
  1027. * @extends LoaderWorker
  1028. */
  1029. THREE.LoaderSupport.WorkerSupport.NodeLoaderWorker = function (){
  1030. THREE.LoaderSupport.WorkerSupport.LoaderWorker.call( this );
  1031. };
  1032. THREE.LoaderSupport.WorkerSupport.NodeLoaderWorker.prototype = Object.create( THREE.LoaderSupport.WorkerSupport.LoaderWorker.prototype );
  1033. THREE.LoaderSupport.WorkerSupport.NodeLoaderWorker.prototype.constructor = THREE.LoaderSupport.WorkerSupport.NodeLoaderWorker;
  1034. /**
  1035. * @inheritdoc
  1036. */
  1037. THREE.LoaderSupport.WorkerSupport.NodeLoaderWorker.checkSupport = function() {
  1038. try {
  1039. // Work around webpack builds failing with NodeJS requires
  1040. var _require = eval( 'require' );
  1041. _require.resolve( 'worker_threads' );
  1042. }
  1043. catch(e) {
  1044. return 'This version of Node does not support web workers!';
  1045. }
  1046. };
  1047. /**
  1048. * @inheritdoc
  1049. */
  1050. THREE.LoaderSupport.WorkerSupport.NodeLoaderWorker.prototype.initWorker = function ( code, runnerImplName ) {
  1051. var supportError = this.checkSupport();
  1052. if( supportError ) {
  1053. throw supportError;
  1054. }
  1055. this.runnerImplName = runnerImplName;
  1056. // Work around webpack builds failing with NodeJS requires
  1057. var _require = eval( 'require' );
  1058. var Worker = _require( 'worker_threads' ).Worker;
  1059. this.worker = new Worker( code, { eval: true } );
  1060. this.worker.onmessage = this._receiveWorkerMessage;
  1061. // set referemce to this, then processing in worker scope within "_receiveWorkerMessage" can access members
  1062. this.worker.runtimeRef = this;
  1063. // process stored queuedMessage
  1064. this._postMessage();
  1065. };
  1066. /**
  1067. * Orchestrate loading of multiple OBJ files/data from an instruction queue with a configurable amount of workers (1-16).
  1068. * Workflow:
  1069. * prepareWorkers
  1070. * enqueueForRun
  1071. * processQueue
  1072. * tearDown (to force stop)
  1073. *
  1074. * @class
  1075. *
  1076. * @param {string} classDef Class definition to be used for construction
  1077. */
  1078. THREE.LoaderSupport.WorkerDirector = function ( classDef ) {
  1079. console.info( 'Using THREE.LoaderSupport.WorkerDirector version: ' + THREE.LoaderSupport.WorkerDirector.LOADER_WORKER_DIRECTOR_VERSION );
  1080. this.logging = {
  1081. enabled: true,
  1082. debug: false
  1083. };
  1084. this.maxQueueSize = THREE.LoaderSupport.WorkerDirector.MAX_QUEUE_SIZE ;
  1085. this.maxWebWorkers = THREE.LoaderSupport.WorkerDirector.MAX_WEB_WORKER;
  1086. this.crossOrigin = null;
  1087. if ( ! THREE.LoaderSupport.Validator.isValid( classDef ) ) throw 'Provided invalid classDef: ' + classDef;
  1088. this.workerDescription = {
  1089. classDef: classDef,
  1090. globalCallbacks: {},
  1091. workerSupports: {},
  1092. forceWorkerDataCopy: true
  1093. };
  1094. this.objectsCompleted = 0;
  1095. this.instructionQueue = [];
  1096. this.instructionQueuePointer = 0;
  1097. this.callbackOnFinishedProcessing = null;
  1098. }
  1099. THREE.LoaderSupport.WorkerDirector.LOADER_WORKER_DIRECTOR_VERSION = '2.3.0';
  1100. THREE.LoaderSupport.WorkerDirector.MAX_WEB_WORKER = 16;
  1101. THREE.LoaderSupport.WorkerDirector.MAX_QUEUE_SIZE = 2048;
  1102. THREE.LoaderSupport.WorkerDirector.prototype = {
  1103. constructor: THREE.LoaderSupport.WorkerDirector,
  1104. /**
  1105. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  1106. *
  1107. * @param {boolean} enabled True or false.
  1108. * @param {boolean} debug True or false.
  1109. */
  1110. setLogging: function ( enabled, debug ) {
  1111. this.logging.enabled = enabled === true;
  1112. this.logging.debug = debug === true;
  1113. },
  1114. /**
  1115. * Returns the maximum length of the instruction queue.
  1116. *
  1117. * @returns {number}
  1118. */
  1119. getMaxQueueSize: function () {
  1120. return this.maxQueueSize;
  1121. },
  1122. /**
  1123. * Returns the maximum number of workers.
  1124. *
  1125. * @returns {number}
  1126. */
  1127. getMaxWebWorkers: function () {
  1128. return this.maxWebWorkers;
  1129. },
  1130. /**
  1131. * Sets the CORS string to be used.
  1132. *
  1133. * @param {string} crossOrigin CORS value
  1134. */
  1135. setCrossOrigin: function ( crossOrigin ) {
  1136. this.crossOrigin = crossOrigin;
  1137. },
  1138. /**
  1139. * Forces all ArrayBuffers to be transferred to worker to be copied.
  1140. *
  1141. * @param {boolean} forceWorkerDataCopy True or false.
  1142. */
  1143. setForceWorkerDataCopy: function ( forceWorkerDataCopy ) {
  1144. this.workerDescription.forceWorkerDataCopy = forceWorkerDataCopy === true;
  1145. },
  1146. /**
  1147. * Create or destroy workers according limits. Set the name and register callbacks for dynamically created web workers.
  1148. *
  1149. * @param {THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks} globalCallbacks Register global callbacks used by all web workers
  1150. * @param {number} maxQueueSize Set the maximum size of the instruction queue (1-1024)
  1151. * @param {number} maxWebWorkers Set the maximum amount of workers (1-16)
  1152. */
  1153. prepareWorkers: function ( globalCallbacks, maxQueueSize, maxWebWorkers ) {
  1154. if ( THREE.LoaderSupport.Validator.isValid( globalCallbacks ) ) this.workerDescription.globalCallbacks = globalCallbacks;
  1155. this.maxQueueSize = Math.min( maxQueueSize, THREE.LoaderSupport.WorkerDirector.MAX_QUEUE_SIZE );
  1156. this.maxWebWorkers = Math.min( maxWebWorkers, THREE.LoaderSupport.WorkerDirector.MAX_WEB_WORKER );
  1157. this.maxWebWorkers = Math.min( this.maxWebWorkers, this.maxQueueSize );
  1158. this.objectsCompleted = 0;
  1159. this.instructionQueue = [];
  1160. this.instructionQueuePointer = 0;
  1161. for ( var instanceNo = 0; instanceNo < this.maxWebWorkers; instanceNo++ ) {
  1162. var workerSupport = new THREE.LoaderSupport.WorkerSupport();
  1163. workerSupport.setLogging( this.logging.enabled, this.logging.debug );
  1164. workerSupport.setForceWorkerDataCopy( this.workerDescription.forceWorkerDataCopy );
  1165. this.workerDescription.workerSupports[ instanceNo ] = {
  1166. instanceNo: instanceNo,
  1167. inUse: false,
  1168. terminateRequested: false,
  1169. workerSupport: workerSupport,
  1170. loader: null
  1171. };
  1172. }
  1173. },
  1174. /**
  1175. * Store run instructions in internal instructionQueue.
  1176. *
  1177. * @param {THREE.LoaderSupport.PrepData} prepData
  1178. */
  1179. enqueueForRun: function ( prepData ) {
  1180. if ( this.instructionQueue.length < this.maxQueueSize ) {
  1181. this.instructionQueue.push( prepData );
  1182. }
  1183. },
  1184. /**
  1185. * Returns if any workers are running.
  1186. *
  1187. * @returns {boolean}
  1188. */
  1189. isRunning: function () {
  1190. var wsKeys = Object.keys( this.workerDescription.workerSupports );
  1191. return ( ( this.instructionQueue.length > 0 && this.instructionQueuePointer < this.instructionQueue.length ) || wsKeys.length > 0 );
  1192. },
  1193. /**
  1194. * Process the instructionQueue until it is depleted.
  1195. */
  1196. processQueue: function () {
  1197. var prepData, supportDesc;
  1198. for ( var instanceNo in this.workerDescription.workerSupports ) {
  1199. supportDesc = this.workerDescription.workerSupports[ instanceNo ];
  1200. if ( ! supportDesc.inUse ) {
  1201. if ( this.instructionQueuePointer < this.instructionQueue.length ) {
  1202. prepData = this.instructionQueue[ this.instructionQueuePointer ];
  1203. this._kickWorkerRun( prepData, supportDesc );
  1204. this.instructionQueuePointer++;
  1205. } else {
  1206. this._deregister( supportDesc );
  1207. }
  1208. }
  1209. }
  1210. if ( ! this.isRunning() && this.callbackOnFinishedProcessing !== null ) {
  1211. this.callbackOnFinishedProcessing();
  1212. this.callbackOnFinishedProcessing = null;
  1213. }
  1214. },
  1215. _kickWorkerRun: function( prepData, supportDesc ) {
  1216. supportDesc.inUse = true;
  1217. supportDesc.workerSupport.setTerminateRequested( supportDesc.terminateRequested );
  1218. if ( this.logging.enabled ) console.info( '\nAssigning next item from queue to worker (queue length: ' + this.instructionQueue.length + ')\n\n' );
  1219. var validator = THREE.LoaderSupport.Validator;
  1220. var scope = this;
  1221. var prepDataCallbacks = prepData.getCallbacks();
  1222. var globalCallbacks = this.workerDescription.globalCallbacks;
  1223. var wrapperOnLoad = function ( event ) {
  1224. if ( validator.isValid( globalCallbacks.onLoad ) ) globalCallbacks.onLoad( event );
  1225. if ( validator.isValid( prepDataCallbacks.onLoad ) ) prepDataCallbacks.onLoad( event );
  1226. scope.objectsCompleted++;
  1227. supportDesc.inUse = false;
  1228. scope.processQueue();
  1229. };
  1230. var wrapperOnProgress = function ( event ) {
  1231. if ( validator.isValid( globalCallbacks.onProgress ) ) globalCallbacks.onProgress( event );
  1232. if ( validator.isValid( prepDataCallbacks.onProgress ) ) prepDataCallbacks.onProgress( event );
  1233. };
  1234. var wrapperOnMeshAlter = function ( event, override ) {
  1235. if ( validator.isValid( globalCallbacks.onMeshAlter ) ) override = globalCallbacks.onMeshAlter( event, override );
  1236. if ( validator.isValid( prepDataCallbacks.onMeshAlter ) ) override = globalCallbacks.onMeshAlter( event, override );
  1237. return override;
  1238. };
  1239. var wrapperOnLoadMaterials = function ( materials ) {
  1240. if ( validator.isValid( globalCallbacks.onLoadMaterials ) ) materials = globalCallbacks.onLoadMaterials( materials );
  1241. if ( validator.isValid( prepDataCallbacks.onLoadMaterials ) ) materials = prepDataCallbacks.onLoadMaterials( materials );
  1242. return materials;
  1243. };
  1244. var wrapperOnReportError = function ( errorMessage ) {
  1245. var continueProcessing = true;
  1246. if ( validator.isValid( globalCallbacks.onReportError ) ) continueProcessing = globalCallbacks.onReportError( supportDesc, errorMessage );
  1247. if ( validator.isValid( prepDataCallbacks.onReportError ) ) continueProcessing = prepDataCallbacks.onReportError( supportDesc, errorMessage );
  1248. if ( ! validator.isValid( globalCallbacks.onReportError ) && ! validator.isValid( prepDataCallbacks.onReportError ) ) {
  1249. console.error( 'Loader reported an error: ' );
  1250. console.error( errorMessage );
  1251. }
  1252. if ( continueProcessing ) {
  1253. supportDesc.inUse = false;
  1254. scope.processQueue();
  1255. }
  1256. };
  1257. supportDesc.loader = this._buildLoader( supportDesc.instanceNo );
  1258. var updatedCallbacks = new THREE.LoaderSupport.Callbacks();
  1259. updatedCallbacks.setCallbackOnLoad( wrapperOnLoad );
  1260. updatedCallbacks.setCallbackOnProgress( wrapperOnProgress );
  1261. updatedCallbacks.setCallbackOnReportError( wrapperOnReportError );
  1262. updatedCallbacks.setCallbackOnMeshAlter( wrapperOnMeshAlter );
  1263. updatedCallbacks.setCallbackOnLoadMaterials( wrapperOnLoadMaterials );
  1264. prepData.callbacks = updatedCallbacks;
  1265. supportDesc.loader.run( prepData, supportDesc.workerSupport );
  1266. },
  1267. _buildLoader: function ( instanceNo ) {
  1268. var classDef = this.workerDescription.classDef;
  1269. var loader = Object.create( classDef.prototype );
  1270. classDef.call( loader, THREE.DefaultLoadingManager );
  1271. // verify that all required functions are implemented
  1272. if ( ! loader.hasOwnProperty( 'instanceNo' ) ) throw classDef.name + ' has no property "instanceNo".';
  1273. loader.instanceNo = instanceNo;
  1274. if ( ! loader.hasOwnProperty( 'workerSupport' ) ) {
  1275. throw classDef.name + ' has no property "workerSupport".';
  1276. }
  1277. if ( typeof loader.run !== 'function' ) throw classDef.name + ' has no function "run".';
  1278. if ( ! loader.hasOwnProperty( 'callbacks' ) || ! THREE.LoaderSupport.Validator.isValid( loader.callbacks ) ) {
  1279. console.warn( classDef.name + ' has an invalid property "callbacks". Will change to "THREE.LoaderSupport.Callbacks"' );
  1280. loader.callbacks = new THREE.LoaderSupport.Callbacks();
  1281. }
  1282. return loader;
  1283. },
  1284. _deregister: function ( supportDesc ) {
  1285. if ( THREE.LoaderSupport.Validator.isValid( supportDesc ) ) {
  1286. supportDesc.workerSupport.setTerminateRequested( true );
  1287. if ( this.logging.enabled ) console.info( 'Requested termination of worker #' + supportDesc.instanceNo + '.' );
  1288. var loaderCallbacks = supportDesc.loader.callbacks;
  1289. if ( THREE.LoaderSupport.Validator.isValid( loaderCallbacks.onProgress ) ) loaderCallbacks.onProgress( { detail: { text: '' } } );
  1290. delete this.workerDescription.workerSupports[ supportDesc.instanceNo ];
  1291. }
  1292. },
  1293. /**
  1294. * Terminate all workers.
  1295. *
  1296. * @param {callback} callbackOnFinishedProcessing Function called once all workers finished processing.
  1297. */
  1298. tearDown: function ( callbackOnFinishedProcessing ) {
  1299. if ( this.logging.enabled ) console.info( 'WorkerDirector received the deregister call. Terminating all workers!' );
  1300. this.instructionQueuePointer = this.instructionQueue.length;
  1301. this.callbackOnFinishedProcessing = THREE.LoaderSupport.Validator.verifyInput( callbackOnFinishedProcessing, null );
  1302. for ( var name in this.workerDescription.workerSupports ) {
  1303. this.workerDescription.workerSupports[ name ].terminateRequested = true;
  1304. }
  1305. }
  1306. };