/** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */!function(a){"use strict";function b(a,b,c,e){// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var f=b&&b.prototype instanceof d?b:d,g=Object.create(f.prototype),h=new m(e||[]);return g._invoke=i(a,c,h),g}// Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function c(a,b,c){try{return{type:"normal",arg:a.call(b,c)}}catch(a){return{type:"throw",arg:a}}}// Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function d(){}function e(){}function f(){}// This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function g(a){["next","throw","return"].forEach(function(b){a[b]=function(a){return this._invoke(b,a)}})}function h(a){function b(d,e,f,g){var h=c(a[d],a,e);if("throw"===h.type)g(h.arg);else{var i=h.arg,j=i.value;return j&&"object"===typeof j&&q.call(j,"__await")?Promise.resolve(j.__await).then(function(a){b("next",a,f,g)},function(a){b("throw",a,f,g)}):Promise.resolve(j).then(function(a){// When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. i.value=a,f(i)},g)}}function d(a,c){function d(){return new Promise(function(d,e){b(a,c,d,e)})}return e=// If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. e?e.then(d,// Avoid propagating failures to Promises returned by later // invocations of the iterator. d):d()}// Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). var e;this._invoke=d}function i(a,b,d){var e="suspendedStart";return function(f,g){if(e==="executing")throw new Error("Generator is already running");if("completed"===e){if("throw"===f)throw g;// Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return o()}for(d.method=f,d.arg=g;;){var h=d.delegate;if(h){var i=j(h,d);if(i){if(i===x)continue;return i}}if("next"===d.method)// Setting context._sent for legacy support of Babel's // function.sent implementation. d.sent=d._sent=d.arg;else if("throw"===d.method){if("suspendedStart"===e)throw e="completed",d.arg;d.dispatchException(d.arg)}else"return"===d.method&&d.abrupt("return",d.arg);e="executing";var k=c(a,b,d);if("normal"===k.type){if(e=d.done?"completed":"suspendedYield",k.arg===x)continue;return{value:k.arg,done:d.done}}"throw"===k.type&&(// Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. e="completed",d.method="throw",d.arg=k.arg)}}}// Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function j(a,b){var d=a.iterator[b.method];if(void 0===d){if(b.delegate=null,"throw"===b.method){if(a.iterator.return&&(b.method="return",b.arg=void 0,j(a,b),"throw"===b.method))// If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return x;b.method="throw",b.arg=new TypeError("The iterator does not provide a 'throw' method")}return x}var e=c(d,a.iterator,b.arg);if("throw"===e.type)return b.method="throw",b.arg=e.arg,b.delegate=null,x;var f=e.arg;if(!f)return b.method="throw",b.arg=new TypeError("iterator result is not an object"),b.delegate=null,x;if(f.done)b[a.resultName]=f.value,b.next=a.nextLoc,"return"!==b.method&&(b.method="next",b.arg=void 0);else// Re-yield the result returned by the delegate method. return f;// The delegate iterator is finished, so forget it and continue with // the outer generator. return b.delegate=null,x}// Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. function k(a){var b={tryLoc:a[0]};1 in a&&(b.catchLoc=a[1]),2 in a&&(b.finallyLoc=a[2],b.afterLoc=a[3]),this.tryEntries.push(b)}function l(a){var b=a.completion||{};b.type="normal",delete b.arg,a.completion=b}function m(a){// The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries=[{tryLoc:"root"}],a.forEach(k,this),this.reset(!0)}function n(a){if(a){var b=a[s];if(b)return b.call(a);if("function"===typeof a.next)return a;if(!isNaN(a.length)){var c=-1,d=function b(){for(;++c=o.length)return{done:true};return{done:false,value:o[i++]};},e:function e(_e2){throw _e2;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var normalCompletion=true,didErr=false,err;return{s:function s(){it=o[Symbol.iterator]();},n:function n(){var step=it.next();normalCompletion=step.done;return step;},e:function e(_e3){didErr=true;err=_e3;},f:function f(){try{if(!normalCompletion&&it.return!=null)it.return();}finally{if(didErr)throw err;}}};}function _toConsumableArray(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||_nonIterableSpread();}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _iterableToArray(iter){if(typeof Symbol!=="undefined"&&Symbol.iterator in Object(iter))return Array.from(iter);}function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i1&&typeof allowMissing!=='boolean'){throw new TypeError('"allowMissing" argument must be a boolean');}var parts=stringToPath(name);var value=getBaseIntrinsic('%'+(parts.length>0?parts[0]:'')+'%',allowMissing);for(var i=1;i=parts.length){var desc=$gOPD(value,parts[i]);if(!allowMissing&&!(parts[i]in value)){throw new $TypeError('base intrinsic for '+name+' exists, but the property is not available.');}value=desc?desc.get||desc.value:value[parts[i]];}else{value=value[parts[i]];}}}return value;};var $TypeError$1=GetIntrinsic('%TypeError%');// http://www.ecma-international.org/ecma-262/5.1/#sec-9.10 var CheckObjectCoercible=function CheckObjectCoercible(value,optMessage){if(value==null){throw new $TypeError$1(optMessage||'Cannot call method on '+value);}return value;};var RequireObjectCoercible=CheckObjectCoercible;var $apply=GetIntrinsic('%Function.prototype.apply%');var $call=GetIntrinsic('%Function.prototype.call%');var $reflectApply=GetIntrinsic('%Reflect.apply%',true)||functionBind.call($call,$apply);var callBind=function callBind(){return $reflectApply(functionBind,$call,arguments);};var apply=function applyBind(){return $reflectApply(functionBind,$apply,arguments);};callBind.apply=apply;var $indexOf=callBind(GetIntrinsic('String.prototype.indexOf'));var callBound=function callBoundIntrinsic(name,allowMissing){var intrinsic=GetIntrinsic(name,!!allowMissing);if(typeof intrinsic==='function'&&$indexOf(name,'.prototype.')){return callBind(intrinsic);}return intrinsic;};var $isEnumerable=callBound('Object.prototype.propertyIsEnumerable');var implementation$1=function values(O){var obj=RequireObjectCoercible(O);var vals=[];for(var key in obj){if(src(obj,key)&&$isEnumerable(obj,key)){vals.push(obj[key]);}}return vals;};var polyfill=function getPolyfill(){return typeof Object.values==='function'?Object.values:implementation$1;};var toStr$1=Object.prototype.toString;var isArguments=function isArguments(value){var str=toStr$1.call(value);var isArgs=str==='[object Arguments]';if(!isArgs){isArgs=str!=='[object Array]'&&value!==null&&_typeof(value)==='object'&&typeof value.length==='number'&&value.length>=0&&toStr$1.call(value.callee)==='[object Function]';}return isArgs;};var keysShim;if(!Object.keys){// modified from https://github.com/es-shims/es5-shim var has=Object.prototype.hasOwnProperty;var toStr$2=Object.prototype.toString;var isArgs=isArguments;// eslint-disable-line global-require var isEnumerable=Object.prototype.propertyIsEnumerable;var hasDontEnumBug=!isEnumerable.call({toString:null},'toString');var hasProtoEnumBug=isEnumerable.call(function(){},'prototype');var dontEnums=['toString','toLocaleString','valueOf','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','constructor'];var equalsConstructorPrototype=function equalsConstructorPrototype(o){var ctor=o.constructor;return ctor&&ctor.prototype===o;};var excludedKeys={$applicationCache:true,$console:true,$external:true,$frame:true,$frameElement:true,$frames:true,$innerHeight:true,$innerWidth:true,$onmozfullscreenchange:true,$onmozfullscreenerror:true,$outerHeight:true,$outerWidth:true,$pageXOffset:true,$pageYOffset:true,$parent:true,$scrollLeft:true,$scrollTop:true,$scrollX:true,$scrollY:true,$self:true,$webkitIndexedDB:true,$webkitStorageInfo:true,$window:true};var hasAutomationEqualityBug=function(){/* global window */if(typeof window==='undefined'){return false;}for(var k in window){try{if(!excludedKeys['$'+k]&&has.call(window,k)&&window[k]!==null&&_typeof(window[k])==='object'){try{equalsConstructorPrototype(window[k]);}catch(e){return true;}}}catch(e){return true;}}return false;}();var equalsConstructorPrototypeIfNotBuggy=function equalsConstructorPrototypeIfNotBuggy(o){/* global window */if(typeof window==='undefined'||!hasAutomationEqualityBug){return equalsConstructorPrototype(o);}try{return equalsConstructorPrototype(o);}catch(e){return false;}};keysShim=function keys(object){var isObject=object!==null&&_typeof(object)==='object';var isFunction=toStr$2.call(object)==='[object Function]';var isArguments=isArgs(object);var isString=isObject&&toStr$2.call(object)==='[object String]';var theKeys=[];if(!isObject&&!isFunction&&!isArguments){throw new TypeError('Object.keys called on a non-object');}var skipProto=hasProtoEnumBug&&isFunction;if(isString&&object.length>0&&!has.call(object,0)){for(var i=0;i0){for(var j=0;j2?arguments[2]:{};var props=objectKeys(map);if(hasSymbols$2){props=concat.call(props,Object.getOwnPropertySymbols(map));}for(var i=0;i2&&arguments[2]!==undefined?arguments[2]:defaultPropertyDeclaration;var ctor=this.constructor;var attr=ctor._attributeNameForProperty(name,options);if(attr!==undefined){var attrValue=ctor._propertyValueToAttribute(value,options);// an undefined value does not change the attribute. if(attrValue===undefined){return;}// Track if the property is being reflected to avoid // setting the property again via `attributeChangedCallback`. Note: // 1. this takes advantage of the fact that the callback is synchronous. // 2. will behave incorrectly if multiple attributes are in the reaction // stack at time of calling. However, since we process attributes // in `update` this should not be possible (or an extreme corner case // that we'd like to discover). // mark state reflecting this._updateState=this._updateState|STATE_IS_REFLECTING_TO_ATTRIBUTE;if(attrValue==null){this.removeAttribute(attr);}else{this.setAttribute(attr,attrValue);}// mark state not reflecting this._updateState=this._updateState&~STATE_IS_REFLECTING_TO_ATTRIBUTE;}}},{key:"_attributeToProperty",value:function _attributeToProperty(name,value){// Use tracking info to avoid deserializing attribute value if it was // just set from a property setter. if(this._updateState&STATE_IS_REFLECTING_TO_ATTRIBUTE){return;}var ctor=this.constructor;// Note, hint this as an `AttributeMap` so closure clearly understands // the type; it has issues with tracking types through statics // tslint:disable-next-line:no-unnecessary-type-assertion var propName=ctor._attributeToPropertyMap.get(name);if(propName!==undefined){var options=ctor.getPropertyOptions(propName);// mark state reflecting this._updateState=this._updateState|STATE_IS_REFLECTING_TO_PROPERTY;this[propName]=// tslint:disable-next-line:no-any ctor._propertyValueFromAttribute(value,options);// mark state not reflecting this._updateState=this._updateState&~STATE_IS_REFLECTING_TO_PROPERTY;}}/** * This protected version of `requestUpdate` does not access or return the * `updateComplete` promise. This promise can be overridden and is therefore * not free to access. */},{key:"requestUpdateInternal",value:function requestUpdateInternal(name,oldValue,options){var shouldRequestUpdate=true;// If we have a property key, perform property update steps. if(name!==undefined){var ctor=this.constructor;options=options||ctor.getPropertyOptions(name);if(ctor._valueHasChanged(this[name],oldValue,options.hasChanged)){if(!this._changedProperties.has(name)){this._changedProperties.set(name,oldValue);}// Add to reflecting properties set. // Note, it's important that every change has a chance to add the // property to `_reflectingProperties`. This ensures setting // attribute + property reflects correctly. if(options.reflect===true&&!(this._updateState&STATE_IS_REFLECTING_TO_PROPERTY)){if(this._reflectingProperties===undefined){this._reflectingProperties=new Map();}this._reflectingProperties.set(name,options);}}else{// Abort the request if the property should not be considered changed. shouldRequestUpdate=false;}}if(!this._hasRequestedUpdate&&shouldRequestUpdate){this._updatePromise=this._enqueueUpdate();}}/** * Requests an update which is processed asynchronously. This should * be called when an element should update based on some state not triggered * by setting a property. In this case, pass no arguments. It should also be * called when manually implementing a property setter. In this case, pass the * property `name` and `oldValue` to ensure that any configured property * options are honored. Returns the `updateComplete` Promise which is resolved * when the update completes. * * @param name {PropertyKey} (optional) name of requesting property * @param oldValue {any} (optional) old value of requesting property * @returns {Promise} A Promise that is resolved when the update completes. */},{key:"requestUpdate",value:function requestUpdate(name,oldValue){this.requestUpdateInternal(name,oldValue);return this.updateComplete;}/** * Sets up the element to asynchronously update. */},{key:"_enqueueUpdate",value:function(){var _enqueueUpdate2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee(){var result;return regeneratorRuntime.wrap(function _callee$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:this._updateState=this._updateState|STATE_UPDATE_REQUESTED;_context2.prev=1;_context2.next=4;return this._updatePromise;case 4:_context2.next=8;break;case 6:_context2.prev=6;_context2.t0=_context2["catch"](1);case 8:result=this.performUpdate();// If `performUpdate` returns a Promise, we await it. This is done to // enable coordinating updates with a scheduler. Note, the result is // checked to avoid delaying an additional microtask unless we need to. if(!(result!=null)){_context2.next=12;break;}_context2.next=12;return result;case 12:return _context2.abrupt("return",!this._hasRequestedUpdate);case 13:case"end":return _context2.stop();}}},_callee,this,[[1,6]]);}));function _enqueueUpdate(){return _enqueueUpdate2.apply(this,arguments);}return _enqueueUpdate;}()},{key:"performUpdate",/** * Performs an element update. Note, if an exception is thrown during the * update, `firstUpdated` and `updated` will not be called. * * You can override this method to change the timing of updates. If this * method is overridden, `super.performUpdate()` must be called. * * For instance, to schedule updates to occur just before the next frame: * * ``` * protected async performUpdate(): Promise { * await new Promise((resolve) => requestAnimationFrame(() => resolve())); * super.performUpdate(); * } * ``` */value:function performUpdate(){// Abort any update if one is not pending when this is called. // This can happen if `performUpdate` is called early to "flush" // the update. if(!this._hasRequestedUpdate){return;}// Mixin instance properties once, if they exist. if(this._instanceProperties){this._applyInstanceProperties();}var shouldUpdate=false;var changedProperties=this._changedProperties;try{shouldUpdate=this.shouldUpdate(changedProperties);if(shouldUpdate){this.update(changedProperties);}else{this._markUpdated();}}catch(e){// Prevent `firstUpdated` and `updated` from running when there's an // update exception. shouldUpdate=false;// Ensure element can accept additional updates after an exception. this._markUpdated();throw e;}if(shouldUpdate){if(!(this._updateState&STATE_HAS_UPDATED)){this._updateState=this._updateState|STATE_HAS_UPDATED;this.firstUpdated(changedProperties);}this.updated(changedProperties);}}},{key:"_markUpdated",value:function _markUpdated(){this._changedProperties=new Map();this._updateState=this._updateState&~STATE_UPDATE_REQUESTED;}/** * Returns a Promise that resolves when the element has completed updating. * The Promise value is a boolean that is `true` if the element completed the * update without triggering another update. The Promise result is `false` if * a property was set inside `updated()`. If the Promise is rejected, an * exception was thrown during the update. * * To await additional asynchronous work, override the `_getUpdateComplete` * method. For example, it is sometimes useful to await a rendered element * before fulfilling this Promise. To do this, first await * `super._getUpdateComplete()`, then any subsequent state. * * @returns {Promise} The Promise returns a boolean that indicates if the * update resolved without triggering another update. */},{key:"_getUpdateComplete",/** * Override point for the `updateComplete` promise. * * It is not safe to override the `updateComplete` getter directly due to a * limitation in TypeScript which means it is not possible to call a * superclass getter (e.g. `super.updateComplete.then(...)`) when the target * language is ES5 (https://github.com/microsoft/TypeScript/issues/338). * This method should be overridden instead. For example: * * class MyElement extends LitElement { * async _getUpdateComplete() { * await super._getUpdateComplete(); * await this._myChild.updateComplete; * } * } */value:function _getUpdateComplete(){return this._updatePromise;}/** * Controls whether or not `update` should be called when the element requests * an update. By default, this method always returns `true`, but this can be * customized to control when to update. * * @param _changedProperties Map of changed properties with old values */},{key:"shouldUpdate",value:function shouldUpdate(_changedProperties){return true;}/** * Updates the element. This method reflects property values to attributes. * It can be overridden to render and keep updated element DOM. * Setting properties inside this method will *not* trigger * another update. * * @param _changedProperties Map of changed properties with old values */},{key:"update",value:function update(_changedProperties){var _this6=this;if(this._reflectingProperties!==undefined&&this._reflectingProperties.size>0){// Use forEach so this works even if for/of loops are compiled to for // loops expecting arrays this._reflectingProperties.forEach(function(v,k){return _this6._propertyToAttribute(k,_this6[k],v);});this._reflectingProperties=undefined;}this._markUpdated();}/** * Invoked whenever the element is updated. Implement to perform * post-updating tasks via DOM APIs, for example, focusing an element. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values */},{key:"updated",value:function updated(_changedProperties){}/** * Invoked when the element is first updated. Implement to perform one time * work on the element after update. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values */},{key:"firstUpdated",value:function firstUpdated(_changedProperties){}},{key:"_hasRequestedUpdate",get:function get(){return this._updateState&STATE_UPDATE_REQUESTED;}},{key:"hasUpdated",get:function get(){return this._updateState&STATE_HAS_UPDATED;}},{key:"updateComplete",get:function get(){return this._getUpdateComplete();}}],[{key:"_ensureClassProperties",/** * Ensures the private `_classProperties` property metadata is created. * In addition to `finalize` this is also called in `createProperty` to * ensure the `@property` decorator can add property metadata. */ /** @nocollapse */value:function _ensureClassProperties(){var _this7=this;// ensure private storage for property declarations. if(!this.hasOwnProperty(JSCompiler_renameProperty('_classProperties',this))){this._classProperties=new Map();// NOTE: Workaround IE11 not supporting Map constructor argument. var superProperties=Object.getPrototypeOf(this)._classProperties;if(superProperties!==undefined){superProperties.forEach(function(v,k){return _this7._classProperties.set(k,v);});}}}/** * Creates a property accessor on the element prototype if one does not exist * and stores a PropertyDeclaration for the property with the given options. * The property setter calls the property's `hasChanged` property option * or uses a strict identity check to determine whether or not to request * an update. * * This method may be overridden to customize properties; however, * when doing so, it's important to call `super.createProperty` to ensure * the property is setup correctly. This method calls * `getPropertyDescriptor` internally to get a descriptor to install. * To customize what properties do when they are get or set, override * `getPropertyDescriptor`. To customize the options for a property, * implement `createProperty` like this: * * static createProperty(name, options) { * options = Object.assign(options, {myOption: true}); * super.createProperty(name, options); * } * * @nocollapse */},{key:"createProperty",value:function createProperty(name){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:defaultPropertyDeclaration;// Note, since this can be called by the `@property` decorator which // is called before `finalize`, we ensure storage exists for property // metadata. this._ensureClassProperties();this._classProperties.set(name,options);// Do not generate an accessor if the prototype already has one, since // it would be lost otherwise and that would never be the user's intention; // Instead, we expect users to call `requestUpdate` themselves from // user-defined accessors. Note that if the super has an accessor we will // still overwrite it if(options.noAccessor||this.prototype.hasOwnProperty(name)){return;}var key=_typeof(name)==='symbol'?Symbol():"__".concat(name);var descriptor=this.getPropertyDescriptor(name,key,options);if(descriptor!==undefined){Object.defineProperty(this.prototype,name,descriptor);}}/** * Returns a property descriptor to be defined on the given named property. * If no descriptor is returned, the property will not become an accessor. * For example, * * class MyElement extends LitElement { * static getPropertyDescriptor(name, key, options) { * const defaultDescriptor = * super.getPropertyDescriptor(name, key, options); * const setter = defaultDescriptor.set; * return { * get: defaultDescriptor.get, * set(value) { * setter.call(this, value); * // custom action. * }, * configurable: true, * enumerable: true * } * } * } * * @nocollapse */},{key:"getPropertyDescriptor",value:function getPropertyDescriptor(name,key,options){return{// tslint:disable-next-line:no-any no symbol in index get:function get(){return this[key];},set:function set(value){var oldValue=this[name];this[key]=value;this.requestUpdateInternal(name,oldValue,options);},configurable:true,enumerable:true};}/** * Returns the property options associated with the given property. * These options are defined with a PropertyDeclaration via the `properties` * object or the `@property` decorator and are registered in * `createProperty(...)`. * * Note, this method should be considered "final" and not overridden. To * customize the options for a given property, override `createProperty`. * * @nocollapse * @final */},{key:"getPropertyOptions",value:function getPropertyOptions(name){return this._classProperties&&this._classProperties.get(name)||defaultPropertyDeclaration;}/** * Creates property accessors for registered properties and ensures * any superclasses are also finalized. * @nocollapse */},{key:"finalize",value:function finalize(){// finalize any superclasses var superCtor=Object.getPrototypeOf(this);if(!superCtor.hasOwnProperty(finalized)){superCtor.finalize();}this[finalized]=true;this._ensureClassProperties();// initialize Map populated in observedAttributes this._attributeToPropertyMap=new Map();// make any properties // Note, only process "own" properties since this element will inherit // any properties defined on the superClass, and finalization ensures // the entire prototype chain is finalized. if(this.hasOwnProperty(JSCompiler_renameProperty('properties',this))){var props=this.properties;// support symbols in properties (IE11 does not support this) var propKeys=[].concat(_toConsumableArray(Object.getOwnPropertyNames(props)),_toConsumableArray(typeof Object.getOwnPropertySymbols==='function'?Object.getOwnPropertySymbols(props):[]));// This for/of is ok because propKeys is an array var _iterator=_createForOfIteratorHelper(propKeys),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var p=_step.value;// note, use of `any` is due to TypeSript lack of support for symbol in // index types // tslint:disable-next-line:no-any no symbol in index this.createProperty(p,props[p]);}}catch(err){_iterator.e(err);}finally{_iterator.f();}}}/** * Returns the property name for the given attribute `name`. * @nocollapse */},{key:"_attributeNameForProperty",value:function _attributeNameForProperty(name,options){var attribute=options.attribute;return attribute===false?undefined:typeof attribute==='string'?attribute:typeof name==='string'?name.toLowerCase():undefined;}/** * Returns true if a property should request an update. * Called when a property value is set and uses the `hasChanged` * option for the property if present or a strict identity check. * @nocollapse */},{key:"_valueHasChanged",value:function _valueHasChanged(value,old){var hasChanged=arguments.length>2&&arguments[2]!==undefined?arguments[2]:notEqual;return hasChanged(value,old);}/** * Returns the property value for the given attribute value. * Called via the `attributeChangedCallback` and uses the property's * `converter` or `converter.fromAttribute` property option. * @nocollapse */},{key:"_propertyValueFromAttribute",value:function _propertyValueFromAttribute(value,options){var type=options.type;var converter=options.converter||defaultConverter;var fromAttribute=typeof converter==='function'?converter:converter.fromAttribute;return fromAttribute?fromAttribute(value,type):value;}/** * Returns the attribute value for the given property value. If this * returns undefined, the property will *not* be reflected to an attribute. * If this returns null, the attribute will be removed, otherwise the * attribute will be set to the value. * This uses the property's `reflect` and `type.toAttribute` property options. * @nocollapse */},{key:"_propertyValueToAttribute",value:function _propertyValueToAttribute(value,options){if(options.reflect===undefined){return;}var type=options.type;var converter=options.converter;var toAttribute=converter&&converter.toAttribute||defaultConverter.toAttribute;return toAttribute(value,type);}},{key:"observedAttributes",get:function get(){var _this8=this;// note: piggy backing on this to ensure we're finalized. this.finalize();var attributes=[];// Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays this._classProperties.forEach(function(v,p){var attr=_this8._attributeNameForProperty(p,v);if(attr!==undefined){_this8._attributeToPropertyMap.set(attr,p);attributes.push(attr);}});return attributes;}}]);return UpdatingElement;}(/*#__PURE__*/_wrapNativeSuper(HTMLElement));_a=finalized;/** * Marks class as having finished creating properties. */UpdatingElement[_a]=true;/** * @license * Copyright (c) 2017 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at * http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */var standardProperty=function standardProperty(options,element){// When decorating an accessor, pass it through and add property metadata. // Note, the `hasOwnProperty` check in `createProperty` ensures we don't // stomp over the user's accessor. if(element.kind==='method'&&element.descriptor&&!('value'in element.descriptor)){return Object.assign(Object.assign({},element),{finisher:function finisher(clazz){clazz.createProperty(element.key,options);}});}else{// createProperty() takes care of defining the property, but we still // must return some kind of descriptor, so return a descriptor for an // unused prototype field. The finisher calls createProperty(). return{kind:'field',key:Symbol(),placement:'own',descriptor:{},// When @babel/plugin-proposal-decorators implements initializers, // do this instead of the initializer below. See: // https://github.com/babel/babel/issues/9260 extras: [ // { // kind: 'initializer', // placement: 'own', // initializer: descriptor.initializer, // } // ], initializer:function initializer(){if(typeof element.initializer==='function'){this[element.key]=element.initializer.call(this);}},finisher:function finisher(clazz){clazz.createProperty(element.key,options);}};}};var legacyProperty=function legacyProperty(options,proto,name){proto.constructor.createProperty(name,options);};/** * A property decorator which creates a LitElement property which reflects a * corresponding attribute value. A [[`PropertyDeclaration`]] may optionally be * supplied to configure property features. * * This decorator should only be used for public fields. Private or protected * fields should use the [[`internalProperty`]] decorator. * * @example * ```ts * class MyElement { * @property({ type: Boolean }) * clicked = false; * } * ``` * @category Decorator * @ExportDecoratedItems */function property(options){// tslint:disable-next-line:no-any decorator return function(protoOrDescriptor,name){return name!==undefined?legacyProperty(options,protoOrDescriptor,name):standardProperty(options,protoOrDescriptor);};}/** @license Copyright (c) 2019 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /** * Whether the current browser supports `adoptedStyleSheets`. */var supportsAdoptingStyleSheets=window.ShadowRoot&&(window.ShadyCSS===undefined||window.ShadyCSS.nativeShadow)&&'adoptedStyleSheets'in Document.prototype&&'replace'in CSSStyleSheet.prototype;/** * @license * Copyright (c) 2017 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at * http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ // IMPORTANT: do not change the property name or the assignment expression. // This line will be used in regexes to search for LitElement usage. // TODO(justinfagnani): inject version number at build time (window['litElementVersions']||(window['litElementVersions']=[])).push('2.4.0');var HAS_WEBXR_DEVICE_API=navigator.xr!=null&&self.XRSession!=null&&navigator.xr.isSessionSupported!=null;var HAS_WEBXR_HIT_TEST_API=HAS_WEBXR_DEVICE_API&&self.XRSession.prototype.requestHitTestSource;var HAS_RESIZE_OBSERVER=self.ResizeObserver!=null;var HAS_INTERSECTION_OBSERVER=self.IntersectionObserver!=null;var IS_WEBXR_AR_CANDIDATE=HAS_WEBXR_HIT_TEST_API;var IS_MOBILE=function(){var userAgent=navigator.userAgent||navigator.vendor||self.opera;var check=false;if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(userAgent)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(userAgent.substr(0,4))){check=true;}return check;}();var IS_CHROMEOS=/\bCrOS\b/.test(navigator.userAgent);var USE_OFFSCREEN_CANVAS=false;var IS_ANDROID=/android/i.test(navigator.userAgent);var IS_IOS=/iPad|iPhone|iPod/.test(navigator.userAgent)&&!self.MSStream||navigator.platform==='MacIntel'&&navigator.maxTouchPoints>1;var IS_AR_QUICKLOOK_CANDIDATE=function(){var tempAnchor=document.createElement('a');return Boolean(tempAnchor.relList&&tempAnchor.relList.supports&&tempAnchor.relList.supports('ar'));}();var IS_SAFARI=/Safari\//.test(navigator.userAgent);var IS_FIREFOX=/firefox/i.test(navigator.userAgent);var IS_OCULUS=/OculusBrowser/.test(navigator.userAgent);var IS_IOS_CHROME=IS_IOS&&/CriOS\//.test(navigator.userAgent);var IS_IOS_SAFARI=IS_IOS&&IS_SAFARI;var IS_SCENEVIEWER_CANDIDATE=IS_ANDROID&&!IS_FIREFOX&&!IS_OCULUS;var CloseIcon="\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n";var ControlsPrompt="\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n";var ARGlyph="\n\n\n\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\n\n";var template=document.createElement('template');template.innerHTML="\n\n
\n
\n \n
\n\n \n
\n \n \n \n
\n\n \n\n
\n
\n \n ").concat(ControlsPrompt,"\n \n
\n
\n\n
\n \n\n
\n \n
\n
\n
\n
\n
\n
\n \n \n
\n
");var makeTemplate=function makeTemplate(tagName){var clone=document.createElement('template');clone.innerHTML=template.innerHTML;if(window.ShadyCSS){window.ShadyCSS.prepareTemplate(clone,tagName);}return clone;};// threejs.org/license var REVISION='121';var CullFaceNone=0;var CullFaceBack=1;var CullFaceFront=2;var PCFShadowMap=1;var PCFSoftShadowMap=2;var VSMShadowMap=3;var FrontSide=0;var BackSide=1;var DoubleSide=2;var FlatShading=1;var NoBlending=0;var NormalBlending=1;var AdditiveBlending=2;var SubtractiveBlending=3;var MultiplyBlending=4;var CustomBlending=5;var AddEquation=100;var SubtractEquation=101;var ReverseSubtractEquation=102;var MinEquation=103;var MaxEquation=104;var ZeroFactor=200;var OneFactor=201;var SrcColorFactor=202;var OneMinusSrcColorFactor=203;var SrcAlphaFactor=204;var OneMinusSrcAlphaFactor=205;var DstAlphaFactor=206;var OneMinusDstAlphaFactor=207;var DstColorFactor=208;var OneMinusDstColorFactor=209;var SrcAlphaSaturateFactor=210;var NeverDepth=0;var AlwaysDepth=1;var LessDepth=2;var LessEqualDepth=3;var EqualDepth=4;var GreaterEqualDepth=5;var GreaterDepth=6;var NotEqualDepth=7;var MultiplyOperation=0;var MixOperation=1;var AddOperation=2;var NoToneMapping=0;var LinearToneMapping=1;var ReinhardToneMapping=2;var CineonToneMapping=3;var ACESFilmicToneMapping=4;var CustomToneMapping=5;var UVMapping=300;var CubeReflectionMapping=301;var CubeRefractionMapping=302;var EquirectangularReflectionMapping=303;var EquirectangularRefractionMapping=304;var CubeUVReflectionMapping=306;var CubeUVRefractionMapping=307;var RepeatWrapping=1000;var ClampToEdgeWrapping=1001;var MirroredRepeatWrapping=1002;var NearestFilter=1003;var NearestMipmapNearestFilter=1004;var NearestMipmapLinearFilter=1005;var LinearFilter=1006;var LinearMipmapNearestFilter=1007;var LinearMipmapLinearFilter=1008;var UnsignedByteType=1009;var ByteType=1010;var ShortType=1011;var UnsignedShortType=1012;var IntType=1013;var UnsignedIntType=1014;var FloatType=1015;var HalfFloatType=1016;var UnsignedShort4444Type=1017;var UnsignedShort5551Type=1018;var UnsignedShort565Type=1019;var UnsignedInt248Type=1020;var AlphaFormat=1021;var RGBFormat=1022;var RGBAFormat=1023;var LuminanceFormat=1024;var LuminanceAlphaFormat=1025;var RGBEFormat=RGBAFormat;var DepthFormat=1026;var DepthStencilFormat=1027;var RedFormat=1028;var RedIntegerFormat=1029;var RGFormat=1030;var RGIntegerFormat=1031;var RGBIntegerFormat=1032;var RGBAIntegerFormat=1033;var RGB_S3TC_DXT1_Format=33776;var RGBA_S3TC_DXT1_Format=33777;var RGBA_S3TC_DXT3_Format=33778;var RGBA_S3TC_DXT5_Format=33779;var RGB_PVRTC_4BPPV1_Format=35840;var RGB_PVRTC_2BPPV1_Format=35841;var RGBA_PVRTC_4BPPV1_Format=35842;var RGBA_PVRTC_2BPPV1_Format=35843;var RGB_ETC1_Format=36196;var RGB_ETC2_Format=37492;var RGBA_ETC2_EAC_Format=37496;var RGBA_ASTC_4x4_Format=37808;var RGBA_ASTC_5x4_Format=37809;var RGBA_ASTC_5x5_Format=37810;var RGBA_ASTC_6x5_Format=37811;var RGBA_ASTC_6x6_Format=37812;var RGBA_ASTC_8x5_Format=37813;var RGBA_ASTC_8x6_Format=37814;var RGBA_ASTC_8x8_Format=37815;var RGBA_ASTC_10x5_Format=37816;var RGBA_ASTC_10x6_Format=37817;var RGBA_ASTC_10x8_Format=37818;var RGBA_ASTC_10x10_Format=37819;var RGBA_ASTC_12x10_Format=37820;var RGBA_ASTC_12x12_Format=37821;var RGBA_BPTC_Format=36492;var SRGB8_ALPHA8_ASTC_4x4_Format=37840;var SRGB8_ALPHA8_ASTC_5x4_Format=37841;var SRGB8_ALPHA8_ASTC_5x5_Format=37842;var SRGB8_ALPHA8_ASTC_6x5_Format=37843;var SRGB8_ALPHA8_ASTC_6x6_Format=37844;var SRGB8_ALPHA8_ASTC_8x5_Format=37845;var SRGB8_ALPHA8_ASTC_8x6_Format=37846;var SRGB8_ALPHA8_ASTC_8x8_Format=37847;var SRGB8_ALPHA8_ASTC_10x5_Format=37848;var SRGB8_ALPHA8_ASTC_10x6_Format=37849;var SRGB8_ALPHA8_ASTC_10x8_Format=37850;var SRGB8_ALPHA8_ASTC_10x10_Format=37851;var SRGB8_ALPHA8_ASTC_12x10_Format=37852;var SRGB8_ALPHA8_ASTC_12x12_Format=37853;var LoopOnce=2200;var LoopRepeat=2201;var LoopPingPong=2202;var InterpolateDiscrete=2300;var InterpolateLinear=2301;var InterpolateSmooth=2302;var ZeroCurvatureEnding=2400;var ZeroSlopeEnding=2401;var WrapAroundEnding=2402;var NormalAnimationBlendMode=2500;var AdditiveAnimationBlendMode=2501;var TrianglesDrawMode=0;var TriangleStripDrawMode=1;var TriangleFanDrawMode=2;var LinearEncoding=3000;var sRGBEncoding=3001;var GammaEncoding=3007;var RGBEEncoding=3002;var LogLuvEncoding=3003;var RGBM7Encoding=3004;var RGBM16Encoding=3005;var RGBDEncoding=3006;var BasicDepthPacking=3200;var RGBADepthPacking=3201;var TangentSpaceNormalMap=0;var ObjectSpaceNormalMap=1;var KeepStencilOp=7680;var AlwaysStencilFunc=519;var StaticDrawUsage=35044;var DynamicDrawUsage=35048;var GLSL3="300 es";/** * https://github.com/mrdoob/eventdispatcher.js/ */function EventDispatcher(){}Object.assign(EventDispatcher.prototype,{addEventListener:function addEventListener(type,listener){if(this._listeners===undefined)this._listeners={};var listeners=this._listeners;if(listeners[type]===undefined){listeners[type]=[];}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener);}},hasEventListener:function hasEventListener(type,listener){if(this._listeners===undefined)return false;var listeners=this._listeners;return listeners[type]!==undefined&&listeners[type].indexOf(listener)!==-1;},removeEventListener:function removeEventListener(type,listener){if(this._listeners===undefined)return;var listeners=this._listeners;var listenerArray=listeners[type];if(listenerArray!==undefined){var index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1);}}},dispatchEvent:function dispatchEvent(event){if(this._listeners===undefined)return;var listeners=this._listeners;var listenerArray=listeners[event.type];if(listenerArray!==undefined){event.target=this;// Make a copy, in case listeners are removed while iterating. var array=listenerArray.slice(0);for(var i=0,l=array.length;i>8&0xff]+_lut[d0>>16&0xff]+_lut[d0>>24&0xff]+'-'+_lut[d1&0xff]+_lut[d1>>8&0xff]+'-'+_lut[d1>>16&0x0f|0x40]+_lut[d1>>24&0xff]+'-'+_lut[d2&0x3f|0x80]+_lut[d2>>8&0xff]+'-'+_lut[d2>>16&0xff]+_lut[d2>>24&0xff]+_lut[d3&0xff]+_lut[d3>>8&0xff]+_lut[d3>>16&0xff]+_lut[d3>>24&0xff];// .toUpperCase() here flattens concatenated strings to save heap memory space. return uuid.toUpperCase();},clamp:function clamp(value,min,max){return Math.max(min,Math.min(max,value));},// compute euclidian modulo of m % n // https://en.wikipedia.org/wiki/Modulo_operation euclideanModulo:function euclideanModulo(n,m){return(n%m+m)%m;},// Linear mapping from range to range mapLinear:function mapLinear(x,a1,a2,b1,b2){return b1+(x-a1)*(b2-b1)/(a2-a1);},// https://en.wikipedia.org/wiki/Linear_interpolation lerp:function lerp(x,y,t){return(1-t)*x+t*y;},// http://en.wikipedia.org/wiki/Smoothstep smoothstep:function smoothstep(x,min,max){if(x<=min)return 0;if(x>=max)return 1;x=(x-min)/(max-min);return x*x*(3-2*x);},smootherstep:function smootherstep(x,min,max){if(x<=min)return 0;if(x>=max)return 1;x=(x-min)/(max-min);return x*x*x*(x*(x*6-15)+10);},// Random integer from interval randInt:function randInt(low,high){return low+Math.floor(Math.random()*(high-low+1));},// Random float from interval randFloat:function randFloat(low,high){return low+Math.random()*(high-low);},// Random float from <-range/2, range/2> interval randFloatSpread:function randFloatSpread(range){return range*(0.5-Math.random());},// Deterministic pseudo-random float in the interval [ 0, 1 ] seededRandom:function seededRandom(s){if(s!==undefined)_seed=s%2147483647;// Park-Miller algorithm _seed=_seed*16807%2147483647;return(_seed-1)/2147483646;},degToRad:function degToRad(degrees){return degrees*MathUtils.DEG2RAD;},radToDeg:function radToDeg(radians){return radians*MathUtils.RAD2DEG;},isPowerOfTwo:function isPowerOfTwo(value){return(value&value-1)===0&&value!==0;},ceilPowerOfTwo:function ceilPowerOfTwo(value){return Math.pow(2,Math.ceil(Math.log(value)/Math.LN2));},floorPowerOfTwo:function floorPowerOfTwo(value){return Math.pow(2,Math.floor(Math.log(value)/Math.LN2));},setQuaternionFromProperEuler:function setQuaternionFromProperEuler(q,a,b,c,order){// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles // rotations are applied to the axes in the order specified by 'order' // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' // angles are in radians var cos=Math.cos;var sin=Math.sin;var c2=cos(b/2);var s2=sin(b/2);var c13=cos((a+c)/2);var s13=sin((a+c)/2);var c1_3=cos((a-c)/2);var s1_3=sin((a-c)/2);var c3_1=cos((c-a)/2);var s3_1=sin((c-a)/2);switch(order){case'XYX':q.set(c2*s13,s2*c1_3,s2*s1_3,c2*c13);break;case'YZY':q.set(s2*s1_3,c2*s13,s2*c1_3,c2*c13);break;case'ZXZ':q.set(s2*c1_3,s2*s1_3,c2*s13,c2*c13);break;case'XZX':q.set(c2*s13,s2*s3_1,s2*c3_1,c2*c13);break;case'YXY':q.set(s2*c3_1,c2*s13,s2*s3_1,c2*c13);break;case'ZYZ':q.set(s2*s3_1,s2*c3_1,c2*s13,c2*c13);break;default:console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: '+order);}}};var Vector2=/*#__PURE__*/function(){function Vector2(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;_classCallCheck(this,Vector2);Object.defineProperty(this,'isVector2',{value:true});this.x=x;this.y=y;}_createClass(Vector2,[{key:"set",value:function set(x,y){this.x=x;this.y=y;return this;}},{key:"setScalar",value:function setScalar(scalar){this.x=scalar;this.y=scalar;return this;}},{key:"setX",value:function setX(x){this.x=x;return this;}},{key:"setY",value:function setY(y){this.y=y;return this;}},{key:"setComponent",value:function setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;default:throw new Error('index is out of range: '+index);}return this;}},{key:"getComponent",value:function getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;default:throw new Error('index is out of range: '+index);}}},{key:"clone",value:function clone(){return new this.constructor(this.x,this.y);}},{key:"copy",value:function copy(v){this.x=v.x;this.y=v.y;return this;}},{key:"add",value:function add(v,w){if(w!==undefined){console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');return this.addVectors(v,w);}this.x+=v.x;this.y+=v.y;return this;}},{key:"addScalar",value:function addScalar(s){this.x+=s;this.y+=s;return this;}},{key:"addVectors",value:function addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this;}},{key:"addScaledVector",value:function addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;return this;}},{key:"sub",value:function sub(v,w){if(w!==undefined){console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');return this.subVectors(v,w);}this.x-=v.x;this.y-=v.y;return this;}},{key:"subScalar",value:function subScalar(s){this.x-=s;this.y-=s;return this;}},{key:"subVectors",value:function subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this;}},{key:"multiply",value:function multiply(v){this.x*=v.x;this.y*=v.y;return this;}},{key:"multiplyScalar",value:function multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;return this;}},{key:"divide",value:function divide(v){this.x/=v.x;this.y/=v.y;return this;}},{key:"divideScalar",value:function divideScalar(scalar){return this.multiplyScalar(1/scalar);}},{key:"applyMatrix3",value:function applyMatrix3(m){var x=this.x,y=this.y;var e=m.elements;this.x=e[0]*x+e[3]*y+e[6];this.y=e[1]*x+e[4]*y+e[7];return this;}},{key:"min",value:function min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);return this;}},{key:"max",value:function max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);return this;}},{key:"clamp",value:function clamp(min,max){// assumes min < max, componentwise this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));return this;}},{key:"clampScalar",value:function clampScalar(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));return this;}},{key:"clampLength",value:function clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));}},{key:"floor",value:function floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this;}},{key:"ceil",value:function ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this;}},{key:"round",value:function round(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this;}},{key:"roundToZero",value:function roundToZero(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);return this;}},{key:"negate",value:function negate(){this.x=-this.x;this.y=-this.y;return this;}},{key:"dot",value:function dot(v){return this.x*v.x+this.y*v.y;}},{key:"cross",value:function cross(v){return this.x*v.y-this.y*v.x;}},{key:"lengthSq",value:function lengthSq(){return this.x*this.x+this.y*this.y;}},{key:"length",value:function length(){return Math.sqrt(this.x*this.x+this.y*this.y);}},{key:"manhattanLength",value:function manhattanLength(){return Math.abs(this.x)+Math.abs(this.y);}},{key:"normalize",value:function normalize(){return this.divideScalar(this.length()||1);}},{key:"angle",value:function angle(){// computes the angle in radians with respect to the positive x-axis var angle=Math.atan2(-this.y,-this.x)+Math.PI;return angle;}},{key:"distanceTo",value:function distanceTo(v){return Math.sqrt(this.distanceToSquared(v));}},{key:"distanceToSquared",value:function distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y;return dx*dx+dy*dy;}},{key:"manhattanDistanceTo",value:function manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y);}},{key:"setLength",value:function setLength(length){return this.normalize().multiplyScalar(length);}},{key:"lerp",value:function lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;return this;}},{key:"lerpVectors",value:function lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;return this;}},{key:"equals",value:function equals(v){return v.x===this.x&&v.y===this.y;}},{key:"fromArray",value:function fromArray(array,offset){if(offset===undefined)offset=0;this.x=array[offset];this.y=array[offset+1];return this;}},{key:"toArray",value:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this.x;array[offset+1]=this.y;return array;}},{key:"fromBufferAttribute",value:function fromBufferAttribute(attribute,index,offset){if(offset!==undefined){console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');}this.x=attribute.getX(index);this.y=attribute.getY(index);return this;}},{key:"rotateAround",value:function rotateAround(center,angle){var c=Math.cos(angle),s=Math.sin(angle);var x=this.x-center.x;var y=this.y-center.y;this.x=x*c-y*s+center.x;this.y=x*s+y*c+center.y;return this;}},{key:"random",value:function random(){this.x=Math.random();this.y=Math.random();return this;}},{key:"width",get:function get(){return this.x;},set:function set(value){this.x=value;}},{key:"height",get:function get(){return this.y;},set:function set(value){this.y=value;}}]);return Vector2;}();var Matrix3=/*#__PURE__*/function(){function Matrix3(){_classCallCheck(this,Matrix3);Object.defineProperty(this,'isMatrix3',{value:true});this.elements=[1,0,0,0,1,0,0,0,1];if(arguments.length>0){console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');}}_createClass(Matrix3,[{key:"set",value:function set(n11,n12,n13,n21,n22,n23,n31,n32,n33){var te=this.elements;te[0]=n11;te[1]=n21;te[2]=n31;te[3]=n12;te[4]=n22;te[5]=n32;te[6]=n13;te[7]=n23;te[8]=n33;return this;}},{key:"identity",value:function identity(){this.set(1,0,0,0,1,0,0,0,1);return this;}},{key:"clone",value:function clone(){return new this.constructor().fromArray(this.elements);}},{key:"copy",value:function copy(m){var te=this.elements;var me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];return this;}},{key:"extractBasis",value:function extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrix3Column(this,0);yAxis.setFromMatrix3Column(this,1);zAxis.setFromMatrix3Column(this,2);return this;}},{key:"setFromMatrix4",value:function setFromMatrix4(m){var me=m.elements;this.set(me[0],me[4],me[8],me[1],me[5],me[9],me[2],me[6],me[10]);return this;}},{key:"multiply",value:function multiply(m){return this.multiplyMatrices(this,m);}},{key:"premultiply",value:function premultiply(m){return this.multiplyMatrices(m,this);}},{key:"multiplyMatrices",value:function multiplyMatrices(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[3],a13=ae[6];var a21=ae[1],a22=ae[4],a23=ae[7];var a31=ae[2],a32=ae[5],a33=ae[8];var b11=be[0],b12=be[3],b13=be[6];var b21=be[1],b22=be[4],b23=be[7];var b31=be[2],b32=be[5],b33=be[8];te[0]=a11*b11+a12*b21+a13*b31;te[3]=a11*b12+a12*b22+a13*b32;te[6]=a11*b13+a12*b23+a13*b33;te[1]=a21*b11+a22*b21+a23*b31;te[4]=a21*b12+a22*b22+a23*b32;te[7]=a21*b13+a22*b23+a23*b33;te[2]=a31*b11+a32*b21+a33*b31;te[5]=a31*b12+a32*b22+a33*b32;te[8]=a31*b13+a32*b23+a33*b33;return this;}},{key:"multiplyScalar",value:function multiplyScalar(s){var te=this.elements;te[0]*=s;te[3]*=s;te[6]*=s;te[1]*=s;te[4]*=s;te[7]*=s;te[2]*=s;te[5]*=s;te[8]*=s;return this;}},{key:"determinant",value:function determinant(){var te=this.elements;var a=te[0],b=te[1],c=te[2],d=te[3],e=te[4],f=te[5],g=te[6],h=te[7],i=te[8];return a*e*i-a*f*h-b*d*i+b*f*g+c*d*h-c*e*g;}},{key:"getInverse",value:function getInverse(matrix,throwOnDegenerate){if(throwOnDegenerate!==undefined){console.warn("THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate.");}var me=matrix.elements,te=this.elements,n11=me[0],n21=me[1],n31=me[2],n12=me[3],n22=me[4],n32=me[5],n13=me[6],n23=me[7],n33=me[8],t11=n33*n22-n32*n23,t12=n32*n13-n33*n12,t13=n23*n12-n22*n13,det=n11*t11+n21*t12+n31*t13;if(det===0)return this.set(0,0,0,0,0,0,0,0,0);var detInv=1/det;te[0]=t11*detInv;te[1]=(n31*n23-n33*n21)*detInv;te[2]=(n32*n21-n31*n22)*detInv;te[3]=t12*detInv;te[4]=(n33*n11-n31*n13)*detInv;te[5]=(n31*n12-n32*n11)*detInv;te[6]=t13*detInv;te[7]=(n21*n13-n23*n11)*detInv;te[8]=(n22*n11-n21*n12)*detInv;return this;}},{key:"transpose",value:function transpose(){var tmp;var m=this.elements;tmp=m[1];m[1]=m[3];m[3]=tmp;tmp=m[2];m[2]=m[6];m[6]=tmp;tmp=m[5];m[5]=m[7];m[7]=tmp;return this;}},{key:"getNormalMatrix",value:function getNormalMatrix(matrix4){return this.setFromMatrix4(matrix4).getInverse(this).transpose();}},{key:"transposeIntoArray",value:function transposeIntoArray(r){var m=this.elements;r[0]=m[0];r[1]=m[3];r[2]=m[6];r[3]=m[1];r[4]=m[4];r[5]=m[7];r[6]=m[2];r[7]=m[5];r[8]=m[8];return this;}},{key:"setUvTransform",value:function setUvTransform(tx,ty,sx,sy,rotation,cx,cy){var c=Math.cos(rotation);var s=Math.sin(rotation);this.set(sx*c,sx*s,-sx*(c*cx+s*cy)+cx+tx,-sy*s,sy*c,-sy*(-s*cx+c*cy)+cy+ty,0,0,1);}},{key:"scale",value:function scale(sx,sy){var te=this.elements;te[0]*=sx;te[3]*=sx;te[6]*=sx;te[1]*=sy;te[4]*=sy;te[7]*=sy;return this;}},{key:"rotate",value:function rotate(theta){var c=Math.cos(theta);var s=Math.sin(theta);var te=this.elements;var a11=te[0],a12=te[3],a13=te[6];var a21=te[1],a22=te[4],a23=te[7];te[0]=c*a11+s*a21;te[3]=c*a12+s*a22;te[6]=c*a13+s*a23;te[1]=-s*a11+c*a21;te[4]=-s*a12+c*a22;te[7]=-s*a13+c*a23;return this;}},{key:"translate",value:function translate(tx,ty){var te=this.elements;te[0]+=tx*te[2];te[3]+=tx*te[5];te[6]+=tx*te[8];te[1]+=ty*te[2];te[4]+=ty*te[5];te[7]+=ty*te[8];return this;}},{key:"equals",value:function equals(matrix){var te=this.elements;var me=matrix.elements;for(var _i=0;_i<9;_i++){if(te[_i]!==me[_i])return false;}return true;}},{key:"fromArray",value:function fromArray(array,offset){if(offset===undefined)offset=0;for(var _i2=0;_i2<9;_i2++){this.elements[_i2]=array[_i2+offset];}return this;}},{key:"toArray",value:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;var te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];return array;}}]);return Matrix3;}();var _canvas;var ImageUtils={getDataURL:function getDataURL(image){if(/^data:/i.test(image.src)){return image.src;}if(typeof HTMLCanvasElement=='undefined'){return image.src;}var canvas;if(_instanceof(image,HTMLCanvasElement)){canvas=image;}else{if(_canvas===undefined)_canvas=document.createElementNS('http://www.w3.org/1999/xhtml','canvas');_canvas.width=image.width;_canvas.height=image.height;var context=_canvas.getContext('2d');if(_instanceof(image,ImageData)){context.putImageData(image,0,0);}else{context.drawImage(image,0,0,image.width,image.height);}canvas=_canvas;}if(canvas.width>2048||canvas.height>2048){return canvas.toDataURL('image/jpeg',0.6);}else{return canvas.toDataURL('image/png');}}};var textureId=0;function Texture(image,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding){Object.defineProperty(this,'id',{value:textureId++});this.uuid=MathUtils.generateUUID();this.name='';this.image=image!==undefined?image:Texture.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=mapping!==undefined?mapping:Texture.DEFAULT_MAPPING;this.wrapS=wrapS!==undefined?wrapS:ClampToEdgeWrapping;this.wrapT=wrapT!==undefined?wrapT:ClampToEdgeWrapping;this.magFilter=magFilter!==undefined?magFilter:LinearFilter;this.minFilter=minFilter!==undefined?minFilter:LinearMipmapLinearFilter;this.anisotropy=anisotropy!==undefined?anisotropy:1;this.format=format!==undefined?format:RGBAFormat;this.internalFormat=null;this.type=type!==undefined?type:UnsignedByteType;this.offset=new Vector2(0,0);this.repeat=new Vector2(1,1);this.center=new Vector2(0,0);this.rotation=0;this.matrixAutoUpdate=true;this.matrix=new Matrix3();this.generateMipmaps=true;this.premultiplyAlpha=false;this.flipY=true;this.unpackAlignment=4;// valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. // // Also changing the encoding after already used by a Material will not automatically make the Material // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. this.encoding=encoding!==undefined?encoding:LinearEncoding;this.version=0;this.onUpdate=null;}Texture.DEFAULT_IMAGE=undefined;Texture.DEFAULT_MAPPING=UVMapping;Texture.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:Texture,isTexture:true,updateMatrix:function updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y);},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(source){this.name=source.name;this.image=source.image;this.mipmaps=source.mipmaps.slice(0);this.mapping=source.mapping;this.wrapS=source.wrapS;this.wrapT=source.wrapT;this.magFilter=source.magFilter;this.minFilter=source.minFilter;this.anisotropy=source.anisotropy;this.format=source.format;this.internalFormat=source.internalFormat;this.type=source.type;this.offset.copy(source.offset);this.repeat.copy(source.repeat);this.center.copy(source.center);this.rotation=source.rotation;this.matrixAutoUpdate=source.matrixAutoUpdate;this.matrix.copy(source.matrix);this.generateMipmaps=source.generateMipmaps;this.premultiplyAlpha=source.premultiplyAlpha;this.flipY=source.flipY;this.unpackAlignment=source.unpackAlignment;this.encoding=source.encoding;return this;},toJSON:function toJSON(meta){var isRootObject=meta===undefined||typeof meta==='string';if(!isRootObject&&meta.textures[this.uuid]!==undefined){return meta.textures[this.uuid];}var output={metadata:{version:4.5,type:'Texture',generator:'Texture.toJSON'},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,type:this.type,encoding:this.encoding,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};if(this.image!==undefined){// TODO: Move to THREE.Image var image=this.image;if(image.uuid===undefined){image.uuid=MathUtils.generateUUID();// UGH }if(!isRootObject&&meta.images[image.uuid]===undefined){var url;if(Array.isArray(image)){// process array of images e.g. CubeTexture url=[];for(var _i3=0,l=image.length;_i31){switch(this.wrapS){case RepeatWrapping:uv.x=uv.x-Math.floor(uv.x);break;case ClampToEdgeWrapping:uv.x=uv.x<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.x)%2)===1){uv.x=Math.ceil(uv.x)-uv.x;}else{uv.x=uv.x-Math.floor(uv.x);}break;}}if(uv.y<0||uv.y>1){switch(this.wrapT){case RepeatWrapping:uv.y=uv.y-Math.floor(uv.y);break;case ClampToEdgeWrapping:uv.y=uv.y<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.y)%2)===1){uv.y=Math.ceil(uv.y)-uv.y;}else{uv.y=uv.y-Math.floor(uv.y);}break;}}if(this.flipY){uv.y=1-uv.y;}return uv;}});Object.defineProperty(Texture.prototype,"needsUpdate",{set:function set(value){if(value===true)this.version++;}});var Vector4=/*#__PURE__*/function(){function Vector4(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var w=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;_classCallCheck(this,Vector4);Object.defineProperty(this,'isVector4',{value:true});this.x=x;this.y=y;this.z=z;this.w=w;}_createClass(Vector4,[{key:"set",value:function set(x,y,z,w){this.x=x;this.y=y;this.z=z;this.w=w;return this;}},{key:"setScalar",value:function setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;this.w=scalar;return this;}},{key:"setX",value:function setX(x){this.x=x;return this;}},{key:"setY",value:function setY(y){this.y=y;return this;}},{key:"setZ",value:function setZ(z){this.z=z;return this;}},{key:"setW",value:function setW(w){this.w=w;return this;}},{key:"setComponent",value:function setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;case 3:this.w=value;break;default:throw new Error('index is out of range: '+index);}return this;}},{key:"getComponent",value:function getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error('index is out of range: '+index);}}},{key:"clone",value:function clone(){return new this.constructor(this.x,this.y,this.z,this.w);}},{key:"copy",value:function copy(v){this.x=v.x;this.y=v.y;this.z=v.z;this.w=v.w!==undefined?v.w:1;return this;}},{key:"add",value:function add(v,w){if(w!==undefined){console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');return this.addVectors(v,w);}this.x+=v.x;this.y+=v.y;this.z+=v.z;this.w+=v.w;return this;}},{key:"addScalar",value:function addScalar(s){this.x+=s;this.y+=s;this.z+=s;this.w+=s;return this;}},{key:"addVectors",value:function addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this;}},{key:"addScaledVector",value:function addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;this.w+=v.w*s;return this;}},{key:"sub",value:function sub(v,w){if(w!==undefined){console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');return this.subVectors(v,w);}this.x-=v.x;this.y-=v.y;this.z-=v.z;this.w-=v.w;return this;}},{key:"subScalar",value:function subScalar(s){this.x-=s;this.y-=s;this.z-=s;this.w-=s;return this;}},{key:"subVectors",value:function subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this;}},{key:"multiplyScalar",value:function multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;this.w*=scalar;return this;}},{key:"applyMatrix4",value:function applyMatrix4(m){var x=this.x,y=this.y,z=this.z,w=this.w;var e=m.elements;this.x=e[0]*x+e[4]*y+e[8]*z+e[12]*w;this.y=e[1]*x+e[5]*y+e[9]*z+e[13]*w;this.z=e[2]*x+e[6]*y+e[10]*z+e[14]*w;this.w=e[3]*x+e[7]*y+e[11]*z+e[15]*w;return this;}},{key:"divideScalar",value:function divideScalar(scalar){return this.multiplyScalar(1/scalar);}},{key:"setAxisAngleFromQuaternion",value:function setAxisAngleFromQuaternion(q){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm // q is assumed to be normalized this.w=2*Math.acos(q.w);var s=Math.sqrt(1-q.w*q.w);if(s<0.0001){this.x=1;this.y=0;this.z=0;}else{this.x=q.x/s;this.y=q.y/s;this.z=q.z/s;}return this;}},{key:"setAxisAngleFromRotationMatrix",value:function setAxisAngleFromRotationMatrix(m){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var angle,x,y,z;// variables for result var epsilon=0.01,// margin to allow for rounding errors epsilon2=0.1,// margin to distinguish between 0 and 180 degrees te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10];if(Math.abs(m12-m21)yy&&xx>zz){// m11 is the largest diagonal term if(xxzz){// m22 is the largest diagonal term if(yy0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var w=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;_classCallCheck(this,Quaternion);Object.defineProperty(this,'isQuaternion',{value:true});this._x=x;this._y=y;this._z=z;this._w=w;}_createClass(Quaternion,[{key:"set",value:function set(x,y,z,w){this._x=x;this._y=y;this._z=z;this._w=w;this._onChangeCallback();return this;}},{key:"clone",value:function clone(){return new this.constructor(this._x,this._y,this._z,this._w);}},{key:"copy",value:function copy(quaternion){this._x=quaternion.x;this._y=quaternion.y;this._z=quaternion.z;this._w=quaternion.w;this._onChangeCallback();return this;}},{key:"setFromEuler",value:function setFromEuler(euler,update){if(!(euler&&euler.isEuler)){throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');}var x=euler._x,y=euler._y,z=euler._z,order=euler._order;// http://www.mathworks.com/matlabcentral/fileexchange/ // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ // content/SpinCalc.m var cos=Math.cos;var sin=Math.sin;var c1=cos(x/2);var c2=cos(y/2);var c3=cos(z/2);var s1=sin(x/2);var s2=sin(y/2);var s3=sin(z/2);switch(order){case'XYZ':this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case'YXZ':this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;case'ZXY':this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case'ZYX':this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;case'YZX':this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case'XZY':this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;default:console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: '+order);}if(update!==false)this._onChangeCallback();return this;}},{key:"setFromAxisAngle",value:function setFromAxisAngle(axis,angle){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm // assumes axis is normalized var halfAngle=angle/2,s=Math.sin(halfAngle);this._x=axis.x*s;this._y=axis.y*s;this._z=axis.z*s;this._w=Math.cos(halfAngle);this._onChangeCallback();return this;}},{key:"setFromRotationMatrix",value:function setFromRotationMatrix(m){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10],trace=m11+m22+m33;if(trace>0){var s=0.5/Math.sqrt(trace+1.0);this._w=0.25/s;this._x=(m32-m23)*s;this._y=(m13-m31)*s;this._z=(m21-m12)*s;}else if(m11>m22&&m11>m33){var _s2=2.0*Math.sqrt(1.0+m11-m22-m33);this._w=(m32-m23)/_s2;this._x=0.25*_s2;this._y=(m12+m21)/_s2;this._z=(m13+m31)/_s2;}else if(m22>m33){var _s3=2.0*Math.sqrt(1.0+m22-m11-m33);this._w=(m13-m31)/_s3;this._x=(m12+m21)/_s3;this._y=0.25*_s3;this._z=(m23+m32)/_s3;}else{var _s4=2.0*Math.sqrt(1.0+m33-m11-m22);this._w=(m21-m12)/_s4;this._x=(m13+m31)/_s4;this._y=(m23+m32)/_s4;this._z=0.25*_s4;}this._onChangeCallback();return this;}},{key:"setFromUnitVectors",value:function setFromUnitVectors(vFrom,vTo){// assumes direction vectors vFrom and vTo are normalized var EPS=0.000001;var r=vFrom.dot(vTo)+1;if(rMath.abs(vFrom.z)){this._x=-vFrom.y;this._y=vFrom.x;this._z=0;this._w=r;}else{this._x=0;this._y=-vFrom.z;this._z=vFrom.y;this._w=r;}}else{// crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 this._x=vFrom.y*vTo.z-vFrom.z*vTo.y;this._y=vFrom.z*vTo.x-vFrom.x*vTo.z;this._z=vFrom.x*vTo.y-vFrom.y*vTo.x;this._w=r;}return this.normalize();}},{key:"angleTo",value:function angleTo(q){return 2*Math.acos(Math.abs(MathUtils.clamp(this.dot(q),-1,1)));}},{key:"rotateTowards",value:function rotateTowards(q,step){var angle=this.angleTo(q);if(angle===0)return this;var t=Math.min(1,step/angle);this.slerp(q,t);return this;}},{key:"identity",value:function identity(){return this.set(0,0,0,1);}},{key:"inverse",value:function inverse(){// quaternion is assumed to have unit length return this.conjugate();}},{key:"conjugate",value:function conjugate(){this._x*=-1;this._y*=-1;this._z*=-1;this._onChangeCallback();return this;}},{key:"dot",value:function dot(v){return this._x*v._x+this._y*v._y+this._z*v._z+this._w*v._w;}},{key:"lengthSq",value:function lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w;}},{key:"length",value:function length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w);}},{key:"normalize",value:function normalize(){var l=this.length();if(l===0){this._x=0;this._y=0;this._z=0;this._w=1;}else{l=1/l;this._x=this._x*l;this._y=this._y*l;this._z=this._z*l;this._w=this._w*l;}this._onChangeCallback();return this;}},{key:"multiply",value:function multiply(q,p){if(p!==undefined){console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');return this.multiplyQuaternions(q,p);}return this.multiplyQuaternions(this,q);}},{key:"premultiply",value:function premultiply(q){return this.multiplyQuaternions(q,this);}},{key:"multiplyQuaternions",value:function multiplyQuaternions(a,b){// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm var qax=a._x,qay=a._y,qaz=a._z,qaw=a._w;var qbx=b._x,qby=b._y,qbz=b._z,qbw=b._w;this._x=qax*qbw+qaw*qbx+qay*qbz-qaz*qby;this._y=qay*qbw+qaw*qby+qaz*qbx-qax*qbz;this._z=qaz*qbw+qaw*qbz+qax*qby-qay*qbx;this._w=qaw*qbw-qax*qbx-qay*qby-qaz*qbz;this._onChangeCallback();return this;}},{key:"slerp",value:function slerp(qb,t){if(t===0)return this;if(t===1)return this.copy(qb);var x=this._x,y=this._y,z=this._z,w=this._w;// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ var cosHalfTheta=w*qb._w+x*qb._x+y*qb._y+z*qb._z;if(cosHalfTheta<0){this._w=-qb._w;this._x=-qb._x;this._y=-qb._y;this._z=-qb._z;cosHalfTheta=-cosHalfTheta;}else{this.copy(qb);}if(cosHalfTheta>=1.0){this._w=w;this._x=x;this._y=y;this._z=z;return this;}var sqrSinHalfTheta=1.0-cosHalfTheta*cosHalfTheta;if(sqrSinHalfTheta<=Number.EPSILON){var s=1-t;this._w=s*w+t*this._w;this._x=s*x+t*this._x;this._y=s*y+t*this._y;this._z=s*z+t*this._z;this.normalize();this._onChangeCallback();return this;}var sinHalfTheta=Math.sqrt(sqrSinHalfTheta);var halfTheta=Math.atan2(sinHalfTheta,cosHalfTheta);var ratioA=Math.sin((1-t)*halfTheta)/sinHalfTheta,ratioB=Math.sin(t*halfTheta)/sinHalfTheta;this._w=w*ratioA+this._w*ratioB;this._x=x*ratioA+this._x*ratioB;this._y=y*ratioA+this._y*ratioB;this._z=z*ratioA+this._z*ratioB;this._onChangeCallback();return this;}},{key:"equals",value:function equals(quaternion){return quaternion._x===this._x&&quaternion._y===this._y&&quaternion._z===this._z&&quaternion._w===this._w;}},{key:"fromArray",value:function fromArray(array,offset){if(offset===undefined)offset=0;this._x=array[offset];this._y=array[offset+1];this._z=array[offset+2];this._w=array[offset+3];this._onChangeCallback();return this;}},{key:"toArray",value:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._w;return array;}},{key:"fromBufferAttribute",value:function fromBufferAttribute(attribute,index){this._x=attribute.getX(index);this._y=attribute.getY(index);this._z=attribute.getZ(index);this._w=attribute.getW(index);return this;}},{key:"_onChange",value:function _onChange(callback){this._onChangeCallback=callback;return this;}},{key:"_onChangeCallback",value:function _onChangeCallback(){}},{key:"x",get:function get(){return this._x;},set:function set(value){this._x=value;this._onChangeCallback();}},{key:"y",get:function get(){return this._y;},set:function set(value){this._y=value;this._onChangeCallback();}},{key:"z",get:function get(){return this._z;},set:function set(value){this._z=value;this._onChangeCallback();}},{key:"w",get:function get(){return this._w;},set:function set(value){this._w=value;this._onChangeCallback();}}],[{key:"slerp",value:function slerp(qa,qb,qm,t){return qm.copy(qa).slerp(qb,t);}},{key:"slerpFlat",value:function slerpFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1,t){// fuzz-free, array-based Quaternion SLERP operation var x0=src0[srcOffset0+0],y0=src0[srcOffset0+1],z0=src0[srcOffset0+2],w0=src0[srcOffset0+3];var x1=src1[srcOffset1+0],y1=src1[srcOffset1+1],z1=src1[srcOffset1+2],w1=src1[srcOffset1+3];if(w0!==w1||x0!==x1||y0!==y1||z0!==z1){var s=1-t;var cos=x0*x1+y0*y1+z0*z1+w0*w1,dir=cos>=0?1:-1,sqrSin=1-cos*cos;// Skip the Slerp for tiny steps to avoid numeric problems: if(sqrSin>Number.EPSILON){var sin=Math.sqrt(sqrSin),len=Math.atan2(sin,cos*dir);s=Math.sin(s*len)/sin;t=Math.sin(t*len)/sin;}var tDir=t*dir;x0=x0*s+x1*tDir;y0=y0*s+y1*tDir;z0=z0*s+z1*tDir;w0=w0*s+w1*tDir;// Normalize in case we just did a lerp: if(s===1-t){var f=1/Math.sqrt(x0*x0+y0*y0+z0*z0+w0*w0);x0*=f;y0*=f;z0*=f;w0*=f;}}dst[dstOffset]=x0;dst[dstOffset+1]=y0;dst[dstOffset+2]=z0;dst[dstOffset+3]=w0;}},{key:"multiplyQuaternionsFlat",value:function multiplyQuaternionsFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1){var x0=src0[srcOffset0];var y0=src0[srcOffset0+1];var z0=src0[srcOffset0+2];var w0=src0[srcOffset0+3];var x1=src1[srcOffset1];var y1=src1[srcOffset1+1];var z1=src1[srcOffset1+2];var w1=src1[srcOffset1+3];dst[dstOffset]=x0*w1+w0*x1+y0*z1-z0*y1;dst[dstOffset+1]=y0*w1+w0*y1+z0*x1-x0*z1;dst[dstOffset+2]=z0*w1+w0*z1+x0*y1-y0*x1;dst[dstOffset+3]=w0*w1-x0*x1-y0*y1-z0*z1;return dst;}}]);return Quaternion;}();var Vector3=/*#__PURE__*/function(){function Vector3(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;_classCallCheck(this,Vector3);Object.defineProperty(this,'isVector3',{value:true});this.x=x;this.y=y;this.z=z;}_createClass(Vector3,[{key:"set",value:function set(x,y,z){if(z===undefined)z=this.z;// sprite.scale.set(x,y) this.x=x;this.y=y;this.z=z;return this;}},{key:"setScalar",value:function setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;return this;}},{key:"setX",value:function setX(x){this.x=x;return this;}},{key:"setY",value:function setY(y){this.y=y;return this;}},{key:"setZ",value:function setZ(z){this.z=z;return this;}},{key:"setComponent",value:function setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;default:throw new Error('index is out of range: '+index);}return this;}},{key:"getComponent",value:function getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error('index is out of range: '+index);}}},{key:"clone",value:function clone(){return new this.constructor(this.x,this.y,this.z);}},{key:"copy",value:function copy(v){this.x=v.x;this.y=v.y;this.z=v.z;return this;}},{key:"add",value:function add(v,w){if(w!==undefined){console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');return this.addVectors(v,w);}this.x+=v.x;this.y+=v.y;this.z+=v.z;return this;}},{key:"addScalar",value:function addScalar(s){this.x+=s;this.y+=s;this.z+=s;return this;}},{key:"addVectors",value:function addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this;}},{key:"addScaledVector",value:function addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;return this;}},{key:"sub",value:function sub(v,w){if(w!==undefined){console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');return this.subVectors(v,w);}this.x-=v.x;this.y-=v.y;this.z-=v.z;return this;}},{key:"subScalar",value:function subScalar(s){this.x-=s;this.y-=s;this.z-=s;return this;}},{key:"subVectors",value:function subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this;}},{key:"multiply",value:function multiply(v,w){if(w!==undefined){console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');return this.multiplyVectors(v,w);}this.x*=v.x;this.y*=v.y;this.z*=v.z;return this;}},{key:"multiplyScalar",value:function multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;return this;}},{key:"multiplyVectors",value:function multiplyVectors(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this;}},{key:"applyEuler",value:function applyEuler(euler){if(!(euler&&euler.isEuler)){console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');}return this.applyQuaternion(_quaternion.setFromEuler(euler));}},{key:"applyAxisAngle",value:function applyAxisAngle(axis,angle){return this.applyQuaternion(_quaternion.setFromAxisAngle(axis,angle));}},{key:"applyMatrix3",value:function applyMatrix3(m){var x=this.x,y=this.y,z=this.z;var e=m.elements;this.x=e[0]*x+e[3]*y+e[6]*z;this.y=e[1]*x+e[4]*y+e[7]*z;this.z=e[2]*x+e[5]*y+e[8]*z;return this;}},{key:"applyNormalMatrix",value:function applyNormalMatrix(m){return this.applyMatrix3(m).normalize();}},{key:"applyMatrix4",value:function applyMatrix4(m){var x=this.x,y=this.y,z=this.z;var e=m.elements;var w=1/(e[3]*x+e[7]*y+e[11]*z+e[15]);this.x=(e[0]*x+e[4]*y+e[8]*z+e[12])*w;this.y=(e[1]*x+e[5]*y+e[9]*z+e[13])*w;this.z=(e[2]*x+e[6]*y+e[10]*z+e[14])*w;return this;}},{key:"applyQuaternion",value:function applyQuaternion(q){var x=this.x,y=this.y,z=this.z;var qx=q.x,qy=q.y,qz=q.z,qw=q.w;// calculate quat * vector var ix=qw*x+qy*z-qz*y;var iy=qw*y+qz*x-qx*z;var iz=qw*z+qx*y-qy*x;var iw=-qx*x-qy*y-qz*z;// calculate result * inverse quat this.x=ix*qw+iw*-qx+iy*-qz-iz*-qy;this.y=iy*qw+iw*-qy+iz*-qx-ix*-qz;this.z=iz*qw+iw*-qz+ix*-qy-iy*-qx;return this;}},{key:"project",value:function project(camera){return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);}},{key:"unproject",value:function unproject(camera){return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);}},{key:"transformDirection",value:function transformDirection(m){// input: THREE.Matrix4 affine matrix // vector interpreted as a direction var x=this.x,y=this.y,z=this.z;var e=m.elements;this.x=e[0]*x+e[4]*y+e[8]*z;this.y=e[1]*x+e[5]*y+e[9]*z;this.z=e[2]*x+e[6]*y+e[10]*z;return this.normalize();}},{key:"divide",value:function divide(v){this.x/=v.x;this.y/=v.y;this.z/=v.z;return this;}},{key:"divideScalar",value:function divideScalar(scalar){return this.multiplyScalar(1/scalar);}},{key:"min",value:function min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);this.z=Math.min(this.z,v.z);return this;}},{key:"max",value:function max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);this.z=Math.max(this.z,v.z);return this;}},{key:"clamp",value:function clamp(min,max){// assumes min < max, componentwise this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));this.z=Math.max(min.z,Math.min(max.z,this.z));return this;}},{key:"clampScalar",value:function clampScalar(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));this.z=Math.max(minVal,Math.min(maxVal,this.z));return this;}},{key:"clampLength",value:function clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));}},{key:"floor",value:function floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this;}},{key:"ceil",value:function ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this;}},{key:"round",value:function round(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this;}},{key:"roundToZero",value:function roundToZero(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z);return this;}},{key:"negate",value:function negate(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this;}},{key:"dot",value:function dot(v){return this.x*v.x+this.y*v.y+this.z*v.z;}// TODO lengthSquared? },{key:"lengthSq",value:function lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z;}},{key:"length",value:function length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);}},{key:"manhattanLength",value:function manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z);}},{key:"normalize",value:function normalize(){return this.divideScalar(this.length()||1);}},{key:"setLength",value:function setLength(length){return this.normalize().multiplyScalar(length);}},{key:"lerp",value:function lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;this.z+=(v.z-this.z)*alpha;return this;}},{key:"lerpVectors",value:function lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;this.z=v1.z+(v2.z-v1.z)*alpha;return this;}},{key:"cross",value:function cross(v,w){if(w!==undefined){console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');return this.crossVectors(v,w);}return this.crossVectors(this,v);}},{key:"crossVectors",value:function crossVectors(a,b){var ax=a.x,ay=a.y,az=a.z;var bx=b.x,by=b.y,bz=b.z;this.x=ay*bz-az*by;this.y=az*bx-ax*bz;this.z=ax*by-ay*bx;return this;}},{key:"projectOnVector",value:function projectOnVector(v){var denominator=v.lengthSq();if(denominator===0)return this.set(0,0,0);var scalar=v.dot(this)/denominator;return this.copy(v).multiplyScalar(scalar);}},{key:"projectOnPlane",value:function projectOnPlane(planeNormal){_vector.copy(this).projectOnVector(planeNormal);return this.sub(_vector);}},{key:"reflect",value:function reflect(normal){// reflect incident vector off plane orthogonal to normal // normal is assumed to have unit length return this.sub(_vector.copy(normal).multiplyScalar(2*this.dot(normal)));}},{key:"angleTo",value:function angleTo(v){var denominator=Math.sqrt(this.lengthSq()*v.lengthSq());if(denominator===0)return Math.PI/2;var theta=this.dot(v)/denominator;// clamp, to handle numerical problems return Math.acos(MathUtils.clamp(theta,-1,1));}},{key:"distanceTo",value:function distanceTo(v){return Math.sqrt(this.distanceToSquared(v));}},{key:"distanceToSquared",value:function distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y,dz=this.z-v.z;return dx*dx+dy*dy+dz*dz;}},{key:"manhattanDistanceTo",value:function manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)+Math.abs(this.z-v.z);}},{key:"setFromSpherical",value:function setFromSpherical(s){return this.setFromSphericalCoords(s.radius,s.phi,s.theta);}},{key:"setFromSphericalCoords",value:function setFromSphericalCoords(radius,phi,theta){var sinPhiRadius=Math.sin(phi)*radius;this.x=sinPhiRadius*Math.sin(theta);this.y=Math.cos(phi)*radius;this.z=sinPhiRadius*Math.cos(theta);return this;}},{key:"setFromCylindrical",value:function setFromCylindrical(c){return this.setFromCylindricalCoords(c.radius,c.theta,c.y);}},{key:"setFromCylindricalCoords",value:function setFromCylindricalCoords(radius,theta,y){this.x=radius*Math.sin(theta);this.y=y;this.z=radius*Math.cos(theta);return this;}},{key:"setFromMatrixPosition",value:function setFromMatrixPosition(m){var e=m.elements;this.x=e[12];this.y=e[13];this.z=e[14];return this;}},{key:"setFromMatrixScale",value:function setFromMatrixScale(m){var sx=this.setFromMatrixColumn(m,0).length();var sy=this.setFromMatrixColumn(m,1).length();var sz=this.setFromMatrixColumn(m,2).length();this.x=sx;this.y=sy;this.z=sz;return this;}},{key:"setFromMatrixColumn",value:function setFromMatrixColumn(m,index){return this.fromArray(m.elements,index*4);}},{key:"setFromMatrix3Column",value:function setFromMatrix3Column(m,index){return this.fromArray(m.elements,index*3);}},{key:"equals",value:function equals(v){return v.x===this.x&&v.y===this.y&&v.z===this.z;}},{key:"fromArray",value:function fromArray(array,offset){if(offset===undefined)offset=0;this.x=array[offset];this.y=array[offset+1];this.z=array[offset+2];return this;}},{key:"toArray",value:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this.x;array[offset+1]=this.y;array[offset+2]=this.z;return array;}},{key:"fromBufferAttribute",value:function fromBufferAttribute(attribute,index,offset){if(offset!==undefined){console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');}this.x=attribute.getX(index);this.y=attribute.getY(index);this.z=attribute.getZ(index);return this;}},{key:"random",value:function random(){this.x=Math.random();this.y=Math.random();this.z=Math.random();return this;}}]);return Vector3;}();var _vector=/*@__PURE__*/new Vector3();var _quaternion=/*@__PURE__*/new Quaternion();var Box3=/*#__PURE__*/function(){function Box3(min,max){_classCallCheck(this,Box3);Object.defineProperty(this,'isBox3',{value:true});this.min=min!==undefined?min:new Vector3(+Infinity,+Infinity,+Infinity);this.max=max!==undefined?max:new Vector3(-Infinity,-Infinity,-Infinity);}_createClass(Box3,[{key:"set",value:function set(min,max){this.min.copy(min);this.max.copy(max);return this;}},{key:"setFromArray",value:function setFromArray(array){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var _i4=0,l=array.length;_i4maxX)maxX=x;if(y>maxY)maxY=y;if(z>maxZ)maxZ=z;}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this;}},{key:"setFromBufferAttribute",value:function setFromBufferAttribute(attribute){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var _i5=0,l=attribute.count;_i5maxX)maxX=x;if(y>maxY)maxY=y;if(z>maxZ)maxZ=z;}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this;}},{key:"setFromPoints",value:function setFromPoints(points){this.makeEmpty();for(var _i6=0,il=points.length;_i6this.max.x||point.ythis.max.y||point.zthis.max.z?false:true;}},{key:"containsBox",value:function containsBox(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y&&this.min.z<=box.min.z&&box.max.z<=this.max.z;}},{key:"getParameter",value:function getParameter(point,target){// This can potentially have a divide by zero if the box // has a size dimension of 0. if(target===undefined){console.warn('THREE.Box3: .getParameter() target is now required');target=new Vector3();}return target.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y),(point.z-this.min.z)/(this.max.z-this.min.z));}},{key:"intersectsBox",value:function intersectsBox(box){// using 6 splitting planes to rule out intersections. return box.max.xthis.max.x||box.max.ythis.max.y||box.max.zthis.max.z?false:true;}},{key:"intersectsSphere",value:function intersectsSphere(sphere){// Find the point on the AABB closest to the sphere center. this.clampPoint(sphere.center,_vector$1);// If that point is inside the sphere, the AABB and sphere intersect. return _vector$1.distanceToSquared(sphere.center)<=sphere.radius*sphere.radius;}},{key:"intersectsPlane",value:function intersectsPlane(plane){// We compute the minimum and maximum dot product values. If those values // are on the same side (back or front) of the plane, then there is no intersection. var min,max;if(plane.normal.x>0){min=plane.normal.x*this.min.x;max=plane.normal.x*this.max.x;}else{min=plane.normal.x*this.max.x;max=plane.normal.x*this.min.x;}if(plane.normal.y>0){min+=plane.normal.y*this.min.y;max+=plane.normal.y*this.max.y;}else{min+=plane.normal.y*this.max.y;max+=plane.normal.y*this.min.y;}if(plane.normal.z>0){min+=plane.normal.z*this.min.z;max+=plane.normal.z*this.max.z;}else{min+=plane.normal.z*this.max.z;max+=plane.normal.z*this.min.z;}return min<=-plane.constant&&max>=-plane.constant;}},{key:"intersectsTriangle",value:function intersectsTriangle(triangle){if(this.isEmpty()){return false;}// compute box center and extents this.getCenter(_center);_extents.subVectors(this.max,_center);// translate triangle to aabb origin _v0.subVectors(triangle.a,_center);_v1.subVectors(triangle.b,_center);_v2.subVectors(triangle.c,_center);// compute edge vectors for triangle _f0.subVectors(_v1,_v0);_f1.subVectors(_v2,_v1);_f2.subVectors(_v0,_v2);// test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) var axes=[0,-_f0.z,_f0.y,0,-_f1.z,_f1.y,0,-_f2.z,_f2.y,_f0.z,0,-_f0.x,_f1.z,0,-_f1.x,_f2.z,0,-_f2.x,-_f0.y,_f0.x,0,-_f1.y,_f1.x,0,-_f2.y,_f2.x,0];if(!satForAxes(axes,_v0,_v1,_v2,_extents)){return false;}// test 3 face normals from the aabb axes=[1,0,0,0,1,0,0,0,1];if(!satForAxes(axes,_v0,_v1,_v2,_extents)){return false;}// finally testing the face normal of the triangle // use already existing triangle edge vectors here _triangleNormal.crossVectors(_f0,_f1);axes=[_triangleNormal.x,_triangleNormal.y,_triangleNormal.z];return satForAxes(axes,_v0,_v1,_v2,_extents);}},{key:"clampPoint",value:function clampPoint(point,target){if(target===undefined){console.warn('THREE.Box3: .clampPoint() target is now required');target=new Vector3();}return target.copy(point).clamp(this.min,this.max);}},{key:"distanceToPoint",value:function distanceToPoint(point){var clampedPoint=_vector$1.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();}},{key:"getBoundingSphere",value:function getBoundingSphere(target){if(target===undefined){console.error('THREE.Box3: .getBoundingSphere() target is now required');//target = new Sphere(); // removed to avoid cyclic dependency }this.getCenter(target.center);target.radius=this.getSize(_vector$1).length()*0.5;return target;}},{key:"intersect",value:function intersect(box){this.min.max(box.min);this.max.min(box.max);// ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. if(this.isEmpty())this.makeEmpty();return this;}},{key:"union",value:function union(box){this.min.min(box.min);this.max.max(box.max);return this;}},{key:"applyMatrix4",value:function applyMatrix4(matrix){// transform of empty box is an empty box. if(this.isEmpty())return this;// NOTE: I am using a binary pattern to specify all 2^3 combinations below _points[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(matrix);// 000 _points[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(matrix);// 001 _points[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(matrix);// 010 _points[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(matrix);// 011 _points[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(matrix);// 100 _points[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(matrix);// 101 _points[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(matrix);// 110 _points[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(matrix);// 111 this.setFromPoints(_points);return this;}},{key:"translate",value:function translate(offset){this.min.add(offset);this.max.add(offset);return this;}},{key:"equals",value:function equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}}]);return Box3;}();function satForAxes(axes,v0,v1,v2,extents){for(var _i8=0,j=axes.length-3;_i8<=j;_i8+=3){_testAxis.fromArray(axes,_i8);// project the aabb onto the seperating axis var r=extents.x*Math.abs(_testAxis.x)+extents.y*Math.abs(_testAxis.y)+extents.z*Math.abs(_testAxis.z);// project all 3 vertices of the triangle onto the seperating axis var p0=v0.dot(_testAxis);var p1=v1.dot(_testAxis);var p2=v2.dot(_testAxis);// actual test, basically see if either of the most extreme of the triangle points intersects r if(Math.max(-Math.max(p0,p1,p2),Math.min(p0,p1,p2))>r){// points of the projected triangle are outside the projected half-length of the aabb // the axis is seperating and we can exit return false;}}return true;}var _points=[/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3()];var _vector$1=/*@__PURE__*/new Vector3();var _box=/*@__PURE__*/new Box3();// triangle centered vertices var _v0=/*@__PURE__*/new Vector3();var _v1=/*@__PURE__*/new Vector3();var _v2=/*@__PURE__*/new Vector3();// triangle edge vectors var _f0=/*@__PURE__*/new Vector3();var _f1=/*@__PURE__*/new Vector3();var _f2=/*@__PURE__*/new Vector3();var _center=/*@__PURE__*/new Vector3();var _extents=/*@__PURE__*/new Vector3();var _triangleNormal=/*@__PURE__*/new Vector3();var _testAxis=/*@__PURE__*/new Vector3();var _box$1=/*@__PURE__*/new Box3();var Sphere=/*#__PURE__*/function(){function Sphere(center,radius){_classCallCheck(this,Sphere);this.center=center!==undefined?center:new Vector3();this.radius=radius!==undefined?radius:-1;}_createClass(Sphere,[{key:"set",value:function set(center,radius){this.center.copy(center);this.radius=radius;return this;}},{key:"setFromPoints",value:function setFromPoints(points,optionalCenter){var center=this.center;if(optionalCenter!==undefined){center.copy(optionalCenter);}else{_box$1.setFromPoints(points).getCenter(center);}var maxRadiusSq=0;for(var _i9=0,il=points.length;_i9this.radius*this.radius){target.sub(this.center).normalize();target.multiplyScalar(this.radius).add(this.center);}return target;}},{key:"getBoundingBox",value:function getBoundingBox(target){if(target===undefined){console.warn('THREE.Sphere: .getBoundingBox() target is now required');target=new Box3();}if(this.isEmpty()){// Empty sphere produces empty bounding box target.makeEmpty();return target;}target.set(this.center,this.center);target.expandByScalar(this.radius);return target;}},{key:"applyMatrix4",value:function applyMatrix4(matrix){this.center.applyMatrix4(matrix);this.radius=this.radius*matrix.getMaxScaleOnAxis();return this;}},{key:"translate",value:function translate(offset){this.center.add(offset);return this;}},{key:"equals",value:function equals(sphere){return sphere.center.equals(this.center)&&sphere.radius===this.radius;}}]);return Sphere;}();var _vector$2=/*@__PURE__*/new Vector3();var _segCenter=/*@__PURE__*/new Vector3();var _segDir=/*@__PURE__*/new Vector3();var _diff=/*@__PURE__*/new Vector3();var _edge1=/*@__PURE__*/new Vector3();var _edge2=/*@__PURE__*/new Vector3();var _normal=/*@__PURE__*/new Vector3();var Ray=/*#__PURE__*/function(){function Ray(origin,direction){_classCallCheck(this,Ray);this.origin=origin!==undefined?origin:new Vector3();this.direction=direction!==undefined?direction:new Vector3(0,0,-1);}_createClass(Ray,[{key:"set",value:function set(origin,direction){this.origin.copy(origin);this.direction.copy(direction);return this;}},{key:"clone",value:function clone(){return new this.constructor().copy(this);}},{key:"copy",value:function copy(ray){this.origin.copy(ray.origin);this.direction.copy(ray.direction);return this;}},{key:"at",value:function at(t,target){if(target===undefined){console.warn('THREE.Ray: .at() target is now required');target=new Vector3();}return target.copy(this.direction).multiplyScalar(t).add(this.origin);}},{key:"lookAt",value:function lookAt(v){this.direction.copy(v).sub(this.origin).normalize();return this;}},{key:"recast",value:function recast(t){this.origin.copy(this.at(t,_vector$2));return this;}},{key:"closestPointToPoint",value:function closestPointToPoint(point,target){if(target===undefined){console.warn('THREE.Ray: .closestPointToPoint() target is now required');target=new Vector3();}target.subVectors(point,this.origin);var directionDistance=target.dot(this.direction);if(directionDistance<0){return target.copy(this.origin);}return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);}},{key:"distanceToPoint",value:function distanceToPoint(point){return Math.sqrt(this.distanceSqToPoint(point));}},{key:"distanceSqToPoint",value:function distanceSqToPoint(point){var directionDistance=_vector$2.subVectors(point,this.origin).dot(this.direction);// point behind the ray if(directionDistance<0){return this.origin.distanceToSquared(point);}_vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);return _vector$2.distanceToSquared(point);}},{key:"distanceSqToSegment",value:function distanceSqToSegment(v0,v1,optionalPointOnRay,optionalPointOnSegment){// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h // It returns the min distance between the ray and the segment // defined by v0 and v1 // It can also set two optional targets : // - The closest point on the ray // - The closest point on the segment _segCenter.copy(v0).add(v1).multiplyScalar(0.5);_segDir.copy(v1).sub(v0).normalize();_diff.copy(this.origin).sub(_segCenter);var segExtent=v0.distanceTo(v1)*0.5;var a01=-this.direction.dot(_segDir);var b0=_diff.dot(this.direction);var b1=-_diff.dot(_segDir);var c=_diff.lengthSq();var det=Math.abs(1-a01*a01);var s0,s1,sqrDist,extDet;if(det>0){// The ray and segment are not parallel. s0=a01*b1-b0;s1=a01*b0-b1;extDet=segExtent*det;if(s0>=0){if(s1>=-extDet){if(s1<=extDet){// region 0 // Minimum at interior points of ray and segment. var invDet=1/det;s0*=invDet;s1*=invDet;sqrDist=s0*(s0+a01*s1+2*b0)+s1*(a01*s0+s1+2*b1)+c;}else{// region 1 s1=segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c;}}else{// region 5 s1=-segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c;}}else{if(s1<=-extDet){// region 4 s0=Math.max(0,-(-a01*segExtent+b0));s1=s0>0?-segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c;}else if(s1<=extDet){// region 3 s0=0;s1=Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=s1*(s1+2*b1)+c;}else{// region 2 s0=Math.max(0,-(a01*segExtent+b0));s1=s0>0?segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c;}}}else{// Ray and segment are parallel. s1=a01>0?-segExtent:segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c;}if(optionalPointOnRay){optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);}if(optionalPointOnSegment){optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);}return sqrDist;}},{key:"intersectSphere",value:function intersectSphere(sphere,target){_vector$2.subVectors(sphere.center,this.origin);var tca=_vector$2.dot(this.direction);var d2=_vector$2.dot(_vector$2)-tca*tca;var radius2=sphere.radius*sphere.radius;if(d2>radius2)return null;var thc=Math.sqrt(radius2-d2);// t0 = first intersect point - entrance on front of sphere var t0=tca-thc;// t1 = second intersect point - exit point on back of sphere var t1=tca+thc;// test to see if both t0 and t1 are behind the ray - if so, return null if(t0<0&&t1<0)return null;// test to see if t0 is behind the ray: // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, // in order to always return an intersect point that is in front of the ray. if(t0<0)return this.at(t1,target);// else t0 is in front of the ray, so return the first collision point scaled by t0 return this.at(t0,target);}},{key:"intersectsSphere",value:function intersectsSphere(sphere){return this.distanceSqToPoint(sphere.center)<=sphere.radius*sphere.radius;}},{key:"distanceToPlane",value:function distanceToPlane(plane){var denominator=plane.normal.dot(this.direction);if(denominator===0){// line is coplanar, return origin if(plane.distanceToPoint(this.origin)===0){return 0;}// Null is preferable to undefined since undefined means.... it is undefined return null;}var t=-(this.origin.dot(plane.normal)+plane.constant)/denominator;// Return if the ray never intersects the plane return t>=0?t:null;}},{key:"intersectPlane",value:function intersectPlane(plane,target){var t=this.distanceToPlane(plane);if(t===null){return null;}return this.at(t,target);}},{key:"intersectsPlane",value:function intersectsPlane(plane){// check if the ray lies on the plane first var distToPoint=plane.distanceToPoint(this.origin);if(distToPoint===0){return true;}var denominator=plane.normal.dot(this.direction);if(denominator*distToPoint<0){return true;}// ray origin is behind the plane (and is pointing behind it) return false;}},{key:"intersectBox",value:function intersectBox(box,target){var tmin,tmax,tymin,tymax,tzmin,tzmax;var invdirx=1/this.direction.x,invdiry=1/this.direction.y,invdirz=1/this.direction.z;var origin=this.origin;if(invdirx>=0){tmin=(box.min.x-origin.x)*invdirx;tmax=(box.max.x-origin.x)*invdirx;}else{tmin=(box.max.x-origin.x)*invdirx;tmax=(box.min.x-origin.x)*invdirx;}if(invdiry>=0){tymin=(box.min.y-origin.y)*invdiry;tymax=(box.max.y-origin.y)*invdiry;}else{tymin=(box.max.y-origin.y)*invdiry;tymax=(box.min.y-origin.y)*invdiry;}if(tmin>tymax||tymin>tmax)return null;// These lines also handle the case where tmin or tmax is NaN // (result of 0 * Infinity). x !== x returns true if x is NaN if(tymin>tmin||tmin!==tmin)tmin=tymin;if(tymax=0){tzmin=(box.min.z-origin.z)*invdirz;tzmax=(box.max.z-origin.z)*invdirz;}else{tzmin=(box.max.z-origin.z)*invdirz;tzmax=(box.min.z-origin.z)*invdirz;}if(tmin>tzmax||tzmin>tmax)return null;if(tzmin>tmin||tmin!==tmin)tmin=tzmin;if(tzmax=0?tmin:tmax,target);}},{key:"intersectsBox",value:function intersectsBox(box){return this.intersectBox(box,_vector$2)!==null;}},{key:"intersectTriangle",value:function intersectTriangle(a,b,c,backfaceCulling,target){// Compute the offset origin, edges, and normal. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h _edge1.subVectors(b,a);_edge2.subVectors(c,a);_normal.crossVectors(_edge1,_edge2);// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) var DdN=this.direction.dot(_normal);var sign;if(DdN>0){if(backfaceCulling)return null;sign=1;}else if(DdN<0){sign=-1;DdN=-DdN;}else{return null;}_diff.subVectors(this.origin,a);var DdQxE2=sign*this.direction.dot(_edge2.crossVectors(_diff,_edge2));// b1 < 0, no intersection if(DdQxE2<0){return null;}var DdE1xQ=sign*this.direction.dot(_edge1.cross(_diff));// b2 < 0, no intersection if(DdE1xQ<0){return null;}// b1+b2 > 1, no intersection if(DdQxE2+DdE1xQ>DdN){return null;}// Line intersects triangle, check if ray does. var QdN=-sign*_diff.dot(_normal);// t < 0, no intersection if(QdN<0){return null;}// Ray intersects triangle. return this.at(QdN/DdN,target);}},{key:"applyMatrix4",value:function applyMatrix4(matrix4){this.origin.applyMatrix4(matrix4);this.direction.transformDirection(matrix4);return this;}},{key:"equals",value:function equals(ray){return ray.origin.equals(this.origin)&&ray.direction.equals(this.direction);}}]);return Ray;}();var Matrix4=/*#__PURE__*/function(){function Matrix4(){_classCallCheck(this,Matrix4);Object.defineProperty(this,'isMatrix4',{value:true});this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];if(arguments.length>0){console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');}}_createClass(Matrix4,[{key:"set",value:function set(n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44){var te=this.elements;te[0]=n11;te[4]=n12;te[8]=n13;te[12]=n14;te[1]=n21;te[5]=n22;te[9]=n23;te[13]=n24;te[2]=n31;te[6]=n32;te[10]=n33;te[14]=n34;te[3]=n41;te[7]=n42;te[11]=n43;te[15]=n44;return this;}},{key:"identity",value:function identity(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this;}},{key:"clone",value:function clone(){return new Matrix4().fromArray(this.elements);}},{key:"copy",value:function copy(m){var te=this.elements;var me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];te[9]=me[9];te[10]=me[10];te[11]=me[11];te[12]=me[12];te[13]=me[13];te[14]=me[14];te[15]=me[15];return this;}},{key:"copyPosition",value:function copyPosition(m){var te=this.elements,me=m.elements;te[12]=me[12];te[13]=me[13];te[14]=me[14];return this;}},{key:"extractBasis",value:function extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrixColumn(this,0);yAxis.setFromMatrixColumn(this,1);zAxis.setFromMatrixColumn(this,2);return this;}},{key:"makeBasis",value:function makeBasis(xAxis,yAxis,zAxis){this.set(xAxis.x,yAxis.x,zAxis.x,0,xAxis.y,yAxis.y,zAxis.y,0,xAxis.z,yAxis.z,zAxis.z,0,0,0,0,1);return this;}},{key:"extractRotation",value:function extractRotation(m){// this method does not support reflection matrices var te=this.elements;var me=m.elements;var scaleX=1/_v1$1.setFromMatrixColumn(m,0).length();var scaleY=1/_v1$1.setFromMatrixColumn(m,1).length();var scaleZ=1/_v1$1.setFromMatrixColumn(m,2).length();te[0]=me[0]*scaleX;te[1]=me[1]*scaleX;te[2]=me[2]*scaleX;te[3]=0;te[4]=me[4]*scaleY;te[5]=me[5]*scaleY;te[6]=me[6]*scaleY;te[7]=0;te[8]=me[8]*scaleZ;te[9]=me[9]*scaleZ;te[10]=me[10]*scaleZ;te[11]=0;te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this;}},{key:"makeRotationFromEuler",value:function makeRotationFromEuler(euler){if(!(euler&&euler.isEuler)){console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');}var te=this.elements;var x=euler.x,y=euler.y,z=euler.z;var a=Math.cos(x),b=Math.sin(x);var c=Math.cos(y),d=Math.sin(y);var e=Math.cos(z),f=Math.sin(z);if(euler.order==='XYZ'){var ae=a*e,af=a*f,be=b*e,bf=b*f;te[0]=c*e;te[4]=-c*f;te[8]=d;te[1]=af+be*d;te[5]=ae-bf*d;te[9]=-b*c;te[2]=bf-ae*d;te[6]=be+af*d;te[10]=a*c;}else if(euler.order==='YXZ'){var ce=c*e,cf=c*f,de=d*e,df=d*f;te[0]=ce+df*b;te[4]=de*b-cf;te[8]=a*d;te[1]=a*f;te[5]=a*e;te[9]=-b;te[2]=cf*b-de;te[6]=df+ce*b;te[10]=a*c;}else if(euler.order==='ZXY'){var _ce=c*e,_cf=c*f,_de=d*e,_df=d*f;te[0]=_ce-_df*b;te[4]=-a*f;te[8]=_de+_cf*b;te[1]=_cf+_de*b;te[5]=a*e;te[9]=_df-_ce*b;te[2]=-a*d;te[6]=b;te[10]=a*c;}else if(euler.order==='ZYX'){var _ae=a*e,_af=a*f,_be=b*e,_bf=b*f;te[0]=c*e;te[4]=_be*d-_af;te[8]=_ae*d+_bf;te[1]=c*f;te[5]=_bf*d+_ae;te[9]=_af*d-_be;te[2]=-d;te[6]=b*c;te[10]=a*c;}else if(euler.order==='YZX'){var ac=a*c,ad=a*d,bc=b*c,bd=b*d;te[0]=c*e;te[4]=bd-ac*f;te[8]=bc*f+ad;te[1]=f;te[5]=a*e;te[9]=-b*e;te[2]=-d*e;te[6]=ad*f+bc;te[10]=ac-bd*f;}else if(euler.order==='XZY'){var _ac=a*c,_ad=a*d,_bc=b*c,_bd=b*d;te[0]=c*e;te[4]=-f;te[8]=d*e;te[1]=_ac*f+_bd;te[5]=a*e;te[9]=_ad*f-_bc;te[2]=_bc*f-_ad;te[6]=b*e;te[10]=_bd*f+_ac;}// bottom row te[3]=0;te[7]=0;te[11]=0;// last column te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this;}},{key:"makeRotationFromQuaternion",value:function makeRotationFromQuaternion(q){return this.compose(_zero,q,_one);}},{key:"lookAt",value:function lookAt(eye,target,up){var te=this.elements;_z.subVectors(eye,target);if(_z.lengthSq()===0){// eye and target are in the same position _z.z=1;}_z.normalize();_x.crossVectors(up,_z);if(_x.lengthSq()===0){// up and z are parallel if(Math.abs(up.z)===1){_z.x+=0.0001;}else{_z.z+=0.0001;}_z.normalize();_x.crossVectors(up,_z);}_x.normalize();_y.crossVectors(_z,_x);te[0]=_x.x;te[4]=_y.x;te[8]=_z.x;te[1]=_x.y;te[5]=_y.y;te[9]=_z.y;te[2]=_x.z;te[6]=_y.z;te[10]=_z.z;return this;}},{key:"multiply",value:function multiply(m,n){if(n!==undefined){console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');return this.multiplyMatrices(m,n);}return this.multiplyMatrices(this,m);}},{key:"premultiply",value:function premultiply(m){return this.multiplyMatrices(m,this);}},{key:"multiplyMatrices",value:function multiplyMatrices(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[4],a13=ae[8],a14=ae[12];var a21=ae[1],a22=ae[5],a23=ae[9],a24=ae[13];var a31=ae[2],a32=ae[6],a33=ae[10],a34=ae[14];var a41=ae[3],a42=ae[7],a43=ae[11],a44=ae[15];var b11=be[0],b12=be[4],b13=be[8],b14=be[12];var b21=be[1],b22=be[5],b23=be[9],b24=be[13];var b31=be[2],b32=be[6],b33=be[10],b34=be[14];var b41=be[3],b42=be[7],b43=be[11],b44=be[15];te[0]=a11*b11+a12*b21+a13*b31+a14*b41;te[4]=a11*b12+a12*b22+a13*b32+a14*b42;te[8]=a11*b13+a12*b23+a13*b33+a14*b43;te[12]=a11*b14+a12*b24+a13*b34+a14*b44;te[1]=a21*b11+a22*b21+a23*b31+a24*b41;te[5]=a21*b12+a22*b22+a23*b32+a24*b42;te[9]=a21*b13+a22*b23+a23*b33+a24*b43;te[13]=a21*b14+a22*b24+a23*b34+a24*b44;te[2]=a31*b11+a32*b21+a33*b31+a34*b41;te[6]=a31*b12+a32*b22+a33*b32+a34*b42;te[10]=a31*b13+a32*b23+a33*b33+a34*b43;te[14]=a31*b14+a32*b24+a33*b34+a34*b44;te[3]=a41*b11+a42*b21+a43*b31+a44*b41;te[7]=a41*b12+a42*b22+a43*b32+a44*b42;te[11]=a41*b13+a42*b23+a43*b33+a44*b43;te[15]=a41*b14+a42*b24+a43*b34+a44*b44;return this;}},{key:"multiplyScalar",value:function multiplyScalar(s){var te=this.elements;te[0]*=s;te[4]*=s;te[8]*=s;te[12]*=s;te[1]*=s;te[5]*=s;te[9]*=s;te[13]*=s;te[2]*=s;te[6]*=s;te[10]*=s;te[14]*=s;te[3]*=s;te[7]*=s;te[11]*=s;te[15]*=s;return this;}},{key:"determinant",value:function determinant(){var te=this.elements;var n11=te[0],n12=te[4],n13=te[8],n14=te[12];var n21=te[1],n22=te[5],n23=te[9],n24=te[13];var n31=te[2],n32=te[6],n33=te[10],n34=te[14];var n41=te[3],n42=te[7],n43=te[11],n44=te[15];//TODO: make this more efficient //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) return n41*(+n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34)+n42*(+n11*n23*n34-n11*n24*n33+n14*n21*n33-n13*n21*n34+n13*n24*n31-n14*n23*n31)+n43*(+n11*n24*n32-n11*n22*n34-n14*n21*n32+n12*n21*n34+n14*n22*n31-n12*n24*n31)+n44*(-n13*n22*n31-n11*n23*n32+n11*n22*n33+n13*n21*n32-n12*n21*n33+n12*n23*n31);}},{key:"transpose",value:function transpose(){var te=this.elements;var tmp;tmp=te[1];te[1]=te[4];te[4]=tmp;tmp=te[2];te[2]=te[8];te[8]=tmp;tmp=te[6];te[6]=te[9];te[9]=tmp;tmp=te[3];te[3]=te[12];te[12]=tmp;tmp=te[7];te[7]=te[13];te[13]=tmp;tmp=te[11];te[11]=te[14];te[14]=tmp;return this;}},{key:"setPosition",value:function setPosition(x,y,z){var te=this.elements;if(x.isVector3){te[12]=x.x;te[13]=x.y;te[14]=x.z;}else{te[12]=x;te[13]=y;te[14]=z;}return this;}},{key:"getInverse",value:function getInverse(m,throwOnDegenerate){if(throwOnDegenerate!==undefined){console.warn("THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate.");}// based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm var te=this.elements,me=m.elements,n11=me[0],n21=me[1],n31=me[2],n41=me[3],n12=me[4],n22=me[5],n32=me[6],n42=me[7],n13=me[8],n23=me[9],n33=me[10],n43=me[11],n14=me[12],n24=me[13],n34=me[14],n44=me[15],t11=n23*n34*n42-n24*n33*n42+n24*n32*n43-n22*n34*n43-n23*n32*n44+n22*n33*n44,t12=n14*n33*n42-n13*n34*n42-n14*n32*n43+n12*n34*n43+n13*n32*n44-n12*n33*n44,t13=n13*n24*n42-n14*n23*n42+n14*n22*n43-n12*n24*n43-n13*n22*n44+n12*n23*n44,t14=n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34;var det=n11*t11+n21*t12+n31*t13+n41*t14;if(det===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);var detInv=1/det;te[0]=t11*detInv;te[1]=(n24*n33*n41-n23*n34*n41-n24*n31*n43+n21*n34*n43+n23*n31*n44-n21*n33*n44)*detInv;te[2]=(n22*n34*n41-n24*n32*n41+n24*n31*n42-n21*n34*n42-n22*n31*n44+n21*n32*n44)*detInv;te[3]=(n23*n32*n41-n22*n33*n41-n23*n31*n42+n21*n33*n42+n22*n31*n43-n21*n32*n43)*detInv;te[4]=t12*detInv;te[5]=(n13*n34*n41-n14*n33*n41+n14*n31*n43-n11*n34*n43-n13*n31*n44+n11*n33*n44)*detInv;te[6]=(n14*n32*n41-n12*n34*n41-n14*n31*n42+n11*n34*n42+n12*n31*n44-n11*n32*n44)*detInv;te[7]=(n12*n33*n41-n13*n32*n41+n13*n31*n42-n11*n33*n42-n12*n31*n43+n11*n32*n43)*detInv;te[8]=t13*detInv;te[9]=(n14*n23*n41-n13*n24*n41-n14*n21*n43+n11*n24*n43+n13*n21*n44-n11*n23*n44)*detInv;te[10]=(n12*n24*n41-n14*n22*n41+n14*n21*n42-n11*n24*n42-n12*n21*n44+n11*n22*n44)*detInv;te[11]=(n13*n22*n41-n12*n23*n41-n13*n21*n42+n11*n23*n42+n12*n21*n43-n11*n22*n43)*detInv;te[12]=t14*detInv;te[13]=(n13*n24*n31-n14*n23*n31+n14*n21*n33-n11*n24*n33-n13*n21*n34+n11*n23*n34)*detInv;te[14]=(n14*n22*n31-n12*n24*n31-n14*n21*n32+n11*n24*n32+n12*n21*n34-n11*n22*n34)*detInv;te[15]=(n12*n23*n31-n13*n22*n31+n13*n21*n32-n11*n23*n32-n12*n21*n33+n11*n22*n33)*detInv;return this;}},{key:"scale",value:function scale(v){var te=this.elements;var x=v.x,y=v.y,z=v.z;te[0]*=x;te[4]*=y;te[8]*=z;te[1]*=x;te[5]*=y;te[9]*=z;te[2]*=x;te[6]*=y;te[10]*=z;te[3]*=x;te[7]*=y;te[11]*=z;return this;}},{key:"getMaxScaleOnAxis",value:function getMaxScaleOnAxis(){var te=this.elements;var scaleXSq=te[0]*te[0]+te[1]*te[1]+te[2]*te[2];var scaleYSq=te[4]*te[4]+te[5]*te[5]+te[6]*te[6];var scaleZSq=te[8]*te[8]+te[9]*te[9]+te[10]*te[10];return Math.sqrt(Math.max(scaleXSq,scaleYSq,scaleZSq));}},{key:"makeTranslation",value:function makeTranslation(x,y,z){this.set(1,0,0,x,0,1,0,y,0,0,1,z,0,0,0,1);return this;}},{key:"makeRotationX",value:function makeRotationX(theta){var c=Math.cos(theta),s=Math.sin(theta);this.set(1,0,0,0,0,c,-s,0,0,s,c,0,0,0,0,1);return this;}},{key:"makeRotationY",value:function makeRotationY(theta){var c=Math.cos(theta),s=Math.sin(theta);this.set(c,0,s,0,0,1,0,0,-s,0,c,0,0,0,0,1);return this;}},{key:"makeRotationZ",value:function makeRotationZ(theta){var c=Math.cos(theta),s=Math.sin(theta);this.set(c,-s,0,0,s,c,0,0,0,0,1,0,0,0,0,1);return this;}},{key:"makeRotationAxis",value:function makeRotationAxis(axis,angle){// Based on http://www.gamedev.net/reference/articles/article1199.asp var c=Math.cos(angle);var s=Math.sin(angle);var t=1-c;var x=axis.x,y=axis.y,z=axis.z;var tx=t*x,ty=t*y;this.set(tx*x+c,tx*y-s*z,tx*z+s*y,0,tx*y+s*z,ty*y+c,ty*z-s*x,0,tx*z-s*y,ty*z+s*x,t*z*z+c,0,0,0,0,1);return this;}},{key:"makeScale",value:function makeScale(x,y,z){this.set(x,0,0,0,0,y,0,0,0,0,z,0,0,0,0,1);return this;}},{key:"makeShear",value:function makeShear(x,y,z){this.set(1,y,z,0,x,1,z,0,x,y,1,0,0,0,0,1);return this;}},{key:"compose",value:function compose(position,quaternion,scale){var te=this.elements;var x=quaternion._x,y=quaternion._y,z=quaternion._z,w=quaternion._w;var x2=x+x,y2=y+y,z2=z+z;var xx=x*x2,xy=x*y2,xz=x*z2;var yy=y*y2,yz=y*z2,zz=z*z2;var wx=w*x2,wy=w*y2,wz=w*z2;var sx=scale.x,sy=scale.y,sz=scale.z;te[0]=(1-(yy+zz))*sx;te[1]=(xy+wz)*sx;te[2]=(xz-wy)*sx;te[3]=0;te[4]=(xy-wz)*sy;te[5]=(1-(xx+zz))*sy;te[6]=(yz+wx)*sy;te[7]=0;te[8]=(xz+wy)*sz;te[9]=(yz-wx)*sz;te[10]=(1-(xx+yy))*sz;te[11]=0;te[12]=position.x;te[13]=position.y;te[14]=position.z;te[15]=1;return this;}},{key:"decompose",value:function decompose(position,quaternion,scale){var te=this.elements;var sx=_v1$1.set(te[0],te[1],te[2]).length();var sy=_v1$1.set(te[4],te[5],te[6]).length();var sz=_v1$1.set(te[8],te[9],te[10]).length();// if determine is negative, we need to invert one scale var det=this.determinant();if(det<0)sx=-sx;position.x=te[12];position.y=te[13];position.z=te[14];// scale the rotation part _m1.copy(this);var invSX=1/sx;var invSY=1/sy;var invSZ=1/sz;_m1.elements[0]*=invSX;_m1.elements[1]*=invSX;_m1.elements[2]*=invSX;_m1.elements[4]*=invSY;_m1.elements[5]*=invSY;_m1.elements[6]*=invSY;_m1.elements[8]*=invSZ;_m1.elements[9]*=invSZ;_m1.elements[10]*=invSZ;quaternion.setFromRotationMatrix(_m1);scale.x=sx;scale.y=sy;scale.z=sz;return this;}},{key:"makePerspective",value:function makePerspective(left,right,top,bottom,near,far){if(far===undefined){console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');}var te=this.elements;var x=2*near/(right-left);var y=2*near/(top-bottom);var a=(right+left)/(right-left);var b=(top+bottom)/(top-bottom);var c=-(far+near)/(far-near);var d=-2*far*near/(far-near);te[0]=x;te[4]=0;te[8]=a;te[12]=0;te[1]=0;te[5]=y;te[9]=b;te[13]=0;te[2]=0;te[6]=0;te[10]=c;te[14]=d;te[3]=0;te[7]=0;te[11]=-1;te[15]=0;return this;}},{key:"makeOrthographic",value:function makeOrthographic(left,right,top,bottom,near,far){var te=this.elements;var w=1.0/(right-left);var h=1.0/(top-bottom);var p=1.0/(far-near);var x=(right+left)*w;var y=(top+bottom)*h;var z=(far+near)*p;te[0]=2*w;te[4]=0;te[8]=0;te[12]=-x;te[1]=0;te[5]=2*h;te[9]=0;te[13]=-y;te[2]=0;te[6]=0;te[10]=-2*p;te[14]=-z;te[3]=0;te[7]=0;te[11]=0;te[15]=1;return this;}},{key:"equals",value:function equals(matrix){var te=this.elements;var me=matrix.elements;for(var _i10=0;_i10<16;_i10++){if(te[_i10]!==me[_i10])return false;}return true;}},{key:"fromArray",value:function fromArray(array,offset){if(offset===undefined)offset=0;for(var _i11=0;_i11<16;_i11++){this.elements[_i11]=array[_i11+offset];}return this;}},{key:"toArray",value:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;var te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];array[offset+9]=te[9];array[offset+10]=te[10];array[offset+11]=te[11];array[offset+12]=te[12];array[offset+13]=te[13];array[offset+14]=te[14];array[offset+15]=te[15];return array;}}]);return Matrix4;}();var _v1$1=/*@__PURE__*/new Vector3();var _m1=/*@__PURE__*/new Matrix4();var _zero=/*@__PURE__*/new Vector3(0,0,0);var _one=/*@__PURE__*/new Vector3(1,1,1);var _x=/*@__PURE__*/new Vector3();var _y=/*@__PURE__*/new Vector3();var _z=/*@__PURE__*/new Vector3();var Euler=/*#__PURE__*/function(){function Euler(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var order=arguments.length>3&&arguments[3]!==undefined?arguments[3]:Euler.DefaultOrder;_classCallCheck(this,Euler);Object.defineProperty(this,'isEuler',{value:true});this._x=x;this._y=y;this._z=z;this._order=order;}_createClass(Euler,[{key:"set",value:function set(x,y,z,order){this._x=x;this._y=y;this._z=z;this._order=order||this._order;this._onChangeCallback();return this;}},{key:"clone",value:function clone(){return new this.constructor(this._x,this._y,this._z,this._order);}},{key:"copy",value:function copy(euler){this._x=euler._x;this._y=euler._y;this._z=euler._z;this._order=euler._order;this._onChangeCallback();return this;}},{key:"setFromRotationMatrix",value:function setFromRotationMatrix(m,order,update){var clamp=MathUtils.clamp;// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var te=m.elements;var m11=te[0],m12=te[4],m13=te[8];var m21=te[1],m22=te[5],m23=te[9];var m31=te[2],m32=te[6],m33=te[10];order=order||this._order;switch(order){case'XYZ':this._y=Math.asin(clamp(m13,-1,1));if(Math.abs(m13)<0.9999999){this._x=Math.atan2(-m23,m33);this._z=Math.atan2(-m12,m11);}else{this._x=Math.atan2(m32,m22);this._z=0;}break;case'YXZ':this._x=Math.asin(-clamp(m23,-1,1));if(Math.abs(m23)<0.9999999){this._y=Math.atan2(m13,m33);this._z=Math.atan2(m21,m22);}else{this._y=Math.atan2(-m31,m11);this._z=0;}break;case'ZXY':this._x=Math.asin(clamp(m32,-1,1));if(Math.abs(m32)<0.9999999){this._y=Math.atan2(-m31,m33);this._z=Math.atan2(-m12,m22);}else{this._y=0;this._z=Math.atan2(m21,m11);}break;case'ZYX':this._y=Math.asin(-clamp(m31,-1,1));if(Math.abs(m31)<0.9999999){this._x=Math.atan2(m32,m33);this._z=Math.atan2(m21,m11);}else{this._x=0;this._z=Math.atan2(-m12,m22);}break;case'YZX':this._z=Math.asin(clamp(m21,-1,1));if(Math.abs(m21)<0.9999999){this._x=Math.atan2(-m23,m22);this._y=Math.atan2(-m31,m11);}else{this._x=0;this._y=Math.atan2(m13,m33);}break;case'XZY':this._z=Math.asin(-clamp(m12,-1,1));if(Math.abs(m12)<0.9999999){this._x=Math.atan2(m32,m22);this._y=Math.atan2(m13,m11);}else{this._x=Math.atan2(-m23,m33);this._y=0;}break;default:console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: '+order);}this._order=order;if(update!==false)this._onChangeCallback();return this;}},{key:"setFromQuaternion",value:function setFromQuaternion(q,order,update){_matrix.makeRotationFromQuaternion(q);return this.setFromRotationMatrix(_matrix,order,update);}},{key:"setFromVector3",value:function setFromVector3(v,order){return this.set(v.x,v.y,v.z,order||this._order);}},{key:"reorder",value:function reorder(newOrder){// WARNING: this discards revolution information -bhouston _quaternion$1.setFromEuler(this);return this.setFromQuaternion(_quaternion$1,newOrder);}},{key:"equals",value:function equals(euler){return euler._x===this._x&&euler._y===this._y&&euler._z===this._z&&euler._order===this._order;}},{key:"fromArray",value:function fromArray(array){this._x=array[0];this._y=array[1];this._z=array[2];if(array[3]!==undefined)this._order=array[3];this._onChangeCallback();return this;}},{key:"toArray",value:function toArray(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._order;return array;}},{key:"toVector3",value:function toVector3(optionalResult){if(optionalResult){return optionalResult.set(this._x,this._y,this._z);}else{return new Vector3(this._x,this._y,this._z);}}},{key:"_onChange",value:function _onChange(callback){this._onChangeCallback=callback;return this;}},{key:"_onChangeCallback",value:function _onChangeCallback(){}},{key:"x",get:function get(){return this._x;},set:function set(value){this._x=value;this._onChangeCallback();}},{key:"y",get:function get(){return this._y;},set:function set(value){this._y=value;this._onChangeCallback();}},{key:"z",get:function get(){return this._z;},set:function set(value){this._z=value;this._onChangeCallback();}},{key:"order",get:function get(){return this._order;},set:function set(value){this._order=value;this._onChangeCallback();}}]);return Euler;}();Euler.DefaultOrder='XYZ';Euler.RotationOrders=['XYZ','YZX','ZXY','XZY','YXZ','ZYX'];var _matrix=/*@__PURE__*/new Matrix4();var _quaternion$1=/*@__PURE__*/new Quaternion();var Layers=/*#__PURE__*/function(){function Layers(){_classCallCheck(this,Layers);this.mask=1|0;}_createClass(Layers,[{key:"set",value:function set(channel){this.mask=1<1){for(var _i12=0;_i121){for(var _i13=0;_i130){object.children=[];for(var _i21=0;_i210)output.geometries=geometries;if(materials.length>0)output.materials=materials;if(textures.length>0)output.textures=textures;if(images.length>0)output.images=images;if(_shapes.length>0)output.shapes=_shapes;}output.object=object;return output;// extract data from the cache hash // remove metadata on each item // and return as array function extractFromCache(cache){var values=[];for(var key in cache){var data=cache[key];delete data.metadata;values.push(data);}return values;}},clone:function clone(recursive){return new this.constructor().copy(this,recursive);},copy:function copy(source,recursive){if(recursive===undefined)recursive=true;this.name=source.name;this.up.copy(source.up);this.position.copy(source.position);this.rotation.order=source.rotation.order;this.quaternion.copy(source.quaternion);this.scale.copy(source.scale);this.matrix.copy(source.matrix);this.matrixWorld.copy(source.matrixWorld);this.matrixAutoUpdate=source.matrixAutoUpdate;this.matrixWorldNeedsUpdate=source.matrixWorldNeedsUpdate;this.layers.mask=source.layers.mask;this.visible=source.visible;this.castShadow=source.castShadow;this.receiveShadow=source.receiveShadow;this.frustumCulled=source.frustumCulled;this.renderOrder=source.renderOrder;this.userData=JSON.parse(JSON.stringify(source.userData));if(recursive===true){for(var _i22=0;_i221){return undefined;}return target.copy(direction).multiplyScalar(t).add(line.start);}},{key:"intersectsLine",value:function intersectsLine(line){// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. var startSign=this.distanceToPoint(line.start);var endSign=this.distanceToPoint(line.end);return startSign<0&&endSign>0||endSign<0&&startSign>0;}},{key:"intersectsBox",value:function intersectsBox(box){return box.intersectsPlane(this);}},{key:"intersectsSphere",value:function intersectsSphere(sphere){return sphere.intersectsPlane(this);}},{key:"coplanarPoint",value:function coplanarPoint(target){if(target===undefined){console.warn('THREE.Plane: .coplanarPoint() target is now required');target=new Vector3();}return target.copy(this.normal).multiplyScalar(-this.constant);}},{key:"applyMatrix4",value:function applyMatrix4(matrix,optionalNormalMatrix){var normalMatrix=optionalNormalMatrix||_normalMatrix.getNormalMatrix(matrix);var referencePoint=this.coplanarPoint(_vector1).applyMatrix4(matrix);var normal=this.normal.applyMatrix3(normalMatrix).normalize();this.constant=-referencePoint.dot(normal);return this;}},{key:"translate",value:function translate(offset){this.constant-=offset.dot(this.normal);return this;}},{key:"equals",value:function equals(plane){return plane.normal.equals(this.normal)&&plane.constant===this.constant;}}]);return Plane;}();var _v0$1=/*@__PURE__*/new Vector3();var _v1$3=/*@__PURE__*/new Vector3();var _v2$1=/*@__PURE__*/new Vector3();var _v3=/*@__PURE__*/new Vector3();var _vab=/*@__PURE__*/new Vector3();var _vac=/*@__PURE__*/new Vector3();var _vbc=/*@__PURE__*/new Vector3();var _vap=/*@__PURE__*/new Vector3();var _vbp=/*@__PURE__*/new Vector3();var _vcp=/*@__PURE__*/new Vector3();var Triangle=/*#__PURE__*/function(){function Triangle(a,b,c){_classCallCheck(this,Triangle);this.a=a!==undefined?a:new Vector3();this.b=b!==undefined?b:new Vector3();this.c=c!==undefined?c:new Vector3();}_createClass(Triangle,[{key:"set",value:function set(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this;}},{key:"setFromPointsAndIndices",value:function setFromPointsAndIndices(points,i0,i1,i2){this.a.copy(points[i0]);this.b.copy(points[i1]);this.c.copy(points[i2]);return this;}},{key:"clone",value:function clone(){return new this.constructor().copy(this);}},{key:"copy",value:function copy(triangle){this.a.copy(triangle.a);this.b.copy(triangle.b);this.c.copy(triangle.c);return this;}},{key:"getArea",value:function getArea(){_v0$1.subVectors(this.c,this.b);_v1$3.subVectors(this.a,this.b);return _v0$1.cross(_v1$3).length()*0.5;}},{key:"getMidpoint",value:function getMidpoint(target){if(target===undefined){console.warn('THREE.Triangle: .getMidpoint() target is now required');target=new Vector3();}return target.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3);}},{key:"getNormal",value:function getNormal(target){return Triangle.getNormal(this.a,this.b,this.c,target);}},{key:"getPlane",value:function getPlane(target){if(target===undefined){console.warn('THREE.Triangle: .getPlane() target is now required');target=new Plane();}return target.setFromCoplanarPoints(this.a,this.b,this.c);}},{key:"getBarycoord",value:function getBarycoord(point,target){return Triangle.getBarycoord(point,this.a,this.b,this.c,target);}},{key:"getUV",value:function getUV(point,uv1,uv2,uv3,target){return Triangle.getUV(point,this.a,this.b,this.c,uv1,uv2,uv3,target);}},{key:"containsPoint",value:function containsPoint(point){return Triangle.containsPoint(point,this.a,this.b,this.c);}},{key:"isFrontFacing",value:function isFrontFacing(direction){return Triangle.isFrontFacing(this.a,this.b,this.c,direction);}},{key:"intersectsBox",value:function intersectsBox(box){return box.intersectsTriangle(this);}},{key:"closestPointToPoint",value:function closestPointToPoint(p,target){if(target===undefined){console.warn('THREE.Triangle: .closestPointToPoint() target is now required');target=new Vector3();}var a=this.a,b=this.b,c=this.c;var v,w;// algorithm thanks to Real-Time Collision Detection by Christer Ericson, // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., // under the accompanying license; see chapter 5.1.5 for detailed explanation. // basically, we're distinguishing which of the voronoi regions of the triangle // the point lies in with the minimum amount of redundant computation. _vab.subVectors(b,a);_vac.subVectors(c,a);_vap.subVectors(p,a);var d1=_vab.dot(_vap);var d2=_vac.dot(_vap);if(d1<=0&&d2<=0){// vertex region of A; barycentric coords (1, 0, 0) return target.copy(a);}_vbp.subVectors(p,b);var d3=_vab.dot(_vbp);var d4=_vac.dot(_vbp);if(d3>=0&&d4<=d3){// vertex region of B; barycentric coords (0, 1, 0) return target.copy(b);}var vc=d1*d4-d3*d2;if(vc<=0&&d1>=0&&d3<=0){v=d1/(d1-d3);// edge region of AB; barycentric coords (1-v, v, 0) return target.copy(a).addScaledVector(_vab,v);}_vcp.subVectors(p,c);var d5=_vab.dot(_vcp);var d6=_vac.dot(_vcp);if(d6>=0&&d5<=d6){// vertex region of C; barycentric coords (0, 0, 1) return target.copy(c);}var vb=d5*d2-d1*d6;if(vb<=0&&d2>=0&&d6<=0){w=d2/(d2-d6);// edge region of AC; barycentric coords (1-w, 0, w) return target.copy(a).addScaledVector(_vac,w);}var va=d3*d6-d5*d4;if(va<=0&&d4-d3>=0&&d5-d6>=0){_vbc.subVectors(c,b);w=(d4-d3)/(d4-d3+(d5-d6));// edge region of BC; barycentric coords (0, 1-w, w) return target.copy(b).addScaledVector(_vbc,w);// edge region of BC }// face region var denom=1/(va+vb+vc);// u = va * denom v=vb*denom;w=vc*denom;return target.copy(a).addScaledVector(_vab,v).addScaledVector(_vac,w);}},{key:"equals",value:function equals(triangle){return triangle.a.equals(this.a)&&triangle.b.equals(this.b)&&triangle.c.equals(this.c);}}],[{key:"getNormal",value:function getNormal(a,b,c,target){if(target===undefined){console.warn('THREE.Triangle: .getNormal() target is now required');target=new Vector3();}target.subVectors(c,b);_v0$1.subVectors(a,b);target.cross(_v0$1);var targetLengthSq=target.lengthSq();if(targetLengthSq>0){return target.multiplyScalar(1/Math.sqrt(targetLengthSq));}return target.set(0,0,0);}// static/instance method to calculate barycentric coordinates // based on: http://www.blackpawn.com/texts/pointinpoly/default.html },{key:"getBarycoord",value:function getBarycoord(point,a,b,c,target){_v0$1.subVectors(c,a);_v1$3.subVectors(b,a);_v2$1.subVectors(point,a);var dot00=_v0$1.dot(_v0$1);var dot01=_v0$1.dot(_v1$3);var dot02=_v0$1.dot(_v2$1);var dot11=_v1$3.dot(_v1$3);var dot12=_v1$3.dot(_v2$1);var denom=dot00*dot11-dot01*dot01;if(target===undefined){console.warn('THREE.Triangle: .getBarycoord() target is now required');target=new Vector3();}// collinear or singular triangle if(denom===0){// arbitrary location outside of triangle? // not sure if this is the best idea, maybe should be returning undefined return target.set(-2,-1,-1);}var invDenom=1/denom;var u=(dot11*dot02-dot01*dot12)*invDenom;var v=(dot00*dot12-dot01*dot02)*invDenom;// barycentric coordinates must always sum to 1 return target.set(1-u-v,v,u);}},{key:"containsPoint",value:function containsPoint(point,a,b,c){this.getBarycoord(point,a,b,c,_v3);return _v3.x>=0&&_v3.y>=0&&_v3.x+_v3.y<=1;}},{key:"getUV",value:function getUV(point,p1,p2,p3,uv1,uv2,uv3,target){this.getBarycoord(point,p1,p2,p3,_v3);target.set(0,0);target.addScaledVector(uv1,_v3.x);target.addScaledVector(uv2,_v3.y);target.addScaledVector(uv3,_v3.z);return target;}},{key:"isFrontFacing",value:function isFrontFacing(a,b,c,direction){_v0$1.subVectors(c,b);_v1$3.subVectors(a,b);// strictly front facing return _v0$1.cross(_v1$3).dot(direction)<0?true:false;}}]);return Triangle;}();var _colorKeywords={'aliceblue':0xF0F8FF,'antiquewhite':0xFAEBD7,'aqua':0x00FFFF,'aquamarine':0x7FFFD4,'azure':0xF0FFFF,'beige':0xF5F5DC,'bisque':0xFFE4C4,'black':0x000000,'blanchedalmond':0xFFEBCD,'blue':0x0000FF,'blueviolet':0x8A2BE2,'brown':0xA52A2A,'burlywood':0xDEB887,'cadetblue':0x5F9EA0,'chartreuse':0x7FFF00,'chocolate':0xD2691E,'coral':0xFF7F50,'cornflowerblue':0x6495ED,'cornsilk':0xFFF8DC,'crimson':0xDC143C,'cyan':0x00FFFF,'darkblue':0x00008B,'darkcyan':0x008B8B,'darkgoldenrod':0xB8860B,'darkgray':0xA9A9A9,'darkgreen':0x006400,'darkgrey':0xA9A9A9,'darkkhaki':0xBDB76B,'darkmagenta':0x8B008B,'darkolivegreen':0x556B2F,'darkorange':0xFF8C00,'darkorchid':0x9932CC,'darkred':0x8B0000,'darksalmon':0xE9967A,'darkseagreen':0x8FBC8F,'darkslateblue':0x483D8B,'darkslategray':0x2F4F4F,'darkslategrey':0x2F4F4F,'darkturquoise':0x00CED1,'darkviolet':0x9400D3,'deeppink':0xFF1493,'deepskyblue':0x00BFFF,'dimgray':0x696969,'dimgrey':0x696969,'dodgerblue':0x1E90FF,'firebrick':0xB22222,'floralwhite':0xFFFAF0,'forestgreen':0x228B22,'fuchsia':0xFF00FF,'gainsboro':0xDCDCDC,'ghostwhite':0xF8F8FF,'gold':0xFFD700,'goldenrod':0xDAA520,'gray':0x808080,'green':0x008000,'greenyellow':0xADFF2F,'grey':0x808080,'honeydew':0xF0FFF0,'hotpink':0xFF69B4,'indianred':0xCD5C5C,'indigo':0x4B0082,'ivory':0xFFFFF0,'khaki':0xF0E68C,'lavender':0xE6E6FA,'lavenderblush':0xFFF0F5,'lawngreen':0x7CFC00,'lemonchiffon':0xFFFACD,'lightblue':0xADD8E6,'lightcoral':0xF08080,'lightcyan':0xE0FFFF,'lightgoldenrodyellow':0xFAFAD2,'lightgray':0xD3D3D3,'lightgreen':0x90EE90,'lightgrey':0xD3D3D3,'lightpink':0xFFB6C1,'lightsalmon':0xFFA07A,'lightseagreen':0x20B2AA,'lightskyblue':0x87CEFA,'lightslategray':0x778899,'lightslategrey':0x778899,'lightsteelblue':0xB0C4DE,'lightyellow':0xFFFFE0,'lime':0x00FF00,'limegreen':0x32CD32,'linen':0xFAF0E6,'magenta':0xFF00FF,'maroon':0x800000,'mediumaquamarine':0x66CDAA,'mediumblue':0x0000CD,'mediumorchid':0xBA55D3,'mediumpurple':0x9370DB,'mediumseagreen':0x3CB371,'mediumslateblue':0x7B68EE,'mediumspringgreen':0x00FA9A,'mediumturquoise':0x48D1CC,'mediumvioletred':0xC71585,'midnightblue':0x191970,'mintcream':0xF5FFFA,'mistyrose':0xFFE4E1,'moccasin':0xFFE4B5,'navajowhite':0xFFDEAD,'navy':0x000080,'oldlace':0xFDF5E6,'olive':0x808000,'olivedrab':0x6B8E23,'orange':0xFFA500,'orangered':0xFF4500,'orchid':0xDA70D6,'palegoldenrod':0xEEE8AA,'palegreen':0x98FB98,'paleturquoise':0xAFEEEE,'palevioletred':0xDB7093,'papayawhip':0xFFEFD5,'peachpuff':0xFFDAB9,'peru':0xCD853F,'pink':0xFFC0CB,'plum':0xDDA0DD,'powderblue':0xB0E0E6,'purple':0x800080,'rebeccapurple':0x663399,'red':0xFF0000,'rosybrown':0xBC8F8F,'royalblue':0x4169E1,'saddlebrown':0x8B4513,'salmon':0xFA8072,'sandybrown':0xF4A460,'seagreen':0x2E8B57,'seashell':0xFFF5EE,'sienna':0xA0522D,'silver':0xC0C0C0,'skyblue':0x87CEEB,'slateblue':0x6A5ACD,'slategray':0x708090,'slategrey':0x708090,'snow':0xFFFAFA,'springgreen':0x00FF7F,'steelblue':0x4682B4,'tan':0xD2B48C,'teal':0x008080,'thistle':0xD8BFD8,'tomato':0xFF6347,'turquoise':0x40E0D0,'violet':0xEE82EE,'wheat':0xF5DEB3,'white':0xFFFFFF,'whitesmoke':0xF5F5F5,'yellow':0xFFFF00,'yellowgreen':0x9ACD32};var _hslA={h:0,s:0,l:0};var _hslB={h:0,s:0,l:0};function hue2rgb(p,q,t){if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*6*(2/3-t);return p;}function SRGBToLinear(c){return c<0.04045?c*0.0773993808:Math.pow(c*0.9478672986+0.0521327014,2.4);}function LinearToSRGB(c){return c<0.0031308?c*12.92:1.055*Math.pow(c,0.41666)-0.055;}var Color=/*#__PURE__*/function(){function Color(r,g,b){_classCallCheck(this,Color);Object.defineProperty(this,'isColor',{value:true});if(g===undefined&&b===undefined){// r is THREE.Color, hex or string return this.set(r);}return this.setRGB(r,g,b);}_createClass(Color,[{key:"set",value:function set(value){if(value&&value.isColor){this.copy(value);}else if(typeof value==='number'){this.setHex(value);}else if(typeof value==='string'){this.setStyle(value);}return this;}},{key:"setScalar",value:function setScalar(scalar){this.r=scalar;this.g=scalar;this.b=scalar;return this;}},{key:"setHex",value:function setHex(hex){hex=Math.floor(hex);this.r=(hex>>16&255)/255;this.g=(hex>>8&255)/255;this.b=(hex&255)/255;return this;}},{key:"setRGB",value:function setRGB(r,g,b){this.r=r;this.g=g;this.b=b;return this;}},{key:"setHSL",value:function setHSL(h,s,l){// h,s,l ranges are in 0.0 - 1.0 h=MathUtils.euclideanModulo(h,1);s=MathUtils.clamp(s,0,1);l=MathUtils.clamp(l,0,1);if(s===0){this.r=this.g=this.b=l;}else{var p=l<=0.5?l*(1+s):l+s-l*s;var q=2*l-p;this.r=hue2rgb(q,p,h+1/3);this.g=hue2rgb(q,p,h);this.b=hue2rgb(q,p,h-1/3);}return this;}},{key:"setStyle",value:function setStyle(style){function handleAlpha(string){if(string===undefined)return;if(parseFloat(string)<1){console.warn('THREE.Color: Alpha component of '+style+' will be ignored.');}}var m;if(m=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)){// rgb / hsl var color;var name=m[1];var components=m[2];switch(name){case'rgb':case'rgba':if(color=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)){// rgb(255,0,0) rgba(255,0,0,0.5) this.r=Math.min(255,parseInt(color[1],10))/255;this.g=Math.min(255,parseInt(color[2],10))/255;this.b=Math.min(255,parseInt(color[3],10))/255;handleAlpha(color[5]);return this;}if(color=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)){// rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) this.r=Math.min(100,parseInt(color[1],10))/100;this.g=Math.min(100,parseInt(color[2],10))/100;this.b=Math.min(100,parseInt(color[3],10))/100;handleAlpha(color[5]);return this;}break;case'hsl':case'hsla':if(color=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)){// hsl(120,50%,50%) hsla(120,50%,50%,0.5) var h=parseFloat(color[1])/360;var s=parseInt(color[2],10)/100;var l=parseInt(color[3],10)/100;handleAlpha(color[5]);return this.setHSL(h,s,l);}break;}}else if(m=/^\#([A-Fa-f0-9]+)$/.exec(style)){// hex color var hex=m[1];var size=hex.length;if(size===3){// #ff0 this.r=parseInt(hex.charAt(0)+hex.charAt(0),16)/255;this.g=parseInt(hex.charAt(1)+hex.charAt(1),16)/255;this.b=parseInt(hex.charAt(2)+hex.charAt(2),16)/255;return this;}else if(size===6){// #ff0000 this.r=parseInt(hex.charAt(0)+hex.charAt(1),16)/255;this.g=parseInt(hex.charAt(2)+hex.charAt(3),16)/255;this.b=parseInt(hex.charAt(4)+hex.charAt(5),16)/255;return this;}}if(style&&style.length>0){return this.setColorName(style);}return this;}},{key:"setColorName",value:function setColorName(style){// color keywords var hex=_colorKeywords[style];if(hex!==undefined){// red this.setHex(hex);}else{// unknown color console.warn('THREE.Color: Unknown color '+style);}return this;}},{key:"clone",value:function clone(){return new this.constructor(this.r,this.g,this.b);}},{key:"copy",value:function copy(color){this.r=color.r;this.g=color.g;this.b=color.b;return this;}},{key:"copyGammaToLinear",value:function copyGammaToLinear(color,gammaFactor){if(gammaFactor===undefined)gammaFactor=2.0;this.r=Math.pow(color.r,gammaFactor);this.g=Math.pow(color.g,gammaFactor);this.b=Math.pow(color.b,gammaFactor);return this;}},{key:"copyLinearToGamma",value:function copyLinearToGamma(color,gammaFactor){if(gammaFactor===undefined)gammaFactor=2.0;var safeInverse=gammaFactor>0?1.0/gammaFactor:1.0;this.r=Math.pow(color.r,safeInverse);this.g=Math.pow(color.g,safeInverse);this.b=Math.pow(color.b,safeInverse);return this;}},{key:"convertGammaToLinear",value:function convertGammaToLinear(gammaFactor){this.copyGammaToLinear(this,gammaFactor);return this;}},{key:"convertLinearToGamma",value:function convertLinearToGamma(gammaFactor){this.copyLinearToGamma(this,gammaFactor);return this;}},{key:"copySRGBToLinear",value:function copySRGBToLinear(color){this.r=SRGBToLinear(color.r);this.g=SRGBToLinear(color.g);this.b=SRGBToLinear(color.b);return this;}},{key:"copyLinearToSRGB",value:function copyLinearToSRGB(color){this.r=LinearToSRGB(color.r);this.g=LinearToSRGB(color.g);this.b=LinearToSRGB(color.b);return this;}},{key:"convertSRGBToLinear",value:function convertSRGBToLinear(){this.copySRGBToLinear(this);return this;}},{key:"convertLinearToSRGB",value:function convertLinearToSRGB(){this.copyLinearToSRGB(this);return this;}},{key:"getHex",value:function getHex(){return this.r*255<<16^this.g*255<<8^this.b*255<<0;}},{key:"getHexString",value:function getHexString(){return('000000'+this.getHex().toString(16)).slice(-6);}},{key:"getHSL",value:function getHSL(target){// h,s,l ranges are in 0.0 - 1.0 if(target===undefined){console.warn('THREE.Color: .getHSL() target is now required');target={h:0,s:0,l:0};}var r=this.r,g=this.g,b=this.b;var max=Math.max(r,g,b);var min=Math.min(r,g,b);var hue,saturation;var lightness=(min+max)/2.0;if(min===max){hue=0;saturation=0;}else{var delta=max-min;saturation=lightness<=0.5?delta/(max+min):delta/(2-max-min);switch(max){case r:hue=(g-b)/delta+(g0)data.alphaTest=this.alphaTest;if(this.premultipliedAlpha===true)data.premultipliedAlpha=this.premultipliedAlpha;if(this.wireframe===true)data.wireframe=this.wireframe;if(this.wireframeLinewidth>1)data.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=='round')data.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=='round')data.wireframeLinejoin=this.wireframeLinejoin;if(this.morphTargets===true)data.morphTargets=true;if(this.morphNormals===true)data.morphNormals=true;if(this.skinning===true)data.skinning=true;if(this.visible===false)data.visible=false;if(this.toneMapped===false)data.toneMapped=false;if(JSON.stringify(this.userData)!=='{}')data.userData=this.userData;// TODO: Copied from Object3D.toJSON function extractFromCache(cache){var values=[];for(var key in cache){var _data=cache[key];delete _data.metadata;values.push(_data);}return values;}if(isRoot){var textures=extractFromCache(meta.textures);var images=extractFromCache(meta.images);if(textures.length>0)data.textures=textures;if(images.length>0)data.images=images;}return data;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(source){this.name=source.name;this.fog=source.fog;this.blending=source.blending;this.side=source.side;this.flatShading=source.flatShading;this.vertexColors=source.vertexColors;this.opacity=source.opacity;this.transparent=source.transparent;this.blendSrc=source.blendSrc;this.blendDst=source.blendDst;this.blendEquation=source.blendEquation;this.blendSrcAlpha=source.blendSrcAlpha;this.blendDstAlpha=source.blendDstAlpha;this.blendEquationAlpha=source.blendEquationAlpha;this.depthFunc=source.depthFunc;this.depthTest=source.depthTest;this.depthWrite=source.depthWrite;this.stencilWriteMask=source.stencilWriteMask;this.stencilFunc=source.stencilFunc;this.stencilRef=source.stencilRef;this.stencilFuncMask=source.stencilFuncMask;this.stencilFail=source.stencilFail;this.stencilZFail=source.stencilZFail;this.stencilZPass=source.stencilZPass;this.stencilWrite=source.stencilWrite;var srcPlanes=source.clippingPlanes;var dstPlanes=null;if(srcPlanes!==null){var n=srcPlanes.length;dstPlanes=new Array(n);for(var _i25=0;_i25!==n;++_i25){dstPlanes[_i25]=srcPlanes[_i25].clone();}}this.clippingPlanes=dstPlanes;this.clipIntersection=source.clipIntersection;this.clipShadows=source.clipShadows;this.shadowSide=source.shadowSide;this.colorWrite=source.colorWrite;this.precision=source.precision;this.polygonOffset=source.polygonOffset;this.polygonOffsetFactor=source.polygonOffsetFactor;this.polygonOffsetUnits=source.polygonOffsetUnits;this.dithering=source.dithering;this.alphaTest=source.alphaTest;this.premultipliedAlpha=source.premultipliedAlpha;this.visible=source.visible;this.toneMapped=source.toneMapped;this.userData=JSON.parse(JSON.stringify(source.userData));return this;},dispose:function dispose(){this.dispatchEvent({type:'dispose'});}});Object.defineProperty(Material.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});/** * parameters = { * color: , * opacity: , * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * depthTest: , * depthWrite: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: * } */function MeshBasicMaterial(parameters){Material.call(this);this.type='MeshBasicMaterial';this.color=new Color(0xffffff);// emissive this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.setValues(parameters);}MeshBasicMaterial.prototype=Object.create(Material.prototype);MeshBasicMaterial.prototype.constructor=MeshBasicMaterial;MeshBasicMaterial.prototype.isMeshBasicMaterial=true;MeshBasicMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;return this;};var _vector$3=new Vector3();var _vector2$1=new Vector2();function BufferAttribute(array,itemSize,normalized){if(Array.isArray(array)){throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');}this.name='';this.array=array;this.itemSize=itemSize;this.count=array!==undefined?array.length/itemSize:0;this.normalized=normalized===true;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0;}Object.defineProperty(BufferAttribute.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(BufferAttribute.prototype,{isBufferAttribute:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(source){this.name=source.name;this.array=new source.array.constructor(source.array);this.itemSize=source.itemSize;this.count=source.count;this.normalized=source.normalized;this.usage=source.usage;return this;},copyAt:function copyAt(index1,attribute,index2){index1*=this.itemSize;index2*=attribute.itemSize;for(var _i26=0,l=this.itemSize;_i260;var hasFaceVertexUv2=faceVertexUvs[1]&&faceVertexUvs[1].length>0;// morphs var morphTargets=geometry.morphTargets;var morphTargetsLength=morphTargets.length;var morphTargetsPosition;if(morphTargetsLength>0){morphTargetsPosition=[];for(var _i36=0;_i360){morphTargetsNormal=[];for(var _i37=0;_i370&&faces.length===0){console.error('THREE.DirectGeometry: Faceless geometries are not supported.');}for(var _i38=0;_i38max)max=array[_i39];}return max;}var _bufferGeometryId=1;// BufferGeometry uses odd numbers as Id var _m1$2=new Matrix4();var _obj=new Object3D();var _offset=new Vector3();var _box$2=new Box3();var _boxMorphTargets=new Box3();var _vector$4=new Vector3();function BufferGeometry(){Object.defineProperty(this,'id',{value:_bufferGeometryId+=2});this.uuid=MathUtils.generateUUID();this.name='';this.type='BufferGeometry';this.index=null;this.attributes={};this.morphAttributes={};this.morphTargetsRelative=false;this.groups=[];this.boundingBox=null;this.boundingSphere=null;this.drawRange={start:0,count:Infinity};this.userData={};}BufferGeometry.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:BufferGeometry,isBufferGeometry:true,getIndex:function getIndex(){return this.index;},setIndex:function setIndex(index){if(Array.isArray(index)){this.index=new(arrayMax(index)>65535?Uint32BufferAttribute:Uint16BufferAttribute)(index,1);}else{this.index=index;}return this;},getAttribute:function getAttribute(name){return this.attributes[name];},setAttribute:function setAttribute(name,attribute){this.attributes[name]=attribute;return this;},deleteAttribute:function deleteAttribute(name){delete this.attributes[name];return this;},addGroup:function addGroup(start,count,materialIndex){this.groups.push({start:start,count:count,materialIndex:materialIndex!==undefined?materialIndex:0});},clearGroups:function clearGroups(){this.groups=[];},setDrawRange:function setDrawRange(start,count){this.drawRange.start=start;this.drawRange.count=count;},applyMatrix4:function applyMatrix4(matrix){var position=this.attributes.position;if(position!==undefined){position.applyMatrix4(matrix);position.needsUpdate=true;}var normal=this.attributes.normal;if(normal!==undefined){var normalMatrix=new Matrix3().getNormalMatrix(matrix);normal.applyNormalMatrix(normalMatrix);normal.needsUpdate=true;}var tangent=this.attributes.tangent;if(tangent!==undefined){tangent.transformDirection(matrix);tangent.needsUpdate=true;}if(this.boundingBox!==null){this.computeBoundingBox();}if(this.boundingSphere!==null){this.computeBoundingSphere();}return this;},rotateX:function rotateX(angle){// rotate geometry around world x-axis _m1$2.makeRotationX(angle);this.applyMatrix4(_m1$2);return this;},rotateY:function rotateY(angle){// rotate geometry around world y-axis _m1$2.makeRotationY(angle);this.applyMatrix4(_m1$2);return this;},rotateZ:function rotateZ(angle){// rotate geometry around world z-axis _m1$2.makeRotationZ(angle);this.applyMatrix4(_m1$2);return this;},translate:function translate(x,y,z){// translate geometry _m1$2.makeTranslation(x,y,z);this.applyMatrix4(_m1$2);return this;},scale:function scale(x,y,z){// scale geometry _m1$2.makeScale(x,y,z);this.applyMatrix4(_m1$2);return this;},lookAt:function lookAt(vector){_obj.lookAt(vector);_obj.updateMatrix();this.applyMatrix4(_obj.matrix);return this;},center:function center(){this.computeBoundingBox();this.boundingBox.getCenter(_offset).negate();this.translate(_offset.x,_offset.y,_offset.z);return this;},setFromObject:function setFromObject(object){// console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); var geometry=object.geometry;if(object.isPoints||object.isLine){var positions=new Float32BufferAttribute(geometry.vertices.length*3,3);var colors=new Float32BufferAttribute(geometry.colors.length*3,3);this.setAttribute('position',positions.copyVector3sArray(geometry.vertices));this.setAttribute('color',colors.copyColorsArray(geometry.colors));if(geometry.lineDistances&&geometry.lineDistances.length===geometry.vertices.length){var lineDistances=new Float32BufferAttribute(geometry.lineDistances.length,1);this.setAttribute('lineDistance',lineDistances.copyArray(geometry.lineDistances));}if(geometry.boundingSphere!==null){this.boundingSphere=geometry.boundingSphere.clone();}if(geometry.boundingBox!==null){this.boundingBox=geometry.boundingBox.clone();}}else if(object.isMesh){if(geometry&&geometry.isGeometry){this.fromGeometry(geometry);}}return this;},setFromPoints:function setFromPoints(points){var position=[];for(var _i40=0,l=points.length;_i400){var normals=new Float32Array(geometry.normals.length*3);this.setAttribute('normal',new BufferAttribute(normals,3).copyVector3sArray(geometry.normals));}if(geometry.colors.length>0){var colors=new Float32Array(geometry.colors.length*3);this.setAttribute('color',new BufferAttribute(colors,3).copyColorsArray(geometry.colors));}if(geometry.uvs.length>0){var uvs=new Float32Array(geometry.uvs.length*2);this.setAttribute('uv',new BufferAttribute(uvs,2).copyVector2sArray(geometry.uvs));}if(geometry.uvs2.length>0){var uvs2=new Float32Array(geometry.uvs2.length*2);this.setAttribute('uv2',new BufferAttribute(uvs2,2).copyVector2sArray(geometry.uvs2));}// groups this.groups=geometry.groups;// morphs for(var name in geometry.morphTargets){var array=[];var morphTargets=geometry.morphTargets[name];for(var _i41=0,l=morphTargets.length;_i410){var skinIndices=new Float32BufferAttribute(geometry.skinIndices.length*4,4);this.setAttribute('skinIndex',skinIndices.copyVector4sArray(geometry.skinIndices));}if(geometry.skinWeights.length>0){var skinWeights=new Float32BufferAttribute(geometry.skinWeights.length*4,4);this.setAttribute('skinWeight',skinWeights.copyVector4sArray(geometry.skinWeights));}// if(geometry.boundingSphere!==null){this.boundingSphere=geometry.boundingSphere.clone();}if(geometry.boundingBox!==null){this.boundingBox=geometry.boundingBox.clone();}return this;},computeBoundingBox:function computeBoundingBox(){if(this.boundingBox===null){this.boundingBox=new Box3();}var position=this.attributes.position;var morphAttributesPosition=this.morphAttributes.position;if(position&&position.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".',this);this.boundingBox.set(new Vector3(-Infinity,-Infinity,-Infinity),new Vector3(+Infinity,+Infinity,+Infinity));return;}if(position!==undefined){this.boundingBox.setFromBufferAttribute(position);// process morph attributes if present if(morphAttributesPosition){for(var _i42=0,il=morphAttributesPosition.length;_i420)data.userData=this.userData;if(this.parameters!==undefined){var parameters=this.parameters;for(var key in parameters){if(parameters[key]!==undefined)data[key]=parameters[key];}return data;}data.data={attributes:{}};var index=this.index;if(index!==null){data.data.index={type:index.array.constructor.name,array:Array.prototype.slice.call(index.array)};}var attributes=this.attributes;for(var _key in attributes){var attribute=attributes[_key];var attributeData=attribute.toJSON(data.data);if(attribute.name!=='')attributeData.name=attribute.name;data.data.attributes[_key]=attributeData;}var morphAttributes={};var hasMorphAttributes=false;for(var _key2 in this.morphAttributes){var attributeArray=this.morphAttributes[_key2];var array=[];for(var _i54=0,il=attributeArray.length;_i540){morphAttributes[_key2]=array;hasMorphAttributes=true;}}if(hasMorphAttributes){data.data.morphAttributes=morphAttributes;data.data.morphTargetsRelative=this.morphTargetsRelative;}var groups=this.groups;if(groups.length>0){data.data.groups=JSON.parse(JSON.stringify(groups));}var boundingSphere=this.boundingSphere;if(boundingSphere!==null){data.data.boundingSphere={center:boundingSphere.center.toArray(),radius:boundingSphere.radius};}return data;},clone:function clone(){/* // Handle primitives const parameters = this.parameters; if ( parameters !== undefined ) { const values = []; for ( const key in parameters ) { values.push( parameters[ key ] ); } const geometry = Object.create( this.constructor.prototype ); this.constructor.apply( geometry, values ); return geometry; } return new this.constructor().copy( this ); */return new BufferGeometry().copy(this);},copy:function copy(source){// reset this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;// used for storing cloned, shared data var data={};// name this.name=source.name;// index var index=source.index;if(index!==null){this.setIndex(index.clone(data));}// attributes var attributes=source.attributes;for(var name in attributes){var attribute=attributes[name];this.setAttribute(name,attribute.clone(data));}// morph attributes var morphAttributes=source.morphAttributes;for(var _name2 in morphAttributes){var array=[];var morphAttribute=morphAttributes[_name2];// morphAttribute: array of Float32BufferAttributes for(var _i55=0,l=morphAttribute.length;_i550){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var m=0,ml=morphAttribute.length;m0){console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');}}},raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var material=this.material;var matrixWorld=this.matrixWorld;if(material===undefined)return;// Checking boundingSphere distance to ray if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere.copy(geometry.boundingSphere);_sphere.applyMatrix4(matrixWorld);if(raycaster.ray.intersectsSphere(_sphere)===false)return;// _inverseMatrix.getInverse(matrixWorld);_ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);// Check boundingBox before continuing if(geometry.boundingBox!==null){if(_ray.intersectsBox(geometry.boundingBox)===false)return;}var intersection;if(geometry.isBufferGeometry){var index=geometry.index;var position=geometry.attributes.position;var morphPosition=geometry.morphAttributes.position;var morphTargetsRelative=geometry.morphTargetsRelative;var uv=geometry.attributes.uv;var uv2=geometry.attributes.uv2;var groups=geometry.groups;var drawRange=geometry.drawRange;if(index!==null){// indexed buffer geometry if(Array.isArray(material)){for(var _i57=0,il=groups.length;_i570)uvs=faceVertexUvs;for(var f=0,fl=faces.length;fraycaster.far)return null;return{distance:distance,point:_intersectionPointWorld.clone(),object:object};}function checkBufferGeometryIntersection(object,material,raycaster,ray,position,morphPosition,morphTargetsRelative,uv,uv2,a,b,c){_vA.fromBufferAttribute(position,a);_vB.fromBufferAttribute(position,b);_vC.fromBufferAttribute(position,c);var morphInfluences=object.morphTargetInfluences;if(material.morphTargets&&morphPosition&&morphInfluences){_morphA.set(0,0,0);_morphB.set(0,0,0);_morphC.set(0,0,0);for(var _i61=0,il=morphPosition.length;_i610&&arguments[0]!==undefined?arguments[0]:1;var height=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var depth=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var widthSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var heightSegments=arguments.length>4&&arguments[4]!==undefined?arguments[4]:1;var depthSegments=arguments.length>5&&arguments[5]!==undefined?arguments[5]:1;_classCallCheck(this,BoxBufferGeometry);_this9=_super2.call(this);_this9.type='BoxBufferGeometry';_this9.parameters={width:width,height:height,depth:depth,widthSegments:widthSegments,heightSegments:heightSegments,depthSegments:depthSegments};var scope=_assertThisInitialized(_this9);// segments widthSegments=Math.floor(widthSegments);heightSegments=Math.floor(heightSegments);depthSegments=Math.floor(depthSegments);// buffers var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables var numberOfVertices=0;var groupStart=0;// build each side of the box geometry buildPlane('z','y','x',-1,-1,depth,height,width,depthSegments,heightSegments,0);// px buildPlane('z','y','x',1,-1,depth,height,-width,depthSegments,heightSegments,1);// nx buildPlane('x','z','y',1,1,width,depth,height,widthSegments,depthSegments,2);// py buildPlane('x','z','y',1,-1,width,depth,-height,widthSegments,depthSegments,3);// ny buildPlane('x','y','z',1,-1,width,height,depth,widthSegments,heightSegments,4);// pz buildPlane('x','y','z',-1,-1,width,height,-depth,widthSegments,heightSegments,5);// nz // build geometry _this9.setIndex(indices);_this9.setAttribute('position',new Float32BufferAttribute(vertices,3));_this9.setAttribute('normal',new Float32BufferAttribute(normals,3));_this9.setAttribute('uv',new Float32BufferAttribute(uvs,2));function buildPlane(u,v,w,udir,vdir,width,height,depth,gridX,gridY,materialIndex){var segmentWidth=width/gridX;var segmentHeight=height/gridY;var widthHalf=width/2;var heightHalf=height/2;var depthHalf=depth/2;var gridX1=gridX+1;var gridY1=gridY+1;var vertexCounter=0;var groupCount=0;var vector=new Vector3();// generate vertices, normals and uvs for(var iy=0;iy0?1:-1;// now apply vector to normal buffer normals.push(vector.x,vector.y,vector.z);// uvs uvs.push(ix/gridX);uvs.push(1-iy/gridY);// counters vertexCounter+=1;}}// indices // 1. you need three indices to draw a single face // 2. a single segment consists of two faces // 3. so we need to generate six (2*3) indices per segment for(var _iy=0;_iy, * vertexShader: , * * wireframe: , * wireframeLinewidth: , * * lights: , * * skinning: , * morphTargets: , * morphNormals: * } */function ShaderMaterial(parameters){Material.call(this);this.type='ShaderMaterial';this.defines={};this.uniforms={};this.vertexShader=default_vertex;this.fragmentShader=default_fragment;this.linewidth=1;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;// set to use scene fog this.lights=false;// set to use scene lights this.clipping=false;// set to use user-defined clipping planes this.skinning=false;// set to use skinning attribute streams this.morphTargets=false;// set to use morph targets this.morphNormals=false;// set to use morph normals this.extensions={derivatives:false,// set to use derivatives fragDepth:false,// set to use fragment depth values drawBuffers:false,// set to use draw buffers shaderTextureLOD:false// set to use shader texture LOD };// When rendered geometry doesn't include these attributes but the material does, // use these default values in WebGL. This avoids errors when buffer data is missing. this.defaultAttributeValues={'color':[1,1,1],'uv':[0,0],'uv2':[0,0]};this.index0AttributeName=undefined;this.uniformsNeedUpdate=false;this.glslVersion=null;if(parameters!==undefined){if(parameters.attributes!==undefined){console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');}this.setValues(parameters);}}ShaderMaterial.prototype=Object.create(Material.prototype);ShaderMaterial.prototype.constructor=ShaderMaterial;ShaderMaterial.prototype.isShaderMaterial=true;ShaderMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.fragmentShader=source.fragmentShader;this.vertexShader=source.vertexShader;this.uniforms=cloneUniforms(source.uniforms);this.defines=Object.assign({},source.defines);this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.lights=source.lights;this.clipping=source.clipping;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;this.extensions=Object.assign({},source.extensions);this.glslVersion=source.glslVersion;return this;};ShaderMaterial.prototype.toJSON=function(meta){var data=Material.prototype.toJSON.call(this,meta);data.glslVersion=this.glslVersion;data.uniforms={};for(var name in this.uniforms){var uniform=this.uniforms[name];var value=uniform.value;if(value&&value.isTexture){data.uniforms[name]={type:'t',value:value.toJSON(meta).uuid};}else if(value&&value.isColor){data.uniforms[name]={type:'c',value:value.getHex()};}else if(value&&value.isVector2){data.uniforms[name]={type:'v2',value:value.toArray()};}else if(value&&value.isVector3){data.uniforms[name]={type:'v3',value:value.toArray()};}else if(value&&value.isVector4){data.uniforms[name]={type:'v4',value:value.toArray()};}else if(value&&value.isMatrix3){data.uniforms[name]={type:'m3',value:value.toArray()};}else if(value&&value.isMatrix4){data.uniforms[name]={type:'m4',value:value.toArray()};}else{data.uniforms[name]={value:value};// note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far }}if(Object.keys(this.defines).length>0)data.defines=this.defines;data.vertexShader=this.vertexShader;data.fragmentShader=this.fragmentShader;var extensions={};for(var key in this.extensions){if(this.extensions[key]===true)extensions[key]=true;}if(Object.keys(extensions).length>0)data.extensions=extensions;return data;};function Camera(){Object3D.call(this);this.type='Camera';this.matrixWorldInverse=new Matrix4();this.projectionMatrix=new Matrix4();this.projectionMatrixInverse=new Matrix4();}Camera.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Camera,isCamera:true,copy:function copy(source,recursive){Object3D.prototype.copy.call(this,source,recursive);this.matrixWorldInverse.copy(source.matrixWorldInverse);this.projectionMatrix.copy(source.projectionMatrix);this.projectionMatrixInverse.copy(source.projectionMatrixInverse);return this;},getWorldDirection:function getWorldDirection(target){if(target===undefined){console.warn('THREE.Camera: .getWorldDirection() target is now required');target=new Vector3();}this.updateMatrixWorld(true);var e=this.matrixWorld.elements;return target.set(-e[8],-e[9],-e[10]).normalize();},updateMatrixWorld:function updateMatrixWorld(force){Object3D.prototype.updateMatrixWorld.call(this,force);this.matrixWorldInverse.getInverse(this.matrixWorld);},updateWorldMatrix:function updateWorldMatrix(updateParents,updateChildren){Object3D.prototype.updateWorldMatrix.call(this,updateParents,updateChildren);this.matrixWorldInverse.getInverse(this.matrixWorld);},clone:function clone(){return new this.constructor().copy(this);}});function PerspectiveCamera(fov,aspect,near,far){Camera.call(this);this.type='PerspectiveCamera';this.fov=fov!==undefined?fov:50;this.zoom=1;this.near=near!==undefined?near:0.1;this.far=far!==undefined?far:2000;this.focus=10;this.aspect=aspect!==undefined?aspect:1;this.view=null;this.filmGauge=35;// width of the film (default in millimeters) this.filmOffset=0;// horizontal film offset (same unit as gauge) this.updateProjectionMatrix();}PerspectiveCamera.prototype=Object.assign(Object.create(Camera.prototype),{constructor:PerspectiveCamera,isPerspectiveCamera:true,copy:function copy(source,recursive){Camera.prototype.copy.call(this,source,recursive);this.fov=source.fov;this.zoom=source.zoom;this.near=source.near;this.far=source.far;this.focus=source.focus;this.aspect=source.aspect;this.view=source.view===null?null:Object.assign({},source.view);this.filmGauge=source.filmGauge;this.filmOffset=source.filmOffset;return this;},/** * Sets the FOV by focal length in respect to the current .filmGauge. * * The default film gauge is 35, so that the focal length can be specified for * a 35mm (full frame) camera. * * Values for focal length and film gauge must have the same unit. */setFocalLength:function setFocalLength(focalLength){// see http://www.bobatkins.com/photography/technical/field_of_view.html var vExtentSlope=0.5*this.getFilmHeight()/focalLength;this.fov=MathUtils.RAD2DEG*2*Math.atan(vExtentSlope);this.updateProjectionMatrix();},/** * Calculates the focal length from the current .fov and .filmGauge. */getFocalLength:function getFocalLength(){var vExtentSlope=Math.tan(MathUtils.DEG2RAD*0.5*this.fov);return 0.5*this.getFilmHeight()/vExtentSlope;},getEffectiveFOV:function getEffectiveFOV(){return MathUtils.RAD2DEG*2*Math.atan(Math.tan(MathUtils.DEG2RAD*0.5*this.fov)/this.zoom);},getFilmWidth:function getFilmWidth(){// film not completely covered in portrait format (aspect < 1) return this.filmGauge*Math.min(this.aspect,1);},getFilmHeight:function getFilmHeight(){// film not completely covered in landscape format (aspect > 1) return this.filmGauge/Math.max(this.aspect,1);},/** * Sets an offset in a larger frustum. This is useful for multi-window or * multi-monitor/multi-machine setups. * * For example, if you have 3x2 monitors and each monitor is 1920x1080 and * the monitors are in grid like this * * +---+---+---+ * | A | B | C | * +---+---+---+ * | D | E | F | * +---+---+---+ * * then for each monitor you would call it like this * * const w = 1920; * const h = 1080; * const fullWidth = w * 3; * const fullHeight = h * 2; * * --A-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); * --B-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); * --C-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); * --D-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); * --E-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); * --F-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); * * Note there is no reason monitors have to be the same size or in a grid. */setViewOffset:function setViewOffset(fullWidth,fullHeight,x,y,width,height){this.aspect=fullWidth/fullHeight;if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1};}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x;this.view.offsetY=y;this.view.width=width;this.view.height=height;this.updateProjectionMatrix();},clearViewOffset:function clearViewOffset(){if(this.view!==null){this.view.enabled=false;}this.updateProjectionMatrix();},updateProjectionMatrix:function updateProjectionMatrix(){var near=this.near;var top=near*Math.tan(MathUtils.DEG2RAD*0.5*this.fov)/this.zoom;var height=2*top;var width=this.aspect*height;var left=-0.5*width;var view=this.view;if(this.view!==null&&this.view.enabled){var fullWidth=view.fullWidth,fullHeight=view.fullHeight;left+=view.offsetX*width/fullWidth;top-=view.offsetY*height/fullHeight;width*=view.width/fullWidth;height*=view.height/fullHeight;}var skew=this.filmOffset;if(skew!==0)left+=near*skew/this.getFilmWidth();this.projectionMatrix.makePerspective(left,left+width,top,top-height,near,this.far);this.projectionMatrixInverse.getInverse(this.projectionMatrix);},toJSON:function toJSON(meta){var data=Object3D.prototype.toJSON.call(this,meta);data.object.fov=this.fov;data.object.zoom=this.zoom;data.object.near=this.near;data.object.far=this.far;data.object.focus=this.focus;data.object.aspect=this.aspect;if(this.view!==null)data.object.view=Object.assign({},this.view);data.object.filmGauge=this.filmGauge;data.object.filmOffset=this.filmOffset;return data;}});var fov=90,aspect=1;function CubeCamera(near,far,renderTarget){Object3D.call(this);this.type='CubeCamera';if(renderTarget.isWebGLCubeRenderTarget!==true){console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');return;}this.renderTarget=renderTarget;var cameraPX=new PerspectiveCamera(fov,aspect,near,far);cameraPX.layers=this.layers;cameraPX.up.set(0,-1,0);cameraPX.lookAt(new Vector3(1,0,0));this.add(cameraPX);var cameraNX=new PerspectiveCamera(fov,aspect,near,far);cameraNX.layers=this.layers;cameraNX.up.set(0,-1,0);cameraNX.lookAt(new Vector3(-1,0,0));this.add(cameraNX);var cameraPY=new PerspectiveCamera(fov,aspect,near,far);cameraPY.layers=this.layers;cameraPY.up.set(0,0,1);cameraPY.lookAt(new Vector3(0,1,0));this.add(cameraPY);var cameraNY=new PerspectiveCamera(fov,aspect,near,far);cameraNY.layers=this.layers;cameraNY.up.set(0,0,-1);cameraNY.lookAt(new Vector3(0,-1,0));this.add(cameraNY);var cameraPZ=new PerspectiveCamera(fov,aspect,near,far);cameraPZ.layers=this.layers;cameraPZ.up.set(0,-1,0);cameraPZ.lookAt(new Vector3(0,0,1));this.add(cameraPZ);var cameraNZ=new PerspectiveCamera(fov,aspect,near,far);cameraNZ.layers=this.layers;cameraNZ.up.set(0,-1,0);cameraNZ.lookAt(new Vector3(0,0,-1));this.add(cameraNZ);this.update=function(renderer,scene){if(this.parent===null)this.updateMatrixWorld();var currentXrEnabled=renderer.xr.enabled;var currentRenderTarget=renderer.getRenderTarget();renderer.xr.enabled=false;var generateMipmaps=renderTarget.texture.generateMipmaps;renderTarget.texture.generateMipmaps=false;renderer.setRenderTarget(renderTarget,0);renderer.render(scene,cameraPX);renderer.setRenderTarget(renderTarget,1);renderer.render(scene,cameraNX);renderer.setRenderTarget(renderTarget,2);renderer.render(scene,cameraPY);renderer.setRenderTarget(renderTarget,3);renderer.render(scene,cameraNY);renderer.setRenderTarget(renderTarget,4);renderer.render(scene,cameraPZ);renderTarget.texture.generateMipmaps=generateMipmaps;renderer.setRenderTarget(renderTarget,5);renderer.render(scene,cameraNZ);renderer.setRenderTarget(currentRenderTarget);renderer.xr.enabled=currentXrEnabled;};this.clear=function(renderer,color,depth,stencil){var currentRenderTarget=renderer.getRenderTarget();for(var _i62=0;_i62<6;_i62++){renderer.setRenderTarget(renderTarget,_i62);renderer.clear(color,depth,stencil);}renderer.setRenderTarget(currentRenderTarget);};}CubeCamera.prototype=Object.create(Object3D.prototype);CubeCamera.prototype.constructor=CubeCamera;function CubeTexture(images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding){images=images!==undefined?images:[];mapping=mapping!==undefined?mapping:CubeReflectionMapping;format=format!==undefined?format:RGBFormat;Texture.call(this,images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.flipY=false;this._needsFlipEnvMap=true;}CubeTexture.prototype=Object.create(Texture.prototype);CubeTexture.prototype.constructor=CubeTexture;CubeTexture.prototype.isCubeTexture=true;Object.defineProperty(CubeTexture.prototype,'images',{get:function get(){return this.image;},set:function set(value){this.image=value;}});function WebGLCubeRenderTarget(size,options,dummy){if(Number.isInteger(options)){console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');options=dummy;}WebGLRenderTarget.call(this,size,size,options);options=options||{};this.texture=new CubeTexture(undefined,options.mapping,options.wrapS,options.wrapT,options.magFilter,options.minFilter,options.format,options.type,options.anisotropy,options.encoding);this.texture._needsFlipEnvMap=false;}WebGLCubeRenderTarget.prototype=Object.create(WebGLRenderTarget.prototype);WebGLCubeRenderTarget.prototype.constructor=WebGLCubeRenderTarget;WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget=true;WebGLCubeRenderTarget.prototype.fromEquirectangularTexture=function(renderer,texture){this.texture.type=texture.type;this.texture.format=RGBAFormat;// see #18859 this.texture.encoding=texture.encoding;this.texture.generateMipmaps=texture.generateMipmaps;this.texture.minFilter=texture.minFilter;this.texture.magFilter=texture.magFilter;var shader={uniforms:{tEquirect:{value:null}},vertexShader:/* glsl */"\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t#include \n\t\t\t\t#include \n\n\t\t\t}\n\t\t",fragmentShader:/* glsl */"\n\n\t\t\tuniform sampler2D tEquirect;\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t}\n\t\t"};var geometry=new BoxBufferGeometry(5,5,5);var material=new ShaderMaterial({name:'CubemapFromEquirect',uniforms:cloneUniforms(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader,side:BackSide,blending:NoBlending});material.uniforms.tEquirect.value=texture;var mesh=new Mesh(geometry,material);var currentMinFilter=texture.minFilter;// Avoid blurred poles if(texture.minFilter===LinearMipmapLinearFilter)texture.minFilter=LinearFilter;var camera=new CubeCamera(1,10,this);camera.update(renderer,mesh);texture.minFilter=currentMinFilter;mesh.geometry.dispose();mesh.material.dispose();return this;};function DataTexture(data,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){Texture.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.image={data:data||null,width:width||1,height:height||1};this.magFilter=magFilter!==undefined?magFilter:NearestFilter;this.minFilter=minFilter!==undefined?minFilter:NearestFilter;this.generateMipmaps=false;this.flipY=false;this.unpackAlignment=1;this.needsUpdate=true;}DataTexture.prototype=Object.create(Texture.prototype);DataTexture.prototype.constructor=DataTexture;DataTexture.prototype.isDataTexture=true;var _sphere$1=/*@__PURE__*/new Sphere();var _vector$5=/*@__PURE__*/new Vector3();var Frustum=/*#__PURE__*/function(){function Frustum(p0,p1,p2,p3,p4,p5){_classCallCheck(this,Frustum);this.planes=[p0!==undefined?p0:new Plane(),p1!==undefined?p1:new Plane(),p2!==undefined?p2:new Plane(),p3!==undefined?p3:new Plane(),p4!==undefined?p4:new Plane(),p5!==undefined?p5:new Plane()];}_createClass(Frustum,[{key:"set",value:function set(p0,p1,p2,p3,p4,p5){var planes=this.planes;planes[0].copy(p0);planes[1].copy(p1);planes[2].copy(p2);planes[3].copy(p3);planes[4].copy(p4);planes[5].copy(p5);return this;}},{key:"clone",value:function clone(){return new this.constructor().copy(this);}},{key:"copy",value:function copy(frustum){var planes=this.planes;for(var _i63=0;_i63<6;_i63++){planes[_i63].copy(frustum.planes[_i63]);}return this;}},{key:"setFromProjectionMatrix",value:function setFromProjectionMatrix(m){var planes=this.planes;var me=m.elements;var me0=me[0],me1=me[1],me2=me[2],me3=me[3];var me4=me[4],me5=me[5],me6=me[6],me7=me[7];var me8=me[8],me9=me[9],me10=me[10],me11=me[11];var me12=me[12],me13=me[13],me14=me[14],me15=me[15];planes[0].setComponents(me3-me0,me7-me4,me11-me8,me15-me12).normalize();planes[1].setComponents(me3+me0,me7+me4,me11+me8,me15+me12).normalize();planes[2].setComponents(me3+me1,me7+me5,me11+me9,me15+me13).normalize();planes[3].setComponents(me3-me1,me7-me5,me11-me9,me15-me13).normalize();planes[4].setComponents(me3-me2,me7-me6,me11-me10,me15-me14).normalize();planes[5].setComponents(me3+me2,me7+me6,me11+me10,me15+me14).normalize();return this;}},{key:"intersectsObject",value:function intersectsObject(object){var geometry=object.geometry;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);return this.intersectsSphere(_sphere$1);}},{key:"intersectsSprite",value:function intersectsSprite(sprite){_sphere$1.center.set(0,0,0);_sphere$1.radius=0.7071067811865476;_sphere$1.applyMatrix4(sprite.matrixWorld);return this.intersectsSphere(_sphere$1);}},{key:"intersectsSphere",value:function intersectsSphere(sphere){var planes=this.planes;var center=sphere.center;var negRadius=-sphere.radius;for(var _i64=0;_i64<6;_i64++){var distance=planes[_i64].distanceToPoint(center);if(distance0?box.max.x:box.min.x;_vector$5.y=plane.normal.y>0?box.max.y:box.min.y;_vector$5.z=plane.normal.z>0?box.max.z:box.min.z;if(plane.distanceToPoint(_vector$5)<0){return false;}}return true;}},{key:"containsPoint",value:function containsPoint(point){var planes=this.planes;for(var _i66=0;_i66<6;_i66++){if(planes[_i66].distanceToPoint(point)<0){return false;}}return true;}}]);return Frustum;}();function WebGLAnimation(){var context=null;var isAnimating=false;var animationLoop=null;var requestId=null;function onAnimationFrame(time,frame){animationLoop(time,frame);requestId=context.requestAnimationFrame(onAnimationFrame);}return{start:function start(){if(isAnimating===true)return;if(animationLoop===null)return;requestId=context.requestAnimationFrame(onAnimationFrame);isAnimating=true;},stop:function stop(){context.cancelAnimationFrame(requestId);isAnimating=false;},setAnimationLoop:function setAnimationLoop(callback){animationLoop=callback;},setContext:function setContext(value){context=value;}};}function WebGLAttributes(gl,capabilities){var isWebGL2=capabilities.isWebGL2;var buffers=new WeakMap();function createBuffer(attribute,bufferType){var array=attribute.array;var usage=attribute.usage;var buffer=gl.createBuffer();gl.bindBuffer(bufferType,buffer);gl.bufferData(bufferType,array,usage);attribute.onUploadCallback();var type=5126;if(_instanceof(array,Float32Array)){type=5126;}else if(_instanceof(array,Float64Array)){console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');}else if(_instanceof(array,Uint16Array)){type=5123;}else if(_instanceof(array,Int16Array)){type=5122;}else if(_instanceof(array,Uint32Array)){type=5125;}else if(_instanceof(array,Int32Array)){type=5124;}else if(_instanceof(array,Int8Array)){type=5120;}else if(_instanceof(array,Uint8Array)){type=5121;}return{buffer:buffer,type:type,bytesPerElement:array.BYTES_PER_ELEMENT,version:attribute.version};}function updateBuffer(buffer,attribute,bufferType){var array=attribute.array;var updateRange=attribute.updateRange;gl.bindBuffer(bufferType,buffer);if(updateRange.count===-1){// Not using update ranges gl.bufferSubData(bufferType,0,array);}else{if(isWebGL2){gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array,updateRange.offset,updateRange.count);}else{gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array.subarray(updateRange.offset,updateRange.offset+updateRange.count));}updateRange.count=-1;// reset range }}// function get(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;return buffers.get(attribute);}function remove(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;var data=buffers.get(attribute);if(data){gl.deleteBuffer(data.buffer);buffers.delete(attribute);}}function update(attribute,bufferType){if(attribute.isGLBufferAttribute){var cached=buffers.get(attribute);if(!cached||cached.version=0){var geometryAttribute=geometryAttributes[name];if(geometryAttribute!==undefined){var normalized=geometryAttribute.normalized;var size=geometryAttribute.itemSize;var attribute=attributes.get(geometryAttribute);// TODO Attribute may not be available on context restore if(attribute===undefined)continue;var buffer=attribute.buffer;var type=attribute.type;var bytesPerElement=attribute.bytesPerElement;if(geometryAttribute.isInterleavedBufferAttribute){var data=geometryAttribute.data;var stride=data.stride;var offset=geometryAttribute.offset;if(data&&data.isInstancedInterleavedBuffer){enableAttributeAndDivisor(programAttribute,data.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=data.meshPerAttribute*data.count;}}else{enableAttribute(programAttribute);}gl.bindBuffer(34962,buffer);vertexAttribPointer(programAttribute,size,type,normalized,stride*bytesPerElement,offset*bytesPerElement);}else{if(geometryAttribute.isInstancedBufferAttribute){enableAttributeAndDivisor(programAttribute,geometryAttribute.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=geometryAttribute.meshPerAttribute*geometryAttribute.count;}}else{enableAttribute(programAttribute);}gl.bindBuffer(34962,buffer);vertexAttribPointer(programAttribute,size,type,normalized,0,0);}}else if(name==='instanceMatrix'){var _attribute7=attributes.get(object.instanceMatrix);// TODO Attribute may not be available on context restore if(_attribute7===undefined)continue;var _buffer=_attribute7.buffer;var _type=_attribute7.type;enableAttributeAndDivisor(programAttribute+0,1);enableAttributeAndDivisor(programAttribute+1,1);enableAttributeAndDivisor(programAttribute+2,1);enableAttributeAndDivisor(programAttribute+3,1);gl.bindBuffer(34962,_buffer);gl.vertexAttribPointer(programAttribute+0,4,_type,false,64,0);gl.vertexAttribPointer(programAttribute+1,4,_type,false,64,16);gl.vertexAttribPointer(programAttribute+2,4,_type,false,64,32);gl.vertexAttribPointer(programAttribute+3,4,_type,false,64,48);}else if(name==='instanceColor'){var _attribute8=attributes.get(object.instanceColor);// TODO Attribute may not be available on context restore if(_attribute8===undefined)continue;var _buffer2=_attribute8.buffer;var _type2=_attribute8.type;enableAttributeAndDivisor(programAttribute,1);gl.bindBuffer(34962,_buffer2);gl.vertexAttribPointer(programAttribute,3,_type2,false,12,0);}else if(materialDefaultAttributeValues!==undefined){var value=materialDefaultAttributeValues[name];if(value!==undefined){switch(value.length){case 2:gl.vertexAttrib2fv(programAttribute,value);break;case 3:gl.vertexAttrib3fv(programAttribute,value);break;case 4:gl.vertexAttrib4fv(programAttribute,value);break;default:gl.vertexAttrib1fv(programAttribute,value);}}}}}disableUnusedAttributes();}function dispose(){reset();for(var geometryId in bindingStates){var programMap=bindingStates[geometryId];for(var programId in programMap){var stateMap=programMap[programId];for(var wireframe in stateMap){deleteVertexArrayObject(stateMap[wireframe].object);delete stateMap[wireframe];}delete programMap[programId];}delete bindingStates[geometryId];}}function releaseStatesOfGeometry(geometry){if(bindingStates[geometry.id]===undefined)return;var programMap=bindingStates[geometry.id];for(var programId in programMap){var stateMap=programMap[programId];for(var wireframe in stateMap){deleteVertexArrayObject(stateMap[wireframe].object);delete stateMap[wireframe];}delete programMap[programId];}delete bindingStates[geometry.id];}function releaseStatesOfProgram(program){for(var geometryId in bindingStates){var programMap=bindingStates[geometryId];if(programMap[program.id]===undefined)continue;var stateMap=programMap[program.id];for(var wireframe in stateMap){deleteVertexArrayObject(stateMap[wireframe].object);delete stateMap[wireframe];}delete programMap[program.id];}}function reset(){resetDefaultState();if(currentState===defaultState)return;currentState=defaultState;bindVertexArrayObject(currentState.object);}// for backward-compatilibity function resetDefaultState(){defaultState.geometry=null;defaultState.program=null;defaultState.wireframe=false;}return{setup:setup,reset:reset,resetDefaultState:resetDefaultState,dispose:dispose,releaseStatesOfGeometry:releaseStatesOfGeometry,releaseStatesOfProgram:releaseStatesOfProgram,initAttributes:initAttributes,enableAttribute:enableAttribute,disableUnusedAttributes:disableUnusedAttributes};}function WebGLBufferRenderer(gl,extensions,info,capabilities){var isWebGL2=capabilities.isWebGL2;var mode;function setMode(value){mode=value;}function render(start,count){gl.drawArrays(mode,start,count);info.update(count,mode,1);}function renderInstances(start,count,primcount){if(primcount===0)return;var extension,methodName;if(isWebGL2){extension=gl;methodName='drawArraysInstanced';}else{extension=extensions.get('ANGLE_instanced_arrays');methodName='drawArraysInstancedANGLE';if(extension===null){console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');return;}}extension[methodName](mode,start,count,primcount);info.update(count,mode,primcount);}// this.setMode=setMode;this.render=render;this.renderInstances=renderInstances;}function WebGLCapabilities(gl,extensions,parameters){var maxAnisotropy;function getMaxAnisotropy(){if(maxAnisotropy!==undefined)return maxAnisotropy;var extension=extensions.get('EXT_texture_filter_anisotropic');if(extension!==null){maxAnisotropy=gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);}else{maxAnisotropy=0;}return maxAnisotropy;}function getMaxPrecision(precision){if(precision==='highp'){if(gl.getShaderPrecisionFormat(35633,36338).precision>0&&gl.getShaderPrecisionFormat(35632,36338).precision>0){return'highp';}precision='mediump';}if(precision==='mediump'){if(gl.getShaderPrecisionFormat(35633,36337).precision>0&&gl.getShaderPrecisionFormat(35632,36337).precision>0){return'mediump';}}return'lowp';}/* eslint-disable no-undef */var isWebGL2=typeof WebGL2RenderingContext!=='undefined'&&_instanceof(gl,WebGL2RenderingContext)||typeof WebGL2ComputeRenderingContext!=='undefined'&&_instanceof(gl,WebGL2ComputeRenderingContext);/* eslint-enable no-undef */var precision=parameters.precision!==undefined?parameters.precision:'highp';var maxPrecision=getMaxPrecision(precision);if(maxPrecision!==precision){console.warn('THREE.WebGLRenderer:',precision,'not supported, using',maxPrecision,'instead.');precision=maxPrecision;}var logarithmicDepthBuffer=parameters.logarithmicDepthBuffer===true;var maxTextures=gl.getParameter(34930);var maxVertexTextures=gl.getParameter(35660);var maxTextureSize=gl.getParameter(3379);var maxCubemapSize=gl.getParameter(34076);var maxAttributes=gl.getParameter(34921);var maxVertexUniforms=gl.getParameter(36347);var maxVaryings=gl.getParameter(36348);var maxFragmentUniforms=gl.getParameter(36349);var vertexTextures=maxVertexTextures>0;var floatFragmentTextures=isWebGL2||!!extensions.get('OES_texture_float');var floatVertexTextures=vertexTextures&&floatFragmentTextures;var maxSamples=isWebGL2?gl.getParameter(36183):0;return{isWebGL2:isWebGL2,getMaxAnisotropy:getMaxAnisotropy,getMaxPrecision:getMaxPrecision,precision:precision,logarithmicDepthBuffer:logarithmicDepthBuffer,maxTextures:maxTextures,maxVertexTextures:maxVertexTextures,maxTextureSize:maxTextureSize,maxCubemapSize:maxCubemapSize,maxAttributes:maxAttributes,maxVertexUniforms:maxVertexUniforms,maxVaryings:maxVaryings,maxFragmentUniforms:maxFragmentUniforms,vertexTextures:vertexTextures,floatFragmentTextures:floatFragmentTextures,floatVertexTextures:floatVertexTextures,maxSamples:maxSamples};}function WebGLClipping(properties){var scope=this;var globalState=null,numGlobalPlanes=0,localClippingEnabled=false,renderingShadows=false;var plane=new Plane(),viewNormalMatrix=new Matrix3(),uniform={value:null,needsUpdate:false};this.uniform=uniform;this.numPlanes=0;this.numIntersection=0;this.init=function(planes,enableLocalClipping,camera){var enabled=planes.length!==0||enableLocalClipping||// enable state of previous frame - the clipping code has to // run another frame in order to reset the state: numGlobalPlanes!==0||localClippingEnabled;localClippingEnabled=enableLocalClipping;globalState=projectPlanes(planes,camera,0);numGlobalPlanes=planes.length;return enabled;};this.beginShadows=function(){renderingShadows=true;projectPlanes(null);};this.endShadows=function(){renderingShadows=false;resetGlobalState();};this.setState=function(material,camera,useCache){var planes=material.clippingPlanes,clipIntersection=material.clipIntersection,clipShadows=material.clipShadows;var materialProperties=properties.get(material);if(!localClippingEnabled||planes===null||planes.length===0||renderingShadows&&!clipShadows){// there's no local clipping if(renderingShadows){// there's no global clipping projectPlanes(null);}else{resetGlobalState();}}else{var nGlobal=renderingShadows?0:numGlobalPlanes,lGlobal=nGlobal*4;var dstArray=materialProperties.clippingState||null;uniform.value=dstArray;// ensure unique state dstArray=projectPlanes(planes,camera,lGlobal,useCache);for(var _i70=0;_i70!==lGlobal;++_i70){dstArray[_i70]=globalState[_i70];}materialProperties.clippingState=dstArray;this.numIntersection=clipIntersection?this.numPlanes:0;this.numPlanes+=nGlobal;}};function resetGlobalState(){if(uniform.value!==globalState){uniform.value=globalState;uniform.needsUpdate=numGlobalPlanes>0;}scope.numPlanes=numGlobalPlanes;scope.numIntersection=0;}function projectPlanes(planes,camera,dstOffset,skipTransform){var nPlanes=planes!==null?planes.length:0;var dstArray=null;if(nPlanes!==0){dstArray=uniform.value;if(skipTransform!==true||dstArray===null){var flatSize=dstOffset+nPlanes*4,viewMatrix=camera.matrixWorldInverse;viewNormalMatrix.getNormalMatrix(viewMatrix);if(dstArray===null||dstArray.length0){var currentRenderList=renderer.getRenderList();var currentRenderTarget=renderer.getRenderTarget();var currentRenderState=renderer.getRenderState();var renderTarget=new WebGLCubeRenderTarget(image.height/2);renderTarget.fromEquirectangularTexture(renderer,texture);cubemaps.set(texture,renderTarget);renderer.setRenderTarget(currentRenderTarget);renderer.setRenderList(currentRenderList);renderer.setRenderState(currentRenderState);return mapTextureMapping(renderTarget.texture,texture.mapping);}else{// image not yet ready. try the conversion next frame return null;}}}}return texture;}function dispose(){cubemaps=new WeakMap();}return{get:get,dispose:dispose};}function WebGLExtensions(gl){var extensions={};return{has:function has(name){if(extensions[name]!==undefined){return extensions[name]!==null;}var extension;switch(name){case'WEBGL_depth_texture':extension=gl.getExtension('WEBGL_depth_texture')||gl.getExtension('MOZ_WEBGL_depth_texture')||gl.getExtension('WEBKIT_WEBGL_depth_texture');break;case'EXT_texture_filter_anisotropic':extension=gl.getExtension('EXT_texture_filter_anisotropic')||gl.getExtension('MOZ_EXT_texture_filter_anisotropic')||gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');break;case'WEBGL_compressed_texture_s3tc':extension=gl.getExtension('WEBGL_compressed_texture_s3tc')||gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc')||gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');break;case'WEBGL_compressed_texture_pvrtc':extension=gl.getExtension('WEBGL_compressed_texture_pvrtc')||gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');break;default:extension=gl.getExtension(name);}extensions[name]=extension;return extension!==null;},get:function get(name){if(!this.has(name)){console.warn('THREE.WebGLRenderer: '+name+' extension not supported.');}return extensions[name];}};}function WebGLGeometries(gl,attributes,info,bindingStates){var geometries=new WeakMap();var wireframeAttributes=new WeakMap();function onGeometryDispose(event){var geometry=event.target;var buffergeometry=geometries.get(geometry);if(buffergeometry.index!==null){attributes.remove(buffergeometry.index);}for(var name in buffergeometry.attributes){attributes.remove(buffergeometry.attributes[name]);}geometry.removeEventListener('dispose',onGeometryDispose);geometries.delete(geometry);var attribute=wireframeAttributes.get(buffergeometry);if(attribute){attributes.remove(attribute);wireframeAttributes.delete(buffergeometry);}bindingStates.releaseStatesOfGeometry(geometry);if(geometry.isInstancedBufferGeometry===true){delete geometry._maxInstanceCount;}// info.memory.geometries--;}function get(object,geometry){var buffergeometry=geometries.get(geometry);if(buffergeometry)return buffergeometry;geometry.addEventListener('dispose',onGeometryDispose);if(geometry.isBufferGeometry){buffergeometry=geometry;}else if(geometry.isGeometry){if(geometry._bufferGeometry===undefined){geometry._bufferGeometry=new BufferGeometry().setFromObject(object);}buffergeometry=geometry._bufferGeometry;}geometries.set(geometry,buffergeometry);info.memory.geometries++;return buffergeometry;}function update(geometry){var geometryAttributes=geometry.attributes;// Updating index buffer in VAO now. See WebGLBindingStates. for(var name in geometryAttributes){attributes.update(geometryAttributes[name],34962);}// morph targets var morphAttributes=geometry.morphAttributes;for(var _name3 in morphAttributes){var array=morphAttributes[_name3];for(var _i72=0,l=array.length;_i7265535?Uint32BufferAttribute:Uint16BufferAttribute)(indices,1);attribute.version=version;// Updating index buffer in VAO now. See WebGLBindingStates // var previousAttribute=wireframeAttributes.get(geometry);if(previousAttribute)attributes.remove(previousAttribute);// wireframeAttributes.set(geometry,attribute);}function getWireframeAttribute(geometry){var currentAttribute=wireframeAttributes.get(geometry);if(currentAttribute){var geometryIndex=geometry.index;if(geometryIndex!==null){// if the attribute is obsolete, create a new one if(currentAttribute.version0)return array;// unoptimized: ! isNaN( firstElem ) // see http://jacksondunstan.com/articles/983 var n=nBlocks*blockSize;var r=arrayCacheF32[n];if(r===undefined){r=new Float32Array(n);arrayCacheF32[n]=r;}if(nBlocks!==0){firstElem.toArray(r,0);for(var _i80=1,offset=0;_i80!==nBlocks;++_i80){offset+=blockSize;array[_i80].toArray(r,offset);}}return r;}function arraysEqual(a,b){if(a.length!==b.length)return false;for(var _i81=0,l=a.length;_i81/gm;function resolveIncludes(string){return string.replace(includePattern,includeReplacer);}function includeReplacer(match,include){var string=ShaderChunk[include];if(string===undefined){throw new Error('Can not resolve #include <'+include+'>');}return resolveIncludes(string);}// Unroll Loops var deprecatedUnrollLoopPattern=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;var unrollLoopPattern=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function unrollLoops(string){return string.replace(unrollLoopPattern,loopReplacer).replace(deprecatedUnrollLoopPattern,deprecatedLoopReplacer);}function deprecatedLoopReplacer(match,start,end,snippet){console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');return loopReplacer(match,start,end,snippet);}function loopReplacer(match,start,end,snippet){var string='';for(var _i92=parseInt(start);_i920?renderer.gammaFactor:1.0;var customExtensions=parameters.isWebGL2?'':generateExtensions(parameters);var customDefines=generateDefines(defines);var program=gl.createProgram();var prefixVertex,prefixFragment;var versionString=parameters.glslVersion?'#version '+parameters.glslVersion+"\n":'';if(parameters.isRawShaderMaterial){prefixVertex=[customDefines].filter(filterEmptyLine).join('\n');if(prefixVertex.length>0){prefixVertex+='\n';}prefixFragment=[customExtensions,customDefines].filter(filterEmptyLine).join('\n');if(prefixFragment.length>0){prefixFragment+='\n';}}else{prefixVertex=[generatePrecision(parameters),'#define SHADER_NAME '+parameters.shaderName,customDefines,parameters.instancing?'#define USE_INSTANCING':'',parameters.instancingColor?'#define USE_INSTANCING_COLOR':'',parameters.supportsVertexTextures?'#define VERTEX_TEXTURES':'','#define GAMMA_FACTOR '+gammaFactorDefine,'#define MAX_BONES '+parameters.maxBones,parameters.useFog&¶meters.fog?'#define USE_FOG':'',parameters.useFog&¶meters.fogExp2?'#define FOG_EXP2':'',parameters.map?'#define USE_MAP':'',parameters.envMap?'#define USE_ENVMAP':'',parameters.envMap?'#define '+envMapModeDefine:'',parameters.lightMap?'#define USE_LIGHTMAP':'',parameters.aoMap?'#define USE_AOMAP':'',parameters.emissiveMap?'#define USE_EMISSIVEMAP':'',parameters.bumpMap?'#define USE_BUMPMAP':'',parameters.normalMap?'#define USE_NORMALMAP':'',parameters.normalMap&¶meters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&¶meters.tangentSpaceNormalMap?'#define TANGENTSPACE_NORMALMAP':'',parameters.clearcoatMap?'#define USE_CLEARCOATMAP':'',parameters.clearcoatRoughnessMap?'#define USE_CLEARCOAT_ROUGHNESSMAP':'',parameters.clearcoatNormalMap?'#define USE_CLEARCOAT_NORMALMAP':'',parameters.displacementMap&¶meters.supportsVertexTextures?'#define USE_DISPLACEMENTMAP':'',parameters.specularMap?'#define USE_SPECULARMAP':'',parameters.roughnessMap?'#define USE_ROUGHNESSMAP':'',parameters.metalnessMap?'#define USE_METALNESSMAP':'',parameters.alphaMap?'#define USE_ALPHAMAP':'',parameters.transmissionMap?'#define USE_TRANSMISSIONMAP':'',parameters.vertexTangents?'#define USE_TANGENT':'',parameters.vertexColors?'#define USE_COLOR':'',parameters.vertexUvs?'#define USE_UV':'',parameters.uvsVertexOnly?'#define UVS_VERTEX_ONLY':'',parameters.flatShading?'#define FLAT_SHADED':'',parameters.skinning?'#define USE_SKINNING':'',parameters.useVertexTexture?'#define BONE_TEXTURE':'',parameters.morphTargets?'#define USE_MORPHTARGETS':'',parameters.morphNormals&¶meters.flatShading===false?'#define USE_MORPHNORMALS':'',parameters.doubleSided?'#define DOUBLE_SIDED':'',parameters.flipSided?'#define FLIP_SIDED':'',parameters.shadowMapEnabled?'#define USE_SHADOWMAP':'',parameters.shadowMapEnabled?'#define '+shadowMapTypeDefine:'',parameters.sizeAttenuation?'#define USE_SIZEATTENUATION':'',parameters.logarithmicDepthBuffer?'#define USE_LOGDEPTHBUF':'',parameters.logarithmicDepthBuffer&¶meters.rendererExtensionFragDepth?'#define USE_LOGDEPTHBUF_EXT':'','uniform mat4 modelMatrix;','uniform mat4 modelViewMatrix;','uniform mat4 projectionMatrix;','uniform mat4 viewMatrix;','uniform mat3 normalMatrix;','uniform vec3 cameraPosition;','uniform bool isOrthographic;','#ifdef USE_INSTANCING',' attribute mat4 instanceMatrix;','#endif','#ifdef USE_INSTANCING_COLOR',' attribute vec3 instanceColor;','#endif','attribute vec3 position;','attribute vec3 normal;','attribute vec2 uv;','#ifdef USE_TANGENT',' attribute vec4 tangent;','#endif','#ifdef USE_COLOR',' attribute vec3 color;','#endif','#ifdef USE_MORPHTARGETS',' attribute vec3 morphTarget0;',' attribute vec3 morphTarget1;',' attribute vec3 morphTarget2;',' attribute vec3 morphTarget3;',' #ifdef USE_MORPHNORMALS',' attribute vec3 morphNormal0;',' attribute vec3 morphNormal1;',' attribute vec3 morphNormal2;',' attribute vec3 morphNormal3;',' #else',' attribute vec3 morphTarget4;',' attribute vec3 morphTarget5;',' attribute vec3 morphTarget6;',' attribute vec3 morphTarget7;',' #endif','#endif','#ifdef USE_SKINNING',' attribute vec4 skinIndex;',' attribute vec4 skinWeight;','#endif','\n'].filter(filterEmptyLine).join('\n');prefixFragment=[customExtensions,generatePrecision(parameters),'#define SHADER_NAME '+parameters.shaderName,customDefines,parameters.alphaTest?'#define ALPHATEST '+parameters.alphaTest+(parameters.alphaTest%1?'':'.0'):'',// add '.0' if integer '#define GAMMA_FACTOR '+gammaFactorDefine,parameters.useFog&¶meters.fog?'#define USE_FOG':'',parameters.useFog&¶meters.fogExp2?'#define FOG_EXP2':'',parameters.map?'#define USE_MAP':'',parameters.matcap?'#define USE_MATCAP':'',parameters.envMap?'#define USE_ENVMAP':'',parameters.envMap?'#define '+envMapTypeDefine:'',parameters.envMap?'#define '+envMapModeDefine:'',parameters.envMap?'#define '+envMapBlendingDefine:'',parameters.lightMap?'#define USE_LIGHTMAP':'',parameters.aoMap?'#define USE_AOMAP':'',parameters.emissiveMap?'#define USE_EMISSIVEMAP':'',parameters.bumpMap?'#define USE_BUMPMAP':'',parameters.normalMap?'#define USE_NORMALMAP':'',parameters.normalMap&¶meters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&¶meters.tangentSpaceNormalMap?'#define TANGENTSPACE_NORMALMAP':'',parameters.clearcoatMap?'#define USE_CLEARCOATMAP':'',parameters.clearcoatRoughnessMap?'#define USE_CLEARCOAT_ROUGHNESSMAP':'',parameters.clearcoatNormalMap?'#define USE_CLEARCOAT_NORMALMAP':'',parameters.specularMap?'#define USE_SPECULARMAP':'',parameters.roughnessMap?'#define USE_ROUGHNESSMAP':'',parameters.metalnessMap?'#define USE_METALNESSMAP':'',parameters.alphaMap?'#define USE_ALPHAMAP':'',parameters.sheen?'#define USE_SHEEN':'',parameters.transmissionMap?'#define USE_TRANSMISSIONMAP':'',parameters.vertexTangents?'#define USE_TANGENT':'',parameters.vertexColors||parameters.instancingColor?'#define USE_COLOR':'',parameters.vertexUvs?'#define USE_UV':'',parameters.uvsVertexOnly?'#define UVS_VERTEX_ONLY':'',parameters.gradientMap?'#define USE_GRADIENTMAP':'',parameters.flatShading?'#define FLAT_SHADED':'',parameters.doubleSided?'#define DOUBLE_SIDED':'',parameters.flipSided?'#define FLIP_SIDED':'',parameters.shadowMapEnabled?'#define USE_SHADOWMAP':'',parameters.shadowMapEnabled?'#define '+shadowMapTypeDefine:'',parameters.premultipliedAlpha?'#define PREMULTIPLIED_ALPHA':'',parameters.physicallyCorrectLights?'#define PHYSICALLY_CORRECT_LIGHTS':'',parameters.logarithmicDepthBuffer?'#define USE_LOGDEPTHBUF':'',parameters.logarithmicDepthBuffer&¶meters.rendererExtensionFragDepth?'#define USE_LOGDEPTHBUF_EXT':'',(parameters.extensionShaderTextureLOD||parameters.envMap)&¶meters.rendererExtensionShaderTextureLod?'#define TEXTURE_LOD_EXT':'','uniform mat4 viewMatrix;','uniform vec3 cameraPosition;','uniform bool isOrthographic;',parameters.toneMapping!==NoToneMapping?'#define TONE_MAPPING':'',parameters.toneMapping!==NoToneMapping?ShaderChunk['tonemapping_pars_fragment']:'',// this code is required here because it is used by the toneMapping() function defined below parameters.toneMapping!==NoToneMapping?getToneMappingFunction('toneMapping',parameters.toneMapping):'',parameters.dithering?'#define DITHERING':'',ShaderChunk['encodings_pars_fragment'],// this code is required here because it is used by the various encoding/decoding function defined below parameters.map?getTexelDecodingFunction('mapTexelToLinear',parameters.mapEncoding):'',parameters.matcap?getTexelDecodingFunction('matcapTexelToLinear',parameters.matcapEncoding):'',parameters.envMap?getTexelDecodingFunction('envMapTexelToLinear',parameters.envMapEncoding):'',parameters.emissiveMap?getTexelDecodingFunction('emissiveMapTexelToLinear',parameters.emissiveMapEncoding):'',parameters.lightMap?getTexelDecodingFunction('lightMapTexelToLinear',parameters.lightMapEncoding):'',getTexelEncodingFunction('linearToOutputTexel',parameters.outputEncoding),parameters.depthPacking?'#define DEPTH_PACKING '+parameters.depthPacking:'','\n'].filter(filterEmptyLine).join('\n');}vertexShader=resolveIncludes(vertexShader);vertexShader=replaceLightNums(vertexShader,parameters);vertexShader=replaceClippingPlaneNums(vertexShader,parameters);fragmentShader=resolveIncludes(fragmentShader);fragmentShader=replaceLightNums(fragmentShader,parameters);fragmentShader=replaceClippingPlaneNums(fragmentShader,parameters);vertexShader=unrollLoops(vertexShader);fragmentShader=unrollLoops(fragmentShader);if(parameters.isWebGL2&¶meters.isRawShaderMaterial!==true){// GLSL 3.0 conversion for built-in materials and ShaderMaterial versionString='#version 300 es\n';prefixVertex=['#define attribute in','#define varying out','#define texture2D texture'].join('\n')+'\n'+prefixVertex;prefixFragment=['#define varying in',parameters.glslVersion===GLSL3?'':'out highp vec4 pc_fragColor;',parameters.glslVersion===GLSL3?'':'#define gl_FragColor pc_fragColor','#define gl_FragDepthEXT gl_FragDepth','#define texture2D texture','#define textureCube texture','#define texture2DProj textureProj','#define texture2DLodEXT textureLod','#define texture2DProjLodEXT textureProjLod','#define textureCubeLodEXT textureLod','#define texture2DGradEXT textureGrad','#define texture2DProjGradEXT textureProjGrad','#define textureCubeGradEXT textureGrad'].join('\n')+'\n'+prefixFragment;}var vertexGlsl=versionString+prefixVertex+vertexShader;var fragmentGlsl=versionString+prefixFragment+fragmentShader;// console.log( '*VERTEX*', vertexGlsl ); // console.log( '*FRAGMENT*', fragmentGlsl ); var glVertexShader=WebGLShader(gl,35633,vertexGlsl);var glFragmentShader=WebGLShader(gl,35632,fragmentGlsl);gl.attachShader(program,glVertexShader);gl.attachShader(program,glFragmentShader);// Force a particular attribute to index 0. if(parameters.index0AttributeName!==undefined){gl.bindAttribLocation(program,0,parameters.index0AttributeName);}else if(parameters.morphTargets===true){// programs with morphTargets displace position out of attribute 0 gl.bindAttribLocation(program,0,'position');}gl.linkProgram(program);// check for link errors if(renderer.debug.checkShaderErrors){var programLog=gl.getProgramInfoLog(program).trim();var vertexLog=gl.getShaderInfoLog(glVertexShader).trim();var fragmentLog=gl.getShaderInfoLog(glFragmentShader).trim();var runnable=true;var haveDiagnostics=true;if(gl.getProgramParameter(program,35714)===false){runnable=false;var vertexErrors=getShaderErrors(gl,glVertexShader,'vertex');var fragmentErrors=getShaderErrors(gl,glFragmentShader,'fragment');console.error('THREE.WebGLProgram: shader error: ',gl.getError(),'35715',gl.getProgramParameter(program,35715),'gl.getProgramInfoLog',programLog,vertexErrors,fragmentErrors);}else if(programLog!==''){console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()',programLog);}else if(vertexLog===''||fragmentLog===''){haveDiagnostics=false;}if(haveDiagnostics){this.diagnostics={runnable:runnable,programLog:programLog,vertexShader:{log:vertexLog,prefix:prefixVertex},fragmentShader:{log:fragmentLog,prefix:prefixFragment}};}}// Clean up // Crashes in iOS9 and iOS10. #18402 // gl.detachShader( program, glVertexShader ); // gl.detachShader( program, glFragmentShader ); gl.deleteShader(glVertexShader);gl.deleteShader(glFragmentShader);// set up caching for uniform locations var cachedUniforms;this.getUniforms=function(){if(cachedUniforms===undefined){cachedUniforms=new WebGLUniforms(gl,program);}return cachedUniforms;};// set up caching for attribute locations var cachedAttributes;this.getAttributes=function(){if(cachedAttributes===undefined){cachedAttributes=fetchAttributeLocations(gl,program);}return cachedAttributes;};// free resource this.destroy=function(){bindingStates.releaseStatesOfProgram(this);gl.deleteProgram(program);this.program=undefined;};// this.name=parameters.shaderName;this.id=programIdCount++;this.cacheKey=cacheKey;this.usedTimes=1;this.program=program;this.vertexShader=glVertexShader;this.fragmentShader=glFragmentShader;return this;}function WebGLPrograms(renderer,cubemaps,extensions,capabilities,bindingStates,clipping){var programs=[];var isWebGL2=capabilities.isWebGL2;var logarithmicDepthBuffer=capabilities.logarithmicDepthBuffer;var floatVertexTextures=capabilities.floatVertexTextures;var maxVertexUniforms=capabilities.maxVertexUniforms;var vertexTextures=capabilities.vertexTextures;var precision=capabilities.precision;var shaderIDs={MeshDepthMaterial:'depth',MeshDistanceMaterial:'distanceRGBA',MeshNormalMaterial:'normal',MeshBasicMaterial:'basic',MeshLambertMaterial:'lambert',MeshPhongMaterial:'phong',MeshToonMaterial:'toon',MeshStandardMaterial:'physical',MeshPhysicalMaterial:'physical',MeshMatcapMaterial:'matcap',LineBasicMaterial:'basic',LineDashedMaterial:'dashed',PointsMaterial:'points',ShadowMaterial:'shadow',SpriteMaterial:'sprite'};var parameterNames=["precision","isWebGL2","supportsVertexTextures","outputEncoding","instancing","instancingColor","map","mapEncoding","matcap","matcapEncoding","envMap","envMapMode","envMapEncoding","envMapCubeUV","lightMap","lightMapEncoding","aoMap","emissiveMap","emissiveMapEncoding","bumpMap","normalMap","objectSpaceNormalMap","tangentSpaceNormalMap","clearcoatMap","clearcoatRoughnessMap","clearcoatNormalMap","displacementMap","specularMap","roughnessMap","metalnessMap","gradientMap","alphaMap","combine","vertexColors","vertexTangents","vertexUvs","uvsVertexOnly","fog","useFog","fogExp2","flatShading","sizeAttenuation","logarithmicDepthBuffer","skinning","maxBones","useVertexTexture","morphTargets","morphNormals","maxMorphTargets","maxMorphNormals","premultipliedAlpha","numDirLights","numPointLights","numSpotLights","numHemiLights","numRectAreaLights","numDirLightShadows","numPointLightShadows","numSpotLightShadows","shadowMapEnabled","shadowMapType","toneMapping",'physicallyCorrectLights',"alphaTest","doubleSided","flipSided","numClippingPlanes","numClipIntersection","depthPacking","dithering","sheen","transmissionMap"];function getMaxBones(object){var skeleton=object.skeleton;var bones=skeleton.bones;if(floatVertexTextures){return 1024;}else{// default for when object is not specified // ( for example when prebuilding shader to be used with multiple objects ) // // - leave some extra space for other uniforms // - limit here is ANGLE's 254 max uniform vectors // (up to 54 should be safe) var nVertexUniforms=maxVertexUniforms;var nVertexMatrices=Math.floor((nVertexUniforms-20)/4);var maxBones=Math.min(nVertexMatrices,bones.length);if(maxBones0,maxBones:maxBones,useVertexTexture:floatVertexTextures,morphTargets:material.morphTargets,morphNormals:material.morphNormals,maxMorphTargets:renderer.maxMorphTargets,maxMorphNormals:renderer.maxMorphNormals,numDirLights:lights.directional.length,numPointLights:lights.point.length,numSpotLights:lights.spot.length,numRectAreaLights:lights.rectArea.length,numHemiLights:lights.hemi.length,numDirLightShadows:lights.directionalShadowMap.length,numPointLightShadows:lights.pointShadowMap.length,numSpotLightShadows:lights.spotShadowMap.length,numClippingPlanes:clipping.numPlanes,numClipIntersection:clipping.numIntersection,dithering:material.dithering,shadowMapEnabled:renderer.shadowMap.enabled&&shadows.length>0,shadowMapType:renderer.shadowMap.type,toneMapping:material.toneMapped?renderer.toneMapping:NoToneMapping,physicallyCorrectLights:renderer.physicallyCorrectLights,premultipliedAlpha:material.premultipliedAlpha,alphaTest:material.alphaTest,doubleSided:material.side===DoubleSide,flipSided:material.side===BackSide,depthPacking:material.depthPacking!==undefined?material.depthPacking:false,index0AttributeName:material.index0AttributeName,extensionDerivatives:material.extensions&&material.extensions.derivatives,extensionFragDepth:material.extensions&&material.extensions.fragDepth,extensionDrawBuffers:material.extensions&&material.extensions.drawBuffers,extensionShaderTextureLOD:material.extensions&&material.extensions.shaderTextureLOD,rendererExtensionFragDepth:isWebGL2||extensions.has('EXT_frag_depth'),rendererExtensionDrawBuffers:isWebGL2||extensions.has('WEBGL_draw_buffers'),rendererExtensionShaderTextureLod:isWebGL2||extensions.has('EXT_shader_texture_lod'),customProgramCacheKey:material.customProgramCacheKey()};return parameters;}function getProgramCacheKey(parameters){var array=[];if(parameters.shaderID){array.push(parameters.shaderID);}else{array.push(parameters.fragmentShader);array.push(parameters.vertexShader);}if(parameters.defines!==undefined){for(var name in parameters.defines){array.push(name);array.push(parameters.defines[name]);}}if(parameters.isRawShaderMaterial===false){for(var _i93=0;_i931)opaque.sort(customOpaqueSort||painterSortStable);if(transparent.length>1)transparent.sort(customTransparentSort||reversePainterSortStable);}function finish(){// Clear references from inactive renderItems in the list for(var _i95=renderItemsIndex,il=renderItems.length;_i950){state.rectAreaLTC1=UniformsLib.LTC_1;state.rectAreaLTC2=UniformsLib.LTC_2;}state.ambient[0]=r;state.ambient[1]=g;state.ambient[2]=b;var hash=state.hash;if(hash.directionalLength!==directionalLength||hash.pointLength!==pointLength||hash.spotLength!==spotLength||hash.rectAreaLength!==rectAreaLength||hash.hemiLength!==hemiLength||hash.numDirectionalShadows!==numDirectionalShadows||hash.numPointShadows!==numPointShadows||hash.numSpotShadows!==numSpotShadows){state.directional.length=directionalLength;state.spot.length=spotLength;state.rectArea.length=rectAreaLength;state.point.length=pointLength;state.hemi.length=hemiLength;state.directionalShadow.length=numDirectionalShadows;state.directionalShadowMap.length=numDirectionalShadows;state.pointShadow.length=numPointShadows;state.pointShadowMap.length=numPointShadows;state.spotShadow.length=numSpotShadows;state.spotShadowMap.length=numSpotShadows;state.directionalShadowMatrix.length=numDirectionalShadows;state.pointShadowMatrix.length=numPointShadows;state.spotShadowMatrix.length=numSpotShadows;hash.directionalLength=directionalLength;hash.pointLength=pointLength;hash.spotLength=spotLength;hash.rectAreaLength=rectAreaLength;hash.hemiLength=hemiLength;hash.numDirectionalShadows=numDirectionalShadows;hash.numPointShadows=numPointShadows;hash.numSpotShadows=numSpotShadows;state.version=nextVersion++;}}return{setup:setup,state:state};}function WebGLRenderState(){var lights=new WebGLLights();var lightsArray=[];var shadowsArray=[];function init(){lightsArray.length=0;shadowsArray.length=0;}function pushLight(light){lightsArray.push(light);}function pushShadow(shadowLight){shadowsArray.push(shadowLight);}function setupLights(camera){lights.setup(lightsArray,shadowsArray,camera);}var state={lightsArray:lightsArray,shadowsArray:shadowsArray,lights:lights};return{init:init,state:state,setupLights:setupLights,pushLight:pushLight,pushShadow:pushShadow};}function WebGLRenderStates(){var renderStates=new WeakMap();function get(scene,camera){var renderState;if(renderStates.has(scene)===false){renderState=new WebGLRenderState();renderStates.set(scene,new WeakMap());renderStates.get(scene).set(camera,renderState);}else{if(renderStates.get(scene).has(camera)===false){renderState=new WebGLRenderState();renderStates.get(scene).set(camera,renderState);}else{renderState=renderStates.get(scene).get(camera);}}return renderState;}function dispose(){renderStates=new WeakMap();}return{get:get,dispose:dispose};}/** * parameters = { * * opacity: , * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * } */function MeshDepthMaterial(parameters){Material.call(this);this.type='MeshDepthMaterial';this.depthPacking=BasicDepthPacking;this.skinning=false;this.morphTargets=false;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;this.setValues(parameters);}MeshDepthMaterial.prototype=Object.create(Material.prototype);MeshDepthMaterial.prototype.constructor=MeshDepthMaterial;MeshDepthMaterial.prototype.isMeshDepthMaterial=true;MeshDepthMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.depthPacking=source.depthPacking;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;return this;};/** * parameters = { * * referencePosition: , * nearDistance: , * farDistance: , * * skinning: , * morphTargets: , * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: * * } */function MeshDistanceMaterial(parameters){Material.call(this);this.type='MeshDistanceMaterial';this.referencePosition=new Vector3();this.nearDistance=1;this.farDistance=1000;this.skinning=false;this.morphTargets=false;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.fog=false;this.setValues(parameters);}MeshDistanceMaterial.prototype=Object.create(Material.prototype);MeshDistanceMaterial.prototype.constructor=MeshDistanceMaterial;MeshDistanceMaterial.prototype.isMeshDistanceMaterial=true;MeshDistanceMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.referencePosition.copy(source.referencePosition);this.nearDistance=source.nearDistance;this.farDistance=source.farDistance;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;return this;};var vsm_frag="uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";var vsm_vert="void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";function WebGLShadowMap(_renderer,_objects,maxTextureSize){var _frustum=new Frustum();var _shadowMapSize=new Vector2(),_viewportSize=new Vector2(),_viewport=new Vector4(),_depthMaterials=[],_distanceMaterials=[],_materialCache={};var shadowSide={0:BackSide,1:FrontSide,2:DoubleSide};var shadowMaterialVertical=new ShaderMaterial({defines:{SAMPLE_RATE:2.0/8.0,HALF_SAMPLE_RATE:1.0/8.0},uniforms:{shadow_pass:{value:null},resolution:{value:new Vector2()},radius:{value:4.0}},vertexShader:vsm_vert,fragmentShader:vsm_frag});var shadowMaterialHorizonal=shadowMaterialVertical.clone();shadowMaterialHorizonal.defines.HORIZONAL_PASS=1;var fullScreenTri=new BufferGeometry();fullScreenTri.setAttribute("position",new BufferAttribute(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));var fullScreenMesh=new Mesh(fullScreenTri,shadowMaterialVertical);var scope=this;this.enabled=false;this.autoUpdate=true;this.needsUpdate=false;this.type=PCFShadowMap;this.render=function(lights,scene,camera){if(scope.enabled===false)return;if(scope.autoUpdate===false&&scope.needsUpdate===false)return;if(lights.length===0)return;var currentRenderTarget=_renderer.getRenderTarget();var activeCubeFace=_renderer.getActiveCubeFace();var activeMipmapLevel=_renderer.getActiveMipmapLevel();var _state=_renderer.state;// Set GL state for depth map. _state.setBlending(NoBlending);_state.buffers.color.setClear(1,1,1,1);_state.buffers.depth.setTest(true);_state.setScissorTest(false);// render depth map for(var _i99=0,il=lights.length;_i99maxTextureSize||_shadowMapSize.y>maxTextureSize){if(_shadowMapSize.x>maxTextureSize){_viewportSize.x=Math.floor(maxTextureSize/shadowFrameExtents.x);_shadowMapSize.x=_viewportSize.x*shadowFrameExtents.x;shadow.mapSize.x=_viewportSize.x;}if(_shadowMapSize.y>maxTextureSize){_viewportSize.y=Math.floor(maxTextureSize/shadowFrameExtents.y);_shadowMapSize.y=_viewportSize.y*shadowFrameExtents.y;shadow.mapSize.y=_viewportSize.y;}}if(shadow.map===null&&!shadow.isPointLightShadow&&this.type===VSMShadowMap){var pars={minFilter:LinearFilter,magFilter:LinearFilter,format:RGBAFormat};shadow.map=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.map.texture.name=light.name+".shadowMap";shadow.mapPass=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.camera.updateProjectionMatrix();}if(shadow.map===null){var _pars={minFilter:NearestFilter,magFilter:NearestFilter,format:RGBAFormat};shadow.map=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,_pars);shadow.map.texture.name=light.name+".shadowMap";shadow.camera.updateProjectionMatrix();}_renderer.setRenderTarget(shadow.map);_renderer.clear();var viewportCount=shadow.getViewportCount();for(var vp=0;vp0;}var useSkinning=false;if(object.isSkinnedMesh===true){if(material.skinning===true){useSkinning=true;}else{console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:',object);}}var useInstancing=object.isInstancedMesh===true;result=getMaterialVariant(useMorphing,useSkinning,useInstancing);}else{result=customMaterial;}if(_renderer.localClippingEnabled&&material.clipShadows===true&&material.clippingPlanes.length!==0){// in this case we need a unique material instance reflecting the // appropriate state var keyA=result.uuid,keyB=material.uuid;var materialsForVariant=_materialCache[keyA];if(materialsForVariant===undefined){materialsForVariant={};_materialCache[keyA]=materialsForVariant;}var cachedMaterial=materialsForVariant[keyB];if(cachedMaterial===undefined){cachedMaterial=result.clone();materialsForVariant[keyB]=cachedMaterial;}result=cachedMaterial;}result.visible=material.visible;result.wireframe=material.wireframe;if(type===VSMShadowMap){result.side=material.shadowSide!==null?material.shadowSide:material.side;}else{result.side=material.shadowSide!==null?material.shadowSide:shadowSide[material.side];}result.clipShadows=material.clipShadows;result.clippingPlanes=material.clippingPlanes;result.clipIntersection=material.clipIntersection;result.wireframeLinewidth=material.wireframeLinewidth;result.linewidth=material.linewidth;if(light.isPointLight===true&&result.isMeshDistanceMaterial===true){result.referencePosition.setFromMatrixPosition(light.matrixWorld);result.nearDistance=shadowCameraNear;result.farDistance=shadowCameraFar;}return result;}function renderObject(object,camera,shadowCamera,light,type){if(object.visible===false)return;var visible=object.layers.test(camera.layers);if(visible&&(object.isMesh||object.isLine||object.isPoints)){if((object.castShadow||object.receiveShadow&&type===VSMShadowMap)&&(!object.frustumCulled||_frustum.intersectsObject(object))){object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse,object.matrixWorld);var geometry=_objects.update(object);var material=object.material;if(Array.isArray(material)){var groups=geometry.groups;for(var k=0,kl=groups.length;k=1.0;}else if(glVersion.indexOf('OpenGL ES')!==-1){version=parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);lineWidthAvailable=version>=2.0;}var currentTextureSlot=null;var currentBoundTextures={};var currentScissor=new Vector4();var currentViewport=new Vector4();function createTexture(type,target,count){var data=new Uint8Array(4);// 4 is required to match default unpack alignment of 4. var texture=gl.createTexture();gl.bindTexture(type,texture);gl.texParameteri(type,10241,9728);gl.texParameteri(type,10240,9728);for(var _i101=0;_i101maxSize||image.height>maxSize){scale=maxSize/Math.max(image.width,image.height);}// only perform resize if necessary if(scale<1||needsPowerOfTwo===true){// only perform resize for certain image types if(typeof HTMLImageElement!=='undefined'&&_instanceof(image,HTMLImageElement)||typeof HTMLCanvasElement!=='undefined'&&_instanceof(image,HTMLCanvasElement)||typeof ImageBitmap!=='undefined'&&_instanceof(image,ImageBitmap)){var floor=needsPowerOfTwo?MathUtils.floorPowerOfTwo:Math.floor;var width=floor(scale*image.width);var height=floor(scale*image.height);if(_canvas===undefined)_canvas=createCanvas(width,height);// cube textures can't reuse the same canvas var canvas=needsNewCanvas?createCanvas(width,height):_canvas;canvas.width=width;canvas.height=height;var context=canvas.getContext('2d');context.drawImage(image,0,0,width,height);console.warn('THREE.WebGLRenderer: Texture has been resized from ('+image.width+'x'+image.height+') to ('+width+'x'+height+').');return canvas;}else{if('data'in image){console.warn('THREE.WebGLRenderer: Image in DataTexture is too big ('+image.width+'x'+image.height+').');}return image;}}return image;}function isPowerOfTwo(image){return MathUtils.isPowerOfTwo(image.width)&&MathUtils.isPowerOfTwo(image.height);}function textureNeedsPowerOfTwo(texture){if(isWebGL2)return false;return texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping||texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter;}function textureNeedsGenerateMipmaps(texture,supportsMips){return texture.generateMipmaps&&supportsMips&&texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter;}function generateMipmap(target,texture,width,height){_gl.generateMipmap(target);var textureProperties=properties.get(texture);// Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11 textureProperties.__maxMipLevel=Math.log(Math.max(width,height))*Math.LOG2E;}function getInternalFormat(internalFormatName,glFormat,glType){if(isWebGL2===false)return glFormat;if(internalFormatName!==null){if(_gl[internalFormatName]!==undefined)return _gl[internalFormatName];console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \''+internalFormatName+'\'');}var internalFormat=glFormat;if(glFormat===6403){if(glType===5126)internalFormat=33326;if(glType===5131)internalFormat=33325;if(glType===5121)internalFormat=33321;}if(glFormat===6407){if(glType===5126)internalFormat=34837;if(glType===5131)internalFormat=34843;if(glType===5121)internalFormat=32849;}if(glFormat===6408){if(glType===5126)internalFormat=34836;if(glType===5131)internalFormat=34842;if(glType===5121)internalFormat=32856;}if(internalFormat===33325||internalFormat===33326||internalFormat===34842||internalFormat===34836){extensions.get('EXT_color_buffer_float');}return internalFormat;}// Fallback filters for non-power-of-2 textures function filterFallback(f){if(f===NearestFilter||f===NearestMipmapNearestFilter||f===NearestMipmapLinearFilter){return 9728;}return 9729;}// function onTextureDispose(event){var texture=event.target;texture.removeEventListener('dispose',onTextureDispose);deallocateTexture(texture);if(texture.isVideoTexture){_videoTextures.delete(texture);}info.memory.textures--;}function onRenderTargetDispose(event){var renderTarget=event.target;renderTarget.removeEventListener('dispose',onRenderTargetDispose);deallocateRenderTarget(renderTarget);info.memory.textures--;}// function deallocateTexture(texture){var textureProperties=properties.get(texture);if(textureProperties.__webglInit===undefined)return;_gl.deleteTexture(textureProperties.__webglTexture);properties.remove(texture);}function deallocateRenderTarget(renderTarget){var renderTargetProperties=properties.get(renderTarget);var textureProperties=properties.get(renderTarget.texture);if(!renderTarget)return;if(textureProperties.__webglTexture!==undefined){_gl.deleteTexture(textureProperties.__webglTexture);}if(renderTarget.depthTexture){renderTarget.depthTexture.dispose();}if(renderTarget.isWebGLCubeRenderTarget){for(var _i102=0;_i102<6;_i102++){_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[_i102]);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[_i102]);}}else{_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);if(renderTargetProperties.__webglMultisampledFramebuffer)_gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);if(renderTargetProperties.__webglColorRenderbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);if(renderTargetProperties.__webglDepthRenderbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);}properties.remove(renderTarget.texture);properties.remove(renderTarget);}// var textureUnits=0;function resetTextureUnits(){textureUnits=0;}function allocateTextureUnit(){var textureUnit=textureUnits;if(textureUnit>=maxTextures){console.warn('THREE.WebGLTextures: Trying to use '+textureUnit+' texture units while this GPU supports only '+maxTextures);}textureUnits+=1;return textureUnit;}// function setTexture2D(texture,slot){var textureProperties=properties.get(texture);if(texture.isVideoTexture)updateVideoTexture(texture);if(texture.version>0&&textureProperties.__version!==texture.version){var image=texture.image;if(image===undefined){console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');}else if(image.complete===false){console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');}else{uploadTexture(textureProperties,texture,slot);return;}}state.activeTexture(33984+slot);state.bindTexture(3553,textureProperties.__webglTexture);}function setTexture2DArray(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return;}state.activeTexture(33984+slot);state.bindTexture(35866,textureProperties.__webglTexture);}function setTexture3D(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return;}state.activeTexture(33984+slot);state.bindTexture(32879,textureProperties.__webglTexture);}function setTextureCube(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadCubeTexture(textureProperties,texture,slot);return;}state.activeTexture(33984+slot);state.bindTexture(34067,textureProperties.__webglTexture);}var wrappingToGL=(_wrappingToGL={},_defineProperty(_wrappingToGL,RepeatWrapping,10497),_defineProperty(_wrappingToGL,ClampToEdgeWrapping,33071),_defineProperty(_wrappingToGL,MirroredRepeatWrapping,33648),_wrappingToGL);var filterToGL=(_filterToGL={},_defineProperty(_filterToGL,NearestFilter,9728),_defineProperty(_filterToGL,NearestMipmapNearestFilter,9984),_defineProperty(_filterToGL,NearestMipmapLinearFilter,9986),_defineProperty(_filterToGL,LinearFilter,9729),_defineProperty(_filterToGL,LinearMipmapNearestFilter,9985),_defineProperty(_filterToGL,LinearMipmapLinearFilter,9987),_filterToGL);function setTextureParameters(textureType,texture,supportsMips){if(supportsMips){_gl.texParameteri(textureType,10242,wrappingToGL[texture.wrapS]);_gl.texParameteri(textureType,10243,wrappingToGL[texture.wrapT]);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,wrappingToGL[texture.wrapR]);}_gl.texParameteri(textureType,10240,filterToGL[texture.magFilter]);_gl.texParameteri(textureType,10241,filterToGL[texture.minFilter]);}else{_gl.texParameteri(textureType,10242,33071);_gl.texParameteri(textureType,10243,33071);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,33071);}if(texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping){console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');}_gl.texParameteri(textureType,10240,filterFallback(texture.magFilter));_gl.texParameteri(textureType,10241,filterFallback(texture.minFilter));if(texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter){console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');}}var extension=extensions.get('EXT_texture_filter_anisotropic');if(extension){if(texture.type===FloatType&&extensions.get('OES_texture_float_linear')===null)return;if(texture.type===HalfFloatType&&(isWebGL2||extensions.get('OES_texture_half_float_linear'))===null)return;if(texture.anisotropy>1||properties.get(texture).__currentAnisotropy){_gl.texParameterf(textureType,extension.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(texture.anisotropy,capabilities.getMaxAnisotropy()));properties.get(texture).__currentAnisotropy=texture.anisotropy;}}}function initTexture(textureProperties,texture){if(textureProperties.__webglInit===undefined){textureProperties.__webglInit=true;texture.addEventListener('dispose',onTextureDispose);textureProperties.__webglTexture=_gl.createTexture();info.memory.textures++;}}function uploadTexture(textureProperties,texture,slot){var textureType=3553;if(texture.isDataTexture2DArray)textureType=35866;if(texture.isDataTexture3D)textureType=32879;initTexture(textureProperties,texture);state.activeTexture(33984+slot);state.bindTexture(textureType,textureProperties.__webglTexture);_gl.pixelStorei(37440,texture.flipY);_gl.pixelStorei(37441,texture.premultiplyAlpha);_gl.pixelStorei(3317,texture.unpackAlignment);var needsPowerOfTwo=textureNeedsPowerOfTwo(texture)&&isPowerOfTwo(texture.image)===false;var image=resizeImage(texture.image,needsPowerOfTwo,false,maxTextureSize);var supportsMips=isPowerOfTwo(image)||isWebGL2,glFormat=utils.convert(texture.format);var glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType);setTextureParameters(textureType,texture,supportsMips);var mipmap;var mipmaps=texture.mipmaps;if(texture.isDepthTexture){// populate depth texture with dummy data glInternalFormat=6402;if(isWebGL2){if(texture.type===FloatType){glInternalFormat=36012;}else if(texture.type===UnsignedIntType){glInternalFormat=33190;}else if(texture.type===UnsignedInt248Type){glInternalFormat=35056;}else{glInternalFormat=33189;// WebGL2 requires sized internalformat for glTexImage2D }}else{if(texture.type===FloatType){console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');}}// validation checks for WebGL 1 if(texture.format===DepthFormat&&glInternalFormat===6402){// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) if(texture.type!==UnsignedShortType&&texture.type!==UnsignedIntType){console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');texture.type=UnsignedShortType;glType=utils.convert(texture.type);}}if(texture.format===DepthStencilFormat&&glInternalFormat===6402){// Depth stencil textures need the DEPTH_STENCIL internal format // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) glInternalFormat=34041;// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) if(texture.type!==UnsignedInt248Type){console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');texture.type=UnsignedInt248Type;glType=utils.convert(texture.type);}}// state.texImage2D(3553,0,glInternalFormat,image.width,image.height,0,glFormat,glType,null);}else if(texture.isDataTexture){// use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if(mipmaps.length>0&&supportsMips){for(var _i103=0,il=mipmaps.length;_i1030&&supportsMips){for(var _i105=0,_il10=mipmaps.length;_i105<_il10;_i105++){mipmap=mipmaps[_i105];state.texImage2D(3553,_i105,glInternalFormat,glFormat,glType,mipmap);}texture.generateMipmaps=false;textureProperties.__maxMipLevel=mipmaps.length-1;}else{state.texImage2D(3553,0,glInternalFormat,glFormat,glType,image);textureProperties.__maxMipLevel=0;}}if(textureNeedsGenerateMipmaps(texture,supportsMips)){generateMipmap(textureType,texture,image.width,image.height);}textureProperties.__version=texture.version;if(texture.onUpdate)texture.onUpdate(texture);}function uploadCubeTexture(textureProperties,texture,slot){if(texture.image.length!==6)return;initTexture(textureProperties,texture);state.activeTexture(33984+slot);state.bindTexture(34067,textureProperties.__webglTexture);_gl.pixelStorei(37440,texture.flipY);var isCompressed=texture&&(texture.isCompressedTexture||texture.image[0].isCompressedTexture);var isDataTexture=texture.image[0]&&texture.image[0].isDataTexture;var cubeImage=[];for(var _i106=0;_i106<6;_i106++){if(!isCompressed&&!isDataTexture){cubeImage[_i106]=resizeImage(texture.image[_i106],false,true,maxCubemapSize);}else{cubeImage[_i106]=isDataTexture?texture.image[_i106].image:texture.image[_i106];}}var image=cubeImage[0],supportsMips=isPowerOfTwo(image)||isWebGL2,glFormat=utils.convert(texture.format),glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType);setTextureParameters(34067,texture,supportsMips);var mipmaps;if(isCompressed){for(var _i107=0;_i107<6;_i107++){mipmaps=cubeImage[_i107].mipmaps;for(var j=0;jdistanceToPinch+threshold){hand.inputState.pinching=false;this.dispatchEvent({type:"pinchend",handedness:inputSource.handedness,target:this});}else if(!hand.inputState.pinching&&distance<=distanceToPinch-threshold){hand.inputState.pinching=true;this.dispatchEvent({type:"pinchstart",handedness:inputSource.handedness,target:this});}}}}else{if(targetRay!==null){inputPose=frame.getPose(inputSource.targetRaySpace,referenceSpace);if(inputPose!==null){targetRay.matrix.fromArray(inputPose.transform.matrix);targetRay.matrix.decompose(targetRay.position,targetRay.rotation,targetRay.scale);}}if(grip!==null&&inputSource.gripSpace){gripPose=frame.getPose(inputSource.gripSpace,referenceSpace);if(gripPose!==null){grip.matrix.fromArray(gripPose.transform.matrix);grip.matrix.decompose(grip.position,grip.rotation,grip.scale);}}}}if(targetRay!==null){targetRay.visible=inputPose!==null;}if(grip!==null){grip.visible=gripPose!==null;}if(hand!==null){hand.visible=handPose!==null;}return this;}});function WebXRManager(renderer,gl){var scope=this;var session=null;var framebufferScaleFactor=1.0;var referenceSpace=null;var referenceSpaceType='local-floor';var pose=null;var controllers=[];var inputSourcesMap=new Map();// var cameraL=new PerspectiveCamera();cameraL.layers.enable(1);cameraL.viewport=new Vector4();var cameraR=new PerspectiveCamera();cameraR.layers.enable(2);cameraR.viewport=new Vector4();var cameras=[cameraL,cameraR];var cameraVR=new ArrayCamera();cameraVR.layers.enable(1);cameraVR.layers.enable(2);var _currentDepthNear=null;var _currentDepthFar=null;// this.enabled=false;this.isPresenting=false;this.getController=function(index){var controller=controllers[index];if(controller===undefined){controller=new WebXRController();controllers[index]=controller;}return controller.getTargetRaySpace();};this.getControllerGrip=function(index){var controller=controllers[index];if(controller===undefined){controller=new WebXRController();controllers[index]=controller;}return controller.getGripSpace();};this.getHand=function(index){var controller=controllers[index];if(controller===undefined){controller=new WebXRController();controllers[index]=controller;}return controller.getHandSpace();};// function onSessionEvent(event){var controller=inputSourcesMap.get(event.inputSource);if(controller){controller.dispatchEvent({type:event.type,data:event.inputSource});}}function onSessionEnd(){inputSourcesMap.forEach(function(controller,inputSource){controller.disconnect(inputSource);});inputSourcesMap.clear();// renderer.setFramebuffer(null);renderer.setRenderTarget(renderer.getRenderTarget());// Hack #15830 animation.stop();scope.isPresenting=false;scope.dispatchEvent({type:'sessionend'});}function onRequestReferenceSpace(value){referenceSpace=value;animation.setContext(session);animation.start();scope.isPresenting=true;scope.dispatchEvent({type:'sessionstart'});}this.setFramebufferScaleFactor=function(value){framebufferScaleFactor=value;if(scope.isPresenting===true){console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');}};this.setReferenceSpaceType=function(value){referenceSpaceType=value;if(scope.isPresenting===true){console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');}};this.getReferenceSpace=function(){return referenceSpace;};this.getSession=function(){return session;};this.setSession=function(value){session=value;if(session!==null){session.addEventListener('select',onSessionEvent);session.addEventListener('selectstart',onSessionEvent);session.addEventListener('selectend',onSessionEvent);session.addEventListener('squeeze',onSessionEvent);session.addEventListener('squeezestart',onSessionEvent);session.addEventListener('squeezeend',onSessionEvent);session.addEventListener('end',onSessionEnd);var attributes=gl.getContextAttributes();if(attributes.xrCompatible!==true){gl.makeXRCompatible();}var layerInit={antialias:attributes.antialias,alpha:attributes.alpha,depth:attributes.depth,stencil:attributes.stencil,framebufferScaleFactor:framebufferScaleFactor};// eslint-disable-next-line no-undef var baseLayer=new XRWebGLLayer(session,gl,layerInit);session.updateRenderState({baseLayer:baseLayer});session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace);// session.addEventListener('inputsourceschange',updateInputSources);}};function updateInputSources(event){var inputSources=session.inputSources;// Assign inputSources to available controllers for(var _i114=0;_i1140)renderObjects(opaqueObjects,scene,camera);if(transparentObjects.length>0)renderObjects(transparentObjects,scene,camera);// if(scene.isScene===true)scene.onAfterRender(_this,scene,camera);// if(_currentRenderTarget!==null){// Generate mipmap if we're using any kind of mipmap filtering textures.updateRenderTargetMipmap(_currentRenderTarget);// resolve multisample renderbuffers to a single-sample texture if necessary textures.updateMultisampleRenderTarget(_currentRenderTarget);}// Ensure depth buffer writing is enabled so it can be cleared on next render state.buffers.depth.setTest(true);state.buffers.depth.setMask(true);state.buffers.color.setMask(true);state.setPolygonOffset(false);// _gl.finish(); currentRenderList=null;currentRenderState=null;};function projectObject(object,camera,groupOrder,sortObjects){if(object.visible===false)return;var visible=object.layers.test(camera.layers);if(visible){if(object.isGroup){groupOrder=object.renderOrder;}else if(object.isLOD){if(object.autoUpdate===true)object.update(camera);}else if(object.isLight){currentRenderState.pushLight(object);if(object.castShadow){currentRenderState.pushShadow(object);}}else if(object.isSprite){if(!object.frustumCulled||_frustum.intersectsSprite(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);}var geometry=objects.update(object);var material=object.material;if(material.visible){currentRenderList.push(object,geometry,material,groupOrder,_vector3.z,null);}}}else if(object.isImmediateRenderObject){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);}currentRenderList.push(object,null,object.material,groupOrder,_vector3.z,null);}else if(object.isMesh||object.isLine||object.isPoints){if(object.isSkinnedMesh){// update skeleton only once in a frame if(object.skeleton.frame!==info.render.frame){object.skeleton.update();object.skeleton.frame=info.render.frame;}}if(!object.frustumCulled||_frustum.intersectsObject(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);}var _geometry2=objects.update(object);var _material=object.material;if(Array.isArray(_material)){var groups=_geometry2.groups;for(var _i123=0,l=groups.length;_i123 column1, column2, column3, column4) // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) var size=Math.sqrt(bones.length*4);// 4 pixels needed for 1 matrix size=MathUtils.ceilPowerOfTwo(size);size=Math.max(size,4);var boneMatrices=new Float32Array(size*size*4);// 4 floats per RGBA pixel boneMatrices.set(skeleton.boneMatrices);// copy current values var boneTexture=new DataTexture(boneMatrices,size,size,RGBAFormat,FloatType);skeleton.boneMatrices=boneMatrices;skeleton.boneTexture=boneTexture;skeleton.boneTextureSize=size;}p_uniforms.setValue(_gl,'boneTexture',skeleton.boneTexture,textures);p_uniforms.setValue(_gl,'boneTextureSize',skeleton.boneTextureSize);}else{p_uniforms.setOptional(_gl,skeleton,'boneMatrices');}}}if(refreshMaterial||materialProperties.receiveShadow!==object.receiveShadow){materialProperties.receiveShadow=object.receiveShadow;p_uniforms.setValue(_gl,'receiveShadow',object.receiveShadow);}if(refreshMaterial){p_uniforms.setValue(_gl,'toneMappingExposure',_this.toneMappingExposure);if(materialProperties.needsLights){// the current material requires lighting info // note: all lighting uniforms are always set correctly // they simply reference the renderer's state for their // values // // use the current material's .needsUpdate flags to set // the GL state when required markUniformsLightsNeedsUpdate(m_uniforms,refreshLights);}// refresh uniforms common to several materials if(fog&&material.fog){materials.refreshFogUniforms(m_uniforms,fog);}materials.refreshMaterialUniforms(m_uniforms,material,_pixelRatio,_height);WebGLUniforms.upload(_gl,materialProperties.uniformsList,m_uniforms,textures);}if(material.isShaderMaterial&&material.uniformsNeedUpdate===true){WebGLUniforms.upload(_gl,materialProperties.uniformsList,m_uniforms,textures);material.uniformsNeedUpdate=false;}if(material.isSpriteMaterial){p_uniforms.setValue(_gl,'center',object.center);}// common matrices p_uniforms.setValue(_gl,'modelViewMatrix',object.modelViewMatrix);p_uniforms.setValue(_gl,'normalMatrix',object.normalMatrix);p_uniforms.setValue(_gl,'modelMatrix',object.matrixWorld);return program;}// If uniforms are marked as clean, they don't need to be loaded to the GPU. function markUniformsLightsNeedsUpdate(uniforms,value){uniforms.ambientLightColor.needsUpdate=value;uniforms.lightProbe.needsUpdate=value;uniforms.directionalLights.needsUpdate=value;uniforms.directionalLightShadows.needsUpdate=value;uniforms.pointLights.needsUpdate=value;uniforms.pointLightShadows.needsUpdate=value;uniforms.spotLights.needsUpdate=value;uniforms.spotLightShadows.needsUpdate=value;uniforms.rectAreaLights.needsUpdate=value;uniforms.hemisphereLights.needsUpdate=value;}function materialNeedsLights(material){return material.isMeshLambertMaterial||material.isMeshToonMaterial||material.isMeshPhongMaterial||material.isMeshStandardMaterial||material.isShadowMaterial||material.isShaderMaterial&&material.lights===true;}// this.setFramebuffer=function(value){if(_framebuffer!==value&&_currentRenderTarget===null)_gl.bindFramebuffer(36160,value);_framebuffer=value;};this.getActiveCubeFace=function(){return _currentActiveCubeFace;};this.getActiveMipmapLevel=function(){return _currentActiveMipmapLevel;};this.getRenderList=function(){return currentRenderList;};this.setRenderList=function(renderList){currentRenderList=renderList;};this.getRenderState=function(){return currentRenderState;};this.setRenderState=function(renderState){currentRenderState=renderState;};this.getRenderTarget=function(){return _currentRenderTarget;};this.setRenderTarget=function(renderTarget){var activeCubeFace=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var activeMipmapLevel=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;_currentRenderTarget=renderTarget;_currentActiveCubeFace=activeCubeFace;_currentActiveMipmapLevel=activeMipmapLevel;if(renderTarget&&properties.get(renderTarget).__webglFramebuffer===undefined){textures.setupRenderTarget(renderTarget);}var framebuffer=_framebuffer;var isCube=false;if(renderTarget){var __webglFramebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget){framebuffer=__webglFramebuffer[activeCubeFace];isCube=true;}else if(renderTarget.isWebGLMultisampleRenderTarget){framebuffer=properties.get(renderTarget).__webglMultisampledFramebuffer;}else{framebuffer=__webglFramebuffer;}_currentViewport.copy(renderTarget.viewport);_currentScissor.copy(renderTarget.scissor);_currentScissorTest=renderTarget.scissorTest;}else{_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();_currentScissorTest=_scissorTest;}if(_currentFramebuffer!==framebuffer){_gl.bindFramebuffer(36160,framebuffer);_currentFramebuffer=framebuffer;}state.viewport(_currentViewport);state.scissor(_currentScissor);state.setScissorTest(_currentScissorTest);if(isCube){var textureProperties=properties.get(renderTarget.texture);_gl.framebufferTexture2D(36160,36064,34069+activeCubeFace,textureProperties.__webglTexture,activeMipmapLevel);}};this.readRenderTargetPixels=function(renderTarget,x,y,width,height,buffer,activeCubeFaceIndex){if(!(renderTarget&&renderTarget.isWebGLRenderTarget)){console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');return;}var framebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget&&activeCubeFaceIndex!==undefined){framebuffer=framebuffer[activeCubeFaceIndex];}if(framebuffer){var restore=false;if(framebuffer!==_currentFramebuffer){_gl.bindFramebuffer(36160,framebuffer);restore=true;}try{var texture=renderTarget.texture;var textureFormat=texture.format;var textureType=texture.type;if(textureFormat!==RGBAFormat&&utils.convert(textureFormat)!==_gl.getParameter(35739)){console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');return;}if(textureType!==UnsignedByteType&&utils.convert(textureType)!==_gl.getParameter(35738)&&// IE11, Edge and Chrome Mac < 52 (#9513) !(textureType===FloatType&&(capabilities.isWebGL2||extensions.get('OES_texture_float')||extensions.get('WEBGL_color_buffer_float')))&&// Chrome Mac >= 52 and Firefox !(textureType===HalfFloatType&&(capabilities.isWebGL2?extensions.get('EXT_color_buffer_float'):extensions.get('EXT_color_buffer_half_float')))){console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');return;}if(_gl.checkFramebufferStatus(36160)===36053){// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) if(x>=0&&x<=renderTarget.width-width&&y>=0&&y<=renderTarget.height-height){_gl.readPixels(x,y,width,height,utils.convert(textureFormat),utils.convert(textureType),buffer);}}else{console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');}}finally{if(restore){_gl.bindFramebuffer(36160,_currentFramebuffer);}}}};this.copyFramebufferToTexture=function(position,texture,level){if(level===undefined)level=0;var levelScale=Math.pow(2,-level);var width=Math.floor(texture.image.width*levelScale);var height=Math.floor(texture.image.height*levelScale);var glFormat=utils.convert(texture.format);textures.setTexture2D(texture,0);_gl.copyTexImage2D(3553,level,glFormat,position.x,position.y,width,height,0);state.unbindTexture();};this.copyTextureToTexture=function(position,srcTexture,dstTexture,level){if(level===undefined)level=0;var width=srcTexture.image.width;var height=srcTexture.image.height;var glFormat=utils.convert(dstTexture.format);var glType=utils.convert(dstTexture.type);textures.setTexture2D(dstTexture,0);// As another texture upload may have changed pixelStorei // parameters, make sure they are correct for the dstTexture _gl.pixelStorei(37440,dstTexture.flipY);_gl.pixelStorei(37441,dstTexture.premultiplyAlpha);_gl.pixelStorei(3317,dstTexture.unpackAlignment);if(srcTexture.isDataTexture){_gl.texSubImage2D(3553,level,position.x,position.y,width,height,glFormat,glType,srcTexture.image.data);}else{if(srcTexture.isCompressedTexture){_gl.compressedTexSubImage2D(3553,level,position.x,position.y,srcTexture.mipmaps[0].width,srcTexture.mipmaps[0].height,glFormat,srcTexture.mipmaps[0].data);}else{_gl.texSubImage2D(3553,level,position.x,position.y,glFormat,glType,srcTexture.image);}}// Generate mipmaps only when copying level 0 if(level===0&&dstTexture.generateMipmaps)_gl.generateMipmap(3553);state.unbindTexture();};this.initTexture=function(texture){textures.setTexture2D(texture,0);state.unbindTexture();};if(typeof __THREE_DEVTOOLS__!=='undefined'){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe',{detail:this}));// eslint-disable-line no-undef }}function WebGL1Renderer(parameters){WebGLRenderer.call(this,parameters);}WebGL1Renderer.prototype=Object.assign(Object.create(WebGLRenderer.prototype),{constructor:WebGL1Renderer,isWebGL1Renderer:true});var Scene=/*#__PURE__*/function(_Object3D){_inherits(Scene,_Object3D);var _super4=_createSuper(Scene);function Scene(){var _this11;_classCallCheck(this,Scene);_this11=_super4.call(this);Object.defineProperty(_assertThisInitialized(_this11),'isScene',{value:true});_this11.type='Scene';_this11.background=null;_this11.environment=null;_this11.fog=null;_this11.overrideMaterial=null;_this11.autoUpdate=true;// checked by the renderer if(typeof __THREE_DEVTOOLS__!=='undefined'){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe',{detail:_assertThisInitialized(_this11)}));// eslint-disable-line no-undef }return _this11;}_createClass(Scene,[{key:"copy",value:function copy(source,recursive){_get(_getPrototypeOf(Scene.prototype),"copy",this).call(this,source,recursive);if(source.background!==null)this.background=source.background.clone();if(source.environment!==null)this.environment=source.environment.clone();if(source.fog!==null)this.fog=source.fog.clone();if(source.overrideMaterial!==null)this.overrideMaterial=source.overrideMaterial.clone();this.autoUpdate=source.autoUpdate;this.matrixAutoUpdate=source.matrixAutoUpdate;return this;}},{key:"toJSON",value:function toJSON(meta){var data=_get(_getPrototypeOf(Scene.prototype),"toJSON",this).call(this,meta);if(this.background!==null)data.object.background=this.background.toJSON(meta);if(this.environment!==null)data.object.environment=this.environment.toJSON(meta);if(this.fog!==null)data.object.fog=this.fog.toJSON();return data;}}]);return Scene;}(Object3D);function InterleavedBuffer(array,stride){this.array=array;this.stride=stride;this.count=array!==undefined?array.length/stride:0;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0;this.uuid=MathUtils.generateUUID();}Object.defineProperty(InterleavedBuffer.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(InterleavedBuffer.prototype,{isInterleavedBuffer:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(source){this.array=new source.array.constructor(source.array);this.count=source.count;this.stride=source.stride;this.usage=source.usage;return this;},copyAt:function copyAt(index1,attribute,index2){index1*=this.stride;index2*=attribute.stride;for(var _i126=0,l=this.stride;_i126, * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * rotation: , * sizeAttenuation: * } */function SpriteMaterial(parameters){Material.call(this);this.type='SpriteMaterial';this.color=new Color(0xffffff);this.map=null;this.alphaMap=null;this.rotation=0;this.sizeAttenuation=true;this.transparent=true;this.setValues(parameters);}SpriteMaterial.prototype=Object.create(Material.prototype);SpriteMaterial.prototype.constructor=SpriteMaterial;SpriteMaterial.prototype.isSpriteMaterial=true;SpriteMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.alphaMap=source.alphaMap;this.rotation=source.rotation;this.sizeAttenuation=source.sizeAttenuation;return this;};var _geometry;var _intersectPoint=new Vector3();var _worldScale=new Vector3();var _mvPosition=new Vector3();var _alignedPosition=new Vector2();var _rotatedPosition=new Vector2();var _viewWorldMatrix=new Matrix4();var _vA$1=new Vector3();var _vB$1=new Vector3();var _vC$1=new Vector3();var _uvA$1=new Vector2();var _uvB$1=new Vector2();var _uvC$1=new Vector2();function Sprite(material){Object3D.call(this);this.type='Sprite';if(_geometry===undefined){_geometry=new BufferGeometry();var float32Array=new Float32Array([-0.5,-0.5,0,0,0,0.5,-0.5,0,1,0,0.5,0.5,0,1,1,-0.5,0.5,0,0,1]);var interleavedBuffer=new InterleavedBuffer(float32Array,5);_geometry.setIndex([0,1,2,0,2,3]);_geometry.setAttribute('position',new InterleavedBufferAttribute(interleavedBuffer,3,0,false));_geometry.setAttribute('uv',new InterleavedBufferAttribute(interleavedBuffer,2,3,false));}this.geometry=_geometry;this.material=material!==undefined?material:new SpriteMaterial();this.center=new Vector2(0.5,0.5);}Sprite.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Sprite,isSprite:true,raycast:function raycast(raycaster,intersects){if(raycaster.camera===null){console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');}_worldScale.setFromMatrixScale(this.matrixWorld);_viewWorldMatrix.copy(raycaster.camera.matrixWorld);this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse,this.matrixWorld);_mvPosition.setFromMatrixPosition(this.modelViewMatrix);if(raycaster.camera.isPerspectiveCamera&&this.material.sizeAttenuation===false){_worldScale.multiplyScalar(-_mvPosition.z);}var rotation=this.material.rotation;var sin,cos;if(rotation!==0){cos=Math.cos(rotation);sin=Math.sin(rotation);}var center=this.center;transformVertex(_vA$1.set(-0.5,-0.5,0),_mvPosition,center,_worldScale,sin,cos);transformVertex(_vB$1.set(0.5,-0.5,0),_mvPosition,center,_worldScale,sin,cos);transformVertex(_vC$1.set(0.5,0.5,0),_mvPosition,center,_worldScale,sin,cos);_uvA$1.set(0,0);_uvB$1.set(1,0);_uvC$1.set(1,1);// check first triangle var intersect=raycaster.ray.intersectTriangle(_vA$1,_vB$1,_vC$1,false,_intersectPoint);if(intersect===null){// check second triangle transformVertex(_vB$1.set(-0.5,0.5,0),_mvPosition,center,_worldScale,sin,cos);_uvB$1.set(0,1);intersect=raycaster.ray.intersectTriangle(_vA$1,_vC$1,_vB$1,false,_intersectPoint);if(intersect===null){return;}}var distance=raycaster.ray.origin.distanceTo(_intersectPoint);if(distanceraycaster.far)return;intersects.push({distance:distance,point:_intersectPoint.clone(),uv:Triangle.getUV(_intersectPoint,_vA$1,_vB$1,_vC$1,_uvA$1,_uvB$1,_uvC$1,new Vector2()),face:null,object:this});},copy:function copy(source){Object3D.prototype.copy.call(this,source);if(source.center!==undefined)this.center.copy(source.center);this.material=source.material;return this;}});function transformVertex(vertexPosition,mvPosition,center,scale,sin,cos){// compute position in camera space _alignedPosition.subVectors(vertexPosition,center).addScalar(0.5).multiply(scale);// to check if rotation is not zero if(sin!==undefined){_rotatedPosition.x=cos*_alignedPosition.x-sin*_alignedPosition.y;_rotatedPosition.y=sin*_alignedPosition.x+cos*_alignedPosition.y;}else{_rotatedPosition.copy(_alignedPosition);}vertexPosition.copy(mvPosition);vertexPosition.x+=_rotatedPosition.x;vertexPosition.y+=_rotatedPosition.y;// transform to world space vertexPosition.applyMatrix4(_viewWorldMatrix);}var _v1$4=new Vector3();var _v2$2=new Vector3();function LOD(){Object3D.call(this);this._currentLevel=0;this.type='LOD';Object.defineProperties(this,{levels:{enumerable:true,value:[]}});this.autoUpdate=true;}LOD.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:LOD,isLOD:true,copy:function copy(source){Object3D.prototype.copy.call(this,source,false);var levels=source.levels;for(var _i130=0,l=levels.length;_i1300){var _i131,l;for(_i131=1,l=levels.length;_i1310){_v1$4.setFromMatrixPosition(this.matrixWorld);var distance=raycaster.ray.origin.distanceTo(_v1$4);this.getObjectForDistance(distance).raycast(raycaster,intersects);}},update:function update(camera){var levels=this.levels;if(levels.length>1){_v1$4.setFromMatrixPosition(camera.matrixWorld);_v2$2.setFromMatrixPosition(this.matrixWorld);var distance=_v1$4.distanceTo(_v2$2)/camera.zoom;levels[0].object.visible=true;var _i132,l;for(_i132=1,l=levels.length;_i132=levels[_i132].distance){levels[_i132-1].object.visible=false;levels[_i132].object.visible=true;}else{break;}}this._currentLevel=_i132-1;for(;_i132, * opacity: , * * linewidth: , * linecap: "round", * linejoin: "round" * } */function LineBasicMaterial(parameters){Material.call(this);this.type='LineBasicMaterial';this.color=new Color(0xffffff);this.linewidth=1;this.linecap='round';this.linejoin='round';this.morphTargets=false;this.setValues(parameters);}LineBasicMaterial.prototype=Object.create(Material.prototype);LineBasicMaterial.prototype.constructor=LineBasicMaterial;LineBasicMaterial.prototype.isLineBasicMaterial=true;LineBasicMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.linewidth=source.linewidth;this.linecap=source.linecap;this.linejoin=source.linejoin;this.morphTargets=source.morphTargets;return this;};var _start=new Vector3();var _end=new Vector3();var _inverseMatrix$1=new Matrix4();var _ray$1=new Ray();var _sphere$2=new Sphere();function Line(geometry,material,mode){if(mode===1){console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');}Object3D.call(this);this.type='Line';this.geometry=geometry!==undefined?geometry:new BufferGeometry();this.material=material!==undefined?material:new LineBasicMaterial();this.updateMorphTargets();}Line.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Line,isLine:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);this.material=source.material;this.geometry=source.geometry;return this;},computeLineDistances:function computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[0];for(var _i143=1,l=positionAttribute.count;_i143localThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.far)continue;intersects.push({distance:distance,// What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point:interSegment.clone().applyMatrix4(this.matrixWorld),index:_i145,face:null,faceIndex:null,object:this});}}else{for(var _i146=0,_l8=positionAttribute.count-1;_i146<_l8;_i146+=step){vStart.fromBufferAttribute(positionAttribute,_i146);vEnd.fromBufferAttribute(positionAttribute,_i146+1);var _distSq=_ray$1.distanceSqToSegment(vStart,vEnd,interRay,interSegment);if(_distSq>localThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var _distance=raycaster.ray.origin.distanceTo(interRay);if(_distanceraycaster.far)continue;intersects.push({distance:_distance,// What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point:interSegment.clone().applyMatrix4(this.matrixWorld),index:_i146,face:null,faceIndex:null,object:this});}}}else if(geometry.isGeometry){var _vertices2=geometry.vertices;var nbVertices=_vertices2.length;for(var _i147=0;_i147localThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation var _distance2=raycaster.ray.origin.distanceTo(interRay);if(_distance2raycaster.far)continue;intersects.push({distance:_distance2,// What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point:interSegment.clone().applyMatrix4(this.matrixWorld),index:_i147,face:null,faceIndex:null,object:this});}}},updateMorphTargets:function updateMorphTargets(){var geometry=this.geometry;if(geometry.isBufferGeometry){var morphAttributes=geometry.morphAttributes;var keys=Object.keys(morphAttributes);if(keys.length>0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var m=0,ml=morphAttribute.length;m0){console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}}});var _start$1=new Vector3();var _end$1=new Vector3();function LineSegments(geometry,material){Line.call(this,geometry,material);this.type='LineSegments';}LineSegments.prototype=Object.assign(Object.create(Line.prototype),{constructor:LineSegments,isLineSegments:true,computeLineDistances:function computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[];for(var _i148=0,l=positionAttribute.count;_i148, * opacity: , * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * * size: , * sizeAttenuation: * * morphTargets: * } */function PointsMaterial(parameters){Material.call(this);this.type='PointsMaterial';this.color=new Color(0xffffff);this.map=null;this.alphaMap=null;this.size=1;this.sizeAttenuation=true;this.morphTargets=false;this.setValues(parameters);}PointsMaterial.prototype=Object.create(Material.prototype);PointsMaterial.prototype.constructor=PointsMaterial;PointsMaterial.prototype.isPointsMaterial=true;PointsMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.alphaMap=source.alphaMap;this.size=source.size;this.sizeAttenuation=source.sizeAttenuation;this.morphTargets=source.morphTargets;return this;};var _inverseMatrix$2=new Matrix4();var _ray$2=new Ray();var _sphere$3=new Sphere();var _position$1=new Vector3();function Points(geometry,material){Object3D.call(this);this.type='Points';this.geometry=geometry!==undefined?geometry:new BufferGeometry();this.material=material!==undefined?material:new PointsMaterial();this.updateMorphTargets();}Points.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Points,isPoints:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);this.material=source.material;this.geometry=source.geometry;return this;},raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var matrixWorld=this.matrixWorld;var threshold=raycaster.params.Points.threshold;// Checking boundingSphere distance to ray if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$3.copy(geometry.boundingSphere);_sphere$3.applyMatrix4(matrixWorld);_sphere$3.radius+=threshold;if(raycaster.ray.intersectsSphere(_sphere$3)===false)return;// _inverseMatrix$2.getInverse(matrixWorld);_ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);var localThreshold=threshold/((this.scale.x+this.scale.y+this.scale.z)/3);var localThresholdSq=localThreshold*localThreshold;if(geometry.isBufferGeometry){var index=geometry.index;var attributes=geometry.attributes;var positionAttribute=attributes.position;if(index!==null){var _indices2=index.array;for(var _i150=0,il=_indices2.length;_i1500){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var m=0,ml=morphAttribute.length;m0){console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}}});function testPoint(point,index,localThresholdSq,matrixWorld,raycaster,intersects,object){var rayPointDistanceSq=_ray$2.distanceSqToPoint(point);if(rayPointDistanceSqraycaster.far)return;intersects.push({distance:distance,distanceToRay:Math.sqrt(rayPointDistanceSq),point:intersectPoint,index:index,face:null,object:object});}}function VideoTexture(video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){Texture.call(this,video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.format=format!==undefined?format:RGBFormat;this.minFilter=minFilter!==undefined?minFilter:LinearFilter;this.magFilter=magFilter!==undefined?magFilter:LinearFilter;this.generateMipmaps=false;var scope=this;function updateVideo(){scope.needsUpdate=true;video.requestVideoFrameCallback(updateVideo);}if('requestVideoFrameCallback'in video){video.requestVideoFrameCallback(updateVideo);}}VideoTexture.prototype=Object.assign(Object.create(Texture.prototype),{constructor:VideoTexture,isVideoTexture:true,update:function update(){var video=this.image;var hasVideoFrameCallback=('requestVideoFrameCallback'in video);if(hasVideoFrameCallback===false&&video.readyState>=video.HAVE_CURRENT_DATA){this.needsUpdate=true;}}});function CompressedTexture(mipmaps,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){Texture.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.image={width:width,height:height};this.mipmaps=mipmaps;// no flipping for cube textures // (also flipping doesn't work for compressed textures ) this.flipY=false;// can't generate mipmaps for compressed textures // mips must be embedded in DDS files this.generateMipmaps=false;}CompressedTexture.prototype=Object.create(Texture.prototype);CompressedTexture.prototype.constructor=CompressedTexture;CompressedTexture.prototype.isCompressedTexture=true;function CanvasTexture(canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){Texture.call(this,canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.needsUpdate=true;}CanvasTexture.prototype=Object.create(Texture.prototype);CanvasTexture.prototype.constructor=CanvasTexture;CanvasTexture.prototype.isCanvasTexture=true;function DepthTexture(width,height,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,format){format=format!==undefined?format:DepthFormat;if(format!==DepthFormat&&format!==DepthStencilFormat){throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');}if(type===undefined&&format===DepthFormat)type=UnsignedShortType;if(type===undefined&&format===DepthStencilFormat)type=UnsignedInt248Type;Texture.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.image={width:width,height:height};this.magFilter=magFilter!==undefined?magFilter:NearestFilter;this.minFilter=minFilter!==undefined?minFilter:NearestFilter;this.flipY=false;this.generateMipmaps=false;}DepthTexture.prototype=Object.create(Texture.prototype);DepthTexture.prototype.constructor=DepthTexture;DepthTexture.prototype.isDepthTexture=true;var _geometryId=0;// Geometry uses even numbers as Id var _m1$3=new Matrix4();var _obj$1=new Object3D();var _offset$1=new Vector3();function Geometry(){Object.defineProperty(this,'id',{value:_geometryId+=2});this.uuid=MathUtils.generateUUID();this.name='';this.type='Geometry';this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingBox=null;this.boundingSphere=null;// update flags this.elementsNeedUpdate=false;this.verticesNeedUpdate=false;this.uvsNeedUpdate=false;this.normalsNeedUpdate=false;this.colorsNeedUpdate=false;this.lineDistancesNeedUpdate=false;this.groupsNeedUpdate=false;}Geometry.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:Geometry,isGeometry:true,applyMatrix4:function applyMatrix4(matrix){var normalMatrix=new Matrix3().getNormalMatrix(matrix);for(var _i153=0,il=this.vertices.length;_i1530){for(var _i156=0;_i1560){this.normalsNeedUpdate=true;}},computeFlatVertexNormals:function computeFlatVertexNormals(){this.computeFaceNormals();for(var f=0,fl=this.faces.length;f0){this.normalsNeedUpdate=true;}},computeMorphNormals:function computeMorphNormals(){// save original normals // - create temp variables on first access // otherwise just copy (for faster repeated calls) for(var f=0,fl=this.faces.length;f=0;_i167--){var idx=faceIndicesToRemove[_i167];this.faces.splice(idx,1);for(var j=0,jl=this.faceVertexUvs.length;j0;var hasFaceVertexNormal=face.vertexNormals.length>0;var hasFaceColor=face.color.r!==1||face.color.g!==1||face.color.b!==1;var hasFaceVertexColor=face.vertexColors.length>0;var faceType=0;faceType=setBit(faceType,0,0);// isQuad faceType=setBit(faceType,1,hasMaterial);faceType=setBit(faceType,2,hasFaceUv);faceType=setBit(faceType,3,hasFaceVertexUv);faceType=setBit(faceType,4,hasFaceNormal);faceType=setBit(faceType,5,hasFaceVertexNormal);faceType=setBit(faceType,6,hasFaceColor);faceType=setBit(faceType,7,hasFaceVertexColor);faces.push(faceType);faces.push(face.a,face.b,face.c);faces.push(face.materialIndex);if(hasFaceVertexUv){var faceVertexUvs=this.faceVertexUvs[0][_i172];faces.push(getUvIndex(faceVertexUvs[0]),getUvIndex(faceVertexUvs[1]),getUvIndex(faceVertexUvs[2]));}if(hasFaceNormal){faces.push(getNormalIndex(face.normal));}if(hasFaceVertexNormal){var vertexNormals=face.vertexNormals;faces.push(getNormalIndex(vertexNormals[0]),getNormalIndex(vertexNormals[1]),getNormalIndex(vertexNormals[2]));}if(hasFaceColor){faces.push(getColorIndex(face.color));}if(hasFaceVertexColor){var vertexColors=face.vertexColors;faces.push(getColorIndex(vertexColors[0]),getColorIndex(vertexColors[1]),getColorIndex(vertexColors[2]));}}function setBit(value,position,enabled){return enabled?value|1<0)data.data.colors=colors;if(uvs.length>0)data.data.uvs=[uvs];// temporal backward compatibility data.data.faces=faces;return data;},clone:function clone(){/* // Handle primitives const parameters = this.parameters; if ( parameters !== undefined ) { const values = []; for ( const key in parameters ) { values.push( parameters[ key ] ); } const geometry = Object.create( this.constructor.prototype ); this.constructor.apply( geometry, values ); return geometry; } return new this.constructor().copy( this ); */return new Geometry().copy(this);},copy:function copy(source){// reset this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingBox=null;this.boundingSphere=null;// name this.name=source.name;// vertices var vertices=source.vertices;for(var _i173=0,il=vertices.length;_i17380*dim){minX=maxX=data[0];minY=maxY=data[1];for(var _i182=dim;_i182maxX)maxX=x;if(y>maxY)maxY=y;}// minX, minY and invSize are later used to transform coords into integers for z-order calculation invSize=Math.max(maxX-minX,maxY-minY);invSize=invSize!==0?1/invSize:0;}earcutLinked(outerNode,triangles,dim,minX,minY,invSize);return triangles;}};// create a circular doubly linked list from polygon points in the specified winding order function linkedList(data,start,end,dim,clockwise){var i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;i=start;i-=dim){last=insertNode(i,data[i],data[i+1],last);}}if(last&&equals(last,last.next)){removeNode(last);last=last.next;}return last;}// eliminate colinear or duplicate points function filterPoints(start,end){if(!start)return start;if(!end)end=start;var p=start,again;do{again=false;if(!p.steiner&&(equals(p,p.next)||area(p.prev,p,p.next)===0)){removeNode(p);p=end=p.prev;if(p===p.next)break;again=true;}else{p=p.next;}}while(again||p!==end);return end;}// main ear slicing loop which triangulates a polygon (given as a linked list) function earcutLinked(ear,triangles,dim,minX,minY,invSize,pass){if(!ear)return;// interlink polygon nodes in z-order if(!pass&&invSize)indexCurve(ear,minX,minY,invSize);var stop=ear,prev,next;// iterate through ears, slicing them one by one while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear)){// cut off the triangle triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode(ear);// skipping the next vertex leads to less sliver triangles ear=next.next;stop=next.next;continue;}ear=next;// if we looped through the whole remaining polygon and can't find any more ears if(ear===stop){// try filtering points and slicing again if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);// if this didn't work, try curing all small self-intersections locally }else if(pass===1){ear=cureLocalIntersections(filterPoints(ear),triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,invSize,2);// as a last resort, try splitting the remaining polygon into two }else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,invSize);}break;}}}// check whether a polygon node forms a valid ear with adjacent nodes function isEar(ear){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p=ear.next.next;while(p!==ear.prev){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.next;}return true;}function isEarHashed(ear,minX,minY,invSize){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear // triangle bbox; min & max are calculated like this for speed var minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y;// z-order range for the current triangle bbox; var minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);var p=ear.prevZ,n=ear.nextZ;// look for points inside the triangle in both directions while(p&&p.z>=minZ&&n&&n.z<=maxZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ;}// look for remaining points in decreasing z-order while(p&&p.z>=minZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;}// look for remaining points in increasing z-order while(n&&n.z<=maxZ){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ;}return true;}// go through all polygon nodes and cure small local self-intersections function cureLocalIntersections(start,triangles,dim){var p=start;do{var a=p.prev,b=p.next.next;if(!equals(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)){triangles.push(a.i/dim);triangles.push(p.i/dim);triangles.push(b.i/dim);// remove two nodes involved removeNode(p);removeNode(p.next);p=start=b;}p=p.next;}while(p!==start);return filterPoints(p);}// try splitting polygon into two and triangulate them independently function splitEarcut(start,triangles,dim,minX,minY,invSize){// look for a valid diagonal that divides the polygon into two var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){// split the polygon in two by the diagonal var c=splitPolygon(a,b);// filter colinear points around the cuts a=filterPoints(a,a.next);c=filterPoints(c,c.next);// run earcut on each half earcutLinked(a,triangles,dim,minX,minY,invSize);earcutLinked(c,triangles,dim,minX,minY,invSize);return;}b=b.next;}a=a.next;}while(a!==start);}// link every hole into the outer loop, producing a single-ring polygon without holes function eliminateHoles(data,holeIndices,outerNode,dim){var queue=[];var i,len,start,end,list;for(i=0,len=holeIndices.length;i=p.next.y&&p.next.y!==p.y){var x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){qx=x;if(x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next;}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))){m=p;tanMin=tan;}}p=p.next;}while(p!==stop);return m;}// whether sector in vertex m contains sector in vertex p in the same coordinates function sectorContainsSector(m,p){return area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0;}// interlink polygon nodes in z-order function indexCurve(start,minX,minY,invSize){var p=start;do{if(p.z===null)p.z=zOrder(p.x,p.y,minX,minY,invSize);p.prevZ=p.prev;p.nextZ=p.next;p=p.next;}while(p!==start);p.prevZ.nextZ=null;p.prevZ=null;sortLinked(p);}// Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html function sortLinked(list){var i,p,q,e,tail,numMerges,pSize,qSize,inSize=1;do{p=list;list=null;tail=null;numMerges=0;while(p){numMerges++;q=p;pSize=0;for(i=0;i0||qSize>0&&q){if(pSize!==0&&(qSize===0||!q||p.z<=q.z)){e=p;p=p.nextZ;pSize--;}else{e=q;q=q.nextZ;qSize--;}if(tail)tail.nextZ=e;else list=e;e.prevZ=tail;tail=e;}p=q;}tail.nextZ=null;inSize*=2;}while(numMerges>1);return list;}// z-order of a point given coords and inverse of the longer side of data bbox function zOrder(x,y,minX,minY,invSize){// coords are transformed into non-negative 15-bit integer range x=32767*(x-minX)*invSize;y=32767*(y-minY)*invSize;x=(x|x<<8)&0x00FF00FF;x=(x|x<<4)&0x0F0F0F0F;x=(x|x<<2)&0x33333333;x=(x|x<<1)&0x55555555;y=(y|y<<8)&0x00FF00FF;y=(y|y<<4)&0x0F0F0F0F;y=(y|y<<2)&0x33333333;y=(y|y<<1)&0x55555555;return x|y<<1;}// find the leftmost node of a polygon ring function getLeftmost(start){var p=start,leftmost=start;do{if(p.x=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0;}// check if a diagonal between two polygon nodes is valid (lies in polygon interior) function isValidDiagonal(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon(a,b)&&(// dones't intersect other edges locallyInside(a,b)&&locallyInside(b,a)&&middleInside(a,b)&&(// locally visible area(a.prev,a,b.prev)||area(a,b.prev,b))||// does not create opposite-facing sectors equals(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0);// special zero-length case }// signed area of a triangle function area(p,q,r){return(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y);}// check if two points are equal function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y;}// check if two segments intersect function intersects(p1,q1,p2,q2){var o1=sign(area(p1,q1,p2));var o2=sign(area(p1,q1,q2));var o3=sign(area(p2,q2,p1));var o4=sign(area(p2,q2,q1));if(o1!==o2&&o3!==o4)return true;// general case if(o1===0&&onSegment(p1,p2,q1))return true;// p1, q1 and p2 are collinear and p2 lies on p1q1 if(o2===0&&onSegment(p1,q2,q1))return true;// p1, q1 and q2 are collinear and q2 lies on p1q1 if(o3===0&&onSegment(p2,p1,q2))return true;// p2, q2 and p1 are collinear and p1 lies on p2q2 if(o4===0&&onSegment(p2,q1,q2))return true;// p2, q2 and q1 are collinear and q1 lies on p2q2 return false;}// for collinear points p, q, r, check if point q lies on segment pr function onSegment(p,q,r){return q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y);}function sign(num){return num>0?1:num<0?-1:0;}// check if a polygon diagonal intersects any polygon segments function intersectsPolygon(a,b){var p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return true;p=p.next;}while(p!==a);return false;}// check if a polygon diagonal is locally inside the polygon function locallyInside(a,b){return area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0;}// check if the middle point of a polygon diagonal is inside the polygon function middleInside(a,b){var p=a,inside=false;var px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{if(p.y>py!==p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x)inside=!inside;p=p.next;}while(p!==a);return inside;}// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon(a,b){var a2=new Node$1(a.i,a.x,a.y),b2=new Node$1(b.i,b.x,b.y),an=a.next,bp=b.prev;a.next=b;b.prev=a;a2.next=an;an.prev=a2;b2.next=a2;a2.prev=b2;bp.next=b2;b2.prev=bp;return b2;}// create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode(i,x,y,last){var p=new Node$1(i,x,y);if(!last){p.prev=p;p.next=p;}else{p.next=last.next;p.prev=last;last.next.prev=p;last.next=p;}return p;}function removeNode(p){p.next.prev=p.prev;p.prev.next=p.next;if(p.prevZ)p.prevZ.nextZ=p.nextZ;if(p.nextZ)p.nextZ.prevZ=p.prevZ;}function Node$1(i,x,y){// vertex index in coordinates array this.i=i;// vertex coordinates this.x=x;this.y=y;// previous and next vertex nodes in a polygon ring this.prev=null;this.next=null;// z-order curve value this.z=null;// previous and next nodes in z-order this.prevZ=null;this.nextZ=null;// indicates whether this is a steiner point this.steiner=false;}function signedArea(data,start,end,dim){var sum=0;for(var _i183=start,j=end-dim;_i1832&&points[l-1].equals(points[0])){points.pop();}}function addContour(vertices,contour){for(var _i186=0;_i186, // number of points on the curves * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too * depth: , // Depth to extrude the shape * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into the original shape bevel goes * bevelSize: , // how far from shape outline (including bevelOffset) is bevel * bevelOffset: , // how far from shape outline does bevel start * bevelSegments: , // number of bevel layers * * extrudePath: // curve to extrude shape along * * UVGenerator: // object that provides UV generator functions * * } */var ExtrudeBufferGeometry=/*#__PURE__*/function(_BufferGeometry3){_inherits(ExtrudeBufferGeometry,_BufferGeometry3);var _super5=_createSuper(ExtrudeBufferGeometry);function ExtrudeBufferGeometry(shapes,options){var _this12;_classCallCheck(this,ExtrudeBufferGeometry);_this12=_super5.call(this);_this12.type='ExtrudeBufferGeometry';_this12.parameters={shapes:shapes,options:options};shapes=Array.isArray(shapes)?shapes:[shapes];var scope=_assertThisInitialized(_this12);var verticesArray=[];var uvArray=[];for(var _i187=0,l=shapes.length;_i187Number.EPSILON){// not collinear // length of vectors for normalizing var v_prev_len=Math.sqrt(v_prev_lensq);var v_next_len=Math.sqrt(v_next_x*v_next_x+v_next_y*v_next_y);// shift adjacent points by unit vectors to the left var ptPrevShift_x=inPrev.x-v_prev_y/v_prev_len;var ptPrevShift_y=inPrev.y+v_prev_x/v_prev_len;var ptNextShift_x=inNext.x-v_next_y/v_next_len;var ptNextShift_y=inNext.y+v_next_x/v_next_len;// scaling factor for v_prev to intersection point var sf=((ptNextShift_x-ptPrevShift_x)*v_next_y-(ptNextShift_y-ptPrevShift_y)*v_next_x)/(v_prev_x*v_next_y-v_prev_y*v_next_x);// vector from inPt to intersection point v_trans_x=ptPrevShift_x+v_prev_x*sf-inPt.x;v_trans_y=ptPrevShift_y+v_prev_y*sf-inPt.y;// Don't normalize!, otherwise sharp corners become ugly // but prevent crazy spikes var v_trans_lensq=v_trans_x*v_trans_x+v_trans_y*v_trans_y;if(v_trans_lensq<=2){return new Vector2(v_trans_x,v_trans_y);}else{shrink_by=Math.sqrt(v_trans_lensq/2);}}else{// handle special case of collinear edges var direction_eq=false;// assumes: opposite if(v_prev_x>Number.EPSILON){if(v_next_x>Number.EPSILON){direction_eq=true;}}else{if(v_prev_x<-Number.EPSILON){if(v_next_x<-Number.EPSILON){direction_eq=true;}}else{if(Math.sign(v_prev_y)===Math.sign(v_next_y)){direction_eq=true;}}}if(direction_eq){// console.log("Warning: lines are a straight sequence"); v_trans_x=-v_prev_y;v_trans_y=v_prev_x;shrink_by=Math.sqrt(v_prev_lensq);}else{// console.log("Warning: lines are a straight spike"); v_trans_x=v_prev_x;v_trans_y=v_prev_y;shrink_by=Math.sqrt(v_prev_lensq/2);}}return new Vector2(v_trans_x/shrink_by,v_trans_y/shrink_by);}var contourMovements=[];for(var _i188=0,il=contour.length,j=il-1,k=_i188+1;_i188 0; b -- ) { var t=b/bevelSegments;var z=bevelThickness*Math.cos(t*Math.PI/2);var _bs=bevelSize*Math.sin(t*Math.PI/2)+bevelOffset;// contract shape for(var _i190=0,_il27=contour.length;_i190<_il27;_i190++){var vert=scalePt2(contour[_i190],contourMovements[_i190],_bs);v(vert.x,vert.y,-z);}// expand holes for(var _h4=0,_hl3=holes.length;_h4<_hl3;_h4++){var _ahole3=holes[_h4];oneHoleMovements=holesMovements[_h4];for(var _i191=0,_il28=_ahole3.length;_i191<_il28;_i191++){var _vert=scalePt2(_ahole3[_i191],oneHoleMovements[_i191],_bs);v(_vert.x,_vert.y,-z);}}}var bs=bevelSize+bevelOffset;// Back facing vertices for(var _i192=0;_i192=0;_b6--){var _t2=_b6/bevelSegments;var _z2=bevelThickness*Math.cos(_t2*Math.PI/2);var _bs2=bevelSize*Math.sin(_t2*Math.PI/2)+bevelOffset;// contract shape for(var _i194=0,_il29=contour.length;_i194<_il29;_i194++){var _vert4=scalePt2(contour[_i194],contourMovements[_i194],_bs2);v(_vert4.x,_vert4.y,depth+_z2);}// expand holes for(var _h5=0,_hl4=holes.length;_h5<_hl4;_h5++){var _ahole4=holes[_h5];oneHoleMovements=holesMovements[_h5];for(var _i195=0,_il30=_ahole4.length;_i195<_il30;_i195++){var _vert5=scalePt2(_ahole4[_i195],oneHoleMovements[_i195],_bs2);if(!extrudeByPath){v(_vert5.x,_vert5.y,depth+_z2);}else{v(_vert5.x,_vert5.y+extrudePts[steps-1].y,extrudePts[steps-1].x+_z2);}}}}/* Faces */ // Top and bottom faces buildLidFaces();// Sides faces buildSideFaces();///// Internal functions function buildLidFaces(){var start=verticesArray.length/3;if(bevelEnabled){var layer=0;// steps + 1 var offset=vlen*layer;// Bottom faces for(var _i196=0;_i196=0){var _j13=i;var _k3=i-1;if(_k3<0)_k3=contour.length-1;//console.log('b', i,j, i-1, k,vertices.length); for(var _s5=0,sl=steps+bevelSegments*2;_s5, // number of points on the curves * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too * depth: , // Depth to extrude the shape * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into the original shape bevel goes * bevelSize: , // how far from shape outline (including bevelOffset) is bevel * bevelOffset: , // how far from shape outline does bevel start * bevelSegments: , // number of bevel layers * * extrudePath: // curve to extrude shape along * * UVGenerator: // object that provides UV generator functions * * } */var ExtrudeGeometry=/*#__PURE__*/function(_Geometry){_inherits(ExtrudeGeometry,_Geometry);var _super6=_createSuper(ExtrudeGeometry);function ExtrudeGeometry(shapes,options){var _this13;_classCallCheck(this,ExtrudeGeometry);_this13=_super6.call(this);_this13.type='ExtrudeGeometry';_this13.parameters={shapes:shapes,options:options};_this13.fromBufferGeometry(new ExtrudeBufferGeometry(shapes,options));_this13.mergeVertices();return _this13;}_createClass(ExtrudeGeometry,[{key:"toJSON",value:function toJSON(){var data=_get(_getPrototypeOf(ExtrudeGeometry.prototype),"toJSON",this).call(this);var shapes=this.parameters.shapes;var options=this.parameters.options;return toJSON$1(shapes,options,data);}}]);return ExtrudeGeometry;}(Geometry);function toJSON$1(shapes,options,data){data.shapes=[];if(Array.isArray(shapes)){for(var _i201=0,l=shapes.length;_i201=0){func(u-EPS,v,p1);pu.subVectors(p0,p1);}else{func(u+EPS,v,p1);pu.subVectors(p1,p0);}if(v-EPS>=0){func(u,v-EPS,p1);pv.subVectors(p0,p1);}else{func(u,v+EPS,p1);pv.subVectors(p1,p0);}// cross product of tangent vectors returns surface normal normal.crossVectors(pu,pv).normalize();normals.push(normal.x,normal.y,normal.z);// uv uvs.push(u,v);}}// generate indices for(var _i203=0;_i203 * } */function ShadowMaterial(parameters){Material.call(this);this.type='ShadowMaterial';this.color=new Color(0x000000);this.transparent=true;this.setValues(parameters);}ShadowMaterial.prototype=Object.create(Material.prototype);ShadowMaterial.prototype.constructor=ShadowMaterial;ShadowMaterial.prototype.isShadowMaterial=true;ShadowMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);return this;};function RawShaderMaterial(parameters){ShaderMaterial.call(this,parameters);this.type='RawShaderMaterial';}RawShaderMaterial.prototype=Object.create(ShaderMaterial.prototype);RawShaderMaterial.prototype.constructor=RawShaderMaterial;RawShaderMaterial.prototype.isRawShaderMaterial=true;/** * parameters = { * color: , * roughness: , * metalness: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * roughnessMap: new THREE.Texture( ), * * metalnessMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * envMapIntensity: * * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshStandardMaterial(parameters){Material.call(this);this.defines={'STANDARD':''};this.type='MeshStandardMaterial';this.color=new Color(0xffffff);// diffuse this.roughness=1.0;this.metalness=0.0;this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.roughnessMap=null;this.metalnessMap=null;this.alphaMap=null;this.envMap=null;this.envMapIntensity=1.0;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.vertexTangents=false;this.setValues(parameters);}MeshStandardMaterial.prototype=Object.create(Material.prototype);MeshStandardMaterial.prototype.constructor=MeshStandardMaterial;MeshStandardMaterial.prototype.isMeshStandardMaterial=true;MeshStandardMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.defines={'STANDARD':''};this.color.copy(source.color);this.roughness=source.roughness;this.metalness=source.metalness;this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.roughnessMap=source.roughnessMap;this.metalnessMap=source.metalnessMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.envMapIntensity=source.envMapIntensity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;this.vertexTangents=source.vertexTangents;return this;};/** * parameters = { * clearcoat: , * clearcoatMap: new THREE.Texture( ), * clearcoatRoughness: , * clearcoatRoughnessMap: new THREE.Texture( ), * clearcoatNormalScale: , * clearcoatNormalMap: new THREE.Texture( ), * * reflectivity: , * ior: , * * sheen: , * * transmission: , * transmissionMap: new THREE.Texture( ) * } */function MeshPhysicalMaterial(parameters){MeshStandardMaterial.call(this);this.defines={'STANDARD':'','PHYSICAL':''};this.type='MeshPhysicalMaterial';this.clearcoat=0.0;this.clearcoatMap=null;this.clearcoatRoughness=0.0;this.clearcoatRoughnessMap=null;this.clearcoatNormalScale=new Vector2(1,1);this.clearcoatNormalMap=null;this.reflectivity=0.5;// maps to F0 = 0.04 Object.defineProperty(this,'ior',{get:function get(){return(1+0.4*this.reflectivity)/(1-0.4*this.reflectivity);},set:function set(ior){this.reflectivity=MathUtils.clamp(2.5*(ior-1)/(ior+1),0,1);}});this.sheen=null;// null will disable sheen bsdf this.transmission=0.0;this.transmissionMap=null;this.setValues(parameters);}MeshPhysicalMaterial.prototype=Object.create(MeshStandardMaterial.prototype);MeshPhysicalMaterial.prototype.constructor=MeshPhysicalMaterial;MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial=true;MeshPhysicalMaterial.prototype.copy=function(source){MeshStandardMaterial.prototype.copy.call(this,source);this.defines={'STANDARD':'','PHYSICAL':''};this.clearcoat=source.clearcoat;this.clearcoatMap=source.clearcoatMap;this.clearcoatRoughness=source.clearcoatRoughness;this.clearcoatRoughnessMap=source.clearcoatRoughnessMap;this.clearcoatNormalMap=source.clearcoatNormalMap;this.clearcoatNormalScale.copy(source.clearcoatNormalScale);this.reflectivity=source.reflectivity;if(source.sheen){this.sheen=(this.sheen||new Color()).copy(source.sheen);}else{this.sheen=null;}this.transmission=source.transmission;this.transmissionMap=source.transmissionMap;return this;};/** * parameters = { * color: , * specular: , * shininess: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.MultiplyOperation, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshPhongMaterial(parameters){Material.call(this);this.type='MeshPhongMaterial';this.color=new Color(0xffffff);// diffuse this.specular=new Color(0x111111);this.shininess=30;this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshPhongMaterial.prototype=Object.create(Material.prototype);MeshPhongMaterial.prototype.constructor=MeshPhongMaterial;MeshPhongMaterial.prototype.isMeshPhongMaterial=true;MeshPhongMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.specular.copy(source.specular);this.shininess=source.shininess;this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/** * parameters = { * color: , * * map: new THREE.Texture( ), * gradientMap: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * alphaMap: new THREE.Texture( ), * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshToonMaterial(parameters){Material.call(this);this.defines={'TOON':''};this.type='MeshToonMaterial';this.color=new Color(0xffffff);this.map=null;this.gradientMap=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshToonMaterial.prototype=Object.create(Material.prototype);MeshToonMaterial.prototype.constructor=MeshToonMaterial;MeshToonMaterial.prototype.isMeshToonMaterial=true;MeshToonMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.gradientMap=source.gradientMap;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/** * parameters = { * opacity: , * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * * skinning: , * morphTargets: , * morphNormals: * } */function MeshNormalMaterial(parameters){Material.call(this);this.type='MeshNormalMaterial';this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshNormalMaterial.prototype=Object.create(Material.prototype);MeshNormalMaterial.prototype.constructor=MeshNormalMaterial;MeshNormalMaterial.prototype.isMeshNormalMaterial=true;MeshNormalMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/** * parameters = { * color: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */function MeshLambertMaterial(parameters){Material.call(this);this.type='MeshLambertMaterial';this.color=new Color(0xffffff);// diffuse this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshLambertMaterial.prototype=Object.create(Material.prototype);MeshLambertMaterial.prototype.constructor=MeshLambertMaterial;MeshLambertMaterial.prototype.isMeshLambertMaterial=true;MeshLambertMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/** * parameters = { * color: , * opacity: , * * matcap: new THREE.Texture( ), * * map: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * alphaMap: new THREE.Texture( ), * * skinning: , * morphTargets: , * morphNormals: * } */function MeshMatcapMaterial(parameters){Material.call(this);this.defines={'MATCAP':''};this.type='MeshMatcapMaterial';this.color=new Color(0xffffff);// diffuse this.matcap=null;this.map=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshMatcapMaterial.prototype=Object.create(Material.prototype);MeshMatcapMaterial.prototype.constructor=MeshMatcapMaterial;MeshMatcapMaterial.prototype.isMeshMatcapMaterial=true;MeshMatcapMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.defines={'MATCAP':''};this.color.copy(source.color);this.matcap=source.matcap;this.map=source.map;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/** * parameters = { * color: , * opacity: , * * linewidth: , * * scale: , * dashSize: , * gapSize: * } */function LineDashedMaterial(parameters){LineBasicMaterial.call(this);this.type='LineDashedMaterial';this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(parameters);}LineDashedMaterial.prototype=Object.create(LineBasicMaterial.prototype);LineDashedMaterial.prototype.constructor=LineDashedMaterial;LineDashedMaterial.prototype.isLineDashedMaterial=true;LineDashedMaterial.prototype.copy=function(source){LineBasicMaterial.prototype.copy.call(this,source);this.scale=source.scale;this.dashSize=source.dashSize;this.gapSize=source.gapSize;return this;};var Materials=/*#__PURE__*/Object.freeze({__proto__:null,ShadowMaterial:ShadowMaterial,SpriteMaterial:SpriteMaterial,RawShaderMaterial:RawShaderMaterial,ShaderMaterial:ShaderMaterial,PointsMaterial:PointsMaterial,MeshPhysicalMaterial:MeshPhysicalMaterial,MeshStandardMaterial:MeshStandardMaterial,MeshPhongMaterial:MeshPhongMaterial,MeshToonMaterial:MeshToonMaterial,MeshNormalMaterial:MeshNormalMaterial,MeshLambertMaterial:MeshLambertMaterial,MeshDepthMaterial:MeshDepthMaterial,MeshDistanceMaterial:MeshDistanceMaterial,MeshBasicMaterial:MeshBasicMaterial,MeshMatcapMaterial:MeshMatcapMaterial,LineDashedMaterial:LineDashedMaterial,LineBasicMaterial:LineBasicMaterial,Material:Material});var AnimationUtils={// same as Array.prototype.slice, but also works on typed arrays arraySlice:function arraySlice(array,from,to){if(AnimationUtils.isTypedArray(array)){// in ios9 array.subarray(from, undefined) will return empty array // but array.subarray(from) or array.subarray(from, len) is correct return new array.constructor(array.subarray(from,to!==undefined?to:array.length));}return array.slice(from,to);},// converts an array to a specific type convertArray:function convertArray(array,type,forceClone){if(!array||// let 'undefined' and 'null' pass !forceClone&&array.constructor===type)return array;if(typeof type.BYTES_PER_ELEMENT==='number'){return new type(array);// create typed array }return Array.prototype.slice.call(array);// create Array },isTypedArray:function isTypedArray(object){return ArrayBuffer.isView(object)&&!_instanceof(object,DataView);},// returns an array by which times and values can be sorted getKeyframeOrder:function getKeyframeOrder(times){function compareTime(i,j){return times[i]-times[j];}var n=times.length;var result=new Array(n);for(var _i211=0;_i211!==n;++_i211){result[_i211]=_i211;}result.sort(compareTime);return result;},// uses the array previously returned by 'getKeyframeOrder' to sort data sortedArray:function sortedArray(values,stride,order){var nValues=values.length;var result=new values.constructor(nValues);for(var _i212=0,dstOffset=0;dstOffset!==nValues;++_i212){var srcOffset=order[_i212]*stride;for(var j=0;j!==stride;++j){result[dstOffset++]=values[srcOffset+j];}}return result;},// function for parsing AOS keyframe formats flattenJSON:function flattenJSON(jsonKeys,times,values,valuePropertyName){var i=1,key=jsonKeys[0];while(key!==undefined&&key[valuePropertyName]===undefined){key=jsonKeys[i++];}if(key===undefined)return;// no data var value=key[valuePropertyName];if(value===undefined)return;// no data if(Array.isArray(value)){do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);values.push.apply(values,value);// push all elements }key=jsonKeys[i++];}while(key!==undefined);}else if(value.toArray!==undefined){// ...assume THREE.Math-ish do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);value.toArray(values,values.length);}key=jsonKeys[i++];}while(key!==undefined);}else{// otherwise push as-is do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);values.push(value);}key=jsonKeys[i++];}while(key!==undefined);}},subclip:function subclip(sourceClip,name,startFrame,endFrame,fps){fps=fps||30;var clip=sourceClip.clone();clip.name=name;var tracks=[];for(var _i213=0;_i213=endFrame)continue;times.push(track.times[j]);for(var k=0;kclip.tracks[_i214].times[0]){minStartTime=clip.tracks[_i214].times[0];}}// shift all tracks such that clip begins at t=0 for(var _i215=0;_i215=referenceTrack.times[lastIndex]){// Reference frame is after the last keyframe, so just use the last keyframe var _startIndex=lastIndex*referenceValueSize+referenceOffset;var _endIndex=_startIndex+referenceValueSize-referenceOffset;referenceValue=AnimationUtils.arraySlice(referenceTrack.values,_startIndex,_endIndex);}else{// Interpolate to the reference value var interpolant=referenceTrack.createInterpolant();var _startIndex2=referenceOffset;var _endIndex2=referenceValueSize-referenceOffset;interpolant.evaluate(referenceTime);referenceValue=AnimationUtils.arraySlice(interpolant.resultBuffer,_startIndex2,_endIndex2);}// Conjugate the quaternion if(referenceTrackType==='quaternion'){var referenceQuat=new Quaternion().fromArray(referenceValue).normalize().conjugate();referenceQuat.toArray(referenceValue);}// Subtract the reference value from all of the track values var numTimes=targetTrack.times.length;for(var j=0;j= t1 || t1 === undefined ) { forward_scan:if(!(t=t0)){// looping? var t1global=pp[1];if(t=t0){// we have arrived at the sought interval break seek;}}// prepare binary search on the left side of the index right=i1;i1=0;break linear_scan;}// the interval is valid break validate_interval;}// linear scan // binary search while(i1>>1;if(t seconds conversions) scale:function scale(timeScale){if(timeScale!==1.0){var times=this.times;for(var _i221=0,n=times.length;_i221!==n;++_i221){times[_i221]*=timeScale;}}return this;},// removes keyframes before and after animation without changing any values within the range [startTime, endTime]. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values trim:function trim(startTime,endTime){var times=this.times,nKeys=times.length;var from=0,to=nKeys-1;while(from!==nKeys&×[from]endTime){--to;}++to;// inclusive -> exclusive bound if(from!==0||to!==nKeys){// empty tracks are forbidden, so keep at least one keyframe if(from>=to){to=Math.max(to,1);from=to-1;}var stride=this.getValueSize();this.times=AnimationUtils.arraySlice(times,from,to);this.values=AnimationUtils.arraySlice(this.values,from*stride,to*stride);}return this;},// ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable validate:function validate(){var valid=true;var valueSize=this.getValueSize();if(valueSize-Math.floor(valueSize)!==0){console.error('THREE.KeyframeTrack: Invalid value size in track.',this);valid=false;}var times=this.times,values=this.values,nKeys=times.length;if(nKeys===0){console.error('THREE.KeyframeTrack: Track is empty.',this);valid=false;}var prevTime=null;for(var _i222=0;_i222!==nKeys;_i222++){var currTime=times[_i222];if(typeof currTime==='number'&&isNaN(currTime)){console.error('THREE.KeyframeTrack: Time is not a valid number.',this,_i222,currTime);valid=false;break;}if(prevTime!==null&&prevTime>currTime){console.error('THREE.KeyframeTrack: Out of order keys.',this,_i222,currTime,prevTime);valid=false;break;}prevTime=currTime;}if(values!==undefined){if(AnimationUtils.isTypedArray(values)){for(var _i223=0,n=values.length;_i223!==n;++_i223){var value=values[_i223];if(isNaN(value)){console.error('THREE.KeyframeTrack: Value is not a valid number.',this,_i223,value);valid=false;break;}}}}return valid;},// removes equivalent sequential keys as common in morph target sequences // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) optimize:function optimize(){// times or values may be shared with other tracks, so overwriting is unsafe var times=AnimationUtils.arraySlice(this.times),values=AnimationUtils.arraySlice(this.values),stride=this.getValueSize(),smoothInterpolation=this.getInterpolation()===InterpolateSmooth,lastIndex=times.length-1;var writeIndex=1;for(var _i224=1;_i2240){times[writeIndex]=times[lastIndex];for(var _readOffset=lastIndex*stride,_writeOffset=writeIndex*stride,_j16=0;_j16!==stride;++_j16){values[_writeOffset+_j16]=values[_readOffset+_j16];}++writeIndex;}if(writeIndex!==times.length){this.times=AnimationUtils.arraySlice(times,0,writeIndex);this.values=AnimationUtils.arraySlice(values,0,writeIndex*stride);}else{this.times=times;this.values=values;}return this;},clone:function clone(){var times=AnimationUtils.arraySlice(this.times,0);var values=AnimationUtils.arraySlice(this.values,0);var TypedKeyframeTrack=this.constructor;var track=new TypedKeyframeTrack(this.name,times,values);// Interpolant argument to constructor is not saved, so copy the factory method directly. track.createInterpolant=this.createInterpolant;return track;}});/** * A Track of Boolean keyframe values. */function BooleanKeyframeTrack(name,times,values){KeyframeTrack.call(this,name,times,values);}BooleanKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:BooleanKeyframeTrack,ValueTypeName:'bool',ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete,InterpolantFactoryMethodLinear:undefined,InterpolantFactoryMethodSmooth:undefined// Note: Actually this track could have a optimized / compressed // representation of a single value and a custom interpolant that // computes "firstValue ^ isOdd( index )". });/** * A Track of keyframe values that represent color. */function ColorKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}ColorKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:ColorKeyframeTrack,ValueTypeName:'color'// ValueBufferType is inherited // DefaultInterpolation is inherited // Note: Very basic implementation and nothing special yet. // However, this is the place for color space parameterization. });/** * A Track of numeric keyframe values. */function NumberKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}NumberKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:NumberKeyframeTrack,ValueTypeName:'number'// ValueBufferType is inherited // DefaultInterpolation is inherited });/** * Spherical linear unit quaternion interpolant. */function QuaternionLinearInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer);}QuaternionLinearInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:QuaternionLinearInterpolant,interpolate_:function interpolate_(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,alpha=(t-t0)/(t1-t0);var offset=i1*stride;for(var end=offset+stride;offset!==end;offset+=4){Quaternion.slerpFlat(result,0,values,offset-stride,values,offset,alpha);}return result;}});/** * A Track of quaternion keyframe values. */function QuaternionKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}QuaternionKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:QuaternionKeyframeTrack,ValueTypeName:'quaternion',// ValueBufferType is inherited DefaultInterpolation:InterpolateLinear,InterpolantFactoryMethodLinear:function InterpolantFactoryMethodLinear(result){return new QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),result);},InterpolantFactoryMethodSmooth:undefined// not yet implemented });/** * A Track that interpolates Strings */function StringKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}StringKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:StringKeyframeTrack,ValueTypeName:'string',ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete,InterpolantFactoryMethodLinear:undefined,InterpolantFactoryMethodSmooth:undefined});/** * A Track of vectored keyframe values. */function VectorKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}VectorKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:VectorKeyframeTrack,ValueTypeName:'vector'// ValueBufferType is inherited // DefaultInterpolation is inherited });function AnimationClip(name,duration,tracks,blendMode){this.name=name;this.tracks=tracks;this.duration=duration!==undefined?duration:-1;this.blendMode=blendMode!==undefined?blendMode:NormalAnimationBlendMode;this.uuid=MathUtils.generateUUID();// this means it should figure out its duration by scanning the tracks if(this.duration<0){this.resetDuration();}}function getTrackTypeForValueTypeName(typeName){switch(typeName.toLowerCase()){case'scalar':case'double':case'float':case'number':case'integer':return NumberKeyframeTrack;case'vector':case'vector2':case'vector3':case'vector4':return VectorKeyframeTrack;case'color':return ColorKeyframeTrack;case'quaternion':return QuaternionKeyframeTrack;case'bool':case'boolean':return BooleanKeyframeTrack;case'string':return StringKeyframeTrack;}throw new Error('THREE.KeyframeTrack: Unsupported typeName: '+typeName);}function parseKeyframeTrack(json){if(json.type===undefined){throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');}var trackType=getTrackTypeForValueTypeName(json.type);if(json.times===undefined){var times=[],values=[];AnimationUtils.flattenJSON(json.keys,times,values,'value');json.times=times;json.values=values;}// derived classes can define a static parse method if(trackType.parse!==undefined){return trackType.parse(json);}else{// by default, we assume a constructor compatible with the base return new trackType(json.name,json.times,json.values,json.interpolation);}}Object.assign(AnimationClip,{parse:function parse(json){var tracks=[],jsonTracks=json.tracks,frameTime=1.0/(json.fps||1.0);for(var _i225=0,n=jsonTracks.length;_i225!==n;++_i225){tracks.push(parseKeyframeTrack(jsonTracks[_i225]).scale(frameTime));}return new AnimationClip(json.name,json.duration,tracks,json.blendMode);},toJSON:function toJSON(clip){var tracks=[],clipTracks=clip.tracks;var json={'name':clip.name,'duration':clip.duration,'tracks':tracks,'uuid':clip.uuid,'blendMode':clip.blendMode};for(var _i226=0,n=clipTracks.length;_i226!==n;++_i226){tracks.push(KeyframeTrack.toJSON(clipTracks[_i226]));}return json;},CreateFromMorphTargetSequence:function CreateFromMorphTargetSequence(name,morphTargetSequence,fps,noLoop){var numMorphTargets=morphTargetSequence.length;var tracks=[];for(var _i227=0;_i2271){var name=parts[1];var animationMorphTargets=animationToMorphTargets[name];if(!animationMorphTargets){animationToMorphTargets[name]=animationMorphTargets=[];}animationMorphTargets.push(morphTarget);}}var clips=[];for(var _name4 in animationToMorphTargets){clips.push(AnimationClip.CreateFromMorphTargetSequence(_name4,animationToMorphTargets[_name4],fps,noLoop));}return clips;},// parse the animation.hierarchy format parseAnimation:function parseAnimation(animation,bones){if(!animation){console.error('THREE.AnimationClip: No animation in JSONLoader data.');return null;}var addNonemptyTrack=function addNonemptyTrack(trackType,trackName,animationKeys,propertyName,destTracks){// only return track if there are actually keys. if(animationKeys.length!==0){var times=[];var values=[];AnimationUtils.flattenJSON(animationKeys,times,values,propertyName);// empty keys are filtered out, so check again if(times.length!==0){destTracks.push(new trackType(trackName,times,values));}}};var tracks=[];var clipName=animation.name||'default';var fps=animation.fps||30;var blendMode=animation.blendMode;// automatic length determination in AnimationClip. var duration=animation.length||-1;var hierarchyTracks=animation.hierarchy||[];for(var h=0;h0||url.search(/^data\:image\/jpeg/)===0;texture.format=isJPEG?RGBFormat:RGBAFormat;texture.needsUpdate=true;if(onLoad!==undefined){onLoad(texture);}},onProgress,onError);return texture;}});/** * Extensible curve object. * * Some common of curve methods: * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) * .getPoints(), .getSpacedPoints() * .getLength() * .updateArcLengths() * * This following curves inherit from THREE.Curve: * * -- 2D curves -- * THREE.ArcCurve * THREE.CubicBezierCurve * THREE.EllipseCurve * THREE.LineCurve * THREE.QuadraticBezierCurve * THREE.SplineCurve * * -- 3D curves -- * THREE.CatmullRomCurve3 * THREE.CubicBezierCurve3 * THREE.LineCurve3 * THREE.QuadraticBezierCurve3 * * A series of curves can be represented as a THREE.CurvePath. * **/function Curve(){this.type='Curve';this.arcLengthDivisions=200;}Object.assign(Curve.prototype,{// Virtual base class method to overwrite and implement in subclasses // - t [0 .. 1] getPoint:function getPoint()/* t, optionalTarget */{console.warn('THREE.Curve: .getPoint() not implemented.');return null;},// Get point at relative position in curve according to arc length // - u [0 .. 1] getPointAt:function getPointAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getPoint(t,optionalTarget);},// Get sequence of points using getPoint( t ) getPoints:function getPoints(divisions){if(divisions===undefined)divisions=5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPoint(d/divisions));}return points;},// Get sequence of points using getPointAt( u ) getSpacedPoints:function getSpacedPoints(divisions){if(divisions===undefined)divisions=5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPointAt(d/divisions));}return points;},// Get total curve arc length getLength:function getLength(){var lengths=this.getLengths();return lengths[lengths.length-1];},// Get list of cumulative segment lengths getLengths:function getLengths(divisions){if(divisions===undefined)divisions=this.arcLengthDivisions;if(this.cacheArcLengths&&this.cacheArcLengths.length===divisions+1&&!this.needsUpdate){return this.cacheArcLengths;}this.needsUpdate=false;var cache=[];var current,last=this.getPoint(0);var sum=0;cache.push(0);for(var p=1;p<=divisions;p++){current=this.getPoint(p/divisions);sum+=current.distanceTo(last);cache.push(sum);last=current;}this.cacheArcLengths=cache;return cache;// { sums: cache, sum: sum }; Sum is in the last element. },updateArcLengths:function updateArcLengths(){this.needsUpdate=true;this.getLengths();},// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant getUtoTmapping:function getUtoTmapping(u,distance){var arcLengths=this.getLengths();var i=0;var il=arcLengths.length;var targetArcLength;// The targeted u distance value to get if(distance){targetArcLength=distance;}else{targetArcLength=u*arcLengths[il-1];}// binary search for the index with largest value smaller than target u distance var low=0,high=il-1,comparison;while(low<=high){i=Math.floor(low+(high-low)/2);// less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats comparison=arcLengths[i]-targetArcLength;if(comparison<0){low=i+1;}else if(comparison>0){high=i-1;}else{high=i;break;// DONE }}i=high;if(arcLengths[i]===targetArcLength){return i/(il-1);}// we could get finer grain at lengths, or use simple interpolation between two points var lengthBefore=arcLengths[i];var lengthAfter=arcLengths[i+1];var segmentLength=lengthAfter-lengthBefore;// determine where we are between the 'before' and 'after' points var segmentFraction=(targetArcLength-lengthBefore)/segmentLength;// add that fractional amount to t var t=(i+segmentFraction)/(il-1);return t;},// Returns a unit vector tangent at t // In case any sub curve does not implement its tangent derivation, // 2 points a small delta apart will be used to find its gradient // which seems to give a reasonable approximation getTangent:function getTangent(t,optionalTarget){var delta=0.0001;var t1=t-delta;var t2=t+delta;// Capping in case of danger if(t1<0)t1=0;if(t2>1)t2=1;var pt1=this.getPoint(t1);var pt2=this.getPoint(t2);var tangent=optionalTarget||(pt1.isVector2?new Vector2():new Vector3());tangent.copy(pt2).sub(pt1).normalize();return tangent;},getTangentAt:function getTangentAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getTangent(t,optionalTarget);},computeFrenetFrames:function computeFrenetFrames(segments,closed){// see http://www.cs.indiana.edu/pub/techreports/TR425.pdf var normal=new Vector3();var tangents=[];var normals=[];var binormals=[];var vec=new Vector3();var mat=new Matrix4();// compute the tangent vectors for each segment on the curve for(var _i246=0;_i246<=segments;_i246++){var u=_i246/segments;tangents[_i246]=this.getTangentAt(u,new Vector3());tangents[_i246].normalize();}// select an initial normal vector perpendicular to the first tangent vector, // and in the direction of the minimum tangent xyz component normals[0]=new Vector3();binormals[0]=new Vector3();var min=Number.MAX_VALUE;var tx=Math.abs(tangents[0].x);var ty=Math.abs(tangents[0].y);var tz=Math.abs(tangents[0].z);if(tx<=min){min=tx;normal.set(1,0,0);}if(ty<=min){min=ty;normal.set(0,1,0);}if(tz<=min){normal.set(0,0,1);}vec.crossVectors(tangents[0],normal).normalize();normals[0].crossVectors(tangents[0],vec);binormals[0].crossVectors(tangents[0],normals[0]);// compute the slowly-varying normal and binormal vectors for each segment on the curve for(var _i247=1;_i247<=segments;_i247++){normals[_i247]=normals[_i247-1].clone();binormals[_i247]=binormals[_i247-1].clone();vec.crossVectors(tangents[_i247-1],tangents[_i247]);if(vec.length()>Number.EPSILON){vec.normalize();var theta=Math.acos(MathUtils.clamp(tangents[_i247-1].dot(tangents[_i247]),-1,1));// clamp for floating pt errors normals[_i247].applyMatrix4(mat.makeRotationAxis(vec,theta));}binormals[_i247].crossVectors(tangents[_i247],normals[_i247]);}// if the curve is closed, postprocess the vectors so the first and last normal vectors are the same if(closed===true){var _theta=Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]),-1,1));_theta/=segments;if(tangents[0].dot(vec.crossVectors(normals[0],normals[segments]))>0){_theta=-_theta;}for(var _i248=1;_i248<=segments;_i248++){// twist a little... normals[_i248].applyMatrix4(mat.makeRotationAxis(tangents[_i248],_theta*_i248));binormals[_i248].crossVectors(tangents[_i248],normals[_i248]);}}return{tangents:tangents,normals:normals,binormals:binormals};},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(source){this.arcLengthDivisions=source.arcLengthDivisions;return this;},toJSON:function toJSON(){var data={metadata:{version:4.5,type:'Curve',generator:'Curve.toJSON'}};data.arcLengthDivisions=this.arcLengthDivisions;data.type=this.type;return data;},fromJSON:function fromJSON(json){this.arcLengthDivisions=json.arcLengthDivisions;return this;}});function EllipseCurve(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation){Curve.call(this);this.type='EllipseCurve';this.aX=aX||0;this.aY=aY||0;this.xRadius=xRadius||1;this.yRadius=yRadius||1;this.aStartAngle=aStartAngle||0;this.aEndAngle=aEndAngle||2*Math.PI;this.aClockwise=aClockwise||false;this.aRotation=aRotation||0;}EllipseCurve.prototype=Object.create(Curve.prototype);EllipseCurve.prototype.constructor=EllipseCurve;EllipseCurve.prototype.isEllipseCurve=true;EllipseCurve.prototype.getPoint=function(t,optionalTarget){var point=optionalTarget||new Vector2();var twoPi=Math.PI*2;var deltaAngle=this.aEndAngle-this.aStartAngle;var samePoints=Math.abs(deltaAngle)twoPi){deltaAngle-=twoPi;}if(deltaAngle0?0:(Math.floor(Math.abs(intPoint)/l)+1)*l;}else if(weight===0&&intPoint===l-1){intPoint=l-2;weight=1;}var p0,p3;// 4 points (p1 & p2 defined below) if(this.closed||intPoint>0){p0=points[(intPoint-1)%l];}else{// extrapolate first point tmp.subVectors(points[0],points[1]).add(points[0]);p0=tmp;}var p1=points[intPoint%l];var p2=points[(intPoint+1)%l];if(this.closed||intPoint+2points.length-2?points.length-1:intPoint+1];var p3=points[intPoint>points.length-3?points.length-1:intPoint+2];point.set(CatmullRom(weight,p0.x,p1.x,p2.x,p3.x),CatmullRom(weight,p0.y,p1.y,p2.y,p3.y));return point;};SplineCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.points=[];for(var _i252=0,l=source.points.length;_i252=d){var diff=curveLengths[i]-d;var curve=this.curves[i];var segmentLength=curve.getLength();var u=segmentLength===0?0:1-diff/segmentLength;return curve.getPointAt(u);}i++;}return null;// loop where sum != 0, sum > d , sum+1 1&&!points[points.length-1].equals(points[0])){points.push(points[0]);}return points;},copy:function copy(source){Curve.prototype.copy.call(this,source);this.curves=[];for(var _i258=0,l=source.curves.length;_i2580){// if a previous curve is present, attempt to join var firstPoint=curve.getPoint(0);if(!firstPoint.equals(this.currentPoint)){this.lineTo(firstPoint.x,firstPoint.y);}}this.curves.push(curve);var lastPoint=curve.getPoint(1);this.currentPoint.copy(lastPoint);return this;},copy:function copy(source){CurvePath.prototype.copy.call(this,source);this.currentPoint.copy(source.currentPoint);return this;},toJSON:function toJSON(){var data=CurvePath.prototype.toJSON.call(this);data.currentPoint=this.currentPoint.toArray();return data;},fromJSON:function fromJSON(json){CurvePath.prototype.fromJSON.call(this,json);this.currentPoint.fromArray(json.currentPoint);return this;}});function Shape(points){Path.call(this,points);this.uuid=MathUtils.generateUUID();this.type='Shape';this.holes=[];}Shape.prototype=Object.assign(Object.create(Path.prototype),{constructor:Shape,getPointsHoles:function getPointsHoles(divisions){var holesPts=[];for(var _i262=0,l=this.holes.length;_i2620?true:false;}else{material.vertexColors=json.vertexColors;}}// Shader Material if(json.uniforms!==undefined){for(var name in json.uniforms){var uniform=json.uniforms[name];material.uniforms[name]={};switch(uniform.type){case't':material.uniforms[name].value=getTexture(uniform.value);break;case'c':material.uniforms[name].value=new Color().setHex(uniform.value);break;case'v2':material.uniforms[name].value=new Vector2().fromArray(uniform.value);break;case'v3':material.uniforms[name].value=new Vector3().fromArray(uniform.value);break;case'v4':material.uniforms[name].value=new Vector4().fromArray(uniform.value);break;case'm3':material.uniforms[name].value=new Matrix3().fromArray(uniform.value);break;case'm4':material.uniforms[name].value=new Matrix4().fromArray(uniform.value);break;default:material.uniforms[name].value=uniform.value;}}}if(json.defines!==undefined)material.defines=json.defines;if(json.vertexShader!==undefined)material.vertexShader=json.vertexShader;if(json.fragmentShader!==undefined)material.fragmentShader=json.fragmentShader;if(json.extensions!==undefined){for(var key in json.extensions){material.extensions[key]=json.extensions[key];}}// Deprecated if(json.shading!==undefined)material.flatShading=json.shading===1;// THREE.FlatShading // for PointsMaterial if(json.size!==undefined)material.size=json.size;if(json.sizeAttenuation!==undefined)material.sizeAttenuation=json.sizeAttenuation;// maps if(json.map!==undefined)material.map=getTexture(json.map);if(json.matcap!==undefined)material.matcap=getTexture(json.matcap);if(json.alphaMap!==undefined)material.alphaMap=getTexture(json.alphaMap);if(json.bumpMap!==undefined)material.bumpMap=getTexture(json.bumpMap);if(json.bumpScale!==undefined)material.bumpScale=json.bumpScale;if(json.normalMap!==undefined)material.normalMap=getTexture(json.normalMap);if(json.normalMapType!==undefined)material.normalMapType=json.normalMapType;if(json.normalScale!==undefined){var normalScale=json.normalScale;if(Array.isArray(normalScale)===false){// Blender exporter used to export a scalar. See #7459 normalScale=[normalScale,normalScale];}material.normalScale=new Vector2().fromArray(normalScale);}if(json.displacementMap!==undefined)material.displacementMap=getTexture(json.displacementMap);if(json.displacementScale!==undefined)material.displacementScale=json.displacementScale;if(json.displacementBias!==undefined)material.displacementBias=json.displacementBias;if(json.roughnessMap!==undefined)material.roughnessMap=getTexture(json.roughnessMap);if(json.metalnessMap!==undefined)material.metalnessMap=getTexture(json.metalnessMap);if(json.emissiveMap!==undefined)material.emissiveMap=getTexture(json.emissiveMap);if(json.emissiveIntensity!==undefined)material.emissiveIntensity=json.emissiveIntensity;if(json.specularMap!==undefined)material.specularMap=getTexture(json.specularMap);if(json.envMap!==undefined)material.envMap=getTexture(json.envMap);if(json.envMapIntensity!==undefined)material.envMapIntensity=json.envMapIntensity;if(json.reflectivity!==undefined)material.reflectivity=json.reflectivity;if(json.refractionRatio!==undefined)material.refractionRatio=json.refractionRatio;if(json.lightMap!==undefined)material.lightMap=getTexture(json.lightMap);if(json.lightMapIntensity!==undefined)material.lightMapIntensity=json.lightMapIntensity;if(json.aoMap!==undefined)material.aoMap=getTexture(json.aoMap);if(json.aoMapIntensity!==undefined)material.aoMapIntensity=json.aoMapIntensity;if(json.gradientMap!==undefined)material.gradientMap=getTexture(json.gradientMap);if(json.clearcoatMap!==undefined)material.clearcoatMap=getTexture(json.clearcoatMap);if(json.clearcoatRoughnessMap!==undefined)material.clearcoatRoughnessMap=getTexture(json.clearcoatRoughnessMap);if(json.clearcoatNormalMap!==undefined)material.clearcoatNormalMap=getTexture(json.clearcoatNormalMap);if(json.clearcoatNormalScale!==undefined)material.clearcoatNormalScale=new Vector2().fromArray(json.clearcoatNormalScale);if(json.transmission!==undefined)material.transmission=json.transmission;if(json.transmissionMap!==undefined)material.transmissionMap=getTexture(json.transmissionMap);return material;},setTextures:function setTextures(value){this.textures=value;return this;}});var LoaderUtils={decodeText:function decodeText(array){if(typeof TextDecoder!=='undefined'){return new TextDecoder().decode(array);}// Avoid the String.fromCharCode.apply(null, array) shortcut, which // throws a "maximum call stack size exceeded" error for large arrays. var s='';for(var _i276=0,il=array.length;_i276 immediate success or // toggling of inside/outside at every single! intersection point of an edge // with the horizontal line through inPt, left of inPt // not counting lowerY endpoints of edges and whole edges on that line var inside=false;for(var p=polyLen-1,q=0;qNumber.EPSILON){// not parallel if(edgeDy<0){edgeLowPt=inPolygon[q];edgeDx=-edgeDx;edgeHighPt=inPolygon[p];edgeDy=-edgeDy;}if(inPt.yedgeHighPt.y)continue;if(inPt.y===edgeLowPt.y){if(inPt.x===edgeLowPt.x)return true;// inPt is on contour ? // continue; // no intersection or edgeLowPt => doesn't count !!! }else{var perpEdge=edgeDy*(inPt.x-edgeLowPt.x)-edgeDx*(inPt.y-edgeLowPt.y);if(perpEdge===0)return true;// inPt is on contour ? if(perpEdge<0)continue;inside=!inside;// true intersection left of inPt }}else{// parallel or collinear if(inPt.y!==edgeLowPt.y)continue;// parallel // edge lies on the same horizontal line as inPt if(edgeHighPt.x<=inPt.x&&inPt.x<=edgeLowPt.x||edgeLowPt.x<=inPt.x&&inPt.x<=edgeHighPt.x)return true;// inPt: Point on contour ! // continue; }}return inside;}var isClockWise=ShapeUtils.isClockWise;var subPaths=this.subPaths;if(subPaths.length===0)return[];if(noHoles===true)return toShapesNoHoles(subPaths);var solid,tmpPath,tmpShape;var shapes=[];if(subPaths.length===1){tmpPath=subPaths[0];tmpShape=new Shape();tmpShape.curves=tmpPath.curves;shapes.push(tmpShape);return shapes;}var holesFirst=!isClockWise(subPaths[0].getPoints());holesFirst=isCCW?!holesFirst:holesFirst;// console.log("Holes first", holesFirst); var betterShapeHoles=[];var newShapes=[];var newShapeHoles=[];var mainIdx=0;var tmpPoints;newShapes[mainIdx]=undefined;newShapeHoles[mainIdx]=[];for(var _i280=0,l=subPaths.length;_i280 probably all Shapes with wrong orientation if(!newShapes[0])return toShapesNoHoles(subPaths);if(newShapes.length>1){var ambiguous=false;var toChange=[];for(var sIdx=0,sLen=newShapes.length;sIdx0){// console.log("to change: ", toChange); if(!ambiguous)newShapeHoles=betterShapeHoles;}}var tmpHoles;for(var _i281=0,il=newShapes.length;_i2810){this.source.connect(this.filters[0]);for(var _i284=1,l=this.filters.length;_i2840){this.source.disconnect(this.filters[0]);for(var _i285=1,l=this.filters.length;_i285' accumulate:function accumulate(accuIndex,weight){// note: happily accumulating nothing when weight = 0, the caller knows // the weight and shouldn't have made the call in the first place var buffer=this.buffer,stride=this.valueSize,offset=accuIndex*stride+stride;var currentWeight=this.cumulativeWeight;if(currentWeight===0){// accuN := incoming * weight for(var _i286=0;_i286!==stride;++_i286){buffer[offset+_i286]=buffer[_i286];}currentWeight=weight;}else{// accuN := accuN + incoming * weight currentWeight+=weight;var mix=weight/currentWeight;this._mixBufferRegion(buffer,offset,0,mix,stride);}this.cumulativeWeight=currentWeight;},// accumulate data in the 'incoming' region into 'add' accumulateAdditive:function accumulateAdditive(weight){var buffer=this.buffer,stride=this.valueSize,offset=stride*this._addIndex;if(this.cumulativeWeightAdditive===0){// add = identity this._setIdentity();}// add := add + incoming * weight this._mixBufferRegionAdditive(buffer,offset,0,weight,stride);this.cumulativeWeightAdditive+=weight;},// apply the state of 'accu' to the binding when accus differ apply:function apply(accuIndex){var stride=this.valueSize,buffer=this.buffer,offset=accuIndex*stride+stride,weight=this.cumulativeWeight,weightAdditive=this.cumulativeWeightAdditive,binding=this.binding;this.cumulativeWeight=0;this.cumulativeWeightAdditive=0;if(weight<1){// accuN := accuN + original * ( 1 - cumulativeWeight ) var originalValueOffset=stride*this._origIndex;this._mixBufferRegion(buffer,offset,originalValueOffset,1-weight,stride);}if(weightAdditive>0){// accuN := accuN + additive accuN this._mixBufferRegionAdditive(buffer,offset,this._addIndex*stride,1,stride);}for(var _i287=stride,e=stride+stride;_i287!==e;++_i287){if(buffer[_i287]!==buffer[_i287+stride]){// value has changed -> update scene graph binding.setValue(buffer,offset);break;}}},// remember the state of the bound property and copy it to both accus saveOriginalState:function saveOriginalState(){var binding=this.binding;var buffer=this.buffer,stride=this.valueSize,originalValueOffset=stride*this._origIndex;binding.getValue(buffer,originalValueOffset);// accu[0..1] := orig -- initially detect changes against the original for(var _i288=stride,e=originalValueOffset;_i288!==e;++_i288){buffer[_i288]=buffer[originalValueOffset+_i288%stride];}// Add to identity for additive this._setIdentity();this.cumulativeWeight=0;this.cumulativeWeightAdditive=0;},// apply the state previously taken via 'saveOriginalState' to the binding restoreOriginalState:function restoreOriginalState(){var originalValueOffset=this.valueSize*3;this.binding.setValue(this.buffer,originalValueOffset);},_setAdditiveIdentityNumeric:function _setAdditiveIdentityNumeric(){var startIndex=this._addIndex*this.valueSize;var endIndex=startIndex+this.valueSize;for(var _i289=startIndex;_i289=0.5){for(var _i291=0;_i291!==stride;++_i291){buffer[dstOffset+_i291]=buffer[srcOffset+_i291];}}},_slerp:function _slerp(buffer,dstOffset,srcOffset,t){Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,srcOffset,t);},_slerpAdditive:function _slerpAdditive(buffer,dstOffset,srcOffset,t,stride){var workOffset=this._workIndex*stride;// Store result in intermediate buffer offset Quaternion.multiplyQuaternionsFlat(buffer,workOffset,buffer,dstOffset,buffer,srcOffset);// Slerp to the intermediate result Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,workOffset,t);},_lerp:function _lerp(buffer,dstOffset,srcOffset,t,stride){var s=1-t;for(var _i292=0;_i292!==stride;++_i292){var j=dstOffset+_i292;buffer[j]=buffer[j]*s+buffer[srcOffset+_i292]*t;}},_lerpAdditive:function _lerpAdditive(buffer,dstOffset,srcOffset,t,stride){for(var _i293=0;_i293!==stride;++_i293){var j=dstOffset+_i293;buffer[j]=buffer[j]+buffer[srcOffset+_i293]*t;}}});// Characters [].:/ are reserved for track binding syntax. var _RESERVED_CHARS_RE='\\[\\]\\.:\\/';var _reservedRe=new RegExp('['+_RESERVED_CHARS_RE+']','g');// Attempts to allow node names from any language. ES5's `\w` regexp matches // only latin characters, and the unicode \p{L} is not yet supported. So // instead, we exclude reserved characters and match everything else. var _wordChar='[^'+_RESERVED_CHARS_RE+']';var _wordCharOrDot='[^'+_RESERVED_CHARS_RE.replace('\\.','')+']';// Parent directories, delimited by '/' or ':'. Currently unused, but must // be matched to parse the rest of the track name. var _directoryRe=/((?:WC+[\/:])*)/.source.replace('WC',_wordChar);// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. var _nodeRe=/(WCOD+)?/.source.replace('WCOD',_wordCharOrDot);// Object on target node, and accessor. May not contain reserved // characters. Accessor may contain any character except closing bracket. var _objectRe=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC',_wordChar);// Property and accessor. May not contain reserved characters. Accessor may // contain any non-bracket characters. var _propertyRe=/\.(WC+)(?:\[(.+)\])?/.source.replace('WC',_wordChar);var _trackRe=new RegExp(''+'^'+_directoryRe+_nodeRe+_objectRe+_propertyRe+'$');var _supportedObjectNames=['material','materials','bones'];function Composite(targetGroup,path,optionalParsedPath){var parsedPath=optionalParsedPath||PropertyBinding.parseTrackName(path);this._targetGroup=targetGroup;this._bindings=targetGroup.subscribe_(path,parsedPath);}Object.assign(Composite.prototype,{getValue:function getValue(array,offset){this.bind();// bind all binding var firstValidIndex=this._targetGroup.nCachedObjects_,binding=this._bindings[firstValidIndex];// and only call .getValue on the first if(binding!==undefined)binding.getValue(array,offset);},setValue:function setValue(array,offset){var bindings=this._bindings;for(var _i294=this._targetGroup.nCachedObjects_,n=bindings.length;_i294!==n;++_i294){bindings[_i294].setValue(array,offset);}},bind:function bind(){var bindings=this._bindings;for(var _i295=this._targetGroup.nCachedObjects_,n=bindings.length;_i295!==n;++_i295){bindings[_i295].bind();}},unbind:function unbind(){var bindings=this._bindings;for(var _i296=this._targetGroup.nCachedObjects_,n=bindings.length;_i296!==n;++_i296){bindings[_i296].unbind();}}});function PropertyBinding(rootNode,path,parsedPath){this.path=path;this.parsedPath=parsedPath||PropertyBinding.parseTrackName(path);this.node=PropertyBinding.findNode(rootNode,this.parsedPath.nodeName)||rootNode;this.rootNode=rootNode;}Object.assign(PropertyBinding,{Composite:Composite,create:function create(root,path,parsedPath){if(!(root&&root.isAnimationObjectGroup)){return new PropertyBinding(root,path,parsedPath);}else{return new PropertyBinding.Composite(root,path,parsedPath);}},/** * Replaces spaces with underscores and removes unsupported characters from * node names, to ensure compatibility with parseTrackName(). * * @param {string} name Node name to be sanitized. * @return {string} */sanitizeNodeName:function sanitizeNodeName(name){return name.replace(/\s/g,'_').replace(_reservedRe,'');},parseTrackName:function parseTrackName(trackName){var matches=_trackRe.exec(trackName);if(!matches){throw new Error('PropertyBinding: Cannot parse trackName: '+trackName);}var results={// directoryName: matches[ 1 ], // (tschw) currently unused nodeName:matches[2],objectName:matches[3],objectIndex:matches[4],propertyName:matches[5],// required propertyIndex:matches[6]};var lastDot=results.nodeName&&results.nodeName.lastIndexOf('.');if(lastDot!==undefined&&lastDot!==-1){var objectName=results.nodeName.substring(lastDot+1);// Object names must be checked against an allowlist. Otherwise, there // is no way to parse 'foo.bar.baz': 'baz' must be a property, but // 'bar' could be the objectName, or part of a nodeName (which can // include '.' characters). if(_supportedObjectNames.indexOf(objectName)!==-1){results.nodeName=results.nodeName.substring(0,lastDot);results.objectName=objectName;}}if(results.propertyName===null||results.propertyName.length===0){throw new Error('PropertyBinding: can not parse propertyName from trackName: '+trackName);}return results;},findNode:function findNode(root,nodeName){if(!nodeName||nodeName===""||nodeName==="."||nodeName===-1||nodeName===root.name||nodeName===root.uuid){return root;}// search into skeleton bones. if(root.skeleton){var bone=root.skeleton.getBoneByName(nodeName);if(bone!==undefined){return bone;}}// search into node subtree. if(root.children){var searchNodeSubtree=function searchNodeSubtree(children){for(var _i297=0;_i297 this._bindingsIndicesByPath={};// inside: indices in these arrays var scope=this;this.stats={objects:{get total(){return scope._objects.length;},get inUse(){return this.total-scope.nCachedObjects_;}},get bindingsPerObject(){return scope._bindings.length;}};}Object.assign(AnimationObjectGroup.prototype,{isAnimationObjectGroup:true,add:function add(){var objects=this._objects,indicesByUUID=this._indicesByUUID,paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,nBindings=bindings.length;var knownObject=undefined,nObjects=objects.length,nCachedObjects=this.nCachedObjects_;for(var _i304=0,n=arguments.length;_i304!==n;++_i304){var object=arguments[_i304],uuid=object.uuid;var index=indicesByUUID[uuid];if(index===undefined){// unknown object -> add it to the ACTIVE region index=nObjects++;indicesByUUID[uuid]=index;objects.push(object);// accounting is done, now do the same for all bindings for(var j=0,m=nBindings;j!==m;++j){bindings[j].push(new PropertyBinding(object,paths[j],parsedPaths[j]));}}else if(index=nCachedObjects){// move existing object into the CACHED region var lastCachedIndex=nCachedObjects++,firstActiveObject=objects[lastCachedIndex];indicesByUUID[firstActiveObject.uuid]=index;objects[index]=firstActiveObject;indicesByUUID[uuid]=lastCachedIndex;objects[lastCachedIndex]=object;// accounting is done, now do the same for all bindings for(var j=0,m=nBindings;j!==m;++j){var bindingsForPath=bindings[j],firstActive=bindingsForPath[lastCachedIndex],binding=bindingsForPath[index];bindingsForPath[index]=firstActive;bindingsForPath[lastCachedIndex]=binding;}}}// for arguments this.nCachedObjects_=nCachedObjects;},// remove & forget uncache:function uncache(){var objects=this._objects,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;var nCachedObjects=this.nCachedObjects_,nObjects=objects.length;for(var _i306=0,n=arguments.length;_i306!==n;++_i306){var object=arguments[_i306],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==undefined){delete indicesByUUID[uuid];if(index zero effective time scale this.enabled=true;// false -> zero effective weight this.clampWhenFinished=false;// keep feeding the last frame? this.zeroSlopeAtStart=true;// for smooth interpolation w/o separate this.zeroSlopeAtEnd=true;// clips for start, loop and end }// State & Scheduling _createClass(AnimationAction,[{key:"play",value:function play(){this._mixer._activateAction(this);return this;}},{key:"stop",value:function stop(){this._mixer._deactivateAction(this);return this.reset();}},{key:"reset",value:function reset(){this.paused=false;this.enabled=true;this.time=0;// restart clip this._loopCount=-1;// forget previous loops this._startTime=null;// forget scheduling return this.stopFading().stopWarping();}},{key:"isRunning",value:function isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this);}// return true when play has been called },{key:"isScheduled",value:function isScheduled(){return this._mixer._isActiveAction(this);}},{key:"startAt",value:function startAt(time){this._startTime=time;return this;}},{key:"setLoop",value:function setLoop(mode,repetitions){this.loop=mode;this.repetitions=repetitions;return this;}// Weight // set the weight stopping any scheduled fading // although .enabled = false yields an effective weight of zero, this // method does *not* change .enabled, because it would be confusing },{key:"setEffectiveWeight",value:function setEffectiveWeight(weight){this.weight=weight;// note: same logic as when updated at runtime this._effectiveWeight=this.enabled?weight:0;return this.stopFading();}// return the weight considering fading and .enabled },{key:"getEffectiveWeight",value:function getEffectiveWeight(){return this._effectiveWeight;}},{key:"fadeIn",value:function fadeIn(duration){return this._scheduleFading(duration,0,1);}},{key:"fadeOut",value:function fadeOut(duration){return this._scheduleFading(duration,1,0);}},{key:"crossFadeFrom",value:function crossFadeFrom(fadeOutAction,duration,warp){fadeOutAction.fadeOut(duration);this.fadeIn(duration);if(warp){var fadeInDuration=this._clip.duration,fadeOutDuration=fadeOutAction._clip.duration,startEndRatio=fadeOutDuration/fadeInDuration,endStartRatio=fadeInDuration/fadeOutDuration;fadeOutAction.warp(1.0,startEndRatio,duration);this.warp(endStartRatio,1.0,duration);}return this;}},{key:"crossFadeTo",value:function crossFadeTo(fadeInAction,duration,warp){return fadeInAction.crossFadeFrom(this,duration,warp);}},{key:"stopFading",value:function stopFading(){var weightInterpolant=this._weightInterpolant;if(weightInterpolant!==null){this._weightInterpolant=null;this._mixer._takeBackControlInterpolant(weightInterpolant);}return this;}// Time Scale Control // set the time scale stopping any scheduled warping // although .paused = true yields an effective time scale of zero, this // method does *not* change .paused, because it would be confusing },{key:"setEffectiveTimeScale",value:function setEffectiveTimeScale(timeScale){this.timeScale=timeScale;this._effectiveTimeScale=this.paused?0:timeScale;return this.stopWarping();}// return the time scale considering warping and .paused },{key:"getEffectiveTimeScale",value:function getEffectiveTimeScale(){return this._effectiveTimeScale;}},{key:"setDuration",value:function setDuration(duration){this.timeScale=this._clip.duration/duration;return this.stopWarping();}},{key:"syncWith",value:function syncWith(action){this.time=action.time;this.timeScale=action.timeScale;return this.stopWarping();}},{key:"halt",value:function halt(duration){return this.warp(this._effectiveTimeScale,0,duration);}},{key:"warp",value:function warp(startTimeScale,endTimeScale,duration){var mixer=this._mixer,now=mixer.time,timeScale=this.timeScale;var interpolant=this._timeScaleInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._timeScaleInterpolant=interpolant;}var times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now;times[1]=now+duration;values[0]=startTimeScale/timeScale;values[1]=endTimeScale/timeScale;return this;}},{key:"stopWarping",value:function stopWarping(){var timeScaleInterpolant=this._timeScaleInterpolant;if(timeScaleInterpolant!==null){this._timeScaleInterpolant=null;this._mixer._takeBackControlInterpolant(timeScaleInterpolant);}return this;}// Object Accessors },{key:"getMixer",value:function getMixer(){return this._mixer;}},{key:"getClip",value:function getClip(){return this._clip;}},{key:"getRoot",value:function getRoot(){return this._localRoot||this._mixer._root;}// Interna },{key:"_update",value:function _update(time,deltaTime,timeDirection,accuIndex){// called by the mixer if(!this.enabled){// call ._updateWeight() to update ._effectiveWeight this._updateWeight(time);return;}var startTime=this._startTime;if(startTime!==null){// check for scheduled start of action var timeRunning=(time-startTime)*timeDirection;if(timeRunning<0||timeDirection===0){return;// yet to come / don't decide when delta = 0 }// start this._startTime=null;// unschedule deltaTime=timeDirection*timeRunning;}// apply time scale and advance time deltaTime*=this._updateTimeScale(time);var clipTime=this._updateTime(deltaTime);// note: _updateTime may disable the action resulting in // an effective weight of 0 var weight=this._updateWeight(time);if(weight>0){var _interpolants=this._interpolants;var propertyMixers=this._propertyBindings;switch(this.blendMode){case AdditiveAnimationBlendMode:for(var j=0,m=_interpolants.length;j!==m;++j){_interpolants[j].evaluate(clipTime);propertyMixers[j].accumulateAdditive(weight);}break;case NormalAnimationBlendMode:default:for(var _j19=0,_m5=_interpolants.length;_j19!==_m5;++_j19){_interpolants[_j19].evaluate(clipTime);propertyMixers[_j19].accumulate(accuIndex,weight);}}}}},{key:"_updateWeight",value:function _updateWeight(time){var weight=0;if(this.enabled){weight=this.weight;var interpolant=this._weightInterpolant;if(interpolant!==null){var interpolantValue=interpolant.evaluate(time)[0];weight*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopFading();if(interpolantValue===0){// faded out, disable this.enabled=false;}}}}this._effectiveWeight=weight;return weight;}},{key:"_updateTimeScale",value:function _updateTimeScale(time){var timeScale=0;if(!this.paused){timeScale=this.timeScale;var interpolant=this._timeScaleInterpolant;if(interpolant!==null){var interpolantValue=interpolant.evaluate(time)[0];timeScale*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopWarping();if(timeScale===0){// motion has halted, pause this.paused=true;}else{// warp done - apply final time scale this.timeScale=timeScale;}}}}this._effectiveTimeScale=timeScale;return timeScale;}},{key:"_updateTime",value:function _updateTime(deltaTime){var duration=this._clip.duration;var loop=this.loop;var time=this.time+deltaTime;var loopCount=this._loopCount;var pingPong=loop===LoopPingPong;if(deltaTime===0){if(loopCount===-1)return time;return pingPong&&(loopCount&1)===1?duration-time:time;}if(loop===LoopOnce){if(loopCount===-1){// just started this._loopCount=0;this._setEndings(true,true,false);}handle_stop:{if(time>=duration){time=duration;}else if(time<0){time=0;}else{this.time=time;break handle_stop;}if(this.clampWhenFinished)this.paused=true;else this.enabled=false;this.time=time;this._mixer.dispatchEvent({type:'finished',action:this,direction:deltaTime<0?-1:1});}}else{// repetitive Repeat or PingPong if(loopCount===-1){// just started if(deltaTime>=0){loopCount=0;this._setEndings(true,this.repetitions===0,pingPong);}else{// when looping in reverse direction, the initial // transition through zero counts as a repetition, // so leave loopCount at -1 this._setEndings(this.repetitions===0,true,pingPong);}}if(time>=duration||time<0){// wrap around var loopDelta=Math.floor(time/duration);// signed time-=duration*loopDelta;loopCount+=Math.abs(loopDelta);var pending=this.repetitions-loopCount;if(pending<=0){// have to stop (switch state, clamp time, fire event) if(this.clampWhenFinished)this.paused=true;else this.enabled=false;time=deltaTime>0?duration:0;this.time=time;this._mixer.dispatchEvent({type:'finished',action:this,direction:deltaTime>0?1:-1});}else{// keep running if(pending===1){// entering the last round var atStart=deltaTime<0;this._setEndings(atStart,!atStart,pingPong);}else{this._setEndings(false,false,pingPong);}this._loopCount=loopCount;this.time=time;this._mixer.dispatchEvent({type:'loop',action:this,loopDelta:loopDelta});}}else{this.time=time;}if(pingPong&&(loopCount&1)===1){// invert time for the "pong round" return duration-time;}}return time;}},{key:"_setEndings",value:function _setEndings(atStart,atEnd,pingPong){var settings=this._interpolantSettings;if(pingPong){settings.endingStart=ZeroSlopeEnding;settings.endingEnd=ZeroSlopeEnding;}else{// assuming for LoopOnce atStart == atEnd == true if(atStart){settings.endingStart=this.zeroSlopeAtStart?ZeroSlopeEnding:ZeroCurvatureEnding;}else{settings.endingStart=WrapAroundEnding;}if(atEnd){settings.endingEnd=this.zeroSlopeAtEnd?ZeroSlopeEnding:ZeroCurvatureEnding;}else{settings.endingEnd=WrapAroundEnding;}}}},{key:"_scheduleFading",value:function _scheduleFading(duration,weightNow,weightThen){var mixer=this._mixer,now=mixer.time;var interpolant=this._weightInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._weightInterpolant=interpolant;}var times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now;values[0]=weightNow;times[1]=now+duration;values[1]=weightThen;return this;}}]);return AnimationAction;}();function AnimationMixer(root){this._root=root;this._initMemoryManager();this._accuIndex=0;this.time=0;this.timeScale=1.0;}AnimationMixer.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:AnimationMixer,_bindAction:function _bindAction(action,prototypeAction){var root=action._localRoot||this._root,tracks=action._clip.tracks,nTracks=tracks.length,bindings=action._propertyBindings,interpolants=action._interpolants,rootUuid=root.uuid,bindingsByRoot=this._bindingsByRootAndName;var bindingsByName=bindingsByRoot[rootUuid];if(bindingsByName===undefined){bindingsByName={};bindingsByRoot[rootUuid]=bindingsByName;}for(var _i309=0;_i309!==nTracks;++_i309){var track=tracks[_i309],trackName=track.name;var binding=bindingsByName[trackName];if(binding!==undefined){bindings[_i309]=binding;}else{binding=bindings[_i309];if(binding!==undefined){// existing binding, make sure the cache knows if(binding._cacheIndex===null){++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName);}continue;}var path=prototypeAction&&prototypeAction._propertyBindings[_i309].binding.parsedPath;binding=new PropertyMixer(PropertyBinding.create(root,trackName,path),track.ValueTypeName,track.getValueSize());++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName);bindings[_i309]=binding;}interpolants[_i309].resultBuffer=binding.buffer;}},_activateAction:function _activateAction(action){if(!this._isActiveAction(action)){if(action._cacheIndex===null){// this action has been forgotten by the cache, but the user // appears to be still using it -> rebind var rootUuid=(action._localRoot||this._root).uuid,clipUuid=action._clip.uuid,actionsForClip=this._actionsByClip[clipUuid];this._bindAction(action,actionsForClip&&actionsForClip.knownActions[0]);this._addInactiveAction(action,clipUuid,rootUuid);}var bindings=action._propertyBindings;// increment reference counts / sort out state for(var _i310=0,n=bindings.length;_i310!==n;++_i310){var binding=bindings[_i310];if(binding.useCount++===0){this._lendBinding(binding);binding.saveOriginalState();}}this._lendAction(action);}},_deactivateAction:function _deactivateAction(action){if(this._isActiveAction(action)){var bindings=action._propertyBindings;// decrement reference counts / sort out state for(var _i311=0,n=bindings.length;_i311!==n;++_i311){var binding=bindings[_i311];if(--binding.useCount===0){binding.restoreOriginalState();this._takeBackBinding(binding);}}this._takeBackAction(action);}},// Memory manager _initMemoryManager:function _initMemoryManager(){this._actions=[];// 'nActiveActions' followed by inactive ones this._nActiveActions=0;this._actionsByClip={};// inside: // { // knownActions: Array< AnimationAction > - used as prototypes // actionByRoot: AnimationAction - lookup // } this._bindings=[];// 'nActiveBindings' followed by inactive ones this._nActiveBindings=0;this._bindingsByRootAndName={};// inside: Map< name, PropertyMixer > this._controlInterpolants=[];// same game as above this._nActiveControlInterpolants=0;var scope=this;this.stats={actions:{get total(){return scope._actions.length;},get inUse(){return scope._nActiveActions;}},bindings:{get total(){return scope._bindings.length;},get inUse(){return scope._nActiveBindings;}},controlInterpolants:{get total(){return scope._controlInterpolants.length;},get inUse(){return scope._nActiveControlInterpolants;}}};},// Memory management for AnimationAction objects _isActiveAction:function _isActiveAction(action){var index=action._cacheIndex;return index!==null&&index| inactive actions ] // s a // <-swap-> // a s var actions=this._actions,prevIndex=action._cacheIndex,lastActiveIndex=this._nActiveActions++,firstInactiveAction=actions[lastActiveIndex];action._cacheIndex=lastActiveIndex;actions[lastActiveIndex]=action;firstInactiveAction._cacheIndex=prevIndex;actions[prevIndex]=firstInactiveAction;},_takeBackAction:function _takeBackAction(action){// [ active actions | inactive actions ] // [ active actions |< inactive actions ] // a s // <-swap-> // s a var actions=this._actions,prevIndex=action._cacheIndex,firstInactiveIndex=--this._nActiveActions,lastActiveAction=actions[firstInactiveIndex];action._cacheIndex=firstInactiveIndex;actions[firstInactiveIndex]=action;lastActiveAction._cacheIndex=prevIndex;actions[prevIndex]=lastActiveAction;},// Memory management for PropertyMixer objects _addInactiveBinding:function _addInactiveBinding(binding,rootUuid,trackName){var bindingsByRoot=this._bindingsByRootAndName,bindings=this._bindings;var bindingByName=bindingsByRoot[rootUuid];if(bindingByName===undefined){bindingByName={};bindingsByRoot[rootUuid]=bindingByName;}bindingByName[trackName]=binding;binding._cacheIndex=bindings.length;bindings.push(binding);},_removeInactiveBinding:function _removeInactiveBinding(binding){var bindings=this._bindings,propBinding=binding.binding,rootUuid=propBinding.rootNode.uuid,trackName=propBinding.path,bindingsByRoot=this._bindingsByRootAndName,bindingByName=bindingsByRoot[rootUuid],lastInactiveBinding=bindings[bindings.length-1],cacheIndex=binding._cacheIndex;lastInactiveBinding._cacheIndex=cacheIndex;bindings[cacheIndex]=lastInactiveBinding;bindings.pop();delete bindingByName[trackName];if(Object.keys(bindingByName).length===0){delete bindingsByRoot[rootUuid];}},_lendBinding:function _lendBinding(binding){var bindings=this._bindings,prevIndex=binding._cacheIndex,lastActiveIndex=this._nActiveBindings++,firstInactiveBinding=bindings[lastActiveIndex];binding._cacheIndex=lastActiveIndex;bindings[lastActiveIndex]=binding;firstInactiveBinding._cacheIndex=prevIndex;bindings[prevIndex]=firstInactiveBinding;},_takeBackBinding:function _takeBackBinding(binding){var bindings=this._bindings,prevIndex=binding._cacheIndex,firstInactiveIndex=--this._nActiveBindings,lastActiveBinding=bindings[firstInactiveIndex];binding._cacheIndex=firstInactiveIndex;bindings[firstInactiveIndex]=binding;lastActiveBinding._cacheIndex=prevIndex;bindings[prevIndex]=lastActiveBinding;},// Memory management of Interpolants for weight and time scale _lendControlInterpolant:function _lendControlInterpolant(){var interpolants=this._controlInterpolants,lastActiveIndex=this._nActiveControlInterpolants++;var interpolant=interpolants[lastActiveIndex];if(interpolant===undefined){interpolant=new LinearInterpolant(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer);interpolant.__cacheIndex=lastActiveIndex;interpolants[lastActiveIndex]=interpolant;}return interpolant;},_takeBackControlInterpolant:function _takeBackControlInterpolant(interpolant){var interpolants=this._controlInterpolants,prevIndex=interpolant.__cacheIndex,firstInactiveIndex=--this._nActiveControlInterpolants,lastActiveInterpolant=interpolants[firstInactiveIndex];interpolant.__cacheIndex=firstInactiveIndex;interpolants[firstInactiveIndex]=interpolant;lastActiveInterpolant.__cacheIndex=prevIndex;interpolants[prevIndex]=lastActiveInterpolant;},_controlInterpolantsResultBuffer:new Float32Array(1),// return an action for a clip optionally using a custom root target // object (this method allocates a lot of dynamic memory in case a // previously unknown clip/root combination is specified) clipAction:function clipAction(clip,optionalRoot,blendMode){var root=optionalRoot||this._root,rootUuid=root.uuid;var clipObject=typeof clip==='string'?AnimationClip.findByName(root,clip):clip;var clipUuid=clipObject!==null?clipObject.uuid:clip;var actionsForClip=this._actionsByClip[clipUuid];var prototypeAction=null;if(blendMode===undefined){if(clipObject!==null){blendMode=clipObject.blendMode;}else{blendMode=NormalAnimationBlendMode;}}if(actionsForClip!==undefined){var existingAction=actionsForClip.actionByRoot[rootUuid];if(existingAction!==undefined&&existingAction.blendMode===blendMode){return existingAction;}// we know the clip, so we don't have to parse all // the bindings again but can just copy prototypeAction=actionsForClip.knownActions[0];// also, take the clip from the prototype action if(clipObject===null)clipObject=prototypeAction._clip;}// clip must be known when specified via string if(clipObject===null)return null;// allocate all resources required to run it var newAction=new AnimationAction(this,clipObject,optionalRoot,blendMode);this._bindAction(newAction,prototypeAction);// and make the action known to the memory manager this._addInactiveAction(newAction,clipUuid,rootUuid);return newAction;},// get an existing action existingAction:function existingAction(clip,optionalRoot){var root=optionalRoot||this._root,rootUuid=root.uuid,clipObject=typeof clip==='string'?AnimationClip.findByName(root,clip):clip,clipUuid=clipObject?clipObject.uuid:clip,actionsForClip=this._actionsByClip[clipUuid];if(actionsForClip!==undefined){return actionsForClip.actionByRoot[rootUuid]||null;}return null;},// deactivates all previously scheduled actions stopAllAction:function stopAllAction(){var actions=this._actions,nActions=this._nActiveActions;for(var _i313=nActions-1;_i313>=0;--_i313){actions[_i313].stop();}return this;},// advance the time and update apply the animation update:function update(deltaTime){deltaTime*=this.timeScale;var actions=this._actions,nActions=this._nActiveActions,time=this.time+=deltaTime,timeDirection=Math.sign(deltaTime),accuIndex=this._accuIndex^=1;// run active actions for(var _i314=0;_i314!==nActions;++_i314){var action=actions[_i314];action._update(time,deltaTime,timeDirection,accuIndex);}// update scene graph var bindings=this._bindings,nBindings=this._nActiveBindings;for(var _i315=0;_i315!==nBindings;++_i315){bindings[_i315].apply(accuIndex);}return this;},// Allows you to seek to a specific time in an animation. setTime:function setTime(timeInSeconds){this.time=0;// Zero out time attribute for AnimationMixer object; for(var _i316=0;_i3160&&arguments[0]!==undefined?arguments[0]:1;var phi=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var theta=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;_classCallCheck(this,Spherical);this.radius=radius;this.phi=phi;// polar angle this.theta=theta;// azimuthal angle return this;}_createClass(Spherical,[{key:"set",value:function set(radius,phi,theta){this.radius=radius;this.phi=phi;this.theta=theta;return this;}},{key:"clone",value:function clone(){return new this.constructor().copy(this);}},{key:"copy",value:function copy(other){this.radius=other.radius;this.phi=other.phi;this.theta=other.theta;return this;}// restrict phi to be betwee EPS and PI-EPS },{key:"makeSafe",value:function makeSafe(){var EPS=0.000001;this.phi=Math.max(EPS,Math.min(Math.PI-EPS,this.phi));return this;}},{key:"setFromVector3",value:function setFromVector3(v){return this.setFromCartesianCoords(v.x,v.y,v.z);}},{key:"setFromCartesianCoords",value:function setFromCartesianCoords(x,y,z){this.radius=Math.sqrt(x*x+y*y+z*z);if(this.radius===0){this.theta=0;this.phi=0;}else{this.theta=Math.atan2(x,z);this.phi=Math.acos(MathUtils.clamp(y/this.radius,-1,1));}return this;}}]);return Spherical;}();var _vector$7=/*@__PURE__*/new Vector2();var Box2=/*#__PURE__*/function(){function Box2(min,max){_classCallCheck(this,Box2);Object.defineProperty(this,'isBox2',{value:true});this.min=min!==undefined?min:new Vector2(+Infinity,+Infinity);this.max=max!==undefined?max:new Vector2(-Infinity,-Infinity);}_createClass(Box2,[{key:"set",value:function set(min,max){this.min.copy(min);this.max.copy(max);return this;}},{key:"setFromPoints",value:function setFromPoints(points){this.makeEmpty();for(var _i320=0,il=points.length;_i320this.max.x||point.ythis.max.y?false:true;}},{key:"containsBox",value:function containsBox(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y;}},{key:"getParameter",value:function getParameter(point,target){// This can potentially have a divide by zero if the box // has a size dimension of 0. if(target===undefined){console.warn('THREE.Box2: .getParameter() target is now required');target=new Vector2();}return target.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y));}},{key:"intersectsBox",value:function intersectsBox(box){// using 4 splitting planes to rule out intersections return box.max.xthis.max.x||box.max.ythis.max.y?false:true;}},{key:"clampPoint",value:function clampPoint(point,target){if(target===undefined){console.warn('THREE.Box2: .clampPoint() target is now required');target=new Vector2();}return target.copy(point).clamp(this.min,this.max);}},{key:"distanceToPoint",value:function distanceToPoint(point){var clampedPoint=_vector$7.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();}},{key:"intersect",value:function intersect(box){this.min.max(box.min);this.max.min(box.max);return this;}},{key:"union",value:function union(box){this.min.min(box.min);this.max.max(box.max);return this;}},{key:"translate",value:function translate(offset){this.min.add(offset);this.max.add(offset);return this;}},{key:"equals",value:function equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}}]);return Box2;}();function ImmediateRenderObject(material){Object3D.call(this);this.material=material;this.render=function()/* renderCallback */{};this.hasPositions=false;this.hasNormals=false;this.hasColors=false;this.hasUvs=false;this.positionArray=null;this.normalArray=null;this.colorArray=null;this.uvArray=null;this.count=0;}ImmediateRenderObject.prototype=Object.create(Object3D.prototype);ImmediateRenderObject.prototype.constructor=ImmediateRenderObject;ImmediateRenderObject.prototype.isImmediateRenderObject=true;var _vector$9=/*@__PURE__*/new Vector3();var _boneMatrix=/*@__PURE__*/new Matrix4();var _matrixWorldInv=/*@__PURE__*/new Matrix4();var SkeletonHelper=/*#__PURE__*/function(_LineSegments){_inherits(SkeletonHelper,_LineSegments);var _super10=_createSuper(SkeletonHelper);function SkeletonHelper(object){var _this17;_classCallCheck(this,SkeletonHelper);var bones=getBoneList(object);var geometry=new BufferGeometry();var vertices=[];var colors=[];var color1=new Color(0,0,1);var color2=new Color(0,1,0);for(var _i321=0;_i3211&&arguments[1]!==undefined?arguments[1]:0;var near=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0.1;var far=arguments.length>3&&arguments[3]!==undefined?arguments[3]:100;_oldTarget=this._renderer.getRenderTarget();var cubeUVRenderTarget=this._allocateTargets();this._sceneToCubeUV(scene,near,far,cubeUVRenderTarget);if(sigma>0){this._blur(cubeUVRenderTarget,0,0,sigma);}this._applyPMREM(cubeUVRenderTarget);this._cleanup(cubeUVRenderTarget);return cubeUVRenderTarget;}/** * Generates a PMREM from an equirectangular texture, which can be either LDR * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512), * as this matches best with the 256 x 256 cubemap output. */},{key:"fromEquirectangular",value:function fromEquirectangular(equirectangular){return this._fromTexture(equirectangular);}/** * Generates a PMREM from an cubemap texture, which can be either LDR * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256, * as this matches best with the 256 x 256 cubemap output. */},{key:"fromCubemap",value:function fromCubemap(cubemap){return this._fromTexture(cubemap);}/** * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during * your texture's network fetch for increased concurrency. */},{key:"compileCubemapShader",value:function compileCubemapShader(){if(this._cubemapShader===null){this._cubemapShader=_getCubemapShader();this._compileMaterial(this._cubemapShader);}}/** * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during * your texture's network fetch for increased concurrency. */},{key:"compileEquirectangularShader",value:function compileEquirectangularShader(){if(this._equirectShader===null){this._equirectShader=_getEquirectShader();this._compileMaterial(this._equirectShader);}}/** * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on * one of them will cause any others to also become unusable. */},{key:"dispose",value:function dispose(){this._blurMaterial.dispose();if(this._cubemapShader!==null)this._cubemapShader.dispose();if(this._equirectShader!==null)this._equirectShader.dispose();for(var _i324=0;_i324<_lodPlanes.length;_i324++){_lodPlanes[_i324].dispose();}}// private interface },{key:"_cleanup",value:function _cleanup(outputTarget){this._pingPongRenderTarget.dispose();this._renderer.setRenderTarget(_oldTarget);outputTarget.scissorTest=false;_setViewport(outputTarget,0,0,outputTarget.width,outputTarget.height);}},{key:"_fromTexture",value:function _fromTexture(texture){_oldTarget=this._renderer.getRenderTarget();var cubeUVRenderTarget=this._allocateTargets(texture);this._textureToCubeUV(texture,cubeUVRenderTarget);this._applyPMREM(cubeUVRenderTarget);this._cleanup(cubeUVRenderTarget);return cubeUVRenderTarget;}},{key:"_allocateTargets",value:function _allocateTargets(texture){// warning: null texture is valid var params={magFilter:NearestFilter,minFilter:NearestFilter,generateMipmaps:false,type:UnsignedByteType,format:RGBEFormat,encoding:_isLDR(texture)?texture.encoding:RGBEEncoding,depthBuffer:false};var cubeUVRenderTarget=_createRenderTarget(params);cubeUVRenderTarget.depthBuffer=texture?false:true;this._pingPongRenderTarget=_createRenderTarget(params);return cubeUVRenderTarget;}},{key:"_compileMaterial",value:function _compileMaterial(material){var tmpMesh=new Mesh(_lodPlanes[0],material);this._renderer.compile(tmpMesh,_flatCamera);}},{key:"_sceneToCubeUV",value:function _sceneToCubeUV(scene,near,far,cubeUVRenderTarget){var fov=90;var aspect=1;var cubeCamera=new PerspectiveCamera(fov,aspect,near,far);var upSign=[1,-1,1,1,1,1];var forwardSign=[1,1,1,-1,-1,-1];var renderer=this._renderer;var outputEncoding=renderer.outputEncoding;var toneMapping=renderer.toneMapping;var clearColor=renderer.getClearColor();var clearAlpha=renderer.getClearAlpha();renderer.toneMapping=NoToneMapping;renderer.outputEncoding=LinearEncoding;var background=scene.background;if(background&&background.isColor){background.convertSRGBToLinear();// Convert linear to RGBE var maxComponent=Math.max(background.r,background.g,background.b);var fExp=Math.min(Math.max(Math.ceil(Math.log2(maxComponent)),-128.0),127.0);background=background.multiplyScalar(Math.pow(2.0,-fExp));var alpha=(fExp+128.0)/255.0;renderer.setClearColor(background,alpha);scene.background=null;}for(var _i325=0;_i325<6;_i325++){var col=_i325%3;if(col==0){cubeCamera.up.set(0,upSign[_i325],0);cubeCamera.lookAt(forwardSign[_i325],0,0);}else if(col==1){cubeCamera.up.set(0,0,upSign[_i325]);cubeCamera.lookAt(0,forwardSign[_i325],0);}else{cubeCamera.up.set(0,upSign[_i325],0);cubeCamera.lookAt(0,0,forwardSign[_i325]);}_setViewport(cubeUVRenderTarget,col*SIZE_MAX,_i325>2?SIZE_MAX:0,SIZE_MAX,SIZE_MAX);renderer.setRenderTarget(cubeUVRenderTarget);renderer.render(scene,cubeCamera);}renderer.toneMapping=toneMapping;renderer.outputEncoding=outputEncoding;renderer.setClearColor(clearColor,clearAlpha);}},{key:"_textureToCubeUV",value:function _textureToCubeUV(texture,cubeUVRenderTarget){var renderer=this._renderer;if(texture.isCubeTexture){if(this._cubemapShader==null){this._cubemapShader=_getCubemapShader();}}else{if(this._equirectShader==null){this._equirectShader=_getEquirectShader();}}var material=texture.isCubeTexture?this._cubemapShader:this._equirectShader;var mesh=new Mesh(_lodPlanes[0],material);var uniforms=material.uniforms;uniforms['envMap'].value=texture;if(!texture.isCubeTexture){uniforms['texelSize'].value.set(1.0/texture.image.width,1.0/texture.image.height);}uniforms['inputEncoding'].value=ENCODINGS[texture.encoding];uniforms['outputEncoding'].value=ENCODINGS[cubeUVRenderTarget.texture.encoding];_setViewport(cubeUVRenderTarget,0,0,3*SIZE_MAX,2*SIZE_MAX);renderer.setRenderTarget(cubeUVRenderTarget);renderer.render(mesh,_flatCamera);}},{key:"_applyPMREM",value:function _applyPMREM(cubeUVRenderTarget){var renderer=this._renderer;var autoClear=renderer.autoClear;renderer.autoClear=false;for(var _i326=1;_i326MAX_SAMPLES){console.warn("sigmaRadians, ".concat(sigmaRadians,", is too large and will clip, as it requested ").concat(samples," samples when the maximum is set to ").concat(MAX_SAMPLES));}var weights=[];var sum=0;for(var _i327=0;_i327LOD_MAX-LOD_MIN?lodOut-LOD_MAX+LOD_MIN:0);_setViewport(targetOut,x,y,3*outputSize,2*outputSize);renderer.setRenderTarget(targetOut);renderer.render(blurMesh,_flatCamera);}}]);return PMREMGenerator;}();function _isLDR(texture){if(texture===undefined||texture.type!==UnsignedByteType)return false;return texture.encoding===LinearEncoding||texture.encoding===sRGBEncoding||texture.encoding===GammaEncoding;}function _createPlanes(){var _lodPlanes=[];var _sizeLods=[];var _sigmas=[];var lod=LOD_MAX;for(var _i329=0;_i329LOD_MAX-LOD_MIN){sigma=EXTRA_LOD_SIGMA[_i329-LOD_MAX+LOD_MIN-1];}else if(_i329==0){sigma=0;}_sigmas.push(sigma);var texelSize=1.0/(sizeLod-1);var min=-texelSize/2;var max=1+texelSize/2;var uv1=[min,min,max,min,max,max,min,min,max,max,min,max];var cubeFaces=6;var _vertices5=6;var positionSize=3;var uvSize=2;var faceIndexSize=1;var position=new Float32Array(positionSize*_vertices5*cubeFaces);var uv=new Float32Array(uvSize*_vertices5*cubeFaces);var faceIndex=new Float32Array(faceIndexSize*_vertices5*cubeFaces);for(var face=0;face2?0:-1;var coordinates=[x,y,0,x+2/3,y,0,x+2/3,y+1,0,x,y,0,x+2/3,y+1,0,x,y+1,0];position.set(coordinates,positionSize*_vertices5*face);uv.set(uv1,uvSize*_vertices5*face);var fill=[face,face,face,face,face,face];faceIndex.set(fill,faceIndexSize*_vertices5*face);}var planes=new BufferGeometry();planes.setAttribute('position',new BufferAttribute(position,positionSize));planes.setAttribute('uv',new BufferAttribute(uv,uvSize));planes.setAttribute('faceIndex',new BufferAttribute(faceIndex,faceIndexSize));_lodPlanes.push(planes);if(lod>LOD_MIN){lod--;}}return{_lodPlanes:_lodPlanes,_sizeLods:_sizeLods,_sigmas:_sigmas};}function _createRenderTarget(params){var cubeUVRenderTarget=new WebGLRenderTarget(3*SIZE_MAX,3*SIZE_MAX,params);cubeUVRenderTarget.texture.mapping=CubeUVReflectionMapping;cubeUVRenderTarget.texture.name='PMREM.cubeUv';cubeUVRenderTarget.scissorTest=true;return cubeUVRenderTarget;}function _setViewport(target,x,y,width,height){target.viewport.set(x,y,width,height);target.scissor.set(x,y,width,height);}function _getBlurShader(maxSamples){var weights=new Float32Array(maxSamples);var poleAxis=new Vector3(0,1,0);var shaderMaterial=new RawShaderMaterial({name:'SphericalGaussianBlur',defines:{'n':maxSamples},uniforms:{'envMap':{value:null},'samples':{value:1},'weights':{value:weights},'latitudinal':{value:false},'dTheta':{value:0},'mipInt':{value:0},'poleAxis':{value:poleAxis},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:/* glsl */"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t".concat(_getEncodings(),"\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial;}function _getEquirectShader(){var texelSize=new Vector2(1,1);var shaderMaterial=new RawShaderMaterial({name:'EquirectangularToCubeUV',uniforms:{'envMap':{value:null},'texelSize':{value:texelSize},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:/* glsl */"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t".concat(_getEncodings(),"\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial;}function _getCubemapShader(){var shaderMaterial=new RawShaderMaterial({name:'CubemapToCubeUV',uniforms:{'envMap':{value:null},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:/* glsl */"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\t".concat(_getEncodings(),"\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial;}function _getCommonVertexShader(){return(/* glsl */"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t");}function _getEncodings(){return(/* glsl */"\n\n\t\tuniform int inputEncoding;\n\t\tuniform int outputEncoding;\n\n\t\t#include \n\n\t\tvec4 inputTexelToLinear( vec4 value ) {\n\n\t\t\tif ( inputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( inputEncoding == 1 ) {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 2 ) {\n\n\t\t\t\treturn RGBEToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 3 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 7.0 );\n\n\t\t\t} else if ( inputEncoding == 4 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 16.0 );\n\n\t\t\t} else if ( inputEncoding == 5 ) {\n\n\t\t\t\treturn RGBDToLinear( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn GammaToLinear( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 linearToOutputTexel( vec4 value ) {\n\n\t\t\tif ( outputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( outputEncoding == 1 ) {\n\n\t\t\t\treturn LinearTosRGB( value );\n\n\t\t\t} else if ( outputEncoding == 2 ) {\n\n\t\t\t\treturn LinearToRGBE( value );\n\n\t\t\t} else if ( outputEncoding == 3 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 7.0 );\n\n\t\t\t} else if ( outputEncoding == 4 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 16.0 );\n\n\t\t\t} else if ( outputEncoding == 5 ) {\n\n\t\t\t\treturn LinearToRGBD( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn LinearToGamma( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 envMapTexelToLinear( vec4 color ) {\n\n\t\t\treturn inputTexelToLinear( color );\n\n\t\t}\n\t");}// Curve.create=function(construct,getPoint){console.log('THREE.Curve.create() has been deprecated');construct.prototype=Object.create(Curve.prototype);construct.prototype.constructor=construct;construct.prototype.getPoint=getPoint;return construct;};// Object.assign(CurvePath.prototype,{createPointsGeometry:function createPointsGeometry(divisions){console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');// generate geometry from path points (for Line or Points objects) var pts=this.getPoints(divisions);return this.createGeometry(pts);},createSpacedPointsGeometry:function createSpacedPointsGeometry(divisions){console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');// generate geometry from equidistant sampling along the path var pts=this.getSpacedPoints(divisions);return this.createGeometry(pts);},createGeometry:function createGeometry(points){console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');var geometry=new Geometry();for(var _i330=0,l=points.length;_i330b._taskLoad?-1:1;});}var worker=_this21.workerPool[_this21.workerPool.length-1];worker._taskCosts[taskID]=taskCost;worker._taskLoad+=taskCost;return worker;});},_releaseTask:function _releaseTask(worker,taskID){worker._taskLoad-=worker._taskCosts[taskID];delete worker._callbacks[taskID];delete worker._taskCosts[taskID];},debug:function debug(){console.log('Task load: ',this.workerPool.map(function(worker){return worker._taskLoad;}));},dispose:function dispose(){for(var i=0;i=2.0 are supported.'));return;}var parser=new GLTFParser(json,{path:path||this.resourcePath||'',crossOrigin:this.crossOrigin,manager:this.manager,ktx2Loader:this.ktx2Loader});parser.fileLoader.setRequestHeader(this.requestHeader);for(var i=0;i=0&&plugins[extensionName]===undefined){console.warn('THREE.GLTFLoader: Unknown extension "'+extensionName+'".');}}}}parser.setExtensions(extensions);parser.setPlugins(plugins);parser.parse(onLoad,onError);}});/* GLTFREGISTRY */function GLTFRegistry(){var objects={};return{get:function get(key){return objects[key];},add:function add(key,object){objects[key]=object;},remove:function remove(key){delete objects[key];},removeAll:function removeAll(){objects={};}};}/*********************************/ /********** EXTENSIONS ***********/ /*********************************/var EXTENSIONS={KHR_BINARY_GLTF:'KHR_binary_glTF',KHR_DRACO_MESH_COMPRESSION:'KHR_draco_mesh_compression',KHR_LIGHTS_PUNCTUAL:'KHR_lights_punctual',KHR_MATERIALS_CLEARCOAT:'KHR_materials_clearcoat',KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:'KHR_materials_pbrSpecularGlossiness',KHR_MATERIALS_TRANSMISSION:'KHR_materials_transmission',KHR_MATERIALS_UNLIT:'KHR_materials_unlit',KHR_TEXTURE_BASISU:'KHR_texture_basisu',KHR_TEXTURE_TRANSFORM:'KHR_texture_transform',KHR_MESH_QUANTIZATION:'KHR_mesh_quantization',MSFT_TEXTURE_DDS:'MSFT_texture_dds'};/** * DDS Texture Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds * */function GLTFTextureDDSExtension(ddsLoader){if(!ddsLoader){throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');}this.name=EXTENSIONS.MSFT_TEXTURE_DDS;this.ddsLoader=ddsLoader;}/** * Punctual Lights Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual */function GLTFLightsExtension(parser){this.parser=parser;this.name=EXTENSIONS.KHR_LIGHTS_PUNCTUAL;// Object3D instance caches this.cache={refs:{},uses:{}};}GLTFLightsExtension.prototype._markDefs=function(){var parser=this.parser;var nodeDefs=this.parser.json.nodes||[];for(var nodeIndex=0,nodeLength=nodeDefs.length;nodeIndex',specularMapParsFragmentChunk).replace('#include ',glossinessMapParsFragmentChunk).replace('#include ',specularMapFragmentChunk).replace('#include ',glossinessMapFragmentChunk).replace('#include ',lightPhysicalFragmentChunk);};Object.defineProperties(this,{specular:{get:function get(){return uniforms.specular.value;},set:function set(v){uniforms.specular.value=v;}},specularMap:{get:function get(){return uniforms.specularMap.value;},set:function set(v){uniforms.specularMap.value=v;if(v){this.defines.USE_SPECULARMAP='';// USE_UV is set by the renderer for specular maps }else{delete this.defines.USE_SPECULARMAP;}}},glossiness:{get:function get(){return uniforms.glossiness.value;},set:function set(v){uniforms.glossiness.value=v;}},glossinessMap:{get:function get(){return uniforms.glossinessMap.value;},set:function set(v){uniforms.glossinessMap.value=v;if(v){this.defines.USE_GLOSSINESSMAP='';this.defines.USE_UV='';}else{delete this.defines.USE_GLOSSINESSMAP;delete this.defines.USE_UV;}}}});delete this.metalness;delete this.roughness;delete this.metalnessMap;delete this.roughnessMap;this.setValues(params);}GLTFMeshStandardSGMaterial.prototype=Object.create(MeshStandardMaterial.prototype);GLTFMeshStandardSGMaterial.prototype.constructor=GLTFMeshStandardSGMaterial;GLTFMeshStandardSGMaterial.prototype.copy=function(source){MeshStandardMaterial.prototype.copy.call(this,source);this.specularMap=source.specularMap;this.specular.copy(source.specular);this.glossinessMap=source.glossinessMap;this.glossiness=source.glossiness;delete this.metalness;delete this.roughness;delete this.metalnessMap;delete this.roughnessMap;return this;};function GLTFMaterialsPbrSpecularGlossinessExtension(){return{name:EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,specularGlossinessParams:['color','map','lightMap','lightMapIntensity','aoMap','aoMapIntensity','emissive','emissiveIntensity','emissiveMap','bumpMap','bumpScale','normalMap','normalMapType','displacementMap','displacementScale','displacementBias','specularMap','specular','glossinessMap','glossiness','alphaMap','envMap','envMapIntensity','refractionRatio'],getMaterialType:function getMaterialType(){return GLTFMeshStandardSGMaterial;},extendParams:function extendParams(materialParams,materialDef,parser){var pbrSpecularGlossiness=materialDef.extensions[this.name];materialParams.color=new Color(1.0,1.0,1.0);materialParams.opacity=1.0;var pending=[];if(Array.isArray(pbrSpecularGlossiness.diffuseFactor)){var array=pbrSpecularGlossiness.diffuseFactor;materialParams.color.fromArray(array);materialParams.opacity=array[3];}if(pbrSpecularGlossiness.diffuseTexture!==undefined){pending.push(parser.assignTexture(materialParams,'map',pbrSpecularGlossiness.diffuseTexture));}materialParams.emissive=new Color(0.0,0.0,0.0);materialParams.glossiness=pbrSpecularGlossiness.glossinessFactor!==undefined?pbrSpecularGlossiness.glossinessFactor:1.0;materialParams.specular=new Color(1.0,1.0,1.0);if(Array.isArray(pbrSpecularGlossiness.specularFactor)){materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);}if(pbrSpecularGlossiness.specularGlossinessTexture!==undefined){var specGlossMapDef=pbrSpecularGlossiness.specularGlossinessTexture;pending.push(parser.assignTexture(materialParams,'glossinessMap',specGlossMapDef));pending.push(parser.assignTexture(materialParams,'specularMap',specGlossMapDef));}return Promise.all(pending);},createMaterial:function createMaterial(materialParams){var material=new GLTFMeshStandardSGMaterial(materialParams);material.fog=true;material.color=materialParams.color;material.map=materialParams.map===undefined?null:materialParams.map;material.lightMap=null;material.lightMapIntensity=1.0;material.aoMap=materialParams.aoMap===undefined?null:materialParams.aoMap;material.aoMapIntensity=1.0;material.emissive=materialParams.emissive;material.emissiveIntensity=1.0;material.emissiveMap=materialParams.emissiveMap===undefined?null:materialParams.emissiveMap;material.bumpMap=materialParams.bumpMap===undefined?null:materialParams.bumpMap;material.bumpScale=1;material.normalMap=materialParams.normalMap===undefined?null:materialParams.normalMap;material.normalMapType=TangentSpaceNormalMap;if(materialParams.normalScale)material.normalScale=materialParams.normalScale;material.displacementMap=null;material.displacementScale=1;material.displacementBias=0;material.specularMap=materialParams.specularMap===undefined?null:materialParams.specularMap;material.specular=materialParams.specular;material.glossinessMap=materialParams.glossinessMap===undefined?null:materialParams.glossinessMap;material.glossiness=materialParams.glossiness;material.alphaMap=null;material.envMap=materialParams.envMap===undefined?null:materialParams.envMap;material.envMapIntensity=1.0;material.refractionRatio=0.98;return material;}};}/** * Mesh Quantization Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization */function GLTFMeshQuantizationExtension(){this.name=EXTENSIONS.KHR_MESH_QUANTIZATION;}/*********************************/ /********** INTERPOLATION ********/ /*********************************/ // Spline Interpolation // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation function GLTFCubicSplineInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer);}GLTFCubicSplineInterpolant.prototype=Object.create(Interpolant.prototype);GLTFCubicSplineInterpolant.prototype.constructor=GLTFCubicSplineInterpolant;GLTFCubicSplineInterpolant.prototype.copySampleValue_=function(index){// Copies a sample value to the result buffer. See description of glTF // CUBICSPLINE values layout in interpolate_() function below. var result=this.resultBuffer,values=this.sampleValues,valueSize=this.valueSize,offset=index*valueSize*3+valueSize;for(var i=0;i!==valueSize;i++){result[i]=values[offset+i];}return result;};GLTFCubicSplineInterpolant.prototype.beforeStart_=GLTFCubicSplineInterpolant.prototype.copySampleValue_;GLTFCubicSplineInterpolant.prototype.afterEnd_=GLTFCubicSplineInterpolant.prototype.copySampleValue_;GLTFCubicSplineInterpolant.prototype.interpolate_=function(i1,t0,t,t1){var result=this.resultBuffer;var values=this.sampleValues;var stride=this.valueSize;var stride2=stride*2;var stride3=stride*3;var td=t1-t0;var p=(t-t0)/td;var pp=p*p;var ppp=pp*p;var offset1=i1*stride3;var offset0=offset1-stride3;var s2=-2*ppp+3*pp;var s3=ppp-pp;var s0=1-s2;var s1=s3-pp+p;// Layout of keyframe output values for CUBICSPLINE animations: // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] for(var i=0;i!==stride;i++){var p0=values[offset0+i+stride];// splineVertex_k var m0=values[offset0+i+stride2]*td;// outTangent_k * (t_k+1 - t_k) var p1=values[offset1+i+stride];// splineVertex_k+1 var m1=values[offset1+i]*td;// inTangent_k+1 * (t_k+1 - t_k) result[i]=s0*p0+s1*m0+s2*p1+s3*m1;}return result;};/*********************************/ /********** INTERNALS ************/ /*********************************/ /* CONSTANTS */var WEBGL_CONSTANTS={FLOAT:5126,//FLOAT_MAT2: 35674, FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123};var WEBGL_COMPONENT_TYPES={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};var WEBGL_FILTERS={9728:NearestFilter,9729:LinearFilter,9984:NearestMipmapNearestFilter,9985:LinearMipmapNearestFilter,9986:NearestMipmapLinearFilter,9987:LinearMipmapLinearFilter};var WEBGL_WRAPPINGS={33071:ClampToEdgeWrapping,33648:MirroredRepeatWrapping,10497:RepeatWrapping};var WEBGL_TYPE_SIZES={'SCALAR':1,'VEC2':2,'VEC3':3,'VEC4':4,'MAT2':4,'MAT3':9,'MAT4':16};var ATTRIBUTES={POSITION:'position',NORMAL:'normal',TANGENT:'tangent',TEXCOORD_0:'uv',TEXCOORD_1:'uv2',COLOR_0:'color',WEIGHTS_0:'skinWeight',JOINTS_0:'skinIndex'};var PATH_PROPERTIES={scale:'scale',translation:'position',rotation:'quaternion',weights:'morphTargetInfluences'};var INTERPOLATION={CUBICSPLINE:undefined,// We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each // keyframe track will be initialized with a default interpolation type, then modified. LINEAR:InterpolateLinear,STEP:InterpolateDiscrete};var ALPHA_MODES={OPAQUE:'OPAQUE',MASK:'MASK',BLEND:'BLEND'};/* UTILITY FUNCTIONS */function resolveURL(url,path){// Invalid URL if(typeof url!=='string'||url==='')return'';// Host Relative URL if(/^https?:\/\//i.test(path)&&/^\//.test(url)){path=path.replace(/(^https?:\/\/[^\/]+).*/i,'$1');}// Absolute URL http://,https://,// if(/^(https?:)?\/\//i.test(url))return url;// Data URI if(/^data:.*,.*$/i.test(url))return url;// Blob URL if(/^blob:.*$/i.test(url))return url;// Relative URL return path+url;}/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material */function createDefaultMaterial(cache){if(cache['DefaultMaterial']===undefined){cache['DefaultMaterial']=new MeshStandardMaterial({color:0xFFFFFF,emissive:0x000000,metalness:1,roughness:1,transparent:false,depthTest:true,side:FrontSide});}return cache['DefaultMaterial'];}function addUnknownExtensionsToUserData(knownExtensions,object,objectDef){// Add unknown glTF extensions to an object's userData. for(var name in objectDef.extensions){if(knownExtensions[name]===undefined){object.userData.gltfExtensions=object.userData.gltfExtensions||{};object.userData.gltfExtensions[name]=objectDef.extensions[name];}}}/** * @param {Object3D|Material|BufferGeometry} object * @param {GLTF.definition} gltfDef */function assignExtrasToUserData(object,gltfDef){if(gltfDef.extras!==undefined){if(_typeof(gltfDef.extras)==='object'){Object.assign(object.userData,gltfDef.extras);}else{console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, '+gltfDef.extras);}}}/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets * * @param {BufferGeometry} geometry * @param {Array} targets * @param {GLTFParser} parser * @return {Promise} */function addMorphTargets(geometry,targets,parser){var hasMorphPosition=false;var hasMorphNormal=false;for(var i=0,il=targets.length;i} */GLTFParser.prototype.getDependency=function(type,index){var cacheKey=type+':'+index;var dependency=this.cache.get(cacheKey);if(!dependency){switch(type){case'scene':dependency=this.loadScene(index);break;case'node':dependency=this.loadNode(index);break;case'mesh':dependency=this._invokeOne(function(ext){return ext.loadMesh&&ext.loadMesh(index);});break;case'accessor':dependency=this.loadAccessor(index);break;case'bufferView':dependency=this._invokeOne(function(ext){return ext.loadBufferView&&ext.loadBufferView(index);});break;case'buffer':dependency=this.loadBuffer(index);break;case'material':dependency=this._invokeOne(function(ext){return ext.loadMaterial&&ext.loadMaterial(index);});break;case'texture':dependency=this._invokeOne(function(ext){return ext.loadTexture&&ext.loadTexture(index);});break;case'skin':dependency=this.loadSkin(index);break;case'animation':dependency=this.loadAnimation(index);break;case'camera':dependency=this.loadCamera(index);break;default:throw new Error('Unknown type: '+type);}this.cache.add(cacheKey,dependency);}return dependency;};/** * Requests all dependencies of the specified type asynchronously, with caching. * @param {string} type * @return {Promise>} */GLTFParser.prototype.getDependencies=function(type){var dependencies=this.cache.get(type);if(!dependencies){var parser=this;var defs=this.json[type+(type==='mesh'?'es':'s')]||[];dependencies=Promise.all(defs.map(function(def,index){return parser.getDependency(type,index);}));this.cache.add(type,dependencies);}return dependencies;};/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferIndex * @return {Promise} */GLTFParser.prototype.loadBuffer=function(bufferIndex){var bufferDef=this.json.buffers[bufferIndex];var loader=this.fileLoader;if(bufferDef.type&&bufferDef.type!=='arraybuffer'){throw new Error('THREE.GLTFLoader: '+bufferDef.type+' buffer type is not supported.');}// If present, GLB container is required to be the first buffer. if(bufferDef.uri===undefined&&bufferIndex===0){return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);}var options=this.options;return new Promise(function(resolve,reject){loader.load(resolveURL(bufferDef.uri,options.path),resolve,undefined,function(){reject(new Error('THREE.GLTFLoader: Failed to load buffer "'+bufferDef.uri+'".'));});});};/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferViewIndex * @return {Promise} */GLTFParser.prototype.loadBufferView=function(bufferViewIndex){var bufferViewDef=this.json.bufferViews[bufferViewIndex];return this.getDependency('buffer',bufferViewDef.buffer).then(function(buffer){var byteLength=bufferViewDef.byteLength||0;var byteOffset=bufferViewDef.byteOffset||0;return buffer.slice(byteOffset,byteOffset+byteLength);});};/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex * @return {Promise} */GLTFParser.prototype.loadAccessor=function(accessorIndex){var parser=this;var json=this.json;var accessorDef=this.json.accessors[accessorIndex];if(accessorDef.bufferView===undefined&&accessorDef.sparse===undefined){// Ignore empty accessors, which may be used to declare runtime // information about attributes coming from another source (e.g. Draco // compression extension). return Promise.resolve(null);}var pendingBufferViews=[];if(accessorDef.bufferView!==undefined){pendingBufferViews.push(this.getDependency('bufferView',accessorDef.bufferView));}else{pendingBufferViews.push(null);}if(accessorDef.sparse!==undefined){pendingBufferViews.push(this.getDependency('bufferView',accessorDef.sparse.indices.bufferView));pendingBufferViews.push(this.getDependency('bufferView',accessorDef.sparse.values.bufferView));}return Promise.all(pendingBufferViews).then(function(bufferViews){var bufferView=bufferViews[0];var itemSize=WEBGL_TYPE_SIZES[accessorDef.type];var TypedArray=WEBGL_COMPONENT_TYPES[accessorDef.componentType];// For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. var elementBytes=TypedArray.BYTES_PER_ELEMENT;var itemBytes=elementBytes*itemSize;var byteOffset=accessorDef.byteOffset||0;var byteStride=accessorDef.bufferView!==undefined?json.bufferViews[accessorDef.bufferView].byteStride:undefined;var normalized=accessorDef.normalized===true;var array,bufferAttribute;// The buffer is not interleaved if the stride is the item size in bytes. if(byteStride&&byteStride!==itemBytes){// Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer // This makes sure that IBA.count reflects accessor.count properly var ibSlice=Math.floor(byteOffset/byteStride);var ibCacheKey='InterleavedBuffer:'+accessorDef.bufferView+':'+accessorDef.componentType+':'+ibSlice+':'+accessorDef.count;var ib=parser.cache.get(ibCacheKey);if(!ib){array=new TypedArray(bufferView,ibSlice*byteStride,accessorDef.count*byteStride/elementBytes);// Integer parameters to IB/IBA are in array elements, not bytes. ib=new InterleavedBuffer(array,byteStride/elementBytes);parser.cache.add(ibCacheKey,ib);}bufferAttribute=new InterleavedBufferAttribute(ib,itemSize,byteOffset%byteStride/elementBytes,normalized);}else{if(bufferView===null){array=new TypedArray(accessorDef.count*itemSize);}else{array=new TypedArray(bufferView,byteOffset,accessorDef.count*itemSize);}bufferAttribute=new BufferAttribute(array,itemSize,normalized);}// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors if(accessorDef.sparse!==undefined){var itemSizeIndices=WEBGL_TYPE_SIZES.SCALAR;var TypedArrayIndices=WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];var byteOffsetIndices=accessorDef.sparse.indices.byteOffset||0;var byteOffsetValues=accessorDef.sparse.values.byteOffset||0;var sparseIndices=new TypedArrayIndices(bufferViews[1],byteOffsetIndices,accessorDef.sparse.count*itemSizeIndices);var sparseValues=new TypedArray(bufferViews[2],byteOffsetValues,accessorDef.sparse.count*itemSize);if(bufferView!==null){// Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes. bufferAttribute=new BufferAttribute(bufferAttribute.array.slice(),bufferAttribute.itemSize,bufferAttribute.normalized);}for(var i=0,il=sparseIndices.length;i=2)bufferAttribute.setY(index,sparseValues[i*itemSize+1]);if(itemSize>=3)bufferAttribute.setZ(index,sparseValues[i*itemSize+2]);if(itemSize>=4)bufferAttribute.setW(index,sparseValues[i*itemSize+3]);if(itemSize>=5)throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');}}return bufferAttribute;});};/** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * @param {number} textureIndex * @return {Promise} */GLTFParser.prototype.loadTexture=function(textureIndex){var parser=this;var json=this.json;var options=this.options;var textureDef=json.textures[textureIndex];var textureExtensions=textureDef.extensions||{};var source;if(textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]){source=json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];}else{source=json.images[textureDef.source];}var loader;if(source.uri){loader=options.manager.getHandler(source.uri);}if(!loader){loader=textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]?parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader:this.textureLoader;}return this.loadTextureImage(textureIndex,source,loader);};GLTFParser.prototype.loadTextureImage=function(textureIndex,source,loader){var parser=this;var json=this.json;var options=this.options;var textureDef=json.textures[textureIndex];var URL=self.URL||self.webkitURL;var sourceURI=source.uri;var isObjectURL=false;var hasAlpha=true;if(source.mimeType==='image/jpeg')hasAlpha=false;if(source.bufferView!==undefined){// Load binary image data from bufferView, if provided. sourceURI=parser.getDependency('bufferView',source.bufferView).then(function(bufferView){if(source.mimeType==='image/png'){// Inspect the PNG 'IHDR' chunk to determine whether the image could have an // alpha channel. This check is conservative — the image could have an alpha // channel with all values == 1, and the indexed type (colorType == 3) only // sometimes contains alpha. // // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header var colorType=new DataView(bufferView,25,1).getUint8(0,false);hasAlpha=colorType===6||colorType===4||colorType===3;}isObjectURL=true;var blob=new Blob([bufferView],{type:source.mimeType});sourceURI=URL.createObjectURL(blob);return sourceURI;});}return Promise.resolve(sourceURI).then(function(sourceURI){return new Promise(function(resolve,reject){var onLoad=resolve;if(loader.isImageBitmapLoader===true){onLoad=function onLoad(imageBitmap){resolve(new CanvasTexture(imageBitmap));};}loader.load(resolveURL(sourceURI,options.path),onLoad,undefined,reject);});}).then(function(texture){// Clean up resources and configure Texture. if(isObjectURL===true){URL.revokeObjectURL(sourceURI);}texture.flipY=false;if(textureDef.name)texture.name=textureDef.name;// When there is definitely no alpha channel in the texture, set RGBFormat to save space. if(!hasAlpha)texture.format=RGBFormat;var samplers=json.samplers||{};var sampler=samplers[textureDef.sampler]||{};texture.magFilter=WEBGL_FILTERS[sampler.magFilter]||LinearFilter;texture.minFilter=WEBGL_FILTERS[sampler.minFilter]||LinearMipmapLinearFilter;texture.wrapS=WEBGL_WRAPPINGS[sampler.wrapS]||RepeatWrapping;texture.wrapT=WEBGL_WRAPPINGS[sampler.wrapT]||RepeatWrapping;parser.associations.set(texture,{type:'textures',index:textureIndex});return texture;});};/** * Asynchronously assigns a texture to the given material parameters. * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef * @return {Promise} */GLTFParser.prototype.assignTexture=function(materialParams,mapName,mapDef){var parser=this;return this.getDependency('texture',mapDef.index).then(function(texture){// Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured // However, we will copy UV set 0 to UV set 1 on demand for aoMap if(mapDef.texCoord!==undefined&&mapDef.texCoord!=0&&!(mapName==='aoMap'&&mapDef.texCoord==1)){console.warn('THREE.GLTFLoader: Custom UV set '+mapDef.texCoord+' for texture '+mapName+' not yet supported.');}if(parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]){var transform=mapDef.extensions!==undefined?mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]:undefined;if(transform){var gltfReference=parser.associations.get(texture);texture=parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture,transform);parser.associations.set(texture,gltfReference);}}materialParams[mapName]=texture;});};/** * Assigns final material to a Mesh, Line, or Points instance. The instance * already has a material (generated from the glTF material options alone) * but reuse of the same glTF material may require multiple threejs materials * to accomodate different primitive types, defines, etc. New materials will * be created if necessary, and reused from a cache. * @param {Object3D} mesh Mesh, Line, or Points instance. */GLTFParser.prototype.assignFinalMaterial=function(mesh){var geometry=mesh.geometry;var material=mesh.material;var useVertexTangents=geometry.attributes.tangent!==undefined;var useVertexColors=geometry.attributes.color!==undefined;var useFlatShading=geometry.attributes.normal===undefined;var useSkinning=mesh.isSkinnedMesh===true;var useMorphTargets=Object.keys(geometry.morphAttributes).length>0;var useMorphNormals=useMorphTargets&&geometry.morphAttributes.normal!==undefined;if(mesh.isPoints){var cacheKey='PointsMaterial:'+material.uuid;var pointsMaterial=this.cache.get(cacheKey);if(!pointsMaterial){pointsMaterial=new PointsMaterial();Material.prototype.copy.call(pointsMaterial,material);pointsMaterial.color.copy(material.color);pointsMaterial.map=material.map;pointsMaterial.sizeAttenuation=false;// glTF spec says points should be 1px this.cache.add(cacheKey,pointsMaterial);}material=pointsMaterial;}else if(mesh.isLine){var cacheKey='LineBasicMaterial:'+material.uuid;var lineMaterial=this.cache.get(cacheKey);if(!lineMaterial){lineMaterial=new LineBasicMaterial();Material.prototype.copy.call(lineMaterial,material);lineMaterial.color.copy(material.color);this.cache.add(cacheKey,lineMaterial);}material=lineMaterial;}// Clone the material if it will be modified if(useVertexTangents||useVertexColors||useFlatShading||useSkinning||useMorphTargets){var cacheKey='ClonedMaterial:'+material.uuid+':';if(material.isGLTFSpecularGlossinessMaterial)cacheKey+='specular-glossiness:';if(useSkinning)cacheKey+='skinning:';if(useVertexTangents)cacheKey+='vertex-tangents:';if(useVertexColors)cacheKey+='vertex-colors:';if(useFlatShading)cacheKey+='flat-shading:';if(useMorphTargets)cacheKey+='morph-targets:';if(useMorphNormals)cacheKey+='morph-normals:';var cachedMaterial=this.cache.get(cacheKey);if(!cachedMaterial){cachedMaterial=material.clone();if(useSkinning)cachedMaterial.skinning=true;if(useVertexTangents)cachedMaterial.vertexTangents=true;if(useVertexColors)cachedMaterial.vertexColors=true;if(useFlatShading)cachedMaterial.flatShading=true;if(useMorphTargets)cachedMaterial.morphTargets=true;if(useMorphNormals)cachedMaterial.morphNormals=true;this.cache.add(cacheKey,cachedMaterial);this.associations.set(cachedMaterial,this.associations.get(material));}material=cachedMaterial;}// workarounds for mesh and geometry if(material.aoMap&&geometry.attributes.uv2===undefined&&geometry.attributes.uv!==undefined){geometry.setAttribute('uv2',geometry.attributes.uv);}// https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 if(material.normalScale&&!useVertexTangents){material.normalScale.y=-material.normalScale.y;}if(material.clearcoatNormalScale&&!useVertexTangents){material.clearcoatNormalScale.y=-material.clearcoatNormalScale.y;}mesh.material=material;};GLTFParser.prototype.getMaterialType=function()/* materialIndex */{return MeshStandardMaterial;};/** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex * @return {Promise} */GLTFParser.prototype.loadMaterial=function(materialIndex){var parser=this;var json=this.json;var extensions=this.extensions;var materialDef=json.materials[materialIndex];var materialType;var materialParams={};var materialExtensions=materialDef.extensions||{};var pending=[];if(materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]){var sgExtension=extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];materialType=sgExtension.getMaterialType();pending.push(sgExtension.extendParams(materialParams,materialDef,parser));}else if(materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]){var kmuExtension=extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];materialType=kmuExtension.getMaterialType();pending.push(kmuExtension.extendParams(materialParams,materialDef,parser));}else{// Specification: // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material var metallicRoughness=materialDef.pbrMetallicRoughness||{};materialParams.color=new Color(1.0,1.0,1.0);materialParams.opacity=1.0;if(Array.isArray(metallicRoughness.baseColorFactor)){var array=metallicRoughness.baseColorFactor;materialParams.color.fromArray(array);materialParams.opacity=array[3];}if(metallicRoughness.baseColorTexture!==undefined){pending.push(parser.assignTexture(materialParams,'map',metallicRoughness.baseColorTexture));}materialParams.metalness=metallicRoughness.metallicFactor!==undefined?metallicRoughness.metallicFactor:1.0;materialParams.roughness=metallicRoughness.roughnessFactor!==undefined?metallicRoughness.roughnessFactor:1.0;if(metallicRoughness.metallicRoughnessTexture!==undefined){pending.push(parser.assignTexture(materialParams,'metalnessMap',metallicRoughness.metallicRoughnessTexture));pending.push(parser.assignTexture(materialParams,'roughnessMap',metallicRoughness.metallicRoughnessTexture));}materialType=this._invokeOne(function(ext){return ext.getMaterialType&&ext.getMaterialType(materialIndex);});pending.push(Promise.all(this._invokeAll(function(ext){return ext.extendMaterialParams&&ext.extendMaterialParams(materialIndex,materialParams);})));}if(materialDef.doubleSided===true){materialParams.side=DoubleSide;}var alphaMode=materialDef.alphaMode||ALPHA_MODES.OPAQUE;if(alphaMode===ALPHA_MODES.BLEND){materialParams.transparent=true;// See: https://github.com/mrdoob/three.js/issues/17706 materialParams.depthWrite=false;}else{materialParams.transparent=false;if(alphaMode===ALPHA_MODES.MASK){materialParams.alphaTest=materialDef.alphaCutoff!==undefined?materialDef.alphaCutoff:0.5;}}if(materialDef.normalTexture!==undefined&&materialType!==MeshBasicMaterial){pending.push(parser.assignTexture(materialParams,'normalMap',materialDef.normalTexture));materialParams.normalScale=new Vector2(1,1);if(materialDef.normalTexture.scale!==undefined){materialParams.normalScale.set(materialDef.normalTexture.scale,materialDef.normalTexture.scale);}}if(materialDef.occlusionTexture!==undefined&&materialType!==MeshBasicMaterial){pending.push(parser.assignTexture(materialParams,'aoMap',materialDef.occlusionTexture));if(materialDef.occlusionTexture.strength!==undefined){materialParams.aoMapIntensity=materialDef.occlusionTexture.strength;}}if(materialDef.emissiveFactor!==undefined&&materialType!==MeshBasicMaterial){materialParams.emissive=new Color().fromArray(materialDef.emissiveFactor);}if(materialDef.emissiveTexture!==undefined&&materialType!==MeshBasicMaterial){pending.push(parser.assignTexture(materialParams,'emissiveMap',materialDef.emissiveTexture));}return Promise.all(pending).then(function(){var material;if(materialType===GLTFMeshStandardSGMaterial){material=extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);}else{material=new materialType(materialParams);}if(materialDef.name)material.name=materialDef.name;// baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding. if(material.map)material.map.encoding=sRGBEncoding;if(material.emissiveMap)material.emissiveMap.encoding=sRGBEncoding;assignExtrasToUserData(material,materialDef);parser.associations.set(material,{type:'materials',index:materialIndex});if(materialDef.extensions)addUnknownExtensionsToUserData(extensions,material,materialDef);return material;});};/** When Object3D instances are targeted by animation, they need unique names. */GLTFParser.prototype.createUniqueName=function(originalName){var name=PropertyBinding.sanitizeNodeName(originalName||'');for(var i=1;this.nodeNamesUsed[name];++i){name=originalName+'_'+i;}this.nodeNamesUsed[name]=true;return name;};/** * @param {BufferGeometry} geometry * @param {GLTF.Primitive} primitiveDef * @param {GLTFParser} parser */function computeBounds(geometry,primitiveDef,parser){var attributes=primitiveDef.attributes;var box=new Box3();if(attributes.POSITION!==undefined){var accessor=parser.json.accessors[attributes.POSITION];var min=accessor.min;var max=accessor.max;// glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. if(min!==undefined&&max!==undefined){box.set(new Vector3(min[0],min[1],min[2]),new Vector3(max[0],max[1],max[2]));}else{console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');return;}}else{return;}var targets=primitiveDef.targets;if(targets!==undefined){var maxDisplacement=new Vector3();var vector=new Vector3();for(var i=0,il=targets.length;i} */function addPrimitiveAttributes(geometry,primitiveDef,parser){var attributes=primitiveDef.attributes;var pending=[];function assignAttributeAccessor(accessorIndex,attributeName){return parser.getDependency('accessor',accessorIndex).then(function(accessor){geometry.setAttribute(attributeName,accessor);});}for(var gltfAttributeName in attributes){var threeAttributeName=ATTRIBUTES[gltfAttributeName]||gltfAttributeName.toLowerCase();// Skip attributes already provided by e.g. Draco extension. if(threeAttributeName in geometry.attributes)continue;pending.push(assignAttributeAccessor(attributes[gltfAttributeName],threeAttributeName));}if(primitiveDef.indices!==undefined&&!geometry.index){var accessor=parser.getDependency('accessor',primitiveDef.indices).then(function(accessor){geometry.setIndex(accessor);});pending.push(accessor);}assignExtrasToUserData(geometry,primitiveDef);computeBounds(geometry,primitiveDef,parser);return Promise.all(pending).then(function(){return primitiveDef.targets!==undefined?addMorphTargets(geometry,primitiveDef.targets,parser):geometry;});}/** * @param {BufferGeometry} geometry * @param {Number} drawMode * @return {BufferGeometry} */function toTrianglesDrawMode(geometry,drawMode){var index=geometry.getIndex();// generate index if not present if(index===null){var indices=[];var position=geometry.getAttribute('position');if(position!==undefined){for(var i=0;i} primitives * @return {Promise>} */GLTFParser.prototype.loadGeometries=function(primitives){var parser=this;var extensions=this.extensions;var cache=this.primitiveCache;function createDracoPrimitive(primitive){return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive,parser).then(function(geometry){return addPrimitiveAttributes(geometry,primitive,parser);});}var pending=[];for(var i=0,il=primitives.length;i} */GLTFParser.prototype.loadMesh=function(meshIndex){var parser=this;var json=this.json;var meshDef=json.meshes[meshIndex];var primitives=meshDef.primitives;var pending=[];for(var i=0,il=primitives.length;i0){updateMorphTargets(mesh,meshDef);}mesh.name=parser.createUniqueName(meshDef.name||'mesh_'+meshIndex);if(geometries.length>1)mesh.name+='_'+i;assignExtrasToUserData(mesh,meshDef);parser.assignFinalMaterial(mesh);meshes.push(mesh);}if(meshes.length===1){return meshes[0];}var group=new Group();for(var i=0,il=meshes.length;i} */GLTFParser.prototype.loadCamera=function(cameraIndex){var camera;var cameraDef=this.json.cameras[cameraIndex];var params=cameraDef[cameraDef.type];if(!params){console.warn('THREE.GLTFLoader: Missing camera parameters.');return;}if(cameraDef.type==='perspective'){camera=new PerspectiveCamera(MathUtils.radToDeg(params.yfov),params.aspectRatio||1,params.znear||1,params.zfar||2e6);}else if(cameraDef.type==='orthographic'){camera=new OrthographicCamera(-params.xmag,params.xmag,params.ymag,-params.ymag,params.znear,params.zfar);}if(cameraDef.name)camera.name=this.createUniqueName(cameraDef.name);assignExtrasToUserData(camera,cameraDef);return Promise.resolve(camera);};/** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins * @param {number} skinIndex * @return {Promise} */GLTFParser.prototype.loadSkin=function(skinIndex){var skinDef=this.json.skins[skinIndex];var skinEntry={joints:skinDef.joints};if(skinDef.inverseBindMatrices===undefined){return Promise.resolve(skinEntry);}return this.getDependency('accessor',skinDef.inverseBindMatrices).then(function(accessor){skinEntry.inverseBindMatrices=accessor;return skinEntry;});};/** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex * @return {Promise} */GLTFParser.prototype.loadAnimation=function(animationIndex){var json=this.json;var animationDef=json.animations[animationIndex];var pendingNodes=[];var pendingInputAccessors=[];var pendingOutputAccessors=[];var pendingSamplers=[];var pendingTargets=[];for(var i=0,il=animationDef.channels.length;i} */GLTFParser.prototype.loadNode=function(nodeIndex){var json=this.json;var extensions=this.extensions;var parser=this;var nodeDef=json.nodes[nodeIndex];// reserve node's name before its dependencies, so the root has the intended name. var nodeName=nodeDef.name?parser.createUniqueName(nodeDef.name):'';return function(){var pending=[];if(nodeDef.mesh!==undefined){pending.push(parser.getDependency('mesh',nodeDef.mesh).then(function(mesh){var node=parser._getNodeRef(parser.meshCache,nodeDef.mesh,mesh);// if weights are provided on the node, override weights on the mesh. if(nodeDef.weights!==undefined){node.traverse(function(o){if(!o.isMesh)return;for(var i=0,il=nodeDef.weights.length;i1){node=new Group();}else if(objects.length===1){node=objects[0];}else{node=new Object3D();}if(node!==objects[0]){for(var i=0,il=objects.length;i} */GLTFParser.prototype.loadScene=function(){// scene node hierachy builder function buildNodeHierachy(nodeId,parentObject,json,parser){var nodeDef=json.nodes[nodeId];return parser.getDependency('node',nodeId).then(function(node){if(nodeDef.skin===undefined)return node;// build skeleton here as well var skinEntry;return parser.getDependency('skin',nodeDef.skin).then(function(skin){skinEntry=skin;var pendingJoints=[];for(var i=0,il=skinEntry.joints.length;i1&&arguments[1]!==undefined?arguments[1]:5;_classCallCheck(this,CacheEvictionPolicy);this[_a$1]=new Map();this[_b]=[];this[$cache]=cache;this[$evictionThreshold]=evictionThreshold;}_createClass(CacheEvictionPolicy,[{key:"retainerCount",value:function retainerCount(key){return this[$retainerCount].get(key)||0;}},{key:"reset",value:function reset(){this[$retainerCount].clear();this[$recentlyUsed]=[];}},{key:"retain",value:function retain(key){if(!this[$retainerCount].has(key)){this[$retainerCount].set(key,0);}this[$retainerCount].set(key,this[$retainerCount].get(key)+1);var recentlyUsedIndex=this[$recentlyUsed].indexOf(key);if(recentlyUsedIndex!==-1){this[$recentlyUsed].splice(recentlyUsedIndex,1);}this[$recentlyUsed].unshift(key);this[$evict]();}},{key:"release",value:function release(key){if(this[$retainerCount].has(key)){this[$retainerCount].set(key,Math.max(this[$retainerCount].get(key)-1,0));}this[$evict]();}},{key:(_a$1=$retainerCount,_b=$recentlyUsed,$evict),value:function value(){if(this[$recentlyUsed].length=this[$evictionThreshold];--_i331){var key=this[$recentlyUsed][_i331];var retainerCount=this[$retainerCount].get(key);if(retainerCount===0){this[$cache].delete(key);this[$recentlyUsed].splice(_i331,1);}}}},{key:"evictionThreshold",set:function set(value){this[$evictionThreshold]=value;this[$evict]();},get:function get(){return this[$evictionThreshold];}},{key:"cache",get:function get(){return this[$cache];}}]);return CacheEvictionPolicy;}();var _a$2,_b$1;var loadWithLoader=function loadWithLoader(url,loader){var progressCallback=arguments.length>2&&arguments[2]!==undefined?arguments[2]:function(){};var onProgress=function onProgress(event){var fraction=event.loaded/event.total;progressCallback(Math.max(0,Math.min(1,isFinite(fraction)?fraction:1)));};return new Promise(function(resolve,reject){loader.load(url,resolve,onProgress,reject);});};var cache=new Map();var preloaded=new Map();var dracoDecoderLocation;var dracoLoader=new DRACOLoader();var $loader=Symbol('loader');var $evictionPolicy=Symbol('evictionPolicy');var $GLTFInstance=Symbol('GLTFInstance');var CachingGLTFLoader=/*#__PURE__*/function(_EventDispatcher){_inherits(CachingGLTFLoader,_EventDispatcher);var _super11=_createSuper(CachingGLTFLoader);function CachingGLTFLoader(GLTFInstance){var _this22;_classCallCheck(this,CachingGLTFLoader);_this22=_super11.call(this);_this22[_b$1]=new GLTFLoader();_this22[$GLTFInstance]=GLTFInstance;_this22[$loader].setDRACOLoader(dracoLoader);return _this22;}_createClass(CachingGLTFLoader,[{key:"preload",value:function(){var _preload=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee2(url,element){var progressCallback,rawGLTFLoads,_GLTFInstance,gltfInstanceLoads,_args2=arguments;return regeneratorRuntime.wrap(function _callee2$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:progressCallback=_args2.length>2&&_args2[2]!==undefined?_args2[2]:function(){};this.dispatchEvent({type:'preload',element:element,src:url});if(!cache.has(url)){rawGLTFLoads=loadWithLoader(url,this[$loader],function(progress){progressCallback(progress*0.8);});_GLTFInstance=this[$GLTFInstance];gltfInstanceLoads=rawGLTFLoads.then(function(rawGLTF){return _GLTFInstance.prepare(rawGLTF);}).then(function(preparedGLTF){progressCallback(0.9);return new _GLTFInstance(preparedGLTF);});cache.set(url,gltfInstanceLoads);}_context3.next=5;return cache.get(url);case 5:preloaded.set(url,true);if(progressCallback){progressCallback(1.0);}case 7:case"end":return _context3.stop();}}},_callee2,this);}));function preload(_x3,_x4){return _preload.apply(this,arguments);}return preload;}()},{key:"load",value:function(){var _load=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee3(url,element){var _this23=this;var progressCallback,gltf,clone,_args3=arguments;return regeneratorRuntime.wrap(function _callee3$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:progressCallback=_args3.length>2&&_args3[2]!==undefined?_args3[2]:function(){};_context4.next=3;return this.preload(url,element,progressCallback);case 3:_context4.next=5;return cache.get(url);case 5:gltf=_context4.sent;_context4.next=8;return gltf.clone();case 8:clone=_context4.sent;this[$evictionPolicy].retain(url);clone.dispose=function(){var originalDispose=clone.dispose;var disposed=false;return function(){if(disposed){return;}disposed=true;originalDispose.apply(clone);_this23[$evictionPolicy].release(url);};}();return _context4.abrupt("return",clone);case 12:case"end":return _context4.stop();}}},_callee3,this);}));function load(_x5,_x6){return _load.apply(this,arguments);}return load;}()},{key:(_a$2=$evictionPolicy,_b$1=$loader,$evictionPolicy),get:function get(){return this.constructor[$evictionPolicy];}}],[{key:"setDRACODecoderLocation",value:function setDRACODecoderLocation(url){dracoDecoderLocation=url;dracoLoader.setDecoderPath(url);}},{key:"getDRACODecoderLocation",value:function getDRACODecoderLocation(){return dracoDecoderLocation;}},{key:"clearCache",value:function clearCache(){var _this24=this;cache.forEach(function(_value,url){_this24.delete(url);});this[$evictionPolicy].reset();}},{key:"has",value:function has(url){return cache.has(url);}},{key:"delete",value:function(){var _delete2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee4(url){var gltfLoads,gltf;return regeneratorRuntime.wrap(function _callee4$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:if(this.has(url)){_context5.next=2;break;}return _context5.abrupt("return");case 2:gltfLoads=cache.get(url);preloaded.delete(url);cache.delete(url);_context5.next=7;return gltfLoads;case 7:gltf=_context5.sent;gltf.dispose();case 9:case"end":return _context5.stop();}}},_callee4,this);}));function _delete(_x7){return _delete2.apply(this,arguments);}return _delete;}()},{key:"hasFinishedLoading",value:function hasFinishedLoading(url){return!!preloaded.get(url);}},{key:"cache",get:function get(){return cache;}}]);return CachingGLTFLoader;}(EventDispatcher);CachingGLTFLoader[_a$2]=new CacheEvictionPolicy(CachingGLTFLoader);var _a$3;var SETTLING_TIME=10000;var DECAY_MILLISECONDS=50;var NATURAL_FREQUENCY=1/DECAY_MILLISECONDS;var NIL_SPEED=0.0002*NATURAL_FREQUENCY;var $velocity=Symbol('velocity');var Damper=/*#__PURE__*/function(){function Damper(){_classCallCheck(this,Damper);this[_a$3]=0;}_createClass(Damper,[{key:"update",value:function update(x,xGoal,timeStepMilliseconds,xNormalization){if(x==null||xNormalization===0){return xGoal;}if(x===xGoal&&this[$velocity]===0){return xGoal;}if(timeStepMilliseconds<0){return x;}var deltaX=x-xGoal;var intermediateVelocity=this[$velocity]+NATURAL_FREQUENCY*deltaX;var intermediateX=deltaX+timeStepMilliseconds*intermediateVelocity;var decay=Math.exp(-NATURAL_FREQUENCY*timeStepMilliseconds);var newVelocity=(intermediateVelocity-NATURAL_FREQUENCY*intermediateX)*decay;var acceleration=-NATURAL_FREQUENCY*(newVelocity+intermediateVelocity*decay);if(Math.abs(newVelocity)=0){this[$velocity]=0;return xGoal;}else{this[$velocity]=newVelocity;return xGoal+intermediateX*decay;}}}]);return Damper;}();_a$3=$velocity;var CSS2DObject=function CSS2DObject(element){Object3D.call(this);this.element=element||document.createElement('div');this.element.style.position='absolute';this.addEventListener('removed',function(){this.traverse(function(object){if(_instanceof(object.element,Element)&&object.element.parentNode!==null){object.element.parentNode.removeChild(object.element);}});});};CSS2DObject.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:CSS2DObject,copy:function copy(source,recursive){Object3D.prototype.copy.call(this,source,recursive);this.element=source.element.cloneNode(true);return this;}});// var CSS2DRenderer=function CSS2DRenderer(){var _this=this;var _width,_height;var _widthHalf,_heightHalf;var vector=new Vector3();var viewMatrix=new Matrix4();var viewProjectionMatrix=new Matrix4();var cache={objects:new WeakMap()};var domElement=document.createElement('div');domElement.style.overflow='hidden';this.domElement=domElement;this.getSize=function(){return{width:_width,height:_height};};this.setSize=function(width,height){_width=width;_height=height;_widthHalf=_width/2;_heightHalf=_height/2;domElement.style.width=width+'px';domElement.style.height=height+'px';};var renderObject=function renderObject(object,scene,camera){if(_instanceof(object,CSS2DObject)){object.onBeforeRender(_this,scene,camera);vector.setFromMatrixPosition(object.matrixWorld);vector.applyMatrix4(viewProjectionMatrix);var element=object.element;var style='translate(-50%,-50%) translate('+(vector.x*_widthHalf+_widthHalf)+'px,'+(-vector.y*_heightHalf+_heightHalf)+'px)';element.style.WebkitTransform=style;element.style.MozTransform=style;element.style.oTransform=style;element.style.transform=style;element.style.display=object.visible&&vector.z>=-1&&vector.z<=1?'':'none';var objectData={distanceToCameraSquared:getDistanceToSquared(camera,object)};cache.objects.set(object,objectData);if(element.parentNode!==domElement){domElement.appendChild(element);}object.onAfterRender(_this,scene,camera);}for(var i=0,l=object.children.length;iMAX_PARSE_ITERATIONS){inputString='';break;}var expressionParseResult=parseExpression(inputString);var expression=expressionParseResult.nodes[0];if(expression==null||expression.terms.length===0){break;}expressions.push(expression);inputString=expressionParseResult.remainingInput;}return cache[cacheKey]=expressions;};}();var parseExpression=function(){var IS_IDENT_RE=/^(\-\-|[a-z\u0240-\uffff])/i;var IS_OPERATOR_RE=/^([\*\+\/]|[\-]\s)/i;var IS_EXPRESSION_END_RE=/^[\),]/;var FUNCTION_ARGUMENTS_FIRST_TOKEN='(';var HEX_FIRST_TOKEN='#';return function(inputString){var terms=[];while(inputString.length){inputString=inputString.trim();if(IS_EXPRESSION_END_RE.test(inputString)){break;}else if(inputString[0]===FUNCTION_ARGUMENTS_FIRST_TOKEN){var _parseFunctionArgumen=parseFunctionArguments(inputString),nodes=_parseFunctionArgumen.nodes,remainingInput=_parseFunctionArgumen.remainingInput;inputString=remainingInput;terms.push({type:'function',name:{type:'ident',value:'calc'},arguments:nodes});}else if(IS_IDENT_RE.test(inputString)){var identParseResult=parseIdent(inputString);var identNode=identParseResult.nodes[0];inputString=identParseResult.remainingInput;if(inputString[0]===FUNCTION_ARGUMENTS_FIRST_TOKEN){var _parseFunctionArgumen2=parseFunctionArguments(inputString),_nodes=_parseFunctionArgumen2.nodes,_remainingInput=_parseFunctionArgumen2.remainingInput;terms.push({type:'function',name:identNode,arguments:_nodes});inputString=_remainingInput;}else{terms.push(identNode);}}else if(IS_OPERATOR_RE.test(inputString)){terms.push({type:'operator',value:inputString[0]});inputString=inputString.slice(1);}else{var _ref=inputString[0]===HEX_FIRST_TOKEN?parseHex(inputString):parseNumber(inputString),_nodes2=_ref.nodes,_remainingInput2=_ref.remainingInput;if(_nodes2.length===0){break;}terms.push(_nodes2[0]);inputString=_remainingInput2;}}return{nodes:[{type:'expression',terms:terms}],remainingInput:inputString};};}();var parseIdent=function(){var NOT_IDENT_RE=/[^a-z^0-9^_^\-^\u0240-\uffff]/i;return function(inputString){var match=inputString.match(NOT_IDENT_RE);var ident=match==null?inputString:inputString.substr(0,match.index);var remainingInput=match==null?'':inputString.substr(match.index);return{nodes:[{type:'ident',value:ident}],remainingInput:remainingInput};};}();var parseNumber=function(){var VALUE_RE=/[\+\-]?(\d+[\.]\d+|\d+|[\.]\d+)([eE][\+\-]?\d+)?/;var UNIT_RE=/^[a-z%]+/i;var ALLOWED_UNITS=/^(m|mm|cm|rad|deg|[%])$/;return function(inputString){var valueMatch=inputString.match(VALUE_RE);var value=valueMatch==null?'0':valueMatch[0];inputString=value==null?inputString:inputString.slice(value.length);var unitMatch=inputString.match(UNIT_RE);var unit=unitMatch!=null&&unitMatch[0]!==''?unitMatch[0]:null;var remainingInput=unitMatch==null?inputString:inputString.slice(unit.length);if(unit!=null&&!ALLOWED_UNITS.test(unit)){unit=null;}return{nodes:[{type:'number',number:parseFloat(value)||0,unit:unit}],remainingInput:remainingInput};};}();var parseHex=function(){var HEX_RE=/^[a-f0-9]*/i;return function(inputString){inputString=inputString.slice(1).trim();var hexMatch=inputString.match(HEX_RE);var nodes=hexMatch==null?[]:[{type:'hex',value:hexMatch[0]}];return{nodes:nodes,remainingInput:hexMatch==null?inputString:inputString.slice(hexMatch[0].length)};};}();var parseFunctionArguments=function parseFunctionArguments(inputString){var expressionNodes=[];inputString=inputString.slice(1).trim();while(inputString.length){var expressionParseResult=parseExpression(inputString);expressionNodes.push(expressionParseResult.nodes[0]);inputString=expressionParseResult.remainingInput.trim();if(inputString[0]===','){inputString=inputString.slice(1).trim();}else if(inputString[0]===')'){inputString=inputString.slice(1);break;}}return{nodes:expressionNodes,remainingInput:inputString};};var $visitedTypes=Symbol('visitedTypes');var ASTWalker=/*#__PURE__*/function(){function ASTWalker(visitedTypes){_classCallCheck(this,ASTWalker);this[$visitedTypes]=visitedTypes;}_createClass(ASTWalker,[{key:"walk",value:function walk(ast,callback){var remaining=ast.slice();while(remaining.length){var next=remaining.shift();if(this[$visitedTypes].indexOf(next.type)>-1){callback(next);}switch(next.type){case'expression':remaining.unshift.apply(remaining,_toConsumableArray(next.terms));break;case'function':remaining.unshift.apply(remaining,[next.name].concat(_toConsumableArray(next.arguments)));break;}}}}]);return ASTWalker;}();var ZERO=Object.freeze({type:'number',number:0,unit:null});var degreesToRadians=function degreesToRadians(numberNode){var fallbackRadianValue=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var number=numberNode.number,unit=numberNode.unit;if(!isFinite(number)){number=fallbackRadianValue;unit='rad';}else if(numberNode.unit==='rad'||numberNode.unit==null){return numberNode;}var valueIsDegrees=unit==='deg'&&number!=null;var value=valueIsDegrees?number:0;var radians=value*Math.PI/180;return{type:'number',number:radians,unit:'rad'};};var lengthToBaseMeters=function lengthToBaseMeters(numberNode){var fallbackMeterValue=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var number=numberNode.number,unit=numberNode.unit;if(!isFinite(number)){number=fallbackMeterValue;unit='m';}else if(numberNode.unit==='m'){return numberNode;}var scale;switch(unit){default:scale=1;break;case'cm':scale=1/100;break;case'mm':scale=1/1000;break;}var value=scale*number;return{type:'number',number:value,unit:'m'};};var normalizeUnit=function(){var identity=function identity(node){return node;};var unitNormalizers={'rad':identity,'deg':degreesToRadians,'m':identity,'mm':lengthToBaseMeters,'cm':lengthToBaseMeters};return function(node){var fallback=arguments.length>1&&arguments[1]!==undefined?arguments[1]:ZERO;var number=node.number,unit=node.unit;if(!isFinite(number)){number=fallback.number;unit=fallback.unit;}if(unit==null){return node;}var normalize=unitNormalizers[unit];if(normalize==null){return fallback;}return normalize(node);};}();var Hotspot=/*#__PURE__*/function(_CSS2DObject){_inherits(Hotspot,_CSS2DObject);var _super12=_createSuper(Hotspot);function Hotspot(config){var _this25;_classCallCheck(this,Hotspot);_this25=_super12.call(this,document.createElement('div'));_this25.normal=new Vector3(0,1,0);_this25.initialized=false;_this25.referenceCount=1;_this25.pivot=document.createElement('div');_this25.slot=document.createElement('slot');_this25.element.classList.add('annotation-wrapper');_this25.slot.name=config.name;_this25.element.appendChild(_this25.pivot);_this25.pivot.appendChild(_this25.slot);_this25.updatePosition(config.position);_this25.updateNormal(config.normal);return _this25;}_createClass(Hotspot,[{key:"show",value:function show(){if(!this.facingCamera||!this.initialized){this.updateVisibility(true);}}},{key:"hide",value:function hide(){if(this.facingCamera||!this.initialized){this.updateVisibility(false);}}},{key:"increment",value:function increment(){this.referenceCount++;}},{key:"decrement",value:function decrement(){if(this.referenceCount>0){--this.referenceCount;}return this.referenceCount===0;}},{key:"updatePosition",value:function updatePosition(position){if(position==null)return;var positionNodes=parseExpressions(position)[0].terms;for(var _i332=0;_i332<3;++_i332){this.position.setComponent(_i332,normalizeUnit(positionNodes[_i332]).number);}}},{key:"updateNormal",value:function updateNormal(normal){if(normal==null)return;var normalNodes=parseExpressions(normal)[0].terms;for(var _i333=0;_i333<3;++_i333){this.normal.setComponent(_i333,normalizeUnit(normalNodes[_i333]).number);}}},{key:"orient",value:function orient(radians){this.pivot.style.transform="rotate(".concat(radians,"rad)");}},{key:"updateVisibility",value:function updateVisibility(show){if(show){this.element.classList.remove('hide');}else{this.element.classList.add('hide');}this.slot.assignedNodes().forEach(function(node){if(node.nodeType!==Node.ELEMENT_NODE){return;}var element=node;var visibilityAttribute=element.dataset.visibilityAttribute;if(visibilityAttribute!=null){var attributeName="data-".concat(visibilityAttribute);if(show){element.setAttribute(attributeName,'');}else{element.removeAttribute(attributeName);}}element.dispatchEvent(new CustomEvent('hotspot-visibility',{detail:{visible:show}}));});this.initialized=true;}},{key:"facingCamera",get:function get(){return!this.element.classList.contains('hide');}}]);return Hotspot;}(CSS2DObject);var reduceVertices=function reduceVertices(model,func){var value=0;var vector=new Vector3();model.traverse(function(object){var i,l;object.updateWorldMatrix(false,false);var geometry=object.geometry;if(geometry!==undefined){if(geometry.isGeometry){var _vertices6=geometry.vertices;for(i=0,l=_vertices6.length;i0;this.boundingBox.copy(model.boundingBox);this.size.copy(model.size);var boundingBox=this.boundingBox,size=this.size;if(this.isAnimated){var maxDimension=Math.max(size.x,size.y,size.z)*ANIMATION_SCALING;size.y=maxDimension;boundingBox.expandByVector(size.subScalar(maxDimension).multiplyScalar(-0.5));boundingBox.max.y=boundingBox.min.y+maxDimension;size.set(maxDimension,maxDimension,maxDimension);}var shadowOffset=size.y*OFFSET;this.position.y=boundingBox.max.y+shadowOffset;boundingBox.getCenter(this.floor.position);this.setSoftness(softness);}},{key:"setSoftness",value:function setSoftness(softness){var resolution=Math.pow(2,LOG_MAX_RESOLUTION-softness*(LOG_MAX_RESOLUTION-LOG_MIN_RESOLUTION));this.setMapSize(resolution);}},{key:"setMapSize",value:function setMapSize(maxMapSize){var _this$shadow=this.shadow,camera=_this$shadow.camera,mapSize=_this$shadow.mapSize,map=_this$shadow.map;var size=this.size,boundingBox=this.boundingBox;if(map!=null){map.dispose();this.shadow.map=null;}if(this.isAnimated){maxMapSize*=ANIMATION_SCALING;}var width=Math.floor(size.x>size.z?maxMapSize:maxMapSize*size.x/size.z);var height=Math.floor(size.x>size.z?maxMapSize*size.z/size.x:maxMapSize);mapSize.set(width,height);var widthPad=2.5*size.x/width;var heightPad=2.5*size.z/height;camera.left=-boundingBox.max.x-widthPad;camera.right=-boundingBox.min.x+widthPad;camera.bottom=boundingBox.min.z-heightPad;camera.top=boundingBox.max.z+heightPad;this.setScaleAndOffset(camera.zoom,0);this.shadow.updateMatrices(this);this.floor.scale.set(size.x+2*widthPad,size.z+2*heightPad,1);this.needsUpdate=true;}},{key:"setIntensity",value:function setIntensity(intensity){this.shadowMaterial.opacity=intensity;if(intensity>0){this.visible=true;this.floor.visible=true;}else{this.visible=false;this.floor.visible=false;}}},{key:"getIntensity",value:function getIntensity(){return this.shadowMaterial.opacity;}},{key:"setRotation",value:function setRotation(radiansY){this.shadow.camera.up.set(Math.sin(radiansY),0,Math.cos(radiansY));this.shadow.updateMatrices(this);}},{key:"setScaleAndOffset",value:function setScaleAndOffset(scale,offset){var sizeY=this.size.y;var inverseScale=1/scale;var shadowOffset=sizeY*OFFSET;this.floor.position.y=2*shadowOffset-sizeY+offset*inverseScale;var camera=this.shadow.camera;camera.zoom=scale;camera.near=0;camera.far=sizeY*scale-offset;camera.projectionMatrix.makeOrthographic(camera.left*scale,camera.right*scale,camera.top*scale,camera.bottom*scale,camera.near,camera.far);camera.projectionMatrixInverse.getInverse(camera.projectionMatrix);}}]);return Shadow;}(DirectionalLight);var _a$4,_b$2;var DEFAULT_FOV_DEG=45;var DEFAULT_HALF_FOV=DEFAULT_FOV_DEG/2*Math.PI/180;var SAFE_RADIUS_RATIO=Math.sin(DEFAULT_HALF_FOV);var DEFAULT_TAN_FOV=Math.tan(DEFAULT_HALF_FOV);var $shadow=Symbol('shadow');var $cancelPendingSourceChange=Symbol('cancelPendingSourceChange');var $currentGLTF=Symbol('currentGLTF');var view=new Vector3();var target=new Vector3();var normalWorld=new Vector3();var Model=/*#__PURE__*/function(_Object3D3){_inherits(Model,_Object3D3);var _super14=_createSuper(Model);function Model(){var _this27;_classCallCheck(this,Model);_this27=_super14.call(this);_this27[_a$4]=null;_this27[_b$2]=null;_this27.animationsByName=new Map();_this27.currentAnimationAction=null;_this27.animations=[];_this27.modelContainer=new Object3D();_this27.animationNames=[];_this27.boundingBox=new Box3();_this27.size=new Vector3();_this27.idealCameraDistance=0;_this27.fieldOfViewAspect=0;_this27.userData={url:null};_this27.url=null;_this27.name='Model';_this27.modelContainer.name='ModelContainer';_this27.add(_this27.modelContainer);_this27.mixer=new AnimationMixer(_this27.modelContainer);return _this27;}_createClass(Model,[{key:"hasModel",value:function hasModel(){return!!this.modelContainer.children.length;}},{key:"setObject",value:function setObject(model){this.clear();this.modelContainer.add(model);this.updateFraming();this.dispatchEvent({type:'model-load'});}},{key:"setSource",value:function(){var _setSource=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee6(element,url,progressCallback){var _this28=this;var gltf,_gltf,animations,animationsByName,animationNames,_iterator2,_step2,animation;return regeneratorRuntime.wrap(function _callee6$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:if(!(!url||url===this.url)){_context7.next=3;break;}if(progressCallback){progressCallback(1);}return _context7.abrupt("return");case 3:if(this[$cancelPendingSourceChange]!=null){this[$cancelPendingSourceChange]();this[$cancelPendingSourceChange]=null;}this.url=url;_context7.prev=5;_context7.next=8;return new Promise(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee5(resolve,reject){var result;return regeneratorRuntime.wrap(function _callee5$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:_this28[$cancelPendingSourceChange]=function(){return reject();};_context6.prev=1;_context6.next=4;return element[$renderer].loader.load(url,element,progressCallback);case 4:result=_context6.sent;resolve(result);_context6.next=11;break;case 8:_context6.prev=8;_context6.t0=_context6["catch"](1);reject(_context6.t0);case 11:case"end":return _context6.stop();}}},_callee5,null,[[1,8]]);}));return function(_x11,_x12){return _ref2.apply(this,arguments);};}());case 8:gltf=_context7.sent;_context7.next=16;break;case 11:_context7.prev=11;_context7.t0=_context7["catch"](5);if(!(_context7.t0==null)){_context7.next=15;break;}return _context7.abrupt("return");case 15:throw _context7.t0;case 16:this.clear();this[$currentGLTF]=gltf;if(gltf!=null){this.modelContainer.add(gltf.scene);}_gltf=gltf,animations=_gltf.animations;animationsByName=new Map();animationNames=[];_iterator2=_createForOfIteratorHelper(animations);try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){animation=_step2.value;animationsByName.set(animation.name,animation);animationNames.push(animation.name);}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}this.animations=animations;this.animationsByName=animationsByName;this.animationNames=animationNames;this.userData.url=url;this.updateFraming();this.dispatchEvent({type:'model-load',url:url});case 30:case"end":return _context7.stop();}}},_callee6,this,[[5,11]]);}));function setSource(_x8,_x9,_x10){return _setSource.apply(this,arguments);}return setSource;}()},{key:"playAnimation",value:function playAnimation(){var name=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var crossfadeTime=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var animations=this.animations;if(animations==null||animations.length===0){console.warn("Cannot play animation (model does not have any animations)");return;}var animationClip=null;if(name!=null){animationClip=this.animationsByName.get(name);}if(animationClip==null){animationClip=animations[0];}try{var lastAnimationAction=this.currentAnimationAction;this.currentAnimationAction=this.mixer.clipAction(animationClip,this).play();this.currentAnimationAction.enabled=true;if(lastAnimationAction!=null&&this.currentAnimationAction!==lastAnimationAction){this.currentAnimationAction.crossFadeFrom(lastAnimationAction,crossfadeTime,false);}}catch(error){console.error(error);}}},{key:"stopAnimation",value:function stopAnimation(){if(this.currentAnimationAction!=null){this.currentAnimationAction.stop();this.currentAnimationAction.reset();this.currentAnimationAction=null;}this.mixer.stopAllAction();}},{key:"updateAnimation",value:function updateAnimation(step){this.mixer.update(step);}},{key:"clear",value:function clear(){this.url=null;this.userData={url:null};var gltf=this[$currentGLTF];if(gltf!=null){var _iterator3=_createForOfIteratorHelper(this.modelContainer.children),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var child=_step3.value;this.modelContainer.remove(child);}}catch(err){_iterator3.e(err);}finally{_iterator3.f();}gltf.dispose();this[$currentGLTF]=null;}if(this.currentAnimationAction!=null){this.currentAnimationAction.stop();this.currentAnimationAction=null;}this.mixer.stopAllAction();this.mixer.uncacheRoot(this);}},{key:"updateFraming",value:function updateFraming(){var _this29=this;var center=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;this.remove(this.modelContainer);if(center==null){this.boundingBox.setFromObject(this.modelContainer);this.boundingBox.getSize(this.size);center=this.boundingBox.getCenter(new Vector3());}var radiusSquared=function radiusSquared(value,vertex){return Math.max(value,center.distanceToSquared(vertex));};var framedRadius=Math.sqrt(reduceVertices(this.modelContainer,radiusSquared));this.idealCameraDistance=framedRadius/SAFE_RADIUS_RATIO;var horizontalFov=function horizontalFov(value,vertex){vertex.sub(center);var radiusXZ=Math.sqrt(vertex.x*vertex.x+vertex.z*vertex.z);return Math.max(value,radiusXZ/(_this29.idealCameraDistance-Math.abs(vertex.y)));};this.fieldOfViewAspect=reduceVertices(this.modelContainer,horizontalFov)/DEFAULT_TAN_FOV;this.add(this.modelContainer);}},{key:"setShadowIntensity",value:function setShadowIntensity(shadowIntensity,shadowSoftness){var shadow=this[$shadow];if(shadow!=null){shadow.setIntensity(shadowIntensity);shadow.setModel(this,shadowSoftness);}else if(shadowIntensity>0){shadow=new Shadow(this,shadowSoftness);shadow.setIntensity(shadowIntensity);this[$shadow]=shadow;}}},{key:"setShadowSoftness",value:function setShadowSoftness(softness){var shadow=this[$shadow];if(shadow!=null){shadow.setSoftness(softness);}}},{key:"setShadowRotation",value:function setShadowRotation(radiansY){var shadow=this[$shadow];if(shadow!=null){shadow.setRotation(radiansY);}}},{key:"updateShadow",value:function updateShadow(){var shadow=this[$shadow];if(shadow==null){return false;}else{var needsUpdate=shadow.needsUpdate;shadow.needsUpdate=false;return needsUpdate;}}},{key:"setShadowScaleAndOffset",value:function setShadowScaleAndOffset(scale,offset){var shadow=this[$shadow];if(shadow!=null){shadow.setScaleAndOffset(scale,offset);}}},{key:"addHotspot",value:function addHotspot(hotspot){this.add(hotspot);}},{key:"removeHotspot",value:function removeHotspot(hotspot){this.remove(hotspot);}},{key:"forHotspots",value:function forHotspots(func){var children=this.children;for(var _i334=0,l=children.length;_i3341&&arguments[1]!==undefined?arguments[1]:this;raycaster.setFromCamera(pixelPosition,this.getCamera());var hits=raycaster.intersectObject(object,true);if(hits.length===0){return null;}var hit=hits[0];if(hit.face==null){return null;}hit.face.normal.applyNormalMatrix(new Matrix3().getNormalMatrix(hit.object.matrixWorld));return{position:hit.point,normal:hit.face.normal};}},{key:"yaw",set:function set(radiansY){this.rotation.y=radiansY;this.model.setShadowRotation(radiansY);this.isDirty=true;},get:function get(){return this.rotation.y;}}]);return ModelScene;}(Scene);/** * This class generates custom mipmaps for a roughness map by encoding the lost variation in the * normal map mip levels as increased roughness in the corresponding roughness mip levels. This * helps with rendering accuracy for MeshStandardMaterial, and also helps with anti-aliasing when * using PMREM. If the normal map is larger than the roughness map, the roughness map will be * enlarged to match the dimensions of the normal map. */var _mipmapMaterial=_getMipmapMaterial();var _mesh$1=new Mesh(new PlaneBufferGeometry(2,2),_mipmapMaterial);var _flatCamera$1=new OrthographicCamera(0,1,0,1,0,1);var _tempTarget=null;var _renderer=null;function RoughnessMipmapper(renderer){_renderer=renderer;_renderer.compile(_mesh$1,_flatCamera$1);}RoughnessMipmapper.prototype={constructor:RoughnessMipmapper,generateMipmaps:function generateMipmaps(material){if('roughnessMap'in material===false)return;var roughnessMap=material.roughnessMap,normalMap=material.normalMap;if(roughnessMap===null||normalMap===null||!roughnessMap.generateMipmaps||material.userData.roughnessUpdated)return;material.userData.roughnessUpdated=true;var width=Math.max(roughnessMap.image.width,normalMap.image.width);var height=Math.max(roughnessMap.image.height,normalMap.image.height);if(!MathUtils.isPowerOfTwo(width)||!MathUtils.isPowerOfTwo(height))return;var oldTarget=_renderer.getRenderTarget();var autoClear=_renderer.autoClear;_renderer.autoClear=false;if(_tempTarget===null||_tempTarget.width!==width||_tempTarget.height!==height){if(_tempTarget!==null)_tempTarget.dispose();_tempTarget=new WebGLRenderTarget(width,height,{depthBuffer:false});_tempTarget.scissorTest=true;}if(width!==roughnessMap.image.width||height!==roughnessMap.image.height){var params={wrapS:roughnessMap.wrapS,wrapT:roughnessMap.wrapT,magFilter:roughnessMap.magFilter,minFilter:roughnessMap.minFilter,depthBuffer:false};var newRoughnessTarget=new WebGLRenderTarget(width,height,params);newRoughnessTarget.texture.generateMipmaps=true;// Setting the render target causes the memory to be allocated. _renderer.setRenderTarget(newRoughnessTarget);material.roughnessMap=newRoughnessTarget.texture;if(material.metalnessMap==roughnessMap)material.metalnessMap=material.roughnessMap;if(material.aoMap==roughnessMap)material.aoMap=material.roughnessMap;}_mipmapMaterial.uniforms.roughnessMap.value=roughnessMap;_mipmapMaterial.uniforms.normalMap.value=normalMap;var position=new Vector2(0,0);var texelSize=_mipmapMaterial.uniforms.texelSize.value;for(var mip=0;width>=1&&height>=1;++mip,width/=2,height/=2){// Rendering to a mip level is not allowed in webGL1. Instead we must set // up a secondary texture to write the result to, then copy it back to the // proper mipmap level. texelSize.set(1.0/width,1.0/height);if(mip==0)texelSize.set(0.0,0.0);_tempTarget.viewport.set(position.x,position.y,width,height);_tempTarget.scissor.set(position.x,position.y,width,height);_renderer.setRenderTarget(_tempTarget);_renderer.render(_mesh$1,_flatCamera$1);_renderer.copyFramebufferToTexture(position,material.roughnessMap,mip);_mipmapMaterial.uniforms.roughnessMap.value=material.roughnessMap;}if(roughnessMap!==material.roughnessMap)roughnessMap.dispose();_renderer.setRenderTarget(oldTarget);_renderer.autoClear=autoClear;},dispose:function dispose(){_mipmapMaterial.dispose();_mesh$1.geometry.dispose();if(_tempTarget!=null)_tempTarget.dispose();}};function _getMipmapMaterial(){var shaderMaterial=new RawShaderMaterial({uniforms:{roughnessMap:{value:null},normalMap:{value:null},texelSize:{value:new Vector2(1,1)}},vertexShader:/* glsl */"\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tattribute vec3 position;\n\t\t\tattribute vec2 uv;\n\n\t\t\tvarying vec2 vUv;\n\n\t\t\tvoid main() {\n\n\t\t\t\tvUv = uv;\n\n\t\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t\t}\n\t\t",fragmentShader:/* glsl */"\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec2 vUv;\n\n\t\t\tuniform sampler2D roughnessMap;\n\t\t\tuniform sampler2D normalMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\n\t\t\tvec4 envMapTexelToLinear( vec4 a ) { return a; }\n\n\t\t\t#include \n\n\t\t\tfloat roughnessToVariance( float roughness ) {\n\n\t\t\t\tfloat variance = 0.0;\n\n\t\t\t\tif ( roughness >= r1 ) {\n\n\t\t\t\t\tvariance = ( r0 - roughness ) * ( v1 - v0 ) / ( r0 - r1 ) + v0;\n\n\t\t\t\t} else if ( roughness >= r4 ) {\n\n\t\t\t\t\tvariance = ( r1 - roughness ) * ( v4 - v1 ) / ( r1 - r4 ) + v1;\n\n\t\t\t\t} else if ( roughness >= r5 ) {\n\n\t\t\t\t\tvariance = ( r4 - roughness ) * ( v5 - v4 ) / ( r4 - r5 ) + v4;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tfloat roughness2 = roughness * roughness;\n\n\t\t\t\t\tvariance = 1.79 * roughness2 * roughness2;\n\n\t\t\t\t}\n\n\t\t\t\treturn variance;\n\n\t\t\t}\n\n\t\t\tfloat varianceToRoughness( float variance ) {\n\n\t\t\t\tfloat roughness = 0.0;\n\n\t\t\t\tif ( variance >= v1 ) {\n\n\t\t\t\t\troughness = ( v0 - variance ) * ( r1 - r0 ) / ( v0 - v1 ) + r0;\n\n\t\t\t\t} else if ( variance >= v4 ) {\n\n\t\t\t\t\troughness = ( v1 - variance ) * ( r4 - r1 ) / ( v1 - v4 ) + r1;\n\n\t\t\t\t} else if ( variance >= v5 ) {\n\n\t\t\t\t\troughness = ( v4 - variance ) * ( r5 - r4 ) / ( v4 - v5 ) + r4;\n\n\t\t\t\t} else {\n\n\t\t\t\t\troughness = pow( 0.559 * variance, 0.25 ); // 0.559 = 1.0 / 1.79\n\n\t\t\t\t}\n\n\t\t\t\treturn roughness;\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = texture2D( roughnessMap, vUv, - 1.0 );\n\n\t\t\t\tif ( texelSize.x == 0.0 ) return;\n\n\t\t\t\tfloat roughness = gl_FragColor.g;\n\n\t\t\t\tfloat variance = roughnessToVariance( roughness );\n\n\t\t\t\tvec3 avgNormal;\n\n\t\t\t\tfor ( float x = - 1.0; x < 2.0; x += 2.0 ) {\n\n\t\t\t\t\tfor ( float y = - 1.0; y < 2.0; y += 2.0 ) {\n\n\t\t\t\t\t\tvec2 uv = vUv + vec2( x, y ) * 0.25 * texelSize;\n\n\t\t\t\t\t\tavgNormal += normalize( texture2D( normalMap, uv, - 1.0 ).xyz - 0.5 );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tvariance += 1.0 - 0.25 * length( avgNormal );\n\n\t\t\t\tgl_FragColor.g = varianceToRoughness( variance );\n\n\t\t\t}\n\t\t",blending:NoBlending,depthTest:false,depthWrite:false});shaderMaterial.type='RoughnessMipmapper';return shaderMaterial;}var deserializeUrl=function deserializeUrl(url){return!!url&&url!=='null'?toFullUrl(url):null;};var assertIsArCandidate=function assertIsArCandidate(){if(IS_WEBXR_AR_CANDIDATE){return;}var missingApis=[];if(!HAS_WEBXR_DEVICE_API){missingApis.push('WebXR Device API');}if(!HAS_WEBXR_HIT_TEST_API){missingApis.push('WebXR Hit Test API');}throw new Error("The following APIs are required for AR, but are missing in this browser: ".concat(missingApis.join(', ')));};var toFullUrl=function toFullUrl(partialUrl){var url=new URL(partialUrl,window.location.toString());return url.toString();};var throttle=function throttle(fn,ms){var timer=null;var throttled=function throttled(){if(timer!=null){return;}fn.apply(void 0,arguments);timer=self.setTimeout(function(){return timer=null;},ms);};throttled.flush=function(){if(timer!=null){self.clearTimeout(timer);timer=null;}};return throttled;};var debounce=function debounce(fn,ms){var timer=null;return function(){for(var _len=arguments.length,args=new Array(_len),_key4=0;_key4<_len;_key4++){args[_key4]=arguments[_key4];}if(timer!=null){self.clearTimeout(timer);}timer=self.setTimeout(function(){timer=null;fn.apply(void 0,args);},ms);};};var clamp=function clamp(value,lowerLimit,upperLimit){return Math.max(lowerLimit,Math.min(upperLimit,value));};var CAPPED_DEVICE_PIXEL_RATIO=1;var resolveDpr=function(){var HAS_META_VIEWPORT_TAG=function(){var metas=document.head!=null?Array.from(document.head.querySelectorAll('meta')):[];var _iterator4=_createForOfIteratorHelper(metas),_step4;try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var meta=_step4.value;if(meta.name==='viewport'){return true;}}}catch(err){_iterator4.e(err);}finally{_iterator4.f();}return false;}();if(!HAS_META_VIEWPORT_TAG){console.warn('No detected; will cap pixel density at 1.');}return function(){return HAS_META_VIEWPORT_TAG?window.devicePixelRatio:CAPPED_DEVICE_PIXEL_RATIO;};}();var isDebugMode=function(){var debugQueryParameterName='model-viewer-debug-mode';var debugQueryParameter=new RegExp("[?&]".concat(debugQueryParameterName,"(&|$)"));return function(){return self.ModelViewerElement&&self.ModelViewerElement.debugMode||self.location&&self.location.search&&self.location.search.match(debugQueryParameter);};}();var getFirstMapKey=function getFirstMapKey(map){if(map.keys!=null){return map.keys().next().value||null;}var firstKey=null;try{map.forEach(function(_value,key,_map){firstKey=key;throw new Error();});}catch(_error){}return firstKey;};var waitForEvent=function waitForEvent(target,eventName){var predicate=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;return new Promise(function(resolve){function handler(event){if(!predicate||predicate(event)){resolve(event);target.removeEventListener(eventName,handler);}}target.addEventListener(eventName,handler);});};var RADIUS=0.2;var LINE_WIDTH=0.03;var MAX_OPACITY=0.75;var SEGMENTS=12;var DELTA_PHI=Math.PI/(2*SEGMENTS);var vector2=new Vector2();var addCorner=function addCorner(vertices,cornerX,cornerY){var phi=cornerX>0?cornerY>0?0:-Math.PI/2:cornerY>0?Math.PI/2:Math.PI;for(var _i335=0;_i335<=SEGMENTS;++_i335){vertices.push(cornerX+(RADIUS-LINE_WIDTH)*Math.cos(phi),cornerY+(RADIUS-LINE_WIDTH)*Math.sin(phi),0,cornerX+RADIUS*Math.cos(phi),cornerY+RADIUS*Math.sin(phi),0);phi+=DELTA_PHI;}};var PlacementBox=/*#__PURE__*/function(_Mesh){_inherits(PlacementBox,_Mesh);var _super16=_createSuper(PlacementBox);function PlacementBox(model){var _this32;_classCallCheck(this,PlacementBox);var geometry=new BufferGeometry();var triangles=[];var vertices=[];var size=model.size,boundingBox=model.boundingBox;var x=size.x/2;var y=size.z/2;addCorner(vertices,x,y);addCorner(vertices,-x,y);addCorner(vertices,-x,-y);addCorner(vertices,x,-y);var numVertices=vertices.length/3;for(var _i336=0;_i3360;}},{key:"dispose",value:function dispose(){var _this$hitPlane=this.hitPlane,geometry=_this$hitPlane.geometry,material=_this$hitPlane.material;geometry.dispose();material.dispose();this.geometry.dispose();this.material.dispose();}},{key:"offsetHeight",set:function set(offset){this.position.y=this.shadowHeight+offset;},get:function get(){return this.position.y-this.shadowHeight;}},{key:"show",set:function set(visible){this.goalOpacity=visible?MAX_OPACITY:0;}}]);return PlacementBox;}(Mesh);var _a$5,_b$3,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x$1,_y$1,_z$1,_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12;var AR_SHADOW_INTENSITY=0.3;var ROTATION_RATE=1.5;var HIT_ANGLE_DEG=20;var INTRO_DAMPER_RATE=0.4;var SCALE_SNAP_HIGH=1.2;var SCALE_SNAP_LOW=1/SCALE_SNAP_HIGH;var MIN_VIEWPORT_SCALE=0.25;var ARStatus={NOT_PRESENTING:'not-presenting',SESSION_STARTED:'session-started',OBJECT_PLACED:'object-placed',FAILED:'failed'};var $presentedScene=Symbol('presentedScene');var $placementBox=Symbol('placementBox');var $lastTick=Symbol('lastTick');var $turntableRotation=Symbol('turntableRotation');var $oldShadowIntensity=Symbol('oldShadowIntensity');var $oldBackground=Symbol('oldBackground');var $rafId=Symbol('rafId');var $currentSession=Symbol('currentSession');var $tick=Symbol('tick');var $refSpace=Symbol('refSpace');var $viewerRefSpace=Symbol('viewerRefSpace');var $frame=Symbol('frame');var $initialized=Symbol('initialized');var $initialModelToWorld=Symbol('initialModelToWorld');var $placementComplete=Symbol('placementComplete');var $initialHitSource=Symbol('hitTestSource');var $transientHitTestSource=Symbol('transiertHitTestSource');var $inputSource=Symbol('inputSource');var $isTranslating=Symbol('isTranslating');var $isRotating=Symbol('isRotating');var $isScaling=Symbol('isScaling');var $lastDragPosition=Symbol('lastDragPosition');var $lastScalar=Symbol('lastScalar');var $goalPosition=Symbol('goalPosition');var $goalYaw=Symbol('goalYaw');var $goalScale=Symbol('goalScale');var $xDamper=Symbol('xDamper');var $yDamper=Symbol('yDamper');var $zDamper=Symbol('zDamper');var $yawDamper=Symbol('yawDamper');var $scaleDamper=Symbol('scaleDamper');var $damperRate=Symbol('damperRate');var $resolveCleanup=Symbol('resolveCleanup');var $exitWebXRButtonContainer=Symbol('exitWebXRButtonContainer');var $onWebXRFrame=Symbol('onWebXRFrame');var $postSessionCleanup=Symbol('postSessionCleanup');var $updateCamera=Symbol('updateCamera');var $placeInitially=Symbol('placeInitially');var $getHitPoint=Symbol('getHitPoint');var $onSelectStart=Symbol('onSelectStart');var $onSelectEnd=Symbol('onSelect');var $onUpdateScene=Symbol('onUpdateScene');var $fingerSeparation=Symbol('fingerSeparation');var $processInput=Symbol('processInput');var $moveScene=Symbol('moveScene');var $onExitWebXRButtonContainerClick=Symbol('onExitWebXRButtonContainerClick');var vector3$1=new Vector3();var matrix4=new Matrix4();var hitPosition=new Vector3();var ARRenderer=/*#__PURE__*/function(_EventDispatcher2){_inherits(ARRenderer,_EventDispatcher2);var _super17=_createSuper(ARRenderer);function ARRenderer(renderer){var _this33;_classCallCheck(this,ARRenderer);_this33=_super17.call(this);_this33.renderer=renderer;_this33.camera=new PerspectiveCamera();_this33[_a$5]=null;_this33[_b$3]=null;_this33[_c]=null;_this33[_d]=null;_this33[_e]=null;_this33[_f]=null;_this33[_g]=null;_this33[_h]=null;_this33[_j]=null;_this33[_k]=null;_this33[_l]=null;_this33[_m]=null;_this33[_o]=null;_this33[_p]=null;_this33[_q]=null;_this33[_r]=null;_this33[_s]=false;_this33[_t]=new Matrix4();_this33[_u]=false;_this33[_v]=false;_this33[_w]=false;_this33[_x$1]=false;_this33[_y$1]=new Vector3();_this33[_z$1]=0;_this33[_0]=new Vector3();_this33[_1]=0;_this33[_2]=1;_this33[_3]=new Damper();_this33[_4]=new Damper();_this33[_5]=new Damper();_this33[_6]=new Damper();_this33[_7]=new Damper();_this33[_8]=1;_this33[_9]=function(){return _this33.stopPresenting();};_this33[_10]=function(){if(_this33[$placementBox]!=null&&_this33.isPresenting){_this33[$placementBox].dispose();_this33[$placementBox]=new PlacementBox(_this33[$presentedScene].model);}};_this33[_11]=function(event){var hitSource=_this33[$transientHitTestSource];if(hitSource==null){return;}var fingers=_this33[$frame].getHitTestResultsForTransientInput(hitSource);var scene=_this33[$presentedScene];var box=_this33[$placementBox];if(fingers.length===1){_this33[$inputSource]=event.inputSource;var axes=_this33[$inputSource].gamepad.axes;var _hitPosition=box.getHit(_this33[$presentedScene],axes[0],axes[1]);box.show=true;if(_hitPosition!=null){_this33[$isTranslating]=true;_this33[$lastDragPosition].copy(_hitPosition);}else{_this33[$isRotating]=true;_this33[$lastScalar]=axes[0];}}else if(fingers.length===2&&scene.canScale){box.show=true;_this33[$isScaling]=true;_this33[$lastScalar]=_this33[$fingerSeparation](fingers)/scene.scale.x;}};_this33[_12]=function(){_this33[$isTranslating]=false;_this33[$isRotating]=false;_this33[$isScaling]=false;_this33[$inputSource]=null;_this33[$goalPosition].y+=_this33[$placementBox].offsetHeight*_this33[$presentedScene].scale.x;_this33[$placementBox].show=false;};_this33.threeRenderer=renderer.threeRenderer;_this33.camera.matrixAutoUpdate=false;return _this33;}_createClass(ARRenderer,[{key:"resolveARSession",value:function(){var _resolveARSession=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee8(scene){var session,gl,waitForXRAnimationFrame,_session$renderState$,framebuffer,framebufferWidth,framebufferHeight,exitButton;return regeneratorRuntime.wrap(function _callee8$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:assertIsArCandidate();_context9.next=3;return navigator.xr.requestSession('immersive-ar',{requiredFeatures:['hit-test'],optionalFeatures:['dom-overlay'],domOverlay:{root:scene.element.shadowRoot.querySelector('div.default')}});case 3:session=_context9.sent;gl=this.threeRenderer.context;_context9.next=7;return gl.makeXRCompatible();case 7:session.updateRenderState({baseLayer:new XRWebGLLayer(session,gl,{alpha:true})});waitForXRAnimationFrame=new Promise(function(resolve,_reject){session.requestAnimationFrame(function(){return resolve();});});_context9.next=11;return waitForXRAnimationFrame;case 11:scene.element[$onResize](window.screen);_session$renderState$=session.renderState.baseLayer,framebuffer=_session$renderState$.framebuffer,framebufferWidth=_session$renderState$.framebufferWidth,framebufferHeight=_session$renderState$.framebufferHeight;this.threeRenderer.setFramebuffer(framebuffer);this.threeRenderer.setPixelRatio(1);this.threeRenderer.setSize(framebufferWidth,framebufferHeight,false);exitButton=scene.element.shadowRoot.querySelector('.slot.exit-webxr-ar-button');exitButton.classList.add('enabled');exitButton.addEventListener('click',this[$onExitWebXRButtonContainerClick]);this[$exitWebXRButtonContainer]=exitButton;return _context9.abrupt("return",session);case 21:case"end":return _context9.stop();}}},_callee8,this);}));function resolveARSession(_x15){return _resolveARSession.apply(this,arguments);}return resolveARSession;}()},{key:"supportsPresentation",value:function(){var _supportsPresentation=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee9(){return regeneratorRuntime.wrap(function _callee9$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:_context10.prev=0;assertIsArCandidate();_context10.next=4;return navigator.xr.isSessionSupported('immersive-ar');case 4:return _context10.abrupt("return",_context10.sent);case 7:_context10.prev=7;_context10.t0=_context10["catch"](0);return _context10.abrupt("return",false);case 10:case"end":return _context10.stop();}}},_callee9,null,[[0,7]]);}));function supportsPresentation(){return _supportsPresentation.apply(this,arguments);}return supportsPresentation;}()},{key:"present",value:function(){var _present=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee10(scene){var _this34=this;var waitForAnimationFrame,currentSession,radians,ray;return regeneratorRuntime.wrap(function _callee10$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:if(this.isPresenting){console.warn('Cannot present while a model is already presenting');}waitForAnimationFrame=new Promise(function(resolve,_reject){requestAnimationFrame(function(){return resolve();});});scene.model.setHotspotsVisibility(false);scene.isDirty=true;_context11.next=6;return waitForAnimationFrame;case 6:this[$presentedScene]=scene;_context11.next=9;return this.resolveARSession(scene);case 9:currentSession=_context11.sent;currentSession.addEventListener('end',function(){_this34[$postSessionCleanup]();},{once:true});_context11.next=13;return currentSession.requestReferenceSpace('local');case 13:this[$refSpace]=_context11.sent;_context11.next=16;return currentSession.requestReferenceSpace('viewer');case 16:this[$viewerRefSpace]=_context11.sent;scene.setCamera(this.camera);this[$initialized]=false;this[$damperRate]=INTRO_DAMPER_RATE;this[$turntableRotation]=scene.yaw;scene.yaw=0;this[$goalYaw]=0;this[$goalScale]=1;this[$oldBackground]=scene.background;scene.background=null;this[$oldShadowIntensity]=scene.shadowIntensity;scene.setShadowIntensity(0);scene.addEventListener('model-load',this[$onUpdateScene]);radians=HIT_ANGLE_DEG*Math.PI/180;ray=new XRRay(new DOMPoint(0,0,0),{x:0,y:-Math.sin(radians),z:-Math.cos(radians)});currentSession.requestHitTestSource({space:this[$viewerRefSpace],offsetRay:ray}).then(function(hitTestSource){_this34[$initialHitSource]=hitTestSource;});this[$currentSession]=currentSession;this[$placementBox]=new PlacementBox(scene.model);this[$placementComplete]=false;this[$lastTick]=performance.now();this[$tick]();case 37:case"end":return _context11.stop();}}},_callee10,this);}));function present(_x16){return _present.apply(this,arguments);}return present;}()},{key:"stopPresenting",value:function(){var _stopPresenting=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee11(){var _this35=this;var cleanupPromise;return regeneratorRuntime.wrap(function _callee11$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:if(this.isPresenting){_context12.next=2;break;}return _context12.abrupt("return");case 2:cleanupPromise=new Promise(function(resolve){_this35[$resolveCleanup]=resolve;});_context12.prev=3;_context12.next=6;return this[$currentSession].end();case 6:_context12.next=8;return cleanupPromise;case 8:_context12.next=15;break;case 10:_context12.prev=10;_context12.t0=_context12["catch"](3);console.warn('Error while trying to end AR session');console.warn(_context12.t0);this[$postSessionCleanup]();case 15:case"end":return _context12.stop();}}},_callee11,this,[[3,10]]);}));function stopPresenting(){return _stopPresenting.apply(this,arguments);}return stopPresenting;}()},{key:(_a$5=$placementBox,_b$3=$lastTick,_c=$turntableRotation,_d=$oldShadowIntensity,_e=$oldBackground,_f=$rafId,_g=$currentSession,_h=$refSpace,_j=$viewerRefSpace,_k=$frame,_l=$initialHitSource,_m=$transientHitTestSource,_o=$inputSource,_p=$presentedScene,_q=$resolveCleanup,_r=$exitWebXRButtonContainer,_s=$initialized,_t=$initialModelToWorld,_u=$placementComplete,_v=$isTranslating,_w=$isRotating,_x$1=$isScaling,_y$1=$lastDragPosition,_z$1=$lastScalar,_0=$goalPosition,_1=$goalYaw,_2=$goalScale,_3=$xDamper,_4=$yDamper,_5=$zDamper,_6=$yawDamper,_7=$scaleDamper,_8=$damperRate,_9=$onExitWebXRButtonContainerClick,$postSessionCleanup),value:function value(){this.threeRenderer.setFramebuffer(null);var session=this[$currentSession];if(session!=null){session.removeEventListener('selectstart',this[$onSelectStart]);session.removeEventListener('selectend',this[$onSelectEnd]);session.cancelAnimationFrame(this[$rafId]);this[$currentSession]=null;}var scene=this[$presentedScene];if(scene!=null){var model=scene.model,element=scene.element;scene.setCamera(scene.camera);model.remove(this[$placementBox]);scene.position.set(0,0,0);scene.scale.set(1,1,1);model.setShadowScaleAndOffset(1,0);var yaw=this[$turntableRotation];if(yaw!=null){scene.yaw=yaw;}var intensity=this[$oldShadowIntensity];if(intensity!=null){scene.setShadowIntensity(intensity);}var background=this[$oldBackground];if(background!=null){scene.background=background;}scene.removeEventListener('model-load',this[$onUpdateScene]);model.orientHotspots(0);element.requestUpdate('cameraTarget');element[$onResize](element.getBoundingClientRect());}this.renderer.height=0;var exitButton=this[$exitWebXRButtonContainer];if(exitButton!=null){exitButton.classList.remove('enabled');exitButton.removeEventListener('click',this[$onExitWebXRButtonContainerClick]);this[$exitWebXRButtonContainer]=null;}var hitSource=this[$transientHitTestSource];if(hitSource!=null){hitSource.cancel();this[$transientHitTestSource]=null;}var hitSourceInitial=this[$initialHitSource];if(hitSourceInitial!=null){hitSourceInitial.cancel();this[$initialHitSource]=null;}if(this[$placementBox]!=null){this[$placementBox].dispose();this[$placementBox]=null;}this[$lastTick]=null;this[$turntableRotation]=null;this[$oldShadowIntensity]=null;this[$oldBackground]=null;this[$rafId]=null;this[$refSpace]=null;this[$presentedScene]=null;this[$viewerRefSpace]=null;this[$frame]=null;this[$inputSource]=null;if(this[$resolveCleanup]!=null){this[$resolveCleanup]();}this.dispatchEvent({type:'status',status:ARStatus.NOT_PRESENTING});}},{key:"updateTarget",value:function updateTarget(){var scene=this[$presentedScene];if(scene!=null){var _target3=scene.getTarget();scene.setTarget(_target3.x,scene.model.boundingBox.min.y,_target3.z);}}},{key:(_10=$onUpdateScene,$updateCamera),value:function value(view){var camera=this.camera;var cameraMatrix=camera.matrix;cameraMatrix.fromArray(view.transform.matrix);camera.updateMatrixWorld(true);camera.position.setFromMatrixPosition(cameraMatrix);if(this[$initialHitSource]!=null){var _this$$presentedScene=this[$presentedScene],position=_this$$presentedScene.position,model=_this$$presentedScene.model;var radius=model.idealCameraDistance;camera.getWorldDirection(position);position.multiplyScalar(radius);position.add(camera.position);}if(!this[$initialized]){camera.projectionMatrix.fromArray(view.projectionMatrix);camera.projectionMatrixInverse.getInverse(camera.projectionMatrix);var _camera$position=camera.position,x=_camera$position.x,z=_camera$position.z;var scene=this[$presentedScene];scene.pointTowards(x,z);scene.model.updateMatrixWorld(true);this[$goalYaw]=scene.yaw;this[$initialModelToWorld].copy(scene.model.matrixWorld);scene.model.setHotspotsVisibility(true);this[$initialized]=true;this.dispatchEvent({type:'status',status:ARStatus.SESSION_STARTED});}if(view.requestViewportScale&&view.recommendedViewportScale){var scale=view.recommendedViewportScale;view.requestViewportScale(Math.max(scale,MIN_VIEWPORT_SCALE));}var layer=this[$currentSession].renderState.baseLayer;var viewport=layer.getViewport(view);this.threeRenderer.setViewport(viewport.x,viewport.y,viewport.width,viewport.height);this[$presentedScene].model.orientHotspots(Math.atan2(cameraMatrix.elements[1],cameraMatrix.elements[5]));}},{key:$placeInitially,value:function value(frame){var _this36=this;var hitSource=this[$initialHitSource];if(hitSource==null){return;}var hitTestResults=frame.getHitTestResults(hitSource);if(hitTestResults.length==0){return;}var hit=hitTestResults[0];var hitMatrix=this[$getHitPoint](hit);if(hitMatrix==null){return;}this.placeModel(hitMatrix);hitSource.cancel();this[$initialHitSource]=null;var session=frame.session;session.addEventListener('selectstart',this[$onSelectStart]);session.addEventListener('selectend',this[$onSelectEnd]);session.requestHitTestSourceForTransientInput({profile:'generic-touchscreen'}).then(function(hitTestSource){_this36[$transientHitTestSource]=hitTestSource;});}},{key:$getHitPoint,value:function value(hitResult){var pose=hitResult.getPose(this[$refSpace]);if(pose==null){return null;}var hitMatrix=matrix4.fromArray(pose.transform.matrix);return hitMatrix.elements[5]>0.75?hitPosition.setFromMatrixPosition(hitMatrix):null;}},{key:"placeModel",value:function placeModel(hit){var scene=this[$presentedScene];var model=scene.model;var _model$boundingBox=model.boundingBox,min=_model$boundingBox.min,max=_model$boundingBox.max;this[$placementBox].show=true;var goal=this[$goalPosition];goal.copy(hit);var floor=hit.y;var origin=this.camera.position.clone();var direction=hit.clone().sub(origin).normalize();origin.sub(direction.multiplyScalar(model.idealCameraDistance));var ray=new Ray(origin,direction.normalize());var modelToWorld=this[$initialModelToWorld];var modelPosition=new Vector3().setFromMatrixPosition(modelToWorld).add(hit);modelToWorld.setPosition(modelPosition);var world2Model=new Matrix4().getInverse(modelToWorld);ray.applyMatrix4(world2Model);max.y+=10;ray.intersectBox(model.boundingBox,modelPosition);max.y-=10;if(modelPosition!=null){modelPosition.applyMatrix4(modelToWorld);goal.add(hit).sub(modelPosition);}var target=scene.getTarget();scene.setTarget(target.x,min.y,target.z);goal.y=floor;this.dispatchEvent({type:'status',status:ARStatus.OBJECT_PLACED});}},{key:(_11=$onSelectStart,_12=$onSelectEnd,$fingerSeparation),value:function value(fingers){var fingerOne=fingers[0].inputSource.gamepad.axes;var fingerTwo=fingers[1].inputSource.gamepad.axes;var deltaX=fingerTwo[0]-fingerOne[0];var deltaY=fingerTwo[1]-fingerOne[1];return Math.sqrt(deltaX*deltaX+deltaY*deltaY);}},{key:$processInput,value:function value(frame){var _this37=this;var hitSource=this[$transientHitTestSource];if(hitSource==null){return;}if(!this[$isTranslating]&&!this[$isScaling]&&!this[$isRotating]){return;}var fingers=frame.getHitTestResultsForTransientInput(hitSource);var scene=this[$presentedScene];var scale=scene.scale.x;if(this[$isScaling]){if(fingers.length<2){this[$isScaling]=false;}else{var separation=this[$fingerSeparation](fingers);var _scale2=separation/this[$lastScalar];this[$goalScale]=_scale2SCALE_SNAP_LOW?1:_scale2;}return;}else if(fingers.length===2&&scene.canScale){this[$isTranslating]=false;this[$isRotating]=false;this[$isScaling]=true;this[$lastScalar]=this[$fingerSeparation](fingers)/scale;return;}if(this[$isRotating]){var thisDragX=this[$inputSource].gamepad.axes[0];this[$goalYaw]+=(thisDragX-this[$lastScalar])*ROTATION_RATE;this[$lastScalar]=thisDragX;}else if(this[$isTranslating]){fingers.forEach(function(finger){if(finger.inputSource!==_this37[$inputSource]||finger.results.length<1){return;}var hit=_this37[$getHitPoint](finger.results[0]);if(hit==null){return;}_this37[$goalPosition].sub(_this37[$lastDragPosition]);var offset=hit.y-_this37[$lastDragPosition].y;if(offset<0){_this37[$placementBox].offsetHeight=offset/scale;_this37[$presentedScene].model.setShadowScaleAndOffset(scale,offset);var cameraPosition=vector3$1.copy(_this37.camera.position);var alpha=-offset/(cameraPosition.y-hit.y);cameraPosition.multiplyScalar(alpha);hit.multiplyScalar(1-alpha).add(cameraPosition);}_this37[$goalPosition].add(hit);_this37[$lastDragPosition].copy(hit);});}}},{key:$moveScene,value:function value(delta){var scene=this[$presentedScene];var model=scene.model,position=scene.position,yaw=scene.yaw;var radius=model.idealCameraDistance;var goal=this[$goalPosition];var oldScale=scene.scale.x;var box=this[$placementBox];if(this[$initialHitSource]==null&&(!goal.equals(position)||this[$goalScale]!==oldScale)){var x=position.x,y=position.y,z=position.z;delta*=this[$damperRate];x=this[$xDamper].update(x,goal.x,delta,radius);y=this[$yDamper].update(y,goal.y,delta,radius);z=this[$zDamper].update(z,goal.z,delta,radius);position.set(x,y,z);var newScale=this[$scaleDamper].update(oldScale,this[$goalScale],delta,1);scene.scale.set(newScale,newScale,newScale);if(!this[$isTranslating]){var offset=goal.y-y;if(this[$placementComplete]){box.offsetHeight=offset/newScale;model.setShadowScaleAndOffset(newScale,offset);}else if(offset===0){this[$placementComplete]=true;box.show=false;scene.setShadowIntensity(AR_SHADOW_INTENSITY);this[$damperRate]=1;}}}box.updateOpacity(delta);scene.updateTarget(delta);scene.updateMatrixWorld(true);scene.yaw=this[$yawDamper].update(yaw,this[$goalYaw],delta,Math.PI);}},{key:$tick,value:function value(){var _this38=this;this[$rafId]=this[$currentSession].requestAnimationFrame(function(time,frame){return _this38[$onWebXRFrame](time,frame);});}},{key:$onWebXRFrame,value:function value(time,frame){this[$frame]=frame;var pose=frame.getViewerPose(this[$refSpace]);this[$tick]();var scene=this[$presentedScene];if(pose==null||scene==null){return;}var isFirstView=true;var _iterator5=_createForOfIteratorHelper(pose.views),_step5;try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var _view3=_step5.value;this[$updateCamera](_view3);if(isFirstView){this[$placeInitially](frame);this[$processInput](frame);var delta=time-this[$lastTick];this[$moveScene](delta);this.renderer.preRender(scene,time,delta);this[$lastTick]=time;}this.threeRenderer.render(scene,this.camera);isFirstView=false;}}catch(err){_iterator5.e(err);}finally{_iterator5.f();}}},{key:"presentedScene",get:function get(){return this[$presentedScene];}},{key:"isPresenting",get:function get(){return this[$presentedScene]!=null;}}]);return ARRenderer;}(EventDispatcher);var Debugger=/*#__PURE__*/function(){function Debugger(renderer){_classCallCheck(this,Debugger);renderer.threeRenderer.debug={checkShaderErrors:true};Promise.resolve().then(function(){self.dispatchEvent(new CustomEvent('model-viewer-renderer-debug',{detail:{renderer:renderer,THREE:{ShaderMaterial:ShaderMaterial,Texture:Texture,Mesh:Mesh,Scene:Scene,PlaneBufferGeometry:PlaneBufferGeometry,OrthographicCamera:OrthographicCamera,WebGLRenderTarget:WebGLRenderTarget}}}));});}_createClass(Debugger,[{key:"addScene",value:function addScene(scene){self.dispatchEvent(new CustomEvent('model-viewer-scene-added-debug',{detail:{scene:scene}}));}},{key:"removeScene",value:function removeScene(scene){self.dispatchEvent(new CustomEvent('model-viewer-scene-removed-debug',{detail:{scene:scene}}));}}]);return Debugger;}();var $threeGLTF=Symbol('threeGLTF');var $gltf=Symbol('gltf');var $gltfElementMap=Symbol('gltfElementMap');var $threeObjectMap=Symbol('threeObjectMap');var $parallelTraverseThreeScene=Symbol('parallelTraverseThreeScene');var $correlateOriginalThreeGLTF=Symbol('correlateOriginalThreeGLTF');var $correlateCloneThreeGLTF=Symbol('correlateCloneThreeGLTF');/** * The Three.js GLTFLoader provides us with an in-memory representation * of a glTF in terms of Three.js constructs. It also provides us with a copy * of the deserialized glTF without any Three.js decoration, and a mapping of * glTF elements to their corresponding Three.js constructs. * * A CorrelatedSceneGraph exposes a synchronously available mapping of glTF * element references to their corresponding Three.js constructs. */var CorrelatedSceneGraph=/*#__PURE__*/function(){function CorrelatedSceneGraph(threeGLTF,gltf,threeObjectMap,gltfElementMap){_classCallCheck(this,CorrelatedSceneGraph);this[$threeGLTF]=threeGLTF;this[$gltf]=gltf;this[$gltfElementMap]=gltfElementMap;this[$threeObjectMap]=threeObjectMap;}/** * Produce a CorrelatedSceneGraph from a naturally generated Three.js GLTF. * Such GLTFs are produced by Three.js' GLTFLoader, and contain cached * details that expedite the correlation step. * * If a CorrelatedSceneGraph is provided as the second argument, re-correlates * a cloned Three.js GLTF with a clone of the glTF hierarchy used to produce * the upstream Three.js GLTF that the clone was created from. The result * CorrelatedSceneGraph is representative of the cloned hierarchy. */_createClass(CorrelatedSceneGraph,[{key:"threeGLTF",/** * The source Three.js GLTF result given to us by a Three.js GLTFLoader. */get:function get(){return this[$threeGLTF];}/** * The in-memory deserialized source glTF. */},{key:"gltf",get:function get(){return this[$gltf];}/** * A Map of glTF element references to arrays of corresponding Three.js * object references. Three.js objects are kept in arrays to account for * cases where more than one Three.js object corresponds to a single glTF * element. */},{key:"gltfElementMap",get:function get(){return this[$gltfElementMap];}/** * A map of individual Three.js objects to corresponding elements in the * source glTF. */},{key:"threeObjectMap",get:function get(){return this[$threeObjectMap];}}],[{key:"from",value:function from(threeGLTF,upstreamCorrelatedSceneGraph){if(upstreamCorrelatedSceneGraph!=null){return this[$correlateCloneThreeGLTF](threeGLTF,upstreamCorrelatedSceneGraph);}else{return this[$correlateOriginalThreeGLTF](threeGLTF);}}},{key:$correlateOriginalThreeGLTF,value:function value(threeGLTF){var gltf=threeGLTF.parser.json;var associations=threeGLTF.parser.associations;var gltfElementMap=new Map();// NOTE: IE11 does not have Map iterator methods associations.forEach(function(gltfElementReference,threeObject){// Note: GLTFLoader creates a "default" material that has no corresponding // glTF element in the case that no materials are specified in the source // glTF. This means that for basic models without any of their own // materials, we might accidentally try to present a configurable glTF // material that doesn't exist. It might be valuable to make this default // material configurable in the future, but for now we ignore it. if(gltfElementReference==null){return;}var type=gltfElementReference.type,index=gltfElementReference.index;var elementArray=gltf[type]||[];var gltfElement=elementArray[index];if(gltfElement==null){// TODO: Maybe throw here... return;}var threeObjects=gltfElementMap.get(gltfElement);if(threeObjects==null){threeObjects=new Set();gltfElementMap.set(gltfElement,threeObjects);}threeObjects.add(threeObject);});return new CorrelatedSceneGraph(threeGLTF,gltf,associations,gltfElementMap);}/** * Transfers the association between a raw glTF and a Three.js scene graph * to a clone of the Three.js scene graph, resolved as a new * CorrelatedsceneGraph instance. */},{key:$correlateCloneThreeGLTF,value:function value(cloneThreeGLTF,upstreamCorrelatedSceneGraph){var originalThreeGLTF=upstreamCorrelatedSceneGraph.threeGLTF;var originalGLTF=upstreamCorrelatedSceneGraph.gltf;var cloneGLTF=JSON.parse(JSON.stringify(originalGLTF));var cloneThreeObjectMap=new Map();var cloneGLTFELementMap=new Map();for(var _i337=0;_i337',alphaChunk);}:function(shader){shader.fragmentShader=shader.fragmentShader.replace('#include ',alphaChunk);oldOnBeforeCompile(shader,undefined);};clone.shadowSide=FrontSide;if(clone.transparent){clone.depthWrite=false;}if(!clone.alphaTest&&!clone.transparent){clone.alphaTest=-0.5;}sourceUUIDToClonedMaterial.set(material.uuid,clone);return clone;}},{key:"correlatedSceneGraph",get:function get(){return this[$preparedGLTF][$correlatedSceneGraph];}}],[{key:$prepare,value:function value(source){var prepared=_get(_getPrototypeOf(ModelViewerGLTFInstance),$prepare,this).call(this,source);if(prepared[$correlatedSceneGraph]==null){prepared[$correlatedSceneGraph]=CorrelatedSceneGraph.from(prepared);}var scene=prepared.scene;var meshesToDuplicate=[];scene.traverse(function(node){node.renderOrder=1000;node.frustumCulled=false;if(!node.name){node.name=node.uuid;}if(!node.isMesh){return;}node.castShadow=true;var mesh=node;var transparent=false;var materials=Array.isArray(mesh.material)?mesh.material:[mesh.material];materials.forEach(function(material){if(material.isMeshStandardMaterial){if(material.transparent&&material.side===DoubleSide){transparent=true;material.side=FrontSide;}Renderer.singleton.roughnessMipmapper.generateMipmaps(material);}});if(transparent){meshesToDuplicate.push(mesh);}});for(var _i340=0,_meshesToDuplicate=meshesToDuplicate;_i340<_meshesToDuplicate.length;_i340++){var mesh=_meshesToDuplicate[_i340];var materials=Array.isArray(mesh.material)?mesh.material:[mesh.material];var duplicateMaterials=materials.map(function(material){var backMaterial=material.clone();backMaterial.side=BackSide;return backMaterial;});var duplicateMaterial=Array.isArray(mesh.material)?duplicateMaterials:duplicateMaterials[0];var meshBack=new Mesh(mesh.geometry,duplicateMaterial);meshBack.renderOrder=-1;mesh.add(meshBack);}return prepared;}}]);return ModelViewerGLTFInstance;}(GLTFInstance);// https://github.com/mrdoob/three.js/issues/5552 // http://en.wikipedia.org/wiki/RGBE_image_format var RGBELoader=function RGBELoader(manager){DataTextureLoader.call(this,manager);this.type=UnsignedByteType;};RGBELoader.prototype=Object.assign(Object.create(DataTextureLoader.prototype),{constructor:RGBELoader,// adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html parse:function parse(buffer){var/* return codes for rgbe routines */ //RGBE_RETURN_SUCCESS = 0, RGBE_RETURN_FAILURE=-1,/* default error routine. change this to change error handling */rgbe_read_error=1,rgbe_write_error=2,rgbe_format_error=3,rgbe_memory_error=4,rgbe_error=function rgbe_error(rgbe_error_code,msg){switch(rgbe_error_code){case rgbe_read_error:console.error("RGBELoader Read Error: "+(msg||''));break;case rgbe_write_error:console.error("RGBELoader Write Error: "+(msg||''));break;case rgbe_format_error:console.error("RGBELoader Bad File Format: "+(msg||''));break;default:case rgbe_memory_error:console.error("RGBELoader: Error: "+(msg||''));}return RGBE_RETURN_FAILURE;},/* offsets to red, green, and blue components in a data (float) pixel */ //RGBE_DATA_RED = 0, //RGBE_DATA_GREEN = 1, //RGBE_DATA_BLUE = 2, /* number of floats per pixel, use 4 since stored in rgba image format */ //RGBE_DATA_SIZE = 4, /* flags indicating which fields in an rgbe_header_info are valid */RGBE_VALID_PROGRAMTYPE=1,RGBE_VALID_FORMAT=2,RGBE_VALID_DIMENSIONS=4,NEWLINE="\n",fgets=function fgets(buffer,lineLimit,consume){lineLimit=!lineLimit?1024:lineLimit;var p=buffer.pos,i=-1,len=0,s='',chunkSize=128,chunk=String.fromCharCode.apply(null,new Uint16Array(buffer.subarray(p,p+chunkSize)));while(0>(i=chunk.indexOf(NEWLINE))&&len=0; i--) { byteCode = m.charCodeAt(i); if (byteCode > 0x7f && byteCode <= 0x7ff) byteLen++; else if (byteCode > 0x7ff && byteCode <= 0xffff) byteLen += 2; if (byteCode >= 0xDC00 && byteCode <= 0xDFFF) i--; //trail surrogate }*/if(false!==consume)buffer.pos+=len+i+1;return s+chunk.slice(0,i);}return false;},/* minimal header reading. modify if you want to parse more information */RGBE_ReadHeader=function RGBE_ReadHeader(buffer){var line,match,// regexes to parse header info fields magic_token_re=/^#\?(\S+)$/,gamma_re=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,exposure_re=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,format_re=/^\s*FORMAT=(\S+)\s*$/,dimensions_re=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,// RGBE format header struct header={valid:0,/* indicate which fields are valid */string:'',/* the actual header string */comments:'',/* comments found in header */programtype:'RGBE',/* listed at beginning of file to identify it after "#?". defaults to "RGBE" */format:'',/* RGBE format, default 32-bit_rle_rgbe */gamma:1.0,/* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */exposure:1.0,/* a value of 1.0 in an image corresponds to watts/steradian/m^2. defaults to 1.0 */width:0,height:0/* image dimensions, width/height */};if(buffer.pos>=buffer.byteLength||!(line=fgets(buffer))){return rgbe_error(rgbe_read_error,"no header found");}/* if you want to require the magic token then uncomment the next line */if(!(match=line.match(magic_token_re))){return rgbe_error(rgbe_format_error,"bad initial token");}header.valid|=RGBE_VALID_PROGRAMTYPE;header.programtype=match[1];header.string+=line+"\n";while(true){line=fgets(buffer);if(false===line)break;header.string+=line+"\n";if('#'===line.charAt(0)){header.comments+=line+"\n";continue;// comment line }if(match=line.match(gamma_re)){header.gamma=parseFloat(match[1],10);}if(match=line.match(exposure_re)){header.exposure=parseFloat(match[1],10);}if(match=line.match(format_re)){header.valid|=RGBE_VALID_FORMAT;header.format=match[1];//'32-bit_rle_rgbe'; }if(match=line.match(dimensions_re)){header.valid|=RGBE_VALID_DIMENSIONS;header.height=parseInt(match[1],10);header.width=parseInt(match[2],10);}if(header.valid&RGBE_VALID_FORMAT&&header.valid&RGBE_VALID_DIMENSIONS)break;}if(!(header.valid&RGBE_VALID_FORMAT)){return rgbe_error(rgbe_format_error,"missing format specifier");}if(!(header.valid&RGBE_VALID_DIMENSIONS)){return rgbe_error(rgbe_format_error,"missing image size specifier");}return header;},RGBE_ReadPixels_RLE=function RGBE_ReadPixels_RLE(buffer,w,h){var data_rgba,offset,pos,count,byteValue,scanline_buffer,ptr,ptr_end,i,l,off,isEncodedRun,scanline_width=w,num_scanlines=h,rgbeStart;if(// run length encoding is not allowed so read flat scanline_width<8||scanline_width>0x7fff||// this file is not run length encoded 2!==buffer[0]||2!==buffer[1]||buffer[2]&0x80){// return the flat buffer return new Uint8Array(buffer);}if(scanline_width!==(buffer[2]<<8|buffer[3])){return rgbe_error(rgbe_format_error,"wrong scanline width");}data_rgba=new Uint8Array(4*w*h);if(!data_rgba.length){return rgbe_error(rgbe_memory_error,"unable to allocate buffer space");}offset=0;pos=0;ptr_end=4*scanline_width;rgbeStart=new Uint8Array(4);scanline_buffer=new Uint8Array(ptr_end);// read in each successive scanline while(num_scanlines>0&&posbuffer.byteLength){return rgbe_error(rgbe_read_error);}rgbeStart[0]=buffer[pos++];rgbeStart[1]=buffer[pos++];rgbeStart[2]=buffer[pos++];rgbeStart[3]=buffer[pos++];if(2!=rgbeStart[0]||2!=rgbeStart[1]||(rgbeStart[2]<<8|rgbeStart[3])!=scanline_width){return rgbe_error(rgbe_format_error,"bad rgbe scanline format");}// read each of the four channels for the scanline into the buffer // first red, then green, then blue, then exponent ptr=0;while(ptr128;if(isEncodedRun)count-=128;if(0===count||ptr+count>ptr_end){return rgbe_error(rgbe_format_error,"bad scanline data");}if(isEncodedRun){// a (encoded) run of the same value byteValue=buffer[pos++];for(i=0;i>16&0x8000;/* Get the sign */var m=x>>12&0x07ff;/* Keep one extra bit for rounding */var e=x>>23&0xff;/* Using int is faster here */ /* If zero, or denormal, or exponent underflows too much for a denormal * half, return signed zero. */if(e<103)return bits;/* If NaN, return NaN. If Inf or exponent overflow, return Inf. */if(e>142){bits|=0x7c00;/* If exponent was 0xff and one mantissa bit was set, it means NaN, * not Inf, so make sure we set one mantissa bit too. */bits|=(e==255?0:1)&&x&0x007fffff;return bits;}/* If exponent underflows but not too much, return a denormal */if(e<113){m|=0x0800;/* Extra rounding may overflow and set mantissa to 0 and exponent * to 1, which is OK. */bits|=(m>>114-e)+(m>>113-e&1);return bits;}bits|=e-112<<10|m>>1;/* Extra rounding. An overflow will set mantissa to 0 and increment * the exponent, which is OK. */bits+=m&1;return bits;}return function(sourceArray,sourceOffset,destArray,destOffset){var e=sourceArray[sourceOffset+3];var scale=Math.pow(2.0,e-128.0)/255.0;destArray[destOffset+0]=toHalf(sourceArray[sourceOffset+0]*scale);destArray[destOffset+1]=toHalf(sourceArray[sourceOffset+1]*scale);destArray[destOffset+2]=toHalf(sourceArray[sourceOffset+2]*scale);};}();var byteArray=new Uint8Array(buffer);byteArray.pos=0;var rgbe_header_info=RGBE_ReadHeader(byteArray);if(RGBE_RETURN_FAILURE!==rgbe_header_info){var w=rgbe_header_info.width,h=rgbe_header_info.height,image_rgba_data=RGBE_ReadPixels_RLE(byteArray.subarray(byteArray.pos),w,h);if(RGBE_RETURN_FAILURE!==image_rgba_data){switch(this.type){case UnsignedByteType:var data=image_rgba_data;var format=RGBEFormat;// handled as THREE.RGBAFormat in shaders var type=UnsignedByteType;break;case FloatType:var numElements=image_rgba_data.length/4*3;var floatArray=new Float32Array(numElements);for(var j=0;j1&&_args12[1]!==undefined?_args12[1]:function(){};_context13.prev=1;isHDR=HDR_FILE_RE.test(url);_loader2=isHDR?hdrLoader:ldrLoader;_context13.next=6;return new Promise(function(resolve,reject){return _loader2.load(url,resolve,function(event){progressCallback(event.loaded/event.total*0.9);},reject);});case 6:texture=_context13.sent;progressCallback(1.0);this.addMetadata(texture,url);texture.mapping=EquirectangularReflectionMapping;if(isHDR){texture.encoding=RGBEEncoding;texture.minFilter=NearestFilter;texture.magFilter=NearestFilter;texture.flipY=true;}else{texture.encoding=GammaEncoding;}return _context13.abrupt("return",texture);case 12:_context13.prev=12;if(progressCallback){progressCallback(1);}return _context13.finish(12);case 15:case"end":return _context13.stop();}}},_callee12,this,[[1,,12,15]]);}));function load(_x17){return _load2.apply(this,arguments);}return load;}()},{key:"generateEnvironmentMapAndSkybox",value:function(){var _generateEnvironmentMapAndSkybox=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee13(){var skyboxUrl,environmentMapUrl,options,progressTracker,updateGenerationProgress,skyboxLoads,environmentMapLoads,_yield$Promise$all,_yield$Promise$all2,environmentMap,skybox,_args13=arguments;return regeneratorRuntime.wrap(function _callee13$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:skyboxUrl=_args13.length>0&&_args13[0]!==undefined?_args13[0]:null;environmentMapUrl=_args13.length>1&&_args13[1]!==undefined?_args13[1]:null;options=_args13.length>2&&_args13[2]!==undefined?_args13[2]:{};progressTracker=options.progressTracker;updateGenerationProgress=progressTracker!=null?progressTracker.beginActivity():function(){};_context14.prev=5;skyboxLoads=Promise.resolve(null);if(!!skyboxUrl){skyboxLoads=this.loadSkyboxFromUrl(skyboxUrl,progressTracker);}if(!!environmentMapUrl){environmentMapLoads=this.loadEnvironmentMapFromUrl(environmentMapUrl,progressTracker);}else if(!!skyboxUrl){environmentMapLoads=this.loadEnvironmentMapFromUrl(skyboxUrl,progressTracker);}else{environmentMapLoads=this.loadGeneratedEnvironmentMap();}_context14.next=11;return Promise.all([environmentMapLoads,skyboxLoads]);case 11:_yield$Promise$all=_context14.sent;_yield$Promise$all2=_slicedToArray(_yield$Promise$all,2);environmentMap=_yield$Promise$all2[0];skybox=_yield$Promise$all2[1];if(!(environmentMap==null)){_context14.next=17;break;}throw new Error('Failed to load environment map.');case 17:return _context14.abrupt("return",{environmentMap:environmentMap,skybox:skybox});case 18:_context14.prev=18;updateGenerationProgress(1.0);return _context14.finish(18);case 21:case"end":return _context14.stop();}}},_callee13,this,[[5,,18,21]]);}));function generateEnvironmentMapAndSkybox(){return _generateEnvironmentMapAndSkybox.apply(this,arguments);}return generateEnvironmentMapAndSkybox;}()},{key:"addMetadata",value:function addMetadata(texture,url){if(texture==null){return;}texture.userData=Object.assign(Object.assign({},userData),{url:url});}},{key:"loadSkyboxFromUrl",value:function loadSkyboxFromUrl(url,progressTracker){if(!this.skyboxCache.has(url)){var progressCallback=progressTracker?progressTracker.beginActivity():function(){};var skyboxMapLoads=this.load(url,progressCallback);this.skyboxCache.set(url,skyboxMapLoads);}return this.skyboxCache.get(url);}},{key:"loadEnvironmentMapFromUrl",value:function loadEnvironmentMapFromUrl(url,progressTracker){var _this42=this;if(!this.environmentMapCache.has(url)){var environmentMapLoads=this.loadSkyboxFromUrl(url,progressTracker).then(function(equirect){var cubeUV=_this42.PMREMGenerator.fromEquirectangular(equirect);_this42.addMetadata(cubeUV.texture,url);return cubeUV;});this.PMREMGenerator.compileEquirectangularShader();this.environmentMapCache.set(url,environmentMapLoads);}return this.environmentMapCache.get(url);}},{key:"loadGeneratedEnvironmentMap",value:function loadGeneratedEnvironmentMap(){if(this.generatedEnvironmentMap==null){var defaultScene=new EnvironmentScene();this.generatedEnvironmentMap=this.PMREMGenerator.fromScene(defaultScene,GENERATED_SIGMA);this.addMetadata(this.generatedEnvironmentMap.texture,null);}return Promise.resolve(this.generatedEnvironmentMap);}},{key:"dispose",value:function(){var _dispose=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee14(){var allTargetsLoad,_i341,_allTargetsLoad,targetLoads,_target4;return regeneratorRuntime.wrap(function _callee14$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:allTargetsLoad=[];this.environmentMapCache.forEach(function(targetLoads){allTargetsLoad.push(targetLoads);});this.environmentMapCache.clear();_i341=0,_allTargetsLoad=allTargetsLoad;case 4:if(!(_i341<_allTargetsLoad.length)){_context15.next=18;break;}targetLoads=_allTargetsLoad[_i341];_context15.prev=6;_context15.next=9;return targetLoads;case 9:_target4=_context15.sent;_target4.dispose();_context15.next=15;break;case 13:_context15.prev=13;_context15.t0=_context15["catch"](6);case 15:_i341++;_context15.next=4;break;case 18:if(this.generatedEnvironmentMap!=null){this.generatedEnvironmentMap.dispose();this.generatedEnvironmentMap=null;}case 19:case"end":return _context15.stop();}}},_callee14,this,[[6,13]]);}));function dispose(){return _dispose.apply(this,arguments);}return dispose;}()}]);return TextureUtils;}(EventDispatcher);var _a$6,_b$4;var DURATION_DECAY=0.2;var LOW_FRAME_DURATION_MS=18;var HIGH_FRAME_DURATION_MS=26;var MAX_AVG_CHANGE_MS=2;var SCALE_STEP=0.79;var DEFAULT_MIN_SCALE=0.5;var $onWebGLContextLost=Symbol('onWebGLContextLost');var $webGLContextLostHandler=Symbol('webGLContextLostHandler');var $singleton=Symbol('singleton');var Renderer=/*#__PURE__*/function(_EventDispatcher4){_inherits(Renderer,_EventDispatcher4);var _super21=_createSuper(Renderer);function Renderer(options){var _this43;_classCallCheck(this,Renderer);_this43=_super21.call(this);_this43.loader=new CachingGLTFLoader(ModelViewerGLTFInstance);_this43.width=0;_this43.height=0;_this43.dpr=1;_this43.minScale=DEFAULT_MIN_SCALE;_this43.debugger=null;_this43.scenes=new Set();_this43.multipleScenesVisible=false;_this43.scale=1;_this43.avgFrameDuration=(HIGH_FRAME_DURATION_MS+LOW_FRAME_DURATION_MS)/2;_this43[_b$4]=function(event){return _this43[$onWebGLContextLost](event);};_this43.dpr=resolveDpr();_this43.canvasElement=document.createElement('canvas');_this43.canvasElement.id='webgl-canvas';_this43.canvas3D=_this43.canvasElement;_this43.canvas3D.addEventListener('webglcontextlost',_this43[$webGLContextLostHandler]);try{_this43.threeRenderer=new WebGL1Renderer({canvas:_this43.canvas3D,alpha:true,antialias:true,powerPreference:'high-performance',preserveDrawingBuffer:true});_this43.threeRenderer.autoClear=true;_this43.threeRenderer.outputEncoding=GammaEncoding;_this43.threeRenderer.gammaFactor=2.2;_this43.threeRenderer.physicallyCorrectLights=true;_this43.threeRenderer.setPixelRatio(1);_this43.threeRenderer.shadowMap.enabled=true;_this43.threeRenderer.shadowMap.type=PCFSoftShadowMap;_this43.threeRenderer.shadowMap.autoUpdate=false;_this43.debugger=options!=null&&!!options.debug?new Debugger(_assertThisInitialized(_this43)):null;_this43.threeRenderer.debug={checkShaderErrors:!!_this43.debugger};_this43.threeRenderer.toneMapping=ACESFilmicToneMapping;}catch(error){console.warn(error);}_this43.arRenderer=new ARRenderer(_assertThisInitialized(_this43));_this43.textureUtils=_this43.canRender?new TextureUtils(_this43.threeRenderer):null;_this43.roughnessMipmapper=new RoughnessMipmapper(_this43.threeRenderer);_this43.updateRendererSize();_this43.lastTick=performance.now();_this43.avgFrameDuration=0;return _this43;}_createClass(Renderer,[{key:"updateRendererSize",value:function updateRendererSize(){var dpr=resolveDpr();if(dpr!==this.dpr){var _iterator6=_createForOfIteratorHelper(this.scenes),_step6;try{for(_iterator6.s();!(_step6=_iterator6.n()).done;){var scene=_step6.value;var element=scene.element;element[$updateSize](element.getBoundingClientRect());}}catch(err){_iterator6.e(err);}finally{_iterator6.f();}}var width=0;var height=0;var _iterator7=_createForOfIteratorHelper(this.scenes),_step7;try{for(_iterator7.s();!(_step7=_iterator7.n()).done;){var _scene=_step7.value;width=Math.max(width,_scene.width);height=Math.max(height,_scene.height);}}catch(err){_iterator7.e(err);}finally{_iterator7.f();}if(width===this.width&&height===this.height&&dpr===this.dpr){return;}this.width=width;this.height=height;this.dpr=dpr;if(this.canRender){this.threeRenderer.setSize(width*dpr,height*dpr,false);}var widthCSS=width/this.scale;var heightCSS=height/this.scale;this.canvasElement.style.width="".concat(widthCSS,"px");this.canvasElement.style.height="".concat(heightCSS,"px");var _iterator8=_createForOfIteratorHelper(this.scenes),_step8;try{for(_iterator8.s();!(_step8=_iterator8.n()).done;){var _scene2=_step8.value;var canvas=_scene2.canvas;canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr);canvas.style.width="".concat(widthCSS,"px");canvas.style.height="".concat(heightCSS,"px");_scene2.isDirty=true;}}catch(err){_iterator8.e(err);}finally{_iterator8.f();}}},{key:"updateRendererScale",value:function updateRendererScale(){var scale=this.scale;if(this.avgFrameDuration>HIGH_FRAME_DURATION_MS&&scale>this.minScale){scale*=SCALE_STEP;}else if(this.avgFrameDuration0){this.threeRenderer.setAnimationLoop(function(time){return _this44.render(time);});}if(this.debugger!=null){this.debugger.addScene(scene);}}},{key:"unregisterScene",value:function unregisterScene(scene){this.scenes.delete(scene);if(this.canRender&&this.scenes.size===0){this.threeRenderer.setAnimationLoop(null);}if(this.debugger!=null){this.debugger.removeScene(scene);}}},{key:"displayCanvas",value:function displayCanvas(scene){return this.multipleScenesVisible?scene.element[$canvas]:this.canvasElement;}},{key:"selectCanvas",value:function selectCanvas(){var visibleScenes=0;var visibleInput=null;var _iterator10=_createForOfIteratorHelper(this.scenes),_step10;try{for(_iterator10.s();!(_step10=_iterator10.n()).done;){var scene=_step10.value;var element=scene.element;if(element.modelIsVisible){++visibleScenes;visibleInput=element[$userInputElement];}}}catch(err){_iterator10.e(err);}finally{_iterator10.f();}var multipleScenesVisible=visibleScenes>1||USE_OFFSCREEN_CANVAS;var canvasElement=this.canvasElement;if(multipleScenesVisible===this.multipleScenesVisible&&(multipleScenesVisible||canvasElement.parentElement===visibleInput)){return;}this.multipleScenesVisible=multipleScenesVisible;if(multipleScenesVisible){canvasElement.classList.remove('show');}var _iterator11=_createForOfIteratorHelper(this.scenes),_step11;try{for(_iterator11.s();!(_step11=_iterator11.n()).done;){var _scene3=_step11.value;var userInputElement=_scene3.element[$userInputElement];var canvas=_scene3.element[$canvas];if(multipleScenesVisible){canvas.classList.add('show');_scene3.isDirty=true;}else if(userInputElement===visibleInput){userInputElement.appendChild(canvasElement);canvasElement.classList.add('show');canvas.classList.remove('show');_scene3.isDirty=true;}}}catch(err){_iterator11.e(err);}finally{_iterator11.f();}}},{key:"orderedScenes",value:function orderedScenes(){var scenes=[];for(var _i342=0,_arr2=[false,true];_i342<_arr2.length;_i342++){var visible=_arr2[_i342];var _iterator12=_createForOfIteratorHelper(this.scenes),_step12;try{for(_iterator12.s();!(_step12=_iterator12.n()).done;){var scene=_step12.value;if(scene.element.modelIsVisible===visible){scenes.push(scene);}}}catch(err){_iterator12.e(err);}finally{_iterator12.f();}}return scenes;}},{key:"preRender",value:function preRender(scene,t,delta){var element=scene.element,exposure=scene.exposure,model=scene.model;element[$tick$1](t,delta);var exposureIsNumber=typeof exposure==='number'&&!self.isNaN(exposure);this.threeRenderer.toneMappingExposure=exposureIsNumber?exposure:1.0;if(model.updateShadow()){this.threeRenderer.shadowMap.needsUpdate=true;}}},{key:"render",value:function render(t){var delta=t-this.lastTick;this.lastTick=t;if(!this.canRender||this.isPresenting){return;}this.avgFrameDuration+=clamp(DURATION_DECAY*(delta-this.avgFrameDuration),-MAX_AVG_CHANGE_MS,MAX_AVG_CHANGE_MS);this.selectCanvas();this.updateRendererSize();this.updateRendererScale();var dpr=this.dpr,scale=this.scale;var _iterator13=_createForOfIteratorHelper(this.orderedScenes()),_step13;try{for(_iterator13.s();!(_step13=_iterator13.n()).done;){var scene=_step13.value;if(!scene.element[$sceneIsReady]()){continue;}this.preRender(scene,t,delta);if(!scene.isDirty){continue;}scene.isDirty=false;if(!scene.element.modelIsVisible&&!this.multipleScenesVisible){var _iterator14=_createForOfIteratorHelper(this.scenes),_step14;try{for(_iterator14.s();!(_step14=_iterator14.n()).done;){var _scene4=_step14.value;if(_scene4.element.modelIsVisible){_scene4.isDirty=true;}}}catch(err){_iterator14.e(err);}finally{_iterator14.f();}}var width=Math.min(Math.ceil(scene.width*scale*dpr),this.canvas3D.width);var height=Math.min(Math.ceil(scene.height*scale*dpr),this.canvas3D.height);this.threeRenderer.setRenderTarget(null);this.threeRenderer.setViewport(0,Math.floor(this.height*dpr)-height,width,height);this.threeRenderer.render(scene,scene.getCamera());if(this.multipleScenesVisible){if(scene.context==null){scene.createContext();}{var context2D=scene.context;context2D.clearRect(0,0,width,height);context2D.drawImage(this.canvas3D,0,0,width,height,0,0,width,height);}}}}catch(err){_iterator13.e(err);}finally{_iterator13.f();}}},{key:"dispose",value:function dispose(){if(this.textureUtils!=null){this.textureUtils.dispose();}if(this.threeRenderer!=null){this.threeRenderer.dispose();}this.textureUtils=null;this.threeRenderer=null;this.scenes.clear();this.canvas3D.removeEventListener('webglcontextlost',this[$webGLContextLostHandler]);}},{key:(_a$6=$singleton,_b$4=$webGLContextLostHandler,$onWebGLContextLost),value:function value(event){this.dispatchEvent({type:'contextlost',sourceEvent:event});}},{key:"canRender",get:function get(){return this.threeRenderer!=null;}},{key:"scaleFactor",get:function get(){return this.scale;}},{key:"isPresenting",get:function get(){return this.arRenderer.isPresenting;}}],[{key:"resetSingleton",value:function resetSingleton(){this[$singleton].dispose();this[$singleton]=new Renderer({debug:isDebugMode()});}},{key:"singleton",get:function get(){return this[$singleton];}}]);return Renderer;}(EventDispatcher);Renderer[_a$6]=new Renderer({debug:isDebugMode()});var dataUrlToBlob=/*#__PURE__*/function(){var _ref4=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee15(base64DataUrl){return regeneratorRuntime.wrap(function _callee15$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:return _context16.abrupt("return",new Promise(function(resolve,reject){var sliceSize=512;var typeMatch=base64DataUrl.match(/data:(.*);/);if(!typeMatch){return reject(new Error("".concat(base64DataUrl," is not a valid data Url")));}var type=typeMatch[1];var base64=base64DataUrl.replace(/data:image\/\w+;base64,/,'');var byteCharacters=atob(base64);var byteArrays=[];for(var offset=0;offset=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var _a$8,_b$6,_c$1,_d$1,_e$1,_f$1,_g$1,_h$1,_j$1,_k$1;var CLEAR_MODEL_TIMEOUT_MS=1000;var FALLBACK_SIZE_UPDATE_THRESHOLD_MS=50;var ANNOUNCE_MODEL_VISIBILITY_DEBOUNCE_THRESHOLD=0;var UNSIZED_MEDIA_WIDTH=300;var UNSIZED_MEDIA_HEIGHT=150;var blobCanvas=document.createElement('canvas');var blobContext=null;var $template=Symbol('template');var $fallbackResizeHandler=Symbol('fallbackResizeHandler');var $defaultAriaLabel=Symbol('defaultAriaLabel');var $resizeObserver=Symbol('resizeObserver');var $intersectionObserver=Symbol('intersectionObserver');var $clearModelTimeout=Symbol('clearModelTimeout');var $onContextLost=Symbol('onContextLost');var $contextLostHandler=Symbol('contextLostHandler');var $loaded=Symbol('loaded');var $updateSize=Symbol('updateSize');var $isElementInViewport=Symbol('isElementInViewport');var $announceModelVisibility=Symbol('announceModelVisibility');var $ariaLabel=Symbol('ariaLabel');var $loadedTime=Symbol('loadedTime');var $updateSource=Symbol('updateSource');var $markLoaded=Symbol('markLoaded');var $container=Symbol('container');var $userInputElement=Symbol('input');var $canvas=Symbol('canvas');var $scene=Symbol('scene');var $needsRender=Symbol('needsRender');var $tick$1=Symbol('tick');var $onModelLoad=Symbol('onModelLoad');var $onResize=Symbol('onResize');var $renderer=Symbol('renderer');var $progressTracker=Symbol('progressTracker');var $getLoaded=Symbol('getLoaded');var $getModelIsVisible=Symbol('getModelIsVisible');var $shouldAttemptPreload=Symbol('shouldAttemptPreload');var $sceneIsReady=Symbol('sceneIsReady');var $hasTransitioned=Symbol('hasTransitioned');var toVector3D=function toVector3D(v){return{x:v.x,y:v.y,z:v.z,toString:function toString(){return"".concat(this.x,"m ").concat(this.y,"m ").concat(this.z,"m");}};};var ModelViewerElementBase=/*#__PURE__*/function(_UpdatingElement){_inherits(ModelViewerElementBase,_UpdatingElement);var _super22=_createSuper(ModelViewerElementBase);function ModelViewerElementBase(){var _this47;_classCallCheck(this,ModelViewerElementBase);_this47=_super22.call(this);_this47.alt=null;_this47.src=null;_this47[_a$8]=false;_this47[_b$6]=false;_this47[_c$1]=0;_this47[_d$1]=null;_this47[_e$1]=debounce(function(){var boundingRect=_this47.getBoundingClientRect();_this47[$updateSize](boundingRect);},FALLBACK_SIZE_UPDATE_THRESHOLD_MS);_this47[_f$1]=debounce(function(oldVisibility){var newVisibility=_this47.modelIsVisible;if(newVisibility!==oldVisibility){_this47.dispatchEvent(new CustomEvent('model-visibility',{detail:{visible:newVisibility}}));}},ANNOUNCE_MODEL_VISIBILITY_DEBOUNCE_THRESHOLD);_this47[_g$1]=null;_this47[_h$1]=null;_this47[_j$1]=new ProgressTracker();_this47[_k$1]=function(event){return _this47[$onContextLost](event);};var template=_this47.constructor.template;if(window.ShadyCSS){window.ShadyCSS.styleElement(_assertThisInitialized(_this47),{});}_this47.attachShadow({mode:'open'});var shadowRoot=_this47.shadowRoot;shadowRoot.appendChild(template.content.cloneNode(true));_this47[$container]=shadowRoot.querySelector('.container');_this47[$userInputElement]=shadowRoot.querySelector('.userInput');_this47[$canvas]=shadowRoot.querySelector('canvas');_this47[$defaultAriaLabel]=_this47[$userInputElement].getAttribute('aria-label');var width,height;if(_this47.isConnected){var rect=_this47.getBoundingClientRect();width=rect.width;height=rect.height;}else{width=UNSIZED_MEDIA_WIDTH;height=UNSIZED_MEDIA_HEIGHT;}_this47[$scene]=new ModelScene({canvas:_this47[$canvas],element:_assertThisInitialized(_this47),width:width,height:height});_this47[$scene].addEventListener('model-load',function(event){_this47[$markLoaded]();_this47[$onModelLoad]();_this47.dispatchEvent(new CustomEvent('load',{detail:{url:event.url}}));});Promise.resolve().then(function(){_this47[$updateSize](_this47.getBoundingClientRect());});if(HAS_RESIZE_OBSERVER){_this47[$resizeObserver]=new ResizeObserver(function(entries){if(_this47[$renderer].isPresenting){return;}var _iterator16=_createForOfIteratorHelper(entries),_step16;try{for(_iterator16.s();!(_step16=_iterator16.n()).done;){var entry=_step16.value;if(entry.target===_assertThisInitialized(_this47)){_this47[$updateSize](entry.contentRect);}}}catch(err){_iterator16.e(err);}finally{_iterator16.f();}});}if(HAS_INTERSECTION_OBSERVER){_this47[$intersectionObserver]=new IntersectionObserver(function(entries){var _iterator17=_createForOfIteratorHelper(entries),_step17;try{for(_iterator17.s();!(_step17=_iterator17.n()).done;){var entry=_step17.value;if(entry.target===_assertThisInitialized(_this47)){var oldVisibility=_this47.modelIsVisible;_this47[$isElementInViewport]=entry.isIntersecting;_this47[$announceModelVisibility](oldVisibility);if(_this47[$isElementInViewport]&&!_this47[$sceneIsReady]()){_this47[$updateSource]();}}}}catch(err){_iterator17.e(err);}finally{_iterator17.f();}},{root:null,rootMargin:'0px',threshold:0});}else{_this47[$isElementInViewport]=true;}return _this47;}_createClass(ModelViewerElementBase,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(ModelViewerElementBase.prototype),"connectedCallback",this)&&_get(_getPrototypeOf(ModelViewerElementBase.prototype),"connectedCallback",this).call(this);if(HAS_RESIZE_OBSERVER){this[$resizeObserver].observe(this);}else{self.addEventListener('resize',this[$fallbackResizeHandler]);}if(HAS_INTERSECTION_OBSERVER){this[$intersectionObserver].observe(this);}var renderer=this[$renderer];renderer.addEventListener('contextlost',this[$contextLostHandler]);renderer.registerScene(this[$scene]);if(this[$clearModelTimeout]!=null){self.clearTimeout(this[$clearModelTimeout]);this[$clearModelTimeout]=null;this.requestUpdate('src',null);}}},{key:"disconnectedCallback",value:function disconnectedCallback(){var _this48=this;_get(_getPrototypeOf(ModelViewerElementBase.prototype),"disconnectedCallback",this)&&_get(_getPrototypeOf(ModelViewerElementBase.prototype),"disconnectedCallback",this).call(this);if(HAS_RESIZE_OBSERVER){this[$resizeObserver].unobserve(this);}else{self.removeEventListener('resize',this[$fallbackResizeHandler]);}if(HAS_INTERSECTION_OBSERVER){this[$intersectionObserver].unobserve(this);}var renderer=this[$renderer];renderer.removeEventListener('contextlost',this[$contextLostHandler]);renderer.unregisterScene(this[$scene]);this[$clearModelTimeout]=self.setTimeout(function(){_this48[$scene].model.clear();},CLEAR_MODEL_TIMEOUT_MS);}},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(ModelViewerElementBase.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('src')&&(this.src==null||this.src!==this[$scene].model.url)){this[$loaded]=false;this[$loadedTime]=0;this[$updateSource]();}if(changedProperties.has('alt')){var ariaLabel=this.alt==null?this[$defaultAriaLabel]:this.alt;this[$userInputElement].setAttribute('aria-label',ariaLabel);}}},{key:"toDataURL",value:function toDataURL(type,encoderOptions){return this[$renderer].displayCanvas(this[$scene]).toDataURL(type,encoderOptions);}},{key:"toBlob",value:function(){var _toBlob=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee17(options){var _this49=this;var mimeType,qualityArgument,idealAspect,_this$$scene,width,height,model,aspect,_this$$renderer,dpr,scaleFactor,outputWidth,outputHeight,offsetX,offsetY,oldHeight,oldWidth;return regeneratorRuntime.wrap(function _callee17$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:mimeType=options?options.mimeType:undefined;qualityArgument=options?options.qualityArgument:undefined;idealAspect=options?options.idealAspect:undefined;_this$$scene=this[$scene],width=_this$$scene.width,height=_this$$scene.height,model=_this$$scene.model,aspect=_this$$scene.aspect;_this$$renderer=this[$renderer],dpr=_this$$renderer.dpr,scaleFactor=_this$$renderer.scaleFactor;outputWidth=width*scaleFactor*dpr;outputHeight=height*scaleFactor*dpr;offsetX=0;offsetY=0;if(idealAspect===true){if(model.fieldOfViewAspect>aspect){oldHeight=outputHeight;outputHeight=Math.round(outputWidth/model.fieldOfViewAspect);offsetY=(oldHeight-outputHeight)/2;}else{oldWidth=outputWidth;outputWidth=Math.round(outputHeight*model.fieldOfViewAspect);offsetX=(oldWidth-outputWidth)/2;}}blobCanvas.width=outputWidth;blobCanvas.height=outputHeight;_context18.prev=12;return _context18.abrupt("return",new Promise(/*#__PURE__*/function(){var _ref5=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee16(resolve,reject){return regeneratorRuntime.wrap(function _callee16$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:if(blobContext==null){blobContext=blobCanvas.getContext('2d');}blobContext.drawImage(_this49[$renderer].displayCanvas(_this49[$scene]),offsetX,offsetY,outputWidth,outputHeight,0,0,outputWidth,outputHeight);if(!blobCanvas.msToBlob){_context17.next=5;break;}if(!(!mimeType||mimeType==='image/png')){_context17.next=5;break;}return _context17.abrupt("return",resolve(blobCanvas.msToBlob()));case 5:if(blobCanvas.toBlob){_context17.next=11;break;}_context17.t0=resolve;_context17.next=9;return dataUrlToBlob(blobCanvas.toDataURL(mimeType,qualityArgument));case 9:_context17.t1=_context17.sent;return _context17.abrupt("return",(0,_context17.t0)(_context17.t1));case 11:blobCanvas.toBlob(function(blob){if(!blob){return reject(new Error('Unable to retrieve canvas blob'));}resolve(blob);},mimeType,qualityArgument);case 12:case"end":return _context17.stop();}}},_callee16);}));return function(_x20,_x21){return _ref5.apply(this,arguments);};}()));case 14:_context18.prev=14;this[$updateSize]({width:width,height:height});return _context18.finish(14);case 17:case"end":return _context18.stop();}}},_callee17,this,[[12,,14,17]]);}));function toBlob(_x19){return _toBlob.apply(this,arguments);}return toBlob;}()},{key:$getLoaded,value:function value(){return this[$loaded];}},{key:$getModelIsVisible,value:function value(){return this.loaded&&this[$isElementInViewport];}},{key:$hasTransitioned,value:function value(){return this.modelIsVisible;}},{key:$shouldAttemptPreload,value:function value(){return!!this.src&&this[$isElementInViewport];}},{key:$sceneIsReady,value:function value(){return this[$loaded];}},{key:$updateSize,value:function value(_ref6){var width=_ref6.width,height=_ref6.height;this[$container].style.width="".concat(width,"px");this[$container].style.height="".concat(height,"px");this[$onResize]({width:parseFloat(width),height:parseFloat(height)});}},{key:$tick$1,value:function value(_time,_delta){}},{key:$markLoaded,value:function value(){if(this[$loaded]){return;}this[$loaded]=true;this[$loadedTime]=performance.now();}},{key:$needsRender,value:function value(){this[$scene].isDirty=true;}},{key:$onModelLoad,value:function value(){}},{key:$onResize,value:function value(e){this[$scene].setSize(e.width,e.height);}},{key:$onContextLost,value:function value(event){this.dispatchEvent(new CustomEvent('error',{detail:{type:'webglcontextlost',sourceError:event.sourceEvent}}));}},{key:$updateSource,value:function(){var _value2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee18(){var updateSourceProgress,source,detail;return regeneratorRuntime.wrap(function _callee18$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:if(!(this.loaded||!this[$shouldAttemptPreload]())){_context19.next=2;break;}return _context19.abrupt("return");case 2:updateSourceProgress=this[$progressTracker].beginActivity();source=this.src;_context19.prev=4;_context19.next=7;return this[$scene].setModelSource(source,function(progress){return updateSourceProgress(progress*0.8);});case 7:detail={url:source};this.dispatchEvent(new CustomEvent('preload',{detail:detail}));_context19.next=14;break;case 11:_context19.prev=11;_context19.t0=_context19["catch"](4);this.dispatchEvent(new CustomEvent('error',{detail:_context19.t0}));case 14:_context19.prev=14;updateSourceProgress(0.9);requestAnimationFrame(function(){requestAnimationFrame(function(){updateSourceProgress(1.0);});});return _context19.finish(14);case 18:case"end":return _context19.stop();}}},_callee18,this,[[4,11,14,18]]);}));function value(){return _value2.apply(this,arguments);}return value;}()},{key:"loaded",get:function get(){return this[$getLoaded]();}},{key:(_a$8=$isElementInViewport,_b$6=$loaded,_c$1=$loadedTime,_d$1=$clearModelTimeout,_e$1=$fallbackResizeHandler,_f$1=$announceModelVisibility,_g$1=$resizeObserver,_h$1=$intersectionObserver,_j$1=$progressTracker,_k$1=$contextLostHandler,$renderer),get:function get(){return Renderer.singleton;}},{key:"modelIsVisible",get:function get(){return this[$getModelIsVisible]();}},{key:$ariaLabel,get:function get(){return this.alt==null||this.alt==='null'?this[$defaultAriaLabel]:this.alt;}}],[{key:"is",get:function get(){return'model-viewer';}},{key:"template",get:function get(){if(!this.hasOwnProperty($template)){this[$template]=makeTemplate(this.is);}return this[$template];}},{key:"modelCacheSize",set:function set(value){CachingGLTFLoader[$evictionPolicy].evictionThreshold=value;},get:function get(){return CachingGLTFLoader[$evictionPolicy].evictionThreshold;}},{key:"minimumRenderScale",set:function set(value){if(value>1){console.warn(' minimumRenderScale has been clamped to a maximum value of 1.');}if(value<=0){console.warn(' minimumRenderScale has been clamped to a minimum value of 0. This could result in single-pixel renders on some devices; consider increasing.');}Renderer.singleton.minScale=Math.max(0,Math.min(1,value));},get:function get(){return Renderer.singleton.minScale;}}]);return ModelViewerElementBase;}(UpdatingElement);__decorate([property({type:String})],ModelViewerElementBase.prototype,"alt",void 0);__decorate([property({type:String})],ModelViewerElementBase.prototype,"src",void 0);var __decorate$1=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var MILLISECONDS_PER_SECOND=1000.0;var $changeAnimation=Symbol('changeAnimation');var $paused=Symbol('paused');var AnimationMixin=function AnimationMixin(ModelViewerElement){var _a;var AnimationModelViewerElement=/*#__PURE__*/function(_ModelViewerElement){_inherits(AnimationModelViewerElement,_ModelViewerElement);var _super23=_createSuper(AnimationModelViewerElement);function AnimationModelViewerElement(){var _this50;_classCallCheck(this,AnimationModelViewerElement);_this50=_super23.apply(this,arguments);_this50.autoplay=false;_this50.animationName=undefined;_this50.animationCrossfadeDuration=300;_this50[_a]=true;return _this50;}_createClass(AnimationModelViewerElement,[{key:"pause",value:function pause(){if(this[$paused]){return;}this[$paused]=true;this[$renderer].threeRenderer.shadowMap.autoUpdate=false;this.dispatchEvent(new CustomEvent('pause'));}},{key:"play",value:function play(){if(this[$paused]&&this.availableAnimations.length>0){this[$paused]=false;this[$renderer].threeRenderer.shadowMap.autoUpdate=true;if(!this[$scene].model.hasActiveAnimation){this[$changeAnimation]();}this.dispatchEvent(new CustomEvent('play'));}}},{key:(_a=$paused,$onModelLoad),value:function value(){_get(_getPrototypeOf(AnimationModelViewerElement.prototype),$onModelLoad,this).call(this);this[$paused]=true;if(this.autoplay){this[$changeAnimation]();this.play();}}},{key:$tick$1,value:function value(_time,delta){_get(_getPrototypeOf(AnimationModelViewerElement.prototype),$tick$1,this).call(this,_time,delta);if(this[$paused]||!this[$hasTransitioned]()){return;}var model=this[$scene].model;model.updateAnimation(delta/MILLISECONDS_PER_SECOND);this[$needsRender]();}},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(AnimationModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('autoplay')&&this.autoplay){this.play();}if(changedProperties.has('animationName')){this[$changeAnimation]();}}},{key:$updateSource,value:function(){var _value3=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee19(){return regeneratorRuntime.wrap(function _callee19$(_context20){while(1){switch(_context20.prev=_context20.next){case 0:this[$scene].model.stopAnimation();return _context20.abrupt("return",_get(_getPrototypeOf(AnimationModelViewerElement.prototype),$updateSource,this).call(this));case 2:case"end":return _context20.stop();}}},_callee19,this);}));function value(){return _value3.apply(this,arguments);}return value;}()},{key:$changeAnimation,value:function value(){var model=this[$scene].model;model.playAnimation(this.animationName,this.animationCrossfadeDuration/MILLISECONDS_PER_SECOND);if(this[$paused]){model.updateAnimation(0);this[$needsRender]();}}},{key:"availableAnimations",get:function get(){if(this.loaded){return this[$scene].model.animationNames;}return[];}},{key:"paused",get:function get(){return this[$paused];}},{key:"currentTime",get:function get(){return this[$scene].model.animationTime;},set:function set(value){this[$scene].model.animationTime=value;this[$renderer].threeRenderer.shadowMap.needsUpdate=true;this[$needsRender]();}}]);return AnimationModelViewerElement;}(ModelViewerElement);__decorate$1([property({type:Boolean})],AnimationModelViewerElement.prototype,"autoplay",void 0);__decorate$1([property({type:String,attribute:'animation-name'})],AnimationModelViewerElement.prototype,"animationName",void 0);__decorate$1([property({type:Number,attribute:'animation-crossfade-duration'})],AnimationModelViewerElement.prototype,"animationCrossfadeDuration",void 0);return AnimationModelViewerElement;};var $annotationRenderer=Symbol('annotationRenderer');var $hotspotMap=Symbol('hotspotMap');var $mutationCallback=Symbol('mutationCallback');var $observer=Symbol('observer');var $addHotspot=Symbol('addHotspot');var $removeHotspot=Symbol('removeHotspot');var pixelPosition=new Vector2();var worldToModel=new Matrix4();var worldToModelNormal=new Matrix3();var AnnotationMixin=function AnnotationMixin(ModelViewerElement){var _a,_b,_c,_d;var AnnotationModelViewerElement=/*#__PURE__*/function(_ModelViewerElement2){_inherits(AnnotationModelViewerElement,_ModelViewerElement2);var _super24=_createSuper(AnnotationModelViewerElement);function AnnotationModelViewerElement(){var _this51;_classCallCheck(this,AnnotationModelViewerElement);for(var _len2=arguments.length,args=new Array(_len2),_key5=0;_key5<_len2;_key5++){args[_key5]=arguments[_key5];}_this51=_super24.call.apply(_super24,[this].concat(args));_this51[_a]=new CSS2DRenderer();_this51[_b]=new Map();_this51[_c]=function(mutations){mutations.forEach(function(mutation){if(!_instanceof(mutation,MutationRecord)||mutation.type==='childList'){mutation.addedNodes.forEach(function(node){_this51[$addHotspot](node);});mutation.removedNodes.forEach(function(node){_this51[$removeHotspot](node);});_this51[$needsRender]();}});};_this51[_d]=new MutationObserver(_this51[$mutationCallback]);var domElement=_this51[$annotationRenderer].domElement;var style=domElement.style;style.display='none';style.pointerEvents='none';style.position='absolute';style.top='0';_this51.shadowRoot.querySelector('.default').appendChild(domElement);return _this51;}_createClass(AnnotationModelViewerElement,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(AnnotationModelViewerElement.prototype),"connectedCallback",this).call(this);for(var _i344=0;_i344-1;});var result=new Set();var _iterator18=_createForOfIteratorHelper(names),_step18;try{for(_iterator18.s();!(_step18=_iterator18.n()).done;){var name=_step18.value;result.add(name);}}catch(err){_iterator18.e(err);}finally{_iterator18.f();}return result;}catch(_error){}return new Set();};};var __decorate$2=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var isWebXRBlocked=false;var isSceneViewerBlocked=false;var noArViewerSigil='#model-viewer-no-ar-fallback';var deserializeQuickLookBrowsers=enumerationDeserializer(['safari','chrome']);var deserializeARModes=enumerationDeserializer(['quick-look','scene-viewer','webxr','none']);var DEFAULT_AR_MODES='webxr scene-viewer quick-look';var ARMode={QUICK_LOOK:'quick-look',SCENE_VIEWER:'scene-viewer',WEBXR:'webxr',NONE:'none'};var $arButtonContainer=Symbol('arButtonContainer');var $enterARWithWebXR=Symbol('enterARWithWebXR');var $openSceneViewer=Symbol('openSceneViewer');var $openIOSARQuickLook=Symbol('openIOSARQuickLook');var $canActivateAR=Symbol('canActivateAR');var $arMode=Symbol('arMode');var $arModes=Symbol('arModes');var $canLaunchQuickLook=Symbol('canLaunchQuickLook');var $quickLookBrowsers=Symbol('quickLookBrowsers');var $arAnchor=Symbol('arAnchor');var $preload=Symbol('preload');var $onARButtonContainerClick=Symbol('onARButtonContainerClick');var $onARStatus=Symbol('onARStatus');var $onARTap=Symbol('onARTap');var $selectARMode=Symbol('selectARMode');var ARMixin=function ARMixin(ModelViewerElement){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k;var ARModelViewerElement=/*#__PURE__*/function(_ModelViewerElement3){_inherits(ARModelViewerElement,_ModelViewerElement3);var _super25=_createSuper(ARModelViewerElement);function ARModelViewerElement(){var _this52;_classCallCheck(this,ARModelViewerElement);_this52=_super25.apply(this,arguments);_this52.ar=false;_this52.arScale='auto';_this52.arModes=DEFAULT_AR_MODES;_this52.iosSrc=null;_this52.quickLookBrowsers='safari';_this52[_a]=false;_this52[_b]=_this52.shadowRoot.querySelector('.ar-button');_this52[_c]=document.createElement('a');_this52[_d]=new Set();_this52[_e]=ARMode.NONE;_this52[_f]=false;_this52[_g]=new Set();_this52[_h]=function(event){event.preventDefault();_this52.activateAR();};_this52[_j]=function(_ref7){var status=_ref7.status;if(status===ARStatus.NOT_PRESENTING||_this52[$renderer].arRenderer.presentedScene===_this52[$scene]){_this52.setAttribute('ar-status',status);_this52.dispatchEvent(new CustomEvent('ar-status',{detail:{status:status}}));}};_this52[_k]=function(event){if(event.data=='_apple_ar_quicklook_button_tapped'){_this52.dispatchEvent(new CustomEvent('quick-look-button-tapped'));}};return _this52;}_createClass(ARModelViewerElement,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(ARModelViewerElement.prototype),"connectedCallback",this).call(this);this[$renderer].arRenderer.addEventListener('status',this[$onARStatus]);this.setAttribute('ar-status',ARStatus.NOT_PRESENTING);this[$arAnchor].addEventListener('message',this[$onARTap]);}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(ARModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$renderer].arRenderer.removeEventListener('status',this[$onARStatus]);this[$arAnchor].removeEventListener('message',this[$onARTap]);}},{key:"update",value:function(){var _update2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee20(changedProperties){return regeneratorRuntime.wrap(function _callee20$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:_get(_getPrototypeOf(ARModelViewerElement.prototype),"update",this).call(this,changedProperties);if(changedProperties.has('quickLookBrowsers')){this[$quickLookBrowsers]=deserializeQuickLookBrowsers(this.quickLookBrowsers);}if(!(!changedProperties.has('ar')&&!changedProperties.has('arModes')&&!changedProperties.has('iosSrc'))){_context21.next=4;break;}return _context21.abrupt("return");case 4:if(changedProperties.has('arModes')){this[$arModes]=deserializeARModes(this.arModes);}if(changedProperties.has('arScale')){this[$scene].canScale=this.arScale!=='fixed';}this[$selectARMode]();case 7:case"end":return _context21.stop();}}},_callee20,this);}));function update(_x22){return _update2.apply(this,arguments);}return update;}()},{key:"activateAR",value:function(){var _activateAR=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee21(){return regeneratorRuntime.wrap(function _callee21$(_context22){while(1){switch(_context22.prev=_context22.next){case 0:_context22.t0=this[$arMode];_context22.next=_context22.t0===ARMode.QUICK_LOOK?3:_context22.t0===ARMode.WEBXR?5:_context22.t0===ARMode.SCENE_VIEWER?8:10;break;case 3:this[$openIOSARQuickLook]();return _context22.abrupt("break",12);case 5:_context22.next=7;return this[$enterARWithWebXR]();case 7:return _context22.abrupt("break",12);case 8:this[$openSceneViewer]();return _context22.abrupt("break",12);case 10:console.warn('No AR Mode can be activated. This is probably due to missing \ configuration or device capabilities');return _context22.abrupt("break",12);case 12:case"end":return _context22.stop();}}},_callee21,this);}));function activateAR(){return _activateAR.apply(this,arguments);}return activateAR;}()},{key:(_a=$canActivateAR,_b=$arButtonContainer,_c=$arAnchor,_d=$arModes,_e=$arMode,_f=$preload,_g=$quickLookBrowsers,_h=$onARButtonContainerClick,_j=$onARStatus,_k=$onARTap,$selectARMode),value:function(){var _value4=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee22(){var arModes,_i345,_arModes,_value5,status;return regeneratorRuntime.wrap(function _callee22$(_context23){while(1){switch(_context23.prev=_context23.next){case 0:this[$arMode]=ARMode.NONE;if(!this.ar){_context23.next=28;break;}arModes=[];this[$arModes].forEach(function(value){arModes.push(value);});_i345=0,_arModes=arModes;case 5:if(!(_i345<_arModes.length)){_context23.next=28;break;}_value5=_arModes[_i345];_context23.t0=_value5==='webxr'&&IS_WEBXR_AR_CANDIDATE&&!isWebXRBlocked;if(!_context23.t0){_context23.next=12;break;}_context23.next=11;return this[$renderer].arRenderer.supportsPresentation();case 11:_context23.t0=_context23.sent;case 12:if(!_context23.t0){_context23.next=17;break;}this[$arMode]=ARMode.WEBXR;return _context23.abrupt("break",28);case 17:if(!(_value5==='scene-viewer'&&IS_SCENEVIEWER_CANDIDATE&&!isSceneViewerBlocked)){_context23.next=22;break;}this[$arMode]=ARMode.SCENE_VIEWER;return _context23.abrupt("break",28);case 22:if(!(_value5==='quick-look'&&!!this.iosSrc&&this[$canLaunchQuickLook]&&IS_AR_QUICKLOOK_CANDIDATE)){_context23.next=25;break;}this[$arMode]=ARMode.QUICK_LOOK;return _context23.abrupt("break",28);case 25:_i345++;_context23.next=5;break;case 28:if(this.canActivateAR){this[$arButtonContainer].classList.add('enabled');this[$arButtonContainer].addEventListener('click',this[$onARButtonContainerClick]);}else if(this[$arButtonContainer].classList.contains('enabled')){this[$arButtonContainer].removeEventListener('click',this[$onARButtonContainerClick]);this[$arButtonContainer].classList.remove('enabled');status=ARStatus.FAILED;this.setAttribute('ar-status',status);this.dispatchEvent(new CustomEvent('ar-status',{detail:{status:status}}));}case 29:case"end":return _context23.stop();}}},_callee22,this);}));function value(){return _value4.apply(this,arguments);}return value;}()},{key:$enterARWithWebXR,value:function(){var _value6=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee23(){return regeneratorRuntime.wrap(function _callee23$(_context24){while(1){switch(_context24.prev=_context24.next){case 0:console.log('Attempting to present in AR...');if(this[$loaded]){_context24.next=7;break;}this[$preload]=true;this[$updateSource]();_context24.next=6;return waitForEvent(this,'load');case 6:this[$preload]=false;case 7:_context24.prev=7;this[$arButtonContainer].removeEventListener('click',this[$onARButtonContainerClick]);_context24.next=11;return this[$renderer].arRenderer.present(this[$scene]);case 11:_context24.next=23;break;case 13:_context24.prev=13;_context24.t0=_context24["catch"](7);console.warn('Error while trying to present to AR');console.error(_context24.t0);_context24.next=19;return this[$renderer].arRenderer.stopPresenting();case 19:isWebXRBlocked=true;_context24.next=22;return this[$selectARMode]();case 22:this.activateAR();case 23:_context24.prev=23;this[$selectARMode]();return _context24.finish(23);case 26:case"end":return _context24.stop();}}},_callee23,this,[[7,13,23,26]]);}));function value(){return _value6.apply(this,arguments);}return value;}()},{key:$shouldAttemptPreload,value:function value(){return _get(_getPrototypeOf(ARModelViewerElement.prototype),$shouldAttemptPreload,this).call(this)||this[$preload];}},{key:$openSceneViewer,value:function value(){var _this53=this;var gltfSrc=this.src.replace('?','&');var location=self.location.toString();var locationUrl=new URL(location);var modelUrl=new URL(gltfSrc,location);locationUrl.hash=noArViewerSigil;var intentParams="?file=".concat(modelUrl.toString(),"&mode=ar_only");if(!gltfSrc.includes('&link=')){intentParams+="&link=".concat(location);}if(!gltfSrc.includes('&title=')){intentParams+="&title=".concat(encodeURIComponent(this.alt||''));}if(this.arScale==='fixed'){intentParams+="&resizable=false";}var intent="intent://arvr.google.com/scene-viewer/1.0".concat(intentParams,"#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;S.browser_fallback_url=").concat(encodeURIComponent(locationUrl.toString()),";end;");var undoHashChange=function undoHashChange(){if(self.location.hash===noArViewerSigil){isSceneViewerBlocked=true;self.history.back();_this53[$selectARMode]();}};self.addEventListener('hashchange',undoHashChange,{once:true});this[$arAnchor].setAttribute('href',intent);this[$arAnchor].click();}},{key:$openIOSARQuickLook,value:function value(){var modelUrl=new URL(this.iosSrc,self.location.toString());if(this.arScale==='fixed'){modelUrl.hash='allowsContentScaling=0';}var anchor=this[$arAnchor];anchor.setAttribute('rel','ar');var img=document.createElement('img');anchor.appendChild(img);anchor.setAttribute('href',modelUrl.toString());anchor.click();anchor.removeChild(img);}},{key:"canActivateAR",get:function get(){return this[$arMode]!==ARMode.NONE;}},{key:$canLaunchQuickLook,get:function get(){if(IS_IOS_CHROME){return this[$quickLookBrowsers].has('chrome');}else if(IS_IOS_SAFARI){return this[$quickLookBrowsers].has('safari');}return false;}}]);return ARModelViewerElement;}(ModelViewerElement);__decorate$2([property({type:Boolean,attribute:'ar'})],ARModelViewerElement.prototype,"ar",void 0);__decorate$2([property({type:String,attribute:'ar-scale'})],ARModelViewerElement.prototype,"arScale",void 0);__decorate$2([property({type:String,attribute:'ar-modes'})],ARModelViewerElement.prototype,"arModes",void 0);__decorate$2([property({type:String,attribute:'ios-src'})],ARModelViewerElement.prototype,"iosSrc",void 0);__decorate$2([property({type:String,attribute:'quick-look-browsers'})],ARModelViewerElement.prototype,"quickLookBrowsers",void 0);return ARModelViewerElement;};var _a$9,_b$7,_c$2;var $evaluate=Symbol('evaluate');var $lastValue=Symbol('lastValue');var Evaluator=/*#__PURE__*/function(){function Evaluator(){_classCallCheck(this,Evaluator);this[_a$9]=null;}_createClass(Evaluator,[{key:"evaluate",value:function evaluate(){if(!this.isConstant||this[$lastValue]==null){this[$lastValue]=this[$evaluate]();}return this[$lastValue];}},{key:"isConstant",get:function get(){return false;}}],[{key:"evaluatableFor",value:function evaluatableFor(node){var basis=arguments.length>1&&arguments[1]!==undefined?arguments[1]:ZERO;if(_instanceof(node,Evaluator)){return node;}if(node.type==='number'){if(node.unit==='%'){return new PercentageEvaluator(node,basis);}return node;}switch(node.name.value){case'calc':return new CalcEvaluator(node,basis);case'env':return new EnvEvaluator(node);}return ZERO;}},{key:"evaluate",value:function evaluate(evaluatable){if(_instanceof(evaluatable,Evaluator)){return evaluatable.evaluate();}return evaluatable;}},{key:"isConstant",value:function isConstant(evaluatable){if(_instanceof(evaluatable,Evaluator)){return evaluatable.isConstant;}return true;}},{key:"applyIntrinsics",value:function applyIntrinsics(evaluated,intrinsics){var basis=intrinsics.basis,keywords=intrinsics.keywords;var auto=keywords.auto;return basis.map(function(basisNode,index){var autoSubstituteNode=auto[index]==null?basisNode:auto[index];var evaluatedNode=evaluated[index]?evaluated[index]:autoSubstituteNode;if(evaluatedNode.type==='ident'){var keyword=evaluatedNode.value;if(keyword in keywords){evaluatedNode=keywords[keyword][index];}}if(evaluatedNode==null||evaluatedNode.type==='ident'){evaluatedNode=autoSubstituteNode;}if(evaluatedNode.unit==='%'){return numberNode(evaluatedNode.number/100*basisNode.number,basisNode.unit);}evaluatedNode=normalizeUnit(evaluatedNode,basisNode);if(evaluatedNode.unit!==basisNode.unit){return basisNode;}return evaluatedNode;});}}]);return Evaluator;}();_a$9=$lastValue;var $percentage=Symbol('percentage');var $basis=Symbol('basis');var PercentageEvaluator=/*#__PURE__*/function(_Evaluator){_inherits(PercentageEvaluator,_Evaluator);var _super26=_createSuper(PercentageEvaluator);function PercentageEvaluator(percentage,basis){var _this54;_classCallCheck(this,PercentageEvaluator);_this54=_super26.call(this);_this54[$percentage]=percentage;_this54[$basis]=basis;return _this54;}_createClass(PercentageEvaluator,[{key:$evaluate,value:function value(){return numberNode(this[$percentage].number/100*this[$basis].number,this[$basis].unit);}},{key:"isConstant",get:function get(){return true;}}]);return PercentageEvaluator;}(Evaluator);var $identNode=Symbol('identNode');var EnvEvaluator=/*#__PURE__*/function(_Evaluator2){_inherits(EnvEvaluator,_Evaluator2);var _super27=_createSuper(EnvEvaluator);function EnvEvaluator(envFunction){var _this55;_classCallCheck(this,EnvEvaluator);_this55=_super27.call(this);_this55[_b$7]=null;var identNode=envFunction.arguments.length?envFunction.arguments[0].terms[0]:null;if(identNode!=null&&identNode.type==='ident'){_this55[$identNode]=identNode;}return _this55;}_createClass(EnvEvaluator,[{key:(_b$7=$identNode,$evaluate),value:function value(){if(this[$identNode]!=null){switch(this[$identNode].value){case'window-scroll-y':var verticalScrollPosition=window.pageYOffset;var verticalScrollMax=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight);var scrollY=verticalScrollPosition/(verticalScrollMax-window.innerHeight)||0;return{type:'number',number:scrollY,unit:null};}}return ZERO;}},{key:"isConstant",get:function get(){return false;}}]);return EnvEvaluator;}(Evaluator);var IS_MULTIPLICATION_RE=/[\*\/]/;var $evaluator=Symbol('evalutor');var CalcEvaluator=/*#__PURE__*/function(_Evaluator3){_inherits(CalcEvaluator,_Evaluator3);var _super28=_createSuper(CalcEvaluator);function CalcEvaluator(calcFunction){var _this56;var basis=arguments.length>1&&arguments[1]!==undefined?arguments[1]:ZERO;_classCallCheck(this,CalcEvaluator);_this56=_super28.call(this);_this56[_c$2]=null;if(calcFunction.arguments.length!==1){return _possibleConstructorReturn(_this56);}var terms=calcFunction.arguments[0].terms.slice();var secondOrderTerms=[];while(terms.length){var term=terms.shift();if(secondOrderTerms.length>0){var previousTerm=secondOrderTerms[secondOrderTerms.length-1];if(previousTerm.type==='operator'&&IS_MULTIPLICATION_RE.test(previousTerm.value)){var operator=secondOrderTerms.pop();var leftValue=secondOrderTerms.pop();if(leftValue==null){return _possibleConstructorReturn(_this56);}secondOrderTerms.push(new OperatorEvaluator(operator,Evaluator.evaluatableFor(leftValue,basis),Evaluator.evaluatableFor(term,basis)));continue;}}secondOrderTerms.push(term.type==='operator'?term:Evaluator.evaluatableFor(term,basis));}while(secondOrderTerms.length>2){var _secondOrderTerms$spl=secondOrderTerms.splice(0,3),_secondOrderTerms$spl2=_slicedToArray(_secondOrderTerms$spl,3),left=_secondOrderTerms$spl2[0],_operator=_secondOrderTerms$spl2[1],right=_secondOrderTerms$spl2[2];if(_operator.type!=='operator'){return _possibleConstructorReturn(_this56);}secondOrderTerms.unshift(new OperatorEvaluator(_operator,Evaluator.evaluatableFor(left,basis),Evaluator.evaluatableFor(right,basis)));}if(secondOrderTerms.length===1){_this56[$evaluator]=secondOrderTerms[0];}return _this56;}_createClass(CalcEvaluator,[{key:(_c$2=$evaluator,$evaluate),value:function value(){return this[$evaluator]!=null?Evaluator.evaluate(this[$evaluator]):ZERO;}},{key:"isConstant",get:function get(){return this[$evaluator]==null||Evaluator.isConstant(this[$evaluator]);}}]);return CalcEvaluator;}(Evaluator);var $operator=Symbol('operator');var $left=Symbol('left');var $right=Symbol('right');var OperatorEvaluator=/*#__PURE__*/function(_Evaluator4){_inherits(OperatorEvaluator,_Evaluator4);var _super29=_createSuper(OperatorEvaluator);function OperatorEvaluator(operator,left,right){var _this57;_classCallCheck(this,OperatorEvaluator);_this57=_super29.call(this);_this57[$operator]=operator;_this57[$left]=left;_this57[$right]=right;return _this57;}_createClass(OperatorEvaluator,[{key:$evaluate,value:function value(){var leftNode=normalizeUnit(Evaluator.evaluate(this[$left]));var rightNode=normalizeUnit(Evaluator.evaluate(this[$right]));var leftValue=leftNode.number,leftUnit=leftNode.unit;var rightValue=rightNode.number,rightUnit=rightNode.unit;if(rightUnit!=null&&leftUnit!=null&&rightUnit!=leftUnit){return ZERO;}var unit=leftUnit||rightUnit;var value;switch(this[$operator].value){case'+':value=leftValue+rightValue;break;case'-':value=leftValue-rightValue;break;case'/':value=leftValue/rightValue;break;case'*':value=leftValue*rightValue;break;default:return ZERO;}return{type:'number',number:value,unit:unit};}},{key:"isConstant",get:function get(){return Evaluator.isConstant(this[$left])&&Evaluator.isConstant(this[$right]);}}]);return OperatorEvaluator;}(Evaluator);var $evaluatables=Symbol('evaluatables');var $intrinsics=Symbol('intrinsics');var StyleEvaluator=/*#__PURE__*/function(_Evaluator5){_inherits(StyleEvaluator,_Evaluator5);var _super30=_createSuper(StyleEvaluator);function StyleEvaluator(expressions,intrinsics){var _this58;_classCallCheck(this,StyleEvaluator);_this58=_super30.call(this);_this58[$intrinsics]=intrinsics;var firstExpression=expressions[0];var terms=firstExpression!=null?firstExpression.terms:[];_this58[$evaluatables]=intrinsics.basis.map(function(basisNode,index){var term=terms[index];if(term==null){return{type:'ident',value:'auto'};}if(term.type==='ident'){return term;}return Evaluator.evaluatableFor(term,basisNode);});return _this58;}_createClass(StyleEvaluator,[{key:$evaluate,value:function value(){var evaluated=this[$evaluatables].map(function(evaluatable){return Evaluator.evaluate(evaluatable);});return Evaluator.applyIntrinsics(evaluated,this[$intrinsics]).map(function(numberNode){return numberNode.number;});}},{key:"isConstant",get:function get(){var _iterator19=_createForOfIteratorHelper(this[$evaluatables]),_step19;try{for(_iterator19.s();!(_step19=_iterator19.n()).done;){var evaluatable=_step19.value;if(!Evaluator.isConstant(evaluatable)){return false;}}}catch(err){_iterator19.e(err);}finally{_iterator19.f();}return true;}}]);return StyleEvaluator;}(Evaluator);var _a$a,_b$8,_c$3,_d$2;var $instances=Symbol('instances');var $activateListener=Symbol('activateListener');var $deactivateListener=Symbol('deactivateListener');var $notifyInstances=Symbol('notifyInstances');var $notify=Symbol('notify');var $scrollCallback=Symbol('callback');var ScrollObserver=/*#__PURE__*/function(){function ScrollObserver(callback){_classCallCheck(this,ScrollObserver);this[$scrollCallback]=callback;}_createClass(ScrollObserver,[{key:"observe",value:function observe(){if(ScrollObserver[$instances].size===0){ScrollObserver[$activateListener]();}ScrollObserver[$instances].add(this);}},{key:"disconnect",value:function disconnect(){ScrollObserver[$instances].delete(this);if(ScrollObserver[$instances].size===0){ScrollObserver[$deactivateListener]();}}},{key:$notify,value:function value(){this[$scrollCallback]();}}],[{key:$notifyInstances,value:function value(){var _iterator20=_createForOfIteratorHelper(ScrollObserver[$instances]),_step20;try{for(_iterator20.s();!(_step20=_iterator20.n()).done;){var instance=_step20.value;instance[$notify]();}}catch(err){_iterator20.e(err);}finally{_iterator20.f();}}},{key:(_a$a=$instances,$activateListener),value:function value(){window.addEventListener('scroll',this[$notifyInstances],{passive:true});}},{key:$deactivateListener,value:function value(){window.removeEventListener('scroll',this[$notifyInstances]);}}]);return ScrollObserver;}();ScrollObserver[_a$a]=new Set();var $computeStyleCallback=Symbol('computeStyleCallback');var $astWalker=Symbol('astWalker');var $dependencies=Symbol('dependencies');var $scrollHandler=Symbol('scrollHandler');var $onScroll=Symbol('onScroll');var StyleEffector=/*#__PURE__*/function(){function StyleEffector(callback){var _this59=this;_classCallCheck(this,StyleEffector);this[_b$8]={};this[_c$3]=new ASTWalker(['function']);this[_d$2]=function(){return _this59[$onScroll]();};this[$computeStyleCallback]=callback;}_createClass(StyleEffector,[{key:"observeEffectsFor",value:function observeEffectsFor(ast){var _this60=this;var newDependencies={};var oldDependencies=this[$dependencies];this[$astWalker].walk(ast,function(functionNode){var name=functionNode.name;var firstArgument=functionNode.arguments[0];var firstTerm=firstArgument.terms[0];if(name.value!=='env'||firstTerm==null||firstTerm.type!=='ident'){return;}switch(firstTerm.value){case'window-scroll-y':if(newDependencies['window-scroll']==null){var observer='window-scroll'in oldDependencies?oldDependencies['window-scroll']:new ScrollObserver(_this60[$scrollHandler]);observer.observe();delete oldDependencies['window-scroll'];newDependencies['window-scroll']=observer;}break;}});for(var environmentState in oldDependencies){var observer=oldDependencies[environmentState];observer.disconnect();}this[$dependencies]=newDependencies;}},{key:"dispose",value:function dispose(){for(var environmentState in this[$dependencies]){var observer=this[$dependencies][environmentState];observer.disconnect();}}},{key:(_b$8=$dependencies,_c$3=$astWalker,_d$2=$scrollHandler,$onScroll),value:function value(){this[$computeStyleCallback]({relatedState:'window-scroll'});}}]);return StyleEffector;}();var style=function style(config){var observeEffects=config.observeEffects||false;var getIntrinsics=_instanceof(config.intrinsics,Function)?config.intrinsics:function(){return config.intrinsics;};return function(proto,propertyName){var _Object$definePropert;var originalUpdated=proto.updated;var originalConnectedCallback=proto.connectedCallback;var originalDisconnectedCallback=proto.disconnectedCallback;var $styleEffector=Symbol("".concat(propertyName,"StyleEffector"));var $styleEvaluator=Symbol("".concat(propertyName,"StyleEvaluator"));var $updateEvaluator=Symbol("".concat(propertyName,"UpdateEvaluator"));var $evaluateAndSync=Symbol("".concat(propertyName,"EvaluateAndSync"));Object.defineProperties(proto,(_Object$definePropert={},_defineProperty(_Object$definePropert,$styleEffector,{value:null,writable:true}),_defineProperty(_Object$definePropert,$styleEvaluator,{value:null,writable:true}),_defineProperty(_Object$definePropert,$updateEvaluator,{value:function value(){var _this61=this;var ast=parseExpressions(this[propertyName]);this[$styleEvaluator]=new StyleEvaluator(ast,getIntrinsics(this));if(this[$styleEffector]==null&&observeEffects){this[$styleEffector]=new StyleEffector(function(){return _this61[$evaluateAndSync]();});}if(this[$styleEffector]!=null){this[$styleEffector].observeEffectsFor(ast);}}}),_defineProperty(_Object$definePropert,$evaluateAndSync,{value:function value(){if(this[$styleEvaluator]==null){return;}var result=this[$styleEvaluator].evaluate();this[config.updateHandler](result);}}),_defineProperty(_Object$definePropert,"updated",{value:function value(changedProperties){if(changedProperties.has(propertyName)){this[$updateEvaluator]();this[$evaluateAndSync]();}originalUpdated.call(this,changedProperties);}}),_defineProperty(_Object$definePropert,"connectedCallback",{value:function value(){originalConnectedCallback.call(this);this.requestUpdate(propertyName,this[propertyName]);}}),_defineProperty(_Object$definePropert,"disconnectedCallback",{value:function value(){originalDisconnectedCallback.call(this);if(this[$styleEffector]!=null){this[$styleEffector].dispose();this[$styleEffector]=null;}}}),_Object$definePropert));};};var DEFAULT_OPTIONS=Object.freeze({minimumRadius:0,maximumRadius:Infinity,minimumPolarAngle:Math.PI/8,maximumPolarAngle:Math.PI-Math.PI/8,minimumAzimuthalAngle:-Infinity,maximumAzimuthalAngle:Infinity,minimumFieldOfView:10,maximumFieldOfView:45,interactionPolicy:'always-allow',touchAction:'pan-y'});var TOUCH_EVENT_RE=/^touch(start|end|move)$/;var KEYBOARD_ORBIT_INCREMENT=Math.PI/8;var ZOOM_SENSITIVITY=0.04;var KeyCode={PAGE_UP:33,PAGE_DOWN:34,LEFT:37,UP:38,RIGHT:39,DOWN:40};var ChangeSource={USER_INTERACTION:'user-interaction',NONE:'none'};var SmoothControls=/*#__PURE__*/function(_EventDispatcher5){_inherits(SmoothControls,_EventDispatcher5);var _super31=_createSuper(SmoothControls);function SmoothControls(camera,element){var _this62;_classCallCheck(this,SmoothControls);_this62=_super31.call(this);_this62.camera=camera;_this62.element=element;_this62.sensitivity=1;_this62._interactionEnabled=false;_this62.isUserChange=false;_this62.isUserPointing=false;_this62.spherical=new Spherical();_this62.goalSpherical=new Spherical();_this62.thetaDamper=new Damper();_this62.phiDamper=new Damper();_this62.radiusDamper=new Damper();_this62.logFov=Math.log(DEFAULT_OPTIONS.maximumFieldOfView);_this62.goalLogFov=_this62.logFov;_this62.fovDamper=new Damper();_this62.pointerIsDown=false;_this62.lastPointerPosition={clientX:0,clientY:0};_this62.touchMode='rotate';_this62.touchDecided=false;_this62.onPointerMove=function(event){if(!_this62.pointerIsDown||!_this62.canInteract){return;}if(TOUCH_EVENT_RE.test(event.type)){var touches=event.touches;switch(_this62.touchMode){case'zoom':if(_this62.lastTouches.length>1&&touches.length>1){var lastTouchDistance=_this62.twoTouchDistance(_this62.lastTouches[0],_this62.lastTouches[1]);var touchDistance=_this62.twoTouchDistance(touches[0],touches[1]);var deltaZoom=ZOOM_SENSITIVITY*(lastTouchDistance-touchDistance)/10.0;_this62.userAdjustOrbit(0,0,deltaZoom);}break;case'rotate':var touchAction=_this62._options.touchAction;if(!_this62.touchDecided&&touchAction!=='none'){_this62.touchDecided=true;var _touches$=touches[0],clientX=_touches$.clientX,clientY=_touches$.clientY;var dx=Math.abs(clientX-_this62.lastPointerPosition.clientX);var dy=Math.abs(clientY-_this62.lastPointerPosition.clientY);if(touchAction==='pan-y'&&dy>dx&&document.body.scrollHeight>window.innerHeight||touchAction==='pan-x'&&dx>dy){_this62.touchMode='scroll';return;}}_this62.handleSinglePointerMove(touches[0]);break;case'scroll':return;}_this62.lastTouches=touches;}else{_this62.handleSinglePointerMove(event);}if(event.cancelable){event.preventDefault();}};_this62.onPointerDown=function(event){_this62.pointerIsDown=true;_this62.isUserPointing=false;if(TOUCH_EVENT_RE.test(event.type)){var touches=event.touches;_this62.touchDecided=false;switch(touches.length){default:case 1:_this62.touchMode='rotate';_this62.handleSinglePointerDown(touches[0]);break;case 2:_this62.touchMode='zoom';break;}_this62.lastTouches=touches;}else{_this62.handleSinglePointerDown(event);}};_this62.onPointerUp=function(_event){_this62.element.style.cursor='grab';_this62.pointerIsDown=false;if(_this62.isUserPointing){_this62.dispatchEvent({type:'pointer-change-end',pointer:Object.assign({},_this62.lastPointerPosition)});}};_this62.onWheel=function(event){if(!_this62.canInteract){return;}var deltaZoom=event.deltaY*(event.deltaMode==1?18:1)*ZOOM_SENSITIVITY/30;_this62.userAdjustOrbit(0,0,deltaZoom);if(event.cancelable){event.preventDefault();}};_this62.onKeyDown=function(event){var relevantKey=false;switch(event.keyCode){case KeyCode.PAGE_UP:relevantKey=true;_this62.userAdjustOrbit(0,0,ZOOM_SENSITIVITY);break;case KeyCode.PAGE_DOWN:relevantKey=true;_this62.userAdjustOrbit(0,0,-1*ZOOM_SENSITIVITY);break;case KeyCode.UP:relevantKey=true;_this62.userAdjustOrbit(0,-KEYBOARD_ORBIT_INCREMENT,0);break;case KeyCode.DOWN:relevantKey=true;_this62.userAdjustOrbit(0,KEYBOARD_ORBIT_INCREMENT,0);break;case KeyCode.LEFT:relevantKey=true;_this62.userAdjustOrbit(-KEYBOARD_ORBIT_INCREMENT,0,0);break;case KeyCode.RIGHT:relevantKey=true;_this62.userAdjustOrbit(KEYBOARD_ORBIT_INCREMENT,0,0);break;}if(relevantKey&&event.cancelable){event.preventDefault();}};_this62._options=Object.assign({},DEFAULT_OPTIONS);_this62.setOrbit(0,Math.PI/2,1);_this62.setFieldOfView(100);_this62.jumpToGoal();return _this62;}_createClass(SmoothControls,[{key:"enableInteraction",value:function enableInteraction(){if(this._interactionEnabled===false){var element=this.element;element.addEventListener('mousemove',this.onPointerMove);element.addEventListener('mousedown',this.onPointerDown);element.addEventListener('wheel',this.onWheel);element.addEventListener('keydown',this.onKeyDown);element.addEventListener('touchstart',this.onPointerDown,{passive:true});element.addEventListener('touchmove',this.onPointerMove);self.addEventListener('mouseup',this.onPointerUp);self.addEventListener('touchend',this.onPointerUp);this.element.style.cursor='grab';this._interactionEnabled=true;}}},{key:"disableInteraction",value:function disableInteraction(){if(this._interactionEnabled===true){var element=this.element;element.removeEventListener('mousemove',this.onPointerMove);element.removeEventListener('mousedown',this.onPointerDown);element.removeEventListener('wheel',this.onWheel);element.removeEventListener('keydown',this.onKeyDown);element.removeEventListener('touchstart',this.onPointerDown);element.removeEventListener('touchmove',this.onPointerMove);self.removeEventListener('mouseup',this.onPointerUp);self.removeEventListener('touchend',this.onPointerUp);element.style.cursor='';this._interactionEnabled=false;}}},{key:"getCameraSpherical",value:function getCameraSpherical(){var target=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Spherical();return target.copy(this.spherical);}},{key:"getFieldOfView",value:function getFieldOfView(){return this.camera.fov;}},{key:"applyOptions",value:function applyOptions(_options){Object.assign(this._options,_options);this.setOrbit();this.setFieldOfView(Math.exp(this.goalLogFov));}},{key:"updateNearFar",value:function updateNearFar(nearPlane,farPlane){this.camera.near=Math.max(nearPlane,farPlane/1000);this.camera.far=farPlane;this.camera.updateProjectionMatrix();}},{key:"updateAspect",value:function updateAspect(aspect){this.camera.aspect=aspect;this.camera.updateProjectionMatrix();}},{key:"setOrbit",value:function setOrbit(){var goalTheta=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.goalSpherical.theta;var goalPhi=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.goalSpherical.phi;var goalRadius=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this.goalSpherical.radius;var _this$_options=this._options,minimumAzimuthalAngle=_this$_options.minimumAzimuthalAngle,maximumAzimuthalAngle=_this$_options.maximumAzimuthalAngle,minimumPolarAngle=_this$_options.minimumPolarAngle,maximumPolarAngle=_this$_options.maximumPolarAngle,minimumRadius=_this$_options.minimumRadius,maximumRadius=_this$_options.maximumRadius;var _this$goalSpherical=this.goalSpherical,theta=_this$goalSpherical.theta,phi=_this$goalSpherical.phi,radius=_this$goalSpherical.radius;var nextTheta=clamp(goalTheta,minimumAzimuthalAngle,maximumAzimuthalAngle);if(!isFinite(minimumAzimuthalAngle)&&!isFinite(maximumAzimuthalAngle)){this.spherical.theta=this.wrapAngle(this.spherical.theta-nextTheta)+nextTheta;}var nextPhi=clamp(goalPhi,minimumPolarAngle,maximumPolarAngle);var nextRadius=clamp(goalRadius,minimumRadius,maximumRadius);if(nextTheta===theta&&nextPhi===phi&&nextRadius===radius){return false;}this.goalSpherical.theta=nextTheta;this.goalSpherical.phi=nextPhi;this.goalSpherical.radius=nextRadius;this.goalSpherical.makeSafe();this.isUserChange=false;return true;}},{key:"setRadius",value:function setRadius(radius){this.goalSpherical.radius=radius;this.setOrbit();}},{key:"setFieldOfView",value:function setFieldOfView(fov){var _this$_options2=this._options,minimumFieldOfView=_this$_options2.minimumFieldOfView,maximumFieldOfView=_this$_options2.maximumFieldOfView;fov=clamp(fov,minimumFieldOfView,maximumFieldOfView);this.goalLogFov=Math.log(fov);}},{key:"adjustOrbit",value:function adjustOrbit(deltaTheta,deltaPhi,deltaZoom){var _this$goalSpherical2=this.goalSpherical,theta=_this$goalSpherical2.theta,phi=_this$goalSpherical2.phi,radius=_this$goalSpherical2.radius;var _this$_options3=this._options,minimumRadius=_this$_options3.minimumRadius,maximumRadius=_this$_options3.maximumRadius,minimumFieldOfView=_this$_options3.minimumFieldOfView,maximumFieldOfView=_this$_options3.maximumFieldOfView;var dTheta=this.spherical.theta-theta;var dThetaLimit=Math.PI-0.001;var goalTheta=theta-clamp(deltaTheta,-dThetaLimit-dTheta,dThetaLimit-dTheta);var goalPhi=phi-deltaPhi;var deltaRatio=deltaZoom===0?0:deltaZoom>0?(maximumRadius-radius)/(Math.log(maximumFieldOfView)-this.goalLogFov):(radius-minimumRadius)/(this.goalLogFov-Math.log(minimumFieldOfView));var goalRadius=radius+deltaZoom*Math.min(isFinite(deltaRatio)?deltaRatio:Infinity,maximumRadius-minimumRadius);this.setOrbit(goalTheta,goalPhi,goalRadius);if(deltaZoom!==0){var goalLogFov=this.goalLogFov+deltaZoom;this.setFieldOfView(Math.exp(goalLogFov));}}},{key:"jumpToGoal",value:function jumpToGoal(){this.update(0,SETTLING_TIME);}},{key:"update",value:function update(_time,delta){if(this.isStationary()){return;}var _this$_options4=this._options,maximumPolarAngle=_this$_options4.maximumPolarAngle,maximumRadius=_this$_options4.maximumRadius;var dTheta=this.spherical.theta-this.goalSpherical.theta;if(Math.abs(dTheta)>Math.PI&&!isFinite(this._options.minimumAzimuthalAngle)&&!isFinite(this._options.maximumAzimuthalAngle)){this.spherical.theta-=Math.sign(dTheta)*2*Math.PI;}this.spherical.theta=this.thetaDamper.update(this.spherical.theta,this.goalSpherical.theta,delta,Math.PI);this.spherical.phi=this.phiDamper.update(this.spherical.phi,this.goalSpherical.phi,delta,maximumPolarAngle);this.spherical.radius=this.radiusDamper.update(this.spherical.radius,this.goalSpherical.radius,delta,maximumRadius);this.logFov=this.fovDamper.update(this.logFov,this.goalLogFov,delta,1);this.moveCamera();}},{key:"isStationary",value:function isStationary(){return this.goalSpherical.theta===this.spherical.theta&&this.goalSpherical.phi===this.spherical.phi&&this.goalSpherical.radius===this.spherical.radius&&this.goalLogFov===this.logFov;}},{key:"moveCamera",value:function moveCamera(){this.spherical.makeSafe();this.camera.position.setFromSpherical(this.spherical);this.camera.setRotationFromEuler(new Euler(this.spherical.phi-Math.PI/2,this.spherical.theta,0,'YXZ'));if(this.camera.fov!==Math.exp(this.logFov)){this.camera.fov=Math.exp(this.logFov);this.camera.updateProjectionMatrix();}var source=this.isUserChange?ChangeSource.USER_INTERACTION:ChangeSource.NONE;this.dispatchEvent({type:'change',source:source});}},{key:"userAdjustOrbit",value:function userAdjustOrbit(deltaTheta,deltaPhi,deltaZoom){this.adjustOrbit(deltaTheta*this.sensitivity,deltaPhi*this.sensitivity,deltaZoom);this.isUserChange=true;this.dispatchEvent({type:'change',source:ChangeSource.USER_INTERACTION});}},{key:"wrapAngle",value:function wrapAngle(radians){var normalized=(radians+Math.PI)/(2*Math.PI);var wrapped=normalized-Math.floor(normalized);return wrapped*2*Math.PI-Math.PI;}},{key:"pixelLengthToSphericalAngle",value:function pixelLengthToSphericalAngle(pixelLength){return 2*Math.PI*pixelLength/this.element.clientHeight;}},{key:"twoTouchDistance",value:function twoTouchDistance(touchOne,touchTwo){var xOne=touchOne.clientX,yOne=touchOne.clientY;var xTwo=touchTwo.clientX,yTwo=touchTwo.clientY;var xDelta=xTwo-xOne;var yDelta=yTwo-yOne;return Math.sqrt(xDelta*xDelta+yDelta*yDelta);}},{key:"handleSinglePointerMove",value:function handleSinglePointerMove(pointer){var clientX=pointer.clientX,clientY=pointer.clientY;var deltaTheta=this.pixelLengthToSphericalAngle(clientX-this.lastPointerPosition.clientX);var deltaPhi=this.pixelLengthToSphericalAngle(clientY-this.lastPointerPosition.clientY);this.lastPointerPosition.clientX=clientX;this.lastPointerPosition.clientY=clientY;if(this.isUserPointing===false){this.isUserPointing=true;this.dispatchEvent({type:'pointer-change-start',pointer:Object.assign({},pointer)});}this.userAdjustOrbit(deltaTheta,deltaPhi,0);}},{key:"handleSinglePointerDown",value:function handleSinglePointerDown(pointer){this.lastPointerPosition.clientX=pointer.clientX;this.lastPointerPosition.clientY=pointer.clientY;this.element.style.cursor='grabbing';}},{key:"interactionEnabled",get:function get(){return this._interactionEnabled;}},{key:"options",get:function get(){return this._options;}},{key:"canInteract",get:function get(){if(this._options.interactionPolicy=='allow-when-focused'){var rootNode=this.element.getRootNode();return rootNode.activeElement===this.element;}return this._options.interactionPolicy==='always-allow';}}]);return SmoothControls;}(EventDispatcher);var easeInOutQuad=function easeInOutQuad(t){return t<.5?2*t*t:-1+(4-2*t)*t;};var interpolate=function interpolate(start,end){var ease=arguments.length>2&&arguments[2]!==undefined?arguments[2]:easeInOutQuad;return function(time){return start+(end-start)*ease(time);};};var sequence=function sequence(tracks,weights){var totalWeight=weights.reduce(function(total,weight){return total+weight;},0);var ratios=weights.map(function(weight){return weight/totalWeight;});return function(time){var start=0;var ratio=Infinity;var track=function track(){return 0;};for(var _i346=0;_i346=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var PROMPT_ANIMATION_TIME=5000;var wiggle=timeline(0,[{frames:5,value:-1},{frames:1,value:-1},{frames:8,value:1},{frames:1,value:1},{frames:5,value:0},{frames:18,value:0}]);var fade=timeline(0,[{frames:1,value:1},{frames:5,value:1},{frames:1,value:0},{frames:6,value:0}]);var DEFAULT_CAMERA_ORBIT='0deg 75deg 105%';var DEFAULT_CAMERA_TARGET='auto auto auto';var DEFAULT_FIELD_OF_VIEW='auto';var MINIMUM_RADIUS_RATIO=1.1*SAFE_RADIUS_RATIO;var AZIMUTHAL_QUADRANT_LABELS=['front','right','back','left'];var POLAR_TRIENT_LABELS=['upper-','','lower-'];var DEFAULT_INTERACTION_PROMPT_THRESHOLD=3000;var INTERACTION_PROMPT='Use mouse, touch or arrow keys to control the camera!';var InteractionPromptStrategy={AUTO:'auto',WHEN_FOCUSED:'when-focused',NONE:'none'};var InteractionPromptStyle={BASIC:'basic',WIGGLE:'wiggle'};var InteractionPolicy={ALWAYS_ALLOW:'always-allow',WHEN_FOCUSED:'allow-when-focused'};var TouchAction={PAN_Y:'pan-y',PAN_X:'pan-x',NONE:'none'};var fieldOfViewIntrinsics=function fieldOfViewIntrinsics(element){return{basis:[numberNode(element[$zoomAdjustedFieldOfView]*Math.PI/180,'rad')],keywords:{auto:[null]}};};var minFieldOfViewIntrinsics={basis:[degreesToRadians(numberNode(25,'deg'))],keywords:{auto:[null]}};var maxFieldOfViewIntrinsics=function maxFieldOfViewIntrinsics(element){var scene=element[$scene];return{basis:[degreesToRadians(numberNode(45,'deg'))],keywords:{auto:[numberNode(scene.framedFieldOfView,'deg')]}};};var cameraOrbitIntrinsics=function(){var defaultTerms=parseExpressions(DEFAULT_CAMERA_ORBIT)[0].terms;var theta=normalizeUnit(defaultTerms[0]);var phi=normalizeUnit(defaultTerms[1]);return function(element){var radius=element[$scene].model.idealCameraDistance;return{basis:[theta,phi,numberNode(radius,'m')],keywords:{auto:[null,null,numberNode(105,'%')]}};};}();var minCameraOrbitIntrinsics=function minCameraOrbitIntrinsics(element){var radius=MINIMUM_RADIUS_RATIO*element[$scene].model.idealCameraDistance;return{basis:[numberNode(-Infinity,'rad'),numberNode(Math.PI/8,'rad'),numberNode(radius,'m')],keywords:{auto:[null,null,null]}};};var maxCameraOrbitIntrinsics=function maxCameraOrbitIntrinsics(element){var orbitIntrinsics=cameraOrbitIntrinsics(element);var evaluator=new StyleEvaluator([],orbitIntrinsics);var defaultRadius=evaluator.evaluate()[2];return{basis:[numberNode(Infinity,'rad'),numberNode(Math.PI-Math.PI/8,'rad'),numberNode(defaultRadius,'m')],keywords:{auto:[null,null,null]}};};var cameraTargetIntrinsics=function cameraTargetIntrinsics(element){var center=element[$scene].model.boundingBox.getCenter(new Vector3());return{basis:[numberNode(center.x,'m'),numberNode(center.y,'m'),numberNode(center.z,'m')],keywords:{auto:[null,null,null]}};};var HALF_PI=Math.PI/2.0;var THIRD_PI=Math.PI/3.0;var QUARTER_PI=HALF_PI/2.0;var TAU=2.0*Math.PI;var $controls=Symbol('controls');var $promptElement=Symbol('promptElement');var $promptAnimatedContainer=Symbol('promptAnimatedContainer');var $deferInteractionPrompt=Symbol('deferInteractionPrompt');var $updateAria=Symbol('updateAria');var $updateCameraForRadius=Symbol('updateCameraForRadius');var $blurHandler=Symbol('blurHandler');var $focusHandler=Symbol('focusHandler');var $changeHandler=Symbol('changeHandler');var $pointerChangeHandler=Symbol('pointerChangeHandler');var $onBlur=Symbol('onBlur');var $onFocus=Symbol('onFocus');var $onChange=Symbol('onChange');var $onPointerChange=Symbol('onPointerChange');var $waitingToPromptUser=Symbol('waitingToPromptUser');var $userHasInteracted=Symbol('userHasInteracted');var $promptElementVisibleTime=Symbol('promptElementVisibleTime');var $lastPromptOffset=Symbol('lastPromptOffset');var $focusedTime=Symbol('focusedTime');var $zoomAdjustedFieldOfView=Symbol('zoomAdjustedFieldOfView');var $lastSpherical=Symbol('lastSpherical');var $jumpCamera=Symbol('jumpCamera');var $initialized$1=Symbol('initialized');var $maintainThetaPhi=Symbol('maintainThetaPhi');var $syncCameraOrbit=Symbol('syncCameraOrbit');var $syncFieldOfView=Symbol('syncFieldOfView');var $syncCameraTarget=Symbol('syncCameraTarget');var $syncMinCameraOrbit=Symbol('syncMinCameraOrbit');var $syncMaxCameraOrbit=Symbol('syncMaxCameraOrbit');var $syncMinFieldOfView=Symbol('syncMinFieldOfView');var $syncMaxFieldOfView=Symbol('syncMaxFieldOfView');var ControlsMixin=function ControlsMixin(ModelViewerElement){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s;var ControlsModelViewerElement=/*#__PURE__*/function(_ModelViewerElement4){_inherits(ControlsModelViewerElement,_ModelViewerElement4);var _super32=_createSuper(ControlsModelViewerElement);function ControlsModelViewerElement(){var _this63;_classCallCheck(this,ControlsModelViewerElement);_this63=_super32.apply(this,arguments);_this63.cameraControls=false;_this63.cameraOrbit=DEFAULT_CAMERA_ORBIT;_this63.cameraTarget=DEFAULT_CAMERA_TARGET;_this63.fieldOfView=DEFAULT_FIELD_OF_VIEW;_this63.minCameraOrbit='auto';_this63.maxCameraOrbit='auto';_this63.minFieldOfView='auto';_this63.maxFieldOfView='auto';_this63.interactionPromptThreshold=DEFAULT_INTERACTION_PROMPT_THRESHOLD;_this63.interactionPromptStyle=InteractionPromptStyle.WIGGLE;_this63.interactionPrompt=InteractionPromptStrategy.AUTO;_this63.interactionPolicy=InteractionPolicy.ALWAYS_ALLOW;_this63.orbitSensitivity=1;_this63.touchAction=TouchAction.PAN_Y;_this63[_a]=_this63.shadowRoot.querySelector('.interaction-prompt');_this63[_b]=_this63.shadowRoot.querySelector('.interaction-prompt > .animated-container');_this63[_c]=Infinity;_this63[_d]=0;_this63[_e]=Infinity;_this63[_f]=false;_this63[_g]=false;_this63[_h]=new SmoothControls(_this63[$scene].camera,_this63[$userInputElement]);_this63[_j]=0;_this63[_k]=new Spherical();_this63[_l]=false;_this63[_m]=false;_this63[_o]=false;_this63[_p]=function(event){return _this63[$onChange](event);};_this63[_q]=function(event){return _this63[$onPointerChange](event);};_this63[_r]=function(){return _this63[$onFocus]();};_this63[_s]=function(){return _this63[$onBlur]();};return _this63;}_createClass(ControlsModelViewerElement,[{key:"getCameraOrbit",value:function getCameraOrbit(){var _this$$lastSpherical=this[$lastSpherical],theta=_this$$lastSpherical.theta,phi=_this$$lastSpherical.phi,radius=_this$$lastSpherical.radius;return{theta:theta,phi:phi,radius:radius};}},{key:"getCameraTarget",value:function getCameraTarget(){return toVector3D(this[$scene].getTarget());}},{key:"getFieldOfView",value:function getFieldOfView(){return this[$controls].getFieldOfView();}},{key:"getMinimumFieldOfView",value:function getMinimumFieldOfView(){return this[$controls].options.minimumFieldOfView;}},{key:"getMaximumFieldOfView",value:function getMaximumFieldOfView(){return this[$controls].options.maximumFieldOfView;}},{key:"jumpCameraToGoal",value:function jumpCameraToGoal(){this[$jumpCamera]=true;this.requestUpdate($jumpCamera,false);}},{key:"resetInteractionPrompt",value:function resetInteractionPrompt(){this[$lastPromptOffset]=0;this[$promptElementVisibleTime]=Infinity;this[$userHasInteracted]=false;this[$waitingToPromptUser]=this.interactionPrompt===InteractionPromptStrategy.AUTO&&this.cameraControls;}},{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(ControlsModelViewerElement.prototype),"connectedCallback",this).call(this);this[$controls].addEventListener('change',this[$changeHandler]);this[$controls].addEventListener('pointer-change-start',this[$pointerChangeHandler]);this[$controls].addEventListener('pointer-change-end',this[$pointerChangeHandler]);}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(ControlsModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$controls].removeEventListener('change',this[$changeHandler]);this[$controls].removeEventListener('pointer-change-start',this[$pointerChangeHandler]);this[$controls].removeEventListener('pointer-change-end',this[$pointerChangeHandler]);}},{key:"updated",value:function updated(changedProperties){var _this64=this;_get(_getPrototypeOf(ControlsModelViewerElement.prototype),"updated",this).call(this,changedProperties);var controls=this[$controls];var input=this[$userInputElement];if(changedProperties.has('cameraControls')){if(this.cameraControls){controls.enableInteraction();if(this.interactionPrompt===InteractionPromptStrategy.AUTO){this[$waitingToPromptUser]=true;}input.addEventListener('focus',this[$focusHandler]);input.addEventListener('blur',this[$blurHandler]);}else{input.removeEventListener('focus',this[$focusHandler]);input.removeEventListener('blur',this[$blurHandler]);controls.disableInteraction();this[$deferInteractionPrompt]();}}if(changedProperties.has('interactionPrompt')||changedProperties.has('cameraControls')||changedProperties.has('src')){if(this.interactionPrompt===InteractionPromptStrategy.AUTO&&this.cameraControls&&!this[$userHasInteracted]){this[$waitingToPromptUser]=true;}else{this[$deferInteractionPrompt]();}}if(changedProperties.has('interactionPromptStyle')){this[$promptElement].classList.toggle('wiggle',this.interactionPromptStyle===InteractionPromptStyle.WIGGLE);}if(changedProperties.has('interactionPolicy')){var interactionPolicy=this.interactionPolicy;controls.applyOptions({interactionPolicy:interactionPolicy});}if(changedProperties.has('touchAction')){var touchAction=this.touchAction;controls.applyOptions({touchAction:touchAction});}if(changedProperties.has('orbitSensitivity')){this[$controls].sensitivity=this.orbitSensitivity;}if(this[$jumpCamera]===true){Promise.resolve().then(function(){_this64[$controls].jumpToGoal();_this64[$scene].jumpToGoal();_this64[$jumpCamera]=false;});}}},{key:(_a=$promptElement,_b=$promptAnimatedContainer,_c=$focusedTime,_d=$lastPromptOffset,_e=$promptElementVisibleTime,_f=$userHasInteracted,_g=$waitingToPromptUser,_h=$controls,_j=$zoomAdjustedFieldOfView,_k=$lastSpherical,_l=$jumpCamera,_m=$initialized$1,_o=$maintainThetaPhi,_p=$changeHandler,_q=$pointerChangeHandler,_r=$focusHandler,_s=$blurHandler,$syncFieldOfView),value:function value(style){this[$controls].setFieldOfView(style[0]*180/Math.PI);}},{key:$syncCameraOrbit,value:function value(style){if(this[$maintainThetaPhi]){var _this$getCameraOrbit=this.getCameraOrbit(),theta=_this$getCameraOrbit.theta,phi=_this$getCameraOrbit.phi;style[0]=theta;style[1]=phi;this[$maintainThetaPhi]=false;}this[$controls].setOrbit(style[0],style[1],style[2]);}},{key:$syncMinCameraOrbit,value:function value(style){this[$controls].applyOptions({minimumAzimuthalAngle:style[0],minimumPolarAngle:style[1],minimumRadius:style[2]});this.jumpCameraToGoal();}},{key:$syncMaxCameraOrbit,value:function value(style){this[$controls].applyOptions({maximumAzimuthalAngle:style[0],maximumPolarAngle:style[1],maximumRadius:style[2]});this[$updateCameraForRadius](style[2]);this.jumpCameraToGoal();}},{key:$syncMinFieldOfView,value:function value(style){this[$controls].applyOptions({minimumFieldOfView:style[0]*180/Math.PI});this.jumpCameraToGoal();}},{key:$syncMaxFieldOfView,value:function value(style){this[$controls].applyOptions({maximumFieldOfView:style[0]*180/Math.PI});this.jumpCameraToGoal();}},{key:$syncCameraTarget,value:function value(style){var _style2=_slicedToArray(style,3),x=_style2[0],y=_style2[1],z=_style2[2];this[$scene].setTarget(x,y,z);this[$renderer].arRenderer.updateTarget();}},{key:$tick$1,value:function value(time,delta){_get(_getPrototypeOf(ControlsModelViewerElement.prototype),$tick$1,this).call(this,time,delta);if(this[$renderer].isPresenting||!this[$hasTransitioned]()){return;}var now=performance.now();if(this[$waitingToPromptUser]){var thresholdTime=this.interactionPrompt===InteractionPromptStrategy.AUTO?this[$loadedTime]:this[$focusedTime];if(this.loaded&&now>thresholdTime+this.interactionPromptThreshold){this[$userInputElement].setAttribute('aria-label',INTERACTION_PROMPT);this[$waitingToPromptUser]=false;this[$promptElementVisibleTime]=now;this[$promptElement].classList.add('visible');}}if(isFinite(this[$promptElementVisibleTime])&&this.interactionPromptStyle===InteractionPromptStyle.WIGGLE){var scene=this[$scene];var animationTime=(now-this[$promptElementVisibleTime])/PROMPT_ANIMATION_TIME%1;var offset=wiggle(animationTime);var opacity=fade(animationTime);this[$promptAnimatedContainer].style.opacity="".concat(opacity);if(offset!==this[$lastPromptOffset]){var xOffset=offset*scene.width*0.05;var deltaTheta=(offset-this[$lastPromptOffset])*Math.PI/16;this[$promptAnimatedContainer].style.transform="translateX(".concat(xOffset,"px)");this[$controls].adjustOrbit(deltaTheta,0,0);this[$lastPromptOffset]=offset;}}this[$controls].update(time,delta);this[$scene].updateTarget(delta);}},{key:$deferInteractionPrompt,value:function value(){this[$waitingToPromptUser]=false;this[$promptElement].classList.remove('visible');this[$promptElementVisibleTime]=Infinity;}},{key:$updateCameraForRadius,value:function value(radius){var idealCameraDistance=this[$scene].model.idealCameraDistance;var maximumRadius=Math.max(idealCameraDistance,radius);var near=0;var far=2*maximumRadius;this[$controls].updateNearFar(near,far);}},{key:$updateAria,value:function value(){var _this$$lastSpherical2=this[$lastSpherical],lastTheta=_this$$lastSpherical2.theta,lastPhi=_this$$lastSpherical2.phi;var _this$$controls$getCa=this[$controls].getCameraSpherical(this[$lastSpherical]),theta=_this$$controls$getCa.theta,phi=_this$$controls$getCa.phi;var rootNode=this.getRootNode();if(rootNode!=null&&rootNode.activeElement===this){var lastAzimuthalQuadrant=(4+Math.floor((lastTheta%TAU+QUARTER_PI)/HALF_PI))%4;var azimuthalQuadrant=(4+Math.floor((theta%TAU+QUARTER_PI)/HALF_PI))%4;var lastPolarTrient=Math.floor(lastPhi/THIRD_PI);var polarTrient=Math.floor(phi/THIRD_PI);if(azimuthalQuadrant!==lastAzimuthalQuadrant||polarTrient!==lastPolarTrient){var azimuthalQuadrantLabel=AZIMUTHAL_QUADRANT_LABELS[azimuthalQuadrant];var polarTrientLabel=POLAR_TRIENT_LABELS[polarTrient];var ariaLabel="View from stage ".concat(polarTrientLabel).concat(azimuthalQuadrantLabel);this[$userInputElement].setAttribute('aria-label',ariaLabel);}}}},{key:$onResize,value:function value(event){var controls=this[$controls];var oldFramedFieldOfView=this[$scene].framedFieldOfView;_get(_getPrototypeOf(ControlsModelViewerElement.prototype),$onResize,this).call(this,event);var newFramedFieldOfView=this[$scene].framedFieldOfView;var zoom=controls.getFieldOfView()/oldFramedFieldOfView;this[$zoomAdjustedFieldOfView]=newFramedFieldOfView*zoom;controls.updateAspect(this[$scene].aspect);this.requestUpdate('maxFieldOfView',this.maxFieldOfView);this.requestUpdate('fieldOfView',this.fieldOfView);this.jumpCameraToGoal();}},{key:$onModelLoad,value:function value(){_get(_getPrototypeOf(ControlsModelViewerElement.prototype),$onModelLoad,this).call(this);var framedFieldOfView=this[$scene].framedFieldOfView;this[$zoomAdjustedFieldOfView]=framedFieldOfView;if(this[$initialized$1]){this[$maintainThetaPhi]=true;}else{this[$initialized$1]=true;}this.requestUpdate('maxFieldOfView',this.maxFieldOfView);this.requestUpdate('fieldOfView',this.fieldOfView);this.requestUpdate('minCameraOrbit',this.minCameraOrbit);this.requestUpdate('maxCameraOrbit',this.maxCameraOrbit);this.requestUpdate('cameraOrbit',this.cameraOrbit);this.requestUpdate('cameraTarget',this.cameraTarget);this.jumpCameraToGoal();}},{key:$onFocus,value:function value(){var input=this[$userInputElement];if(!isFinite(this[$focusedTime])){this[$focusedTime]=performance.now();}var ariaLabel=this[$ariaLabel];if(input.getAttribute('aria-label')!==ariaLabel){input.setAttribute('aria-label',ariaLabel);}if(this.interactionPrompt===InteractionPromptStrategy.WHEN_FOCUSED&&!this[$userHasInteracted]){this[$waitingToPromptUser]=true;}}},{key:$onBlur,value:function value(){if(this.interactionPrompt!==InteractionPromptStrategy.WHEN_FOCUSED){return;}this[$waitingToPromptUser]=false;this[$promptElement].classList.remove('visible');this[$promptElementVisibleTime]=Infinity;this[$focusedTime]=Infinity;}},{key:$onChange,value:function value(_ref8){var source=_ref8.source;this[$updateAria]();this[$needsRender]();if(source===ChangeSource.USER_INTERACTION){this[$userHasInteracted]=true;this[$deferInteractionPrompt]();}this.dispatchEvent(new CustomEvent('camera-change',{detail:{source:source}}));}},{key:$onPointerChange,value:function value(event){if(event.type==='pointer-change-start'){this[$container].classList.add('pointer-tumbling');}else{this[$container].classList.remove('pointer-tumbling');}}}]);return ControlsModelViewerElement;}(ModelViewerElement);__decorate$3([property({type:Boolean,attribute:'camera-controls'})],ControlsModelViewerElement.prototype,"cameraControls",void 0);__decorate$3([style({intrinsics:cameraOrbitIntrinsics,observeEffects:true,updateHandler:$syncCameraOrbit}),property({type:String,attribute:'camera-orbit',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"cameraOrbit",void 0);__decorate$3([style({intrinsics:cameraTargetIntrinsics,observeEffects:true,updateHandler:$syncCameraTarget}),property({type:String,attribute:'camera-target',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"cameraTarget",void 0);__decorate$3([style({intrinsics:fieldOfViewIntrinsics,observeEffects:true,updateHandler:$syncFieldOfView}),property({type:String,attribute:'field-of-view',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"fieldOfView",void 0);__decorate$3([style({intrinsics:minCameraOrbitIntrinsics,updateHandler:$syncMinCameraOrbit}),property({type:String,attribute:'min-camera-orbit',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"minCameraOrbit",void 0);__decorate$3([style({intrinsics:maxCameraOrbitIntrinsics,updateHandler:$syncMaxCameraOrbit}),property({type:String,attribute:'max-camera-orbit',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"maxCameraOrbit",void 0);__decorate$3([style({intrinsics:minFieldOfViewIntrinsics,updateHandler:$syncMinFieldOfView}),property({type:String,attribute:'min-field-of-view',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"minFieldOfView",void 0);__decorate$3([style({intrinsics:maxFieldOfViewIntrinsics,updateHandler:$syncMaxFieldOfView}),property({type:String,attribute:'max-field-of-view',hasChanged:function hasChanged(){return true;}})],ControlsModelViewerElement.prototype,"maxFieldOfView",void 0);__decorate$3([property({type:Number,attribute:'interaction-prompt-threshold'})],ControlsModelViewerElement.prototype,"interactionPromptThreshold",void 0);__decorate$3([property({type:String,attribute:'interaction-prompt-style'})],ControlsModelViewerElement.prototype,"interactionPromptStyle",void 0);__decorate$3([property({type:String,attribute:'interaction-prompt'})],ControlsModelViewerElement.prototype,"interactionPrompt",void 0);__decorate$3([property({type:String,attribute:'interaction-policy'})],ControlsModelViewerElement.prototype,"interactionPolicy",void 0);__decorate$3([property({type:Number,attribute:'orbit-sensitivity'})],ControlsModelViewerElement.prototype,"orbitSensitivity",void 0);__decorate$3([property({type:String,attribute:'touch-action'})],ControlsModelViewerElement.prototype,"touchAction",void 0);return ControlsModelViewerElement;};var __decorate$4=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var BASE_OPACITY=0.1;var DEFAULT_SHADOW_INTENSITY=0.0;var DEFAULT_SHADOW_SOFTNESS=1.0;var DEFAULT_EXPOSURE=1.0;var $currentEnvironmentMap=Symbol('currentEnvironmentMap');var $applyEnvironmentMap=Symbol('applyEnvironmentMap');var $updateEnvironment=Symbol('updateEnvironment');var $cancelEnvironmentUpdate=Symbol('cancelEnvironmentUpdate');var $onPreload=Symbol('onPreload');var EnvironmentMixin=function EnvironmentMixin(ModelViewerElement){var _a,_b,_c;var EnvironmentModelViewerElement=/*#__PURE__*/function(_ModelViewerElement5){_inherits(EnvironmentModelViewerElement,_ModelViewerElement5);var _super33=_createSuper(EnvironmentModelViewerElement);function EnvironmentModelViewerElement(){var _this65;_classCallCheck(this,EnvironmentModelViewerElement);_this65=_super33.apply(this,arguments);_this65.environmentImage=null;_this65.skyboxImage=null;_this65.shadowIntensity=DEFAULT_SHADOW_INTENSITY;_this65.shadowSoftness=DEFAULT_SHADOW_SOFTNESS;_this65.exposure=DEFAULT_EXPOSURE;_this65[_a]=null;_this65[_b]=null;_this65[_c]=function(event){if(event.element===_assertThisInitialized(_this65)){_this65[$updateEnvironment]();}};return _this65;}_createClass(EnvironmentModelViewerElement,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(EnvironmentModelViewerElement.prototype),"connectedCallback",this).call(this);this[$renderer].loader.addEventListener('preload',this[$onPreload]);}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(EnvironmentModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$renderer].loader.removeEventListener('preload',this[$onPreload]);}},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(EnvironmentModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('shadowIntensity')){this[$scene].setShadowIntensity(this.shadowIntensity*BASE_OPACITY);this[$needsRender]();}if(changedProperties.has('shadowSoftness')){this[$scene].setShadowSoftness(this.shadowSoftness);this[$needsRender]();}if(changedProperties.has('exposure')){this[$scene].exposure=this.exposure;this[$needsRender]();}if((changedProperties.has('environmentImage')||changedProperties.has('skyboxImage'))&&this[$shouldAttemptPreload]()){this[$updateEnvironment]();}}},{key:(_a=$currentEnvironmentMap,_b=$cancelEnvironmentUpdate,_c=$onPreload,$onModelLoad),value:function value(){_get(_getPrototypeOf(EnvironmentModelViewerElement.prototype),$onModelLoad,this).call(this);if(this[$currentEnvironmentMap]!=null){this[$applyEnvironmentMap](this[$currentEnvironmentMap]);}}},{key:$updateEnvironment,value:function(){var _value7=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee25(){var _this66=this;var skyboxImage,environmentImage,textureUtils,_yield$Promise,environmentMap,skybox,environment;return regeneratorRuntime.wrap(function _callee25$(_context26){while(1){switch(_context26.prev=_context26.next){case 0:skyboxImage=this.skyboxImage,environmentImage=this.environmentImage;if(this[$cancelEnvironmentUpdate]!=null){this[$cancelEnvironmentUpdate]();this[$cancelEnvironmentUpdate]=null;}textureUtils=this[$renderer].textureUtils;if(!(textureUtils==null)){_context26.next=5;break;}return _context26.abrupt("return");case 5:_context26.prev=5;_context26.next=8;return new Promise(/*#__PURE__*/function(){var _ref9=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee24(resolve,reject){var texturesLoad;return regeneratorRuntime.wrap(function _callee24$(_context25){while(1){switch(_context25.prev=_context25.next){case 0:texturesLoad=textureUtils.generateEnvironmentMapAndSkybox(deserializeUrl(skyboxImage),deserializeUrl(environmentImage),{progressTracker:_this66[$progressTracker]});_this66[$cancelEnvironmentUpdate]=function(){return reject(texturesLoad);};_context25.t0=resolve;_context25.next=5;return texturesLoad;case 5:_context25.t1=_context25.sent;(0,_context25.t0)(_context25.t1);case 7:case"end":return _context25.stop();}}},_callee24);}));return function(_x23,_x24){return _ref9.apply(this,arguments);};}());case 8:_yield$Promise=_context26.sent;environmentMap=_yield$Promise.environmentMap;skybox=_yield$Promise.skybox;environment=environmentMap.texture;if(skybox!=null){this[$scene].background=skybox.userData.url===environment.userData.url?environment:skybox;}else{this[$scene].background=null;}this[$applyEnvironmentMap](environmentMap.texture);this[$scene].model.dispatchEvent({type:'envmap-update'});_context26.next=22;break;case 17:_context26.prev=17;_context26.t0=_context26["catch"](5);if(!_instanceof(_context26.t0,Error)){_context26.next=22;break;}this[$applyEnvironmentMap](null);throw _context26.t0;case 22:case"end":return _context26.stop();}}},_callee25,this,[[5,17]]);}));function value(){return _value7.apply(this,arguments);}return value;}()},{key:$applyEnvironmentMap,value:function value(environmentMap){this[$currentEnvironmentMap]=environmentMap;this[$scene].environment=this[$currentEnvironmentMap];this.dispatchEvent(new CustomEvent('environment-change'));this[$needsRender]();}}]);return EnvironmentModelViewerElement;}(ModelViewerElement);__decorate$4([property({type:String,attribute:'environment-image'})],EnvironmentModelViewerElement.prototype,"environmentImage",void 0);__decorate$4([property({type:String,attribute:'skybox-image'})],EnvironmentModelViewerElement.prototype,"skyboxImage",void 0);__decorate$4([property({type:Number,attribute:'shadow-intensity'})],EnvironmentModelViewerElement.prototype,"shadowIntensity",void 0);__decorate$4([property({type:Number,attribute:'shadow-softness'})],EnvironmentModelViewerElement.prototype,"shadowSoftness",void 0);__decorate$4([property({type:Number})],EnvironmentModelViewerElement.prototype,"exposure",void 0);return EnvironmentModelViewerElement;};var _a$b,_b$9;var INITIAL_STATUS_ANNOUNCEMENT='This page includes one or more 3D models that are loading';var FINISHED_LOADING_ANNOUNCEMENT='All 3D models in the page have loaded';var UPDATE_STATUS_DEBOUNCE_MS=100;var $modelViewerStatusInstance=Symbol('modelViewerStatusInstance');var $updateStatus=Symbol('updateStatus');var LoadingStatusAnnouncer=/*#__PURE__*/function(_EventDispatcher6){_inherits(LoadingStatusAnnouncer,_EventDispatcher6);var _super34=_createSuper(LoadingStatusAnnouncer);function LoadingStatusAnnouncer(){var _this67;_classCallCheck(this,LoadingStatusAnnouncer);_this67=_super34.call(this);_this67[_a$b]=null;_this67.registeredInstanceStatuses=new Map();_this67.loadingPromises=[];_this67.statusElement=document.createElement('p');_this67.statusUpdateInProgress=false;_this67[_b$9]=debounce(function(){return _this67.updateStatus();},UPDATE_STATUS_DEBOUNCE_MS);var _assertThisInitialize=_assertThisInitialized(_this67),statusElement=_assertThisInitialize.statusElement;var style=statusElement.style;statusElement.setAttribute('role','status');statusElement.classList.add('screen-reader-only');style.top=style.left='0';style.pointerEvents='none';return _this67;}_createClass(LoadingStatusAnnouncer,[{key:"registerInstance",value:function registerInstance(modelViewer){if(this.registeredInstanceStatuses.has(modelViewer)){return;}var onUnregistered=function onUnregistered(){};var loadShouldBeMeasured=modelViewer.loaded===false&&!!modelViewer.src;var loadAttemptCompletes=new Promise(function(resolve){if(!loadShouldBeMeasured){resolve();return;}var resolveHandler=function resolveHandler(){resolve();modelViewer.removeEventListener('load',resolveHandler);modelViewer.removeEventListener('error',resolveHandler);};modelViewer.addEventListener('load',resolveHandler);modelViewer.addEventListener('error',resolveHandler);onUnregistered=resolveHandler;});this.registeredInstanceStatuses.set(modelViewer,{onUnregistered:onUnregistered});this.loadingPromises.push(loadAttemptCompletes);if(this.modelViewerStatusInstance==null){this.modelViewerStatusInstance=modelViewer;}}},{key:"unregisterInstance",value:function unregisterInstance(modelViewer){if(!this.registeredInstanceStatuses.has(modelViewer)){return;}var statuses=this.registeredInstanceStatuses;var instanceStatus=statuses.get(modelViewer);statuses.delete(modelViewer);instanceStatus.onUnregistered();if(this.modelViewerStatusInstance===modelViewer){this.modelViewerStatusInstance=statuses.size>0?getFirstMapKey(statuses):null;}}},{key:"updateStatus",value:function(){var _updateStatus=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee26(){var loadingPromises;return regeneratorRuntime.wrap(function _callee26$(_context27){while(1){switch(_context27.prev=_context27.next){case 0:if(!(this.statusUpdateInProgress||this.loadingPromises.length===0)){_context27.next=2;break;}return _context27.abrupt("return");case 2:this.statusElement.textContent=INITIAL_STATUS_ANNOUNCEMENT;this.statusUpdateInProgress=true;this.dispatchEvent({type:'initial-status-announced'});case 5:if(!this.loadingPromises.length){_context27.next=12;break;}loadingPromises=this.loadingPromises;this.loadingPromises=[];_context27.next=10;return Promise.all(loadingPromises);case 10:_context27.next=5;break;case 12:this.statusElement.textContent=FINISHED_LOADING_ANNOUNCEMENT;this.statusUpdateInProgress=false;this.dispatchEvent({type:'finished-loading-announced'});case 15:case"end":return _context27.stop();}}},_callee26,this);}));function updateStatus(){return _updateStatus.apply(this,arguments);}return updateStatus;}()},{key:"modelViewerStatusInstance",get:function get(){return this[$modelViewerStatusInstance];},set:function set(value){var currentInstance=this[$modelViewerStatusInstance];if(currentInstance===value){return;}var statusElement=this.statusElement;if(value!=null&&value.shadowRoot!=null){value.shadowRoot.appendChild(statusElement);}else if(statusElement.parentNode!=null){statusElement.parentNode.removeChild(statusElement);}this[$modelViewerStatusInstance]=value;this[$updateStatus]();}}]);return LoadingStatusAnnouncer;}(EventDispatcher);_a$b=$modelViewerStatusInstance,_b$9=$updateStatus;var __decorate$5=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var PROGRESS_BAR_UPDATE_THRESHOLD=100;var PROGRESS_MASK_BASE_OPACITY=0.2;var DEFAULT_DRACO_DECODER_LOCATION='https://www.gstatic.com/draco/versioned/decoders/1.3.6/';var SPACE_KEY=32;var ENTER_KEY=13;var RevealStrategy={AUTO:'auto',INTERACTION:'interaction',MANUAL:'manual'};var LoadingStrategy={AUTO:'auto',LAZY:'lazy',EAGER:'eager'};var PosterDismissalSource={INTERACTION:'interaction'};var loadingStatusAnnouncer=new LoadingStatusAnnouncer();var $defaultProgressBarElement=Symbol('defaultProgressBarElement');var $defaultProgressMaskElement=Symbol('defaultProgressMaskElement');var $posterContainerElement=Symbol('posterContainerElement');var $defaultPosterElement=Symbol('defaultPosterElement');var $posterDismissalSource=Symbol('posterDismissalSource');var $showPoster=Symbol('showPoster');var $hidePoster=Symbol('hidePoster');var $modelIsRevealed=Symbol('modelIsRevealed');var $updateProgressBar=Symbol('updateProgressBar');var $lastReportedProgress=Symbol('lastReportedProgress');var $transitioned=Symbol('transitioned');var $ariaLabelCallToAction=Symbol('ariaLabelCallToAction');var $clickHandler=Symbol('clickHandler');var $keydownHandler=Symbol('keydownHandler');var $progressHandler=Symbol('processHandler');var $onClick=Symbol('onClick');var $onKeydown=Symbol('onKeydown');var $onProgress=Symbol('onProgress');var LoadingMixin=function LoadingMixin(ModelViewerElement){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o;var LoadingModelViewerElement=/*#__PURE__*/function(_ModelViewerElement6){_inherits(LoadingModelViewerElement,_ModelViewerElement6);var _super35=_createSuper(LoadingModelViewerElement);function LoadingModelViewerElement(){var _this68;_classCallCheck(this,LoadingModelViewerElement);for(var _len3=arguments.length,args=new Array(_len3),_key6=0;_key6<_len3;_key6++){args[_key6]=arguments[_key6];}_this68=_super35.call.apply(_super35,[this].concat(args));_this68.poster=null;_this68.reveal=RevealStrategy.AUTO;_this68.loading=LoadingStrategy.AUTO;_this68[_a]=false;_this68[_b]=false;_this68[_c]=0;_this68[_d]=null;_this68[_e]=_this68.shadowRoot.querySelector('.slot.poster');_this68[_f]=_this68.shadowRoot.querySelector('#default-poster');_this68[_g]=_this68.shadowRoot.querySelector('#default-progress-bar > .bar');_this68[_h]=_this68.shadowRoot.querySelector('#default-progress-bar > .mask');_this68[_j]=_this68[$defaultPosterElement].getAttribute('aria-label');_this68[_k]=function(){return _this68[$onClick]();};_this68[_l]=function(event){return _this68[$onKeydown](event);};_this68[_m]=function(event){return _this68[$onProgress](event);};_this68[_o]=throttle(function(progress){var parentNode=_this68[$defaultProgressBarElement].parentNode;requestAnimationFrame(function(){_this68[$defaultProgressMaskElement].style.opacity="".concat((1.0-progress)*PROGRESS_MASK_BASE_OPACITY);_this68[$defaultProgressBarElement].style.transform="scaleX(".concat(progress,")");if(progress===0){parentNode.removeChild(_this68[$defaultProgressBarElement]);parentNode.appendChild(_this68[$defaultProgressBarElement]);}if(progress===1.0){_this68[$defaultProgressBarElement].classList.add('hide');}else{_this68[$defaultProgressBarElement].classList.remove('hide');}});},PROGRESS_BAR_UPDATE_THRESHOLD);var ModelViewerElement=self.ModelViewerElement||{};var dracoDecoderLocation=ModelViewerElement.dracoDecoderLocation||DEFAULT_DRACO_DECODER_LOCATION;CachingGLTFLoader.setDRACODecoderLocation(dracoDecoderLocation);return _this68;}_createClass(LoadingModelViewerElement,[{key:"dismissPoster",value:function dismissPoster(){if(this[$sceneIsReady]()){this[$hidePoster]();}else{this[$posterDismissalSource]=PosterDismissalSource.INTERACTION;this[$updateSource]();}}},{key:"getDimensions",value:function getDimensions(){return toVector3D(this[$scene].model.size);}},{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(LoadingModelViewerElement.prototype),"connectedCallback",this).call(this);this[$posterContainerElement].addEventListener('click',this[$clickHandler]);this[$posterContainerElement].addEventListener('keydown',this[$keydownHandler]);this[$progressTracker].addEventListener('progress',this[$progressHandler]);loadingStatusAnnouncer.registerInstance(this);}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(LoadingModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$posterContainerElement].removeEventListener('click',this[$clickHandler]);this[$posterContainerElement].removeEventListener('keydown',this[$keydownHandler]);this[$progressTracker].removeEventListener('progress',this[$progressHandler]);loadingStatusAnnouncer.unregisterInstance(this);}},{key:"updated",value:function(){var _updated=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee27(changedProperties){return regeneratorRuntime.wrap(function _callee27$(_context28){while(1){switch(_context28.prev=_context28.next){case 0:_get(_getPrototypeOf(LoadingModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('poster')&&this.poster!=null){this[$defaultPosterElement].style.backgroundImage="url(".concat(this.poster,")");}if(changedProperties.has('alt')){this[$defaultPosterElement].setAttribute('aria-label',"".concat(this[$ariaLabel],". ").concat(this[$ariaLabelCallToAction]));}if(changedProperties.has('reveal')||changedProperties.has('loaded')){if(!this[$sceneIsReady]()){this[$updateSource]();}}case 4:case"end":return _context28.stop();}}},_callee27,this);}));function updated(_x25){return _updated.apply(this,arguments);}return updated;}()},{key:(_a=$modelIsRevealed,_b=$transitioned,_c=$lastReportedProgress,_d=$posterDismissalSource,_e=$posterContainerElement,_f=$defaultPosterElement,_g=$defaultProgressBarElement,_h=$defaultProgressMaskElement,_j=$ariaLabelCallToAction,_k=$clickHandler,_l=$keydownHandler,_m=$progressHandler,_o=$updateProgressBar,$onClick),value:function value(){if(this.reveal===RevealStrategy.MANUAL){return;}this.dismissPoster();}},{key:$onKeydown,value:function value(event){if(this.reveal===RevealStrategy.MANUAL){return;}switch(event.keyCode){case SPACE_KEY:case ENTER_KEY:this.dismissPoster();break;}}},{key:$onProgress,value:function value(event){var progress=event.detail.totalProgress;this[$lastReportedProgress]=Math.max(progress,this[$lastReportedProgress]);if(progress===1.0){this[$updateProgressBar].flush();if(this[$sceneIsReady]()&&(this[$posterDismissalSource]!=null||this.reveal===RevealStrategy.AUTO)){this[$hidePoster]();}}this[$updateProgressBar](progress);this.dispatchEvent(new CustomEvent('progress',{detail:{totalProgress:progress}}));}},{key:$shouldAttemptPreload,value:function value(){return!!this.src&&(this[$posterDismissalSource]!=null||this.loading===LoadingStrategy.EAGER||this.reveal===RevealStrategy.AUTO&&this[$isElementInViewport]);}},{key:$sceneIsReady,value:function value(){var src=this.src;return!!src&&_get(_getPrototypeOf(LoadingModelViewerElement.prototype),$sceneIsReady,this).call(this)&&this[$lastReportedProgress]===1.0;}},{key:$showPoster,value:function value(){var posterContainerElement=this[$posterContainerElement];var defaultPosterElement=this[$defaultPosterElement];defaultPosterElement.removeAttribute('tabindex');defaultPosterElement.removeAttribute('aria-hidden');posterContainerElement.classList.add('show');var oldVisibility=this.modelIsVisible;this[$modelIsRevealed]=false;this[$announceModelVisibility](oldVisibility);this[$transitioned]=false;}},{key:$hidePoster,value:function value(){var _this69=this;this[$posterDismissalSource]=null;var posterContainerElement=this[$posterContainerElement];var defaultPosterElement=this[$defaultPosterElement];if(posterContainerElement.classList.contains('show')){posterContainerElement.classList.remove('show');var oldVisibility=this.modelIsVisible;this[$modelIsRevealed]=true;this[$announceModelVisibility](oldVisibility);posterContainerElement.addEventListener('transitionend',function(){requestAnimationFrame(function(){_this69[$transitioned]=true;var root=_this69.getRootNode();if(root&&root.activeElement===_this69){_this69[$userInputElement].focus();}defaultPosterElement.setAttribute('aria-hidden','true');defaultPosterElement.tabIndex=-1;_this69.dispatchEvent(new CustomEvent('poster-dismissed'));});},{once:true});}}},{key:$getModelIsVisible,value:function value(){return _get(_getPrototypeOf(LoadingModelViewerElement.prototype),$getModelIsVisible,this).call(this)&&this[$modelIsRevealed];}},{key:$hasTransitioned,value:function value(){return _get(_getPrototypeOf(LoadingModelViewerElement.prototype),$hasTransitioned,this).call(this)&&this[$transitioned];}},{key:$updateSource,value:function(){var _value8=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee28(){return regeneratorRuntime.wrap(function _callee28$(_context29){while(1){switch(_context29.prev=_context29.next){case 0:this[$lastReportedProgress]=0;if(this[$scene].model.currentGLTF==null||this.src==null||!this[$shouldAttemptPreload]()){this[$showPoster]();}_context29.next=4;return _get(_getPrototypeOf(LoadingModelViewerElement.prototype),$updateSource,this).call(this);case 4:case"end":return _context29.stop();}}},_callee28,this);}));function value(){return _value8.apply(this,arguments);}return value;}()}],[{key:"mapURLs",value:function mapURLs(callback){Renderer.singleton.loader[$loader].manager.setURLModifier(callback);}},{key:"dracoDecoderLocation",set:function set(value){CachingGLTFLoader.setDRACODecoderLocation(value);},get:function get(){return CachingGLTFLoader.getDRACODecoderLocation();}}]);return LoadingModelViewerElement;}(ModelViewerElement);__decorate$5([property({type:String})],LoadingModelViewerElement.prototype,"poster",void 0);__decorate$5([property({type:String})],LoadingModelViewerElement.prototype,"reveal",void 0);__decorate$5([property({type:String})],LoadingModelViewerElement.prototype,"loading",void 0);return LoadingModelViewerElement;};/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The protocol between 3DOM execution contexts is strictly defined. * Only specific types of messages are allowed, and their types are * all included in the ThreeDOMMessageType map. */var ThreeDOMMessageType={// === Host -> Scene Graph === // Used when the host execution context and scene graph execution context // are negotiating a connection HANDSHAKE:1,// A message that indicates that a custom script is meant to be imported // into the scene graph execution context IMPORT_SCRIPT:2,// A notification from the host execution context that the main Model has // changed, including the sparse, serialized scene graph of the new Model MODEL_CHANGE:3,// A notification that confirms or denies a request from the scene graph // context to mutate the scene graph MUTATION_RESULT:4,// === Scene Graph => Host === // Notification sent to the host execution context to indicate that the // scene graph execution context has finished initializing CONTEXT_INITIALIZED:5,// A request from the scene graph execution context to mutate some detail // of the backing host scene graph MUTATE:6};/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var $ownerModel=Symbol('ownerModel');/** * The basic implementation for all 3DOM scene graph participants. * Scene graph nodes are distinguished by their "owner" Model. All scene * graph nodes have an owner Model associated with them except for the * sole Model in the scene graph, whose ownerModel property is not defined. */var ThreeDOMElement=/*#__PURE__*/function(){function ThreeDOMElement(kernel){_classCallCheck(this,ThreeDOMElement);if(kernel==null){throw new Error('Illegal constructor');}this[$ownerModel]=kernel.model;}/** * The Model of provenance for this scene graph element, or undefined if * element is itself a Model. */_createClass(ThreeDOMElement,[{key:"ownerModel",get:function get(){return this[$ownerModel];}}]);return ThreeDOMElement;}();/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var $kernel=Symbol('kernel');var $uri=Symbol('uri');var $name=Symbol('name');var Image=/*#__PURE__*/function(_ThreeDOMElement){_inherits(Image,_ThreeDOMElement);var _super36=_createSuper(Image);function Image(kernel,serialized){var _this70;_classCallCheck(this,Image);_this70=_super36.call(this,kernel);_this70[$kernel]=kernel;_this70[$uri]=serialized.uri||null;if(serialized.name!=null){_this70[$name]=serialized.name;}return _this70;}_createClass(Image,[{key:"setURI",value:function(){var _setURI=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee29(uri){return regeneratorRuntime.wrap(function _callee29$(_context30){while(1){switch(_context30.prev=_context30.next){case 0:_context30.next=2;return this[$kernel].mutate(this,'uri',uri);case 2:this[$uri]=uri;case 3:case"end":return _context30.stop();}}},_callee29,this);}));function setURI(_x26){return _setURI.apply(this,arguments);}return setURI;}()},{key:"name",get:function get(){return this[$name];}},{key:"type",get:function get(){return this.uri!=null?'external':'embedded';}},{key:"uri",get:function get(){return this[$uri];}}]);return Image;}(ThreeDOMElement);/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$c,_b$a,_c$4;var $pbrMetallicRoughness=Symbol('pbrMetallicRoughness');var $normalTexture=Symbol('normalTexture');var $occlusionTexture=Symbol('occlusionTexture');var $emissiveTexture=Symbol('emissiveTexture');var $kernel$1=Symbol('kernel');var $name$1=Symbol('name');/** * A Material represents a live material in the backing scene graph. Its * primary purpose is to give the user write access to discrete properties * (for example, the base color factor) of the backing material. */var Material$1=/*#__PURE__*/function(_ThreeDOMElement2){_inherits(Material$1,_ThreeDOMElement2);var _super37=_createSuper(Material$1);function Material$1(kernel,serialized){var _this71;_classCallCheck(this,Material$1);_this71=_super37.call(this,kernel);_this71[_a$c]=null;_this71[_b$a]=null;_this71[_c$4]=null;_this71[$kernel$1]=kernel;if(serialized.name!=null){_this71[$name$1]=serialized.name;}var pbrMetallicRoughness=serialized.pbrMetallicRoughness,normalTexture=serialized.normalTexture,occlusionTexture=serialized.occlusionTexture,emissiveTexture=serialized.emissiveTexture;_this71[$pbrMetallicRoughness]=kernel.deserialize('pbr-metallic-roughness',pbrMetallicRoughness);if(normalTexture!=null){_this71[$normalTexture]=kernel.deserialize('texture-info',normalTexture);}if(occlusionTexture!=null){_this71[$occlusionTexture]=kernel.deserialize('texture-info',occlusionTexture);}if(emissiveTexture!=null){_this71[$emissiveTexture]=kernel.deserialize('texture-info',emissiveTexture);}return _this71;}/** * The PBR properties that are assigned to this material, if any. */_createClass(Material$1,[{key:"pbrMetallicRoughness",get:function get(){return this[$pbrMetallicRoughness];}},{key:"normalTexture",get:function get(){return this[$normalTexture];}},{key:"occlusionTexture",get:function get(){return this[$occlusionTexture];}},{key:"emissiveTexture",get:function get(){return this[$emissiveTexture];}/** * The name of the material. Note that names are optional and not * guaranteed to be unique. */},{key:"name",get:function get(){return this[$name$1];}}]);return Material$1;}(ThreeDOMElement);_a$c=$normalTexture,_b$a=$occlusionTexture,_c$4=$emissiveTexture;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$d;var $materials=Symbol('material');var $kernel$2=Symbol('kernel');/** * A Model is the root element of a 3DOM scene graph. It is considered the * element of provenance for all other elements that participate in the same * graph. All other elements in the graph can be accessed in from the Model * in some fashion. */var Model$1=/*#__PURE__*/function(_ThreeDOMElement3){_inherits(Model$1,_ThreeDOMElement3);var _super38=_createSuper(Model$1);function Model$1(kernel,serialized){var _this72;_classCallCheck(this,Model$1);_this72=_super38.call(this,kernel);_this72[_a$d]=Object.freeze([]);_this72[$kernel$2]=kernel;var _iterator21=_createForOfIteratorHelper(serialized.materials),_step21;try{for(_iterator21.s();!(_step21=_iterator21.n()).done;){var material=_step21.value;_this72[$kernel$2].deserialize('material',material);}}catch(err){_iterator21.e(err);}finally{_iterator21.f();}return _this72;}/** * The set of Material elements in the graph, in sparse traversal order. * Note that this set will include any Materials that are not part of the * currently activate scene. * * TODO(#1002): This value needs to be sensitive to scene graph order */_createClass(Model$1,[{key:"materials",get:function get(){return this[$kernel$2].getElementsByType('material');}/** * A Model has no owner model; it owns itself. */},{key:"ownerModel",get:function get(){return this;}}]);return Model$1;}(ThreeDOMElement);_a$d=$materials;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$e,_b$b;var $kernel$3=Symbol('kernel');var $baseColorFactor=Symbol('baseColorFactor');var $baseColorTexture=Symbol('baseColorTexture');var $metallicRoughnessTexture=Symbol('metallicRoughnessTexture');var $metallicFactor=Symbol('metallicFactor');var $roughnessFactor=Symbol('roughnessFactor');/** * PBRMetallicRoughness exposes the PBR properties for a given Material. */var PBRMetallicRoughness=/*#__PURE__*/function(_ThreeDOMElement4){_inherits(PBRMetallicRoughness,_ThreeDOMElement4);var _super39=_createSuper(PBRMetallicRoughness);function PBRMetallicRoughness(kernel,serialized){var _this73;_classCallCheck(this,PBRMetallicRoughness);_this73=_super39.call(this,kernel);_this73[_a$e]=null;_this73[_b$b]=null;_this73[$kernel$3]=kernel;_this73[$baseColorFactor]=Object.freeze(serialized.baseColorFactor);_this73[$metallicFactor]=serialized.metallicFactor;_this73[$roughnessFactor]=serialized.roughnessFactor;var baseColorTexture=serialized.baseColorTexture,metallicRoughnessTexture=serialized.metallicRoughnessTexture;if(baseColorTexture!=null){_this73[$baseColorTexture]=kernel.deserialize('texture-info',baseColorTexture);}if(metallicRoughnessTexture!=null){_this73[$metallicRoughnessTexture]=kernel.deserialize('texture-info',metallicRoughnessTexture);}return _this73;}/** * The base color factor of the material in RGBA format. */_createClass(PBRMetallicRoughness,[{key:"setBaseColorFactor",/** * Set the base color factor of the material. * * @see ../api.ts */value:function(){var _setBaseColorFactor=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee30(color){return regeneratorRuntime.wrap(function _callee30$(_context31){while(1){switch(_context31.prev=_context31.next){case 0:_context31.next=2;return this[$kernel$3].mutate(this,'baseColorFactor',color);case 2:this[$baseColorFactor]=Object.freeze(color);case 3:case"end":return _context31.stop();}}},_callee30,this);}));function setBaseColorFactor(_x27){return _setBaseColorFactor.apply(this,arguments);}return setBaseColorFactor;}()/** * Set the metallic factor of the material. * * @see ../api.ts */},{key:"setMetallicFactor",value:function(){var _setMetallicFactor=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee31(factor){return regeneratorRuntime.wrap(function _callee31$(_context32){while(1){switch(_context32.prev=_context32.next){case 0:_context32.next=2;return this[$kernel$3].mutate(this,'metallicFactor',factor);case 2:this[$metallicFactor]=factor;case 3:case"end":return _context32.stop();}}},_callee31,this);}));function setMetallicFactor(_x28){return _setMetallicFactor.apply(this,arguments);}return setMetallicFactor;}()/** * Set the roughness factor of the material. * * @see ../api.ts */},{key:"setRoughnessFactor",value:function(){var _setRoughnessFactor=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee32(factor){return regeneratorRuntime.wrap(function _callee32$(_context33){while(1){switch(_context33.prev=_context33.next){case 0:_context33.next=2;return this[$kernel$3].mutate(this,'roughnessFactor',factor);case 2:this[$roughnessFactor]=factor;case 3:case"end":return _context33.stop();}}},_callee32,this);}));function setRoughnessFactor(_x29){return _setRoughnessFactor.apply(this,arguments);}return setRoughnessFactor;}()},{key:"baseColorFactor",get:function get(){return this[$baseColorFactor];}/** * The metalness factor of the material in range [0,1]. */},{key:"metallicFactor",get:function get(){return this[$metallicFactor];}/** * The roughness factor of the material in range [0,1]. */},{key:"roughnessFactor",get:function get(){return this[$roughnessFactor];}},{key:"baseColorTexture",get:function get(){return this[$baseColorTexture];}},{key:"metallicRoughnessTexture",get:function get(){return this[$metallicRoughnessTexture];}}]);return PBRMetallicRoughness;}(ThreeDOMElement);_a$e=$baseColorTexture,_b$b=$metallicRoughnessTexture;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$f,_b$c;var $kernel$4=Symbol('kernel');var $minFilter=Symbol('minFilter');var $magFilter=Symbol('magFilter');var $wrapS=Symbol('wrapS');var $wrapT=Symbol('wrapT');var $name$2=Symbol('name');var Sampler=/*#__PURE__*/function(_ThreeDOMElement5){_inherits(Sampler,_ThreeDOMElement5);var _super40=_createSuper(Sampler);function Sampler(kernel,serialized){var _this74;_classCallCheck(this,Sampler);_this74=_super40.call(this,kernel);_this74[_a$f]=null;_this74[_b$c]=null;_this74[$kernel$4]=kernel;if(serialized.name!=null){_this74[$name$2]=serialized.name;}_this74[$minFilter]=serialized.minFilter||null;_this74[$magFilter]=serialized.magFilter||null;_this74[$wrapS]=serialized.wrapS||10497;_this74[$wrapT]=serialized.wrapT||10497;return _this74;}_createClass(Sampler,[{key:"setMinFilter",value:function(){var _setMinFilter=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee33(filter){return regeneratorRuntime.wrap(function _callee33$(_context34){while(1){switch(_context34.prev=_context34.next){case 0:_context34.next=2;return this[$kernel$4].mutate(this,'minFilter',filter);case 2:this[$minFilter]=filter;case 3:case"end":return _context34.stop();}}},_callee33,this);}));function setMinFilter(_x30){return _setMinFilter.apply(this,arguments);}return setMinFilter;}()},{key:"setMagFilter",value:function(){var _setMagFilter=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee34(filter){return regeneratorRuntime.wrap(function _callee34$(_context35){while(1){switch(_context35.prev=_context35.next){case 0:_context35.next=2;return this[$kernel$4].mutate(this,'magFilter',filter);case 2:this[$magFilter]=filter;case 3:case"end":return _context35.stop();}}},_callee34,this);}));function setMagFilter(_x31){return _setMagFilter.apply(this,arguments);}return setMagFilter;}()},{key:"setWrapS",value:function(){var _setWrapS=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee35(mode){return regeneratorRuntime.wrap(function _callee35$(_context36){while(1){switch(_context36.prev=_context36.next){case 0:_context36.next=2;return this[$kernel$4].mutate(this,'wrapS',mode);case 2:this[$wrapS]=mode;case 3:case"end":return _context36.stop();}}},_callee35,this);}));function setWrapS(_x32){return _setWrapS.apply(this,arguments);}return setWrapS;}()},{key:"setWrapT",value:function(){var _setWrapT=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee36(mode){return regeneratorRuntime.wrap(function _callee36$(_context37){while(1){switch(_context37.prev=_context37.next){case 0:_context37.next=2;return this[$kernel$4].mutate(this,'wrapT',mode);case 2:this[$wrapT]=mode;case 3:case"end":return _context37.stop();}}},_callee36,this);}));function setWrapT(_x33){return _setWrapT.apply(this,arguments);}return setWrapT;}()},{key:"name",get:function get(){return this[$name$2];}},{key:"minFilter",get:function get(){return this[$minFilter];}},{key:"magFilter",get:function get(){return this[$magFilter];}},{key:"wrapS",get:function get(){return this[$wrapS];}},{key:"wrapT",get:function get(){return this[$wrapT];}}]);return Sampler;}(ThreeDOMElement);_a$f=$minFilter,_b$c=$magFilter;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$g;var $kernel$5=Symbol('kernel');var $texture=Symbol('texture');var TextureInfo=/*#__PURE__*/function(_ThreeDOMElement6){_inherits(TextureInfo,_ThreeDOMElement6);var _super41=_createSuper(TextureInfo);function TextureInfo(kernel,serialized){var _this75;_classCallCheck(this,TextureInfo);_this75=_super41.call(this,kernel);_this75[_a$g]=null;_this75[$kernel$5]=kernel;var texture=serialized.texture;if(texture!=null){_this75[$texture]=kernel.deserialize('texture',texture);}return _this75;}_createClass(TextureInfo,[{key:"setTexture",value:function(){var _setTexture=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee37(texture){return regeneratorRuntime.wrap(function _callee37$(_context38){while(1){switch(_context38.prev=_context38.next){case 0:_context38.next=2;return this[$kernel$5].mutate(this,'texture',texture);case 2:this[$texture]=texture;case 3:case"end":return _context38.stop();}}},_callee37,this);}));function setTexture(_x34){return _setTexture.apply(this,arguments);}return setTexture;}()},{key:"texture",get:function get(){return this[$texture];}}]);return TextureInfo;}(ThreeDOMElement);_a$g=$texture;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$h,_b$d;var $kernel$6=Symbol('kernel');var $source=Symbol('source');var $sampler=Symbol('sampler');var $name$3=Symbol('name');var Texture$1=/*#__PURE__*/function(_ThreeDOMElement7){_inherits(Texture$1,_ThreeDOMElement7);var _super42=_createSuper(Texture$1);function Texture$1(kernel,serialized){var _this76;_classCallCheck(this,Texture$1);_this76=_super42.call(this,kernel);_this76[_a$h]=null;_this76[_b$d]=null;_this76[$kernel$6]=kernel;var sampler=serialized.sampler,source=serialized.source,name=serialized.name;if(name!=null){_this76[$name$3]=name;}if(sampler!=null){_this76[$sampler]=kernel.deserialize('sampler',sampler);}if(source!=null){_this76[$source]=kernel.deserialize('image',source);}return _this76;}_createClass(Texture$1,[{key:"setSampler",value:function(){var _setSampler=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee38(sampler){return regeneratorRuntime.wrap(function _callee38$(_context39){while(1){switch(_context39.prev=_context39.next){case 0:_context39.next=2;return this[$kernel$6].mutate(this,'sampler',sampler);case 2:this[$sampler]=sampler;case 3:case"end":return _context39.stop();}}},_callee38,this);}));function setSampler(_x35){return _setSampler.apply(this,arguments);}return setSampler;}()},{key:"setSource",value:function(){var _setSource2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee39(image){return regeneratorRuntime.wrap(function _callee39$(_context40){while(1){switch(_context40.prev=_context40.next){case 0:_context40.next=2;return this[$kernel$6].mutate(this,'source',image);case 2:this[$source]=image;case 3:case"end":return _context40.stop();}}},_callee39,this);}));function setSource(_x36){return _setSource2.apply(this,arguments);}return setSource;}()},{key:"name",get:function get(){return this[$name$3];}},{key:"sampler",get:function get(){return this[$sampler];}},{key:"source",get:function get(){return this[$source];}}]);return Texture$1;}(ThreeDOMElement);_a$h=$source,_b$d=$sampler;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$i,_b$e,_c$5,_d$3,_e$2,_f$2;var ThreeDOMElementMap={'model':Model$1,'material':Material$1,'pbr-metallic-roughness':PBRMetallicRoughness,'image':Image,'sampler':Sampler,'texture':Texture$1,'texture-info':TextureInfo};var $onMessageEvent=Symbol('onMessageEvent');var $port=Symbol('port');var $model=Symbol('model');var $elementsByLocalId=Symbol('elementsByLocalId');var $localIdsByElement=Symbol('localIdsByElement');var $elementsByType=Symbol('elementsByType');var $pendingMutations=Symbol('pendingMutations');var $nextMutationId=Symbol('nextMutationId');/** * A ModelKernel is the core business logic implementation for a distinct * Model that has been exposed to a script execution context. The ModelKernel * is an internal detail, and should never be explicitly exposed to users of * a Model. * * The ModelKernel primarily handles deserializing scene graph elements, and * communicating mutations from the 3DOM execution context to the host * execution context where the backing scene graph lives. * * A ModelKernel also maintains a comprehensive map of elements by type to * assist scene graph elements in querying for their contemporaries. */var ModelKernel=/*#__PURE__*/function(){function ModelKernel(port,serialized){var _this77=this;_classCallCheck(this,ModelKernel);this[_a$i]=new Map();this[_b$e]=new Map();this[_c$5]=new Map();this[_d$3]=new Map();this[_e$2]=0;this[_f$2]=function(event){var data=event.data;switch(data&&data.type){case ThreeDOMMessageType.MUTATION_RESULT:{var message=data;var applied=message.applied,mutationId=message.mutationId;var pendingMutation=_this77[$pendingMutations].get(mutationId);_this77[$pendingMutations].delete(mutationId);if(pendingMutation!=null){applied?pendingMutation.resolve():pendingMutation.reject();}break;}}};var types=new Array('model','material','pbr-metallic-roughness','sampler','image','texture','texture-info');for(var _i348=0,_types=types;_i348<_types.length;_i348++){var type=_types[_i348];this[$elementsByType].set(type,new Set());}this[$port]=port;this[$port].addEventListener('message',this[$onMessageEvent]);this[$port].start();this[$model]=this.deserialize('model',serialized);}/** * The root scene graph element, a Model, that is the entrypoint for the * entire scene graph that is backed by this kernel. */_createClass(ModelKernel,[{key:"mutate",/** * Mutate a property of a property of a given scene graph element. All * direct mutations of the scene graph are considered asynchronous. This * method returns a Promise that resolves when the mutation has been * successfully applied to the backing scene graph, and rejects if the * mutation failed or is otherwise not allowed. * * TODO(#1006): How to validate values? */value:function(){var _mutate=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee40(element,property,value){var _this78=this;var id;return regeneratorRuntime.wrap(function _callee40$(_context41){while(1){switch(_context41.prev=_context41.next){case 0:if(this[$localIdsByElement].has(element)){_context41.next=2;break;}throw new Error('Cannot mutate unknown element');case 2:id=this[$localIdsByElement].get(element);if(_instanceof(value,ThreeDOMElement)){value=this[$localIdsByElement].get(value);}return _context41.abrupt("return",new Promise(function(resolve,reject){var mutationId=_this78[$nextMutationId]++;// TODO(#1006): Validate mutations before sending to host context: _this78[$port].postMessage({type:ThreeDOMMessageType.MUTATE,id:id,property:property,value:value,mutationId:mutationId});// TODO(#1011): Add timeout to reject this mutation: _this78[$pendingMutations].set(mutationId,{resolve:resolve,reject:reject});}));case 5:case"end":return _context41.stop();}}},_callee40,this);}));function mutate(_x37,_x38,_x39){return _mutate.apply(this,arguments);}return mutate;}()/** * Deserializes a JSON representation of a scene graph element into a live * element that is backed by this ModelKernel. */},{key:"deserialize",value:function deserialize(type,serialized){var id=serialized.id;// TODO: Add test to ensure that we don't double-deserialize elements if(this[$elementsByLocalId].has(id)){return this[$elementsByLocalId].get(id);}var ElementConstructor=ThreeDOMElementMap[type];if(ElementConstructor==null){throw new Error("Cannot deserialize unknown type: ".concat(type));}// eslint-disable-next-line @typescript-eslint/no-explicit-any var element=new ElementConstructor(this,serialized);this[$elementsByLocalId].set(id,element);this[$localIdsByElement].set(element,id);// We know that the all accepted types have been pre-populated in the // [$elementsByType] map: // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this[$elementsByType].get(type).add(element);return element;}/** * Look up all scene graph elements given a type string. Type strings * are lower-cased, hyphenated versions of the constructor names of their * corresponding classes. For example, a query for 'pbr-metallic-roughness' * element types will yield the list of PBRMetallicRoughness elements in * sparse tree order. */},{key:"getElementsByType",value:function getElementsByType(type){if(!this[$elementsByType].has(type)){return[];}// eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Array.from(this[$elementsByType].get(type));}/** * Deactivate the ModelKernel. This has the effect of blocking all future * mutations to the scene graph. Once deactivated, a ModelKernel cannot be * reactivated. * * The ModelKernel should be deactivated before it is disposed of, or else * it will leak in memory. */},{key:"deactivate",value:function deactivate(){this[$port].close();this[$port].removeEventListener('message',this[$onMessageEvent]);}},{key:"model",get:function get(){return this[$model];}}]);return ModelKernel;}();_a$i=$elementsByLocalId,_b$e=$localIdsByElement,_c$5=$elementsByType,_d$3=$pendingMutations,_e$2=$nextMutationId,_f$2=$onMessageEvent;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$j;var $modelGraft=Symbol('modelGraft');var $port$1=Symbol('port');var $onMessageEvent$1=Symbol('onMessageEvent');/** * A ModelGraftManipulator is an internal construct intended to consolidate * any mutations that operate on the backing scene graph. It can be thought * of as a host execution context counterpart to the ModelKernel in the scene * graph execution context. */var ModelGraftManipulator=/*#__PURE__*/function(){function ModelGraftManipulator(modelGraft,port){var _this79=this;_classCallCheck(this,ModelGraftManipulator);this[_a$j]=/*#__PURE__*/function(){var _ref10=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee41(event){var data,applied,mutationId;return regeneratorRuntime.wrap(function _callee41$(_context42){while(1){switch(_context42.prev=_context42.next){case 0:data=event.data;if(!(data&&data.type)){_context42.next=12;break;}if(!(data.type===ThreeDOMMessageType.MUTATE)){_context42.next=12;break;}applied=false;mutationId=data.mutationId;_context42.prev=5;_context42.next=8;return _this79[$modelGraft].mutate(data.id,data.property,data.value);case 8:applied=true;case 9:_context42.prev=9;_this79[$port$1].postMessage({type:ThreeDOMMessageType.MUTATION_RESULT,applied:applied,mutationId:mutationId});return _context42.finish(9);case 12:case"end":return _context42.stop();}}},_callee41,null,[[5,,9,12]]);}));return function(_x40){return _ref10.apply(this,arguments);};}();this[$modelGraft]=modelGraft;this[$port$1]=port;this[$port$1].addEventListener('message',this[$onMessageEvent$1]);this[$port$1].start();}/** * Clean up internal state so that the ModelGraftManipulator can be properly * garbage collected. */_createClass(ModelGraftManipulator,[{key:"dispose",value:function dispose(){this[$port$1].removeEventListener('message',this[$onMessageEvent$1]);this[$port$1].close();}}]);return ModelGraftManipulator;}();_a$j=$onMessageEvent$1;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Produces a "locally" unique ID. This ID is only guaranteed to be unique * over the lifetime of the function and in the current execution context. */var getLocallyUniqueId=function(){var id=0;return function(){return id++;};}();var $callbacks=Symbol('callbacks');var $visitMesh=Symbol('visitMesh');var $visitElement=Symbol('visitElement');var $visitNode=Symbol('visitNode');var $visitScene=Symbol('visitScene');var $visitMaterial=Symbol('visitMaterial');/** * GLTFTreeVisitor implements a deterministic traversal order of a valid, * deserialized glTF 2.0 model. It supports selective element visitation via * callbacks configured based on element type. For example, to visit all * materials in all scenes in a glTF: * * ```javascript * const visitor = new GLTFTreeVisitor({ * material: (material, index, hierarchy) => { * // material is a glTF 2.0 Material * // index is the index of material in gltf.materials * // hierarchy includes ancestors of material in the glTF * } * }); * * visitor.visit(someInMemoryGLTF, { allScenes: true }); * ``` * * The traversal order of the visitor is pre-order, depth-first. * * Note that the traversal order is not guaranteed to correspond to the * index of a given element in any way. Rather, traversal order is based * on the hierarchical order of the scene graph. */var GLTFTreeVisitor=/*#__PURE__*/function(){function GLTFTreeVisitor(callbacks){_classCallCheck(this,GLTFTreeVisitor);this[$callbacks]=callbacks;}/** * Visit a given in-memory glTF via the configured callbacks of this visitor. * Optionally, all scenes may be visited (as opposed to just the active one). * Sparse traversal can also be specified, in which case elements that * re-appear multiple times in the scene graph will only be visited once. */_createClass(GLTFTreeVisitor,[{key:"visit",value:function visit(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var allScenes=!!options.allScenes;var sparse=!!options.sparse;var scenes=allScenes?gltf.scenes||[]:gltf.scenes&&gltf.scene!=null?[gltf.scenes[gltf.scene]]:[];var state={hierarchy:[],visited:new Set(),sparse:sparse,gltf:gltf};var _iterator22=_createForOfIteratorHelper(scenes),_step22;try{for(_iterator22.s();!(_step22=_iterator22.n()).done;){var scene=_step22.value;this[$visitScene](gltf.scenes.indexOf(scene),state);}}catch(err){_iterator22.e(err);}finally{_iterator22.f();}}},{key:$visitElement,value:function value(index,elementList,state,visit,traverse){if(elementList==null){return;}var element=elementList[index];var sparse=state.sparse,hierarchy=state.hierarchy,visited=state.visited;if(element==null){return;}if(sparse&&visited.has(element)){return;}visited.add(element);hierarchy.push(element);if(visit!=null){visit(element,index,hierarchy);}if(traverse!=null){traverse(element);}hierarchy.pop();}},{key:$visitScene,value:function value(index,state){var _this80=this;var gltf=state.gltf;var visit=this[$callbacks].scene;this[$visitElement](index,gltf.scenes,state,visit,function(scene){// A scene is not required to have a list of nodes if(scene.nodes==null){return;}var _iterator23=_createForOfIteratorHelper(scene.nodes),_step23;try{for(_iterator23.s();!(_step23=_iterator23.n()).done;){var nodeIndex=_step23.value;_this80[$visitNode](nodeIndex,state);}}catch(err){_iterator23.e(err);}finally{_iterator23.f();}});}},{key:$visitNode,value:function value(index,state){var _this81=this;var gltf=state.gltf;var visit=this[$callbacks].node;this[$visitElement](index,gltf.nodes,state,visit,function(node){if(node.mesh!=null){_this81[$visitMesh](node.mesh,state);}if(node.children!=null){var _iterator24=_createForOfIteratorHelper(node.children),_step24;try{for(_iterator24.s();!(_step24=_iterator24.n()).done;){var childNodeIndex=_step24.value;_this81[$visitNode](childNodeIndex,state);}}catch(err){_iterator24.e(err);}finally{_iterator24.f();}}});}},{key:$visitMesh,value:function value(index,state){var _this82=this;var gltf=state.gltf;var visit=this[$callbacks].mesh;this[$visitElement](index,gltf.meshes,state,visit,function(mesh){var _iterator25=_createForOfIteratorHelper(mesh.primitives),_step25;try{for(_iterator25.s();!(_step25=_iterator25.n()).done;){var primitive=_step25.value;if(primitive.material!=null){_this82[$visitMaterial](primitive.material,state);}}}catch(err){_iterator25.e(err);}finally{_iterator25.f();}});}},{key:$visitMaterial,value:function value(index,state){var gltf=state.gltf;var visit=this[$callbacks].material;this[$visitElement](index,gltf.materials,state,visit);}}]);return GLTFTreeVisitor;}();/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$k;var $correlatedObjects=Symbol('correlatedObjects');var $sourceObject=Symbol('sourceObject');var $graft=Symbol('graft');var $id=Symbol('id');/** * A SerializableThreeDOMElement is the common primitive of all scene graph * elements that have been facaded in the host execution context. It adds * a common interface to these elements in support of convenient * serializability. */var ThreeDOMElement$1=/*#__PURE__*/function(){function ThreeDOMElement$1(graft,element){var correlatedObjects=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;_classCallCheck(this,ThreeDOMElement$1);this[_a$k]=getLocallyUniqueId();this[$graft]=graft;this[$sourceObject]=element;this[$correlatedObjects]=correlatedObjects;graft.adopt(this);}/** * The Model of provenance for this scene graph element. */_createClass(ThreeDOMElement$1,[{key:"mutate",/** * Mutate a property of the scene graph element. Returns a promise that * resolves when the mutation has been successfully applied. */value:function mutate(_property,_value){throw new Error('Mutation not implemented for this element');}/** * Serialize the element in order to share it with a worker context. */},{key:"toJSON",value:function toJSON(){var serialized={id:this[$id]};var name=this.name;if(name!=null){serialized.name=name;}return serialized;}},{key:"ownerModel",get:function get(){return this[$graft].model;}/** * The unique ID that marks this element. In generally, an ID should only be * considered unique to the element in the context of its scene graph. These * IDs are not guaranteed to be stable across script executions. */},{key:"internalID",get:function get(){return this[$id];}/** * Some (but not all) scene graph elements may have an optional name. The * Object3D.prototype.name property is sometimes auto-generated by Three.js. * We only want to expose a name that is set in the source glTF, so Three.js * generated names are ignored. */},{key:"name",get:function get(){return this[$sourceObject].name||null;}/** * The backing Three.js scene graph construct for this element. */},{key:"correlatedObjects",get:function get(){return this[$correlatedObjects];}/** * The canonical GLTF or GLTFElement represented by this facade. */},{key:"sourceObject",get:function get(){return this[$sourceObject];}}]);return ThreeDOMElement$1;}();_a$k=$id;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$l;var loader=new ImageLoader();var $threeTextures=Symbol('threeTextures');var $bufferViewImages=Symbol('bufferViewImages');/** * Image facade implementation for Three.js textures */var Image$1=/*#__PURE__*/function(_ThreeDOMElement$){_inherits(Image$1,_ThreeDOMElement$);var _super43=_createSuper(Image$1);function Image$1(graft,image,correlatedTextures){var _this83;_classCallCheck(this,Image$1);_this83=_super43.call(this,graft,image,correlatedTextures);_this83[_a$l]=new WeakMap();if(image.bufferView!=null){var _iterator26=_createForOfIteratorHelper(correlatedTextures),_step26;try{for(_iterator26.s();!(_step26=_iterator26.n()).done;){var texture=_step26.value;_this83[$bufferViewImages].set(texture,texture.image);}}catch(err){_iterator26.e(err);}finally{_iterator26.f();}}return _this83;}_createClass(Image$1,[{key:"mutate",value:function(){var _mutate2=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee42(property,value){var image,_iterator27,_step27,texture;return regeneratorRuntime.wrap(function _callee42$(_context43){while(1){switch(_context43.prev=_context43.next){case 0:image=null;if(!(property!=='uri')){_context43.next=3;break;}throw new Error("Cannot configure property \"".concat(property,"\" on Image"));case 3:if(!(value!=null)){_context43.next=7;break;}_context43.next=6;return new Promise(function(resolve,reject){loader.load(value,resolve,undefined,reject);});case 6:image=_context43.sent;case 7:_iterator27=_createForOfIteratorHelper(this[$threeTextures]);try{for(_iterator27.s();!(_step27=_iterator27.n()).done;){texture=_step27.value;// If the URI is set to null but the Image had an associated buffer view // (this would happen if it started out as embedded), then fall back to // the cached object URL created by GLTFLoader: if(image==null&&this.sourceObject.bufferView!=null){texture.image=this[$bufferViewImages].get(texture);}else{texture.image=image;}texture.needsUpdate=true;}}catch(err){_iterator27.e(err);}finally{_iterator27.f();}case 9:case"end":return _context43.stop();}}},_callee42,this);}));function mutate(_x41,_x42){return _mutate2.apply(this,arguments);}return mutate;}()},{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Image$1.prototype),"toJSON",this).call(this);var uri=this.sourceObject.uri;if(uri!=null){serialized.uri=uri;}return serialized;}},{key:$threeTextures,get:function get(){return this[$correlatedObjects];}}]);return Image$1;}(ThreeDOMElement$1);_a$l=$bufferViewImages;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var isMinFilter=function(){var minFilterValues=[9728,9729,9984,9985,9986,9987];return function(value){return minFilterValues.indexOf(value)>-1;};}();var isMagFilter=function(){var magFilterValues=[9728,9729];return function(value){return magFilterValues.indexOf(value)>-1;};}();var isWrapMode=function(){var wrapModes=[33071,33648,10497];return function(value){return wrapModes.indexOf(value)>-1;};}();var isValidSamplerValue=function isValidSamplerValue(property,value){switch(property){case'minFilter':return isMinFilter(value);case'magFilter':return isMagFilter(value);case'wrapS':case'wrapT':return isWrapMode(value);default:throw new Error("Cannot configure property \"".concat(property,"\" on Sampler"));}};// These defaults represent a convergence of glTF defaults for wrap mode and // Three.js defaults for filters. Per glTF 2.0 spec, a renderer may choose its // own defaults for filters. // @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-sampler // @see https://threejs.org/docs/#api/en/textures/Texture var defaultValues={minFilter:9987,magFilter:9729,wrapS:10497,wrapT:10497};var $threeTextures$1=Symbol('threeTextures');/** * Sampler facade implementation for Three.js textures */var Sampler$1=/*#__PURE__*/function(_ThreeDOMElement$2){_inherits(Sampler$1,_ThreeDOMElement$2);var _super44=_createSuper(Sampler$1);_createClass(Sampler$1,[{key:$threeTextures$1,get:function get(){return this[$correlatedObjects];}}]);function Sampler$1(graft,sampler,correlatedTextures){_classCallCheck(this,Sampler$1);return _super44.call(this,graft,sampler,correlatedTextures);}_createClass(Sampler$1,[{key:"mutate",value:function(){var _mutate3=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee43(property,value){var sampler,_iterator28,_step28,texture,_iterator29,_step29,_texture;return regeneratorRuntime.wrap(function _callee43$(_context44){while(1){switch(_context44.prev=_context44.next){case 0:sampler=this.sourceObject;if(value!=null){if(isValidSamplerValue(property,value)){sampler[property]=value;_iterator28=_createForOfIteratorHelper(this[$threeTextures$1]);try{for(_iterator28.s();!(_step28=_iterator28.n()).done;){texture=_step28.value;texture[property]=value;texture.needsUpdate=true;}}catch(err){_iterator28.e(err);}finally{_iterator28.f();}}}else if(property in sampler){delete sampler[property];_iterator29=_createForOfIteratorHelper(this[$threeTextures$1]);try{for(_iterator29.s();!(_step29=_iterator29.n()).done;){_texture=_step29.value;_texture[property]=defaultValues[property];_texture.needsUpdate=true;}}catch(err){_iterator29.e(err);}finally{_iterator29.f();}}case 2:case"end":return _context44.stop();}}},_callee43,this);}));function mutate(_x43,_x44){return _mutate3.apply(this,arguments);}return mutate;}()},{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Sampler$1.prototype),"toJSON",this).call(this);var _this$sourceObject=this.sourceObject,minFilter=_this$sourceObject.minFilter,magFilter=_this$sourceObject.magFilter,wrapS=_this$sourceObject.wrapS,wrapT=_this$sourceObject.wrapT;if(minFilter!=null){serialized.minFilter=minFilter;}if(magFilter!=null){serialized.magFilter=magFilter;}if(wrapS!==10497){serialized.wrapS=wrapS;}if(wrapT!==10497){serialized.wrapT=wrapT;}return serialized;}}]);return Sampler$1;}(ThreeDOMElement$1);/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$m,_b$f;var $source$1=Symbol('source');var $sampler$1=Symbol('sampler');/** * Material facade implementation for Three.js materials */var Texture$2=/*#__PURE__*/function(_ThreeDOMElement$3){_inherits(Texture$2,_ThreeDOMElement$3);var _super45=_createSuper(Texture$2);function Texture$2(graft,texture,correlatedTextures){var _this84;_classCallCheck(this,Texture$2);_this84=_super45.call(this,graft,texture,correlatedTextures);_this84[_a$m]=null;_this84[_b$f]=null;var glTF=graft.correlatedSceneGraph.gltf;var samplerIndex=texture.sampler,imageIndex=texture.source;if(samplerIndex!=null){var sampler=glTF.samplers&&glTF.samplers[samplerIndex];if(sampler!=null){_this84[$sampler$1]=new Sampler$1(graft,sampler,correlatedTextures);}}if(imageIndex!=null){var image=glTF.images&&glTF.images[imageIndex];if(image!=null){_this84[$source$1]=new Image$1(graft,image,correlatedTextures);}}return _this84;}_createClass(Texture$2,[{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Texture$2.prototype),"toJSON",this).call(this);var sampler=this.sampler,source=this.source;if(sampler!=null){serialized.sampler=sampler.toJSON();}if(source!=null){serialized.source=source.toJSON();}return serialized;}},{key:"sampler",get:function get(){return this[$sampler$1];}},{key:"source",get:function get(){return this[$source$1];}}]);return Texture$2;}(ThreeDOMElement$1);_a$m=$source$1,_b$f=$sampler$1;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$n;var $texture$1=Symbol('texture');/** * TextureInfo facade implementation for Three.js materials */var TextureInfo$1=/*#__PURE__*/function(_ThreeDOMElement$4){_inherits(TextureInfo$1,_ThreeDOMElement$4);var _super46=_createSuper(TextureInfo$1);function TextureInfo$1(graft,textureInfo,correlatedTextures){var _this85;_classCallCheck(this,TextureInfo$1);_this85=_super46.call(this,graft,textureInfo,correlatedTextures);_this85[_a$n]=null;var glTF=graft.correlatedSceneGraph.gltf;var textureIndex=textureInfo.index;var texture=textureIndex!=null&&glTF.textures!=null?glTF.textures[textureIndex]:null;if(texture!=null){_this85[$texture$1]=new Texture$2(graft,texture,correlatedTextures);}return _this85;}_createClass(TextureInfo$1,[{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(TextureInfo$1.prototype),"toJSON",this).call(this);var texture=this.texture;if(texture!=null){serialized.texture=texture.toJSON();}return serialized;}},{key:"texture",get:function get(){return this[$texture$1];}}]);return TextureInfo$1;}(ThreeDOMElement$1);_a$n=$texture$1;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$o,_b$g;var $threeMaterials=Symbol('threeMaterials');var $baseColorTexture$1=Symbol('baseColorTexture');var $metallicRoughnessTexture$1=Symbol('metallicRoughnessTexture');/** * PBR material properties facade implementation for Three.js materials */var PBRMetallicRoughness$1=/*#__PURE__*/function(_ThreeDOMElement$5){_inherits(PBRMetallicRoughness$1,_ThreeDOMElement$5);var _super47=_createSuper(PBRMetallicRoughness$1);function PBRMetallicRoughness$1(graft,pbrMetallicRoughness,correlatedMaterials){var _this86;_classCallCheck(this,PBRMetallicRoughness$1);_this86=_super47.call(this,graft,pbrMetallicRoughness,correlatedMaterials);_this86[_a$o]=null;_this86[_b$g]=null;var baseColorTexture=pbrMetallicRoughness.baseColorTexture,metallicRoughnessTexture=pbrMetallicRoughness.metallicRoughnessTexture;var baseColorTextures=new Set();var metallicRoughnessTextures=new Set();var _iterator30=_createForOfIteratorHelper(correlatedMaterials),_step30;try{for(_iterator30.s();!(_step30=_iterator30.n()).done;){var material=_step30.value;if(baseColorTexture!=null&&material.map!=null){baseColorTextures.add(material.map);}// NOTE: GLTFLoader users the same texture for metalnessMap and // roughnessMap in this case // @see https://github.com/mrdoob/three.js/blob/b4473c25816df4a09405c7d887d5c418ef47ee76/examples/js/loaders/GLTFLoader.js#L2173-L2174 if(metallicRoughnessTexture!=null&&material.metalnessMap!=null){metallicRoughnessTextures.add(material.metalnessMap);}}}catch(err){_iterator30.e(err);}finally{_iterator30.f();}if(baseColorTextures.size>0){_this86[$baseColorTexture$1]=new TextureInfo$1(graft,baseColorTexture,baseColorTextures);}if(metallicRoughnessTextures.size>0){_this86[$metallicRoughnessTexture$1]=new TextureInfo$1(graft,metallicRoughnessTexture,metallicRoughnessTextures);}return _this86;}_createClass(PBRMetallicRoughness$1,[{key:"mutate",value:function(){var _mutate4=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee44(property,value){var _iterator31,_step31,material,pbrMetallicRoughness,_iterator32,_step32,_material2,_pbrMetallicRoughness,_iterator33,_step33,_material3,_pbrMetallicRoughness2;return regeneratorRuntime.wrap(function _callee44$(_context45){while(1){switch(_context45.prev=_context45.next){case 0:if(['baseColorFactor','metallicFactor','roughnessFactor'].includes(property)){_context45.next=2;break;}throw new Error("Cannot mutate ".concat(property," on PBRMetallicRoughness"));case 2:_context45.t0=property;_context45.next=_context45.t0==='baseColorFactor'?5:_context45.t0==='metallicFactor'?8:_context45.t0==='roughnessFactor'?11:14;break;case 5:_iterator31=_createForOfIteratorHelper(this[$threeMaterials]);try{for(_iterator31.s();!(_step31=_iterator31.n()).done;){material=_step31.value;material.color.fromArray(value);material.opacity=value[3];pbrMetallicRoughness=this[$sourceObject];if(value===1&&value===1&&value===1&&value===1){delete pbrMetallicRoughness.baseColorFactor;}else{pbrMetallicRoughness.baseColorFactor=value;}}}catch(err){_iterator31.e(err);}finally{_iterator31.f();}return _context45.abrupt("break",14);case 8:_iterator32=_createForOfIteratorHelper(this[$threeMaterials]);try{for(_iterator32.s();!(_step32=_iterator32.n()).done;){_material2=_step32.value;_material2.metalness=value;_pbrMetallicRoughness=this[$sourceObject];_pbrMetallicRoughness.metallicFactor=value;}}catch(err){_iterator32.e(err);}finally{_iterator32.f();}return _context45.abrupt("break",14);case 11:_iterator33=_createForOfIteratorHelper(this[$threeMaterials]);try{for(_iterator33.s();!(_step33=_iterator33.n()).done;){_material3=_step33.value;_material3.roughness=value;_pbrMetallicRoughness2=this[$sourceObject];_pbrMetallicRoughness2.roughnessFactor=value;}}catch(err){_iterator33.e(err);}finally{_iterator33.f();}return _context45.abrupt("break",14);case 14:case"end":return _context45.stop();}}},_callee44,this);}));function mutate(_x45,_x46){return _mutate4.apply(this,arguments);}return mutate;}()},{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(PBRMetallicRoughness$1.prototype),"toJSON",this).call(this);var baseColorTexture=this.baseColorTexture,metallicRoughnessTexture=this.metallicRoughnessTexture,baseColorFactor=this.baseColorFactor,roughnessFactor=this.roughnessFactor,metallicFactor=this.metallicFactor;if(baseColorTexture!=null){serialized.baseColorTexture=baseColorTexture.toJSON();}if(baseColorFactor!=null){serialized.baseColorFactor=baseColorFactor;}if(metallicFactor!=null){serialized.metallicFactor=metallicFactor;}if(roughnessFactor!=null){serialized.roughnessFactor=roughnessFactor;}if(metallicRoughnessTexture!=null){serialized.metallicRoughnessTexture=metallicRoughnessTexture.toJSON();}return serialized;}},{key:(_a$o=$baseColorTexture$1,_b$g=$metallicRoughnessTexture$1,$threeMaterials),get:function get(){return this[$correlatedObjects];}},{key:"baseColorFactor",get:function get(){return this.sourceObject.baseColorFactor||[1,1,1,1];}},{key:"metallicFactor",get:function get(){return this.sourceObject.metallicFactor||0;}},{key:"roughnessFactor",get:function get(){return this.sourceObject.roughnessFactor||0;}},{key:"baseColorTexture",get:function get(){return this[$baseColorTexture$1];}},{key:"metallicRoughnessTexture",get:function get(){return this[$metallicRoughnessTexture$1];}}]);return PBRMetallicRoughness$1;}(ThreeDOMElement$1);/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$p,_b$h,_c$6,_d$4;var $pbrMetallicRoughness$1=Symbol('pbrMetallicRoughness');var $normalTexture$1=Symbol('normalTexture');var $occlusionTexture$1=Symbol('occlusionTexture');var $emissiveTexture$1=Symbol('emissiveTexture');/** * Material facade implementation for Three.js materials */var Material$2=/*#__PURE__*/function(_ThreeDOMElement$6){_inherits(Material$2,_ThreeDOMElement$6);var _super48=_createSuper(Material$2);function Material$2(graft,material,correlatedMaterials){var _this87;_classCallCheck(this,Material$2);_this87=_super48.call(this,graft,material,correlatedMaterials);_this87[_a$p]=null;_this87[_b$h]=null;_this87[_c$6]=null;_this87[_d$4]=null;var pbrMetallicRoughness=material.pbrMetallicRoughness,normalTexture=material.normalTexture,occlusionTexture=material.occlusionTexture,emissiveTexture=material.emissiveTexture;if(pbrMetallicRoughness!=null){_this87[$pbrMetallicRoughness$1]=new PBRMetallicRoughness$1(graft,pbrMetallicRoughness,correlatedMaterials);}var normalTextures=new Set();var occlusionTextures=new Set();var emissiveTextures=new Set();var _iterator34=_createForOfIteratorHelper(correlatedMaterials),_step34;try{for(_iterator34.s();!(_step34=_iterator34.n()).done;){var _material4=_step34.value;var normalMap=_material4.normalMap,aoMap=_material4.aoMap,emissiveMap=_material4.emissiveMap;if(normalTexture!=null&&normalMap!=null){normalTextures.add(normalMap);}if(occlusionTexture!=null&&aoMap!=null){occlusionTextures.add(aoMap);}if(emissiveTexture!=null&&emissiveMap!=null){emissiveTextures.add(emissiveMap);}}}catch(err){_iterator34.e(err);}finally{_iterator34.f();}if(normalTextures.size>0){_this87[$normalTexture$1]=new TextureInfo$1(graft,normalTexture,normalTextures);}if(occlusionTextures.size>0){_this87[$occlusionTexture$1]=new TextureInfo$1(graft,occlusionTexture,occlusionTextures);}if(emissiveTextures.size>0){_this87[$emissiveTexture$1]=new TextureInfo$1(graft,emissiveTexture,emissiveTextures);}return _this87;}_createClass(Material$2,[{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Material$2.prototype),"toJSON",this).call(this);var pbrMetallicRoughness=this.pbrMetallicRoughness,normalTexture=this.normalTexture,occlusionTexture=this.occlusionTexture,emissiveTexture=this.emissiveTexture;if(pbrMetallicRoughness!=null){serialized.pbrMetallicRoughness=pbrMetallicRoughness.toJSON();}if(normalTexture!=null){serialized.normalTexture=normalTexture.toJSON();}if(occlusionTexture!=null){serialized.occlusionTexture=occlusionTexture.toJSON();}if(emissiveTexture!=null){serialized.emissiveTexture=emissiveTexture.toJSON();}return serialized;}},{key:"pbrMetallicRoughness",get:function get(){return this[$pbrMetallicRoughness$1];}},{key:"normalTexture",get:function get(){return this[$normalTexture$1];}},{key:"occlusionTexture",get:function get(){return this[$occlusionTexture$1];}},{key:"emissiveTexture",get:function get(){return this[$emissiveTexture$1];}}]);return Material$2;}(ThreeDOMElement$1);_a$p=$pbrMetallicRoughness$1,_b$h=$normalTexture$1,_c$6=$occlusionTexture$1,_d$4=$emissiveTexture$1;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$q,_b$i;var $modelUri=Symbol('modelUri');var $materials$1=Symbol('materials');/** * A Model facades the top-level GLTF object returned by Three.js' GLTFLoader. * Currently, the model only bothers itself with the materials in the Three.js * scene graph. */var Model$2=/*#__PURE__*/function(_ThreeDOMElement$7){_inherits(Model$2,_ThreeDOMElement$7);var _super49=_createSuper(Model$2);function Model$2(graft,modelUri,correlatedSceneGraph){var _this88;_classCallCheck(this,Model$2);_this88=_super49.call(this,graft,correlatedSceneGraph.gltf);_this88[_a$q]='';_this88[_b$i]=[];_this88[$modelUri]=modelUri;var visitor=new GLTFTreeVisitor({material:function material(_material5){_this88[$materials$1].push(new Material$2(graft,_material5,correlatedSceneGraph.gltfElementMap.get(_material5)));}});visitor.visit(correlatedSceneGraph.gltf,{sparse:true});return _this88;}/** * A flat list of all unique materials found in this scene graph. Materials * are listed in the order they appear during pre-order, depth-first traveral * of the scene graph. * * TODO(#1003): How do we handle non-active scenes? * TODO(#1002): Desctibe and enforce traversal order */_createClass(Model$2,[{key:"toJSON",value:function toJSON(){var serialized=_get(_getPrototypeOf(Model$2.prototype),"toJSON",this).call(this);serialized.modelUri=this[$modelUri];serialized.materials=this[$materials$1].map(function(material){return material.toJSON();});return serialized;}},{key:"materials",get:function get(){return this[$materials$1];}}]);return Model$2;}(ThreeDOMElement$1);_a$q=$modelUri,_b$i=$materials$1;/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var _a$r,_b$j;var $model$1=Symbol('model');var $correlatedSceneGraph$1=Symbol('correlatedSceneGraph');var $elementsByInternalId=Symbol('elementsByInternalId');var $eventDelegate$1=Symbol('eventDelegate');/** * ModelGraft * * This is a coordination primitive between a scene graph as represented by the * output for Three.js' GLTFLoader and a counterpart 3DOM facade. Since this is * the Three.js-specific implementation of the facade, the input is a GLTF-like * object whose keys refer to Three.js-specific constructs (e.g., gltf.scene is * a THREE.Scene). * * When created, the ModelGraft produces a Model that can be traversed and * manipulated to mutate the Three.js scene graph synchronously (but * indirectly). The benefit of this is that mutations to the Three.js scene can * be performed in a Three.js-agnostic fashion that is potentially portable to * alternative rendering backends. * * The scene graph representation produced by the ModelGraft is designed to * match the structures described in the glTF 2.0 spec as closely as possible. * Where there are deviations, it is usually for the purpose of making * synchronization easier, or else for ergonomics. For example, in glTF 2.0, the * graph is a series of flat arrays where nodes cross-reference each other by * index to represent hierarchy, but in a Model nodes have array members * containing refrences to their hierarchical children. * * An important goal of ModelGraft is to enable a scene in one JavaScript * context to be manipulated by script in a remote context, such as a distant * worker thread or even a different process. So, every node in the graph * is able to be serialized, and the serialized form includes an ID that is * locally unique to the ModelGraft instance that the node came from so that * the remote context can refer back to it. A ModelGraft can be thought of as * the host execution context counterpart to the ModelKernel in the scene graph * execution context. */var ModelGraft=/*#__PURE__*/function(){function ModelGraft(modelUri,correlatedSceneGraph){var _this89=this;_classCallCheck(this,ModelGraft);// NOTE(cdata): This eventDelegate hack is a quick trick to let us get the // EventTarget interface without implementing or requiring a full polyfill. We // should remove this once EventTarget is inheritable everywhere. this[_a$r]=document.createDocumentFragment();// NOTE(cdata): We declare each of these methods independently here so that we // can inherit the correct types from EventTarget's interface. Maybe there is // a better way to do this dynamically so that we don't repeat ourselves? this.addEventListener=function(){var _this89$$eventDelegat;return(_this89$$eventDelegat=_this89[$eventDelegate$1]).addEventListener.apply(_this89$$eventDelegat,arguments);};this.removeEventListener=function(){var _this89$$eventDelegat2;return(_this89$$eventDelegat2=_this89[$eventDelegate$1]).removeEventListener.apply(_this89$$eventDelegat2,arguments);};this.dispatchEvent=function(){var _this89$$eventDelegat3;return(_this89$$eventDelegat3=_this89[$eventDelegate$1]).dispatchEvent.apply(_this89$$eventDelegat3,arguments);};this[_b$j]=new Map();this[$correlatedSceneGraph$1]=correlatedSceneGraph;this[$model$1]=new Model$2(this,modelUri,correlatedSceneGraph);}_createClass(ModelGraft,[{key:"getElementByInternalId",value:function getElementByInternalId(id){var element=this[$elementsByInternalId].get(id);if(element==null){return null;}return element;}},{key:"adopt",value:function adopt(element){this[$elementsByInternalId].set(element.internalID,element);}},{key:"mutate",value:function(){var _mutate5=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee45(id,property,value){var element;return regeneratorRuntime.wrap(function _callee45$(_context46){while(1){switch(_context46.prev=_context46.next){case 0:element=this.getElementByInternalId(id);_context46.next=3;return element.mutate(property,value);case 3:this.dispatchEvent(new CustomEvent('mutation',{detail:{element:element}}));case 4:case"end":return _context46.stop();}}},_callee45,this);}));function mutate(_x47,_x48,_x49){return _mutate5.apply(this,arguments);}return mutate;}()},{key:"correlatedSceneGraph",get:function get(){return this[$correlatedSceneGraph$1];}},{key:"model",get:function get(){return this[$model$1];}}]);return ModelGraft;}();_a$r=$eventDelegate$1,_b$j=$elementsByInternalId;//------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ var WEBGL_CONSTANTS={POINTS:0x0000,LINES:0x0001,LINE_LOOP:0x0002,LINE_STRIP:0x0003,TRIANGLES:0x0004,TRIANGLE_STRIP:0x0005,TRIANGLE_FAN:0x0006,UNSIGNED_BYTE:0x1401,UNSIGNED_SHORT:0x1403,FLOAT:0x1406,UNSIGNED_INT:0x1405,ARRAY_BUFFER:0x8892,ELEMENT_ARRAY_BUFFER:0x8893,NEAREST:0x2600,LINEAR:0x2601,NEAREST_MIPMAP_NEAREST:0x2700,LINEAR_MIPMAP_NEAREST:0x2701,NEAREST_MIPMAP_LINEAR:0x2702,LINEAR_MIPMAP_LINEAR:0x2703,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};var THREE_TO_WEBGL={};THREE_TO_WEBGL[NearestFilter]=WEBGL_CONSTANTS.NEAREST;THREE_TO_WEBGL[NearestMipmapNearestFilter]=WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;THREE_TO_WEBGL[NearestMipmapLinearFilter]=WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;THREE_TO_WEBGL[LinearFilter]=WEBGL_CONSTANTS.LINEAR;THREE_TO_WEBGL[LinearMipmapNearestFilter]=WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;THREE_TO_WEBGL[LinearMipmapLinearFilter]=WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;THREE_TO_WEBGL[ClampToEdgeWrapping]=WEBGL_CONSTANTS.CLAMP_TO_EDGE;THREE_TO_WEBGL[RepeatWrapping]=WEBGL_CONSTANTS.REPEAT;THREE_TO_WEBGL[MirroredRepeatWrapping]=WEBGL_CONSTANTS.MIRRORED_REPEAT;var PATH_PROPERTIES={scale:'scale',position:'translation',quaternion:'rotation',morphTargetInfluences:'weights'};//------------------------------------------------------------------------------ // GLTF Exporter //------------------------------------------------------------------------------ var GLTFExporter=function GLTFExporter(){};GLTFExporter.prototype={constructor:GLTFExporter,/** * Parse scenes and generate GLTF output * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes * @param {Function} onDone Callback on completed * @param {Object} options options */parse:function parse(input,onDone,options){var DEFAULT_OPTIONS={binary:false,trs:false,onlyVisible:true,truncateDrawRange:true,embedImages:true,maxTextureSize:Infinity,animations:[],forcePowerOfTwoTextures:false,includeCustomExtensions:false};options=Object.assign({},DEFAULT_OPTIONS,options);if(options.animations.length>0){// Only TRS properties, and not matrices, may be targeted by animation. options.trs=true;}var outputJSON={asset:{version:"2.0",generator:"GLTFExporter"}};var byteOffset=0;var buffers=[];var pending=[];var nodeMap=new Map();var skins=[];var extensionsUsed={};var cachedData={meshes:new Map(),attributes:new Map(),attributesNormalized:new Map(),materials:new Map(),textures:new Map(),images:new Map()};var cachedCanvas;var uids=new Map();var uid=0;/** * Assign and return a temporal unique id for an object * especially which doesn't have .uuid * @param {Object} object * @return {Integer} */function getUID(object){if(!uids.has(object))uids.set(object,uid++);return uids.get(object);}/** * Compare two arrays * @param {Array} array1 Array 1 to compare * @param {Array} array2 Array 2 to compare * @return {Boolean} Returns true if both arrays are equal */function equalArray(array1,array2){return array1.length===array2.length&&array1.every(function(element,index){return element===array2[index];});}/** * Converts a string to an ArrayBuffer. * @param {string} text * @return {ArrayBuffer} */function stringToArrayBuffer(text){if(window.TextEncoder!==undefined){return new TextEncoder().encode(text).buffer;}var array=new Uint8Array(new ArrayBuffer(text.length));for(var i=0,il=text.length;i0xFF?0x20:value;}return array.buffer;}/** * Get the min and max vectors from the given attribute * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count * @param {Integer} start * @param {Integer} count * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components) */function getMinMax(attribute,start,count){var output={min:new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY)};for(var i=start;i0.0005)return false;}return true;}/** * Creates normalized normal buffer attribute. * * @param {BufferAttribute} normal * @returns {BufferAttribute} * */function createNormalizedNormalAttribute(normal){if(cachedData.attributesNormalized.has(normal)){return cachedData.attributesNormalized.get(normal);}var attribute=normal.clone();var v=new Vector3();for(var i=0,il=attribute.count;i0){gltfProperty.extras=json;}}catch(error){console.warn('THREE.GLTFExporter: userData of \''+object.name+'\' '+'won\'t be serialized because of JSON.stringify error - '+error.message);}}/** * Applies a texture transform, if present, to the map definition. Requires * the KHR_texture_transform extension. */function applyTextureTransform(mapDef,texture){var didTransform=false;var transformDef={};if(texture.offset.x!==0||texture.offset.y!==0){transformDef.offset=texture.offset.toArray();didTransform=true;}if(texture.rotation!==0){transformDef.rotation=texture.rotation;didTransform=true;}if(texture.repeat.x!==1||texture.repeat.y!==1){transformDef.scale=texture.repeat.toArray();didTransform=true;}if(didTransform){mapDef.extensions=mapDef.extensions||{};mapDef.extensions['KHR_texture_transform']=transformDef;extensionsUsed['KHR_texture_transform']=true;}}/** * Process a buffer to append to the default one. * @param {ArrayBuffer} buffer * @return {Integer} */function processBuffer(buffer){if(!outputJSON.buffers){outputJSON.buffers=[{byteLength:0}];}// All buffers are merged before export. buffers.push(buffer);return 0;}/** * Process and generate a BufferView * @param {BufferAttribute} attribute * @param {number} componentType * @param {number} start * @param {number} count * @param {number} target (Optional) Target usage of the BufferView * @return {Object} */function processBufferView(attribute,componentType,start,count,target){if(!outputJSON.bufferViews){outputJSON.bufferViews=[];}// Create a new dataview and dump the attribute's array into it var componentSize;if(componentType===WEBGL_CONSTANTS.UNSIGNED_BYTE){componentSize=1;}else if(componentType===WEBGL_CONSTANTS.UNSIGNED_SHORT){componentSize=2;}else{componentSize=4;}var byteLength=getPaddedBufferSize(count*attribute.itemSize*componentSize);var dataView=new DataView(new ArrayBuffer(byteLength));var offset=0;for(var i=start;i4){// no support for interleaved data for itemSize > 4 value=attribute.array[i*attribute.itemSize+a];}else{if(a===0)value=attribute.getX(i);else if(a===1)value=attribute.getY(i);else if(a===2)value=attribute.getZ(i);else if(a===3)value=attribute.getW(i);}if(componentType===WEBGL_CONSTANTS.FLOAT){dataView.setFloat32(offset,value,true);}else if(componentType===WEBGL_CONSTANTS.UNSIGNED_INT){dataView.setUint32(offset,value,true);}else if(componentType===WEBGL_CONSTANTS.UNSIGNED_SHORT){dataView.setUint16(offset,value,true);}else if(componentType===WEBGL_CONSTANTS.UNSIGNED_BYTE){dataView.setUint8(offset,value);}offset+=componentSize;}}var gltfBufferView={buffer:processBuffer(dataView.buffer),byteOffset:byteOffset,byteLength:byteLength};if(target!==undefined)gltfBufferView.target=target;if(target===WEBGL_CONSTANTS.ARRAY_BUFFER){// Only define byteStride for vertex attributes. gltfBufferView.byteStride=attribute.itemSize*componentSize;}byteOffset+=byteLength;outputJSON.bufferViews.push(gltfBufferView);// @TODO Merge bufferViews where possible. var output={id:outputJSON.bufferViews.length-1,byteLength:0};return output;}/** * Process and generate a BufferView from an image Blob. * @param {Blob} blob * @return {Promise} */function processBufferViewImage(blob){if(!outputJSON.bufferViews){outputJSON.bufferViews=[];}return new Promise(function(resolve){var reader=new window.FileReader();reader.readAsArrayBuffer(blob);reader.onloadend=function(){var buffer=getPaddedArrayBuffer(reader.result);var bufferView={buffer:processBuffer(buffer),byteOffset:byteOffset,byteLength:buffer.byteLength};byteOffset+=buffer.byteLength;outputJSON.bufferViews.push(bufferView);resolve(outputJSON.bufferViews.length-1);};});}/** * Process attribute to generate an accessor * @param {BufferAttribute} attribute Attribute to process * @param {BufferGeometry} geometry (Optional) Geometry used for truncated draw range * @param {Integer} start (Optional) * @param {Integer} count (Optional) * @return {Integer} Index of the processed accessor on the "accessors" array */function processAccessor(attribute,geometry,start,count){var types={1:'SCALAR',2:'VEC2',3:'VEC3',4:'VEC4',16:'MAT4'};var componentType;// Detect the component type of the attribute array (float, uint or ushort) if(attribute.array.constructor===Float32Array){componentType=WEBGL_CONSTANTS.FLOAT;}else if(attribute.array.constructor===Uint32Array){componentType=WEBGL_CONSTANTS.UNSIGNED_INT;}else if(attribute.array.constructor===Uint16Array){componentType=WEBGL_CONSTANTS.UNSIGNED_SHORT;}else if(attribute.array.constructor===Uint8Array){componentType=WEBGL_CONSTANTS.UNSIGNED_BYTE;}else{throw new Error('THREE.GLTFExporter: Unsupported bufferAttribute component type.');}if(start===undefined)start=0;if(count===undefined)count=attribute.count;// @TODO Indexed buffer geometry with drawRange not supported yet if(options.truncateDrawRange&&geometry!==undefined&&geometry.index===null){var end=start+count;var end2=geometry.drawRange.count===Infinity?attribute.count:geometry.drawRange.start+geometry.drawRange.count;start=Math.max(start,geometry.drawRange.start);count=Math.min(end,end2)-start;if(count<0)count=0;}// Skip creating an accessor if the attribute doesn't have data to export if(count===0){return null;}var minMax=getMinMax(attribute,start,count);var bufferViewTarget;// If geometry isn't provided, don't infer the target usage of the bufferView. For // animation samplers, target must not be set. if(geometry!==undefined){bufferViewTarget=attribute===geometry.index?WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER:WEBGL_CONSTANTS.ARRAY_BUFFER;}var bufferView=processBufferView(attribute,componentType,start,count,bufferViewTarget);var gltfAccessor={bufferView:bufferView.id,byteOffset:bufferView.byteOffset,componentType:componentType,count:count,max:minMax.max,min:minMax.min,type:types[attribute.itemSize]};if(attribute.normalized===true){gltfAccessor.normalized=true;}if(!outputJSON.accessors){outputJSON.accessors=[];}outputJSON.accessors.push(gltfAccessor);return outputJSON.accessors.length-1;}/** * Process image * @param {Image} image to process * @param {Integer} format of the image (e.g. THREE.RGBFormat, RGBAFormat etc) * @param {Boolean} flipY before writing out the image * @return {Integer} Index of the processed texture in the "images" array */function processImage(image,format,flipY){if(!cachedData.images.has(image)){cachedData.images.set(image,{});}var cachedImages=cachedData.images.get(image);var mimeType=format===RGBAFormat?'image/png':'image/jpeg';var key=mimeType+":flipY/"+flipY.toString();if(cachedImages[key]!==undefined){return cachedImages[key];}if(!outputJSON.images){outputJSON.images=[];}var gltfImage={mimeType:mimeType};if(options.embedImages){var canvas=cachedCanvas=cachedCanvas||document.createElement('canvas');canvas.width=Math.min(image.width,options.maxTextureSize);canvas.height=Math.min(image.height,options.maxTextureSize);if(options.forcePowerOfTwoTextures&&!isPowerOfTwo(canvas)){console.warn('GLTFExporter: Resized non-power-of-two image.',image);canvas.width=MathUtils.floorPowerOfTwo(canvas.width);canvas.height=MathUtils.floorPowerOfTwo(canvas.height);}var ctx=canvas.getContext('2d');if(flipY===true){ctx.translate(0,canvas.height);ctx.scale(1,-1);}ctx.drawImage(image,0,0,canvas.width,canvas.height);if(options.binary===true){pending.push(new Promise(function(resolve){canvas.toBlob(function(blob){processBufferViewImage(blob).then(function(bufferViewIndex){gltfImage.bufferView=bufferViewIndex;resolve();});},mimeType);}));}else{gltfImage.uri=canvas.toDataURL(mimeType);}}else{gltfImage.uri=image.src;}outputJSON.images.push(gltfImage);var index=outputJSON.images.length-1;cachedImages[key]=index;return index;}/** * Process sampler * @param {Texture} map Texture to process * @return {Integer} Index of the processed texture in the "samplers" array */function processSampler(map){if(!outputJSON.samplers){outputJSON.samplers=[];}var gltfSampler={magFilter:THREE_TO_WEBGL[map.magFilter],minFilter:THREE_TO_WEBGL[map.minFilter],wrapS:THREE_TO_WEBGL[map.wrapS],wrapT:THREE_TO_WEBGL[map.wrapT]};outputJSON.samplers.push(gltfSampler);return outputJSON.samplers.length-1;}/** * Process texture * @param {Texture} map Map to process * @return {Integer} Index of the processed texture in the "textures" array */function processTexture(map){if(cachedData.textures.has(map)){return cachedData.textures.get(map);}if(!outputJSON.textures){outputJSON.textures=[];}var gltfTexture={sampler:processSampler(map),source:processImage(map.image,map.format,map.flipY)};if(map.name){gltfTexture.name=map.name;}outputJSON.textures.push(gltfTexture);var index=outputJSON.textures.length-1;cachedData.textures.set(map,index);return index;}/** * Process material * @param {THREE.Material} material Material to process * @return {Integer} Index of the processed material in the "materials" array */function processMaterial(material){if(cachedData.materials.has(material)){return cachedData.materials.get(material);}if(material.isShaderMaterial){console.warn('GLTFExporter: THREE.ShaderMaterial not supported.');return null;}if(!outputJSON.materials){outputJSON.materials=[];}// @QUESTION Should we avoid including any attribute that has the default value? var gltfMaterial={pbrMetallicRoughness:{}};if(material.isMeshBasicMaterial){gltfMaterial.extensions={KHR_materials_unlit:{}};extensionsUsed['KHR_materials_unlit']=true;}else if(material.isGLTFSpecularGlossinessMaterial){gltfMaterial.extensions={KHR_materials_pbrSpecularGlossiness:{}};extensionsUsed['KHR_materials_pbrSpecularGlossiness']=true;}else if(!material.isMeshStandardMaterial){console.warn('GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.');}// pbrMetallicRoughness.baseColorFactor var color=material.color.toArray().concat([material.opacity]);if(!equalArray(color,[1,1,1,1])){gltfMaterial.pbrMetallicRoughness.baseColorFactor=color;}if(material.isMeshStandardMaterial){gltfMaterial.pbrMetallicRoughness.metallicFactor=material.metalness;gltfMaterial.pbrMetallicRoughness.roughnessFactor=material.roughness;}else if(material.isMeshBasicMaterial){gltfMaterial.pbrMetallicRoughness.metallicFactor=0.0;gltfMaterial.pbrMetallicRoughness.roughnessFactor=0.9;}else{gltfMaterial.pbrMetallicRoughness.metallicFactor=0.5;gltfMaterial.pbrMetallicRoughness.roughnessFactor=0.5;}// pbrSpecularGlossiness diffuse, specular and glossiness factor if(material.isGLTFSpecularGlossinessMaterial){if(gltfMaterial.pbrMetallicRoughness.baseColorFactor){gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseFactor=gltfMaterial.pbrMetallicRoughness.baseColorFactor;}var specularFactor=[1,1,1];material.specular.toArray(specularFactor,0);gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularFactor=specularFactor;gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.glossinessFactor=material.glossiness;}// pbrMetallicRoughness.metallicRoughnessTexture if(material.metalnessMap||material.roughnessMap){if(material.metalnessMap===material.roughnessMap){var metalRoughMapDef={index:processTexture(material.metalnessMap)};applyTextureTransform(metalRoughMapDef,material.metalnessMap);gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture=metalRoughMapDef;}else{console.warn('THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.');}}// pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture if(material.map){var baseColorMapDef={index:processTexture(material.map)};applyTextureTransform(baseColorMapDef,material.map);if(material.isGLTFSpecularGlossinessMaterial){gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseTexture=baseColorMapDef;}gltfMaterial.pbrMetallicRoughness.baseColorTexture=baseColorMapDef;}// pbrSpecularGlossiness specular map if(material.isGLTFSpecularGlossinessMaterial&&material.specularMap){var specularMapDef={index:processTexture(material.specularMap)};applyTextureTransform(specularMapDef,material.specularMap);gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularGlossinessTexture=specularMapDef;}if(material.emissive){// emissiveFactor var emissive=material.emissive.clone().multiplyScalar(material.emissiveIntensity).toArray();if(!equalArray(emissive,[0,0,0])){gltfMaterial.emissiveFactor=emissive;}// emissiveTexture if(material.emissiveMap){var emissiveMapDef={index:processTexture(material.emissiveMap)};applyTextureTransform(emissiveMapDef,material.emissiveMap);gltfMaterial.emissiveTexture=emissiveMapDef;}}// normalTexture if(material.normalMap){var normalMapDef={index:processTexture(material.normalMap)};if(material.normalScale&&material.normalScale.x!==-1){if(material.normalScale.x!==material.normalScale.y){console.warn('THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.');}normalMapDef.scale=material.normalScale.x;}applyTextureTransform(normalMapDef,material.normalMap);gltfMaterial.normalTexture=normalMapDef;}// occlusionTexture if(material.aoMap){var occlusionMapDef={index:processTexture(material.aoMap),texCoord:1};if(material.aoMapIntensity!==1.0){occlusionMapDef.strength=material.aoMapIntensity;}applyTextureTransform(occlusionMapDef,material.aoMap);gltfMaterial.occlusionTexture=occlusionMapDef;}// alphaMode if(material.transparent){gltfMaterial.alphaMode='BLEND';}else{if(material.alphaTest>0.0){gltfMaterial.alphaMode='MASK';gltfMaterial.alphaCutoff=material.alphaTest;}}// doubleSided if(material.side===DoubleSide){gltfMaterial.doubleSided=true;}if(material.name!==''){gltfMaterial.name=material.name;}serializeUserData(material,gltfMaterial);outputJSON.materials.push(gltfMaterial);var index=outputJSON.materials.length-1;cachedData.materials.set(material,index);return index;}/** * Process mesh * @param {THREE.Mesh} mesh Mesh to process * @return {Integer} Index of the processed mesh in the "meshes" array */function processMesh(mesh){var meshCacheKeyParts=[mesh.geometry.uuid];if(Array.isArray(mesh.material)){for(var i=0,l=mesh.material.length;i0){var weights=[];var targetNames=[];var reverseDictionary={};if(mesh.morphTargetDictionary!==undefined){for(var key in mesh.morphTargetDictionary){reverseDictionary[mesh.morphTargetDictionary[key]]=key;}}for(var i=0;i0){gltfMesh.extras={};gltfMesh.extras.targetNames=targetNames;}}var isMultiMaterial=Array.isArray(mesh.material);if(isMultiMaterial&&geometry.groups.length===0)return null;var materials=isMultiMaterial?mesh.material:[mesh.material];var groups=isMultiMaterial?geometry.groups:[{materialIndex:0,start:undefined,count:undefined}];for(var i=0,il=groups.length;i0)primitive.targets=targets;if(geometry.index!==null){var cacheKey=getUID(geometry.index);if(groups[i].start!==undefined||groups[i].count!==undefined){cacheKey+=':'+groups[i].start+':'+groups[i].count;}if(cachedData.attributes.has(cacheKey)){primitive.indices=cachedData.attributes.get(cacheKey);}else{primitive.indices=processAccessor(geometry.index,geometry,groups[i].start,groups[i].count);cachedData.attributes.set(cacheKey,primitive.indices);}if(primitive.indices===null)delete primitive.indices;}var material=processMaterial(materials[groups[i].materialIndex]);if(material!==null){primitive.material=material;}primitives.push(primitive);}gltfMesh.primitives=primitives;if(!outputJSON.meshes){outputJSON.meshes=[];}outputJSON.meshes.push(gltfMesh);var index=outputJSON.meshes.length-1;cachedData.meshes.set(meshCacheKey,index);return index;}/** * Process camera * @param {THREE.Camera} camera Camera to process * @return {Integer} Index of the processed mesh in the "camera" array */function processCamera(camera){if(!outputJSON.cameras){outputJSON.cameras=[];}var isOrtho=camera.isOrthographicCamera;var gltfCamera={type:isOrtho?'orthographic':'perspective'};if(isOrtho){gltfCamera.orthographic={xmag:camera.right*2,ymag:camera.top*2,zfar:camera.far<=0?0.001:camera.far,znear:camera.near<0?0:camera.near};}else{gltfCamera.perspective={aspectRatio:camera.aspect,yfov:MathUtils.degToRad(camera.fov),zfar:camera.far<=0?0.001:camera.far,znear:camera.near<0?0:camera.near};}if(camera.name!==''){gltfCamera.name=camera.type;}outputJSON.cameras.push(gltfCamera);return outputJSON.cameras.length-1;}/** * Creates glTF animation entry from AnimationClip object. * * Status: * - Only properties listed in PATH_PROPERTIES may be animated. * * @param {THREE.AnimationClip} clip * @param {THREE.Object3D} root * @return {number} */function processAnimation(clip,root){if(!outputJSON.animations){outputJSON.animations=[];}clip=GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(),root);var tracks=clip.tracks;var channels=[];var samplers=[];for(var i=0;i0)lightDef.range=light.distance;}else if(light.isSpotLight){lightDef.type='spot';if(light.distance>0)lightDef.range=light.distance;lightDef.spot={};lightDef.spot.innerConeAngle=(light.penumbra-1.0)*light.angle*-1.0;lightDef.spot.outerConeAngle=light.angle;}if(light.decay!==undefined&&light.decay!==2){console.warn('THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '+'and expects light.decay=2.');}if(light.target&&(light.target.parent!==light||light.target.position.x!==0||light.target.position.y!==0||light.target.position.z!==-1)){console.warn('THREE.GLTFExporter: Light direction may be lost. For best results, '+'make light.target a child of the light with position 0,0,-1.');}var lights=outputJSON.extensions['KHR_lights_punctual'].lights;lights.push(lightDef);return lights.length-1;}/** * Process Object3D node * @param {THREE.Object3D} node Object3D to processNode * @return {Integer} Index of the node in the nodes list */function processNode(object){if(!outputJSON.nodes){outputJSON.nodes=[];}var gltfNode={};if(options.trs){var rotation=object.quaternion.toArray();var position=object.position.toArray();var scale=object.scale.toArray();if(!equalArray(rotation,[0,0,0,1])){gltfNode.rotation=rotation;}if(!equalArray(position,[0,0,0])){gltfNode.translation=position;}if(!equalArray(scale,[1,1,1])){gltfNode.scale=scale;}}else{if(object.matrixAutoUpdate){object.updateMatrix();}if(!equalArray(object.matrix.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])){gltfNode.matrix=object.matrix.elements;}}// We don't export empty strings name because it represents no-name in Three.js. if(object.name!==''){gltfNode.name=String(object.name);}serializeUserData(object,gltfNode);if(object.isMesh||object.isLine||object.isPoints){var mesh=processMesh(object);if(mesh!==null){gltfNode.mesh=mesh;}}else if(object.isCamera){gltfNode.camera=processCamera(object);}else if(object.isDirectionalLight||object.isPointLight||object.isSpotLight){if(!extensionsUsed['KHR_lights_punctual']){outputJSON.extensions=outputJSON.extensions||{};outputJSON.extensions['KHR_lights_punctual']={lights:[]};extensionsUsed['KHR_lights_punctual']=true;}gltfNode.extensions=gltfNode.extensions||{};gltfNode.extensions['KHR_lights_punctual']={light:processLight(object)};}else if(object.isLight){console.warn('THREE.GLTFExporter: Only directional, point, and spot lights are supported.',object);return null;}if(object.isSkinnedMesh){skins.push(object);}if(object.children.length>0){var children=[];for(var i=0,l=object.children.length;i0){gltfNode.children=children;}}outputJSON.nodes.push(gltfNode);var nodeIndex=outputJSON.nodes.length-1;nodeMap.set(object,nodeIndex);return nodeIndex;}/** * Process Scene * @param {Scene} node Scene to process */function processScene(scene){if(!outputJSON.scenes){outputJSON.scenes=[];outputJSON.scene=0;}var gltfScene={};if(scene.name!==''){gltfScene.name=scene.name;}outputJSON.scenes.push(gltfScene);var nodes=[];for(var i=0,l=scene.children.length;i0){gltfScene.nodes=nodes;}serializeUserData(scene,gltfScene);}/** * Creates a Scene to hold a list of objects and parse it * @param {Array} objects List of objects to process */function processObjects(objects){var scene=new Scene();scene.name='AuxScene';for(var i=0;i0){processObjects(objectsWithoutScene);}for(var i=0;i0)outputJSON.extensionsUsed=extensionsUsedList;// Update bytelength of the single buffer. if(outputJSON.buffers&&outputJSON.buffers.length>0)outputJSON.buffers[0].byteLength=blob.size;if(options.binary===true){// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification var GLB_HEADER_BYTES=12;var GLB_HEADER_MAGIC=0x46546C67;var GLB_VERSION=2;var GLB_CHUNK_PREFIX_BYTES=8;var GLB_CHUNK_TYPE_JSON=0x4E4F534A;var GLB_CHUNK_TYPE_BIN=0x004E4942;var reader=new window.FileReader();reader.readAsArrayBuffer(blob);reader.onloadend=function(){// Binary chunk. var binaryChunk=getPaddedArrayBuffer(reader.result);var binaryChunkPrefix=new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES));binaryChunkPrefix.setUint32(0,binaryChunk.byteLength,true);binaryChunkPrefix.setUint32(4,GLB_CHUNK_TYPE_BIN,true);// JSON chunk. var jsonChunk=getPaddedArrayBuffer(stringToArrayBuffer(JSON.stringify(outputJSON)),0x20);var jsonChunkPrefix=new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES));jsonChunkPrefix.setUint32(0,jsonChunk.byteLength,true);jsonChunkPrefix.setUint32(4,GLB_CHUNK_TYPE_JSON,true);// GLB header. var header=new ArrayBuffer(GLB_HEADER_BYTES);var headerView=new DataView(header);headerView.setUint32(0,GLB_HEADER_MAGIC,true);headerView.setUint32(4,GLB_VERSION,true);var totalByteLength=GLB_HEADER_BYTES+jsonChunkPrefix.byteLength+jsonChunk.byteLength+binaryChunkPrefix.byteLength+binaryChunk.byteLength;headerView.setUint32(8,totalByteLength,true);var glbBlob=new Blob([header,jsonChunkPrefix,jsonChunk,binaryChunkPrefix,binaryChunk],{type:'application/octet-stream'});var glbReader=new window.FileReader();glbReader.readAsArrayBuffer(glbBlob);glbReader.onloadend=function(){onDone(glbReader.result);};};}else{if(outputJSON.buffers&&outputJSON.buffers.length>0){var reader=new window.FileReader();reader.readAsDataURL(blob);reader.onloadend=function(){var base64data=reader.result;outputJSON.buffers[0].uri=base64data;onDone(outputJSON);};}else{onDone(outputJSON);}}});}};GLTFExporter.Utils={insertKeyframe:function insertKeyframe(track,time){var tolerance=0.001;// 1ms var valueSize=track.getValueSize();var times=new track.TimeBufferType(track.times.length+1);var values=new track.ValueBufferType(track.values.length+valueSize);var interpolant=track.createInterpolant(new track.ValueBufferType(valueSize));var index;if(track.times.length===0){times[0]=time;for(var i=0;itrack.times[track.times.length-1]){if(Math.abs(track.times[track.times.length-1]-time)time){times.set(track.times.slice(0,i+1),0);times[i+1]=time;times.set(track.times.slice(i+1),i+2);values.set(track.values.slice(0,(i+1)*valueSize),0);values.set(interpolant.evaluate(time),(i+1)*valueSize);values.set(track.values.slice((i+1)*valueSize),(i+2)*valueSize);index=i+1;break;}}}track.times=times;track.values=values;return index;},mergeMorphTargetTracks:function mergeMorphTargetTracks(clip,root){var tracks=[];var mergedTracks={};var sourceTracks=clip.tracks;for(var i=0;i=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var $updateThreeSide=Symbol('updateThreeSide');var $currentGLTF$1=Symbol('currentGLTF');var $modelGraft$1=Symbol('modelGraft');var $mainPort=Symbol('mainPort');var $threePort=Symbol('threePort');var $manipulator=Symbol('manipulator');var $modelKernel=Symbol('modelKernel');var $onModelChange=Symbol('onModelChange');var $onModelGraftMutation=Symbol('onModelGraftMutation');var SceneGraphMixin=function SceneGraphMixin(ModelViewerElement){var _a,_b,_c,_d,_e,_f,_g;var _h;var SceneGraphModelViewerElement=/*#__PURE__*/function(_ModelViewerElement7){_inherits(SceneGraphModelViewerElement,_ModelViewerElement7);var _super50=_createSuper(SceneGraphModelViewerElement);function SceneGraphModelViewerElement(){var _this90;_classCallCheck(this,SceneGraphModelViewerElement);_this90=_super50.apply(this,arguments);_this90[_h]=null;_this90[_a]=null;_this90[_b]=null;_this90[_c]=null;_this90[_d]=null;_this90[_e]=null;_this90[_f]=function(event){var data=event.data;if(data&&data.type===ThreeDOMMessageType.MODEL_CHANGE){var serialized=data.model;var currentKernel=_this90[$modelKernel];if(currentKernel!=null){currentKernel.deactivate();}else if(serialized==null){return;}if(serialized!=null){_this90[$modelKernel]=new ModelKernel(data.port,serialized);}else{_this90[$modelKernel]=null;}_this90.dispatchEvent(new CustomEvent('scene-graph-ready',{detail:{url:serialized?serialized.modelUri:null}}));}};_this90[_g]=function(_event){_this90[$needsRender]();};return _this90;}_createClass(SceneGraphModelViewerElement,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(SceneGraphModelViewerElement.prototype),"connectedCallback",this).call(this);var _MessageChannel=new MessageChannel(),port1=_MessageChannel.port1,port2=_MessageChannel.port2;port1.start();port2.start();this[$mainPort]=port1;this[$threePort]=port2;this[$mainPort].onmessage=this[$onModelChange];}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(SceneGraphModelViewerElement.prototype),"disconnectedCallback",this).call(this);this[$mainPort].close();this[$threePort].close();this[$mainPort]=null;this[$threePort]=null;if(this[$manipulator]!=null){this[$manipulator].dispose();}if(this[$modelKernel]!=null){this[$modelKernel].deactivate();}}},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(SceneGraphModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has($modelGraft$1)){var oldModelGraft=changedProperties.get($modelGraft$1);if(oldModelGraft!=null){oldModelGraft.removeEventListener('mutation',this[$onModelGraftMutation]);}var modelGraft=this[$modelGraft$1];if(modelGraft!=null){modelGraft.addEventListener('mutation',this[$onModelGraftMutation]);}}}},{key:(_h=$modelGraft$1,_a=$currentGLTF$1,_b=$mainPort,_c=$threePort,_d=$manipulator,_e=$modelKernel,$onModelLoad),value:function value(){_get(_getPrototypeOf(SceneGraphModelViewerElement.prototype),$onModelLoad,this).call(this);this[$updateThreeSide]();}},{key:$updateThreeSide,value:function value(){var scene=this[$scene];var model=scene.model;var currentGLTF=model.currentGLTF;var modelGraft=null;var manipulator=null;if(currentGLTF!=null){var correlatedSceneGraph=currentGLTF.correlatedSceneGraph;var currentModelGraft=this[$modelGraft$1];var currentManipulator=this[$manipulator];if(correlatedSceneGraph!=null){if(currentManipulator!=null){currentManipulator.dispose();}if(currentModelGraft!=null&¤tGLTF===this[$currentGLTF$1]){return;}modelGraft=new ModelGraft(model.url||'',correlatedSceneGraph);var channel=null;if(modelGraft!=null&&modelGraft.model!=null){channel=new MessageChannel();manipulator=new ModelGraftManipulator(modelGraft,channel.port1);this[$threePort].postMessage({type:ThreeDOMMessageType.MODEL_CHANGE,model:modelGraft.model.toJSON(),port:channel.port2},[channel.port2]);}else{this[$threePort].postMessage({type:ThreeDOMMessageType.MODEL_CHANGE,model:null,port:null});}}}this[$modelGraft$1]=modelGraft;this[$manipulator]=manipulator;this[$currentGLTF$1]=currentGLTF;}},{key:"exportScene",value:function(){var _exportScene=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee47(options){var model;return regeneratorRuntime.wrap(function _callee47$(_context48){while(1){switch(_context48.prev=_context48.next){case 0:model=this[$scene].model;return _context48.abrupt("return",new Promise(/*#__PURE__*/function(){var _ref11=_asyncToGenerator(/*#__PURE__*/regeneratorRuntime.mark(function _callee46(resolve,reject){var opts,shadow,visible,exporter;return regeneratorRuntime.wrap(function _callee46$(_context47){while(1){switch(_context47.prev=_context47.next){case 0:if(!(model==null)){_context47.next=2;break;}return _context47.abrupt("return",reject('Model missing or not yet loaded'));case 2:opts={binary:true,onlyVisible:true,maxTextureSize:Infinity,forcePowerOfTwoTextures:false,includeCustomExtensions:false,embedImages:true};Object.assign(opts,options);opts.animations=model.animations;opts.truncateDrawRange=true;shadow=model[$shadow];visible=false;if(shadow!=null){visible=shadow.visible;shadow.visible=false;}exporter=new GLTFExporter();exporter.parse(model.modelContainer,function(gltf){return resolve(new Blob([opts.binary?gltf:JSON.stringify(gltf)],{type:opts.binary?'application/octet-stream':'application/json'}));},opts);if(shadow!=null){shadow.visible=visible;}case 12:case"end":return _context47.stop();}}},_callee46);}));return function(_x51,_x52){return _ref11.apply(this,arguments);};}()));case 2:case"end":return _context48.stop();}}},_callee47,this);}));function exportScene(_x50){return _exportScene.apply(this,arguments);}return exportScene;}()},{key:"model",get:function get(){var kernel=this[$modelKernel];return kernel?kernel.model:undefined;}}]);return SceneGraphModelViewerElement;}(ModelViewerElement);_f=$onModelChange,_g=$onModelGraftMutation;__decorate$6([property({type:Object})],SceneGraphModelViewerElement.prototype,_h,void 0);return SceneGraphModelViewerElement;};var __decorate$7=undefined&&undefined.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if((typeof Reflect==="undefined"?"undefined":_typeof(Reflect))==="object"&&typeof undefined==="function")r=undefined(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--){if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;}return c>3&&r&&Object.defineProperty(target,key,r),r;};var DEFAULT_ROTATION_SPEED=Math.PI/32;var AUTO_ROTATE_DELAY_DEFAULT=3000;var rotationRateIntrinsics={basis:[degreesToRadians(numberNode(DEFAULT_ROTATION_SPEED,'rad'))],keywords:{auto:[null]}};var $autoRotateStartTime=Symbol('autoRotateStartTime');var $radiansPerSecond=Symbol('radiansPerSecond');var $syncRotationRate=Symbol('syncRotationRate');var $cameraChangeHandler=Symbol('cameraChangeHandler');var $onCameraChange=Symbol('onCameraChange');var StagingMixin=function StagingMixin(ModelViewerElement){var _a,_b,_c;var StagingModelViewerElement=/*#__PURE__*/function(_ModelViewerElement8){_inherits(StagingModelViewerElement,_ModelViewerElement8);var _super51=_createSuper(StagingModelViewerElement);function StagingModelViewerElement(){var _this91;_classCallCheck(this,StagingModelViewerElement);_this91=_super51.apply(this,arguments);_this91.autoRotate=false;_this91.autoRotateDelay=AUTO_ROTATE_DELAY_DEFAULT;_this91.rotationPerSecond='auto';_this91[_a]=performance.now();_this91[_b]=0;_this91[_c]=function(event){return _this91[$onCameraChange](event);};return _this91;}_createClass(StagingModelViewerElement,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(StagingModelViewerElement.prototype),"connectedCallback",this).call(this);this.addEventListener('camera-change',this[$cameraChangeHandler]);this[$autoRotateStartTime]=performance.now();}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(StagingModelViewerElement.prototype),"disconnectedCallback",this).call(this);this.removeEventListener('camera-change',this[$cameraChangeHandler]);this[$autoRotateStartTime]=performance.now();}},{key:"updated",value:function updated(changedProperties){_get(_getPrototypeOf(StagingModelViewerElement.prototype),"updated",this).call(this,changedProperties);if(changedProperties.has('autoRotate')){this[$autoRotateStartTime]=performance.now();}}},{key:(_a=$autoRotateStartTime,_b=$radiansPerSecond,_c=$cameraChangeHandler,$syncRotationRate),value:function value(style){this[$radiansPerSecond]=style[0];}},{key:$tick$1,value:function value(time,delta){_get(_getPrototypeOf(StagingModelViewerElement.prototype),$tick$1,this).call(this,time,delta);if(!this.autoRotate||!this[$hasTransitioned]()||this[$renderer].isPresenting){return;}var rotationDelta=Math.min(delta,time-this[$autoRotateStartTime]-this.autoRotateDelay);if(rotationDelta>0){this[$scene].yaw=this.turntableRotation+this[$radiansPerSecond]*rotationDelta*0.001;}}},{key:$onCameraChange,value:function value(event){if(!this.autoRotate){return;}if(event.detail.source==='user-interaction'){this[$autoRotateStartTime]=performance.now();}}},{key:"resetTurntableRotation",value:function resetTurntableRotation(){var theta=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;this[$scene].yaw=theta;}},{key:"turntableRotation",get:function get(){return this[$scene].yaw;}}]);return StagingModelViewerElement;}(ModelViewerElement);__decorate$7([property({type:Boolean,attribute:'auto-rotate'})],StagingModelViewerElement.prototype,"autoRotate",void 0);__decorate$7([property({type:Number,attribute:'auto-rotate-delay'})],StagingModelViewerElement.prototype,"autoRotateDelay",void 0);__decorate$7([style({intrinsics:rotationRateIntrinsics,updateHandler:$syncRotationRate}),property({type:String,attribute:'rotation-per-second'})],StagingModelViewerElement.prototype,"rotationPerSecond",void 0);return StagingModelViewerElement;};var FocusVisiblePolyfillMixin=function FocusVisiblePolyfillMixin(SuperClass){var _a;var coordinateWithPolyfill=function coordinateWithPolyfill(instance){if(instance.shadowRoot==null||instance.hasAttribute('data-js-focus-visible')){return function(){};}if(self.applyFocusVisiblePolyfill){self.applyFocusVisiblePolyfill(instance.shadowRoot);}else{var coordinationHandler=function coordinationHandler(){self.applyFocusVisiblePolyfill(instance.shadowRoot);};self.addEventListener('focus-visible-polyfill-ready',coordinationHandler,{once:true});return function(){self.removeEventListener('focus-visible-polyfill-ready',coordinationHandler);};}return function(){};};var $endPolyfillCoordination=Symbol('endPolyfillCoordination');var FocusVisibleCoordinator=/*#__PURE__*/function(_SuperClass){_inherits(FocusVisibleCoordinator,_SuperClass);var _super52=_createSuper(FocusVisibleCoordinator);function FocusVisibleCoordinator(){var _this92;_classCallCheck(this,FocusVisibleCoordinator);_this92=_super52.apply(this,arguments);_this92[_a]=null;return _this92;}_createClass(FocusVisibleCoordinator,[{key:"connectedCallback",value:function connectedCallback(){_get(_getPrototypeOf(FocusVisibleCoordinator.prototype),"connectedCallback",this)&&_get(_getPrototypeOf(FocusVisibleCoordinator.prototype),"connectedCallback",this).call(this);if(this[$endPolyfillCoordination]==null){this[$endPolyfillCoordination]=coordinateWithPolyfill(this);}}},{key:"disconnectedCallback",value:function disconnectedCallback(){_get(_getPrototypeOf(FocusVisibleCoordinator.prototype),"disconnectedCallback",this)&&_get(_getPrototypeOf(FocusVisibleCoordinator.prototype),"disconnectedCallback",this).call(this);if(this[$endPolyfillCoordination]!=null){this[$endPolyfillCoordination]();this[$endPolyfillCoordination]=null;}}}]);return FocusVisibleCoordinator;}(SuperClass);_a=$endPolyfillCoordination;return FocusVisibleCoordinator;};var ModelViewerElement=AnnotationMixin(SceneGraphMixin(StagingMixin(EnvironmentMixin(ControlsMixin(ARMixin(LoadingMixin(AnimationMixin(FocusVisiblePolyfillMixin(ModelViewerElementBase)))))))));customElements.define('model-viewer',ModelViewerElement);exports.ModelViewerElement=ModelViewerElement;Object.defineProperty(exports,'__esModule',{value:true});});