@displayxr/inline3d 1.48.0 → 1.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/call.js CHANGED
@@ -1,22 +1,22 @@
1
- /* @displayxr/inline3d 1.48.0 — dist/call.js — Apache-2.0 — https://github.com/DisplayXR/displayxr-web */
2
- var Zs=Object.defineProperty;var he=(n,e)=>()=>(n&&(e=n(n=0)),e);var Qs=(n,e)=>{for(var t in e)Zs(n,t,{get:e[t],enumerable:!0})};function kn(n,e,t=1){let i=et,r=!!n&&n.displayWidthMeters>0&&n.displayHeightMeters>0&&n.displayPixelWidth>0&&n.displayPixelHeight>0,s=r?[n.displayWidthMeters,n.displayHeightMeters]:[...i.displaySizeM],o=r?[n.displayPixelWidth,n.displayPixelHeight]:[...i.displayPixels],a=(s[0]/o[0]+s[1]/o[1])/2,l=t>0?t:1,c=r?a*l:a*(o[1]/Math.max(1,globalThis.innerHeight||o[1])),h=n?.nominalViewerPosition?.z,d=Number.isFinite(h)&&h>.1;return{canvasSizeM:[(e?.width||0)*c,(e?.height||0)*c],metersPerCssPx:c,displaySizeM:s,nominalViewerM:d?h:i.nominalViewerM,eyeSeparationM:i.eyeSeparationM,source:{size:r?"display":"default",viewer:d?"display":"default",eyeSeparation:"default"}}}var et,Zt=he(()=>{"use strict";et=Object.freeze({displaySizeM:Object.freeze([.3456,.1944]),displayPixels:Object.freeze([1920,1080]),nominalViewerM:.65,eyeSeparationM:.063})});function gt(n,e,t,i,r,s,o,a,l,c,h){if(s<0||s+a>t||o<0)return-1;let d=0,u=0,f=0,p=a*l;for(let _=0;_<l;_++){let x=(r+_)*e+i,R=(o+_)*e+t+s;for(let E=0;E<a;E++){let C=n[R+E];d+=C,u+=C*C,f+=n[x+E]*C}}let m=d/p,w=u/p-m*m;return w<1?-1:(f/p-c*m)/(h*Math.sqrt(w))}function ta(n,e,t,i,r,s){let o=0,a=0;for(let h=0;h<s;h++){let d=(i+h)*e+t;for(let u=0;u<r;u++){let f=n[d+u];o+=f,a+=f*f}}let l=r*s,c=o/l;return{mean:c,std:Math.sqrt(Math.max(0,a/l-c*c))}}function ye(n,e,t,i,r,s,o,{dMin:a,dMax:l,dyMax:c=2,uniq:h}={}){let d=e/2,{mean:u,std:f}=ta(n,e,i,r,s,o);if(f<6)return null;let p=-2,m=0,w=0,_=new Map,x=(M,g,S,y,O)=>{for(let I=y;I<=O;I++){let P=r+I;if(!(P<0||P+o>t))for(let N=M;N<=g;N+=S){let $=gt(n,e,d,i,r,i-N,P,s,o,u,f);$>(_.get(N)??-2)&&_.set(N,$),$>p&&(p=$,m=N,w=I)}}},R=l-a>8;if(x(a,l,R?2:1,-c,c),R&&p>-1){let M=m,g=w;x(Math.max(a,M-2),Math.min(l,M+2),1,Math.max(-c,g-1),Math.min(c,g+1))}if(p<-1)return null;let E=-2,C=M=>{let g=-2;for(let S=-c;S<=c;S++){let y=r+S;if(!(y<0||y+o>t))for(let O=M-1;O<=M+1;O++)g=Math.max(g,gt(n,e,d,i,r,i-O,y,s,o,u,f))}return g};for(let[M,g]of _){if(Math.abs(M-m)<3||g<=E)continue;let y=g>=(_.get(M-2)??-2)&&g>=(_.get(M+2)??-2)&&g>0?C(M):g;y>E&&(E=y)}if(l-a>12&&E>-2&&p-E<(h??.08))return null;let k=gt(n,e,d,i,r,i-(m-1),r+w,s,o,u,f),T=gt(n,e,d,i,r,i-(m+1),r+w,s,o,u,f),v=0,b=k-2*p+T;return k>-1&&T>-1&&b<0&&(v=Math.max(-.5,Math.min(.5,.5*(k-T)/b))),{d:m+v,dy:w,c:p}}function ia(n,e,t,i={}){let r=e/2,s=i.block||Math.max(8,Math.round(r/20)),o=i.step||s,a=i.dMax??Math.round(r*.3),l=i.dMin??-Math.round(r*.05),c=Math.round(r*(i.roiX0??.15)),h=Math.round(r*(i.roiX1??.85))-s,d=Math.round(t*(i.roiY0??.05)),u=Math.round(t*(i.roiY1??.85))-s,f=[];for(let p=d;p<=u;p+=o)for(let m=c;m<=h;m+=o){let w=ye(n,e,t,m,p,s,s,{dMin:l,dMax:a,dyMax:i.dyMax??2,uniq:i.uniq});w&&w.c>=(i.minNcc??.8)&&f.push({x:m,y:p,...w})}return f}function na(n,{tol:e=2,relTol:t=.1,minFrac:i=.12,minBlocks:r=3}={}){if(!n.length)return null;let s=Math.max(r,Math.ceil(n.length*i)),o=n.map(a=>a.d).sort((a,l)=>l-a);for(let a of o){let l=Math.max(e,t*Math.abs(a)),c=n.filter(h=>Math.abs(h.d-a)<=l);if(c.length>=s){let h=c.map(d=>d.d).sort((d,u)=>d-u);return{d:h[h.length>>1],members:c}}}return null}function ra(n,e){let t=Math.min(...n.map(l=>l.y)),r=n.filter(l=>l.y<=t+2*e).map(l=>l.x),s=Math.min(...r),o=Math.max(...r)+e,a=o-s;return{x:(s+o)/2,y:t+.4*1.3*a}}function Di(n,e,t,i={}){let r=e/2,s=i.block||Math.max(8,Math.round(r/20)),o=i.dMax??Math.round(r*.3),a=i.dMin??-Math.round(r*.05),l=i.focus||null,c="focus",h=0,d=null;if(!l){let R=ia(n,e,t,{...i,block:s,dMax:o,dMin:a});h=R.length;let E=na(R,i);if(!E)return null;l=ra(E.members,s),d=E.d,c="mode"}let u=Math.round(s*(i.refineW??3)),f=Math.round(s*(i.refineH??1.5)),p=Math.round(Math.max(0,Math.min(r-u,l.x-u/2))),m=Math.round(Math.max(0,Math.min(t-f,l.y-f/2))),w=d===null?a:Math.max(a,Math.floor(d)-4),_=d===null?o:Math.min(o,Math.ceil(d)+4),x=ye(n,e,t,p,m,u,f,{dMin:w,dMax:_,dyMax:i.dyMax??2});return x&&x.c>=(i.minNcc??.8)?{d:x.d,x:l.x,y:l.y,c:x.c,method:c,blocks:h}:d!==null?{d,x:l.x,y:l.y,c:0,method:c,blocks:h}:null}function _t(n,e){let t=new Uint8Array(e);for(let i=0,r=0;i<e;i++,r+=4)t[i]=n[r]*77+n[r+1]*150+n[r+2]*29>>8;return t}function we({n=3}={}){let e=[],t={value:null,push(i){if(i===null||!Number.isFinite(i))return t.value;e.push(i),e.length>n&&e.shift();let r=[...e].sort((s,o)=>s-o);return t.value=r[r.length>>1],t.value},reset(){e.length=0,t.value=null}};return t}function br(n,e,t,i,r,s){let o=new Float32Array(r*s);for(let a=0;a<s;a++)for(let l=0;l<r;l++)o[a*r+l]=n[(i+a)*e+t+l];return o}function sa(n,e,t,i,r,s,o,a,l,c){let h=e/2,d=r*s,u=0,f=0;for(let x=0;x<d;x++)u+=i[x],f+=i[x]*i[x];u/=d;let p=Math.sqrt(Math.max(1e-6,f/d-u*u)),m=-2,w=o,_=a;for(let x=Math.max(0,a-c);x<=Math.min(t-s,a+c);x++)for(let R=Math.max(0,o-l);R<=Math.min(h-r,o+l);R++){let E=0,C=0,k=0;for(let M=0;M<s;M++){let g=(x+M)*e+R;for(let S=0;S<r;S++){let y=n[g+S];E+=y,C+=y*y,k+=y*i[M*r+S]}}let T=E/d,v=C/d-T*T;if(v<1)continue;let b=(k/d-T*u)/(Math.sqrt(v)*p);b>m&&(m=b,w=R,_=x)}return{x:w,y:_,c:m}}function se({fullEveryMs:n=2e3,dWin:e=4,rx:t=12,ry:i=8,minTrackNcc:r=.75,jump:s=8}={}){let o=null,a=null;return{measure(c,h,d,u,f={}){let p=h/2,m=f.block||Math.max(8,Math.round(p/20)),w=Math.round(m*3),_=Math.round(m*1.5),x=null;if(o&&o.w===w&&o.h===_){let T=sa(c,h,d,o.tpl,w,_,o.x,o.y,t,i);if(T.c>=r){let v=ye(c,h,d,T.x,T.y,w,_,{dMin:Math.floor(o.d)-e,dMax:Math.ceil(o.d)+e,dyMax:2});v&&v.c>=.8&&(x={m:v,f:T})}}let R=({m:T,f:v})=>(o={...o,x:v.x,y:v.y,d:T.d,tpl:br(c,h,v.x,v.y,w,_)},{d:T.d,x:v.x+w/2,y:v.y+_/2,c:T.c,method:"track",blocks:0});if(x&&u-o.at<n)return R(x);let E=Di(c,h,d,f);if(x&&(!E||Math.abs(E.d-x.m.d)>s)){let T=E&&a&&Math.abs(a.d-E.d)<=3;if(a=E&&!T?{d:E.d}:null,!T)return o.at=u,R(x)}else a=null;if(!E)return o=null,null;let C=Math.round(Math.max(0,Math.min(p-w,E.x-w/2))),k=Math.round(Math.max(0,Math.min(d-_,E.y-_/2)));return o={x:C,y:k,d:E.d,tpl:br(c,h,C,k,w,_),w,h:_,at:u},E},reset(){o=null,a=null}}}function xr(n,e,t,i,r,s){let o=Math.max(1,s|0),a=Math.floor(i/o);a-=a&1;let l=Math.floor(r/o),c=new Uint8Array(a*l);if(o<=2){let u=o*o;for(let f=0;f<l;f++)for(let p=0;p<a;p++){let m=0;for(let w=0;w<o;w++){let _=e+(f*o+w)*t+p*o;for(let x=0;x<o;x++)m+=n[_+x]}c[f*a+p]=m/u|0}return{img:c,w:a,h:l}}let h=o>>2,d=3*o>>2;for(let u=0;u<l;u++){let f=e+(u*o+h)*t,p=e+(u*o+d)*t;for(let m=0;m<a;m++){let w=m*o+h,_=m*o+d;c[u*a+m]=n[f+w]+n[f+_]+n[p+w]+n[p+_]>>2}}return{img:c,w:a,h:l}}var vt=he(()=>{"use strict"});function St(n,e="@displayxr/inline3d"){if(n==null||n===!0)return{...be};n===!1&&(n="off");let t=()=>new Error(`${e}: cursor.soften ${JSON.stringify(n)} \u2014 expected ${wt.map(s=>`'${s}'`).join(" | ")} or { ${bt.join(", ")} }.`);if(typeof n=="string"){if(!wt.includes(n))throw t();return{...be,...Sr(n)}}if(typeof n!="object"||Array.isArray(n))throw t();let i=Object.keys(n).filter(s=>!bt.includes(s));if(i.length)throw new Error(`${e}: cursor.soften \u2014 unknown option(s) ${i.join(", ")}; expected ${bt.join(", ")}.`);if(n.mode!==void 0&&!wt.includes(n.mode))throw t();let r={...be,...Sr(n.mode??"both")};for(let s of Object.keys(xt)){if(n[s]===void 0)continue;let[o,a,l]=xt[s];if(!oa(s,n[s]))throw new Error(`${e}: cursor.soften.${s} must be a number in ${l?"(":"["}${o}, ${a}].`);r[s]=n[s]}return r}function Er(n,e="@displayxr/inline3d"){if(n==null||n===!1)return null;if(n==="depth"||n===!0)return{};if(typeof n!="object")throw new Error(`${e}: cursor ${JSON.stringify(n)} \u2014 expected 'depth' or { ${yt.join(", ")} }.`);let t=Object.keys(n).filter(i=>!yt.includes(i));if(t.length)throw new Error(`${e}: cursor \u2014 unknown option(s) ${t.join(", ")}; expected ${yt.join(", ")}.`);if(n.anchor!==void 0&&!Li.includes(n.anchor))throw new Error(`${e}: cursor.anchor "${n.anchor}" \u2014 expected ${Li.join(", ")}.`);if(n.pointerScope!==void 0&&n.pointerScope!=="canvas"&&n.pointerScope!=="window")throw new Error(`${e}: cursor.pointerScope "${n.pointerScope}" \u2014 expected 'canvas' or 'window'.`);if(n.debug!==void 0&&typeof n.debug!="boolean"&&n.debug!=="both")throw new Error(`${e}: cursor.debug ${JSON.stringify(n.debug)} \u2014 expected true, false or 'both'.`);for(let i of["height","margin"])if(n[i]!==void 0&&!(typeof n[i]=="number"&&n[i]>0&&Number.isFinite(n[i])))throw new Error(`${e}: cursor.${i} must be a positive number.`);if(n.soften!==void 0&&St(n.soften,e),n.shape!==void 0&&!xe.includes(n.shape))throw new Error(`${e}: cursor.shape ${JSON.stringify(n.shape)} \u2014 expected ${xe.map(i=>`'${i}'`).join(" | ")}.`);if(n.shapeFor!==void 0&&n.shapeFor!==null&&typeof n.shapeFor!="function")throw new Error(`${e}: cursor.shapeFor must be a function (hit) => shape.`);return{...n}}function Mt(n,e="@displayxr/inline3d"){let t=Er(n,e);if(!t)return null;let i=Object.keys(t).filter(r=>!Mr.includes(r));if(i.length)throw new Error(`${e}: cursor \u2014 ${i.join(", ")} not supported on a stereo pair; expected ${Mr.join(", ")}.`);return t}var Li,yt,Se,xe,wt,be,xt,bt,oa,Sr,Mr,Me=he(()=>{"use strict";Li=Object.freeze(["hybrid","screen","world"]),yt=Object.freeze(["height","margin","anchor","pointerScope","debug","soften","shape","shapeFor"]),Se=Object.freeze(["arrow","pointer","grab","grabbing","move","text","vertical-text","crosshair","not-allowed","help","wait","progress","copy","alias","context-menu","cell","ns-resize","ew-resize","nesw-resize","nwse-resize","col-resize","row-resize","zoom-in","zoom-out"]),xe=Object.freeze(["auto","none",...Se]),wt=Object.freeze(["both","off","alpha","blur"]),be=Object.freeze({blur:!0,alpha:!0,blurK:.1,blurMaxPx:8,blurMaxFrac:.06,alphaMin:.5,fullD:.03}),xt=Object.freeze({blurK:[0,1e3,!1],blurMaxPx:[0,8,!1],blurMaxFrac:[0,.5,!1],alphaMin:[0,1,!1],fullD:[0,1e3,!0]}),bt=Object.freeze(["mode",...Object.keys(xt)]),oa=(n,e)=>{let[t,i,r]=xt[n];return typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=i&&!(r&&e<=t)},Sr=n=>({blur:n==="both"||n==="blur",alpha:n==="both"||n==="alpha"});Mr=Object.freeze(["height","pointerScope","soften","shape","shapeFor"])});function Hi(n){return typeof n=="string"&&Xr[n.trim().toLowerCase()]||"arrow"}function pa(n){let e=[],t=0,i="",r="";for(let s=0;s<n.length;s++){let o=n[s];if(i){if(o==="\\"&&s+1<n.length){r+=o+n[++s];continue}o===i&&(i="")}else if(o==='"'||o==="'")i=o;else if(o==="(")t++;else if(o===")")t=Math.max(0,t-1);else if(o===","&&t===0){e.push(r.trim()),r="";continue}r+=o}return r.trim()&&e.push(r.trim()),e}function $i(n){if(typeof n!="string")return{images:[],keyword:"auto"};let e=kt.get(n);if(e)return e;let t=[],i="auto";for(let r of pa(n)){let s=/^url\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^)\s]*))\s*\)\s*(.*)$/is.exec(r);if(s){let o=(s[1]??s[2]??s[3]??"").replace(/\\(.)/g,"$1"),a=(s[4]||"").trim().split(/\s+/).filter(Boolean).map(Number),l=a.length===2&&a.every(Number.isFinite)?[a[0],a[1]]:null;o&&t.push({url:o,hotspot:l});continue}/^(-webkit-)?image-set\(/i.test(r)||(i=r.trim().toLowerCase())}return e=Object.freeze({images:Object.freeze(t),keyword:i}),kt.size>64&&kt.clear(),kt.set(n,e),e}function Gr(n){return Hi($i(n).keyword)}function qr(n,e=0){if(!n||n.byteLength<22)return null;let t=new DataView(n);if(t.getUint16(0,!0)!==0||t.getUint16(2,!0)!==2)return null;let i=t.getUint16(4,!0),r=-1;for(let o=0;o<i&&6+16*o+16<=n.byteLength;o++){let a=t.getUint8(6+16*o)||256;if((r<0||a===e)&&(r=o),a===e)break}if(r<0)return null;let s=6+16*r;return[t.getUint16(s+4,!0),t.getUint16(s+6,!0)]}function Yr(n,e=Ui){let t=$i(n);for(let i of t.images){let r=e.get(i.url);if(r.state==="failed")continue;if(r.state!=="ready")break;let s=Math.min(1,Br/Math.max(r.width,r.height)),o=i.hotspot||r.curHotspot||[0,0],a=r.width*s,l=r.height*s,c=[Math.min(a,Math.max(0,o[0]*s)),Math.min(l,Math.max(0,o[1]*s))];return{kind:"image",key:i.url,entry:r,width:a,height:l,hotspot:c}}return Re(Hi(t.keyword))}function Re(n){if(n==="none")return{kind:"none"};let e=Se.includes(n)?n:"arrow";return{kind:"shape",name:e,key:`shape:${e}`}}function A(n,e,t,i,[r=0,s=0,o=0,a=0]=[]){let l=[],c=(h,d)=>{let u=l[l.length-1];(!u||Math.abs(u[0]-h)>1e-9||Math.abs(u[1]-d)>1e-9)&&l.push([h,d])};return c(n+r,e),c(t-s,e),c(t,e+s),c(t,i-o),c(t-o,i),c(n+a,i),c(n,i-a),c(n,e+r),l.length>1&&Math.abs(l[0][0]-l[l.length-1][0])<1e-9&&Math.abs(l[0][1]-l[l.length-1][1])<1e-9&&l.pop(),l}function Ot(n,e,t,i,r,s=r/3.5){let o=t-n,a=i-e,l=Math.hypot(o,a),c=o/l,h=a/l,d=-h*(r/2),u=c*(r/2),f=t-c*s,p=i-h*s,m=1-2*s/r;return ke([[n+d,e+u],[f+d,p+u],[t+d*m,i+u*m],[t-d*m,i-u*m],[f-d,p-u],[n-d,e-u]])}function Wr(n,e,t,i,r){let s=t-n,o=i-e,a=Math.hypot(s,o),l=-o/a*(r/2),c=s/a*(r/2);return ke([[n+l,e+c],[t+l,i+c],[t-l,i-c],[n-l,e-c]])}function Kr(n,e,t,i=20){return ke(Array.from({length:i},(r,s)=>[n+t*Math.cos(2*Math.PI*s/i),e+t*Math.sin(2*Math.PI*s/i)]))}function ga(n,e,t,i,r=24){let s=[],o=(a,l)=>[n+a*Math.cos(l),e+a*Math.sin(l)];for(let a=0;a<r;a++){let l=[0,1,2,3].map(c=>2*Math.PI*(a+c)/r);s.push(ke([...l.map(c=>o(i,c)),...l.reverse().map(c=>o(t,c))]))}return s}function va(){return{pointer:{hot:[6.8,0],parts:[A(5,0,8.6,14,[1.2,1.2,0,0]),A(7.6,5.4,10.9,14,[1.1,1.1,0,0]),A(9.9,6.4,13.2,14,[1.1,1.1,0,0]),A(12.2,7.6,15.2,14,[.9,.9,0,0]),A(4.2,10.8,15.2,19,[0,0,3,2.2]),Ot(7.4,15,1,9,3.6)]},grab:{hot:[8.6,12.5],parts:[A(3,2.6,6.6,12.4,[1.2,1.2,0,0]),A(5.6,.6,9.2,12.4,[1.2,1.2,0,0]),A(8.2,1.4,11.8,12.4,[1.2,1.2,0,0]),A(10.8,3.6,14.2,12.4,[1.1,1.1,0,0]),A(3,9.4,14.2,18,[0,0,2.6,2.6]),Ot(6.2,14.4,.4,7,3.6)]},grabbing:{hot:[8.6,13],parts:[A(3,5.6,6.6,12.4,[1.2,1.2,0,0]),A(5.6,5,9.2,12.4,[1.2,1.2,0,0]),A(8.2,5.2,11.8,12.4,[1.2,1.2,0,0]),A(10.8,6,14.2,12.4,[1.1,1.1,0,0]),A(3,9.4,14.2,18,[0,0,2.6,2.6]),Ot(6,14.2,1.2,9,3.6)]},move:{hot:[9.5,9.5],parts:[A(3,7.8,16,11.2),A(7.8,3,11.2,16),V([9.5,0],[14,4.6],[5,4.6]),V([9.5,19],[5,14.4],[14,14.4]),V([0,9.5],[4.6,5],[4.6,14]),V([19,9.5],[14.4,14],[14.4,5])]},text:{hot:[9.5,9.5],parts:[A(8,.5,11,18.5),A(4.5,0,14.5,3),A(4.5,16,14.5,19)]},"vertical-text":{hot:[9.5,9.5],parts:Ge([A(8,.5,11,18.5),A(4.5,0,14.5,3),A(4.5,16,14.5,19)],90,9.5,9.5)},crosshair:{hot:[9.5,9.5],parts:[A(0,8,19,11),A(8,0,11,19)]},cell:{hot:[9.5,9.5],parts:[A(1.5,6.3,17.5,12.7),A(6.3,1.5,12.7,17.5)]},"not-allowed":{hot:[9.5,9.5],parts:[...ga(9.5,9.5,5.4,8.8),Wr(4.6,4.6,14.4,14.4,3.4)]},help:{hot:[0,0],parts:[...oe(qe(),.8),Kr(13.6,12.4,5.4)],detail:[A(11.6,9,15.4,10.2),A(14.4,9,15.6,12.6),A(12.9,11.6,15.6,12.8),A(12.9,11.6,14.1,13.8),A(12.9,14.8,14.1,16)]},wait:{hot:[9.5,9.5],parts:_a()},progress:{hot:[0,0],parts:[...oe(qe(),.8),A(10.6,9,18.8,11.6),A(10.6,16.4,18.8,19),V([11.4,10.2],[18,10.2],[14.7,14.4]),V([14.7,13.6],[18,17.8],[11.4,17.8])]},copy:{hot:[0,0],parts:[...oe(qe(),.8),A(9.6,9.8,18.8,19,[1.2,1.2,1.2,1.2])],detail:[A(13.6,11.8,14.8,17),A(11.6,13.8,16.8,15)]},alias:{hot:[0,0],parts:[...oe(qe(),.8),A(9.6,9.8,18.8,19,[1.2,1.2,1.2,1.2])],detail:[Wr(11.8,16.8,15.6,13,1.3),V([16.8,11.8],[16.8,15.4],[13.2,11.8])]},"context-menu":{hot:[0,0],parts:[...oe(qe(),.8),A(9.2,8.6,18.8,19)],detail:[A(11,10.8,17,11.8),A(11,13.3,17,14.3),A(11,15.8,17,16.8)]},"ns-resize":{hot:[9.5,9.5],parts:Tt()},"ew-resize":{hot:[9.5,9.5],parts:Ge(Tt(),90,9.5,9.5)},"nesw-resize":{hot:[9.5,9.5],parts:oe(Ge(Tt(),45,9.5,9.5),1.2,-1.9,-1.9)},"nwse-resize":{hot:[9.5,9.5],parts:oe(Ge(Tt(),-45,9.5,9.5),1.2,-1.9,-1.9)},"col-resize":{hot:[9.5,9.5],parts:Hr()},"row-resize":{hot:[9.5,9.5],parts:Ge(Hr(),90,9.5,9.5)},"zoom-in":{hot:[7.5,7.5],parts:$r(),detail:[A(4.4,6.9,10.6,8.1),A(6.9,4.4,8.1,10.6)]},"zoom-out":{hot:[7.5,7.5],parts:$r(),detail:[A(4.4,6.9,10.6,8.1)]}}}function Vi(n){let e=Se.includes(n)?n:"arrow",t=Ur.get(e);if(t)return t;let i=c=>Object.freeze(c.map(h=>Object.freeze(h.map(d=>Object.freeze(d))))),r,s,o;if(e==="arrow")r=[ee],s=[ts],o=[];else{let c=(ya||=va())[e],h=d=>d.map(u=>u.map(([f,p])=>[(f-c.hot[0])/19,(p-c.hot[1])/19]));r=i(h(c.parts)),s=i(r.map(d=>Lt(1/19,d))),o=i(h(c.detail||[]))}let a=r.flat().map(c=>c[0]),l=r.flat().map(c=>c[1]);return t=Object.freeze({name:e,parts:Object.freeze(r),fill:Object.freeze(s),detail:Object.freeze(o),box:Object.freeze([Math.min(...a),Math.min(...l),Math.max(...a),Math.max(...l)])}),Ur.set(e,t),t}function Te(n,e=1/19){let t=Vi(n);return Math.abs(e-1/19)<1e-12?{outline:t.parts,fill:t.fill,detail:t.detail}:{outline:t.parts,fill:t.parts.map(i=>Lt(e,i)),detail:t.detail}}function Jr(n,e,t=0){let i=Vi(n).box,r=(e>0&&Number.isFinite(e)?e:0)+(t>0&&Number.isFinite(t)?t:0);return[i[0]-r,i[1]-r,i[2]+r,i[3]+r]}function Zr(n,e,t,i,r,s=Yi,o=Ki,a=Te(n)){let l=0,c=0,h=0,d=0,u=0,f=i>0?Ke:Ke.slice(0,1),p=a.detail&&a.detail.length?a.detail:null;for(let[m,w,_]of f){let x=e+m*i,R=t+w*i,E=Wi(zi(a.outline,x,R),r),C=E>0?Wi(zi(a.fill,x,R),r):0;p&&C>0&&(C*=1-Wi(zi(p,x,R),r)),l+=_*(o[0]*E+(s[0]-o[0])*C),c+=_*(o[1]*E+(s[1]-o[1])*C),h+=_*(o[2]*E+(s[2]-o[2])*C),d+=_*E,u+=_}return d/=u,d>1e-5?[l/u/d,c/u/d,h/u/d,d]:[0,0,0,0]}function Bi(n,e,t,i,r,s,o=Yi,a=Ki,l=Te(n)){let c=i>0&&Number.isFinite(i)?i:1,h=1/c,[d,u,f,p]=Jr(n,r,h),m=Math.floor(e+d*c),w=Math.floor(t+u*c),_=Math.max(1,Math.ceil(e+f*c)-m),x=Math.max(1,Math.ceil(t+p*c)-w),R=new Uint8ClampedArray(_*x*4),E=s>=0&&s<=1?s:1;for(let C=0;C<x;C++){let k=(w+C+.5-t)/c;for(let T=0;T<_;T++){let v=Zr(n,(m+T+.5-e)/c,k,r,h,o,a,l);if(!(v[3]>0))continue;let b=(C*_+T)*4;R[b]=Math.round(v[0]*255),R[b+1]=Math.round(v[1]*255),R[b+2]=Math.round(v[2]*255),R[b+3]=Math.round(v[3]*E*255)}}return{x0:m,y0:w,width:_,height:x,data:R}}function Xi(n,e,t,i,r,s=Te(e),o="#fff",a="#000"){for(let[l,c]of[[s.outline,a],[s.fill,o],[s.detail||[],a]]){n.fillStyle=c;for(let h of l)n.beginPath(),h.forEach(([d,u],f)=>(f?n.lineTo:n.moveTo).call(n,t+d*r,i+u*r)),n.closePath(),n.fill()}}function Gi(n,e,t,i,r){let s=i>0&&Number.isFinite(i)?Math.ceil(i)+1:0,o=e+2*s,a=t+2*s,l=new Uint8ClampedArray(o*a*4),c=r>=0&&r<=1?r:1,h=s?Ke:Ke.slice(0,1);for(let d=0;d<a;d++)for(let u=0;u<o;u++){let f=0,p=0,m=0,w=0,_=0;for(let[R,E,C]of h){_+=C;let k=Math.round(u-s+R*i),T=Math.round(d-s+E*i);if(k<0||T<0||k>=e||T>=t)continue;let v=(T*e+k)*4,b=n[v+3]/255*C;f+=n[v]*b,p+=n[v+1]*b,m+=n[v+2]*b,w+=b}if(!(w>1e-5))continue;let x=(d*o+u)*4;l[x]=f/w,l[x+1]=p/w,l[x+2]=m/w,l[x+3]=w/_*c*255}return{pad:s,width:o,height:a,data:l}}function Dt(n=globalThis.document){if(!n||!n.createElement)return!1;let e="inline3d-cursor-style";if(n.getElementById&&n.getElementById(e))return!0;let t=n.createElement("style");return t.id=e,t.textContent=Vr,(n.head||n.documentElement)?.appendChild(t),!0}function es(n,e){let t=globalThis.getComputedStyle;if(!n||typeof t!="function")return null;let i=[];for(let r of e)r&&r.hasAttribute&&r.hasAttribute(B)&&(i.push([r,r.getAttribute(B)]),r.removeAttribute(B));try{let r=t(n).cursor;return typeof r=="string"?r:null}catch{return null}finally{for(let[r,s]of i)r.setAttribute(B,s??"")}}var B,Vr,Br,Xr,fa,kt,ma,At,Ui,ke,V,Ge,oe,qe,Tt,Hr,_a,$r,ya,Ur,zi,Wi,Qr,Pt,Ye,qi=he(()=>{"use strict";Ji();Me();B="data-inline3d-cursor-hidden",Vr=`[${B}],[${B}] *{cursor:none!important}`,Br=128,Xr=Object.freeze({auto:"arrow",default:"arrow",none:"none",pointer:"pointer",grab:"grab","-webkit-grab":"grab",grabbing:"grabbing","-webkit-grabbing":"grabbing",move:"move","all-scroll":"move",text:"text","vertical-text":"vertical-text",crosshair:"crosshair","not-allowed":"not-allowed","no-drop":"not-allowed",help:"help",wait:"wait",progress:"progress",copy:"copy",alias:"alias","context-menu":"context-menu",cell:"cell","n-resize":"ns-resize","s-resize":"ns-resize","ns-resize":"ns-resize","e-resize":"ew-resize","w-resize":"ew-resize","ew-resize":"ew-resize","ne-resize":"nesw-resize","sw-resize":"nesw-resize","nesw-resize":"nesw-resize","nw-resize":"nwse-resize","se-resize":"nwse-resize","nwse-resize":"nwse-resize","col-resize":"col-resize","row-resize":"row-resize","zoom-in":"zoom-in","-webkit-zoom-in":"zoom-in","zoom-out":"zoom-out","-webkit-zoom-out":"zoom-out"}),fa=Object.freeze(Object.keys(Xr));kt=new Map;ma=n=>/\.cur(?:[?#]|$)/i.test(n)||/^data:image\/(?:x-win-bitmap|x-icon|vnd\.microsoft\.icon)/i.test(n),At=class{constructor({ImageCtor:e=globalThis.Image,fetchFn:t=globalThis.fetch}={}){this._Image=e,this._fetch=t,this._m=new Map}get(e){let t=this._m.get(e);if(t)return t;if(t={url:e,state:"loading",image:null,width:0,height:0,curHotspot:null},this._m.set(e,t),typeof this._Image!="function")return t.state="failed",t;let i=new this._Image;i.crossOrigin="anonymous";let r=1,s=()=>{--r>0||t.state==="failed"||(t.state="ready")};return i.onload=()=>{let o=i.naturalWidth||i.width,a=i.naturalHeight||i.height;if(!(o>0&&a>0))return void(t.state="failed");t.image=i,t.width=o,t.height=a,s()},i.onerror=()=>{t.state="failed"},ma(e)&&typeof this._fetch=="function"&&(r++,Promise.resolve().then(()=>this._fetch(e,e.startsWith("data:")?void 0:{mode:"cors"})).then(o=>o&&o.ok!==!1?o.arrayBuffer():null).then(o=>{t.curHotspot=o?qr(o,t.width):null}).catch(()=>{}).finally(s)),i.src=e,t}},Ui=new At;ke=n=>{let e=0;for(let t=0;t<n.length;t++){let[i,r]=n[t],[s,o]=n[(t+1)%n.length];e+=i*o-s*r}return e>0?n:n.reverse()};V=(n,e,t)=>ke([n,e,t]),Ge=(n,e,t,i)=>{let r=e*Math.PI/180,s=Math.cos(r),o=Math.sin(r);return n.map(a=>ke(a.map(([l,c])=>[t+(l-t)*s-(c-i)*o,i+(l-t)*o+(c-i)*s])))},oe=(n,e,t=0,i=0)=>n.map(r=>r.map(([s,o])=>[s*e+t,o*e+i])),qe=()=>[ee.map(([n,e])=>[n*19,e*19])],Tt=()=>[A(8,3,11,16),V([9.5,0],[14.2,5],[4.8,5]),V([9.5,19],[4.8,14],[14.2,14])],Hr=()=>[A(8,1,11,18),A(3.4,8,7.4,11),V([0,9.5],[4.4,5],[4.4,14]),A(11.6,8,15.6,11),V([19,9.5],[14.6,14],[14.6,5])],_a=()=>[A(3,0,16,3),A(3,16,16,19),V([4.2,.5],[14.8,.5],[9.5,10]),V([9.5,9],[14.8,18.5],[4.2,18.5])],$r=()=>[Kr(7.5,7.5,7),Ot(11.6,11.6,18.4,18.4,3.8,1)];ya=null,Ur=new Map;zi=(n,e,t)=>{let i=1/0;for(let r of n)i=Math.min(i,is(r,e,t));return i},Wi=(n,e)=>e>0?Math.min(1,Math.max(0,.5-n/e)):n<0?1:0;Qr=100;Pt=class{constructor(e,{throttleMs:t=Qr}={}){this.pointer=e,this.throttleMs=t,this.css=null,this.reads=0,this._el=null,this._stale=!0,this._urgent=!0,this._lastRead=-1/0;let i=r=>s=>{let o=typeof s.composedPath=="function"?s.composedPath():null,a=o&&o.length?o[0]:s.target;a&&a.nodeType===1&&(this._el=a),this._stale=!0,r&&(this._urgent=!0)};this._onMove=i(!1),this._onPress=i(!0),this._target=e.scope==="window"?globalThis:e.canvas,this._target&&this._target.addEventListener&&(this._target.addEventListener("pointermove",this._onMove),this._target.addEventListener("pointerdown",this._onPress),this._target.addEventListener("pointerup",this._onPress),this._target.addEventListener("pointercancel",this._onPress))}value(e=globalThis.performance?globalThis.performance.now():Date.now()){return this._stale&&(this._urgent||this.css===null||e-this._lastRead>=this.throttleMs)&&this.read(e),this.css??"auto"}shape(e){return Gr(this.value(e))}read(e=globalThis.performance?globalThis.performance.now():Date.now()){let t=globalThis.document,i=this.pointer.canvas,r=this._el;r&&r.isConnected===!1&&(r=null);let s=es(r||i,[i,t&&t.documentElement]);return this.reads++,this._lastRead=e,this._stale=!1,this._urgent=!1,s!==null&&(this.css=s),this.css??"auto"}dispose(){this._target&&this._target.removeEventListener&&(this._target.removeEventListener("pointermove",this._onMove),this._target.removeEventListener("pointerdown",this._onPress),this._target.removeEventListener("pointerup",this._onPress),this._target.removeEventListener("pointercancel",this._onPress))}},Ye=class{constructor(e,{shape:t="auto",shapeFor:i=null,images:r=Ui}={}){if(!xe.includes(t))throw new Error(`@displayxr/inline3d: cursor.shape "${t}" \u2014 expected ${xe.join(", ")}.`);this.option=t,this.shapeFor=typeof i=="function"?i:null,this.images=r,this.reader=t==="auto"?new Pt(e):null,this.sprite=Re(t==="auto"?"arrow":t)}get current(){return this.sprite.kind==="shape"?this.sprite.name:this.sprite.kind}pick(e,t){let i=this.reader?this.reader.value(t):null,r=i===null?null:Yr(i,this.images),s=r?r.kind==="shape"?r.name:r.kind:null,o;if(this.shapeFor)try{o=this.shapeFor({...e,css:s,cssValue:i})}catch(l){this._warned||(this._warned=!0,console.warn("[inline3d] cursor.shapeFor threw; using the page cursor.",l))}let a=l=>l==="none"||Se.includes(l);return a(o)?this.sprite=Re(o):a(this.option)?this.sprite=Re(this.option):this.sprite=r||Re("arrow"),this.sprite}dispose(){this.reader?.dispose()}}});function os(n){return n>0&&Number.isFinite(n)?Math.min(.5,en/n):wa}function as(n,e){return n<=ba?!(e>0&&Number.isFinite(e))||-n*e>=xa:!1}function tn(n,e,t){if(!e||!Number.isFinite(t)||!(t<0))return 0;let i=Math.min(0,Number.isFinite(n.maxDisparity)?n.maxDisparity:0);return Math.min(i,Math.max(n.minDisparity,t-n.margin))}function ls(n,e,t,i){if(!n.primed||i<n.last||i-n.last>e.stale)return n.primed=!0,n.disparity=t,n.last=i,t;if(i===n.last)return n.disparity;let r=i-n.last,s=t<n.disparity?e.riseTau:e.sinkTau,o=s>0?1-Math.exp(-r/s):1;return n.disparity+=o*(t-n.disparity),n.last=i,n.disparity}function ns(n){let e=n&&n.pointerType;return!e||e==="mouse"?!0:e==="pen"?!(n.buttons>0):!1}function Sa(n){return!!n&&"onpointerrawupdate"in n&&globalThis.isSecureContext!==!1}function Ma(n){let e=globalThis.document;if(!e||!e.documentElement)return;n&&Dt(e),Zi=Math.max(0,Zi+(n?1:-1));let t=e.documentElement;Zi>0?t.setAttribute?.(B,""):t.removeAttribute?.(B)}function rs(n){return!!n&&typeof n.setCursorDepth=="function"&&typeof n.getCursorDepthSupport=="function"}function ka(n,e,t,i){let r=.75*t,s=[[n,e]];for(let o=0;o<8;o++){let a=o*Math.PI/4;s.push([n+r*Math.cos(a)/i,e+r*Math.sin(a)])}return s}function cs(n,e,t,i){return[[n,e],...ka(n+.3*t/i,e+.5*t,t,i)]}function Lt(n,e=ee){let t=0;for(let s=0;s<e.length;s++){let[o,a]=e[s],[l,c]=e[(s+1)%e.length];t+=o*c-l*a}let i=t>0?1:-1,r=e.map((s,o)=>{let a=e[(o+1)%e.length],l=a[0]-s[0],c=a[1]-s[1],h=Math.hypot(l,c)||1;return[-c/h*i,l/h*i]});return e.map((s,o)=>{let a=r[(o+e.length-1)%e.length],l=r[o],c=n/(1+a[0]*l[0]+a[1]*l[1]);return[s[0]+(a[0]+l[0])*c,s[1]+(a[1]+l[1])*c]})}function hs(n,e,t,i=be){let r={blurPx:0,alpha:1},s=i;if(!s)return r;if(s.blur&&Number.isFinite(e)&&s.blurK>0&&s.blurMaxPx>0){let o=s.blurMaxPx;if(s.blurMaxFrac>0&&Number.isFinite(t)&&t>0){let l=s.blurMaxFrac*t;o=l<o?l:o}let a=s.blurK*Math.abs(e);r.blurPx=a<o?a:o}if(s.alpha&&Number.isFinite(n)&&s.fullD>0){let o=Math.abs(n)/s.fullD;o=o<1?o:1;let a=o*o*(3-2*o),l=s.alphaMin<0?0:s.alphaMin>1?1:s.alphaMin;r.alpha=1-(1-l)*a}return r}function is(n,e,t){let i=(e-n[0][0])**2+(t-n[0][1])**2,r=1;for(let s=0,o=n.length-1;s<n.length;o=s,s++){let a=n[s],l=n[o],c=l[0]-a[0],h=l[1]-a[1],d=e-a[0],u=t-a[1],f=Math.min(1,Math.max(0,(d*c+u*h)/(c*c+h*h))),p=d-c*f,m=u-h*f;i=Math.min(i,p*p+m*m);let w=t>=a[1],_=t<l[1],x=c*u>h*d;(w&&_&&x||!w&&!_&&!x)&&(r=-r)}return r*Math.sqrt(i)}var wa,en,ba,xa,Nt,It,Zi,Ea,Ca,Ra,Qi,Ft,ss,ee,ic,ts,Yi,Ki,Ke,nc,rc,sc,Ji=he(()=>{"use strict";Me();Me();qi();qi();wa=.03,en=19;ba=-.005,xa=.5;Nt=Object.freeze({margin:.015,minDisparity:-.6,maxDisparity:0,riseTau:.03,sinkTau:.25,stale:.5});It=class{constructor(e,{scope:t="canvas",keepCss:i=!1}={}){if(t!=="canvas"&&t!=="window")throw new Error(`@displayxr/inline3d: cursor pointerScope "${t}" \u2014 expected 'canvas' or 'window'.`);this.canvas=e,this.scope=t,this.keepCss=!!i,this._uv=null,this.sampleTime=0,this.samples=0,this._hidden=!1,this._cx=0,this._cy=0,this._pending=!1,this._onMove=r=>this._sample(r),this._onLeave=()=>{this.uv=null},this._onDown=r=>{ns(r)||(this.uv=null)},this._target=t==="window"?globalThis:e,this.source=Sa(this._target)?"pointerrawupdate":"pointermove",this._target.addEventListener("pointermove",this._onMove),this.source==="pointerrawupdate"&&this._target.addEventListener("pointerrawupdate",this._onMove),this._target.addEventListener("pointerdown",this._onDown),t==="window"?(this._onOut=r=>{r.relatedTarget||(this.uv=null)},globalThis.addEventListener("pointerout",this._onOut),globalThis.addEventListener("blur",this._onLeave)):e.addEventListener("pointerleave",this._onLeave)}get uv(){if(this._pending){this._pending=!1;let e=this.canvas.getBoundingClientRect();if(!(e.width>0&&e.height>0))this._uv=null;else{let t=(this._cx-e.left)/e.width,i=(this._cy-e.top)/e.height;this._uv=t>=0&&t<=1&&i>=0&&i<=1?[t,i]:null}}return this._uv}set uv(e){this._pending=!1,this._uv=e}_sample(e){if(!ns(e)){this.uv=null;return}let t=typeof e.getCoalescedEvents=="function"?e.getCoalescedEvents():null,i=t&&t.length?t[t.length-1]:e,r=i.timeStamp>0?i.timeStamp:e.timeStamp>0?e.timeStamp:globalThis.performance?globalThis.performance.now():Date.now();r<this.sampleTime||(this.samples++,this.sampleTime=r,this._cx=i.clientX,this._cy=i.clientY,this._pending=!0)}set(e,t){this.uv=e==null?null:[e,t]}aspect(){let e=this.canvas.getBoundingClientRect();return e.height>0?e.width/e.height:1}cssHeight(){let e=this.canvas.getBoundingClientRect();return e.height>0?e.height:0}panelPx(){return this.cssHeight()*(globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1)}panelSize(){let e=this.canvas.getBoundingClientRect(),t=globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1;return e.width>0&&e.height>0?[e.width*t,e.height*t]:[0,0]}hideCss(e){this.keepCss&&(e=!1),e!==this._hidden&&(this.scope==="window"?Ma(e):this.canvas.setAttribute&&(e?(Dt(),this.canvas.setAttribute(B,"")):this.canvas.removeAttribute(B)),this._hidden=e)}dispose(){this._target.removeEventListener("pointermove",this._onMove),this.source==="pointerrawupdate"&&this._target.removeEventListener("pointerrawupdate",this._onMove),this._target.removeEventListener("pointerdown",this._onDown),this.scope==="window"?(globalThis.removeEventListener("pointerout",this._onOut),globalThis.removeEventListener("blur",this._onLeave)):this.canvas.removeEventListener("pointerleave",this._onLeave),this.hideCss(!1)}};Zi=0;Ea=2e3,Ca=6,Ra=1e4;Qi=new WeakMap,Ft=class{constructor(){this.target=null,this._sent=!1,this.last=null}get support(){let e=this.target;if(!rs(e))return"none";let t=Qi.get(e);return t?t.state:"pending"}get drawing(){return this.support==="runtime"}bind(e){let t=e||null;if(t!==this.target&&(this.withdraw(),this.target=t),!rs(t))return!1;let i=Qi.get(t);if(i||Qi.set(t,i={state:"pending",probes:0,inFlight:!1,at:0}),i.state==="runtime"||i.inFlight)return i.state==="runtime";let r=globalThis.performance?globalThis.performance.now():Date.now(),s=i.probes<Ca?Ea:Ra;if(i.probes===0||r-i.at>=s){i.probes++,i.at=r,i.inFlight=!0;let o;try{o=Promise.resolve(t.getCursorDepthSupport())}catch(a){o=Promise.reject(a)}o.then(a=>{i.inFlight=!1,i.state=a==="runtime"?"runtime":"none"},()=>{i.inFlight=!1,i.state="none"})}return i.state==="runtime"}report(e,t,i){if(!this.drawing)return!1;let r={u:ss(e),v:ss(t)};i!=null&&Number.isFinite(i)&&(r.disparityPx=i);try{this.target.setCursorDepth(r)}catch{return!1}return this._sent=!0,this.last={u:r.u,v:r.v,disparityPx:r.disparityPx??null},!0}withdraw(){if(this.last=null,!!this._sent){this._sent=!1;try{this.target?.setCursorDepth()}catch{}}}dispose(){this.withdraw(),this.target=null}},ss=n=>n>0?n<1?n:1:0;ee=Object.freeze([[0,0],[0,16],[4.2,12.4],[6.9,18.6],[9.5,17.5],[6.8,11.5],[11.7,11.5]].map(([n,e])=>Object.freeze([n/19,e/19]))),ic=Object.freeze([[0,1,2],[0,2,5],[0,5,6],[2,3,4],[2,4,5]]);ts=Object.freeze(Lt(1/19).map(n=>Object.freeze(n))),Yi=Object.freeze([1,1,1,1]),Ki=Object.freeze([.02,.02,.03,1]);Ke=Object.freeze([Object.freeze([0,0,1]),...[[.5,0],[-.5,0],[0,.5],[0,-.5]].map(([n,e])=>Object.freeze([n,e,.7066])),...Array.from({length:8},(n,e)=>{let t=.3927+.7854*e;return Object.freeze([Math.cos(t),Math.sin(t),.2494])})]),nc=Object.freeze([Math.max(...ee.map(n=>n[0])),Math.max(...ee.map(n=>n[1]))]);rc=Object.freeze({declarations:`#ifdef PICK_PASS
1
+ /* @displayxr/inline3d 1.49.1 — dist/call.js — Apache-2.0 — https://github.com/DisplayXR/displayxr-web */
2
+ var uo=Object.defineProperty;var fe=(i,e)=>()=>(i&&(e=i(i=0)),e);var fo=(i,e)=>{for(var t in e)uo(i,t,{get:e[t],enumerable:!0})};function Fi(i,e,t=1){let n=st,r=!!i&&i.displayWidthMeters>0&&i.displayHeightMeters>0&&i.displayPixelWidth>0&&i.displayPixelHeight>0,s=r?[i.displayWidthMeters,i.displayHeightMeters]:[...n.displaySizeM],o=r?[i.displayPixelWidth,i.displayPixelHeight]:[...n.displayPixels],a=(s[0]/o[0]+s[1]/o[1])/2,l=t>0?t:1,c=r?a*l:a*(o[1]/Math.max(1,globalThis.innerHeight||o[1])),h=i?.nominalViewerPosition?.z,u=Number.isFinite(h)&&h>.1;return{canvasSizeM:[(e?.width||0)*c,(e?.height||0)*c],metersPerCssPx:c,displaySizeM:s,nominalViewerM:u?h:n.nominalViewerM,eyeSeparationM:n.eyeSeparationM,source:{size:r?"display":"default",viewer:u?"display":"default",eyeSeparation:"default"}}}var st,an=fe(()=>{"use strict";st=Object.freeze({displaySizeM:Object.freeze([.3456,.1944]),displayPixels:Object.freeze([1920,1080]),nominalViewerM:.65,eyeSeparationM:.063})});function Mt(i,e,t,n,r,s,o,a,l,c,h){if(s<0||s+a>t||o<0)return-1;let u=0,d=0,p=0,f=a*l;for(let b=0;b<l;b++){let w=(r+b)*e+n,M=(o+b)*e+t+s;for(let S=0;S<a;S++){let k=i[M+S];u+=k,d+=k*k,p+=i[w+S]*k}}let g=u/f,x=d/f-g*g;return x<1?-1:(p/f-c*g)/(h*Math.sqrt(x))}function ma(i,e,t,n,r,s){let o=0,a=0;for(let h=0;h<s;h++){let u=(n+h)*e+t;for(let d=0;d<r;d++){let p=i[u+d];o+=p,a+=p*p}}let l=r*s,c=o/l;return{mean:c,std:Math.sqrt(Math.max(0,a/l-c*c))}}function be(i,e,t,n,r,s,o,{dMin:a,dMax:l,dyMax:c=2,uniq:h}={}){let u=e/2,{mean:d,std:p}=ma(i,e,n,r,s,o);if(p<6)return null;let f=-2,g=0,x=0,b=new Map,w=(v,m,_,y,C)=>{for(let I=y;I<=C;I++){let T=r+I;if(!(T<0||T+o>t))for(let N=v;N<=m;N+=_){let $=Mt(i,e,u,n,r,n-N,T,s,o,d,p);$>(b.get(N)??-2)&&b.set(N,$),$>f&&(f=$,g=N,x=I)}}},M=l-a>8;if(w(a,l,M?2:1,-c,c),M&&f>-1){let v=g,m=x;w(Math.max(a,v-2),Math.min(l,v+2),1,Math.max(-c,m-1),Math.min(c,m+1))}if(f<-1)return null;let S=-2,k=v=>{let m=-2;for(let _=-c;_<=c;_++){let y=r+_;if(!(y<0||y+o>t))for(let C=v-1;C<=v+1;C++)m=Math.max(m,Mt(i,e,u,n,r,n-C,y,s,o,d,p))}return m};for(let[v,m]of b){if(Math.abs(v-g)<3||m<=S)continue;let y=m>=(b.get(v-2)??-2)&&m>=(b.get(v+2)??-2)&&m>0?k(v):m;y>S&&(S=y)}if(l-a>12&&S>-2&&f-S<(h??.08))return null;let R=Mt(i,e,u,n,r,n-(g-1),r+x,s,o,d,p),E=Mt(i,e,u,n,r,n-(g+1),r+x,s,o,d,p),D=0,O=R-2*f+E;return R>-1&&E>-1&&O<0&&(D=Math.max(-.5,Math.min(.5,.5*(R-E)/O))),{d:g+D,dy:x,c:f}}function ga(i,e,t,n={}){let r=e/2,s=n.block||Math.max(8,Math.round(r/20)),o=n.step||s,a=n.dMax??Math.round(r*.3),l=n.dMin??-Math.round(r*.05),c=Math.round(r*(n.roiX0??.15)),h=Math.round(r*(n.roiX1??.85))-s,u=Math.round(t*(n.roiY0??.05)),d=Math.round(t*(n.roiY1??.85))-s,p=[];for(let f=u;f<=d;f+=o)for(let g=c;g<=h;g+=o){let x=be(i,e,t,g,f,s,s,{dMin:l,dMax:a,dyMax:n.dyMax??2,uniq:n.uniq});x&&x.c>=(n.minNcc??.8)&&p.push({x:g,y:f,...x})}return p}function _a(i,{tol:e=2,relTol:t=.1,minFrac:n=.12,minBlocks:r=3}={}){if(!i.length)return null;let s=Math.max(r,Math.ceil(i.length*n)),o=i.map(a=>a.d).sort((a,l)=>l-a);for(let a of o){let l=Math.max(e,t*Math.abs(a)),c=i.filter(h=>Math.abs(h.d-a)<=l);if(c.length>=s){let h=c.map(u=>u.d).sort((u,d)=>u-d);return{d:h[h.length>>1],members:c}}}return null}function va(i,e){let t=Math.min(...i.map(l=>l.y)),r=i.filter(l=>l.y<=t+2*e).map(l=>l.x),s=Math.min(...r),o=Math.max(...r)+e,a=o-s;return{x:(s+o)/2,y:t+.4*1.3*a}}function $n(i,e,t,n={}){let r=e/2,s=n.block||Math.max(8,Math.round(r/20)),o=n.dMax??Math.round(r*.3),a=n.dMin??-Math.round(r*.05),l=n.focus||null,c="focus",h=0,u=null;if(!l){let M=ga(i,e,t,{...n,block:s,dMax:o,dMin:a});h=M.length;let S=_a(M,n);if(!S)return null;l=va(S.members,s),u=S.d,c="mode"}let d=Math.round(s*(n.refineW??3)),p=Math.round(s*(n.refineH??1.5)),f=Math.round(Math.max(0,Math.min(r-d,l.x-d/2))),g=Math.round(Math.max(0,Math.min(t-p,l.y-p/2))),x=u===null?a:Math.max(a,Math.floor(u)-4),b=u===null?o:Math.min(o,Math.ceil(u)+4),w=be(i,e,t,f,g,d,p,{dMin:x,dMax:b,dyMax:n.dyMax??2});return w&&w.c>=(n.minNcc??.8)?{d:w.d,x:l.x,y:l.y,c:w.c,method:c,blocks:h}:u!==null?{d:u,x:l.x,y:l.y,c:0,method:c,blocks:h}:null}function Et(i,e){let t=new Uint8Array(e);for(let n=0,r=0;n<e;n++,r+=4)t[n]=i[r]*77+i[r+1]*150+i[r+2]*29>>8;return t}function xe({n:i=3}={}){let e=[],t={value:null,push(n){if(n===null||!Number.isFinite(n))return t.value;e.push(n),e.length>i&&e.shift();let r=[...e].sort((s,o)=>s-o);return t.value=r[r.length>>1],t.value},reset(){e.length=0,t.value=null}};return t}function Dr(i,e,t,n,r,s){let o=new Float32Array(r*s);for(let a=0;a<s;a++)for(let l=0;l<r;l++)o[a*r+l]=i[(n+a)*e+t+l];return o}function ya(i,e,t,n,r,s,o,a,l,c){let h=e/2,u=r*s,d=0,p=0;for(let w=0;w<u;w++)d+=n[w],p+=n[w]*n[w];d/=u;let f=Math.sqrt(Math.max(1e-6,p/u-d*d)),g=-2,x=o,b=a;for(let w=Math.max(0,a-c);w<=Math.min(t-s,a+c);w++)for(let M=Math.max(0,o-l);M<=Math.min(h-r,o+l);M++){let S=0,k=0,R=0;for(let v=0;v<s;v++){let m=(w+v)*e+M;for(let _=0;_<r;_++){let y=i[m+_];S+=y,k+=y*y,R+=y*n[v*r+_]}}let E=S/u,D=k/u-E*E;if(D<1)continue;let O=(R/u-E*d)/(Math.sqrt(D)*f);O>g&&(g=O,x=M,b=w)}return{x,y:b,c:g}}function ce({fullEveryMs:i=2e3,dWin:e=4,rx:t=12,ry:n=8,minTrackNcc:r=.75,jump:s=8}={}){let o=null,a=null;return{measure(c,h,u,d,p={}){let f=h/2,g=p.block||Math.max(8,Math.round(f/20)),x=Math.round(g*3),b=Math.round(g*1.5),w=null;if(o&&o.w===x&&o.h===b){let E=ya(c,h,u,o.tpl,x,b,o.x,o.y,t,n);if(E.c>=r){let D=be(c,h,u,E.x,E.y,x,b,{dMin:Math.floor(o.d)-e,dMax:Math.ceil(o.d)+e,dyMax:2});D&&D.c>=.8&&(w={m:D,f:E})}}let M=({m:E,f:D})=>(o={...o,x:D.x,y:D.y,d:E.d,tpl:Dr(c,h,D.x,D.y,x,b)},{d:E.d,x:D.x+x/2,y:D.y+b/2,c:E.c,method:"track",blocks:0});if(w&&d-o.at<i)return M(w);let S=$n(c,h,u,p);if(w&&(!S||Math.abs(S.d-w.m.d)>s)){let E=S&&a&&Math.abs(a.d-S.d)<=3;if(a=S&&!E?{d:S.d}:null,!E)return o.at=d,M(w)}else a=null;if(!S)return o=null,null;let k=Math.round(Math.max(0,Math.min(f-x,S.x-x/2))),R=Math.round(Math.max(0,Math.min(u-b,S.y-b/2)));return o={x:k,y:R,d:S.d,tpl:Dr(c,h,k,R,x,b),w:x,h:b,at:d},S},reset(){o=null,a=null}}}function Pr(i,e,t,n,r,s){let o=Math.max(1,s|0),a=Math.floor(n/o);a-=a&1;let l=Math.floor(r/o),c=new Uint8Array(a*l);if(o<=2){let d=o*o;for(let p=0;p<l;p++)for(let f=0;f<a;f++){let g=0;for(let x=0;x<o;x++){let b=e+(p*o+x)*t+f*o;for(let w=0;w<o;w++)g+=i[b+w]}c[p*a+f]=g/d|0}return{img:c,w:a,h:l}}let h=o>>2,u=3*o>>2;for(let d=0;d<l;d++){let p=e+(d*o+h)*t,f=e+(d*o+u)*t;for(let g=0;g<a;g++){let x=g*o+h,b=g*o+u;c[d*a+g]=i[p+x]+i[p+b]+i[f+x]+i[f+b]>>2}}return{img:c,w:a,h:l}}var Ct=fe(()=>{"use strict"});function Ot(i,e="@displayxr/inline3d"){if(i==null||i===!0)return{...Se};i===!1&&(i="off");let t=()=>new Error(`${e}: cursor.soften ${JSON.stringify(i)} \u2014 expected ${kt.map(s=>`'${s}'`).join(" | ")} or { ${Tt.join(", ")} }.`);if(typeof i=="string"){if(!kt.includes(i))throw t();return{...Se,...Lr(i)}}if(typeof i!="object"||Array.isArray(i))throw t();let n=Object.keys(i).filter(s=>!Tt.includes(s));if(n.length)throw new Error(`${e}: cursor.soften \u2014 unknown option(s) ${n.join(", ")}; expected ${Tt.join(", ")}.`);if(i.mode!==void 0&&!kt.includes(i.mode))throw t();let r={...Se,...Lr(i.mode??"both")};for(let s of Object.keys(At)){if(i[s]===void 0)continue;let[o,a,l]=At[s];if(!wa(s,i[s]))throw new Error(`${e}: cursor.soften.${s} must be a number in ${l?"(":"["}${o}, ${a}].`);r[s]=i[s]}return r}function Fr(i,e="@displayxr/inline3d"){if(i==null||i===!1)return null;if(i==="depth"||i===!0)return{};if(typeof i!="object")throw new Error(`${e}: cursor ${JSON.stringify(i)} \u2014 expected 'depth' or { ${Rt.join(", ")} }.`);let t=Object.keys(i).filter(n=>!Rt.includes(n));if(t.length)throw new Error(`${e}: cursor \u2014 unknown option(s) ${t.join(", ")}; expected ${Rt.join(", ")}.`);if(i.anchor!==void 0&&!Un.includes(i.anchor))throw new Error(`${e}: cursor.anchor "${i.anchor}" \u2014 expected ${Un.join(", ")}.`);if(i.pointerScope!==void 0&&i.pointerScope!=="canvas"&&i.pointerScope!=="window")throw new Error(`${e}: cursor.pointerScope "${i.pointerScope}" \u2014 expected 'canvas' or 'window'.`);if(i.debug!==void 0&&typeof i.debug!="boolean"&&i.debug!=="both")throw new Error(`${e}: cursor.debug ${JSON.stringify(i.debug)} \u2014 expected true, false or 'both'.`);for(let n of["height","margin"])if(i[n]!==void 0&&!(typeof i[n]=="number"&&i[n]>0&&Number.isFinite(i[n])))throw new Error(`${e}: cursor.${n} must be a positive number.`);if(i.soften!==void 0&&Ot(i.soften,e),i.shape!==void 0&&!Me.includes(i.shape))throw new Error(`${e}: cursor.shape ${JSON.stringify(i.shape)} \u2014 expected ${Me.map(n=>`'${n}'`).join(" | ")}.`);if(i.shapeFor!==void 0&&i.shapeFor!==null&&typeof i.shapeFor!="function")throw new Error(`${e}: cursor.shapeFor must be a function (hit) => shape.`);return{...i}}function Dt(i,e="@displayxr/inline3d"){let t=Fr(i,e);if(!t)return null;let n=Object.keys(t).filter(r=>!Ir.includes(r));if(n.length)throw new Error(`${e}: cursor \u2014 ${n.join(", ")} not supported on a stereo pair; expected ${Ir.join(", ")}.`);return t}var Un,Rt,Ee,Me,kt,Se,At,Tt,wa,Lr,Ir,Ce=fe(()=>{"use strict";Un=Object.freeze(["hybrid","screen","world"]),Rt=Object.freeze(["height","margin","anchor","pointerScope","debug","soften","shape","shapeFor"]),Ee=Object.freeze(["arrow","pointer","grab","grabbing","move","text","vertical-text","crosshair","not-allowed","help","wait","progress","copy","alias","context-menu","cell","ns-resize","ew-resize","nesw-resize","nwse-resize","col-resize","row-resize","zoom-in","zoom-out"]),Me=Object.freeze(["auto","none",...Ee]),kt=Object.freeze(["both","off","alpha","blur"]),Se=Object.freeze({blur:!0,alpha:!0,blurK:.1,blurMaxPx:8,blurMaxFrac:.06,alphaMin:.5,fullD:.03}),At=Object.freeze({blurK:[0,1e3,!1],blurMaxPx:[0,8,!1],blurMaxFrac:[0,.5,!1],alphaMin:[0,1,!1],fullD:[0,1e3,!0]}),Tt=Object.freeze(["mode",...Object.keys(At)]),wa=(i,e)=>{let[t,n,r]=At[i];return typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n&&!(r&&e<=t)},Lr=i=>({blur:i==="both"||i==="blur",alpha:i==="both"||i==="alpha"});Ir=Object.freeze(["height","pointerScope","soften","shape","shapeFor"])});function Kn(i){return typeof i=="string"&&is[i.trim().toLowerCase()]||"arrow"}function ka(i){let e=[],t=0,n="",r="";for(let s=0;s<i.length;s++){let o=i[s];if(n){if(o==="\\"&&s+1<i.length){r+=o+i[++s];continue}o===n&&(n="")}else if(o==='"'||o==="'")n=o;else if(o==="(")t++;else if(o===")")t=Math.max(0,t-1);else if(o===","&&t===0){e.push(r.trim()),r="";continue}r+=o}return r.trim()&&e.push(r.trim()),e}function Jn(i){if(typeof i!="string")return{images:[],keyword:"auto"};let e=Ft.get(i);if(e)return e;let t=[],n="auto";for(let r of ka(i)){let s=/^url\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^)\s]*))\s*\)\s*(.*)$/is.exec(r);if(s){let o=(s[1]??s[2]??s[3]??"").replace(/\\(.)/g,"$1"),a=(s[4]||"").trim().split(/\s+/).filter(Boolean).map(Number),l=a.length===2&&a.every(Number.isFinite)?[a[0],a[1]]:null;o&&t.push({url:o,hotspot:l});continue}/^(-webkit-)?image-set\(/i.test(r)||(n=r.trim().toLowerCase())}return e=Object.freeze({images:Object.freeze(t),keyword:n}),Ft.size>64&&Ft.clear(),Ft.set(i,e),e}function rs(i){return Kn(Jn(i).keyword)}function ss(i,e=0){if(!i||i.byteLength<22)return null;let t=new DataView(i);if(t.getUint16(0,!0)!==0||t.getUint16(2,!0)!==2)return null;let n=t.getUint16(4,!0),r=-1;for(let o=0;o<n&&6+16*o+16<=i.byteLength;o++){let a=t.getUint8(6+16*o)||256;if((r<0||a===e)&&(r=o),a===e)break}if(r<0)return null;let s=6+16*r;return[t.getUint16(s+4,!0),t.getUint16(s+6,!0)]}function os(i,e=Zn){let t=Jn(i);for(let n of t.images){let r=e.get(n.url);if(r.state==="failed")continue;if(r.state!=="ready")break;let s=Math.min(1,ns/Math.max(r.width,r.height)),o=n.hotspot||r.curHotspot||[0,0],a=r.width*s,l=r.height*s,c=[Math.min(a,Math.max(0,o[0]*s)),Math.min(l,Math.max(0,o[1]*s))];return{kind:"image",key:n.url,entry:r,width:a,height:l,hotspot:c}}return Te(Kn(t.keyword))}function Te(i){if(i==="none")return{kind:"none"};let e=Ee.includes(i)?i:"arrow";return{kind:"shape",name:e,key:`shape:${e}`}}function A(i,e,t,n,[r=0,s=0,o=0,a=0]=[]){let l=[],c=(h,u)=>{let d=l[l.length-1];(!d||Math.abs(d[0]-h)>1e-9||Math.abs(d[1]-u)>1e-9)&&l.push([h,u])};return c(i+r,e),c(t-s,e),c(t,e+s),c(t,n-o),c(t-o,n),c(i+a,n),c(i,n-a),c(i,e+r),l.length>1&&Math.abs(l[0][0]-l[l.length-1][0])<1e-9&&Math.abs(l[0][1]-l[l.length-1][1])<1e-9&&l.pop(),l}function jt(i,e,t,n,r,s=r/3.5){let o=t-i,a=n-e,l=Math.hypot(o,a),c=o/l,h=a/l,u=-h*(r/2),d=c*(r/2),p=t-c*s,f=n-h*s,g=1-2*s/r;return Ae([[i+u,e+d],[p+u,f+d],[t+u*g,n+d*g],[t-u*g,n-d*g],[p-u,f-d],[i-u,e-d]])}function Jr(i,e,t,n,r){let s=t-i,o=n-e,a=Math.hypot(s,o),l=-o/a*(r/2),c=s/a*(r/2);return Ae([[i+l,e+c],[t+l,n+c],[t-l,n-c],[i-l,e-c]])}function as(i,e,t,n=20){return Ae(Array.from({length:n},(r,s)=>[i+t*Math.cos(2*Math.PI*s/n),e+t*Math.sin(2*Math.PI*s/n)]))}function Aa(i,e,t,n,r=24){let s=[],o=(a,l)=>[i+a*Math.cos(l),e+a*Math.sin(l)];for(let a=0;a<r;a++){let l=[0,1,2,3].map(c=>2*Math.PI*(a+c)/r);s.push(Ae([...l.map(c=>o(n,c)),...l.reverse().map(c=>o(t,c))]))}return s}function Da(){return{pointer:{hot:[6.8,0],parts:[A(5,0,8.6,14,[1.2,1.2,0,0]),A(7.6,5.4,10.9,14,[1.1,1.1,0,0]),A(9.9,6.4,13.2,14,[1.1,1.1,0,0]),A(12.2,7.6,15.2,14,[.9,.9,0,0]),A(4.2,10.8,15.2,19,[0,0,3,2.2]),jt(7.4,15,1,9,3.6)]},grab:{hot:[8.6,12.5],parts:[A(3,2.6,6.6,12.4,[1.2,1.2,0,0]),A(5.6,.6,9.2,12.4,[1.2,1.2,0,0]),A(8.2,1.4,11.8,12.4,[1.2,1.2,0,0]),A(10.8,3.6,14.2,12.4,[1.1,1.1,0,0]),A(3,9.4,14.2,18,[0,0,2.6,2.6]),jt(6.2,14.4,.4,7,3.6)]},grabbing:{hot:[8.6,13],parts:[A(3,5.6,6.6,12.4,[1.2,1.2,0,0]),A(5.6,5,9.2,12.4,[1.2,1.2,0,0]),A(8.2,5.2,11.8,12.4,[1.2,1.2,0,0]),A(10.8,6,14.2,12.4,[1.1,1.1,0,0]),A(3,9.4,14.2,18,[0,0,2.6,2.6]),jt(6,14.2,1.2,9,3.6)]},move:{hot:[9.5,9.5],parts:[A(3,7.8,16,11.2),A(7.8,3,11.2,16),B([9.5,0],[14,4.6],[5,4.6]),B([9.5,19],[5,14.4],[14,14.4]),B([0,9.5],[4.6,5],[4.6,14]),B([19,9.5],[14.4,14],[14.4,5])]},text:{hot:[9.5,9.5],parts:[A(8,.5,11,18.5),A(4.5,0,14.5,3),A(4.5,16,14.5,19)]},"vertical-text":{hot:[9.5,9.5],parts:Je([A(8,.5,11,18.5),A(4.5,0,14.5,3),A(4.5,16,14.5,19)],90,9.5,9.5)},crosshair:{hot:[9.5,9.5],parts:[A(0,8,19,11),A(8,0,11,19)]},cell:{hot:[9.5,9.5],parts:[A(1.5,6.3,17.5,12.7),A(6.3,1.5,12.7,17.5)]},"not-allowed":{hot:[9.5,9.5],parts:[...Aa(9.5,9.5,5.4,8.8),Jr(4.6,4.6,14.4,14.4,3.4)]},help:{hot:[0,0],parts:[...he(Ze(),.8),as(13.6,12.4,5.4)],detail:[A(11.6,9,15.4,10.2),A(14.4,9,15.6,12.6),A(12.9,11.6,15.6,12.8),A(12.9,11.6,14.1,13.8),A(12.9,14.8,14.1,16)]},wait:{hot:[9.5,9.5],parts:Oa()},progress:{hot:[0,0],parts:[...he(Ze(),.8),A(10.6,9,18.8,11.6),A(10.6,16.4,18.8,19),B([11.4,10.2],[18,10.2],[14.7,14.4]),B([14.7,13.6],[18,17.8],[11.4,17.8])]},copy:{hot:[0,0],parts:[...he(Ze(),.8),A(9.6,9.8,18.8,19,[1.2,1.2,1.2,1.2])],detail:[A(13.6,11.8,14.8,17),A(11.6,13.8,16.8,15)]},alias:{hot:[0,0],parts:[...he(Ze(),.8),A(9.6,9.8,18.8,19,[1.2,1.2,1.2,1.2])],detail:[Jr(11.8,16.8,15.6,13,1.3),B([16.8,11.8],[16.8,15.4],[13.2,11.8])]},"context-menu":{hot:[0,0],parts:[...he(Ze(),.8),A(9.2,8.6,18.8,19)],detail:[A(11,10.8,17,11.8),A(11,13.3,17,14.3),A(11,15.8,17,16.8)]},"ns-resize":{hot:[9.5,9.5],parts:Nt()},"ew-resize":{hot:[9.5,9.5],parts:Je(Nt(),90,9.5,9.5)},"nesw-resize":{hot:[9.5,9.5],parts:he(Je(Nt(),45,9.5,9.5),1.2,-1.9,-1.9)},"nwse-resize":{hot:[9.5,9.5],parts:he(Je(Nt(),-45,9.5,9.5),1.2,-1.9,-1.9)},"col-resize":{hot:[9.5,9.5],parts:Zr()},"row-resize":{hot:[9.5,9.5],parts:Je(Zr(),90,9.5,9.5)},"zoom-in":{hot:[7.5,7.5],parts:Qr(),detail:[A(4.4,6.9,10.6,8.1),A(6.9,4.4,8.1,10.6)]},"zoom-out":{hot:[7.5,7.5],parts:Qr(),detail:[A(4.4,6.9,10.6,8.1)]}}}function Qn(i){let e=Ee.includes(i)?i:"arrow",t=es.get(e);if(t)return t;let n=c=>Object.freeze(c.map(h=>Object.freeze(h.map(u=>Object.freeze(u))))),r,s,o;if(e==="arrow")r=[ie],s=[ds],o=[];else{let c=(Pa||=Da())[e],h=u=>u.map(d=>d.map(([p,f])=>[(p-c.hot[0])/19,(f-c.hot[1])/19]));r=n(h(c.parts)),s=n(r.map(u=>$t(1/19,u))),o=n(h(c.detail||[]))}let a=r.flat().map(c=>c[0]),l=r.flat().map(c=>c[1]);return t=Object.freeze({name:e,parts:Object.freeze(r),fill:Object.freeze(s),detail:Object.freeze(o),box:Object.freeze([Math.min(...a),Math.min(...l),Math.max(...a),Math.max(...l)])}),es.set(e,t),t}function Oe(i,e=1/19){let t=Qn(i);return Math.abs(e-1/19)<1e-12?{outline:t.parts,fill:t.fill,detail:t.detail}:{outline:t.parts,fill:t.parts.map(n=>$t(e,n)),detail:t.detail}}function ls(i,e,t=0){let n=Qn(i).box,r=(e>0&&Number.isFinite(e)?e:0)+(t>0&&Number.isFinite(t)?t:0);return[n[0]-r,n[1]-r,n[2]+r,n[3]+r]}function cs(i,e,t,n,r,s=ri,o=si,a=Oe(i)){let l=0,c=0,h=0,u=0,d=0,p=n>0?et:et.slice(0,1),f=a.detail&&a.detail.length?a.detail:null;for(let[g,x,b]of p){let w=e+g*n,M=t+x*n,S=Yn(qn(a.outline,w,M),r),k=S>0?Yn(qn(a.fill,w,M),r):0;f&&k>0&&(k*=1-Yn(qn(f,w,M),r)),l+=b*(o[0]*S+(s[0]-o[0])*k),c+=b*(o[1]*S+(s[1]-o[1])*k),h+=b*(o[2]*S+(s[2]-o[2])*k),u+=b*S,d+=b}return u/=d,u>1e-5?[l/d/u,c/d/u,h/d/u,u]:[0,0,0,0]}function ei(i,e,t,n,r,s,o=ri,a=si,l=Oe(i)){let c=n>0&&Number.isFinite(n)?n:1,h=1/c,[u,d,p,f]=ls(i,r,h),g=Math.floor(e+u*c),x=Math.floor(t+d*c),b=Math.max(1,Math.ceil(e+p*c)-g),w=Math.max(1,Math.ceil(t+f*c)-x),M=new Uint8ClampedArray(b*w*4),S=s>=0&&s<=1?s:1;for(let k=0;k<w;k++){let R=(x+k+.5-t)/c;for(let E=0;E<b;E++){let D=cs(i,(g+E+.5-e)/c,R,r,h,o,a,l);if(!(D[3]>0))continue;let O=(k*b+E)*4;M[O]=Math.round(D[0]*255),M[O+1]=Math.round(D[1]*255),M[O+2]=Math.round(D[2]*255),M[O+3]=Math.round(D[3]*S*255)}}return{x0:g,y0:x,width:b,height:w,data:M}}function ti(i,e,t,n,r,s=Oe(e),o="#fff",a="#000"){for(let[l,c]of[[s.outline,a],[s.fill,o],[s.detail||[],a]]){i.fillStyle=c;for(let h of l)i.beginPath(),h.forEach(([u,d],p)=>(p?i.lineTo:i.moveTo).call(i,t+u*r,n+d*r)),i.closePath(),i.fill()}}function ni(i,e,t,n,r){let s=n>0&&Number.isFinite(n)?Math.ceil(n)+1:0,o=e+2*s,a=t+2*s,l=new Uint8ClampedArray(o*a*4),c=r>=0&&r<=1?r:1,h=s?et:et.slice(0,1);for(let u=0;u<a;u++)for(let d=0;d<o;d++){let p=0,f=0,g=0,x=0,b=0;for(let[M,S,k]of h){b+=k;let R=Math.round(d-s+M*n),E=Math.round(u-s+S*n);if(R<0||E<0||R>=e||E>=t)continue;let D=(E*e+R)*4,O=i[D+3]/255*k;p+=i[D]*O,f+=i[D+1]*O,g+=i[D+2]*O,x+=O}if(!(x>1e-5))continue;let w=(u*o+d)*4;l[w]=p/x,l[w+1]=f/x,l[w+2]=g/x,l[w+3]=x/b*c*255}return{pad:s,width:o,height:a,data:l}}function Ht(i=globalThis.document){if(!i||!i.createElement)return!1;let e="inline3d-cursor-style";if(i.getElementById&&i.getElementById(e))return!0;let t=i.createElement("style");return t.id=e,t.textContent=ts,(i.head||i.documentElement)?.appendChild(t),!0}function us(i,e){let t=globalThis.getComputedStyle;if(!i||typeof t!="function")return null;let n=[];for(let r of e)r&&r.hasAttribute&&r.hasAttribute(X)&&(n.push([r,r.getAttribute(X)]),r.removeAttribute(X));try{let r=t(i).cursor;return typeof r=="string"?r:null}catch{return null}finally{for(let[r,s]of n)r.setAttribute(X,s??"")}}var X,ts,ns,is,Ra,Ft,Ta,zt,Zn,Ae,B,Je,he,Ze,Nt,Zr,Oa,Qr,Pa,es,qn,Yn,hs,Wt,Qe,ii=fe(()=>{"use strict";oi();Ce();X="data-inline3d-cursor-hidden",ts=`[${X}],[${X}] *{cursor:none!important}`,ns=128,is=Object.freeze({auto:"arrow",default:"arrow",none:"none",pointer:"pointer",grab:"grab","-webkit-grab":"grab",grabbing:"grabbing","-webkit-grabbing":"grabbing",move:"move","all-scroll":"move",text:"text","vertical-text":"vertical-text",crosshair:"crosshair","not-allowed":"not-allowed","no-drop":"not-allowed",help:"help",wait:"wait",progress:"progress",copy:"copy",alias:"alias","context-menu":"context-menu",cell:"cell","n-resize":"ns-resize","s-resize":"ns-resize","ns-resize":"ns-resize","e-resize":"ew-resize","w-resize":"ew-resize","ew-resize":"ew-resize","ne-resize":"nesw-resize","sw-resize":"nesw-resize","nesw-resize":"nesw-resize","nw-resize":"nwse-resize","se-resize":"nwse-resize","nwse-resize":"nwse-resize","col-resize":"col-resize","row-resize":"row-resize","zoom-in":"zoom-in","-webkit-zoom-in":"zoom-in","zoom-out":"zoom-out","-webkit-zoom-out":"zoom-out"}),Ra=Object.freeze(Object.keys(is));Ft=new Map;Ta=i=>/\.cur(?:[?#]|$)/i.test(i)||/^data:image\/(?:x-win-bitmap|x-icon|vnd\.microsoft\.icon)/i.test(i),zt=class{constructor({ImageCtor:e=globalThis.Image,fetchFn:t=globalThis.fetch}={}){this._Image=e,this._fetch=t,this._m=new Map}get(e){let t=this._m.get(e);if(t)return t;if(t={url:e,state:"loading",image:null,width:0,height:0,curHotspot:null},this._m.set(e,t),typeof this._Image!="function")return t.state="failed",t;let n=new this._Image;n.crossOrigin="anonymous";let r=1,s=()=>{--r>0||t.state==="failed"||(t.state="ready")};return n.onload=()=>{let o=n.naturalWidth||n.width,a=n.naturalHeight||n.height;if(!(o>0&&a>0))return void(t.state="failed");t.image=n,t.width=o,t.height=a,s()},n.onerror=()=>{t.state="failed"},Ta(e)&&typeof this._fetch=="function"&&(r++,Promise.resolve().then(()=>this._fetch(e,e.startsWith("data:")?void 0:{mode:"cors"})).then(o=>o&&o.ok!==!1?o.arrayBuffer():null).then(o=>{t.curHotspot=o?ss(o,t.width):null}).catch(()=>{}).finally(s)),n.src=e,t}},Zn=new zt;Ae=i=>{let e=0;for(let t=0;t<i.length;t++){let[n,r]=i[t],[s,o]=i[(t+1)%i.length];e+=n*o-s*r}return e>0?i:i.reverse()};B=(i,e,t)=>Ae([i,e,t]),Je=(i,e,t,n)=>{let r=e*Math.PI/180,s=Math.cos(r),o=Math.sin(r);return i.map(a=>Ae(a.map(([l,c])=>[t+(l-t)*s-(c-n)*o,n+(l-t)*o+(c-n)*s])))},he=(i,e,t=0,n=0)=>i.map(r=>r.map(([s,o])=>[s*e+t,o*e+n])),Ze=()=>[ie.map(([i,e])=>[i*19,e*19])],Nt=()=>[A(8,3,11,16),B([9.5,0],[14.2,5],[4.8,5]),B([9.5,19],[4.8,14],[14.2,14])],Zr=()=>[A(8,1,11,18),A(3.4,8,7.4,11),B([0,9.5],[4.4,5],[4.4,14]),A(11.6,8,15.6,11),B([19,9.5],[14.6,14],[14.6,5])],Oa=()=>[A(3,0,16,3),A(3,16,16,19),B([4.2,.5],[14.8,.5],[9.5,10]),B([9.5,9],[14.8,18.5],[4.2,18.5])],Qr=()=>[as(7.5,7.5,7),jt(11.6,11.6,18.4,18.4,3.8,1)];Pa=null,es=new Map;qn=(i,e,t)=>{let n=1/0;for(let r of i)n=Math.min(n,fs(r,e,t));return n},Yn=(i,e)=>e>0?Math.min(1,Math.max(0,.5-i/e)):i<0?1:0;hs=100;Wt=class{constructor(e,{throttleMs:t=hs}={}){this.pointer=e,this.throttleMs=t,this.css=null,this.reads=0,this._el=null,this._stale=!0,this._urgent=!0,this._lastRead=-1/0;let n=r=>s=>{let o=typeof s.composedPath=="function"?s.composedPath():null,a=o&&o.length?o[0]:s.target;a&&a.nodeType===1&&(this._el=a),this._stale=!0,r&&(this._urgent=!0)};this._onMove=n(!1),this._onPress=n(!0),this._target=e.scope==="window"?globalThis:e.canvas,this._target&&this._target.addEventListener&&(this._target.addEventListener("pointermove",this._onMove),this._target.addEventListener("pointerdown",this._onPress),this._target.addEventListener("pointerup",this._onPress),this._target.addEventListener("pointercancel",this._onPress))}value(e=globalThis.performance?globalThis.performance.now():Date.now()){return this._stale&&(this._urgent||this.css===null||e-this._lastRead>=this.throttleMs)&&this.read(e),this.css??"auto"}shape(e){return rs(this.value(e))}read(e=globalThis.performance?globalThis.performance.now():Date.now()){let t=globalThis.document,n=this.pointer.canvas,r=this._el;r&&r.isConnected===!1&&(r=null);let s=us(r||n,[n,t&&t.documentElement]);return this.reads++,this._lastRead=e,this._stale=!1,this._urgent=!1,s!==null&&(this.css=s),this.css??"auto"}dispose(){this._target&&this._target.removeEventListener&&(this._target.removeEventListener("pointermove",this._onMove),this._target.removeEventListener("pointerdown",this._onPress),this._target.removeEventListener("pointerup",this._onPress),this._target.removeEventListener("pointercancel",this._onPress))}},Qe=class{constructor(e,{shape:t="auto",shapeFor:n=null,images:r=Zn}={}){if(!Me.includes(t))throw new Error(`@displayxr/inline3d: cursor.shape "${t}" \u2014 expected ${Me.join(", ")}.`);this.option=t,this.shapeFor=typeof n=="function"?n:null,this.images=r,this.reader=t==="auto"?new Wt(e):null,this.sprite=Te(t==="auto"?"arrow":t)}get current(){return this.sprite.kind==="shape"?this.sprite.name:this.sprite.kind}pick(e,t){let n=this.reader?this.reader.value(t):null,r=n===null?null:os(n,this.images),s=r?r.kind==="shape"?r.name:r.kind:null,o;if(this.shapeFor)try{o=this.shapeFor({...e,css:s,cssValue:n})}catch(l){this._warned||(this._warned=!0,console.warn("[inline3d] cursor.shapeFor threw; using the page cursor.",l))}let a=l=>l==="none"||Ee.includes(l);return a(o)?this.sprite=Te(o):a(this.option)?this.sprite=Te(this.option):this.sprite=r||Te("arrow"),this.sprite}dispose(){this.reader?.dispose()}}});function _s(i){return i>0&&Number.isFinite(i)?Math.min(.5,ci/i):La}function vs(i,e){return i<=Ia?!(e>0&&Number.isFinite(e))||-i*e>=Fa:!1}function hi(i,e,t){if(!e||!Number.isFinite(t)||!(t<0))return 0;let n=Math.min(0,Number.isFinite(i.maxDisparity)?i.maxDisparity:0);return Math.min(n,Math.max(i.minDisparity,t-i.margin))}function ys(i,e,t,n){if(!i.primed||n<i.last||n-i.last>e.stale)return i.primed=!0,i.disparity=t,i.last=n,t;if(n===i.last)return i.disparity;let r=n-i.last,s=t<i.disparity?e.riseTau:e.sinkTau,o=s>0?1-Math.exp(-r/s):1;return i.disparity+=o*(t-i.disparity),i.last=n,i.disparity}function ps(i){let e=i&&i.pointerType;return!e||e==="mouse"?!0:e==="pen"?!(i.buttons>0):!1}function Na(i){return!!i&&"onpointerrawupdate"in i&&globalThis.isSecureContext!==!1}function ja(i){let e=globalThis.document;if(!e||!e.documentElement)return;i&&Ht(e),ai=Math.max(0,ai+(i?1:-1));let t=e.documentElement;ai>0?t.setAttribute?.(X,""):t.removeAttribute?.(X)}function ms(i){return!!i&&typeof i.setCursorDepth=="function"&&typeof i.getCursorDepthSupport=="function"}function $a(i,e,t,n){let r=.75*t,s=[[i,e]];for(let o=0;o<8;o++){let a=o*Math.PI/4;s.push([i+r*Math.cos(a)/n,e+r*Math.sin(a)])}return s}function ws(i,e,t,n){return[[i,e],...$a(i+.3*t/n,e+.5*t,t,n)]}function $t(i,e=ie){let t=0;for(let s=0;s<e.length;s++){let[o,a]=e[s],[l,c]=e[(s+1)%e.length];t+=o*c-l*a}let n=t>0?1:-1,r=e.map((s,o)=>{let a=e[(o+1)%e.length],l=a[0]-s[0],c=a[1]-s[1],h=Math.hypot(l,c)||1;return[-c/h*n,l/h*n]});return e.map((s,o)=>{let a=r[(o+e.length-1)%e.length],l=r[o],c=i/(1+a[0]*l[0]+a[1]*l[1]);return[s[0]+(a[0]+l[0])*c,s[1]+(a[1]+l[1])*c]})}function bs(i,e,t,n=Se){let r={blurPx:0,alpha:1},s=n;if(!s)return r;if(s.blur&&Number.isFinite(e)&&s.blurK>0&&s.blurMaxPx>0){let o=s.blurMaxPx;if(s.blurMaxFrac>0&&Number.isFinite(t)&&t>0){let l=s.blurMaxFrac*t;o=l<o?l:o}let a=s.blurK*Math.abs(e);r.blurPx=a<o?a:o}if(s.alpha&&Number.isFinite(i)&&s.fullD>0){let o=Math.abs(i)/s.fullD;o=o<1?o:1;let a=o*o*(3-2*o),l=s.alphaMin<0?0:s.alphaMin>1?1:s.alphaMin;r.alpha=1-(1-l)*a}return r}function fs(i,e,t){let n=(e-i[0][0])**2+(t-i[0][1])**2,r=1;for(let s=0,o=i.length-1;s<i.length;o=s,s++){let a=i[s],l=i[o],c=l[0]-a[0],h=l[1]-a[1],u=e-a[0],d=t-a[1],p=Math.min(1,Math.max(0,(u*c+d*h)/(c*c+h*h))),f=u-c*p,g=d-h*p;n=Math.min(n,f*f+g*g);let x=t>=a[1],b=t<l[1],w=c*d>h*u;(x&&b&&w||!x&&!b&&!w)&&(r=-r)}return r*Math.sqrt(n)}var La,ci,Ia,Fa,Bt,Ut,ai,za,Wa,Ha,li,Vt,gs,ie,vc,ds,ri,si,et,yc,wc,bc,oi=fe(()=>{"use strict";Ce();Ce();ii();ii();La=.03,ci=19;Ia=-.005,Fa=.5;Bt=Object.freeze({margin:.015,minDisparity:-.6,maxDisparity:0,riseTau:.03,sinkTau:.25,stale:.5});Ut=class{constructor(e,{scope:t="canvas",keepCss:n=!1}={}){if(t!=="canvas"&&t!=="window")throw new Error(`@displayxr/inline3d: cursor pointerScope "${t}" \u2014 expected 'canvas' or 'window'.`);this.canvas=e,this.scope=t,this.keepCss=!!n,this._uv=null,this.sampleTime=0,this.samples=0,this._hidden=!1,this._cx=0,this._cy=0,this._pending=!1,this._onMove=r=>this._sample(r),this._onLeave=()=>{this.uv=null},this._onDown=r=>{ps(r)||(this.uv=null)},this._target=t==="window"?globalThis:e,this.source=Na(this._target)?"pointerrawupdate":"pointermove",this._target.addEventListener("pointermove",this._onMove),this.source==="pointerrawupdate"&&this._target.addEventListener("pointerrawupdate",this._onMove),this._target.addEventListener("pointerdown",this._onDown),t==="window"?(this._onOut=r=>{r.relatedTarget||(this.uv=null)},globalThis.addEventListener("pointerout",this._onOut),globalThis.addEventListener("blur",this._onLeave)):e.addEventListener("pointerleave",this._onLeave)}get uv(){if(this._pending){this._pending=!1;let e=this.canvas.getBoundingClientRect();if(!(e.width>0&&e.height>0))this._uv=null;else{let t=(this._cx-e.left)/e.width,n=(this._cy-e.top)/e.height;this._uv=t>=0&&t<=1&&n>=0&&n<=1?[t,n]:null}}return this._uv}set uv(e){this._pending=!1,this._uv=e}_sample(e){if(!ps(e)){this.uv=null;return}let t=typeof e.getCoalescedEvents=="function"?e.getCoalescedEvents():null,n=t&&t.length?t[t.length-1]:e,r=n.timeStamp>0?n.timeStamp:e.timeStamp>0?e.timeStamp:globalThis.performance?globalThis.performance.now():Date.now();r<this.sampleTime||(this.samples++,this.sampleTime=r,this._cx=n.clientX,this._cy=n.clientY,this._pending=!0)}set(e,t){this.uv=e==null?null:[e,t]}aspect(){let e=this.canvas.getBoundingClientRect();return e.height>0?e.width/e.height:1}cssHeight(){let e=this.canvas.getBoundingClientRect();return e.height>0?e.height:0}panelPx(){return this.cssHeight()*(globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1)}panelSize(){let e=this.canvas.getBoundingClientRect(),t=globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1;return e.width>0&&e.height>0?[e.width*t,e.height*t]:[0,0]}hideCss(e){this.keepCss&&(e=!1),e!==this._hidden&&(this.scope==="window"?ja(e):this.canvas.setAttribute&&(e?(Ht(),this.canvas.setAttribute(X,"")):this.canvas.removeAttribute(X)),this._hidden=e)}dispose(){this._target.removeEventListener("pointermove",this._onMove),this.source==="pointerrawupdate"&&this._target.removeEventListener("pointerrawupdate",this._onMove),this._target.removeEventListener("pointerdown",this._onDown),this.scope==="window"?(globalThis.removeEventListener("pointerout",this._onOut),globalThis.removeEventListener("blur",this._onLeave)):this.canvas.removeEventListener("pointerleave",this._onLeave),this.hideCss(!1)}};ai=0;za=2e3,Wa=6,Ha=1e4;li=new WeakMap,Vt=class{constructor(){this.target=null,this._sent=!1,this.last=null}get support(){let e=this.target;if(!ms(e))return"none";let t=li.get(e);return t?t.state:"pending"}get drawing(){return this.support==="runtime"}bind(e){let t=e||null;if(t!==this.target&&(this.withdraw(),this.target=t),!ms(t))return!1;let n=li.get(t);if(n||li.set(t,n={state:"pending",probes:0,inFlight:!1,at:0}),n.state==="runtime"||n.inFlight)return n.state==="runtime";let r=globalThis.performance?globalThis.performance.now():Date.now(),s=n.probes<Wa?za:Ha;if(n.probes===0||r-n.at>=s){n.probes++,n.at=r,n.inFlight=!0;let o;try{o=Promise.resolve(t.getCursorDepthSupport())}catch(a){o=Promise.reject(a)}o.then(a=>{n.inFlight=!1,n.state=a==="runtime"?"runtime":"none"},()=>{n.inFlight=!1,n.state="none"})}return n.state==="runtime"}report(e,t,n){if(!this.drawing)return!1;let r={u:gs(e),v:gs(t)};n!=null&&Number.isFinite(n)&&(r.disparityPx=n);try{this.target.setCursorDepth(r)}catch{return!1}return this._sent=!0,this.last={u:r.u,v:r.v,disparityPx:r.disparityPx??null},!0}withdraw(){if(this.last=null,!!this._sent){this._sent=!1;try{this.target?.setCursorDepth()}catch{}}}dispose(){this.withdraw(),this.target=null}},gs=i=>i>0?i<1?i:1:0;ie=Object.freeze([[0,0],[0,16],[4.2,12.4],[6.9,18.6],[9.5,17.5],[6.8,11.5],[11.7,11.5]].map(([i,e])=>Object.freeze([i/19,e/19]))),vc=Object.freeze([[0,1,2],[0,2,5],[0,5,6],[2,3,4],[2,4,5]]);ds=Object.freeze($t(1/19).map(i=>Object.freeze(i))),ri=Object.freeze([1,1,1,1]),si=Object.freeze([.02,.02,.03,1]);et=Object.freeze([Object.freeze([0,0,1]),...[[.5,0],[-.5,0],[0,.5],[0,-.5]].map(([i,e])=>Object.freeze([i,e,.7066])),...Array.from({length:8},(i,e)=>{let t=.3927+.7854*e;return Object.freeze([Math.cos(t),Math.sin(t),.2494])})]),yc=Object.freeze([Math.max(...ie.map(i=>i[0])),Math.max(...ie.map(i=>i[1]))]);wc=Object.freeze({declarations:`#ifdef PICK_PASS
3
3
  #include "pickPS"
4
4
  #endif
5
5
  `,output:`pcFragColor0 = getPickOutput();
6
6
  #ifdef DEPTH_PICK_PASS
7
7
  pcFragColor1 = getPickDepth();
8
8
  #endif
9
- `}),sc=Object.freeze({declarations:`#ifdef PICK_PASS
9
+ `}),bc=Object.freeze({declarations:`#ifdef PICK_PASS
10
10
  #include "pickPS"
11
11
  #endif
12
12
  `,output:`output.color = getPickOutput();
13
13
  #ifdef DEPTH_PICK_PASS
14
14
  output.color1 = getPickDepth();
15
15
  #endif
16
- `})});var sn={};Qs(sn,{PAIR_CURSOR_ARROW:()=>Oa,PAIR_CURSOR_CSS_PX:()=>Ta,PAIR_CURSOR_CSS_PX_M:()=>ps,PAIR_CURSOR_HEIGHT:()=>fs,PAIR_SUPPORT_COPY_PX:()=>gs,PairCursor:()=>rn,consistentMatch:()=>nn,drawPairArrow:()=>bs,drawPairArrowSoft:()=>Ss,drawPairImage:()=>Ms,pairCursorScale:()=>vs,pairCursorTarget:()=>Pa,pairFootprintDisparity:()=>ms,pairNearestSupported:()=>_s,pairPxPerBaseline:()=>ys});function ms(n,e,t,i,r,s){if(!n||!n.img||!e||!e.rL||!e.rR||!(e.outW>0))return null;let{img:o,w:a,h:l,scale:c}=n,h=a/2,d=Math.max(8,Math.round(h/20)),u=Math.round(h*.3),f=-Math.round(h*.05),{rL:p,rR:m}=e,w=e.outW/p.sw,_=Aa(n),x=[],R=new Set,E=(M,g)=>{let S=Math.round((p.sy+g*p.sh)*c-d/2);if(S<0||S+d>l)return;let y=Math.round((p.sx+M*p.sw)*c-d/2),O=Math.round((m.sx+M*m.sw)*c-d/2);if(!R.has(`L${y},${S}`)){R.add(`L${y},${S}`);let I=nn(o,_,a,l,y,S,d,f,u);I!==null&&x.push({d:I,x:y,y:S,eye:0})}if(!R.has(`R${O},${S}`)){R.add(`R${O},${S}`);let I=nn(_,o,a,l,O,S,d,-u,-f);I!==null&&x.push({d:-I,x:O,y:S,eye:1})}},C=0,k=0,T=0;for(let[M,g]of cs(t,i,r,s))M>=0&&M<=1&&g>=0&&g<=1&&(E(e.mirror?1-M:M,g),C+=M,k+=g,T++);if(!T)return null;let v=d/2/c/p.sw,b=d/2/c/p.sh;for(let[M,g]of[[-v,0],[v,0],[0,-b],[0,b]]){let S=C/T+M,y=k/T+g;S>=0&&S<=1&&y>=0&&y<=1&&E(e.mirror?1-S:S,y)}for(let M of x)M.d=(M.d/c-(p.sx-m.sx))*w;return _s(x,gs/c*w,d/2)}function Aa(n){let e=ds.get(n);if(e)return e;let{img:t,w:i,h:r}=n,s=i/2;e=new Uint8Array(i*r);for(let o=0;o<r;o++){let a=o*i;for(let l=0;l<s;l++)e[a+l]=t[a+s+l],e[a+s+l]=t[a+l]}return ds.set(n,e),e}function nn(n,e,t,i,r,s,o,a,l){let c=t/2;if(r<0||r+o>c)return null;let h=ye(n,t,i,r,s,o,o,{dMin:a,dMax:l,dyMax:2});if(!h||h.c<.8)return null;let d=Math.round(r-h.d),u=s+h.dy;if(d<0||d+o>c||u<0||u+o>i)return null;let f=ye(e,t,i,d,u,o,o,{dMin:-Math.ceil(h.d)-2,dMax:-Math.floor(h.d)+2,dyMax:1});return!f||f.c<.8||Math.abs(-f.d-h.d)>1?null:h.d}function _s(n,e,t=0){let i=n.map(o=>typeof o=="number"?{d:o,x:0,y:0,eye:-1}:o);if(i.length<2)return null;let r=[...i].sort((o,a)=>a.d-o.d),s=(o,a)=>o.eye===-1||o.eye!==a.eye||Math.abs(o.x-a.x)+Math.abs(o.y-a.y)>=t;for(let o of r)for(let a of r)if(a!==o&&Math.abs(o.d-a.d)<=e&&s(o,a))return o.d;return null}function vs(n,e,t){let i=t>0&&Number.isFinite(t)?t:ps;return e>0?n/e/i:n/(1e3*i)}function ys(n,e,t,i=et.eyeSeparationM){return vs(n,e,t)*i}function Pa(n,e,t=Nt){return n===null||!Number.isFinite(n)||!(e>0)?0:-tn(t,!0,-n/e)*e||0}function ws(n,e){let t=e>0?Math.max(.05263157894736842,1/e):.05263157894736842,i=`${n}:${Math.round(t*1e4)}`,r=jt.get(i);return r||(jt.size>64&&jt.clear(),jt.set(i,r=Te(n,t))),r}function bs(n,e,t,i,r,s,o,a="arrow"){let l=r*t,c=ws(a,o);for(let h of[0,1]){let d=h*e+i*e+(h===0?s/2:-s/2);n.save(),n.beginPath(),n.rect(h*e,0,e,t),n.clip(),Xi(n,a,d,l,o,c),n.restore()}}function xs(n,e){if(!X||typeof OffscreenCanvas=="function"&&!(X instanceof OffscreenCanvas))try{typeof OffscreenCanvas=="function"?X=new OffscreenCanvas(1,1):globalThis.document&&document.createElement&&(X=document.createElement("canvas"))}catch{X=null}return!X||typeof X.getContext!="function"?null:(X.width<n&&(X.width=n),X.height<e&&(X.height=e),X.getContext("2d"))}function Ss(n,e,t,i,r,s,o,a,l,c="arrow"){let h=r*t,d=ws(c,o),u=[0,1].map(p=>{let m=p*e+i*e+(p===0?s/2:-s/2);return Bi(c,m,h,o,a,l,[1,1,1,1],[0,0,0,1],d)}),f=xs(Math.max(u[0].width,u[1].width),Math.max(u[0].height,u[1].height));if(!f||typeof f.putImageData!="function"||typeof ImageData!="function")return!1;for(let p of[0,1]){let m=u[p];f.putImageData(new ImageData(m.data,m.width,m.height),0,0),n.save(),n.beginPath(),n.rect(p*e,0,e,t),n.clip(),n.drawImage(f.canvas,0,0,m.width,m.height,m.x0,m.y0,m.width,m.height),n.restore()}return!0}function Ms(n,e,t,i,r,s,o,a,l,c){let h=o/19,d=Math.max(1,Math.round(a.width*h)),u=Math.max(1,Math.round(a.height*h)),f=xs(d+2*(Math.ceil(l)+2),u+2*(Math.ceil(l)+2));if(!f||typeof f.getImageData!="function"||typeof ImageData!="function")return!1;f.clearRect(0,0,f.canvas.width,f.canvas.height),f.drawImage(a.entry.image,0,0,d,u);let p=Gi(f.getImageData(0,0,d,u).data,d,u,l,c);f.clearRect(0,0,f.canvas.width,f.canvas.height),f.putImageData(new ImageData(p.data,p.width,p.height),0,0);let m=r*t-a.hotspot[1]*h-p.pad;for(let w of[0,1]){let _=w*e+i*e+(w===0?s/2:-s/2)-a.hotspot[0]*h-p.pad;n.save(),n.beginPath(),n.rect(w*e,0,e,t),n.clip(),n.drawImage(f.canvas,0,0,p.width,p.height,Math.round(_),Math.round(m),p.width,p.height),n.restore()}return!0}var Ta,fs,Oa,ps,gs,ds,jt,X,rn,on=he(()=>{"use strict";Ji();Zt();vt();Ta=en,fs=.06,Oa=ee,ps=.0254/96;gs=1.5,ds=new WeakMap;jt=new Map;X=null;rn=class{constructor(e,{height:t,pointerScope:i="window",soften:r,shape:s="auto",shapeFor:o=null}={}){this.pointer=new It(e,{scope:i}),this.shapes=new Ye(this.pointer,{shape:s,shapeFor:o}),this.soften=St(r,"@displayxr/inline3d pair cursor"),this.height=t>0?t:null,this.filter={},this._luma=null,this._uv=null,this._content=null,this._metricsFor=null,this.metersPerCssPx=null,this.eyeSeparationM=et.eyeSeparationM,this.last=null,this.runtime=new Ft}get hovering(){return!!this.pointer.uv}draw(e,t,i,r){let s=this.runtime.bind(i&&i.handle),o=this.pointer.uv;if(!o)return this.idle();let[a,l]=o,c=this.height??this._osArrowFraction();(t!==this._luma||!this._uv||this._uv[0]!==a||this._uv[1]!==l)&&(this._content=ms(t,i,a,l,c,i.outW/i.outH),this._luma=t,this._uv=o);let h=this.pointer.canvas.getBoundingClientRect?.();if(s)return this._drawRuntime(a,l,h,i);this._askMetrics(i.handle);let d=ys(i.outW,h&&h.width,this.metersPerCssPx,this.eyeSeparationM),u=this._content===null?null:-this._content/d,f=tn(Nt,u!==null,u),p=ls(this.filter,Nt,f,r),m=as(p,d),w=-p*d,_=null,x=null;if(m){let R=c*i.outH,E=globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1,C=h&&h.width>0?h.width*E/i.outW:1,k=h&&h.height>0?c*h.height*E:R,T=hs(p,w*C,k,this.soften),v=this.shapes.pick({u:a,v:l,point:null},r*1e3);x=this.shapes.current,_={blurPx:T.blurPx,alpha:T.alpha,ghostPx:Math.abs(w*C),spritePx:k,radius:k>0?T.blurPx/k:0,soft:T.blurPx>0||T.alpha<1},v.kind==="image"?Ms(e,i.outW,i.outH,a,l,w,R,v,_.soft?_.radius*R:0,_.soft?T.alpha:1):v.kind==="shape"&&(!_.soft||!Ss(e,i.outW,i.outH,a,l,w,R,_.radius,T.alpha,x))&&bs(e,i.outW,i.outH,a,l,w,R,x)}return this.pointer.hideCss(m),this.last={contentPx:this._content,targetPx:-f*d||0,disparityPx:m?w:0,filteredPx:w||0,drawn:m,pxPerBaseline:d,soften:_,shape:x},this.last}_drawRuntime(e,t,i,r){this.pointer.hideCss(!1),this.filter={};let s=globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1,o=i&&i.width>0&&r.outW>0?i.width*s/r.outW:null,a=this._content===null||o===null?null:-this._content*o;return this.runtime.report(e,t,a),this.last={contentPx:this._content,targetPx:0,disparityPx:0,filteredPx:0,drawn:!1,runtime:!0,runtimeDisparityPx:a,pxPerBaseline:null,soften:null,shape:null},this.last}_askMetrics(e){!e||e===this._metricsFor||typeof e.displayMetrics!="function"||(this._metricsFor=e,Promise.resolve().then(()=>e.displayMetrics()).then(t=>{this._metricsFor!==e||!t||(t.metersPerCssPx>0&&(this.metersPerCssPx=t.metersPerCssPx),t.eyeSeparationM>0&&(this.eyeSeparationM=t.eyeSeparationM))}).catch(()=>{}))}_osArrowFraction(){let e=this.pointer.canvas.getBoundingClientRect?.();return e&&e.height>0?os(e.height):fs}idle(){return this.runtime.withdraw(),this.pointer.hideCss(!1),this.filter={},this._uv=null,this.last=null,null}dispose(){this.runtime.dispose(),this.pointer.dispose(),this.shapes.dispose()}}});var Le=Object.freeze({speaker:"high",other:"normal",hidden:"paused"}),eo=["high","normal","low","paused"],to=.02,io=1e3/20,no=3e3,ro=1e3/28;function Fe(n){return typeof n=="function"?n:n===!1||n==="off"?"off":"auto"}function Gt(n=import.meta.url){return De?typeof De=="function"?De():De:new URL("../lift/index.js",n).href}var De=null;function En(n){De=n||null}function so(){return import(Gt())}async function qt(n,{importer:e=so,nav:t=globalThis.navigator,log:i=null,capsOpts:r={webFallback:!0}}={}){let s=(u,f)=>i&&i(u,f),o=(u,f={})=>(s("lift-unavailable",{reason:u,...f}),{lift:null,capabilities:null,caps:null,source:"none",reason:u}),a=Fe(n);if(a==="off")return{lift:null,capabilities:null,caps:null,source:"none",reason:"off"};if(typeof a=="function"){let u=typeof a.liftCapabilities=="function"?a.liftCapabilities:null;return{lift:a,capabilities:u,caps:null,source:"injected",reason:null}}let l;try{l=await e()}catch(u){return o("import-failed",{message:String(u&&u.message||u).slice(0,200)})}let c=l&&typeof l.lift=="function"?l.lift:null;if(!c)return o("no-lift-export");let h=typeof l.liftCapabilities=="function"?l.liftCapabilities:null,d=null;if(h){try{d=await h(r)}catch{d=null}let u=!!(d&&d.webFallback&&d.webFallback.webgpu);if(d&&!d.native&&!u)return o("no-provider",{native:!1,webgpu:!1})}else if(!(t&&t.gpu))return o("no-webgpu");return s("lift-ready",{native:!!(d&&d.native),provider:d&&d.provider||null}),{lift:c,capabilities:h,caps:d,source:"module",reason:null}}function Ie(n){let e=Number.isFinite(+n)&&n!==null?Math.max(-1,Math.min(1,+n)):0;return Math.abs(e)<to?"auto":Math.round((.5+.5*e)*1e3)/1e3}function Qe({id:n,speakerId:e,visible:t=!0}){return t?n!=null&&n===e?Le.speaker:Le.other:Le.hidden}function Yt(n,e){if(!n||!eo.includes(e)||typeof n.setPriority!="function")return!1;try{return n.setPriority(e)!==!1}catch{return!1}}function Kt({degradedMs:n=io,recoveredMs:e=ro,holdMs:t=no,alpha:i=.1}={}){let r=null,s=0,o=!1;return{feed(a){if(!(a>0)||a>1e3)return null;if(r=r===null?a:r+i*(a-r),o){if(r<e)return o=!1,s=0,"recovered"}else if(s=r>n?s+a:0,s>=t)return o=!0,"degraded";return null},reset(){r=null,s=0,o=!1},get frameMs(){return r},get degraded(){return o}}}function Jt({lift:n,max:e=4,log:t=null,options:i=null}={}){let r=i&&typeof i=="object"?i:{},s=new Map,o=null,a=0,l=0,c=(u,f)=>t&&t(u,f),h=(u,f)=>{if(!f.handle)return;let p=Qe({id:u,speakerId:o,visible:f.visible});if(p===f.priority)return;f.priority=p;let m=Yt(f.handle,p);c("lift-priority",{peer:u,priority:p,applied:m})},d={get size(){return s.size},get max(){return e},set max(u){e=Math.max(0,u|0)},has:u=>s.has(u),handle:u=>s.get(u)&&s.get(u).handle||null,priority:u=>s.get(u)&&s.get(u).priority||null,canAcquire:u=>s.has(u)||s.size<e,acquire(u,f,{wall:p,visible:m=!0,onError:w}={}){let _=s.get(u);if(_)return _.pending||Promise.resolve(_.handle);if(s.size>=e)return Promise.resolve(null);let x=++l,R=Qe({id:u,speakerId:o,visible:m}),E={gen:x,handle:null,visible:m,priority:R,pending:null};s.set(u,E);let C={quality:"auto",...r,mode:"live",wall:p,ui:"none",convergence:Ie(a),priority:R};return c("lift-acquire",{peer:u,priority:R,convergence:C.convergence}),E.pending=Promise.resolve().then(()=>n(f,C)).then(k=>{if(s.get(u)!==E||E.gen!==x){try{k&&k.remove&&k.remove()}catch{}return null}return E.pending=null,E.handle=k||null,E.priority=null,h(u,E),k&&typeof k.setConvergence=="function"&&k.setConvergence(Ie(a)),E.handle},k=>(s.get(u)===E&&s.delete(u),c("lift-failed",{peer:u,message:String(k&&k.message||k).slice(0,200)}),w&&w(k),null)),E.pending},release(u){let f=s.get(u);if(f){if(s.delete(u),f.handle)try{f.handle.remove()}catch{}c("lift-release",{peer:u})}},releaseAll(){for(let u of[...s.keys()])d.release(u)},setSpeaker(u){o=u===void 0?null:u;for(let[f,p]of s)h(f,p)},setVisible(u,f){let p=s.get(u);!p||p.visible===!!f||(p.visible=!!f,h(u,p))},setDepth(u){a=u;let f=Ie(u);for(let p of s.values())p.handle&&typeof p.handle.setConvergence=="function"&&p.handle.setConvergence(f);return f},get anyWeb(){for(let u of s.values())if(u.handle&&!u.handle.native)return!0;return!1},list(){return[...s].map(([u,f])=>({id:u,priority:f.priority,pending:!!f.pending,native:!!(f.handle&&f.handle.native)}))}};return d}var ao=null;function Cn(n){ao=typeof n=="function"?n:null}var lo=new WeakMap;function Rn(n,e){n&&(typeof n=="object"||typeof n=="function")&&lo.set(n,e)}Zt();var gl=Object.freeze(["shibata","percival"]);var co="[inline3d] camera rig with convergenceDiopters 0: convergence at infinity puts the whole scene in front of the glass; set convergence to the subject's distance.",ho=new WeakSet;function uo(n){let e=[];return!n||typeof n!="object"||(n.type==="camera"?(n.convergenceDiopters>0||e.push(["convergence",co]),n.verticalFov>Math.PI&&e.push(["fov",`[inline3d] camera rig verticalFov ${n.verticalFov} is more than \u03C0: it looks like DEGREES \u2014 the descriptor takes RADIANS (cameraRigFromCamera / cameraRigFromPose convert three's degrees for you).`])):(n.ipdFactor>1||n.parallaxFactor>1)&&e.push(["factor",`[inline3d] display rig ipdFactor ${n.ipdFactor??1} / parallaxFactor ${n.parallaxFactor??1}: above 1 exaggerates depth past what the display shows by construction (1 = correct; below 1 = a comfort dial). Sent as given.`])),e}function Qt(n,e){if(!(!e||typeof e!="object")&&!(e.type==="camera"?e.convergenceDiopters>0&&!(e.verticalFov>Math.PI):!(e.ipdFactor>1||e.parallaxFactor>1)))for(let[t,i]of uo(e))n.has(t)||(n.add(t),!(t==="convergence"&&ho.has(e))&&console.warn(i))}function Tn(n){let e=String(n||"");return e.startsWith("cross-pass")?"the canvas is inside its own render surface: a CSS effect on it or an ancestor (filter, opacity < 1, mask, clip-path, mix-blend-mode, backdrop-filter). Remove it (woven-canvas rule 7)":e==="no-quad"?"the canvas drew nothing the compositor can see: it is not drawing, is occluded, or a CSS effect on it or an ancestor (filter, opacity < 1, mask, clip-path, mix-blend-mode, backdrop-filter) hides it (woven-canvas rule 7)":e==="no-identity"?"the canvas reached the browser without its identity: register it once, keep it mounted, cover it until firstWoven (woven-canvas rules 3-5)":e==="no-join"?"nothing joined this rect; harmless off screen, otherwise check the canvas is drawing and on screen":e==="resolve-dropped"?"the browser could not resolve the canvas's GPU resource (a browser-side issue)":"see docs/woven-canvas-rules.md \xA73"}var On=new WeakMap,Q;function An(n){let e=null;for(let[t,i]of n)i>0&&(!e||i<e[1])&&(e=[t,i]);return e}function fo(n){if(!n||typeof n.getParameter!="function")return null;let e=On.get(n);if(e)return e;let t,i,r;try{t=n.getParameter(n.MAX_TEXTURE_SIZE??3379),i=n.getParameter(n.MAX_RENDERBUFFER_SIZE??34024),r=n.getParameter(n.MAX_VIEWPORT_DIMS??3386)}catch{return null}let s=r&&r.length>=2?r[0]:0,o=r&&r.length>=2?r[1]:0,a=An([["MAX_TEXTURE_SIZE",t],["MAX_RENDERBUFFER_SIZE",i],["MAX_VIEWPORT_DIMS",s]]),l=An([["MAX_TEXTURE_SIZE",t],["MAX_RENDERBUFFER_SIZE",i],["MAX_VIEWPORT_DIMS",o]]);if(!a||!l)return null;let c={maxW:a[1],maxH:l[1],nameW:a[0],nameH:l[0],valueW:a[1],valueH:l[1]};return On.set(n,c),c}function Pn(){if(Q!==void 0)return Q;Q=null;try{if(typeof document>"u"||!document||typeof document.createElement!="function")return Q;let n=document.createElement("canvas"),e=n.getContext("webgl2")||n.getContext("webgl");if(!e)return Q;Q=fo(e),e.getExtension?.("WEBGL_lose_context")?.loseContext?.()}catch{Q=null}return Q}function Dn(n,e,t,{cols:i=2,rows:r=1}={}){let s=n*i,o=e*r,a={eyeW:n,eyeH:e,cols:i,scale:1,clamped:!1,reqW:s,reqH:o,bufW:s,bufH:o,limitName:"",limitValue:0};if(!t||!(n>0)||!(e>0))return a;let l=t.maxW/s,c=t.maxH/o,h=Math.min(l,c);if(!(h<1))return a;let d=l<=c,u=Math.max(1,Math.min(Math.floor(n*h+1e-9),Math.floor(t.maxW/i))),f=Math.max(1,Math.min(Math.floor(e*h+1e-9),Math.floor(t.maxH/r)));return{eyeW:u,eyeH:f,cols:i,scale:h,clamped:!0,reqW:s,reqH:o,bufW:u*i,bufH:f*r,limitName:d?t.nameW:t.nameH,limitValue:d?t.valueW:t.valueH}}function ei(n){return Math.round(n*1e3)/1e3}function Ln(n,e,t){let i=typeof t=="number"?` (renderScale ${ei(t)} \u2192 ${ei(t*e.scale)})`:` (scale ${ei(e.scale)})`;return`${n} ${e.cols===1?"buffer":"SBS buffer"} ${e.reqW}\xD7${e.reqH} exceeds ${e.limitName} ${e.limitValue} on this device; rendering at ${e.bufW}\xD7${e.bufH}${i}.`}function In(n,e){let t=n?.width||0,i=n?.height||0,r=e&&e.drawingBufferWidth>0?e.drawingBufferWidth:t,s=e&&e.drawingBufferHeight>0?e.drawingBufferHeight:i,o=t>0?r/t:1,a=i>0?s/i:1;return{sx:o,sy:a,w:r,h:s,mismatch:o!==1||a!==1}}function Fn(n,e,t,i="laying the eyes out from the drawing buffer. Lower renderScale to stay inside the device limit."){return`${n} the browser clamped this canvas's drawing buffer to ${t.w}\xD7${t.h} (canvas.width/height say ${e.width}\xD7${e.height}); ${i}`}var de="smoothstep",ii=["linear","smoothstep","easeoutcubic"];function ni(n){if(typeof n!="string")return null;let e=n.toLowerCase().replace(/[-_\s]/g,"");return ii.includes(e)?e:null}function po(n,e){if(e<=0)return 0;if(e>=1)return 1;if(n==="linear")return e;if(n==="easeoutcubic"){let t=1-e;return 1-t*t*t}return e*e*(3-2*e)}var ue="idle",Nn="rampDownThenFire",ti="fireThenRampUp",tt=class{constructor(e,t){this._phase=ue,this._targetMode=null,this._firePending=!1,this._fireAtEnd=!1,this._from=0,this._to=0,this._cur=0,this._t=1,this._dur=180/1e3,this._easing=de,(e!==void 0||t!==void 0)&&this.configure(e,t)}configure(e,t){if(e!==void 0){let i=Number(e);this._dur=Number.isFinite(i)&&i>0?i:0}return t!==void 0&&(this._easing=ni(t)||de),this}get durationS(){return this._dur}get easing(){return this._easing}request({targetMode:e=null,targetViewCount:t,currentMode:i=null,currentViewCount:r,current:s,steady:o=1}={}){let a=!(t>1),l=!(r>1),c=Number.isFinite(o)?o:1,h=Number.isFinite(s)?s:c;return this._targetMode=e,this._from=h,a&&!l?(this._phase=Nn,this._to=0,this._fireAtEnd=!0,this._firePending=!1):!a&&l?(this._phase=ti,this._from=0,this._to=c,this._firePending=!0,this._fireAtEnd=!1):(this._phase=ti,this._to=a?h:c,this._firePending=!(e!==null&&e===i),this._fireAtEnd=!1),this._t=this._dur>0?0:1,this._cur=this._from,this}update(e){let t=!1;if(this._phase!==ue){let i=Number.isFinite(e)&&e>0?e:0;this._t<1&&this._dur>0?(this._t+=i/this._dur,this._t>1&&(this._t=1)):this._t=1,this._cur=this._from+(this._to-this._from)*po(this._easing,this._t),this._phase===ti?(this._firePending&&(this._firePending=!1,t=!0),this._t>=1&&(this._phase=ue)):this._t>=1&&(this._fireAtEnd&&(this._fireAtEnd=!1,t=!0),this._phase=ue)}return{factor:this._cur,fire:t,mode:this._targetMode}}active(){return this._phase!==ue}value(){return this._cur}firePending(){return this._phase===Nn?this._fireAtEnd:this._firePending}cancel(){return this._phase=ue,this._firePending=!1,this._fireAtEnd=!1,this._t=1,this}};var Y=null;Cn(n=>{let e=Y;if(!e||!e._running||!n)return null;let t=i=>({layer:i.layer,session:e.session});for(let i of e._windows.values())if(i.canvas===n&&i.layer)return t(i);for(let i of e._windows.values())if(i.layer&&typeof n.contains=="function"&&n.contains(i.canvas))return t(i);for(let i of e._windows.values()){let r=i.canvas.parentElement;if(i.layer&&r&&typeof r.contains=="function"&&r.contains(n))return t(i)}return null});var mo=()=>typeof navigator<"u"&&!!navigator.xr,re=()=>typeof window<"u"&&typeof window.XRDisplayLayer=="function",it=()=>re()&&"excludeElement"in window.XRDisplayLayer.prototype,ri=()=>{if(!re())return!1;try{return"setViewRig"in window.XRDisplayLayer.prototype}catch{return!1}},go=["getDisplayInfo","getRenderingModes","requestRenderingMode"],qn=["renderingmodechange","hardwaredisplaystatechange"],fi="trackingstatechange",Yn=["unknown","tracking","searching"],zn=[...qn,fi];function nt(n){try{let e=n?n.trackingState:void 0;return Yn.includes(e)?e:null}catch{return null}}var si=()=>{if(!re())return!1;try{let n=window.XRDisplayLayer.prototype;return go.every(e=>typeof n[e]=="function")}catch{return!1}},oi=()=>{if(!re())return!1;try{return typeof window.XRDisplayLayer.prototype.undock=="function"}catch{return!1}},pe=null;function fe(){if(pe!==null)return pe;if(!re())return!1;try{let n=window.XRDisplayLayer.occlusionByDrawOrder;if(typeof n=="boolean")return pe=n}catch{}return!1}function _o(n){if(pe!==null)return pe;if(!n||!re()||!("occlusionByDrawOrder"in window.XRDisplayLayer.prototype))return null;try{return pe=!!n.occlusionByDrawOrder}catch{return null}}var Wn=!1;function ai(){Wn||(Wn=!0,console.info("[inline3d] This browser composites 2D over woven 3D automatically, per-pixel by draw order \u2014 overlay exclusion is obsolete here, so exclude()/addGlobalOverlay()/data-inline3d-overlay/autoChrome are accepted and ignored. Your 2D chrome already occludes the tiles correctly. The calls are harmless (keep them if you also ship to older DisplayXR Browsers); gate on inline3dOcclusionByDrawOrder() to drop them."))}function Kn(){return mo()&&re()}function li(n){return{type:"display",position:{x:0,y:0,z:0},orientation:{x:0,y:0,z:0,w:1},virtualDisplayHeight:n.virtualDisplayHeight>0?n.virtualDisplayHeight:.24,ipdFactor:1,parallaxFactor:1,perspectiveFactor:1}}function vo(n,e){let t=Number.isFinite(n.ipdFactor)?n.ipdFactor:1,i=Number.isFinite(n.parallaxFactor)?n.parallaxFactor:1;return{...n,ipdFactor:t*e,parallaxFactor:i*e}}var yo=16;function H(){return typeof performance<"u"&&performance&&typeof performance.now=="function"?performance.now():Date.now()}var pi=1200,wo=new Set(["pending","woven","withheld"]),Hn=3,bo=new Set(["getDisplayInfo","getRenderingModes","requestRenderingMode"]),xo=new Set(["getDisplayInfo","getRenderingModes"]);function So(n){return n==null||Array.isArray(n)&&n.length===0}function ci(){try{let n=typeof XRDisplayLayer=="function"?XRDisplayLayer:null;return!!(n&&n.prototype&&"wovenState"in n.prototype)}catch{return!1}}function rt(n){try{let e=n?n.wovenState:null;return wo.has(e)?e:null}catch{return null}}function hi(n){try{let e=n?n.withheldReason:null;return typeof e=="string"&&e?e:null}catch{return null}}var $n=!1;function Mo(n){if(n==null)return de;let e=ni(n);return e||($n||($n=!0,console.warn(`[inline3d] createInline3D({ modeSwitch: { easing: ${JSON.stringify(n)} } }) is not a curve this SDK knows (${ii.join(" / ")}); using '${de}'.`)),de)}var Un=!1;function Eo(){Un||(Un=!0,console.info("[inline3d] The active rendering mode is 1-view, so this SDK has zeroed every window rig (ipdFactor/parallaxFactor -> 0) \u2014 both eyes now render from one place. The runtime keeps weaving the same two-view atlas whatever the page submits, so leaving stereo in it would put two slightly different images on a flat panel, i.e. a blurry double image instead of 2D. Your rendering is unchanged; the flattening is a copy applied on the way to the layer and it is undone the moment a 2-view mode goes active again."))}function mi(n){return n&&n.detail!==void 0&&n.detail!==null?n.detail:void 0}function Jn(n){let e=mi(n);return e!==void 0?[e,n]:[n]}function Co(n){for(let e of Jn(n)){if(typeof e=="number"&&Number.isFinite(e))return e;if(e&&typeof e=="object"){let t=e.modeIndex!==void 0?e.modeIndex:e.mode;if(typeof t=="number"&&Number.isFinite(t))return t}}return-1}function Ro(n){for(let e of Jn(n)){if(e==="2d"||e==="3d")return e;if(e&&typeof e=="object"){let t=e.state!==void 0?e.state:e.hardwareDisplayState;if(t==="2d"||t==="3d")return t}}return null}var Vn=!1;function ko(){Vn||(Vn=!0,console.warn("[inline3d] This browser has no XRDisplayLayer.setViewRig, so the view rig was ignored (the window still weaves \u2014 the runtime keeps the default display rig, scaled by virtualDisplayHeight). Gate on inline3dViewRigSupported() if your page's framing depends on the rig; further calls are silent."))}var Bn=!1;function To(){Bn||(Bn=!0,console.warn("[inline3d] addScene got BOTH viewRig and virtualDisplayHeight; on a browser with rig support the rig wins and the height is dropped. They describe the same slot \u2014 virtualDisplayHeight is shorthand for exactly one rig (display, identity pose, all factors 1) \u2014 so there is no merge. This is only worth passing as a PAIR deliberately: the height is what a browser without setViewRig will use, so a camera-rig scene can name its own fallback framing. Otherwise say it once, inside the rig."))}async function Zn(n={}){let{referenceSpace:e="viewer",lazy:t=!0,rootMargin:i="50% 0px",autoChrome:r=!0,modeSwitch:s=null,untrackedFallback:o="none",viewerEase:a}=n;if(!Kn())return{supported:!1,trackingState:"unknown"};let l;try{l=await navigator.xr.requestSession("inline-3d")}catch(h){return{supported:!1,trackingState:"unknown",error:h}}a!==void 0&&Rn(l,a);let c=null;try{c=await l.requestReferenceSpace(e)}catch{}return new gi(l,c,{lazy:t,rootMargin:i,autoChrome:r,modeSwitch:s,untrackedFallback:o})}var Ne=null;function ot(n={}){return Y&&Y._running?Promise.resolve(Y):Ne||(Ne=Zn(n).finally(()=>{Ne=null}),Ne)}var Xn=.7,Oo=new Set(["IMG","SVG","VIDEO","CANVAS","BUTTON","INPUT","SELECT","TEXTAREA"]);function Ao(n){let e=[],t=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT);for(let i=t.nextNode();i;i=t.nextNode())if(!i.closest("[data-inline3d-no-overlay]")){if(Oo.has(i.tagName.toUpperCase())){e.push(i);continue}for(let r of i.childNodes)if(r.nodeType===Node.TEXT_NODE&&r.nodeValue.trim()){e.push(i);break}}return e}var ui=4;function di(n){let e=typeof window<"u"&&window.devicePixelRatio||1,t="";if(typeof n.getBoundingClientRect=="function"){let i=n.getBoundingClientRect()||{},r=typeof window<"u"&&window.scrollX||0,s=typeof window<"u"&&window.scrollY||0;t=`+${Math.round((i.left??i.x??0)+r)},${Math.round((i.top??i.y??0)+s)}`}return`${n.clientWidth}x${n.clientHeight}@${e}${t}`}function Gn(n){let e=typeof window<"u"&&window.devicePixelRatio||1;return{width:n.clientWidth||0,height:n.clientHeight||0,dpr:e}}function Po(n){if(n==null||n===!1||n==="off")return null;if(n==="auto"||n===!0)return{color:"#000",snapshot:!0};if(typeof n=="object"){if(n.color!==void 0&&typeof n.color!="string")throw new TypeError("[inline3d] rectCover.color must be a CSS color string.");return{color:n.color||"#000",snapshot:n.snapshot!==!1}}throw new TypeError(`[inline3d] rectCover: expected 'auto', 'off' or { color?, snapshot? }; got ${JSON.stringify(n)}.`)}var gi=class{constructor(e,t,{lazy:i,rootMargin:r,autoChrome:s=!0,modeSwitch:o=null,untrackedFallback:a="none"}){this.supported=!0,this.session=e,this.refSpace=t,this._windows=new Map,this._claims=new Map,this._doubleWarned=new WeakSet,this._globalOverlays=new Set,this._isolatedBy=new WeakMap,this._autoChrome=s,this._autoChromeEls=new Set,this._lastChromeScan=0,this._fullTileWarned=new WeakSet,this._stoodDown=!1,this._activeModeIndex=-1,this._activeViewCount=0,this._hardwareDisplayState=null,this._modes=null,this._stereoCollapsed=!1,this._displayListeners=new Map,this._primedDisplayState=!1;let l=o&&typeof o=="object"?o:{};this._msEnabled=l.enabled!==!1,this._modeSwitch=new tt((Number.isFinite(l.durationMs)?Math.max(0,l.durationMs):180)/1e3,Mo(l.easing)),this._stereoFactor=1,this._msFire=null,this._msArmedUp=!1,this._msLastMs=null,this._msTick=null,this._trackingSupported=nt(e)!==null,this._trackingState=this._trackingSupported?nt(e):"unknown",this._untrackedFallback=a==="mono"?"mono":"none",this._bakedStereo=1,this._bakedTarget=1,this._bakedAt=null,this._bakedEaseS=(Number.isFinite(l.durationMs)?Math.max(0,l.durationMs):180)/1e3,this._applyUntrackedTarget(),this.undock=oi()?{model:!1,splat:!1}:null,this._undockRead=!1,this._running=!0,this._lazy=i,this._observer=i&&typeof IntersectionObserver=="function"?new IntersectionObserver(c=>this._onIntersect(c),{rootMargin:r}):null,this._loopId=0,this._framePending=!1,this._frameCount=0,this._frameWatchdog=null,this._suspended=null,Y&&Y._running&&Y!==this&&console.warn("[inline3d] A second inline-3D session is live in this document. The browser's element-rect channel is a whole-widget setter, so both managers clobber each other's rect list every frame \u2014 tiles may flicker, ghost, or weave at a stale rect. Use ONE createInline3D() per document and add every window to it; if you are switching views, close() the previous manager first."),Y=this,e.addEventListener("end",()=>this._teardown()),this._bindDisplayEvents(),this._bindTrackingEvents(),this._scanChrome(),this._bindLifecycle(),this._armDprWatch(),this._requestFrame()}get liveCount(){let e=0;for(let t of this._windows.values())t.layer&&e++;return e}addGlobalOverlay(e){if(!(!e||this._globalOverlays.has(e))){fe()&&ai(),this._globalOverlays.add(e);for(let t of this._windows.values())t.layer&&this._applyExclusion(t,e)}}removeGlobalOverlay(e){if(!(!e||!this._globalOverlays.delete(e)))for(let t of this._windows.values())t.layer&&this._dropExclusion(t,e)}_scanChrome(){if(fe()||!this._autoChrome||!it()||typeof document>"u")return;let e=Date.now();if(e-this._lastChromeScan<1e3)return;this._lastChromeScan=e;let t=document.body;if(!t)return;let i=new Set,r=t.querySelectorAll(":scope > *, :scope > * > *, :scope > * > * > *");for(let s of r){if(s.closest("[data-inline3d-no-overlay]"))continue;let o=getComputedStyle(s).position;if(o!=="fixed"&&o!=="sticky")continue;let a=!1;for(let l of this._windows.keys())if(s===l||s.contains(l)){a=!0;break}if(!a){i.add(s);for(let l of Ao(s))i.add(l)}}for(let s of this._autoChromeEls){let o=!1;if(s.isConnected){for(let a of this._windows.keys())if(s===a||s.contains(a)){o=!0;break}}(!s.isConnected||o)&&(this._autoChromeEls.delete(s),this.removeGlobalOverlay(s))}for(let s of i)this._globalOverlays.has(s)||(this._autoChromeEls.add(s),this.addGlobalOverlay(s))}addImage(e,t,i={}){this._warnDoubleAttach(e,"addImage",i._dxrClaim);let r=this._register(e,"image",i);return r.method="addImage",r.ready=Lo(t).then(s=>{r.img=s,r.repaint()}),this._handle(e,r)}addVideo(e,t,i={}){this._warnDoubleAttach(e,"addVideo",i._dxrClaim);let r=this._register(e,"video",i);return r.method="addVideo",r.video=t,this._handle(e,r)}addScene(e,t,i={}){this._warnDoubleAttach(e,"addScene",i._dxrClaim),i.viewRig&&i.virtualDisplayHeight!==void 0&&To();let r=this._register(e,"scene",{virtualDisplayHeight:.24,...i});return r.method="addScene",r.onFrame=t,r.ownsBuffer=!1,i.bufferClamped===!0&&(r.warnedBufMismatch=!0),this._handle(e,r)}_liveRegistration(e,t){let i=this._claims.get(e);if(i&&i.token!==t)return i.method;let r=this._windows.get(e);return r?r.method||"add*":null}_warnDoubleAttach(e,t,i){let r=this._liveRegistration(e,i);!r||this._doubleWarned.has(e)||(this._doubleWarned.add(e),console.warn(`[inline3d] ${t}() on a canvas that is already registered on this inline-3D session (by ${r}(), not yet removed). This call is rebuilding the canvas's layer (a fresh 0.4-1.2 s identity gap) or putting a second renderer on its context. Change what is IN the canvas instead (setSource, your onFrame, a redrawn source canvas), or call handle.remove() on the first registration first. (Warned once per canvas.)`,e))}_attachGuard(e,t,i={}){let r=this._claims.get(e);if(i&&i._dxrClaim&&r&&r.token===i._dxrClaim)return{opts:i,own:()=>{}};this._warnDoubleAttach(e,t,null);let s={};return{opts:{...i,_dxrClaim:s},own:o=>this._claim(e,t,o,s)}}_claim(e,t,i,r){if(!this._running||!i||typeof i!="object")return;let s={token:r,method:t};this._claims.set(e,s);let o=i.remove,a=(...l)=>(this._claims.get(e)===s&&this._claims.delete(e),typeof o=="function"?o.apply(i,l):void 0);Object.defineProperty(i,"remove",{configurable:!0,enumerable:!0,get:()=>a,set:l=>{o=l}})}_handle(e,t){let i=this;return{remove:()=>this._remove(e),exclude:r=>{r&&(fe()&&ai(),t.excluded.add(r),this._applyExclusion(t,r))},unexclude:r=>{!r||!t.excluded.delete(r)||this._dropExclusion(t,r)},get trackingState(){return i._trackingState},setViewRig:r=>(t.viewRig=r||null,r&&Qt(t.rigWarned,r),this._pushViewRig(t)),setCursorDepth:r=>{let s=t.layer;if(!s||typeof s.setCursorDepth!="function")return!1;try{return r?s.setCursorDepth(r):s.setCursorDepth(),!0}catch{return!1}},getCursorDepthSupport:()=>{let r=t.layer;if(!r||typeof r.getCursorDepthSupport!="function")return Promise.resolve("none");try{return Promise.resolve(r.getCursorDepthSupport()).then(s=>s==="runtime"?"runtime":"none",()=>"none")}catch{return Promise.resolve("none")}},getDisplayInfo:()=>this._layerCall(t,"getDisplayInfo","getDisplayInfo()"),displayMetrics:async()=>{let r=null;try{r=await this._layerCall(t,"getDisplayInfo","getDisplayInfo()")}catch{}return kn(r,e.getBoundingClientRect(),globalThis.devicePixelRatio||1)},getRenderingModes:()=>this._getRenderingModes(t),requestRenderingMode:r=>this._requestRenderingModeEased(r,t),setStereoEnabled:r=>this._setStereoEnabled(r,t),on:(r,s)=>this.on(r,s),off:(r,s)=>this.off(r,s),onDisplayModeChange:r=>this._onDisplayModeChange(r),stats:()=>({frames:t.frames,monoFrames:t.monoFrames}),get wovenState(){return ci()?t.layer?rt(t.layer):"pending":null},get withheldReason(){return!ci()||!t.layer?null:rt(t.layer)==="withheld"?hi(t.layer):null},get firstWoven(){return t.fwPromise},onFirstWoven:r=>{if(typeof r!="function")throw new TypeError("[inline3d] onFirstWoven() takes a function.");let s=!0;return t.fwPromise.then(o=>{if(s)try{r(o)}catch(a){console.error("[inline3d] onFirstWoven callback threw",a)}}),()=>{s=!1}},rewoven:()=>this._rewoven(t)}}getDisplayInfo(){return this._layerCall(this._liveWindow(null),"getDisplayInfo","getDisplayInfo()")}getRenderingModes(){return this._getRenderingModes(null)}requestRenderingMode(e){return this._requestRenderingModeEased(e,null)}setStereoEnabled(e){return this._setStereoEnabled(e,null)}get trackingState(){return this._trackingState}get hardwareDisplayState(){return this._hardwareDisplayState}get activeMode(){return{modeIndex:this._activeModeIndex,viewCount:this._activeViewCount}}get stereoCollapsed(){return this._stereoCollapsed}get modeSwitch(){return{active:this._msTransitionActive(),factor:this._stereoFactor}}close(){try{this.session.end()}catch{}this._teardown()}_effectiveViewRig(e){return this._stereoFactor>=1?e.viewRig||(e.stereoSynthRig?li(e):null):(e.viewRig||(e.stereoSynthRig=!0),vo(e.viewRig||li(e),this._stereoFactor))}_setStereoCollapsed(e){let t=!!e;if(this._stereoCollapsed!==t){this._stereoCollapsed=t,t&&Eo(),!t&&this._msArmedUp?(this._msArmedUp=!1,this._startUpRamp()):this._modeSwitch.active()||(this._stereoFactor=t?0:1);for(let i of this._windows.values()){if(t){let r=i.viewRig||li(i);i.stereoSaved={ipdFactor:r.ipdFactor,parallaxFactor:r.parallaxFactor}}else i.stereoSaved=null;this._pushViewRig(i)}}}_pushViewRig(e){if(!ri())return ko(),!1;if(!e.layer)return!1;let t=this._effectiveViewRig(e);try{return e.layer.setViewRig(t),!0}catch{return!1}}_layerCall(e,t,i,r=[]){if(!si())return Promise.reject(new Error(`[inline3d] ${i} needs a DisplayXR Browser with the display-mode API (XRDisplayLayer.getDisplayInfo/getRenderingModes/requestRenderingMode). Gate on inline3dDisplayModesSupported().`));if(!e||!e.layer)return Promise.reject(new Error(`[inline3d] ${i} needs a live weave layer, and this window has none right now (lazy mode closes the layer while the tile is off screen). Call it once the tile is visible, or create the manager with { lazy: false }.`));if(bo.has(t)&&!e.layerFramed&&this._layerReadPending(e))return this._whenLayerFramed(e).then(()=>this._layerCall(e,t,i,r));let o;try{o=Promise.resolve(e.layer[t](...r))}catch(l){return Promise.reject(l)}if(!xo.has(t)||!this._layerReadPending(e))return o;let a=e.layer;return o.then(l=>e.layer!==a?l:So(l)?this._layerReadPending(e)?this._whenLayerFramed(e).then(()=>this._layerCall(e,t,i,r)):l:(e.lfAnswered=!0,l))}_layerFramedCap(e){return ui*Math.max(e.fwHoldMs,pi)}_layerReadPending(e){return!e.layer||e.lfAnswered||e.lfCapped?!1:H()-e.lfAt>=this._layerFramedCap(e)?(e.lfCapped=!0,!1):!0}_whenLayerFramed(e){return new Promise(t=>{let i=e.layer,r={resolve:t,timer:null},s=Math.max(0,this._layerFramedCap(e)-(H()-e.lfAt));r.timer=setTimeout(()=>{let o=e.framedWaiters.indexOf(r);o>=0&&e.framedWaiters.splice(o,1),e.layer===i&&(e.lfCapped=!0),t()},s),r.timer&&typeof r.timer.unref=="function"&&r.timer.unref(),e.framedWaiters.push(r)})}_tickLayerFramed(e){let t=e.wsLive?rt(e.layer):null;(t?t==="woven":e.lfStereo)?this._noteLayerFramed(e,!0):e.framedWaiters.length&&!this._layerReadPending(e)&&this._noteLayerFramed(e,!1)}_noteLayerFramed(e,t=!0){t&&(e.layerFramed=!0);let i=e.framedWaiters.splice(0);for(let r of i)clearTimeout(r.timer),r.resolve()}_liveWindow(e){if(e&&e.layer)return e;for(let t of this._windows.values())if(t.layer)return t;return e||null}async _getRenderingModes(e){let t=await this._layerCall(this._liveWindow(e),"getRenderingModes","getRenderingModes()"),i=Array.isArray(t)?t:[];this._modes=i;let r=i.find(s=>s.isActive);return r&&(this._activeModeIndex=r.modeIndex,this._activeViewCount=r.viewCount,(r.viewCount===1||r.viewCount===2)&&this._setStereoCollapsed(r.viewCount===1)),this._primedDisplayState=!0,t}_requestRenderingMode(e,t){return this._layerCall(this._liveWindow(t),"requestRenderingMode","requestRenderingMode()",[e])}_msTransitionActive(){return this._modeSwitch.active()||this._msArmedUp||this._msFire!==null}async _requestRenderingModeEased(e,t){if(!this._msEnabled||!ri())return this._requestRenderingMode(e,t);let i=this._modes;if(!Array.isArray(i)||i.length===0)try{i=await this._getRenderingModes(t)}catch{i=null}let r=(Array.isArray(i)?i:[]).find(a=>a&&a.modeIndex===e),s=r&&Number.isFinite(r.viewCount)?r.viewCount:0,o=this._activeViewCount;return s<1||s>2||o<1?this._requestRenderingMode(e,t):s===1?o===1?this._requestRenderingMode(e,t):this._rampDownThenRequest(e,t):this._requestThenRampUp(e,t)}_rampDownThenRequest(e,t){if(this._msFire&&this._msFire.modeIndex===e)return this._msFire.promise;this._settlePendingDown("superseded",`a request for mode ${e} replaced it`);let i={modeIndex:e,win:t,resolve:null,reject:null,promise:null};return i.promise=new Promise((r,s)=>{i.resolve=r,i.reject=s}),this._msFire=i,this._modeSwitch.request({targetMode:e,targetViewCount:1,currentMode:this._activeModeIndex,currentViewCount:this._activeViewCount,current:this._stereoFactor,steady:1}),this._msLastMs=H(),this._armModeSwitchTick(),i.promise}_requestThenRampUp(e,t){let r=this._msFire!==null&&e===this._activeModeIndex;this._settlePendingDown("superseded",`a request for mode ${e} reversed it`);let s=r?Promise.resolve(void 0):this._requestRenderingMode(e,t);return this._stereoFactor<1&&(this._stereoCollapsed?(this._msArmedUp=!0,this._modeSwitch.cancel(),this._stereoFactor=0):this._startUpRamp()),s.catch(o=>{throw this._msArmedUp&&(this._msArmedUp=!1,this._modeSwitch.active()||(this._stereoFactor=this._stereoCollapsed?0:1)),o})}_startUpRamp(){this._settlePendingDown("superseded","the display returned to 3D"),this._modeSwitch.request({targetMode:this._activeModeIndex,targetViewCount:2,currentMode:this._activeModeIndex,currentViewCount:2,current:this._stereoFactor,steady:1}),this._msLastMs=H(),this._armModeSwitchTick()}_settlePendingDown(e,t){let i=this._msFire;if(!i)return;this._msFire=null;let r=new Error(`[inline3d] the request for rendering mode ${i.modeIndex} was never forwarded: ${t}. A ->2D switch is held until the disparity has ramped out, so a request that is reversed or replaced in that window is dropped rather than fired late.`);r.name=e,i.reject(r)}_advanceModeSwitch(){if(!this._modeSwitch.active()){this._msLastMs=null,this._disarmModeSwitchTick();return}let e=H(),t=typeof this._msLastMs=="number"?Math.max(0,(e-this._msLastMs)/1e3):0;this._msLastMs=e;let i=this._modeSwitch.update(t);if(i.factor!==this._stereoFactor){this._stereoFactor=i.factor;for(let r of this._windows.values())this._pushViewRig(r)}if(i.fire&&this._msFire){let r=this._msFire;this._msFire=null,this._requestRenderingMode(r.modeIndex,r.win).then(s=>r.resolve(s),s=>{this._startUpRamp(),r.reject(s)})}this._modeSwitch.active()||(this._msLastMs=null,this._disarmModeSwitchTick())}_armModeSwitchTick(){this._msTick!==null||typeof setTimeout!="function"||(this._msTick=setTimeout(()=>{this._msTick=null,this._running&&(this._advanceModeSwitch(),this._modeSwitch.active()&&this._armModeSwitchTick())},yo))}_disarmModeSwitchTick(){this._msTick!==null&&(typeof clearTimeout=="function"&&clearTimeout(this._msTick),this._msTick=null)}async _setStereoEnabled(e,t){let i=e?2:1,r=await this._getRenderingModes(t),s=Array.isArray(r)?r:[],o=s.find(a=>a.viewCount===i&&a.isRequestable);if(!o)throw new Error(`[inline3d] setStereoEnabled(${!!e}) found no requestable ${i}-view mode on this display (${s.length} mode(s) listed). It is sugar over requestRenderingMode() and cannot invent one \u2014 read getRenderingModes() and drive the list yourself.`);return o.isActive&&!this._msTransitionActive()||await this._requestRenderingModeEased(o.modeIndex,t),!!e}_bindDisplayEvents(){let e=this.session;!e||typeof e.addEventListener!="function"||si()&&(e.addEventListener("renderingmodechange",t=>{this._onRenderingModeChange(t).catch(()=>{})}),e.addEventListener("hardwaredisplaystatechange",t=>{this._onHardwareDisplayStateChange(t).catch(()=>{})}))}_onHardwareDisplayStateChange(e){let t=Ro(e),i=mi(e),r=a=>{a&&(this._hardwareDisplayState=a),this._emitDisplay({type:"hardwaredisplaystatechange",state:a||this._hardwareDisplayState,detail:i})};t&&r(t);let s=this._activeModeIndex,o=this._activeViewCount;return this._getRenderingModes(null).then(a=>{let l=(Array.isArray(a)?a:[]).find(c=>c.isActive)||null;if(l&&(l.modeIndex!==s||l.viewCount!==o)&&this._emitDisplay({type:"renderingmodechange",modeIndex:this._activeModeIndex,viewCount:this._activeViewCount||null,mode:l,detail:null}),!t){let c=l&&typeof l.hardwareDisplay3D=="boolean"?l.hardwareDisplay3D?"3d":"2d":null;r(c)}}).catch(()=>{t||r(null)})}async _onRenderingModeChange(e){let t=mi(e),i=Co(e),r=null;try{let s=await this._getRenderingModes(null),o=Array.isArray(s)?s:[];r=(i>=0?o.find(a=>a.modeIndex===i):null)||o.find(a=>a.isActive)||null}catch{}r?(this._activeModeIndex=r.modeIndex,this._activeViewCount=r.viewCount):i>=0&&(this._activeModeIndex=i),(this._activeViewCount===1||this._activeViewCount===2)&&this._setStereoCollapsed(this._activeViewCount===1),this._emitDisplay({type:"renderingmodechange",modeIndex:this._activeModeIndex,viewCount:this._activeViewCount||null,mode:r,detail:t})}_emitDisplay(e,t){let i=this._displayListeners.get(e.type);if(!i)return;let r=t||[e];for(let s of[...i])try{s(...r)}catch(o){console.error(`[inline3d] ${e.type} listener threw`,o)}}on(e,t){if(typeof t!="function")throw new TypeError("[inline3d] on() takes (type, function).");if(!zn.includes(e))throw new TypeError(`[inline3d] on() knows ${zn.join(" / ")}, got ${JSON.stringify(e)}.`);let i=this._displayListeners.get(e);return i||this._displayListeners.set(e,i=new Set),i.add(t),()=>this.off(e,t)}off(e,t){let i=this._displayListeners.get(e);i&&i.delete(t)}_onDisplayModeChange(e){if(typeof e!="function")throw new TypeError("[inline3d] onDisplayModeChange() takes a function.");let t=qn.map(i=>this.on(i,e));return()=>{for(let i of t)i()}}async refreshUndock(){if(!oi())return this.undock=null;let e=this._liveWindow(null);if(!e||!e.layer||typeof e.layer.getUndockCapabilities!="function")return this.undock;try{let t=await e.layer.getUndockCapabilities();this.undock={model:!!(t&&t.model),splat:!!(t&&t.splat)}}catch{}return this.undock}_register(e,t,i){this._windows.has(e)&&this._remove(e),e.style.willChange="transform",e.style.transform="translateZ(0)";let r={canvas:e,kind:t,layer:null,img:null,video:null,onFrame:null,onLayerLost:typeof i.onLayerLost=="function"?i.onLayerLost:null,layerLostSent:!1,onResize:t==="scene"&&typeof i.onResize=="function"?i.onResize:null,resizeBox:null,inResize:!1,ready:null,ownsBuffer:t!=="scene",cornerRadius:i.cornerRadius||0,feather:i.feather||0,reqW:i.width||0,reqH:i.height||0,virtualDisplayHeight:i.virtualDisplayHeight||0,viewRig:i.viewRig||null,rigWarned:new Set,warnedWithheld:!1,stereoSaved:null,stereoSynthRig:!1,observeEl:i.observe||e,ctx:t==="scene"?null:e.getContext("2d"),repaint:()=>this._paint(r,null),excluded:new Set,autoExcluded:new Set,overlayObserver:null,sizeObserver:null,resizePending:!1,frames:0,monoFrames:0,fwResult:null,fwResolve:null,fwPromise:null,fwHoldMs:Do(i.firstWovenHoldMs),fwRegAt:H(),fwLayerAt:null,fwStereo:!1,rw:null,rwGone:null,wsLive:!1,rc:null,layerFramed:!1,lfAnswered:!1,lfStereo:!1,lfAt:0,lfCapped:!1,framedWaiters:[]},s=Po(i.rectCover);return s&&(r.rc={cfg:s,box:null,el:null,up:!1,snapped:!1,snapWanted:!1,waiting:null,w:0,h:0}),r.fwPromise=new Promise(o=>{r.fwResolve=o}),r.viewRig&&Qt(r.rigWarned,r.viewRig),this._windows.set(e,r),this._lazy&&this._observer?this._observer.observe(r.observeEl):this._activate(r),r}_remove(e){let t=this._windows.get(e);t&&(this._observer&&this._observer.unobserve(t.observeEl),this._deactivate(t),this._windows.delete(e),this._settleFirstWoven(t,!1,"removed"),this._dropCover(t))}_onIntersect(e){for(let t of e){let i=null;for(let r of this._windows.values())if(r.observeEl===t.target){i=r;break}i&&(t.isIntersecting?this._activate(i):this._deactivate(i))}}_activate(e){if(!e.layer){this._scanChrome();try{let t=ri()?this._effectiveViewRig(e):null,i=t?{viewRig:t}:e.virtualDisplayHeight>0?{virtualDisplayHeight:e.virtualDisplayHeight}:{};e.layer=new XRDisplayLayer(this.session,e.canvas,i)}catch(t){e.layer=null,e.layerFailWarned||(e.layerFailWarned=!0,console.warn("[inline3d] new XRDisplayLayer() failed for this window \u2014 it will show FLAT 2D instead of woven 3D, and the SDK will not retry. The canvas has been repainted mono so it cannot be left holding a raw side-by-side pair.",t)),this._paintMono(e),this._notifyLayerLost(e),this._settleFirstWoven(e,!1,"layer-failed");return}e.fwResult||(e.fwLayerAt=H(),e.fwStereo=!1),e.wsLive=ci(),e.layerFramed=!1,e.lfAnswered=!1,e.lfStereo=!1,e.lfCapped=!1,e.lfAt=H(),this._restartRewoven(e),e.layerLostSent=!1,!this._primedDisplayState&&si()&&(this._primedDisplayState=!0,this._getRenderingModes(e).catch(()=>{this._primedDisplayState=!1})),oi()&&this.undock&&!this._undockRead&&(this._undockRead=!0,this.refreshUndock().catch(()=>{})),_o(e.layer)===!0&&this._standDownLegacyOcclusion();for(let t of e.excluded)this._applyExclusion(e,t);for(let t of this._globalOverlays)this._applyExclusion(e,t);this._startOverlayScan(e),e.ownsBuffer&&(this._sizeBuffer(e,!0),this._paint(e,null)),this._startSizeWatch(e)}}_deactivate(e){if(this._noteLayerFramed(e,!1),this._stopOverlayScan(e),this._stopSizeWatch(e),e.layer){try{e.layer.close()}catch{}e.layer=null}this._paintMono(e)}_paintMono(e){!e.ownsBuffer||e.kind==="scene"||(this._sizeBuffer(e,!1),this._paint(e,null))}_notifyLayerLost(e){if(!(e.kind!=="scene"||typeof e.onLayerLost!="function"||e.layerLostSent)){e.layerLostSent=!0;try{e.onLayerLost()}catch(t){console.warn("[inline3d] a scene window's onLayerLost callback threw",t)}}}_isFullTileOverlay(e,t){if(!t||typeof t.getBoundingClientRect!="function")return!1;let i=t.getBoundingClientRect(),r=e.canvas.getBoundingClientRect(),s=i.width*i.height,o=r.width*r.height;if(s<=0||o<=0)return!1;let a=Math.min(i.right,r.right)-Math.max(i.left,r.left),l=Math.min(i.bottom,r.bottom)-Math.max(i.top,r.top);if(a<=0||l<=0)return!1;let c=a*l;return c/s<Xn||c/o<Xn?!1:(this._fullTileWarned.has(t)||(this._fullTileWarned.add(t),console.warn("[inline3d] Refusing a full-tile overlay: this element covers its own woven canvas, and the browser's geometric matcher cannot tell the two apart \u2014 it would stage the CANVAS as the overlay and the tile would show its raw side-by-side buffer instead of 3D. Make the overlay a PARTIAL region of the tile (a caption band, a badge, a corner plate), or move it outside the tile and register it with addGlobalOverlay().",t)),!0)}_applyExclusion(e,t){if(fe()||!e.layer||!it()||this._isFullTileOverlay(e,t))return;let i=this._isolatedBy.get(t);if(i||(i=new Set,this._isolatedBy.set(t,i)),i.add(e),!t.dataset.inline3dIsolated){t.dataset.inline3dPriorWillChange=t.style.willChange||"";let r=t.style.willChange&&t.style.willChange!=="auto"?t.style.willChange+", transform":"transform";t.style.willChange=r,t.dataset.inline3dIsolated="1"}try{e.layer.excludeElement(t)}catch{}}_dropExclusion(e,t){if(fe())return;let i=this._isolatedBy.get(t);if(i&&i.delete(e),(!i||i.size===0)&&this._unpromote(t),!(!e.layer||!it()))try{e.layer.unexcludeElement(t)}catch{}}_unpromote(e){return!e||!e.dataset||!e.dataset.inline3dIsolated?!1:(e.style.willChange=e.dataset.inline3dPriorWillChange||"",delete e.dataset.inline3dPriorWillChange,delete e.dataset.inline3dIsolated,!0)}_standDownLegacyOcclusion(){if(this._stoodDown)return;this._stoodDown=!0;let e=!1;for(let t of this._windows.values()){t.overlayObserver&&(this._stopOverlayScan(t),e=!0);for(let i of t.excluded)this._unpromote(i)&&(e=!0)}for(let t of this._autoChromeEls)this._globalOverlays.delete(t),this._unpromote(t),e=!0;this._autoChromeEls.clear();for(let t of this._globalOverlays)this._unpromote(t)&&(e=!0);this._isolatedBy=new WeakMap,e&&ai()}_startOverlayScan(e){if(fe()||!it()||typeof MutationObserver!="function")return;let t=e.canvas.parentElement;if(!t)return;let i=()=>{let r=new Set(t.querySelectorAll("[data-inline3d-overlay]"));for(let s of e.autoExcluded)r.has(s)||(e.autoExcluded.delete(s),this._dropExclusion(e,s));for(let s of r)e.autoExcluded.has(s)||(e.autoExcluded.add(s),this._applyExclusion(e,s))};i(),e.overlayObserver=new MutationObserver(i),e.overlayObserver.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-inline3d-overlay"]})}_stopOverlayScan(e){e.overlayObserver&&(e.overlayObserver.disconnect(),e.overlayObserver=null),e.autoExcluded.clear()}_eyeSize(e,t=!0){let i=Math.min(window.devicePixelRatio||1,2),r=e.reqW||Math.round((e.canvas.clientWidth||256)*i),s=e.reqH||Math.round((e.canvas.clientHeight||256)*i),o=1,a=!e.reqW&&!e.reqH&&this._sourceEyeSize(e);if(a){let c=Math.max(a.w/r,a.h/s);c<1&&(o=c,r=Math.max(1,Math.round(r*c)),s=Math.max(1,Math.round(s*c)))}let l=Dn(r,s,Pn(),{cols:t?2:1});return l.clamped&&(o*=l.scale,r=l.eyeW,s=l.eyeH,e.warnedBufClamp||(e.warnedBufClamp=!0,console.warn(Ln("[inline3d]",l)))),e.bufScale=o,{w:r,h:s}}_sourceEyeSize(e){if(e.kind!=="video"&&e.kind!=="image")return null;let t=e.kind==="video"?e.video:e.img;if(!t)return null;let i=t.videoWidth||t.naturalWidth||t.width,r=t.videoHeight||t.naturalHeight||t.height;return!(i>1)||!(r>0)?null:{w:i/2,h:r}}_checkSceneBuffer(e){let t=e.canvas;if(!t||typeof t.getContext!="function")return;if(e.sceneGl===void 0){let r=null;try{r=t.getContext("webgl2")||t.getContext("webgl")}catch{r=null}e.sceneGl=r&&typeof r.drawingBufferWidth=="number"?r:null}if(!e.sceneGl)return;let i=In(t,e.sceneGl);i.mismatch&&(e.warnedBufMismatch=!0,console.warn(Fn("[inline3d]",t,i,"getViewport() splits canvas.width, so the eyes are off-centre in the woven buffer. This scene canvas is sized by the page: keep 2 \xD7 eye width and the height within MAX_TEXTURE_SIZE / MAX_RENDERBUFFER_SIZE / MAX_VIEWPORT_DIMS, or map getViewport() onto gl.drawingBufferWidth/Height.")))}_sizeBuffer(e,t){let{w:i,h:r}=this._eyeSize(e,t);e.eyeW=i,e.eyeH=r,e.canvas.width=t?i*2:i,e.canvas.height=r,e.sbs=t}_startSizeWatch(e){if(typeof ResizeObserver=="function"&&!e.sizeObserver){if(e.kind==="scene"){if(!e.onResize)return;e.resizeBox=Gn(e.canvas),e.sizeObserver=new ResizeObserver(()=>this._onSceneResize(e)),e.sizeObserver.observe(e.canvas);return}!e.ownsBuffer||e.reqW&&e.reqH||(e.sizeObserver=new ResizeObserver(()=>this._onBoxChange(e)),e.sizeObserver.observe(e.canvas))}}_onSceneResize(e){if(!e.layer||!e.onResize||e.inResize)return;let t=Gn(e.canvas),i=e.resizeBox;if(!(i&&i.width===t.width&&i.height===t.height&&i.dpr===t.dpr)){e.resizeBox=t,e.inResize=!0;try{e.onResize(t)}catch(r){e.resizeThrewWarned||(e.resizeThrewWarned=!0,console.warn("[inline3d] a scene window's onResize threw; further throws from it are silent.",r))}finally{e.inResize=!1}}}_stopSizeWatch(e){e.sizeObserver&&(e.sizeObserver.disconnect(),e.sizeObserver=null),e.resizePending=!1}_onBoxChange(e){if(!e.layer||!e.ownsBuffer||e.resizePending)return;e.resizePending=!0;let t=()=>{if(!e.resizePending||(e.resizePending=!1,!e.layer||!e.ownsBuffer))return;this._noteRewovenBox(e);let{w:i,h:r}=this._eyeSize(e);i===e.eyeW&&r===e.eyeH||(this._sizeBuffer(e,!0),this._paint(e,null))};typeof requestAnimationFrame=="function"?requestAnimationFrame(t):t()}_armDprWatch(){if(typeof window>"u"||typeof window.matchMedia!="function")return;this._disarmDprWatch();let e;try{e=window.matchMedia(`(resolution: ${window.devicePixelRatio||1}dppx)`)}catch{return}let t=()=>{if(this._running){this._armDprWatch();for(let i of this._windows.values())i.layer&&this._onBoxChange(i)}};try{e.addEventListener("change",t)}catch{return}this._dprWatch={q:e,onChange:t}}_disarmDprWatch(){if(this._dprWatch){try{this._dprWatch.q.removeEventListener("change",this._dprWatch.onChange)}catch{}this._dprWatch=null}}_paint(e,t){if(e.kind==="scene"||!e.ctx)return;let i=this._running&&!!e.layer;!i&&e.sbs&&this._sizeBuffer(e,!1);let r=e.kind==="video"?e.video:e.img;if(!r)return;if(e.kind==="video"&&(r.readyState||0)<2){i&&this._recommitLastFrame(e);return}let s=e.canvas,o=e.ctx,a=r.videoWidth||r.naturalWidth||r.width,l=r.videoHeight||r.naturalHeight||r.height;if(!a||!l)return;let c=a+"x"+l;if(e.srcKey!==c&&(e.srcKey=c,e.ownsBuffer&&!(e.reqW&&e.reqH))){let{w:m,h:w}=this._eyeSize(e,e.sbs);(m!==e.eyeW||w!==e.eyeH)&&this._sizeBuffer(e,e.sbs)}let h=e.bufScale||1,d=e.cornerRadius*h,u=e.feather*h;if(o.clearRect(0,0,s.width,s.height),!e.sbs){st(o,r,0,0,a/2,l,0,0,s.width,s.height,d,u);return}let f=s.width/2,p=Math.min(this._stereoFactor,this._bakedStereo);if(p<1){st(o,r,0,0,a/2,l,0,0,f,s.height,d,u),Io(o,r,a/2,l,f,s.height,p,d,u);return}d>0||u>0?(st(o,r,0,0,a/2,l,0,0,f,s.height,d,u),st(o,r,a/2,0,a/2,l,f,0,f,s.height,d,u)):o.drawImage(r,0,0,a,l,0,0,s.width,s.height)}_bindTrackingEvents(){let e=this.session;!e||typeof e.addEventListener!="function"||this._trackingSupported&&e.addEventListener(fi,()=>{this._setTrackingState(nt(e)||"unknown")})}_setTrackingState(e){let t=Yn.includes(e)?e:"unknown";if(t===this._trackingState)return;this._trackingState=t,this._applyUntrackedTarget();let i={type:fi,state:t};this._emitDisplay(i,[t,i])}_applyUntrackedTarget(){if(this._untrackedFallback!=="mono"){this._bakedTarget=1;return}this._trackingState==="searching"?this._bakedTarget=0:this._trackingState==="tracking"&&(this._bakedTarget=1)}_trackBakedStereo(e){this._trackingSupported&&this._setTrackingState(nt(this.session)||"unknown");let t=this._bakedAt===null||!Number.isFinite(e)?0:Math.max(0,(e-this._bakedAt)/1e3);this._bakedAt=Number.isFinite(e)?e:this._bakedAt;let i=this._bakedStereo,r=this._bakedTarget;if(i===r)return;let s=this._bakedEaseS>0?t/this._bakedEaseS:1;this._bakedStereo=r>i?Math.min(r,i+s):Math.max(r,i-s)}_recommitLastFrame(e){let t=e.canvas;if(!t.width||!t.height)return;let i=e.ctx;try{i.save(),i.globalCompositeOperation="copy",i.drawImage(t,0,0),i.restore()}catch{}}_requestFrame(e){if(!this._running||this._framePending&&!e)return;let t=e?++this._loopId:this._loopId;this._framePending=!0;try{this.session.requestAnimationFrame((i,r)=>{t===this._loopId&&(this._framePending=!1,this._frameCount++,this._frame(i,r))})}catch{this._framePending=!1}}_frame(e,t){if(!this._running)return;this._requestFrame(),this._advanceModeSwitch();let i=this.refSpace?t.getViewerPose(this.refSpace):null,r=i?i.views:null;this._trackBakedStereo(e);for(let s of this._windows.values())if(s.layer){if(s.rc&&this._rectCoverCheck(s),s.kind==="scene"){if(r&&s.onFrame){if(s.frames++,r.length<2&&(s.monoFrames++,s.monoFrames%300===1&&typeof console<"u"&&console.debug)){let o=(100*s.monoFrames/Math.max(1,s.frames)).toFixed(1);console.debug(`[inline3d] scene window: ${s.monoFrames} non-stereo view lists in ${s.frames} frames (${o}%). The viewer replays its last good stereo frame for these; a rising rate means the session is falling back under load.`)}try{s.onFrame(r,s.layer,t),r.length>=2&&(s.fwStereo=!0,s.lfStereo=!0,s.warnedBufMismatch||this._checkSceneBuffer(s),s.rw&&(s.rw.stereo=!0))}catch(o){s.frameThrewWarned||(s.frameThrewWarned=!0,console.warn("[inline3d] a scene window's onFrame threw; this window will keep whatever it last drew, and the other windows carry on. Further throws from it are silent.",o))}}}else this._paint(s,r),s.sbs&&(s.kind==="video"?(s.video&&s.video.readyState||0)>=2:s.img)&&(s.fwStereo=!0,s.lfStereo=!0,s.rw&&(s.rw.stereo=!0));s.rc&&s.rc.snapWanted&&this._rectCoverSnap(s),(!s.layerFramed||s.framedWaiters.length)&&this._tickLayerFramed(s),this._tickFirstWoven(s)}}_tickFirstWoven(e){let t=e.wsLive&&e.layer?rt(e.layer):null;if(t){this._tickWovenState(e,t);return}if(e.rw){this._noteRewovenBox(e);let i=e.rw,r=H();i.stereo&&r-i.at>=e.fwHoldMs?this._settleRewoven(e,!0,"hold-elapsed"):i.at>i.calledAt&&r-i.calledAt>=ui*e.fwHoldMs&&this._settleRewoven(e,!0,"hold-capped")}e.fwResult||!e.fwStereo||e.fwLayerAt===null||H()-e.fwLayerAt<e.fwHoldMs||this._settleFirstWoven(e,!0,"hold-elapsed")}_tickWovenState(e,t){let i=H(),r=ui*Math.max(e.fwHoldMs,pi);if(e.rw){this._noteRewovenBox(e);let s=e.rw;t!=="woven"?s.gap=!0:s.stereo&&(s.gap||s.boxFrame!==null&&this._frameCount-s.boxFrame>=Hn||s.boxFrame===null&&this._frameCount-s.callFrame>=Hn)&&this._settleRewoven(e,!0,"woven",!0),e.rw&&i-s.calledAt>=r&&(t==="woven"?this._settleRewoven(e,!0,"hold-capped",!0):this._settleRewoven(e,!1,hi(e.layer)||t,!0))}e.fwResult||e.fwLayerAt===null||(e.fwStereo&&t==="woven"?this._settleFirstWoven(e,!0,"woven",!0):i-e.fwLayerAt>=r&&(t==="woven"?this._settleFirstWoven(e,!0,"hold-capped",!0):this._settleFirstWoven(e,!1,hi(e.layer)||t,!0)))}_noteWithheld(e,t,i,r){t||!r||e.warnedWithheld||!i||i==="pending"||i==="hold-capped"||(e.warnedWithheld=!0,console.warn(`[inline3d] the browser withheld this canvas from the weave (${i}): ${Tn(i)}.`,e.canvas))}_settleFirstWoven(e,t,i,r=!1){this._noteWithheld(e,t,i,r),!t&&!r&&(e.rwGone||(e.rwGone=i),this._settleRewoven(e,!1,i)),!e.fwResult&&(e.fwResult=Object.freeze({woven:t,confirmed:r,reason:i,ms:Math.round(H()-e.fwRegAt)}),e.fwResolve(e.fwResult),e.fwResolve=null)}_rewoven(e){if(!e.fwResult)return e.fwPromise;if(!e.fwResult.woven&&!e.fwResult.confirmed)return Promise.resolve(e.fwResult);if(e.rwGone)return Promise.resolve(Object.freeze({woven:!1,confirmed:!1,reason:e.rwGone,ms:0}));if(e.rw)return this._restartRewoven(e),e.rw.promise;let t,i=new Promise(s=>{t=s}),r=H();return e.rw={promise:i,resolve:t,calledAt:r,at:r,stereo:!1,box:di(e.canvas),gap:!1,boxFrame:null,callFrame:this._frameCount},i}_noteRewovenBox(e){let t=e.rw;if(!t)return;let i=di(e.canvas);i!==t.box&&(t.box=i,this._restartRewoven(e))}_restartRewoven(e){e.rw&&(e.rw.at=H(),e.rw.stereo=!1,e.rw.gap=!1,e.rw.boxFrame=this._frameCount)}_settleRewoven(e,t,i,r=!1){let s=e.rw;s&&(this._noteWithheld(e,t,i,r),e.rw=null,s.resolve(Object.freeze({woven:t,confirmed:r,reason:i,ms:Math.round(H()-s.calledAt)})))}_rectCoverCheck(e){let t=e.rc,i=di(e.canvas);if(i===t.box)return;let r=t.box===null,s=t.w,o=t.h;if(t.box=i,t.w=e.canvas.clientWidth||0,t.h=e.canvas.clientHeight||0,r)return;t.up&&this._placeCover(e);let a=e.fwResult;if(!a||e.rwGone||!(a.woven||a.confirmed))return;t.up||(t.snapped||(t.aspect=o>0?s/o:0),this._raiseCover(e)),t.cfg.snapshot&&!t.snapped&&t.w>0&&t.h>0&&(t.snapWanted=!0);let l;e.rw?(this._noteRewovenBox(e),l=e.rw.promise):(l=this._rewoven(e),e.rw&&(e.rw.boxFrame=this._frameCount)),t.waiting!==l&&(t.waiting=l,l.then(()=>{t.waiting===l&&(t.waiting=null,this._lowerCover(e))}))}_raiseCover(e){let t=e.rc;if(!t.el){if(typeof document>"u"||!document||typeof document.createElement!="function"||!e.canvas.parentElement)return;let i=document.createElement("canvas");i.setAttribute?.("aria-hidden","true"),i.dataset&&(i.dataset.inline3dCover="");let r=i.style;r.position="absolute",r.pointerEvents="none",r.margin="0",r.border="0",r.padding="0",r.background=t.cfg.color,r.display="none";try{let s=typeof getComputedStyle=="function"?getComputedStyle(e.canvas).zIndex:"auto";s&&s!=="auto"&&(r.zIndex=s)}catch{}t.el=i}this._placeCover(e),t.el.style.display="block",t.up=!0,this._fullTileWarned.add(t.el),this._applyExclusion(e,t.el)}_placeCover(e){let i=e.rc.el,r=e.canvas;if(!i)return;let s=r.parentElement;s&&(i.parentElement!==s||i.previousSibling!==r)&&s.insertBefore(i,r.nextSibling);let o=i.style;if(r.offsetParent)o.position="absolute",o.left=`${r.offsetLeft}px`,o.top=`${r.offsetTop}px`,o.width=`${r.offsetWidth}px`,o.height=`${r.offsetHeight}px`;else{let a=r.getBoundingClientRect();o.position="fixed",o.left=`${a.left??a.x??0}px`,o.top=`${a.top??a.y??0}px`,o.width=`${a.width}px`,o.height=`${a.height}px`}}_rectCoverSnap(e){let t=e.rc;t.snapWanted=!1;let i=t.el,r=e.canvas;if(!i||!t.up||!(r.width>1)||!(r.height>0))return;let s=Math.max(1,Math.round(t.w)),o=Math.max(1,Math.round(t.h)),a=s/o,l=t.aspect>0?t.aspect:r.width/2/r.height,c=1,h=1;a>l?h=l/a:c=a/l;let d=r.width/2*c,u=r.height*h,f=(r.width/2-d)/2,p=(r.height-u)/2;try{i.width=s,i.height=o;let m=i.getContext("2d");if(!m)return;m.drawImage(r,f,p,d,u,0,0,s,o),t.snapped=!0}catch{}}_lowerCover(e){let t=e.rc;t&&(t.up=!1,t.snapped=!1,t.snapWanted=!1,t.el&&(t.el.style.display="none",this._dropExclusion(e,t.el)))}_dropCover(e){let t=e.rc;t&&(t.waiting=null,this._lowerCover(e),t.el&&t.el.parentElement&&t.el.parentElement.removeChild(t.el),t.el=null)}_bindLifecycle(){typeof window>"u"||(this._onPageHide=()=>this._suspend(),this._onPageShow=e=>this._resume(!!(e&&e.persisted)),window.addEventListener("pagehide",this._onPageHide),window.addEventListener("pageshow",this._onPageShow),typeof document<"u"&&"onfreeze"in document&&(this._onFreeze=()=>this._suspend(),this._onResume=()=>this._resume(!0),document.addEventListener("freeze",this._onFreeze),document.addEventListener("resume",this._onResume)))}_unbindLifecycle(){typeof window>"u"||(this._onPageHide&&window.removeEventListener("pagehide",this._onPageHide),this._onPageShow&&window.removeEventListener("pageshow",this._onPageShow),this._onFreeze&&typeof document<"u"&&(document.removeEventListener("freeze",this._onFreeze),document.removeEventListener("resume",this._onResume)),this._onPageHide=this._onPageShow=this._onFreeze=this._onResume=null,this._frameWatchdog&&(clearTimeout(this._frameWatchdog),this._frameWatchdog=null))}_suspend(){if(!this._running||this._suspended)return;let e=[];for(let t of this._windows.values())t.layer&&(e.push(t),this._deactivate(t));this._suspended=e}_resume(e){if(!this._running)return;let t=this._suspended;if(this._suspended=null,t)for(let i of t)this._windows.has(i.canvas)&&(this._lazy&&this._observer?(this._observer.unobserve(i.observeEl),this._observer.observe(i.observeEl)):this._activate(i));this._lastChromeScan=0,this._scanChrome(),this._armDprWatch(),e&&this._watchForStalledFrames()}_watchForStalledFrames(){if(this._frameWatchdog||typeof setTimeout!="function")return;let e=this._frameCount;this._frameWatchdog=setTimeout(()=>{this._frameWatchdog=null,!(!this._running||this._frameCount!==e)&&this._requestFrame(!0)},1e3)}_teardown(){if(this._running){this._running=!1,Y===this&&(Y=null),this._unbindLifecycle(),this._disarmDprWatch(),this._disarmModeSwitchTick(),this._modeSwitch.cancel(),this._msArmedUp=!1,this._settlePendingDown("closed","the inline-3D session closed first"),this._observer&&this._observer.disconnect();for(let e of this._windows.values()){if(this._stopOverlayScan(e),this._stopSizeWatch(e),e.layer){try{e.layer.close()}catch{}e.layer=null}this._paintMono(e),this._notifyLayerLost(e),this._settleFirstWoven(e,!1,"session-ended"),this._dropCover(e),this._noteLayerFramed(e,!1)}this._windows.clear(),this._claims.clear(),this._setTrackingState("unknown"),this._displayListeners.clear()}}};function Do(n){return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:pi}function Lo(n){return typeof n!="string"?Promise.resolve(n):new Promise((e,t)=>{let i=new Image;i.decoding="async",i.onload=()=>e(i),i.onerror=t,i.src=n})}function st(n,e,t,i,r,s,o,a,l,c,h,d){h>0&&n.roundRect?(n.save(),n.beginPath(),n.roundRect(o,a,l,c,h),n.clip(),n.drawImage(e,t,i,r,s,o,a,l,c),n.restore()):n.drawImage(e,t,i,r,s,o,a,l,c),d>0&&Qn(n,o,a,l,c,d)}function Io(n,e,t,i,r,s,o,a,l){n.save(),a>0&&n.roundRect&&(n.beginPath(),n.roundRect(r,0,r,s,a),n.clip()),n.drawImage(e,0,0,t,i,r,0,r,s),o>0&&(n.globalAlpha=o,n.drawImage(e,t,0,t,i,r,0,r,s)),n.restore(),l>0&&Qn(n,r,0,r,s,l)}function Qn(n,e,t,i,r,s){let o=Math.min(s,Math.floor(Math.min(i,r)/2));if(o<=0)return;n.save(),n.globalCompositeOperation="destination-out";let a=[[e,t,i,o,[e,t],[e,t+o]],[e,t+r-o,i,o,[e,t+r],[e,t+r-o]],[e,t,o,r,[e,t],[e+o,t]],[e+i-o,t,o,r,[e+i,t],[e+i-o,t]]];for(let[l,c,h,d,u,f]of a){let p=n.createLinearGradient(u[0],u[1],f[0],f[1]);p.addColorStop(0,"rgba(0,0,0,1)"),p.addColorStop(1,"rgba(0,0,0,0)"),n.fillStyle=p,n.fillRect(l,c,h,d)}n.restore()}function _i(n,e){return n>0&&e>0&&n/e>2.5}function G(n,e,t,i,r){let s=Math.abs(i||0),o=Math.min(n-2*s,e*t);o=Math.max(1,o);let a=Math.min(e,o/t);o=a*t;let l=(n-o)/2+(r===0?i:-i);return{sx:Math.max(0,Math.min(n-o,l)),sy:(e-a)/2,sw:o,sh:a}}function je(n,e,t){let i=Math.min(n,e*t),r=i/t;return{w:Math.max(2,Math.round(i/2)*2),h:Math.max(2,Math.round(r/2)*2)}}function me(n,e){let t=n/2;return[{src:"R",sx:t,sw:t,sy:0,sh:e,dx:0,dw:t,mirror:!0},{src:"L",sx:0,sw:t,sy:0,sh:e,dx:t,dw:t,mirror:!0}]}function vi(n,e,t){let i=new n.constructor(n.length);for(let r of me(e,t))for(let s=0;s<t;s++)for(let o=0;o<r.dw;o++){let a=r.sx+(r.sw-1-o);i[s*e+r.dx+o]=n[s*e+a]}return i}function er(n,e){return!(n>0)||!(e>0)||e>=180?null:n/2/Math.tan(e/2*Math.PI/180)}function at({eyeWidthPx:n,hfovDeg:e,baselineMm:t,subjectZmm:i}){let r=er(n,e);return r===null||!(t>0)||!(i>0)?0:r*t/(2*i)}function lt(n,e,t=.2){let i=Math.max(0,e*t);return Math.max(-i,Math.min(i,n||0))}function ct(n,e,t=.2){let i=n+t*(e-n);return Math.abs(e-i)<.05?e:i}function ze(){let n={hello:null,subjectZmm:null,measuredPx:null,depth:0,current:0,target(e){let t=n.measuredPx!==null?n.measuredPx/2:n.hello&&n.subjectZmm?at({eyeWidthPx:e,hfovDeg:n.hello.hfovDeg,baselineMm:n.hello.baselineMm,subjectZmm:n.subjectZmm}):0;return lt(t+n.depth*.05*e,e)},step(e){return n.current=ct(n.current,n.target(e)),n.current}};return n}var ht=1,wi="inline3d-call/1",ir=Object.freeze(["sbs","mono"]),ge=4,nr=4,bi=5,rr=5,sr=10,or=400,ar=1200,yi=.5,Fo=16*1024,lr=20,cr=40,tr=64,No=150,jo=5e3,zo=/^[A-Za-z0-9_-]{16,64}$/,Wo=16;function xi(n){let e=new Uint8Array(Wo);return(n||(i=>globalThis.crypto.getRandomValues(i)))(e),ur(e)}function hr(n){let e=new Uint8Array(8);return(n||(i=>globalThis.crypto.getRandomValues(i)))(e),ur(e)}function ur(n){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",t="",i=0;for(;i+2<n.length;i+=3){let s=n[i]<<16|n[i+1]<<8|n[i+2];t+=e[s>>18&63]+e[s>>12&63]+e[s>>6&63]+e[s&63]}let r=n.length-i;if(r===1){let s=n[i]<<16;t+=e[s>>18&63]+e[s>>12&63]}else if(r===2){let s=n[i]<<16|n[i+1]<<8;t+=e[s>>18&63]+e[s>>12&63]+e[s>>6&63]}return t}function _e(n){return typeof n=="string"&&zo.test(n)}function We(n){if(!n)return null;let e="";if(typeof n=="object")e=n.hash||n.href&&String(n.href).split("#")[1]||"";else{let t=String(n),i=t.indexOf("#");e=i>=0?t.slice(i+1):t.includes("=")&&!t.includes("://")?t:""}e=e.replace(/^#/,"");for(let t of e.split("&")){let i=t.indexOf("=");if(i<0||decodeURIComponent(t.slice(0,i))!=="room")continue;let r=decodeURIComponent(t.slice(i+1));return _e(r)?r:null}return null}function ut(n,e){if(!_e(e))throw new Error(`@displayxr/inline3d/call: invalid room id "${e}"`);return`${String(n||"").split("#")[0]}#room=${e}`}function Si(n){if(!n||typeof n!="object"||n.type!=="hello")return null;let e=(t,i,r)=>typeof t=="number"&&Number.isFinite(t)&&t>=i&&t<=r?t:null;return{type:"hello",v:typeof n.v=="number"?n.v:ht,format:ir.includes(n.format)?n.format:"mono",width:e(n.width,1,16384),height:e(n.height,1,16384),baselineMm:e(n.baselineMm,1,1e3),hfovDeg:e(n.hfovDeg,5,170),rectified:n.rectified===!0,sdk:typeof n.sdk=="string"?n.sdk.slice(0,64):null,conv:n.conv===!0,name:ve(n.name)}}function ve(n){if(typeof n!="string")return null;let e=n.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g," ").replace(/\s+/g," ").trim();if(!e)return null;let t=Array.from(e);return t.length>tr?t.slice(0,tr).join("").trim():e}function Mi({format:n,width:e,height:t,baselineMm:i,hfovDeg:r,rectified:s,conv:o,name:a}={}){let l={type:"hello",v:ht,format:ir.includes(n)?n:"mono",width:e||0,height:t||0,rectified:!!s,sdk:wi};Number.isFinite(i)&&(l.baselineMm=i),Number.isFinite(r)&&(l.hfovDeg=r),l.format==="sbs"&&o&&(l.conv=!0);let c=ve(a);return c&&(l.name=c),l}function Ei(n){if(n===void 0||typeof n=="function")return null;let e;try{e=JSON.stringify({type:"app",d:n})}catch{return null}if(typeof e!="string")return null;let t=Ho(e);return t>Fo?null:{json:e,bytes:t}}function dr(n){return!n||typeof n!="object"||n.type!=="app"||!("d"in n)?null:{data:n.d}}function Ho(n){if(typeof TextEncoder=="function")return new TextEncoder().encode(n).length;let e=0;for(let t of n){let i=t.codePointAt(0);e+=i<128?1:i<2048?2:i<65536?3:4}return e}function Ci(n,e=1e3){let t=[];return i=>{for(;t.length&&i-t[0]>=e;)t.shift();return t.length>=n?!1:(t.push(i),!0)}}function fr(n,e){let t={type:"conv",d:typeof n=="number"&&Number.isFinite(n)?Math.max(-yi,Math.min(yi,n)):null};return typeof e=="number"&&Number.isFinite(e)&&(t.c=Math.max(0,Math.min(1,e))),t}function pr(n){if(!n||typeof n!="object"||n.type!=="conv")return null;let e=n.d;if(e!==null&&!(typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=yi))return null;let t={type:"conv",d:e};return typeof n.c=="number"&&Number.isFinite(n.c)&&(t.c=Math.max(0,Math.min(1,n.c))),t}function Ri(n){if(!n||n.type!=="hint")return null;let e=n.subjectZmm;return typeof e=="number"&&Number.isFinite(e)&&e>=No&&e<=jo?{type:"hint",subjectZmm:e}:null}function mr(n){return!n||n.type!=="state"?null:{type:"state",muted:n.muted===!0,cameraOff:n.cameraOff===!0,speaking:n.speaking===!0}}function He(n,e=0){let t=1e3/n-Math.max(0,e),i=-1/0;return r=>r-i<t?!1:(i=r,!0)}function gr(n){let e=[];n.forEach(h=>e.push(h));let t=h=>(h&&typeof n.get=="function"?n.get(h):e.find(d=>d.id===h))||null,i=e.find(h=>h.type==="transport"&&h.selectedCandidatePairId),r=i&&t(i.selectedCandidatePairId)||e.find(h=>h.type==="candidate-pair"&&h.selected)||e.find(h=>h.type==="candidate-pair"&&h.nominated&&h.state==="succeeded");if(!r)return{path:null,rttMs:null};let s=t(r.localCandidateId),o=t(r.remoteCandidateId),a=s?s.candidateType:null,l=a==="relay"||o&&o.candidateType==="relay"?"relay":["host","srflx","prflx"].includes(a)?a:null,c=typeof r.currentRoundTripTime=="number"?Math.round(r.currentRoundTripTime*1e3):null;return{path:l,rttMs:c}}function ki({format:n,woven:e,mono3D:t="auto",lift:i=!1,overBudget:r=!1,failed:s=!1}){return(n==="sbs"?"sbs":"mono")==="sbs"?{route:e?"woven-sbs":"flat-left"}:e?t==="off"||t===!1?{route:"flat",mono3d:"off"}:i?s?{route:"flat",mono3d:"failed"}:r?{route:"flat",mono3d:"budget"}:{route:"lifted",mono3d:"lifted"}:{route:"flat",mono3d:"unavailable"}:{route:"flat"}}function Ti(n){return n==="woven-sbs"?"3D":n==="lifted"?"2D\u21923D":"2D"}function Oi({need:n=10,needNoPose:e=30}={}){let t=0,i=0,r=!1;return{feed(s){return r?!0:(i++,s===null?r=i>=e:(t=s>=1?t+1:0,r=t>=n),r)},get live(){return r}}}function dt(n,e){let t=Math.max(1,e|0),r=n==="sbs"?[6e3,4e3,3e3]:[2500,1800,1400];return r[Math.min(t,r.length)-1]}function K(n,{baseMs:e=1e3,maxMs:t=3e4,rand:i=Math.random}={}){let r=Math.min(t,e*Math.pow(2,Math.max(0,n)));return Math.round(r*(.8+.4*i()))}var $e=Object.freeze(["VP9","VP8","AV1"]);function Uo(n,e=$e){let t=e.indexOf(String(n||"").toUpperCase());return t<0?e.length:t}function ft(n,e=$e){let t=i=>Uo(String(i.mimeType||"").split("/")[1],e);return n.map((i,r)=>({c:i,i:r,r:t(i)})).sort((i,r)=>i.r-r.r||i.i-r.i).map(i=>i.c)}function Ue(n,e=$e){if(!n)return n;let t=n.includes(`\r
16
+ `})});var fi={};fo(fi,{PAIR_CURSOR_ARROW:()=>Va,PAIR_CURSOR_CSS_PX:()=>Ua,PAIR_CURSOR_CSS_PX_M:()=>Es,PAIR_CURSOR_HEIGHT:()=>Ms,PAIR_SUPPORT_COPY_PX:()=>Rs,PairCursor:()=>di,consistentMatch:()=>ui,drawPairArrow:()=>Ds,drawPairArrowSoft:()=>Ls,drawPairImage:()=>Is,pairCursorScale:()=>Ts,pairCursorTarget:()=>Xa,pairFootprintDisparity:()=>Cs,pairNearestSupported:()=>ks,pairPxPerBaseline:()=>As});function Cs(i,e,t,n,r,s){if(!i||!i.img||!e||!e.rL||!e.rR||!(e.outW>0))return null;let{img:o,w:a,h:l,scale:c}=i,h=a/2,u=Math.max(8,Math.round(h/20)),d=Math.round(h*.3),p=-Math.round(h*.05),{rL:f,rR:g}=e,x=e.outW/f.sw,b=Ba(i),w=[],M=new Set,S=(v,m)=>{let _=Math.round((f.sy+m*f.sh)*c-u/2);if(_<0||_+u>l)return;let y=Math.round((f.sx+v*f.sw)*c-u/2),C=Math.round((g.sx+v*g.sw)*c-u/2);if(!M.has(`L${y},${_}`)){M.add(`L${y},${_}`);let I=ui(o,b,a,l,y,_,u,p,d);I!==null&&w.push({d:I,x:y,y:_,eye:0})}if(!M.has(`R${C},${_}`)){M.add(`R${C},${_}`);let I=ui(b,o,a,l,C,_,u,-d,-p);I!==null&&w.push({d:-I,x:C,y:_,eye:1})}},k=0,R=0,E=0;for(let[v,m]of ws(t,n,r,s))v>=0&&v<=1&&m>=0&&m<=1&&(S(e.mirror?1-v:v,m),k+=v,R+=m,E++);if(!E)return null;let D=u/2/c/f.sw,O=u/2/c/f.sh;for(let[v,m]of[[-D,0],[D,0],[0,-O],[0,O]]){let _=k/E+v,y=R/E+m;_>=0&&_<=1&&y>=0&&y<=1&&S(e.mirror?1-_:_,y)}for(let v of w)v.d=(v.d/c-(f.sx-g.sx))*x;return ks(w,Rs/c*x,u/2)}function Ba(i){let e=Ss.get(i);if(e)return e;let{img:t,w:n,h:r}=i,s=n/2;e=new Uint8Array(n*r);for(let o=0;o<r;o++){let a=o*n;for(let l=0;l<s;l++)e[a+l]=t[a+s+l],e[a+s+l]=t[a+l]}return Ss.set(i,e),e}function ui(i,e,t,n,r,s,o,a,l){let c=t/2;if(r<0||r+o>c)return null;let h=be(i,t,n,r,s,o,o,{dMin:a,dMax:l,dyMax:2});if(!h||h.c<.8)return null;let u=Math.round(r-h.d),d=s+h.dy;if(u<0||u+o>c||d<0||d+o>n)return null;let p=be(e,t,n,u,d,o,o,{dMin:-Math.ceil(h.d)-2,dMax:-Math.floor(h.d)+2,dyMax:1});return!p||p.c<.8||Math.abs(-p.d-h.d)>1?null:h.d}function ks(i,e,t=0){let n=i.map(o=>typeof o=="number"?{d:o,x:0,y:0,eye:-1}:o);if(n.length<2)return null;let r=[...n].sort((o,a)=>a.d-o.d),s=(o,a)=>o.eye===-1||o.eye!==a.eye||Math.abs(o.x-a.x)+Math.abs(o.y-a.y)>=t;for(let o of r)for(let a of r)if(a!==o&&Math.abs(o.d-a.d)<=e&&s(o,a))return o.d;return null}function Ts(i,e,t){let n=t>0&&Number.isFinite(t)?t:Es;return e>0?i/e/n:i/(1e3*n)}function As(i,e,t,n=st.eyeSeparationM){return Ts(i,e,t)*n}function Xa(i,e,t=Bt){return i===null||!Number.isFinite(i)||!(e>0)?0:-hi(t,!0,-i/e)*e||0}function Os(i,e){let t=e>0?Math.max(.05263157894736842,1/e):.05263157894736842,n=`${i}:${Math.round(t*1e4)}`,r=Xt.get(n);return r||(Xt.size>64&&Xt.clear(),Xt.set(n,r=Oe(i,t))),r}function Ds(i,e,t,n,r,s,o,a="arrow"){let l=r*t,c=Os(a,o);for(let h of[0,1]){let u=h*e+n*e+(h===0?s/2:-s/2);i.save(),i.beginPath(),i.rect(h*e,0,e,t),i.clip(),ti(i,a,u,l,o,c),i.restore()}}function Ps(i,e){if(!G||typeof OffscreenCanvas=="function"&&!(G instanceof OffscreenCanvas))try{typeof OffscreenCanvas=="function"?G=new OffscreenCanvas(1,1):globalThis.document&&document.createElement&&(G=document.createElement("canvas"))}catch{G=null}return!G||typeof G.getContext!="function"?null:(G.width<i&&(G.width=i),G.height<e&&(G.height=e),G.getContext("2d"))}function Ls(i,e,t,n,r,s,o,a,l,c="arrow"){let h=r*t,u=Os(c,o),d=[0,1].map(f=>{let g=f*e+n*e+(f===0?s/2:-s/2);return ei(c,g,h,o,a,l,[1,1,1,1],[0,0,0,1],u)}),p=Ps(Math.max(d[0].width,d[1].width),Math.max(d[0].height,d[1].height));if(!p||typeof p.putImageData!="function"||typeof ImageData!="function")return!1;for(let f of[0,1]){let g=d[f];p.putImageData(new ImageData(g.data,g.width,g.height),0,0),i.save(),i.beginPath(),i.rect(f*e,0,e,t),i.clip(),i.drawImage(p.canvas,0,0,g.width,g.height,g.x0,g.y0,g.width,g.height),i.restore()}return!0}function Is(i,e,t,n,r,s,o,a,l,c){let h=o/19,u=Math.max(1,Math.round(a.width*h)),d=Math.max(1,Math.round(a.height*h)),p=Ps(u+2*(Math.ceil(l)+2),d+2*(Math.ceil(l)+2));if(!p||typeof p.getImageData!="function"||typeof ImageData!="function")return!1;p.clearRect(0,0,p.canvas.width,p.canvas.height),p.drawImage(a.entry.image,0,0,u,d);let f=ni(p.getImageData(0,0,u,d).data,u,d,l,c);p.clearRect(0,0,p.canvas.width,p.canvas.height),p.putImageData(new ImageData(f.data,f.width,f.height),0,0);let g=r*t-a.hotspot[1]*h-f.pad;for(let x of[0,1]){let b=x*e+n*e+(x===0?s/2:-s/2)-a.hotspot[0]*h-f.pad;i.save(),i.beginPath(),i.rect(x*e,0,e,t),i.clip(),i.drawImage(p.canvas,0,0,f.width,f.height,Math.round(b),Math.round(g),f.width,f.height),i.restore()}return!0}var Ua,Ms,Va,Es,Rs,Ss,Xt,G,di,pi=fe(()=>{"use strict";oi();an();Ct();Ua=ci,Ms=.06,Va=ie,Es=.0254/96;Rs=1.5,Ss=new WeakMap;Xt=new Map;G=null;di=class{constructor(e,{height:t,pointerScope:n="window",soften:r,shape:s="auto",shapeFor:o=null}={}){this.pointer=new Ut(e,{scope:n}),this.shapes=new Qe(this.pointer,{shape:s,shapeFor:o}),this.soften=Ot(r,"@displayxr/inline3d pair cursor"),this.height=t>0?t:null,this.filter={},this._luma=null,this._uv=null,this._content=null,this._metricsFor=null,this.metersPerCssPx=null,this.eyeSeparationM=st.eyeSeparationM,this.last=null,this.runtime=new Vt}get hovering(){return!!this.pointer.uv}draw(e,t,n,r){let s=this.runtime.bind(n&&n.handle),o=this.pointer.uv;if(!o)return this.idle();let[a,l]=o,c=this.height??this._osArrowFraction();(t!==this._luma||!this._uv||this._uv[0]!==a||this._uv[1]!==l)&&(this._content=Cs(t,n,a,l,c,n.outW/n.outH),this._luma=t,this._uv=o);let h=this.pointer.canvas.getBoundingClientRect?.();if(s)return this._drawRuntime(a,l,h,n);this._askMetrics(n.handle);let u=As(n.outW,h&&h.width,this.metersPerCssPx,this.eyeSeparationM),d=this._content===null?null:-this._content/u,p=hi(Bt,d!==null,d),f=ys(this.filter,Bt,p,r),g=vs(f,u),x=-f*u,b=null,w=null;if(g){let M=c*n.outH,S=globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1,k=h&&h.width>0?h.width*S/n.outW:1,R=h&&h.height>0?c*h.height*S:M,E=bs(f,x*k,R,this.soften),D=this.shapes.pick({u:a,v:l,point:null},r*1e3);w=this.shapes.current,b={blurPx:E.blurPx,alpha:E.alpha,ghostPx:Math.abs(x*k),spritePx:R,radius:R>0?E.blurPx/R:0,soft:E.blurPx>0||E.alpha<1},D.kind==="image"?Is(e,n.outW,n.outH,a,l,x,M,D,b.soft?b.radius*M:0,b.soft?E.alpha:1):D.kind==="shape"&&(!b.soft||!Ls(e,n.outW,n.outH,a,l,x,M,b.radius,E.alpha,w))&&Ds(e,n.outW,n.outH,a,l,x,M,w)}return this.pointer.hideCss(g),this.last={contentPx:this._content,targetPx:-p*u||0,disparityPx:g?x:0,filteredPx:x||0,drawn:g,pxPerBaseline:u,soften:b,shape:w},this.last}_drawRuntime(e,t,n,r){this.pointer.hideCss(!1),this.filter={};let s=globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1,o=n&&n.width>0&&r.outW>0?n.width*s/r.outW:null,a=this._content===null||o===null?null:-this._content*o;return this.runtime.report(e,t,a),this.last={contentPx:this._content,targetPx:0,disparityPx:0,filteredPx:0,drawn:!1,runtime:!0,runtimeDisparityPx:a,pxPerBaseline:null,soften:null,shape:null},this.last}_askMetrics(e){!e||e===this._metricsFor||typeof e.displayMetrics!="function"||(this._metricsFor=e,Promise.resolve().then(()=>e.displayMetrics()).then(t=>{this._metricsFor!==e||!t||(t.metersPerCssPx>0&&(this.metersPerCssPx=t.metersPerCssPx),t.eyeSeparationM>0&&(this.eyeSeparationM=t.eyeSeparationM))}).catch(()=>{}))}_osArrowFraction(){let e=this.pointer.canvas.getBoundingClientRect?.();return e&&e.height>0?_s(e.height):Ms}idle(){return this.runtime.withdraw(),this.pointer.hideCss(!1),this.filter={},this._uv=null,this.last=null,null}dispose(){this.runtime.dispose(),this.pointer.dispose(),this.shapes.dispose()}}});var Fe=Object.freeze({speaker:"high",other:"normal",hidden:"paused"}),po=["high","normal","low","paused"],mo=.02,go=1e3/20,_o=3e3,vo=1e3/28;function je(i){return typeof i=="function"?i:i===!1||i==="off"?"off":"auto"}function tn(i=import.meta.url){return Ie?typeof Ie=="function"?Ie():Ie:new URL("../lift/index.js",i).href}var Ie=null;function Pi(i){Ie=i||null}function yo(){return import(tn())}async function nn(i,{importer:e=yo,nav:t=globalThis.navigator,log:n=null,capsOpts:r={webFallback:!0}}={}){let s=(d,p)=>n&&n(d,p),o=(d,p={})=>(s("lift-unavailable",{reason:d,...p}),{lift:null,capabilities:null,caps:null,source:"none",reason:d}),a=je(i);if(a==="off")return{lift:null,capabilities:null,caps:null,source:"none",reason:"off"};if(typeof a=="function"){let d=typeof a.liftCapabilities=="function"?a.liftCapabilities:null;return{lift:a,capabilities:d,caps:null,source:"injected",reason:null}}let l;try{l=await e()}catch(d){return o("import-failed",{message:String(d&&d.message||d).slice(0,200)})}let c=l&&typeof l.lift=="function"?l.lift:null;if(!c)return o("no-lift-export");let h=typeof l.liftCapabilities=="function"?l.liftCapabilities:null,u=null;if(h){try{u=await h(r)}catch{u=null}let d=!!(u&&u.webFallback&&u.webFallback.webgpu);if(u&&!u.native&&!d)return o("no-provider",{native:!1,webgpu:!1})}else if(!(t&&t.gpu))return o("no-webgpu");return s("lift-ready",{native:!!(u&&u.native),provider:u&&u.provider||null}),{lift:c,capabilities:h,caps:u,source:"module",reason:null}}function Ne(i){let e=Number.isFinite(+i)&&i!==null?Math.max(-1,Math.min(1,+i)):0;return Math.abs(e)<mo?"auto":Math.round((.5+.5*e)*1e3)/1e3}function rt({id:i,speakerId:e,visible:t=!0}){return t?i!=null&&i===e?Fe.speaker:Fe.other:Fe.hidden}function rn(i,e){if(!i||!po.includes(e)||typeof i.setPriority!="function")return!1;try{return i.setPriority(e)!==!1}catch{return!1}}function sn({degradedMs:i=go,recoveredMs:e=vo,holdMs:t=_o,alpha:n=.1}={}){let r=null,s=0,o=!1;return{feed(a){if(!(a>0)||a>1e3)return null;if(r=r===null?a:r+n*(a-r),o){if(r<e)return o=!1,s=0,"recovered"}else if(s=r>i?s+a:0,s>=t)return o=!0,"degraded";return null},reset(){r=null,s=0,o=!1},get frameMs(){return r},get degraded(){return o}}}function on({lift:i,max:e=4,log:t=null,options:n=null}={}){let r=n&&typeof n=="object"?n:{},s=new Map,o=null,a=0,l=0,c=(d,p)=>t&&t(d,p),h=(d,p)=>{if(!p.handle)return;let f=rt({id:d,speakerId:o,visible:p.visible});if(f===p.priority)return;p.priority=f;let g=rn(p.handle,f);c("lift-priority",{peer:d,priority:f,applied:g})},u={get size(){return s.size},get max(){return e},set max(d){e=Math.max(0,d|0)},has:d=>s.has(d),handle:d=>s.get(d)&&s.get(d).handle||null,priority:d=>s.get(d)&&s.get(d).priority||null,canAcquire:d=>s.has(d)||s.size<e,acquire(d,p,{wall:f,visible:g=!0,onError:x}={}){let b=s.get(d);if(b)return b.pending||Promise.resolve(b.handle);if(s.size>=e)return Promise.resolve(null);let w=++l,M=rt({id:d,speakerId:o,visible:g}),S={gen:w,handle:null,visible:g,priority:M,pending:null};s.set(d,S);let k={quality:"auto",...r,mode:"live",wall:f,ui:"none",convergence:Ne(a),priority:M};return c("lift-acquire",{peer:d,priority:M,convergence:k.convergence}),S.pending=Promise.resolve().then(()=>i(p,k)).then(R=>{if(s.get(d)!==S||S.gen!==w){try{R&&R.remove&&R.remove()}catch{}return null}return S.pending=null,S.handle=R||null,S.priority=null,h(d,S),R&&typeof R.setConvergence=="function"&&R.setConvergence(Ne(a)),S.handle},R=>(s.get(d)===S&&s.delete(d),c("lift-failed",{peer:d,message:String(R&&R.message||R).slice(0,200)}),x&&x(R),null)),S.pending},release(d){let p=s.get(d);if(p){if(s.delete(d),p.handle)try{p.handle.remove()}catch{}c("lift-release",{peer:d})}},releaseAll(){for(let d of[...s.keys()])u.release(d)},setSpeaker(d){o=d===void 0?null:d;for(let[p,f]of s)h(p,f)},setVisible(d,p){let f=s.get(d);!f||f.visible===!!p||(f.visible=!!p,h(d,f))},setDepth(d){a=d;let p=Ne(d);for(let f of s.values())f.handle&&typeof f.handle.setConvergence=="function"&&f.handle.setConvergence(p);return p},get anyWeb(){for(let d of s.values())if(d.handle&&!d.handle.native)return!0;return!1},list(){return[...s].map(([d,p])=>({id:d,priority:p.priority,pending:!!p.pending,native:!!(p.handle&&p.handle.native)}))}};return u}var bo=null;function Li(i){bo=typeof i=="function"?i:null}var xo=new WeakMap;function Ii(i,e){i&&(typeof i=="object"||typeof i=="function")&&xo.set(i,e)}an();var Al=Object.freeze(["shibata","percival"]);var So="[inline3d] camera rig with convergenceDiopters 0: convergence at infinity puts the whole scene in front of the glass; set convergence to the subject's distance.",Mo=new WeakSet;function Eo(i){let e=[];return!i||typeof i!="object"||(i.type==="camera"?(i.convergenceDiopters>0||e.push(["convergence",So]),i.verticalFov>Math.PI&&e.push(["fov",`[inline3d] camera rig verticalFov ${i.verticalFov} is more than \u03C0: it looks like DEGREES \u2014 the descriptor takes RADIANS (cameraRigFromCamera / cameraRigFromPose convert three's degrees for you).`])):(i.ipdFactor>1||i.parallaxFactor>1)&&e.push(["factor",`[inline3d] display rig ipdFactor ${i.ipdFactor??1} / parallaxFactor ${i.parallaxFactor??1}: above 1 exaggerates depth past what the display shows by construction (1 = correct; below 1 = a comfort dial). Sent as given.`])),e}function ln(i,e){if(!(!e||typeof e!="object")&&!(e.type==="camera"?e.convergenceDiopters>0&&!(e.verticalFov>Math.PI):!(e.ipdFactor>1||e.parallaxFactor>1)))for(let[t,n]of Eo(e))i.has(t)||(i.add(t),!(t==="convergence"&&Mo.has(e))&&console.warn(n))}function Ni(i){let e=String(i||"");return e.startsWith("cross-pass")?"the canvas is inside its own render surface: a CSS effect on it or an ancestor (filter, opacity < 1, mask, clip-path, mix-blend-mode, backdrop-filter). Remove it (woven-canvas rule 7)":e==="no-quad"?"the canvas drew nothing the compositor can see: it is not drawing, is occluded, or a CSS effect on it or an ancestor (filter, opacity < 1, mask, clip-path, mix-blend-mode, backdrop-filter) hides it (woven-canvas rule 7)":e==="no-identity"?"the canvas reached the browser without its identity: register it once, keep it mounted, cover it until firstWoven (woven-canvas rules 3-5)":e==="no-join"?"nothing joined this rect; harmless off screen, otherwise check the canvas is drawing and on screen":e==="resolve-dropped"?"the browser could not resolve the canvas's GPU resource (a browser-side issue)":"see docs/woven-canvas-rules.md \xA73"}var ji=new WeakMap,te;function zi(i){let e=null;for(let[t,n]of i)n>0&&(!e||n<e[1])&&(e=[t,n]);return e}function Co(i){if(!i||typeof i.getParameter!="function")return null;let e=ji.get(i);if(e)return e;let t,n,r;try{t=i.getParameter(i.MAX_TEXTURE_SIZE??3379),n=i.getParameter(i.MAX_RENDERBUFFER_SIZE??34024),r=i.getParameter(i.MAX_VIEWPORT_DIMS??3386)}catch{return null}let s=r&&r.length>=2?r[0]:0,o=r&&r.length>=2?r[1]:0,a=zi([["MAX_TEXTURE_SIZE",t],["MAX_RENDERBUFFER_SIZE",n],["MAX_VIEWPORT_DIMS",s]]),l=zi([["MAX_TEXTURE_SIZE",t],["MAX_RENDERBUFFER_SIZE",n],["MAX_VIEWPORT_DIMS",o]]);if(!a||!l)return null;let c={maxW:a[1],maxH:l[1],nameW:a[0],nameH:l[0],valueW:a[1],valueH:l[1]};return ji.set(i,c),c}function Wi(){if(te!==void 0)return te;te=null;try{if(typeof document>"u"||!document||typeof document.createElement!="function")return te;let i=document.createElement("canvas"),e=i.getContext("webgl2")||i.getContext("webgl");if(!e)return te;te=Co(e),e.getExtension?.("WEBGL_lose_context")?.loseContext?.()}catch{te=null}return te}function Hi(i,e,t,{cols:n=2,rows:r=1}={}){let s=i*n,o=e*r,a={eyeW:i,eyeH:e,cols:n,scale:1,clamped:!1,reqW:s,reqH:o,bufW:s,bufH:o,limitName:"",limitValue:0};if(!t||!(i>0)||!(e>0))return a;let l=t.maxW/s,c=t.maxH/o,h=Math.min(l,c);if(!(h<1))return a;let u=l<=c,d=Math.max(1,Math.min(Math.floor(i*h+1e-9),Math.floor(t.maxW/n))),p=Math.max(1,Math.min(Math.floor(e*h+1e-9),Math.floor(t.maxH/r)));return{eyeW:d,eyeH:p,cols:n,scale:h,clamped:!0,reqW:s,reqH:o,bufW:d*n,bufH:p*r,limitName:u?t.nameW:t.nameH,limitValue:u?t.valueW:t.valueH}}function cn(i){return Math.round(i*1e3)/1e3}function $i(i,e,t){let n=typeof t=="number"?` (renderScale ${cn(t)} \u2192 ${cn(t*e.scale)})`:` (scale ${cn(e.scale)})`;return`${i} ${e.cols===1?"buffer":"SBS buffer"} ${e.reqW}\xD7${e.reqH} exceeds ${e.limitName} ${e.limitValue} on this device; rendering at ${e.bufW}\xD7${e.bufH}${n}.`}function Ui(i,e){let t=i?.width||0,n=i?.height||0,r=e&&e.drawingBufferWidth>0?e.drawingBufferWidth:t,s=e&&e.drawingBufferHeight>0?e.drawingBufferHeight:n,o=t>0?r/t:1,a=n>0?s/n:1;return{sx:o,sy:a,w:r,h:s,mismatch:o!==1||a!==1}}function Vi(i,e,t,n="laying the eyes out from the drawing buffer. Lower renderScale to stay inside the device limit."){return`${i} the browser clamped this canvas's drawing buffer to ${t.w}\xD7${t.h} (canvas.width/height say ${e.width}\xD7${e.height}); ${n}`}var me="smoothstep",un=["linear","smoothstep","easeoutcubic"];function dn(i){if(typeof i!="string")return null;let e=i.toLowerCase().replace(/[-_\s]/g,"");return un.includes(e)?e:null}function Ro(i,e){if(e<=0)return 0;if(e>=1)return 1;if(i==="linear")return e;if(i==="easeoutcubic"){let t=1-e;return 1-t*t*t}return e*e*(3-2*e)}var pe="idle",Bi="rampDownThenFire",hn="fireThenRampUp",ot=class{constructor(e,t){this._phase=pe,this._targetMode=null,this._firePending=!1,this._fireAtEnd=!1,this._from=0,this._to=0,this._cur=0,this._t=1,this._dur=180/1e3,this._easing=me,(e!==void 0||t!==void 0)&&this.configure(e,t)}configure(e,t){if(e!==void 0){let n=Number(e);this._dur=Number.isFinite(n)&&n>0?n:0}return t!==void 0&&(this._easing=dn(t)||me),this}get durationS(){return this._dur}get easing(){return this._easing}request({targetMode:e=null,targetViewCount:t,currentMode:n=null,currentViewCount:r,current:s,steady:o=1}={}){let a=!(t>1),l=!(r>1),c=Number.isFinite(o)?o:1,h=Number.isFinite(s)?s:c;return this._targetMode=e,this._from=h,a&&!l?(this._phase=Bi,this._to=0,this._fireAtEnd=!0,this._firePending=!1):!a&&l?(this._phase=hn,this._from=0,this._to=c,this._firePending=!0,this._fireAtEnd=!1):(this._phase=hn,this._to=a?h:c,this._firePending=!(e!==null&&e===n),this._fireAtEnd=!1),this._t=this._dur>0?0:1,this._cur=this._from,this}update(e){let t=!1;if(this._phase!==pe){let n=Number.isFinite(e)&&e>0?e:0;this._t<1&&this._dur>0?(this._t+=n/this._dur,this._t>1&&(this._t=1)):this._t=1,this._cur=this._from+(this._to-this._from)*Ro(this._easing,this._t),this._phase===hn?(this._firePending&&(this._firePending=!1,t=!0),this._t>=1&&(this._phase=pe)):this._t>=1&&(this._fireAtEnd&&(this._fireAtEnd=!1,t=!0),this._phase=pe)}return{factor:this._cur,fire:t,mode:this._targetMode}}active(){return this._phase!==pe}value(){return this._cur}firePending(){return this._phase===Bi?this._fireAtEnd:this._firePending}cancel(){return this._phase=pe,this._firePending=!1,this._fireAtEnd=!1,this._t=1,this}};var J=null;Li(i=>{let e=J;if(!e||!e._running||!i)return null;let t=n=>({layer:n.layer,session:e.session});for(let n of e._windows.values())if(n.canvas===i&&n.layer)return t(n);for(let n of e._windows.values())if(n.layer&&typeof i.contains=="function"&&i.contains(n.canvas))return t(n);for(let n of e._windows.values()){let r=n.canvas.parentElement;if(n.layer&&r&&typeof r.contains=="function"&&r.contains(i))return t(n)}return null});var ko=()=>typeof navigator<"u"&&!!navigator.xr,le=()=>typeof window<"u"&&typeof window.XRDisplayLayer=="function",at=()=>le()&&"excludeElement"in window.XRDisplayLayer.prototype,fn=()=>{if(!le())return!1;try{return"setViewRig"in window.XRDisplayLayer.prototype}catch{return!1}},To=["getDisplayInfo","getRenderingModes","requestRenderingMode"],nr=["renderingmodechange","hardwaredisplaystatechange"],xn="trackingstatechange",ir=["unknown","tracking","searching"],Gi=[...nr,xn];function lt(i){try{let e=i?i.trackingState:void 0;return ir.includes(e)?e:null}catch{return null}}var pn=()=>{if(!le())return!1;try{let i=window.XRDisplayLayer.prototype;return To.every(e=>typeof i[e]=="function")}catch{return!1}},mn=()=>{if(!le())return!1;try{return typeof window.XRDisplayLayer.prototype.undock=="function"}catch{return!1}},_e=null;function ge(){if(_e!==null)return _e;if(!le())return!1;try{let i=window.XRDisplayLayer.occlusionByDrawOrder;if(typeof i=="boolean")return _e=i}catch{}return!1}function Ao(i){if(_e!==null)return _e;if(!i||!le()||!("occlusionByDrawOrder"in window.XRDisplayLayer.prototype))return null;try{return _e=!!i.occlusionByDrawOrder}catch{return null}}var qi=!1;function gn(){qi||(qi=!0,console.info("[inline3d] This browser composites 2D over woven 3D automatically, per-pixel by draw order \u2014 overlay exclusion is obsolete here, so exclude()/addGlobalOverlay()/data-inline3d-overlay/autoChrome are accepted and ignored. Your 2D chrome already occludes the tiles correctly. The calls are harmless (keep them if you also ship to older DisplayXR Browsers); gate on inline3dOcclusionByDrawOrder() to drop them."))}function rr(){return ko()&&le()}function _n(i){return{type:"display",position:{x:0,y:0,z:0},orientation:{x:0,y:0,z:0,w:1},virtualDisplayHeight:i.virtualDisplayHeight>0?i.virtualDisplayHeight:.24,ipdFactor:1,parallaxFactor:1,perspectiveFactor:1}}function Oo(i,e){let t=Number.isFinite(i.ipdFactor)?i.ipdFactor:1,n=Number.isFinite(i.parallaxFactor)?i.parallaxFactor:1;return{...i,ipdFactor:t*e,parallaxFactor:n*e}}var Do=16;function H(){return typeof performance<"u"&&performance&&typeof performance.now=="function"?performance.now():Date.now()}var Sn=1200,Po=new Set(["pending","woven","withheld"]),Yi=3,Lo=new Set(["getDisplayInfo","getRenderingModes","requestRenderingMode"]),Io=new Set(["getDisplayInfo","getRenderingModes"]);function Fo(i){return i==null||Array.isArray(i)&&i.length===0}function vn(){try{let i=typeof XRDisplayLayer=="function"?XRDisplayLayer:null;return!!(i&&i.prototype&&"wovenState"in i.prototype)}catch{return!1}}function ct(i){try{let e=i?i.wovenState:null;return Po.has(e)?e:null}catch{return null}}function yn(i){try{let e=i?i.withheldReason:null;return typeof e=="string"&&e?e:null}catch{return null}}var Ki=!1;function No(i){if(i==null)return me;let e=dn(i);return e||(Ki||(Ki=!0,console.warn(`[inline3d] createInline3D({ modeSwitch: { easing: ${JSON.stringify(i)} } }) is not a curve this SDK knows (${un.join(" / ")}); using '${me}'.`)),me)}var Ji=!1;function jo(){Ji||(Ji=!0,console.info("[inline3d] The active rendering mode is 1-view, so this SDK has zeroed every window rig (ipdFactor/parallaxFactor -> 0) \u2014 both eyes now render from one place. The runtime keeps weaving the same two-view atlas whatever the page submits, so leaving stereo in it would put two slightly different images on a flat panel, i.e. a blurry double image instead of 2D. Your rendering is unchanged; the flattening is a copy applied on the way to the layer and it is undone the moment a 2-view mode goes active again."))}function Mn(i){return i&&i.detail!==void 0&&i.detail!==null?i.detail:void 0}function sr(i){let e=Mn(i);return e!==void 0?[e,i]:[i]}function zo(i){for(let e of sr(i)){if(typeof e=="number"&&Number.isFinite(e))return e;if(e&&typeof e=="object"){let t=e.modeIndex!==void 0?e.modeIndex:e.mode;if(typeof t=="number"&&Number.isFinite(t))return t}}return-1}function Wo(i){for(let e of sr(i)){if(e==="2d"||e==="3d")return e;if(e&&typeof e=="object"){let t=e.state!==void 0?e.state:e.hardwareDisplayState;if(t==="2d"||t==="3d")return t}}return null}var Zi=!1;function Ho(){Zi||(Zi=!0,console.warn("[inline3d] This browser has no XRDisplayLayer.setViewRig, so the view rig was ignored (the window still weaves \u2014 the runtime keeps the default display rig, scaled by virtualDisplayHeight). Gate on inline3dViewRigSupported() if your page's framing depends on the rig; further calls are silent."))}var Qi=!1;function $o(){Qi||(Qi=!0,console.warn("[inline3d] addScene got BOTH viewRig and virtualDisplayHeight; on a browser with rig support the rig wins and the height is dropped. They describe the same slot \u2014 virtualDisplayHeight is shorthand for exactly one rig (display, identity pose, all factors 1) \u2014 so there is no merge. This is only worth passing as a PAIR deliberately: the height is what a browser without setViewRig will use, so a camera-rig scene can name its own fallback framing. Otherwise say it once, inside the rig."))}async function or(i={}){let{referenceSpace:e="viewer",lazy:t=!0,rootMargin:n="50% 0px",autoChrome:r=!0,modeSwitch:s=null,untrackedFallback:o="none",viewerEase:a}=i;if(!rr())return{supported:!1,trackingState:"unknown"};let l;try{l=await navigator.xr.requestSession("inline-3d")}catch(h){return{supported:!1,trackingState:"unknown",error:h}}a!==void 0&&Ii(l,a);let c=null;try{c=await l.requestReferenceSpace(e)}catch{}return new En(l,c,{lazy:t,rootMargin:n,autoChrome:r,modeSwitch:s,untrackedFallback:o})}var ze=null;function ut(i={}){return J&&J._running?Promise.resolve(J):ze||(ze=or(i).finally(()=>{ze=null}),ze)}var er=.7,Uo=new Set(["IMG","SVG","VIDEO","CANVAS","BUTTON","INPUT","SELECT","TEXTAREA"]);function Vo(i){let e=[],t=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT);for(let n=t.nextNode();n;n=t.nextNode())if(!n.closest("[data-inline3d-no-overlay]")){if(Uo.has(n.tagName.toUpperCase())){e.push(n);continue}for(let r of n.childNodes)if(r.nodeType===Node.TEXT_NODE&&r.nodeValue.trim()){e.push(n);break}}return e}var wn=4;function bn(i){let e=typeof window<"u"&&window.devicePixelRatio||1,t="";if(typeof i.getBoundingClientRect=="function"){let n=i.getBoundingClientRect()||{},r=typeof window<"u"&&window.scrollX||0,s=typeof window<"u"&&window.scrollY||0;t=`+${Math.round((n.left??n.x??0)+r)},${Math.round((n.top??n.y??0)+s)}`}return`${i.clientWidth}x${i.clientHeight}@${e}${t}`}function tr(i){let e=typeof window<"u"&&window.devicePixelRatio||1;return{width:i.clientWidth||0,height:i.clientHeight||0,dpr:e}}function Bo(i){if(i==null||i===!1||i==="off")return null;if(i==="auto"||i===!0)return{color:"#000",snapshot:!0};if(typeof i=="object"){if(i.color!==void 0&&typeof i.color!="string")throw new TypeError("[inline3d] rectCover.color must be a CSS color string.");return{color:i.color||"#000",snapshot:i.snapshot!==!1}}throw new TypeError(`[inline3d] rectCover: expected 'auto', 'off' or { color?, snapshot? }; got ${JSON.stringify(i)}.`)}var En=class{constructor(e,t,{lazy:n,rootMargin:r,autoChrome:s=!0,modeSwitch:o=null,untrackedFallback:a="none"}){this.supported=!0,this.session=e,this.refSpace=t,this._windows=new Map,this._claims=new Map,this._doubleWarned=new WeakSet,this._globalOverlays=new Set,this._isolatedBy=new WeakMap,this._autoChrome=s,this._autoChromeEls=new Set,this._lastChromeScan=0,this._fullTileWarned=new WeakSet,this._stoodDown=!1,this._activeModeIndex=-1,this._activeViewCount=0,this._hardwareDisplayState=null,this._modes=null,this._stereoCollapsed=!1,this._displayListeners=new Map,this._primedDisplayState=!1;let l=o&&typeof o=="object"?o:{};this._msEnabled=l.enabled!==!1,this._modeSwitch=new ot((Number.isFinite(l.durationMs)?Math.max(0,l.durationMs):180)/1e3,No(l.easing)),this._stereoFactor=1,this._msFire=null,this._msArmedUp=!1,this._msLastMs=null,this._msTick=null,this._trackingSupported=lt(e)!==null,this._trackingState=this._trackingSupported?lt(e):"unknown",this._untrackedFallback=a==="mono"?"mono":"none",this._bakedStereo=1,this._bakedTarget=1,this._bakedAt=null,this._bakedEaseS=(Number.isFinite(l.durationMs)?Math.max(0,l.durationMs):180)/1e3,this._applyUntrackedTarget(),this.undock=mn()?{model:!1,splat:!1}:null,this._undockRead=!1,this._running=!0,this._lazy=n,this._observer=n&&typeof IntersectionObserver=="function"?new IntersectionObserver(c=>this._onIntersect(c),{rootMargin:r}):null,this._loopId=0,this._framePending=!1,this._frameCount=0,this._frameWatchdog=null,this._suspended=null,J&&J._running&&J!==this&&console.warn("[inline3d] A second inline-3D session is live in this document. The browser's element-rect channel is a whole-widget setter, so both managers clobber each other's rect list every frame \u2014 tiles may flicker, ghost, or weave at a stale rect. Use ONE createInline3D() per document and add every window to it; if you are switching views, close() the previous manager first."),J=this,e.addEventListener("end",()=>this._teardown()),this._bindDisplayEvents(),this._bindTrackingEvents(),this._scanChrome(),this._bindLifecycle(),this._armDprWatch(),this._requestFrame()}get liveCount(){let e=0;for(let t of this._windows.values())t.layer&&e++;return e}addGlobalOverlay(e){if(!(!e||this._globalOverlays.has(e))){ge()&&gn(),this._globalOverlays.add(e);for(let t of this._windows.values())t.layer&&this._applyExclusion(t,e)}}removeGlobalOverlay(e){if(!(!e||!this._globalOverlays.delete(e)))for(let t of this._windows.values())t.layer&&this._dropExclusion(t,e)}_scanChrome(){if(ge()||!this._autoChrome||!at()||typeof document>"u")return;let e=Date.now();if(e-this._lastChromeScan<1e3)return;this._lastChromeScan=e;let t=document.body;if(!t)return;let n=new Set,r=t.querySelectorAll(":scope > *, :scope > * > *, :scope > * > * > *");for(let s of r){if(s.closest("[data-inline3d-no-overlay]"))continue;let o=getComputedStyle(s).position;if(o!=="fixed"&&o!=="sticky")continue;let a=!1;for(let l of this._windows.keys())if(s===l||s.contains(l)){a=!0;break}if(!a){n.add(s);for(let l of Vo(s))n.add(l)}}for(let s of this._autoChromeEls){let o=!1;if(s.isConnected){for(let a of this._windows.keys())if(s===a||s.contains(a)){o=!0;break}}(!s.isConnected||o)&&(this._autoChromeEls.delete(s),this.removeGlobalOverlay(s))}for(let s of n)this._globalOverlays.has(s)||(this._autoChromeEls.add(s),this.addGlobalOverlay(s))}addImage(e,t,n={}){this._warnDoubleAttach(e,"addImage",n._dxrClaim);let r=this._register(e,"image",n);return r.method="addImage",r.ready=Go(t).then(s=>{r.img=s,r.repaint()}),this._handle(e,r)}addVideo(e,t,n={}){this._warnDoubleAttach(e,"addVideo",n._dxrClaim);let r=this._register(e,"video",n);return r.method="addVideo",r.video=t,this._handle(e,r)}addScene(e,t,n={}){this._warnDoubleAttach(e,"addScene",n._dxrClaim),n.viewRig&&n.virtualDisplayHeight!==void 0&&$o();let r=this._register(e,"scene",{virtualDisplayHeight:.24,...n});return r.method="addScene",r.onFrame=t,r.ownsBuffer=!1,n.bufferClamped===!0&&(r.warnedBufMismatch=!0),this._handle(e,r)}_liveRegistration(e,t){let n=this._claims.get(e);if(n&&n.token!==t)return n.method;let r=this._windows.get(e);return r?r.method||"add*":null}_warnDoubleAttach(e,t,n){let r=this._liveRegistration(e,n);!r||this._doubleWarned.has(e)||(this._doubleWarned.add(e),console.warn(`[inline3d] ${t}() on a canvas that is already registered on this inline-3D session (by ${r}(), not yet removed). This call is rebuilding the canvas's layer (a fresh 0.4-1.2 s identity gap) or putting a second renderer on its context. Change what is IN the canvas instead (setSource, your onFrame, a redrawn source canvas), or call handle.remove() on the first registration first. (Warned once per canvas.)`,e))}_attachGuard(e,t,n={}){let r=this._claims.get(e);if(n&&n._dxrClaim&&r&&r.token===n._dxrClaim)return{opts:n,own:()=>{}};this._warnDoubleAttach(e,t,null);let s={};return{opts:{...n,_dxrClaim:s},own:o=>this._claim(e,t,o,s)}}_claim(e,t,n,r){if(!this._running||!n||typeof n!="object")return;let s={token:r,method:t};this._claims.set(e,s);let o=n.remove,a=(...l)=>(this._claims.get(e)===s&&this._claims.delete(e),typeof o=="function"?o.apply(n,l):void 0);Object.defineProperty(n,"remove",{configurable:!0,enumerable:!0,get:()=>a,set:l=>{o=l}})}_handle(e,t){let n=this;return{remove:()=>this._remove(e),exclude:r=>{r&&(ge()&&gn(),t.excluded.add(r),this._applyExclusion(t,r))},unexclude:r=>{!r||!t.excluded.delete(r)||this._dropExclusion(t,r)},get trackingState(){return n._trackingState},setViewRig:r=>(t.viewRig=r||null,r&&ln(t.rigWarned,r),this._pushViewRig(t)),setCursorDepth:r=>{let s=t.layer;if(!s||typeof s.setCursorDepth!="function")return!1;try{return r?s.setCursorDepth(r):s.setCursorDepth(),!0}catch{return!1}},getCursorDepthSupport:()=>{let r=t.layer;if(!r||typeof r.getCursorDepthSupport!="function")return Promise.resolve("none");try{return Promise.resolve(r.getCursorDepthSupport()).then(s=>s==="runtime"?"runtime":"none",()=>"none")}catch{return Promise.resolve("none")}},getDisplayInfo:()=>this._layerCall(t,"getDisplayInfo","getDisplayInfo()"),displayMetrics:async()=>{let r=null;try{r=await this._layerCall(t,"getDisplayInfo","getDisplayInfo()")}catch{}return Fi(r,e.getBoundingClientRect(),globalThis.devicePixelRatio||1)},getRenderingModes:()=>this._getRenderingModes(t),requestRenderingMode:r=>this._requestRenderingModeEased(r,t),setStereoEnabled:r=>this._setStereoEnabled(r,t),on:(r,s)=>this.on(r,s),off:(r,s)=>this.off(r,s),onDisplayModeChange:r=>this._onDisplayModeChange(r),stats:()=>({frames:t.frames,monoFrames:t.monoFrames}),get wovenState(){return vn()?t.layer?ct(t.layer):"pending":null},get withheldReason(){return!vn()||!t.layer?null:ct(t.layer)==="withheld"?yn(t.layer):null},get firstWoven(){return t.fwPromise},onFirstWoven:r=>{if(typeof r!="function")throw new TypeError("[inline3d] onFirstWoven() takes a function.");let s=!0;return t.fwPromise.then(o=>{if(s)try{r(o)}catch(a){console.error("[inline3d] onFirstWoven callback threw",a)}}),()=>{s=!1}},rewoven:()=>this._rewoven(t)}}getDisplayInfo(){return this._layerCall(this._liveWindow(null),"getDisplayInfo","getDisplayInfo()")}getRenderingModes(){return this._getRenderingModes(null)}requestRenderingMode(e){return this._requestRenderingModeEased(e,null)}setStereoEnabled(e){return this._setStereoEnabled(e,null)}get trackingState(){return this._trackingState}get hardwareDisplayState(){return this._hardwareDisplayState}get activeMode(){return{modeIndex:this._activeModeIndex,viewCount:this._activeViewCount}}get stereoCollapsed(){return this._stereoCollapsed}get modeSwitch(){return{active:this._msTransitionActive(),factor:this._stereoFactor}}close(){try{this.session.end()}catch{}this._teardown()}_effectiveViewRig(e){return this._stereoFactor>=1?e.viewRig||(e.stereoSynthRig?_n(e):null):(e.viewRig||(e.stereoSynthRig=!0),Oo(e.viewRig||_n(e),this._stereoFactor))}_setStereoCollapsed(e){let t=!!e;if(this._stereoCollapsed!==t){this._stereoCollapsed=t,t&&jo(),!t&&this._msArmedUp?(this._msArmedUp=!1,this._startUpRamp()):this._modeSwitch.active()||(this._stereoFactor=t?0:1);for(let n of this._windows.values()){if(t){let r=n.viewRig||_n(n);n.stereoSaved={ipdFactor:r.ipdFactor,parallaxFactor:r.parallaxFactor}}else n.stereoSaved=null;this._pushViewRig(n)}}}_pushViewRig(e){if(!fn())return Ho(),!1;if(!e.layer)return!1;let t=this._effectiveViewRig(e);try{return e.layer.setViewRig(t),!0}catch{return!1}}_layerCall(e,t,n,r=[]){if(!pn())return Promise.reject(new Error(`[inline3d] ${n} needs a DisplayXR Browser with the display-mode API (XRDisplayLayer.getDisplayInfo/getRenderingModes/requestRenderingMode). Gate on inline3dDisplayModesSupported().`));if(!e||!e.layer)return Promise.reject(new Error(`[inline3d] ${n} needs a live weave layer, and this window has none right now (lazy mode closes the layer while the tile is off screen). Call it once the tile is visible, or create the manager with { lazy: false }.`));if(Lo.has(t)&&!e.layerFramed&&this._layerReadPending(e))return this._whenLayerFramed(e).then(()=>this._layerCall(e,t,n,r));let o;try{o=Promise.resolve(e.layer[t](...r))}catch(l){return Promise.reject(l)}if(!Io.has(t)||!this._layerReadPending(e))return o;let a=e.layer;return o.then(l=>e.layer!==a?l:Fo(l)?this._layerReadPending(e)?this._whenLayerFramed(e).then(()=>this._layerCall(e,t,n,r)):l:(e.lfAnswered=!0,l))}_layerFramedCap(e){return wn*Math.max(e.fwHoldMs,Sn)}_layerReadPending(e){return!e.layer||e.lfAnswered||e.lfCapped?!1:H()-e.lfAt>=this._layerFramedCap(e)?(e.lfCapped=!0,!1):!0}_whenLayerFramed(e){return new Promise(t=>{let n=e.layer,r={resolve:t,timer:null},s=Math.max(0,this._layerFramedCap(e)-(H()-e.lfAt));r.timer=setTimeout(()=>{let o=e.framedWaiters.indexOf(r);o>=0&&e.framedWaiters.splice(o,1),e.layer===n&&(e.lfCapped=!0),t()},s),r.timer&&typeof r.timer.unref=="function"&&r.timer.unref(),e.framedWaiters.push(r)})}_tickLayerFramed(e){let t=e.wsLive?ct(e.layer):null;(t?t==="woven":e.lfStereo)?this._noteLayerFramed(e,!0):e.framedWaiters.length&&!this._layerReadPending(e)&&this._noteLayerFramed(e,!1)}_noteLayerFramed(e,t=!0){t&&(e.layerFramed=!0);let n=e.framedWaiters.splice(0);for(let r of n)clearTimeout(r.timer),r.resolve()}_liveWindow(e){if(e&&e.layer)return e;for(let t of this._windows.values())if(t.layer)return t;return e||null}async _getRenderingModes(e){let t=await this._layerCall(this._liveWindow(e),"getRenderingModes","getRenderingModes()"),n=Array.isArray(t)?t:[];this._modes=n;let r=n.find(s=>s.isActive);return r&&(this._activeModeIndex=r.modeIndex,this._activeViewCount=r.viewCount,(r.viewCount===1||r.viewCount===2)&&this._setStereoCollapsed(r.viewCount===1)),this._primedDisplayState=!0,t}_requestRenderingMode(e,t){return this._layerCall(this._liveWindow(t),"requestRenderingMode","requestRenderingMode()",[e])}_msTransitionActive(){return this._modeSwitch.active()||this._msArmedUp||this._msFire!==null}async _requestRenderingModeEased(e,t){if(!this._msEnabled||!fn())return this._requestRenderingMode(e,t);let n=this._modes;if(!Array.isArray(n)||n.length===0)try{n=await this._getRenderingModes(t)}catch{n=null}let r=(Array.isArray(n)?n:[]).find(a=>a&&a.modeIndex===e),s=r&&Number.isFinite(r.viewCount)?r.viewCount:0,o=this._activeViewCount;return s<1||s>2||o<1?this._requestRenderingMode(e,t):s===1?o===1?this._requestRenderingMode(e,t):this._rampDownThenRequest(e,t):this._requestThenRampUp(e,t)}_rampDownThenRequest(e,t){if(this._msFire&&this._msFire.modeIndex===e)return this._msFire.promise;this._settlePendingDown("superseded",`a request for mode ${e} replaced it`);let n={modeIndex:e,win:t,resolve:null,reject:null,promise:null};return n.promise=new Promise((r,s)=>{n.resolve=r,n.reject=s}),this._msFire=n,this._modeSwitch.request({targetMode:e,targetViewCount:1,currentMode:this._activeModeIndex,currentViewCount:this._activeViewCount,current:this._stereoFactor,steady:1}),this._msLastMs=H(),this._armModeSwitchTick(),n.promise}_requestThenRampUp(e,t){let r=this._msFire!==null&&e===this._activeModeIndex;this._settlePendingDown("superseded",`a request for mode ${e} reversed it`);let s=r?Promise.resolve(void 0):this._requestRenderingMode(e,t);return this._stereoFactor<1&&(this._stereoCollapsed?(this._msArmedUp=!0,this._modeSwitch.cancel(),this._stereoFactor=0):this._startUpRamp()),s.catch(o=>{throw this._msArmedUp&&(this._msArmedUp=!1,this._modeSwitch.active()||(this._stereoFactor=this._stereoCollapsed?0:1)),o})}_startUpRamp(){this._settlePendingDown("superseded","the display returned to 3D"),this._modeSwitch.request({targetMode:this._activeModeIndex,targetViewCount:2,currentMode:this._activeModeIndex,currentViewCount:2,current:this._stereoFactor,steady:1}),this._msLastMs=H(),this._armModeSwitchTick()}_settlePendingDown(e,t){let n=this._msFire;if(!n)return;this._msFire=null;let r=new Error(`[inline3d] the request for rendering mode ${n.modeIndex} was never forwarded: ${t}. A ->2D switch is held until the disparity has ramped out, so a request that is reversed or replaced in that window is dropped rather than fired late.`);r.name=e,n.reject(r)}_advanceModeSwitch(){if(!this._modeSwitch.active()){this._msLastMs=null,this._disarmModeSwitchTick();return}let e=H(),t=typeof this._msLastMs=="number"?Math.max(0,(e-this._msLastMs)/1e3):0;this._msLastMs=e;let n=this._modeSwitch.update(t);if(n.factor!==this._stereoFactor){this._stereoFactor=n.factor;for(let r of this._windows.values())this._pushViewRig(r)}if(n.fire&&this._msFire){let r=this._msFire;this._msFire=null,this._requestRenderingMode(r.modeIndex,r.win).then(s=>r.resolve(s),s=>{this._startUpRamp(),r.reject(s)})}this._modeSwitch.active()||(this._msLastMs=null,this._disarmModeSwitchTick())}_armModeSwitchTick(){this._msTick!==null||typeof setTimeout!="function"||(this._msTick=setTimeout(()=>{this._msTick=null,this._running&&(this._advanceModeSwitch(),this._modeSwitch.active()&&this._armModeSwitchTick())},Do))}_disarmModeSwitchTick(){this._msTick!==null&&(typeof clearTimeout=="function"&&clearTimeout(this._msTick),this._msTick=null)}async _setStereoEnabled(e,t){let n=e?2:1,r=await this._getRenderingModes(t),s=Array.isArray(r)?r:[],o=s.find(a=>a.viewCount===n&&a.isRequestable);if(!o)throw new Error(`[inline3d] setStereoEnabled(${!!e}) found no requestable ${n}-view mode on this display (${s.length} mode(s) listed). It is sugar over requestRenderingMode() and cannot invent one \u2014 read getRenderingModes() and drive the list yourself.`);return o.isActive&&!this._msTransitionActive()||await this._requestRenderingModeEased(o.modeIndex,t),!!e}_bindDisplayEvents(){let e=this.session;!e||typeof e.addEventListener!="function"||pn()&&(e.addEventListener("renderingmodechange",t=>{this._onRenderingModeChange(t).catch(()=>{})}),e.addEventListener("hardwaredisplaystatechange",t=>{this._onHardwareDisplayStateChange(t).catch(()=>{})}))}_onHardwareDisplayStateChange(e){let t=Wo(e),n=Mn(e),r=a=>{a&&(this._hardwareDisplayState=a),this._emitDisplay({type:"hardwaredisplaystatechange",state:a||this._hardwareDisplayState,detail:n})};t&&r(t);let s=this._activeModeIndex,o=this._activeViewCount;return this._getRenderingModes(null).then(a=>{let l=(Array.isArray(a)?a:[]).find(c=>c.isActive)||null;if(l&&(l.modeIndex!==s||l.viewCount!==o)&&this._emitDisplay({type:"renderingmodechange",modeIndex:this._activeModeIndex,viewCount:this._activeViewCount||null,mode:l,detail:null}),!t){let c=l&&typeof l.hardwareDisplay3D=="boolean"?l.hardwareDisplay3D?"3d":"2d":null;r(c)}}).catch(()=>{t||r(null)})}async _onRenderingModeChange(e){let t=Mn(e),n=zo(e),r=null;try{let s=await this._getRenderingModes(null),o=Array.isArray(s)?s:[];r=(n>=0?o.find(a=>a.modeIndex===n):null)||o.find(a=>a.isActive)||null}catch{}r?(this._activeModeIndex=r.modeIndex,this._activeViewCount=r.viewCount):n>=0&&(this._activeModeIndex=n),(this._activeViewCount===1||this._activeViewCount===2)&&this._setStereoCollapsed(this._activeViewCount===1),this._emitDisplay({type:"renderingmodechange",modeIndex:this._activeModeIndex,viewCount:this._activeViewCount||null,mode:r,detail:t})}_emitDisplay(e,t){let n=this._displayListeners.get(e.type);if(!n)return;let r=t||[e];for(let s of[...n])try{s(...r)}catch(o){console.error(`[inline3d] ${e.type} listener threw`,o)}}on(e,t){if(typeof t!="function")throw new TypeError("[inline3d] on() takes (type, function).");if(!Gi.includes(e))throw new TypeError(`[inline3d] on() knows ${Gi.join(" / ")}, got ${JSON.stringify(e)}.`);let n=this._displayListeners.get(e);return n||this._displayListeners.set(e,n=new Set),n.add(t),()=>this.off(e,t)}off(e,t){let n=this._displayListeners.get(e);n&&n.delete(t)}_onDisplayModeChange(e){if(typeof e!="function")throw new TypeError("[inline3d] onDisplayModeChange() takes a function.");let t=nr.map(n=>this.on(n,e));return()=>{for(let n of t)n()}}async refreshUndock(){if(!mn())return this.undock=null;let e=this._liveWindow(null);if(!e||!e.layer||typeof e.layer.getUndockCapabilities!="function")return this.undock;try{let t=await e.layer.getUndockCapabilities();this.undock={model:!!(t&&t.model),splat:!!(t&&t.splat)}}catch{}return this.undock}_register(e,t,n){this._windows.has(e)&&this._remove(e),e.style.willChange="transform",e.style.transform="translateZ(0)";let r={canvas:e,kind:t,layer:null,img:null,video:null,onFrame:null,onLayerLost:typeof n.onLayerLost=="function"?n.onLayerLost:null,layerLostSent:!1,onResize:t==="scene"&&typeof n.onResize=="function"?n.onResize:null,resizeBox:null,inResize:!1,ready:null,ownsBuffer:t!=="scene",cornerRadius:n.cornerRadius||0,feather:n.feather||0,reqW:n.width||0,reqH:n.height||0,virtualDisplayHeight:n.virtualDisplayHeight||0,viewRig:n.viewRig||null,rigWarned:new Set,warnedWithheld:!1,stereoSaved:null,stereoSynthRig:!1,observeEl:n.observe||e,ctx:t==="scene"?null:e.getContext("2d"),repaint:()=>this._paint(r,null),excluded:new Set,autoExcluded:new Set,overlayObserver:null,sizeObserver:null,resizePending:!1,frames:0,monoFrames:0,fwResult:null,fwResolve:null,fwPromise:null,fwHoldMs:Xo(n.firstWovenHoldMs),fwRegAt:H(),fwLayerAt:null,fwStereo:!1,rw:null,rwGone:null,wsLive:!1,rc:null,layerFramed:!1,lfAnswered:!1,lfStereo:!1,lfAt:0,lfCapped:!1,framedWaiters:[]},s=Bo(n.rectCover);return s&&(r.rc={cfg:s,box:null,el:null,up:!1,snapped:!1,snapWanted:!1,waiting:null,w:0,h:0}),r.fwPromise=new Promise(o=>{r.fwResolve=o}),r.viewRig&&ln(r.rigWarned,r.viewRig),this._windows.set(e,r),this._lazy&&this._observer?this._observer.observe(r.observeEl):this._activate(r),r}_remove(e){let t=this._windows.get(e);t&&(this._observer&&this._observer.unobserve(t.observeEl),this._deactivate(t),this._windows.delete(e),this._settleFirstWoven(t,!1,"removed"),this._dropCover(t))}_onIntersect(e){for(let t of e){let n=null;for(let r of this._windows.values())if(r.observeEl===t.target){n=r;break}n&&(t.isIntersecting?this._activate(n):this._deactivate(n))}}_activate(e){if(!e.layer){this._scanChrome();try{let t=fn()?this._effectiveViewRig(e):null,n=t?{viewRig:t}:e.virtualDisplayHeight>0?{virtualDisplayHeight:e.virtualDisplayHeight}:{};e.layer=new XRDisplayLayer(this.session,e.canvas,n)}catch(t){e.layer=null,e.layerFailWarned||(e.layerFailWarned=!0,console.warn("[inline3d] new XRDisplayLayer() failed for this window \u2014 it will show FLAT 2D instead of woven 3D, and the SDK will not retry. The canvas has been repainted mono so it cannot be left holding a raw side-by-side pair.",t)),this._paintMono(e),this._notifyLayerLost(e),this._settleFirstWoven(e,!1,"layer-failed");return}e.fwResult||(e.fwLayerAt=H(),e.fwStereo=!1),e.wsLive=vn(),e.layerFramed=!1,e.lfAnswered=!1,e.lfStereo=!1,e.lfCapped=!1,e.lfAt=H(),this._restartRewoven(e),e.layerLostSent=!1,!this._primedDisplayState&&pn()&&(this._primedDisplayState=!0,this._getRenderingModes(e).catch(()=>{this._primedDisplayState=!1})),mn()&&this.undock&&!this._undockRead&&(this._undockRead=!0,this.refreshUndock().catch(()=>{})),Ao(e.layer)===!0&&this._standDownLegacyOcclusion();for(let t of e.excluded)this._applyExclusion(e,t);for(let t of this._globalOverlays)this._applyExclusion(e,t);this._startOverlayScan(e),e.ownsBuffer&&(this._sizeBuffer(e,!0),this._paint(e,null)),this._startSizeWatch(e)}}_deactivate(e){if(this._noteLayerFramed(e,!1),this._stopOverlayScan(e),this._stopSizeWatch(e),e.layer){try{e.layer.close()}catch{}e.layer=null}this._paintMono(e)}_paintMono(e){!e.ownsBuffer||e.kind==="scene"||(this._sizeBuffer(e,!1),this._paint(e,null))}_notifyLayerLost(e){if(!(e.kind!=="scene"||typeof e.onLayerLost!="function"||e.layerLostSent)){e.layerLostSent=!0;try{e.onLayerLost()}catch(t){console.warn("[inline3d] a scene window's onLayerLost callback threw",t)}}}_isFullTileOverlay(e,t){if(!t||typeof t.getBoundingClientRect!="function")return!1;let n=t.getBoundingClientRect(),r=e.canvas.getBoundingClientRect(),s=n.width*n.height,o=r.width*r.height;if(s<=0||o<=0)return!1;let a=Math.min(n.right,r.right)-Math.max(n.left,r.left),l=Math.min(n.bottom,r.bottom)-Math.max(n.top,r.top);if(a<=0||l<=0)return!1;let c=a*l;return c/s<er||c/o<er?!1:(this._fullTileWarned.has(t)||(this._fullTileWarned.add(t),console.warn("[inline3d] Refusing a full-tile overlay: this element covers its own woven canvas, and the browser's geometric matcher cannot tell the two apart \u2014 it would stage the CANVAS as the overlay and the tile would show its raw side-by-side buffer instead of 3D. Make the overlay a PARTIAL region of the tile (a caption band, a badge, a corner plate), or move it outside the tile and register it with addGlobalOverlay().",t)),!0)}_applyExclusion(e,t){if(ge()||!e.layer||!at()||this._isFullTileOverlay(e,t))return;let n=this._isolatedBy.get(t);if(n||(n=new Set,this._isolatedBy.set(t,n)),n.add(e),!t.dataset.inline3dIsolated){t.dataset.inline3dPriorWillChange=t.style.willChange||"";let r=t.style.willChange&&t.style.willChange!=="auto"?t.style.willChange+", transform":"transform";t.style.willChange=r,t.dataset.inline3dIsolated="1"}try{e.layer.excludeElement(t)}catch{}}_dropExclusion(e,t){if(ge())return;let n=this._isolatedBy.get(t);if(n&&n.delete(e),(!n||n.size===0)&&this._unpromote(t),!(!e.layer||!at()))try{e.layer.unexcludeElement(t)}catch{}}_unpromote(e){return!e||!e.dataset||!e.dataset.inline3dIsolated?!1:(e.style.willChange=e.dataset.inline3dPriorWillChange||"",delete e.dataset.inline3dPriorWillChange,delete e.dataset.inline3dIsolated,!0)}_standDownLegacyOcclusion(){if(this._stoodDown)return;this._stoodDown=!0;let e=!1;for(let t of this._windows.values()){t.overlayObserver&&(this._stopOverlayScan(t),e=!0);for(let n of t.excluded)this._unpromote(n)&&(e=!0)}for(let t of this._autoChromeEls)this._globalOverlays.delete(t),this._unpromote(t),e=!0;this._autoChromeEls.clear();for(let t of this._globalOverlays)this._unpromote(t)&&(e=!0);this._isolatedBy=new WeakMap,e&&gn()}_startOverlayScan(e){if(ge()||!at()||typeof MutationObserver!="function")return;let t=e.canvas.parentElement;if(!t)return;let n=()=>{let r=new Set(t.querySelectorAll("[data-inline3d-overlay]"));for(let s of e.autoExcluded)r.has(s)||(e.autoExcluded.delete(s),this._dropExclusion(e,s));for(let s of r)e.autoExcluded.has(s)||(e.autoExcluded.add(s),this._applyExclusion(e,s))};n(),e.overlayObserver=new MutationObserver(n),e.overlayObserver.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-inline3d-overlay"]})}_stopOverlayScan(e){e.overlayObserver&&(e.overlayObserver.disconnect(),e.overlayObserver=null),e.autoExcluded.clear()}_eyeSize(e,t=!0){let n=Math.min(window.devicePixelRatio||1,2),r=e.reqW||Math.round((e.canvas.clientWidth||256)*n),s=e.reqH||Math.round((e.canvas.clientHeight||256)*n),o=1,a=!e.reqW&&!e.reqH&&this._sourceEyeSize(e);if(a){let c=Math.max(a.w/r,a.h/s);c<1&&(o=c,r=Math.max(1,Math.round(r*c)),s=Math.max(1,Math.round(s*c)))}let l=Hi(r,s,Wi(),{cols:t?2:1});return l.clamped&&(o*=l.scale,r=l.eyeW,s=l.eyeH,e.warnedBufClamp||(e.warnedBufClamp=!0,console.warn($i("[inline3d]",l)))),e.bufScale=o,{w:r,h:s}}_sourceEyeSize(e){if(e.kind!=="video"&&e.kind!=="image")return null;let t=e.kind==="video"?e.video:e.img;if(!t)return null;let n=t.videoWidth||t.naturalWidth||t.width,r=t.videoHeight||t.naturalHeight||t.height;return!(n>1)||!(r>0)?null:{w:n/2,h:r}}_checkSceneBuffer(e){let t=e.canvas;if(!t||typeof t.getContext!="function")return;if(e.sceneGl===void 0){let r=null;try{r=t.getContext("webgl2")||t.getContext("webgl")}catch{r=null}e.sceneGl=r&&typeof r.drawingBufferWidth=="number"?r:null}if(!e.sceneGl)return;let n=Ui(t,e.sceneGl);n.mismatch&&(e.warnedBufMismatch=!0,console.warn(Vi("[inline3d]",t,n,"getViewport() splits canvas.width, so the eyes are off-centre in the woven buffer. This scene canvas is sized by the page: keep 2 \xD7 eye width and the height within MAX_TEXTURE_SIZE / MAX_RENDERBUFFER_SIZE / MAX_VIEWPORT_DIMS, or map getViewport() onto gl.drawingBufferWidth/Height.")))}_sizeBuffer(e,t){let{w:n,h:r}=this._eyeSize(e,t);e.eyeW=n,e.eyeH=r,e.canvas.width=t?n*2:n,e.canvas.height=r,e.sbs=t}_startSizeWatch(e){if(typeof ResizeObserver=="function"&&!e.sizeObserver){if(e.kind==="scene"){if(!e.onResize)return;e.resizeBox=tr(e.canvas),e.sizeObserver=new ResizeObserver(()=>this._onSceneResize(e)),e.sizeObserver.observe(e.canvas);return}!e.ownsBuffer||e.reqW&&e.reqH||(e.sizeObserver=new ResizeObserver(()=>this._onBoxChange(e)),e.sizeObserver.observe(e.canvas))}}_onSceneResize(e){if(!e.layer||!e.onResize||e.inResize)return;let t=tr(e.canvas),n=e.resizeBox;if(!(n&&n.width===t.width&&n.height===t.height&&n.dpr===t.dpr)){e.resizeBox=t,e.inResize=!0;try{e.onResize(t)}catch(r){e.resizeThrewWarned||(e.resizeThrewWarned=!0,console.warn("[inline3d] a scene window's onResize threw; further throws from it are silent.",r))}finally{e.inResize=!1}}}_stopSizeWatch(e){e.sizeObserver&&(e.sizeObserver.disconnect(),e.sizeObserver=null),e.resizePending=!1}_onBoxChange(e){if(!e.layer||!e.ownsBuffer||e.resizePending)return;e.resizePending=!0;let t=()=>{if(!e.resizePending||(e.resizePending=!1,!e.layer||!e.ownsBuffer))return;this._noteRewovenBox(e);let{w:n,h:r}=this._eyeSize(e);n===e.eyeW&&r===e.eyeH||(this._sizeBuffer(e,!0),this._paint(e,null))};typeof requestAnimationFrame=="function"?requestAnimationFrame(t):t()}_armDprWatch(){if(typeof window>"u"||typeof window.matchMedia!="function")return;this._disarmDprWatch();let e;try{e=window.matchMedia(`(resolution: ${window.devicePixelRatio||1}dppx)`)}catch{return}let t=()=>{if(this._running){this._armDprWatch();for(let n of this._windows.values())n.layer&&this._onBoxChange(n)}};try{e.addEventListener("change",t)}catch{return}this._dprWatch={q:e,onChange:t}}_disarmDprWatch(){if(this._dprWatch){try{this._dprWatch.q.removeEventListener("change",this._dprWatch.onChange)}catch{}this._dprWatch=null}}_paint(e,t){if(e.kind==="scene"||!e.ctx)return;let n=this._running&&!!e.layer;!n&&e.sbs&&this._sizeBuffer(e,!1);let r=e.kind==="video"?e.video:e.img;if(!r)return;if(e.kind==="video"&&(r.readyState||0)<2){n&&this._recommitLastFrame(e);return}let s=e.canvas,o=e.ctx,a=r.videoWidth||r.naturalWidth||r.width,l=r.videoHeight||r.naturalHeight||r.height;if(!a||!l)return;let c=a+"x"+l;if(e.srcKey!==c&&(e.srcKey=c,e.ownsBuffer&&!(e.reqW&&e.reqH))){let{w:g,h:x}=this._eyeSize(e,e.sbs);(g!==e.eyeW||x!==e.eyeH)&&this._sizeBuffer(e,e.sbs)}let h=e.bufScale||1,u=e.cornerRadius*h,d=e.feather*h;if(o.clearRect(0,0,s.width,s.height),!e.sbs){ht(o,r,0,0,a/2,l,0,0,s.width,s.height,u,d);return}let p=s.width/2,f=Math.min(this._stereoFactor,this._bakedStereo);if(f<1){ht(o,r,0,0,a/2,l,0,0,p,s.height,u,d),qo(o,r,a/2,l,p,s.height,f,u,d);return}u>0||d>0?(ht(o,r,0,0,a/2,l,0,0,p,s.height,u,d),ht(o,r,a/2,0,a/2,l,p,0,p,s.height,u,d)):o.drawImage(r,0,0,a,l,0,0,s.width,s.height)}_bindTrackingEvents(){let e=this.session;!e||typeof e.addEventListener!="function"||this._trackingSupported&&e.addEventListener(xn,()=>{this._setTrackingState(lt(e)||"unknown")})}_setTrackingState(e){let t=ir.includes(e)?e:"unknown";if(t===this._trackingState)return;this._trackingState=t,this._applyUntrackedTarget();let n={type:xn,state:t};this._emitDisplay(n,[t,n])}_applyUntrackedTarget(){if(this._untrackedFallback!=="mono"){this._bakedTarget=1;return}this._trackingState==="searching"?this._bakedTarget=0:this._trackingState==="tracking"&&(this._bakedTarget=1)}_trackBakedStereo(e){this._trackingSupported&&this._setTrackingState(lt(this.session)||"unknown");let t=this._bakedAt===null||!Number.isFinite(e)?0:Math.max(0,(e-this._bakedAt)/1e3);this._bakedAt=Number.isFinite(e)?e:this._bakedAt;let n=this._bakedStereo,r=this._bakedTarget;if(n===r)return;let s=this._bakedEaseS>0?t/this._bakedEaseS:1;this._bakedStereo=r>n?Math.min(r,n+s):Math.max(r,n-s)}_recommitLastFrame(e){let t=e.canvas;if(!t.width||!t.height)return;let n=e.ctx;try{n.save(),n.globalCompositeOperation="copy",n.drawImage(t,0,0),n.restore()}catch{}}_requestFrame(e){if(!this._running||this._framePending&&!e)return;let t=e?++this._loopId:this._loopId;this._framePending=!0;try{this.session.requestAnimationFrame((n,r)=>{t===this._loopId&&(this._framePending=!1,this._frameCount++,this._frame(n,r))})}catch{this._framePending=!1}}_frame(e,t){if(!this._running)return;this._requestFrame(),this._advanceModeSwitch();let n=this.refSpace?t.getViewerPose(this.refSpace):null,r=n?n.views:null;this._trackBakedStereo(e);for(let s of this._windows.values())if(s.layer){if(s.rc&&this._rectCoverCheck(s),s.kind==="scene"){if(r&&s.onFrame){if(s.frames++,r.length<2&&(s.monoFrames++,s.monoFrames%300===1&&typeof console<"u"&&console.debug)){let o=(100*s.monoFrames/Math.max(1,s.frames)).toFixed(1);console.debug(`[inline3d] scene window: ${s.monoFrames} non-stereo view lists in ${s.frames} frames (${o}%). The viewer replays its last good stereo frame for these; a rising rate means the session is falling back under load.`)}try{s.onFrame(r,s.layer,t),r.length>=2&&(s.fwStereo=!0,s.lfStereo=!0,s.warnedBufMismatch||this._checkSceneBuffer(s),s.rw&&(s.rw.stereo=!0))}catch(o){s.frameThrewWarned||(s.frameThrewWarned=!0,console.warn("[inline3d] a scene window's onFrame threw; this window will keep whatever it last drew, and the other windows carry on. Further throws from it are silent.",o))}}}else this._paint(s,r),s.sbs&&(s.kind==="video"?(s.video&&s.video.readyState||0)>=2:s.img)&&(s.fwStereo=!0,s.lfStereo=!0,s.rw&&(s.rw.stereo=!0));s.rc&&s.rc.snapWanted&&this._rectCoverSnap(s),(!s.layerFramed||s.framedWaiters.length)&&this._tickLayerFramed(s),this._tickFirstWoven(s)}}_tickFirstWoven(e){let t=e.wsLive&&e.layer?ct(e.layer):null;if(t){this._tickWovenState(e,t);return}if(e.rw){this._noteRewovenBox(e);let n=e.rw,r=H();n.stereo&&r-n.at>=e.fwHoldMs?this._settleRewoven(e,!0,"hold-elapsed"):n.at>n.calledAt&&r-n.calledAt>=wn*e.fwHoldMs&&this._settleRewoven(e,!0,"hold-capped")}e.fwResult||!e.fwStereo||e.fwLayerAt===null||H()-e.fwLayerAt<e.fwHoldMs||this._settleFirstWoven(e,!0,"hold-elapsed")}_tickWovenState(e,t){let n=H(),r=wn*Math.max(e.fwHoldMs,Sn);if(e.rw){this._noteRewovenBox(e);let s=e.rw;t!=="woven"?s.gap=!0:s.stereo&&(s.gap||s.boxFrame!==null&&this._frameCount-s.boxFrame>=Yi||s.boxFrame===null&&this._frameCount-s.callFrame>=Yi)&&this._settleRewoven(e,!0,"woven",!0),e.rw&&n-s.calledAt>=r&&(t==="woven"?this._settleRewoven(e,!0,"hold-capped",!0):this._settleRewoven(e,!1,yn(e.layer)||t,!0))}e.fwResult||e.fwLayerAt===null||(e.fwStereo&&t==="woven"?this._settleFirstWoven(e,!0,"woven",!0):n-e.fwLayerAt>=r&&(t==="woven"?this._settleFirstWoven(e,!0,"hold-capped",!0):this._settleFirstWoven(e,!1,yn(e.layer)||t,!0)))}_noteWithheld(e,t,n,r){t||!r||e.warnedWithheld||!n||n==="pending"||n==="hold-capped"||(e.warnedWithheld=!0,console.warn(`[inline3d] the browser withheld this canvas from the weave (${n}): ${Ni(n)}.`,e.canvas))}_settleFirstWoven(e,t,n,r=!1){this._noteWithheld(e,t,n,r),!t&&!r&&(e.rwGone||(e.rwGone=n),this._settleRewoven(e,!1,n)),!e.fwResult&&(e.fwResult=Object.freeze({woven:t,confirmed:r,reason:n,ms:Math.round(H()-e.fwRegAt)}),e.fwResolve(e.fwResult),e.fwResolve=null)}_rewoven(e){if(!e.fwResult)return e.fwPromise;if(!e.fwResult.woven&&!e.fwResult.confirmed)return Promise.resolve(e.fwResult);if(e.rwGone)return Promise.resolve(Object.freeze({woven:!1,confirmed:!1,reason:e.rwGone,ms:0}));if(e.rw)return this._restartRewoven(e),e.rw.promise;let t,n=new Promise(s=>{t=s}),r=H();return e.rw={promise:n,resolve:t,calledAt:r,at:r,stereo:!1,box:bn(e.canvas),gap:!1,boxFrame:null,callFrame:this._frameCount},n}_noteRewovenBox(e){let t=e.rw;if(!t)return;let n=bn(e.canvas);n!==t.box&&(t.box=n,this._restartRewoven(e))}_restartRewoven(e){e.rw&&(e.rw.at=H(),e.rw.stereo=!1,e.rw.gap=!1,e.rw.boxFrame=this._frameCount)}_settleRewoven(e,t,n,r=!1){let s=e.rw;s&&(this._noteWithheld(e,t,n,r),e.rw=null,s.resolve(Object.freeze({woven:t,confirmed:r,reason:n,ms:Math.round(H()-s.calledAt)})))}_rectCoverCheck(e){let t=e.rc,n=bn(e.canvas);if(n===t.box)return;let r=t.box===null,s=t.w,o=t.h;if(t.box=n,t.w=e.canvas.clientWidth||0,t.h=e.canvas.clientHeight||0,r)return;t.up&&this._placeCover(e);let a=e.fwResult;if(!a||e.rwGone||!(a.woven||a.confirmed))return;t.up||(t.snapped||(t.aspect=o>0?s/o:0),this._raiseCover(e)),t.cfg.snapshot&&!t.snapped&&t.w>0&&t.h>0&&(t.snapWanted=!0);let l;e.rw?(this._noteRewovenBox(e),l=e.rw.promise):(l=this._rewoven(e),e.rw&&(e.rw.boxFrame=this._frameCount)),t.waiting!==l&&(t.waiting=l,l.then(()=>{t.waiting===l&&(t.waiting=null,this._lowerCover(e))}))}_raiseCover(e){let t=e.rc;if(!t.el){if(typeof document>"u"||!document||typeof document.createElement!="function"||!e.canvas.parentElement)return;let n=document.createElement("canvas");n.setAttribute?.("aria-hidden","true"),n.dataset&&(n.dataset.inline3dCover="");let r=n.style;r.position="absolute",r.pointerEvents="none",r.margin="0",r.border="0",r.padding="0",r.background=t.cfg.color,r.display="none";try{let s=typeof getComputedStyle=="function"?getComputedStyle(e.canvas).zIndex:"auto";s&&s!=="auto"&&(r.zIndex=s)}catch{}t.el=n}this._placeCover(e),t.el.style.display="block",t.up=!0,this._fullTileWarned.add(t.el),this._applyExclusion(e,t.el)}_placeCover(e){let n=e.rc.el,r=e.canvas;if(!n)return;let s=r.parentElement;s&&(n.parentElement!==s||n.previousSibling!==r)&&s.insertBefore(n,r.nextSibling);let o=n.style;if(r.offsetParent)o.position="absolute",o.left=`${r.offsetLeft}px`,o.top=`${r.offsetTop}px`,o.width=`${r.offsetWidth}px`,o.height=`${r.offsetHeight}px`;else{let a=r.getBoundingClientRect();o.position="fixed",o.left=`${a.left??a.x??0}px`,o.top=`${a.top??a.y??0}px`,o.width=`${a.width}px`,o.height=`${a.height}px`}}_rectCoverSnap(e){let t=e.rc;t.snapWanted=!1;let n=t.el,r=e.canvas;if(!n||!t.up||!(r.width>1)||!(r.height>0))return;let s=Math.max(1,Math.round(t.w)),o=Math.max(1,Math.round(t.h)),a=s/o,l=t.aspect>0?t.aspect:r.width/2/r.height,c=1,h=1;a>l?h=l/a:c=a/l;let u=r.width/2*c,d=r.height*h,p=(r.width/2-u)/2,f=(r.height-d)/2;try{n.width=s,n.height=o;let g=n.getContext("2d");if(!g)return;g.drawImage(r,p,f,u,d,0,0,s,o),t.snapped=!0}catch{}}_lowerCover(e){let t=e.rc;t&&(t.up=!1,t.snapped=!1,t.snapWanted=!1,t.el&&(t.el.style.display="none",this._dropExclusion(e,t.el)))}_dropCover(e){let t=e.rc;t&&(t.waiting=null,this._lowerCover(e),t.el&&t.el.parentElement&&t.el.parentElement.removeChild(t.el),t.el=null)}_bindLifecycle(){typeof window>"u"||(this._onPageHide=()=>this._suspend(),this._onPageShow=e=>this._resume(!!(e&&e.persisted)),window.addEventListener("pagehide",this._onPageHide),window.addEventListener("pageshow",this._onPageShow),typeof document<"u"&&"onfreeze"in document&&(this._onFreeze=()=>this._suspend(),this._onResume=()=>this._resume(!0),document.addEventListener("freeze",this._onFreeze),document.addEventListener("resume",this._onResume)))}_unbindLifecycle(){typeof window>"u"||(this._onPageHide&&window.removeEventListener("pagehide",this._onPageHide),this._onPageShow&&window.removeEventListener("pageshow",this._onPageShow),this._onFreeze&&typeof document<"u"&&(document.removeEventListener("freeze",this._onFreeze),document.removeEventListener("resume",this._onResume)),this._onPageHide=this._onPageShow=this._onFreeze=this._onResume=null,this._frameWatchdog&&(clearTimeout(this._frameWatchdog),this._frameWatchdog=null))}_suspend(){if(!this._running||this._suspended)return;let e=[];for(let t of this._windows.values())t.layer&&(e.push(t),this._deactivate(t));this._suspended=e}_resume(e){if(!this._running)return;let t=this._suspended;if(this._suspended=null,t)for(let n of t)this._windows.has(n.canvas)&&(this._lazy&&this._observer?(this._observer.unobserve(n.observeEl),this._observer.observe(n.observeEl)):this._activate(n));this._lastChromeScan=0,this._scanChrome(),this._armDprWatch(),e&&this._watchForStalledFrames()}_watchForStalledFrames(){if(this._frameWatchdog||typeof setTimeout!="function")return;let e=this._frameCount;this._frameWatchdog=setTimeout(()=>{this._frameWatchdog=null,!(!this._running||this._frameCount!==e)&&this._requestFrame(!0)},1e3)}_teardown(){if(this._running){this._running=!1,J===this&&(J=null),this._unbindLifecycle(),this._disarmDprWatch(),this._disarmModeSwitchTick(),this._modeSwitch.cancel(),this._msArmedUp=!1,this._settlePendingDown("closed","the inline-3D session closed first"),this._observer&&this._observer.disconnect();for(let e of this._windows.values()){if(this._stopOverlayScan(e),this._stopSizeWatch(e),e.layer){try{e.layer.close()}catch{}e.layer=null}this._paintMono(e),this._notifyLayerLost(e),this._settleFirstWoven(e,!1,"session-ended"),this._dropCover(e),this._noteLayerFramed(e,!1)}this._windows.clear(),this._claims.clear(),this._setTrackingState("unknown"),this._displayListeners.clear()}}};function Xo(i){return typeof i=="number"&&Number.isFinite(i)&&i>=0?i:Sn}function Go(i){return typeof i!="string"?Promise.resolve(i):new Promise((e,t)=>{let n=new Image;n.decoding="async",n.onload=()=>e(n),n.onerror=t,n.src=i})}function ht(i,e,t,n,r,s,o,a,l,c,h,u){h>0&&i.roundRect?(i.save(),i.beginPath(),i.roundRect(o,a,l,c,h),i.clip(),i.drawImage(e,t,n,r,s,o,a,l,c),i.restore()):i.drawImage(e,t,n,r,s,o,a,l,c),u>0&&ar(i,o,a,l,c,u)}function qo(i,e,t,n,r,s,o,a,l){i.save(),a>0&&i.roundRect&&(i.beginPath(),i.roundRect(r,0,r,s,a),i.clip()),i.drawImage(e,0,0,t,n,r,0,r,s),o>0&&(i.globalAlpha=o,i.drawImage(e,t,0,t,n,r,0,r,s)),i.restore(),l>0&&ar(i,r,0,r,s,l)}function ar(i,e,t,n,r,s){let o=Math.min(s,Math.floor(Math.min(n,r)/2));if(o<=0)return;i.save(),i.globalCompositeOperation="destination-out";let a=[[e,t,n,o,[e,t],[e,t+o]],[e,t+r-o,n,o,[e,t+r],[e,t+r-o]],[e,t,o,r,[e,t],[e+o,t]],[e+n-o,t,o,r,[e+n,t],[e+n-o,t]]];for(let[l,c,h,u,d,p]of a){let f=i.createLinearGradient(d[0],d[1],p[0],p[1]);f.addColorStop(0,"rgba(0,0,0,1)"),f.addColorStop(1,"rgba(0,0,0,0)"),i.fillStyle=f,i.fillRect(l,c,h,u)}i.restore()}function Cn(i,e){return i>0&&e>0&&i/e>2.5}function q(i,e,t,n,r){let s=Math.abs(n||0),o=Math.min(i-2*s,e*t);o=Math.max(1,o);let a=Math.min(e,o/t);o=a*t;let l=(i-o)/2+(r===0?n:-n);return{sx:Math.max(0,Math.min(i-o,l)),sy:(e-a)/2,sw:o,sh:a}}function We(i,e,t){let n=Math.min(i,e*t),r=n/t;return{w:Math.max(2,Math.round(n/2)*2),h:Math.max(2,Math.round(r/2)*2)}}function ve(i,e){let t=i/2;return[{src:"R",sx:t,sw:t,sy:0,sh:e,dx:0,dw:t,mirror:!0},{src:"L",sx:0,sw:t,sy:0,sh:e,dx:t,dw:t,mirror:!0}]}function Rn(i,e,t){let n=new i.constructor(i.length);for(let r of ve(e,t))for(let s=0;s<t;s++)for(let o=0;o<r.dw;o++){let a=r.sx+(r.sw-1-o);n[s*e+r.dx+o]=i[s*e+a]}return n}function lr(i,e){return!(i>0)||!(e>0)||e>=180?null:i/2/Math.tan(e/2*Math.PI/180)}function dt({eyeWidthPx:i,hfovDeg:e,baselineMm:t,subjectZmm:n}){let r=lr(i,e);return r===null||!(t>0)||!(n>0)?0:r*t/(2*n)}function ft(i,e,t=.2){let n=Math.max(0,e*t);return Math.max(-n,Math.min(n,i||0))}function pt(i,e,t=.2){let n=i+t*(e-i);return Math.abs(e-n)<.05?e:n}function He(){let i={hello:null,subjectZmm:null,measuredPx:null,depth:0,current:0,target(e){let t=i.measuredPx!==null?i.measuredPx/2:i.hello&&i.subjectZmm?dt({eyeWidthPx:e,hfovDeg:i.hello.hfovDeg,baselineMm:i.hello.baselineMm,subjectZmm:i.subjectZmm}):0;return ft(t+i.depth*.05*e,e)},step(e){return i.current=pt(i.current,i.target(e)),i.current}};return i}var mt=1,kn="inline3d-call/1",gt=Object.freeze(["sbs","mono"]),ye=4,hr=4,Tn=5,ur=5,dr=10,fr=400,pr=1200,ee=.5,Yo=16*1024,mr=20,gr=40,cr=64,Ko=150,Jo=5e3,Zo=/^[A-Za-z0-9_-]{16,64}$/,Qo=16;function An(i){let e=new Uint8Array(Qo);return(i||(n=>globalThis.crypto.getRandomValues(n)))(e),vr(e)}function _r(i){let e=new Uint8Array(8);return(i||(n=>globalThis.crypto.getRandomValues(n)))(e),vr(e)}function vr(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",t="",n=0;for(;n+2<i.length;n+=3){let s=i[n]<<16|i[n+1]<<8|i[n+2];t+=e[s>>18&63]+e[s>>12&63]+e[s>>6&63]+e[s&63]}let r=i.length-n;if(r===1){let s=i[n]<<16;t+=e[s>>18&63]+e[s>>12&63]}else if(r===2){let s=i[n]<<16|i[n+1]<<8;t+=e[s>>18&63]+e[s>>12&63]+e[s>>6&63]}return t}function we(i){return typeof i=="string"&&Zo.test(i)}function $e(i){if(!i)return null;let e="";if(typeof i=="object")e=i.hash||i.href&&String(i.href).split("#")[1]||"";else{let t=String(i),n=t.indexOf("#");e=n>=0?t.slice(n+1):t.includes("=")&&!t.includes("://")?t:""}e=e.replace(/^#/,"");for(let t of e.split("&")){let n=t.indexOf("=");if(n<0||decodeURIComponent(t.slice(0,n))!=="room")continue;let r=decodeURIComponent(t.slice(n+1));return we(r)?r:null}return null}function _t(i,e){if(!we(e))throw new Error(`@displayxr/inline3d/call: invalid room id "${e}"`);return`${String(i||"").split("#")[0]}#room=${e}`}function On(i){if(!i||typeof i!="object"||i.type!=="hello")return null;let e=(t,n,r)=>typeof t=="number"&&Number.isFinite(t)&&t>=n&&t<=r?t:null;return{type:"hello",v:typeof i.v=="number"?i.v:mt,format:gt.includes(i.format)?i.format:"mono",width:e(i.width,1,16384),height:e(i.height,1,16384),baselineMm:e(i.baselineMm,1,1e3),hfovDeg:e(i.hfovDeg,5,170),rectified:i.rectified===!0,sdk:typeof i.sdk=="string"?i.sdk.slice(0,64):null,conv:i.conv===!0,name:U(i.name),content:i.content===!0}}function U(i){if(typeof i!="string")return null;let e=i.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g," ").replace(/\s+/g," ").trim();if(!e)return null;let t=Array.from(e);return t.length>cr?t.slice(0,cr).join("").trim():e}function Dn({format:i,width:e,height:t,baselineMm:n,hfovDeg:r,rectified:s,conv:o,name:a,content:l}={}){let c={type:"hello",v:mt,format:gt.includes(i)?i:"mono",width:e||0,height:t||0,rectified:!!s,sdk:kn};Number.isFinite(n)&&(c.baselineMm=n),Number.isFinite(r)&&(c.hfovDeg=r),c.format==="sbs"&&o&&(c.conv=!0);let h=U(a);return h&&(c.name=h),l&&(c.content=!0),c}var yr=16384;function vt({on:i=!0,format:e,width:t,height:n,convergence:r,appName:s}={}){if(!i)return{type:"content",on:!1};let o=gt.includes(e)?e:"sbs",a=d=>typeof d=="number"&&Number.isFinite(d)&&d>=1&&d<=yr?Math.round(d):0,l=!!(r&&r.known),c=l?r.frac:null,h={type:"content",on:!0,format:o,width:a(t),height:a(n),convergence:l?{known:!0,frac:typeof c=="number"&&Number.isFinite(c)?Math.max(-ee,Math.min(ee,c)):0}:{known:!1,frac:null}},u=U(s);return u&&(h.appName=u),h}function wr(i){if(!i||typeof i!="object"||i.type!=="content")return null;if(i.on!==!0)return{type:"content",on:!1,format:null,width:null,height:null,convergence:{known:!1,frac:null},appName:null};let e=n=>typeof n=="number"&&Number.isFinite(n)&&n>=1&&n<=yr?n:null,t={known:!1,frac:null};try{let n=i.convergence;n&&typeof n=="object"&&n.known===!0&&typeof n.frac=="number"&&Number.isFinite(n.frac)&&Math.abs(n.frac)<=ee&&(t={known:!0,frac:n.frac})}catch{}return{type:"content",on:!0,format:gt.includes(i.format)?i.format:"mono",width:e(i.width),height:e(i.height),convergence:t,appName:U(i.appName)}}function Pn(i){if(i===void 0||typeof i=="function")return null;let e;try{e=JSON.stringify({type:"app",d:i})}catch{return null}if(typeof e!="string")return null;let t=ea(e);return t>Yo?null:{json:e,bytes:t}}function br(i){return!i||typeof i!="object"||i.type!=="app"||!("d"in i)?null:{data:i.d}}function ea(i){if(typeof TextEncoder=="function")return new TextEncoder().encode(i).length;let e=0;for(let t of i){let n=t.codePointAt(0);e+=n<128?1:n<2048?2:n<65536?3:4}return e}function Ln(i,e=1e3){let t=[];return n=>{for(;t.length&&n-t[0]>=e;)t.shift();return t.length>=i?!1:(t.push(n),!0)}}function xr(i,e){let t={type:"conv",d:typeof i=="number"&&Number.isFinite(i)?Math.max(-ee,Math.min(ee,i)):null};return typeof e=="number"&&Number.isFinite(e)&&(t.c=Math.max(0,Math.min(1,e))),t}function Sr(i){if(!i||typeof i!="object"||i.type!=="conv")return null;let e=i.d;if(e!==null&&!(typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=ee))return null;let t={type:"conv",d:e};return typeof i.c=="number"&&Number.isFinite(i.c)&&(t.c=Math.max(0,Math.min(1,i.c))),t}function In(i){if(!i||i.type!=="hint")return null;let e=i.subjectZmm;return typeof e=="number"&&Number.isFinite(e)&&e>=Ko&&e<=Jo?{type:"hint",subjectZmm:e}:null}function Mr(i){return!i||i.type!=="state"?null:{type:"state",muted:i.muted===!0,cameraOff:i.cameraOff===!0,speaking:i.speaking===!0}}function Ue(i,e=0){let t=1e3/i-Math.max(0,e),n=-1/0;return r=>r-n<t?!1:(n=r,!0)}function Er(i){let e=[];i.forEach(h=>e.push(h));let t=h=>(h&&typeof i.get=="function"?i.get(h):e.find(u=>u.id===h))||null,n=e.find(h=>h.type==="transport"&&h.selectedCandidatePairId),r=n&&t(n.selectedCandidatePairId)||e.find(h=>h.type==="candidate-pair"&&h.selected)||e.find(h=>h.type==="candidate-pair"&&h.nominated&&h.state==="succeeded");if(!r)return{path:null,rttMs:null};let s=t(r.localCandidateId),o=t(r.remoteCandidateId),a=s?s.candidateType:null,l=a==="relay"||o&&o.candidateType==="relay"?"relay":["host","srflx","prflx"].includes(a)?a:null,c=typeof r.currentRoundTripTime=="number"?Math.round(r.currentRoundTripTime*1e3):null;return{path:l,rttMs:c}}function Fn({format:i,woven:e,mono3D:t="auto",lift:n=!1,overBudget:r=!1,failed:s=!1}){return(i==="sbs"?"sbs":"mono")==="sbs"?{route:e?"woven-sbs":"flat-left"}:e?t==="off"||t===!1?{route:"flat",mono3d:"off"}:n?s?{route:"flat",mono3d:"failed"}:r?{route:"flat",mono3d:"budget"}:{route:"lifted",mono3d:"lifted"}:{route:"flat",mono3d:"unavailable"}:{route:"flat"}}function Nn(i){return i==="woven-sbs"?"3D":i==="lifted"?"2D\u21923D":"2D"}function jn({need:i=10,needNoPose:e=30}={}){let t=0,n=0,r=!1;return{feed(s){return r?!0:(n++,s===null?r=n>=e:(t=s>=1?t+1:0,r=t>=i),r)},get live(){return r}}}function Ve(i,e){let t=Math.max(1,e|0),r=i==="sbs"?[6e3,4e3,3e3]:[2500,1800,1400];return r[Math.min(t,r.length)-1]}function Z(i,{baseMs:e=1e3,maxMs:t=3e4,rand:n=Math.random}={}){let r=Math.min(t,e*Math.pow(2,Math.max(0,i)));return Math.round(r*(.8+.4*n()))}var Be=Object.freeze(["VP9","VP8","AV1"]);function na(i,e=Be){let t=e.indexOf(String(i||"").toUpperCase());return t<0?e.length:t}function yt(i,e=Be){let t=n=>na(String(n.mimeType||"").split("/")[1],e);return i.map((n,r)=>({c:n,i:r,r:t(n)})).sort((n,r)=>n.r-r.r||n.i-r.i).map(n=>n.c)}function Xe(i,e=Be){if(!i)return i;let t=i.includes(`\r
17
17
  `)?`\r
18
18
  `:`
19
- `,i=n.split(t),r=i.findIndex(f=>f.startsWith("m=video"));if(r<0)return n;let s=i.findIndex((f,p)=>p>r&&f.startsWith("m="));s<0&&(s=i.length);let o=i.slice(r,s),a=new Map,l=new Map;for(let f of o){let p=f.match(/^a=rtpmap:(\d+) ([\w-]+)\//);p&&a.set(p[1],p[2].toUpperCase());let m=f.match(/^a=fmtp:(\d+) apt=(\d+)/);m&&(l.has(m[2])||l.set(m[2],[]),l.get(m[2]).push(m[1]))}let c=i[r].split(" "),h=c.slice(3),d=[];for(let f of e)for(let p of h)if(a.get(p)===f&&!d.includes(p)){d.push(p);for(let m of l.get(p)||[])h.includes(m)&&!d.includes(m)&&d.push(m)}if(!d.length)return n;let u=h.filter(f=>!d.includes(f));return i[r]=[...c.slice(0,3),...d,...u].join(" "),i.join(t)}var _r=Object.freeze([{urls:"stun:stun.l.google.com:19302"}]),Bo=4e3,Xo=1e4,Go=2e4,qo=8e3,Yo=1e4;function Be(n){let e=Number.isInteger(n)?n:ge;return Math.max(2,Math.min(nr,e))}function vr(n,e){return n<e}var Ve=class{constructor({signaling:e,id:t,maxPeers:i,iceServers:r,RTCPeerConnection:s,log:o,unreachableMs:a}={}){this.unreachableMs=a>0?a:Yo,this.signaling=e,this.id=t,this.maxPeers=Be(i),this.pageIce=r||null,this.iceServers=r||_r,this.PC=s||globalThis.RTCPeerConnection,this.log=o||(()=>{}),this.peers=new Map,this.session=null,this.ready=!1,this._pending=[],this.stopped=!1,this.sendFormat="mono",this.localStream=null}get size(){return this.peers.size}async start({room:e,localStream:t,sendFormat:i,onPeer:r,onPeerLeft:s,onStream:o,onMessage:a,onPeerState:l,onRefused:c,onSignalingState:h,onGhost:d}){this.localStream=t,this.sendFormat=i||"mono",this.cb={onPeer:r,onPeerLeft:s,onStream:o,onMessage:a,onPeerState:l,onRefused:c,onSignalingState:h,onGhost:d};let u=m=>(...w)=>this.ready?m(...w):this._pending.push(()=>m(...w));this.session=await this.signaling.join(e,{id:this.id,maxPeers:this.maxPeers,onPeerJoined:u(m=>this._onPeerJoined(m)),onPeerLeft:u(m=>this._onPeerLeftSignaling(m)),onSignal:u((m,w)=>this._onSignal(m,w)),onDisconnect:m=>h?.(m?"closed":"reconnecting",m),onPeerUnreachable:u(m=>d?.(m,!0)),onPeerReachable:u(m=>d?.(m,!1)),onReconnect:u(m=>{h?.("connected");for(let w of m)this._onPeerJoined(w)})}),!this.pageIce&&this.session.iceServers&&this.session.iceServers.length&&(this.iceServers=[..._r,...this.session.iceServers]);let f=this.session.peers||[];if(f.length>=this.maxPeers){this.session.leave();let m=new Error(`@displayxr/inline3d/call: this call is full (${this.maxPeers} participants)`);throw m.code="room-full",m}this.ready=!0;for(let m of f)this._onPeerJoined(m);let p=this._pending;this._pending=[];for(let m of p)m();return this.session}_onPeerJoined(e){if(this.stopped||e===this.id)return;let t=this.peers.get(e);if(t){t.absent=!1,t.state!=="connected"&&vr(this.id,e)&&this._rebuild(t,"rejoined");return}if(this.peers.size>=this.maxPeers-1){this.log("refused",{peer:e,reason:"maxPeers",maxPeers:this.maxPeers}),this.cb.onRefused?.(e);return}let i=this._newRecord(e);this.cb.onPeer?.(e),i.offerer?this._build(i,1):i.waitTimer=setTimeout(()=>this._askRestart(i),qo)}_onPeerLeftSignaling(e){let t=this.peers.get(e);t&&(t.absent=!0,t.state!=="connected"&&this._drop(t,"left"))}_newRecord(e){let t={id:e,offerer:vr(this.id,e),pc:null,builtAt:0,offerAt:0,dc:null,gen:0,state:"new",stream:null,attempts:0,iceRestarted:!1,absent:!1,pendingCandidates:[],timers:new Set,waitTimer:null,unreachable:!1,unreachTimer:null};return this.peers.set(e,t),this._armUnreachable(t),t}_build(e,t){this._closePc(e),e.gen=t,e.builtAt=Date.now(),e.iceRestarted=!1,e.pendingCandidates=[],e.stream=null;let i=new this.PC({iceServers:this.iceServers});e.pc=i;let r=i.createDataChannel("dxr-call",{negotiated:!0,id:0,ordered:!0});if(this._wireDc(e,r),e.offerer){let s=this.localStream?this.localStream.getTracks():[],o=s.find(h=>h.kind==="audio"),a=s.find(h=>h.kind==="video"),l=this.localStream?[this.localStream]:[];i.addTransceiver(o||"audio",{direction:"sendrecv",streams:l});let c=i.addTransceiver(a||"video",{direction:"sendrecv",streams:l});this._preferCodecs(c)}return i.onicecandidate=s=>{s.candidate&&this._signal(e,{kind:"candidate",candidate:s.candidate.toJSON?s.candidate.toJSON():s.candidate})},i.ontrack=s=>{if(e.stream||(e.stream=new MediaStream),!e.stream.getTracks().includes(s.track)){for(let o of e.stream.getTracks())o.kind===s.track.kind&&e.stream.removeTrack(o);e.stream.addTrack(s.track)}this.cb.onStream?.(e.id,e.stream)},i.onconnectionstatechange=()=>this._onConnState(e,i),this._arm(e,Go,()=>{e.pc===i&&i.connectionState!=="connected"&&this._fail(e,"connect-timeout")}),e.offerer&&this._offer(e).catch(s=>this.log("offer-error",{peer:e.id,err:String(s)})),this._setState(e,e.attempts>0?"reconnecting":"connecting"),i}async _offer(e,{iceRestart:t=!1}={}){let i=e.pc,r=await i.createOffer(t?{iceRestart:!0}:void 0);this._canPreferCodecs||(r.sdp=Ue(r.sdp)),await i.setLocalDescription(r),this._signal(e,{kind:"offer",sdp:i.localDescription.sdp})}async _onSignal(e,t){if(this.stopped||!t||typeof t!="object")return;let i=this.peers.get(e);if(!i&&(t.kind!=="offer"||(this._onPeerJoined(e),i=this.peers.get(e),!i)))return;let r=t.gen|0;try{switch(t.kind){case"offer":{if(i.offerer||(clearTimeout(i.waitTimer),r<i.gen))return;i.offerAt=Date.now(),(r>i.gen||!i.pc)&&this._build(i,r);let s=i.pc;await s.setRemoteDescription({type:"offer",sdp:t.sdp}),this._attachAnswererTracks(i);let o=await s.createAnswer();this._canPreferCodecs||(o.sdp=Ue(o.sdp)),await s.setLocalDescription(o),this._signal(i,{kind:"answer",sdp:s.localDescription.sdp}),this._flushCandidates(i);break}case"answer":if(!i.offerer||r!==i.gen||!i.pc||i.pc.signalingState!=="have-local-offer")return;await i.pc.setRemoteDescription({type:"answer",sdp:t.sdp}),this._flushCandidates(i);break;case"candidate":if(r!==i.gen||!i.pc)return;i.pc.remoteDescription?await i.pc.addIceCandidate(t.candidate).catch(()=>{}):i.pendingCandidates.push(t.candidate);break;case"restart":if(!i.offerer||i.pc&&i.state!=="connected"&&Date.now()-i.builtAt<5e3)return;this._rebuild(i,"peer-asked");break;case"bye":this._drop(i,"left");break}}catch(s){this.log("signal-error",{peer:e,kind:t.kind,err:String(s)})}}_flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let i of t)e.pc.addIceCandidate(i).catch(()=>{})}_attachAnswererTracks(e){let t=e.pc,i=this.localStream?this.localStream.getTracks():[];for(let r of t.getTransceivers()){let s=r.receiver&&r.receiver.track?r.receiver.track.kind:null;if(!s||r.sender.track)continue;let o=i.find(a=>a.kind===s);o&&(r.sender.replaceTrack(o).catch(()=>{}),this.localStream&&r.sender.setStreams&&r.sender.setStreams(this.localStream)),r.direction="sendrecv",s==="video"&&this._preferCodecs(r)}}_preferCodecs(e){let t=globalThis.RTCRtpReceiver&&RTCRtpReceiver.getCapabilities&&RTCRtpReceiver.getCapabilities("video");if(this._canPreferCodecs=!!(e&&e.setCodecPreferences&&t),!!this._canPreferCodecs)try{e.setCodecPreferences(ft(t.codecs))}catch{this._canPreferCodecs=!1}}_onConnState(e,t){if(e.pc!==t)return;let i=t.connectionState;this.log("pc-state",{peer:e.id,state:i,gen:e.gen}),i==="connected"?(this._clearTimers(e),e.attempts=0,e.iceRestarted=!1,this._setState(e,"connected"),this.tuneSenders()):i==="disconnected"?(this._setState(e,"reconnecting"),this._arm(e,Bo,()=>{e.pc===t&&t.connectionState!=="connected"&&this._fail(e,"disconnected")})):i==="failed"?this._fail(e,"failed"):i==="closed"&&!this.stopped&&this.peers.get(e.id)===e&&this._fail(e,"closed")}_fail(e,t){if(this.stopped||this.peers.get(e.id)!==e)return;if(e.absent)return this._drop(e,"left");if(this._setState(e,"reconnecting"),!e.offerer)return this._askRestart(e);let i=e.pc;if(i&&!e.iceRestarted&&i.connectionState!=="closed"&&i.signalingState!=="closed"){e.iceRestarted=!0,this.log("ice-restart",{peer:e.id,why:t,gen:e.gen}),this._offer(e,{iceRestart:!0}).catch(()=>this._rebuild(e,"ice-restart-failed")),this._arm(e,Xo,()=>{e.pc===i&&i.connectionState!=="connected"&&this._rebuild(e,"ice-restart-timeout")});return}this._rebuild(e,t)}_rebuild(e,t){if(this.stopped||this.peers.get(e.id)!==e)return;this._clearTimers(e),this._closePc(e),this._setState(e,"reconnecting");let i=K(e.attempts++);this.log("redial",{peer:e.id,why:t,attempt:e.attempts,inMs:i}),this._arm(e,i,()=>this._build(e,e.gen+1))}_askRestart(e){if(this.stopped||this.peers.get(e.id)!==e||e.offerer)return;let t=Date.now();this._signal(e,{kind:"restart"}),this._arm(e,Math.max(3e3,K(e.attempts++)),()=>{e.state!=="connected"&&!(e.offerAt>=t)&&this._askRestart(e)})}_drop(e,t){this.peers.get(e.id)===e&&(this._clearTimers(e),clearTimeout(e.unreachTimer),clearTimeout(e.waitTimer),this._closePc(e),this.peers.delete(e.id),this._setState(e,"left"),this.cb.onPeerLeft?.(e.id,t),this.tuneSenders())}_closePc(e){if(e.dc){try{e.dc.close()}catch{}e.dc=null}if(e.pc){let t=e.pc;e.pc=null;try{t.close()}catch{}}}_arm(e,t,i){let r=setTimeout(()=>{e.timers.delete(r),i()},t);e.timers.add(r)}_clearTimers(e){for(let t of e.timers)clearTimeout(t);e.timers.clear()}_armUnreachable(e){e.unreachTimer||e.unreachable||(e.unreachTimer=setTimeout(()=>{e.unreachTimer=null,!(this.stopped||this.peers.get(e.id)!==e||e.state==="connected")&&(e.unreachable=!0,this.log("unreachable",{peer:e.id,afterMs:this.unreachableMs,pc:e.pc?e.pc.iceConnectionState:null}),this._setState(e,"unreachable"))},this.unreachableMs))}_setState(e,t){t==="connected"?(clearTimeout(e.unreachTimer),e.unreachTimer=null,e.unreachable=!1):(t==="connecting"||t==="reconnecting")&&(e.unreachable?t="unreachable":this._armUnreachable(e)),e.state!==t&&(e.state=t,this.cb.onPeerState?.(e.id,t))}_signal(e,t){this.session?.send(e.id,{...t,gen:e.gen})}_wireDc(e,t){e.dc=t,t.onopen=()=>this.cb.onMessage?.(e.id,{type:"__open"}),t.onmessage=i=>{let r;try{r=JSON.parse(i.data)}catch{return}if(r&&r.type==="bye")return this._drop(e,"left");this.cb.onMessage?.(e.id,r)}}send(e,t){let i=this.peers.get(e);return i&&i.dc&&i.dc.readyState==="open"?(i.dc.send(JSON.stringify(t)),!0):!1}broadcast(e){for(let t of this.peers.keys())this.send(t,e)}sendRaw(e,t){let i=this.peers.get(e);return i&&i.dc&&i.dc.readyState==="open"?(i.dc.send(t),!0):!1}peerConnection(e){let t=this.peers.get(e);return t?t.pc:null}peerState(e){let t=this.peers.get(e);return t?t.state:null}async replaceTrack(e,t,i){i&&(this.localStream=i);for(let r of this.peers.values())if(r.pc)for(let s of r.pc.getTransceivers())(s.receiver&&s.receiver.track?s.receiver.track.kind:null)===e&&await s.sender.replaceTrack(t).catch(()=>{});await this.tuneSenders()}setSendFormat(e){return this.sendFormat=e,this.tuneSenders()}async tuneSenders(){let e=this.peers.size,t=dt(this.sendFormat,e);for(let i of this.peers.values())if(i.pc){for(let r of i.pc.getSenders())if(!(!r.track||r.track.kind!=="video"))try{let s=r.getParameters();s.degradationPreference="maintain-resolution",(!s.encodings||!s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=t*1e3,await r.setParameters(s)}catch(s){this.log("setParameters-error",{peer:i.id,err:String(s)})}}return t}stop(){if(!this.stopped){this.broadcast({type:"bye"}),this.stopped=!0;for(let e of this.peers.values())this._clearTimers(e),clearTimeout(e.waitTimer),clearTimeout(e.unreachTimer),this._signal(e,{kind:"bye"}),this._closePc(e);this.peers.clear();try{this.session?.leave()}catch{}}}_debugKill(e){let t=this.peers.get(e);return!t||!t.pc?!1:(this._closePc(t),this._fail(t,"debug-kill"),!0)}};var pt={width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},Ai={width:{ideal:3840},height:{ideal:1080},frameRate:{ideal:30}},Ko=Object.freeze({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0});function Jo(n){return!!n&&(n.name==="NotReadableError"||n.name==="TrackStartError"||/in use|busy/i.test(n.message||""))}function Zo(n){return!!n&&(n.name==="NotAllowedError"||n.name==="PermissionDeniedError"||n.name==="SecurityError")}function yr(n){let e=n.filter(t=>!t.excluded);return e.length&&e.every(t=>t.busy)?"camera-busy":e.some(t=>t.denied)?"permission-denied":"no-camera"}var Qo=/\b(hand[- ]?track|tracking camera|eye[- ]?track|depth camera)/i;function ea(n){if(n===!1)return()=>!1;let e=[Qo];for(let t of n==null?[]:Array.isArray(n)?n:[n])(t instanceof RegExp||typeof t=="string"&&t)&&e.push(t);return(t,i)=>{let r=String(t||"");for(let s of e)if(s instanceof RegExp){if(s.lastIndex=0,r&&s.test(r))return!0}else if(r&&r.toLowerCase().includes(s.toLowerCase())||i&&i===s)return!0;return!1}}function mt(n){return/stereo|\b3d\b|\bsbs\b|dual/i.test(n||"")}async function wr(n="auto",e={}){let t=e.mediaDevices||globalThis.navigator&&navigator.mediaDevices,i=e.log||(()=>{}),r=[],s=e.calibration||{},o=ea(e.exclude);if(n&&typeof n=="object"&&typeof n.getVideoTracks=="function"){let v=n.getVideoTracks()[0],b=v?v.getSettings():{},M=e.format==="sbs"?"sbs":"mono";return{stream:n,format:M,width:b.width||0,height:b.height||0,deviceId:b.deviceId||null,label:v?v.label:"",owned:!1,skipped:r,calibration:s}}if(!t||!t.getUserMedia)throw Object.assign(new Error("getUserMedia is not available (insecure context?)"),{code:"no-camera"});let a=async v=>{let b=await t.getUserMedia({video:v,audio:!1}),M=b.getVideoTracks()[0],g=M?M.getSettings():{};if(!M||M.readyState==="ended"||!(g.width>0)||!(g.height>0))throw b.getTracks().forEach(y=>y.stop()),Object.assign(new Error("the camera opened but delivers no picture (0x0)"),{name:"NotReadableError"});let S=g.displayxrStereo&&g.displayxrStereo.layout==="side-by-side"?g.displayxrStereo:null;return{stream:b,track:M,width:g.width,height:g.height,deviceId:g.deviceId||null,label:M.label||"",stereo:S}},l=(v,b)=>{r.push({label:v,error:`${b.name}: ${b.message}`,busy:Jo(b),denied:Zo(b)}),i("camera-skip",{label:v,error:b.name})},c=v=>v&&v.stream.getTracks().forEach(b=>b.stop()),h=new Set,d=(v,b)=>{b&&h.has(b)||(b&&h.add(b),r.push({label:v,error:"excluded",excluded:!0}),i("camera-skip",{label:v,error:"excluded"}))},u=v=>!v.label||!o(v.label,v.deviceId)?!1:(d(v.label,v.deviceId),!0),f=!1,p=async v=>{let b=await a(v);return o(b.label,b.deviceId)?(c(b),d(b.label,b.deviceId),f=!0,null):b},m=async(v,b)=>{try{await v.track.applyConstraints(b);let M=v.track.getSettings();if(M.width>0&&M.height>0)return{...v,width:M.width,height:M.height}}catch{}return v},w=v=>!!v&&(!!v.stereo||_i(v.width,v.height)),_=(v,b)=>({stream:v.stream,format:b,width:v.width,height:v.height,deviceId:v.deviceId,label:v.label,owned:!0,skipped:r,calibration:{rectified:!1,...b==="sbs"&&v.stereo?{rectified:!!v.stereo.rectified,...v.stereo.baselineMm>0?{baselineMm:v.stereo.baselineMm}:{},...v.stereo.horizontalFovDeg>0?{hfovDeg:v.stereo.horizontalFovDeg}:{}}:{},...s}});if(typeof n=="string"&&!["auto","stereo","mono"].includes(n)){let v;try{v=await a({deviceId:{exact:n},...Ai})}catch(b){throw l(n,b),Object.assign(new Error(`camera unavailable: ${b.message}`),{code:yr(r),skipped:r})}return w(v)?_(v,"sbs"):(c(v),_(await a({deviceId:{exact:n},...pt}),"mono"))}let x=new Set,R=async()=>{try{return(await t.enumerateDevices()).filter(v=>v.kind==="videoinput")}catch{return[]}},E=async v=>{for(let b of v){if(!b.deviceId||!mt(b.label)||x.has(b.deviceId)||(x.add(b.deviceId),u(b)))continue;let M=null;try{M=await a({deviceId:{exact:b.deviceId},...Ai})}catch(g){l(b.label,g);continue}if(w(M))return i("camera-sbs",{label:M.label,width:M.width,height:M.height,direct:!0}),M;c(M)}return null},C=null;if(n!=="mono"){let v=await R(),b=await E(v);if(b||v.some(M=>M.label)&&!v.some(M=>mt(M.label))&&(v=await R(),b=await E(v),b))return _(b,"sbs");if(v.length&&v.every(M=>!M.label)){let M=null;try{M=await p(!0)}catch(S){l("default",S)}if(M&&M.stereo)return _(M,"sbs");M&&M.deviceId&&x.add(M.deviceId);let g=await E(await R());if(g)return c(M),_(g,"sbs");if(M&&w(M))return _(M,"sbs");M&&(C=await m(M,pt))}}if(!C&&!f)try{C=await p(pt)}catch(v){l("default",v)}if(n==="mono"&&C)return _(C,"mono");if(C&&w(C))return _(C,"sbs");let k=[];try{k=(await t.enumerateDevices()).filter(v=>v.kind==="videoinput")}catch{}k.sort((v,b)=>Number(mt(b.label))-Number(mt(v.label)));for(let v of k){if(!v.deviceId||C&&v.deviceId===C.deviceId||x.has(v.deviceId)||h.has(v.deviceId)||u(v))continue;let b=null;try{b=await a({deviceId:{exact:v.deviceId},...Ai})}catch(M){l(v.label,M);continue}if(w(b)&&n!=="mono")return c(C),i("camera-sbs",{label:b.label,width:b.width,height:b.height}),_(b,"sbs");if(!C&&!w(b)){if(C=await m(b,pt),n==="mono")return _(C,"mono");continue}c(b)}if(C)return n==="stereo"&&i("camera-no-stereo",{fallback:C.label}),_(C,"mono");let T=yr(r);throw Object.assign(new Error(T==="camera-busy"?"camera unavailable: in use by another app (e.g. eye tracking) or unable to deliver a picture":T==="permission-denied"?"camera access was denied":"no camera could be opened"),{code:T,skipped:r})}async function Pi(n={}){let e=n.mediaDevices||globalThis.navigator&&navigator.mediaDevices;try{return(await e.getUserMedia({audio:{...Ko,...n.deviceId?{deviceId:{exact:n.deviceId}}:{}},video:!1})).getAudioTracks()[0]||null}catch(t){return(n.log||(()=>{}))("mic-skip",{error:t&&t.name}),null}}vt();Me();var Cr="http://displayxr.org/ns/stereo/1.0/",Et="http://ns.adobe.com/xap/1.0/\0";function Rt(n={}){let e=i=>typeof i=="number"&&Number.isFinite(i)?i:null,t=n.layout==="sbs"||n.layout==="side-by-side"?"sbs":"mono";return{layout:t,columns:t==="sbs"?2:1,rows:1,convergencePx:e(n.convergencePx),baselineMm:e(n.baselineMm),horizontalFovDeg:e(n.horizontalFovDeg),rectified:n.rectified===!0?!0:n.rectified===!1?!1:null,eyeWidth:e(n.eyeWidth),eyeHeight:e(n.eyeHeight),software:typeof n.software=="string"&&n.software?n.software:null}}var aa=n=>String(n).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),Ce=n=>Math.round(n*1e3)/1e3;function Rr(n){let e=Rt(n),t=[["Layout",e.layout==="sbs"?"side-by-side":"mono"],["Columns",e.columns],["Rows",e.rows],["ConvergencePx",e.convergencePx===null?null:Ce(e.convergencePx)],["BaselineMm",e.baselineMm===null?null:Ce(e.baselineMm)],["HorizontalFovDeg",e.horizontalFovDeg===null?null:Ce(e.horizontalFovDeg)],["Rectified",e.rectified===null?null:e.rectified?"True":"False"],["EyeWidth",e.eyeWidth],["EyeHeight",e.eyeHeight],["Software",e.software]].filter(([,i])=>i!=null).map(([i,r])=>` dxr:${i}="${aa(r)}"`).join("");return`<?xpacket begin="\uFEFF" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dxr="${Cr}"${t}/></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`}function Fi(n){if(typeof n!="string"||!n.includes(Cr))return null;let e=o=>{let a=new RegExp(`\\bdxr:${o}="([^"]*)"`).exec(n);if(a)return a[1];let l=new RegExp(`<dxr:${o}>([^<]*)</dxr:${o}>`).exec(n);return l?l[1]:null},t=o=>{let a=e(o);return a===null||a===""||!Number.isFinite(+a)?null:+a},i=e("Rectified"),r=e("Layout"),s=e("Software");return Rt({layout:r==="side-by-side"||r==="sbs"?"sbs":"mono",convergencePx:t("ConvergencePx"),baselineMm:t("BaselineMm"),horizontalFovDeg:t("HorizontalFovDeg"),rectified:i===null?null:/^true$/i.test(i),eyeWidth:t("EyeWidth"),eyeHeight:t("EyeHeight"),software:s===null?null:s.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&amp;/g,"&")})}var Ct=n=>new TextEncoder().encode(n),Ii=n=>new TextDecoder().decode(n),kr=n=>n.length>4&&n[0]===255&&n[1]===216;function*Tr(n){let e=2;for(;e+4<=n.length;){if(n[e]!==255)return;let t=n[e+1];if(t===216||t>=208&&t<=215||t===1||t===255){e+=t===255?1:2;continue}if(t===218||t===217)return;let i=n[e+2]<<8|n[e+3];if(i<2||e+2+i>n.length)return;yield{marker:t,start:e,end:e+2+i,data:n.subarray(e+4,e+2+i)},e+=2+i}}function Or(n,e){if(n.length<e.length)return!1;for(let t=0;t<e.length;t++)if(n[t]!==e.charCodeAt(t))return!1;return!0}function Ar(n,e){if(!kr(n))throw new TypeError("jpegWithXmp: not a JPEG");let t=new Uint8Array([...Ct(Et),...Ct(e)]),i=t.length+2;if(i>65535)throw new RangeError("jpegWithXmp: XMP packet too large for one APP1 segment");let r=new Uint8Array(4+t.length);r[0]=255,r[1]=225,r[2]=i>>8,r[3]=i&255,r.set(t,4);let s=2,o=null;for(let h of Tr(n)){if(h.marker===225&&Or(h.data,Et)){o=h;break}if(h.marker===224||h.marker===225)s=h.end;else break}let[a,l]=o?[o.start,o.end]:[s,s],c=new Uint8Array(n.length-(l-a)+r.length);return c.set(n.subarray(0,a),0),c.set(r,a),c.set(n.subarray(l),a+r.length),c}function Ni(n){if(!kr(n))return null;for(let e of Tr(n))if(e.marker===225&&Or(e.data,Et))return Ii(e.data.subarray(Et.length));return null}var Pr=n=>Fi(Ni(n)),U={EBML:440786851,Segment:408125543,Tags:307544935,Tag:29555,Targets:25536,SimpleTag:26568,TagName:17827,TagString:17543},la=n=>n.length>4&&n[0]===26&&n[1]===69&&n[2]===223&&n[3]===163;function Dr(n){let e=[];for(let t=n;t>0;t=Math.floor(t/256))e.unshift(t%256);return e}function Lr(n,e=0){let t=e;if(!t)for(t=1;t<8&&n>2**(7*t)-2;t++);let i=new Array(t).fill(0),r=n;for(let s=t-1;s>=1;s--)i[s]=r%256,r=Math.floor(r/256);return i[0]=128>>t-1|r,i}function ji(n,e){let t=n[e],i=t>=128?1:t>=64?2:t>=32?3:t>=16?4:0;if(!i||e+i>n.length)return null;let r=0;for(let s=0;s<i;s++)r=r*256+n[e+s];return{id:r,width:i}}function Xe(n,e){let t=n[e],i=1;for(;i<=8&&!(t&128>>i-1);)i++;if(i>8||e+i>n.length)return null;let r=t&255>>i,s=r===127>>i-1;for(let o=1;o<i;o++)r=r*256+n[e+o],n[e+o]!==255&&(s=!1);return{size:r,width:i,unknown:s}}function Ee(n,e){return[...Dr(n),...Lr(e.length),...e]}function ca(n){let e=[];for(let[i,r]of Object.entries(n))r!=null&&e.push(...Ee(U.SimpleTag,[...Ee(U.TagName,[...Ct(String(i))]),...Ee(U.TagString,[...Ct(String(r))])]));let t=Ee(U.Tag,[...Ee(U.Targets,[]),...e]);return new Uint8Array(Ee(U.Tags,t))}function Ir(n){let e=Rt(n);return{DXR_LAYOUT:e.layout==="sbs"?"side-by-side":"mono",DXR_COLUMNS:String(e.columns),DXR_ROWS:String(e.rows),DXR_CONVERGENCE_PX:e.convergencePx===null?null:String(Ce(e.convergencePx)),DXR_BASELINE_MM:e.baselineMm===null?null:String(Ce(e.baselineMm)),DXR_HFOV_DEG:e.horizontalFovDeg===null?null:String(Ce(e.horizontalFovDeg)),DXR_RECTIFIED:e.rectified===null?null:e.rectified?"true":"false",DXR_EYE_WIDTH:e.eyeWidth===null?null:String(e.eyeWidth),DXR_EYE_HEIGHT:e.eyeHeight===null?null:String(e.eyeHeight),DXR_SOFTWARE:e.software}}function ha(n){if(!n||!("DXR_LAYOUT"in n))return null;let e=t=>n[t]===void 0||n[t]===""||!Number.isFinite(+n[t])?null:+n[t];return Rt({layout:n.DXR_LAYOUT==="side-by-side"?"sbs":"mono",convergencePx:e("DXR_CONVERGENCE_PX"),baselineMm:e("DXR_BASELINE_MM"),horizontalFovDeg:e("DXR_HFOV_DEG"),rectified:n.DXR_RECTIFIED===void 0?null:n.DXR_RECTIFIED==="true",eyeWidth:e("DXR_EYE_WIDTH"),eyeHeight:e("DXR_EYE_HEIGHT"),software:n.DXR_SOFTWARE??null})}function Fr(n){if(!la(n))return null;let e=Xe(n,4);if(!e)return null;let t=4+e.width+e.size;for(;t<n.length;){let i=ji(n,t);if(!i)return null;let r=Xe(n,t+i.width);if(!r)return null;let s=t+i.width+r.width;if(i.id===U.Segment)return{sizeAt:t+i.width,sizeWidth:r.width,unknown:r.unknown,dataStart:s,size:r.size};if(r.unknown)return null;t=s+r.size}return null}function Nr(n,e){let t=Fr(n);if(!t)throw new TypeError("webmWithTags: not a WebM/Matroska file (no Segment)");let i=ca(e);if(t.unknown){let h=new Uint8Array(n.length+i.length);return h.set(n,0),h.set(i,n.length),h}let r=Math.min(n.length,t.dataStart+t.size),s=r-t.dataStart+i.length,o=s<=2**(7*t.sizeWidth)-2,a=Lr(s,o?t.sizeWidth:8),l=new Uint8Array(t.sizeAt+a.length+(r-t.dataStart)+i.length+(n.length-r));l.set(n.subarray(0,t.sizeAt),0),l.set(a,t.sizeAt);let c=t.sizeAt+a.length;return l.set(n.subarray(t.dataStart,r),c),c+=r-t.dataStart,l.set(i,c),c+=i.length,l.set(n.subarray(r),c),l}function jr(n,e,t){let i={},r=(s,o,a)=>{let l=s;for(;l<o;){let c=ji(n,l);if(!c)return;let h=Xe(n,l+c.width);if(!h||h.unknown)return;let d=l+c.width+h.width;a(c.id,d,Math.min(o,d+h.size)),l=d+h.size}};return r(e,t,(s,o,a)=>{s===U.Tag&&r(o,a,(l,c,h)=>{if(l!==U.SimpleTag)return;let d=null,u=null;r(c,h,(f,p,m)=>{f===U.TagName?d=Ii(n.subarray(p,m)):f===U.TagString&&(u=Ii(n.subarray(p,m)))}),d!==null&&(i[d]=u??"")})}),i}function ua(n){let e=Fr(n);if(!e)return null;let t=e.unknown?n.length:Math.min(n.length,e.dataStart+e.size),i=null,r=e.dataStart;for(;r<t;){let s=ji(n,r);if(!s)break;let o=Xe(n,r+s.width);if(!o)break;let a=r+s.width+o.width;if(s.id===U.Tags&&!o.unknown&&(i={...i||{},...jr(n,a,Math.min(t,a+o.size))}),o.unknown){i=i||da(n,t);break}r=a+o.size}return i}function da(n,e){let t=Dr(U.Tags);for(let i=e-t.length-1;i>=0;i--){if(n[i]!==t[0]||n[i+1]!==t[1]||n[i+2]!==t[2]||n[i+3]!==t[3])continue;let r=Xe(n,i+4);if(r&&!r.unknown&&i+4+r.width+r.size===e)return jr(n,i+4+r.width,e)}return null}var zr=n=>ha(ua(n));var ae="[inline3d/camera]",Rs="inline3d-camera/1",Da=200,La=240,Ia=66,Fa=4e3,Na=4,ja=1500,za=2e4,Wa=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"],zt=()=>typeof document<"u"&&document&&typeof document.createElement=="function",Es=()=>{let n=new Date,e=t=>String(t).padStart(2,"0");return`${n.getFullYear()}${e(n.getMonth()+1)}${e(n.getDate())}-${e(n.getHours())}${e(n.getMinutes())}${e(n.getSeconds())}`},Ha=n=>/jpe?g/.test(n)?"jpg":/png/.test(n)?"png":/webp/.test(n)?"webp":/mp4/.test(n)?"mp4":/webm/.test(n)?"webm":"bin";function Wt(n,e,t){return`${String(n||"capture").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"capture"}${e==="sbs"?"_2x1":""}.${Ha(t)}`}var te=(n,e,t={})=>Object.assign(new Error(`${ae} ${n}`),{code:e,...t});function Cs(n,e=Fa){return n?(n.readyState||0)>=2&&n.videoWidth?Promise.resolve():new Promise((t,i)=>{let r=!1,s=()=>{r||(n.readyState||0)<2||!n.videoWidth||(r=!0,clearTimeout(o),n.removeEventListener("loadeddata",s),n.removeEventListener("playing",s),n.removeEventListener("resize",s),t())},o=setTimeout(()=>{r||(r=!0,i(te("the camera delivered no frame in time","no-frame")))},e);n.addEventListener("loadeddata",s),n.addEventListener("playing",s),n.addEventListener("resize",s),n.play?.().catch(()=>{})}):Promise.reject(te("no video element (no document?)","no-frame"))}function ks(n,e,t=La){let i=n.videoWidth,r=n.videoHeight;if(!i||!r||(n.readyState||0)<2)return null;let s=Math.min(1,t/(i/2)),o=Math.max(2,Math.round(i*s/2)*2),a=Math.max(2,Math.round(r*s));(e.width!==o||e.height!==a)&&(e.width=o,e.height=a);let l=e.getContext("2d",{willReadFrequently:!0});try{return l.drawImage(n,0,0,o,a),{img:_t(l.getImageData(0,0,o,a).data,o*a),w:o,h:a,scale:o/i}}catch{return null}}var an=class{constructor(e,{log:t=null}={}){this.format=e.format,this.stream=e.stream,this.width=e.width||0,this.height=e.height||0,this.deviceId=e.deviceId||null,this.label=e.label||"",this.owned=!!e.owned,this.skipped=Object.freeze([...e.skipped||[]]),this.calibration=Object.freeze({...e.calibration||{}});let i=this.calibration;this.stereo=this.format==="sbs"?Object.freeze({rectified:!!i.rectified,baselineMm:i.baselineMm>0?i.baselineMm:null,horizontalFovDeg:i.hfovDeg>0?i.hfovDeg:null}):null,this.state="live",this._log=t,this._listeners=new Map,this._scratch=null,this._views=new Set,this.video=null,zt()&&(this.video=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,autoplay:!0}),this.video.srcObject=this.stream,this.video.play?.().catch(()=>{})),this._onEnded=()=>this._ended("ended");for(let r of this.stream.getVideoTracks())r.addEventListener?.("ended",this._onEnded)}get facing(){try{let e=this.stream.getVideoTracks()[0]?.getSettings?.().facingMode;return typeof e=="string"&&e?e:null}catch{return null}}get eyeWidth(){return this.format==="sbs"?this.width/2:this.width}log(e,t={}){this._log&&this._log(e,t)}on(e,t){if(typeof t!="function")throw new TypeError(`${ae} on() takes a function`);return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e,t){for(let i of[...this._listeners.get(e)||[]])try{i(t)}catch(r){console.error(`${ae} '${e}' listener threw`,r)}}_ended(e){this.state==="live"&&(this.state="ended",this.log("ended",{reason:e}),this._emit("ended",{reason:e}))}async measureConvergence(){if(this.format!=="sbs"||!this.video||!zt())return null;try{await Cs(this.video)}catch{return null}this._scratch=this._scratch||document.createElement("canvas");let e=ks(this.video,this._scratch);if(!e)return null;let t=se().measure(e.img,e.w,e.h,0);return t?t.d/e.scale:null}_meta(e,t=this.width,i=this.height){let r=this.stereo;return{layout:this.format,convergencePx:e,baselineMm:r?r.baselineMm:null,horizontalFovDeg:r?r.horizontalFovDeg:null,rectified:r?r.rectified:null,eyeWidth:this.format==="sbs"?t/2:t,eyeHeight:i,software:Rs}}async capturePhoto({type:e="image/jpeg",quality:t=.92,name:i,convergencePx:r}={}){if(this.state==="closed")throw te("the camera is closed","closed");if(!this.video||!zt())throw te("capturePhoto needs a document","no-frame");await Cs(this.video);let s=this.video.videoWidth,o=this.video.videoHeight,a=typeof r=="number"&&Number.isFinite(r)?r:await this.measureConvergence(),l=document.createElement("canvas");l.width=s,l.height=o,l.getContext("2d").drawImage(this.video,0,0,s,o);let c=await new Promise((f,p)=>l.toBlob(m=>m?f(m):p(te("toBlob produced nothing","encode-failed")),e,t)),h=this._meta(a,s,o),d=null;(c.type==="image/jpeg"||/jpe?g/.test(e))&&(d=Rr(h),c=new Blob([Ar(new Uint8Array(await c.arrayBuffer()),d)],{type:"image/jpeg"}));let u={blob:c,type:c.type||e,width:s,height:o,layout:this.format,convergencePx:a,stereo:this.stereo,suggestedName:Wt(i||`photo-${Es()}`,this.format,c.type||e),xmp:d};return this.log("photo",{width:s,height:o,layout:this.format,convergencePx:a,bytes:c.size,name:u.suggestedName}),u}record({mimeType:e,mono:t=!1,audio:i=null,videoBitsPerSecond:r,timesliceMs:s=1e3,name:o,fps:a=30}={}){if(this.state==="closed")throw te("the camera is closed","closed");if(typeof MediaRecorder!="function")throw te("MediaRecorder is not available here","unsupported");let l=e||Wa.find(g=>typeof MediaRecorder.isTypeSupported!="function"||MediaRecorder.isTypeSupported(g))||"";if(l&&typeof MediaRecorder.isTypeSupported=="function"&&!MediaRecorder.isTypeSupported(l))throw te(`${l} is not a supported recording type here`,"unsupported");let c=[...this.stream.getVideoTracks()],h=i&&typeof i.getAudioTracks=="function"?i.getAudioTracks():i&&i.kind==="audio"?[i]:[];c.push(...h);let d=new MediaStream(c),u={...l?{mimeType:l}:{},...r?{videoBitsPerSecond:r}:{}},f=new MediaRecorder(d,u),p=[];f.ondataavailable=g=>g.data&&g.data.size&&p.push(g.data);let m=null,w=[],_=null,x=0,R=!!t&&this.format==="sbs"&&zt()&&this.video;if(R){_=document.createElement("canvas");let g=()=>{x=requestAnimationFrame(g);let y=this.video,O=y.videoWidth,I=y.videoHeight;!O||!I||(y.readyState||0)<2||((_.width!==O/2||_.height!==I)&&(_.width=O/2,_.height=I),_.getContext("2d").drawImage(y,0,0,O/2,I,0,0,O/2,I))};g();let S=_.captureStream(a);for(let y of h)S.addTrack(y);m=new MediaRecorder(S,u),m.ondataavailable=y=>y.data&&y.data.size&&w.push(y.data)}let E=performance.now(),C=[],k=this.format==="sbs"?setInterval(()=>this.measureConvergence().then(g=>g!==null&&C.push(g)),1500):0;this.measureConvergence().then(g=>g!==null&&C.push(g)),f.start(s),m?.start(s),this.log("record-start",{mimeType:l,mono:R,audio:h.length});let T=(g,S)=>new Promise(y=>{if(!g||g.state==="inactive")return y(S);g.onstop=()=>y(S),g.stop()}),v=o||`clip-${Es()}`,b=this;return{get state(){return f.state},get mimeType(){return f.mimeType||l},pause(){f.state==="recording"&&f.pause(),m&&m.state==="recording"&&m.pause()},resume(){f.state==="paused"&&f.resume(),m&&m.state==="paused"&&m.resume()},async stop(){clearInterval(k),x&&cancelAnimationFrame(x);let[g,S]=await Promise.all([T(f,p),T(m,w)]),y=f.mimeType||l||g[0]&&g[0].type||"video/webm",O=[...C].sort((Pe,q)=>Pe-q),I=O.length?O[Math.floor(O.length/2)]:null,P=b._meta(I),N=/webm|matroska/.test(y),$=async(Pe,q)=>{let ne=new Blob(Pe,{type:y});if(N&&ne.size)try{ne=new Blob([Nr(new Uint8Array(await ne.arrayBuffer()),Ir({...P,layout:q}))],{type:y})}catch(Mn){b.log("record-tag-failed",{message:String(Mn&&Mn.message)})}return ne},L=await $(g,b.format),z={blob:L,type:y,layout:b.format,durationMs:Math.round(performance.now()-E),convergencePx:I,stereo:b.stereo,suggestedName:Wt(v,b.format,y),tagged:N&&L.size>0};return m&&(z.mono=await $(S,"mono"),z.monoSuggestedName=Wt(v,"mono",y)),b.log("record-stop",{bytes:L.size,mono:z.mono?z.mono.size:null,ms:z.durationMs,convergencePx:I,name:z.suggestedName}),z}}}close(){if(this.state!=="closed"){this.state="closed";for(let e of this.stream.getVideoTracks())e.removeEventListener?.("ended",this._onEnded);for(let e of[...this._views])e.remove();this.owned&&this.stream.getTracks().forEach(e=>e.stop()),this.video&&(this.video.srcObject=null),this.log("closed",{})}}};async function cn(n={}){let e=typeof n=="string"||n&&typeof n.getVideoTracks=="function"?{prefer:n}:n||{},t=e.prefer===void 0||e.prefer===null?"auto":e.prefer,i=typeof e.log=="function"?e.log:e.debug?(a,l)=>console.log(`${ae} ${a} ${JSON.stringify(l)}`):null,r=e.calibration&&typeof e.calibration=="object"?{...e.calibration}:{};r.horizontalFovDeg>0&&!(r.hfovDeg>0)&&(r.hfovDeg=r.horizontalFovDeg),delete r.horizontalFovDeg;let s=await wr(t,{format:e.format,calibration:r,mediaDevices:e.mediaDevices,log:i||void 0,exclude:e.exclude});if(s.format==="sbs"&&typeof e.rectify=="function")try{let a=await e.rectify(s.stream,{width:s.width,height:s.height,deviceId:s.deviceId,label:s.label});a&&typeof a.getVideoTracks=="function"&&(s.stream=a,s.calibration={...s.calibration,rectified:!0})}catch(a){i?.("rectify-failed",{message:String(a&&a.message)}),s.rectifyError=a}let o=new an(s,{log:i});return s.rectifyError&&(o.rectifyError=s.rectifyError),o.log("open",{format:o.format,width:o.width,height:o.height,label:o.label,stereo:o.stereo,skipped:o.skipped.length}),o}var Ht=n=>!!n&&typeof n=="object"&&typeof n.capturePhoto=="function"&&typeof n.record=="function"&&n.stream&&typeof n.stream.getVideoTracks=="function";function $a(n){let e=Math.min(globalThis.devicePixelRatio||1,2),t=Math.round((n.clientWidth||0)*e),i=Math.round((n.clientHeight||0)*e);return!t||!i?!1:((n.width!==t||n.height!==i)&&(n.width=t,n.height=i),!0)}function hn(n,e,t,i={}){if(!e||typeof e.getContext!="function")throw new TypeError(`${ae} addCameraView(wall, canvas, cam, opts) needs a canvas`);if(!Ht(t))throw new TypeError(`${ae} addCameraView: cam must be a StereoCamera from openCamera()`);let r=new ln(n,e,t,i);return t._views?.add(r),r}var ln=class{constructor(e,t,i,r){this.wall=e||null,this.canvas=t,this.cam=i,this.mirror=r.mirror===void 0?i.facing!=="environment":!!r.mirror,this.aspect=r.aspect==="fill"?"fill":typeof r.aspect=="number"&&r.aspect>.3&&r.aspect<4?r.aspect:16/9,this.rectCover=r.rectCover,this.autoConverge=!!r.autoConverge,this.conv=ze(),this.conv.depth=0,this.setDepth(r.depth),this.route=null,this.handle=null,this.fallbackReason=null,this._fw=null,this._onRouteChange=typeof r.onRouteChange=="function"?r.onRouteChange:null,this._layerFails=0,this._layerTimer=0,this.buffer=null,this.removed=!1,this._raf=0,this._loop=r._loop!==!1,this._autoAt=0,this._track=we(),this._focus=se(),this._scratch=null,this._luma=null,this.disparityPx=null,this._cursorOpt=Mt(r.cursor,"@displayxr/inline3d/camera"),this.cursor=null,this._cursorOpt&&Promise.resolve().then(()=>(on(),sn)).then(s=>{this.removed||(this.cursor=new s.PairCursor(this.canvas,this._cursorOpt))}),this._reroute(!1),this._loop&&this._start()}get woven(){return this.route==="woven-sbs"}weaveState(){return{route:this.route,woven:this.woven,reason:this.fallbackReason,firstWoven:this.route==="woven-sbs"?this._fw?{...this._fw}:"pending":null,layerRetries:this._layerFails}}get convergencePx(){return this.conv.current}get depth(){return this.conv.depth}setDepth(e){let t=e==null||!Number.isFinite(+e)?0:Math.max(-1,Math.min(1,+e));return this.conv.depth=t,t}setMirror(e){return this.mirror=e===void 0?!this.mirror:!!e,this.mirror}setAutoConverge(e){return this.autoConverge=e===void 0?!this.autoConverge:!!e,this.autoConverge||(this._track.reset(),this._focus.reset(),this.conv.measuredPx=null,this.disparityPx=null),this.autoConverge}_reroute(e,t){if(t!==void 0&&(this.wall=t),this.removed)return;e&&this.fallbackReason&&(this.fallbackReason=null,clearTimeout(this._layerTimer),this._layerTimer=0);let i=this.cam,r=i.state==="live"&&i.video,o=i.format==="sbs"&&r&&this.wall&&this.wall.supported&&!this.fallbackReason?"woven-sbs":i.format==="sbs"?"flat-left":"flat";if(!e&&o===this.route)return;let a=this.route;this._unregister(),this.route=o,o==="woven-sbs"&&this._registerWoven(),o!==a&&this._routeChanged()}_registerWoven(){this.buffer||(this.buffer=document.createElement("canvas")),this._paintWoven();let e=this.rectCover===void 0?this.wall.addImage(this.canvas,this.buffer):this.wall.addImage(this.canvas,this.buffer,{rectCover:this.rectCover});this.handle=e,this._fw=null;let t=e&&e.firstWoven;!t||typeof t.then!="function"||t.then(i=>{this.handle!==e||this.removed||!i||(this._fw={woven:!!i.woven,confirmed:!!i.confirmed,reason:i.reason||null,ms:i.ms},this.cam.log?.("view-first-woven",{woven:!!i.woven,reason:i.reason||null}),i.woven?(this._layerFails=0,this._routeChanged()):i.reason!=="removed"&&this._layerLost(i.reason||"layer-failed"))})}_layerLost(e){if(this.fallbackReason=e,this._reroute(!1),e!=="layer-failed"||this._layerFails>=Na)return;let t=Math.min(za,ja*Math.pow(2,this._layerFails++));this.cam.log?.("view-layer-retry",{attempt:this._layerFails,inMs:t}),clearTimeout(this._layerTimer),this._layerTimer=setTimeout(()=>{this._layerTimer=0,!(this.removed||this.fallbackReason!==e)&&this._reroute(!0)},t)}_routeChanged(){if(this._onRouteChange)try{this._onRouteChange(this.route,this.weaveState())}catch(e){console.error(`${ae} onRouteChange threw`,e)}}_onWallLost(){this._reroute(!0,{supported:!1})}_unregister(){if(this.handle){try{this.handle.remove()}catch{}this.handle=null}}_start(){let e=()=>{this._raf=requestAnimationFrame(e),this.paint()};this._raf=requestAnimationFrame(e)}paint(){if(this.removed)return;let e=this.cam.video;!e||this.cam.state==="closed"||(this.route==="woven-sbs"?this._paintWoven():this._paintFlat(e))}_paintFlat(e){if(this.cursor?.idle(),!$a(this.canvas))return;let t=e.videoWidth,i=e.videoHeight;if(!t||!i||(e.readyState||0)<2)return;let r=this.canvas.getContext("2d"),s=this.route==="flat-left"?t/2:t,o=G(s,i,this.canvas.width/this.canvas.height,0,0);r.save(),this.mirror&&(r.translate(this.canvas.width,0),r.scale(-1,1)),r.drawImage(e,o.sx,o.sy,o.sw,o.sh,0,0,this.canvas.width,this.canvas.height),r.restore()}_paintWoven(){let e=this.cam.video,t=e.videoWidth,i=e.videoHeight;if(!t||!i||(e.readyState||0)<2||!this.buffer)return;let r=t/2,s=this._eyeAspect(),{w:o,h:a}=je(r,i,s),l=this.buffer;(l.width!==2*o||l.height!==a)&&(l.width=2*o,l.height=a);let c=!!(this.cursor&&this.cursor.hovering);(this.autoConverge||c)&&this._sample(e,c);let h=this.conv.step(r),d=l.getContext("2d");if(this.mirror)for(let u of me(t,i)){let f=u.src==="L"?0:1,p=G(r,i,s,h,f),m=u.dx===0?0:o;d.save(),d.translate(m+o,0),d.scale(-1,1),d.drawImage(e,u.sx+p.sx,p.sy,p.sw,p.sh,0,0,o,a),d.restore()}else for(let u of[0,1]){let f=G(r,i,s,h,u);d.drawImage(e,u*r+f.sx,f.sy,f.sw,f.sh,u*o,0,o,a)}if(this.cursor){let u={rL:G(r,i,s,h,0),rR:G(r,i,s,h,1),outW:o,outH:a,mirror:this.mirror,handle:this.handle};this.cursor.draw(d,this._luma,u,performance.now()/1e3)}}_eyeAspect(){if(this.aspect!=="fill")return this.aspect;let e=this.canvas.clientWidth||0,t=this.canvas.clientHeight||0;return e>0&&t>0&&(this._fillAspect=Math.max(.3,Math.min(4,e/t))),this._fillAspect||16/9}_sample(e,t=!1){let i=performance.now();if(i-this._autoAt<(t?Ia:Da))return;this._autoAt=i,this._scratch=this._scratch||document.createElement("canvas");let r=ks(e,this._scratch);if(r&&(this._luma=r),!this.autoConverge)return;let s=r?this._focus.measure(r.img,r.w,r.h,i):null,o=this._track.push(s?s.d/r.scale:null);this.conv.measuredPx=o,this.disparityPx=o}remove(){this.removed||(this.removed=!0,this._raf&&cancelAnimationFrame(this._raf),this._raf=0,clearTimeout(this._layerTimer),this._layerTimer=0,this._unregister(),this.cursor?.dispose(),this.cursor=null,this.cam._views?.delete(this))}};var Os=[[-1,7,10,15,20,26,18,20,24,30,18],[-1,10,16,26,18,24,16,18,22,22,26]],As=[[-1,1,1,1,1,1,2,2,2,2,4],[-1,1,1,1,2,2,4,4,4,5,5]],Ua=[1,0],un=10;function Ps(n){let e=(16*n+128)*n+64;if(n>=2){let t=Math.floor(n/7)+2;e-=(25*t-10)*t-55,n>=7&&(e-=36)}return e}var Ts=(n,e)=>Math.floor(Ps(n)/8)-Os[e][n]*As[e][n];function dn(n,e){let t=0;for(let i=7;i>=0;i--)t=t<<1^(t>>>7)*285,t^=(e>>>i&1)*n;return t}function Va(n){let e=new Array(n-1).fill(0);e.push(1);let t=1;for(let i=0;i<n;i++){for(let r=0;r<e.length;r++)e[r]=dn(e[r],t),r+1<e.length&&(e[r]^=e[r+1]);t=dn(t,2)}return e}function Ba(n,e){let t=e.map(()=>0);for(let i of n){let r=i^t.shift();t.push(0),e.forEach((s,o)=>t[o]^=dn(s,r))}return t}function fn(n,e={}){let t=e.ecl==="L"?0:1,i=[...new TextEncoder().encode(String(n))],r=1;for(;r<=un&&!(4+(r<=9?8:16)+i.length*8<=Ts(r,t)*8);r++);if(r>un)throw new Error(`qrEncode: ${i.length} bytes is too long for a version-${un} code`);let s=[],o=(g,S)=>{for(let y=S-1;y>=0;y--)s.push(g>>>y&1)};o(4,4),o(i.length,r<=9?8:16);for(let g of i)o(g,8);let a=Ts(r,t)*8;o(0,Math.min(4,a-s.length)),o(0,(8-s.length%8)%8);for(let g=236;s.length<a;g^=253)o(g,8);let l=[];for(let g=0;g<s.length;g+=8)l.push(s.slice(g,g+8).reduce((S,y)=>S<<1|y,0));let c=As[t][r],h=Os[t][r],d=Math.floor(Ps(r)/8),u=c-d%c,f=Math.floor(d/c),p=Va(h),m=[];for(let g=0,S=0;g<c;g++){let y=l.slice(S,S+f-h+(g<u?0:1));S+=y.length;let O=Ba(y,p);g<u&&y.push(0),m.push(y.concat(O))}let w=[];for(let g=0;g<m[0].length;g++)for(let S=0;S<m.length;S++)(g!==f-h||S>=u)&&w.push(m[S][g]);let _=r*4+17,x=Array.from({length:_},()=>new Array(_).fill(!1)),R=Array.from({length:_},()=>new Array(_).fill(!1)),E=(g,S,y)=>{x[S][g]=y,R[S][g]=!0};for(let g=0;g<_;g++)E(6,g,g%2===0),E(g,6,g%2===0);let C=(g,S)=>{for(let y=-4;y<=4;y++)for(let O=-4;O<=4;O++){let I=Math.max(Math.abs(O),Math.abs(y)),P=g+O,N=S+y;P>=0&&P<_&&N>=0&&N<_&&E(P,N,I!==2&&I!==4)}};C(3,3),C(_-4,3),C(3,_-4);let k=[];if(r>1){let g=Math.floor(r/7)+2,S=Math.ceil((r*4+4)/(g*2-2))*2;k.push(6);for(let y=_-7;k.length<g;y-=S)k.splice(1,0,y)}for(let g=0;g<k.length;g++)for(let S=0;S<k.length;S++)if(!(g===0&&S===0||g===0&&S===k.length-1||g===k.length-1&&S===0))for(let y=-2;y<=2;y++)for(let O=-2;O<=2;O++)E(k[g]+O,k[S]+y,Math.max(Math.abs(O),Math.abs(y))!==1);let T=g=>{let S=Ua[t]<<3|g,y=S;for(let P=0;P<10;P++)y=y<<1^(y>>>9)*1335;let O=(S<<10|y)^21522,I=P=>(O>>>P&1)!==0;for(let P=0;P<=5;P++)E(8,P,I(P));E(8,7,I(6)),E(8,8,I(7)),E(7,8,I(8));for(let P=9;P<15;P++)E(14-P,8,I(P));for(let P=0;P<8;P++)E(_-1-P,8,I(P));for(let P=8;P<15;P++)E(8,_-15+P,I(P));E(8,_-8,!0)};if(T(0),r>=7){let g=r;for(let y=0;y<12;y++)g=g<<1^(g>>>11)*7973;let S=r<<12|g;for(let y=0;y<18;y++){let O=(S>>>y&1)!==0,I=_-11+y%3,P=Math.floor(y/3);E(I,P,O),E(P,I,O)}}let v=0;for(let g=_-1;g>=1;g-=2){g===6&&(g=5);for(let S=0;S<_;S++)for(let y=0;y<2;y++){let O=g-y,P=(g+1&2)===0?_-1-S:S;!R[P][O]&&v<w.length*8&&(x[P][O]=(w[v>>>3]>>>7-(v&7)&1)!==0,v++)}}let b=g=>{for(let S=0;S<_;S++)for(let y=0;y<_;y++){if(R[S][y])continue;let O;switch(g){case 0:O=(y+S)%2===0;break;case 1:O=S%2===0;break;case 2:O=y%3===0;break;case 3:O=(y+S)%3===0;break;case 4:O=(Math.floor(y/3)+Math.floor(S/2))%2===0;break;case 5:O=y*S%2+y*S%3===0;break;case 6:O=(y*S%2+y*S%3)%2===0;break;default:O=((y+S)%2+y*S%3)%2===0}O&&(x[S][y]=!x[S][y])}},M=Number.isInteger(e.mask)?e.mask:-1;if(M<0){let g=1/0;for(let S=0;S<8;S++){b(S),T(S);let y=Xa(x,_);y<g&&(g=y,M=S),b(S)}}return b(M),T(M),{version:r,size:_,mask:M,modules:x}}function Xa(n,e){let t=0,i=[];for(let o=0;o<e;o++)i.push(n[o]);for(let o=0;o<e;o++)i.push(n.map(a=>a[o]));for(let o of i){let a=1;for(let c=1;c<=e;c++)c<e&&o[c]===o[c-1]?a++:(a>=5&&(t+=a-2),a=1);let l=o.map(c=>c?"1":"0").join("");for(let c of["10111010000","00001011101"])for(let h=l.indexOf(c);h>=0;h=l.indexOf(c,h+1))t+=40}let r=0;for(let o=0;o<e;o++)for(let a=0;a<e;a++)if(n[o][a]&&r++,a<e-1&&o<e-1){let l=n[o][a];l===n[o][a+1]&&l===n[o+1][a]&&l===n[o+1][a+1]&&(t+=3)}let s=e*e;return t+=Math.floor(Math.abs(r*20-s*10)/s)*10,t}function Ds(n,e,{px:t=4,dark:i="#000",light:r="#fff",ecl:s="M"}={}){let o=fn(e,{ecl:s}),a=o.size+8;n.width=n.height=a*t;let l=n.getContext("2d");l.fillStyle=r,l.fillRect(0,0,a*t,a*t),l.fillStyle=i;for(let c=0;c<o.size;c++)for(let h=0;h<o.size;h++)o.modules[c][h]&&l.fillRect((h+4)*t,(c+4)*t,t,t);return o}function ie(n,e){let t=new Error(`@displayxr/inline3d/call: ${e}`);return t.code=n,t}async function pn(n){let e=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(String(n)));return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}var $t="wss://signal.displayxr.org",Ls=Object.freeze([$t,"wss://dxr-signal.displayxr.workers.dev"]),Is=["bad-room","bad-id","bad-version","bad-key","origin-not-allowed","blocked"];function Oe(n=$t,e={}){if(!n||typeof n!="string")throw ie("no-signaling-url","dxrSignaling(url): url must be a ws:// or wss:// string (omit it for the hosted DisplayXR server)");let t=c=>String(c).replace(/\/+$/,""),i=t(n),r=e.WebSocket||globalThis.WebSocket,s=e.pingMs||2e4,o=Array.isArray(e.aliases)?e.aliases.filter(c=>typeof c=="string"&&c).map(t):Ls.includes(i)?[...Ls]:[],a=[i,...o.filter(c=>c!==i)],l=0;return{name:"dxr",url:i,async join(c,h){let u=`k=${await pn(c)}${typeof e.key=="string"&&e.key?`&key=${encodeURIComponent(e.key)}`:""}`,f=b=>`${a[b]}/v1/connect?${u}`,p=null,m=!1,w=0,_=null,x=new Set,R=[],E=b=>C(b,a.length),C=(b,M)=>new Promise((g,S)=>{let y=!1,O=!1,I=!1,P=new r(f(l));p=P;let N=$=>{if(!y){y=!0;try{P.close()}catch{}S($)}};P.onopen=()=>{I=!0,P.send(JSON.stringify({t:"join",v:1,room:c,id:h.id,max:h.maxPeers}))},P.onmessage=$=>{let L;try{L=JSON.parse(typeof $.data=="string"?$.data:String($.data))}catch{return}switch(L.t){case"welcome":{w=0;let z=Array.isArray(L.peers)?L.peers.filter(q=>typeof q=="string"):[];clearInterval(_),_=setInterval(()=>k({t:"ping"}),s);let Pe=R;R=[];for(let q of Pe)k(q);if(b){let q=new Set(z);for(let ne of x)q.has(ne)||h.onPeerLeft?.(ne);x=q,h.onReconnect?.(z)}else x=new Set(z);y=!0,O=!0,g({id:L.id,peers:z,iceServers:Array.isArray(L.iceServers)?L.iceServers:void 0,max:L.max,tier:L.tier==="key"?"key":"anon",key:typeof L.key=="string"?L.key:void 0,turn:L.turn&&typeof L.turn=="object"?L.turn:void 0});break}case"full":m=!0,N(ie("room-full",`this call is full (${L.max} participants)`));break;case"expired":{m=!0,clearInterval(_);let z=ie("expired","this room has reached its lifetime on the signalling server");y?h.onDisconnect?.(z):N(z);break}case"error":if(!y&&Is.includes(L.code))m=!0,N(ie(L.code,L.message||L.code));else if(!y&&(L.code==="rate-limited"||L.code==="quota")){let z=ie(L.code,L.message||L.code);z.retryMs=L.retryMs>0?L.retryMs:0,N(z)}else!y&&L.code==="id-taken"&&N(ie("id-taken","peer id still held; retrying"));break;case"peer-joined":typeof L.id=="string"&&!x.has(L.id)&&(x.add(L.id),h.onPeerJoined?.(L.id));break;case"peer-left":typeof L.id=="string"&&(x.delete(L.id),h.onPeerLeft?.(L.id));break;case"signal":typeof L.from=="string"&&h.onSignal?.(L.from,L.data);break}},P.onerror=()=>{if(!I&&!y&&M>1){y=!0,l=(l+1)%a.length,C(b,M-1).then(g,S);return}N(ie("signaling-unreachable",`cannot reach ${a[l]}`))},P.onclose=()=>{clearInterval(_),N(ie("signaling-closed","signalling closed before joining")),O&&!m&&p===P&&T()}}),k=b=>{p&&p.readyState===1?p.send(JSON.stringify(b)):m||R.push(b)},T=()=>{h.onDisconnect?.();let b=()=>{m||E(!0).catch(M=>{if(m||M&&(M.code==="room-full"||Is.includes(M.code))){h.onDisconnect?.(M);return}setTimeout(b,Math.max(K(w++,{baseMs:500,maxMs:15e3}),M&&M.retryMs||0))})};setTimeout(b,K(w++,{baseMs:300,maxMs:15e3}))};return{...await E(!1),send:(b,M)=>k({t:"signal",to:b,data:M}),leave:()=>{if(!m){m=!0,clearInterval(_);try{p&&p.readyState===1&&p.send(JSON.stringify({t:"leave"})),p&&p.close(1e3,"leave")}catch{}}}}}}}var mn=Object.freeze({azure:"#4da3ff",violet:"#9b7bff",magenta:"#ff4fa3",sunset:"#ff7a45",amber:"#ffc23d",lime:"#9be15d",mint:"#35e0b0",ice:"#8fe3ff"}),Ns=n=>typeof n=="string"&&mn[n.toLowerCase()]||n,js=Object.freeze({accent:"--dxr-accent",ink:"--dxr-ink",shell:"--dxr-shell",danger:"--dxr-danger",radius:"--dxr-radius",font:"--dxr-font"}),Je=Object.freeze({lobbyStartTitle:"Start a 3D call",lobbyJoinTitle:"Join the 3D call",lobbyFullTitle:"This call is full",lobbyLeftTitle:"You left the call",lobbyFullText:"It already has {maxPeers} participants.",lobbyText:"Check your framing below. Camera: {camera} \u2014 {kind}.",cameraDefault:"default",kindBusy:"busy (joining audio-only)",kindNone:"none (joining audio-only)",kindSbs:"sending 3D (side-by-side, {width}\xD7{height})",kindMono:"sending 2D ({width}\xD7{height})",liftOff:"Mono cameras: 2D (2D\u21923D is off).",liftChecking:"Mono cameras: checking 2D\u21923D\u2026",liftMissing:"Mono cameras: 2D\u21923D unavailable in this build.",liftNoProvider:"Mono cameras: 2D (no 2D\u21923D provider here).",liftNative:"Mono cameras: 2D\u21923D (native{provider}).",liftWeb:"Mono cameras: 2D\u21923D (in this page, WebGPU).",liftProven:"Mono cameras: 2D\u21923D.",liftUnproven:"Mono cameras: 2D\u21923D (confirmed on the first mono participant).",start:"Start 3D call",join:"Join call",rejoin:"Rejoin",retryCamera:"Retry camera",cameraSelect:"Camera",joining:"Joining\u2026",waitingTitle:"Waiting for others",waitingText:"Share this link (or scan the code). Anyone who opens it joins \u2014 keep it private.",inviteTitle:"Invite",inviteText:"Anyone with this link can join.",inviteLink:"Invite link",copyLink:"Copy link",copied:"Copied",pressCopy:"Press Ctrl/Cmd+C",qrLabel:"QR code of the invite link",banner2D:"You are seeing this call in 2D.",bannerLink:"View in 3D with DisplayXR Browser",mute:"Mute microphone",unmute:"Unmute microphone",cameraOn:"Turn camera on",cameraOff:"Turn camera off",cameraRetry:"No camera \u2014 click to retry",cameraBusyRetry:"{cameraBusy} \u2014 click to retry",depth:"Depth",invite:"Invite",leave:"Leave call",connecting:"Connecting\u2026",reconnecting:"Reconnecting\u2026",leftCall:"Left the call",cameraOffPlate:"Camera off",noCamera:"No camera",unreachable:"Can't reach this participant \u2014 the network needs a relay (TURN)",cameraBusy:"Camera busy \u2014 in use by another app (e.g. eye tracking)",you:"You",badge3D:"3D",badge2D3D:"2D\u21923D",badge2D:"2D",badgePending:"\u2026"});function zs(n){let e={...Je,...n&&typeof n=="object"?n:{}};return(t,i)=>{let r=typeof e[t]=="string"?e[t]:Je[t]||t;if(i)for(let[s,o]of Object.entries(i))r=r.split(`{${s}}`).join(String(o));return r}}var Fs="dxr-call-style",Ya=`
19
+ `,n=i.split(t),r=n.findIndex(p=>p.startsWith("m=video"));if(r<0)return i;let s=n.findIndex((p,f)=>f>r&&p.startsWith("m="));s<0&&(s=n.length);let o=n.slice(r,s),a=new Map,l=new Map;for(let p of o){let f=p.match(/^a=rtpmap:(\d+) ([\w-]+)\//);f&&a.set(f[1],f[2].toUpperCase());let g=p.match(/^a=fmtp:(\d+) apt=(\d+)/);g&&(l.has(g[2])||l.set(g[2],[]),l.get(g[2]).push(g[1]))}let c=n[r].split(" "),h=c.slice(3),u=[];for(let p of e)for(let f of h)if(a.get(f)===p&&!u.includes(f)){u.push(f);for(let g of l.get(f)||[])h.includes(g)&&!u.includes(g)&&u.push(g)}if(!u.length)return i;let d=h.filter(p=>!u.includes(p));return n[r]=[...c.slice(0,3),...u,...d].join(" "),n.join(t)}var Cr=Object.freeze([{urls:"stun:stun.l.google.com:19302"}]),ra=4e3,sa=1e4,oa=2e4,aa=8e3,la=1e4,ca=.6;function qe(i){let e=Number.isInteger(i)?i:ye;return Math.max(2,Math.min(hr,e))}function Rr(i,e){return i<e}var Ge=class{constructor({signaling:e,id:t,maxPeers:n,iceServers:r,RTCPeerConnection:s,log:o,unreachableMs:a}={}){this.unreachableMs=a>0?a:la,this.signaling=e,this.id=t,this.maxPeers=qe(n),this.pageIce=r||null,this.iceServers=r||Cr,this.PC=s||globalThis.RTCPeerConnection,this.log=o||(()=>{}),this.peers=new Map,this.session=null,this.ready=!1,this._pending=[],this.stopped=!1,this.sendFormat="mono",this.localStream=null,this.contentTrack=null,this.contentStream=null}get size(){return this.peers.size}async start({room:e,localStream:t,sendFormat:n,contentTrack:r,contentStream:s,onPeer:o,onPeerLeft:a,onStream:l,onContentStream:c,onMessage:h,onPeerState:u,onRefused:d,onSignalingState:p,onGhost:f}){this.localStream=t,this.sendFormat=n||"mono",r!==void 0&&(this.contentTrack=r||null),s!==void 0&&(this.contentStream=s||null),this.cb={onPeer:o,onPeerLeft:a,onStream:l,onContentStream:c,onMessage:h,onPeerState:u,onRefused:d,onSignalingState:p,onGhost:f};let g=w=>(...M)=>this.ready?w(...M):this._pending.push(()=>w(...M));this.session=await this.signaling.join(e,{id:this.id,maxPeers:this.maxPeers,onPeerJoined:g(w=>this._onPeerJoined(w)),onPeerLeft:g(w=>this._onPeerLeftSignaling(w)),onSignal:g((w,M)=>this._onSignal(w,M)),onDisconnect:w=>p?.(w?"closed":"reconnecting",w),onPeerUnreachable:g(w=>f?.(w,!0)),onPeerReachable:g(w=>f?.(w,!1)),onReconnect:g(w=>{p?.("connected");for(let M of w)this._onPeerJoined(M)})}),!this.pageIce&&this.session.iceServers&&this.session.iceServers.length&&(this.iceServers=[...Cr,...this.session.iceServers]);let x=this.session.peers||[];if(x.length>=this.maxPeers){this.session.leave();let w=new Error(`@displayxr/inline3d/call: this call is full (${this.maxPeers} participants)`);throw w.code="room-full",w}this.ready=!0;for(let w of x)this._onPeerJoined(w);let b=this._pending;this._pending=[];for(let w of b)w();return this.session}_onPeerJoined(e){if(this.stopped||e===this.id)return;let t=this.peers.get(e);if(t){t.absent=!1,t.state!=="connected"&&Rr(this.id,e)&&this._rebuild(t,"rejoined");return}if(this.peers.size>=this.maxPeers-1){this.log("refused",{peer:e,reason:"maxPeers",maxPeers:this.maxPeers}),this.cb.onRefused?.(e);return}let n=this._newRecord(e);this.cb.onPeer?.(e),n.offerer?this._build(n,1):n.waitTimer=setTimeout(()=>this._askRestart(n),aa)}_onPeerLeftSignaling(e){let t=this.peers.get(e);t&&(t.absent=!0,t.state!=="connected"&&this._drop(t,"left"))}_newRecord(e){let t={id:e,offerer:Rr(this.id,e),pc:null,builtAt:0,offerAt:0,dc:null,gen:0,state:"new",stream:null,contentCap:!1,contentStream:null,renegotiate:!1,attempts:0,iceRestarted:!1,absent:!1,pendingCandidates:[],timers:new Set,waitTimer:null,unreachable:!1,unreachTimer:null};return this.peers.set(e,t),this._armUnreachable(t),t}_build(e,t){this._closePc(e),e.gen=t,e.builtAt=Date.now(),e.iceRestarted=!1,e.pendingCandidates=[],e.stream=null,e.renegotiate=!1,e.contentStream&&(e.contentStream=null,this.cb.onContentStream?.(e.id,null));let n=new this.PC({iceServers:this.iceServers});e.pc=n;let r=n.createDataChannel("dxr-call",{negotiated:!0,id:0,ordered:!0});if(this._wireDc(e,r),e.offerer){let s=this.localStream?this.localStream.getTracks():[],o=s.find(h=>h.kind==="audio"),a=s.find(h=>h.kind==="video"),l=this.localStream?[this.localStream]:[];n.addTransceiver(o||"audio",{direction:"sendrecv",streams:l});let c=n.addTransceiver(a||"video",{direction:"sendrecv",streams:l});this._preferCodecs(c),e.contentCap&&this._addContent(e,n)}return n.onicecandidate=s=>{s.candidate&&this._signal(e,{kind:"candidate",candidate:s.candidate.toJSON?s.candidate.toJSON():s.candidate})},n.ontrack=s=>{if(e.pc===n){if(this._isContent(n,s.transceiver,s.track)){e.contentStream=new MediaStream([s.track]),this.cb.onContentStream?.(e.id,e.contentStream);return}if(e.stream||(e.stream=new MediaStream),!e.stream.getTracks().includes(s.track)){for(let o of e.stream.getTracks())o.kind===s.track.kind&&e.stream.removeTrack(o);e.stream.addTrack(s.track)}this.cb.onStream?.(e.id,e.stream)}},n.onconnectionstatechange=()=>this._onConnState(e,n),this._arm(e,oa,()=>{e.pc===n&&n.connectionState!=="connected"&&this._fail(e,"connect-timeout")}),e.offerer&&this._offer(e).catch(s=>this.log("offer-error",{peer:e.id,err:String(s)})),this._setState(e,e.attempts>0?"reconnecting":"connecting"),n}async _offer(e,{iceRestart:t=!1}={}){let n=e.pc,r=await n.createOffer(t?{iceRestart:!0}:void 0);this._canPreferCodecs||(r.sdp=Xe(r.sdp)),await n.setLocalDescription(r),this._signal(e,{kind:"offer",sdp:n.localDescription.sdp})}async _onSignal(e,t){if(this.stopped||!t||typeof t!="object")return;let n=this.peers.get(e);if(!n&&(t.kind!=="offer"||(this._onPeerJoined(e),n=this.peers.get(e),!n)))return;let r=t.gen|0;try{switch(t.kind){case"offer":{if(n.offerer||(clearTimeout(n.waitTimer),r<n.gen))return;n.offerAt=Date.now(),(r>n.gen||!n.pc)&&this._build(n,r);let s=n.pc;await s.setRemoteDescription({type:"offer",sdp:t.sdp}),this._attachAnswererTracks(n);let o=await s.createAnswer();this._canPreferCodecs||(o.sdp=Xe(o.sdp)),await s.setLocalDescription(o),this._signal(n,{kind:"answer",sdp:s.localDescription.sdp}),this._flushCandidates(n),n.state==="connected"&&this.tuneSenders();break}case"answer":if(!n.offerer||r!==n.gen||!n.pc||n.pc.signalingState!=="have-local-offer")return;await n.pc.setRemoteDescription({type:"answer",sdp:t.sdp}),this._flushCandidates(n),n.renegotiate?(n.renegotiate=!1,this._offer(n).catch(s=>this.log("offer-error",{peer:n.id,err:String(s)}))):n.state==="connected"&&this.tuneSenders();break;case"candidate":if(r!==n.gen||!n.pc)return;n.pc.remoteDescription?await n.pc.addIceCandidate(t.candidate).catch(()=>{}):n.pendingCandidates.push(t.candidate);break;case"restart":if(!n.offerer||n.pc&&n.state!=="connected"&&Date.now()-n.builtAt<5e3)return;this._rebuild(n,"peer-asked");break;case"bye":this._drop(n,"left");break}}catch(s){this.log("signal-error",{peer:e,kind:t.kind,err:String(s)})}}_flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let n of t)e.pc.addIceCandidate(n).catch(()=>{})}_attachAnswererTracks(e){let t=e.pc,n=this.localStream?this.localStream.getTracks():[],r=this._contentTransceiver(t);r&&(this.contentTrack&&r.sender.track!==this.contentTrack&&(r.sender.replaceTrack(this.contentTrack).catch(()=>{}),this.contentStream&&r.sender.setStreams&&r.sender.setStreams(this.contentStream)),r.direction="sendrecv",this._preferCodecs(r));for(let s of t.getTransceivers()){if(s===r)continue;let o=s.receiver&&s.receiver.track?s.receiver.track.kind:null;if(!o||s.sender.track)continue;let a=n.find(l=>l.kind===o);a&&(s.sender.replaceTrack(a).catch(()=>{}),this.localStream&&s.sender.setStreams&&s.sender.setStreams(this.localStream)),s.direction="sendrecv",o==="video"&&this._preferCodecs(s)}}_videoTransceivers(e){return!e||typeof e.getTransceivers!="function"?[]:e.getTransceivers().filter(t=>t&&t.receiver&&t.receiver.track&&t.receiver.track.kind==="video")}_contentTransceiver(e){return this._videoTransceivers(e)[1]||null}_isContent(e,t,n){let r=this._contentTransceiver(e);return r?t?t===r:!!(n&&r.receiver&&r.receiver.track===n):!1}_addContent(e,t){if(this._contentTransceiver(t))return this._contentTransceiver(t);let n=this.contentStream?[this.contentStream]:[],r=t.addTransceiver(this.contentTrack||"video",{direction:"sendrecv",streams:n});return this._preferCodecs(r),r}addContentTransceiver(e){let t=this.peers.get(e);if(!t||this.stopped||(t.contentCap=!0,!t.offerer))return!1;let n=t.pc;return!n||this._contentTransceiver(n)||(this._addContent(t,n),this.log("content-transceiver",{peer:t.id,gen:t.gen}),n.signalingState==="stable"?this._offer(t).catch(r=>this.log("offer-error",{peer:t.id,err:String(r)})):t.renegotiate=!0),!0}hasContent(e){let t=this.peers.get(e);return!!(t&&t.pc&&this._contentTransceiver(t.pc))}_preferCodecs(e){let t=globalThis.RTCRtpReceiver&&RTCRtpReceiver.getCapabilities&&RTCRtpReceiver.getCapabilities("video");if(this._canPreferCodecs=!!(e&&e.setCodecPreferences&&t),!!this._canPreferCodecs)try{e.setCodecPreferences(yt(t.codecs))}catch{this._canPreferCodecs=!1}}_onConnState(e,t){if(e.pc!==t)return;let n=t.connectionState;this.log("pc-state",{peer:e.id,state:n,gen:e.gen}),n==="connected"?(this._clearTimers(e),e.attempts=0,e.iceRestarted=!1,this._setState(e,"connected"),this.tuneSenders()):n==="disconnected"?(this._setState(e,"reconnecting"),this._arm(e,ra,()=>{e.pc===t&&t.connectionState!=="connected"&&this._fail(e,"disconnected")})):n==="failed"?this._fail(e,"failed"):n==="closed"&&!this.stopped&&this.peers.get(e.id)===e&&this._fail(e,"closed")}_fail(e,t){if(this.stopped||this.peers.get(e.id)!==e)return;if(e.absent)return this._drop(e,"left");if(this._setState(e,"reconnecting"),!e.offerer)return this._askRestart(e);let n=e.pc;if(n&&!e.iceRestarted&&n.connectionState!=="closed"&&n.signalingState!=="closed"){e.iceRestarted=!0,this.log("ice-restart",{peer:e.id,why:t,gen:e.gen}),this._offer(e,{iceRestart:!0}).catch(()=>this._rebuild(e,"ice-restart-failed")),this._arm(e,sa,()=>{e.pc===n&&n.connectionState!=="connected"&&this._rebuild(e,"ice-restart-timeout")});return}this._rebuild(e,t)}_rebuild(e,t){if(this.stopped||this.peers.get(e.id)!==e)return;this._clearTimers(e),this._closePc(e),this._setState(e,"reconnecting");let n=Z(e.attempts++);this.log("redial",{peer:e.id,why:t,attempt:e.attempts,inMs:n}),this._arm(e,n,()=>this._build(e,e.gen+1))}_askRestart(e){if(this.stopped||this.peers.get(e.id)!==e||e.offerer)return;let t=Date.now();this._signal(e,{kind:"restart"}),this._arm(e,Math.max(3e3,Z(e.attempts++)),()=>{e.state!=="connected"&&!(e.offerAt>=t)&&this._askRestart(e)})}_drop(e,t){this.peers.get(e.id)===e&&(this._clearTimers(e),clearTimeout(e.unreachTimer),clearTimeout(e.waitTimer),this._closePc(e),this.peers.delete(e.id),e.contentStream&&(e.contentStream=null,this.cb.onContentStream?.(e.id,null)),this._setState(e,"left"),this.cb.onPeerLeft?.(e.id,t),this.tuneSenders())}_closePc(e){if(e.dc){try{e.dc.close()}catch{}e.dc=null}if(e.pc){let t=e.pc;e.pc=null;try{t.close()}catch{}}}_arm(e,t,n){let r=setTimeout(()=>{e.timers.delete(r),n()},t);e.timers.add(r)}_clearTimers(e){for(let t of e.timers)clearTimeout(t);e.timers.clear()}_armUnreachable(e){e.unreachTimer||e.unreachable||(e.unreachTimer=setTimeout(()=>{e.unreachTimer=null,!(this.stopped||this.peers.get(e.id)!==e||e.state==="connected")&&(e.unreachable=!0,this.log("unreachable",{peer:e.id,afterMs:this.unreachableMs,pc:e.pc?e.pc.iceConnectionState:null}),this._setState(e,"unreachable"))},this.unreachableMs))}_setState(e,t){t==="connected"?(clearTimeout(e.unreachTimer),e.unreachTimer=null,e.unreachable=!1):(t==="connecting"||t==="reconnecting")&&(e.unreachable?t="unreachable":this._armUnreachable(e)),e.state!==t&&(e.state=t,this.cb.onPeerState?.(e.id,t))}_signal(e,t){this.session?.send(e.id,{...t,gen:e.gen})}_wireDc(e,t){e.dc=t,t.onopen=()=>this.cb.onMessage?.(e.id,{type:"__open"}),t.onmessage=n=>{let r;try{r=JSON.parse(n.data)}catch{return}if(r&&r.type==="bye")return this._drop(e,"left");this.cb.onMessage?.(e.id,r)}}send(e,t){let n=this.peers.get(e);return n&&n.dc&&n.dc.readyState==="open"?(n.dc.send(JSON.stringify(t)),!0):!1}broadcast(e){for(let t of this.peers.keys())this.send(t,e)}sendRaw(e,t){let n=this.peers.get(e);return n&&n.dc&&n.dc.readyState==="open"?(n.dc.send(t),!0):!1}peerConnection(e){let t=this.peers.get(e);return t?t.pc:null}peerState(e){let t=this.peers.get(e);return t?t.state:null}async replaceTrack(e,t,n,{slot:r="camera"}={}){r==="content"?(this.contentTrack=t||null,this.contentStream=t&&n||null):n&&(this.localStream=n);for(let s of this.peers.values()){if(!s.pc)continue;let o=this._contentTransceiver(s.pc);if(r==="content"){if(!o)continue;await o.sender.replaceTrack(t||null).catch(()=>{}),t&&n&&o.sender.setStreams&&o.sender.setStreams(n);continue}for(let a of s.pc.getTransceivers()){if(a===o)continue;(a.receiver&&a.receiver.track?a.receiver.track.kind:null)===e&&await a.sender.replaceTrack(t).catch(()=>{})}}await this.tuneSenders()}setSendFormat(e){return this.sendFormat=e,this.tuneSenders()}async tuneSenders(){let e=this.peers.size,t=!!this.contentTrack,n=Math.round(Ve(this.sendFormat,e)*(t?ca:1)),r=Ve("sbs",e);for(let s of this.peers.values()){if(!s.pc)continue;let o=this._contentTransceiver(s.pc);for(let a of s.pc.getSenders()){if(!a.track||a.track.kind!=="video")continue;let l=!!(o&&o.sender===a);try{let c=a.getParameters();c.degradationPreference="maintain-resolution",(!c.encodings||!c.encodings.length)&&(c.encodings=[{}]),c.encodings[0].maxBitrate=(l?r:n)*1e3,await a.setParameters(c)}catch(c){this.log("setParameters-error",{peer:s.id,err:String(c)})}}}return n}stop(){if(!this.stopped){this.broadcast({type:"bye"}),this.stopped=!0;for(let e of this.peers.values())this._clearTimers(e),clearTimeout(e.waitTimer),clearTimeout(e.unreachTimer),this._signal(e,{kind:"bye"}),this._closePc(e);this.peers.clear();try{this.session?.leave()}catch{}}}_debugKill(e){let t=this.peers.get(e);return!t||!t.pc?!1:(this._closePc(t),this._fail(t,"debug-kill"),!0)}};var wt="dxr-app:",bt=/^DisplayXR: (.+) \(3D\)$/,kr=/^3D Camera \(DisplayXR\)\s+-\s+(.+)$/;function xt(i){if(!i||typeof i!="object")return!1;try{let e=i;return typeof e.source=="string"?e.source==="app":e.layout!=null&&e.layout!=="side-by-side"?!1:e.baselineMm===0&&e.horizontalFovDeg===0}catch{return!1}}function Tr(i){let e="";try{e=typeof i=="string"?i:i&&typeof i=="object"?i.label:""}catch{return null}let t=typeof e=="string"?kr.exec(e.trim()):null,n=t?t[1].trim():"";return n?{appName:n}:null}function Ar(i){let e=typeof i=="string"?bt.exec(i.trim()):null;return e&&e[1].trim()||null}function ne(i){if(!i)return!1;if(typeof i=="string")return bt.test(i.trim())||i.startsWith(wt);if(typeof i!="object")return!1;let e=i;try{if(typeof e.label=="string"&&bt.test(e.label.trim())||typeof e.deviceId=="string"&&e.deviceId.startsWith(wt))return!0;let t=e.displayxrStereo||(typeof e.getSettings=="function"?(e.getSettings()||{}).displayxrStereo:null);if(xt(t))return!0;if(typeof e.getSettings=="function"){let n=(e.getSettings()||{}).deviceId;if(typeof n=="string"&&n.startsWith(wt))return!0}}catch{}return!1}var Ye={width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},zn={width:{ideal:3840},height:{ideal:1080},frameRate:{ideal:30}},ha=Object.freeze({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0});function ua(i){return!!i&&(i.name==="NotReadableError"||i.name==="TrackStartError"||/in use|busy/i.test(i.message||""))}function da(i){return!!i&&(i.name==="NotAllowedError"||i.name==="PermissionDeniedError"||i.name==="SecurityError")}function Wn(i){let e=i.filter(t=>!t.excluded);return e.length&&e.every(t=>t.busy)?"camera-busy":e.some(t=>t.denied)?"permission-denied":"no-camera"}var fa=/\b(hand[- ]?track|tracking camera|eye[- ]?track|depth camera|ultraleap|leap motion|infrared|ir camera)/i;function pa(i){let e=(n,r)=>ne({label:String(n||""),deviceId:typeof r=="string"?r:""});if(i===!1)return e;let t=[fa];for(let n of i==null?[]:Array.isArray(i)?i:[i])(n instanceof RegExp||typeof n=="string"&&n)&&t.push(n);return(n,r)=>{if(e(n,r))return!0;let s=String(n||"");for(let o of t)if(o instanceof RegExp){if(o.lastIndex=0,s&&o.test(s))return!0}else if(s&&s.toLowerCase().includes(o.toLowerCase())||r&&r===o)return!0;return!1}}function St(i){return ne(String(i||""))?!1:/stereo|\b3d\b|\bsbs\b|dual/i.test(i||"")}async function Or(i="auto",e={}){let t=e.mediaDevices||globalThis.navigator&&navigator.mediaDevices,n=e.log||(()=>{}),r=[],s=e.calibration||{},o=pa(e.exclude);if(i&&typeof i=="object"&&typeof i.getVideoTracks=="function"){let v=i.getVideoTracks()[0],m=v?v.getSettings():{},_=e.format==="sbs"?"sbs":"mono";return{stream:i,format:_,width:m.width||0,height:m.height||0,deviceId:m.deviceId||null,label:v?v.label:"",owned:!1,skipped:r,calibration:s}}if(!t||!t.getUserMedia)throw Object.assign(new Error("getUserMedia is not available (insecure context?)"),{code:"no-camera"});let a=async v=>{let m=await t.getUserMedia({video:v,audio:!1}),_=m.getVideoTracks()[0],y=_?_.getSettings():{};if(!_||_.readyState==="ended"||!(y.width>0)||!(y.height>0))throw m.getTracks().forEach(T=>T.stop()),Object.assign(new Error("the camera opened but delivers no picture (0x0)"),{name:"NotReadableError"});let C=y.displayxrStereo&&y.displayxrStereo.layout==="side-by-side"?y.displayxrStereo:null,I=ne({label:_.label||"",deviceId:y.deviceId||""})||xt(y.displayxrStereo);return{stream:m,track:_,width:y.width,height:y.height,deviceId:y.deviceId||null,label:_.label||"",stereo:C,appShare:I}},l=(v,m)=>{r.push({label:v,error:`${m.name}: ${m.message}`,busy:ua(m),denied:da(m)}),n("camera-skip",{label:v,error:m.name})},c=v=>v&&v.stream.getTracks().forEach(m=>m.stop()),h=async()=>{try{return(await t.enumerateDevices()).filter(v=>v.kind==="videoinput")}catch{return[]}},u=new Set,d=(v,m,_="excluded")=>{m&&u.has(m)||(m&&u.add(m),r.push({label:v,error:"excluded",excluded:!0,reason:_}),n("camera-skip",{label:v,error:"excluded",reason:_}))},p=v=>ne({label:v.label||"",deviceId:v.deviceId||""}),f=v=>p(v)?(d(v.label||"",v.deviceId,"app-share"),!0):!v.label||!o(v.label,v.deviceId)?!1:(d(v.label,v.deviceId),!0),g=v=>v.appShare?(c(v),d(v.label,v.deviceId,"app-share"),!0):o(v.label,v.deviceId)?(c(v),d(v.label,v.deviceId),!0):!1,x=!1,b=async v=>{let m=await a(v);return g(m)?(x=!0,null):m},w=async(v,m)=>{try{await v.track.applyConstraints(m);let _=v.track.getSettings();if(_.width>0&&_.height>0)return{...v,width:_.width,height:_.height}}catch{}return v},M=v=>!!v&&(!!v.stereo||Cn(v.width,v.height)),S=(v,m)=>({stream:v.stream,format:m,width:v.width,height:v.height,deviceId:v.deviceId,label:v.label,owned:!0,skipped:r,calibration:{rectified:!1,...m==="sbs"&&v.stereo?{rectified:!!v.stereo.rectified,...v.stereo.baselineMm>0?{baselineMm:v.stereo.baselineMm}:{},...v.stereo.horizontalFovDeg>0?{hfovDeg:v.stereo.horizontalFovDeg}:{}}:{},...s}});if(typeof i=="string"&&i.startsWith("label:")){let v=i.slice(6).trim().toLowerCase(),m=await h();if(v&&m.length&&m.every(y=>!y.label)){try{c(await a(!0))}catch(y){l("default",y)}m=await h()}let _=v?m.find(y=>y.deviceId&&!p(y)&&(y.label||"").toLowerCase().includes(v)):null;if(!_)throw Object.assign(new Error(`camera unavailable: no camera labelled "${v}"`),{code:Wn(r),skipped:r});n("camera-label",{label:_.label,needle:v}),i=_.deviceId}if(typeof i=="string"&&!["auto","stereo","mono"].includes(i)){let v;try{v=await a({deviceId:{exact:i},...zn})}catch(m){throw l(i,m),Object.assign(new Error(`camera unavailable: ${m.message}`),{code:Wn(r),skipped:r})}return M(v)?S(v,"sbs"):(c(v),S(await a({deviceId:{exact:i},...Ye}),"mono"))}let k=new Set,R=async v=>{for(let m of v){if(!m.deviceId||!St(m.label)||k.has(m.deviceId)||(k.add(m.deviceId),f(m)))continue;let _=null;try{_=await a({deviceId:{exact:m.deviceId},...zn})}catch(y){l(m.label,y);continue}if(!g(_)){if(M(_))return n("camera-sbs",{label:_.label,width:_.width,height:_.height,direct:!0}),_;c(_)}}return null},E=null;if(i!=="mono"){let v=await h(),m=await R(v);if(m||v.some(_=>_.label)&&!v.some(_=>St(_.label))&&(v=await h(),m=await R(v),m))return S(m,"sbs");if(v.length&&v.every(_=>!_.label)){let _=null;try{_=await b(!0)}catch(C){l("default",C)}if(_&&_.stereo)return S(_,"sbs");_&&_.deviceId&&k.add(_.deviceId);let y=await R(await h());if(y)return c(_),S(y,"sbs");if(_&&M(_))return S(_,"sbs");_&&(E=await w(_,Ye))}}if(!E&&!x){let v=await h(),_=v.filter(f).length>0&&v.find(y=>y.deviceId&&!u.has(y.deviceId))||null;if(_){_.deviceId&&k.add(_.deviceId);try{E=await a({deviceId:{exact:_.deviceId},...Ye}),g(E)&&(E=null)}catch(y){l(_.label,y)}}else try{E=await b(Ye)}catch(y){l("default",y)}}if(i==="mono"&&E)return S(E,"mono");if(E&&M(E))return S(E,"sbs");let D=[];try{D=(await t.enumerateDevices()).filter(v=>v.kind==="videoinput")}catch{}D.sort((v,m)=>Number(St(m.label))-Number(St(v.label)));for(let v of D){if(!v.deviceId||E&&v.deviceId===E.deviceId||k.has(v.deviceId)||u.has(v.deviceId)||f(v))continue;let m=null;try{m=await a({deviceId:{exact:v.deviceId},...zn})}catch(_){l(v.label,_);continue}if(!g(m)){if(M(m)&&i!=="mono")return c(E),n("camera-sbs",{label:m.label,width:m.width,height:m.height}),S(m,"sbs");if(!E&&!M(m)){if(E=await w(m,Ye),i==="mono")return S(E,"mono");continue}c(m)}}if(E)return i==="stereo"&&n("camera-no-stereo",{fallback:E.label}),S(E,"mono");let O=Wn(r);throw Object.assign(new Error(O==="camera-busy"?"camera unavailable: in use by another app (e.g. eye tracking) or unable to deliver a picture":O==="permission-denied"?"camera access was denied":"no camera could be opened"),{code:O,skipped:r})}async function Hn(i={}){let e=i.mediaDevices||globalThis.navigator&&navigator.mediaDevices;try{return(await e.getUserMedia({audio:{...ha,...i.deviceId?{deviceId:{exact:i.deviceId}}:{}},video:!1})).getAudioTracks()[0]||null}catch(t){return(i.log||(()=>{}))("mic-skip",{error:t&&t.name}),null}}Ct();Ce();var Nr="http://displayxr.org/ns/stereo/1.0/",Pt="http://ns.adobe.com/xap/1.0/\0";function It(i={}){let e=n=>typeof n=="number"&&Number.isFinite(n)?n:null,t=i.layout==="sbs"||i.layout==="side-by-side"?"sbs":"mono";return{layout:t,columns:t==="sbs"?2:1,rows:1,convergencePx:e(i.convergencePx),baselineMm:e(i.baselineMm),horizontalFovDeg:e(i.horizontalFovDeg),rectified:i.rectified===!0?!0:i.rectified===!1?!1:null,eyeWidth:e(i.eyeWidth),eyeHeight:e(i.eyeHeight),software:typeof i.software=="string"&&i.software?i.software:null}}var ba=i=>String(i).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),ke=i=>Math.round(i*1e3)/1e3;function jr(i){let e=It(i),t=[["Layout",e.layout==="sbs"?"side-by-side":"mono"],["Columns",e.columns],["Rows",e.rows],["ConvergencePx",e.convergencePx===null?null:ke(e.convergencePx)],["BaselineMm",e.baselineMm===null?null:ke(e.baselineMm)],["HorizontalFovDeg",e.horizontalFovDeg===null?null:ke(e.horizontalFovDeg)],["Rectified",e.rectified===null?null:e.rectified?"True":"False"],["EyeWidth",e.eyeWidth],["EyeHeight",e.eyeHeight],["Software",e.software]].filter(([,n])=>n!=null).map(([n,r])=>` dxr:${n}="${ba(r)}"`).join("");return`<?xpacket begin="\uFEFF" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dxr="${Nr}"${t}/></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`}function Bn(i){if(typeof i!="string"||!i.includes(Nr))return null;let e=o=>{let a=new RegExp(`\\bdxr:${o}="([^"]*)"`).exec(i);if(a)return a[1];let l=new RegExp(`<dxr:${o}>([^<]*)</dxr:${o}>`).exec(i);return l?l[1]:null},t=o=>{let a=e(o);return a===null||a===""||!Number.isFinite(+a)?null:+a},n=e("Rectified"),r=e("Layout"),s=e("Software");return It({layout:r==="side-by-side"||r==="sbs"?"sbs":"mono",convergencePx:t("ConvergencePx"),baselineMm:t("BaselineMm"),horizontalFovDeg:t("HorizontalFovDeg"),rectified:n===null?null:/^true$/i.test(n),eyeWidth:t("EyeWidth"),eyeHeight:t("EyeHeight"),software:s===null?null:s.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&amp;/g,"&")})}var Lt=i=>new TextEncoder().encode(i),Vn=i=>new TextDecoder().decode(i),zr=i=>i.length>4&&i[0]===255&&i[1]===216;function*Wr(i){let e=2;for(;e+4<=i.length;){if(i[e]!==255)return;let t=i[e+1];if(t===216||t>=208&&t<=215||t===1||t===255){e+=t===255?1:2;continue}if(t===218||t===217)return;let n=i[e+2]<<8|i[e+3];if(n<2||e+2+n>i.length)return;yield{marker:t,start:e,end:e+2+n,data:i.subarray(e+4,e+2+n)},e+=2+n}}function Hr(i,e){if(i.length<e.length)return!1;for(let t=0;t<e.length;t++)if(i[t]!==e.charCodeAt(t))return!1;return!0}function $r(i,e){if(!zr(i))throw new TypeError("jpegWithXmp: not a JPEG");let t=new Uint8Array([...Lt(Pt),...Lt(e)]),n=t.length+2;if(n>65535)throw new RangeError("jpegWithXmp: XMP packet too large for one APP1 segment");let r=new Uint8Array(4+t.length);r[0]=255,r[1]=225,r[2]=n>>8,r[3]=n&255,r.set(t,4);let s=2,o=null;for(let h of Wr(i)){if(h.marker===225&&Hr(h.data,Pt)){o=h;break}if(h.marker===224||h.marker===225)s=h.end;else break}let[a,l]=o?[o.start,o.end]:[s,s],c=new Uint8Array(i.length-(l-a)+r.length);return c.set(i.subarray(0,a),0),c.set(r,a),c.set(i.subarray(l),a+r.length),c}function Xn(i){if(!zr(i))return null;for(let e of Wr(i))if(e.marker===225&&Hr(e.data,Pt))return Vn(e.data.subarray(Pt.length));return null}var Ur=i=>Bn(Xn(i)),V={EBML:440786851,Segment:408125543,Tags:307544935,Tag:29555,Targets:25536,SimpleTag:26568,TagName:17827,TagString:17543},xa=i=>i.length>4&&i[0]===26&&i[1]===69&&i[2]===223&&i[3]===163;function Vr(i){let e=[];for(let t=i;t>0;t=Math.floor(t/256))e.unshift(t%256);return e}function Br(i,e=0){let t=e;if(!t)for(t=1;t<8&&i>2**(7*t)-2;t++);let n=new Array(t).fill(0),r=i;for(let s=t-1;s>=1;s--)n[s]=r%256,r=Math.floor(r/256);return n[0]=128>>t-1|r,n}function Gn(i,e){let t=i[e],n=t>=128?1:t>=64?2:t>=32?3:t>=16?4:0;if(!n||e+n>i.length)return null;let r=0;for(let s=0;s<n;s++)r=r*256+i[e+s];return{id:r,width:n}}function Ke(i,e){let t=i[e],n=1;for(;n<=8&&!(t&128>>n-1);)n++;if(n>8||e+n>i.length)return null;let r=t&255>>n,s=r===127>>n-1;for(let o=1;o<n;o++)r=r*256+i[e+o],i[e+o]!==255&&(s=!1);return{size:r,width:n,unknown:s}}function Re(i,e){return[...Vr(i),...Br(e.length),...e]}function Sa(i){let e=[];for(let[n,r]of Object.entries(i))r!=null&&e.push(...Re(V.SimpleTag,[...Re(V.TagName,[...Lt(String(n))]),...Re(V.TagString,[...Lt(String(r))])]));let t=Re(V.Tag,[...Re(V.Targets,[]),...e]);return new Uint8Array(Re(V.Tags,t))}function Xr(i){let e=It(i);return{DXR_LAYOUT:e.layout==="sbs"?"side-by-side":"mono",DXR_COLUMNS:String(e.columns),DXR_ROWS:String(e.rows),DXR_CONVERGENCE_PX:e.convergencePx===null?null:String(ke(e.convergencePx)),DXR_BASELINE_MM:e.baselineMm===null?null:String(ke(e.baselineMm)),DXR_HFOV_DEG:e.horizontalFovDeg===null?null:String(ke(e.horizontalFovDeg)),DXR_RECTIFIED:e.rectified===null?null:e.rectified?"true":"false",DXR_EYE_WIDTH:e.eyeWidth===null?null:String(e.eyeWidth),DXR_EYE_HEIGHT:e.eyeHeight===null?null:String(e.eyeHeight),DXR_SOFTWARE:e.software}}function Ma(i){if(!i||!("DXR_LAYOUT"in i))return null;let e=t=>i[t]===void 0||i[t]===""||!Number.isFinite(+i[t])?null:+i[t];return It({layout:i.DXR_LAYOUT==="side-by-side"?"sbs":"mono",convergencePx:e("DXR_CONVERGENCE_PX"),baselineMm:e("DXR_BASELINE_MM"),horizontalFovDeg:e("DXR_HFOV_DEG"),rectified:i.DXR_RECTIFIED===void 0?null:i.DXR_RECTIFIED==="true",eyeWidth:e("DXR_EYE_WIDTH"),eyeHeight:e("DXR_EYE_HEIGHT"),software:i.DXR_SOFTWARE??null})}function Gr(i){if(!xa(i))return null;let e=Ke(i,4);if(!e)return null;let t=4+e.width+e.size;for(;t<i.length;){let n=Gn(i,t);if(!n)return null;let r=Ke(i,t+n.width);if(!r)return null;let s=t+n.width+r.width;if(n.id===V.Segment)return{sizeAt:t+n.width,sizeWidth:r.width,unknown:r.unknown,dataStart:s,size:r.size};if(r.unknown)return null;t=s+r.size}return null}function qr(i,e){let t=Gr(i);if(!t)throw new TypeError("webmWithTags: not a WebM/Matroska file (no Segment)");let n=Sa(e);if(t.unknown){let h=new Uint8Array(i.length+n.length);return h.set(i,0),h.set(n,i.length),h}let r=Math.min(i.length,t.dataStart+t.size),s=r-t.dataStart+n.length,o=s<=2**(7*t.sizeWidth)-2,a=Br(s,o?t.sizeWidth:8),l=new Uint8Array(t.sizeAt+a.length+(r-t.dataStart)+n.length+(i.length-r));l.set(i.subarray(0,t.sizeAt),0),l.set(a,t.sizeAt);let c=t.sizeAt+a.length;return l.set(i.subarray(t.dataStart,r),c),c+=r-t.dataStart,l.set(n,c),c+=n.length,l.set(i.subarray(r),c),l}function Yr(i,e,t){let n={},r=(s,o,a)=>{let l=s;for(;l<o;){let c=Gn(i,l);if(!c)return;let h=Ke(i,l+c.width);if(!h||h.unknown)return;let u=l+c.width+h.width;a(c.id,u,Math.min(o,u+h.size)),l=u+h.size}};return r(e,t,(s,o,a)=>{s===V.Tag&&r(o,a,(l,c,h)=>{if(l!==V.SimpleTag)return;let u=null,d=null;r(c,h,(p,f,g)=>{p===V.TagName?u=Vn(i.subarray(f,g)):p===V.TagString&&(d=Vn(i.subarray(f,g)))}),u!==null&&(n[u]=d??"")})}),n}function Ea(i){let e=Gr(i);if(!e)return null;let t=e.unknown?i.length:Math.min(i.length,e.dataStart+e.size),n=null,r=e.dataStart;for(;r<t;){let s=Gn(i,r);if(!s)break;let o=Ke(i,r+s.width);if(!o)break;let a=r+s.width+o.width;if(s.id===V.Tags&&!o.unknown&&(n={...n||{},...Yr(i,a,Math.min(t,a+o.size))}),o.unknown){n=n||Ca(i,t);break}r=a+o.size}return n}function Ca(i,e){let t=Vr(V.Tags);for(let n=e-t.length-1;n>=0;n--){if(i[n]!==t[0]||i[n+1]!==t[1]||i[n+2]!==t[2]||i[n+3]!==t[3])continue;let r=Ke(i,n+4);if(r&&!r.unknown&&n+4+r.width+r.size===e)return Yr(i,n+4+r.width,e)}return null}var Kr=i=>Ma(Ea(i));var ue="[inline3d/camera]",js="inline3d-camera/1",Ga=200,qa=240,Ya=66,Ka=4e3,Ja=4,Za=1500,Qa=2e4,el=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"],Gt=()=>typeof document<"u"&&document&&typeof document.createElement=="function",Fs=()=>{let i=new Date,e=t=>String(t).padStart(2,"0");return`${i.getFullYear()}${e(i.getMonth()+1)}${e(i.getDate())}-${e(i.getHours())}${e(i.getMinutes())}${e(i.getSeconds())}`},tl=i=>/jpe?g/.test(i)?"jpg":/png/.test(i)?"png":/webp/.test(i)?"webp":/mp4/.test(i)?"mp4":/webm/.test(i)?"webm":"bin";function qt(i,e,t){return`${String(i||"capture").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"capture"}${e==="sbs"?"_2x1":""}.${tl(t)}`}var re=(i,e,t={})=>Object.assign(new Error(`${ue} ${i}`),{code:e,...t});function Ns(i,e=Ka){return i?(i.readyState||0)>=2&&i.videoWidth?Promise.resolve():new Promise((t,n)=>{let r=!1,s=()=>{r||(i.readyState||0)<2||!i.videoWidth||(r=!0,clearTimeout(o),i.removeEventListener("loadeddata",s),i.removeEventListener("playing",s),i.removeEventListener("resize",s),t())},o=setTimeout(()=>{r||(r=!0,n(re("the camera delivered no frame in time","no-frame")))},e);i.addEventListener("loadeddata",s),i.addEventListener("playing",s),i.addEventListener("resize",s),i.play?.().catch(()=>{})}):Promise.reject(re("no video element (no document?)","no-frame"))}function zs(i,e,t=qa){let n=i.videoWidth,r=i.videoHeight;if(!n||!r||(i.readyState||0)<2)return null;let s=Math.min(1,t/(n/2)),o=Math.max(2,Math.round(n*s/2)*2),a=Math.max(2,Math.round(r*s));(e.width!==o||e.height!==a)&&(e.width=o,e.height=a);let l=e.getContext("2d",{willReadFrequently:!0});try{return l.drawImage(i,0,0,o,a),{img:Et(l.getImageData(0,0,o,a).data,o*a),w:o,h:a,scale:o/n}}catch{return null}}var mi=class{constructor(e,{log:t=null}={}){this.format=e.format,this.stream=e.stream,this.width=e.width||0,this.height=e.height||0,this.deviceId=e.deviceId||null,this.label=e.label||"",this.owned=!!e.owned,this.skipped=Object.freeze([...e.skipped||[]]),this.calibration=Object.freeze({...e.calibration||{}});let n=this.calibration;this.stereo=this.format==="sbs"?Object.freeze({rectified:!!n.rectified,baselineMm:n.baselineMm>0?n.baselineMm:null,horizontalFovDeg:n.hfovDeg>0?n.hfovDeg:null}):null,this.state="live",this._log=t,this._listeners=new Map,this._scratch=null,this._views=new Set,this.video=null,Gt()&&(this.video=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,autoplay:!0}),this.video.srcObject=this.stream,this.video.play?.().catch(()=>{})),this._onEnded=()=>this._ended("ended");for(let r of this.stream.getVideoTracks())r.addEventListener?.("ended",this._onEnded)}get facing(){try{let e=this.stream.getVideoTracks()[0]?.getSettings?.().facingMode;return typeof e=="string"&&e?e:null}catch{return null}}get eyeWidth(){return this.format==="sbs"?this.width/2:this.width}log(e,t={}){this._log&&this._log(e,t)}on(e,t){if(typeof t!="function")throw new TypeError(`${ue} on() takes a function`);return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e,t){for(let n of[...this._listeners.get(e)||[]])try{n(t)}catch(r){console.error(`${ue} '${e}' listener threw`,r)}}_ended(e){this.state==="live"&&(this.state="ended",this.log("ended",{reason:e}),this._emit("ended",{reason:e}))}async measureConvergence(){if(this.format!=="sbs"||!this.video||!Gt())return null;try{await Ns(this.video)}catch{return null}this._scratch=this._scratch||document.createElement("canvas");let e=zs(this.video,this._scratch);if(!e)return null;let t=ce().measure(e.img,e.w,e.h,0);return t?t.d/e.scale:null}_meta(e,t=this.width,n=this.height){let r=this.stereo;return{layout:this.format,convergencePx:e,baselineMm:r?r.baselineMm:null,horizontalFovDeg:r?r.horizontalFovDeg:null,rectified:r?r.rectified:null,eyeWidth:this.format==="sbs"?t/2:t,eyeHeight:n,software:js}}async capturePhoto({type:e="image/jpeg",quality:t=.92,name:n,convergencePx:r}={}){if(this.state==="closed")throw re("the camera is closed","closed");if(!this.video||!Gt())throw re("capturePhoto needs a document","no-frame");await Ns(this.video);let s=this.video.videoWidth,o=this.video.videoHeight,a=typeof r=="number"&&Number.isFinite(r)?r:await this.measureConvergence(),l=document.createElement("canvas");l.width=s,l.height=o,l.getContext("2d").drawImage(this.video,0,0,s,o);let c=await new Promise((p,f)=>l.toBlob(g=>g?p(g):f(re("toBlob produced nothing","encode-failed")),e,t)),h=this._meta(a,s,o),u=null;(c.type==="image/jpeg"||/jpe?g/.test(e))&&(u=jr(h),c=new Blob([$r(new Uint8Array(await c.arrayBuffer()),u)],{type:"image/jpeg"}));let d={blob:c,type:c.type||e,width:s,height:o,layout:this.format,convergencePx:a,stereo:this.stereo,suggestedName:qt(n||`photo-${Fs()}`,this.format,c.type||e),xmp:u};return this.log("photo",{width:s,height:o,layout:this.format,convergencePx:a,bytes:c.size,name:d.suggestedName}),d}record({mimeType:e,mono:t=!1,audio:n=null,videoBitsPerSecond:r,timesliceMs:s=1e3,name:o,fps:a=30}={}){if(this.state==="closed")throw re("the camera is closed","closed");if(typeof MediaRecorder!="function")throw re("MediaRecorder is not available here","unsupported");let l=e||el.find(m=>typeof MediaRecorder.isTypeSupported!="function"||MediaRecorder.isTypeSupported(m))||"";if(l&&typeof MediaRecorder.isTypeSupported=="function"&&!MediaRecorder.isTypeSupported(l))throw re(`${l} is not a supported recording type here`,"unsupported");let c=[...this.stream.getVideoTracks()],h=n&&typeof n.getAudioTracks=="function"?n.getAudioTracks():n&&n.kind==="audio"?[n]:[];c.push(...h);let u=new MediaStream(c),d={...l?{mimeType:l}:{},...r?{videoBitsPerSecond:r}:{}},p=new MediaRecorder(u,d),f=[];p.ondataavailable=m=>m.data&&m.data.size&&f.push(m.data);let g=null,x=[],b=null,w=0,M=!!t&&this.format==="sbs"&&Gt()&&this.video;if(M){b=document.createElement("canvas");let m=()=>{w=requestAnimationFrame(m);let y=this.video,C=y.videoWidth,I=y.videoHeight;!C||!I||(y.readyState||0)<2||((b.width!==C/2||b.height!==I)&&(b.width=C/2,b.height=I),b.getContext("2d").drawImage(y,0,0,C/2,I,0,0,C/2,I))};m();let _=b.captureStream(a);for(let y of h)_.addTrack(y);g=new MediaRecorder(_,d),g.ondataavailable=y=>y.data&&y.data.size&&x.push(y.data)}let S=performance.now(),k=[],R=this.format==="sbs"?setInterval(()=>this.measureConvergence().then(m=>m!==null&&k.push(m)),1500):0;this.measureConvergence().then(m=>m!==null&&k.push(m)),p.start(s),g?.start(s),this.log("record-start",{mimeType:l,mono:M,audio:h.length});let E=(m,_)=>new Promise(y=>{if(!m||m.state==="inactive")return y(_);m.onstop=()=>y(_),m.stop()}),D=o||`clip-${Fs()}`,O=this;return{get state(){return p.state},get mimeType(){return p.mimeType||l},pause(){p.state==="recording"&&p.pause(),g&&g.state==="recording"&&g.pause()},resume(){p.state==="paused"&&p.resume(),g&&g.state==="paused"&&g.resume()},async stop(){clearInterval(R),w&&cancelAnimationFrame(w);let[m,_]=await Promise.all([E(p,f),E(g,x)]),y=p.mimeType||l||m[0]&&m[0].type||"video/webm",C=[...k].sort((Le,K)=>Le-K),I=C.length?C[Math.floor(C.length/2)]:null,T=O._meta(I),N=/webm|matroska/.test(y),$=async(Le,K)=>{let ae=new Blob(Le,{type:y});if(N&&ae.size)try{ae=new Blob([qr(new Uint8Array(await ae.arrayBuffer()),Xr({...T,layout:K}))],{type:y})}catch(Di){O.log("record-tag-failed",{message:String(Di&&Di.message)})}return ae},L=await $(m,O.format),z={blob:L,type:y,layout:O.format,durationMs:Math.round(performance.now()-S),convergencePx:I,stereo:O.stereo,suggestedName:qt(D,O.format,y),tagged:N&&L.size>0};return g&&(z.mono=await $(_,"mono"),z.monoSuggestedName=qt(D,"mono",y)),O.log("record-stop",{bytes:L.size,mono:z.mono?z.mono.size:null,ms:z.durationMs,convergencePx:I,name:z.suggestedName}),z}}}close(){if(this.state!=="closed"){this.state="closed";for(let e of this.stream.getVideoTracks())e.removeEventListener?.("ended",this._onEnded);for(let e of[...this._views])e.remove();this.owned&&this.stream.getTracks().forEach(e=>e.stop()),this.video&&(this.video.srcObject=null),this.log("closed",{})}}};async function _i(i={}){let e=typeof i=="string"||i&&typeof i.getVideoTracks=="function"?{prefer:i}:i||{},t=e.prefer===void 0||e.prefer===null?"auto":e.prefer,n=typeof e.log=="function"?e.log:e.debug?(a,l)=>console.log(`${ue} ${a} ${JSON.stringify(l)}`):null,r=e.calibration&&typeof e.calibration=="object"?{...e.calibration}:{};r.horizontalFovDeg>0&&!(r.hfovDeg>0)&&(r.hfovDeg=r.horizontalFovDeg),delete r.horizontalFovDeg;let s=await Or(t,{format:e.format,calibration:r,mediaDevices:e.mediaDevices,log:n||void 0,exclude:e.exclude});if(s.format==="sbs"&&typeof e.rectify=="function")try{let a=await e.rectify(s.stream,{width:s.width,height:s.height,deviceId:s.deviceId,label:s.label});a&&typeof a.getVideoTracks=="function"&&(s.stream=a,s.calibration={...s.calibration,rectified:!0})}catch(a){n?.("rectify-failed",{message:String(a&&a.message)}),s.rectifyError=a}let o=new mi(s,{log:n});return s.rectifyError&&(o.rectifyError=s.rectifyError),o.log("open",{format:o.format,width:o.width,height:o.height,label:o.label,stereo:o.stereo,skipped:o.skipped.length}),o}var Yt=i=>!!i&&typeof i=="object"&&typeof i.capturePhoto=="function"&&typeof i.record=="function"&&i.stream&&typeof i.stream.getVideoTracks=="function";function nl(i){let e=Math.min(globalThis.devicePixelRatio||1,2),t=Math.round((i.clientWidth||0)*e),n=Math.round((i.clientHeight||0)*e);return!t||!n?!1:((i.width!==t||i.height!==n)&&(i.width=t,i.height=n),!0)}function vi(i,e,t,n={}){if(!e||typeof e.getContext!="function")throw new TypeError(`${ue} addCameraView(wall, canvas, cam, opts) needs a canvas`);if(!Yt(t))throw new TypeError(`${ue} addCameraView: cam must be a StereoCamera from openCamera()`);let r=new gi(i,e,t,n);return t._views?.add(r),r}var gi=class{constructor(e,t,n,r){this.wall=e||null,this.canvas=t,this.cam=n,this.mirror=r.mirror===void 0?n.facing!=="environment":!!r.mirror,this.aspect=r.aspect==="fill"?"fill":typeof r.aspect=="number"&&r.aspect>.3&&r.aspect<4?r.aspect:16/9,this.rectCover=r.rectCover,this.autoConverge=!!r.autoConverge,this.conv=He(),this.conv.depth=0,this.setDepth(r.depth),this.route=null,this.handle=null,this.fallbackReason=null,this._fw=null,this._onRouteChange=typeof r.onRouteChange=="function"?r.onRouteChange:null,this._layerFails=0,this._layerTimer=0,this.buffer=null,this.removed=!1,this._raf=0,this._loop=r._loop!==!1,this._autoAt=0,this._track=xe(),this._focus=ce(),this._scratch=null,this._luma=null,this.disparityPx=null,this._cursorOpt=Dt(r.cursor,"@displayxr/inline3d/camera"),this.cursor=null,this._cursorOpt&&Promise.resolve().then(()=>(pi(),fi)).then(s=>{this.removed||(this.cursor=new s.PairCursor(this.canvas,this._cursorOpt))}),this._reroute(!1),this._loop&&this._start()}get woven(){return this.route==="woven-sbs"}weaveState(){return{route:this.route,woven:this.woven,reason:this.fallbackReason,firstWoven:this.route==="woven-sbs"?this._fw?{...this._fw}:"pending":null,layerRetries:this._layerFails}}get convergencePx(){return this.conv.current}get depth(){return this.conv.depth}setDepth(e){let t=e==null||!Number.isFinite(+e)?0:Math.max(-1,Math.min(1,+e));return this.conv.depth=t,t}setMirror(e){return this.mirror=e===void 0?!this.mirror:!!e,this.mirror}setAutoConverge(e){return this.autoConverge=e===void 0?!this.autoConverge:!!e,this.autoConverge||(this._track.reset(),this._focus.reset(),this.conv.measuredPx=null,this.disparityPx=null),this.autoConverge}_reroute(e,t){if(t!==void 0&&(this.wall=t),this.removed)return;e&&this.fallbackReason&&(this.fallbackReason=null,clearTimeout(this._layerTimer),this._layerTimer=0);let n=this.cam,r=n.state==="live"&&n.video,o=n.format==="sbs"&&r&&this.wall&&this.wall.supported&&!this.fallbackReason?"woven-sbs":n.format==="sbs"?"flat-left":"flat";if(!e&&o===this.route)return;let a=this.route;this._unregister(),this.route=o,o==="woven-sbs"&&this._registerWoven(),o!==a&&this._routeChanged()}_registerWoven(){this.buffer||(this.buffer=document.createElement("canvas")),this._paintWoven();let e=this.rectCover===void 0?this.wall.addImage(this.canvas,this.buffer):this.wall.addImage(this.canvas,this.buffer,{rectCover:this.rectCover});this.handle=e,this._fw=null;let t=e&&e.firstWoven;!t||typeof t.then!="function"||t.then(n=>{this.handle!==e||this.removed||!n||(this._fw={woven:!!n.woven,confirmed:!!n.confirmed,reason:n.reason||null,ms:n.ms},this.cam.log?.("view-first-woven",{woven:!!n.woven,reason:n.reason||null}),n.woven?(this._layerFails=0,this._routeChanged()):n.reason!=="removed"&&this._layerLost(n.reason||"layer-failed"))})}_layerLost(e){if(this.fallbackReason=e,this._reroute(!1),e!=="layer-failed"||this._layerFails>=Ja)return;let t=Math.min(Qa,Za*Math.pow(2,this._layerFails++));this.cam.log?.("view-layer-retry",{attempt:this._layerFails,inMs:t}),clearTimeout(this._layerTimer),this._layerTimer=setTimeout(()=>{this._layerTimer=0,!(this.removed||this.fallbackReason!==e)&&this._reroute(!0)},t)}_routeChanged(){if(this._onRouteChange)try{this._onRouteChange(this.route,this.weaveState())}catch(e){console.error(`${ue} onRouteChange threw`,e)}}_onWallLost(){this._reroute(!0,{supported:!1})}_unregister(){if(this.handle){try{this.handle.remove()}catch{}this.handle=null}}_start(){let e=()=>{this._raf=requestAnimationFrame(e),this.paint()};this._raf=requestAnimationFrame(e)}paint(){if(this.removed)return;let e=this.cam.video;!e||this.cam.state==="closed"||(this.route==="woven-sbs"?this._paintWoven():this._paintFlat(e))}_paintFlat(e){if(this.cursor?.idle(),!nl(this.canvas))return;let t=e.videoWidth,n=e.videoHeight;if(!t||!n||(e.readyState||0)<2)return;let r=this.canvas.getContext("2d"),s=this.route==="flat-left"?t/2:t,o=q(s,n,this.canvas.width/this.canvas.height,0,0);r.save(),this.mirror&&(r.translate(this.canvas.width,0),r.scale(-1,1)),r.drawImage(e,o.sx,o.sy,o.sw,o.sh,0,0,this.canvas.width,this.canvas.height),r.restore()}_paintWoven(){let e=this.cam.video,t=e.videoWidth,n=e.videoHeight;if(!t||!n||(e.readyState||0)<2||!this.buffer)return;let r=t/2,s=this._eyeAspect(),{w:o,h:a}=We(r,n,s),l=this.buffer;(l.width!==2*o||l.height!==a)&&(l.width=2*o,l.height=a);let c=!!(this.cursor&&this.cursor.hovering);(this.autoConverge||c)&&this._sample(e,c);let h=this.conv.step(r),u=l.getContext("2d");if(this.mirror)for(let d of ve(t,n)){let p=d.src==="L"?0:1,f=q(r,n,s,h,p),g=d.dx===0?0:o;u.save(),u.translate(g+o,0),u.scale(-1,1),u.drawImage(e,d.sx+f.sx,f.sy,f.sw,f.sh,0,0,o,a),u.restore()}else for(let d of[0,1]){let p=q(r,n,s,h,d);u.drawImage(e,d*r+p.sx,p.sy,p.sw,p.sh,d*o,0,o,a)}if(this.cursor){let d={rL:q(r,n,s,h,0),rR:q(r,n,s,h,1),outW:o,outH:a,mirror:this.mirror,handle:this.handle};this.cursor.draw(u,this._luma,d,performance.now()/1e3)}}_eyeAspect(){if(this.aspect!=="fill")return this.aspect;let e=this.canvas.clientWidth||0,t=this.canvas.clientHeight||0;return e>0&&t>0&&(this._fillAspect=Math.max(.3,Math.min(4,e/t))),this._fillAspect||16/9}_sample(e,t=!1){let n=performance.now();if(n-this._autoAt<(t?Ya:Ga))return;this._autoAt=n,this._scratch=this._scratch||document.createElement("canvas");let r=zs(e,this._scratch);if(r&&(this._luma=r),!this.autoConverge)return;let s=r?this._focus.measure(r.img,r.w,r.h,n):null,o=this._track.push(s?s.d/r.scale:null);this.conv.measuredPx=o,this.disparityPx=o}remove(){this.removed||(this.removed=!0,this._raf&&cancelAnimationFrame(this._raf),this._raf=0,clearTimeout(this._layerTimer),this._layerTimer=0,this._unregister(),this.cursor?.dispose(),this.cursor=null,this.cam._views?.delete(this))}};var Hs=[[-1,7,10,15,20,26,18,20,24,30,18],[-1,10,16,26,18,24,16,18,22,22,26]],$s=[[-1,1,1,1,1,1,2,2,2,2,4],[-1,1,1,1,2,2,4,4,4,5,5]],il=[1,0],yi=10;function Us(i){let e=(16*i+128)*i+64;if(i>=2){let t=Math.floor(i/7)+2;e-=(25*t-10)*t-55,i>=7&&(e-=36)}return e}var Ws=(i,e)=>Math.floor(Us(i)/8)-Hs[e][i]*$s[e][i];function wi(i,e){let t=0;for(let n=7;n>=0;n--)t=t<<1^(t>>>7)*285,t^=(e>>>n&1)*i;return t}function rl(i){let e=new Array(i-1).fill(0);e.push(1);let t=1;for(let n=0;n<i;n++){for(let r=0;r<e.length;r++)e[r]=wi(e[r],t),r+1<e.length&&(e[r]^=e[r+1]);t=wi(t,2)}return e}function sl(i,e){let t=e.map(()=>0);for(let n of i){let r=n^t.shift();t.push(0),e.forEach((s,o)=>t[o]^=wi(s,r))}return t}function bi(i,e={}){let t=e.ecl==="L"?0:1,n=[...new TextEncoder().encode(String(i))],r=1;for(;r<=yi&&!(4+(r<=9?8:16)+n.length*8<=Ws(r,t)*8);r++);if(r>yi)throw new Error(`qrEncode: ${n.length} bytes is too long for a version-${yi} code`);let s=[],o=(m,_)=>{for(let y=_-1;y>=0;y--)s.push(m>>>y&1)};o(4,4),o(n.length,r<=9?8:16);for(let m of n)o(m,8);let a=Ws(r,t)*8;o(0,Math.min(4,a-s.length)),o(0,(8-s.length%8)%8);for(let m=236;s.length<a;m^=253)o(m,8);let l=[];for(let m=0;m<s.length;m+=8)l.push(s.slice(m,m+8).reduce((_,y)=>_<<1|y,0));let c=$s[t][r],h=Hs[t][r],u=Math.floor(Us(r)/8),d=c-u%c,p=Math.floor(u/c),f=rl(h),g=[];for(let m=0,_=0;m<c;m++){let y=l.slice(_,_+p-h+(m<d?0:1));_+=y.length;let C=sl(y,f);m<d&&y.push(0),g.push(y.concat(C))}let x=[];for(let m=0;m<g[0].length;m++)for(let _=0;_<g.length;_++)(m!==p-h||_>=d)&&x.push(g[_][m]);let b=r*4+17,w=Array.from({length:b},()=>new Array(b).fill(!1)),M=Array.from({length:b},()=>new Array(b).fill(!1)),S=(m,_,y)=>{w[_][m]=y,M[_][m]=!0};for(let m=0;m<b;m++)S(6,m,m%2===0),S(m,6,m%2===0);let k=(m,_)=>{for(let y=-4;y<=4;y++)for(let C=-4;C<=4;C++){let I=Math.max(Math.abs(C),Math.abs(y)),T=m+C,N=_+y;T>=0&&T<b&&N>=0&&N<b&&S(T,N,I!==2&&I!==4)}};k(3,3),k(b-4,3),k(3,b-4);let R=[];if(r>1){let m=Math.floor(r/7)+2,_=Math.ceil((r*4+4)/(m*2-2))*2;R.push(6);for(let y=b-7;R.length<m;y-=_)R.splice(1,0,y)}for(let m=0;m<R.length;m++)for(let _=0;_<R.length;_++)if(!(m===0&&_===0||m===0&&_===R.length-1||m===R.length-1&&_===0))for(let y=-2;y<=2;y++)for(let C=-2;C<=2;C++)S(R[m]+C,R[_]+y,Math.max(Math.abs(C),Math.abs(y))!==1);let E=m=>{let _=il[t]<<3|m,y=_;for(let T=0;T<10;T++)y=y<<1^(y>>>9)*1335;let C=(_<<10|y)^21522,I=T=>(C>>>T&1)!==0;for(let T=0;T<=5;T++)S(8,T,I(T));S(8,7,I(6)),S(8,8,I(7)),S(7,8,I(8));for(let T=9;T<15;T++)S(14-T,8,I(T));for(let T=0;T<8;T++)S(b-1-T,8,I(T));for(let T=8;T<15;T++)S(8,b-15+T,I(T));S(8,b-8,!0)};if(E(0),r>=7){let m=r;for(let y=0;y<12;y++)m=m<<1^(m>>>11)*7973;let _=r<<12|m;for(let y=0;y<18;y++){let C=(_>>>y&1)!==0,I=b-11+y%3,T=Math.floor(y/3);S(I,T,C),S(T,I,C)}}let D=0;for(let m=b-1;m>=1;m-=2){m===6&&(m=5);for(let _=0;_<b;_++)for(let y=0;y<2;y++){let C=m-y,T=(m+1&2)===0?b-1-_:_;!M[T][C]&&D<x.length*8&&(w[T][C]=(x[D>>>3]>>>7-(D&7)&1)!==0,D++)}}let O=m=>{for(let _=0;_<b;_++)for(let y=0;y<b;y++){if(M[_][y])continue;let C;switch(m){case 0:C=(y+_)%2===0;break;case 1:C=_%2===0;break;case 2:C=y%3===0;break;case 3:C=(y+_)%3===0;break;case 4:C=(Math.floor(y/3)+Math.floor(_/2))%2===0;break;case 5:C=y*_%2+y*_%3===0;break;case 6:C=(y*_%2+y*_%3)%2===0;break;default:C=((y+_)%2+y*_%3)%2===0}C&&(w[_][y]=!w[_][y])}},v=Number.isInteger(e.mask)?e.mask:-1;if(v<0){let m=1/0;for(let _=0;_<8;_++){O(_),E(_);let y=ol(w,b);y<m&&(m=y,v=_),O(_)}}return O(v),E(v),{version:r,size:b,mask:v,modules:w}}function ol(i,e){let t=0,n=[];for(let o=0;o<e;o++)n.push(i[o]);for(let o=0;o<e;o++)n.push(i.map(a=>a[o]));for(let o of n){let a=1;for(let c=1;c<=e;c++)c<e&&o[c]===o[c-1]?a++:(a>=5&&(t+=a-2),a=1);let l=o.map(c=>c?"1":"0").join("");for(let c of["10111010000","00001011101"])for(let h=l.indexOf(c);h>=0;h=l.indexOf(c,h+1))t+=40}let r=0;for(let o=0;o<e;o++)for(let a=0;a<e;a++)if(i[o][a]&&r++,a<e-1&&o<e-1){let l=i[o][a];l===i[o][a+1]&&l===i[o+1][a]&&l===i[o+1][a+1]&&(t+=3)}let s=e*e;return t+=Math.floor(Math.abs(r*20-s*10)/s)*10,t}function Vs(i,e,{px:t=4,dark:n="#000",light:r="#fff",ecl:s="M"}={}){let o=bi(e,{ecl:s}),a=o.size+8;i.width=i.height=a*t;let l=i.getContext("2d");l.fillStyle=r,l.fillRect(0,0,a*t,a*t),l.fillStyle=n;for(let c=0;c<o.size;c++)for(let h=0;h<o.size;h++)o.modules[c][h]&&l.fillRect((h+4)*t,(c+4)*t,t,t);return o}function se(i,e){let t=new Error(`@displayxr/inline3d/call: ${e}`);return t.code=i,t}async function xi(i){let e=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(String(i)));return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}var Kt="wss://signal.displayxr.org",Bs=Object.freeze([Kt,"wss://dxr-signal.displayxr.workers.dev"]),Xs=["bad-room","bad-id","bad-version","bad-key","origin-not-allowed","blocked"];function De(i=Kt,e={}){if(!i||typeof i!="string")throw se("no-signaling-url","dxrSignaling(url): url must be a ws:// or wss:// string (omit it for the hosted DisplayXR server)");let t=c=>String(c).replace(/\/+$/,""),n=t(i),r=e.WebSocket||globalThis.WebSocket,s=e.pingMs||2e4,o=Array.isArray(e.aliases)?e.aliases.filter(c=>typeof c=="string"&&c).map(t):Bs.includes(n)?[...Bs]:[],a=[n,...o.filter(c=>c!==n)],l=0;return{name:"dxr",url:n,async join(c,h){let d=`k=${await xi(c)}${typeof e.key=="string"&&e.key?`&key=${encodeURIComponent(e.key)}`:""}`,p=O=>`${a[O]}/v1/connect?${d}`,f=null,g=!1,x=0,b=null,w=new Set,M=[],S=O=>k(O,a.length),k=(O,v)=>new Promise((m,_)=>{let y=!1,C=!1,I=!1,T=new r(p(l));f=T;let N=$=>{if(!y){y=!0;try{T.close()}catch{}_($)}};T.onopen=()=>{I=!0,T.send(JSON.stringify({t:"join",v:1,room:c,id:h.id,max:h.maxPeers}))},T.onmessage=$=>{let L;try{L=JSON.parse(typeof $.data=="string"?$.data:String($.data))}catch{return}switch(L.t){case"welcome":{x=0;let z=Array.isArray(L.peers)?L.peers.filter(K=>typeof K=="string"):[];clearInterval(b),b=setInterval(()=>R({t:"ping"}),s);let Le=M;M=[];for(let K of Le)R(K);if(O){let K=new Set(z);for(let ae of w)K.has(ae)||h.onPeerLeft?.(ae);w=K,h.onReconnect?.(z)}else w=new Set(z);y=!0,C=!0,m({id:L.id,peers:z,iceServers:Array.isArray(L.iceServers)?L.iceServers:void 0,max:L.max,tier:L.tier==="key"?"key":"anon",key:typeof L.key=="string"?L.key:void 0,turn:L.turn&&typeof L.turn=="object"?L.turn:void 0});break}case"full":g=!0,N(se("room-full",`this call is full (${L.max} participants)`));break;case"expired":{g=!0,clearInterval(b);let z=se("expired","this room has reached its lifetime on the signalling server");y?h.onDisconnect?.(z):N(z);break}case"error":if(!y&&Xs.includes(L.code))g=!0,N(se(L.code,L.message||L.code));else if(!y&&(L.code==="rate-limited"||L.code==="quota")){let z=se(L.code,L.message||L.code);z.retryMs=L.retryMs>0?L.retryMs:0,N(z)}else!y&&L.code==="id-taken"&&N(se("id-taken","peer id still held; retrying"));break;case"peer-joined":typeof L.id=="string"&&!w.has(L.id)&&(w.add(L.id),h.onPeerJoined?.(L.id));break;case"peer-left":typeof L.id=="string"&&(w.delete(L.id),h.onPeerLeft?.(L.id));break;case"signal":typeof L.from=="string"&&h.onSignal?.(L.from,L.data);break}},T.onerror=()=>{if(!I&&!y&&v>1){y=!0,l=(l+1)%a.length,k(O,v-1).then(m,_);return}N(se("signaling-unreachable",`cannot reach ${a[l]}`))},T.onclose=()=>{clearInterval(b),N(se("signaling-closed","signalling closed before joining")),C&&!g&&f===T&&E()}}),R=O=>{f&&f.readyState===1?f.send(JSON.stringify(O)):g||M.push(O)},E=()=>{h.onDisconnect?.();let O=()=>{g||S(!0).catch(v=>{if(g||v&&(v.code==="room-full"||Xs.includes(v.code))){h.onDisconnect?.(v);return}setTimeout(O,Math.max(Z(x++,{baseMs:500,maxMs:15e3}),v&&v.retryMs||0))})};setTimeout(O,Z(x++,{baseMs:300,maxMs:15e3}))};return{...await S(!1),send:(O,v)=>R({t:"signal",to:O,data:v}),leave:()=>{if(!g){g=!0,clearInterval(b);try{f&&f.readyState===1&&f.send(JSON.stringify({t:"leave"})),f&&f.close(1e3,"leave")}catch{}}}}}}}var Si=Object.freeze({azure:"#4da3ff",violet:"#9b7bff",magenta:"#ff4fa3",sunset:"#ff7a45",amber:"#ffc23d",lime:"#9be15d",mint:"#35e0b0",ice:"#8fe3ff"}),qs=i=>typeof i=="string"&&Si[i.toLowerCase()]||i,Ys=Object.freeze({accent:"--dxr-accent",ink:"--dxr-ink",shell:"--dxr-shell",danger:"--dxr-danger",radius:"--dxr-radius",font:"--dxr-font"}),tt=Object.freeze({lobbyStartTitle:"Start a 3D call",lobbyJoinTitle:"Join the 3D call",lobbyFullTitle:"This call is full",lobbyLeftTitle:"You left the call",lobbyFullText:"It already has {maxPeers} participants.",lobbyText:"Check your framing below. Camera: {camera} \u2014 {kind}.",cameraDefault:"default",kindBusy:"busy (joining audio-only)",kindNone:"none (joining audio-only)",kindSbs:"sending 3D (side-by-side, {width}\xD7{height})",kindMono:"sending 2D ({width}\xD7{height})",liftOff:"Mono cameras: 2D (2D\u21923D is off).",liftChecking:"Mono cameras: checking 2D\u21923D\u2026",liftMissing:"Mono cameras: 2D\u21923D unavailable in this build.",liftNoProvider:"Mono cameras: 2D (no 2D\u21923D provider here).",liftNative:"Mono cameras: 2D\u21923D (native{provider}).",liftWeb:"Mono cameras: 2D\u21923D (in this page, WebGPU).",liftProven:"Mono cameras: 2D\u21923D.",liftUnproven:"Mono cameras: 2D\u21923D (confirmed on the first mono participant).",start:"Start 3D call",join:"Join call",rejoin:"Rejoin",retryCamera:"Retry camera",cameraSelect:"Camera",joining:"Joining\u2026",waitingTitle:"Waiting for others",waitingText:"Share this link (or scan the code). Anyone who opens it joins \u2014 keep it private.",inviteTitle:"Invite",inviteText:"Anyone with this link can join.",inviteLink:"Invite link",copyLink:"Copy link",copied:"Copied",pressCopy:"Press Ctrl/Cmd+C",qrLabel:"QR code of the invite link",banner2D:"You are seeing this call in 2D.",bannerLink:"View in 3D with DisplayXR Browser",mute:"Mute microphone",unmute:"Unmute microphone",cameraOn:"Turn camera on",cameraOff:"Turn camera off",cameraRetry:"No camera \u2014 click to retry",cameraBusyRetry:"{cameraBusy} \u2014 click to retry",depth:"Depth",invite:"Invite",leave:"Leave call",connecting:"Connecting\u2026",reconnecting:"Reconnecting\u2026",leftCall:"Left the call",cameraOffPlate:"Camera off",noCamera:"No camera",unreachable:"Can't reach this participant \u2014 the network needs a relay (TURN)",cameraBusy:"Camera busy \u2014 in use by another app (e.g. eye tracking)",you:"You",badge3D:"3D",badge2D3D:"2D\u21923D",badge2D:"2D",badgePending:"\u2026"});function Ks(i){let e={...tt,...i&&typeof i=="object"?i:{}};return(t,n)=>{let r=typeof e[t]=="string"?e[t]:tt[t]||t;if(n)for(let[s,o]of Object.entries(n))r=r.split(`{${s}}`).join(String(o));return r}}var Gs="dxr-call-style",cl=`
20
20
  .dxr-call-host{--dxr-accent:#4da3ff;--dxr-ink:#fff;--dxr-shell:rgba(16,17,22,.92);--dxr-danger:#ff5a5f;--dxr-radius:12px;
21
21
  --dxr-font:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
22
22
  display:flex;flex-direction:column;gap:12px;color:var(--dxr-ink);
@@ -37,6 +37,9 @@ output.color1 = getPickDepth();
37
37
  .dxr-call-grid[data-layout="speaker"]{grid-template-columns:repeat(3,1fr);}
38
38
  .dxr-call-grid[data-layout="speaker"] .dxr-call-tile--main{grid-column:1/-1;}
39
39
  .dxr-call-grid[data-layout="speaker"][data-n="1"]{grid-template-columns:1fr;}
40
+ /* Shared content (3D app share): the content tile spans the row, the people form a strip under it. */
41
+ .dxr-call-grid[data-content="1"]:not([data-n="1"]){grid-template-columns:repeat(3,1fr);max-width:calc(var(--dxr-call-h)*4/3);}
42
+ .dxr-call-grid[data-content="1"] .dxr-call-tile--main{grid-column:1/-1;}
40
43
  /* layout:'none' \u2014 the module creates the tiles but does not position them: the grid box steps
41
44
  aside (display:contents) so each [data-dxr-peer] tile is laid out by the PAGE's own CSS on the
42
45
  host. A tile is never moved; it is styled in place (woven-canvas rule 2). */
@@ -99,4 +102,4 @@ output.color1 = getPickDepth();
99
102
  .dxr-call-depth{display:flex;align-items:center;gap:6px;padding:0 8px;font-size:12px;opacity:.9;}
100
103
  .dxr-call-depth input{width:110px;accent-color:var(--dxr-accent);}
101
104
  .dxr-call-note{font-size:12px;opacity:.65;}
102
- `;function Ws(n=document){if(n.getElementById(Fs))return;let e=n.createElement("style");e.id=Fs,e.textContent=Ya,(n.head||n.documentElement).appendChild(e)}var le=n=>`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="${n}"/></svg>`,J={mic:le("M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3zm5-3a5 5 0 0 1-10 0H5a7 7 0 0 0 6 6.92V21h2v-3.08A7 7 0 0 0 19 11z"),micOff:le("M19 11h-2a5 5 0 0 1-.4 1.97l1.47 1.47A6.96 6.96 0 0 0 19 11zM15 11V5a3 3 0 0 0-5.94-.6L15 10.34zM4.27 3 3 4.27l6 6V11a3 3 0 0 0 4.52 2.59l1.46 1.46A5 5 0 0 1 7 11H5a7 7 0 0 0 6 6.92V21h2v-3.08a6.9 6.9 0 0 0 3.02-1.14L19.73 21 21 19.73z"),cam:le("M17 10.5V7a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-3.5l4 4v-11z"),camOff:le("M21 6.5l-4 4V7a1 1 0 0 0-1-1H9.82L21 17.18zM3.27 2 2 3.27 4.73 6H4a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h12c.21 0 .39-.08.54-.18L19.73 21 21 19.73z"),link:le("M3.9 12a3.1 3.1 0 0 1 3.1-3.1h4V7H7a5 5 0 0 0 0 10h4v-1.9H7A3.1 3.1 0 0 1 3.9 12zM8 13h8v-2H8zm9-6h-4v1.9h4a3.1 3.1 0 0 1 0 6.2h-4V17h4a5 5 0 0 0 0-10z"),leave:le("M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85a1 1 0 0 1-1.41-.02L.29 13.08a1 1 0 0 1 0-1.41C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67a1 1 0 0 1 0 1.41l-2.48 2.48a1 1 0 0 1-1.41.02 11.3 11.3 0 0 0-2.66-1.85 1 1 0 0 1-.56-.9v-3.1A15.3 15.3 0 0 0 12 9z"),mutedSmall:le("M19 11h-2a5 5 0 0 1-.4 1.97l1.47 1.47A6.96 6.96 0 0 0 19 11zM15 11V5a3 3 0 0 0-5.94-.6L15 10.34zM4.27 3 3 4.27l6 6V11a3 3 0 0 0 4.52 2.59l1.46 1.46A5 5 0 0 1 7 11H5a7 7 0 0 0 6 6.92V21h2v-3.08a6.9 6.9 0 0 0 3.02-1.14L19.73 21 21 19.73z")};function D(n,e={},t=[]){let i=document.createElement(n);for(let[r,s]of Object.entries(e))s!=null&&(r==="class"?i.className=s:r==="html"?i.innerHTML=s:r==="text"?i.textContent=s:r.startsWith("on")&&typeof s=="function"?i.addEventListener(r.slice(2),s):r in i&&typeof s!="string"?i[r]=s:i.setAttribute(r,s));for(let r of[].concat(t))r&&i.appendChild(typeof r=="string"?document.createTextNode(r):r);return i}var j=(n,e)=>n&&n.classList.toggle("dxr-call-hidden",!e);Me();var $s="[inline3d/call]",Ka="https://github.com/DisplayXR/displayxr-browser",Us=Object.freeze({accent:"theme.accent",tileAspect:"theme.tileAspect",inviteBase:"invite.base",updateUrl:"invite.updateUrl",browserUrl:"landing.browserUrl",maxLifted:"liftOptions.max",calibration:"openCamera({ calibration }) of '@displayxr/inline3d/camera' (pass the camera as `camera`)",rectify:"openCamera({ rectify }) of '@displayxr/inline3d/camera'",log:"debug: true (and diagnostics())",recoverSession:"nothing \u2014 a call always recovers the document's session (sharedInline3D())",wallOptions:"sharedInline3D(opts) \u2014 the document's wall is configured by the page",scrollIntoView:"nothing \u2014 always on with ui: true"}),Hs=new Set;function Ja(n){Hs.has(n)||(Hs.add(n),console.warn(`${$s} option \`${n}\` is deprecated (removed in 1.31) \u2014 use ${Us[n]}`))}function gn(n={}){for(let x of Object.keys(Us))n[x]!==void 0&&Ja(x);let e=n.theme&&typeof n.theme=="object"?n.theme:{},t=n.invite&&typeof n.invite=="object"?n.invite:{},i=n.landing&&typeof n.landing=="object"?n.landing:{},r=n.ui===void 0?!0:n.ui==="tiles"?"tiles":!!n.ui,s=r===!0,o=e.tileAspect!==void 0?e.tileAspect:n.tileAspect,a=o==="fill"?"fill":typeof o=="number"&&o>.3&&o<4?o:16/9,l=n.layout==="speaker"?"speaker":n.layout==="none"?"none":"grid",c=n.tileCover==="auto"||n.tileCover==="off"?n.tileCover:l==="none"?"auto":"off",h=n.room===void 0||n.room===null?"auto":n.room;if(h!=="auto"&&!_e(h)){let x=We(h);if(!x)throw new Error(`@displayxr/inline3d/call: room "${h}" is not a valid room id (16-64 base64url chars) or invite link`);h=x}let d=n.liftOptions&&typeof n.liftOptions=="object"?{...n.liftOptions}:null,u=d&&d.max!==void 0?d.max:n.maxLifted;d&&delete d.max;let f=e.accent!==void 0?e.accent:n.accent,p={};for(let[x,R]of Object.entries(js)){let E=x==="accent"?f:e[x];typeof E=="string"&&E?p[R]=x==="accent"?Ns(E):E:typeof E=="number"&&x==="radius"&&(p[R]=`${E}px`)}let m=t.base!==void 0?t.base:n.inviteBase,w=t.updateUrl!==void 0?t.updateUrl:n.updateUrl,_=i.browserUrl!==void 0?i.browserUrl:n.browserUrl;return{room:h,signaling:n.signaling||Oe(void 0,typeof n.key=="string"&&n.key?{key:n.key}:{}),iceServers:Array.isArray(n.iceServers)?n.iceServers:void 0,camera:n.camera===void 0?"auto":n.camera,format:n.format==="sbs"?"sbs":n.format==="mono"?"mono":void 0,calibration:n.calibration&&typeof n.calibration=="object"?{...n.calibration}:{},rectify:typeof n.rectify=="function"?n.rectify:null,audio:n.audio===void 0?!0:!!n.audio,autoConverge:n.autoConverge===void 0?!0:!!n.autoConverge,sendConvergence:n.sendConvergence===void 0?!0:!!n.sendConvergence,cursor:Mt(n.cursor,"@displayxr/inline3d/call"),mono3D:Fe(n.mono3D),maxPeers:Be(n.maxPeers===void 0?ge:n.maxPeers),liftOptions:d&&Object.keys(d).length?d:null,maxLifted:Number.isFinite(+u)&&u!==null&&u!==void 0?Math.max(0,Math.min(ge,Math.floor(+u))):ge,layout:l,tileCover:c,name:ve(n.name),cameraExclude:n.cameraExclude===!1?!1:Array.isArray(n.cameraExclude)?[...n.cameraExclude]:void 0,ui:r,chrome:s,autoJoin:n.autoJoin===void 0?!s:!!n.autoJoin,selfView:n.selfView===void 0?!0:!!n.selfView,tileAspect:a,cssVars:p,strings:e.strings&&typeof e.strings=="object"?{...e.strings}:null,invite:{base:typeof m=="string"?m:null,updateUrl:w===void 0?s:!!w},landing:{browserUrl:typeof _=="string"?_:Ka,allow2D:i.allow2D===void 0?!0:!!i.allow2D},debug:!!n.debug,log:typeof n.log=="function"?n.log:n.debug?(x,R)=>console.log(`${$s} ${x} ${JSON.stringify(R)}`):null,_liftImporter:typeof n._liftImporter=="function"?n._liftImporter:void 0,_convGrab:typeof n._convGrab=="function"?n._convGrab:void 0}}var Rc=Object.freeze(["normalizeCallOptions","newRoomId","isValidRoomId","buildInviteLink","normalizeHello","makeHello","routeFor","badgeFor","createLiveGate","convergenceShiftPx","lowPass","clampShift","eyeCropRect","mirrorSwapOps","mirrorSwapPixels","maxBitrateKbps","measureFocusDisparity","preferVideoCodecs","sortCodecCapabilities","VIDEO_CODEC_ORDER","MeshTransport","clampMaxPeers","qrEncode","roomKey","SIGNAL_PROTOCOL","WIRE_VERSION","CALL_SDK","PLATE_TEXT","CALL_ACCENTS","normalizeMono3D","resolveLift","createLiftPool","createFrameWatch","liftConvergenceFor","liftPriorityFor","setLiftPriority","defaultLiftSpecifier","LIFT_PRIORITY"]);var vn="dxr-call:",Za=["joined","left","peer","peerleft","state","display","speaker","quality","error","warning","name","message","signal","weave","speaking"],_n="[inline3d/call] <dxr-call>",ce=n=>n!=null&&!/^(false|0|off|no)$/i.test(String(n).trim()),Vs=n=>{if(n==null||String(n).trim()==="")return;let e=/^\s*([0-9.]+)\s*\/\s*([0-9.]+)\s*$/.exec(String(n)),t=e?+e[1]/+e[2]:+n;return Number.isFinite(t)?t:void 0},W=n=>n==null||String(n).trim()===""?void 0:String(n).trim();function yn(n){let e=typeof n=="function"?n:l=>n&&typeof n.getAttribute=="function"?n.getAttribute(l):null,t={},i=(l,c)=>{c!==void 0&&(t[l]=c)};i("room",W(e("room")));let r=W(e("signaling"));r&&(t.signaling=Oe(r,W(e("key"))?{key:W(e("key"))}:{})),i("key",W(e("key"))),i("camera",W(e("camera"))),i("layout",W(e("layout"))),i("maxPeers",Vs(e("max-peers")));let s=W(e("ui"));ce(e("no-ui"))?t.ui=!1:s==="tiles"&&(t.ui="tiles"),ce(e("auto-join"))&&(t.autoJoin=!0);let o=W(e("mono3d"));o&&/^(off|false|0|no)$/i.test(o)&&(t.mono3D="off"),ce(e("no-audio"))&&(t.audio=!1),ce(e("no-self-view"))&&(t.selfView=!1),ce(e("no-auto-converge"))&&(t.autoConverge=!1),ce(e("no-send-convergence"))&&(t.sendConvergence=!1),W(e("cursor"))==="depth"&&(t.cursor="depth"),i("name",W(e("name")));let a={accent:W(e("accent")),tileAspect:W(e("tile-aspect"))==="fill"?"fill":Vs(e("tile-aspect"))};return(a.accent!==void 0||a.tileAspect!==void 0)&&(t.theme=Object.fromEntries(Object.entries(a).filter(([,l])=>l!==void 0))),W(e("invite-base"))&&(t.invite={base:W(e("invite-base"))}),W(e("browser-url"))&&(t.landing={browserUrl:W(e("browser-url"))}),ce(e("debug"))&&(t.debug=!0),t}var Qa=typeof HTMLElement=="function"?HTMLElement:class{},Ae=class n extends Qa{static mount=null;constructor(){super(),this.options=null,this.call=null,this.ready=null,this._gen=0,this._off=[],this._pending=null}connectedCallback(){if(this.call||this._pending)return;let e=++this._gen,t={...yn(this),...this.options&&typeof this.options=="object"?this.options:{}},i=this.constructor.mount||n.mount||wn;this._pending=new Promise(r=>r(i(this,t))).then(r=>{if(this._pending=null,e!==this._gen)return r.leave(),null;if(this.call=r,this._off=Za.map(s=>r.on(s,o=>this._dispatch(s,o))),this._off.push(r.on("error",s=>console.warn(`${_n} ${s.code}: ${s.message}`))),this._dispatch("ready",{call:r}),r.state==="in-call"){this._dispatch("joined",{room:r.room,id:r.id});for(let s of r.peers)this._dispatch("peer",{id:s.id})}return r},r=>{throw this._pending=null,this._dispatch("error",{code:"mount-failed",message:String(r&&r.message||r),error:r||null}),console.warn(`${_n} mount failed: ${String(r&&r.message||r)}`),r}),this.ready=this._pending,this.ready.catch(()=>{})}disconnectedCallback(){this._gen++;let e=this.call;this.call=null,e&&e.leave();for(let t of this._off)try{t()}catch{}this._off=[]}_dispatch(e,t){typeof CustomEvent!="function"||typeof this.dispatchEvent!="function"||this.dispatchEvent(new CustomEvent(vn+e,{detail:t,bubbles:!0,composed:!0}))}};function Ut(n="dxr-call",e=globalThis.customElements){if(!e||typeof e.define!="function")return!1;let t=e.get(n);return t?(t!==Ae&&console.warn(`${_n} <${n}> is already defined by another class; leaving it`),!1):(e.define(n,Ae),!0)}vt();var el=200,Bs=240,tl=new Set(["I420","I420A","I422","I444","NV12"]),Ze=()=>globalThis.performance?performance.now():Date.now();async function bn(n,{eyeMax:e=Bs,scratch:t=null}={}){let i=n?n.videoWidth:0,r=n?n.videoHeight:0;if(!i||!r||(n.readyState||0)<2)return null;if(typeof VideoFrame=="function"){let h=null;try{h=new VideoFrame(n)}catch{h=null}if(h&&tl.has(h.format))try{let d=h.visibleRect?h.visibleRect.width:h.displayWidth,u=h.visibleRect?h.visibleRect.height:h.displayHeight,f=new Uint8Array(h.allocationSize()),p=await h.copyTo(f),m=Ze(),w=Math.max(1,Math.ceil(d/2/e)),_=xr(f,p[0].offset,p[0].stride,d,u,w);return{img:_.img,w:_.w,h:_.h,scale:_.w/d,via:"videoframe",readMs:Ze()-m}}catch{return null}finally{h.close()}h&&h.close()}let s=Ze(),o=Math.min(1,e/(i/2)),a=Math.max(2,Math.round(i*o/2)*2),l=Math.max(2,Math.round(r*o)),c=t||(globalThis.document?document.createElement("canvas"):null);if(!c)return null;(c.width!==a||c.height!==l)&&(c.width=a,c.height=l);try{let h=c.getContext("2d",{willReadFrequently:!0});return h.drawImage(n,0,0,a,l),{img:_t(h.getImageData(0,0,a,l).data,a*l),w:a,h:l,scale:a/i,via:"canvas",readMs:Ze()-s}}catch{return null}}function Xs({intervalMs:n=el,eyeMax:e=Bs,grab:t=bn,now:i=Ze}={}){let r=se(),s=we(),o=-1/0,a=!1,l=0,c=null;return{get busy(){return a},get d(){return s.value},async sample(d,u=i()){if(a||u-o<n)return null;o=u,a=!0;let f=l;try{!c&&globalThis.document&&typeof document.createElement=="function"&&(c=document.createElement("canvas"));let p=null;try{p=await t(d,{eyeMax:e,scratch:c})}catch{p=null}if(f!==l)return null;let m=i(),w=p?r.measure(p.img,p.w,p.h,u):null,_=s.push(w?w.d/p.scale:null),x=d&&d.videoWidth;return{d:_,frac:_!==null&&x>0?_/(x/2):null,luma:p?{img:p.img,w:p.w,h:p.h,scale:p.scale}:null,ncc:w?w.c:null,method:w?w.method:null,via:p?p.via:null,ms:(p?p.readMs:0)+(i()-m)}}finally{f===l&&(a=!1)}},reset(){l++,a=!1,o=-1/0,r.reset(),s.reset()}}}var Z="[inline3d/call]",il=2e3,nl=2500,rl=500,xn=.02,sl=4,ol=2,Ys=200,al=240,ll=66;async function Ks(n,e,t={}){if(!e||typeof e.appendChild!="function")throw new TypeError("@displayxr/inline3d/call: addCall(wall, container, opts) needs a container element");let i=gn(t);if(!i.signaling||typeof i.signaling.join!="function")throw new TypeError("@displayxr/inline3d/call: opts.signaling must be a SignalingAdapter \u2014 dxrSignaling([url]) or your own");let r=new Sn(n,e,i);return await r._init(),r.handle}async function wn(n,e={}){if(!n||typeof n.appendChild!="function")throw new TypeError("@displayxr/inline3d/call: mountCall(el, opts) needs a container element");let{wall:t,...i}=e,r=t||await ot(i.wallOptions);return Ks(r,n,i)}var Sn=class{constructor(e,t,i){this.o=i,this.t=zs(i.strings),this.container=t,this.wall=e||null,this.wallLive=!!(e&&e.supported),this.weaveLive=!1,this.camStatus="pending",this.id=hr(),this.room=i.room==="auto"?We(globalThis.location):i.room,this.state="idle",this.tiles=new Map,this.listeners=new Map,this.local=null,this.muted=!1,this.camOff=!1,this.depth=0,this.speakerId=null,this.transport=null,this.name=i.name,this.signalState=null,this.selfViewOn=i.selfView,this.sinkId=null,this._appOut=new Map,this._appIn=new Map,this._raf=0,this._statsTimer=0,this._hintGate=He(bi),this._convGate=He(rr,20),this._convMeter=Xs({intervalMs:0,grab:i._convGrab}),this._convOut={frac:null,sentAt:0,msg:null},this._convGen=0,this._convTimer=0,this.mono3D=i.mono3D,this.mono3DOn=i.mono3D!=="off",this.liftApi=null,this.liftPool=null,this._liftP=null,this.liftProven=!1,this.liftMissing=!1,this._liftWarned=!1,this._frameWatch=Kt(),this.handle=this._makeHandle(),this.wallLive&&this._hookWall(this.wall)}get woven(){return!!(this.wall&&this.wall.supported&&this.wallLive)}log(e,t={}){this.o.log&&this.o.log(e,t)}emit(e,t){let i=this.listeners.get(e);if(i)for(let r of[...i])try{r(t)}catch(s){console.error(`${Z} '${e}' listener threw`,s)}}error(e,t,i){this.log("error",{code:e,message:t}),this.listeners.get("error")?.size||console.warn(`${Z} ${e}: ${t}`),this.emit("error",{code:e,message:t,error:i||null})}warning(e,t){this.log("warning",{code:e,message:t}),console.warn(`${Z} ${e}: ${t}`),this.emit("warning",{code:e,message:t})}async _init(){this._buildDom(),this.wallLive&&this._ensureLift(),await this._openMedia(this.o.camera),this._startLoop(),this.o.autoJoin?await this.join():this._setState("lobby")}async _openMedia(e,t,{keepOnFail:i=!1}={}){let r=(u,f)=>this.log(u,f),s=null,o=null,a=Ht(e)?e:null;try{if(s=a||await cn({prefer:e,format:t||this.o.format,calibration:this.o.calibration,rectify:this.o.rectify||void 0,exclude:this.o.cameraExclude,log:r}),a&&a.state!=="live")throw Object.assign(new Error("the camera given is not live"),{code:"no-camera",skipped:[]})}catch(u){o=u;let f=u.code==="camera-busy";if(this.error(f?"camera-busy":u.code||"no-camera",f?`${this.t("cameraBusy")}. Joining audio-only.`:`no camera: ${u.message}. Joining audio-only.`,u),i&&this.local&&this.local.videoTrack)return this.local;this.camStatus=f?"busy":"none"}s&&(this.camStatus="ok"),s&&s.rectifyError&&this.error("rectify-failed",`rectify() threw \u2014 sending the raw pair: ${s.rectifyError.message}`,s.rectifyError);let l=this.local?this.local.audioTrack:null;this.o.audio&&!l&&(l=await Pi({log:r})),l&&(l.enabled=!this.muted);let c=s&&s.stream.getVideoTracks()[0]||null;if(c){try{c.contentHint="detail"}catch{}c.enabled=!this.camOff}let h=new MediaStream([c,l].filter(Boolean)),d=this.local;return this.local={stream:h,cam:s,camStream:s?s.stream:null,video:s?s.video:null,videoTrack:c,audioTrack:l,format:s?s.format:"mono",width:s?s.width:0,height:s?s.height:0,calibration:s?s.calibration:{},owned:s?s.owned&&s!==a:!1,label:s?s.label:"",skipped:s?s.skipped:o?.skipped||[]},s&&s!==d?.cam&&(this._camEndedOff?.(),this._camEndedOff=s.on("ended",()=>{this.local?.cam===s&&(this.local.videoTrack=null,this.camStatus="none",this.error("no-camera",'the camera ended (revoked, unplugged, or taken by another app). Audio-only until "Retry camera".'),this.transport?.broadcast(this.stateMsg()),this._refreshSelf(),this._refreshBar())})),this.log("camera",{format:this.local.format,width:this.local.width,height:this.local.height,label:this.local.label,skipped:this.local.skipped.length}),d&&d.owned&&d.cam&&d.cam!==s&&d.cam.close(),this._refreshSelf(),this._refreshLobby(),this.local}hello(){let e=this.local||{};return Mi({format:e.format,width:e.width,height:e.height,baselineMm:e.calibration?.baselineMm,hfovDeg:e.calibration?.hfovDeg,rectified:!!e.calibration?.rectified,conv:this.o.sendConvergence&&e.format==="sbs",name:this.name})}stateMsg(){return{type:"state",muted:this.muted,cameraOff:this.camOff||!this.local?.videoTrack,speaking:!!this._selfSpeaking}}async join(){if(this.state==="joining"||this.state==="in-call")return this.handle;if(this.state==="left"&&!this.local?.videoTrack&&await this._openMedia(this.o.camera),this.room||(this.room=xi(),this.log("room-created",{})),this.o.invite.updateUrl&&globalThis.history&&globalThis.location)try{history.replaceState(history.state,"",ut(location.href,this.room))}catch{}this._setState("joining");let e=new Ve({signaling:this.o.signaling,id:this.id,maxPeers:this.o.maxPeers,iceServers:this.o.iceServers,log:(i,r)=>this.log(i,r)});this.transport=e;let t=null;try{t=await e.start({room:this.room,localStream:this.local.stream,sendFormat:this.local.format,onPeer:i=>this._onPeer(i),onPeerLeft:(i,r)=>this._onPeerLeft(i,r),onStream:(i,r)=>this.tiles.get(i)?.setStream(r),onMessage:(i,r)=>this._onMessage(i,r),onPeerState:(i,r)=>{this.tiles.get(i)?.setConn(r),this.emit("state",{id:i,state:r})},onRefused:i=>this.log("refused-peer",{id:i}),onGhost:(i,r)=>this._onGhost(i,r),onSignalingState:(i,r)=>{this.log("signaling",{state:i}),this._setSignal(i,r),i==="closed"&&r&&this.error(r.code||"signaling-closed",r.message,r)}})}catch(i){throw this.transport=null,i&&i.code==="room-full"?(this._setState("full"),this.error("room-full",i.message,i)):(this._setState("lobby"),this.error(i.code||"join-failed",`could not join: ${i.message}`,i)),i}if(this._setState("in-call"),this._setSignal("connected"),this.o.chrome)try{this.container.scrollIntoView?.({block:"start",behavior:"instant"}),this._fitGrid()}catch{}return this._startStats(),this._startConvSend(),this._pagehide=()=>this.leave("pagehide"),globalThis.addEventListener?.("pagehide",this._pagehide),this.log("joined",{id:this.id,peers:this.tiles.size}),this.emit("joined",{room:this.room,id:this.id}),setTimeout(()=>{this.transport===e&&this._reportTurn(t)},0),this.handle}_reportTurn(e){let t=e&&e.turn;!t||typeof t!="object"||(t.status==="off"&&t.reason==="cap"?this.error("turn-cap","relay (TURN) capacity for this month is used up; direct connections still work, but a participant behind a strict NAT may be unreachable",null):(t.reason==="budget"||t.reason==="rate")&&this.warning("turn-shed",t.reason==="rate"?"no relay (TURN) for this session: too many credential requests from this address this hour":"no relay (TURN) for this anonymous session: the hosted service is near its monthly relay budget (a publishable key keeps TURN)"))}_onPeer(e){if(this.tiles.has(e))return;let t=new Bt(this,e);this.tiles.set(e,t),this._layout(),this.emit("peer",{id:e})}_onGhost(e,t){let i=this.tiles.get(e);if(t&&!i){let r=new Bt(this,e);r.ghost=!0,this.tiles.set(e,r),r.setConn("unreachable"),this._layout()}else!t&&i&&i.ghost&&(i.destroy(),this.tiles.delete(e),this._layout())}_onPeerLeft(e,t){let i=this.tiles.get(e);i&&(i.setConn("left"),this.emit("peerleft",{id:e,reason:t}),i.leaveTimer=setTimeout(()=>{i.destroy(),this.tiles.get(e)===i&&this.tiles.delete(e),this.speakerId===e&&this._setSpeaker(null),this._layout()},nl))}_onMessage(e,t){let i=this.tiles.get(e);if(!i||!t)return;if(t.type==="__open"){this.transport.send(e,this.hello()),this.transport.send(e,this.stateMsg()),this._convOut.msg&&this._convSending()&&this.transport.send(e,this._convOut.msg),i.onChannelOpen();return}let r=Si(t);if(r)return i.setHello(r);let s=Ri(t);if(s)return i.setHint(s);let o=mr(t);if(o)return i.setRemoteState(o);let a=pr(t);if(a)return i.setConv(a);let l=dr(t);if(l){let c=this._appIn.get(e);c||this._appIn.set(e,c=Ci(cr)),c(performance.now())&&this.emit("message",{from:e,data:l.data})}}_setSignal(e,t){if(e===this.signalState)return;this.signalState=e;let i={state:e};t&&t.code&&(i.code=t.code),this.emit("signal",i)}setName(e){return this.name=ve(e),this.transport?.broadcast(this.hello()),this.name}sendApp(e,t){if(!this.transport)return!1;let i=Ei(t);return i?this._sendAppTo(e,i.json):!1}broadcastApp(e){if(!this.transport)return!1;let t=Ei(e);if(!t)return!1;let i=!1,r=!0;for(let s of this.tiles.keys())this.transport.peerState?.(s)!==null&&(i=!0,this._sendAppTo(s,t.json)||(r=!1));return i&&r}_sendAppTo(e,t){if(!this.tiles.has(e))return!1;let i=this._appOut.get(e);return i||this._appOut.set(e,i=Ci(lr)),i(performance.now())?this.transport.sendRaw?this.transport.sendRaw(e,t):this.transport.send(e,JSON.parse(t)):!1}async setMic(e){let t=await Pi({deviceId:e||void 0,log:(s,o)=>this.log(s,o)});if(!t)return!1;let i=this.local;if(!i)return t.stop(),!1;let r=i.audioTrack;return t.enabled=!this.muted,i.audioTrack=t,i.stream=new MediaStream([i.videoTrack,t].filter(Boolean)),this.transport&&await this.transport.replaceTrack("audio",t,i.stream),r&&r!==t&&r.stop(),this.log("mic",{deviceId:e||null}),!0}async setAudioOutput(e){return this.sinkId=e||"",(await Promise.all([...this.tiles.values()].map(i=>i.applySink()))).every(Boolean)}setSelfView(e){let t=e===void 0?!this.selfViewOn:!!e;return t===this.selfViewOn||(this.selfViewOn=t,t?(this.self||(this.self=new Xt(this,this.ui.selfSlot)),j(this.ui.selfSlot,!0),j(this.self.el,!0),this.self.update()):this.self&&(this.self.detach(),j(this.self.el,!1)),this.log("self-view",{on:t})),t}_startConvSend(){this._stopConvSend(),this._convTimer=setInterval(()=>this._tickConv(),Ys)}_stopConvSend(){clearInterval(this._convTimer),this._convTimer=0}_resetConvSend(){this._convGen++,this._convMeter.reset(),this._convOut={frac:null,sentAt:0,msg:null}}_convSending(){let e=this.local;return!!(this.transport&&this.o.sendConvergence&&e&&e.format==="sbs"&&e.videoTrack&&!this.camOff&&e.video)}_tickConv(){if(!this._convSending()||this._convMeter.busy)return;let e=this.local.video,t=this._convGen;this._convMeter.sample(e,performance.now()).then(i=>{if(!i||t!==this._convGen||!this._convSending())return;let r=performance.now(),s=this._convOut,o=(e.videoWidth||0)/2,a=o>0?.25/o:0,l=i.frac===null!=(s.frac===null)||i.frac!==null&&Math.abs(i.frac-s.frac)>=a,c=!s.msg||r-s.sentAt>=or;if(!l&&!c||!this._convGate(r))return;let h=fr(i.frac,i.ncc);this.transport.broadcast(h),this._convOut={frac:i.frac,sentAt:r,msg:h},i.frac!==null&&!this._convLogged&&(this._convLogged=!0,this.log("send-conv",{frac:Math.round(i.frac*1e4)/1e4,disparityPx:Math.round(i.d*10)/10,method:i.method,via:i.via,ms:Math.round(i.ms)}))}).catch(()=>{})}inviteLink(){if(!this.room)return null;let e=this.o.invite.base||(globalThis.location?location.href:"");return ut(e,this.room)}mute(e){return this.muted=e===void 0?!this.muted:!!e,this.local?.audioTrack&&(this.local.audioTrack.enabled=!this.muted),this.transport?.broadcast(this.stateMsg()),this._refreshBar(),this.log("mute",{muted:this.muted}),this.muted}setCameraOff(e){return this.camOff=e===void 0?!this.camOff:!!e,this.local?.videoTrack&&(this.local.videoTrack.enabled=!this.camOff),this.transport?.broadcast(this.stateMsg()),this._refreshBar(),this._refreshSelf(),this.camOff}setDepth(e){let t=e==null||!Number.isFinite(+e)?0:Math.max(-1,Math.min(1,+e));this.depth=t;for(let i of this.tiles.values())i.conv.depth=t;return this.liftPool?.setDepth(t),this.ui?.depth&&+this.ui.depth.value!==t&&(this.ui.depth.value=String(t)),t}async setCamera(e,{format:t}={}){let i=this.local?.format,r=await this._openMedia(e,t,{keepOnFail:!0});return this._resetConvSend(),this.transport&&(await this.transport.replaceTrack("video",r.videoTrack,r.stream),await this.transport.setSendFormat(r.format),this.transport.broadcast(this.hello()),this.transport.broadcast(this.stateMsg())),i!==r.format&&this.log("send-format",{format:r.format}),{format:r.format,width:r.width,height:r.height,label:r.label}}retryCamera(){return this.setCamera(this.o.camera,{format:this.o.format})}sendHint(e){if(!this._hintGate(performance.now()))return!1;let t=Ri({type:"hint",subjectZmm:e});return t?(this.transport?.broadcast(t),!0):!1}leave(e="left"){if(this.state!=="left"){globalThis.removeEventListener?.("pagehide",this._pagehide),this.transport?.stop(),this.transport=null,this._stopConvSend(),this._resetConvSend();for(let t of this.tiles.values())t.destroy();this.tiles.clear(),this.liftPool?.releaseAll(),clearInterval(this._statsTimer),this._setSpeaker(null),this.local&&(this._camEndedOff?.(),this._camEndedOff=null,this.local.stream.getTracks().forEach(t=>t.stop()),this.local.owned&&this.local.cam?this.local.cam.close():this.local.cam&&this.self?.detach(),this.local.videoTrack=null,this.local.audioTrack=null),this.self?.detach(),this.signalState=null,this._appOut.clear(),this._appIn.clear(),this._unhookWall(),this._setState("left"),this._layout(),this.emit("left",{room:this.room,reason:e})}}_hookWall(e){if(!e||!e.session||typeof e.session.addEventListener!="function")return;let t=e.close;this._wallHook={w:e,orig:t,pageClosed:!1};let i=this._wallHook;e.close=(...r)=>(i.pageClosed=!0,t.apply(e,r)),i.onEnd=()=>this._sessionEnded(i),e.session.addEventListener("end",i.onEnd),this._watchLive(e)}_watchLive(e){this.weaveLive=!1;let t=e.session;if(!t||typeof t.requestAnimationFrame!="function"){this.weaveLive=!0;return}let i=Oi(),r=performance.now(),s=(o,a)=>{if(e!==this.wall||!this.wallLive||this.state==="left")return;let l=null;if(e.refSpace)try{let c=a.getViewerPose(e.refSpace);l=c&&c.views?c.views.length:0}catch{l=0}if(!i.feed(l)){try{t.requestAnimationFrame(s)}catch{}return}this.weaveLive=!0,this.log("weave-live",{ms:Math.round(performance.now()-r)});for(let c of this.tiles.values())(c.route==="woven-sbs"||c.route==="lifted")&&c.reroute(!0);this.self&&this.self.route==="woven-sbs"&&this.self.reroute(!0),this._layout()};try{t.requestAnimationFrame(s)}catch{this.weaveLive=!0}}_unhookWall(){let e=this._wallHook;if(e){this._wallHook=null,e.w.close!==e.orig&&(e.w.close=e.orig);try{e.w.session.removeEventListener("end",e.onEnd)}catch{}}}_sessionEnded(e){if(this._wallHook===e){this.wallLive=!1,this.weaveLive=!1,this.log("session-ended",{byPage:e.pageClosed});for(let t of this.tiles.values())t.onWallLost();if(this.self?.onWallLost(),e.pageClosed||this.state==="left"){this._unhookWall();return}this.error("session-ended","the inline-3D session ended; tiles are flat while it is re-opened"),this._unhookWall(),this._recoverWall(0)}}_recoverWall(e){this.state==="left"||e>10||setTimeout(async()=>{if(this.state==="left")return;let t=null;try{t=await ot()}catch{t=null}if(!t||!t.supported)return this._recoverWall(e+1);this.wall=t,this.wallLive=!0,this._hookWall(t),this.log("session-recovered",{attempt:e});for(let i of this.tiles.values())i.reroute(!0);this.self?.reroute(!0)},K(e,{baseMs:1e3,maxMs:15e3}))}_startLoop(){let e=0,t=i=>{this._raf=requestAnimationFrame(t);for(let r of this.tiles.values())r.paint();e&&this.liftPool&&this.liftPool.anyWeb&&this._watchFrames(i-e),e=i};this._raf=requestAnimationFrame(t)}_watchFrames(e){let t=this._frameWatch.feed(e);if(!t)return;let i={degraded:t==="degraded",frameMs:Math.round(this._frameWatch.frameMs*10)/10,tiles:this.liftPool.size};this.log("lift-frame-time",i),t==="degraded"&&console.warn(`${Z} lifted tiles are slowing the page (~${Math.round(1e3/i.frameMs)} fps with ${i.tiles} lifted) \u2014 setMono3D(false) shows mono peers flat`),this.emit("quality",{id:null,in:null,out:null,lift:i})}_ensureLift(){if(!this.mono3DOn)return Promise.resolve(null);if(!this._liftP){let e=(r,s)=>this.log(r,s),t=this.o.liftOptions,i={webFallback:!0,...t&&t.models?{models:t.models}:{}};this._liftP=qt(this.mono3D,{log:e,capsOpts:i,...this.o._liftImporter?{importer:this.o._liftImporter}:{}}).then(r=>(this.liftApi=r,r.lift?(this.liftPool=Jt({lift:r.lift,max:this.o.maxLifted,log:e,options:this.o.liftOptions}),this.liftPool.setDepth(this.depth),this.liftPool.setSpeaker(this.speakerId),!r.caps&&r.capabilities&&Promise.resolve().then(()=>r.capabilities(i)).then(s=>{r.caps=s||null,this._refreshLobby()}).catch(()=>{})):r.reason==="import-failed"||r.reason==="no-lift-export"?this.liftMissing=!0:r.reason!=="off"&&console.info(`${Z} mono\u21923D unavailable (${r.reason}) \u2014 mono participants are shown flat`),this._rerouteMono(),this._refreshLobby(),r))}return this._liftP}_warnLiftMissing(){this._liftWarned||!this.liftMissing||!this.mono3DOn||(this._liftWarned=!0,this.warning("lift-not-bundled","a 2D participant is on a 3D display but the 2D\u21923D module could not be imported from this build, so they stay flat. Import it explicitly \u2014 `import { lift } from '@displayxr/inline3d/lift'; mountCall(el, { mono3D: lift })` \u2014 or use `@displayxr/inline3d/call/full`, which bundles it."))}_rerouteMono(){for(let e of this.tiles.values())e.format&&e.format!=="sbs"&&e.reroute(!1)}setMono3D(e){let t=e===void 0?!this.mono3DOn:!!e;return t===this.mono3DOn||(this.mono3DOn=t,t&&this.mono3D==="off"&&(this.mono3D="auto"),this._frameWatch.reset(),this.log("mono3d",{on:t}),this._rerouteMono(),t&&this.wallLive&&this._ensureLift(),this._refreshLobby()),t}_liftHint(){if(!this.wallLive)return"";let e=this.t;if(!this.mono3DOn)return e("liftOff");let t=this.liftApi;if(!t)return e("liftChecking");if(!t.lift)return this.liftMissing?e("liftMissing"):e("liftNoProvider");let i=t.caps;return i&&i.native?e("liftNative",{provider:i.provider?`, ${i.provider}`:""}):i&&i.webFallback&&i.webFallback.webgpu?e("liftWeb"):this.liftProven?e("liftProven"):e("liftUnproven")}_mono3DInfo(){let e=this.liftApi,t=e&&e.caps;return Object.freeze({on:this.mono3DOn,state:this.mono3DOn?e?e.lift?"ready":"unavailable":this._liftP?"loading":"idle":"off",reason:e?e.reason:null,native:t?!!t.native:null,provider:t&&t.provider||null,lifted:this.liftPool?this.liftPool.size:0,max:this.o.maxLifted,proven:this.liftProven})}_startStats(){clearInterval(this._statsTimer);let e=0;this._statsTimer=setInterval(()=>this._stats(++e%4===0),rl)}async _stats(e){if(!this.transport)return;let t=null,i=0;for(let[o,a]of this.tiles){let l=this.transport.peerConnection(o);if(!l)continue;let c;try{c=await l.getStats()}catch{continue}let h={};c.forEach(f=>{f.type==="codec"&&(h[f.id]=f.mimeType)});let d={in:null,out:null};e&&Object.assign(d,gr(c)),c.forEach(f=>{if(f.type==="inbound-rtp"&&f.kind==="audio"&&typeof f.audioLevel=="number"&&(a.level=Math.max(f.audioLevel,(a.level||0)*.6)),f.type==="media-source"&&f.kind==="audio"&&typeof f.audioLevel=="number"&&(i=Math.max(i,f.audioLevel)),!!e){if(f.type==="inbound-rtp"&&f.kind==="video"){let p=a._prevIn;d.in={width:f.frameWidth||0,height:f.frameHeight||0,fps:f.framesPerSecond||0,codec:h[f.codecId]||null,kbps:p?Math.round((f.bytesReceived-p.bytes)*8/(f.timestamp-p.t)):null,dropped:f.framesDropped||0,decoder:f.decoderImplementation||null},a._prevIn={bytes:f.bytesReceived,t:f.timestamp}}else if(f.type==="outbound-rtp"&&f.kind==="video"){let p=a._prevOut;d.out={width:f.frameWidth||0,height:f.frameHeight||0,fps:f.framesPerSecond||0,codec:h[f.codecId]||null,kbps:p?Math.round((f.bytesSent-p.bytes)*8/(f.timestamp-p.t)):null,limitation:f.qualityLimitationReason||null,encoder:f.encoderImplementation||null},a._prevOut={bytes:f.bytesSent,t:f.timestamp}}}}),e&&(d.in||d.out||d.path)&&(a.quality=d,this.emit("quality",{id:o,...d}));let u=a.remote.muted?0:a.level||0;a.setSpeaking(u>xn||a.remote.speaking),u>xn&&(!t||u>t.lvl)&&(t={id:o,lvl:u})}let r=t?t.id:null;r&&r!==this.speakerId?(this._challengeTicks=this._challenger===r?(this._challengeTicks||0)+1:1,this._challenger=r,this._challengeTicks>=2&&this._setSpeaker(r)):(this._challenger=null,this._challengeTicks=0);let s=!this.muted&&i>xn;s!==!!this._selfSpeaking&&(this._selfSpeaking=s,this.transport?.broadcast(this.stateMsg()),this.self?.setSpeaking(s),this.emit("speaking",{id:"self",on:s}))}_setSpeaker(e){e!==this.speakerId&&(this.speakerId=e,this._challengeTicks=0,this.liftPool?.setSpeaker(e),this.emit("speaker",{id:e}),this.o.layout==="speaker"&&this._layout())}_fitGrid(){let e=this.ui;if(!e||!this.o.chrome||typeof globalThis.innerHeight!="number")return;let t=this.container.getBoundingClientRect?.(),i=e.grid.getBoundingClientRect?.();if(!t||!i||!i.height)return;let r=Math.max(160,Math.floor(globalThis.innerHeight-Math.max(0,t.top)-(t.height-i.height)-8)),s=parseFloat(this.container.style.getPropertyValue("--dxr-call-fit"))||0;Math.abs(r-s)>2&&this.container.style.setProperty("--dxr-call-fit",`${r}px`),this._fitHooked||(this._fitHooked=!0,globalThis.addEventListener?.("resize",()=>this._fitGrid()))}_setState(e){this.state=e,this.log("state",{state:e}),this._layout()}_buildDom(){let e=this.container,t=this.t;Ws(e.ownerDocument||document),e.classList.add("dxr-call-host"),e.classList.toggle("dxr-call-host--none",this.o.layout==="none");for(let[r,s]of Object.entries(this.o.cssVars))e.style.setProperty(r,s);let i=this.ui={};i.banner=D("div",{class:"dxr-call-banner dxr-call-hidden",part:"banner"},[D("span",{text:t("banner2D")}),D("a",{href:this.o.landing.browserUrl,target:"_blank",rel:"noopener",text:t("bannerLink")})]),i.grid=D("div",{class:"dxr-call-grid",part:"grid","data-layout":this.o.layout,"data-n":"0"}),i.panel=D("div",{class:"dxr-call-panel dxr-call-hidden",part:"lobby"}),i.selfSlot=D("div",{class:"dxr-call-self",part:"self"}),i.bar=D("div",{class:"dxr-call-bar",part:"bar"}),i.foot=D("div",{class:"dxr-call-foot"},[i.selfSlot,i.bar]),i.invite=D("div",{class:"dxr-call-panel dxr-call-hidden",part:"invite"}),this.o.chrome||j(i.bar,!1),e.append(i.banner,i.panel,i.grid,i.invite,i.foot),this.selfViewOn?this.self=new Xt(this,i.selfSlot):j(i.selfSlot,!1),this.o.chrome&&this._buildBar()}_buildBar(){let e=this.ui,t=this.t,i=(r,s,o,a="")=>D("button",{class:`dxr-call-ib ${a}`,type:"button","aria-label":r,title:r,html:s,onclick:o});e.mic=i(t("mute"),J.mic,()=>this.mute()),e.cam=i(t("cameraOff"),J.cam,()=>this.local?.videoTrack?this.setCameraOff():this.retryCamera().catch(()=>{})),e.depth=D("input",{type:"range",min:"-1",max:"1",step:"0.05",value:"0","aria-label":t("depth")}),e.depth.addEventListener("input",()=>this.setDepth(+e.depth.value)),e.depth.addEventListener("dblclick",()=>this.setDepth(0)),e.inviteBtn=i(t("invite"),J.link,()=>{this._showInvite=!this._showInvite,this._layout()}),e.leave=i(t("leave"),J.leave,()=>this.leave(),"dxr-call-ib--leave"),e.bar.append(e.mic,e.cam,D("label",{class:"dxr-call-depth"},[t("depth"),e.depth]),e.inviteBtn,e.leave)}_refreshBar(){let e=this.ui;if(!e||!e.mic)return;let t=this.t;e.mic.innerHTML=this.muted?J.micOff:J.mic,e.mic.setAttribute("aria-pressed",String(this.muted)),e.mic.title=this.muted?t("unmute"):t("mute");let i=!this.local?.videoTrack;e.cam.innerHTML=this.camOff||i?J.camOff:J.cam,e.cam.setAttribute("aria-pressed",String(this.camOff||i)),e.cam.title=i?this.camStatus==="busy"?t("cameraBusyRetry",{cameraBusy:t("cameraBusy")}):t("cameraRetry"):this.camOff?t("cameraOn"):t("cameraOff")}_refreshSelf(){this.self?.update()}_refreshLobby(){(this.state==="lobby"||this.state==="idle")&&this._layout()}_renderInvite(e,t,i){e.replaceChildren();let r=this.inviteLink();if(!r)return;let s=this.t,o=D("input",{type:"text",readOnly:!0,value:r,"aria-label":s("inviteLink")});o.addEventListener("focus",()=>o.select());let a=D("button",{class:"dxr-call-btn dxr-call-btn--primary",type:"button",text:s("copyLink")});a.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(r),a.textContent=s("copied")}catch{o.select(),a.textContent=s("pressCopy")}setTimeout(()=>a.textContent=s("copyLink"),1800)});let l=D("canvas",{"aria-label":s("qrLabel"),role:"img"});try{Ds(l,r,{px:4})}catch{l.style.display="none"}e.append(D("h3",{text:t}),D("p",{text:i}),D("div",{class:"dxr-call-invite"},[D("div",{class:"dxr-call-row",style:"flex:1 1 280px"},[o,a]),l]))}_layout(){let e=this.ui;if(!e)return;let t=this.container,i=this.t,r=this.o.chrome&&(this.state==="lobby"||this.state==="idle"||this.state==="full"||this.state==="left");t.classList.toggle("dxr-call-host--lobby",r),j(e.banner,this.o.chrome&&!this.woven);let s=this.tiles.size;e.grid.dataset.n=String(Math.min(s,4)),j(e.grid,s>0&&this.state!=="left");let o=this.o.layout==="speaker"?this.speakerId||[...this.tiles.keys()][0]:null;for(let[c,h]of this.tiles)h.el.classList.toggle("dxr-call-tile--main",c===o);if(!this.o.chrome)return;this._refreshBar(),queueMicrotask(()=>this._fitGrid());let a=e.panel;if(r){j(a,!0),a.replaceChildren();let c=this.local,h=!!this.room,d=this.state==="full"?i("lobbyFullTitle"):this.state==="left"?i("lobbyLeftTitle"):i(h?"lobbyJoinTitle":"lobbyStartTitle"),u={width:c?.width||0,height:c?.height||0},f=this.camStatus==="busy"?i("kindBusy"):!c||!c.videoTrack?i("kindNone"):c.format==="sbs"?i("kindSbs",u):i("kindMono",u),p=this.state==="full"?i("lobbyFullText",{maxPeers:this.o.maxPeers}):`${i("lobbyText",{camera:c?.label||i("cameraDefault"),kind:f})}${this._liftHint()?` ${this._liftHint()}`:""}`,m=D("button",{class:"dxr-call-btn dxr-call-btn--primary",type:"button",text:this.state==="left"?i("rejoin"):i(h?"join":"start")});m.addEventListener("click",()=>this.join().catch(()=>{}));let w=D("select",{class:"dxr-call-select","aria-label":i("cameraSelect")});this._fillCameras(w),w.addEventListener("change",()=>this.setCamera(w.value).catch(x=>this.error("camera-failed",x.message,x)));let _=!c||!c.videoTrack?D("button",{class:"dxr-call-btn",type:"button",text:i("retryCamera")}):null;_?.addEventListener("click",()=>this.retryCamera().catch(()=>{})),a.append(D("h3",{text:d}),D("p",{text:p}),D("div",{class:"dxr-call-row"},[this.state==="full"?null:m,_,w]))}else this.state==="in-call"&&s===0?(j(a,!0),this._renderInvite(a,i("waitingTitle"),i("waitingText"))):this.state==="joining"?(j(a,!0),a.replaceChildren(D("p",{text:i("joining")}))):j(a,!1);let l=this.state==="in-call"&&s>0&&this._showInvite;l&&!e.invite.childElementCount&&this._renderInvite(e.invite,i("inviteTitle"),i("inviteText")),j(e.invite,l),l||e.invite.replaceChildren(),e.inviteBtn?.setAttribute("aria-pressed",String(!!l))}diagnostics(){let e=this.local;return{sdk:wi,wire:ht,state:this.state,wall:this.wall,wallLive:this.wallLive,weaveLive:this.weaveLive,woven:this.woven,local:e?{format:e.format,width:e.width,height:e.height,label:e.label,calibration:e.calibration,owned:e.owned,skipped:e.skipped,camera:e.cam||null,stream:e.stream}:null,hello:this.hello(),transport:this.transport,peers:[...this.tiles.values()].map(t=>t.diag()),self:this.self?this.self.diag():null,mono3D:{...this._mono3DInfo(),lift:this.liftApi,pool:this.liftPool?this.liftPool.list():[]},speaker:this.speakerId,depth:this.depth,options:this.o,kill:t=>this.transport?._debugKill(t)}}async _fillCameras(e){let t=[];try{t=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{}let i=this.local?.videoTrack?.getSettings?.().deviceId;e.replaceChildren(...t.map((r,s)=>D("option",{value:r.deviceId,text:r.label||`Camera ${s+1}`}))),i&&(e.value=i),j(e,t.length>1)}_makeHandle(){let e=this,t={format:"display",session:null},i={get room(){return e.room},get id(){return e.id},get state(){return e.state},get localFormat(){return e.local?e.local.format:null},get muted(){return e.muted},get cameraOff(){return e.camOff},get depth(){return e.depth},get speaker(){return e.speakerId},get camera(){return e.camStatus},get mono3D(){return e._mono3DInfo()},get peers(){return Object.freeze([...e.tiles.values()].map(s=>s.info()))},join:()=>e.join().then(()=>{}),inviteLink:()=>e.inviteLink(),mute:s=>e.mute(s),setCameraOff:s=>e.setCameraOff(s),setCamera:(s,o)=>e.setCamera(s,o),setDepth:s=>e.setDepth(s),retryCamera:()=>e.retryCamera(),setMono3D:s=>e.setMono3D(s),leave:()=>e.leave("left"),tile:s=>s==="self"?e.self?.el||null:e.tiles.get(s)?.el||null,get name(){return e.name},setName:s=>e.setName(s),send:(s,o)=>e.sendApp(s,o),broadcast:s=>e.broadcastApp(s),get signal(){return e.signalState},setSelfView:s=>e.setSelfView(s),setMic:s=>e.setMic(s),setAudioOutput:s=>e.setAudioOutput(s),get localStream(){return e.local?e.local.stream:null},diagnostics:()=>e.diagnostics(),on(s,o){if(typeof o!="function")throw new TypeError(`${Z} on() takes a function`);if(s in t&&!e._eventWarned?.has(s)){(e._eventWarned||=new Set).add(s);let a=t[s];console.warn(`${Z} the '${s}' event is deprecated (removed in 1.31)${a?` \u2014 listen for '${a}'`:" \u2014 it is internal now; diagnostics() has the wall"}`)}return e.listeners.has(s)||e.listeners.set(s,new Set),e.listeners.get(s).add(o),()=>e.listeners.get(s)?.delete(o)},off(s,o){e.listeners.get(s)?.delete(o)}},r={wall:["diagnostics().wall (or the wall you passed / sharedInline3D())",()=>e.wall],format:["localFormat",()=>i.localFormat],sendHint:["nothing \u2014 auto-convergence superseded it",()=>s=>e.sendHint(s)],_debug:["diagnostics()",()=>({transport:e.transport,kill:s=>e.transport?._debugKill(s)})]};for(let[s,[o,a]]of Object.entries(r))Object.defineProperty(i,s,{enumerable:!1,configurable:!0,get(){return e._handleWarned?.has(s)||((e._handleWarned||=new Set).add(s),console.warn(`${Z} handle.${s} is deprecated (removed in 1.31) \u2014 use ${o}`)),a()}});return i}};function Js(n,e){if(typeof ResizeObserver!="function")return null;let t=new ResizeObserver(()=>e(n.clientWidth||0,n.clientHeight||0));return t.observe(n),()=>t.disconnect()}function Vt(n,e){let t={id:n,state:e.woven?"woven":"flat",ms:Math.round(e.ms||0)};return e.reason&&(t.reason=e.reason),t}var cl=(n,e)=>Math.max(.3,Math.min(4,n/e));function hl(n){let e=Math.min(globalThis.devicePixelRatio||1,2),t=Math.round((n.clientWidth||0)*e),i=Math.round((n.clientHeight||0)*e);return!t||!i?!1:((n.width!==t||n.height!==i)&&(n.width=t,n.height=i),!0)}function Gs(n,e,{eyeHalf:t=null,mirror:i=!1}={}){if(!hl(n))return;let r=n.getContext("2d"),s=e.videoWidth,o=e.videoHeight;if(!s||!o||(e.readyState||0)<2)return;let a=t===null?s:s/2,l=G(a,o,n.width/n.height,0,0);r.save(),i&&(r.translate(n.width,0),r.scale(-1,1)),r.drawImage(e,(t||0)*a+l.sx,l.sy,l.sw,l.sh,0,0,n.width,n.height),r.restore()}var Bt=class{constructor(e,t){this.call=e,this.id=t,this.hello=null,this.format=null,this.route=null,this.routedKey=null,this.handle=null,this.conn="connecting",this.remote={muted:!1,cameraOff:!1,speaking:!1},this.level=0,this.speaking=!1,this.quality=null,this.conv=ze(),this.autoTrack=we(),this.autoFocus=se(),this.autoAt=0,this.autoCanvas=null,this.autoLocked=!1,this.autoStats={n:0,ms:0,readMs:0,method:null,via:null},this.autoGrabs=0,this.autoPending=!1,this.autoGen=0,this.luma=null,this.destroyed=!1,this.conv.depth=e.depth,this.hintGate=He(bi),this.convGate=He(sr),this.senderConv=null,this.layerFails=0,this.forceFlat=!1,this.lifted=!1,this.liftHandle=null,this.liftLive=!1,this.liftFailed=!1,this.liftFails=0,this.visible=!0,this.video=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,autoplay:!0}),this.audio=Object.assign(document.createElement("audio"),{autoplay:!0}),this.video.addEventListener("playing",()=>this._maybeRoute()),this.video.addEventListener("loadeddata",()=>this._maybeRoute()),this.video.addEventListener("resize",()=>this._maybeRoute()),this.canvas=D("canvas"),this.cover=D("div",{class:"dxr-call-cover dxr-call-hidden"}),this.badge=D("div",{class:"dxr-call-badge",part:"badge"}),this.plate=D("div",{class:"dxr-call-state",part:"plate",text:e.t("connecting")}),this.stage=D("div",{class:"dxr-call-stage"},[this.canvas,this.cover,this.badge,this.plate]),e.o.tileAspect!=="fill"&&(this.stage.style.aspectRatio=String(e.o.tileAspect)),this._box=null,this._aspect=null,this._rwP=null,this._unobserve=Js(this.stage,(i,r)=>this._onBox(i,r)),this.el=D("div",{class:"dxr-call-tile",part:"tile","data-dxr-peer":t,"data-peer":t},[this.stage,D("div",{class:"dxr-call-talk"})]),e.o.ui||j(this.badge,!1),e.ui.grid.appendChild(this.el),e.sinkId&&this.applySink(),this._renderBadge(),this.cursor=null,e.o.cursor&&(e._pairCursorMod=e._pairCursorMod||Promise.resolve().then(()=>(on(),sn)),e._pairCursorMod.then(i=>{this.destroyed||(this.cursor=new i.PairCursor(this.canvas,e.o.cursor))}))}display(){return Ti(this.route)}info(){return Object.freeze({id:this.id,format:this.format||"mono",display:this.display(),state:this.conn,muted:this.remote.muted,cameraOff:this.remote.cameraOff,speaking:this.speaking,name:this.hello&&this.hello.name||null})}_onBox(e,t){let i=this._box;if(this._box={w:e,h:t},e>0&&t>0&&(this._aspect=cl(e,t)),!i||!e||!t||i.w===e&&i.h===t)return;let r=this.handle;if(!r||!this._fwSettled||typeof r.rewoven!="function")return;let s=r.rewoven();s===this._rwP||!s||typeof s.then!="function"||(this._rwP=s,s.then(o=>{this._rwP!==s||this.handle!==r||!o||(this._rwP=null,this.call.emit("weave",Vt(this.id,o)))}))}applySink(){let e=this.audio;return typeof e.setSinkId!="function"?Promise.resolve(!1):e.setSinkId(this.call.sinkId||"").then(()=>!0,()=>!1)}diag(){return{...this.info(),route:this.route,rectified:!!(this.hello&&this.hello.rectified),hello:this.hello,quality:this.quality,convergencePx:this.conv.current,cursor:this.cursor?this.cursor.last:null,autoConverge:{disparityPx:this.conv.measuredPx,ms:this.autoStats.n?this.autoStats.ms/this.autoStats.n:null,readMs:this.autoStats.n?this.autoStats.readMs/this.autoStats.n:null,method:this.autoStats.method,via:this.autoStats.via,samples:this.autoGrabs,source:this.call.o.autoConverge?this._senderFrac(performance.now())!==null?"sender":this.conv.measuredPx!==null?"local":null:null,senderFrac:this.senderConv?this.senderConv.frac:null},lift:this.lifted?{live:this.liftLive,native:!!(this.liftHandle&&this.liftHandle.native),priority:this.call.liftPool?this.call.liftPool.priority(this.id):null,state:this.liftHandle?this.liftHandle.state||null:"pending"}:null,element:this.el}}setStream(e){this.video.srcObject!==e&&(this.video.srcObject=e,this.audio.srcObject=e,this._resetAutoConverge()),this.video.play().catch(()=>{}),this.audio.play().catch(()=>{})}onChannelOpen(){clearTimeout(this.helloTimer),this.helloTimer=setTimeout(()=>{this.format||(this.format="mono",this._maybeRoute())},il)}setHello(e){clearTimeout(this.helloTimer);let t=this.hello&&this.hello.name||null;this.hello=e,this.conv.hello=e,(e.name||null)!==t&&this.call.emit("name",{id:this.id,name:e.name||null});let i=this.format!==e.format;this.format=e.format,this.call.log("hello",{peer:this.id,format:e.format,width:e.width,height:e.height,rectified:e.rectified}),i?this._maybeRoute():this._renderBadge()}setHint(e){this.hintGate(performance.now())&&(this.conv.subjectZmm=e.subjectZmm)}setConv(e){let t=performance.now();if(this.convGate(t)){if(e.d===null){this.senderConv&&(this.senderConv.at=t);return}this.senderConv={frac:e.d,c:e.c===void 0?null:e.c,at:t}}}_senderFrac(e){let t=this.senderConv;return!t||!this.hello||!this.hello.conv||e-t.at>=ar?null:t.frac}setRemoteState(e){this.remote=e,this._renderBadge(),this._renderPlate(),this._updateVisible()}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.el.classList.toggle("dxr-call-tile--speaking",e),this.call.emit("speaking",{id:this.id,on:e}))}setConn(e){e==="unreachable"&&this.conn!=="unreachable"&&this.call.error("unreachable",`${this.call.t("unreachable")}. Still retrying in the background.`,Object.assign(new Error("unreachable"),{peer:this.id})),this.conn=e,e==="connected"&&this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this._renderPlate()}_renderPlate(){let e=this.call.t,t=this.conn==="left"?e("leftCall"):this.conn==="unreachable"?e("unreachable"):this.conn==="reconnecting"?e("reconnecting"):this.conn!=="connected"?e("connecting"):this.remote.cameraOff?e("cameraOffPlate"):null;this.plate.textContent=t||"",j(this.plate,!!t)}_renderBadge(){let e=this.call.t,t=this.route==="woven-sbs"?e("badge3D"):this.route==="lifted"?e("badge2D3D"):e("badge2D"),i=this.route?this.route==="lifted"&&!this.liftLive?`${t}${e("badgePending")}`:t:e("badgePending");this.badge.replaceChildren(D("b",{text:i})),this.badge.dataset.route=this.route||"",this.remote.muted&&this.badge.insertAdjacentHTML("beforeend",J.mutedSmall)}_maybeRoute(){!this.format||(this.video.readyState||0)<2||!this.video.videoWidth||this.reroute(!1)}reroute(e){let t=this.call,i=t.liftPool,r=this.forceFlat&&this.format==="sbs"?{route:"flat-left"}:ki({format:this.format,woven:t.woven,mono3D:t.mono3DOn?"auto":"off",lift:!!i,overBudget:i?!i.canAcquire(this.id):!1,failed:this.liftFailed});this.format!=="sbs"&&t.woven&&t.mono3DOn&&!t._liftP&&t._ensureLift(),this.format!=="sbs"&&t.woven&&t.liftMissing&&t._warnLiftMissing();let s=`${r.route}|${this.format}`;!e&&s===this.routedKey||(this.routedKey=s,this._unregister(),this.route=r.route,r.route==="woven-sbs"?this._registerWoven():r.route==="lifted"&&this._registerLifted(),t.log("route",{peer:this.id,route:r.route,format:this.format,mono3d:r.mono3d||null}),t.emit("display",{id:this.id,display:this.display()}),t.listeners.get("format")?.size&&t.emit("format",{id:this.id,format:this.format,route:r.route,mono3d:r.mono3d||null,hello:this.hello}),this._renderBadge())}_registerWoven(){let e=this.call;this.convCanvas||(this.convCanvas=document.createElement("canvas")),this._paintConv(),j(this.cover,!0);let t=e.o.tileCover==="auto"?e.wall.addImage(this.canvas,this.convCanvas,{rectCover:"auto"}):e.wall.addImage(this.canvas,this.convCanvas);this.handle=t,this._fwSettled=!1,this._rwP=null,t.firstWoven?.then(i=>{this.handle===t&&(this._fwSettled=!0,j(this.cover,!1),e.log("first-woven",{peer:this.id,woven:i.woven,reason:i.reason,ms:Math.round(i.ms)}),e.emit("weave",Vt(this.id,i)),!i.woven&&i.reason==="layer-failed"&&this._layerFailed())})}_registerLifted(){let e=this.call,t=e.liftPool;this.lifted=!0,this.liftLive=!1,this.video.classList.add("dxr-call-liftsrc"),this.canvas.classList.add("dxr-call-liftflat"),this.video.parentNode!==this.stage&&this.stage.insertBefore(this.video,this.stage.firstChild),this._observeVisible(),t.acquire(this.id,this.video,{wall:e.wall,visible:this.visible,onError:i=>this._liftError(i)}).then(i=>{if(!i||!this.lifted||t.handle(this.id)!==i)return;this.liftHandle=i;let r=s=>{s==="live"?this._liftShowing(!0):(s==="error"||s==="disposed")&&this._liftShowing(!1)};this._liftOff=[i.on?.("statechange",s=>r(s&&s.state)),i.on?.("error",s=>{s&&s.fatal&&this._liftError(s.error)})],i.state==="live"?this._liftShowing(!0):i.canvas&&i.canvas.style&&(i.canvas.style.visibility="hidden"),e.log("lifted",{peer:this.id,native:!!i.native,woven:!!i.woven,state:i.state||null,provider:i.stats&&i.stats.provider||null})})}_liftShowing(e){if(e===this.liftLive)return;this.liftLive=e;let t=this.liftHandle;e?(t&&t.canvas&&t.canvas.style&&!t.native&&(t.canvas.style.visibility=""),this.canvas.style.visibility="hidden",this.liftFails=0,this.call.liftProven||(this.call.liftProven=!0,this.call._refreshLobby())):this.canvas.style.visibility="",this.call.log("lift-live",{peer:this.id,live:e}),this._renderBadge()}_liftError(e){this.lifted&&(this.call.log("lift-error",{peer:this.id,message:String(e&&e.message||e).slice(0,200)}),this.liftFailed=!0,this.reroute(!0),!(this.liftFails++>=ol)&&(clearTimeout(this.liftTimer),this.liftTimer=setTimeout(()=>{this.liftFailed=!1,this.reroute(!1)},K(this.liftFails-1,{baseMs:3e3,maxMs:3e4}))))}_observeVisible(){this._io||typeof IntersectionObserver!="function"||(this._io=new IntersectionObserver(e=>{let t=e[e.length-1];this._onscreen=!!(t&&t.isIntersecting),this._updateVisible()}),this._io.observe(this.stage))}_updateVisible(){let e=this._onscreen!==!1&&!this.remote.cameraOff;e!==this.visible&&(this.visible=e,this.call.liftPool?.setVisible(this.id,e))}_layerFailed(){if(this.forceFlat=!0,this.reroute(!0),this.layerFails++>=sl)return;let e=K(this.layerFails-1,{baseMs:1500,maxMs:2e4});this.call.log("layer-retry",{peer:this.id,attempt:this.layerFails,inMs:e}),clearTimeout(this.layerTimer),this.layerTimer=setTimeout(()=>{this.forceFlat=!1,this.call.woven&&this.reroute(!0)},e)}onWallLost(){this.handle=null,this.reroute(!0)}_unregister(){if(j(this.cover,!1),this.lifted){this.lifted=!1;for(let e of this._liftOff||[])typeof e=="function"&&e();this._liftOff=null,this.call.liftPool?.release(this.id),queueMicrotask(()=>this.call.state!=="left"&&this.call._rerouteMono()),this.liftHandle=null,this.liftLive=!1,this.canvas.style.visibility="",this.canvas.classList.remove("dxr-call-liftflat"),this._io&&(this._io.disconnect(),this._io=null),this.video.parentNode&&(this.video.remove(),this.video.classList.remove("dxr-call-liftsrc"),setTimeout(()=>this.video.srcObject&&this.video.play().catch(()=>{}),0))}if(this.handle){try{this.handle.remove()}catch{}this.handle=null}}paint(){this.route&&(this._box&&(!this._box.w||!this._box.h)||(this.route!=="woven-sbs"&&this.cursor?.idle(),this.route==="woven-sbs"?this._paintConv():this.route==="lifted"?this.liftLive||Gs(this.canvas,this.video):Gs(this.canvas,this.video,{eyeHalf:this.route==="flat-left"?0:null})))}_paintConv(){let e=this.video,t=e.videoWidth,i=e.videoHeight;if(!t||!i||(e.readyState||0)<2||!this.convCanvas)return;let r=t/2,s=this.call.o.tileAspect==="fill"?this._aspect||16/9:this.call.o.tileAspect,{w:o,h:a}=je(r,i,s),l=this.convCanvas;(l.width!==2*o||l.height!==a)&&(l.width=2*o,l.height=a);let c=!!(this.cursor&&this.cursor.hovering),h=this.call.o.autoConverge,d=h?this._senderFrac(performance.now()):null;d!==null&&(this.conv.measuredPx=d*r),(c||h&&d===null)&&this._sampleDisparity(e,t,i,c);let u=this.conv.step(r),f=l.getContext("2d"),p=[];for(let m of[0,1]){let w=p[m]=G(r,i,s,u,m);f.drawImage(e,m*r+w.sx,w.sy,w.sw,w.sh,m*o,0,o,a)}this.cursor&&this.cursor.draw(f,this.luma,{rL:p[0],rR:p[1],outW:o,outH:a,handle:this.handle},performance.now()/1e3)}_sampleDisparity(e,t,i,r=!1){let s=performance.now();if(this.autoPending||s-this.autoAt<(r?ll:Ys))return;this.autoAt=s,this.autoPending=!0;let o=this.autoGen;this.autoCanvas||(this.autoCanvas=document.createElement("canvas")),bn(e,{eyeMax:al,scratch:this.autoCanvas}).then(a=>{o===this.autoGen&&(a?this._applyMeasurement(a.img,a.w,a.h,a.scale,s,a.readMs,a.via):this._applyMeasurement(null,0,0,1,s,0,this.autoStats.via))}).finally(()=>{this.autoPending=!1})}_applyMeasurement(e,t,i,r,s,o,a){if(this.destroyed||(this.autoGrabs++,e&&(this.luma={img:e,w:t,h:i,scale:r}),!this.call.o.autoConverge)||this._senderFrac(performance.now())!==null)return;let l=performance.now(),c=e?this.autoFocus.measure(e,t,i,s):null,h=this.autoTrack.push(c?c.d/r:null);h!==null&&(this.conv.measuredPx=h),this.autoStats.n++,this.autoStats.readMs+=o,this.autoStats.ms+=o+(performance.now()-l),this.autoStats.method=c?c.method:null,this.autoStats.via=a,c&&!this.autoLocked&&(this.autoLocked=!0,this.call.log("auto-converge",{peer:this.id,disparityPx:Math.round(h*10)/10,at:{x:Math.round(c.x/r),y:Math.round(c.y/r)},ncc:Math.round(c.c*100)/100,method:c.method,via:a,ms:Math.round(o+(performance.now()-l))}))}_resetAutoConverge(){this.autoGen++,this.senderConv=null,this.luma=null,this.autoTrack.reset(),this.autoFocus.reset(),this.conv.measuredPx=null,this.autoLocked=!1}destroy(){this.destroyed=!0,this.autoGen++,this.cursor?.dispose(),this.cursor=null,clearTimeout(this.helloTimer),clearTimeout(this.layerTimer),clearTimeout(this.leaveTimer),clearTimeout(this.liftTimer),this._unregister(),this._unobserve?.(),this._unobserve=null,this.video.srcObject=null,this.audio.srcObject=null,this.el.remove()}},Xt=class{constructor(e,t){this.call=e,this.canvas=D("canvas"),this.badge=D("div",{class:"dxr-call-badge",part:"badge"}),this.plate=D("div",{class:"dxr-call-state dxr-call-hidden",part:"plate"}),this.stage=D("div",{class:"dxr-call-stage"},[this.canvas,this.badge,this.plate]),e.o.tileAspect!=="fill"&&(this.stage.style.aspectRatio=String(e.o.tileAspect)),this.el=D("div",{class:"dxr-call-tile dxr-call-tile--self",part:"tile","data-dxr-peer":"self"},[this.stage,D("div",{class:"dxr-call-talk"})]),t.appendChild(this.el),this._box=null,this._rwP=null,this._unobserve=Js(this.stage,(i,r)=>this._onBox(i,r)),this.view=null,this.cam=null}get route(){return this.view?this.view.route:null}update(){let e=this.call.local,t=this.call.t,i=!e||!e.videoTrack;this.plate.textContent=i?this.call.camStatus==="busy"?t("cameraBusy"):this.call.camStatus==="pending"?"":t("noCamera"):this.call.camOff?t("cameraOffPlate"):"",j(this.plate,i||this.call.camOff),this.reroute(!1)}reroute(e){let t=this.call.local,i=t&&t.videoTrack?t.cam:null,r=this.call.woven?this.call.wall:{supported:!1};if(!i||i.state!=="live"||!this.call.selfViewOn)return this.detach(),this._badge();this.view&&this.cam===i?this.view._reroute(e,r):(this.detach(),this.cam=i,this.view=hn(r,this.canvas,i,{autoConverge:!!this.call.o.autoConverge,cursor:this.call.o.cursor||void 0,aspect:this.call.o.tileAspect,...this.call.o.tileCover==="auto"?{rectCover:"auto"}:{},onRouteChange:(s,o)=>{this.cam===i&&(this.call.log("self-route",{route:s,woven:o.woven,reason:o.reason}),this._badge(),this._weave(o))}})),this._badge()}_weave(e){let t=e.firstWoven,i=null;t&&typeof t=="object"?i=Vt("self",t):e.route!=="woven-sbs"&&e.reason&&(i={id:"self",state:"flat",reason:e.reason,ms:0}),i&&this.call.emit("weave",i)}_onBox(e,t){let i=this._box;if(this._box={w:e,h:t},!i||!e||!t||i.w===e&&i.h===t)return;let r=this.view&&this.view.woven?this.view.handle:null,s=this.view?this.view.weaveState().firstWoven:null;if(!r||!s||typeof s!="object"||typeof r.rewoven!="function")return;let o=r.rewoven();o===this._rwP||!o||typeof o.then!="function"||(this._rwP=o,o.then(a=>{this._rwP!==o||!this.view||this.view.handle!==r||!a||(this._rwP=null,this.call.emit("weave",Vt("self",a)))}))}_badge(){let e=this.call.t,t=!!(this.view&&this.view.woven);this.badge.replaceChildren(D("b",{text:`${e("you")} \xB7 ${e(t?"badge3D":"badge2D")}`})),this.badge.dataset.route=this.route||""}diag(){return this.view?this.view.weaveState():{route:null,woven:!1,reason:"no-camera",firstWoven:null,layerRetries:0}}onWallLost(){this.view?._onWallLost(),this._badge()}detach(){this.view&&this.view.remove(),this.view=null,this.cam=null}setSpeaking(e){this.el.classList.toggle("dxr-call-tile--speaking",e)}},ul="1.31",qs=new Set;function F(n,e,t){let i=()=>{qs.has(n)||(qs.add(n),console.warn(`${Z} \`${n}\` is internal and leaves '@displayxr/inline3d/call' in ${ul} \u2014 import it from ${e} if you must, or stop depending on it`))};return typeof t=="function"?new Proxy(t,{apply(r,s,o){return i(),Reflect.apply(r,s,o)},construct(r,s){return i(),Reflect.construct(r,s)}}):t&&typeof t=="object"?new Proxy(t,{get(r,s,o){return typeof s=="string"&&i(),Reflect.get(r,s,o)}}):t}var qc=F("normalizeCallOptions","js/call/options.js",gn),Yc=F("newRoomId","js/call/wire.js",xi),Kc=F("isValidRoomId","js/call/wire.js",_e),Jc=F("buildInviteLink","js/call/wire.js",ut),Zc=F("normalizeHello","js/call/wire.js",Si),Qc=F("makeHello","js/call/wire.js",Mi),eh=F("routeFor","js/call/wire.js",ki),th=F("badgeFor","js/call/wire.js",Ti),ih=F("createLiveGate","js/call/wire.js",Oi),nh=F("convergenceShiftPx","js/camera/converge.js",at),rh=F("lowPass","js/camera/converge.js",ct),sh=F("clampShift","js/camera/converge.js",lt),oh=F("eyeCropRect","js/camera/geometry.js",G),ah=F("mirrorSwapOps","js/camera/geometry.js",me),lh=F("mirrorSwapPixels","js/camera/geometry.js",vi),ch=F("maxBitrateKbps","js/call/wire.js",dt),hh=F("measureFocusDisparity","js/camera/disparity.js",Di),uh=F("preferVideoCodecs","js/call/sdp.js",Ue),dh=F("sortCodecCapabilities","js/call/sdp.js",ft),fh=F("VIDEO_CODEC_ORDER","js/call/sdp.js",$e),ph=F("MeshTransport","js/call/transport.js",Ve),mh=F("clampMaxPeers","js/call/transport.js",Be),gh=F("qrEncode","js/call/qr.js",fn),_h=F("roomKey","js/call/signaling.js",pn);var vh=F("PLATE_TEXT","js/call/ui.js (CALL_STRINGS)",Object.freeze({unreachable:Je.unreachable,cameraBusy:Je.cameraBusy})),yh=F("CALL_ACCENTS","js/call/ui.js",mn),wh=F("normalizeMono3D","js/call/lift.js",Fe),bh=F("resolveLift","js/call/lift.js",qt),xh=F("createLiftPool","js/call/lift.js",Jt),Sh=F("createFrameWatch","js/call/lift.js",Kt),Mh=F("liftConvergenceFor","js/call/lift.js",Ie),Eh=F("liftPriorityFor","js/call/lift.js",Qe),Ch=F("setLiftPriority","js/call/lift.js",Yt),Rh=F("defaultLiftSpecifier","js/call/lift.js",Gt),kh=F("LIFT_PRIORITY","js/call/lift.js",Le);Ut();En(()=>new URL("./lift.js",import.meta.url).href);export{vn as CALL_EVENT_PREFIX,Rs as CAMERA_SDK,$t as DXR_SIGNAL_DEFAULT,Ae as DxrCallElement,Ks as addCall,hn as addCameraView,yn as attrsToOpts,Zn as createInline3D,Ut as defineCallElement,Oe as dxrSignaling,Kn as inline3DAvailable,Ht as isStereoCamera,wn as mountCall,cn as openCamera,We as parseInviteLink,Fi as parseStereoXmp,Pr as readJpegStereoMeta,Ni as readJpegXmp,zr as readWebmStereoMeta,ot as sharedInline3D,Wt as suggestedName};
105
+ `;function Js(i=document){if(i.getElementById(Gs))return;let e=i.createElement("style");e.id=Gs,e.textContent=cl,(i.head||i.documentElement).appendChild(e)}var de=i=>`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="${i}"/></svg>`,Q={mic:de("M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3zm5-3a5 5 0 0 1-10 0H5a7 7 0 0 0 6 6.92V21h2v-3.08A7 7 0 0 0 19 11z"),micOff:de("M19 11h-2a5 5 0 0 1-.4 1.97l1.47 1.47A6.96 6.96 0 0 0 19 11zM15 11V5a3 3 0 0 0-5.94-.6L15 10.34zM4.27 3 3 4.27l6 6V11a3 3 0 0 0 4.52 2.59l1.46 1.46A5 5 0 0 1 7 11H5a7 7 0 0 0 6 6.92V21h2v-3.08a6.9 6.9 0 0 0 3.02-1.14L19.73 21 21 19.73z"),cam:de("M17 10.5V7a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-3.5l4 4v-11z"),camOff:de("M21 6.5l-4 4V7a1 1 0 0 0-1-1H9.82L21 17.18zM3.27 2 2 3.27 4.73 6H4a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h12c.21 0 .39-.08.54-.18L19.73 21 21 19.73z"),link:de("M3.9 12a3.1 3.1 0 0 1 3.1-3.1h4V7H7a5 5 0 0 0 0 10h4v-1.9H7A3.1 3.1 0 0 1 3.9 12zM8 13h8v-2H8zm9-6h-4v1.9h4a3.1 3.1 0 0 1 0 6.2h-4V17h4a5 5 0 0 0 0-10z"),leave:de("M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85a1 1 0 0 1-1.41-.02L.29 13.08a1 1 0 0 1 0-1.41C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67a1 1 0 0 1 0 1.41l-2.48 2.48a1 1 0 0 1-1.41.02 11.3 11.3 0 0 0-2.66-1.85 1 1 0 0 1-.56-.9v-3.1A15.3 15.3 0 0 0 12 9z"),mutedSmall:de("M19 11h-2a5 5 0 0 1-.4 1.97l1.47 1.47A6.96 6.96 0 0 0 19 11zM15 11V5a3 3 0 0 0-5.94-.6L15 10.34zM4.27 3 3 4.27l6 6V11a3 3 0 0 0 4.52 2.59l1.46 1.46A5 5 0 0 1 7 11H5a7 7 0 0 0 6 6.92V21h2v-3.08a6.9 6.9 0 0 0 3.02-1.14L19.73 21 21 19.73z")};function P(i,e={},t=[]){let n=document.createElement(i);for(let[r,s]of Object.entries(e))s!=null&&(r==="class"?n.className=s:r==="html"?n.innerHTML=s:r==="text"?n.textContent=s:r.startsWith("on")&&typeof s=="function"?n.addEventListener(r.slice(2),s):r in n&&typeof s!="string"?n[r]=s:n.setAttribute(r,s));for(let r of[].concat(t))r&&n.appendChild(typeof r=="string"?document.createTextNode(r):r);return n}var j=(i,e)=>i&&i.classList.toggle("dxr-call-hidden",!e);Ce();var Qs="[inline3d/call]",hl="https://github.com/DisplayXR/displayxr-browser",eo=Object.freeze({accent:"theme.accent",tileAspect:"theme.tileAspect",inviteBase:"invite.base",updateUrl:"invite.updateUrl",browserUrl:"landing.browserUrl",maxLifted:"liftOptions.max",calibration:"openCamera({ calibration }) of '@displayxr/inline3d/camera' (pass the camera as `camera`)",rectify:"openCamera({ rectify }) of '@displayxr/inline3d/camera'",log:"debug: true (and diagnostics())",recoverSession:"nothing \u2014 a call always recovers the document's session (sharedInline3D())",wallOptions:"sharedInline3D(opts) \u2014 the document's wall is configured by the page",scrollIntoView:"nothing \u2014 always on with ui: true"}),Zs=new Set;function ul(i){Zs.has(i)||(Zs.add(i),console.warn(`${Qs} option \`${i}\` is deprecated (removed in 1.31) \u2014 use ${eo[i]}`))}function Mi(i={}){for(let w of Object.keys(eo))i[w]!==void 0&&ul(w);let e=i.theme&&typeof i.theme=="object"?i.theme:{},t=i.invite&&typeof i.invite=="object"?i.invite:{},n=i.landing&&typeof i.landing=="object"?i.landing:{},r=i.ui===void 0?!0:i.ui==="tiles"?"tiles":!!i.ui,s=r===!0,o=e.tileAspect!==void 0?e.tileAspect:i.tileAspect,a=o==="fill"?"fill":typeof o=="number"&&o>.3&&o<4?o:16/9,l=i.layout==="speaker"?"speaker":i.layout==="none"?"none":"grid",c=i.tileCover==="auto"||i.tileCover==="off"?i.tileCover:l==="none"?"auto":"off",h=i.room===void 0||i.room===null?"auto":i.room;if(h!=="auto"&&!we(h)){let w=$e(h);if(!w)throw new Error(`@displayxr/inline3d/call: room "${h}" is not a valid room id (16-64 base64url chars) or invite link`);h=w}let u=i.liftOptions&&typeof i.liftOptions=="object"?{...i.liftOptions}:null,d=u&&u.max!==void 0?u.max:i.maxLifted;u&&delete u.max;let p=e.accent!==void 0?e.accent:i.accent,f={};for(let[w,M]of Object.entries(Ys)){let S=w==="accent"?p:e[w];typeof S=="string"&&S?f[M]=w==="accent"?qs(S):S:typeof S=="number"&&w==="radius"&&(f[M]=`${S}px`)}let g=t.base!==void 0?t.base:i.inviteBase,x=t.updateUrl!==void 0?t.updateUrl:i.updateUrl,b=n.browserUrl!==void 0?n.browserUrl:i.browserUrl;return{room:h,signaling:i.signaling||De(void 0,typeof i.key=="string"&&i.key?{key:i.key}:{}),iceServers:Array.isArray(i.iceServers)?i.iceServers:void 0,camera:i.camera===void 0?"auto":i.camera,format:i.format==="sbs"?"sbs":i.format==="mono"?"mono":void 0,calibration:i.calibration&&typeof i.calibration=="object"?{...i.calibration}:{},rectify:typeof i.rectify=="function"?i.rectify:null,audio:i.audio===void 0?!0:!!i.audio,autoConverge:i.autoConverge===void 0?!0:!!i.autoConverge,sendConvergence:i.sendConvergence===void 0?!0:!!i.sendConvergence,cursor:Dt(i.cursor,"@displayxr/inline3d/call"),mono3D:je(i.mono3D),maxPeers:qe(i.maxPeers===void 0?ye:i.maxPeers),liftOptions:u&&Object.keys(u).length?u:null,maxLifted:Number.isFinite(+d)&&d!==null&&d!==void 0?Math.max(0,Math.min(ye,Math.floor(+d))):ye,layout:l,tileCover:c,name:U(i.name),cameraExclude:i.cameraExclude===!1?!1:Array.isArray(i.cameraExclude)?[...i.cameraExclude]:void 0,ui:r,chrome:s,autoJoin:i.autoJoin===void 0?!s:!!i.autoJoin,selfView:i.selfView===void 0?!0:!!i.selfView,selfContentView:!!i.selfContentView,tileAspect:a,cssVars:f,strings:e.strings&&typeof e.strings=="object"?{...e.strings}:null,invite:{base:typeof g=="string"?g:null,updateUrl:x===void 0?s:!!x},landing:{browserUrl:typeof b=="string"?b:hl,allow2D:n.allow2D===void 0?!0:!!n.allow2D},debug:!!i.debug,log:typeof i.log=="function"?i.log:i.debug?(w,M)=>console.log(`${Qs} ${w} ${JSON.stringify(M)}`):null,_liftImporter:typeof i._liftImporter=="function"?i._liftImporter:void 0,_convGrab:typeof i._convGrab=="function"?i._convGrab:void 0}}var Uc=Object.freeze(["normalizeCallOptions","newRoomId","isValidRoomId","buildInviteLink","normalizeHello","makeHello","routeFor","badgeFor","createLiveGate","convergenceShiftPx","lowPass","clampShift","eyeCropRect","mirrorSwapOps","mirrorSwapPixels","maxBitrateKbps","measureFocusDisparity","preferVideoCodecs","sortCodecCapabilities","VIDEO_CODEC_ORDER","MeshTransport","clampMaxPeers","qrEncode","roomKey","SIGNAL_PROTOCOL","WIRE_VERSION","CALL_SDK","PLATE_TEXT","CALL_ACCENTS","normalizeMono3D","resolveLift","createLiftPool","createFrameWatch","liftConvergenceFor","liftPriorityFor","setLiftPriority","defaultLiftSpecifier","LIFT_PRIORITY"]);var Ci="dxr-call:",dl=["joined","left","peer","peerleft","state","display","speaker","quality","error","warning","name","message","signal","weave","speaking","content"],Ei="[inline3d/call] <dxr-call>",oe=i=>i!=null&&!/^(false|0|off|no)$/i.test(String(i).trim()),to=i=>{if(i==null||String(i).trim()==="")return;let e=/^\s*([0-9.]+)\s*\/\s*([0-9.]+)\s*$/.exec(String(i)),t=e?+e[1]/+e[2]:+i;return Number.isFinite(t)?t:void 0},W=i=>i==null||String(i).trim()===""?void 0:String(i).trim();function Ri(i){let e=typeof i=="function"?i:l=>i&&typeof i.getAttribute=="function"?i.getAttribute(l):null,t={},n=(l,c)=>{c!==void 0&&(t[l]=c)};n("room",W(e("room")));let r=W(e("signaling"));r&&(t.signaling=De(r,W(e("key"))?{key:W(e("key"))}:{})),n("key",W(e("key"))),n("camera",W(e("camera"))),n("layout",W(e("layout"))),n("maxPeers",to(e("max-peers")));let s=W(e("ui"));oe(e("no-ui"))?t.ui=!1:s==="tiles"&&(t.ui="tiles"),oe(e("auto-join"))&&(t.autoJoin=!0);let o=W(e("mono3d"));o&&/^(off|false|0|no)$/i.test(o)&&(t.mono3D="off"),oe(e("no-audio"))&&(t.audio=!1),oe(e("no-self-view"))&&(t.selfView=!1),oe(e("self-content-view"))&&(t.selfContentView=!0),oe(e("no-auto-converge"))&&(t.autoConverge=!1),oe(e("no-send-convergence"))&&(t.sendConvergence=!1),W(e("cursor"))==="depth"&&(t.cursor="depth"),n("name",W(e("name")));let a={accent:W(e("accent")),tileAspect:W(e("tile-aspect"))==="fill"?"fill":to(e("tile-aspect"))};return(a.accent!==void 0||a.tileAspect!==void 0)&&(t.theme=Object.fromEntries(Object.entries(a).filter(([,l])=>l!==void 0))),W(e("invite-base"))&&(t.invite={base:W(e("invite-base"))}),W(e("browser-url"))&&(t.landing={browserUrl:W(e("browser-url"))}),oe(e("debug"))&&(t.debug=!0),t}var fl=typeof HTMLElement=="function"?HTMLElement:class{},Pe=class i extends fl{static mount=null;constructor(){super(),this.options=null,this.call=null,this.ready=null,this._gen=0,this._off=[],this._pending=null}connectedCallback(){if(this.call||this._pending)return;let e=++this._gen,t={...Ri(this),...this.options&&typeof this.options=="object"?this.options:{}},n=this.constructor.mount||i.mount||ki;this._pending=new Promise(r=>r(n(this,t))).then(r=>{if(this._pending=null,e!==this._gen)return r.leave(),null;if(this.call=r,this._off=dl.map(s=>r.on(s,o=>this._dispatch(s,o))),this._off.push(r.on("error",s=>console.warn(`${Ei} ${s.code}: ${s.message}`))),this._dispatch("ready",{call:r}),r.state==="in-call"){this._dispatch("joined",{room:r.room,id:r.id});for(let s of r.peers)this._dispatch("peer",{id:s.id})}return r},r=>{throw this._pending=null,this._dispatch("error",{code:"mount-failed",message:String(r&&r.message||r),error:r||null}),console.warn(`${Ei} mount failed: ${String(r&&r.message||r)}`),r}),this.ready=this._pending,this.ready.catch(()=>{})}disconnectedCallback(){this._gen++;let e=this.call;this.call=null,e&&e.leave();for(let t of this._off)try{t()}catch{}this._off=[]}_dispatch(e,t){typeof CustomEvent!="function"||typeof this.dispatchEvent!="function"||this.dispatchEvent(new CustomEvent(Ci+e,{detail:t,bubbles:!0,composed:!0}))}};function Jt(i="dxr-call",e=globalThis.customElements){if(!e||typeof e.define!="function")return!1;let t=e.get(i);return t?(t!==Pe&&console.warn(`${Ei} <${i}> is already defined by another class; leaving it`),!1):(e.define(i,Pe),!0)}Ct();var pl=200,no=240,ml=new Set(["I420","I420A","I422","I444","NV12"]),nt=()=>globalThis.performance?performance.now():Date.now();async function Ti(i,{eyeMax:e=no,scratch:t=null}={}){let n=i?i.videoWidth:0,r=i?i.videoHeight:0;if(!n||!r||(i.readyState||0)<2)return null;if(typeof VideoFrame=="function"){let h=null;try{h=new VideoFrame(i)}catch{h=null}if(h&&ml.has(h.format))try{let u=h.visibleRect?h.visibleRect.width:h.displayWidth,d=h.visibleRect?h.visibleRect.height:h.displayHeight,p=new Uint8Array(h.allocationSize()),f=await h.copyTo(p),g=nt(),x=Math.max(1,Math.ceil(u/2/e)),b=Pr(p,f[0].offset,f[0].stride,u,d,x);return{img:b.img,w:b.w,h:b.h,scale:b.w/u,via:"videoframe",readMs:nt()-g}}catch{return null}finally{h.close()}h&&h.close()}let s=nt(),o=Math.min(1,e/(n/2)),a=Math.max(2,Math.round(n*o/2)*2),l=Math.max(2,Math.round(r*o)),c=t||(globalThis.document?document.createElement("canvas"):null);if(!c)return null;(c.width!==a||c.height!==l)&&(c.width=a,c.height=l);try{let h=c.getContext("2d",{willReadFrequently:!0});return h.drawImage(i,0,0,a,l),{img:Et(h.getImageData(0,0,a,l).data,a*l),w:a,h:l,scale:a/n,via:"canvas",readMs:nt()-s}}catch{return null}}function io({intervalMs:i=pl,eyeMax:e=no,grab:t=Ti,now:n=nt}={}){let r=ce(),s=xe(),o=-1/0,a=!1,l=0,c=null;return{get busy(){return a},get d(){return s.value},async sample(u,d=n()){if(a||d-o<i)return null;o=d,a=!0;let p=l;try{!c&&globalThis.document&&typeof document.createElement=="function"&&(c=document.createElement("canvas"));let f=null;try{f=await t(u,{eyeMax:e,scratch:c})}catch{f=null}if(p!==l)return null;let g=n(),x=f?r.measure(f.img,f.w,f.h,d):null,b=s.push(x?x.d/f.scale:null),w=u&&u.videoWidth;return{d:b,frac:b!==null&&w>0?b/(w/2):null,luma:f?{img:f.img,w:f.w,h:f.h,scale:f.scale}:null,ncc:x?x.c:null,method:x?x.method:null,via:f?f.via:null,ms:(f?f.readMs:0)+(n()-g)}}finally{p===l&&(a=!1)}},reset(){l++,a=!1,o=-1/0,r.reset(),s.reset()}}}var ro=i=>U(Ar(i))||U((Tr(i)||{}).appName)||null,Zc=Object.freeze({width:2560,height:720,frameRate:30});function so(i,e=""){let t={};try{t=i&&typeof i.getSettings=="function"&&i.getSettings()||{}}catch{t={}}let n=t.displayxrStereo&&typeof t.displayxrStereo=="object"?t.displayxrStereo:{},r=n.zeroDisparityShiftFrac,s=typeof r=="number"&&Number.isFinite(r)?Math.max(-ee,Math.min(ee,r)):0,o=U(n.appName)||ro(i&&i.label)||ro(e)||null;return{kind:"content",format:n.layout&&n.layout!=="side-by-side"?"mono":"sbs",width:t.width>0?t.width:0,height:t.height>0?t.height:0,convergence:{known:!0,frac:s},appName:o}}var Y="[inline3d/call]",gl=2e3,_l=2500,vl=500,Ai=.02,yl=4,wl=2,lo=200,bl=240,xl=66;async function co(i,e,t={}){if(!e||typeof e.appendChild!="function")throw new TypeError("@displayxr/inline3d/call: addCall(wall, container, opts) needs a container element");let n=Mi(t);if(!n.signaling||typeof n.signaling.join!="function")throw new TypeError("@displayxr/inline3d/call: opts.signaling must be a SignalingAdapter \u2014 dxrSignaling([url]) or your own");let r=new Oi(i,e,n);return await r._init(),r.handle}async function ki(i,e={}){if(!i||typeof i.appendChild!="function")throw new TypeError("@displayxr/inline3d/call: mountCall(el, opts) needs a container element");let{wall:t,...n}=e,r=t||await ut(n.wallOptions);return co(r,i,n)}var Oi=class{constructor(e,t,n){this.o=n,this.t=Ks(n.strings),this.container=t,this.wall=e||null,this.wallLive=!!(e&&e.supported),this.weaveLive=!1,this.camStatus="pending",this.id=_r(),this.room=n.room==="auto"?$e(globalThis.location):n.room,this.state="idle",this.tiles=new Map,this.contentTiles=new Map,this.contentStreams=new Map,this.content=null,this._contentWarned=new Set,this.listeners=new Map,this.local=null,this.muted=!1,this.camOff=!1,this.depth=0,this.speakerId=null,this.transport=null,this.name=n.name,this.signalState=null,this.selfViewOn=n.selfView,this.sinkId=null,this._appOut=new Map,this._appIn=new Map,this._raf=0,this._statsTimer=0,this._hintGate=Ue(Tn),this._convGate=Ue(ur,20),this._convMeter=io({intervalMs:0,grab:n._convGrab}),this._convOut={frac:null,sentAt:0,msg:null},this._convGen=0,this._convTimer=0,this.mono3D=n.mono3D,this.mono3DOn=n.mono3D!=="off",this.liftApi=null,this.liftPool=null,this._liftP=null,this.liftProven=!1,this.liftMissing=!1,this._liftWarned=!1,this._frameWatch=sn(),this.handle=this._makeHandle(),this.wallLive&&this._hookWall(this.wall)}get woven(){return!!(this.wall&&this.wall.supported&&this.wallLive)}log(e,t={}){this.o.log&&this.o.log(e,t)}emit(e,t){let n=this.listeners.get(e);if(n)for(let r of[...n])try{r(t)}catch(s){console.error(`${Y} '${e}' listener threw`,s)}}error(e,t,n){this.log("error",{code:e,message:t}),this.listeners.get("error")?.size||console.warn(`${Y} ${e}: ${t}`),this.emit("error",{code:e,message:t,error:n||null})}warning(e,t){this.log("warning",{code:e,message:t}),console.warn(`${Y} ${e}: ${t}`),this.emit("warning",{code:e,message:t})}async _init(){this._buildDom(),this.wallLive&&this._ensureLift(),await this._openMedia(this.o.camera),this._startLoop(),this.o.autoJoin?await this.join():this._setState("lobby")}async _openMedia(e,t,{keepOnFail:n=!1}={}){let r=(d,p)=>this.log(d,p),s=null,o=null,a=Yt(e)?e:null;try{if(s=a||await _i({prefer:e,format:t||this.o.format,calibration:this.o.calibration,rectify:this.o.rectify||void 0,exclude:this.o.cameraExclude,log:r}),a&&a.state!=="live")throw Object.assign(new Error("the camera given is not live"),{code:"no-camera",skipped:[]})}catch(d){o=d;let p=d.code==="camera-busy";if(this.error(p?"camera-busy":d.code||"no-camera",p?`${this.t("cameraBusy")}. Joining audio-only.`:`no camera: ${d.message}. Joining audio-only.`,d),n&&this.local&&this.local.videoTrack)return this.local;this.camStatus=p?"busy":"none"}s&&(this.camStatus="ok"),s&&s.rectifyError&&this.error("rectify-failed",`rectify() threw \u2014 sending the raw pair: ${s.rectifyError.message}`,s.rectifyError);let l=this.local?this.local.audioTrack:null;this.o.audio&&!l&&(l=await Hn({log:r})),l&&(l.enabled=!this.muted);let c=s&&s.stream.getVideoTracks()[0]||null;if(c){try{c.contentHint="detail"}catch{}c.enabled=!this.camOff}let h=new MediaStream([c,l].filter(Boolean)),u=this.local;return this.local={stream:h,cam:s,camStream:s?s.stream:null,video:s?s.video:null,videoTrack:c,audioTrack:l,format:s?s.format:"mono",width:s?s.width:0,height:s?s.height:0,calibration:s?s.calibration:{},owned:s?s.owned&&s!==a:!1,label:s?s.label:"",skipped:s?s.skipped:o?.skipped||[]},s&&s!==u?.cam&&(this._camEndedOff?.(),this._camEndedOff=s.on("ended",()=>{this.local?.cam===s&&(this.local.videoTrack=null,this.camStatus="none",this.error("no-camera",'the camera ended (revoked, unplugged, or taken by another app). Audio-only until "Retry camera".'),this.transport?.broadcast(this.stateMsg()),this._refreshSelf(),this._refreshBar())})),this.log("camera",{format:this.local.format,width:this.local.width,height:this.local.height,label:this.local.label,skipped:this.local.skipped.length}),u&&u.owned&&u.cam&&u.cam!==s&&u.cam.close(),this._refreshSelf(),this._refreshLobby(),this.local}hello(){let e=this.local||{};return Dn({format:e.format,width:e.width,height:e.height,baselineMm:e.calibration?.baselineMm,hfovDeg:e.calibration?.hfovDeg,rectified:!!e.calibration?.rectified,conv:this.o.sendConvergence&&e.format==="sbs",name:this.name,content:!0})}stateMsg(){return{type:"state",muted:this.muted,cameraOff:this.camOff||!this.local?.videoTrack,speaking:!!this._selfSpeaking}}async join(){if(this.state==="joining"||this.state==="in-call")return this.handle;if(this.state==="left"&&!this.local?.videoTrack&&await this._openMedia(this.o.camera),this.room||(this.room=An(),this.log("room-created",{})),this.o.invite.updateUrl&&globalThis.history&&globalThis.location)try{history.replaceState(history.state,"",_t(location.href,this.room))}catch{}this._setState("joining");let e=new Ge({signaling:this.o.signaling,id:this.id,maxPeers:this.o.maxPeers,iceServers:this.o.iceServers,log:(n,r)=>this.log(n,r)});this.transport=e;let t=null;try{t=await e.start({room:this.room,localStream:this.local.stream,sendFormat:this.local.format,contentTrack:this.content?this.content.track:null,contentStream:this.content?this.content.stream:null,onPeer:n=>this._onPeer(n),onPeerLeft:(n,r)=>this._onPeerLeft(n,r),onStream:(n,r)=>this.tiles.get(n)?.setStream(r),onContentStream:(n,r)=>this._onContentStream(n,r),onMessage:(n,r)=>this._onMessage(n,r),onPeerState:(n,r)=>{this.tiles.get(n)?.setConn(r),this.emit("state",{id:n,state:r})},onRefused:n=>this.log("refused-peer",{id:n}),onGhost:(n,r)=>this._onGhost(n,r),onSignalingState:(n,r)=>{this.log("signaling",{state:n}),this._setSignal(n,r),n==="closed"&&r&&this.error(r.code||"signaling-closed",r.message,r)}})}catch(n){throw this.transport=null,n&&n.code==="room-full"?(this._setState("full"),this.error("room-full",n.message,n)):(this._setState("lobby"),this.error(n.code||"join-failed",`could not join: ${n.message}`,n)),n}if(this._setState("in-call"),this._setSignal("connected"),this.o.chrome)try{this.container.scrollIntoView?.({block:"start",behavior:"instant"}),this._fitGrid()}catch{}return this._startStats(),this._startConvSend(),this._pagehide=()=>this.leave("pagehide"),globalThis.addEventListener?.("pagehide",this._pagehide),this.log("joined",{id:this.id,peers:this.tiles.size}),this.emit("joined",{room:this.room,id:this.id}),setTimeout(()=>{this.transport===e&&this._reportTurn(t)},0),this.handle}_reportTurn(e){let t=e&&e.turn;!t||typeof t!="object"||(t.status==="off"&&t.reason==="cap"?this.error("turn-cap","relay (TURN) capacity for this month is used up; direct connections still work, but a participant behind a strict NAT may be unreachable",null):(t.reason==="budget"||t.reason==="rate")&&this.warning("turn-shed",t.reason==="rate"?"no relay (TURN) for this session: too many credential requests from this address this hour":"no relay (TURN) for this anonymous session: the hosted service is near its monthly relay budget (a publishable key keeps TURN)"))}_onPeer(e){if(this.tiles.has(e))return;let t=new it(this,e);this.tiles.set(e,t),this._layout(),this.emit("peer",{id:e})}_onGhost(e,t){let n=this.tiles.get(e);if(t&&!n){let r=new it(this,e);r.ghost=!0,this.tiles.set(e,r),r.setConn("unreachable"),this._layout()}else!t&&n&&n.ghost&&(n.destroy(),this.tiles.delete(e),this._layout())}_onPeerLeft(e,t){let n=this.tiles.get(e);n&&(this._dropRemoteContent(e),this.contentStreams.delete(e),n.setConn("left"),this.emit("peerleft",{id:e,reason:t}),n.leaveTimer=setTimeout(()=>{n.destroy(),this.tiles.get(e)===n&&this.tiles.delete(e),this.speakerId===e&&this._setSpeaker(null),this._layout()},_l))}_onMessage(e,t){let n=this.tiles.get(e);if(!n||!t)return;if(t.type==="__open"){this.transport.send(e,this.hello()),this.transport.send(e,this.stateMsg()),this._convOut.msg&&this._convSending()&&this.transport.send(e,this._convOut.msg),this.content&&this.transport.send(e,vt(this.content.desc)),n.onChannelOpen();return}let r=On(t);if(r){n.setHello(r),this._onPeerHello(e,r);return}let s=wr(t);if(s)return this._onRemoteContent(e,s);let o=In(t);if(o)return n.setHint(o);let a=Mr(t);if(a)return n.setRemoteState(a);let l=Sr(t);if(l)return n.setConv(l);let c=br(t);if(c){let h=this._appIn.get(e);h||this._appIn.set(e,h=Ln(gr)),h(performance.now())&&this.emit("message",{from:e,data:c.data})}}_onPeerHello(e,t){t.content?this.transport?.addContentTransceiver?.(e):this._warnContentPeer(e)}_warnContentPeer(e){let t=this.tiles.get(e);!this.content||!t||!t.hello||t.hello.content||this._contentWarned.has(e)||(this._contentWarned.add(e),this.warning("content-unsupported",`participant ${e} is on an older SDK that cannot receive a shared app; they keep seeing your camera only`))}_onContentStream(e,t){t?this.contentStreams.set(e,t):this.contentStreams.delete(e);let n=this.contentTiles.get(e);n&&t&&n.setStream(t)}_onRemoteContent(e,t){let n=this.tiles.get(e);if(!n)return;let r=n.content;if(!t.on){r.on&&this._dropRemoteContent(e);return}n.content={on:!0,format:t.format,appName:t.appName};let s=this.contentTiles.get(e);if(!s){s=new Qt(this,e),this.contentTiles.set(e,s);let o=this.contentStreams.get(e);o&&s.setStream(o)}s.setContent(t),this.log("content",{peer:e,on:!0,format:t.format,appName:t.appName,convergence:t.convergence}),(!r.on||r.appName!==t.appName)&&this.emit("content",{id:e,on:!0,appName:t.appName}),this._layout()}_dropRemoteContent(e){let t=this.tiles.get(e),n=this.contentTiles.get(e),r=t?t.content:null;t&&(t.content={on:!1,format:null,appName:null}),n&&(n.destroy(),this.contentTiles.delete(e)),r&&r.on&&(this.log("content",{peer:e,on:!1}),this.emit("content",{id:e,on:!1,appName:r.appName})),this._layout()}async shareContent(e,t={}){let n=!!(e&&typeof e.getVideoTracks=="function"),r=n?e.getVideoTracks()[0]||null:e&&e.kind==="video"?e:null;if(!r)throw new TypeError(`${Y} shareContent(src) needs a MediaStream with a video track, or a video MediaStreamTrack`);if(r.readyState==="ended")throw Object.assign(new Error(`${Y} shareContent: that track has ended`),{code:"content-ended"});let s=n?e:new MediaStream([r]),o=t&&typeof t=="object"?t:{},a=so(r),l=ne(r),c=o.convergence,h={format:o.format==="mono"||o.format==="sbs"?o.format:a.format,width:o.width>0?o.width:a.width,height:o.height>0?o.height:a.height,convergence:c&&typeof c=="object"?{known:!!c.known,frac:c.known&&Number.isFinite(c.frac)?c.frac:c.known?0:null}:l?a.convergence:{known:!1,frac:null},appName:U(o.appName)||a.appName},u=vt(h);h.convergence=u.convergence,h.width=u.width,h.height=u.height;try{r.contentHint="detail"}catch{}this.content&&this.content.track!==r&&this.content.off();let d=()=>{this.content&&this.content.track===r&&this.stopContent({},"ended").catch(()=>{})};(!this.content||this.content.track!==r)&&r.addEventListener?.("ended",d);let p=()=>r.removeEventListener?.("ended",d),f=this.content;if(this.content={track:r,stream:s,desc:h,off:f&&f.track===r?f.off:p},this._contentWarned.clear(),this.transport){await this.transport.replaceTrack("video",r,s,{slot:"content"}),this.transport.broadcast(u);for(let g of this.tiles.keys())this._warnContentPeer(g)}return this._refreshSelfContent(),this.log("share-content",{format:h.format,width:h.width,height:h.height,appName:h.appName,convergence:h.convergence}),(!f||f.desc.appName!==h.appName)&&this.emit("content",{id:"self",on:!0,appName:h.appName}),this.contentInfo()}async stopContent({stopTrack:e=!1}={},t="stopped"){let n=this.content;return n?(this.content=null,n.off(),this._refreshSelfContent(),this.transport&&(this.transport.broadcast(vt({on:!1})),await this.transport.replaceTrack("video",null,null,{slot:"content"})),e&&n.track.stop?.(),this.log("stop-content",{reason:t}),this.emit("content",{id:"self",on:!1,appName:n.desc.appName,reason:t}),!0):!1}contentInfo(){let e=this.content;if(!e)return null;let t=e.desc;return Object.freeze({on:!0,format:t.format,width:t.width,height:t.height,appName:t.appName,convergence:Object.freeze({...t.convergence})})}_refreshSelfContent(){let e=!!(this.content&&this.o.selfContentView&&this.state!=="left"),t=this.contentTiles.get("self");if(!e){t&&(t.destroy(),this.contentTiles.delete("self"),this._layout());return}t||(t=new Qt(this,"self"),this.contentTiles.set("self",t)),t.setStream(this.content.stream),t.setContent({on:!0,...this.content.desc}),this._layout()}_setSignal(e,t){if(e===this.signalState)return;this.signalState=e;let n={state:e};t&&t.code&&(n.code=t.code),this.emit("signal",n)}setName(e){return this.name=U(e),this.transport?.broadcast(this.hello()),this.name}sendApp(e,t){if(!this.transport)return!1;let n=Pn(t);return n?this._sendAppTo(e,n.json):!1}broadcastApp(e){if(!this.transport)return!1;let t=Pn(e);if(!t)return!1;let n=!1,r=!0;for(let s of this.tiles.keys())this.transport.peerState?.(s)!==null&&(n=!0,this._sendAppTo(s,t.json)||(r=!1));return n&&r}_sendAppTo(e,t){if(!this.tiles.has(e))return!1;let n=this._appOut.get(e);return n||this._appOut.set(e,n=Ln(mr)),n(performance.now())?this.transport.sendRaw?this.transport.sendRaw(e,t):this.transport.send(e,JSON.parse(t)):!1}async setMic(e){let t=await Hn({deviceId:e||void 0,log:(s,o)=>this.log(s,o)});if(!t)return!1;let n=this.local;if(!n)return t.stop(),!1;let r=n.audioTrack;return t.enabled=!this.muted,n.audioTrack=t,n.stream=new MediaStream([n.videoTrack,t].filter(Boolean)),this.transport&&await this.transport.replaceTrack("audio",t,n.stream),r&&r!==t&&r.stop(),this.log("mic",{deviceId:e||null}),!0}async setAudioOutput(e){return this.sinkId=e||"",(await Promise.all([...this.tiles.values()].map(n=>n.applySink()))).every(Boolean)}setSelfView(e){let t=e===void 0?!this.selfViewOn:!!e;return t===this.selfViewOn||(this.selfViewOn=t,t?(this.self||(this.self=new en(this,this.ui.selfSlot)),j(this.ui.selfSlot,!0),j(this.self.el,!0),this.self.update()):this.self&&(this.self.detach(),j(this.self.el,!1)),this.log("self-view",{on:t})),t}_startConvSend(){this._stopConvSend(),this._convTimer=setInterval(()=>this._tickConv(),lo)}_stopConvSend(){clearInterval(this._convTimer),this._convTimer=0}_resetConvSend(){this._convGen++,this._convMeter.reset(),this._convOut={frac:null,sentAt:0,msg:null}}_convSending(){let e=this.local;return!!(this.transport&&this.o.sendConvergence&&e&&e.format==="sbs"&&e.videoTrack&&!this.camOff&&e.video)}_tickConv(){if(!this._convSending()||this._convMeter.busy)return;let e=this.local.video,t=this._convGen;this._convMeter.sample(e,performance.now()).then(n=>{if(!n||t!==this._convGen||!this._convSending())return;let r=performance.now(),s=this._convOut,o=(e.videoWidth||0)/2,a=o>0?.25/o:0,l=n.frac===null!=(s.frac===null)||n.frac!==null&&Math.abs(n.frac-s.frac)>=a,c=!s.msg||r-s.sentAt>=fr;if(!l&&!c||!this._convGate(r))return;let h=xr(n.frac,n.ncc);this.transport.broadcast(h),this._convOut={frac:n.frac,sentAt:r,msg:h},n.frac!==null&&!this._convLogged&&(this._convLogged=!0,this.log("send-conv",{frac:Math.round(n.frac*1e4)/1e4,disparityPx:Math.round(n.d*10)/10,method:n.method,via:n.via,ms:Math.round(n.ms)}))}).catch(()=>{})}inviteLink(){if(!this.room)return null;let e=this.o.invite.base||(globalThis.location?location.href:"");return _t(e,this.room)}mute(e){return this.muted=e===void 0?!this.muted:!!e,this.local?.audioTrack&&(this.local.audioTrack.enabled=!this.muted),this.transport?.broadcast(this.stateMsg()),this._refreshBar(),this.log("mute",{muted:this.muted}),this.muted}setCameraOff(e){return this.camOff=e===void 0?!this.camOff:!!e,this.local?.videoTrack&&(this.local.videoTrack.enabled=!this.camOff),this.transport?.broadcast(this.stateMsg()),this._refreshBar(),this._refreshSelf(),this.camOff}setDepth(e){let t=e==null||!Number.isFinite(+e)?0:Math.max(-1,Math.min(1,+e));this.depth=t;for(let n of this.tiles.values())n.conv.depth=t;for(let n of this.contentTiles.values())n.conv.depth=t;return this.liftPool?.setDepth(t),this.ui?.depth&&+this.ui.depth.value!==t&&(this.ui.depth.value=String(t)),t}async setCamera(e,{format:t}={}){let n=this.local?.format,r=await this._openMedia(e,t,{keepOnFail:!0});return this._resetConvSend(),this.transport&&(await this.transport.replaceTrack("video",r.videoTrack,r.stream),await this.transport.setSendFormat(r.format),this.transport.broadcast(this.hello()),this.transport.broadcast(this.stateMsg())),n!==r.format&&this.log("send-format",{format:r.format}),{format:r.format,width:r.width,height:r.height,label:r.label}}retryCamera(){return this.setCamera(this.o.camera,{format:this.o.format})}sendHint(e){if(!this._hintGate(performance.now()))return!1;let t=In({type:"hint",subjectZmm:e});return t?(this.transport?.broadcast(t),!0):!1}leave(e="left"){if(this.state!=="left"){globalThis.removeEventListener?.("pagehide",this._pagehide),this.transport?.stop(),this.transport=null,this._stopConvSend(),this._resetConvSend();for(let t of this.tiles.values())t.destroy();this.tiles.clear();for(let t of this.contentTiles.values())t.destroy();if(this.contentTiles.clear(),this.contentStreams.clear(),this.content){let t=this.content;this.content=null,t.off(),this.emit("content",{id:"self",on:!1,appName:t.desc.appName,reason:"left"})}this.liftPool?.releaseAll(),clearInterval(this._statsTimer),this._setSpeaker(null),this.local&&(this._camEndedOff?.(),this._camEndedOff=null,this.local.stream.getTracks().forEach(t=>t.stop()),this.local.owned&&this.local.cam?this.local.cam.close():this.local.cam&&this.self?.detach(),this.local.videoTrack=null,this.local.audioTrack=null),this.self?.detach(),this.signalState=null,this._appOut.clear(),this._appIn.clear(),this._unhookWall(),this._setState("left"),this._layout(),this.emit("left",{room:this.room,reason:e})}}_hookWall(e){if(!e||!e.session||typeof e.session.addEventListener!="function")return;let t=e.close;this._wallHook={w:e,orig:t,pageClosed:!1};let n=this._wallHook;e.close=(...r)=>(n.pageClosed=!0,t.apply(e,r)),n.onEnd=()=>this._sessionEnded(n),e.session.addEventListener("end",n.onEnd),this._watchLive(e)}_watchLive(e){this.weaveLive=!1;let t=e.session;if(!t||typeof t.requestAnimationFrame!="function"){this.weaveLive=!0;return}let n=jn(),r=performance.now(),s=(o,a)=>{if(e!==this.wall||!this.wallLive||this.state==="left")return;let l=null;if(e.refSpace)try{let c=a.getViewerPose(e.refSpace);l=c&&c.views?c.views.length:0}catch{l=0}if(!n.feed(l)){try{t.requestAnimationFrame(s)}catch{}return}this.weaveLive=!0,this.log("weave-live",{ms:Math.round(performance.now()-r)});for(let c of this.tiles.values())(c.route==="woven-sbs"||c.route==="lifted")&&c.reroute(!0);for(let c of this.contentTiles.values())c.route==="woven-sbs"&&c.reroute(!0);this.self&&this.self.route==="woven-sbs"&&this.self.reroute(!0),this._layout()};try{t.requestAnimationFrame(s)}catch{this.weaveLive=!0}}_unhookWall(){let e=this._wallHook;if(e){this._wallHook=null,e.w.close!==e.orig&&(e.w.close=e.orig);try{e.w.session.removeEventListener("end",e.onEnd)}catch{}}}_sessionEnded(e){if(this._wallHook===e){this.wallLive=!1,this.weaveLive=!1,this.log("session-ended",{byPage:e.pageClosed});for(let t of this.tiles.values())t.onWallLost();for(let t of this.contentTiles.values())t.onWallLost();if(this.self?.onWallLost(),e.pageClosed||this.state==="left"){this._unhookWall();return}this.error("session-ended","the inline-3D session ended; tiles are flat while it is re-opened"),this._unhookWall(),this._recoverWall(0)}}_recoverWall(e){this.state==="left"||e>10||setTimeout(async()=>{if(this.state==="left")return;let t=null;try{t=await ut()}catch{t=null}if(!t||!t.supported)return this._recoverWall(e+1);this.wall=t,this.wallLive=!0,this._hookWall(t),this.log("session-recovered",{attempt:e});for(let n of this.tiles.values())n.reroute(!0);for(let n of this.contentTiles.values())n.reroute(!0);this.self?.reroute(!0)},Z(e,{baseMs:1e3,maxMs:15e3}))}_startLoop(){let e=0,t=n=>{this._raf=requestAnimationFrame(t);for(let r of this.tiles.values())r.paint();for(let r of this.contentTiles.values())r.paint();e&&this.liftPool&&this.liftPool.anyWeb&&this._watchFrames(n-e),e=n};this._raf=requestAnimationFrame(t)}_watchFrames(e){let t=this._frameWatch.feed(e);if(!t)return;let n={degraded:t==="degraded",frameMs:Math.round(this._frameWatch.frameMs*10)/10,tiles:this.liftPool.size};this.log("lift-frame-time",n),t==="degraded"&&console.warn(`${Y} lifted tiles are slowing the page (~${Math.round(1e3/n.frameMs)} fps with ${n.tiles} lifted) \u2014 setMono3D(false) shows mono peers flat`),this.emit("quality",{id:null,in:null,out:null,lift:n})}_ensureLift(){if(!this.mono3DOn)return Promise.resolve(null);if(!this._liftP){let e=(r,s)=>this.log(r,s),t=this.o.liftOptions,n={webFallback:!0,...t&&t.models?{models:t.models}:{}};this._liftP=nn(this.mono3D,{log:e,capsOpts:n,...this.o._liftImporter?{importer:this.o._liftImporter}:{}}).then(r=>(this.liftApi=r,r.lift?(this.liftPool=on({lift:r.lift,max:this.o.maxLifted,log:e,options:this.o.liftOptions}),this.liftPool.setDepth(this.depth),this.liftPool.setSpeaker(this.speakerId),!r.caps&&r.capabilities&&Promise.resolve().then(()=>r.capabilities(n)).then(s=>{r.caps=s||null,this._refreshLobby()}).catch(()=>{})):r.reason==="import-failed"||r.reason==="no-lift-export"?this.liftMissing=!0:r.reason!=="off"&&console.info(`${Y} mono\u21923D unavailable (${r.reason}) \u2014 mono participants are shown flat`),this._rerouteMono(),this._refreshLobby(),r))}return this._liftP}_warnLiftMissing(){this._liftWarned||!this.liftMissing||!this.mono3DOn||(this._liftWarned=!0,this.warning("lift-not-bundled","a 2D participant is on a 3D display but the 2D\u21923D module could not be imported from this build, so they stay flat. Import it explicitly \u2014 `import { lift } from '@displayxr/inline3d/lift'; mountCall(el, { mono3D: lift })` \u2014 or use `@displayxr/inline3d/call/full`, which bundles it."))}_rerouteMono(){for(let e of this.tiles.values())e.format&&e.format!=="sbs"&&e.reroute(!1)}setMono3D(e){let t=e===void 0?!this.mono3DOn:!!e;return t===this.mono3DOn||(this.mono3DOn=t,t&&this.mono3D==="off"&&(this.mono3D="auto"),this._frameWatch.reset(),this.log("mono3d",{on:t}),this._rerouteMono(),t&&this.wallLive&&this._ensureLift(),this._refreshLobby()),t}_liftHint(){if(!this.wallLive)return"";let e=this.t;if(!this.mono3DOn)return e("liftOff");let t=this.liftApi;if(!t)return e("liftChecking");if(!t.lift)return this.liftMissing?e("liftMissing"):e("liftNoProvider");let n=t.caps;return n&&n.native?e("liftNative",{provider:n.provider?`, ${n.provider}`:""}):n&&n.webFallback&&n.webFallback.webgpu?e("liftWeb"):this.liftProven?e("liftProven"):e("liftUnproven")}_mono3DInfo(){let e=this.liftApi,t=e&&e.caps;return Object.freeze({on:this.mono3DOn,state:this.mono3DOn?e?e.lift?"ready":"unavailable":this._liftP?"loading":"idle":"off",reason:e?e.reason:null,native:t?!!t.native:null,provider:t&&t.provider||null,lifted:this.liftPool?this.liftPool.size:0,max:this.o.maxLifted,proven:this.liftProven})}_startStats(){clearInterval(this._statsTimer);let e=0;this._statsTimer=setInterval(()=>this._stats(++e%4===0),vl)}async _stats(e){if(!this.transport)return;let t=null,n=0;for(let[o,a]of this.tiles){let l=this.transport.peerConnection(o);if(!l)continue;let c;try{c=await l.getStats()}catch{continue}let h={};c.forEach(f=>{f.type==="codec"&&(h[f.id]=f.mimeType)});let u={in:null,out:null};e&&Object.assign(u,Er(c));let d=new Set;for(let f of this.contentStreams.get(o)?.getTracks?.()||[])d.add(f.id);this.content&&this.content.track&&d.add(this.content.track.id),c.forEach(f=>{if(f.type==="inbound-rtp"&&f.kind==="audio"&&typeof f.audioLevel=="number"&&(a.level=Math.max(f.audioLevel,(a.level||0)*.6)),f.type==="media-source"&&f.kind==="audio"&&typeof f.audioLevel=="number"&&(n=Math.max(n,f.audioLevel)),!!e&&!(f.trackIdentifier&&d.has(f.trackIdentifier))){if(f.type==="inbound-rtp"&&f.kind==="video"){let g=a._prevIn;u.in={width:f.frameWidth||0,height:f.frameHeight||0,fps:f.framesPerSecond||0,codec:h[f.codecId]||null,kbps:g?Math.round((f.bytesReceived-g.bytes)*8/(f.timestamp-g.t)):null,dropped:f.framesDropped||0,decoder:f.decoderImplementation||null},a._prevIn={bytes:f.bytesReceived,t:f.timestamp}}else if(f.type==="outbound-rtp"&&f.kind==="video"){let g=a._prevOut;u.out={width:f.frameWidth||0,height:f.frameHeight||0,fps:f.framesPerSecond||0,codec:h[f.codecId]||null,kbps:g?Math.round((f.bytesSent-g.bytes)*8/(f.timestamp-g.t)):null,limitation:f.qualityLimitationReason||null,encoder:f.encoderImplementation||null},a._prevOut={bytes:f.bytesSent,t:f.timestamp}}}}),e&&(u.in||u.out||u.path)&&(a.quality=u,this.emit("quality",{id:o,...u}));let p=a.remote.muted?0:a.level||0;a.setSpeaking(p>Ai||a.remote.speaking),p>Ai&&(!t||p>t.lvl)&&(t={id:o,lvl:p})}let r=t?t.id:null;r&&r!==this.speakerId?(this._challengeTicks=this._challenger===r?(this._challengeTicks||0)+1:1,this._challenger=r,this._challengeTicks>=2&&this._setSpeaker(r)):(this._challenger=null,this._challengeTicks=0);let s=!this.muted&&n>Ai;s!==!!this._selfSpeaking&&(this._selfSpeaking=s,this.transport?.broadcast(this.stateMsg()),this.self?.setSpeaking(s),this.emit("speaking",{id:"self",on:s,kind:"camera"}))}_setSpeaker(e){e!==this.speakerId&&(this.speakerId=e,this._challengeTicks=0,this.liftPool?.setSpeaker(e),this.emit("speaker",{id:e}),this.o.layout==="speaker"&&this._layout())}_fitGrid(){let e=this.ui;if(!e||!this.o.chrome||typeof globalThis.innerHeight!="number")return;let t=this.container.getBoundingClientRect?.(),n=e.grid.getBoundingClientRect?.();if(!t||!n||!n.height)return;let r=Math.max(160,Math.floor(globalThis.innerHeight-Math.max(0,t.top)-(t.height-n.height)-8)),s=parseFloat(this.container.style.getPropertyValue("--dxr-call-fit"))||0;Math.abs(r-s)>2&&this.container.style.setProperty("--dxr-call-fit",`${r}px`),this._fitHooked||(this._fitHooked=!0,globalThis.addEventListener?.("resize",()=>this._fitGrid()))}_setState(e){this.state=e,this.log("state",{state:e}),this._layout()}_buildDom(){let e=this.container,t=this.t;Js(e.ownerDocument||document),e.classList.add("dxr-call-host"),e.classList.toggle("dxr-call-host--none",this.o.layout==="none");for(let[r,s]of Object.entries(this.o.cssVars))e.style.setProperty(r,s);let n=this.ui={};n.banner=P("div",{class:"dxr-call-banner dxr-call-hidden",part:"banner"},[P("span",{text:t("banner2D")}),P("a",{href:this.o.landing.browserUrl,target:"_blank",rel:"noopener",text:t("bannerLink")})]),n.grid=P("div",{class:"dxr-call-grid",part:"grid","data-layout":this.o.layout,"data-n":"0"}),n.panel=P("div",{class:"dxr-call-panel dxr-call-hidden",part:"lobby"}),n.selfSlot=P("div",{class:"dxr-call-self",part:"self"}),n.bar=P("div",{class:"dxr-call-bar",part:"bar"}),n.foot=P("div",{class:"dxr-call-foot"},[n.selfSlot,n.bar]),n.invite=P("div",{class:"dxr-call-panel dxr-call-hidden",part:"invite"}),this.o.chrome||j(n.bar,!1),e.append(n.banner,n.panel,n.grid,n.invite,n.foot),this.selfViewOn?this.self=new en(this,n.selfSlot):j(n.selfSlot,!1),this.o.chrome&&this._buildBar()}_buildBar(){let e=this.ui,t=this.t,n=(r,s,o,a="")=>P("button",{class:`dxr-call-ib ${a}`,type:"button","aria-label":r,title:r,html:s,onclick:o});e.mic=n(t("mute"),Q.mic,()=>this.mute()),e.cam=n(t("cameraOff"),Q.cam,()=>this.local?.videoTrack?this.setCameraOff():this.retryCamera().catch(()=>{})),e.depth=P("input",{type:"range",min:"-1",max:"1",step:"0.05",value:"0","aria-label":t("depth")}),e.depth.addEventListener("input",()=>this.setDepth(+e.depth.value)),e.depth.addEventListener("dblclick",()=>this.setDepth(0)),e.inviteBtn=n(t("invite"),Q.link,()=>{this._showInvite=!this._showInvite,this._layout()}),e.leave=n(t("leave"),Q.leave,()=>this.leave(),"dxr-call-ib--leave"),e.bar.append(e.mic,e.cam,P("label",{class:"dxr-call-depth"},[t("depth"),e.depth]),e.inviteBtn,e.leave)}_refreshBar(){let e=this.ui;if(!e||!e.mic)return;let t=this.t;e.mic.innerHTML=this.muted?Q.micOff:Q.mic,e.mic.setAttribute("aria-pressed",String(this.muted)),e.mic.title=this.muted?t("unmute"):t("mute");let n=!this.local?.videoTrack;e.cam.innerHTML=this.camOff||n?Q.camOff:Q.cam,e.cam.setAttribute("aria-pressed",String(this.camOff||n)),e.cam.title=n?this.camStatus==="busy"?t("cameraBusyRetry",{cameraBusy:t("cameraBusy")}):t("cameraRetry"):this.camOff?t("cameraOn"):t("cameraOff")}_refreshSelf(){this.self?.update()}_refreshLobby(){(this.state==="lobby"||this.state==="idle")&&this._layout()}_renderInvite(e,t,n){e.replaceChildren();let r=this.inviteLink();if(!r)return;let s=this.t,o=P("input",{type:"text",readOnly:!0,value:r,"aria-label":s("inviteLink")});o.addEventListener("focus",()=>o.select());let a=P("button",{class:"dxr-call-btn dxr-call-btn--primary",type:"button",text:s("copyLink")});a.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(r),a.textContent=s("copied")}catch{o.select(),a.textContent=s("pressCopy")}setTimeout(()=>a.textContent=s("copyLink"),1800)});let l=P("canvas",{"aria-label":s("qrLabel"),role:"img"});try{Vs(l,r,{px:4})}catch{l.style.display="none"}e.append(P("h3",{text:t}),P("p",{text:n}),P("div",{class:"dxr-call-invite"},[P("div",{class:"dxr-call-row",style:"flex:1 1 280px"},[o,a]),l]))}_layout(){let e=this.ui;if(!e)return;let t=this.container,n=this.t,r=this.o.chrome&&(this.state==="lobby"||this.state==="idle"||this.state==="full"||this.state==="left");t.classList.toggle("dxr-call-host--lobby",r),j(e.banner,this.o.chrome&&!this.woven);let s=this.tiles.size,o=this.contentTiles.size;e.grid.dataset.n=String(Math.min(s+o,4)),e.grid.dataset.content=o?"1":"0",j(e.grid,s+o>0&&this.state!=="left");let a=o&&this.o.layout!=="none"?[...this.contentTiles.values()][0]:null,l=a?null:this.o.layout==="speaker"?this.speakerId||[...this.tiles.keys()][0]:null;for(let[u,d]of this.tiles)d.el.classList.toggle("dxr-call-tile--main",u===l);for(let u of this.contentTiles.values())u.el.classList.toggle("dxr-call-tile--main",u===a);if(!this.o.chrome)return;this._refreshBar(),queueMicrotask(()=>this._fitGrid());let c=e.panel;if(r){j(c,!0),c.replaceChildren();let u=this.local,d=!!this.room,p=this.state==="full"?n("lobbyFullTitle"):this.state==="left"?n("lobbyLeftTitle"):n(d?"lobbyJoinTitle":"lobbyStartTitle"),f={width:u?.width||0,height:u?.height||0},g=this.camStatus==="busy"?n("kindBusy"):!u||!u.videoTrack?n("kindNone"):u.format==="sbs"?n("kindSbs",f):n("kindMono",f),x=this.state==="full"?n("lobbyFullText",{maxPeers:this.o.maxPeers}):`${n("lobbyText",{camera:u?.label||n("cameraDefault"),kind:g})}${this._liftHint()?` ${this._liftHint()}`:""}`,b=P("button",{class:"dxr-call-btn dxr-call-btn--primary",type:"button",text:this.state==="left"?n("rejoin"):n(d?"join":"start")});b.addEventListener("click",()=>this.join().catch(()=>{}));let w=P("select",{class:"dxr-call-select","aria-label":n("cameraSelect")});this._fillCameras(w),w.addEventListener("change",()=>this.setCamera(w.value).catch(S=>this.error("camera-failed",S.message,S)));let M=!u||!u.videoTrack?P("button",{class:"dxr-call-btn",type:"button",text:n("retryCamera")}):null;M?.addEventListener("click",()=>this.retryCamera().catch(()=>{})),c.append(P("h3",{text:p}),P("p",{text:x}),P("div",{class:"dxr-call-row"},[this.state==="full"?null:b,M,w]))}else this.state==="in-call"&&s===0?(j(c,!0),this._renderInvite(c,n("waitingTitle"),n("waitingText"))):this.state==="joining"?(j(c,!0),c.replaceChildren(P("p",{text:n("joining")}))):j(c,!1);let h=this.state==="in-call"&&s>0&&this._showInvite;h&&!e.invite.childElementCount&&this._renderInvite(e.invite,n("inviteTitle"),n("inviteText")),j(e.invite,h),h||e.invite.replaceChildren(),e.inviteBtn?.setAttribute("aria-pressed",String(!!h))}diagnostics(){let e=this.local;return{sdk:kn,wire:mt,state:this.state,wall:this.wall,wallLive:this.wallLive,weaveLive:this.weaveLive,woven:this.woven,local:e?{format:e.format,width:e.width,height:e.height,label:e.label,calibration:e.calibration,owned:e.owned,skipped:e.skipped,camera:e.cam||null,stream:e.stream}:null,hello:this.hello(),transport:this.transport,peers:[...this.tiles.values()].map(t=>t.diag()),content:[...this.contentTiles.values()].map(t=>t.diag()),sharing:this.contentInfo(),self:this.self?this.self.diag():null,mono3D:{...this._mono3DInfo(),lift:this.liftApi,pool:this.liftPool?this.liftPool.list():[]},speaker:this.speakerId,depth:this.depth,options:this.o,kill:t=>this.transport?._debugKill(t)}}async _fillCameras(e){let t=[];try{t=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{}let n=this.local?.videoTrack?.getSettings?.().deviceId;e.replaceChildren(...t.map((r,s)=>P("option",{value:r.deviceId,text:r.label||`Camera ${s+1}`}))),n&&(e.value=n),j(e,t.length>1)}_makeHandle(){let e=this,t={format:"display",session:null},n={get room(){return e.room},get id(){return e.id},get state(){return e.state},get localFormat(){return e.local?e.local.format:null},get muted(){return e.muted},get cameraOff(){return e.camOff},get depth(){return e.depth},get speaker(){return e.speakerId},get camera(){return e.camStatus},get mono3D(){return e._mono3DInfo()},get peers(){return Object.freeze([...e.tiles.values()].map(s=>s.info()))},join:()=>e.join().then(()=>{}),inviteLink:()=>e.inviteLink(),mute:s=>e.mute(s),setCameraOff:s=>e.setCameraOff(s),setCamera:(s,o)=>e.setCamera(s,o),setDepth:s=>e.setDepth(s),retryCamera:()=>e.retryCamera(),setMono3D:s=>e.setMono3D(s),leave:()=>e.leave("left"),tile:(s,o="camera")=>o==="content"?e.contentTiles.get(s)?.el||null:s==="self"?e.self?.el||null:e.tiles.get(s)?.el||null,shareContent:(s,o)=>e.shareContent(s,o),stopContent:s=>e.stopContent(s),get content(){return e.contentInfo()},get name(){return e.name},setName:s=>e.setName(s),send:(s,o)=>e.sendApp(s,o),broadcast:s=>e.broadcastApp(s),get signal(){return e.signalState},setSelfView:s=>e.setSelfView(s),setMic:s=>e.setMic(s),setAudioOutput:s=>e.setAudioOutput(s),get localStream(){return e.local?e.local.stream:null},diagnostics:()=>e.diagnostics(),on(s,o){if(typeof o!="function")throw new TypeError(`${Y} on() takes a function`);if(s in t&&!e._eventWarned?.has(s)){(e._eventWarned||=new Set).add(s);let a=t[s];console.warn(`${Y} the '${s}' event is deprecated (removed in 1.31)${a?` \u2014 listen for '${a}'`:" \u2014 it is internal now; diagnostics() has the wall"}`)}return e.listeners.has(s)||e.listeners.set(s,new Set),e.listeners.get(s).add(o),()=>e.listeners.get(s)?.delete(o)},off(s,o){e.listeners.get(s)?.delete(o)}},r={wall:["diagnostics().wall (or the wall you passed / sharedInline3D())",()=>e.wall],format:["localFormat",()=>n.localFormat],sendHint:["nothing \u2014 auto-convergence superseded it",()=>s=>e.sendHint(s)],_debug:["diagnostics()",()=>({transport:e.transport,kill:s=>e.transport?._debugKill(s)})]};for(let[s,[o,a]]of Object.entries(r))Object.defineProperty(n,s,{enumerable:!1,configurable:!0,get(){return e._handleWarned?.has(s)||((e._handleWarned||=new Set).add(s),console.warn(`${Y} handle.${s} is deprecated (removed in 1.31) \u2014 use ${o}`)),a()}});return n}};function ho(i,e){if(typeof ResizeObserver!="function")return null;let t=new ResizeObserver(()=>e(i.clientWidth||0,i.clientHeight||0));return t.observe(i),()=>t.disconnect()}function Zt(i,e,t="camera"){let n={id:i,state:e.woven?"woven":"flat",ms:Math.round(e.ms||0),kind:t};return e.reason&&(n.reason=e.reason),n}var Sl=(i,e)=>Math.max(.3,Math.min(4,i/e));function Ml(i){let e=Math.min(globalThis.devicePixelRatio||1,2),t=Math.round((i.clientWidth||0)*e),n=Math.round((i.clientHeight||0)*e);return!t||!n?!1:((i.width!==t||i.height!==n)&&(i.width=t,i.height=n),!0)}function oo(i,e,{eyeHalf:t=null,mirror:n=!1}={}){if(!Ml(i))return;let r=i.getContext("2d"),s=e.videoWidth,o=e.videoHeight;if(!s||!o||(e.readyState||0)<2)return;let a=t===null?s:s/2,l=q(a,o,i.width/i.height,0,0);r.save(),n&&(r.translate(i.width,0),r.scale(-1,1)),r.drawImage(e,(t||0)*a+l.sx,l.sy,l.sw,l.sh,0,0,i.width,i.height),r.restore()}var it=class{constructor(e,t,n="camera"){this.call=e,this.id=t,this.kind=n,this.content={on:!1,format:null,appName:null},this.hello=null,this.format=null,this.route=null,this.routedKey=null,this.handle=null,this.conn="connecting",this.remote={muted:!1,cameraOff:!1,speaking:!1},this.level=0,this.speaking=!1,this.quality=null,this.conv=He(),this.autoTrack=xe(),this.autoFocus=ce(),this.autoAt=0,this.autoCanvas=null,this.autoLocked=!1,this.autoStats={n:0,ms:0,readMs:0,method:null,via:null},this.autoGrabs=0,this.autoPending=!1,this.autoGen=0,this.luma=null,this.destroyed=!1,this.conv.depth=e.depth,this.hintGate=Ue(Tn),this.convGate=Ue(dr),this.senderConv=null,this.layerFails=0,this.forceFlat=!1,this.lifted=!1,this.liftHandle=null,this.liftLive=!1,this.liftFailed=!1,this.liftFails=0,this.visible=!0,this.video=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,autoplay:!0}),this.audio=n==="content"?null:Object.assign(document.createElement("audio"),{autoplay:!0}),this.video.addEventListener("playing",()=>this._maybeRoute()),this.video.addEventListener("loadeddata",()=>this._maybeRoute()),this.video.addEventListener("resize",()=>this._maybeRoute()),this.canvas=P("canvas"),this.cover=P("div",{class:"dxr-call-cover dxr-call-hidden"}),this.badge=P("div",{class:"dxr-call-badge",part:"badge"}),this.plate=P("div",{class:"dxr-call-state",part:"plate",text:e.t("connecting")}),this.stage=P("div",{class:"dxr-call-stage"},[this.canvas,this.cover,this.badge,this.plate]),e.o.tileAspect!=="fill"&&(this.stage.style.aspectRatio=String(e.o.tileAspect)),this._box=null,this._aspect=null,this._rwP=null,this._unobserve=ho(this.stage,(s,o)=>this._onBox(s,o));let r={class:`dxr-call-tile${n==="content"?" dxr-call-tile--content":""}`,part:"tile","data-dxr-peer":t,"data-dxr-kind":n};n!=="content"&&(r["data-peer"]=t),this.el=P("div",r,[this.stage,P("div",{class:"dxr-call-talk"})]),e.o.ui||j(this.badge,!1),n==="content"?e.ui.grid.insertBefore(this.el,e.ui.grid.firstChild):e.ui.grid.appendChild(this.el),e.sinkId&&this.applySink(),this._renderBadge(),this.cursor=null,e.o.cursor&&n!=="content"&&(e._pairCursorMod=e._pairCursorMod||Promise.resolve().then(()=>(pi(),fi)),e._pairCursorMod.then(s=>{this.destroyed||(this.cursor=new s.PairCursor(this.canvas,e.o.cursor))}))}display(){return Nn(this.route)}info(){return Object.freeze({id:this.id,format:this.format||"mono",display:this.display(),state:this.conn,muted:this.remote.muted,cameraOff:this.remote.cameraOff,speaking:this.speaking,name:this.hello&&this.hello.name||null,content:Object.freeze({...this.content})})}_onBox(e,t){let n=this._box;if(this._box={w:e,h:t},e>0&&t>0&&(this._aspect=Sl(e,t)),!n||!e||!t||n.w===e&&n.h===t)return;let r=this.handle;if(!r||!this._fwSettled||typeof r.rewoven!="function")return;let s=r.rewoven();s===this._rwP||!s||typeof s.then!="function"||(this._rwP=s,s.then(o=>{this._rwP!==s||this.handle!==r||!o||(this._rwP=null,this.call.emit("weave",Zt(this.id,o,this.kind)))}))}applySink(){let e=this.audio;return e?typeof e.setSinkId!="function"?Promise.resolve(!1):e.setSinkId(this.call.sinkId||"").then(()=>!0,()=>!1):Promise.resolve(!0)}diag(){return{...this.info(),route:this.route,rectified:!!(this.hello&&this.hello.rectified),hello:this.hello,quality:this.quality,convergencePx:this.conv.current,cursor:this.cursor?this.cursor.last:null,autoConverge:{disparityPx:this.conv.measuredPx,ms:this.autoStats.n?this.autoStats.ms/this.autoStats.n:null,readMs:this.autoStats.n?this.autoStats.readMs/this.autoStats.n:null,method:this.autoStats.method,via:this.autoStats.via,samples:this.autoGrabs,source:this.call.o.autoConverge?this._senderFrac(performance.now())!==null?"sender":this.conv.measuredPx!==null?"local":null:null,senderFrac:this.senderConv?this.senderConv.frac:null},lift:this.lifted?{live:this.liftLive,native:!!(this.liftHandle&&this.liftHandle.native),priority:this.call.liftPool?this.call.liftPool.priority(this.id):null,state:this.liftHandle?this.liftHandle.state||null:"pending"}:null,element:this.el}}setStream(e){this.video.srcObject!==e&&(this.video.srcObject=e,this.audio&&(this.audio.srcObject=e),this._resetAutoConverge()),this.video.play().catch(()=>{}),this.audio?.play().catch(()=>{})}onChannelOpen(){clearTimeout(this.helloTimer),this.helloTimer=setTimeout(()=>{this.format||(this.format="mono",this._maybeRoute())},gl)}setHello(e){clearTimeout(this.helloTimer);let t=this.hello&&this.hello.name||null;this.hello=e,this.conv.hello=e,(e.name||null)!==t&&this.call.emit("name",{id:this.id,name:e.name||null});let n=this.format!==e.format;this.format=e.format,this.call.log("hello",{peer:this.id,format:e.format,width:e.width,height:e.height,rectified:e.rectified}),n?this._maybeRoute():this._renderBadge()}setHint(e){this.hintGate(performance.now())&&(this.conv.subjectZmm=e.subjectZmm)}setConv(e){let t=performance.now();if(this.convGate(t)){if(e.d===null){this.senderConv&&(this.senderConv.at=t);return}this.senderConv={frac:e.d,c:e.c===void 0?null:e.c,at:t}}}_senderFrac(e){let t=this.senderConv;return!t||!this.hello||!this.hello.conv||e-t.at>=pr?null:t.frac}setRemoteState(e){this.remote=e,this._renderBadge(),this._renderPlate(),this._updateVisible()}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.el.classList.toggle("dxr-call-tile--speaking",e),this.call.emit("speaking",{id:this.id,on:e,kind:this.kind}))}setConn(e){e==="unreachable"&&this.conn!=="unreachable"&&this.call.error("unreachable",`${this.call.t("unreachable")}. Still retrying in the background.`,Object.assign(new Error("unreachable"),{peer:this.id})),this.conn=e,e==="connected"&&this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this._renderPlate()}_renderPlate(){let e=this.call.t,t=this.conn==="left"?e("leftCall"):this.conn==="unreachable"?e("unreachable"):this.conn==="reconnecting"?e("reconnecting"):this.conn!=="connected"?e("connecting"):this.remote.cameraOff?e("cameraOffPlate"):null;this.plate.textContent=t||"",j(this.plate,!!t)}_renderBadge(){let e=this.call.t,t=this.route==="woven-sbs"?e("badge3D"):this.route==="lifted"?e("badge2D3D"):e("badge2D"),n=this.route?this.route==="lifted"&&!this.liftLive?`${t}${e("badgePending")}`:t:e("badgePending");this.badge.replaceChildren(P("b",{text:n})),this.badge.dataset.route=this.route||"",this.remote.muted&&this.badge.insertAdjacentHTML("beforeend",Q.mutedSmall)}_maybeRoute(){!this.format||(this.video.readyState||0)<2||!this.video.videoWidth||this.reroute(!1)}reroute(e){let t=this.call,n=t.liftPool,r=this.kind==="content",s=this.forceFlat&&this.format==="sbs"?{route:"flat-left"}:r?{route:this.format==="sbs"?t.woven?"woven-sbs":"flat-left":"flat"}:Fn({format:this.format,woven:t.woven,mono3D:t.mono3DOn?"auto":"off",lift:!!n,overBudget:n?!n.canAcquire(this.id):!1,failed:this.liftFailed});!r&&this.format!=="sbs"&&t.woven&&t.mono3DOn&&!t._liftP&&t._ensureLift(),!r&&this.format!=="sbs"&&t.woven&&t.liftMissing&&t._warnLiftMissing();let o=`${s.route}|${this.format}`;!e&&o===this.routedKey||(this.routedKey=o,this._unregister(),this.route=s.route,s.route==="woven-sbs"?this._registerWoven():s.route==="lifted"&&this._registerLifted(),t.log("route",{peer:this.id,kind:this.kind,route:s.route,format:this.format,mono3d:s.mono3d||null}),t.emit("display",{id:this.id,display:this.display(),kind:this.kind}),!r&&t.listeners.get("format")?.size&&t.emit("format",{id:this.id,format:this.format,route:s.route,mono3d:s.mono3d||null,hello:this.hello}),this._renderBadge())}_registerWoven(){let e=this.call;this.convCanvas||(this.convCanvas=document.createElement("canvas")),this._paintConv(),j(this.cover,!0);let t=e.o.tileCover==="auto"?e.wall.addImage(this.canvas,this.convCanvas,{rectCover:"auto"}):e.wall.addImage(this.canvas,this.convCanvas);this.handle=t,this._fwSettled=!1,this._rwP=null,t.firstWoven?.then(n=>{this.handle===t&&(this._fwSettled=!0,j(this.cover,!1),e.log("first-woven",{peer:this.id,kind:this.kind,woven:n.woven,reason:n.reason,ms:Math.round(n.ms)}),e.emit("weave",Zt(this.id,n,this.kind)),!n.woven&&n.reason==="layer-failed"&&this._layerFailed())})}_registerLifted(){let e=this.call,t=e.liftPool;this.lifted=!0,this.liftLive=!1,this.video.classList.add("dxr-call-liftsrc"),this.canvas.classList.add("dxr-call-liftflat"),this.video.parentNode!==this.stage&&this.stage.insertBefore(this.video,this.stage.firstChild),this._observeVisible(),t.acquire(this.id,this.video,{wall:e.wall,visible:this.visible,onError:n=>this._liftError(n)}).then(n=>{if(!n||!this.lifted||t.handle(this.id)!==n)return;this.liftHandle=n;let r=s=>{s==="live"?this._liftShowing(!0):(s==="error"||s==="disposed")&&this._liftShowing(!1)};this._liftOff=[n.on?.("statechange",s=>r(s&&s.state)),n.on?.("error",s=>{s&&s.fatal&&this._liftError(s.error)})],n.state==="live"?this._liftShowing(!0):n.canvas&&n.canvas.style&&(n.canvas.style.visibility="hidden"),e.log("lifted",{peer:this.id,native:!!n.native,woven:!!n.woven,state:n.state||null,provider:n.stats&&n.stats.provider||null})})}_liftShowing(e){if(e===this.liftLive)return;this.liftLive=e;let t=this.liftHandle;e?(t&&t.canvas&&t.canvas.style&&!t.native&&(t.canvas.style.visibility=""),this.canvas.style.visibility="hidden",this.liftFails=0,this.call.liftProven||(this.call.liftProven=!0,this.call._refreshLobby())):this.canvas.style.visibility="",this.call.log("lift-live",{peer:this.id,live:e}),this._renderBadge()}_liftError(e){this.lifted&&(this.call.log("lift-error",{peer:this.id,message:String(e&&e.message||e).slice(0,200)}),this.liftFailed=!0,this.reroute(!0),!(this.liftFails++>=wl)&&(clearTimeout(this.liftTimer),this.liftTimer=setTimeout(()=>{this.liftFailed=!1,this.reroute(!1)},Z(this.liftFails-1,{baseMs:3e3,maxMs:3e4}))))}_observeVisible(){this._io||typeof IntersectionObserver!="function"||(this._io=new IntersectionObserver(e=>{let t=e[e.length-1];this._onscreen=!!(t&&t.isIntersecting),this._updateVisible()}),this._io.observe(this.stage))}_updateVisible(){let e=this._onscreen!==!1&&!this.remote.cameraOff;e!==this.visible&&(this.visible=e,this.call.liftPool?.setVisible(this.id,e))}_layerFailed(){if(this.forceFlat=!0,this.reroute(!0),this.layerFails++>=yl)return;let e=Z(this.layerFails-1,{baseMs:1500,maxMs:2e4});this.call.log("layer-retry",{peer:this.id,attempt:this.layerFails,inMs:e}),clearTimeout(this.layerTimer),this.layerTimer=setTimeout(()=>{this.forceFlat=!1,this.call.woven&&this.reroute(!0)},e)}onWallLost(){this.handle=null,this.reroute(!0)}_unregister(){if(j(this.cover,!1),this.lifted){this.lifted=!1;for(let e of this._liftOff||[])typeof e=="function"&&e();this._liftOff=null,this.call.liftPool?.release(this.id),queueMicrotask(()=>this.call.state!=="left"&&this.call._rerouteMono()),this.liftHandle=null,this.liftLive=!1,this.canvas.style.visibility="",this.canvas.classList.remove("dxr-call-liftflat"),this._io&&(this._io.disconnect(),this._io=null),this.video.parentNode&&(this.video.remove(),this.video.classList.remove("dxr-call-liftsrc"),setTimeout(()=>this.video.srcObject&&this.video.play().catch(()=>{}),0))}if(this.handle){try{this.handle.remove()}catch{}this.handle=null}}paint(){this.route&&(this._box&&(!this._box.w||!this._box.h)||(this.route!=="woven-sbs"&&this.cursor?.idle(),this.route==="woven-sbs"?this._paintConv():this.route==="lifted"?this.liftLive||oo(this.canvas,this.video):oo(this.canvas,this.video,{eyeHalf:this.route==="flat-left"?0:null})))}_paintConv(){let e=this.video,t=e.videoWidth,n=e.videoHeight;if(!t||!n||(e.readyState||0)<2||!this.convCanvas)return;let r=t/2,s=this.call.o.tileAspect==="fill"?this._aspect||16/9:this.call.o.tileAspect,{w:o,h:a}=We(r,n,s),l=this.convCanvas;(l.width!==2*o||l.height!==a)&&(l.width=2*o,l.height=a);let c=!!(this.cursor&&this.cursor.hovering);if(this.kind==="content")this.conv.measuredPx=this.contentFrac()*r;else{let p=this.call.o.autoConverge,f=p?this._senderFrac(performance.now()):null;f!==null&&(this.conv.measuredPx=f*r),(c||p&&f===null)&&this._sampleDisparity(e,t,n,c)}let h=this.conv.step(r),u=l.getContext("2d"),d=[];for(let p of[0,1]){let f=d[p]=q(r,n,s,h,p);u.drawImage(e,p*r+f.sx,f.sy,f.sw,f.sh,p*o,0,o,a)}this.cursor&&this.cursor.draw(u,this.luma,{rL:d[0],rR:d[1],outW:o,outH:a,handle:this.handle},performance.now()/1e3)}_sampleDisparity(e,t,n,r=!1){let s=performance.now();if(this.autoPending||s-this.autoAt<(r?xl:lo))return;this.autoAt=s,this.autoPending=!0;let o=this.autoGen;this.autoCanvas||(this.autoCanvas=document.createElement("canvas")),Ti(e,{eyeMax:bl,scratch:this.autoCanvas}).then(a=>{o===this.autoGen&&(a?this._applyMeasurement(a.img,a.w,a.h,a.scale,s,a.readMs,a.via):this._applyMeasurement(null,0,0,1,s,0,this.autoStats.via))}).finally(()=>{this.autoPending=!1})}_applyMeasurement(e,t,n,r,s,o,a){if(this.destroyed||(this.autoGrabs++,e&&(this.luma={img:e,w:t,h:n,scale:r}),!this.call.o.autoConverge)||this._senderFrac(performance.now())!==null)return;let l=performance.now(),c=e?this.autoFocus.measure(e,t,n,s):null,h=this.autoTrack.push(c?c.d/r:null);h!==null&&(this.conv.measuredPx=h),this.autoStats.n++,this.autoStats.readMs+=o,this.autoStats.ms+=o+(performance.now()-l),this.autoStats.method=c?c.method:null,this.autoStats.via=a,c&&!this.autoLocked&&(this.autoLocked=!0,this.call.log("auto-converge",{peer:this.id,disparityPx:Math.round(h*10)/10,at:{x:Math.round(c.x/r),y:Math.round(c.y/r)},ncc:Math.round(c.c*100)/100,method:c.method,via:a,ms:Math.round(o+(performance.now()-l))}))}_resetAutoConverge(){this.autoGen++,this.senderConv=null,this.luma=null,this.autoTrack.reset(),this.autoFocus.reset(),this.conv.measuredPx=null,this.autoLocked=!1}destroy(){this.destroyed=!0,this.autoGen++,this.cursor?.dispose(),this.cursor=null,clearTimeout(this.helloTimer),clearTimeout(this.layerTimer),clearTimeout(this.leaveTimer),clearTimeout(this.liftTimer),this._unregister(),this._unobserve?.(),this._unobserve=null,this.video.srcObject=null,this.audio&&(this.audio.srcObject=null),this.el.remove()}contentFrac(){return 0}},Qt=class extends it{constructor(e,t){super(e,t,"content"),this.desc=null,this.conn="connected",this._renderPlate()}setContent(e){let t=this.format!==e.format;this.desc=e,this.format=e.format,this.content={on:!0,format:e.format,appName:e.appName||null},t&&this._maybeRoute(),this._renderBadge()}contentFrac(){let e=this.desc&&this.desc.convergence;return e&&e.known&&typeof e.frac=="number"&&Number.isFinite(e.frac)?e.frac:0}_renderBadge(){super._renderBadge();let e=this.desc&&this.desc.appName;e&&this.route&&this.badge.replaceChildren(P("b",{text:`${e} \xB7 ${this.display()==="3D"?this.call.t("badge3D"):this.call.t("badge2D")}`}))}diag(){return{id:this.id,kind:"content",route:this.route,display:this.display(),format:this.format,appName:this.desc?this.desc.appName:null,width:this.desc?this.desc.width:null,height:this.desc?this.desc.height:null,convergence:this.desc?this.desc.convergence:null,convergencePx:this.conv.current,samples:this.autoGrabs,element:this.el}}},en=class{constructor(e,t){this.call=e,this.canvas=P("canvas"),this.badge=P("div",{class:"dxr-call-badge",part:"badge"}),this.plate=P("div",{class:"dxr-call-state dxr-call-hidden",part:"plate"}),this.stage=P("div",{class:"dxr-call-stage"},[this.canvas,this.badge,this.plate]),e.o.tileAspect!=="fill"&&(this.stage.style.aspectRatio=String(e.o.tileAspect)),this.el=P("div",{class:"dxr-call-tile dxr-call-tile--self",part:"tile","data-dxr-peer":"self"},[this.stage,P("div",{class:"dxr-call-talk"})]),t.appendChild(this.el),this._box=null,this._rwP=null,this._unobserve=ho(this.stage,(n,r)=>this._onBox(n,r)),this.view=null,this.cam=null}get route(){return this.view?this.view.route:null}update(){let e=this.call.local,t=this.call.t,n=!e||!e.videoTrack;this.plate.textContent=n?this.call.camStatus==="busy"?t("cameraBusy"):this.call.camStatus==="pending"?"":t("noCamera"):this.call.camOff?t("cameraOffPlate"):"",j(this.plate,n||this.call.camOff),this.reroute(!1)}reroute(e){let t=this.call.local,n=t&&t.videoTrack?t.cam:null,r=this.call.woven?this.call.wall:{supported:!1};if(!n||n.state!=="live"||!this.call.selfViewOn)return this.detach(),this._badge();this.view&&this.cam===n?this.view._reroute(e,r):(this.detach(),this.cam=n,this.view=vi(r,this.canvas,n,{autoConverge:!!this.call.o.autoConverge,cursor:this.call.o.cursor||void 0,aspect:this.call.o.tileAspect,...this.call.o.tileCover==="auto"?{rectCover:"auto"}:{},onRouteChange:(s,o)=>{this.cam===n&&(this.call.log("self-route",{route:s,woven:o.woven,reason:o.reason}),this._badge(),this._weave(o))}})),this._badge()}_weave(e){let t=e.firstWoven,n=null;t&&typeof t=="object"?n=Zt("self",t):e.route!=="woven-sbs"&&e.reason&&(n={id:"self",state:"flat",reason:e.reason,ms:0,kind:"camera"}),n&&this.call.emit("weave",n)}_onBox(e,t){let n=this._box;if(this._box={w:e,h:t},!n||!e||!t||n.w===e&&n.h===t)return;let r=this.view&&this.view.woven?this.view.handle:null,s=this.view?this.view.weaveState().firstWoven:null;if(!r||!s||typeof s!="object"||typeof r.rewoven!="function")return;let o=r.rewoven();o===this._rwP||!o||typeof o.then!="function"||(this._rwP=o,o.then(a=>{this._rwP!==o||!this.view||this.view.handle!==r||!a||(this._rwP=null,this.call.emit("weave",Zt("self",a)))}))}_badge(){let e=this.call.t,t=!!(this.view&&this.view.woven);this.badge.replaceChildren(P("b",{text:`${e("you")} \xB7 ${e(t?"badge3D":"badge2D")}`})),this.badge.dataset.route=this.route||""}diag(){return this.view?this.view.weaveState():{route:null,woven:!1,reason:"no-camera",firstWoven:null,layerRetries:0}}onWallLost(){this.view?._onWallLost(),this._badge()}detach(){this.view&&this.view.remove(),this.view=null,this.cam=null}setSpeaking(e){this.el.classList.toggle("dxr-call-tile--speaking",e)}},El="1.31",ao=new Set;function F(i,e,t){let n=()=>{ao.has(i)||(ao.add(i),console.warn(`${Y} \`${i}\` is internal and leaves '@displayxr/inline3d/call' in ${El} \u2014 import it from ${e} if you must, or stop depending on it`))};return typeof t=="function"?new Proxy(t,{apply(r,s,o){return n(),Reflect.apply(r,s,o)},construct(r,s){return n(),Reflect.construct(r,s)}}):t&&typeof t=="object"?new Proxy(t,{get(r,s,o){return typeof s=="string"&&n(),Reflect.get(r,s,o)}}):t}var mh=F("normalizeCallOptions","js/call/options.js",Mi),gh=F("newRoomId","js/call/wire.js",An),_h=F("isValidRoomId","js/call/wire.js",we),vh=F("buildInviteLink","js/call/wire.js",_t),yh=F("normalizeHello","js/call/wire.js",On),wh=F("makeHello","js/call/wire.js",Dn),bh=F("routeFor","js/call/wire.js",Fn),xh=F("badgeFor","js/call/wire.js",Nn),Sh=F("createLiveGate","js/call/wire.js",jn),Mh=F("convergenceShiftPx","js/camera/converge.js",dt),Eh=F("lowPass","js/camera/converge.js",pt),Ch=F("clampShift","js/camera/converge.js",ft),Rh=F("eyeCropRect","js/camera/geometry.js",q),kh=F("mirrorSwapOps","js/camera/geometry.js",ve),Th=F("mirrorSwapPixels","js/camera/geometry.js",Rn),Ah=F("maxBitrateKbps","js/call/wire.js",Ve),Oh=F("measureFocusDisparity","js/camera/disparity.js",$n),Dh=F("preferVideoCodecs","js/call/sdp.js",Xe),Ph=F("sortCodecCapabilities","js/call/sdp.js",yt),Lh=F("VIDEO_CODEC_ORDER","js/call/sdp.js",Be),Ih=F("MeshTransport","js/call/transport.js",Ge),Fh=F("clampMaxPeers","js/call/transport.js",qe),Nh=F("qrEncode","js/call/qr.js",bi),jh=F("roomKey","js/call/signaling.js",xi);var zh=F("PLATE_TEXT","js/call/ui.js (CALL_STRINGS)",Object.freeze({unreachable:tt.unreachable,cameraBusy:tt.cameraBusy})),Wh=F("CALL_ACCENTS","js/call/ui.js",Si),Hh=F("normalizeMono3D","js/call/lift.js",je),$h=F("resolveLift","js/call/lift.js",nn),Uh=F("createLiftPool","js/call/lift.js",on),Vh=F("createFrameWatch","js/call/lift.js",sn),Bh=F("liftConvergenceFor","js/call/lift.js",Ne),Xh=F("liftPriorityFor","js/call/lift.js",rt),Gh=F("setLiftPriority","js/call/lift.js",rn),qh=F("defaultLiftSpecifier","js/call/lift.js",tn),Yh=F("LIFT_PRIORITY","js/call/lift.js",Fe);Jt();Pi(()=>new URL("./lift.js",import.meta.url).href);export{Ci as CALL_EVENT_PREFIX,js as CAMERA_SDK,Kt as DXR_SIGNAL_DEFAULT,Pe as DxrCallElement,co as addCall,vi as addCameraView,Ri as attrsToOpts,or as createInline3D,Jt as defineCallElement,De as dxrSignaling,rr as inline3DAvailable,Yt as isStereoCamera,ki as mountCall,_i as openCamera,$e as parseInviteLink,Bn as parseStereoXmp,Ur as readJpegStereoMeta,Xn as readJpegXmp,Kr as readWebmStereoMeta,ut as sharedInline3D,qt as suggestedName};