From fafd43da6ce49dd86d7cf8d94ff69a6cca593f9b Mon Sep 17 00:00:00 2001 From: Felix Zhang Date: Wed, 22 Sep 2021 15:41:39 -0700 Subject: [PATCH] expose trigger axes --- build/webxr-polyfill.js | 12 ++++++------ build/webxr-polyfill.min.js | 2 +- build/webxr-polyfill.module.js | 12 ++++++------ src/devices/GamepadMappings.js | 12 ++++++------ 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/build/webxr-polyfill.js b/build/webxr-polyfill.js index 9e336de..470e169 100644 --- a/build/webxr-polyfill.js +++ b/build/webxr-polyfill.js @@ -5091,8 +5091,8 @@ let oculusTouch = { profiles: ['oculus-touch', 'generic-trigger-squeeze-thumbstick'], axes: { length: 4, - 0: null, - 1: null, + 0: 2, + 1: 3, 2: 0, 3: 1 }, @@ -5119,8 +5119,8 @@ let oculusTouchV2 = { profiles: ['oculus-touch-v2', 'oculus-touch', 'generic-trigger-squeeze-thumbstick'], axes: { length: 4, - 0: null, - 1: null, + 0: 2, + 1: 3, 2: 0, 3: 1 }, @@ -5147,8 +5147,8 @@ let oculusTouchV3 = { profiles: ['oculus-touch-v3', 'oculus-touch-v2', 'oculus-touch', 'generic-trigger-squeeze-thumbstick'], axes: { length: 4, - 0: null, - 1: null, + 0: 2, + 1: 3, 2: 0, 3: 1 }, diff --git a/build/webxr-polyfill.min.js b/build/webxr-polyfill.min.js index 6563691..0cc0588 100644 --- a/build/webxr-polyfill.min.js +++ b/build/webxr-polyfill.min.js @@ -92,4 +92,4 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.WebXRPolyfill=t()}(this,function(){"use strict";const e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t=Symbol("@@webxr-polyfill/EventTarget");class i{constructor(){this[t]={listeners:new Map}}addEventListener(e,i){if("string"!=typeof e)throw new Error("`type` must be a string");if("function"!=typeof i)throw new Error("`listener` must be a function");const r=this[t].listeners.get(e)||[];r.push(i),this[t].listeners.set(e,r)}removeEventListener(e,i){if("string"!=typeof e)throw new Error("`type` must be a string");if("function"!=typeof i)throw new Error("`listener` must be a function");const r=this[t].listeners.get(e)||[];for(let e=r.length;e>=0;e--)r[e]===i&&r.pop()}dispatchEvent(e,i){const r=this[t].listeners.get(e)||[],s=[];for(let e=0;e0?(r=2*Math.sqrt(i+1),e[3]=.25*r,e[0]=(t[6]-t[9])/r,e[1]=(t[8]-t[2])/r,e[2]=(t[1]-t[4])/r):t[0]>t[5]&&t[0]>t[10]?(r=2*Math.sqrt(1+t[0]-t[5]-t[10]),e[3]=(t[6]-t[9])/r,e[0]=.25*r,e[1]=(t[1]+t[4])/r,e[2]=(t[8]+t[2])/r):t[5]>t[10]?(r=2*Math.sqrt(1+t[5]-t[0]-t[10]),e[3]=(t[8]-t[2])/r,e[0]=(t[1]+t[4])/r,e[1]=.25*r,e[2]=(t[6]+t[9])/r):(r=2*Math.sqrt(1+t[10]-t[0]-t[5]),e[3]=(t[1]-t[4])/r,e[0]=(t[8]+t[2])/r,e[1]=(t[6]+t[9])/r,e[2]=.25*r),e}function d(e,t,i,r,s){let n,a=1/Math.tan(t/2);return e[0]=a/i,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=a,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,null!=s&&s!==1/0?(n=1/(r-s),e[10]=(s+r)*n,e[14]=2*s*r*n):(e[10]=-1,e[14]=-2*r),e}function u(){let e=new s(3);return s!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e}function p(e){var t=new s(3);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function f(e,t,i){let r=new s(3);return r[0]=e,r[1]=t,r[2]=i,r}function m(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function g(e,t,i){return e[0]=t[0]+i[0],e[1]=t[1]+i[1],e[2]=t[2]+i[2],e}function v(e,t,i){return e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e}function w(e,t){let i=t[0],r=t[1],s=t[2],n=i*i+r*r+s*s;return n>0&&(n=1/Math.sqrt(n),e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n),e}function y(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function b(e,t,i){let r=t[0],s=t[1],n=t[2],a=i[0],o=i[1],l=i[2];return e[0]=s*l-n*o,e[1]=n*a-r*l,e[2]=r*o-s*a,e}function E(e,t,i){let r=i[0],s=i[1],n=i[2],a=i[3],o=t[0],l=t[1],A=t[2],h=s*A-n*l,c=n*o-r*A,d=r*l-s*o,u=s*d-n*c,p=n*h-r*d,f=r*c-s*h,m=2*a;return h*=m,c*=m,d*=m,u*=2,p*=2,f*=2,e[0]=o+h+u,e[1]=l+c+p,e[2]=A+d+f,e}const S=function(e){let t=e[0],i=e[1],r=e[2];return Math.sqrt(t*t+i*i+r*r)};!function(){let e=u()}();!function(){let e=function(){let e=new s(4);return s!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0,e[3]=0),e}()}();function M(){let e=new s(4);return s!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e[3]=1,e}function x(e,t,i){let r=t[0],s=t[1],n=t[2],a=t[3],o=i[0],l=i[1],A=i[2],h=i[3];return e[0]=r*h+a*o+s*A-n*l,e[1]=s*h+a*l+n*o-r*A,e[2]=n*h+a*A+r*l-s*o,e[3]=a*h-r*o-s*l-n*A,e}function _(e,t,i,s){let n,a,o,l,A,h=t[0],c=t[1],d=t[2],u=t[3],p=i[0],f=i[1],m=i[2],g=i[3];return(a=h*p+c*f+d*m+u*g)<0&&(a=-a,p=-p,f=-f,m=-m,g=-g),1-a>r?(n=Math.acos(a),o=Math.sin(n),l=Math.sin((1-s)*n)/o,A=Math.sin(s*n)/o):(l=1-s,A=s),e[0]=l*h+A*p,e[1]=l*c+A*f,e[2]=l*d+A*m,e[3]=l*u+A*g,e}function F(e,t){let i=t[0],r=t[1],s=t[2],n=t[3],a=i*i+r*r+s*s+n*n,o=a?1/a:0;return e[0]=-i*o,e[1]=-r*o,e[2]=-s*o,e[3]=n*o,e}const R=function(e){let t=new s(4);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t},T=function(e,t,i,r){let n=new s(4);return n[0]=e,n[1]=t,n[2]=i,n[3]=r,n},P=function(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e},B=function(e,t){let i=t[0],r=t[1],s=t[2],n=t[3],a=i*i+r*r+s*s+n*n;return a>0&&(a=1/Math.sqrt(a),e[0]=i*a,e[1]=r*a,e[2]=s*a,e[3]=n*a),e},C=(function(){let e=u(),t=f(1,0,0),i=f(0,1,0)}(),function(){let e=M(),t=M()}(),function(){let e=function(){let e=new s(9);return s!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[5]=0,e[6]=0,e[7]=0),e[0]=1,e[4]=1,e[8]=1,e}()}(),Symbol("@@webxr-polyfill/XRRigidTransform"));class D{constructor(){if(this[C]={matrix:null,position:null,orientation:null,inverse:null},0===arguments.length)this[C].matrix=a(new Float32Array(16));else if(1===arguments.length)arguments[0]instanceof Float32Array?this[C].matrix=arguments[0]:(this[C].position=this._getPoint(arguments[0]),this[C].orientation=DOMPointReadOnly.fromPoint({x:0,y:0,z:0,w:1}));else{if(2!==arguments.length)throw new Error("Too many arguments!");this[C].position=this._getPoint(arguments[0]),this[C].orientation=this._getPoint(arguments[1])}if(this[C].matrix){let e=u();h(e,this[C].matrix),this[C].position=DOMPointReadOnly.fromPoint({x:e[0],y:e[1],z:e[2]});let t=M();c(t,this[C].matrix),this[C].orientation=DOMPointReadOnly.fromPoint({x:t[0],y:t[1],z:t[2],w:t[3]})}else this[C].matrix=a(new Float32Array(16)),A(this[C].matrix,T(this[C].orientation.x,this[C].orientation.y,this[C].orientation.z,this[C].orientation.w),f(this[C].position.x,this[C].position.y,this[C].position.z))}_getPoint(e){return e instanceof DOMPointReadOnly?e:DOMPointReadOnly.fromPoint(e)}get matrix(){return this[C].matrix}get position(){return this[C].position}get orientation(){return this[C].orientation}get inverse(){if(null===this[C].inverse){let e=a(new Float32Array(16));o(e,this[C].matrix),this[C].inverse=new D(e),this[C].inverse[C].inverse=this}return this[C].inverse}}const I=Symbol("@@webxr-polyfill/XRSpace");class L{constructor(e=null,t=null){this[I]={specialType:e,inputSource:t,baseMatrix:null,inverseBaseMatrix:null,lastFrameId:-1}}get _specialType(){return this[I].specialType}get _inputSource(){return this[I].inputSource}_ensurePoseUpdated(e,t){t!=this[I].lastFrameId&&(this[I].lastFrameId=t,this._onPoseUpdate(e))}_onPoseUpdate(e){"viewer"==this[I].specialType&&(this._baseMatrix=e.getBasePoseMatrix())}set _baseMatrix(e){this[I].baseMatrix=e,this[I].inverseBaseMatrix=null}get _baseMatrix(){return this[I].baseMatrix||this[I].inverseBaseMatrix&&(this[I].baseMatrix=new Float32Array(16),o(this[I].baseMatrix,this[I].inverseBaseMatrix)),this[I].baseMatrix}set _inverseBaseMatrix(e){this[I].inverseBaseMatrix=e,this[I].baseMatrix=null}get _inverseBaseMatrix(){return this[I].inverseBaseMatrix||this[I].baseMatrix&&(this[I].inverseBaseMatrix=new Float32Array(16),o(this[I].inverseBaseMatrix,this[I].baseMatrix)),this[I].inverseBaseMatrix}_getSpaceRelativeTransform(e){if(!this._inverseBaseMatrix||!e._baseMatrix)return null;let t=new Float32Array(16);return l(t,this._inverseBaseMatrix,e._baseMatrix),new D(t)}}const O=1.6,N=Symbol("@@webxr-polyfill/XRReferenceSpace"),G=["viewer","local","local-floor","bounded-floor","unbounded"];class Q extends L{constructor(e,t=null){if(!G.includes(e))throw new Error(`XRReferenceSpaceType must be one of ${G}`);if(super(e),"bounded-floor"===e&&!t)throw new Error("XRReferenceSpace cannot use 'bounded-floor' type if the platform does not provide the floor level");(function(e){return"bounded-floor"===e||"local-floor"===e})(e)&&!t&&((t=a(new Float32Array(16)))[13]=O),this._inverseBaseMatrix=t||a(new Float32Array(16)),this[N]={type:e,transform:t,originOffset:a(new Float32Array(16))}}_transformBasePoseMatrix(e,t){l(e,this._inverseBaseMatrix,t)}_originOffsetMatrix(){return this[N].originOffset}_adjustForOriginOffset(e){let t=new Float32Array(16);o(t,this[N].originOffset),l(e,t,e)}_getSpaceRelativeTransform(e){let t=super._getSpaceRelativeTransform(e);return this._adjustForOriginOffset(t.matrix),new XRRigidTransform(t.matrix)}getOffsetReferenceSpace(e){let t=new Q(this[N].type,this[N].transform,this[N].bounds);return l(t[N].originOffset,this[N].originOffset,e.matrix),t}}const k=Symbol("@@webxr-polyfill/XR"),z=["inline","immersive-vr","immersive-ar"],V={inline:{requiredFeatures:["viewer"],optionalFeatures:[]},"immersive-vr":{requiredFeatures:["viewer","local"],optionalFeatures:[]},"immersive-ar":{requiredFeatures:["viewer","local"],optionalFeatures:[]}},U="Polyfill Error: Must call navigator.xr.isSessionSupported() with any XRSessionMode\nor navigator.xr.requestSession('inline') prior to requesting an immersive\nsession. This is a limitation specific to the WebXR Polyfill and does not apply\nto native implementations of the API.";let H;if("performance"in e==!1){let e=Date.now();H=(()=>Date.now()-e)}else H=(()=>performance.now());var X=H;const W=Symbol("@@webxr-polyfill/XRPose");class j{constructor(e,t){this[W]={transform:e,emulatedPosition:t}}get transform(){return this[W].transform}get emulatedPosition(){return this[W].emulatedPosition}}const q=Symbol("@@webxr-polyfill/XRViewerPose");class Y extends j{constructor(e,t,i=!1){super(e,i),this[q]={views:t}}get views(){return this[q].views}}const Z=Symbol("@@webxr-polyfill/XRViewport");class J{constructor(e){this[Z]={target:e}}get x(){return this[Z].target.x}get y(){return this[Z].target.y}get width(){return this[Z].target.width}get height(){return this[Z].target.height}}const K=["left","right","none"],$=Symbol("@@webxr-polyfill/XRView");class ee{constructor(e,t,i,r,s){if(!K.includes(i))throw new Error(`XREye must be one of: ${K}`);const n=Object.create(null),a=new J(n);this[$]={device:e,eye:i,viewport:a,temp:n,sessionId:r,transform:t,viewIndex:s}}get eye(){return this[$].eye}get projectionMatrix(){return this[$].device.getProjectionMatrix(this.eye,this[$].viewIndex)}get transform(){return this[$].transform}_getViewport(e){if(this[$].device.getViewport(this[$].sessionId,this.eye,e,this[$].temp,this[$].viewIndex))return this[$].viewport}}const te=Symbol("@@webxr-polyfill/XRFrame"),ie="XRFrame access outside the callback that produced it is invalid.",re="getViewerPose can only be called on XRFrame objects passed to XRSession.requestAnimationFrame callbacks.";let se=0;class ne{constructor(e,t,i){this[te]={id:++se,active:!1,animationFrame:!1,device:e,session:t,sessionId:i}}get session(){return this[te].session}getViewerPose(e){if(!this[te].animationFrame)throw new DOMException(re,"InvalidStateError");if(!this[te].active)throw new DOMException(ie,"InvalidStateError");const t=this[te].device,i=this[te].session;i[fe].viewerSpace._ensurePoseUpdated(t,this[te].id),e._ensurePoseUpdated(t,this[te].id);let r=e._getSpaceRelativeTransform(i[fe].viewerSpace);const s=[];for(const r of i[fe].viewSpaces){r._ensurePoseUpdated(t,this[te].id);let i=e._getSpaceRelativeTransform(r),n=new ee(t,i,r.eye,this[te].sessionId,r.viewIndex);s.push(n)}return new Y(r,s,!1)}getPose(e,t){if(!this[te].active)throw new DOMException(ie,"InvalidStateError");const i=this[te].device;if("target-ray"===e._specialType||"grip"===e._specialType)return i.getInputPose(e._inputSource,t,e._specialType);{e._ensurePoseUpdated(i,this[te].id),t._ensurePoseUpdated(i,this[te].id);let r=t._getSpaceRelativeTransform(e);return r?new XRPose(r,!1):null}}}const ae=Symbol("@@webxr-polyfill/XRRenderState"),oe=Object.freeze({depthNear:.1,depthFar:1e3,inlineVerticalFieldOfView:null,baseLayer:null});class le{constructor(e={}){const t=Object.assign({},oe,e);this[ae]={config:t}}get depthNear(){return this[ae].config.depthNear}get depthFar(){return this[ae].config.depthFar}get inlineVerticalFieldOfView(){return this[ae].config.inlineVerticalFieldOfView}get baseLayer(){return this[ae].config.baseLayer}}const Ae=Symbol("@@webxr-polyfill/XRInputSourceEvent");class he extends Event{constructor(e,t){super(e,t),this[Ae]={frame:t.frame,inputSource:t.inputSource},Object.setPrototypeOf(this,he.prototype)}get frame(){return this[Ae].frame}get inputSource(){return this[Ae].inputSource}}const ce=Symbol("@@webxr-polyfill/XRSessionEvent");class de extends Event{constructor(e,t){super(e,t),this[ce]={session:t.session},Object.setPrototypeOf(this,de.prototype)}get session(){return this[ce].session}}const ue=Symbol("@@webxr-polyfill/XRInputSourcesChangeEvent");class pe extends Event{constructor(e,t){super(e,t),this[ue]={session:t.session,added:t.added,removed:t.removed},Object.setPrototypeOf(this,pe.prototype)}get session(){return this[ue].session}get added(){return this[ue].added}get removed(){return this[ue].removed}}const fe=Symbol("@@webxr-polyfill/XRSession");class me extends L{constructor(e){super(e)}get eye(){return this._specialType}_onPoseUpdate(e){this._inverseBaseMatrix=e.getBaseViewMatrix(this._specialType)}}class ge extends i{constructor(e,t,i){super();let r="inline"!=t,s=new le({inlineVerticalFieldOfView:r?null:.5*Math.PI});const n=r?[new me("left"),new me("right")]:[new me("none")];Object.freeze(n),this[fe]={device:e,mode:t,immersive:r,ended:!1,suspended:!1,frameCallbacks:[],currentFrameCallbacks:null,frameHandle:0,deviceFrameHandle:null,id:i,activeRenderState:s,pendingRenderState:null,viewerSpace:new Q("viewer"),get viewSpaces(){return e.getViewSpaces(t)||n},currentInputSources:[]},this[fe].onDeviceFrame=(()=>{if(this[fe].ended||this[fe].suspended)return;if(this[fe].deviceFrameHandle=null,this[fe].startDeviceFrameLoop(),null!==this[fe].pendingRenderState&&(this[fe].activeRenderState=new le(this[fe].pendingRenderState),this[fe].pendingRenderState=null,this[fe].activeRenderState.baseLayer&&this[fe].device.onBaseLayerSet(this[fe].id,this[fe].activeRenderState.baseLayer)),null===this[fe].activeRenderState.baseLayer)return;const t=new ne(e,this,this[fe].id),i=this[fe].currentFrameCallbacks=this[fe].frameCallbacks;this[fe].frameCallbacks=[],t[te].active=!0,t[te].animationFrame=!0,this[fe].device.onFrameStart(this[fe].id,this[fe].activeRenderState),this._checkInputSourcesChange();const r=X();for(let e=0;e{null===this[fe].deviceFrameHandle&&(this[fe].deviceFrameHandle=this[fe].device.requestAnimationFrame(this[fe].onDeviceFrame))}),this[fe].stopDeviceFrameLoop=(()=>{const e=this[fe].deviceFrameHandle;null!==e&&(this[fe].device.cancelAnimationFrame(e),this[fe].deviceFrameHandle=null)}),this[fe].onPresentationEnd=(t=>{if(t!==this[fe].id)return this[fe].suspended=!1,this[fe].startDeviceFrameLoop(),void this.dispatchEvent("focus",{session:this});this[fe].ended=!0,this[fe].stopDeviceFrameLoop(),e.removeEventListener("@@webxr-polyfill/vr-present-end",this[fe].onPresentationEnd),e.removeEventListener("@@webxr-polyfill/vr-present-start",this[fe].onPresentationStart),e.removeEventListener("@@webxr-polyfill/input-select-start",this[fe].onSelectStart),e.removeEventListener("@@webxr-polyfill/input-select-end",this[fe].onSelectEnd),this.dispatchEvent("end",new de("end",{session:this}))}),e.addEventListener("@@webxr-polyfill/vr-present-end",this[fe].onPresentationEnd),this[fe].onPresentationStart=(e=>{e!==this[fe].id&&(this[fe].suspended=!0,this[fe].stopDeviceFrameLoop(),this.dispatchEvent("blur",{session:this}))}),e.addEventListener("@@webxr-polyfill/vr-present-start",this[fe].onPresentationStart),this[fe].onSelectStart=(e=>{e.sessionId===this[fe].id&&this[fe].dispatchInputSourceEvent("selectstart",e.inputSource)}),e.addEventListener("@@webxr-polyfill/input-select-start",this[fe].onSelectStart),this[fe].onSelectEnd=(e=>{e.sessionId===this[fe].id&&(this[fe].dispatchInputSourceEvent("select",e.inputSource),this[fe].dispatchInputSourceEvent("selectend",e.inputSource))}),e.addEventListener("@@webxr-polyfill/input-select-end",this[fe].onSelectEnd),this[fe].onSqueezeStart=(e=>{e.sessionId===this[fe].id&&this[fe].dispatchInputSourceEvent("squeezestart",e.inputSource)}),e.addEventListener("@@webxr-polyfill/input-squeeze-start",this[fe].onSqueezeStart),this[fe].onSqueezeEnd=(e=>{e.sessionId===this[fe].id&&(this[fe].dispatchInputSourceEvent("squeezeend",e.inputSource),this[fe].dispatchInputSourceEvent("squeeze",e.inputSource))}),e.addEventListener("@@webxr-polyfill/input-squeeze-end",this[fe].onSqueezeEnd),this[fe].dispatchInputSourceEvent=((t,i)=>{const r=new ne(e,this,this[fe].id),s=new he(t,{frame:r,inputSource:i});r[te].active=!0,this.dispatchEvent(t,s),r[te].active=!1}),this[fe].startDeviceFrameLoop(),this.onblur=void 0,this.onfocus=void 0,this.onresetpose=void 0,this.onend=void 0,this.onselect=void 0,this.onselectstart=void 0,this.onselectend=void 0}get renderState(){return this[fe].activeRenderState}get environmentBlendMode(){return this[fe].device.environmentBlendMode||"opaque"}async requestReferenceSpace(e){if(this[fe].ended)return;if(!G.includes(e))throw new TypeError(`XRReferenceSpaceType must be one of ${G}`);if(!this[fe].device.doesSessionSupportReferenceSpace(this[fe].id,e))throw new DOMException(`The ${e} reference space is not supported by this session.`,"NotSupportedError");if("viewer"===e)return this[fe].viewerSpace;let t=await this[fe].device.requestFrameOfReferenceTransform(e);if("bounded-floor"===e){if(!t)throw new DOMException(`${e} XRReferenceSpace not supported by this device.`,"NotSupportedError");if(!this[fe].device.requestStageBounds())throw new DOMException(`${e} XRReferenceSpace not supported by this device.`,"NotSupportedError");throw new DOMException(`The WebXR polyfill does not support the ${e} reference space yet.`,"NotSupportedError")}return new Q(e,t)}requestAnimationFrame(e){if(this[fe].ended)return;const t=++this[fe].frameHandle;return this[fe].frameCallbacks.push({handle:t,callback:e,cancelled:!1}),t}cancelAnimationFrame(e){let t=this[fe].frameCallbacks,i=t.findIndex(t=>t&&t.handle===e);i>-1&&(t[i].cancelled=!0,t.splice(i,1)),(t=this[fe].currentFrameCallbacks)&&(i=t.findIndex(t=>t&&t.handle===e))>-1&&(t[i].cancelled=!0)}get inputSources(){return this[fe].device.getInputSources()}async end(){if(!this[fe].ended)return this[fe].immersive&&(this[fe].ended=!0,this[fe].device.removeEventListener("@@webxr-polyfill/vr-present-start",this[fe].onPresentationStart),this[fe].device.removeEventListener("@@webxr-polyfill/vr-present-end",this[fe].onPresentationEnd),this[fe].device.removeEventListener("@@webxr-polyfill/input-select-start",this[fe].onSelectStart),this[fe].device.removeEventListener("@@webxr-polyfill/input-select-end",this[fe].onSelectEnd),this.dispatchEvent("end",new de("end",{session:this}))),this[fe].stopDeviceFrameLoop(),this[fe].device.endSession(this[fe].id)}updateRenderState(e){if(this[fe].ended){throw new Error("Can't call updateRenderState on an XRSession that has already ended.")}if(e.baseLayer&&e.baseLayer._session!==this){throw new Error("Called updateRenderState with a base layer that was created by a different session.")}if(null!==e.inlineVerticalFieldOfView&&void 0!==e.inlineVerticalFieldOfView){if(this[fe].immersive){throw new Error("inlineVerticalFieldOfView must not be set for an XRRenderState passed to updateRenderState for an immersive session.")}e.inlineVerticalFieldOfView=Math.min(3.13,Math.max(.01,e.inlineVerticalFieldOfView))}if(null===this[fe].pendingRenderState){const e=this[fe].activeRenderState;this[fe].pendingRenderState={depthNear:e.depthNear,depthFar:e.depthFar,inlineVerticalFieldOfView:e.inlineVerticalFieldOfView,baseLayer:e.baseLayer}}Object.assign(this[fe].pendingRenderState,e)}_checkInputSourcesChange(){const e=[],t=[],i=this.inputSources,r=this[fe].currentInputSources;for(const t of i)r.includes(t)||e.push(t);for(const e of r)i.includes(e)||t.push(e);(e.length>0||t.length>0)&&this.dispatchEvent("inputsourceschange",new pe("inputsourceschange",{session:this,added:e,removed:t})),this[fe].currentInputSources.length=0;for(const e of i)this[fe].currentInputSources.push(e)}}const ve=Symbol("@@webxr-polyfill/XRInputSource");class we{constructor(e){this[ve]={impl:e,gripSpace:new L("grip",this),targetRaySpace:new L("target-ray",this)}}get handedness(){return this[ve].impl.handedness}get targetRayMode(){return this[ve].impl.targetRayMode}get gripSpace(){let e=this[ve].impl.targetRayMode;return"gaze"===e||"screen"===e?null:this[ve].gripSpace}get targetRaySpace(){return this[ve].targetRaySpace}get profiles(){return this[ve].impl.profiles}get gamepad(){return this[ve].impl.gamepad}}const ye=Symbol("@@webxr-polyfill/polyfilled-xr-compatible"),be=Symbol("@@webxr-polyfill/xr-compatible"),Ee=Symbol("@@webxr-polyfill/XRWebGLLayer"),Se=Object.freeze({antialias:!0,depth:!0,stencil:!1,alpha:!0,multiview:!1,ignoreDepthValues:!1,framebufferScaleFactor:1});const Me=Symbol("@@webxr-polyfill/XRReferenceSpaceEvent");class xe extends Event{constructor(e,t){super(e,t),this[Me]={referenceSpace:t.referenceSpace,transform:t.transform||null},Object.setPrototypeOf(this,xe.prototype)}get referenceSpace(){return this[Me].referenceSpace}get transform(){return this[Me].transform}}var _e={XRSystem:class extends i{constructor(e){super(),this[k]={device:null,devicePromise:e,immersiveSession:null,inlineSessions:new Set},e.then(e=>{this[k].device=e})}async isSessionSupported(e){return this[k].device||await this[k].devicePromise,"inline"!=e?Promise.resolve(this[k].device.isSessionSupported(e)):Promise.resolve(!0)}async requestSession(e,t){if(!this[k].device){if("inline"!=e)throw new Error(U);await this[k].devicePromise}if(!z.includes(e))throw new TypeError(`The provided value '${e}' is not a valid enum value of type XRSessionMode`);const i=V[e],r=i.requiredFeatures.concat(t&&t.requiredFeatures?t.requiredFeatures:[]),s=i.optionalFeatures.concat(t&&t.optionalFeatures?t.optionalFeatures:[]),n=new Set;let a=!1;for(let e of r)this[k].device.isFeatureSupported(e)?n.add(e):(console.error(`The required feature '${e}' is not supported`),a=!0);if(a)throw new DOMException("Session does not support some required features","NotSupportedError");for(let e of s)this[k].device.isFeatureSupported(e)?n.add(e):console.log(`The optional feature '${e}' is not supported`);const o=await this[k].device.requestSession(e,n),l=new XRSession(this[k].device,e,o);"inline"==e?this[k].inlineSessions.add(l):this[k].immersiveSession=l;const A=()=>{"inline"==e?this[k].inlineSessions.delete(l):this[k].immersiveSession=null,l.removeEventListener("end",A)};return l.addEventListener("end",A),l}},XRSession:ge,XRSessionEvent:de,XRFrame:ne,XRView:ee,XRViewport:J,XRViewerPose:Y,XRWebGLLayer:class{constructor(e,t,i={}){const r=Object.assign({},Se,i);if(!(e instanceof ge))throw new Error("session must be a XRSession");if(e.ended)throw new Error("InvalidStateError");if(t[ye]&&!0!==t[be])throw new Error("InvalidStateError");this[Ee]={context:t,config:r,session:e}}get context(){return this[Ee].context}get antialias(){return this[Ee].config.antialias}get ignoreDepthValues(){return!0}get framebuffer(){return null}get framebufferWidth(){return this[Ee].context.drawingBufferWidth}get framebufferHeight(){return this[Ee].context.drawingBufferHeight}get _session(){return this[Ee].session}getViewport(e){return e._getViewport(this)}static getNativeFramebufferScaleFactor(e){if(!e)throw new TypeError("getNativeFramebufferScaleFactor must be passed a session.");return e[fe].ended?0:1}},XRSpace:L,XRReferenceSpace:Q,XRReferenceSpaceEvent:xe,XRInputSource:we,XRInputSourceEvent:he,XRInputSourcesChangeEvent:pe,XRRenderState:le,XRRigidTransform:D,XRPose:j};const Fe=e=>"function"!=typeof e.prototype.makeXRCompatible&&(e.prototype.makeXRCompatible=function(){return this[be]=!0,Promise.resolve()},!0),Re=e=>{const t=e.prototype.getContext;e.prototype.getContext=function(e,i){const r=t.call(this,e,i);return r&&(r[ye]=!0,i&&"xrCompatible"in i&&(r[be]=i.xrCompatible)),r}},Te=e=>!(!e.ImageBitmapRenderingContext||!e.createImageBitmap);var Pe;const Be=e=>{e.style.display="block",e.style.position="absolute",e.style.width=e.style.height="1px",e.style.top=e.style.left="0px"};var Ce="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var De,Ie,Le=(function(e,t){e.exports=function(){var e,t,i,r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=function(){function e(e,t){for(var i=0;ie.TEXTURE31){console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit"),r.push(null,null);break}s||(s=e.getParameter(e.ACTIVE_TEXTURE)),e.activeTexture(o),r.push(e.getParameter(a),null);break;case e.ACTIVE_TEXTURE:s=e.getParameter(e.ACTIVE_TEXTURE),r.push(null);break;default:r.push(e.getParameter(a))}}i(e);for(var n=0;ne.TEXTURE31)break;e.activeTexture(o),e.bindTexture(e.TEXTURE_2D,l);break;case e.TEXTURE_BINDING_CUBE_MAP:var o=t[++n];if(oe.TEXTURE31)break;e.activeTexture(o),e.bindTexture(e.TEXTURE_CUBE_MAP,l);break;case e.VIEWPORT:e.viewport(l[0],l[1],l[2],l[3]);break;case e.BLEND:case e.CULL_FACE:case e.DEPTH_TEST:case e.SCISSOR_TEST:case e.STENCIL_TEST:l?e.enable(a):e.disable(a);break;default:console.log("No GL restore behavior for 0x"+a.toString(16))}s&&e.activeTexture(s)}}else i(e)},T=["attribute vec2 position;","attribute vec3 texCoord;","varying vec2 vTexCoord;","uniform vec4 viewportOffsetScale[2];","void main() {"," vec4 viewport = viewportOffsetScale[int(texCoord.z)];"," vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;"," gl_Position = vec4( position, 1.0, 1.0 );","}"].join("\n"),P=["precision mediump float;","uniform sampler2D diffuse;","varying vec2 vTexCoord;","void main() {"," gl_FragColor = texture2D(diffuse, vTexCoord);","}"].join("\n");function B(e,t,i,r){this.gl=e,this.cardboardUI=t,this.bufferScale=i,this.dirtySubmitFrameBindings=r,this.ctxAttribs=e.getContextAttributes(),this.instanceExt=e.getExtension("ANGLE_instanced_arrays"),this.meshWidth=20,this.meshHeight=20,this.bufferWidth=e.drawingBufferWidth,this.bufferHeight=e.drawingBufferHeight,this.realBindFramebuffer=e.bindFramebuffer,this.realEnable=e.enable,this.realDisable=e.disable,this.realColorMask=e.colorMask,this.realClearColor=e.clearColor,this.realViewport=e.viewport,o()||(this.realCanvasWidth=Object.getOwnPropertyDescriptor(e.canvas.__proto__,"width"),this.realCanvasHeight=Object.getOwnPropertyDescriptor(e.canvas.__proto__,"height")),this.isPatched=!1,this.lastBoundFramebuffer=null,this.cullFace=!1,this.depthTest=!1,this.blend=!1,this.scissorTest=!1,this.stencilTest=!1,this.viewport=[0,0,0,0],this.colorMask=[!0,!0,!0,!0],this.clearColor=[0,0,0,0],this.attribs={position:0,texCoord:1},this.program=w(e,T,P,this.attribs),this.uniforms=y(e,this.program),this.viewportOffsetScale=new Float32Array(8),this.setTextureBounds(),this.vertexBuffer=e.createBuffer(),this.indexBuffer=e.createBuffer(),this.indexCount=0,this.renderTarget=e.createTexture(),this.framebuffer=e.createFramebuffer(),this.depthStencilBuffer=null,this.depthBuffer=null,this.stencilBuffer=null,this.ctxAttribs.depth&&this.ctxAttribs.stencil?this.depthStencilBuffer=e.createRenderbuffer():this.ctxAttribs.depth?this.depthBuffer=e.createRenderbuffer():this.ctxAttribs.stencil&&(this.stencilBuffer=e.createRenderbuffer()),this.patch(),this.onResize()}B.prototype.destroy=function(){var e=this.gl;this.unpatch(),e.deleteProgram(this.program),e.deleteBuffer(this.vertexBuffer),e.deleteBuffer(this.indexBuffer),e.deleteTexture(this.renderTarget),e.deleteFramebuffer(this.framebuffer),this.depthStencilBuffer&&e.deleteRenderbuffer(this.depthStencilBuffer),this.depthBuffer&&e.deleteRenderbuffer(this.depthBuffer),this.stencilBuffer&&e.deleteRenderbuffer(this.stencilBuffer),this.cardboardUI&&this.cardboardUI.destroy()},B.prototype.onResize=function(){var e=this.gl,t=this,i=[e.RENDERBUFFER_BINDING,e.TEXTURE_BINDING_2D,e.TEXTURE0];R(e,i,function(e){t.realBindFramebuffer.call(e,e.FRAMEBUFFER,null),t.scissorTest&&t.realDisable.call(e,e.SCISSOR_TEST),t.realColorMask.call(e,!0,!0,!0,!0),t.realViewport.call(e,0,0,e.drawingBufferWidth,e.drawingBufferHeight),t.realClearColor.call(e,0,0,0,1),e.clear(e.COLOR_BUFFER_BIT),t.realBindFramebuffer.call(e,e.FRAMEBUFFER,t.framebuffer),e.bindTexture(e.TEXTURE_2D,t.renderTarget),e.texImage2D(e.TEXTURE_2D,0,t.ctxAttribs.alpha?e.RGBA:e.RGB,t.bufferWidth,t.bufferHeight,0,t.ctxAttribs.alpha?e.RGBA:e.RGB,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.renderTarget,0),t.ctxAttribs.depth&&t.ctxAttribs.stencil?(e.bindRenderbuffer(e.RENDERBUFFER,t.depthStencilBuffer),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,t.bufferWidth,t.bufferHeight),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t.depthStencilBuffer)):t.ctxAttribs.depth?(e.bindRenderbuffer(e.RENDERBUFFER,t.depthBuffer),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,t.bufferWidth,t.bufferHeight),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t.depthBuffer)):t.ctxAttribs.stencil&&(e.bindRenderbuffer(e.RENDERBUFFER,t.stencilBuffer),e.renderbufferStorage(e.RENDERBUFFER,e.STENCIL_INDEX8,t.bufferWidth,t.bufferHeight),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.STENCIL_ATTACHMENT,e.RENDERBUFFER,t.stencilBuffer)),!e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE&&console.error("Framebuffer incomplete!"),t.realBindFramebuffer.call(e,e.FRAMEBUFFER,t.lastBoundFramebuffer),t.scissorTest&&t.realEnable.call(e,e.SCISSOR_TEST),t.realColorMask.apply(e,t.colorMask),t.realViewport.apply(e,t.viewport),t.realClearColor.apply(e,t.clearColor)}),this.cardboardUI&&this.cardboardUI.onResize()},B.prototype.patch=function(){if(!this.isPatched){var e=this,t=this.gl.canvas,i=this.gl;o()||(t.width=m()*this.bufferScale,t.height=g()*this.bufferScale,Object.defineProperty(t,"width",{configurable:!0,enumerable:!0,get:function(){return e.bufferWidth},set:function(i){e.bufferWidth=i,e.realCanvasWidth.set.call(t,i),e.onResize()}}),Object.defineProperty(t,"height",{configurable:!0,enumerable:!0,get:function(){return e.bufferHeight},set:function(i){e.bufferHeight=i,e.realCanvasHeight.set.call(t,i),e.onResize()}})),this.lastBoundFramebuffer=i.getParameter(i.FRAMEBUFFER_BINDING),null==this.lastBoundFramebuffer&&(this.lastBoundFramebuffer=this.framebuffer,this.gl.bindFramebuffer(i.FRAMEBUFFER,this.framebuffer)),this.gl.bindFramebuffer=function(t,r){e.lastBoundFramebuffer=r||e.framebuffer,e.realBindFramebuffer.call(i,t,e.lastBoundFramebuffer)},this.cullFace=i.getParameter(i.CULL_FACE),this.depthTest=i.getParameter(i.DEPTH_TEST),this.blend=i.getParameter(i.BLEND),this.scissorTest=i.getParameter(i.SCISSOR_TEST),this.stencilTest=i.getParameter(i.STENCIL_TEST),i.enable=function(t){switch(t){case i.CULL_FACE:e.cullFace=!0;break;case i.DEPTH_TEST:e.depthTest=!0;break;case i.BLEND:e.blend=!0;break;case i.SCISSOR_TEST:e.scissorTest=!0;break;case i.STENCIL_TEST:e.stencilTest=!0}e.realEnable.call(i,t)},i.disable=function(t){switch(t){case i.CULL_FACE:e.cullFace=!1;break;case i.DEPTH_TEST:e.depthTest=!1;break;case i.BLEND:e.blend=!1;break;case i.SCISSOR_TEST:e.scissorTest=!1;break;case i.STENCIL_TEST:e.stencilTest=!1}e.realDisable.call(i,t)},this.colorMask=i.getParameter(i.COLOR_WRITEMASK),i.colorMask=function(t,r,s,n){e.colorMask[0]=t,e.colorMask[1]=r,e.colorMask[2]=s,e.colorMask[3]=n,e.realColorMask.call(i,t,r,s,n)},this.clearColor=i.getParameter(i.COLOR_CLEAR_VALUE),i.clearColor=function(t,r,s,n){e.clearColor[0]=t,e.clearColor[1]=r,e.clearColor[2]=s,e.clearColor[3]=n,e.realClearColor.call(i,t,r,s,n)},this.viewport=i.getParameter(i.VIEWPORT),i.viewport=function(t,r,s,n){e.viewport[0]=t,e.viewport[1]=r,e.viewport[2]=s,e.viewport[3]=n,e.realViewport.call(i,t,r,s,n)},this.isPatched=!0,S(t)}},B.prototype.unpatch=function(){if(this.isPatched){var e=this.gl,t=this.gl.canvas;o()||(Object.defineProperty(t,"width",this.realCanvasWidth),Object.defineProperty(t,"height",this.realCanvasHeight)),t.width=this.bufferWidth,t.height=this.bufferHeight,e.bindFramebuffer=this.realBindFramebuffer,e.enable=this.realEnable,e.disable=this.realDisable,e.colorMask=this.realColorMask,e.clearColor=this.realClearColor,e.viewport=this.realViewport,this.lastBoundFramebuffer==this.framebuffer&&e.bindFramebuffer(e.FRAMEBUFFER,null),this.isPatched=!1,setTimeout(function(){S(t)},1)}},B.prototype.setTextureBounds=function(e,t){e||(e=[0,0,.5,1]),t||(t=[.5,0,.5,1]),this.viewportOffsetScale[0]=e[0],this.viewportOffsetScale[1]=e[1],this.viewportOffsetScale[2]=e[2],this.viewportOffsetScale[3]=e[3],this.viewportOffsetScale[4]=t[0],this.viewportOffsetScale[5]=t[1],this.viewportOffsetScale[6]=t[2],this.viewportOffsetScale[7]=t[3]},B.prototype.submitFrame=function(){var e=this.gl,t=this,i=[];if(this.dirtySubmitFrameBindings||i.push(e.CURRENT_PROGRAM,e.ARRAY_BUFFER_BINDING,e.ELEMENT_ARRAY_BUFFER_BINDING,e.TEXTURE_BINDING_2D,e.TEXTURE0),R(e,i,function(e){t.realBindFramebuffer.call(e,e.FRAMEBUFFER,null);var i=0,r=0;t.instanceExt&&(i=e.getVertexAttrib(t.attribs.position,t.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE),r=e.getVertexAttrib(t.attribs.texCoord,t.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE)),t.cullFace&&t.realDisable.call(e,e.CULL_FACE),t.depthTest&&t.realDisable.call(e,e.DEPTH_TEST),t.blend&&t.realDisable.call(e,e.BLEND),t.scissorTest&&t.realDisable.call(e,e.SCISSOR_TEST),t.stencilTest&&t.realDisable.call(e,e.STENCIL_TEST),t.realColorMask.call(e,!0,!0,!0,!0),t.realViewport.call(e,0,0,e.drawingBufferWidth,e.drawingBufferHeight),(t.ctxAttribs.alpha||o())&&(t.realClearColor.call(e,0,0,0,1),e.clear(e.COLOR_BUFFER_BIT)),e.useProgram(t.program),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.indexBuffer),e.bindBuffer(e.ARRAY_BUFFER,t.vertexBuffer),e.enableVertexAttribArray(t.attribs.position),e.enableVertexAttribArray(t.attribs.texCoord),e.vertexAttribPointer(t.attribs.position,2,e.FLOAT,!1,20,0),e.vertexAttribPointer(t.attribs.texCoord,3,e.FLOAT,!1,20,8),t.instanceExt&&(0!=i&&t.instanceExt.vertexAttribDivisorANGLE(t.attribs.position,0),0!=r&&t.instanceExt.vertexAttribDivisorANGLE(t.attribs.texCoord,0)),e.activeTexture(e.TEXTURE0),e.uniform1i(t.uniforms.diffuse,0),e.bindTexture(e.TEXTURE_2D,t.renderTarget),e.uniform4fv(t.uniforms.viewportOffsetScale,t.viewportOffsetScale),e.drawElements(e.TRIANGLES,t.indexCount,e.UNSIGNED_SHORT,0),t.cardboardUI&&t.cardboardUI.renderNoState(),t.realBindFramebuffer.call(t.gl,e.FRAMEBUFFER,t.framebuffer),t.ctxAttribs.preserveDrawingBuffer||(t.realClearColor.call(e,0,0,0,0),e.clear(e.COLOR_BUFFER_BIT)),t.dirtySubmitFrameBindings||t.realBindFramebuffer.call(e,e.FRAMEBUFFER,t.lastBoundFramebuffer),t.cullFace&&t.realEnable.call(e,e.CULL_FACE),t.depthTest&&t.realEnable.call(e,e.DEPTH_TEST),t.blend&&t.realEnable.call(e,e.BLEND),t.scissorTest&&t.realEnable.call(e,e.SCISSOR_TEST),t.stencilTest&&t.realEnable.call(e,e.STENCIL_TEST),t.realColorMask.apply(e,t.colorMask),t.realViewport.apply(e,t.viewport),!t.ctxAttribs.alpha&&t.ctxAttribs.preserveDrawingBuffer||t.realClearColor.apply(e,t.clearColor),t.instanceExt&&(0!=i&&t.instanceExt.vertexAttribDivisorANGLE(t.attribs.position,i),0!=r&&t.instanceExt.vertexAttribDivisorANGLE(t.attribs.texCoord,r))}),o()){var r=e.canvas;r.width==t.bufferWidth&&r.height==t.bufferHeight||(t.bufferWidth=r.width,t.bufferHeight=r.height,t.onResize())}},B.prototype.updateDeviceInfo=function(e){var t=this.gl,i=this,r=[t.ARRAY_BUFFER_BINDING,t.ELEMENT_ARRAY_BUFFER_BINDING];R(t,r,function(t){var r=i.computeMeshVertices_(i.meshWidth,i.meshHeight,e);if(t.bindBuffer(t.ARRAY_BUFFER,i.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,r,t.STATIC_DRAW),!i.indexCount){var s=i.computeMeshIndices_(i.meshWidth,i.meshHeight);t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,i.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,s,t.STATIC_DRAW),i.indexCount=s.length}})},B.prototype.computeMeshVertices_=function(e,t,i){for(var r=new Float32Array(2*e*t*5),s=i.getLeftEyeVisibleTanAngles(),n=i.getLeftEyeNoLensTanAngles(),o=i.getLeftEyeVisibleScreenRect(n),l=0,A=0;A<2;A++){for(var h=0;hs-42&&r.clientXi.clientHeight-42?e(r):r.clientX<42&&r.clientY<42&&t(r)},i.addEventListener("click",this.listener,!1)},O.prototype.onResize=function(){var e=this.gl,t=this,i=[e.ARRAY_BUFFER_BINDING];R(e,i,function(e){var i=[],r=e.drawingBufferWidth/2,s=Math.max(screen.width,screen.height)*window.devicePixelRatio,n=e.drawingBufferWidth/s,a=n*window.devicePixelRatio,o=4*a/2,l=42*a,A=28*a/2,h=14*a;function c(e,t){var s=(90-e)*I,n=Math.cos(s),a=Math.sin(s);i.push(L*n*A+r,L*a*A+A),i.push(t*n*A+r,t*a*A+A)}i.push(r-o,l),i.push(r-o,e.drawingBufferHeight),i.push(r+o,l),i.push(r+o,e.drawingBufferHeight),t.gearOffset=i.length/2;for(var d=0;d<=6;d++){var u=60*d;c(u,1),c(u+12,1),c(u+20,.75),c(u+40,.75),c(u+48,1)}function p(t,r){i.push(h+t,e.drawingBufferHeight-h-r)}t.gearVertexCount=i.length/2-t.gearOffset,t.arrowOffset=i.length/2;var f=o/Math.sin(45*I);p(0,A),p(A,0),p(A+f,f),p(f,A+f),p(f,A-f),p(0,A),p(A,2*A),p(A+f,2*A-f),p(f,A-f),p(0,A),p(f,A-o),p(28*a,A-o),p(f,A+o),p(28*a,A+o),t.arrowVertexCount=i.length/2-t.arrowOffset,e.bindBuffer(e.ARRAY_BUFFER,t.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array(i),e.STATIC_DRAW)})},O.prototype.render=function(){var e=this.gl,t=this,i=[e.CULL_FACE,e.DEPTH_TEST,e.BLEND,e.SCISSOR_TEST,e.STENCIL_TEST,e.COLOR_WRITEMASK,e.VIEWPORT,e.CURRENT_PROGRAM,e.ARRAY_BUFFER_BINDING];R(e,i,function(e){e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.BLEND),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.colorMask(!0,!0,!0,!0),e.viewport(0,0,e.drawingBufferWidth,e.drawingBufferHeight),t.renderNoState()})},O.prototype.renderNoState=function(){var e,t,i,r,s,n,a,o,l,A,h=this.gl;h.useProgram(this.program),h.bindBuffer(h.ARRAY_BUFFER,this.vertexBuffer),h.enableVertexAttribArray(this.attribs.position),h.vertexAttribPointer(this.attribs.position,2,h.FLOAT,!1,8,0),h.uniform4f(this.uniforms.color,1,1,1,1),e=this.projMat,t=0,i=h.drawingBufferWidth,r=0,s=h.drawingBufferHeight,o=1/(t-i),l=1/(r-s),A=1/((n=.1)-(a=1024)),e[0]=-2*o,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*l,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=2*A,e[11]=0,e[12]=(t+i)*o,e[13]=(s+r)*l,e[14]=(a+n)*A,e[15]=1,h.uniformMatrix4fv(this.uniforms.projectionMat,!1,this.projMat),h.drawArrays(h.TRIANGLE_STRIP,0,4),h.drawArrays(h.TRIANGLE_STRIP,this.gearOffset,this.gearVertexCount),h.drawArrays(h.TRIANGLE_STRIP,this.arrowOffset,this.arrowVertexCount)},N.prototype.distortInverse=function(e){for(var t=0,i=1,r=e-this.distort(t);Math.abs(i-t)>1e-4;){var s=e-this.distort(i),n=i-s*((i-t)/(s-r));t=i,i=n,r=s}return i},N.prototype.distort=function(e){for(var t=e*e,i=0,r=0;r=1)return this.w=n,this.x=i,this.y=r,this.z=s,this;var o=Math.acos(a),l=Math.sqrt(1-a*a);if(Math.abs(l)<.001)return this.w=.5*(n+this.w),this.x=.5*(i+this.x),this.y=.5*(r+this.y),this.z=.5*(s+this.z),this;var A=Math.sin((1-t)*o)/l,h=Math.sin(t*o)/l;return this.w=n*A+this.w*h,this.x=i*A+this.x*h,this.y=r*A+this.y*h,this.z=s*A+this.z*h,this},setFromUnitVectors:function(e,t){return void 0===z&&(z=new k),(V=e.dot(t)+1)<1e-6?(V=0,Math.abs(e.x)>Math.abs(e.z)?z.set(-e.y,e.x,0):z.set(0,-e.z,e.y)):z.crossVectors(e,t),this.x=z.x,this.y=z.y,this.z=z.z,this.w=V,this.normalize(),this}};var X=new H({widthMeters:.11,heightMeters:.062,bevelMeters:.004}),W=new H({widthMeters:.1038,heightMeters:.0584,bevelMeters:.004}),j={CardboardV1:new Y({id:"CardboardV1",label:"Cardboard I/O 2014",fov:40,interLensDistance:.06,baselineLensDistance:.035,screenLensDistance:.042,distortionCoefficients:[.441,.156],inverseCoefficients:[-.4410035,.42756155,-.4804439,.5460139,-.58821183,.5733938,-.48303202,.33299083,-.17573841,.0651772,-.01488963,.001559834]}),CardboardV2:new Y({id:"CardboardV2",label:"Cardboard I/O 2015",fov:60,interLensDistance:.064,baselineLensDistance:.035,screenLensDistance:.039,distortionCoefficients:[.34,.55],inverseCoefficients:[-.33836704,-.18162185,.862655,-1.2462051,1.0560602,-.58208317,.21609078,-.05444823,.009177956,-.0009904169,6183535e-11,-16981803e-13]})};function q(e,t){this.viewer=j.CardboardV2,this.updateDeviceParams(e),this.distortion=new N(this.viewer.distortionCoefficients);for(var i=0;i=200&&i.status<=299?(r.dpdb=JSON.parse(i.response),r.recalculateDeviceParams_()):console.error("Error loading online DPDB!")}),i.send()}}function K(e){this.xdpi=e.xdpi,this.ydpi=e.ydpi,this.bevelMm=e.bevelMm}function $(e,t){this.set(e,t)}function ee(e,t){this.kFilter=e,this.isDebug=t,this.currentAccelMeasurement=new $,this.currentGyroMeasurement=new $,this.previousGyroMeasurement=new $,o()?this.filterQ=new U(-1,0,0,1):this.filterQ=new U(1,0,0,1),this.previousFilterQ=new U,this.previousFilterQ.copy(this.filterQ),this.accelQ=new U,this.isOrientationInitialized=!1,this.estimatedGravity=new k,this.measuredGravity=new k,this.gyroIntegralQ=new U}function te(e,t){this.predictionTimeS=e,this.isDebug=t,this.previousQ=new U,this.previousTimestampS=null,this.deltaQ=new U,this.outQ=new U}function ie(e,t,i,r){this.yawOnly=i,this.accelerometer=new k,this.gyroscope=new k,this.filter=new ee(e,r),this.posePredictor=new te(t,r),this.isFirefoxAndroid=h(),this.isIOS=o();var s=c();this.isDeviceMotionInRadians=!this.isIOS&&s&&s<66,this.isWithoutDeviceMotion=u()||d(),this.filterToWorldQ=new U,o()?this.filterToWorldQ.setFromAxisAngle(new k(1,0,0),Math.PI/2):this.filterToWorldQ.setFromAxisAngle(new k(1,0,0),-Math.PI/2),this.inverseWorldToScreenQ=new U,this.worldToScreenQ=new U,this.originalPoseAdjustQ=new U,this.originalPoseAdjustQ.setFromAxisAngle(new k(0,0,1),-window.orientation*Math.PI/180),this.setScreenTransform_(),f()&&this.filterToWorldQ.multiply(this.inverseWorldToScreenQ),this.resetQ=new U,this.orientationOut_=new Float32Array(4),this.start()}J.prototype.getDeviceParams=function(){return this.deviceParams},J.prototype.recalculateDeviceParams_=function(){var e=this.calcDeviceParams_();e?(this.deviceParams=e,this.onDeviceParamsUpdated&&this.onDeviceParamsUpdated(this.deviceParams)):console.error("Failed to recalculate device parameters.")},J.prototype.calcDeviceParams_=function(){var e=this.dpdb;if(!e)return console.error("DPDB not available."),null;if(1!=e.format)return console.error("DPDB has unexpected format version."),null;if(!e.devices||!e.devices.length)return console.error("DPDB does not have a devices section."),null;var t=navigator.userAgent||navigator.vendor||window.opera,i=m(),r=g();if(!e.devices)return console.error("DPDB has no devices section."),null;for(var s=0;s1)&&this.run_(),this.previousGyroMeasurement.copy(this.currentGyroMeasurement)},ee.prototype.run_=function(){if(!this.isOrientationInitialized)return this.accelQ=this.accelToQuaternion_(this.currentAccelMeasurement.sample),this.previousFilterQ.copy(this.accelQ),void(this.isOrientationInitialized=!0);var e=this.currentGyroMeasurement.timestampS-this.previousGyroMeasurement.timestampS,t=this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample,e);this.gyroIntegralQ.multiply(t),this.filterQ.copy(this.previousFilterQ),this.filterQ.multiply(t);var i=new U;i.copy(this.filterQ),i.inverse(),this.estimatedGravity.set(0,0,-1),this.estimatedGravity.applyQuaternion(i),this.estimatedGravity.normalize(),this.measuredGravity.copy(this.currentAccelMeasurement.sample),this.measuredGravity.normalize();var r,s=new U;s.setFromUnitVectors(this.estimatedGravity,this.measuredGravity),s.inverse(),this.isDebug&&console.log("Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)",Q*((r=s).w>1?(console.warn("getQuaternionAngle: w > 1"),0):2*Math.acos(r.w)),this.estimatedGravity.x.toFixed(1),this.estimatedGravity.y.toFixed(1),this.estimatedGravity.z.toFixed(1),this.measuredGravity.x.toFixed(1),this.measuredGravity.y.toFixed(1),this.measuredGravity.z.toFixed(1));var n=new U;n.copy(this.filterQ),n.multiply(s),this.filterQ.slerp(n,1-this.kFilter),this.previousFilterQ.copy(this.filterQ)},ee.prototype.getOrientation=function(){return this.filterQ},ee.prototype.accelToQuaternion_=function(e){var t=new k;t.copy(e),t.normalize();var i=new U;return i.setFromUnitVectors(new k(0,0,-1),t),i.inverse(),i},ee.prototype.gyroToQuaternionDelta_=function(e,t){var i=new U,r=new k;return r.copy(e),r.normalize(),i.setFromAxisAngle(r,e.length()*t),i},te.prototype.getPrediction=function(e,t,i){if(!this.previousTimestampS)return this.previousQ.copy(e),this.previousTimestampS=i,e;var r=new k;r.copy(t),r.normalize();var s=t.length();if(s<20*G)return this.isDebug&&console.log("Moving slowly, at %s deg/s: no prediction",(Q*s).toFixed(1)),this.outQ.copy(e),this.previousQ.copy(e),this.outQ;var n=s*this.predictionTimeS;return this.deltaQ.setFromAxisAngle(r,n),this.outQ.copy(this.previousQ),this.outQ.multiply(this.deltaQ),this.previousQ.copy(e),this.previousTimestampS=i,this.outQ},ie.prototype.getPosition=function(){return null},ie.prototype.getOrientation=function(){var e=void 0;if(this.isWithoutDeviceMotion&&this._deviceOrientationQ){this.deviceOrientationFixQ=this.deviceOrientationFixQ||(r=(new U).setFromAxisAngle(new k(0,0,-1),0),s=new U,-90===window.orientation?s.setFromAxisAngle(new k(0,1,0),Math.PI/-2):s.setFromAxisAngle(new k(0,1,0),Math.PI/2),r.multiply(s)),this.deviceOrientationFilterToWorldQ=this.deviceOrientationFilterToWorldQ||((i=new U).setFromAxisAngle(new k(1,0,0),-Math.PI/2),i),e=this._deviceOrientationQ;var t=new U;return t.copy(e),t.multiply(this.deviceOrientationFilterToWorldQ),t.multiply(this.resetQ),t.multiply(this.worldToScreenQ),t.multiplyQuaternions(this.deviceOrientationFixQ,t),this.yawOnly&&(t.x=0,t.z=0,t.normalize()),this.orientationOut_[0]=t.x,this.orientationOut_[1]=t.y,this.orientationOut_[2]=t.z,this.orientationOut_[3]=t.w,this.orientationOut_}var i,r,s,n=this.filter.getOrientation();e=this.posePredictor.getPrediction(n,this.gyroscope,this.previousTimestampS);var t=new U;return t.copy(this.filterToWorldQ),t.multiply(this.resetQ),t.multiply(e),t.multiply(this.worldToScreenQ),this.yawOnly&&(t.x=0,t.z=0,t.normalize()),this.orientationOut_[0]=t.x,this.orientationOut_[1]=t.y,this.orientationOut_[2]=t.z,this.orientationOut_[3]=t.w,this.orientationOut_},ie.prototype.resetPose=function(){this.resetQ.copy(this.filter.getOrientation()),this.resetQ.x=0,this.resetQ.y=0,this.resetQ.z*=-1,this.resetQ.normalize(),f()&&this.resetQ.multiply(this.inverseWorldToScreenQ),this.resetQ.multiply(this.originalPoseAdjustQ)},ie.prototype.onDeviceOrientation_=function(e){this._deviceOrientationQ=this._deviceOrientationQ||new U;var t=e.alpha,i=e.beta,r=e.gamma;t=(t||0)*Math.PI/180,i=(i||0)*Math.PI/180,r=(r||0)*Math.PI/180,this._deviceOrientationQ.setFromEulerYXZ(i,t,-r)},ie.prototype.onDeviceMotion_=function(e){this.updateDeviceMotion_(e)},ie.prototype.updateDeviceMotion_=function(e){var t=e.accelerationIncludingGravity,i=e.rotationRate,r=e.timeStamp/1e3,s=r-this.previousTimestampS;return s<0?(_("fusion-pose-sensor:invalid:non-monotonic","Invalid timestamps detected: non-monotonic timestamp from devicemotion"),void(this.previousTimestampS=r)):s<=.001||s>1?(_("fusion-pose-sensor:invalid:outside-threshold","Invalid timestamps detected: Timestamp from devicemotion outside expected range."),void(this.previousTimestampS=r)):(this.accelerometer.set(-t.x,-t.y,-t.z),i&&(p()?this.gyroscope.set(-i.beta,i.alpha,i.gamma):this.gyroscope.set(i.alpha,i.beta,i.gamma),this.isDeviceMotionInRadians||this.gyroscope.multiplyScalar(Math.PI/180),this.filter.addGyroMeasurement(this.gyroscope,r)),this.filter.addAccelMeasurement(this.accelerometer,r),void(this.previousTimestampS=r))},ie.prototype.onOrientationChange_=function(e){this.setScreenTransform_()},ie.prototype.onMessage_=function(e){var t=e.data;if(t&&t.type){var i=t.type.toLowerCase();"devicemotion"===i&&this.updateDeviceMotion_(t.deviceMotionEvent)}},ie.prototype.setScreenTransform_=function(){switch(this.worldToScreenQ.set(0,0,0,1),window.orientation){case 0:break;case 90:this.worldToScreenQ.setFromAxisAngle(new k(0,0,1),-Math.PI/2);break;case-90:this.worldToScreenQ.setFromAxisAngle(new k(0,0,1),Math.PI/2)}this.inverseWorldToScreenQ.copy(this.worldToScreenQ),this.inverseWorldToScreenQ.inverse()},ie.prototype.start=function(){var e,t,i;this.onDeviceMotionCallback_=this.onDeviceMotion_.bind(this),this.onOrientationChangeCallback_=this.onOrientationChange_.bind(this),this.onMessageCallback_=this.onMessage_.bind(this),this.onDeviceOrientationCallback_=this.onDeviceOrientation_.bind(this),o()&&(e=window.self!==window.top,t=x(document.referrer),i=x(window.location.href),e&&t!==i)&&window.addEventListener("message",this.onMessageCallback_),window.addEventListener("orientationchange",this.onOrientationChangeCallback_),this.isWithoutDeviceMotion?window.addEventListener("deviceorientation",this.onDeviceOrientationCallback_):window.addEventListener("devicemotion",this.onDeviceMotionCallback_)},ie.prototype.stop=function(){window.removeEventListener("devicemotion",this.onDeviceMotionCallback_),window.removeEventListener("deviceorientation",this.onDeviceOrientationCallback_),window.removeEventListener("orientationchange",this.onOrientationChangeCallback_),window.removeEventListener("message",this.onMessageCallback_)};var re=new k(1,0,0),se=new k(0,0,1),ne=new U;ne.setFromAxisAngle(re,-Math.PI/2),ne.multiply((new U).setFromAxisAngle(se,Math.PI/2));var ae=function(){function e(t){r(this,e),this.config=t,this.sensor=null,this.fusionSensor=null,this._out=new Float32Array(4),this.api=null,this.errors=[],this._sensorQ=new U,this._outQ=new U,this._onSensorRead=this._onSensorRead.bind(this),this._onSensorError=this._onSensorError.bind(this),this.init()}return s(e,[{key:"init",value:function(){var e=null;try{(e=new RelativeOrientationSensor({frequency:60,referenceFrame:"screen"})).addEventListener("error",this._onSensorError)}catch(e){this.errors.push(e),"SecurityError"===e.name?(console.error("Cannot construct sensors due to the Feature Policy"),console.warn('Attempting to fall back using "devicemotion"; however this will fail in the future without correct permissions.'),this.useDeviceMotion()):"ReferenceError"===e.name?this.useDeviceMotion():console.error(e)}e&&(this.api="sensor",this.sensor=e,this.sensor.addEventListener("reading",this._onSensorRead),this.sensor.start())}},{key:"useDeviceMotion",value:function(){this.api="devicemotion",this.fusionSensor=new ie(this.config.K_FILTER,this.config.PREDICTION_TIME_S,this.config.YAW_ONLY,this.config.DEBUG),this.sensor&&(this.sensor.removeEventListener("reading",this._onSensorRead),this.sensor.removeEventListener("error",this._onSensorError),this.sensor=null)}},{key:"getOrientation",value:function(){if(this.fusionSensor)return this.fusionSensor.getOrientation();if(!this.sensor||!this.sensor.quaternion)return this._out[0]=this._out[1]=this._out[2]=0,this._out[3]=1,this._out;var e=this.sensor.quaternion;this._sensorQ.set(e[0],e[1],e[2],e[3]);var t=this._outQ;return t.copy(ne),t.multiply(this._sensorQ),this.config.YAW_ONLY&&(t.x=t.z=0,t.normalize()),this._out[0]=t.x,this._out[1]=t.y,this._out[2]=t.z,this._out[3]=t.w,this._out}},{key:"_onSensorError",value:function(e){this.errors.push(e.error),"NotAllowedError"===e.error.name?console.error("Permission to access sensor was denied"):"NotReadableError"===e.error.name?console.error("Sensor could not be read"):console.error(e.error),this.useDeviceMotion()}},{key:"_onSensorRead",value:function(){}}]),e}();function oe(){this.loadIcon_();var e=document.createElement("div"),t=e.style;t.position="fixed",t.top=0,t.right=0,t.bottom=0,t.left=0,t.backgroundColor="gray",t.fontFamily="sans-serif",t.zIndex=1e6;var i=document.createElement("img");i.src=this.icon;var t=i.style;t.marginLeft="25%",t.marginTop="25%",t.width="50%",e.appendChild(i);var r=document.createElement("div"),t=r.style;t.textAlign="center",t.fontSize="16px",t.lineHeight="24px",t.margin="24px 25%",t.width="50%",r.innerHTML="Place your phone into your Cardboard viewer.",e.appendChild(r);var s=document.createElement("div"),t=s.style;t.backgroundColor="#CFD8DC",t.position="fixed",t.bottom=0,t.width="100%",t.height="48px",t.padding="14px 24px",t.boxSizing="border-box",t.color="#656A6B",e.appendChild(s);var n=document.createElement("div");n.style.float="left",n.innerHTML="No Cardboard viewer?";var a=document.createElement("a");a.href="https://www.google.com/get/cardboard/get-cardboard/",a.innerHTML="get one",a.target="_blank";var t=a.style;t.float="right",t.fontWeight=600,t.textTransform="uppercase",t.borderLeft="1px solid gray",t.paddingLeft="24px",t.textDecoration="none",t.color="#656A6B",s.appendChild(n),s.appendChild(a),this.overlay=e,this.text=r,this.hide()}oe.prototype.show=function(e){e||this.overlay.parentElement?e&&(this.overlay.parentElement&&this.overlay.parentElement!=e&&this.overlay.parentElement.removeChild(this.overlay),e.appendChild(this.overlay)):document.body.appendChild(this.overlay),this.overlay.style.display="block";var t=this.overlay.querySelector("img"),i=t.style;f()?(i.width="20%",i.marginLeft="40%",i.marginTop="3%"):(i.width="50%",i.marginLeft="25%",i.marginTop="25%")},oe.prototype.hide=function(){this.overlay.style.display="none"},oe.prototype.showTemporarily=function(e,t){this.show(t),this.timer=setTimeout(this.hide.bind(this),e)},oe.prototype.disableShowTemporarily=function(){clearTimeout(this.timer)},oe.prototype.update=function(){this.disableShowTemporarily(),!f()&&b()?this.show():this.hide()},oe.prototype.loadIcon_=function(){this.icon="data:image/svg+xml,"+encodeURIComponent("")};var le="CardboardV1",Ae="WEBVR_CARDBOARD_VIEWER";function he(e){try{this.selectedKey=localStorage.getItem(Ae)}catch(e){console.error("Failed to load viewer profile: %s",e)}this.selectedKey||(this.selectedKey=e||le),this.dialog=this.createDialog_(q.Viewers),this.root=null,this.onChangeCallbacks_=[]}he.prototype.show=function(e){this.root=e,e.appendChild(this.dialog);var t=this.dialog.querySelector("#"+this.selectedKey);t.checked=!0,this.dialog.style.display="block"},he.prototype.hide=function(){this.root&&this.root.contains(this.dialog)&&this.root.removeChild(this.dialog),this.dialog.style.display="none"},he.prototype.getCurrentViewer=function(){return q.Viewers[this.selectedKey]},he.prototype.getSelectedKey_=function(){var e=this.dialog.querySelector("input[name=field]:checked");return e?e.id:null},he.prototype.onChange=function(e){this.onChangeCallbacks_.push(e)},he.prototype.fireOnChange_=function(e){for(var t=0;t.5&&(this.noSleepVideo.currentTime=Math.random())}.bind(this)))}return r(e,[{key:"enable",value:function(){n?(this.disable(),this.noSleepTimer=window.setInterval(function(){window.location.href="/",window.setTimeout(window.stop,0)},15e3)):this.noSleepVideo.play()}},{key:"disable",value:function(){n?this.noSleepTimer&&(window.clearInterval(this.noSleepTimer),this.noSleepTimer=null):this.noSleepVideo.pause()}}]),e}();e.exports=a},function(e,t,i){e.exports="data:video/mp4;base64,AAAAIGZ0eXBtcDQyAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAACKBtZGF0AAAC8wYF///v3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE0MiByMjQ3OSBkZDc5YTYxIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxNCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTEgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDExMSBtZT1oZXggc3VibWU9MiBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0wIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MCA4eDhkY3Q9MCBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0wIHRocmVhZHM9NiBsb29rYWhlYWRfdGhyZWFkcz0xIHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTMgYl9weXJhbWlkPTIgYl9hZGFwdD0xIGJfYmlhcz0wIGRpcmVjdD0xIHdlaWdodGI9MSBvcGVuX2dvcD0wIHdlaWdodHA9MSBrZXlpbnQ9MzAwIGtleWludF9taW49MzAgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD0xMCByYz1jcmYgbWJ0cmVlPTEgY3JmPTIwLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IHZidl9tYXhyYXRlPTIwMDAwIHZidl9idWZzaXplPTI1MDAwIGNyZl9tYXg9MC4wIG5hbF9ocmQ9bm9uZSBmaWxsZXI9MCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAAAOWWIhAA3//p+C7v8tDDSTjf97w55i3SbRPO4ZY+hkjD5hbkAkL3zpJ6h/LR1CAABzgB1kqqzUorlhQAAAAxBmiQYhn/+qZYADLgAAAAJQZ5CQhX/AAj5IQAD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"}])},e.exports=i()}(de={exports:{}},de.exports),(ce=de.exports)&&ce.__esModule&&Object.prototype.hasOwnProperty.call(ce,"default")?ce.default:ce),pe=1e3,fe=[0,0,.5,1],me=[.5,0,.5,1],ge=window.requestAnimationFrame,ve=window.cancelAnimationFrame;function we(e){Object.defineProperties(this,{hasPosition:{writable:!1,enumerable:!0,value:e.hasPosition},hasExternalDisplay:{writable:!1,enumerable:!0,value:e.hasExternalDisplay},canPresent:{writable:!1,enumerable:!0,value:e.canPresent},maxLayers:{writable:!1,enumerable:!0,value:e.maxLayers},hasOrientation:{enumerable:!0,get:function(){return F("VRDisplayCapabilities.prototype.hasOrientation","VRDisplay.prototype.getFrameData"),e.hasOrientation}}})}function ye(e){var t=!("wakelock"in(e=e||{}))||e.wakelock;this.isPolyfilled=!0,this.displayId=pe++,this.displayName="",this.depthNear=.01,this.depthFar=1e4,this.isPresenting=!1,Object.defineProperty(this,"isConnected",{get:function(){return F("VRDisplay.prototype.isConnected","VRDisplayCapabilities.prototype.hasExternalDisplay"),!1}}),this.capabilities=new we({hasPosition:!1,hasOrientation:!1,hasExternalDisplay:!1,canPresent:!1,maxLayers:1}),this.stageParameters=null,this.waitingForPresent_=!1,this.layer_=null,this.originalParent_=null,this.fullscreenElement_=null,this.fullscreenWrapper_=null,this.fullscreenElementCachedStyle_=null,this.fullscreenEventTarget_=null,this.fullscreenChangeHandler_=null,this.fullscreenErrorHandler_=null,t&&b()&&(this.wakelock_=new ue)}ye.prototype.getFrameData=function(e){return M(e,this._getPose(),this)},ye.prototype.getPose=function(){return F("VRDisplay.prototype.getPose","VRDisplay.prototype.getFrameData"),this._getPose()},ye.prototype.resetPose=function(){return F("VRDisplay.prototype.resetPose"),this._resetPose()},ye.prototype.getImmediatePose=function(){return F("VRDisplay.prototype.getImmediatePose","VRDisplay.prototype.getFrameData"),this._getPose()},ye.prototype.requestAnimationFrame=function(e){return ge(e)},ye.prototype.cancelAnimationFrame=function(e){return ve(e)},ye.prototype.wrapForFullscreen=function(e){if(o())return e;if(!this.fullscreenWrapper_){this.fullscreenWrapper_=document.createElement("div");var t=["height: "+Math.min(screen.height,screen.width)+"px !important","top: 0 !important","left: 0 !important","right: 0 !important","border: 0","margin: 0","padding: 0","z-index: 999999 !important","position: fixed"];this.fullscreenWrapper_.setAttribute("style",t.join("; ")+";"),this.fullscreenWrapper_.classList.add("webvr-polyfill-fullscreen-wrapper")}if(this.fullscreenElement_==e)return this.fullscreenWrapper_;if(this.fullscreenElement_&&(this.originalParent_?this.originalParent_.appendChild(this.fullscreenElement_):this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_)),this.fullscreenElement_=e,this.originalParent_=e.parentElement,this.originalParent_||document.body.appendChild(e),!this.fullscreenWrapper_.parentElement){var i=this.fullscreenElement_.parentElement;i.insertBefore(this.fullscreenWrapper_,this.fullscreenElement_),i.removeChild(this.fullscreenElement_)}this.fullscreenWrapper_.insertBefore(this.fullscreenElement_,this.fullscreenWrapper_.firstChild),this.fullscreenElementCachedStyle_=this.fullscreenElement_.getAttribute("style");var r=this;return function(){if(r.fullscreenElement_){var e=["position: absolute","top: 0","left: 0","width: "+Math.max(screen.width,screen.height)+"px","height: "+Math.min(screen.height,screen.width)+"px","border: 0","margin: 0","padding: 0"];r.fullscreenElement_.setAttribute("style",e.join("; ")+";")}}(),this.fullscreenWrapper_},ye.prototype.removeFullscreenWrapper=function(){if(this.fullscreenElement_){var e=this.fullscreenElement_;this.fullscreenElementCachedStyle_?e.setAttribute("style",this.fullscreenElementCachedStyle_):e.removeAttribute("style"),this.fullscreenElement_=null,this.fullscreenElementCachedStyle_=null;var t=this.fullscreenWrapper_.parentElement;return this.fullscreenWrapper_.removeChild(e),this.originalParent_===t?t.insertBefore(e,this.fullscreenWrapper_):this.originalParent_&&this.originalParent_.appendChild(e),t.removeChild(this.fullscreenWrapper_),e}},ye.prototype.requestPresent=function(e){var t=this.isPresenting,i=this;return e instanceof Array||(F("VRDisplay.prototype.requestPresent with non-array argument","an array of VRLayers as the first argument"),e=[e]),new Promise(function(r,s){if(i.capabilities.canPresent)if(0==e.length||e.length>i.capabilities.maxLayers)s(new Error("Invalid number of layers."));else{var n=e[0];if(n.source){var a=n.leftBounds||fe,A=n.rightBounds||me;if(t){var h=i.layer_;h.source!==n.source&&(h.source=n.source);for(var c=0;c<4;c++)h.leftBounds[c]=a[c],h.rightBounds[c]=A[c];return i.wrapForFullscreen(i.layer_.source),i.updatePresent_(),void r()}if(i.layer_={predistorted:n.predistorted,source:n.source,leftBounds:a.slice(0),rightBounds:A.slice(0)},i.waitingForPresent_=!1,i.layer_&&i.layer_.source){var d=i.wrapForFullscreen(i.layer_.source);i.addFullscreenListeners_(d,function(){var e=document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement;i.isPresenting=d===e,i.isPresenting?(screen.orientation&&screen.orientation.lock&&screen.orientation.lock("landscape-primary").catch(function(e){console.error("screen.orientation.lock() failed due to",e.message)}),i.waitingForPresent_=!1,i.beginPresent_(),r()):(screen.orientation&&screen.orientation.unlock&&screen.orientation.unlock(),i.removeFullscreenWrapper(),i.disableWakeLock(),i.endPresent_(),i.removeFullscreenListeners_()),i.fireVRDisplayPresentChange_()},function(){i.waitingForPresent_&&(i.removeFullscreenWrapper(),i.removeFullscreenListeners_(),i.disableWakeLock(),i.waitingForPresent_=!1,i.isPresenting=!1,s(new Error("Unable to present.")))}),function(e){if(l())return!1;if(e.requestFullscreen)e.requestFullscreen();else if(e.webkitRequestFullscreen)e.webkitRequestFullscreen();else if(e.mozRequestFullScreen)e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)return!1;e.msRequestFullscreen()}return!0}(d)?(i.enableWakeLock(),i.waitingForPresent_=!0):(o()||l())&&(i.enableWakeLock(),i.isPresenting=!0,i.beginPresent_(),i.fireVRDisplayPresentChange_(),r())}i.waitingForPresent_||o()||(v(),s(new Error("Unable to present.")))}else r()}else s(new Error("VRDisplay is not capable of presenting."))})},ye.prototype.exitPresent=function(){var e=this.isPresenting,t=this;return this.isPresenting=!1,this.layer_=null,this.disableWakeLock(),new Promise(function(i,r){e?(!v()&&o()&&(t.endPresent_(),t.fireVRDisplayPresentChange_()),l()&&(t.removeFullscreenWrapper(),t.removeFullscreenListeners_(),t.endPresent_(),t.fireVRDisplayPresentChange_()),i()):r(new Error("Was not presenting to VRDisplay."))})},ye.prototype.getLayers=function(){return this.layer_?[this.layer_]:[]},ye.prototype.fireVRDisplayPresentChange_=function(){var e=new CustomEvent("vrdisplaypresentchange",{detail:{display:this}});window.dispatchEvent(e)},ye.prototype.fireVRDisplayConnect_=function(){var e=new CustomEvent("vrdisplayconnect",{detail:{display:this}});window.dispatchEvent(e)},ye.prototype.addFullscreenListeners_=function(e,t,i){this.removeFullscreenListeners_(),this.fullscreenEventTarget_=e,this.fullscreenChangeHandler_=t,this.fullscreenErrorHandler_=i,t&&(document.fullscreenEnabled?e.addEventListener("fullscreenchange",t,!1):document.webkitFullscreenEnabled?e.addEventListener("webkitfullscreenchange",t,!1):document.mozFullScreenEnabled?document.addEventListener("mozfullscreenchange",t,!1):document.msFullscreenEnabled&&e.addEventListener("msfullscreenchange",t,!1)),i&&(document.fullscreenEnabled?e.addEventListener("fullscreenerror",i,!1):document.webkitFullscreenEnabled?e.addEventListener("webkitfullscreenerror",i,!1):document.mozFullScreenEnabled?document.addEventListener("mozfullscreenerror",i,!1):document.msFullscreenEnabled&&e.addEventListener("msfullscreenerror",i,!1))},ye.prototype.removeFullscreenListeners_=function(){if(this.fullscreenEventTarget_){var e=this.fullscreenEventTarget_;if(this.fullscreenChangeHandler_){var t=this.fullscreenChangeHandler_;e.removeEventListener("fullscreenchange",t,!1),e.removeEventListener("webkitfullscreenchange",t,!1),document.removeEventListener("mozfullscreenchange",t,!1),e.removeEventListener("msfullscreenchange",t,!1)}if(this.fullscreenErrorHandler_){var i=this.fullscreenErrorHandler_;e.removeEventListener("fullscreenerror",i,!1),e.removeEventListener("webkitfullscreenerror",i,!1),document.removeEventListener("mozfullscreenerror",i,!1),e.removeEventListener("msfullscreenerror",i,!1)}this.fullscreenEventTarget_=null,this.fullscreenChangeHandler_=null,this.fullscreenErrorHandler_=null}},ye.prototype.enableWakeLock=function(){this.wakelock_&&this.wakelock_.enable()},ye.prototype.disableWakeLock=function(){this.wakelock_&&this.wakelock_.disable()},ye.prototype.beginPresent_=function(){},ye.prototype.endPresent_=function(){},ye.prototype.submitFrame=function(e){},ye.prototype.getEyeParameters=function(e){return null};var be={ADDITIONAL_VIEWERS:[],DEFAULT_VIEWER:"",MOBILE_WAKE_LOCK:!0,DEBUG:!1,DPDB_URL:"https://dpdb.webvr.rocks/dpdb.json",K_FILTER:.98,PREDICTION_TIME_S:.04,CARDBOARD_UI_DISABLED:!1,ROTATE_INSTRUCTIONS_DISABLED:!1,YAW_ONLY:!1,BUFFER_SCALE:.5,DIRTY_SUBMIT_FRAME_BINDINGS:!1},Ee={LEFT:"left",RIGHT:"right"};function Se(e){var t=E({},be);e=E(t,e||{}),ye.call(this,{wakelock:e.MOBILE_WAKE_LOCK}),this.config=e,this.displayName="Cardboard VRDisplay",this.capabilities=new we({hasPosition:!1,hasOrientation:!0,hasExternalDisplay:!1,canPresent:!0,maxLayers:1}),this.stageParameters=null,this.bufferScale_=this.config.BUFFER_SCALE,this.poseSensor_=new ae(this.config),this.distorter_=null,this.cardboardUI_=null,this.dpdb_=new J(this.config.DPDB_URL,this.onDeviceParamsUpdated_.bind(this)),this.deviceInfo_=new q(this.dpdb_.getDeviceParams(),e.ADDITIONAL_VIEWERS),this.viewerSelector_=new he(e.DEFAULT_VIEWER),this.viewerSelector_.onChange(this.onViewerChanged_.bind(this)),this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer()),this.config.ROTATE_INSTRUCTIONS_DISABLED||(this.rotateInstructions_=new oe),o()&&window.addEventListener("resize",this.onResize_.bind(this))}return Se.prototype=Object.create(ye.prototype),Se.prototype._getPose=function(){return{position:null,orientation:this.poseSensor_.getOrientation(),linearVelocity:null,linearAcceleration:null,angularVelocity:null,angularAcceleration:null}},Se.prototype._resetPose=function(){this.poseSensor_.resetPose&&this.poseSensor_.resetPose()},Se.prototype._getFieldOfView=function(e){var t;if(e==Ee.LEFT)t=this.deviceInfo_.getFieldOfViewLeftEye();else{if(e!=Ee.RIGHT)return console.error("Invalid eye provided: %s",e),null;t=this.deviceInfo_.getFieldOfViewRightEye()}return t},Se.prototype._getEyeOffset=function(e){var t;if(e==Ee.LEFT)t=[.5*-this.deviceInfo_.viewer.interLensDistance,0,0];else{if(e!=Ee.RIGHT)return console.error("Invalid eye provided: %s",e),null;t=[.5*this.deviceInfo_.viewer.interLensDistance,0,0]}return t},Se.prototype.getEyeParameters=function(e){var t=this._getEyeOffset(e),i=this._getFieldOfView(e),r={offset:t,renderWidth:.5*this.deviceInfo_.device.width*this.bufferScale_,renderHeight:this.deviceInfo_.device.height*this.bufferScale_};return Object.defineProperty(r,"fieldOfView",{enumerable:!0,get:function(){return F("VRFieldOfView","VRFrameData's projection matrices"),i}}),r},Se.prototype.onDeviceParamsUpdated_=function(e){this.config.DEBUG&&console.log("DPDB reported that device params were updated."),this.deviceInfo_.updateDeviceParams(e),this.distorter_&&this.distorter_.updateDeviceInfo(this.deviceInfo_)},Se.prototype.updateBounds_=function(){this.layer_&&this.distorter_&&(this.layer_.leftBounds||this.layer_.rightBounds)&&this.distorter_.setTextureBounds(this.layer_.leftBounds,this.layer_.rightBounds)},Se.prototype.beginPresent_=function(){var e=this.layer_.source.getContext("webgl");e||(e=this.layer_.source.getContext("experimental-webgl")),e||(e=this.layer_.source.getContext("webgl2")),e&&(this.layer_.predistorted?this.config.CARDBOARD_UI_DISABLED||(e.canvas.width=m()*this.bufferScale_,e.canvas.height=g()*this.bufferScale_,this.cardboardUI_=new O(e)):(this.config.CARDBOARD_UI_DISABLED||(this.cardboardUI_=new O(e)),this.distorter_=new B(e,this.cardboardUI_,this.config.BUFFER_SCALE,this.config.DIRTY_SUBMIT_FRAME_BINDINGS),this.distorter_.updateDeviceInfo(this.deviceInfo_)),this.cardboardUI_&&this.cardboardUI_.listen(function(e){this.viewerSelector_.show(this.layer_.source.parentElement),e.stopPropagation(),e.preventDefault()}.bind(this),function(e){this.exitPresent(),e.stopPropagation(),e.preventDefault()}.bind(this)),this.rotateInstructions_&&(f()&&b()?this.rotateInstructions_.showTemporarily(3e3,this.layer_.source.parentElement):this.rotateInstructions_.update()),this.orientationHandler=this.onOrientationChange_.bind(this),window.addEventListener("orientationchange",this.orientationHandler),this.vrdisplaypresentchangeHandler=this.updateBounds_.bind(this),window.addEventListener("vrdisplaypresentchange",this.vrdisplaypresentchangeHandler),this.fireVRDisplayDeviceParamsChange_())},Se.prototype.endPresent_=function(){this.distorter_&&(this.distorter_.destroy(),this.distorter_=null),this.cardboardUI_&&(this.cardboardUI_.destroy(),this.cardboardUI_=null),this.rotateInstructions_&&this.rotateInstructions_.hide(),this.viewerSelector_.hide(),window.removeEventListener("orientationchange",this.orientationHandler),window.removeEventListener("vrdisplaypresentchange",this.vrdisplaypresentchangeHandler)},Se.prototype.updatePresent_=function(){this.endPresent_(),this.beginPresent_()},Se.prototype.submitFrame=function(e){if(this.distorter_)this.updateBounds_(),this.distorter_.submitFrame();else if(this.cardboardUI_&&this.layer_){var t=this.layer_.source.getContext("webgl");t||(t=this.layer_.source.getContext("experimental-webgl")),t||(t=this.layer_.source.getContext("webgl2"));var i=t.canvas;i.width==this.lastWidth&&i.height==this.lastHeight||this.cardboardUI_.onResize(),this.lastWidth=i.width,this.lastHeight=i.height,this.cardboardUI_.render()}},Se.prototype.onOrientationChange_=function(e){this.viewerSelector_.hide(),this.rotateInstructions_&&this.rotateInstructions_.update(),this.onResize_()},Se.prototype.onResize_=function(e){if(this.layer_){var t=this.layer_.source.getContext("webgl");t||(t=this.layer_.source.getContext("experimental-webgl")),t||(t=this.layer_.source.getContext("webgl2")),t.canvas.setAttribute("style",["position: absolute","top: 0","left: 0","width: 100vw","height: 100vh","border: 0","margin: 0","padding: 0px","box-sizing: content-box"].join("; ")+";"),S(t.canvas)}},Se.prototype.onViewerChanged_=function(e){this.deviceInfo_.setViewer(e),this.distorter_&&this.distorter_.updateDeviceInfo(this.deviceInfo_),this.fireVRDisplayDeviceParamsChange_()},Se.prototype.fireVRDisplayDeviceParamsChange_=function(){var e=new CustomEvent("vrdisplaydeviceparamschange",{detail:{vrdisplay:this,deviceInfo:this.deviceInfo_}});window.dispatchEvent(e)},Se.VRFrameData=function(){this.leftProjectionMatrix=new Float32Array(16),this.leftViewMatrix=new Float32Array(16),this.rightProjectionMatrix=new Float32Array(16),this.rightViewMatrix=new Float32Array(16),this.pose=null},Se.VRDisplay=ye,Se}()}(De={exports:{}},De.exports),De.exports),Oe=(Ie=Le)&&Ie.__esModule&&Object.prototype.hasOwnProperty.call(Ie,"default")?Ie.default:Ie;class Ne extends i{constructor(e){super(),this.global=e,this.onWindowResize=this.onWindowResize.bind(this),this.global.window.addEventListener("resize",this.onWindowResize),this.environmentBlendMode="opaque"}onBaseLayerSet(e,t){throw new Error("Not implemented")}isSessionSupported(e){throw new Error("Not implemented")}isFeatureSupported(e){throw new Error("Not implemented")}async requestSession(e,t){throw new Error("Not implemented")}requestAnimationFrame(e){throw new Error("Not implemented")}onFrameStart(e){throw new Error("Not implemented")}onFrameEnd(e){throw new Error("Not implemented")}doesSessionSupportReferenceSpace(e,t){throw new Error("Not implemented")}requestStageBounds(){throw new Error("Not implemented")}async requestFrameOfReferenceTransform(e,t){}cancelAnimationFrame(e){throw new Error("Not implemented")}endSession(e){throw new Error("Not implemented")}getViewSpaces(e){}getViewport(e,t,i,r,s){throw new Error("Not implemented")}getProjectionMatrix(e,t){throw new Error("Not implemented")}getBasePoseMatrix(){throw new Error("Not implemented")}getBaseViewMatrix(e){throw new Error("Not implemented")}getInputSources(){throw new Error("Not implemented")}getInputPose(e,t,i){throw new Error("Not implemented")}onWindowResize(){this.onWindowResize()}}let Ge={mapping:"xr-standard",profiles:["oculus-go","generic-trigger-touchpad"],buttons:{length:3,0:1,1:null,2:0},gripTransform:{orientation:[.11*Math.PI,0,0,1]}},Qe={mapping:"xr-standard",displayProfiles:{"Oculus Quest":["oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"]},profiles:["oculus-touch","generic-trigger-squeeze-thumbstick"],axes:{length:4,0:null,1:null,2:0,3:1},buttons:{length:7,0:1,1:2,2:null,3:0,4:3,5:4,6:null},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},ke={mapping:"xr-standard",displayProfiles:{"Oculus Quest":["oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"]},profiles:["oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"],axes:{length:4,0:null,1:null,2:0,3:1},buttons:{length:7,0:1,1:2,2:null,3:0,4:3,5:4,6:null},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},ze={mapping:"xr-standard",displayProfiles:{"Oculus Quest":["oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"]},profiles:["oculus-touch-v3","oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"],axes:{length:4,0:null,1:null,2:0,3:1},buttons:{length:7,0:1,1:2,2:null,3:0,4:3,5:4,6:null},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},Ve={mapping:"xr-standard",profiles:["htc-vive","generic-trigger-squeeze-touchpad"],displayProfiles:{"HTC Vive":["htc-vive","generic-trigger-squeeze-touchpad"],"HTC Vive DVT":["htc-vive","generic-trigger-squeeze-touchpad"],"Valve Index":["valve-index","generic-trigger-squeeze-touchpad-thumbstick"]},buttons:{length:3,0:1,1:2,2:0},gripTransform:{position:[0,0,.05,1]},targetRayTransform:{orientation:[-.08*Math.PI,0,0,1]},userAgentOverrides:{Firefox:{axes:{invert:[1,3]}}}},Ue={mapping:"xr-standard",profiles:["samsung-gearvr","generic-trigger-touchpad"],buttons:{length:3,0:1,1:null,2:0},gripTransform:{orientation:[.11*Math.PI,0,0,1]}},He={mapping:"xr-standard",profiles:["samsung-odyssey","microsoft-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"],buttons:{length:4,0:1,1:0,2:2,3:4},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},Xe={mapping:"xr-standard",profiles:["microsoft-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"],buttons:{length:4,0:1,1:0,2:2,3:4},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},We={"Daydream Controller":{mapping:"",profiles:["google-daydream","generic-trigger-touchpad"],buttons:{length:3,0:null,1:null,2:0}},"Gear VR Controller":Ue,"HTC Vive Focus Controller":{mapping:"xr-standard",profiles:["htc-vive-focus","generic-trigger-touchpad"],buttons:{length:3,0:1,1:null,2:0}},"Oculus Go Controller":Ge,"Oculus Touch (Right)":Qe,"Oculus Touch (Left)":Qe,"Oculus Touch V2 (Right)":ke,"Oculus Touch V2 (Left)":ke,"Oculus Touch V3 (Right)":ze,"Oculus Touch V3 (Left)":ze,"OpenVR Gamepad":Ve,"Spatial Controller (Spatial Interaction Source) 045E-065A":Xe,"Spatial Controller (Spatial Interaction Source) 045E-065D":He,"Windows Mixed Reality (Right)":Xe,"Windows Mixed Reality (Left)":Xe};const je=f(.155,-.465,-.15),qe=f(-.155,-.465,-.15),Ye=f(0,0,-.25),Ze=f(0,0,.05),Je=f(-.08,.14,.08),Ke=.4,$e=.4,et=.61,tt=.175,it=.12,rt=.87,st=180/Math.PI;class nt{constructor(){this.hand="right",this.headElbowOffset=je,this.controllerQ=M(),this.lastControllerQ=M(),this.headQ=M(),this.headPos=u(),this.elbowPos=u(),this.wristPos=u(),this.time=null,this.lastTime=null,this.rootQ=M(),this.position=u()}setHandedness(e){this.hand!=e&&(this.hand=e,"left"==this.hand?this.headElbowOffset=qe:this.headElbowOffset=je)}update(e,t){this.time=X(),e&&(P(this.lastControllerQ,this.controllerQ),P(this.controllerQ,e)),t&&(h(this.headPos,t),c(this.headQ,t));let i=this.getHeadYawOrientation_(),r=this.quatAngle_(this.lastControllerQ,this.controllerQ);r/((this.time-this.lastTime)/1e3)>et?_(this.rootQ,this.rootQ,i,Math.min(r/tt,1)):P(this.rootQ,i);let s=f(0,0,-1);E(s,s,this.controllerQ);let n=y(s,[0,1,0]),a=this.clamp_((n-it)/rt,0,1),o=R(this.rootQ);F(o,o),x(o,o,this.controllerQ);let l=this.elbowPos;m(l,this.headPos),g(l,l,this.headElbowOffset);let A=p(Je);v(A,A,a),g(l,l,A);let d=this.quatAngle_(o,M())*st,u=(1-Math.pow(d/180,4))*(Ke+(1-Ke)*a*$e),w=M();_(w,w,o,u);let b=F(M(),w),S=R(o);x(S,S,b);let T=this.wristPos;m(T,Ze),E(T,T,w),g(T,T,Ye),E(T,T,S),g(T,T,l);let B=p(Je);v(B,B,a),g(this.position,this.wristPos,B),E(this.position,this.position,this.rootQ),this.lastTime=this.time}getPosition(){return this.position}getHeadYawOrientation_(){let e=u();return function(e,t,i){function r(e,t,i){return ei?i:e}var s=t[0]*t[0],n=t[1]*t[1],a=t[2]*t[2],o=t[3]*t[3];if("XYZ"===i)e[0]=Math.atan2(2*(t[0]*t[3]-t[1]*t[2]),o-s-n+a),e[1]=Math.asin(r(2*(t[0]*t[2]+t[1]*t[3]),-1,1)),e[2]=Math.atan2(2*(t[2]*t[3]-t[0]*t[1]),o+s-n-a);else if("YXZ"===i)e[0]=Math.asin(r(2*(t[0]*t[3]-t[1]*t[2]),-1,1)),e[1]=Math.atan2(2*(t[0]*t[2]+t[1]*t[3]),o-s-n+a),e[2]=Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),o-s+n-a);else if("ZXY"===i)e[0]=Math.asin(r(2*(t[0]*t[3]+t[1]*t[2]),-1,1)),e[1]=Math.atan2(2*(t[1]*t[3]-t[2]*t[0]),o-s-n+a),e[2]=Math.atan2(2*(t[2]*t[3]-t[0]*t[1]),o-s+n-a);else if("ZYX"===i)e[0]=Math.atan2(2*(t[0]*t[3]+t[2]*t[1]),o-s-n+a),e[1]=Math.asin(r(2*(t[1]*t[3]-t[0]*t[2]),-1,1)),e[2]=Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),o+s-n-a);else if("YZX"===i)e[0]=Math.atan2(2*(t[0]*t[3]-t[2]*t[1]),o-s+n-a),e[1]=Math.atan2(2*(t[1]*t[3]-t[0]*t[2]),o+s-n-a),e[2]=Math.asin(r(2*(t[0]*t[1]+t[2]*t[3]),-1,1));else{if("XZY"!==i)return void console.log("No order given for quaternion to euler conversion.");e[0]=Math.atan2(2*(t[0]*t[3]+t[1]*t[2]),o-s+n-a),e[1]=Math.atan2(2*(t[0]*t[2]+t[1]*t[3]),o+s-n-a),e[2]=Math.asin(r(2*(t[2]*t[3]-t[0]*t[1]),-1,1))}}(e,this.headQ,"YXZ"),function(e,t,i,r){let s=.5*Math.PI/180;t*=s,i*=s,r*=s;let n=Math.sin(t),a=Math.cos(t),o=Math.sin(i),l=Math.cos(i),A=Math.sin(r),h=Math.cos(r);return e[0]=n*l*h-a*o*A,e[1]=a*o*h+n*l*A,e[2]=a*l*A-n*o*h,e[3]=a*l*h+n*o*A,e}(M(),0,e[1]*st,0)}clamp_(e,t,i){return Math.min(Math.max(e,t),i)}quatAngle_(e,t){let i=[0,0,-1],r=[0,0,-1];return E(i,i,e),E(r,r,t),function(e,t){let i=f(e[0],e[1],e[2]),r=f(t[0],t[1],t[2]);w(i,i),w(r,r);let s=y(i,r);return s>1?0:s<-1?Math.PI:Math.acos(s)}(i,r)}}const at=Symbol("@@webxr-polyfill/XRRemappedGamepad"),ot={pressed:!1,touched:!1,value:0};Object.freeze(ot);class lt{constructor(e,t,i){if(i||(i={}),i.userAgentOverrides)for(let e in i.userAgentOverrides)if(navigator.userAgent.includes(e)){let t=i.userAgentOverrides[e];for(let e in t)e in i?Object.assign(i[e],t[e]):i[e]=t[e];break}let r=new Array(i.axes&&i.axes.length?i.axes.length:e.axes.length),s=new Array(i.buttons&&i.buttons.length?i.buttons.length:e.buttons.length),a=null;if(i.gripTransform){let e=i.gripTransform.orientation||[0,0,0,1];A(a=n(),B(e,e),i.gripTransform.position||[0,0,0])}let o=null;if(i.targetRayTransform){let e=i.targetRayTransform.orientation||[0,0,0,1];A(o=n(),B(e,e),i.targetRayTransform.position||[0,0,0])}let l=i.profiles;i.displayProfiles&&t.displayName in i.displayProfiles&&(l=i.displayProfiles[t.displayName]),this[at]={gamepad:e,map:i,profiles:l||[e.id],mapping:i.mapping||e.mapping,axes:r,buttons:s,gripTransform:a,targetRayTransform:o},this._update()}_update(){let e=this[at].gamepad,t=this[at].map,i=this[at].axes;for(let r=0;r{ht||this.global.document.body.contains(r)||(i.modifiedCanvasLayer=!0,this.global.document.body.appendChild(r),Be(r)),i.baseLayer=t})}else i.baseLayer=t}isSessionSupported(e){return"immersive-ar"!=e&&("immersive-vr"!=e||!1!==this.canPresent)}isFeatureSupported(e){switch(e){case"viewer":case"local":case"local-floor":return!0;case"bounded":case"unbounded":default:return!1}}async requestSession(e,t){if(!this.isSessionSupported(e))return Promise.reject();let i="immersive-vr"==e;if(i){const e=this.global.document.createElement("canvas");if(!ht){e.getContext("webgl")}await this.display.requestPresent([{source:e,attributes:ct}])}const r=new pt(e,t,{renderContextType:this.HAS_BITMAP_SUPPORT?"bitmaprenderer":"2d"});return this.sessions.set(r.id,r),i&&(this.immersiveSession=r,this.dispatchEvent("@@webxr-polyfill/vr-present-start",r.id)),Promise.resolve(r.id)}requestAnimationFrame(e){return this.display.requestAnimationFrame(e)}getPrimaryButtonIndex(e){let t=0,i=e.id.toLowerCase();for(let e in dt)if(i.includes(e)){t=dt[e];break}return Math.min(t,e.buttons.length-1)}onFrameStart(e,t){this.display.depthNear=t.depthNear,this.display.depthFar=t.depthFar,this.display.getFrameData(this.frame);const i=this.sessions.get(e);if(i.immersive&&this.CAN_USE_GAMEPAD){let e=this.gamepadInputSources;this.gamepadInputSources={};let t=this.global.navigator.getGamepads();for(let r=0;r0){let t=e[r];if(t||(t=new At(this,this.display,this.getPrimaryButtonIndex(s))),t.updateFromGamepad(s),this.gamepadInputSources[r]=t,-1!=t.primaryButtonIndex){let e=s.buttons[t.primaryButtonIndex].pressed;e&&!t.primaryActionPressed?this.dispatchEvent("@@webxr-polyfill/input-select-start",{sessionId:i.id,inputSource:t.inputSource}):!e&&t.primaryActionPressed&&this.dispatchEvent("@@webxr-polyfill/input-select-end",{sessionId:i.id,inputSource:t.inputSource}),t.primaryActionPressed=e}if(-1!=t.primarySqueezeButtonIndex){let e=s.buttons[t.primarySqueezeButtonIndex].pressed;e&&!t.primarySqueezeActionPressed?this.dispatchEvent("@@webxr-polyfill/input-squeeze-start",{sessionId:i.id,inputSource:t.inputSource}):!e&&t.primarySqueezeActionPressed&&this.dispatchEvent("@@webxr-polyfill/input-squeeze-end",{sessionId:i.id,inputSource:t.inputSource}),t.primarySqueezeActionPressed=e}}}}if(!ht&&!i.immersive&&i.baseLayer){const e=i.baseLayer.context.canvas;d(this.frame.leftProjectionMatrix,t.inlineVerticalFieldOfView,e.width/e.height,t.depthNear,t.depthFar)}}onFrameEnd(e){const t=this.sessions.get(e);if(!t.ended&&t.baseLayer){if(t.outputContext&&(!t.immersive||this.display.capabilities.hasExternalDisplay)){const e=t.immersive&&this.display.capabilities.hasExternalDisplay,i=t.baseLayer.context.canvas,r=e?i.width/2:i.width,s=i.height;if(!ht){const e=t.outputContext.canvas,n=e.width,a=e.height,o=t.renderContext;this.HAS_BITMAP_SUPPORT?i.transferToImageBitmap?o.transferFromImageBitmap(i.transferToImageBitmap()):this.global.createImageBitmap(i,0,0,r,s,{resizeWidth:n,resizeHeight:a}).then(e=>o.transferFromImageBitmap(e)):o.drawImage(i,0,0,r,s,0,0,n,a)}}t.immersive&&t.baseLayer&&this.display.submitFrame()}}cancelAnimationFrame(e){this.display.cancelAnimationFrame(e)}async endSession(e){const t=this.sessions.get(e);if(!t.ended)return t.immersive?this.display.exitPresent():void(t.ended=!0)}doesSessionSupportReferenceSpace(e,t){const i=this.sessions.get(e);return!i.ended&&i.enabledFeatures.has(t)}requestStageBounds(){if(this.display.stageParameters){const e=this.display.stageParameters.sizeX,t=this.display.stageParameters.sizeZ,i=[];return i.push(-e/2),i.push(-t/2),i.push(e/2),i.push(-t/2),i.push(e/2),i.push(t/2),i.push(-e/2),i.push(t/2),i}return null}async requestFrameOfReferenceTransform(e,t){return("local-floor"===e||"bounded-floor"===e)&&this.display.stageParameters&&this.display.stageParameters.sittingToStandingTransform?this.display.stageParameters.sittingToStandingTransform:null}getProjectionMatrix(e){if("left"===e)return this.frame.leftProjectionMatrix;if("right"===e)return this.frame.rightProjectionMatrix;if("none"===e)return this.frame.leftProjectionMatrix;throw new Error("eye must be of type 'left' or 'right'")}getViewport(e,t,i,r){const s=this.sessions.get(e),{width:n,height:a}=i.context.canvas;if(!s.immersive)return r.x=r.y=0,r.width=n,r.height=a,!0;if("left"===t||"none"===t)r.x=0;else{if("right"!==t)return!1;r.x=n/2}return r.y=0,r.width=n/2,r.height=a,!0}getBasePoseMatrix(){let{position:e,orientation:t}=this.frame.pose;return e||t?(e||((e=this.tempVec3)[0]=e[1]=e[2]=0),A(this.baseModelMatrix,t,e),this.baseModelMatrix):this.baseModelMatrix}getBaseViewMatrix(e){if("left"===e||"none"===e)return this.frame.leftViewMatrix;if("right"===e)return this.frame.rightViewMatrix;throw new Error("eye must be of type 'left' or 'right'")}getInputSources(){let e=[];for(let t in this.gamepadInputSources)e.push(this.gamepadInputSources[t].inputSource);return e}getInputPose(e,t,i){if(!t)return null;for(let r in this.gamepadInputSources){let s=this.gamepadInputSources[r];if(s.inputSource===e)return s.getXRPose(t,i)}return null}onWindowResize(){}onVRDisplayPresentChange(e){this.display.isPresenting||this.sessions.forEach(e=>{if(e.immersive&&!e.ended){if(e.modifiedCanvasLayer){const t=e.baseLayer.context.canvas;document.body.removeChild(t),t.setAttribute("style","")}this.immersiveSession===e&&(this.immersiveSession=null),this.dispatchEvent("@@webxr-polyfill/vr-present-end",e.id)}})}}const mt=!1;let gt=0;class vt{constructor(e,t){this.mode=e,this.enabledFeatures=t,this.ended=null,this.baseLayer=null,this.id=++gt}}const wt=async function(e,t){if(t.webvr){let t=await async function(e){let t=null;if("getVRDisplays"in e.navigator)try{const i=await e.navigator.getVRDisplays();i&&i.length&&(t=new ft(e,i[0]))}catch(e){}return t}(e);if(t)return t}let i=(e=>{var t=!1;return Pe=e.navigator.userAgent||e.navigator.vendor||e.opera,(/(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(Pe)||/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(Pe.substr(0,4)))&&(t=!0),t})(e);return i&&t.cardboard||!i&&t.allowCardboardOnDesktop?(e.VRFrameData||(e.VRFrameData=function(){this.rightViewMatrix=new Float32Array(16),this.leftViewMatrix=new Float32Array(16),this.rightProjectionMatrix=new Float32Array(16),this.leftProjectionMatrix=new Float32Array(16),this.pose=null}),new class extends ft{constructor(e,t){const i=new Oe(t||{});super(e,i),this.display=i,this.frame={rightViewMatrix:new Float32Array(16),leftViewMatrix:new Float32Array(16),rightProjectionMatrix:new Float32Array(16),leftProjectionMatrix:new Float32Array(16),pose:null,timestamp:null}}}(e,t.cardboardConfig)):new class extends Ne{constructor(e){super(e),this.sessions=new Map,this.projectionMatrix=n(),this.identityMatrix=n()}onBaseLayerSet(e,t){this.sessions.get(e).baseLayer=t}isSessionSupported(e){return"inline"==e}isFeatureSupported(e){switch(e){case"viewer":return!0;default:return!1}}async requestSession(e,t){if(!this.isSessionSupported(e))return Promise.reject();const i=new vt(e,t);return this.sessions.set(i.id,i),Promise.resolve(i.id)}requestAnimationFrame(e){return window.requestAnimationFrame(e)}cancelAnimationFrame(e){window.cancelAnimationFrame(e)}onFrameStart(e,t){if(mt)return;const i=this.sessions.get(e);if(i.baseLayer){const e=i.baseLayer.context.canvas;d(this.projectionMatrix,t.inlineVerticalFieldOfView,e.width/e.height,t.depthNear,t.depthFar)}}onFrameEnd(e){}async endSession(e){this.sessions.get(e).ended=!0}doesSessionSupportReferenceSpace(e,t){const i=this.sessions.get(e);return!i.ended&&i.enabledFeatures.has(t)}requestStageBounds(){return null}async requestFrameOfReferenceTransform(e,t){return null}getProjectionMatrix(e){return this.projectionMatrix}getViewport(e,t,i,r){const{width:s,height:n}=i.context.canvas;return this.sessions.get(e),r.x=r.y=0,r.width=s,r.height=n,!0}getBasePoseMatrix(){return this.identityMatrix}getBaseViewMatrix(e){return this.identityMatrix}getInputSources(){return[]}getInputPose(e,t,i){return null}onWindowResize(){}}(e)},yt={global:e,webvr:!0,cardboard:!0,cardboardConfig:null,allowCardboardOnDesktop:!1},bt=["navigator","HTMLCanvasElement","WebGLRenderingContext"];return class{constructor(e={}){this.config=Object.freeze(Object.assign({},yt,e)),this.global=this.config.global,this.nativeWebXR="xr"in this.global.navigator,this.injected=!1,this.nativeWebXR?this._injectCompatibilityShims(this.global):this._injectPolyfill(this.global)}_injectPolyfill(e){if(!bt.every(t=>!!e[t]))throw new Error(`Global must have the following attributes : ${bt}`);for(const t of Object.keys(_e))void 0!==e[t]?console.warn(`${t} already defined on global.`):e[t]=_e[t];Fe(e.WebGLRenderingContext)&&(Re(e.HTMLCanvasElement),e.OffscreenCanvas&&Re(e.OffscreenCanvas),e.WebGL2RenderingContext&&Fe(e.WebGL2RenderingContext),window.isSecureContext||console.warn("WebXR Polyfill Warning:\nThis page is not running in a secure context (https:// or localhost)!\nThis means that although the page may be able to use the WebXR Polyfill it will\nnot be able to use native WebXR implementations, and as such will not be able to\naccess dedicated VR or AR hardware, and will not be able to take advantage of\nany performance improvements a native WebXR implementation may offer. Please\nhost this content on a secure origin for the best user experience.\n")),this.injected=!0,this._patchNavigatorXR()}_patchNavigatorXR(){let e=wt(this.global,this.config);this.xr=new _e.XRSystem(e),Object.defineProperty(this.global.navigator,"xr",{value:this.xr,configurable:!0})}_injectCompatibilityShims(e){if(!bt.every(t=>!!e[t]))throw new Error(`Global must have the following attributes : ${bt}`);if(e.navigator.xr&&"supportsSession"in e.navigator.xr&&!("isSessionSupported"in e.navigator.xr)){let t=e.navigator.xr.supportsSession;e.navigator.xr.isSessionSupported=function(e){return t.call(this,e).then(()=>!0).catch(()=>!1)},e.navigator.xr.supportsSession=function(e){return console.warn("navigator.xr.supportsSession() is deprecated. Please call navigator.xr.isSessionSupported() instead and check the boolean value returned when the promise resolves."),t.call(this,e)}}}}}); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.WebXRPolyfill=t()}(this,function(){"use strict";const e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t=Symbol("@@webxr-polyfill/EventTarget");class i{constructor(){this[t]={listeners:new Map}}addEventListener(e,i){if("string"!=typeof e)throw new Error("`type` must be a string");if("function"!=typeof i)throw new Error("`listener` must be a function");const r=this[t].listeners.get(e)||[];r.push(i),this[t].listeners.set(e,r)}removeEventListener(e,i){if("string"!=typeof e)throw new Error("`type` must be a string");if("function"!=typeof i)throw new Error("`listener` must be a function");const r=this[t].listeners.get(e)||[];for(let e=r.length;e>=0;e--)r[e]===i&&r.pop()}dispatchEvent(e,i){const r=this[t].listeners.get(e)||[],s=[];for(let e=0;e0?(r=2*Math.sqrt(i+1),e[3]=.25*r,e[0]=(t[6]-t[9])/r,e[1]=(t[8]-t[2])/r,e[2]=(t[1]-t[4])/r):t[0]>t[5]&&t[0]>t[10]?(r=2*Math.sqrt(1+t[0]-t[5]-t[10]),e[3]=(t[6]-t[9])/r,e[0]=.25*r,e[1]=(t[1]+t[4])/r,e[2]=(t[8]+t[2])/r):t[5]>t[10]?(r=2*Math.sqrt(1+t[5]-t[0]-t[10]),e[3]=(t[8]-t[2])/r,e[0]=(t[1]+t[4])/r,e[1]=.25*r,e[2]=(t[6]+t[9])/r):(r=2*Math.sqrt(1+t[10]-t[0]-t[5]),e[3]=(t[1]-t[4])/r,e[0]=(t[8]+t[2])/r,e[1]=(t[6]+t[9])/r,e[2]=.25*r),e}function d(e,t,i,r,s){let n,a=1/Math.tan(t/2);return e[0]=a/i,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=a,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,null!=s&&s!==1/0?(n=1/(r-s),e[10]=(s+r)*n,e[14]=2*s*r*n):(e[10]=-1,e[14]=-2*r),e}function u(){let e=new s(3);return s!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e}function p(e){var t=new s(3);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function f(e,t,i){let r=new s(3);return r[0]=e,r[1]=t,r[2]=i,r}function m(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function g(e,t,i){return e[0]=t[0]+i[0],e[1]=t[1]+i[1],e[2]=t[2]+i[2],e}function v(e,t,i){return e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e}function w(e,t){let i=t[0],r=t[1],s=t[2],n=i*i+r*r+s*s;return n>0&&(n=1/Math.sqrt(n),e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n),e}function y(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function b(e,t,i){let r=t[0],s=t[1],n=t[2],a=i[0],o=i[1],l=i[2];return e[0]=s*l-n*o,e[1]=n*a-r*l,e[2]=r*o-s*a,e}function E(e,t,i){let r=i[0],s=i[1],n=i[2],a=i[3],o=t[0],l=t[1],A=t[2],h=s*A-n*l,c=n*o-r*A,d=r*l-s*o,u=s*d-n*c,p=n*h-r*d,f=r*c-s*h,m=2*a;return h*=m,c*=m,d*=m,u*=2,p*=2,f*=2,e[0]=o+h+u,e[1]=l+c+p,e[2]=A+d+f,e}const S=function(e){let t=e[0],i=e[1],r=e[2];return Math.sqrt(t*t+i*i+r*r)};!function(){let e=u()}();!function(){let e=function(){let e=new s(4);return s!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0,e[3]=0),e}()}();function M(){let e=new s(4);return s!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e[3]=1,e}function x(e,t,i){let r=t[0],s=t[1],n=t[2],a=t[3],o=i[0],l=i[1],A=i[2],h=i[3];return e[0]=r*h+a*o+s*A-n*l,e[1]=s*h+a*l+n*o-r*A,e[2]=n*h+a*A+r*l-s*o,e[3]=a*h-r*o-s*l-n*A,e}function _(e,t,i,s){let n,a,o,l,A,h=t[0],c=t[1],d=t[2],u=t[3],p=i[0],f=i[1],m=i[2],g=i[3];return(a=h*p+c*f+d*m+u*g)<0&&(a=-a,p=-p,f=-f,m=-m,g=-g),1-a>r?(n=Math.acos(a),o=Math.sin(n),l=Math.sin((1-s)*n)/o,A=Math.sin(s*n)/o):(l=1-s,A=s),e[0]=l*h+A*p,e[1]=l*c+A*f,e[2]=l*d+A*m,e[3]=l*u+A*g,e}function F(e,t){let i=t[0],r=t[1],s=t[2],n=t[3],a=i*i+r*r+s*s+n*n,o=a?1/a:0;return e[0]=-i*o,e[1]=-r*o,e[2]=-s*o,e[3]=n*o,e}const R=function(e){let t=new s(4);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t},T=function(e,t,i,r){let n=new s(4);return n[0]=e,n[1]=t,n[2]=i,n[3]=r,n},P=function(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e},B=function(e,t){let i=t[0],r=t[1],s=t[2],n=t[3],a=i*i+r*r+s*s+n*n;return a>0&&(a=1/Math.sqrt(a),e[0]=i*a,e[1]=r*a,e[2]=s*a,e[3]=n*a),e},C=(function(){let e=u(),t=f(1,0,0),i=f(0,1,0)}(),function(){let e=M(),t=M()}(),function(){let e=function(){let e=new s(9);return s!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[5]=0,e[6]=0,e[7]=0),e[0]=1,e[4]=1,e[8]=1,e}()}(),Symbol("@@webxr-polyfill/XRRigidTransform"));class D{constructor(){if(this[C]={matrix:null,position:null,orientation:null,inverse:null},0===arguments.length)this[C].matrix=a(new Float32Array(16));else if(1===arguments.length)arguments[0]instanceof Float32Array?this[C].matrix=arguments[0]:(this[C].position=this._getPoint(arguments[0]),this[C].orientation=DOMPointReadOnly.fromPoint({x:0,y:0,z:0,w:1}));else{if(2!==arguments.length)throw new Error("Too many arguments!");this[C].position=this._getPoint(arguments[0]),this[C].orientation=this._getPoint(arguments[1])}if(this[C].matrix){let e=u();h(e,this[C].matrix),this[C].position=DOMPointReadOnly.fromPoint({x:e[0],y:e[1],z:e[2]});let t=M();c(t,this[C].matrix),this[C].orientation=DOMPointReadOnly.fromPoint({x:t[0],y:t[1],z:t[2],w:t[3]})}else this[C].matrix=a(new Float32Array(16)),A(this[C].matrix,T(this[C].orientation.x,this[C].orientation.y,this[C].orientation.z,this[C].orientation.w),f(this[C].position.x,this[C].position.y,this[C].position.z))}_getPoint(e){return e instanceof DOMPointReadOnly?e:DOMPointReadOnly.fromPoint(e)}get matrix(){return this[C].matrix}get position(){return this[C].position}get orientation(){return this[C].orientation}get inverse(){if(null===this[C].inverse){let e=a(new Float32Array(16));o(e,this[C].matrix),this[C].inverse=new D(e),this[C].inverse[C].inverse=this}return this[C].inverse}}const I=Symbol("@@webxr-polyfill/XRSpace");class L{constructor(e=null,t=null){this[I]={specialType:e,inputSource:t,baseMatrix:null,inverseBaseMatrix:null,lastFrameId:-1}}get _specialType(){return this[I].specialType}get _inputSource(){return this[I].inputSource}_ensurePoseUpdated(e,t){t!=this[I].lastFrameId&&(this[I].lastFrameId=t,this._onPoseUpdate(e))}_onPoseUpdate(e){"viewer"==this[I].specialType&&(this._baseMatrix=e.getBasePoseMatrix())}set _baseMatrix(e){this[I].baseMatrix=e,this[I].inverseBaseMatrix=null}get _baseMatrix(){return this[I].baseMatrix||this[I].inverseBaseMatrix&&(this[I].baseMatrix=new Float32Array(16),o(this[I].baseMatrix,this[I].inverseBaseMatrix)),this[I].baseMatrix}set _inverseBaseMatrix(e){this[I].inverseBaseMatrix=e,this[I].baseMatrix=null}get _inverseBaseMatrix(){return this[I].inverseBaseMatrix||this[I].baseMatrix&&(this[I].inverseBaseMatrix=new Float32Array(16),o(this[I].inverseBaseMatrix,this[I].baseMatrix)),this[I].inverseBaseMatrix}_getSpaceRelativeTransform(e){if(!this._inverseBaseMatrix||!e._baseMatrix)return null;let t=new Float32Array(16);return l(t,this._inverseBaseMatrix,e._baseMatrix),new D(t)}}const O=1.6,N=Symbol("@@webxr-polyfill/XRReferenceSpace"),G=["viewer","local","local-floor","bounded-floor","unbounded"];class Q extends L{constructor(e,t=null){if(!G.includes(e))throw new Error(`XRReferenceSpaceType must be one of ${G}`);if(super(e),"bounded-floor"===e&&!t)throw new Error("XRReferenceSpace cannot use 'bounded-floor' type if the platform does not provide the floor level");(function(e){return"bounded-floor"===e||"local-floor"===e})(e)&&!t&&((t=a(new Float32Array(16)))[13]=O),this._inverseBaseMatrix=t||a(new Float32Array(16)),this[N]={type:e,transform:t,originOffset:a(new Float32Array(16))}}_transformBasePoseMatrix(e,t){l(e,this._inverseBaseMatrix,t)}_originOffsetMatrix(){return this[N].originOffset}_adjustForOriginOffset(e){let t=new Float32Array(16);o(t,this[N].originOffset),l(e,t,e)}_getSpaceRelativeTransform(e){let t=super._getSpaceRelativeTransform(e);return this._adjustForOriginOffset(t.matrix),new XRRigidTransform(t.matrix)}getOffsetReferenceSpace(e){let t=new Q(this[N].type,this[N].transform,this[N].bounds);return l(t[N].originOffset,this[N].originOffset,e.matrix),t}}const k=Symbol("@@webxr-polyfill/XR"),z=["inline","immersive-vr","immersive-ar"],V={inline:{requiredFeatures:["viewer"],optionalFeatures:[]},"immersive-vr":{requiredFeatures:["viewer","local"],optionalFeatures:[]},"immersive-ar":{requiredFeatures:["viewer","local"],optionalFeatures:[]}},U="Polyfill Error: Must call navigator.xr.isSessionSupported() with any XRSessionMode\nor navigator.xr.requestSession('inline') prior to requesting an immersive\nsession. This is a limitation specific to the WebXR Polyfill and does not apply\nto native implementations of the API.";let H;if("performance"in e==!1){let e=Date.now();H=(()=>Date.now()-e)}else H=(()=>performance.now());var X=H;const W=Symbol("@@webxr-polyfill/XRPose");class j{constructor(e,t){this[W]={transform:e,emulatedPosition:t}}get transform(){return this[W].transform}get emulatedPosition(){return this[W].emulatedPosition}}const q=Symbol("@@webxr-polyfill/XRViewerPose");class Y extends j{constructor(e,t,i=!1){super(e,i),this[q]={views:t}}get views(){return this[q].views}}const Z=Symbol("@@webxr-polyfill/XRViewport");class J{constructor(e){this[Z]={target:e}}get x(){return this[Z].target.x}get y(){return this[Z].target.y}get width(){return this[Z].target.width}get height(){return this[Z].target.height}}const K=["left","right","none"],$=Symbol("@@webxr-polyfill/XRView");class ee{constructor(e,t,i,r,s){if(!K.includes(i))throw new Error(`XREye must be one of: ${K}`);const n=Object.create(null),a=new J(n);this[$]={device:e,eye:i,viewport:a,temp:n,sessionId:r,transform:t,viewIndex:s}}get eye(){return this[$].eye}get projectionMatrix(){return this[$].device.getProjectionMatrix(this.eye,this[$].viewIndex)}get transform(){return this[$].transform}_getViewport(e){if(this[$].device.getViewport(this[$].sessionId,this.eye,e,this[$].temp,this[$].viewIndex))return this[$].viewport}}const te=Symbol("@@webxr-polyfill/XRFrame"),ie="XRFrame access outside the callback that produced it is invalid.",re="getViewerPose can only be called on XRFrame objects passed to XRSession.requestAnimationFrame callbacks.";let se=0;class ne{constructor(e,t,i){this[te]={id:++se,active:!1,animationFrame:!1,device:e,session:t,sessionId:i}}get session(){return this[te].session}getViewerPose(e){if(!this[te].animationFrame)throw new DOMException(re,"InvalidStateError");if(!this[te].active)throw new DOMException(ie,"InvalidStateError");const t=this[te].device,i=this[te].session;i[fe].viewerSpace._ensurePoseUpdated(t,this[te].id),e._ensurePoseUpdated(t,this[te].id);let r=e._getSpaceRelativeTransform(i[fe].viewerSpace);const s=[];for(const r of i[fe].viewSpaces){r._ensurePoseUpdated(t,this[te].id);let i=e._getSpaceRelativeTransform(r),n=new ee(t,i,r.eye,this[te].sessionId,r.viewIndex);s.push(n)}return new Y(r,s,!1)}getPose(e,t){if(!this[te].active)throw new DOMException(ie,"InvalidStateError");const i=this[te].device;if("target-ray"===e._specialType||"grip"===e._specialType)return i.getInputPose(e._inputSource,t,e._specialType);{e._ensurePoseUpdated(i,this[te].id),t._ensurePoseUpdated(i,this[te].id);let r=t._getSpaceRelativeTransform(e);return r?new XRPose(r,!1):null}}}const ae=Symbol("@@webxr-polyfill/XRRenderState"),oe=Object.freeze({depthNear:.1,depthFar:1e3,inlineVerticalFieldOfView:null,baseLayer:null});class le{constructor(e={}){const t=Object.assign({},oe,e);this[ae]={config:t}}get depthNear(){return this[ae].config.depthNear}get depthFar(){return this[ae].config.depthFar}get inlineVerticalFieldOfView(){return this[ae].config.inlineVerticalFieldOfView}get baseLayer(){return this[ae].config.baseLayer}}const Ae=Symbol("@@webxr-polyfill/XRInputSourceEvent");class he extends Event{constructor(e,t){super(e,t),this[Ae]={frame:t.frame,inputSource:t.inputSource},Object.setPrototypeOf(this,he.prototype)}get frame(){return this[Ae].frame}get inputSource(){return this[Ae].inputSource}}const ce=Symbol("@@webxr-polyfill/XRSessionEvent");class de extends Event{constructor(e,t){super(e,t),this[ce]={session:t.session},Object.setPrototypeOf(this,de.prototype)}get session(){return this[ce].session}}const ue=Symbol("@@webxr-polyfill/XRInputSourcesChangeEvent");class pe extends Event{constructor(e,t){super(e,t),this[ue]={session:t.session,added:t.added,removed:t.removed},Object.setPrototypeOf(this,pe.prototype)}get session(){return this[ue].session}get added(){return this[ue].added}get removed(){return this[ue].removed}}const fe=Symbol("@@webxr-polyfill/XRSession");class me extends L{constructor(e){super(e)}get eye(){return this._specialType}_onPoseUpdate(e){this._inverseBaseMatrix=e.getBaseViewMatrix(this._specialType)}}class ge extends i{constructor(e,t,i){super();let r="inline"!=t,s=new le({inlineVerticalFieldOfView:r?null:.5*Math.PI});const n=r?[new me("left"),new me("right")]:[new me("none")];Object.freeze(n),this[fe]={device:e,mode:t,immersive:r,ended:!1,suspended:!1,frameCallbacks:[],currentFrameCallbacks:null,frameHandle:0,deviceFrameHandle:null,id:i,activeRenderState:s,pendingRenderState:null,viewerSpace:new Q("viewer"),get viewSpaces(){return e.getViewSpaces(t)||n},currentInputSources:[]},this[fe].onDeviceFrame=(()=>{if(this[fe].ended||this[fe].suspended)return;if(this[fe].deviceFrameHandle=null,this[fe].startDeviceFrameLoop(),null!==this[fe].pendingRenderState&&(this[fe].activeRenderState=new le(this[fe].pendingRenderState),this[fe].pendingRenderState=null,this[fe].activeRenderState.baseLayer&&this[fe].device.onBaseLayerSet(this[fe].id,this[fe].activeRenderState.baseLayer)),null===this[fe].activeRenderState.baseLayer)return;const t=new ne(e,this,this[fe].id),i=this[fe].currentFrameCallbacks=this[fe].frameCallbacks;this[fe].frameCallbacks=[],t[te].active=!0,t[te].animationFrame=!0,this[fe].device.onFrameStart(this[fe].id,this[fe].activeRenderState),this._checkInputSourcesChange();const r=X();for(let e=0;e{null===this[fe].deviceFrameHandle&&(this[fe].deviceFrameHandle=this[fe].device.requestAnimationFrame(this[fe].onDeviceFrame))}),this[fe].stopDeviceFrameLoop=(()=>{const e=this[fe].deviceFrameHandle;null!==e&&(this[fe].device.cancelAnimationFrame(e),this[fe].deviceFrameHandle=null)}),this[fe].onPresentationEnd=(t=>{if(t!==this[fe].id)return this[fe].suspended=!1,this[fe].startDeviceFrameLoop(),void this.dispatchEvent("focus",{session:this});this[fe].ended=!0,this[fe].stopDeviceFrameLoop(),e.removeEventListener("@@webxr-polyfill/vr-present-end",this[fe].onPresentationEnd),e.removeEventListener("@@webxr-polyfill/vr-present-start",this[fe].onPresentationStart),e.removeEventListener("@@webxr-polyfill/input-select-start",this[fe].onSelectStart),e.removeEventListener("@@webxr-polyfill/input-select-end",this[fe].onSelectEnd),this.dispatchEvent("end",new de("end",{session:this}))}),e.addEventListener("@@webxr-polyfill/vr-present-end",this[fe].onPresentationEnd),this[fe].onPresentationStart=(e=>{e!==this[fe].id&&(this[fe].suspended=!0,this[fe].stopDeviceFrameLoop(),this.dispatchEvent("blur",{session:this}))}),e.addEventListener("@@webxr-polyfill/vr-present-start",this[fe].onPresentationStart),this[fe].onSelectStart=(e=>{e.sessionId===this[fe].id&&this[fe].dispatchInputSourceEvent("selectstart",e.inputSource)}),e.addEventListener("@@webxr-polyfill/input-select-start",this[fe].onSelectStart),this[fe].onSelectEnd=(e=>{e.sessionId===this[fe].id&&(this[fe].dispatchInputSourceEvent("select",e.inputSource),this[fe].dispatchInputSourceEvent("selectend",e.inputSource))}),e.addEventListener("@@webxr-polyfill/input-select-end",this[fe].onSelectEnd),this[fe].onSqueezeStart=(e=>{e.sessionId===this[fe].id&&this[fe].dispatchInputSourceEvent("squeezestart",e.inputSource)}),e.addEventListener("@@webxr-polyfill/input-squeeze-start",this[fe].onSqueezeStart),this[fe].onSqueezeEnd=(e=>{e.sessionId===this[fe].id&&(this[fe].dispatchInputSourceEvent("squeezeend",e.inputSource),this[fe].dispatchInputSourceEvent("squeeze",e.inputSource))}),e.addEventListener("@@webxr-polyfill/input-squeeze-end",this[fe].onSqueezeEnd),this[fe].dispatchInputSourceEvent=((t,i)=>{const r=new ne(e,this,this[fe].id),s=new he(t,{frame:r,inputSource:i});r[te].active=!0,this.dispatchEvent(t,s),r[te].active=!1}),this[fe].startDeviceFrameLoop(),this.onblur=void 0,this.onfocus=void 0,this.onresetpose=void 0,this.onend=void 0,this.onselect=void 0,this.onselectstart=void 0,this.onselectend=void 0}get renderState(){return this[fe].activeRenderState}get environmentBlendMode(){return this[fe].device.environmentBlendMode||"opaque"}async requestReferenceSpace(e){if(this[fe].ended)return;if(!G.includes(e))throw new TypeError(`XRReferenceSpaceType must be one of ${G}`);if(!this[fe].device.doesSessionSupportReferenceSpace(this[fe].id,e))throw new DOMException(`The ${e} reference space is not supported by this session.`,"NotSupportedError");if("viewer"===e)return this[fe].viewerSpace;let t=await this[fe].device.requestFrameOfReferenceTransform(e);if("bounded-floor"===e){if(!t)throw new DOMException(`${e} XRReferenceSpace not supported by this device.`,"NotSupportedError");if(!this[fe].device.requestStageBounds())throw new DOMException(`${e} XRReferenceSpace not supported by this device.`,"NotSupportedError");throw new DOMException(`The WebXR polyfill does not support the ${e} reference space yet.`,"NotSupportedError")}return new Q(e,t)}requestAnimationFrame(e){if(this[fe].ended)return;const t=++this[fe].frameHandle;return this[fe].frameCallbacks.push({handle:t,callback:e,cancelled:!1}),t}cancelAnimationFrame(e){let t=this[fe].frameCallbacks,i=t.findIndex(t=>t&&t.handle===e);i>-1&&(t[i].cancelled=!0,t.splice(i,1)),(t=this[fe].currentFrameCallbacks)&&(i=t.findIndex(t=>t&&t.handle===e))>-1&&(t[i].cancelled=!0)}get inputSources(){return this[fe].device.getInputSources()}async end(){if(!this[fe].ended)return this[fe].immersive&&(this[fe].ended=!0,this[fe].device.removeEventListener("@@webxr-polyfill/vr-present-start",this[fe].onPresentationStart),this[fe].device.removeEventListener("@@webxr-polyfill/vr-present-end",this[fe].onPresentationEnd),this[fe].device.removeEventListener("@@webxr-polyfill/input-select-start",this[fe].onSelectStart),this[fe].device.removeEventListener("@@webxr-polyfill/input-select-end",this[fe].onSelectEnd),this.dispatchEvent("end",new de("end",{session:this}))),this[fe].stopDeviceFrameLoop(),this[fe].device.endSession(this[fe].id)}updateRenderState(e){if(this[fe].ended){throw new Error("Can't call updateRenderState on an XRSession that has already ended.")}if(e.baseLayer&&e.baseLayer._session!==this){throw new Error("Called updateRenderState with a base layer that was created by a different session.")}if(null!==e.inlineVerticalFieldOfView&&void 0!==e.inlineVerticalFieldOfView){if(this[fe].immersive){throw new Error("inlineVerticalFieldOfView must not be set for an XRRenderState passed to updateRenderState for an immersive session.")}e.inlineVerticalFieldOfView=Math.min(3.13,Math.max(.01,e.inlineVerticalFieldOfView))}if(null===this[fe].pendingRenderState){const e=this[fe].activeRenderState;this[fe].pendingRenderState={depthNear:e.depthNear,depthFar:e.depthFar,inlineVerticalFieldOfView:e.inlineVerticalFieldOfView,baseLayer:e.baseLayer}}Object.assign(this[fe].pendingRenderState,e)}_checkInputSourcesChange(){const e=[],t=[],i=this.inputSources,r=this[fe].currentInputSources;for(const t of i)r.includes(t)||e.push(t);for(const e of r)i.includes(e)||t.push(e);(e.length>0||t.length>0)&&this.dispatchEvent("inputsourceschange",new pe("inputsourceschange",{session:this,added:e,removed:t})),this[fe].currentInputSources.length=0;for(const e of i)this[fe].currentInputSources.push(e)}}const ve=Symbol("@@webxr-polyfill/XRInputSource");class we{constructor(e){this[ve]={impl:e,gripSpace:new L("grip",this),targetRaySpace:new L("target-ray",this)}}get handedness(){return this[ve].impl.handedness}get targetRayMode(){return this[ve].impl.targetRayMode}get gripSpace(){let e=this[ve].impl.targetRayMode;return"gaze"===e||"screen"===e?null:this[ve].gripSpace}get targetRaySpace(){return this[ve].targetRaySpace}get profiles(){return this[ve].impl.profiles}get gamepad(){return this[ve].impl.gamepad}}const ye=Symbol("@@webxr-polyfill/polyfilled-xr-compatible"),be=Symbol("@@webxr-polyfill/xr-compatible"),Ee=Symbol("@@webxr-polyfill/XRWebGLLayer"),Se=Object.freeze({antialias:!0,depth:!0,stencil:!1,alpha:!0,multiview:!1,ignoreDepthValues:!1,framebufferScaleFactor:1});const Me=Symbol("@@webxr-polyfill/XRReferenceSpaceEvent");class xe extends Event{constructor(e,t){super(e,t),this[Me]={referenceSpace:t.referenceSpace,transform:t.transform||null},Object.setPrototypeOf(this,xe.prototype)}get referenceSpace(){return this[Me].referenceSpace}get transform(){return this[Me].transform}}var _e={XRSystem:class extends i{constructor(e){super(),this[k]={device:null,devicePromise:e,immersiveSession:null,inlineSessions:new Set},e.then(e=>{this[k].device=e})}async isSessionSupported(e){return this[k].device||await this[k].devicePromise,"inline"!=e?Promise.resolve(this[k].device.isSessionSupported(e)):Promise.resolve(!0)}async requestSession(e,t){if(!this[k].device){if("inline"!=e)throw new Error(U);await this[k].devicePromise}if(!z.includes(e))throw new TypeError(`The provided value '${e}' is not a valid enum value of type XRSessionMode`);const i=V[e],r=i.requiredFeatures.concat(t&&t.requiredFeatures?t.requiredFeatures:[]),s=i.optionalFeatures.concat(t&&t.optionalFeatures?t.optionalFeatures:[]),n=new Set;let a=!1;for(let e of r)this[k].device.isFeatureSupported(e)?n.add(e):(console.error(`The required feature '${e}' is not supported`),a=!0);if(a)throw new DOMException("Session does not support some required features","NotSupportedError");for(let e of s)this[k].device.isFeatureSupported(e)?n.add(e):console.log(`The optional feature '${e}' is not supported`);const o=await this[k].device.requestSession(e,n),l=new XRSession(this[k].device,e,o);"inline"==e?this[k].inlineSessions.add(l):this[k].immersiveSession=l;const A=()=>{"inline"==e?this[k].inlineSessions.delete(l):this[k].immersiveSession=null,l.removeEventListener("end",A)};return l.addEventListener("end",A),l}},XRSession:ge,XRSessionEvent:de,XRFrame:ne,XRView:ee,XRViewport:J,XRViewerPose:Y,XRWebGLLayer:class{constructor(e,t,i={}){const r=Object.assign({},Se,i);if(!(e instanceof ge))throw new Error("session must be a XRSession");if(e.ended)throw new Error("InvalidStateError");if(t[ye]&&!0!==t[be])throw new Error("InvalidStateError");this[Ee]={context:t,config:r,session:e}}get context(){return this[Ee].context}get antialias(){return this[Ee].config.antialias}get ignoreDepthValues(){return!0}get framebuffer(){return null}get framebufferWidth(){return this[Ee].context.drawingBufferWidth}get framebufferHeight(){return this[Ee].context.drawingBufferHeight}get _session(){return this[Ee].session}getViewport(e){return e._getViewport(this)}static getNativeFramebufferScaleFactor(e){if(!e)throw new TypeError("getNativeFramebufferScaleFactor must be passed a session.");return e[fe].ended?0:1}},XRSpace:L,XRReferenceSpace:Q,XRReferenceSpaceEvent:xe,XRInputSource:we,XRInputSourceEvent:he,XRInputSourcesChangeEvent:pe,XRRenderState:le,XRRigidTransform:D,XRPose:j};const Fe=e=>"function"!=typeof e.prototype.makeXRCompatible&&(e.prototype.makeXRCompatible=function(){return this[be]=!0,Promise.resolve()},!0),Re=e=>{const t=e.prototype.getContext;e.prototype.getContext=function(e,i){const r=t.call(this,e,i);return r&&(r[ye]=!0,i&&"xrCompatible"in i&&(r[be]=i.xrCompatible)),r}},Te=e=>!(!e.ImageBitmapRenderingContext||!e.createImageBitmap);var Pe;const Be=e=>{e.style.display="block",e.style.position="absolute",e.style.width=e.style.height="1px",e.style.top=e.style.left="0px"};var Ce="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var De,Ie,Le=(function(e,t){e.exports=function(){var e,t,i,r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=function(){function e(e,t){for(var i=0;ie.TEXTURE31){console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit"),r.push(null,null);break}s||(s=e.getParameter(e.ACTIVE_TEXTURE)),e.activeTexture(o),r.push(e.getParameter(a),null);break;case e.ACTIVE_TEXTURE:s=e.getParameter(e.ACTIVE_TEXTURE),r.push(null);break;default:r.push(e.getParameter(a))}}i(e);for(var n=0;ne.TEXTURE31)break;e.activeTexture(o),e.bindTexture(e.TEXTURE_2D,l);break;case e.TEXTURE_BINDING_CUBE_MAP:var o=t[++n];if(oe.TEXTURE31)break;e.activeTexture(o),e.bindTexture(e.TEXTURE_CUBE_MAP,l);break;case e.VIEWPORT:e.viewport(l[0],l[1],l[2],l[3]);break;case e.BLEND:case e.CULL_FACE:case e.DEPTH_TEST:case e.SCISSOR_TEST:case e.STENCIL_TEST:l?e.enable(a):e.disable(a);break;default:console.log("No GL restore behavior for 0x"+a.toString(16))}s&&e.activeTexture(s)}}else i(e)},T=["attribute vec2 position;","attribute vec3 texCoord;","varying vec2 vTexCoord;","uniform vec4 viewportOffsetScale[2];","void main() {"," vec4 viewport = viewportOffsetScale[int(texCoord.z)];"," vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;"," gl_Position = vec4( position, 1.0, 1.0 );","}"].join("\n"),P=["precision mediump float;","uniform sampler2D diffuse;","varying vec2 vTexCoord;","void main() {"," gl_FragColor = texture2D(diffuse, vTexCoord);","}"].join("\n");function B(e,t,i,r){this.gl=e,this.cardboardUI=t,this.bufferScale=i,this.dirtySubmitFrameBindings=r,this.ctxAttribs=e.getContextAttributes(),this.instanceExt=e.getExtension("ANGLE_instanced_arrays"),this.meshWidth=20,this.meshHeight=20,this.bufferWidth=e.drawingBufferWidth,this.bufferHeight=e.drawingBufferHeight,this.realBindFramebuffer=e.bindFramebuffer,this.realEnable=e.enable,this.realDisable=e.disable,this.realColorMask=e.colorMask,this.realClearColor=e.clearColor,this.realViewport=e.viewport,o()||(this.realCanvasWidth=Object.getOwnPropertyDescriptor(e.canvas.__proto__,"width"),this.realCanvasHeight=Object.getOwnPropertyDescriptor(e.canvas.__proto__,"height")),this.isPatched=!1,this.lastBoundFramebuffer=null,this.cullFace=!1,this.depthTest=!1,this.blend=!1,this.scissorTest=!1,this.stencilTest=!1,this.viewport=[0,0,0,0],this.colorMask=[!0,!0,!0,!0],this.clearColor=[0,0,0,0],this.attribs={position:0,texCoord:1},this.program=w(e,T,P,this.attribs),this.uniforms=y(e,this.program),this.viewportOffsetScale=new Float32Array(8),this.setTextureBounds(),this.vertexBuffer=e.createBuffer(),this.indexBuffer=e.createBuffer(),this.indexCount=0,this.renderTarget=e.createTexture(),this.framebuffer=e.createFramebuffer(),this.depthStencilBuffer=null,this.depthBuffer=null,this.stencilBuffer=null,this.ctxAttribs.depth&&this.ctxAttribs.stencil?this.depthStencilBuffer=e.createRenderbuffer():this.ctxAttribs.depth?this.depthBuffer=e.createRenderbuffer():this.ctxAttribs.stencil&&(this.stencilBuffer=e.createRenderbuffer()),this.patch(),this.onResize()}B.prototype.destroy=function(){var e=this.gl;this.unpatch(),e.deleteProgram(this.program),e.deleteBuffer(this.vertexBuffer),e.deleteBuffer(this.indexBuffer),e.deleteTexture(this.renderTarget),e.deleteFramebuffer(this.framebuffer),this.depthStencilBuffer&&e.deleteRenderbuffer(this.depthStencilBuffer),this.depthBuffer&&e.deleteRenderbuffer(this.depthBuffer),this.stencilBuffer&&e.deleteRenderbuffer(this.stencilBuffer),this.cardboardUI&&this.cardboardUI.destroy()},B.prototype.onResize=function(){var e=this.gl,t=this,i=[e.RENDERBUFFER_BINDING,e.TEXTURE_BINDING_2D,e.TEXTURE0];R(e,i,function(e){t.realBindFramebuffer.call(e,e.FRAMEBUFFER,null),t.scissorTest&&t.realDisable.call(e,e.SCISSOR_TEST),t.realColorMask.call(e,!0,!0,!0,!0),t.realViewport.call(e,0,0,e.drawingBufferWidth,e.drawingBufferHeight),t.realClearColor.call(e,0,0,0,1),e.clear(e.COLOR_BUFFER_BIT),t.realBindFramebuffer.call(e,e.FRAMEBUFFER,t.framebuffer),e.bindTexture(e.TEXTURE_2D,t.renderTarget),e.texImage2D(e.TEXTURE_2D,0,t.ctxAttribs.alpha?e.RGBA:e.RGB,t.bufferWidth,t.bufferHeight,0,t.ctxAttribs.alpha?e.RGBA:e.RGB,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.renderTarget,0),t.ctxAttribs.depth&&t.ctxAttribs.stencil?(e.bindRenderbuffer(e.RENDERBUFFER,t.depthStencilBuffer),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,t.bufferWidth,t.bufferHeight),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t.depthStencilBuffer)):t.ctxAttribs.depth?(e.bindRenderbuffer(e.RENDERBUFFER,t.depthBuffer),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,t.bufferWidth,t.bufferHeight),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t.depthBuffer)):t.ctxAttribs.stencil&&(e.bindRenderbuffer(e.RENDERBUFFER,t.stencilBuffer),e.renderbufferStorage(e.RENDERBUFFER,e.STENCIL_INDEX8,t.bufferWidth,t.bufferHeight),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.STENCIL_ATTACHMENT,e.RENDERBUFFER,t.stencilBuffer)),!e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE&&console.error("Framebuffer incomplete!"),t.realBindFramebuffer.call(e,e.FRAMEBUFFER,t.lastBoundFramebuffer),t.scissorTest&&t.realEnable.call(e,e.SCISSOR_TEST),t.realColorMask.apply(e,t.colorMask),t.realViewport.apply(e,t.viewport),t.realClearColor.apply(e,t.clearColor)}),this.cardboardUI&&this.cardboardUI.onResize()},B.prototype.patch=function(){if(!this.isPatched){var e=this,t=this.gl.canvas,i=this.gl;o()||(t.width=m()*this.bufferScale,t.height=g()*this.bufferScale,Object.defineProperty(t,"width",{configurable:!0,enumerable:!0,get:function(){return e.bufferWidth},set:function(i){e.bufferWidth=i,e.realCanvasWidth.set.call(t,i),e.onResize()}}),Object.defineProperty(t,"height",{configurable:!0,enumerable:!0,get:function(){return e.bufferHeight},set:function(i){e.bufferHeight=i,e.realCanvasHeight.set.call(t,i),e.onResize()}})),this.lastBoundFramebuffer=i.getParameter(i.FRAMEBUFFER_BINDING),null==this.lastBoundFramebuffer&&(this.lastBoundFramebuffer=this.framebuffer,this.gl.bindFramebuffer(i.FRAMEBUFFER,this.framebuffer)),this.gl.bindFramebuffer=function(t,r){e.lastBoundFramebuffer=r||e.framebuffer,e.realBindFramebuffer.call(i,t,e.lastBoundFramebuffer)},this.cullFace=i.getParameter(i.CULL_FACE),this.depthTest=i.getParameter(i.DEPTH_TEST),this.blend=i.getParameter(i.BLEND),this.scissorTest=i.getParameter(i.SCISSOR_TEST),this.stencilTest=i.getParameter(i.STENCIL_TEST),i.enable=function(t){switch(t){case i.CULL_FACE:e.cullFace=!0;break;case i.DEPTH_TEST:e.depthTest=!0;break;case i.BLEND:e.blend=!0;break;case i.SCISSOR_TEST:e.scissorTest=!0;break;case i.STENCIL_TEST:e.stencilTest=!0}e.realEnable.call(i,t)},i.disable=function(t){switch(t){case i.CULL_FACE:e.cullFace=!1;break;case i.DEPTH_TEST:e.depthTest=!1;break;case i.BLEND:e.blend=!1;break;case i.SCISSOR_TEST:e.scissorTest=!1;break;case i.STENCIL_TEST:e.stencilTest=!1}e.realDisable.call(i,t)},this.colorMask=i.getParameter(i.COLOR_WRITEMASK),i.colorMask=function(t,r,s,n){e.colorMask[0]=t,e.colorMask[1]=r,e.colorMask[2]=s,e.colorMask[3]=n,e.realColorMask.call(i,t,r,s,n)},this.clearColor=i.getParameter(i.COLOR_CLEAR_VALUE),i.clearColor=function(t,r,s,n){e.clearColor[0]=t,e.clearColor[1]=r,e.clearColor[2]=s,e.clearColor[3]=n,e.realClearColor.call(i,t,r,s,n)},this.viewport=i.getParameter(i.VIEWPORT),i.viewport=function(t,r,s,n){e.viewport[0]=t,e.viewport[1]=r,e.viewport[2]=s,e.viewport[3]=n,e.realViewport.call(i,t,r,s,n)},this.isPatched=!0,S(t)}},B.prototype.unpatch=function(){if(this.isPatched){var e=this.gl,t=this.gl.canvas;o()||(Object.defineProperty(t,"width",this.realCanvasWidth),Object.defineProperty(t,"height",this.realCanvasHeight)),t.width=this.bufferWidth,t.height=this.bufferHeight,e.bindFramebuffer=this.realBindFramebuffer,e.enable=this.realEnable,e.disable=this.realDisable,e.colorMask=this.realColorMask,e.clearColor=this.realClearColor,e.viewport=this.realViewport,this.lastBoundFramebuffer==this.framebuffer&&e.bindFramebuffer(e.FRAMEBUFFER,null),this.isPatched=!1,setTimeout(function(){S(t)},1)}},B.prototype.setTextureBounds=function(e,t){e||(e=[0,0,.5,1]),t||(t=[.5,0,.5,1]),this.viewportOffsetScale[0]=e[0],this.viewportOffsetScale[1]=e[1],this.viewportOffsetScale[2]=e[2],this.viewportOffsetScale[3]=e[3],this.viewportOffsetScale[4]=t[0],this.viewportOffsetScale[5]=t[1],this.viewportOffsetScale[6]=t[2],this.viewportOffsetScale[7]=t[3]},B.prototype.submitFrame=function(){var e=this.gl,t=this,i=[];if(this.dirtySubmitFrameBindings||i.push(e.CURRENT_PROGRAM,e.ARRAY_BUFFER_BINDING,e.ELEMENT_ARRAY_BUFFER_BINDING,e.TEXTURE_BINDING_2D,e.TEXTURE0),R(e,i,function(e){t.realBindFramebuffer.call(e,e.FRAMEBUFFER,null);var i=0,r=0;t.instanceExt&&(i=e.getVertexAttrib(t.attribs.position,t.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE),r=e.getVertexAttrib(t.attribs.texCoord,t.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE)),t.cullFace&&t.realDisable.call(e,e.CULL_FACE),t.depthTest&&t.realDisable.call(e,e.DEPTH_TEST),t.blend&&t.realDisable.call(e,e.BLEND),t.scissorTest&&t.realDisable.call(e,e.SCISSOR_TEST),t.stencilTest&&t.realDisable.call(e,e.STENCIL_TEST),t.realColorMask.call(e,!0,!0,!0,!0),t.realViewport.call(e,0,0,e.drawingBufferWidth,e.drawingBufferHeight),(t.ctxAttribs.alpha||o())&&(t.realClearColor.call(e,0,0,0,1),e.clear(e.COLOR_BUFFER_BIT)),e.useProgram(t.program),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.indexBuffer),e.bindBuffer(e.ARRAY_BUFFER,t.vertexBuffer),e.enableVertexAttribArray(t.attribs.position),e.enableVertexAttribArray(t.attribs.texCoord),e.vertexAttribPointer(t.attribs.position,2,e.FLOAT,!1,20,0),e.vertexAttribPointer(t.attribs.texCoord,3,e.FLOAT,!1,20,8),t.instanceExt&&(0!=i&&t.instanceExt.vertexAttribDivisorANGLE(t.attribs.position,0),0!=r&&t.instanceExt.vertexAttribDivisorANGLE(t.attribs.texCoord,0)),e.activeTexture(e.TEXTURE0),e.uniform1i(t.uniforms.diffuse,0),e.bindTexture(e.TEXTURE_2D,t.renderTarget),e.uniform4fv(t.uniforms.viewportOffsetScale,t.viewportOffsetScale),e.drawElements(e.TRIANGLES,t.indexCount,e.UNSIGNED_SHORT,0),t.cardboardUI&&t.cardboardUI.renderNoState(),t.realBindFramebuffer.call(t.gl,e.FRAMEBUFFER,t.framebuffer),t.ctxAttribs.preserveDrawingBuffer||(t.realClearColor.call(e,0,0,0,0),e.clear(e.COLOR_BUFFER_BIT)),t.dirtySubmitFrameBindings||t.realBindFramebuffer.call(e,e.FRAMEBUFFER,t.lastBoundFramebuffer),t.cullFace&&t.realEnable.call(e,e.CULL_FACE),t.depthTest&&t.realEnable.call(e,e.DEPTH_TEST),t.blend&&t.realEnable.call(e,e.BLEND),t.scissorTest&&t.realEnable.call(e,e.SCISSOR_TEST),t.stencilTest&&t.realEnable.call(e,e.STENCIL_TEST),t.realColorMask.apply(e,t.colorMask),t.realViewport.apply(e,t.viewport),!t.ctxAttribs.alpha&&t.ctxAttribs.preserveDrawingBuffer||t.realClearColor.apply(e,t.clearColor),t.instanceExt&&(0!=i&&t.instanceExt.vertexAttribDivisorANGLE(t.attribs.position,i),0!=r&&t.instanceExt.vertexAttribDivisorANGLE(t.attribs.texCoord,r))}),o()){var r=e.canvas;r.width==t.bufferWidth&&r.height==t.bufferHeight||(t.bufferWidth=r.width,t.bufferHeight=r.height,t.onResize())}},B.prototype.updateDeviceInfo=function(e){var t=this.gl,i=this,r=[t.ARRAY_BUFFER_BINDING,t.ELEMENT_ARRAY_BUFFER_BINDING];R(t,r,function(t){var r=i.computeMeshVertices_(i.meshWidth,i.meshHeight,e);if(t.bindBuffer(t.ARRAY_BUFFER,i.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,r,t.STATIC_DRAW),!i.indexCount){var s=i.computeMeshIndices_(i.meshWidth,i.meshHeight);t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,i.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,s,t.STATIC_DRAW),i.indexCount=s.length}})},B.prototype.computeMeshVertices_=function(e,t,i){for(var r=new Float32Array(2*e*t*5),s=i.getLeftEyeVisibleTanAngles(),n=i.getLeftEyeNoLensTanAngles(),o=i.getLeftEyeVisibleScreenRect(n),l=0,A=0;A<2;A++){for(var h=0;hs-42&&r.clientXi.clientHeight-42?e(r):r.clientX<42&&r.clientY<42&&t(r)},i.addEventListener("click",this.listener,!1)},O.prototype.onResize=function(){var e=this.gl,t=this,i=[e.ARRAY_BUFFER_BINDING];R(e,i,function(e){var i=[],r=e.drawingBufferWidth/2,s=Math.max(screen.width,screen.height)*window.devicePixelRatio,n=e.drawingBufferWidth/s,a=n*window.devicePixelRatio,o=4*a/2,l=42*a,A=28*a/2,h=14*a;function c(e,t){var s=(90-e)*I,n=Math.cos(s),a=Math.sin(s);i.push(L*n*A+r,L*a*A+A),i.push(t*n*A+r,t*a*A+A)}i.push(r-o,l),i.push(r-o,e.drawingBufferHeight),i.push(r+o,l),i.push(r+o,e.drawingBufferHeight),t.gearOffset=i.length/2;for(var d=0;d<=6;d++){var u=60*d;c(u,1),c(u+12,1),c(u+20,.75),c(u+40,.75),c(u+48,1)}function p(t,r){i.push(h+t,e.drawingBufferHeight-h-r)}t.gearVertexCount=i.length/2-t.gearOffset,t.arrowOffset=i.length/2;var f=o/Math.sin(45*I);p(0,A),p(A,0),p(A+f,f),p(f,A+f),p(f,A-f),p(0,A),p(A,2*A),p(A+f,2*A-f),p(f,A-f),p(0,A),p(f,A-o),p(28*a,A-o),p(f,A+o),p(28*a,A+o),t.arrowVertexCount=i.length/2-t.arrowOffset,e.bindBuffer(e.ARRAY_BUFFER,t.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array(i),e.STATIC_DRAW)})},O.prototype.render=function(){var e=this.gl,t=this,i=[e.CULL_FACE,e.DEPTH_TEST,e.BLEND,e.SCISSOR_TEST,e.STENCIL_TEST,e.COLOR_WRITEMASK,e.VIEWPORT,e.CURRENT_PROGRAM,e.ARRAY_BUFFER_BINDING];R(e,i,function(e){e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.BLEND),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.colorMask(!0,!0,!0,!0),e.viewport(0,0,e.drawingBufferWidth,e.drawingBufferHeight),t.renderNoState()})},O.prototype.renderNoState=function(){var e,t,i,r,s,n,a,o,l,A,h=this.gl;h.useProgram(this.program),h.bindBuffer(h.ARRAY_BUFFER,this.vertexBuffer),h.enableVertexAttribArray(this.attribs.position),h.vertexAttribPointer(this.attribs.position,2,h.FLOAT,!1,8,0),h.uniform4f(this.uniforms.color,1,1,1,1),e=this.projMat,t=0,i=h.drawingBufferWidth,r=0,s=h.drawingBufferHeight,o=1/(t-i),l=1/(r-s),A=1/((n=.1)-(a=1024)),e[0]=-2*o,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*l,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=2*A,e[11]=0,e[12]=(t+i)*o,e[13]=(s+r)*l,e[14]=(a+n)*A,e[15]=1,h.uniformMatrix4fv(this.uniforms.projectionMat,!1,this.projMat),h.drawArrays(h.TRIANGLE_STRIP,0,4),h.drawArrays(h.TRIANGLE_STRIP,this.gearOffset,this.gearVertexCount),h.drawArrays(h.TRIANGLE_STRIP,this.arrowOffset,this.arrowVertexCount)},N.prototype.distortInverse=function(e){for(var t=0,i=1,r=e-this.distort(t);Math.abs(i-t)>1e-4;){var s=e-this.distort(i),n=i-s*((i-t)/(s-r));t=i,i=n,r=s}return i},N.prototype.distort=function(e){for(var t=e*e,i=0,r=0;r=1)return this.w=n,this.x=i,this.y=r,this.z=s,this;var o=Math.acos(a),l=Math.sqrt(1-a*a);if(Math.abs(l)<.001)return this.w=.5*(n+this.w),this.x=.5*(i+this.x),this.y=.5*(r+this.y),this.z=.5*(s+this.z),this;var A=Math.sin((1-t)*o)/l,h=Math.sin(t*o)/l;return this.w=n*A+this.w*h,this.x=i*A+this.x*h,this.y=r*A+this.y*h,this.z=s*A+this.z*h,this},setFromUnitVectors:function(e,t){return void 0===z&&(z=new k),(V=e.dot(t)+1)<1e-6?(V=0,Math.abs(e.x)>Math.abs(e.z)?z.set(-e.y,e.x,0):z.set(0,-e.z,e.y)):z.crossVectors(e,t),this.x=z.x,this.y=z.y,this.z=z.z,this.w=V,this.normalize(),this}};var X=new H({widthMeters:.11,heightMeters:.062,bevelMeters:.004}),W=new H({widthMeters:.1038,heightMeters:.0584,bevelMeters:.004}),j={CardboardV1:new Y({id:"CardboardV1",label:"Cardboard I/O 2014",fov:40,interLensDistance:.06,baselineLensDistance:.035,screenLensDistance:.042,distortionCoefficients:[.441,.156],inverseCoefficients:[-.4410035,.42756155,-.4804439,.5460139,-.58821183,.5733938,-.48303202,.33299083,-.17573841,.0651772,-.01488963,.001559834]}),CardboardV2:new Y({id:"CardboardV2",label:"Cardboard I/O 2015",fov:60,interLensDistance:.064,baselineLensDistance:.035,screenLensDistance:.039,distortionCoefficients:[.34,.55],inverseCoefficients:[-.33836704,-.18162185,.862655,-1.2462051,1.0560602,-.58208317,.21609078,-.05444823,.009177956,-.0009904169,6183535e-11,-16981803e-13]})};function q(e,t){this.viewer=j.CardboardV2,this.updateDeviceParams(e),this.distortion=new N(this.viewer.distortionCoefficients);for(var i=0;i=200&&i.status<=299?(r.dpdb=JSON.parse(i.response),r.recalculateDeviceParams_()):console.error("Error loading online DPDB!")}),i.send()}}function K(e){this.xdpi=e.xdpi,this.ydpi=e.ydpi,this.bevelMm=e.bevelMm}function $(e,t){this.set(e,t)}function ee(e,t){this.kFilter=e,this.isDebug=t,this.currentAccelMeasurement=new $,this.currentGyroMeasurement=new $,this.previousGyroMeasurement=new $,o()?this.filterQ=new U(-1,0,0,1):this.filterQ=new U(1,0,0,1),this.previousFilterQ=new U,this.previousFilterQ.copy(this.filterQ),this.accelQ=new U,this.isOrientationInitialized=!1,this.estimatedGravity=new k,this.measuredGravity=new k,this.gyroIntegralQ=new U}function te(e,t){this.predictionTimeS=e,this.isDebug=t,this.previousQ=new U,this.previousTimestampS=null,this.deltaQ=new U,this.outQ=new U}function ie(e,t,i,r){this.yawOnly=i,this.accelerometer=new k,this.gyroscope=new k,this.filter=new ee(e,r),this.posePredictor=new te(t,r),this.isFirefoxAndroid=h(),this.isIOS=o();var s=c();this.isDeviceMotionInRadians=!this.isIOS&&s&&s<66,this.isWithoutDeviceMotion=u()||d(),this.filterToWorldQ=new U,o()?this.filterToWorldQ.setFromAxisAngle(new k(1,0,0),Math.PI/2):this.filterToWorldQ.setFromAxisAngle(new k(1,0,0),-Math.PI/2),this.inverseWorldToScreenQ=new U,this.worldToScreenQ=new U,this.originalPoseAdjustQ=new U,this.originalPoseAdjustQ.setFromAxisAngle(new k(0,0,1),-window.orientation*Math.PI/180),this.setScreenTransform_(),f()&&this.filterToWorldQ.multiply(this.inverseWorldToScreenQ),this.resetQ=new U,this.orientationOut_=new Float32Array(4),this.start()}J.prototype.getDeviceParams=function(){return this.deviceParams},J.prototype.recalculateDeviceParams_=function(){var e=this.calcDeviceParams_();e?(this.deviceParams=e,this.onDeviceParamsUpdated&&this.onDeviceParamsUpdated(this.deviceParams)):console.error("Failed to recalculate device parameters.")},J.prototype.calcDeviceParams_=function(){var e=this.dpdb;if(!e)return console.error("DPDB not available."),null;if(1!=e.format)return console.error("DPDB has unexpected format version."),null;if(!e.devices||!e.devices.length)return console.error("DPDB does not have a devices section."),null;var t=navigator.userAgent||navigator.vendor||window.opera,i=m(),r=g();if(!e.devices)return console.error("DPDB has no devices section."),null;for(var s=0;s1)&&this.run_(),this.previousGyroMeasurement.copy(this.currentGyroMeasurement)},ee.prototype.run_=function(){if(!this.isOrientationInitialized)return this.accelQ=this.accelToQuaternion_(this.currentAccelMeasurement.sample),this.previousFilterQ.copy(this.accelQ),void(this.isOrientationInitialized=!0);var e=this.currentGyroMeasurement.timestampS-this.previousGyroMeasurement.timestampS,t=this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample,e);this.gyroIntegralQ.multiply(t),this.filterQ.copy(this.previousFilterQ),this.filterQ.multiply(t);var i=new U;i.copy(this.filterQ),i.inverse(),this.estimatedGravity.set(0,0,-1),this.estimatedGravity.applyQuaternion(i),this.estimatedGravity.normalize(),this.measuredGravity.copy(this.currentAccelMeasurement.sample),this.measuredGravity.normalize();var r,s=new U;s.setFromUnitVectors(this.estimatedGravity,this.measuredGravity),s.inverse(),this.isDebug&&console.log("Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)",Q*((r=s).w>1?(console.warn("getQuaternionAngle: w > 1"),0):2*Math.acos(r.w)),this.estimatedGravity.x.toFixed(1),this.estimatedGravity.y.toFixed(1),this.estimatedGravity.z.toFixed(1),this.measuredGravity.x.toFixed(1),this.measuredGravity.y.toFixed(1),this.measuredGravity.z.toFixed(1));var n=new U;n.copy(this.filterQ),n.multiply(s),this.filterQ.slerp(n,1-this.kFilter),this.previousFilterQ.copy(this.filterQ)},ee.prototype.getOrientation=function(){return this.filterQ},ee.prototype.accelToQuaternion_=function(e){var t=new k;t.copy(e),t.normalize();var i=new U;return i.setFromUnitVectors(new k(0,0,-1),t),i.inverse(),i},ee.prototype.gyroToQuaternionDelta_=function(e,t){var i=new U,r=new k;return r.copy(e),r.normalize(),i.setFromAxisAngle(r,e.length()*t),i},te.prototype.getPrediction=function(e,t,i){if(!this.previousTimestampS)return this.previousQ.copy(e),this.previousTimestampS=i,e;var r=new k;r.copy(t),r.normalize();var s=t.length();if(s<20*G)return this.isDebug&&console.log("Moving slowly, at %s deg/s: no prediction",(Q*s).toFixed(1)),this.outQ.copy(e),this.previousQ.copy(e),this.outQ;var n=s*this.predictionTimeS;return this.deltaQ.setFromAxisAngle(r,n),this.outQ.copy(this.previousQ),this.outQ.multiply(this.deltaQ),this.previousQ.copy(e),this.previousTimestampS=i,this.outQ},ie.prototype.getPosition=function(){return null},ie.prototype.getOrientation=function(){var e=void 0;if(this.isWithoutDeviceMotion&&this._deviceOrientationQ){this.deviceOrientationFixQ=this.deviceOrientationFixQ||(r=(new U).setFromAxisAngle(new k(0,0,-1),0),s=new U,-90===window.orientation?s.setFromAxisAngle(new k(0,1,0),Math.PI/-2):s.setFromAxisAngle(new k(0,1,0),Math.PI/2),r.multiply(s)),this.deviceOrientationFilterToWorldQ=this.deviceOrientationFilterToWorldQ||((i=new U).setFromAxisAngle(new k(1,0,0),-Math.PI/2),i),e=this._deviceOrientationQ;var t=new U;return t.copy(e),t.multiply(this.deviceOrientationFilterToWorldQ),t.multiply(this.resetQ),t.multiply(this.worldToScreenQ),t.multiplyQuaternions(this.deviceOrientationFixQ,t),this.yawOnly&&(t.x=0,t.z=0,t.normalize()),this.orientationOut_[0]=t.x,this.orientationOut_[1]=t.y,this.orientationOut_[2]=t.z,this.orientationOut_[3]=t.w,this.orientationOut_}var i,r,s,n=this.filter.getOrientation();e=this.posePredictor.getPrediction(n,this.gyroscope,this.previousTimestampS);var t=new U;return t.copy(this.filterToWorldQ),t.multiply(this.resetQ),t.multiply(e),t.multiply(this.worldToScreenQ),this.yawOnly&&(t.x=0,t.z=0,t.normalize()),this.orientationOut_[0]=t.x,this.orientationOut_[1]=t.y,this.orientationOut_[2]=t.z,this.orientationOut_[3]=t.w,this.orientationOut_},ie.prototype.resetPose=function(){this.resetQ.copy(this.filter.getOrientation()),this.resetQ.x=0,this.resetQ.y=0,this.resetQ.z*=-1,this.resetQ.normalize(),f()&&this.resetQ.multiply(this.inverseWorldToScreenQ),this.resetQ.multiply(this.originalPoseAdjustQ)},ie.prototype.onDeviceOrientation_=function(e){this._deviceOrientationQ=this._deviceOrientationQ||new U;var t=e.alpha,i=e.beta,r=e.gamma;t=(t||0)*Math.PI/180,i=(i||0)*Math.PI/180,r=(r||0)*Math.PI/180,this._deviceOrientationQ.setFromEulerYXZ(i,t,-r)},ie.prototype.onDeviceMotion_=function(e){this.updateDeviceMotion_(e)},ie.prototype.updateDeviceMotion_=function(e){var t=e.accelerationIncludingGravity,i=e.rotationRate,r=e.timeStamp/1e3,s=r-this.previousTimestampS;return s<0?(_("fusion-pose-sensor:invalid:non-monotonic","Invalid timestamps detected: non-monotonic timestamp from devicemotion"),void(this.previousTimestampS=r)):s<=.001||s>1?(_("fusion-pose-sensor:invalid:outside-threshold","Invalid timestamps detected: Timestamp from devicemotion outside expected range."),void(this.previousTimestampS=r)):(this.accelerometer.set(-t.x,-t.y,-t.z),i&&(p()?this.gyroscope.set(-i.beta,i.alpha,i.gamma):this.gyroscope.set(i.alpha,i.beta,i.gamma),this.isDeviceMotionInRadians||this.gyroscope.multiplyScalar(Math.PI/180),this.filter.addGyroMeasurement(this.gyroscope,r)),this.filter.addAccelMeasurement(this.accelerometer,r),void(this.previousTimestampS=r))},ie.prototype.onOrientationChange_=function(e){this.setScreenTransform_()},ie.prototype.onMessage_=function(e){var t=e.data;if(t&&t.type){var i=t.type.toLowerCase();"devicemotion"===i&&this.updateDeviceMotion_(t.deviceMotionEvent)}},ie.prototype.setScreenTransform_=function(){switch(this.worldToScreenQ.set(0,0,0,1),window.orientation){case 0:break;case 90:this.worldToScreenQ.setFromAxisAngle(new k(0,0,1),-Math.PI/2);break;case-90:this.worldToScreenQ.setFromAxisAngle(new k(0,0,1),Math.PI/2)}this.inverseWorldToScreenQ.copy(this.worldToScreenQ),this.inverseWorldToScreenQ.inverse()},ie.prototype.start=function(){var e,t,i;this.onDeviceMotionCallback_=this.onDeviceMotion_.bind(this),this.onOrientationChangeCallback_=this.onOrientationChange_.bind(this),this.onMessageCallback_=this.onMessage_.bind(this),this.onDeviceOrientationCallback_=this.onDeviceOrientation_.bind(this),o()&&(e=window.self!==window.top,t=x(document.referrer),i=x(window.location.href),e&&t!==i)&&window.addEventListener("message",this.onMessageCallback_),window.addEventListener("orientationchange",this.onOrientationChangeCallback_),this.isWithoutDeviceMotion?window.addEventListener("deviceorientation",this.onDeviceOrientationCallback_):window.addEventListener("devicemotion",this.onDeviceMotionCallback_)},ie.prototype.stop=function(){window.removeEventListener("devicemotion",this.onDeviceMotionCallback_),window.removeEventListener("deviceorientation",this.onDeviceOrientationCallback_),window.removeEventListener("orientationchange",this.onOrientationChangeCallback_),window.removeEventListener("message",this.onMessageCallback_)};var re=new k(1,0,0),se=new k(0,0,1),ne=new U;ne.setFromAxisAngle(re,-Math.PI/2),ne.multiply((new U).setFromAxisAngle(se,Math.PI/2));var ae=function(){function e(t){r(this,e),this.config=t,this.sensor=null,this.fusionSensor=null,this._out=new Float32Array(4),this.api=null,this.errors=[],this._sensorQ=new U,this._outQ=new U,this._onSensorRead=this._onSensorRead.bind(this),this._onSensorError=this._onSensorError.bind(this),this.init()}return s(e,[{key:"init",value:function(){var e=null;try{(e=new RelativeOrientationSensor({frequency:60,referenceFrame:"screen"})).addEventListener("error",this._onSensorError)}catch(e){this.errors.push(e),"SecurityError"===e.name?(console.error("Cannot construct sensors due to the Feature Policy"),console.warn('Attempting to fall back using "devicemotion"; however this will fail in the future without correct permissions.'),this.useDeviceMotion()):"ReferenceError"===e.name?this.useDeviceMotion():console.error(e)}e&&(this.api="sensor",this.sensor=e,this.sensor.addEventListener("reading",this._onSensorRead),this.sensor.start())}},{key:"useDeviceMotion",value:function(){this.api="devicemotion",this.fusionSensor=new ie(this.config.K_FILTER,this.config.PREDICTION_TIME_S,this.config.YAW_ONLY,this.config.DEBUG),this.sensor&&(this.sensor.removeEventListener("reading",this._onSensorRead),this.sensor.removeEventListener("error",this._onSensorError),this.sensor=null)}},{key:"getOrientation",value:function(){if(this.fusionSensor)return this.fusionSensor.getOrientation();if(!this.sensor||!this.sensor.quaternion)return this._out[0]=this._out[1]=this._out[2]=0,this._out[3]=1,this._out;var e=this.sensor.quaternion;this._sensorQ.set(e[0],e[1],e[2],e[3]);var t=this._outQ;return t.copy(ne),t.multiply(this._sensorQ),this.config.YAW_ONLY&&(t.x=t.z=0,t.normalize()),this._out[0]=t.x,this._out[1]=t.y,this._out[2]=t.z,this._out[3]=t.w,this._out}},{key:"_onSensorError",value:function(e){this.errors.push(e.error),"NotAllowedError"===e.error.name?console.error("Permission to access sensor was denied"):"NotReadableError"===e.error.name?console.error("Sensor could not be read"):console.error(e.error),this.useDeviceMotion()}},{key:"_onSensorRead",value:function(){}}]),e}();function oe(){this.loadIcon_();var e=document.createElement("div"),t=e.style;t.position="fixed",t.top=0,t.right=0,t.bottom=0,t.left=0,t.backgroundColor="gray",t.fontFamily="sans-serif",t.zIndex=1e6;var i=document.createElement("img");i.src=this.icon;var t=i.style;t.marginLeft="25%",t.marginTop="25%",t.width="50%",e.appendChild(i);var r=document.createElement("div"),t=r.style;t.textAlign="center",t.fontSize="16px",t.lineHeight="24px",t.margin="24px 25%",t.width="50%",r.innerHTML="Place your phone into your Cardboard viewer.",e.appendChild(r);var s=document.createElement("div"),t=s.style;t.backgroundColor="#CFD8DC",t.position="fixed",t.bottom=0,t.width="100%",t.height="48px",t.padding="14px 24px",t.boxSizing="border-box",t.color="#656A6B",e.appendChild(s);var n=document.createElement("div");n.style.float="left",n.innerHTML="No Cardboard viewer?";var a=document.createElement("a");a.href="https://www.google.com/get/cardboard/get-cardboard/",a.innerHTML="get one",a.target="_blank";var t=a.style;t.float="right",t.fontWeight=600,t.textTransform="uppercase",t.borderLeft="1px solid gray",t.paddingLeft="24px",t.textDecoration="none",t.color="#656A6B",s.appendChild(n),s.appendChild(a),this.overlay=e,this.text=r,this.hide()}oe.prototype.show=function(e){e||this.overlay.parentElement?e&&(this.overlay.parentElement&&this.overlay.parentElement!=e&&this.overlay.parentElement.removeChild(this.overlay),e.appendChild(this.overlay)):document.body.appendChild(this.overlay),this.overlay.style.display="block";var t=this.overlay.querySelector("img"),i=t.style;f()?(i.width="20%",i.marginLeft="40%",i.marginTop="3%"):(i.width="50%",i.marginLeft="25%",i.marginTop="25%")},oe.prototype.hide=function(){this.overlay.style.display="none"},oe.prototype.showTemporarily=function(e,t){this.show(t),this.timer=setTimeout(this.hide.bind(this),e)},oe.prototype.disableShowTemporarily=function(){clearTimeout(this.timer)},oe.prototype.update=function(){this.disableShowTemporarily(),!f()&&b()?this.show():this.hide()},oe.prototype.loadIcon_=function(){this.icon="data:image/svg+xml,"+encodeURIComponent("")};var le="CardboardV1",Ae="WEBVR_CARDBOARD_VIEWER";function he(e){try{this.selectedKey=localStorage.getItem(Ae)}catch(e){console.error("Failed to load viewer profile: %s",e)}this.selectedKey||(this.selectedKey=e||le),this.dialog=this.createDialog_(q.Viewers),this.root=null,this.onChangeCallbacks_=[]}he.prototype.show=function(e){this.root=e,e.appendChild(this.dialog);var t=this.dialog.querySelector("#"+this.selectedKey);t.checked=!0,this.dialog.style.display="block"},he.prototype.hide=function(){this.root&&this.root.contains(this.dialog)&&this.root.removeChild(this.dialog),this.dialog.style.display="none"},he.prototype.getCurrentViewer=function(){return q.Viewers[this.selectedKey]},he.prototype.getSelectedKey_=function(){var e=this.dialog.querySelector("input[name=field]:checked");return e?e.id:null},he.prototype.onChange=function(e){this.onChangeCallbacks_.push(e)},he.prototype.fireOnChange_=function(e){for(var t=0;t.5&&(this.noSleepVideo.currentTime=Math.random())}.bind(this)))}return r(e,[{key:"enable",value:function(){n?(this.disable(),this.noSleepTimer=window.setInterval(function(){window.location.href="/",window.setTimeout(window.stop,0)},15e3)):this.noSleepVideo.play()}},{key:"disable",value:function(){n?this.noSleepTimer&&(window.clearInterval(this.noSleepTimer),this.noSleepTimer=null):this.noSleepVideo.pause()}}]),e}();e.exports=a},function(e,t,i){e.exports="data:video/mp4;base64,AAAAIGZ0eXBtcDQyAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAACKBtZGF0AAAC8wYF///v3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE0MiByMjQ3OSBkZDc5YTYxIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxNCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTEgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDExMSBtZT1oZXggc3VibWU9MiBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0wIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MCA4eDhkY3Q9MCBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0wIHRocmVhZHM9NiBsb29rYWhlYWRfdGhyZWFkcz0xIHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTMgYl9weXJhbWlkPTIgYl9hZGFwdD0xIGJfYmlhcz0wIGRpcmVjdD0xIHdlaWdodGI9MSBvcGVuX2dvcD0wIHdlaWdodHA9MSBrZXlpbnQ9MzAwIGtleWludF9taW49MzAgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD0xMCByYz1jcmYgbWJ0cmVlPTEgY3JmPTIwLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IHZidl9tYXhyYXRlPTIwMDAwIHZidl9idWZzaXplPTI1MDAwIGNyZl9tYXg9MC4wIG5hbF9ocmQ9bm9uZSBmaWxsZXI9MCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAAAOWWIhAA3//p+C7v8tDDSTjf97w55i3SbRPO4ZY+hkjD5hbkAkL3zpJ6h/LR1CAABzgB1kqqzUorlhQAAAAxBmiQYhn/+qZYADLgAAAAJQZ5CQhX/AAj5IQADQGgcIQADQGgcAAAACQGeYUQn/wALKCEAA0BoHAAAAAkBnmNEJ/8ACykhAANAaBwhAANAaBwAAAANQZpoNExDP/6plgAMuSEAA0BoHAAAAAtBnoZFESwr/wAI+SEAA0BoHCEAA0BoHAAAAAkBnqVEJ/8ACykhAANAaBwAAAAJAZ6nRCf/AAsoIQADQGgcIQADQGgcAAAADUGarDRMQz/+qZYADLghAANAaBwAAAALQZ7KRRUsK/8ACPkhAANAaBwAAAAJAZ7pRCf/AAsoIQADQGgcIQADQGgcAAAACQGe60Qn/wALKCEAA0BoHAAAAA1BmvA0TEM//qmWAAy5IQADQGgcIQADQGgcAAAAC0GfDkUVLCv/AAj5IQADQGgcAAAACQGfLUQn/wALKSEAA0BoHCEAA0BoHAAAAAkBny9EJ/8ACyghAANAaBwAAAANQZs0NExDP/6plgAMuCEAA0BoHAAAAAtBn1JFFSwr/wAI+SEAA0BoHCEAA0BoHAAAAAkBn3FEJ/8ACyghAANAaBwAAAAJAZ9zRCf/AAsoIQADQGgcIQADQGgcAAAADUGbeDRMQz/+qZYADLkhAANAaBwAAAALQZ+WRRUsK/8ACPghAANAaBwhAANAaBwAAAAJAZ+1RCf/AAspIQADQGgcAAAACQGft0Qn/wALKSEAA0BoHCEAA0BoHAAAAA1Bm7w0TEM//qmWAAy4IQADQGgcAAAAC0Gf2kUVLCv/AAj5IQADQGgcAAAACQGf+UQn/wALKCEAA0BoHCEAA0BoHAAAAAkBn/tEJ/8ACykhAANAaBwAAAANQZvgNExDP/6plgAMuSEAA0BoHCEAA0BoHAAAAAtBnh5FFSwr/wAI+CEAA0BoHAAAAAkBnj1EJ/8ACyghAANAaBwhAANAaBwAAAAJAZ4/RCf/AAspIQADQGgcAAAADUGaJDRMQz/+qZYADLghAANAaBwAAAALQZ5CRRUsK/8ACPkhAANAaBwhAANAaBwAAAAJAZ5hRCf/AAsoIQADQGgcAAAACQGeY0Qn/wALKSEAA0BoHCEAA0BoHAAAAA1Bmmg0TEM//qmWAAy5IQADQGgcAAAAC0GehkUVLCv/AAj5IQADQGgcIQADQGgcAAAACQGepUQn/wALKSEAA0BoHAAAAAkBnqdEJ/8ACyghAANAaBwAAAANQZqsNExDP/6plgAMuCEAA0BoHCEAA0BoHAAAAAtBnspFFSwr/wAI+SEAA0BoHAAAAAkBnulEJ/8ACyghAANAaBwhAANAaBwAAAAJAZ7rRCf/AAsoIQADQGgcAAAADUGa8DRMQz/+qZYADLkhAANAaBwhAANAaBwAAAALQZ8ORRUsK/8ACPkhAANAaBwAAAAJAZ8tRCf/AAspIQADQGgcIQADQGgcAAAACQGfL0Qn/wALKCEAA0BoHAAAAA1BmzQ0TEM//qmWAAy4IQADQGgcAAAAC0GfUkUVLCv/AAj5IQADQGgcIQADQGgcAAAACQGfcUQn/wALKCEAA0BoHAAAAAkBn3NEJ/8ACyghAANAaBwhAANAaBwAAAANQZt4NExC//6plgAMuSEAA0BoHAAAAAtBn5ZFFSwr/wAI+CEAA0BoHCEAA0BoHAAAAAkBn7VEJ/8ACykhAANAaBwAAAAJAZ+3RCf/AAspIQADQGgcAAAADUGbuzRMQn/+nhAAYsAhAANAaBwhAANAaBwAAAAJQZ/aQhP/AAspIQADQGgcAAAACQGf+UQn/wALKCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHAAACiFtb292AAAAbG12aGQAAAAA1YCCX9WAgl8AAAPoAAAH/AABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAGGlvZHMAAAAAEICAgAcAT////v7/AAAF+XRyYWsAAABcdGtoZAAAAAPVgIJf1YCCXwAAAAEAAAAAAAAH0AAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAygAAAMoAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAB9AAABdwAAEAAAAABXFtZGlhAAAAIG1kaGQAAAAA1YCCX9WAgl8AAV+QAAK/IFXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAUcbWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAAE3HN0YmwAAACYc3RzZAAAAAAAAAABAAAAiGF2YzEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAygDKAEgAAABIAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY//8AAAAyYXZjQwFNQCj/4QAbZ01AKOyho3ySTUBAQFAAAAMAEAAr8gDxgxlgAQAEaO+G8gAAABhzdHRzAAAAAAAAAAEAAAA8AAALuAAAABRzdHNzAAAAAAAAAAEAAAABAAAB8GN0dHMAAAAAAAAAPAAAAAEAABdwAAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAAC7gAAAAAQAAF3AAAAABAAAAAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAEEc3RzegAAAAAAAAAAAAAAPAAAAzQAAAAQAAAADQAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAANAAAADQAAAQBzdGNvAAAAAAAAADwAAAAwAAADZAAAA3QAAAONAAADoAAAA7kAAAPQAAAD6wAAA/4AAAQXAAAELgAABEMAAARcAAAEbwAABIwAAAShAAAEugAABM0AAATkAAAE/wAABRIAAAUrAAAFQgAABV0AAAVwAAAFiQAABaAAAAW1AAAFzgAABeEAAAX+AAAGEwAABiwAAAY/AAAGVgAABnEAAAaEAAAGnQAABrQAAAbPAAAG4gAABvUAAAcSAAAHJwAAB0AAAAdTAAAHcAAAB4UAAAeeAAAHsQAAB8gAAAfjAAAH9gAACA8AAAgmAAAIQQAACFQAAAhnAAAIhAAACJcAAAMsdHJhawAAAFx0a2hkAAAAA9WAgl/VgIJfAAAAAgAAAAAAAAf8AAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAACsm1kaWEAAAAgbWRoZAAAAADVgIJf1YCCXwAArEQAAWAAVcQAAAAAACdoZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU3RlcmVvAAAAAmNtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAidzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAADDUAAAAAABYCAgAISEAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAABYAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAAAGAAAAWAAAAXBzdGNvAAAAAAAAAFgAAAOBAAADhwAAA5oAAAOtAAADswAAA8oAAAPfAAAD5QAAA/gAAAQLAAAEEQAABCgAAAQ9AAAEUAAABFYAAARpAAAEgAAABIYAAASbAAAErgAABLQAAATHAAAE3gAABPMAAAT5AAAFDAAABR8AAAUlAAAFPAAABVEAAAVXAAAFagAABX0AAAWDAAAFmgAABa8AAAXCAAAFyAAABdsAAAXyAAAF+AAABg0AAAYgAAAGJgAABjkAAAZQAAAGZQAABmsAAAZ+AAAGkQAABpcAAAauAAAGwwAABskAAAbcAAAG7wAABwYAAAcMAAAHIQAABzQAAAc6AAAHTQAAB2QAAAdqAAAHfwAAB5IAAAeYAAAHqwAAB8IAAAfXAAAH3QAAB/AAAAgDAAAICQAACCAAAAg1AAAIOwAACE4AAAhhAAAIeAAACH4AAAiRAAAIpAAACKoAAAiwAAAItgAACLwAAAjCAAAAFnVkdGEAAAAObmFtZVN0ZXJlbwAAAHB1ZHRhAAAAaG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAO2lsc3QAAAAzqXRvbwAAACtkYXRhAAAAAQAAAABIYW5kQnJha2UgMC4xMC4yIDIwMTUwNjExMDA="}])},e.exports=i()}(de={exports:{}},de.exports),(ce=de.exports)&&ce.__esModule&&Object.prototype.hasOwnProperty.call(ce,"default")?ce.default:ce),pe=1e3,fe=[0,0,.5,1],me=[.5,0,.5,1],ge=window.requestAnimationFrame,ve=window.cancelAnimationFrame;function we(e){Object.defineProperties(this,{hasPosition:{writable:!1,enumerable:!0,value:e.hasPosition},hasExternalDisplay:{writable:!1,enumerable:!0,value:e.hasExternalDisplay},canPresent:{writable:!1,enumerable:!0,value:e.canPresent},maxLayers:{writable:!1,enumerable:!0,value:e.maxLayers},hasOrientation:{enumerable:!0,get:function(){return F("VRDisplayCapabilities.prototype.hasOrientation","VRDisplay.prototype.getFrameData"),e.hasOrientation}}})}function ye(e){var t=!("wakelock"in(e=e||{}))||e.wakelock;this.isPolyfilled=!0,this.displayId=pe++,this.displayName="",this.depthNear=.01,this.depthFar=1e4,this.isPresenting=!1,Object.defineProperty(this,"isConnected",{get:function(){return F("VRDisplay.prototype.isConnected","VRDisplayCapabilities.prototype.hasExternalDisplay"),!1}}),this.capabilities=new we({hasPosition:!1,hasOrientation:!1,hasExternalDisplay:!1,canPresent:!1,maxLayers:1}),this.stageParameters=null,this.waitingForPresent_=!1,this.layer_=null,this.originalParent_=null,this.fullscreenElement_=null,this.fullscreenWrapper_=null,this.fullscreenElementCachedStyle_=null,this.fullscreenEventTarget_=null,this.fullscreenChangeHandler_=null,this.fullscreenErrorHandler_=null,t&&b()&&(this.wakelock_=new ue)}ye.prototype.getFrameData=function(e){return M(e,this._getPose(),this)},ye.prototype.getPose=function(){return F("VRDisplay.prototype.getPose","VRDisplay.prototype.getFrameData"),this._getPose()},ye.prototype.resetPose=function(){return F("VRDisplay.prototype.resetPose"),this._resetPose()},ye.prototype.getImmediatePose=function(){return F("VRDisplay.prototype.getImmediatePose","VRDisplay.prototype.getFrameData"),this._getPose()},ye.prototype.requestAnimationFrame=function(e){return ge(e)},ye.prototype.cancelAnimationFrame=function(e){return ve(e)},ye.prototype.wrapForFullscreen=function(e){if(o())return e;if(!this.fullscreenWrapper_){this.fullscreenWrapper_=document.createElement("div");var t=["height: "+Math.min(screen.height,screen.width)+"px !important","top: 0 !important","left: 0 !important","right: 0 !important","border: 0","margin: 0","padding: 0","z-index: 999999 !important","position: fixed"];this.fullscreenWrapper_.setAttribute("style",t.join("; ")+";"),this.fullscreenWrapper_.classList.add("webvr-polyfill-fullscreen-wrapper")}if(this.fullscreenElement_==e)return this.fullscreenWrapper_;if(this.fullscreenElement_&&(this.originalParent_?this.originalParent_.appendChild(this.fullscreenElement_):this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_)),this.fullscreenElement_=e,this.originalParent_=e.parentElement,this.originalParent_||document.body.appendChild(e),!this.fullscreenWrapper_.parentElement){var i=this.fullscreenElement_.parentElement;i.insertBefore(this.fullscreenWrapper_,this.fullscreenElement_),i.removeChild(this.fullscreenElement_)}this.fullscreenWrapper_.insertBefore(this.fullscreenElement_,this.fullscreenWrapper_.firstChild),this.fullscreenElementCachedStyle_=this.fullscreenElement_.getAttribute("style");var r=this;return function(){if(r.fullscreenElement_){var e=["position: absolute","top: 0","left: 0","width: "+Math.max(screen.width,screen.height)+"px","height: "+Math.min(screen.height,screen.width)+"px","border: 0","margin: 0","padding: 0"];r.fullscreenElement_.setAttribute("style",e.join("; ")+";")}}(),this.fullscreenWrapper_},ye.prototype.removeFullscreenWrapper=function(){if(this.fullscreenElement_){var e=this.fullscreenElement_;this.fullscreenElementCachedStyle_?e.setAttribute("style",this.fullscreenElementCachedStyle_):e.removeAttribute("style"),this.fullscreenElement_=null,this.fullscreenElementCachedStyle_=null;var t=this.fullscreenWrapper_.parentElement;return this.fullscreenWrapper_.removeChild(e),this.originalParent_===t?t.insertBefore(e,this.fullscreenWrapper_):this.originalParent_&&this.originalParent_.appendChild(e),t.removeChild(this.fullscreenWrapper_),e}},ye.prototype.requestPresent=function(e){var t=this.isPresenting,i=this;return e instanceof Array||(F("VRDisplay.prototype.requestPresent with non-array argument","an array of VRLayers as the first argument"),e=[e]),new Promise(function(r,s){if(i.capabilities.canPresent)if(0==e.length||e.length>i.capabilities.maxLayers)s(new Error("Invalid number of layers."));else{var n=e[0];if(n.source){var a=n.leftBounds||fe,A=n.rightBounds||me;if(t){var h=i.layer_;h.source!==n.source&&(h.source=n.source);for(var c=0;c<4;c++)h.leftBounds[c]=a[c],h.rightBounds[c]=A[c];return i.wrapForFullscreen(i.layer_.source),i.updatePresent_(),void r()}if(i.layer_={predistorted:n.predistorted,source:n.source,leftBounds:a.slice(0),rightBounds:A.slice(0)},i.waitingForPresent_=!1,i.layer_&&i.layer_.source){var d=i.wrapForFullscreen(i.layer_.source);i.addFullscreenListeners_(d,function(){var e=document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement;i.isPresenting=d===e,i.isPresenting?(screen.orientation&&screen.orientation.lock&&screen.orientation.lock("landscape-primary").catch(function(e){console.error("screen.orientation.lock() failed due to",e.message)}),i.waitingForPresent_=!1,i.beginPresent_(),r()):(screen.orientation&&screen.orientation.unlock&&screen.orientation.unlock(),i.removeFullscreenWrapper(),i.disableWakeLock(),i.endPresent_(),i.removeFullscreenListeners_()),i.fireVRDisplayPresentChange_()},function(){i.waitingForPresent_&&(i.removeFullscreenWrapper(),i.removeFullscreenListeners_(),i.disableWakeLock(),i.waitingForPresent_=!1,i.isPresenting=!1,s(new Error("Unable to present.")))}),function(e){if(l())return!1;if(e.requestFullscreen)e.requestFullscreen();else if(e.webkitRequestFullscreen)e.webkitRequestFullscreen();else if(e.mozRequestFullScreen)e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)return!1;e.msRequestFullscreen()}return!0}(d)?(i.enableWakeLock(),i.waitingForPresent_=!0):(o()||l())&&(i.enableWakeLock(),i.isPresenting=!0,i.beginPresent_(),i.fireVRDisplayPresentChange_(),r())}i.waitingForPresent_||o()||(v(),s(new Error("Unable to present.")))}else r()}else s(new Error("VRDisplay is not capable of presenting."))})},ye.prototype.exitPresent=function(){var e=this.isPresenting,t=this;return this.isPresenting=!1,this.layer_=null,this.disableWakeLock(),new Promise(function(i,r){e?(!v()&&o()&&(t.endPresent_(),t.fireVRDisplayPresentChange_()),l()&&(t.removeFullscreenWrapper(),t.removeFullscreenListeners_(),t.endPresent_(),t.fireVRDisplayPresentChange_()),i()):r(new Error("Was not presenting to VRDisplay."))})},ye.prototype.getLayers=function(){return this.layer_?[this.layer_]:[]},ye.prototype.fireVRDisplayPresentChange_=function(){var e=new CustomEvent("vrdisplaypresentchange",{detail:{display:this}});window.dispatchEvent(e)},ye.prototype.fireVRDisplayConnect_=function(){var e=new CustomEvent("vrdisplayconnect",{detail:{display:this}});window.dispatchEvent(e)},ye.prototype.addFullscreenListeners_=function(e,t,i){this.removeFullscreenListeners_(),this.fullscreenEventTarget_=e,this.fullscreenChangeHandler_=t,this.fullscreenErrorHandler_=i,t&&(document.fullscreenEnabled?e.addEventListener("fullscreenchange",t,!1):document.webkitFullscreenEnabled?e.addEventListener("webkitfullscreenchange",t,!1):document.mozFullScreenEnabled?document.addEventListener("mozfullscreenchange",t,!1):document.msFullscreenEnabled&&e.addEventListener("msfullscreenchange",t,!1)),i&&(document.fullscreenEnabled?e.addEventListener("fullscreenerror",i,!1):document.webkitFullscreenEnabled?e.addEventListener("webkitfullscreenerror",i,!1):document.mozFullScreenEnabled?document.addEventListener("mozfullscreenerror",i,!1):document.msFullscreenEnabled&&e.addEventListener("msfullscreenerror",i,!1))},ye.prototype.removeFullscreenListeners_=function(){if(this.fullscreenEventTarget_){var e=this.fullscreenEventTarget_;if(this.fullscreenChangeHandler_){var t=this.fullscreenChangeHandler_;e.removeEventListener("fullscreenchange",t,!1),e.removeEventListener("webkitfullscreenchange",t,!1),document.removeEventListener("mozfullscreenchange",t,!1),e.removeEventListener("msfullscreenchange",t,!1)}if(this.fullscreenErrorHandler_){var i=this.fullscreenErrorHandler_;e.removeEventListener("fullscreenerror",i,!1),e.removeEventListener("webkitfullscreenerror",i,!1),document.removeEventListener("mozfullscreenerror",i,!1),e.removeEventListener("msfullscreenerror",i,!1)}this.fullscreenEventTarget_=null,this.fullscreenChangeHandler_=null,this.fullscreenErrorHandler_=null}},ye.prototype.enableWakeLock=function(){this.wakelock_&&this.wakelock_.enable()},ye.prototype.disableWakeLock=function(){this.wakelock_&&this.wakelock_.disable()},ye.prototype.beginPresent_=function(){},ye.prototype.endPresent_=function(){},ye.prototype.submitFrame=function(e){},ye.prototype.getEyeParameters=function(e){return null};var be={ADDITIONAL_VIEWERS:[],DEFAULT_VIEWER:"",MOBILE_WAKE_LOCK:!0,DEBUG:!1,DPDB_URL:"https://dpdb.webvr.rocks/dpdb.json",K_FILTER:.98,PREDICTION_TIME_S:.04,CARDBOARD_UI_DISABLED:!1,ROTATE_INSTRUCTIONS_DISABLED:!1,YAW_ONLY:!1,BUFFER_SCALE:.5,DIRTY_SUBMIT_FRAME_BINDINGS:!1},Ee={LEFT:"left",RIGHT:"right"};function Se(e){var t=E({},be);e=E(t,e||{}),ye.call(this,{wakelock:e.MOBILE_WAKE_LOCK}),this.config=e,this.displayName="Cardboard VRDisplay",this.capabilities=new we({hasPosition:!1,hasOrientation:!0,hasExternalDisplay:!1,canPresent:!0,maxLayers:1}),this.stageParameters=null,this.bufferScale_=this.config.BUFFER_SCALE,this.poseSensor_=new ae(this.config),this.distorter_=null,this.cardboardUI_=null,this.dpdb_=new J(this.config.DPDB_URL,this.onDeviceParamsUpdated_.bind(this)),this.deviceInfo_=new q(this.dpdb_.getDeviceParams(),e.ADDITIONAL_VIEWERS),this.viewerSelector_=new he(e.DEFAULT_VIEWER),this.viewerSelector_.onChange(this.onViewerChanged_.bind(this)),this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer()),this.config.ROTATE_INSTRUCTIONS_DISABLED||(this.rotateInstructions_=new oe),o()&&window.addEventListener("resize",this.onResize_.bind(this))}return Se.prototype=Object.create(ye.prototype),Se.prototype._getPose=function(){return{position:null,orientation:this.poseSensor_.getOrientation(),linearVelocity:null,linearAcceleration:null,angularVelocity:null,angularAcceleration:null}},Se.prototype._resetPose=function(){this.poseSensor_.resetPose&&this.poseSensor_.resetPose()},Se.prototype._getFieldOfView=function(e){var t;if(e==Ee.LEFT)t=this.deviceInfo_.getFieldOfViewLeftEye();else{if(e!=Ee.RIGHT)return console.error("Invalid eye provided: %s",e),null;t=this.deviceInfo_.getFieldOfViewRightEye()}return t},Se.prototype._getEyeOffset=function(e){var t;if(e==Ee.LEFT)t=[.5*-this.deviceInfo_.viewer.interLensDistance,0,0];else{if(e!=Ee.RIGHT)return console.error("Invalid eye provided: %s",e),null;t=[.5*this.deviceInfo_.viewer.interLensDistance,0,0]}return t},Se.prototype.getEyeParameters=function(e){var t=this._getEyeOffset(e),i=this._getFieldOfView(e),r={offset:t,renderWidth:.5*this.deviceInfo_.device.width*this.bufferScale_,renderHeight:this.deviceInfo_.device.height*this.bufferScale_};return Object.defineProperty(r,"fieldOfView",{enumerable:!0,get:function(){return F("VRFieldOfView","VRFrameData's projection matrices"),i}}),r},Se.prototype.onDeviceParamsUpdated_=function(e){this.config.DEBUG&&console.log("DPDB reported that device params were updated."),this.deviceInfo_.updateDeviceParams(e),this.distorter_&&this.distorter_.updateDeviceInfo(this.deviceInfo_)},Se.prototype.updateBounds_=function(){this.layer_&&this.distorter_&&(this.layer_.leftBounds||this.layer_.rightBounds)&&this.distorter_.setTextureBounds(this.layer_.leftBounds,this.layer_.rightBounds)},Se.prototype.beginPresent_=function(){var e=this.layer_.source.getContext("webgl");e||(e=this.layer_.source.getContext("experimental-webgl")),e||(e=this.layer_.source.getContext("webgl2")),e&&(this.layer_.predistorted?this.config.CARDBOARD_UI_DISABLED||(e.canvas.width=m()*this.bufferScale_,e.canvas.height=g()*this.bufferScale_,this.cardboardUI_=new O(e)):(this.config.CARDBOARD_UI_DISABLED||(this.cardboardUI_=new O(e)),this.distorter_=new B(e,this.cardboardUI_,this.config.BUFFER_SCALE,this.config.DIRTY_SUBMIT_FRAME_BINDINGS),this.distorter_.updateDeviceInfo(this.deviceInfo_)),this.cardboardUI_&&this.cardboardUI_.listen(function(e){this.viewerSelector_.show(this.layer_.source.parentElement),e.stopPropagation(),e.preventDefault()}.bind(this),function(e){this.exitPresent(),e.stopPropagation(),e.preventDefault()}.bind(this)),this.rotateInstructions_&&(f()&&b()?this.rotateInstructions_.showTemporarily(3e3,this.layer_.source.parentElement):this.rotateInstructions_.update()),this.orientationHandler=this.onOrientationChange_.bind(this),window.addEventListener("orientationchange",this.orientationHandler),this.vrdisplaypresentchangeHandler=this.updateBounds_.bind(this),window.addEventListener("vrdisplaypresentchange",this.vrdisplaypresentchangeHandler),this.fireVRDisplayDeviceParamsChange_())},Se.prototype.endPresent_=function(){this.distorter_&&(this.distorter_.destroy(),this.distorter_=null),this.cardboardUI_&&(this.cardboardUI_.destroy(),this.cardboardUI_=null),this.rotateInstructions_&&this.rotateInstructions_.hide(),this.viewerSelector_.hide(),window.removeEventListener("orientationchange",this.orientationHandler),window.removeEventListener("vrdisplaypresentchange",this.vrdisplaypresentchangeHandler)},Se.prototype.updatePresent_=function(){this.endPresent_(),this.beginPresent_()},Se.prototype.submitFrame=function(e){if(this.distorter_)this.updateBounds_(),this.distorter_.submitFrame();else if(this.cardboardUI_&&this.layer_){var t=this.layer_.source.getContext("webgl");t||(t=this.layer_.source.getContext("experimental-webgl")),t||(t=this.layer_.source.getContext("webgl2"));var i=t.canvas;i.width==this.lastWidth&&i.height==this.lastHeight||this.cardboardUI_.onResize(),this.lastWidth=i.width,this.lastHeight=i.height,this.cardboardUI_.render()}},Se.prototype.onOrientationChange_=function(e){this.viewerSelector_.hide(),this.rotateInstructions_&&this.rotateInstructions_.update(),this.onResize_()},Se.prototype.onResize_=function(e){if(this.layer_){var t=this.layer_.source.getContext("webgl");t||(t=this.layer_.source.getContext("experimental-webgl")),t||(t=this.layer_.source.getContext("webgl2")),t.canvas.setAttribute("style",["position: absolute","top: 0","left: 0","width: 100vw","height: 100vh","border: 0","margin: 0","padding: 0px","box-sizing: content-box"].join("; ")+";"),S(t.canvas)}},Se.prototype.onViewerChanged_=function(e){this.deviceInfo_.setViewer(e),this.distorter_&&this.distorter_.updateDeviceInfo(this.deviceInfo_),this.fireVRDisplayDeviceParamsChange_()},Se.prototype.fireVRDisplayDeviceParamsChange_=function(){var e=new CustomEvent("vrdisplaydeviceparamschange",{detail:{vrdisplay:this,deviceInfo:this.deviceInfo_}});window.dispatchEvent(e)},Se.VRFrameData=function(){this.leftProjectionMatrix=new Float32Array(16),this.leftViewMatrix=new Float32Array(16),this.rightProjectionMatrix=new Float32Array(16),this.rightViewMatrix=new Float32Array(16),this.pose=null},Se.VRDisplay=ye,Se}()}(De={exports:{}},De.exports),De.exports),Oe=(Ie=Le)&&Ie.__esModule&&Object.prototype.hasOwnProperty.call(Ie,"default")?Ie.default:Ie;class Ne extends i{constructor(e){super(),this.global=e,this.onWindowResize=this.onWindowResize.bind(this),this.global.window.addEventListener("resize",this.onWindowResize),this.environmentBlendMode="opaque"}onBaseLayerSet(e,t){throw new Error("Not implemented")}isSessionSupported(e){throw new Error("Not implemented")}isFeatureSupported(e){throw new Error("Not implemented")}async requestSession(e,t){throw new Error("Not implemented")}requestAnimationFrame(e){throw new Error("Not implemented")}onFrameStart(e){throw new Error("Not implemented")}onFrameEnd(e){throw new Error("Not implemented")}doesSessionSupportReferenceSpace(e,t){throw new Error("Not implemented")}requestStageBounds(){throw new Error("Not implemented")}async requestFrameOfReferenceTransform(e,t){}cancelAnimationFrame(e){throw new Error("Not implemented")}endSession(e){throw new Error("Not implemented")}getViewSpaces(e){}getViewport(e,t,i,r,s){throw new Error("Not implemented")}getProjectionMatrix(e,t){throw new Error("Not implemented")}getBasePoseMatrix(){throw new Error("Not implemented")}getBaseViewMatrix(e){throw new Error("Not implemented")}getInputSources(){throw new Error("Not implemented")}getInputPose(e,t,i){throw new Error("Not implemented")}onWindowResize(){this.onWindowResize()}}let Ge={mapping:"xr-standard",profiles:["oculus-go","generic-trigger-touchpad"],buttons:{length:3,0:1,1:null,2:0},gripTransform:{orientation:[.11*Math.PI,0,0,1]}},Qe={mapping:"xr-standard",displayProfiles:{"Oculus Quest":["oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"]},profiles:["oculus-touch","generic-trigger-squeeze-thumbstick"],axes:{length:4,0:2,1:3,2:0,3:1},buttons:{length:7,0:1,1:2,2:null,3:0,4:3,5:4,6:null},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},ke={mapping:"xr-standard",displayProfiles:{"Oculus Quest":["oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"]},profiles:["oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"],axes:{length:4,0:2,1:3,2:0,3:1},buttons:{length:7,0:1,1:2,2:null,3:0,4:3,5:4,6:null},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},ze={mapping:"xr-standard",displayProfiles:{"Oculus Quest":["oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"]},profiles:["oculus-touch-v3","oculus-touch-v2","oculus-touch","generic-trigger-squeeze-thumbstick"],axes:{length:4,0:2,1:3,2:0,3:1},buttons:{length:7,0:1,1:2,2:null,3:0,4:3,5:4,6:null},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},Ve={mapping:"xr-standard",profiles:["htc-vive","generic-trigger-squeeze-touchpad"],displayProfiles:{"HTC Vive":["htc-vive","generic-trigger-squeeze-touchpad"],"HTC Vive DVT":["htc-vive","generic-trigger-squeeze-touchpad"],"Valve Index":["valve-index","generic-trigger-squeeze-touchpad-thumbstick"]},buttons:{length:3,0:1,1:2,2:0},gripTransform:{position:[0,0,.05,1]},targetRayTransform:{orientation:[-.08*Math.PI,0,0,1]},userAgentOverrides:{Firefox:{axes:{invert:[1,3]}}}},Ue={mapping:"xr-standard",profiles:["samsung-gearvr","generic-trigger-touchpad"],buttons:{length:3,0:1,1:null,2:0},gripTransform:{orientation:[.11*Math.PI,0,0,1]}},He={mapping:"xr-standard",profiles:["samsung-odyssey","microsoft-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"],buttons:{length:4,0:1,1:0,2:2,3:4},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},Xe={mapping:"xr-standard",profiles:["microsoft-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"],buttons:{length:4,0:1,1:0,2:2,3:4},gripTransform:{position:[0,-.02,.04,1],orientation:[.11*Math.PI,0,0,1]}},We={"Daydream Controller":{mapping:"",profiles:["google-daydream","generic-trigger-touchpad"],buttons:{length:3,0:null,1:null,2:0}},"Gear VR Controller":Ue,"HTC Vive Focus Controller":{mapping:"xr-standard",profiles:["htc-vive-focus","generic-trigger-touchpad"],buttons:{length:3,0:1,1:null,2:0}},"Oculus Go Controller":Ge,"Oculus Touch (Right)":Qe,"Oculus Touch (Left)":Qe,"Oculus Touch V2 (Right)":ke,"Oculus Touch V2 (Left)":ke,"Oculus Touch V3 (Right)":ze,"Oculus Touch V3 (Left)":ze,"OpenVR Gamepad":Ve,"Spatial Controller (Spatial Interaction Source) 045E-065A":Xe,"Spatial Controller (Spatial Interaction Source) 045E-065D":He,"Windows Mixed Reality (Right)":Xe,"Windows Mixed Reality (Left)":Xe};const je=f(.155,-.465,-.15),qe=f(-.155,-.465,-.15),Ye=f(0,0,-.25),Ze=f(0,0,.05),Je=f(-.08,.14,.08),Ke=.4,$e=.4,et=.61,tt=.175,it=.12,rt=.87,st=180/Math.PI;class nt{constructor(){this.hand="right",this.headElbowOffset=je,this.controllerQ=M(),this.lastControllerQ=M(),this.headQ=M(),this.headPos=u(),this.elbowPos=u(),this.wristPos=u(),this.time=null,this.lastTime=null,this.rootQ=M(),this.position=u()}setHandedness(e){this.hand!=e&&(this.hand=e,"left"==this.hand?this.headElbowOffset=qe:this.headElbowOffset=je)}update(e,t){this.time=X(),e&&(P(this.lastControllerQ,this.controllerQ),P(this.controllerQ,e)),t&&(h(this.headPos,t),c(this.headQ,t));let i=this.getHeadYawOrientation_(),r=this.quatAngle_(this.lastControllerQ,this.controllerQ);r/((this.time-this.lastTime)/1e3)>et?_(this.rootQ,this.rootQ,i,Math.min(r/tt,1)):P(this.rootQ,i);let s=f(0,0,-1);E(s,s,this.controllerQ);let n=y(s,[0,1,0]),a=this.clamp_((n-it)/rt,0,1),o=R(this.rootQ);F(o,o),x(o,o,this.controllerQ);let l=this.elbowPos;m(l,this.headPos),g(l,l,this.headElbowOffset);let A=p(Je);v(A,A,a),g(l,l,A);let d=this.quatAngle_(o,M())*st,u=(1-Math.pow(d/180,4))*(Ke+(1-Ke)*a*$e),w=M();_(w,w,o,u);let b=F(M(),w),S=R(o);x(S,S,b);let T=this.wristPos;m(T,Ze),E(T,T,w),g(T,T,Ye),E(T,T,S),g(T,T,l);let B=p(Je);v(B,B,a),g(this.position,this.wristPos,B),E(this.position,this.position,this.rootQ),this.lastTime=this.time}getPosition(){return this.position}getHeadYawOrientation_(){let e=u();return function(e,t,i){function r(e,t,i){return ei?i:e}var s=t[0]*t[0],n=t[1]*t[1],a=t[2]*t[2],o=t[3]*t[3];if("XYZ"===i)e[0]=Math.atan2(2*(t[0]*t[3]-t[1]*t[2]),o-s-n+a),e[1]=Math.asin(r(2*(t[0]*t[2]+t[1]*t[3]),-1,1)),e[2]=Math.atan2(2*(t[2]*t[3]-t[0]*t[1]),o+s-n-a);else if("YXZ"===i)e[0]=Math.asin(r(2*(t[0]*t[3]-t[1]*t[2]),-1,1)),e[1]=Math.atan2(2*(t[0]*t[2]+t[1]*t[3]),o-s-n+a),e[2]=Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),o-s+n-a);else if("ZXY"===i)e[0]=Math.asin(r(2*(t[0]*t[3]+t[1]*t[2]),-1,1)),e[1]=Math.atan2(2*(t[1]*t[3]-t[2]*t[0]),o-s-n+a),e[2]=Math.atan2(2*(t[2]*t[3]-t[0]*t[1]),o-s+n-a);else if("ZYX"===i)e[0]=Math.atan2(2*(t[0]*t[3]+t[2]*t[1]),o-s-n+a),e[1]=Math.asin(r(2*(t[1]*t[3]-t[0]*t[2]),-1,1)),e[2]=Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),o+s-n-a);else if("YZX"===i)e[0]=Math.atan2(2*(t[0]*t[3]-t[2]*t[1]),o-s+n-a),e[1]=Math.atan2(2*(t[1]*t[3]-t[0]*t[2]),o+s-n-a),e[2]=Math.asin(r(2*(t[0]*t[1]+t[2]*t[3]),-1,1));else{if("XZY"!==i)return void console.log("No order given for quaternion to euler conversion.");e[0]=Math.atan2(2*(t[0]*t[3]+t[1]*t[2]),o-s+n-a),e[1]=Math.atan2(2*(t[0]*t[2]+t[1]*t[3]),o+s-n-a),e[2]=Math.asin(r(2*(t[2]*t[3]-t[0]*t[1]),-1,1))}}(e,this.headQ,"YXZ"),function(e,t,i,r){let s=.5*Math.PI/180;t*=s,i*=s,r*=s;let n=Math.sin(t),a=Math.cos(t),o=Math.sin(i),l=Math.cos(i),A=Math.sin(r),h=Math.cos(r);return e[0]=n*l*h-a*o*A,e[1]=a*o*h+n*l*A,e[2]=a*l*A-n*o*h,e[3]=a*l*h+n*o*A,e}(M(),0,e[1]*st,0)}clamp_(e,t,i){return Math.min(Math.max(e,t),i)}quatAngle_(e,t){let i=[0,0,-1],r=[0,0,-1];return E(i,i,e),E(r,r,t),function(e,t){let i=f(e[0],e[1],e[2]),r=f(t[0],t[1],t[2]);w(i,i),w(r,r);let s=y(i,r);return s>1?0:s<-1?Math.PI:Math.acos(s)}(i,r)}}const at=Symbol("@@webxr-polyfill/XRRemappedGamepad"),ot={pressed:!1,touched:!1,value:0};Object.freeze(ot);class lt{constructor(e,t,i){if(i||(i={}),i.userAgentOverrides)for(let e in i.userAgentOverrides)if(navigator.userAgent.includes(e)){let t=i.userAgentOverrides[e];for(let e in t)e in i?Object.assign(i[e],t[e]):i[e]=t[e];break}let r=new Array(i.axes&&i.axes.length?i.axes.length:e.axes.length),s=new Array(i.buttons&&i.buttons.length?i.buttons.length:e.buttons.length),a=null;if(i.gripTransform){let e=i.gripTransform.orientation||[0,0,0,1];A(a=n(),B(e,e),i.gripTransform.position||[0,0,0])}let o=null;if(i.targetRayTransform){let e=i.targetRayTransform.orientation||[0,0,0,1];A(o=n(),B(e,e),i.targetRayTransform.position||[0,0,0])}let l=i.profiles;i.displayProfiles&&t.displayName in i.displayProfiles&&(l=i.displayProfiles[t.displayName]),this[at]={gamepad:e,map:i,profiles:l||[e.id],mapping:i.mapping||e.mapping,axes:r,buttons:s,gripTransform:a,targetRayTransform:o},this._update()}_update(){let e=this[at].gamepad,t=this[at].map,i=this[at].axes;for(let r=0;r{ht||this.global.document.body.contains(r)||(i.modifiedCanvasLayer=!0,this.global.document.body.appendChild(r),Be(r)),i.baseLayer=t})}else i.baseLayer=t}isSessionSupported(e){return"immersive-ar"!=e&&("immersive-vr"!=e||!1!==this.canPresent)}isFeatureSupported(e){switch(e){case"viewer":case"local":case"local-floor":return!0;case"bounded":case"unbounded":default:return!1}}async requestSession(e,t){if(!this.isSessionSupported(e))return Promise.reject();let i="immersive-vr"==e;if(i){const e=this.global.document.createElement("canvas");if(!ht){e.getContext("webgl")}await this.display.requestPresent([{source:e,attributes:ct}])}const r=new pt(e,t,{renderContextType:this.HAS_BITMAP_SUPPORT?"bitmaprenderer":"2d"});return this.sessions.set(r.id,r),i&&(this.immersiveSession=r,this.dispatchEvent("@@webxr-polyfill/vr-present-start",r.id)),Promise.resolve(r.id)}requestAnimationFrame(e){return this.display.requestAnimationFrame(e)}getPrimaryButtonIndex(e){let t=0,i=e.id.toLowerCase();for(let e in dt)if(i.includes(e)){t=dt[e];break}return Math.min(t,e.buttons.length-1)}onFrameStart(e,t){this.display.depthNear=t.depthNear,this.display.depthFar=t.depthFar,this.display.getFrameData(this.frame);const i=this.sessions.get(e);if(i.immersive&&this.CAN_USE_GAMEPAD){let e=this.gamepadInputSources;this.gamepadInputSources={};let t=this.global.navigator.getGamepads();for(let r=0;r0){let t=e[r];if(t||(t=new At(this,this.display,this.getPrimaryButtonIndex(s))),t.updateFromGamepad(s),this.gamepadInputSources[r]=t,-1!=t.primaryButtonIndex){let e=s.buttons[t.primaryButtonIndex].pressed;e&&!t.primaryActionPressed?this.dispatchEvent("@@webxr-polyfill/input-select-start",{sessionId:i.id,inputSource:t.inputSource}):!e&&t.primaryActionPressed&&this.dispatchEvent("@@webxr-polyfill/input-select-end",{sessionId:i.id,inputSource:t.inputSource}),t.primaryActionPressed=e}if(-1!=t.primarySqueezeButtonIndex){let e=s.buttons[t.primarySqueezeButtonIndex].pressed;e&&!t.primarySqueezeActionPressed?this.dispatchEvent("@@webxr-polyfill/input-squeeze-start",{sessionId:i.id,inputSource:t.inputSource}):!e&&t.primarySqueezeActionPressed&&this.dispatchEvent("@@webxr-polyfill/input-squeeze-end",{sessionId:i.id,inputSource:t.inputSource}),t.primarySqueezeActionPressed=e}}}}if(!ht&&!i.immersive&&i.baseLayer){const e=i.baseLayer.context.canvas;d(this.frame.leftProjectionMatrix,t.inlineVerticalFieldOfView,e.width/e.height,t.depthNear,t.depthFar)}}onFrameEnd(e){const t=this.sessions.get(e);if(!t.ended&&t.baseLayer){if(t.outputContext&&(!t.immersive||this.display.capabilities.hasExternalDisplay)){const e=t.immersive&&this.display.capabilities.hasExternalDisplay,i=t.baseLayer.context.canvas,r=e?i.width/2:i.width,s=i.height;if(!ht){const e=t.outputContext.canvas,n=e.width,a=e.height,o=t.renderContext;this.HAS_BITMAP_SUPPORT?i.transferToImageBitmap?o.transferFromImageBitmap(i.transferToImageBitmap()):this.global.createImageBitmap(i,0,0,r,s,{resizeWidth:n,resizeHeight:a}).then(e=>o.transferFromImageBitmap(e)):o.drawImage(i,0,0,r,s,0,0,n,a)}}t.immersive&&t.baseLayer&&this.display.submitFrame()}}cancelAnimationFrame(e){this.display.cancelAnimationFrame(e)}async endSession(e){const t=this.sessions.get(e);if(!t.ended)return t.immersive?this.display.exitPresent():void(t.ended=!0)}doesSessionSupportReferenceSpace(e,t){const i=this.sessions.get(e);return!i.ended&&i.enabledFeatures.has(t)}requestStageBounds(){if(this.display.stageParameters){const e=this.display.stageParameters.sizeX,t=this.display.stageParameters.sizeZ,i=[];return i.push(-e/2),i.push(-t/2),i.push(e/2),i.push(-t/2),i.push(e/2),i.push(t/2),i.push(-e/2),i.push(t/2),i}return null}async requestFrameOfReferenceTransform(e,t){return("local-floor"===e||"bounded-floor"===e)&&this.display.stageParameters&&this.display.stageParameters.sittingToStandingTransform?this.display.stageParameters.sittingToStandingTransform:null}getProjectionMatrix(e){if("left"===e)return this.frame.leftProjectionMatrix;if("right"===e)return this.frame.rightProjectionMatrix;if("none"===e)return this.frame.leftProjectionMatrix;throw new Error("eye must be of type 'left' or 'right'")}getViewport(e,t,i,r){const s=this.sessions.get(e),{width:n,height:a}=i.context.canvas;if(!s.immersive)return r.x=r.y=0,r.width=n,r.height=a,!0;if("left"===t||"none"===t)r.x=0;else{if("right"!==t)return!1;r.x=n/2}return r.y=0,r.width=n/2,r.height=a,!0}getBasePoseMatrix(){let{position:e,orientation:t}=this.frame.pose;return e||t?(e||((e=this.tempVec3)[0]=e[1]=e[2]=0),A(this.baseModelMatrix,t,e),this.baseModelMatrix):this.baseModelMatrix}getBaseViewMatrix(e){if("left"===e||"none"===e)return this.frame.leftViewMatrix;if("right"===e)return this.frame.rightViewMatrix;throw new Error("eye must be of type 'left' or 'right'")}getInputSources(){let e=[];for(let t in this.gamepadInputSources)e.push(this.gamepadInputSources[t].inputSource);return e}getInputPose(e,t,i){if(!t)return null;for(let r in this.gamepadInputSources){let s=this.gamepadInputSources[r];if(s.inputSource===e)return s.getXRPose(t,i)}return null}onWindowResize(){}onVRDisplayPresentChange(e){this.display.isPresenting||this.sessions.forEach(e=>{if(e.immersive&&!e.ended){if(e.modifiedCanvasLayer){const t=e.baseLayer.context.canvas;document.body.removeChild(t),t.setAttribute("style","")}this.immersiveSession===e&&(this.immersiveSession=null),this.dispatchEvent("@@webxr-polyfill/vr-present-end",e.id)}})}}const mt=!1;let gt=0;class vt{constructor(e,t){this.mode=e,this.enabledFeatures=t,this.ended=null,this.baseLayer=null,this.id=++gt}}const wt=async function(e,t){if(t.webvr){let t=await async function(e){let t=null;if("getVRDisplays"in e.navigator)try{const i=await e.navigator.getVRDisplays();i&&i.length&&(t=new ft(e,i[0]))}catch(e){}return t}(e);if(t)return t}let i=(e=>{var t=!1;return Pe=e.navigator.userAgent||e.navigator.vendor||e.opera,(/(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(Pe)||/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(Pe.substr(0,4)))&&(t=!0),t})(e);return i&&t.cardboard||!i&&t.allowCardboardOnDesktop?(e.VRFrameData||(e.VRFrameData=function(){this.rightViewMatrix=new Float32Array(16),this.leftViewMatrix=new Float32Array(16),this.rightProjectionMatrix=new Float32Array(16),this.leftProjectionMatrix=new Float32Array(16),this.pose=null}),new class extends ft{constructor(e,t){const i=new Oe(t||{});super(e,i),this.display=i,this.frame={rightViewMatrix:new Float32Array(16),leftViewMatrix:new Float32Array(16),rightProjectionMatrix:new Float32Array(16),leftProjectionMatrix:new Float32Array(16),pose:null,timestamp:null}}}(e,t.cardboardConfig)):new class extends Ne{constructor(e){super(e),this.sessions=new Map,this.projectionMatrix=n(),this.identityMatrix=n()}onBaseLayerSet(e,t){this.sessions.get(e).baseLayer=t}isSessionSupported(e){return"inline"==e}isFeatureSupported(e){switch(e){case"viewer":return!0;default:return!1}}async requestSession(e,t){if(!this.isSessionSupported(e))return Promise.reject();const i=new vt(e,t);return this.sessions.set(i.id,i),Promise.resolve(i.id)}requestAnimationFrame(e){return window.requestAnimationFrame(e)}cancelAnimationFrame(e){window.cancelAnimationFrame(e)}onFrameStart(e,t){if(mt)return;const i=this.sessions.get(e);if(i.baseLayer){const e=i.baseLayer.context.canvas;d(this.projectionMatrix,t.inlineVerticalFieldOfView,e.width/e.height,t.depthNear,t.depthFar)}}onFrameEnd(e){}async endSession(e){this.sessions.get(e).ended=!0}doesSessionSupportReferenceSpace(e,t){const i=this.sessions.get(e);return!i.ended&&i.enabledFeatures.has(t)}requestStageBounds(){return null}async requestFrameOfReferenceTransform(e,t){return null}getProjectionMatrix(e){return this.projectionMatrix}getViewport(e,t,i,r){const{width:s,height:n}=i.context.canvas;return this.sessions.get(e),r.x=r.y=0,r.width=s,r.height=n,!0}getBasePoseMatrix(){return this.identityMatrix}getBaseViewMatrix(e){return this.identityMatrix}getInputSources(){return[]}getInputPose(e,t,i){return null}onWindowResize(){}}(e)},yt={global:e,webvr:!0,cardboard:!0,cardboardConfig:null,allowCardboardOnDesktop:!1},bt=["navigator","HTMLCanvasElement","WebGLRenderingContext"];return class{constructor(e={}){this.config=Object.freeze(Object.assign({},yt,e)),this.global=this.config.global,this.nativeWebXR="xr"in this.global.navigator,this.injected=!1,this.nativeWebXR?this._injectCompatibilityShims(this.global):this._injectPolyfill(this.global)}_injectPolyfill(e){if(!bt.every(t=>!!e[t]))throw new Error(`Global must have the following attributes : ${bt}`);for(const t of Object.keys(_e))void 0!==e[t]?console.warn(`${t} already defined on global.`):e[t]=_e[t];Fe(e.WebGLRenderingContext)&&(Re(e.HTMLCanvasElement),e.OffscreenCanvas&&Re(e.OffscreenCanvas),e.WebGL2RenderingContext&&Fe(e.WebGL2RenderingContext),window.isSecureContext||console.warn("WebXR Polyfill Warning:\nThis page is not running in a secure context (https:// or localhost)!\nThis means that although the page may be able to use the WebXR Polyfill it will\nnot be able to use native WebXR implementations, and as such will not be able to\naccess dedicated VR or AR hardware, and will not be able to take advantage of\nany performance improvements a native WebXR implementation may offer. Please\nhost this content on a secure origin for the best user experience.\n")),this.injected=!0,this._patchNavigatorXR()}_patchNavigatorXR(){let e=wt(this.global,this.config);this.xr=new _e.XRSystem(e),Object.defineProperty(this.global.navigator,"xr",{value:this.xr,configurable:!0})}_injectCompatibilityShims(e){if(!bt.every(t=>!!e[t]))throw new Error(`Global must have the following attributes : ${bt}`);if(e.navigator.xr&&"supportsSession"in e.navigator.xr&&!("isSessionSupported"in e.navigator.xr)){let t=e.navigator.xr.supportsSession;e.navigator.xr.isSessionSupported=function(e){return t.call(this,e).then(()=>!0).catch(()=>!1)},e.navigator.xr.supportsSession=function(e){return console.warn("navigator.xr.supportsSession() is deprecated. Please call navigator.xr.isSessionSupported() instead and check the boolean value returned when the promise resolves."),t.call(this,e)}}}}}); diff --git a/build/webxr-polyfill.module.js b/build/webxr-polyfill.module.js index bde903d..abb6638 100644 --- a/build/webxr-polyfill.module.js +++ b/build/webxr-polyfill.module.js @@ -5085,8 +5085,8 @@ let oculusTouch = { profiles: ['oculus-touch', 'generic-trigger-squeeze-thumbstick'], axes: { length: 4, - 0: null, - 1: null, + 0: 2, + 1: 3, 2: 0, 3: 1 }, @@ -5113,8 +5113,8 @@ let oculusTouchV2 = { profiles: ['oculus-touch-v2', 'oculus-touch', 'generic-trigger-squeeze-thumbstick'], axes: { length: 4, - 0: null, - 1: null, + 0: 2, + 1: 3, 2: 0, 3: 1 }, @@ -5141,8 +5141,8 @@ let oculusTouchV3 = { profiles: ['oculus-touch-v3', 'oculus-touch-v2', 'oculus-touch', 'generic-trigger-squeeze-thumbstick'], axes: { length: 4, - 0: null, - 1: null, + 0: 2, + 1: 3, 2: 0, 3: 1 }, diff --git a/src/devices/GamepadMappings.js b/src/devices/GamepadMappings.js index 72f314a..3fa9585 100644 --- a/src/devices/GamepadMappings.js +++ b/src/devices/GamepadMappings.js @@ -92,8 +92,8 @@ let oculusTouch = { profiles: ['oculus-touch', 'generic-trigger-squeeze-thumbstick'], axes: { length: 4, - 0: null, - 1: null, + 0: 2, + 1: 3, 2: 0, 3: 1 }, @@ -123,8 +123,8 @@ let oculusTouchV2 = { profiles: ['oculus-touch-v2', 'oculus-touch', 'generic-trigger-squeeze-thumbstick'], axes: { length: 4, - 0: null, - 1: null, + 0: 2, + 1: 3, 2: 0, 3: 1 }, @@ -154,8 +154,8 @@ let oculusTouchV3 = { profiles: ['oculus-touch-v3', 'oculus-touch-v2', 'oculus-touch', 'generic-trigger-squeeze-thumbstick'], axes: { length: 4, - 0: null, - 1: null, + 0: 2, + 1: 3, 2: 0, 3: 1 },