123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155 |
- /**
- * @author Kai Salmen / https://kaisalmen.de
- * Development repository: https://github.com/kaisalmen/WWOBJLoader
- */
- 'use strict';
- if ( THREE.LoaderSupport === undefined ) { THREE.LoaderSupport = {} }
- /**
- * Validation functions
- * @class
- */
- THREE.LoaderSupport.Validator = {
- /**
- * If given input is null or undefined, false is returned otherwise true.
- *
- * @param input Anything
- * @returns {boolean}
- */
- isValid: function( input ) {
- return ( input !== null && input !== undefined );
- },
- /**
- * If given input is null or undefined, the defaultValue is returned otherwise the given input.
- *
- * @param input Anything
- * @param defaultValue Anything
- * @returns {*}
- */
- verifyInput: function( input, defaultValue ) {
- return ( input === null || input === undefined ) ? defaultValue : input;
- }
- };
- /**
- * Callbacks utilized by functions working with WWLoader implementations
- * @class
- */
- THREE.LoaderSupport.Callbacks = (function () {
- var Validator = THREE.LoaderSupport.Validator;
- function Callbacks() {
- this.onProgress = null;
- this.onMeshAlter = null;
- this.onLoad = null;
- }
- /**
- * Register callback function that is invoked by internal function "announceProgress" to print feedback.
- * @memberOf THREE.LoaderSupport.Callbacks
- *
- * @param {callback} callbackOnProgress Callback function for described functionality
- */
- Callbacks.prototype.setCallbackOnProgress = function ( callbackOnProgress ) {
- this.onProgress = Validator.verifyInput( callbackOnProgress, this.onProgress );
- };
- /**
- * Register callback function that is called every time a mesh was loaded.
- * Use {@link THREE.LoaderSupport.LoadedMeshUserOverride} for alteration instructions (geometry, material or disregard mesh).
- * @memberOf THREE.LoaderSupport.Callbacks
- *
- * @param {callback} callbackOnMeshAlter Callback function for described functionality
- */
- Callbacks.prototype.setCallbackOnMeshAlter = function ( callbackOnMeshAlter ) {
- this.onMeshAlter = Validator.verifyInput( callbackOnMeshAlter, this.onMeshAlter );
- };
- /**
- * Register callback function that is called once loading of the complete model is completed.
- * @memberOf THREE.LoaderSupport.Callbacks
- *
- * @param {callback} callbackOnLoad Callback function for described functionality
- */
- Callbacks.prototype.setCallbackOnLoad = function ( callbackOnLoad ) {
- this.onLoad = Validator.verifyInput( callbackOnLoad, this.onLoad );
- };
- return Callbacks;
- })();
- /**
- * Global callback definition
- * @class
- */
- THREE.LoaderSupport.Builder = (function () {
- var Validator = THREE.LoaderSupport.Validator;
- function Builder() {
- this.callbacks = new THREE.LoaderSupport.Callbacks();
- this.materials = [];
- this.materialNames = [];
- this._createDefaultMaterials();
- }
- Builder.prototype._createDefaultMaterials = function () {
- var defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
- defaultMaterial.name = 'defaultMaterial';
- if ( ! Validator.isValid( this.materials[ defaultMaterial ] ) ) {
- this.materials[ defaultMaterial.name ] = defaultMaterial;
- }
- this.materialNames.push( defaultMaterial.name );
- var vertexColorMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
- vertexColorMaterial.name = 'vertexColorMaterial';
- vertexColorMaterial.vertexColors = THREE.VertexColors;
- if ( ! Validator.isValid( this.materials[ vertexColorMaterial.name ] ) ) {
- this.materials[ vertexColorMaterial.name ] = vertexColorMaterial;
- }
- this.materialNames.push( vertexColorMaterial.name );
- };
- /**
- * Set materials loaded by any supplier of an Array of {@link THREE.Material}.
- * @memberOf THREE.LoaderSupport.Builder
- *
- * @param {THREE.Material[]} materials Array of {@link THREE.Material}
- */
- Builder.prototype.setMaterials = function ( materials ) {
- if ( Validator.isValid( materials ) && Object.keys( materials ).length > 0 ) {
- var materialName;
- for ( materialName in materials ) {
- if ( materials.hasOwnProperty( materialName ) && ! this.materials.hasOwnProperty( materialName) ) {
- this.materials[ materialName ] = materials[ materialName ];
- }
- }
- // always reset list of names as they are an array
- this.materialNames = [];
- for ( materialName in materials ) this.materialNames.push( materialName );
- }
- };
- Builder.prototype._setCallbacks = function ( callbackOnProgress, callbackOnMeshAlter, callbackOnLoad ) {
- this.callbacks.setCallbackOnProgress( callbackOnProgress );
- this.callbacks.setCallbackOnMeshAlter( callbackOnMeshAlter );
- this.callbacks.setCallbackOnLoad( callbackOnLoad );
- };
- /**
- * Builds one or multiple meshes from the data described in the payload (buffers, params, material info,
- *
- * @param {Object} payload buffers, params, materials
- * @returns {THREE.Mesh[]} mesh Array of {@link THREE.Mesh}
- */
- Builder.prototype.buildMeshes = function ( payload ) {
- var meshName = payload.params.meshName;
- var bufferGeometry = new THREE.BufferGeometry();
- bufferGeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( payload.buffers.vertices ), 3 ) );
- if ( Validator.isValid( payload.buffers.indices ) ) {
- bufferGeometry.setIndex( new THREE.BufferAttribute( new Uint32Array( payload.buffers.indices ), 1 ));
- }
- var haveVertexColors = Validator.isValid( payload.buffers.colors );
- if ( haveVertexColors ) {
- bufferGeometry.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( payload.buffers.colors ), 3 ) );
- }
- if ( Validator.isValid( payload.buffers.normals ) ) {
- bufferGeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( payload.buffers.normals ), 3 ) );
- } else {
- bufferGeometry.computeVertexNormals();
- }
- if ( Validator.isValid( payload.buffers.uvs ) ) {
- bufferGeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( payload.buffers.uvs ), 2 ) );
- }
- var materialDescriptions = payload.materials.materialDescriptions;
- var materialDescription;
- var material;
- var materialName;
- var createMultiMaterial = payload.materials.multiMaterial;
- var multiMaterials = [];
- var key;
- for ( key in materialDescriptions ) {
- materialDescription = materialDescriptions[ key ];
- material = this.materials[ materialDescription.name ];
- material = Validator.verifyInput( material, this.materials[ 'defaultMaterial' ] );
- if ( haveVertexColors ) {
- if ( material.hasOwnProperty( 'vertexColors' ) ) {
- materialName = material.name + '_vertexColor';
- var materialClone = this.materials[ materialName ];
- if ( ! Validator.isValid( materialClone ) ) {
- materialClone = material.clone();
- materialClone.name = materialName;
- materialClone.vertexColors = THREE.VertexColors;
- this.materials[ materialName ] = materialClone;
- }
- material = materialClone;
- } else {
- material = this.materials[ 'vertexColorMaterial' ];
- }
- }
- if ( materialDescription.flat ) {
- materialName = material.name + '_flat';
- var materialClone = this.materials[ materialName ];
- if ( ! Validator.isValid( materialClone ) ) {
- materialClone = material.clone();
- materialClone.name = materialName;
- materialClone.flatShading = true;
- this.materials[ materialName ] = materialClone;
- }
- material = materialClone;
- }
- if ( createMultiMaterial ) multiMaterials.push( material );
- }
- if ( createMultiMaterial ) {
- material = multiMaterials;
- var materialGroups = payload.materials.materialGroups;
- var materialGroup;
- for ( key in materialGroups ) {
- materialGroup = materialGroups[ key ];
- bufferGeometry.addGroup( materialGroup.start, materialGroup.count, materialGroup.index );
- }
- }
- var meshes = [];
- var mesh;
- var callbackOnMeshAlter = this.callbacks.onMeshAlter;
- var callbackOnMeshAlterResult;
- var useOrgMesh = true;
- if ( Validator.isValid( callbackOnMeshAlter ) ) {
- callbackOnMeshAlterResult = callbackOnMeshAlter( meshName, bufferGeometry, material );
- if ( Validator.isValid( callbackOnMeshAlterResult ) ) {
- if ( ! callbackOnMeshAlterResult.isDisregardMesh() && callbackOnMeshAlterResult.providesAlteredMeshes() ) {
- for ( var i in callbackOnMeshAlterResult.meshes ) {
- meshes.push( callbackOnMeshAlterResult.meshes[ i ] );
- }
- }
- useOrgMesh = false;
- }
- }
- if ( useOrgMesh ) {
- mesh = new THREE.Mesh( bufferGeometry, material );
- mesh.name = meshName;
- meshes.push( mesh );
- }
- var progressMessage;
- if ( Validator.isValid( meshes ) && meshes.length > 0 ) {
- var meshNames = [];
- for ( var i in meshes ) {
- mesh = meshes[ i ];
- meshNames[ i ] = mesh.name;
- }
- progressMessage = 'Adding mesh(es) (' + meshNames.length + ': ' + meshNames + ') from input mesh: ' + meshName;
- } else {
- progressMessage = 'Not adding mesh: ' + meshName;
- }
- var callbackOnProgress = this.callbacks.onProgress;
- if ( Validator.isValid( callbackOnProgress ) ) callbackOnProgress( progressMessage );
- return meshes;
- };
- return Builder;
- })();
- /**
- * Global callback definition
- * @class
- */
- THREE.LoaderSupport.Commons = (function () {
- var Validator = THREE.LoaderSupport.Validator;
- function Commons( manager ) {
- this.manager = Validator.verifyInput( manager, THREE.DefaultLoadingManager );
- this.modelName = '';
- this.instanceNo = 0;
- this.path = '';
- this.debug = false;
- this.useIndices = false;
- this.disregardNormals = false;
- this.loaderRootNode = new THREE.Group();
- this.builder = new THREE.LoaderSupport.Builder();
- this.callbacks = new THREE.LoaderSupport.Callbacks();
- };
- Commons.prototype._applyPrepData = function ( prepData ) {
- if ( Validator.isValid( prepData ) ) {
- this.setModelName( prepData.modelName );
- this.setStreamMeshesTo( prepData.streamMeshesTo );
- this.builder.setMaterials( prepData.materials );
- this.setUseIndices( prepData.useIndices );
- this.setDisregardNormals( prepData.disregardNormals );
- this._setCallbacks( prepData.getCallbacks().onProgress, prepData.getCallbacks().onMeshAlter, prepData.getCallbacks().onLoad );
- }
- };
- Commons.prototype._setCallbacks = function ( callbackOnProgress, callbackOnMeshAlter, callbackOnLoad ) {
- this.callbacks.setCallbackOnProgress( callbackOnProgress );
- this.callbacks.setCallbackOnMeshAlter( callbackOnMeshAlter );
- this.callbacks.setCallbackOnLoad( callbackOnLoad );
- this.builder._setCallbacks( callbackOnProgress, callbackOnMeshAlter, callbackOnLoad );
- };
- Commons.prototype.setModelName = function ( modelName ) {
- this.modelName = Validator.verifyInput( modelName, this.modelName );
- };
- /**
- * The URL of the base path
- * @param {string} path
- */
- Commons.prototype.setPath = function ( path ) {
- this.path = Validator.verifyInput( path, this.path );
- };
- /**
- * Allows to set debug mode.
- * @memberOf THREE.LoaderSupport.Commons
- *
- * @param {boolean} enabled
- */
- Commons.prototype.setDebug = function ( enabled ) {
- this.debug = enabled;
- };
- /**
- * Set the node where the loaded objects will be attached directly.
- * @memberOf THREE.LoaderSupport.Commons
- *
- * @param {THREE.Object3D} streamMeshesTo Attached scenegraph object where meshes will be attached live
- */
- Commons.prototype.setStreamMeshesTo = function ( streamMeshesTo ) {
- this.loaderRootNode = Validator.verifyInput( streamMeshesTo, this.loaderRootNode );
- };
- /**
- * Set materials loaded by MTLLoader or any other supplier of an Array of {@link THREE.Material}.
- * @memberOf THREE.LoaderSupport.Commons
- *
- * @param {THREE.Material[]} materials Array of {@link THREE.Material}
- */
- Commons.prototype.setMaterials = function ( materials ) {
- this.builder.setMaterials( materials );
- };
- /**
- * Tells whether indices should be used
- * @memberOf THREE.LoaderSupport.Commons
- *
- * @param {boolean} useIndices=false Default is false
- */
- Commons.prototype.setUseIndices = function ( useIndices ) {
- this.useIndices = useIndices === true;
- };
- /**
- * Tells whether normals should be completely disregarded
- * @memberOf THREE.LoaderSupport.Commons
- *
- * @param {boolean} disregardNormals=false Default is false
- */
- Commons.prototype.setDisregardNormals = function ( disregardNormals ) {
- this.disregardNormals = disregardNormals === true;
- };
- /**
- * Announce feedback which is give to the registered callbacks and logged if debug is enabled
- * @memberOf THREE.LoaderSupport.Commons
- *
- * @param baseText
- * @param text
- */
- Commons.prototype.onProgress = function ( baseText, text ) {
- var content = Validator.isValid( baseText ) ? baseText: '';
- content = Validator.isValid( text ) ? content + ' ' + text : content;
- if ( Validator.isValid( this.callbacks.onProgress ) ) this.callbacks.onProgress( content, this.modelName, this.instanceNo );
- if ( this.debug ) console.log( content );
- };
- return Commons;
- })();
- /**
- * Object to return by {@link THREE.LoaderSupport.Commons}.callbacks.meshLoaded.
- * Used to disregard a certain mesh or to return one to many created meshes.
- * @class
- *
- * @param {boolean} disregardMesh=false Tell implementation to completely disregard this mesh
- */
- THREE.LoaderSupport.LoadedMeshUserOverride = (function () {
- function LoadedMeshUserOverride( disregardMesh, alteredMesh ) {
- this.disregardMesh = disregardMesh === true;
- this.alteredMesh = alteredMesh === true;
- this.meshes = [];
- }
- /**
- * Add a mesh created within callback.
- *
- * @memberOf THREE.OBJLoader2.LoadedMeshUserOverride
- *
- * @param {THREE.Mesh} mesh
- */
- LoadedMeshUserOverride.prototype.addMesh = function ( mesh ) {
- this.meshes.push( mesh );
- };
- /**
- * Answers if mesh shall be disregarded completely.
- *
- * @returns {boolean}
- */
- LoadedMeshUserOverride.prototype.isDisregardMesh = function () {
- return this.disregardMesh;
- };
- /**
- * Answers if new mesh(es) were created.
- *
- * @returns {boolean}
- */
- LoadedMeshUserOverride.prototype.providesAlteredMeshes = function () {
- return this.alteredMesh;
- };
- return LoadedMeshUserOverride;
- })();
- /**
- * A resource description used by {@link THREE.LoaderSupport.PrepData} and others.
- * @class
- *
- * @param {string} url URL to the file
- * @param {string} extension The file extension (type)
- */
- THREE.LoaderSupport.ResourceDescriptor = (function () {
- var Validator = THREE.LoaderSupport.Validator;
- function ResourceDescriptor( url, extension ) {
- var urlParts = url.split( '/' );
- if ( urlParts.length < 2 ) {
- this.path = null;
- this.name = this.name = url;
- this.url = url;
- } else {
- this.path = Validator.verifyInput( urlParts.slice( 0, urlParts.length - 1).join( '/' ) + '/', null );
- this.name = Validator.verifyInput( urlParts[ urlParts.length - 1 ], null );
- this.url = url;
- }
- this.extension = Validator.verifyInput( extension, "default" );
- this.extension = this.extension.trim();
- this.content = null;
- }
- /**
- * Set the content of this resource (String)
- * @memberOf THREE.LoaderSupport.ResourceDescriptor
- *
- * @param {Object} content The file content as arraybuffer or text
- */
- ResourceDescriptor.prototype.setContent = function ( content ) {
- this.content = Validator.verifyInput( content, null );
- };
- return ResourceDescriptor;
- })();
- /**
- * Base class for configuration of prepareRun when using {@link THREE.LoaderSupport.WorkerSupport}.
- * @class
- */
- THREE.LoaderSupport.PrepData = (function () {
- var Validator = THREE.LoaderSupport.Validator;
- function PrepData( modelName ) {
- this.modelName = Validator.verifyInput( modelName, '' );
- this.resources = [];
- this.streamMeshesTo = null;
- this.materialPerSmoothingGroup = false;
- this.useIndices = false;
- this.disregardNormals = false;
- this.callbacks = new THREE.LoaderSupport.Callbacks();
- this.crossOrigin;
- this.useAsync = false;
- }
- /**
- * {@link THREE.Object3D} where meshes will be attached.
- * @memberOf THREE.LoaderSupport.PrepData
- *
- * @param {THREE.Object3D} streamMeshesTo Scene graph object
- */
- PrepData.prototype.setStreamMeshesTo = function ( streamMeshesTo ) {
- this.streamMeshesTo = Validator.verifyInput( streamMeshesTo, null );
- };
- /**
- * Tells whether a material shall be created per smoothing group
- * @memberOf THREE.LoaderSupport.PrepData
- *
- * @param {boolean} materialPerSmoothingGroup
- */
- PrepData.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
- this.materialPerSmoothingGroup = materialPerSmoothingGroup;
- };
- /**
- * Tells whether indices should be used
- * @memberOf THREE.LoaderSupport.PrepData
- *
- * @param {boolean} useIndices=false Default is false
- */
- PrepData.prototype.setUseIndices = function ( useIndices ) {
- this.useIndices = useIndices === true;
- };
- /**
- * Tells whether normals should be completely disregarded
- * @memberOf THREE.LoaderSupport.PrepData
- *
- * @param {boolean} disregardNormals=false Default is false
- */
- PrepData.prototype.setDisregardNormals = function ( disregardNormals ) {
- this.disregardNormals = disregardNormals === true;
- };
- /**
- * Returns all callbacks as {@link THREE.LoaderSupport.Callbacks}
- * @memberOf THREE.LoaderSupport.PrepData
- *
- * @returns {THREE.LoaderSupport.Callbacks}
- */
- PrepData.prototype.getCallbacks = function () {
- return this.callbacks;
- };
- /**
- * Sets the CORS string to be used.
- * @memberOf THREE.LoaderSupport.PrepData
- *
- * @param {string} crossOrigin CORS value
- */
- PrepData.prototype.setCrossOrigin = function ( crossOrigin ) {
- this.crossOrigin = crossOrigin;
- };
- /**
- * Add a resource description
- * @memberOf THREE.LoaderSupport.PrepData
- *
- * @param {THREE.LoaderSupport.ResourceDescriptor} The resource description
- */
- PrepData.prototype.addResource = function ( resource ) {
- this.resources.push( resource );
- };
- /**
- *
- * @param {boolean} useAsync
- */
- PrepData.prototype.setUseAsync = function ( useAsync ) {
- this.useAsync = useAsync === true;
- };
- /**
- * Clones this object and returns it afterwards.
- *
- * @returns {@link THREE.LoaderSupport.PrepData}
- */
- PrepData.prototype.clone = function () {
- var clone = new THREE.LoaderSupport.PrepData( this.modelName );
- clone.resources = this.resources;
- clone.streamMeshesTo = this.streamMeshesTo;
- clone.materialPerSmoothingGroup = this.materialPerSmoothingGroup;
- clone.useIndices = this.useIndices;
- clone.disregardNormals = this.disregardNormals;
- clone.callbacks = this.callbacks;
- clone.crossOrigin = this.crossOrigin;
- clone.useAsync = this.useAsync;
- return clone;
- };
- return PrepData;
- })();
- THREE.LoaderSupport.WorkerRunnerRefImpl = (function () {
- function WorkerRunnerRefImpl() {
- var scope = this;
- var scopedRunner = function( event ) {
- scope.run( event.data );
- };
- self.addEventListener( 'message', scopedRunner, false );
- }
- WorkerRunnerRefImpl.prototype.applyProperties = function ( parser, params ) {
- var property, funcName, values;
- for ( property in params ) {
- funcName = 'set' + property.substring( 0, 1 ).toLocaleUpperCase() + property.substring( 1 );
- values = params[ property ];
- if ( parser.hasOwnProperty( property ) ) {
- if ( typeof parser[ funcName ] === 'function' ) {
- parser[ funcName ]( values );
- } else {
- parser[ property ] = values;
- }
- }
- }
- };
- WorkerRunnerRefImpl.prototype.run = function ( payload ) {
- if ( payload.cmd === 'run' ) {
- console.log( 'WorkerRunner: Starting Run...' );
- var callbacks = {
- callbackBuilder: function ( payload ) {
- self.postMessage( payload );
- },
- callbackProgress: function ( message ) {
- console.log( 'WorkerRunner: progress: ' + message );
- }
- };
- // Parser is expected to be named as such
- var parser = new Parser();
- this.applyProperties( parser, payload.params );
- this.applyProperties( parser, payload.materials );
- this.applyProperties( parser, callbacks );
- parser.parse( payload.buffers.input );
- console.log( 'WorkerRunner: Run complete!' );
- callbacks.callbackBuilder( {
- cmd: 'complete',
- msg: 'WorkerRunner completed run.'
- } );
- } else {
- console.error( 'WorkerRunner: Received unknown command: ' + payload.cmd );
- }
- };
- return WorkerRunnerRefImpl;
- })();
- THREE.LoaderSupport.WorkerSupport = (function () {
- var WORKER_SUPPORT_VERSION = '1.0.0-dev';
- var Validator = THREE.LoaderSupport.Validator;
- function WorkerSupport() {
- console.log( "Using THREE.LoaderSupport.WorkerSupport version: " + WORKER_SUPPORT_VERSION );
- // check worker support first
- if ( window.Worker === undefined ) throw "This browser does not support web workers!";
- if ( window.Blob === undefined ) throw "This browser does not support Blob!";
- if ( typeof window.URL.createObjectURL !== 'function' ) throw "This browser does not support Object creation from URL!";
- this.worker = null;
- this.workerCode = null;
- this.running = false;
- this.terminateRequested = false;
- this.callbacks = {
- builder: null,
- onLoad: null
- };
- }
- WorkerSupport.prototype.validate = function ( functionCodeBuilder, forceWorkerReload, runnerImpl ) {
- this.running = false;
- if ( forceWorkerReload ) {
- this.worker = null;
- this.workerCode = null;
- this.callbacks.builder = null;
- this.callbacks.onLoad = null;
- }
- if ( ! Validator.isValid( this.worker ) ) {
- console.log( 'WorkerSupport: Building worker code...' );
- console.time( 'buildWebWorkerCode' );
- var workerRunner;
- if ( Validator.isValid( runnerImpl ) ) {
- console.log( 'WorkerSupport: Using "' + runnerImpl.name + '" as Runncer class for worker.');
- workerRunner = runnerImpl;
- } else {
- console.log( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.WorkerRunnerRefImpl" as Runncer class for worker.');
- workerRunner = THREE.LoaderSupport.WorkerRunnerRefImpl;
- }
- this.workerCode = functionCodeBuilder( buildObject, buildSingelton );
- this.workerCode += buildSingelton( workerRunner.name, workerRunner.name, workerRunner );
- this.workerCode += 'new ' + workerRunner.name + '();\n\n';
- var blob = new Blob( [ this.workerCode ], { type: 'text/plain' } );
- this.worker = new Worker( window.URL.createObjectURL( blob ) );
- console.timeEnd( 'buildWebWorkerCode' );
- var scope = this;
- var receiveWorkerMessage = function ( e ) {
- var payload = e.data;
- switch ( payload.cmd ) {
- case 'meshData':
- scope.callbacks.builder( payload );
- break;
- case 'complete':
- scope.callbacks.onLoad( payload.msg );
- scope.running = false;
- if ( scope.terminateRequested ) {
- console.log( 'WorkerSupport: Run is complete. Terminating application on request!' );
- scope.terminateWorker();
- }
- break;
- default:
- console.error( 'WorkerSupport: Received unknown command: ' + payload.cmd );
- break;
- }
- };
- this.worker.addEventListener( 'message', receiveWorkerMessage, false );
- }
- };
- WorkerSupport.prototype.terminateWorker = function () {
- if ( Validator.isValid( this.worker ) ) {
- this.worker.terminate();
- }
- this.worker = null;
- this.workerCode = null;
- };
- WorkerSupport.prototype.setCallbacks = function ( builder, onLoad ) {
- this.callbacks = {
- builder: builder,
- onLoad: onLoad
- };
- };
- var buildObject = function ( fullName, object ) {
- var objectString = fullName + ' = {\n';
- var part;
- for ( var name in object ) {
- part = object[ name ];
- if ( typeof( part ) === 'string' || part instanceof String ) {
- part = part.replace( '\n', '\\n' );
- part = part.replace( '\r', '\\r' );
- objectString += '\t' + name + ': "' + part + '",\n';
- } else if ( part instanceof Array ) {
- objectString += '\t' + name + ': [' + part + '],\n';
- } else if ( Number.isInteger( part ) ) {
- objectString += '\t' + name + ': ' + part + ',\n';
- } else if ( typeof part === 'function' ) {
- objectString += '\t' + name + ': ' + part + ',\n';
- }
- }
- objectString += '}\n\n';
- return objectString;
- };
- var buildSingelton = function ( fullName, internalName, object ) {
- var objectString = fullName + ' = (function () {\n\n';
- objectString += '\t' + object.prototype.constructor.toString() + '\n\n';
- var funcString;
- var objectPart;
- for ( var name in object.prototype ) {
- objectPart = object.prototype[ name ];
- if ( typeof objectPart === 'function' ) {
- funcString = objectPart.toString();
- objectString += '\t' + internalName + '.prototype.' + name + ' = ' + funcString + ';\n\n';
- }
- }
- objectString += '\treturn ' + internalName + ';\n';
- objectString += '})();\n\n';
- return objectString;
- };
- WorkerSupport.prototype.setTerminateRequested = function ( terminateRequested ) {
- this.terminateRequested = terminateRequested === true;
- };
- WorkerSupport.prototype.run = function ( messageObject ) {
- if ( ! Validator.isValid( this.callbacks.builder ) ) throw 'Unable to run as no "builder" callback is set.';
- if ( ! Validator.isValid( this.callbacks.onLoad ) ) throw 'Unable to run as no "onLoad" callback is set.';
- if ( Validator.isValid( this.worker ) ) {
- this.running = true;
- this.worker.postMessage( messageObject );
- }
- };
- return WorkerSupport;
- })();
- /**
- * Orchestrate loading of multiple OBJ files/data from an instruction queue with a configurable amount of workers (1-16).
- * Workflow:
- * prepareWorkers
- * enqueueForRun
- * processQueue
- * deregister
- *
- * @class
- */
- THREE.LoaderSupport.WorkerDirector = (function () {
- var LOADER_WORKER_DIRECTOR_VERSION = '1.0.0-dev';
- var Validator = THREE.LoaderSupport.Validator;
- var MAX_WEB_WORKER = 16;
- var MAX_QUEUE_SIZE = 8192;
- function WorkerDirector( classDef ) {
- console.log( "Using THREE.LoaderSupport.WorkerDirector version: " + LOADER_WORKER_DIRECTOR_VERSION );
- this.maxQueueSize = MAX_QUEUE_SIZE ;
- this.maxWebWorkers = MAX_WEB_WORKER;
- this.crossOrigin = null;
- if ( ! Validator.isValid( classDef ) ) throw 'Provided invalid classDef: ' + classDef;
- this.workerDescription = {
- classDef: classDef,
- globalCallbacks: {},
- workerSupports: []
- };
- this.objectsCompleted = 0;
- this.instructionQueue = [];
- }
- /**
- * Returns the maximum length of the instruction queue.
- * @memberOf THREE.LoaderSupport.WorkerDirector
- *
- * @returns {number}
- */
- WorkerDirector.prototype.getMaxQueueSize = function () {
- return this.maxQueueSize;
- };
- /**
- * Returns the maximum number of workers.
- * @memberOf THREE.LoaderSupport.WorkerDirector
- *
- * @returns {number}
- */
- WorkerDirector.prototype.getMaxWebWorkers = function () {
- return this.maxWebWorkers;
- };
- /**
- * Sets the CORS string to be used.
- * @memberOf THREE.LoaderSupport.WorkerDirector
- *
- * @param {string} crossOrigin CORS value
- */
- WorkerDirector.prototype.setCrossOrigin = function ( crossOrigin ) {
- this.crossOrigin = crossOrigin;
- };
- /**
- * Create or destroy workers according limits. Set the name and register callbacks for dynamically created web workers.
- * @memberOf THREE.LoaderSupport.WorkerDirector
- *
- * @param {THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks} globalCallbacks Register global callbacks used by all web workers
- * @param {number} maxQueueSize Set the maximum size of the instruction queue (1-1024)
- * @param {number} maxWebWorkers Set the maximum amount of workers (1-16)
- */
- WorkerDirector.prototype.prepareWorkers = function ( globalCallbacks, maxQueueSize, maxWebWorkers ) {
- if ( Validator.isValid( globalCallbacks ) ) this.workerDescription.globalCallbacks = globalCallbacks;
- this.maxQueueSize = Math.min( maxQueueSize, MAX_QUEUE_SIZE );
- this.maxWebWorkers = Math.min( maxWebWorkers, MAX_WEB_WORKER );
- this.objectsCompleted = 0;
- this.instructionQueue = [];
- var start = this.workerDescription.workerSupports.length;
- var i;
- if ( start < this.maxWebWorkers ) {
- for ( i = start; i < this.maxWebWorkers; i++ ) {
- this.workerDescription.workerSupports[ i ] = {
- workerSupport: new THREE.LoaderSupport.WorkerSupport(),
- loader: null
- };
- }
- } else {
- for ( i = start - 1; i >= this.maxWebWorkers; i-- ) {
- this.workerDescription.workerSupports[ i ].workerSupport.setRequestTerminate( true );
- this.workerDescription.workerSupports.pop();
- }
- }
- };
- /**
- * Store run instructions in internal instructionQueue.
- * @memberOf THREE.LoaderSupport.WorkerDirector
- *
- * @param {Object} prepData Either {@link THREE.LoaderSupport.PrepData}
- */
- WorkerDirector.prototype.enqueueForRun = function ( prepData ) {
- if ( this.instructionQueue.length < this.maxQueueSize ) {
- this.instructionQueue.push( prepData );
- }
- };
- /**
- * Process the instructionQueue until it is depleted.
- * @memberOf THREE.LoaderSupport.WorkerDirector
- */
- WorkerDirector.prototype.processQueue = function () {
- if ( this.instructionQueue.length === 0 ) return;
- var length = Math.min( this.maxWebWorkers, this.instructionQueue.length );
- for ( var i = 0; i < length; i++ ) {
- this._kickWorkerRun( this.instructionQueue[ 0 ], i );
- this.instructionQueue.shift();
- }
- };
- WorkerDirector.prototype._kickWorkerRun = function( prepData, workerInstanceNo ) {
- var scope = this;
- var directorOnLoad = function ( sceneGraphBaseNode, modelName, instanceNo ) {
- scope.objectsCompleted++;
- var nextPrepData = scope.instructionQueue[ 0 ];
- if ( Validator.isValid( nextPrepData ) ) {
- scope.instructionQueue.shift();
- console.log( '\nAssigning next item from queue to worker (queue length: ' + scope.instructionQueue.length + ')\n\n' );
- scope._kickWorkerRun( nextPrepData, instanceNo );
- } else if ( scope.instructionQueue.length === 0 ) {
- scope.deregister();
- }
- };
- var prepDataCallbacks = prepData.getCallbacks();
- var globalCallbacks = this.workerDescription.globalCallbacks;
- var wrapperOnLoad = function ( sceneGraphBaseNode, modelName, instanceNo ) {
- if ( Validator.isValid( globalCallbacks.onLoad ) ) {
- globalCallbacks.onLoad( sceneGraphBaseNode, modelName, instanceNo );
- }
- if ( Validator.isValid( prepDataCallbacks.onLoad ) ) {
- prepDataCallbacks.onLoad( sceneGraphBaseNode, modelName, instanceNo );
- }
- directorOnLoad( sceneGraphBaseNode, modelName, instanceNo );
- };
- var wrapperOnProgress = function ( content, modelName, instanceNo ) {
- if ( Validator.isValid( globalCallbacks.onProgress ) ) {
- globalCallbacks.onProgress( content, modelName, instanceNo );
- }
- if ( Validator.isValid( prepDataCallbacks.onProgress ) ) {
- prepDataCallbacks.onProgress( content, modelName, instanceNo );
- }
- };
- var wrapperOnMeshAlter = function ( meshName, bufferGeometry, material ) {
- if ( Validator.isValid( globalCallbacks.onMeshAlter ) ) {
- globalCallbacks.onMeshAlter( meshName, bufferGeometry, material );
- }
- if ( Validator.isValid( prepDataCallbacks.onMeshAlter ) ) {
- prepDataCallbacks.onMeshAlter( meshName, bufferGeometry, material );
- }
- };
- var supportTuple = this.workerDescription.workerSupports[ workerInstanceNo ];
- supportTuple.loader = this._buildLoader( workerInstanceNo );
- var updatedCallbacks = new THREE.LoaderSupport.Callbacks();
- updatedCallbacks.setCallbackOnLoad( wrapperOnLoad );
- updatedCallbacks.setCallbackOnProgress( wrapperOnProgress );
- updatedCallbacks.setCallbackOnMeshAlter( wrapperOnMeshAlter );
- prepData.callbacks = updatedCallbacks;
- supportTuple.loader.run( prepData, supportTuple.workerSupport );
- };
- WorkerDirector.prototype._buildLoader = function ( instanceNo ) {
- var classDef = this.workerDescription.classDef;
- var loader = Object.create( classDef.prototype );
- this.workerDescription.classDef.call( loader );
- // verify that all required functions are implemented
- if ( ! loader.hasOwnProperty( 'instanceNo' ) ) throw classDef.name + ' has no property "instanceNo".';
- loader.instanceNo = instanceNo;
- if ( ! loader.hasOwnProperty( 'workerSupport' ) ) {
- throw classDef.name + ' has no property "workerSupport".';
- } else if ( ! classDef.workerSupport instanceof THREE.LoaderSupport.WorkerSupport ) {
- throw classDef.name + '.workerSupport is not of type "THREE.LoaderSupport.WorkerSupport".';
- }
- if ( typeof loader.run !== 'function' ) throw classDef.name + ' has no function "run".';
- return loader;
- };
- /**
- * Terminate all workers.
- * @memberOf THREE.LoaderSupport.WorkerDirector
- */
- WorkerDirector.prototype.deregister = function () {
- console.log( 'WorkerDirector received the deregister call. Terminating all workers!' );
- for ( var i = 0, length = this.workerDescription.workerSupports.length; i < length; i++ ) {
- var supportTuple = this.workerDescription.workerSupports[ i ];
- supportTuple.workerSupport.setTerminateRequested( true );
- console.log( 'Requested termination of worker.' );
- var loaderCallbacks = supportTuple.loader.callbacks;
- if ( Validator.isValid( loaderCallbacks.onProgress ) ) loaderCallbacks.onProgress( '' );
- }
- this.workerDescription.workerSupports = [];
- this.instructionQueue = [];
- };
- return WorkerDirector;
- })();
|