LoaderSupport.js 47 KB

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