LoaderSupport.js 43 KB

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