@displayxr/inline3d 1.49.3 → 1.51.0
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/CHANGELOG.md +56 -0
- package/README.md +6 -1
- package/call.d.ts +16 -0
- package/dist/call.js +6 -6
- package/docs/making-3d-look-right.md +14 -7
- package/docs/woven-canvas-rules.md +30 -1
- package/hands.d.ts +198 -0
- package/index.d.ts +4 -0
- package/js/call/share.js +90 -0
- package/js/camera/capture.js +9 -0
- package/js/camera/half-sbs.js +109 -0
- package/js/inline3d-call.js +1 -1
- package/js/inline3d-hands.js +618 -0
- package/js/inline3d-model-entry.js +3 -1
- package/js/inline3d-splat-playcanvas.js +71 -16
- package/js/inline3d-splat-shared.js +12 -1
- package/js/inline3d-viewer.js +39 -8
- package/llms.txt +2 -2
- package/model.d.ts +10 -0
- package/package.json +7 -1
- package/splat.d.ts +16 -0
- package/viewer.d.ts +12 -0
package/dist/call.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
/* @displayxr/inline3d 1.
|
|
2
|
-
var fo=Object.defineProperty;var fe=(i,e)=>()=>(i&&(e=i(i=0)),e);var po=(i,e)=>{for(var t in e)fo(i,t,{get:e[t],enumerable:!0})};function Fi(i,e,t=1){let n=ot,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 ot,an=fe(()=>{"use strict";ot=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,m=0,f=a*l;for(let v=0;v<l;v++){let _=(r+v)*e+n,C=(o+v)*e+t+s;for(let S=0;S<a;S++){let A=i[C+S];u+=A,d+=A*A,m+=i[_+S]*A}}let g=u/f,x=d/f-g*g;return x<1?-1:(m/f-c*g)/(h*Math.sqrt(x))}function ba(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 m=i[u+d];o+=m,a+=m*m}}let l=r*s,c=o/l;return{mean:c,std:Math.sqrt(Math.max(0,a/l-c*c))}}function xe(i,e,t,n,r,s,o,{dMin:a,dMax:l,dyMax:c=2,uniq:h}={}){let u=e/2,{mean:d,std:m}=ba(i,e,n,r,s,o);if(m<6)return null;let f=-2,g=0,x=0,v=new Map,_=(T,w,b,p,y)=>{for(let M=p;M<=y;M++){let E=r+M;if(!(E<0||E+o>t))for(let N=T;N<=w;N+=b){let W=Mt(i,e,u,n,r,n-N,E,s,o,d,m);W>(v.get(N)??-2)&&v.set(N,W),W>f&&(f=W,g=N,x=M)}}},C=l-a>8;if(_(a,l,C?2:1,-c,c),C&&f>-1){let T=g,w=x;_(Math.max(a,T-2),Math.min(l,T+2),1,Math.max(-c,w-1),Math.min(c,w+1))}if(f<-1)return null;let S=-2,A=T=>{let w=-2;for(let b=-c;b<=c;b++){let p=r+b;if(!(p<0||p+o>t))for(let y=T-1;y<=T+1;y++)w=Math.max(w,Mt(i,e,u,n,r,n-y,p,s,o,d,m))}return w};for(let[T,w]of v){if(Math.abs(T-g)<3||w<=S)continue;let p=w>=(v.get(T-2)??-2)&&w>=(v.get(T+2)??-2)&&w>0?A(T):w;p>S&&(S=p)}if(l-a>12&&S>-2&&f-S<(h??.08))return null;let k=Mt(i,e,u,n,r,n-(g-1),r+x,s,o,d,m),O=Mt(i,e,u,n,r,n-(g+1),r+x,s,o,d,m),P=0,R=k-2*f+O;return k>-1&&O>-1&&R<0&&(P=Math.max(-.5,Math.min(.5,.5*(k-O)/R))),{d:g+P,dy:x,c:f}}function xa(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,m=[];for(let f=u;f<=d;f+=o)for(let g=c;g<=h;g+=o){let x=xe(i,e,t,g,f,s,s,{dMin:l,dMax:a,dyMax:n.dyMax??2,uniq:n.uniq});x&&x.c>=(n.minNcc??.8)&&m.push({x:g,y:f,...x})}return m}function Sa(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 Ma(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 C=xa(i,e,t,{...n,block:s,dMax:o,dMin:a});h=C.length;let S=Sa(C,n);if(!S)return null;l=Ma(S.members,s),u=S.d,c="mode"}let d=Math.round(s*(n.refineW??3)),m=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-m,l.y-m/2))),x=u===null?a:Math.max(a,Math.floor(u)-4),v=u===null?o:Math.min(o,Math.ceil(u)+4),_=xe(i,e,t,f,g,d,m,{dMin:x,dMax:v,dyMax:n.dyMax??2});return _&&_.c>=(n.minNcc??.8)?{d:_.d,x:l.x,y:l.y,c:_.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 Se({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 Pr(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 Ea(i,e,t,n,r,s,o,a,l,c){let h=e/2,u=r*s,d=0,m=0;for(let _=0;_<u;_++)d+=n[_],m+=n[_]*n[_];d/=u;let f=Math.sqrt(Math.max(1e-6,m/u-d*d)),g=-2,x=o,v=a;for(let _=Math.max(0,a-c);_<=Math.min(t-s,a+c);_++)for(let C=Math.max(0,o-l);C<=Math.min(h-r,o+l);C++){let S=0,A=0,k=0;for(let T=0;T<s;T++){let w=(_+T)*e+C;for(let b=0;b<r;b++){let p=i[w+b];S+=p,A+=p*p,k+=p*n[T*r+b]}}let O=S/u,P=A/u-O*O;if(P<1)continue;let R=(k/u-O*d)/(Math.sqrt(P)*f);R>g&&(g=R,x=C,v=_)}return{x,y:v,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,m={}){let f=h/2,g=m.block||Math.max(8,Math.round(f/20)),x=Math.round(g*3),v=Math.round(g*1.5),_=null;if(o&&o.w===x&&o.h===v){let O=Ea(c,h,u,o.tpl,x,v,o.x,o.y,t,n);if(O.c>=r){let P=xe(c,h,u,O.x,O.y,x,v,{dMin:Math.floor(o.d)-e,dMax:Math.ceil(o.d)+e,dyMax:2});P&&P.c>=.8&&(_={m:P,f:O})}}let C=({m:O,f:P})=>(o={...o,x:P.x,y:P.y,d:O.d,tpl:Pr(c,h,P.x,P.y,x,v)},{d:O.d,x:P.x+x/2,y:P.y+v/2,c:O.c,method:"track",blocks:0});if(_&&d-o.at<i)return C(_);let S=$n(c,h,u,m);if(_&&(!S||Math.abs(S.d-_.m.d)>s)){let O=S&&a&&Math.abs(a.d-S.d)<=3;if(a=S&&!O?{d:S.d}:null,!O)return o.at=d,C(_)}else a=null;if(!S)return o=null,null;let A=Math.round(Math.max(0,Math.min(f-x,S.x-x/2))),k=Math.round(Math.max(0,Math.min(u-v,S.y-v/2)));return o={x:A,y:k,d:S.d,tpl:Pr(c,h,A,k,x,v),w:x,h:v,at:d},S},reset(){o=null,a=null}}}function Lr(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 m=0;m<l;m++)for(let f=0;f<a;f++){let g=0;for(let x=0;x<o;x++){let v=e+(m*o+x)*t+f*o;for(let _=0;_<o;_++)g+=i[v+_]}c[m*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 m=e+(d*o+h)*t,f=e+(d*o+u)*t;for(let g=0;g<a;g++){let x=g*o+h,v=g*o+u;c[d*a+g]=i[m+x]+i[m+v]+i[f+x]+i[f+v]>>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{...Me};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{...Me,...Ir(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={...Me,...Ir(i.mode??"both")};for(let s of Object.keys(At)){if(i[s]===void 0)continue;let[o,a,l]=At[s];if(!Ca(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 Nr(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&&!Ee.includes(i.shape))throw new Error(`${e}: cursor.shape ${JSON.stringify(i.shape)} \u2014 expected ${Ee.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=Nr(i,e);if(!t)return null;let n=Object.keys(t).filter(r=>!Fr.includes(r));if(n.length)throw new Error(`${e}: cursor \u2014 ${n.join(", ")} not supported on a stereo pair; expected ${Fr.join(", ")}.`);return t}var Un,Rt,Ce,Ee,kt,Me,At,Tt,Ca,Ir,Fr,Re=fe(()=>{"use strict";Un=Object.freeze(["hybrid","screen","world"]),Rt=Object.freeze(["height","margin","anchor","pointerScope","debug","soften","shape","shapeFor"]),Ce=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"]),Ee=Object.freeze(["auto","none",...Ce]),kt=Object.freeze(["both","off","alpha","blur"]),Me=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)]),Ca=(i,e)=>{let[t,n,r]=At[i];return typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n&&!(r&&e<=t)},Ir=i=>({blur:i==="both"||i==="blur",alpha:i==="both"||i==="alpha"});Fr=Object.freeze(["height","pointerScope","soften","shape","shapeFor"])});function Kn(i){return typeof i=="string"&&rs[i.trim().toLowerCase()]||"arrow"}function La(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 La(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 ss(i){return Kn(Jn(i).keyword)}function os(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 as(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,is/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 Ae(Kn(t.keyword))}function Ae(i){if(i==="none")return{kind:"none"};let e=Ce.includes(i)?i:"arrow";return{kind:"shape",name:e,key:`shape:${e}`}}function D(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),m=t-c*s,f=n-h*s,g=1-2*s/r;return Oe([[i+u,e+d],[m+u,f+d],[t+u*g,n+d*g],[t-u*g,n-d*g],[m-u,f-d],[i-u,e-d]])}function Zr(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 Oe([[i+l,e+c],[t+l,n+c],[t-l,n-c],[i-l,e-c]])}function ls(i,e,t,n=20){return Oe(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 Fa(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(Oe([...l.map(c=>o(n,c)),...l.reverse().map(c=>o(t,c))]))}return s}function ja(){return{pointer:{hot:[6.8,0],parts:[D(5,0,8.6,14,[1.2,1.2,0,0]),D(7.6,5.4,10.9,14,[1.1,1.1,0,0]),D(9.9,6.4,13.2,14,[1.1,1.1,0,0]),D(12.2,7.6,15.2,14,[.9,.9,0,0]),D(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:[D(3,2.6,6.6,12.4,[1.2,1.2,0,0]),D(5.6,.6,9.2,12.4,[1.2,1.2,0,0]),D(8.2,1.4,11.8,12.4,[1.2,1.2,0,0]),D(10.8,3.6,14.2,12.4,[1.1,1.1,0,0]),D(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:[D(3,5.6,6.6,12.4,[1.2,1.2,0,0]),D(5.6,5,9.2,12.4,[1.2,1.2,0,0]),D(8.2,5.2,11.8,12.4,[1.2,1.2,0,0]),D(10.8,6,14.2,12.4,[1.1,1.1,0,0]),D(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:[D(3,7.8,16,11.2),D(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:[D(8,.5,11,18.5),D(4.5,0,14.5,3),D(4.5,16,14.5,19)]},"vertical-text":{hot:[9.5,9.5],parts:Ze([D(8,.5,11,18.5),D(4.5,0,14.5,3),D(4.5,16,14.5,19)],90,9.5,9.5)},crosshair:{hot:[9.5,9.5],parts:[D(0,8,19,11),D(8,0,11,19)]},cell:{hot:[9.5,9.5],parts:[D(1.5,6.3,17.5,12.7),D(6.3,1.5,12.7,17.5)]},"not-allowed":{hot:[9.5,9.5],parts:[...Fa(9.5,9.5,5.4,8.8),Zr(4.6,4.6,14.4,14.4,3.4)]},help:{hot:[0,0],parts:[...he(Qe(),.8),ls(13.6,12.4,5.4)],detail:[D(11.6,9,15.4,10.2),D(14.4,9,15.6,12.6),D(12.9,11.6,15.6,12.8),D(12.9,11.6,14.1,13.8),D(12.9,14.8,14.1,16)]},wait:{hot:[9.5,9.5],parts:Na()},progress:{hot:[0,0],parts:[...he(Qe(),.8),D(10.6,9,18.8,11.6),D(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(Qe(),.8),D(9.6,9.8,18.8,19,[1.2,1.2,1.2,1.2])],detail:[D(13.6,11.8,14.8,17),D(11.6,13.8,16.8,15)]},alias:{hot:[0,0],parts:[...he(Qe(),.8),D(9.6,9.8,18.8,19,[1.2,1.2,1.2,1.2])],detail:[Zr(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(Qe(),.8),D(9.2,8.6,18.8,19)],detail:[D(11,10.8,17,11.8),D(11,13.3,17,14.3),D(11,15.8,17,16.8)]},"ns-resize":{hot:[9.5,9.5],parts:Nt()},"ew-resize":{hot:[9.5,9.5],parts:Ze(Nt(),90,9.5,9.5)},"nesw-resize":{hot:[9.5,9.5],parts:he(Ze(Nt(),45,9.5,9.5),1.2,-1.9,-1.9)},"nwse-resize":{hot:[9.5,9.5],parts:he(Ze(Nt(),-45,9.5,9.5),1.2,-1.9,-1.9)},"col-resize":{hot:[9.5,9.5],parts:Qr()},"row-resize":{hot:[9.5,9.5],parts:Ze(Qr(),90,9.5,9.5)},"zoom-in":{hot:[7.5,7.5],parts:es(),detail:[D(4.4,6.9,10.6,8.1),D(6.9,4.4,8.1,10.6)]},"zoom-out":{hot:[7.5,7.5],parts:es(),detail:[D(4.4,6.9,10.6,8.1)]}}}function Qn(i){let e=Ce.includes(i)?i:"arrow",t=ts.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=[fs],o=[];else{let c=(Wa||=ja())[e],h=u=>u.map(d=>d.map(([m,f])=>[(m-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)])}),ts.set(e,t),t}function De(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 cs(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 hs(i,e,t,n,r,s=ri,o=si,a=De(i)){let l=0,c=0,h=0,u=0,d=0,m=n>0?tt:tt.slice(0,1),f=a.detail&&a.detail.length?a.detail:null;for(let[g,x,v]of m){let _=e+g*n,C=t+x*n,S=Yn(qn(a.outline,_,C),r),A=S>0?Yn(qn(a.fill,_,C),r):0;f&&A>0&&(A*=1-Yn(qn(f,_,C),r)),l+=v*(o[0]*S+(s[0]-o[0])*A),c+=v*(o[1]*S+(s[1]-o[1])*A),h+=v*(o[2]*S+(s[2]-o[2])*A),u+=v*S,d+=v}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=De(i)){let c=n>0&&Number.isFinite(n)?n:1,h=1/c,[u,d,m,f]=cs(i,r,h),g=Math.floor(e+u*c),x=Math.floor(t+d*c),v=Math.max(1,Math.ceil(e+m*c)-g),_=Math.max(1,Math.ceil(t+f*c)-x),C=new Uint8ClampedArray(v*_*4),S=s>=0&&s<=1?s:1;for(let A=0;A<_;A++){let k=(x+A+.5-t)/c;for(let O=0;O<v;O++){let P=hs(i,(g+O+.5-e)/c,k,r,h,o,a,l);if(!(P[3]>0))continue;let R=(A*v+O)*4;C[R]=Math.round(P[0]*255),C[R+1]=Math.round(P[1]*255),C[R+2]=Math.round(P[2]*255),C[R+3]=Math.round(P[3]*S*255)}}return{x0:g,y0:x,width:v,height:_,data:C}}function ti(i,e,t,n,r,s=De(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],m)=>(m?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?tt:tt.slice(0,1);for(let u=0;u<a;u++)for(let d=0;d<o;d++){let m=0,f=0,g=0,x=0,v=0;for(let[C,S,A]of h){v+=A;let k=Math.round(d-s+C*n),O=Math.round(u-s+S*n);if(k<0||O<0||k>=e||O>=t)continue;let P=(O*e+k)*4,R=i[P+3]/255*A;m+=i[P]*R,f+=i[P+1]*R,g+=i[P+2]*R,x+=R}if(!(x>1e-5))continue;let _=(u*o+d)*4;l[_]=m/x,l[_+1]=f/x,l[_+2]=g/x,l[_+3]=x/v*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=ns,(i.head||i.documentElement)?.appendChild(t),!0}function ds(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,ns,is,rs,Pa,Ft,Ia,Wt,Zn,Oe,B,Ze,he,Qe,Nt,Qr,Na,es,Wa,ts,qn,Yn,us,zt,et,ii=fe(()=>{"use strict";oi();Re();X="data-inline3d-cursor-hidden",ns=`[${X}],[${X}] *{cursor:none!important}`,is=128,rs=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"}),Pa=Object.freeze(Object.keys(rs));Ft=new Map;Ia=i=>/\.cur(?:[?#]|$)/i.test(i)||/^data:image\/(?:x-win-bitmap|x-icon|vnd\.microsoft\.icon)/i.test(i),Wt=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"},Ia(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?os(o,t.width):null}).catch(()=>{}).finally(s)),n.src=e,t}},Zn=new Wt;Oe=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)=>Oe([i,e,t]),Ze=(i,e,t,n)=>{let r=e*Math.PI/180,s=Math.cos(r),o=Math.sin(r);return i.map(a=>Oe(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])),Qe=()=>[ie.map(([i,e])=>[i*19,e*19])],Nt=()=>[D(8,3,11,16),B([9.5,0],[14.2,5],[4.8,5]),B([9.5,19],[4.8,14],[14.2,14])],Qr=()=>[D(8,1,11,18),D(3.4,8,7.4,11),B([0,9.5],[4.4,5],[4.4,14]),D(11.6,8,15.6,11),B([19,9.5],[14.6,14],[14.6,5])],Na=()=>[D(3,0,16,3),D(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])],es=()=>[ls(7.5,7.5,7),jt(11.6,11.6,18.4,18.4,3.8,1)];Wa=null,ts=new Map;qn=(i,e,t)=>{let n=1/0;for(let r of i)n=Math.min(n,ps(r,e,t));return n},Yn=(i,e)=>e>0?Math.min(1,Math.max(0,.5-i/e)):i<0?1:0;us=100;zt=class{constructor(e,{throttleMs:t=us}={}){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 ss(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=ds(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))}},et=class{constructor(e,{shape:t="auto",shapeFor:n=null,images:r=Zn}={}){if(!Ee.includes(t))throw new Error(`@displayxr/inline3d: cursor.shape "${t}" \u2014 expected ${Ee.join(", ")}.`);this.option=t,this.shapeFor=typeof n=="function"?n:null,this.images=r,this.reader=t==="auto"?new zt(e):null,this.sprite=Ae(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:as(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"||Ce.includes(l);return a(o)?this.sprite=Ae(o):a(this.option)?this.sprite=Ae(this.option):this.sprite=r||Ae("arrow"),this.sprite}dispose(){this.reader?.dispose()}}});function vs(i){return i>0&&Number.isFinite(i)?Math.min(.5,ci/i):za}function ys(i,e){return i<=Ha?!(e>0&&Number.isFinite(e))||-i*e>=$a:!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 ws(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 ms(i){let e=i&&i.pointerType;return!e||e==="mouse"?!0:e==="pen"?!(i.buttons>0):!1}function Ua(i){return!!i&&"onpointerrawupdate"in i&&globalThis.isSecureContext!==!1}function Va(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 gs(i){return!!i&&typeof i.setCursorDepth=="function"&&typeof i.getCursorDepthSupport=="function"}function qa(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 bs(i,e,t,n){return[[i,e],...qa(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 xs(i,e,t,n=Me){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 ps(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],m=Math.min(1,Math.max(0,(u*c+d*h)/(c*c+h*h))),f=u-c*m,g=d-h*m;n=Math.min(n,f*f+g*g);let x=t>=a[1],v=t<l[1],_=c*d>h*u;(x&&v&&_||!x&&!v&&!_)&&(r=-r)}return r*Math.sqrt(n)}var za,ci,Ha,$a,Bt,Ut,ai,Ba,Xa,Ga,li,Vt,_s,ie,Mc,fs,ri,si,tt,Ec,Cc,Rc,oi=fe(()=>{"use strict";Re();Re();ii();ii();za=.03,ci=19;Ha=-.005,$a=.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=>{ms(r)||(this.uv=null)},this._target=t==="window"?globalThis:e,this.source=Ua(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(!ms(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"?Va(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;Ba=2e3,Xa=6,Ga=1e4;li=new WeakMap,Vt=class{constructor(){this.target=null,this._sent=!1,this.last=null}get support(){let e=this.target;if(!gs(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),!gs(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<Xa?Ba:Ga;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:_s(e),v:_s(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}},_s=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]))),Mc=Object.freeze([[0,1,2],[0,2,5],[0,5,6],[2,3,4],[2,4,5]]);fs=Object.freeze($t(1/19).map(i=>Object.freeze(i))),ri=Object.freeze([1,1,1,1]),si=Object.freeze([.02,.02,.03,1]);tt=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])})]),Ec=Object.freeze([Math.max(...ie.map(i=>i[0])),Math.max(...ie.map(i=>i[1]))]);Cc=Object.freeze({declarations:`#ifdef PICK_PASS
|
|
1
|
+
/* @displayxr/inline3d 1.51.0 — dist/call.js — Apache-2.0 — https://github.com/DisplayXR/displayxr-web */
|
|
2
|
+
var go=Object.defineProperty;var fe=(i,e)=>()=>(i&&(e=i(i=0)),e);var _o=(i,e)=>{for(var t in e)go(i,t,{get:e[t],enumerable:!0})};function Fi(i,e,t=1){let n=ot,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 ot,an=fe(()=>{"use strict";ot=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,m=0,f=a*l;for(let v=0;v<l;v++){let _=(r+v)*e+n,C=(o+v)*e+t+s;for(let M=0;M<a;M++){let A=i[C+M];u+=A,d+=A*A,m+=i[_+M]*A}}let g=u/f,x=d/f-g*g;return x<1?-1:(m/f-c*g)/(h*Math.sqrt(x))}function ka(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 m=i[u+d];o+=m,a+=m*m}}let l=r*s,c=o/l;return{mean:c,std:Math.sqrt(Math.max(0,a/l-c*c))}}function xe(i,e,t,n,r,s,o,{dMin:a,dMax:l,dyMax:c=2,uniq:h}={}){let u=e/2,{mean:d,std:m}=ka(i,e,n,r,s,o);if(m<6)return null;let f=-2,g=0,x=0,v=new Map,_=(T,w,S,p,y)=>{for(let b=p;b<=y;b++){let E=r+b;if(!(E<0||E+o>t))for(let N=T;N<=w;N+=S){let z=Mt(i,e,u,n,r,n-N,E,s,o,d,m);z>(v.get(N)??-2)&&v.set(N,z),z>f&&(f=z,g=N,x=b)}}},C=l-a>8;if(_(a,l,C?2:1,-c,c),C&&f>-1){let T=g,w=x;_(Math.max(a,T-2),Math.min(l,T+2),1,Math.max(-c,w-1),Math.min(c,w+1))}if(f<-1)return null;let M=-2,A=T=>{let w=-2;for(let S=-c;S<=c;S++){let p=r+S;if(!(p<0||p+o>t))for(let y=T-1;y<=T+1;y++)w=Math.max(w,Mt(i,e,u,n,r,n-y,p,s,o,d,m))}return w};for(let[T,w]of v){if(Math.abs(T-g)<3||w<=M)continue;let p=w>=(v.get(T-2)??-2)&&w>=(v.get(T+2)??-2)&&w>0?A(T):w;p>M&&(M=p)}if(l-a>12&&M>-2&&f-M<(h??.08))return null;let k=Mt(i,e,u,n,r,n-(g-1),r+x,s,o,d,m),O=Mt(i,e,u,n,r,n-(g+1),r+x,s,o,d,m),L=0,R=k-2*f+O;return k>-1&&O>-1&&R<0&&(L=Math.max(-.5,Math.min(.5,.5*(k-O)/R))),{d:g+L,dy:x,c:f}}function Ta(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,m=[];for(let f=u;f<=d;f+=o)for(let g=c;g<=h;g+=o){let x=xe(i,e,t,g,f,s,s,{dMin:l,dMax:a,dyMax:n.dyMax??2,uniq:n.uniq});x&&x.c>=(n.minNcc??.8)&&m.push({x:g,y:f,...x})}return m}function Aa(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 Oa(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 C=Ta(i,e,t,{...n,block:s,dMax:o,dMin:a});h=C.length;let M=Aa(C,n);if(!M)return null;l=Oa(M.members,s),u=M.d,c="mode"}let d=Math.round(s*(n.refineW??3)),m=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-m,l.y-m/2))),x=u===null?a:Math.max(a,Math.floor(u)-4),v=u===null?o:Math.min(o,Math.ceil(u)+4),_=xe(i,e,t,f,g,d,m,{dMin:x,dMax:v,dyMax:n.dyMax??2});return _&&_.c>=(n.minNcc??.8)?{d:_.d,x:l.x,y:l.y,c:_.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 Se({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 Fr(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 Da(i,e,t,n,r,s,o,a,l,c){let h=e/2,u=r*s,d=0,m=0;for(let _=0;_<u;_++)d+=n[_],m+=n[_]*n[_];d/=u;let f=Math.sqrt(Math.max(1e-6,m/u-d*d)),g=-2,x=o,v=a;for(let _=Math.max(0,a-c);_<=Math.min(t-s,a+c);_++)for(let C=Math.max(0,o-l);C<=Math.min(h-r,o+l);C++){let M=0,A=0,k=0;for(let T=0;T<s;T++){let w=(_+T)*e+C;for(let S=0;S<r;S++){let p=i[w+S];M+=p,A+=p*p,k+=p*n[T*r+S]}}let O=M/u,L=A/u-O*O;if(L<1)continue;let R=(k/u-O*d)/(Math.sqrt(L)*f);R>g&&(g=R,x=C,v=_)}return{x,y:v,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,m={}){let f=h/2,g=m.block||Math.max(8,Math.round(f/20)),x=Math.round(g*3),v=Math.round(g*1.5),_=null;if(o&&o.w===x&&o.h===v){let O=Da(c,h,u,o.tpl,x,v,o.x,o.y,t,n);if(O.c>=r){let L=xe(c,h,u,O.x,O.y,x,v,{dMin:Math.floor(o.d)-e,dMax:Math.ceil(o.d)+e,dyMax:2});L&&L.c>=.8&&(_={m:L,f:O})}}let C=({m:O,f:L})=>(o={...o,x:L.x,y:L.y,d:O.d,tpl:Fr(c,h,L.x,L.y,x,v)},{d:O.d,x:L.x+x/2,y:L.y+v/2,c:O.c,method:"track",blocks:0});if(_&&d-o.at<i)return C(_);let M=$n(c,h,u,m);if(_&&(!M||Math.abs(M.d-_.m.d)>s)){let O=M&&a&&Math.abs(a.d-M.d)<=3;if(a=M&&!O?{d:M.d}:null,!O)return o.at=d,C(_)}else a=null;if(!M)return o=null,null;let A=Math.round(Math.max(0,Math.min(f-x,M.x-x/2))),k=Math.round(Math.max(0,Math.min(u-v,M.y-v/2)));return o={x:A,y:k,d:M.d,tpl:Fr(c,h,A,k,x,v),w:x,h:v,at:d},M},reset(){o=null,a=null}}}function Nr(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 m=0;m<l;m++)for(let f=0;f<a;f++){let g=0;for(let x=0;x<o;x++){let v=e+(m*o+x)*t+f*o;for(let _=0;_<o;_++)g+=i[v+_]}c[m*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 m=e+(d*o+h)*t,f=e+(d*o+u)*t;for(let g=0;g<a;g++){let x=g*o+h,v=g*o+u;c[d*a+g]=i[m+x]+i[m+v]+i[f+x]+i[f+v]>>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{...Me};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{...Me,...jr(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={...Me,...jr(i.mode??"both")};for(let s of Object.keys(At)){if(i[s]===void 0)continue;let[o,a,l]=At[s];if(!Pa(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 Wr(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&&!Ee.includes(i.shape))throw new Error(`${e}: cursor.shape ${JSON.stringify(i.shape)} \u2014 expected ${Ee.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=Wr(i,e);if(!t)return null;let n=Object.keys(t).filter(r=>!zr.includes(r));if(n.length)throw new Error(`${e}: cursor \u2014 ${n.join(", ")} not supported on a stereo pair; expected ${zr.join(", ")}.`);return t}var Un,Rt,Ce,Ee,kt,Me,At,Tt,Pa,jr,zr,Re=fe(()=>{"use strict";Un=Object.freeze(["hybrid","screen","world"]),Rt=Object.freeze(["height","margin","anchor","pointerScope","debug","soften","shape","shapeFor"]),Ce=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"]),Ee=Object.freeze(["auto","none",...Ce]),kt=Object.freeze(["both","off","alpha","blur"]),Me=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)]),Pa=(i,e)=>{let[t,n,r]=At[i];return typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n&&!(r&&e<=t)},jr=i=>({blur:i==="both"||i==="blur",alpha:i==="both"||i==="alpha"});zr=Object.freeze(["height","pointerScope","soften","shape","shapeFor"])});function Kn(i){return typeof i=="string"&&as[i.trim().toLowerCase()]||"arrow"}function Ha(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 Ha(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 ls(i){return Kn(Jn(i).keyword)}function cs(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 hs(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,os/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 Ae(Kn(t.keyword))}function Ae(i){if(i==="none")return{kind:"none"};let e=Ce.includes(i)?i:"arrow";return{kind:"shape",name:e,key:`shape:${e}`}}function D(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),m=t-c*s,f=n-h*s,g=1-2*s/r;return Oe([[i+u,e+d],[m+u,f+d],[t+u*g,n+d*g],[t-u*g,n-d*g],[m-u,f-d],[i-u,e-d]])}function ts(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 Oe([[i+l,e+c],[t+l,n+c],[t-l,n-c],[i-l,e-c]])}function us(i,e,t,n=20){return Oe(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 Ua(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(Oe([...l.map(c=>o(n,c)),...l.reverse().map(c=>o(t,c))]))}return s}function Ba(){return{pointer:{hot:[6.8,0],parts:[D(5,0,8.6,14,[1.2,1.2,0,0]),D(7.6,5.4,10.9,14,[1.1,1.1,0,0]),D(9.9,6.4,13.2,14,[1.1,1.1,0,0]),D(12.2,7.6,15.2,14,[.9,.9,0,0]),D(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:[D(3,2.6,6.6,12.4,[1.2,1.2,0,0]),D(5.6,.6,9.2,12.4,[1.2,1.2,0,0]),D(8.2,1.4,11.8,12.4,[1.2,1.2,0,0]),D(10.8,3.6,14.2,12.4,[1.1,1.1,0,0]),D(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:[D(3,5.6,6.6,12.4,[1.2,1.2,0,0]),D(5.6,5,9.2,12.4,[1.2,1.2,0,0]),D(8.2,5.2,11.8,12.4,[1.2,1.2,0,0]),D(10.8,6,14.2,12.4,[1.1,1.1,0,0]),D(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:[D(3,7.8,16,11.2),D(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:[D(8,.5,11,18.5),D(4.5,0,14.5,3),D(4.5,16,14.5,19)]},"vertical-text":{hot:[9.5,9.5],parts:Ze([D(8,.5,11,18.5),D(4.5,0,14.5,3),D(4.5,16,14.5,19)],90,9.5,9.5)},crosshair:{hot:[9.5,9.5],parts:[D(0,8,19,11),D(8,0,11,19)]},cell:{hot:[9.5,9.5],parts:[D(1.5,6.3,17.5,12.7),D(6.3,1.5,12.7,17.5)]},"not-allowed":{hot:[9.5,9.5],parts:[...Ua(9.5,9.5,5.4,8.8),ts(4.6,4.6,14.4,14.4,3.4)]},help:{hot:[0,0],parts:[...he(Qe(),.8),us(13.6,12.4,5.4)],detail:[D(11.6,9,15.4,10.2),D(14.4,9,15.6,12.6),D(12.9,11.6,15.6,12.8),D(12.9,11.6,14.1,13.8),D(12.9,14.8,14.1,16)]},wait:{hot:[9.5,9.5],parts:Va()},progress:{hot:[0,0],parts:[...he(Qe(),.8),D(10.6,9,18.8,11.6),D(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(Qe(),.8),D(9.6,9.8,18.8,19,[1.2,1.2,1.2,1.2])],detail:[D(13.6,11.8,14.8,17),D(11.6,13.8,16.8,15)]},alias:{hot:[0,0],parts:[...he(Qe(),.8),D(9.6,9.8,18.8,19,[1.2,1.2,1.2,1.2])],detail:[ts(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(Qe(),.8),D(9.2,8.6,18.8,19)],detail:[D(11,10.8,17,11.8),D(11,13.3,17,14.3),D(11,15.8,17,16.8)]},"ns-resize":{hot:[9.5,9.5],parts:Nt()},"ew-resize":{hot:[9.5,9.5],parts:Ze(Nt(),90,9.5,9.5)},"nesw-resize":{hot:[9.5,9.5],parts:he(Ze(Nt(),45,9.5,9.5),1.2,-1.9,-1.9)},"nwse-resize":{hot:[9.5,9.5],parts:he(Ze(Nt(),-45,9.5,9.5),1.2,-1.9,-1.9)},"col-resize":{hot:[9.5,9.5],parts:ns()},"row-resize":{hot:[9.5,9.5],parts:Ze(ns(),90,9.5,9.5)},"zoom-in":{hot:[7.5,7.5],parts:is(),detail:[D(4.4,6.9,10.6,8.1),D(6.9,4.4,8.1,10.6)]},"zoom-out":{hot:[7.5,7.5],parts:is(),detail:[D(4.4,6.9,10.6,8.1)]}}}function Qn(i){let e=Ce.includes(i)?i:"arrow",t=rs.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=[gs],o=[];else{let c=(Xa||=Ba())[e],h=u=>u.map(d=>d.map(([m,f])=>[(m-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)])}),rs.set(e,t),t}function De(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 ds(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 fs(i,e,t,n,r,s=ri,o=si,a=De(i)){let l=0,c=0,h=0,u=0,d=0,m=n>0?tt:tt.slice(0,1),f=a.detail&&a.detail.length?a.detail:null;for(let[g,x,v]of m){let _=e+g*n,C=t+x*n,M=Yn(qn(a.outline,_,C),r),A=M>0?Yn(qn(a.fill,_,C),r):0;f&&A>0&&(A*=1-Yn(qn(f,_,C),r)),l+=v*(o[0]*M+(s[0]-o[0])*A),c+=v*(o[1]*M+(s[1]-o[1])*A),h+=v*(o[2]*M+(s[2]-o[2])*A),u+=v*M,d+=v}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=De(i)){let c=n>0&&Number.isFinite(n)?n:1,h=1/c,[u,d,m,f]=ds(i,r,h),g=Math.floor(e+u*c),x=Math.floor(t+d*c),v=Math.max(1,Math.ceil(e+m*c)-g),_=Math.max(1,Math.ceil(t+f*c)-x),C=new Uint8ClampedArray(v*_*4),M=s>=0&&s<=1?s:1;for(let A=0;A<_;A++){let k=(x+A+.5-t)/c;for(let O=0;O<v;O++){let L=fs(i,(g+O+.5-e)/c,k,r,h,o,a,l);if(!(L[3]>0))continue;let R=(A*v+O)*4;C[R]=Math.round(L[0]*255),C[R+1]=Math.round(L[1]*255),C[R+2]=Math.round(L[2]*255),C[R+3]=Math.round(L[3]*M*255)}}return{x0:g,y0:x,width:v,height:_,data:C}}function ti(i,e,t,n,r,s=De(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],m)=>(m?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?tt:tt.slice(0,1);for(let u=0;u<a;u++)for(let d=0;d<o;d++){let m=0,f=0,g=0,x=0,v=0;for(let[C,M,A]of h){v+=A;let k=Math.round(d-s+C*n),O=Math.round(u-s+M*n);if(k<0||O<0||k>=e||O>=t)continue;let L=(O*e+k)*4,R=i[L+3]/255*A;m+=i[L]*R,f+=i[L+1]*R,g+=i[L+2]*R,x+=R}if(!(x>1e-5))continue;let _=(u*o+d)*4;l[_]=m/x,l[_+1]=f/x,l[_+2]=g/x,l[_+3]=x/v*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=ss,(i.head||i.documentElement)?.appendChild(t),!0}function ms(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,ss,os,as,Wa,Ft,$a,zt,Zn,Oe,B,Ze,he,Qe,Nt,ns,Va,is,Xa,rs,qn,Yn,ps,Wt,et,ii=fe(()=>{"use strict";oi();Re();X="data-inline3d-cursor-hidden",ss=`[${X}],[${X}] *{cursor:none!important}`,os=128,as=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"}),Wa=Object.freeze(Object.keys(as));Ft=new Map;$a=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"},$a(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?cs(o,t.width):null}).catch(()=>{}).finally(s)),n.src=e,t}},Zn=new zt;Oe=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)=>Oe([i,e,t]),Ze=(i,e,t,n)=>{let r=e*Math.PI/180,s=Math.cos(r),o=Math.sin(r);return i.map(a=>Oe(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])),Qe=()=>[ie.map(([i,e])=>[i*19,e*19])],Nt=()=>[D(8,3,11,16),B([9.5,0],[14.2,5],[4.8,5]),B([9.5,19],[4.8,14],[14.2,14])],ns=()=>[D(8,1,11,18),D(3.4,8,7.4,11),B([0,9.5],[4.4,5],[4.4,14]),D(11.6,8,15.6,11),B([19,9.5],[14.6,14],[14.6,5])],Va=()=>[D(3,0,16,3),D(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])],is=()=>[us(7.5,7.5,7),jt(11.6,11.6,18.4,18.4,3.8,1)];Xa=null,rs=new Map;qn=(i,e,t)=>{let n=1/0;for(let r of i)n=Math.min(n,_s(r,e,t));return n},Yn=(i,e)=>e>0?Math.min(1,Math.max(0,.5-i/e)):i<0?1:0;ps=100;Wt=class{constructor(e,{throttleMs:t=ps}={}){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 ls(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=ms(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))}},et=class{constructor(e,{shape:t="auto",shapeFor:n=null,images:r=Zn}={}){if(!Ee.includes(t))throw new Error(`@displayxr/inline3d: cursor.shape "${t}" \u2014 expected ${Ee.join(", ")}.`);this.option=t,this.shapeFor=typeof n=="function"?n:null,this.images=r,this.reader=t==="auto"?new Wt(e):null,this.sprite=Ae(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:hs(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"||Ce.includes(l);return a(o)?this.sprite=Ae(o):a(this.option)?this.sprite=Ae(this.option):this.sprite=r||Ae("arrow"),this.sprite}dispose(){this.reader?.dispose()}}});function bs(i){return i>0&&Number.isFinite(i)?Math.min(.5,ci/i):Ga}function xs(i,e){return i<=qa?!(e>0&&Number.isFinite(e))||-i*e>=Ya:!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 Ss(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 vs(i){let e=i&&i.pointerType;return!e||e==="mouse"?!0:e==="pen"?!(i.buttons>0):!1}function Ka(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 ys(i){return!!i&&typeof i.setCursorDepth=="function"&&typeof i.getCursorDepthSupport=="function"}function tl(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 Ms(i,e,t,n){return[[i,e],...tl(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 Es(i,e,t,n=Me){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 _s(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],m=Math.min(1,Math.max(0,(u*c+d*h)/(c*c+h*h))),f=u-c*m,g=d-h*m;n=Math.min(n,f*f+g*g);let x=t>=a[1],v=t<l[1],_=c*d>h*u;(x&&v&&_||!x&&!v&&!_)&&(r=-r)}return r*Math.sqrt(n)}var Ga,ci,qa,Ya,Bt,Ut,ai,Za,Qa,el,li,Vt,ws,ie,Pc,gs,ri,si,tt,Lc,Ic,Fc,oi=fe(()=>{"use strict";Re();Re();ii();ii();Ga=.03,ci=19;qa=-.005,Ya=.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=>{vs(r)||(this.uv=null)},this._target=t==="window"?globalThis:e,this.source=Ka(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(!vs(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,Qa=6,el=1e4;li=new WeakMap,Vt=class{constructor(){this.target=null,this._sent=!1,this.last=null}get support(){let e=this.target;if(!ys(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),!ys(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<Qa?Za:el;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:ws(e),v:ws(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}},ws=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]))),Pc=Object.freeze([[0,1,2],[0,2,5],[0,5,6],[2,3,4],[2,4,5]]);gs=Object.freeze($t(1/19).map(i=>Object.freeze(i))),ri=Object.freeze([1,1,1,1]),si=Object.freeze([.02,.02,.03,1]);tt=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])})]),Lc=Object.freeze([Math.max(...ie.map(i=>i[0])),Math.max(...ie.map(i=>i[1]))]);Ic=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
|
-
`}),
|
|
9
|
+
`}),Fc=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 fi={};po(fi,{PAIR_CURSOR_ARROW:()=>Ka,PAIR_CURSOR_CSS_PX:()=>Ya,PAIR_CURSOR_CSS_PX_M:()=>Cs,PAIR_CURSOR_HEIGHT:()=>Es,PAIR_SUPPORT_COPY_PX:()=>ks,PairCursor:()=>di,consistentMatch:()=>ui,drawPairArrow:()=>Ps,drawPairArrowSoft:()=>Is,drawPairImage:()=>Fs,pairCursorScale:()=>As,pairCursorTarget:()=>Za,pairFootprintDisparity:()=>Rs,pairNearestSupported:()=>Ts,pairPxPerBaseline:()=>Os});function Rs(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),m=-Math.round(h*.05),{rL:f,rR:g}=e,x=e.outW/f.sw,v=Ja(i),_=[],C=new Set,S=(T,w)=>{let b=Math.round((f.sy+w*f.sh)*c-u/2);if(b<0||b+u>l)return;let p=Math.round((f.sx+T*f.sw)*c-u/2),y=Math.round((g.sx+T*g.sw)*c-u/2);if(!C.has(`L${p},${b}`)){C.add(`L${p},${b}`);let M=ui(o,v,a,l,p,b,u,m,d);M!==null&&_.push({d:M,x:p,y:b,eye:0})}if(!C.has(`R${y},${b}`)){C.add(`R${y},${b}`);let M=ui(v,o,a,l,y,b,u,-d,-m);M!==null&&_.push({d:-M,x:y,y:b,eye:1})}},A=0,k=0,O=0;for(let[T,w]of bs(t,n,r,s))T>=0&&T<=1&&w>=0&&w<=1&&(S(e.mirror?1-T:T,w),A+=T,k+=w,O++);if(!O)return null;let P=u/2/c/f.sw,R=u/2/c/f.sh;for(let[T,w]of[[-P,0],[P,0],[0,-R],[0,R]]){let b=A/O+T,p=k/O+w;b>=0&&b<=1&&p>=0&&p<=1&&S(e.mirror?1-b:b,p)}for(let T of _)T.d=(T.d/c-(f.sx-g.sx))*x;return Ts(_,ks/c*x,u/2)}function Ja(i){let e=Ms.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 Ms.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=xe(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 m=xe(e,t,n,u,d,o,o,{dMin:-Math.ceil(h.d)-2,dMax:-Math.floor(h.d)+2,dyMax:1});return!m||m.c<.8||Math.abs(-m.d-h.d)>1?null:h.d}function Ts(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 As(i,e,t){let n=t>0&&Number.isFinite(t)?t:Cs;return e>0?i/e/n:i/(1e3*n)}function Os(i,e,t,n=ot.eyeSeparationM){return As(i,e,t)*n}function Za(i,e,t=Bt){return i===null||!Number.isFinite(i)||!(e>0)?0:-hi(t,!0,-i/e)*e||0}function Ds(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=De(i,t))),r}function Ps(i,e,t,n,r,s,o,a="arrow"){let l=r*t,c=Ds(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 Ls(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 Is(i,e,t,n,r,s,o,a,l,c="arrow"){let h=r*t,u=Ds(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)}),m=Ls(Math.max(d[0].width,d[1].width),Math.max(d[0].height,d[1].height));if(!m||typeof m.putImageData!="function"||typeof ImageData!="function")return!1;for(let f of[0,1]){let g=d[f];m.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(m.canvas,0,0,g.width,g.height,g.x0,g.y0,g.width,g.height),i.restore()}return!0}function Fs(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)),m=Ls(u+2*(Math.ceil(l)+2),d+2*(Math.ceil(l)+2));if(!m||typeof m.getImageData!="function"||typeof ImageData!="function")return!1;m.clearRect(0,0,m.canvas.width,m.canvas.height),m.drawImage(a.entry.image,0,0,u,d);let f=ni(m.getImageData(0,0,u,d).data,u,d,l,c);m.clearRect(0,0,m.canvas.width,m.canvas.height),m.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 v=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(m.canvas,0,0,f.width,f.height,Math.round(v),Math.round(g),f.width,f.height),i.restore()}return!0}var Ya,Es,Ka,Cs,ks,Ms,Xt,G,di,pi=fe(()=>{"use strict";oi();an();Ct();Ya=ci,Es=.06,Ka=ie,Cs=.0254/96;ks=1.5,Ms=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 et(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=ot.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=Rs(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=Os(n.outW,h&&h.width,this.metersPerCssPx,this.eyeSeparationM),d=this._content===null?null:-this._content/u,m=hi(Bt,d!==null,d),f=ws(this.filter,Bt,m,r),g=ys(f,u),x=-f*u,v=null,_=null;if(g){let C=c*n.outH,S=globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1,A=h&&h.width>0?h.width*S/n.outW:1,k=h&&h.height>0?c*h.height*S:C,O=xs(f,x*A,k,this.soften),P=this.shapes.pick({u:a,v:l,point:null},r*1e3);_=this.shapes.current,v={blurPx:O.blurPx,alpha:O.alpha,ghostPx:Math.abs(x*A),spritePx:k,radius:k>0?O.blurPx/k:0,soft:O.blurPx>0||O.alpha<1},P.kind==="image"?Fs(e,n.outW,n.outH,a,l,x,C,P,v.soft?v.radius*C:0,v.soft?O.alpha:1):P.kind==="shape"&&(!v.soft||!Is(e,n.outW,n.outH,a,l,x,C,v.radius,O.alpha,_))&&Ps(e,n.outW,n.outH,a,l,x,C,_)}return this.pointer.hideCss(g),this.last={contentPx:this._content,targetPx:-m*u||0,disparityPx:g?x:0,filteredPx:x||0,drawn:g,pxPerBaseline:u,soften:v,shape:_},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?vs(e.height):Es}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 Ne=Object.freeze({speaker:"high",other:"normal",hidden:"paused"}),mo=["high","normal","low","paused"],go=.02,_o=1e3/20,vo=3e3,yo=1e3/28;function We(i){return typeof i=="function"?i:i===!1||i==="off"?"off":"auto"}function tn(i=import.meta.url){return Fe?typeof Fe=="function"?Fe():Fe:new URL("../lift/index.js",i).href}var Fe=null;function Pi(i){Fe=i||null}function wo(){return import(tn())}async function nn(i,{importer:e=wo,nav:t=globalThis.navigator,log:n=null,capsOpts:r={webFallback:!0}}={}){let s=(d,m)=>n&&n(d,m),o=(d,m={})=>(s("lift-unavailable",{reason:d,...m}),{lift:null,capabilities:null,caps:null,source:"none",reason:d}),a=We(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 je(i){let e=Number.isFinite(+i)&&i!==null?Math.max(-1,Math.min(1,+i)):0;return Math.abs(e)<go?"auto":Math.round((.5+.5*e)*1e3)/1e3}function st({id:i,speakerId:e,visible:t=!0}){return t?i!=null&&i===e?Ne.speaker:Ne.other:Ne.hidden}function rn(i,e){if(!i||!mo.includes(e)||typeof i.setPriority!="function")return!1;try{return i.setPriority(e)!==!1}catch{return!1}}function sn({degradedMs:i=_o,recoveredMs:e=yo,holdMs:t=vo,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,m)=>t&&t(d,m),h=(d,m)=>{if(!m.handle)return;let f=st({id:d,speakerId:o,visible:m.visible});if(f===m.priority)return;m.priority=f;let g=rn(m.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,m,{wall:f,visible:g=!0,onError:x}={}){let v=s.get(d);if(v)return v.pending||Promise.resolve(v.handle);if(s.size>=e)return Promise.resolve(null);let _=++l,C=st({id:d,speakerId:o,visible:g}),S={gen:_,handle:null,visible:g,priority:C,pending:null};s.set(d,S);let A={quality:"auto",...r,mode:"live",wall:f,ui:"none",convergence:je(a),priority:C};return c("lift-acquire",{peer:d,priority:C,convergence:A.convergence}),S.pending=Promise.resolve().then(()=>i(m,A)).then(k=>{if(s.get(d)!==S||S.gen!==_){try{k&&k.remove&&k.remove()}catch{}return null}return S.pending=null,S.handle=k||null,S.priority=null,h(d,S),k&&typeof k.setConvergence=="function"&&k.setConvergence(je(a)),S.handle},k=>(s.get(d)===S&&s.delete(d),c("lift-failed",{peer:d,message:String(k&&k.message||k).slice(0,200)}),x&&x(k),null)),S.pending},release(d){let m=s.get(d);if(m){if(s.delete(d),m.handle)try{m.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[m,f]of s)h(m,f)},setVisible(d,m){let f=s.get(d);!f||f.visible===!!m||(f.visible=!!m,h(d,f))},setDepth(d){a=d;let m=je(d);for(let f of s.values())f.handle&&typeof f.handle.setConvergence=="function"&&f.handle.setConvergence(m);return m},get anyWeb(){for(let d of s.values())if(d.handle&&!d.handle.native)return!0;return!1},list(){return[...s].map(([d,m])=>({id:d,priority:m.priority,pending:!!m.pending,native:!!(m.handle&&m.handle.native)}))}};return u}var xo=null;function Li(i){xo=typeof i=="function"?i:null}var So=new WeakMap;function Ii(i,e){i&&(typeof i=="object"||typeof i=="function")&&So.set(i,e)}an();var Fl=Object.freeze(["shibata","percival"]);var Mo="[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.",Eo=new WeakSet;function Co(i){let e=[];return!i||typeof i!="object"||(i.type==="camera"?(i.convergenceDiopters>0||e.push(["convergence",Mo]),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 Co(e))i.has(t)||(i.add(t),!(t==="convergence"&&Eo.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 Wi(i){let e=null;for(let[t,n]of i)n>0&&(!e||n<e[1])&&(e=[t,n]);return e}function Ro(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=Wi([["MAX_TEXTURE_SIZE",t],["MAX_RENDERBUFFER_SIZE",n],["MAX_VIEWPORT_DIMS",s]]),l=Wi([["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 zi(){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=Ro(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))),m=Math.max(1,Math.min(Math.floor(e*h+1e-9),Math.floor(t.maxH/r)));return{eyeW:d,eyeH:m,cols:n,scale:h,clamped:!0,reqW:s,reqH:o,bufW:d*n,bufH:m*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 ko(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",at=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)*ko(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 To=()=>typeof navigator<"u"&&!!navigator.xr,le=()=>typeof window<"u"&&typeof window.XRDisplayLayer=="function",lt=()=>le()&&"excludeElement"in window.XRDisplayLayer.prototype,fn=()=>{if(!le())return!1;try{return"setViewRig"in window.XRDisplayLayer.prototype}catch{return!1}},Ao=["getDisplayInfo","getRenderingModes","requestRenderingMode"],nr=["renderingmodechange","hardwaredisplaystatechange"],xn="trackingstatechange",ir=["unknown","tracking","searching"],Gi=[...nr,xn];function ct(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 Ao.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 Oo(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 To()&&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 Do(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 Po=16;function $(){return typeof performance<"u"&&performance&&typeof performance.now=="function"?performance.now():Date.now()}var Sn=1200,Lo=new Set(["pending","woven","withheld"]),Yi=3,Io=new Set(["getDisplayInfo","getRenderingModes","requestRenderingMode"]),Fo=new Set(["getDisplayInfo","getRenderingModes"]);function No(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 ht(i){try{let e=i?i.wovenState:null;return Lo.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 jo(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 Wo(){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 Ho(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 $o(){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 Uo(){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 dt(i={}){return J&&J._running?Promise.resolve(J):ze||(ze=or(i).finally(()=>{ze=null}),ze)}var er=.7,Vo=new Set(["IMG","SVG","VIDEO","CANVAS","BUTTON","INPUT","SELECT","TEXTAREA"]);function Bo(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(Vo.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 Xo(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 at((Number.isFinite(l.durationMs)?Math.max(0,l.durationMs):180)/1e3,jo(l.easing)),this._stereoFactor=1,this._msFire=null,this._msArmedUp=!1,this._msLastMs=null,this._msTick=null,this._trackingSupported=ct(e)!==null,this._trackingState=this._trackingSupported?ct(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||!lt()||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 Bo(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=Yo(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&&Uo();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?ht(t.layer):"pending":null},get withheldReason(){return!vn()||!t.layer?null:ht(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),Do(e.viewRig||_n(e),this._stereoFactor))}_setStereoCollapsed(e){let t=!!e;if(this._stereoCollapsed!==t){this._stereoCollapsed=t,t&&Wo(),!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 $o(),!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(Io.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(!Fo.has(t)||!this._layerReadPending(e))return o;let a=e.layer;return o.then(l=>e.layer!==a?l:No(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:$()-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)-($()-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?ht(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=$(),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=$(),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=$(),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())},Po))}_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=Ho(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:Go(n.firstWovenHoldMs),fwRegAt:$(),fwLayerAt:null,fwStereo:!1,rw:null,rwGone:null,wsLive:!1,rc:null,layerFramed:!1,lfAnswered:!1,lfStereo:!1,lfAt:0,lfCapped:!1,framedWaiters:[]},s=Xo(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=$(),e.fwStereo=!1),e.wsLive=vn(),e.layerFramed=!1,e.lfAnswered=!1,e.lfStereo=!1,e.lfCapped=!1,e.lfAt=$(),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(()=>{})),Oo(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||!lt()||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||!lt()))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()||!lt()||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,zi(),{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){ut(o,r,0,0,a/2,l,0,0,s.width,s.height,u,d);return}let m=s.width/2,f=Math.min(this._stereoFactor,this._bakedStereo);if(f<1){ut(o,r,0,0,a/2,l,0,0,m,s.height,u,d),Ko(o,r,a/2,l,m,s.height,f,u,d);return}u>0||d>0?(ut(o,r,0,0,a/2,l,0,0,m,s.height,u,d),ut(o,r,a/2,0,a/2,l,m,0,m,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(ct(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(ct(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:qo(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?ht(e.layer):null;if(t){this._tickWovenState(e,t);return}if(e.rw){this._noteRewovenBox(e);let n=e.rw,r=$();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||$()-e.fwLayerAt<e.fwHoldMs||this._settleFirstWoven(e,!0,"hold-elapsed")}_tickWovenState(e,t){let n=$(),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($()-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=$();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=$(),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($()-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,m=(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,m,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 Go(i){return typeof i=="number"&&Number.isFinite(i)&&i>=0?i:Sn}function qo(i){if(!i)return!1;let e=i.naturalWidth??i.videoWidth??i.width,t=i.naturalHeight??i.videoHeight??i.height;return e===void 0&&t===void 0?!0:e>0&&t>0}function Yo(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 ut(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 Ko(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,m]of a){let f=i.createLinearGradient(d[0],d[1],m[0],m[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 He(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 ft({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 pt(i,e,t=.2){let n=Math.max(0,e*t);return Math.max(-n,Math.min(n,i||0))}function mt(i,e,t=.2){let n=i+t*(e-i);return Math.abs(e-n)<.05?e:n}function $e(){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?ft({eyeWidthPx:e,hfovDeg:i.hello.hfovDeg,baselineMm:i.hello.baselineMm,subjectZmm:i.subjectZmm}):0;return pt(t+i.depth*.05*e,e)},step(e){return i.current=mt(i.current,i.target(e)),i.current}};return i}var gt=1,kn="inline3d-call/1",_t=Object.freeze(["sbs","mono"]),ye=4,hr=4,Tn=5,ur=5,dr=10,fr=400,pr=1200,ee=.5,Jo=16*1024,mr=20,gr=40,cr=64,Zo=150,Qo=5e3,ea=/^[A-Za-z0-9_-]{16,64}$/,ta=16;function An(i){let e=new Uint8Array(ta);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"&&ea.test(i)}function Ue(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 vt(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:gt,format:_t.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:gt,format:_t.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 yt({on:i=!0,format:e,width:t,height:n,convergence:r,appName:s}={}){if(!i)return{type:"content",on:!1};let o=_t.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:_t.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=na(e);return t>Jo?null:{json:e,bytes:t}}function br(i){return!i||typeof i!="object"||i.type!=="app"||!("d"in i)?null:{data:i.d}}function na(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>=Zo&&e<=Qo?{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 Ve(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 Be(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 Xe=Object.freeze(["VP9","VP8","AV1"]);function ra(i,e=Xe){let t=e.indexOf(String(i||"").toUpperCase());return t<0?e.length:t}function wt(i,e=Xe){let t=n=>ra(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 Ge(i,e=Xe){if(!i)return i;let t=i.includes(`\r
|
|
16
|
+
`})});var fi={};_o(fi,{PAIR_CURSOR_ARROW:()=>il,PAIR_CURSOR_CSS_PX:()=>nl,PAIR_CURSOR_CSS_PX_M:()=>Ts,PAIR_CURSOR_HEIGHT:()=>ks,PAIR_SUPPORT_COPY_PX:()=>Os,PairCursor:()=>di,consistentMatch:()=>ui,drawPairArrow:()=>Fs,drawPairArrowSoft:()=>js,drawPairImage:()=>zs,pairCursorScale:()=>Ps,pairCursorTarget:()=>sl,pairFootprintDisparity:()=>As,pairNearestSupported:()=>Ds,pairPxPerBaseline:()=>Ls});function As(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),m=-Math.round(h*.05),{rL:f,rR:g}=e,x=e.outW/f.sw,v=rl(i),_=[],C=new Set,M=(T,w)=>{let S=Math.round((f.sy+w*f.sh)*c-u/2);if(S<0||S+u>l)return;let p=Math.round((f.sx+T*f.sw)*c-u/2),y=Math.round((g.sx+T*g.sw)*c-u/2);if(!C.has(`L${p},${S}`)){C.add(`L${p},${S}`);let b=ui(o,v,a,l,p,S,u,m,d);b!==null&&_.push({d:b,x:p,y:S,eye:0})}if(!C.has(`R${y},${S}`)){C.add(`R${y},${S}`);let b=ui(v,o,a,l,y,S,u,-d,-m);b!==null&&_.push({d:-b,x:y,y:S,eye:1})}},A=0,k=0,O=0;for(let[T,w]of Ms(t,n,r,s))T>=0&&T<=1&&w>=0&&w<=1&&(M(e.mirror?1-T:T,w),A+=T,k+=w,O++);if(!O)return null;let L=u/2/c/f.sw,R=u/2/c/f.sh;for(let[T,w]of[[-L,0],[L,0],[0,-R],[0,R]]){let S=A/O+T,p=k/O+w;S>=0&&S<=1&&p>=0&&p<=1&&M(e.mirror?1-S:S,p)}for(let T of _)T.d=(T.d/c-(f.sx-g.sx))*x;return Ds(_,Os/c*x,u/2)}function rl(i){let e=Rs.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 Rs.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=xe(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 m=xe(e,t,n,u,d,o,o,{dMin:-Math.ceil(h.d)-2,dMax:-Math.floor(h.d)+2,dyMax:1});return!m||m.c<.8||Math.abs(-m.d-h.d)>1?null:h.d}function Ds(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 Ps(i,e,t){let n=t>0&&Number.isFinite(t)?t:Ts;return e>0?i/e/n:i/(1e3*n)}function Ls(i,e,t,n=ot.eyeSeparationM){return Ps(i,e,t)*n}function sl(i,e,t=Bt){return i===null||!Number.isFinite(i)||!(e>0)?0:-hi(t,!0,-i/e)*e||0}function Is(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=De(i,t))),r}function Fs(i,e,t,n,r,s,o,a="arrow"){let l=r*t,c=Is(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 Ns(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 js(i,e,t,n,r,s,o,a,l,c="arrow"){let h=r*t,u=Is(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)}),m=Ns(Math.max(d[0].width,d[1].width),Math.max(d[0].height,d[1].height));if(!m||typeof m.putImageData!="function"||typeof ImageData!="function")return!1;for(let f of[0,1]){let g=d[f];m.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(m.canvas,0,0,g.width,g.height,g.x0,g.y0,g.width,g.height),i.restore()}return!0}function zs(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)),m=Ns(u+2*(Math.ceil(l)+2),d+2*(Math.ceil(l)+2));if(!m||typeof m.getImageData!="function"||typeof ImageData!="function")return!1;m.clearRect(0,0,m.canvas.width,m.canvas.height),m.drawImage(a.entry.image,0,0,u,d);let f=ni(m.getImageData(0,0,u,d).data,u,d,l,c);m.clearRect(0,0,m.canvas.width,m.canvas.height),m.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 v=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(m.canvas,0,0,f.width,f.height,Math.round(v),Math.round(g),f.width,f.height),i.restore()}return!0}var nl,ks,il,Ts,Os,Rs,Xt,G,di,pi=fe(()=>{"use strict";oi();an();Ct();nl=ci,ks=.06,il=ie,Ts=.0254/96;Os=1.5,Rs=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 et(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=ot.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=As(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=Ls(n.outW,h&&h.width,this.metersPerCssPx,this.eyeSeparationM),d=this._content===null?null:-this._content/u,m=hi(Bt,d!==null,d),f=Ss(this.filter,Bt,m,r),g=xs(f,u),x=-f*u,v=null,_=null;if(g){let C=c*n.outH,M=globalThis.devicePixelRatio>0?globalThis.devicePixelRatio:1,A=h&&h.width>0?h.width*M/n.outW:1,k=h&&h.height>0?c*h.height*M:C,O=Es(f,x*A,k,this.soften),L=this.shapes.pick({u:a,v:l,point:null},r*1e3);_=this.shapes.current,v={blurPx:O.blurPx,alpha:O.alpha,ghostPx:Math.abs(x*A),spritePx:k,radius:k>0?O.blurPx/k:0,soft:O.blurPx>0||O.alpha<1},L.kind==="image"?zs(e,n.outW,n.outH,a,l,x,C,L,v.soft?v.radius*C:0,v.soft?O.alpha:1):L.kind==="shape"&&(!v.soft||!js(e,n.outW,n.outH,a,l,x,C,v.radius,O.alpha,_))&&Fs(e,n.outW,n.outH,a,l,x,C,_)}return this.pointer.hideCss(g),this.last={contentPx:this._content,targetPx:-m*u||0,disparityPx:g?x:0,filteredPx:x||0,drawn:g,pxPerBaseline:u,soften:v,shape:_},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?bs(e.height):ks}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 Ne=Object.freeze({speaker:"high",other:"normal",hidden:"paused"}),vo=["high","normal","low","paused"],yo=.02,wo=1e3/20,bo=3e3,xo=1e3/28;function ze(i){return typeof i=="function"?i:i===!1||i==="off"?"off":"auto"}function tn(i=import.meta.url){return Fe?typeof Fe=="function"?Fe():Fe:new URL("../lift/index.js",i).href}var Fe=null;function Pi(i){Fe=i||null}function So(){return import(tn())}async function nn(i,{importer:e=So,nav:t=globalThis.navigator,log:n=null,capsOpts:r={webFallback:!0}}={}){let s=(d,m)=>n&&n(d,m),o=(d,m={})=>(s("lift-unavailable",{reason:d,...m}),{lift:null,capabilities:null,caps:null,source:"none",reason:d}),a=ze(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 je(i){let e=Number.isFinite(+i)&&i!==null?Math.max(-1,Math.min(1,+i)):0;return Math.abs(e)<yo?"auto":Math.round((.5+.5*e)*1e3)/1e3}function st({id:i,speakerId:e,visible:t=!0}){return t?i!=null&&i===e?Ne.speaker:Ne.other:Ne.hidden}function rn(i,e){if(!i||!vo.includes(e)||typeof i.setPriority!="function")return!1;try{return i.setPriority(e)!==!1}catch{return!1}}function sn({degradedMs:i=wo,recoveredMs:e=xo,holdMs:t=bo,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,m)=>t&&t(d,m),h=(d,m)=>{if(!m.handle)return;let f=st({id:d,speakerId:o,visible:m.visible});if(f===m.priority)return;m.priority=f;let g=rn(m.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,m,{wall:f,visible:g=!0,onError:x}={}){let v=s.get(d);if(v)return v.pending||Promise.resolve(v.handle);if(s.size>=e)return Promise.resolve(null);let _=++l,C=st({id:d,speakerId:o,visible:g}),M={gen:_,handle:null,visible:g,priority:C,pending:null};s.set(d,M);let A={quality:"auto",...r,mode:"live",wall:f,ui:"none",convergence:je(a),priority:C};return c("lift-acquire",{peer:d,priority:C,convergence:A.convergence}),M.pending=Promise.resolve().then(()=>i(m,A)).then(k=>{if(s.get(d)!==M||M.gen!==_){try{k&&k.remove&&k.remove()}catch{}return null}return M.pending=null,M.handle=k||null,M.priority=null,h(d,M),k&&typeof k.setConvergence=="function"&&k.setConvergence(je(a)),M.handle},k=>(s.get(d)===M&&s.delete(d),c("lift-failed",{peer:d,message:String(k&&k.message||k).slice(0,200)}),x&&x(k),null)),M.pending},release(d){let m=s.get(d);if(m){if(s.delete(d),m.handle)try{m.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[m,f]of s)h(m,f)},setVisible(d,m){let f=s.get(d);!f||f.visible===!!m||(f.visible=!!m,h(d,f))},setDepth(d){a=d;let m=je(d);for(let f of s.values())f.handle&&typeof f.handle.setConvergence=="function"&&f.handle.setConvergence(m);return m},get anyWeb(){for(let d of s.values())if(d.handle&&!d.handle.native)return!0;return!1},list(){return[...s].map(([d,m])=>({id:d,priority:m.priority,pending:!!m.pending,native:!!(m.handle&&m.handle.native)}))}};return u}var Eo=null;function Li(i){Eo=typeof i=="function"?i:null}var Co=new WeakMap;function Ii(i,e){i&&(typeof i=="object"||typeof i=="function")&&Co.set(i,e)}an();var Ul=Object.freeze(["shibata","percival"]);var Ro="[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.",ko=new WeakSet;function To(i){let e=[];return!i||typeof i!="object"||(i.type==="camera"?(i.convergenceDiopters>0||e.push(["convergence",Ro]),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 To(e))i.has(t)||(i.add(t),!(t==="convergence"&&ko.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 Ao(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=Ao(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))),m=Math.max(1,Math.min(Math.floor(e*h+1e-9),Math.floor(t.maxH/r)));return{eyeW:d,eyeH:m,cols:n,scale:h,clamped:!0,reqW:s,reqH:o,bufW:d*n,bufH:m*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 Oo(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",at=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)*Oo(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 Do=()=>typeof navigator<"u"&&!!navigator.xr,le=()=>typeof window<"u"&&typeof window.XRDisplayLayer=="function",lt=()=>le()&&"excludeElement"in window.XRDisplayLayer.prototype,fn=()=>{if(!le())return!1;try{return"setViewRig"in window.XRDisplayLayer.prototype}catch{return!1}},Po=["getDisplayInfo","getRenderingModes","requestRenderingMode"],nr=["renderingmodechange","hardwaredisplaystatechange"],xn="trackingstatechange",ir=["unknown","tracking","searching"],Gi=[...nr,xn];function ct(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 Po.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 Lo(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 Do()&&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 Io(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 Fo=16;function $(){return typeof performance<"u"&&performance&&typeof performance.now=="function"?performance.now():Date.now()}var Sn=1200,No=new Set(["pending","woven","withheld"]),Yi=3,jo=new Set(["getDisplayInfo","getRenderingModes","requestRenderingMode"]),zo=new Set(["getDisplayInfo","getRenderingModes"]);function Wo(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 ht(i){try{let e=i?i.wovenState:null;return No.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 Ho(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 $o(){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 Uo(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 Vo(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 Bo(){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 Xo(){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 We=null;function dt(i={}){return J&&J._running?Promise.resolve(J):We||(We=or(i).finally(()=>{We=null}),We)}var er=.7,Go=new Set(["IMG","SVG","VIDEO","CANVAS","BUTTON","INPUT","SELECT","TEXTAREA"]);function qo(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(Go.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 Yo(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 at((Number.isFinite(l.durationMs)?Math.max(0,l.durationMs):180)/1e3,Ho(l.easing)),this._stereoFactor=1,this._msFire=null,this._msArmedUp=!1,this._msLastMs=null,this._msTick=null,this._trackingSupported=ct(e)!==null,this._trackingState=this._trackingSupported?ct(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||!lt()||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 qo(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=Zo(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&&Xo();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?ht(t.layer):"pending":null},get withheldReason(){return!vn()||!t.layer?null:ht(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),Io(e.viewRig||_n(e),this._stereoFactor))}_setStereoCollapsed(e){let t=!!e;if(this._stereoCollapsed!==t){this._stereoCollapsed=t,t&&$o(),!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 Bo(),!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(jo.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(!zo.has(t)||!this._layerReadPending(e))return o;let a=e.layer;return o.then(l=>e.layer!==a?l:Wo(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:$()-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)-($()-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?ht(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=$(),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=$(),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=$(),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())},Fo))}_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=Vo(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=Uo(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:Ko(n.firstWovenHoldMs),fwRegAt:$(),fwLayerAt:null,fwStereo:!1,rw:null,rwGone:null,wsLive:!1,rc:null,layerFramed:!1,lfAnswered:!1,lfStereo:!1,lfAt:0,lfCapped:!1,framedWaiters:[]},s=Yo(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=$(),e.fwStereo=!1),e.wsLive=vn(),e.layerFramed=!1,e.lfAnswered=!1,e.lfStereo=!1,e.lfCapped=!1,e.lfAt=$(),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(()=>{})),Lo(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||!lt()||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||!lt()))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()||!lt()||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){ut(o,r,0,0,a/2,l,0,0,s.width,s.height,u,d);return}let m=s.width/2,f=Math.min(this._stereoFactor,this._bakedStereo);if(f<1){ut(o,r,0,0,a/2,l,0,0,m,s.height,u,d),Qo(o,r,a/2,l,m,s.height,f,u,d);return}u>0||d>0?(ut(o,r,0,0,a/2,l,0,0,m,s.height,u,d),ut(o,r,a/2,0,a/2,l,m,0,m,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(ct(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(ct(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:Jo(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?ht(e.layer):null;if(t){this._tickWovenState(e,t);return}if(e.rw){this._noteRewovenBox(e);let n=e.rw,r=$();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||$()-e.fwLayerAt<e.fwHoldMs||this._settleFirstWoven(e,!0,"hold-elapsed")}_tickWovenState(e,t){let n=$(),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($()-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=$();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=$(),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($()-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,m=(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,m,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 Ko(i){return typeof i=="number"&&Number.isFinite(i)&&i>=0?i:Sn}function Jo(i){if(!i)return!1;let e=i.naturalWidth??i.videoWidth??i.width,t=i.naturalHeight??i.videoHeight??i.height;return e===void 0&&t===void 0?!0:e>0&&t>0}function Zo(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 ut(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,m]of a){let f=i.createLinearGradient(d[0],d[1],m[0],m[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 He(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 ft({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 pt(i,e,t=.2){let n=Math.max(0,e*t);return Math.max(-n,Math.min(n,i||0))}function mt(i,e,t=.2){let n=i+t*(e-i);return Math.abs(e-n)<.05?e:n}function $e(){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?ft({eyeWidthPx:e,hfovDeg:i.hello.hfovDeg,baselineMm:i.hello.baselineMm,subjectZmm:i.subjectZmm}):0;return pt(t+i.depth*.05*e,e)},step(e){return i.current=mt(i.current,i.target(e)),i.current}};return i}var gt=1,kn="inline3d-call/1",_t=Object.freeze(["sbs","mono"]),ye=4,hr=4,Tn=5,ur=5,dr=10,fr=400,pr=1200,ee=.5,ea=16*1024,mr=20,gr=40,cr=64,ta=150,na=5e3,ia=/^[A-Za-z0-9_-]{16,64}$/,ra=16;function An(i){let e=new Uint8Array(ra);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"&&ia.test(i)}function Ue(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 vt(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:gt,format:_t.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:gt,format:_t.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 yt({on:i=!0,format:e,width:t,height:n,convergence:r,appName:s}={}){if(!i)return{type:"content",on:!1};let o=_t.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:_t.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=sa(e);return t>ea?null:{json:e,bytes:t}}function br(i){return!i||typeof i!="object"||i.type!=="app"||!("d"in i)?null:{data:i.d}}function sa(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>=ta&&e<=na?{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 Ve(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 Be(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 Xe=Object.freeze(["VP9","VP8","AV1"]);function aa(i,e=Xe){let t=e.indexOf(String(i||"").toUpperCase());return t<0?e.length:t}function wt(i,e=Xe){let t=n=>aa(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 Ge(i,e=Xe){if(!i)return i;let t=i.includes(`\r
|
|
17
17
|
`)?`\r
|
|
18
18
|
`:`
|
|
19
|
-
`,n=i.split(t),r=n.findIndex(m=>m.startsWith("m=video"));if(r<0)return i;let s=n.findIndex((m,f)=>f>r&&m.startsWith("m="));s<0&&(s=n.length);let o=n.slice(r,s),a=new Map,l=new Map;for(let m of o){let f=m.match(/^a=rtpmap:(\d+) ([\w-]+)\//);f&&a.set(f[1],f[2].toUpperCase());let g=m.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 m of e)for(let f of h)if(a.get(f)===m&&!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(m=>!u.includes(m));return n[r]=[...c.slice(0,3),...u,...d].join(" "),n.join(t)}var Cr=Object.freeze([{urls:"stun:stun.l.google.com:19302"}]),oa=4e3,aa=1e4,la=2e4,ca=8e3,ha=1e4,ua=.6;function Ye(i){let e=Number.isInteger(i)?i:ye;return Math.max(2,Math.min(hr,e))}function Rr(i,e){return i<e}var qe=class{constructor({signaling:e,id:t,maxPeers:n,iceServers:r,RTCPeerConnection:s,log:o,unreachableMs:a}={}){this.unreachableMs=a>0?a:ha,this.signaling=e,this.id=t,this.maxPeers=Ye(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:m,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:m,onGhost:f};let g=_=>(...C)=>this.ready?_(...C):this._pending.push(()=>_(...C));this.session=await this.signaling.join(e,{id:this.id,maxPeers:this.maxPeers,onPeerJoined:g(_=>this._onPeerJoined(_)),onPeerLeft:g(_=>this._onPeerLeftSignaling(_)),onSignal:g((_,C)=>this._onSignal(_,C)),onDisconnect:_=>m?.(_?"closed":"reconnecting",_),onPeerUnreachable:g(_=>f?.(_,!0)),onPeerReachable:g(_=>f?.(_,!1)),onReconnect:g(_=>{m?.("connected");for(let C of _)this._onPeerJoined(C)})}),!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 _=new Error(`@displayxr/inline3d/call: this call is full (${this.maxPeers} participants)`);throw _.code="room-full",_}this.ready=!0;for(let _ of x)this._onPeerJoined(_);let v=this._pending;this._pending=[];for(let _ of v)_();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),ca)}_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,la,()=>{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=Ge(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=Ge(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(wt(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,oa,()=>{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,aa,()=>{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(Be(this.sendFormat,e)*(t?ua:1)),r=Be("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 bt="dxr-app:",xt=/^DisplayXR: (.+) \(3D\)$/,kr=/^3D Camera \(DisplayXR\)\s+-\s+(.+)$/;function St(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"?xt.exec(i.trim()):null;return e&&e[1].trim()||null}function ne(i){if(!i)return!1;if(typeof i=="string")return xt.test(i.trim())||i.startsWith(bt);if(typeof i!="object")return!1;let e=i;try{if(typeof e.label=="string"&&xt.test(e.label.trim())||typeof e.deviceId=="string"&&e.deviceId.startsWith(bt))return!0;let t=e.displayxrStereo||(typeof e.getSettings=="function"?(e.getSettings()||{}).displayxrStereo:null);if(St(t))return!0;if(typeof e.getSettings=="function"){let n=(e.getSettings()||{}).deviceId;if(typeof n=="string"&&n.startsWith(bt))return!0}}catch{}return!1}var Ke={width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},Wn={width:{ideal:3840},height:{ideal:1080},frameRate:{ideal:30}},da=Object.freeze({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),fa=2500,pa=500;function ma(){return Or()?fa:0}function Or(){return typeof navigator<"u"&&!!navigator.xr&&typeof window<"u"&&typeof window.XRDisplayLayer=="function"}function ga(i,e){return new Promise(t=>{let n=0,r=()=>{clearTimeout(n);try{i.removeEventListener?.("devicechange",r)}catch{}t()};n=setTimeout(r,e);try{i.addEventListener?.("devicechange",r)}catch{}})}function _a(i){return!!i&&(i.name==="NotReadableError"||i.name==="TrackStartError"||/in use|busy/i.test(i.message||""))}function va(i){return!!i&&(i.name==="NotAllowedError"||i.name==="PermissionDeniedError"||i.name==="SecurityError")}function zn(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 ya=/\b(hand[- ]?track|tracking camera|eye[- ]?track|depth camera|ultraleap|leap motion|infrared|ir camera)/i;function wa(i){let e=(n,r)=>ne({label:String(n||""),deviceId:typeof r=="string"?r:""});if(i===!1)return e;let t=[ya];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 be(i){return ne(String(i||""))?!1:/stereo|\b3d\b|\bsbs\b|dual/i.test(i||"")}async function Dr(i="auto",e={}){let t=e.mediaDevices||globalThis.navigator&&navigator.mediaDevices,n=e.log||(()=>{}),r=[],s=e.calibration||{},o=wa(e.exclude);if(i&&typeof i=="object"&&typeof i.getVideoTracks=="function"){let p=i.getVideoTracks()[0],y=p?p.getSettings():{},M=e.format==="sbs"?"sbs":"mono";return{stream:i,format:M,width:y.width||0,height:y.height||0,deviceId:y.deviceId||null,label:p?p.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 p=>{let y=await t.getUserMedia({video:p,audio:!1}),M=y.getVideoTracks()[0],E=M?M.getSettings():{};if(!M||M.readyState==="ended"||!(E.width>0)||!(E.height>0))throw y.getTracks().forEach(I=>I.stop()),Object.assign(new Error("the camera opened but delivers no picture (0x0)"),{name:"NotReadableError"});let N=E.displayxrStereo&&E.displayxrStereo.layout==="side-by-side"?E.displayxrStereo:null,W=ne({label:M.label||"",deviceId:E.deviceId||""})||St(E.displayxrStereo);return{stream:y,track:M,width:E.width,height:E.height,deviceId:E.deviceId||null,label:M.label||"",stereo:N,appShare:W}},l=(p,y)=>{r.push({label:p,error:`${y.name}: ${y.message}`,busy:_a(y),denied:va(y)}),n("camera-skip",{label:p,error:y.name})},c=p=>p&&p.stream.getTracks().forEach(y=>y.stop()),h=async()=>{try{return(await t.enumerateDevices()).filter(p=>p.kind==="videoinput")}catch{return[]}},u=new Set,d=(p,y,M="excluded")=>{y&&u.has(y)||(y&&u.add(y),r.push({label:p,error:"excluded",excluded:!0,reason:M}),n("camera-skip",{label:p,error:"excluded",reason:M}))},m=p=>ne({label:p.label||"",deviceId:p.deviceId||""}),f=p=>m(p)?(d(p.label||"",p.deviceId,"app-share"),!0):!p.label||!o(p.label,p.deviceId)?!1:(d(p.label,p.deviceId),!0),g=p=>p.appShare?(c(p),d(p.label,p.deviceId,"app-share"),!0):o(p.label,p.deviceId)?(c(p),d(p.label,p.deviceId),!0):!1,x=!1,v=async p=>{let y=await a(p);return g(y)?(x=!0,null):y},_=async(p,y)=>{try{await p.track.applyConstraints(y);let M=p.track.getSettings();if(M.width>0&&M.height>0)return{...p,width:M.width,height:M.height}}catch{}return p},C=p=>!!p&&(!!p.stereo||Cn(p.width,p.height)),S=(p,y)=>({stream:p.stream,format:y,width:p.width,height:p.height,deviceId:p.deviceId,label:p.label,owned:!0,skipped:r,calibration:{rectified:!1,...y==="sbs"&&p.stereo?{rectified:!!p.stereo.rectified,...p.stereo.baselineMm>0?{baselineMm:p.stereo.baselineMm}:{},...p.stereo.horizontalFovDeg>0?{hfovDeg:p.stereo.horizontalFovDeg}:{}}:{},...s}});if(typeof i=="string"&&i.startsWith("label:")){let p=i.slice(6).trim().toLowerCase(),y=await h();if(p&&y.length&&y.every(E=>!E.label)){try{c(await a(!0))}catch(E){l("default",E)}y=await h()}let M=p?y.find(E=>E.deviceId&&!m(E)&&(E.label||"").toLowerCase().includes(p)):null;if(!M)throw Object.assign(new Error(`camera unavailable: no camera labelled "${p}"`),{code:zn(r),skipped:r});n("camera-label",{label:M.label,needle:p}),i=M.deviceId}if(typeof i=="string"&&!["auto","stereo","mono"].includes(i)){let p;try{p=await a({deviceId:{exact:i},...Wn})}catch(y){throw l(i,y),Object.assign(new Error(`camera unavailable: ${y.message}`),{code:zn(r),skipped:r})}return C(p)?S(p,"sbs"):(c(p),S(await a({deviceId:{exact:i},...Ke}),"mono"))}let A=new Set,k=async p=>{for(let y of p){if(!y.deviceId||!be(y.label)||A.has(y.deviceId)||(A.add(y.deviceId),f(y)))continue;let M=null;try{M=await a({deviceId:{exact:y.deviceId},...Wn})}catch(E){l(y.label,E);continue}if(!g(M)){if(C(M))return n("camera-sbs",{label:M.label,width:M.width,height:M.height,direct:!0}),M;c(M)}}return null},O=Number.isFinite(e.stereoWaitMs)?Math.max(0,e.stereoWaitMs):ma(),P=async p=>{if(!(p>0))return k(await h());let y=Date.now()+p;for(n("camera-wait-stereo",{ms:p});;){let M=y-Date.now();if(M<=0)break;await ga(t,Math.min(pa,M));let E=await h(),N=await k(E);if(N)return N;if(E.some(W=>be(W.label)&&!m(W)))break}return n("camera-no-stereo-listed",{ms:p}),null},R=null;if(i!=="mono"){let p=await h(),y=await k(p);if(y||p.some(M=>M.label)&&!p.some(M=>be(M.label))&&(y=await P(O),y))return S(y,"sbs");if(p.length&&p.every(M=>!M.label)){let M=null;try{M=await v(!0)}catch(N){l("default",N)}if(M&&M.stereo)return S(M,"sbs");M&&M.deviceId&&A.add(M.deviceId);let E=await k(await h());if(E)return c(M),S(E,"sbs");if(M&&C(M))return S(M,"sbs");M&&(R=await _(M,Ke))}}if(!R&&!x){let p=await h(),M=p.filter(f).length>0&&p.find(E=>E.deviceId&&!u.has(E.deviceId))||null;if(M){M.deviceId&&A.add(M.deviceId);try{R=await a({deviceId:{exact:M.deviceId},...Ke}),g(R)&&(R=null)}catch(E){l(M.label,E)}}else try{R=await v(Ke)}catch(E){l("default",E)}}if(i==="mono"&&R)return S(R,"mono");if(R&&C(R))return S(R,"sbs");let T=[];try{T=(await t.enumerateDevices()).filter(p=>p.kind==="videoinput")}catch{}T.sort((p,y)=>Number(be(y.label))-Number(be(p.label)));let w=!Or();for(let p of T){if(!p.deviceId||R&&p.deviceId===R.deviceId||R&&!w&&!be(p.label)||A.has(p.deviceId)||u.has(p.deviceId)||f(p))continue;let y=null;try{y=await a({deviceId:{exact:p.deviceId},...Wn})}catch(M){l(p.label,M);continue}if(!g(y)){if(C(y)&&i!=="mono")return c(R),n("camera-sbs",{label:y.label,width:y.width,height:y.height}),S(y,"sbs");if(!R&&!C(y)){if(R=await _(y,Ke),i==="mono"||!w)return S(R,"mono");continue}c(y)}}if(R)return i==="stereo"&&n("camera-no-stereo",{fallback:R.label}),S(R,"mono");let b=zn(r);throw Object.assign(new Error(b==="camera-busy"?"camera unavailable: in use by another app (e.g. eye tracking) or unable to deliver a picture":b==="permission-denied"?"camera access was denied":"no camera could be opened"),{code:b,skipped:r})}async function Hn(i={}){let e=i.mediaDevices||globalThis.navigator&&navigator.mediaDevices;try{return(await e.getUserMedia({audio:{...da,...i.deviceId?{deviceId:{exact:i.deviceId}}:{}},video:!1})).getAudioTracks()[0]||null}catch(t){return(i.log||(()=>{}))("mic-skip",{error:t&&t.name}),null}}Ct();Re();var jr="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 Ra=i=>String(i).replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),Te=i=>Math.round(i*1e3)/1e3;function Wr(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:Te(e.convergencePx)],["BaselineMm",e.baselineMm===null?null:Te(e.baselineMm)],["HorizontalFovDeg",e.horizontalFovDeg===null?null:Te(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}="${Ra(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="${jr}"${t}/></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`}function Bn(i){if(typeof i!="string"||!i.includes(jr))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(/"/g,'"').replace(/</g,"<").replace(/&/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*Hr(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 $r(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 Ur(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 Hr(i)){if(h.marker===225&&$r(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 Hr(i))if(e.marker===225&&$r(e.data,Pt))return Vn(e.data.subarray(Pt.length));return null}var Vr=i=>Bn(Xn(i)),V={EBML:440786851,Segment:408125543,Tags:307544935,Tag:29555,Targets:25536,SimpleTag:26568,TagName:17827,TagString:17543},ka=i=>i.length>4&&i[0]===26&&i[1]===69&&i[2]===223&&i[3]===163;function Br(i){let e=[];for(let t=i;t>0;t=Math.floor(t/256))e.unshift(t%256);return e}function Xr(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 Je(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 ke(i,e){return[...Br(i),...Xr(e.length),...e]}function Ta(i){let e=[];for(let[n,r]of Object.entries(i))r!=null&&e.push(...ke(V.SimpleTag,[...ke(V.TagName,[...Lt(String(n))]),...ke(V.TagString,[...Lt(String(r))])]));let t=ke(V.Tag,[...ke(V.Targets,[]),...e]);return new Uint8Array(ke(V.Tags,t))}function Gr(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(Te(e.convergencePx)),DXR_BASELINE_MM:e.baselineMm===null?null:String(Te(e.baselineMm)),DXR_HFOV_DEG:e.horizontalFovDeg===null?null:String(Te(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 Aa(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 qr(i){if(!ka(i))return null;let e=Je(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=Je(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 Yr(i,e){let t=qr(i);if(!t)throw new TypeError("webmWithTags: not a WebM/Matroska file (no Segment)");let n=Ta(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=Xr(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 Kr(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=Je(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,(m,f,g)=>{m===V.TagName?u=Vn(i.subarray(f,g)):m===V.TagString&&(d=Vn(i.subarray(f,g)))}),u!==null&&(n[u]=d??"")})}),n}function Oa(i){let e=qr(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=Je(i,r+s.width);if(!o)break;let a=r+s.width+o.width;if(s.id===V.Tags&&!o.unknown&&(n={...n||{},...Kr(i,a,Math.min(t,a+o.size))}),o.unknown){n=n||Da(i,t);break}r=a+o.size}return n}function Da(i,e){let t=Br(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=Je(i,n+4);if(r&&!r.unknown&&n+4+r.width+r.size===e)return Kr(i,n+4+r.width,e)}return null}var Jr=i=>Aa(Oa(i));var ue="[inline3d/camera]",Ws="inline3d-camera/1",Qa=200,el=240,tl=66,nl=4e3,il=4,rl=1500,sl=2e4,ol=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"],Gt=()=>typeof document<"u"&&document&&typeof document.createElement=="function",Ns=()=>{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())}`},al=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":""}.${al(t)}`}var re=(i,e,t={})=>Object.assign(new Error(`${ue} ${i}`),{code:e,...t});function js(i,e=nl){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=el){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 js(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:Ws}}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 js(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((m,f)=>l.toBlob(g=>g?m(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=Wr(h),c=new Blob([Ur(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-${Ns()}`,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||ol.find(w=>typeof MediaRecorder.isTypeSupported!="function"||MediaRecorder.isTypeSupported(w))||"";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}:{}},m=new MediaRecorder(u,d),f=[];m.ondataavailable=w=>w.data&&w.data.size&&f.push(w.data);let g=null,x=[],v=null,_=0,C=!!t&&this.format==="sbs"&&Gt()&&this.video;if(C){v=document.createElement("canvas");let w=()=>{_=requestAnimationFrame(w);let p=this.video,y=p.videoWidth,M=p.videoHeight;!y||!M||(p.readyState||0)<2||((v.width!==y/2||v.height!==M)&&(v.width=y/2,v.height=M),v.getContext("2d").drawImage(p,0,0,y/2,M,0,0,y/2,M))};w();let b=v.captureStream(a);for(let p of h)b.addTrack(p);g=new MediaRecorder(b,d),g.ondataavailable=p=>p.data&&p.data.size&&x.push(p.data)}let S=performance.now(),A=[],k=this.format==="sbs"?setInterval(()=>this.measureConvergence().then(w=>w!==null&&A.push(w)),1500):0;this.measureConvergence().then(w=>w!==null&&A.push(w)),m.start(s),g?.start(s),this.log("record-start",{mimeType:l,mono:C,audio:h.length});let O=(w,b)=>new Promise(p=>{if(!w||w.state==="inactive")return p(b);w.onstop=()=>p(b),w.stop()}),P=o||`clip-${Ns()}`,R=this;return{get state(){return m.state},get mimeType(){return m.mimeType||l},pause(){m.state==="recording"&&m.pause(),g&&g.state==="recording"&&g.pause()},resume(){m.state==="paused"&&m.resume(),g&&g.state==="paused"&&g.resume()},async stop(){clearInterval(k),_&&cancelAnimationFrame(_);let[w,b]=await Promise.all([O(m,f),O(g,x)]),p=m.mimeType||l||w[0]&&w[0].type||"video/webm",y=[...A].sort((Ie,K)=>Ie-K),M=y.length?y[Math.floor(y.length/2)]:null,E=R._meta(M),N=/webm|matroska/.test(p),W=async(Ie,K)=>{let ae=new Blob(Ie,{type:p});if(N&&ae.size)try{ae=new Blob([Yr(new Uint8Array(await ae.arrayBuffer()),Gr({...E,layout:K}))],{type:p})}catch(Di){R.log("record-tag-failed",{message:String(Di&&Di.message)})}return ae},I=await W(w,R.format),z={blob:I,type:p,layout:R.format,durationMs:Math.round(performance.now()-S),convergencePx:M,stereo:R.stereo,suggestedName:qt(P,R.format,p),tagged:N&&I.size>0};return g&&(z.mono=await W(b,"mono"),z.monoSuggestedName=qt(P,"mono",p)),R.log("record-stop",{bytes:I.size,mono:z.mono?z.mono.size:null,ms:z.durationMs,convergencePx:M,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 Dr(t,{format:e.format,calibration:r,mediaDevices:e.mediaDevices,log:n||void 0,exclude:e.exclude,stereoWaitMs:e.stereoWaitMs});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 ll(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=$e(),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=Se(),this._focus=ce(),this._scratch=null,this._luma=null,this.disparityPx=null,this._lastFrameAt=0,this._lastVideoTime=-1,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,frameAgeMs:this.frameAgeMs}}get frameAgeMs(){return this._lastFrameAt?Math.round(performance.now()-this._lastFrameAt):null}_noteFrame(e){if((e.readyState||0)<2)return;let t=e.currentTime;t!==this._lastVideoTime&&(this._lastVideoTime=t,this._lastFrameAt=performance.now())}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.buffer.width=0,this.buffer.height=0),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>=il)return;let t=Math.min(sl,rl*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._noteFrame(e),this.route==="woven-sbs"?this._paintWoven():this._paintFlat(e))}_paintFlat(e){if(this.cursor?.idle(),!ll(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}=He(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 m=d.src==="L"?0:1,f=q(r,n,s,h,m),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 m=q(r,n,s,h,d);u.drawImage(e,d*r+m.sx,m.sy,m.sw,m.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?tl:Qa))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 $s=[[-1,7,10,15,20,26,18,20,24,30,18],[-1,10,16,26,18,24,16,18,22,22,26]],Us=[[-1,1,1,1,1,1,2,2,2,2,4],[-1,1,1,1,2,2,4,4,4,5,5]],cl=[1,0],yi=10;function Vs(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 Hs=(i,e)=>Math.floor(Vs(i)/8)-$s[e][i]*Us[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 hl(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 ul(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<=Hs(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=(w,b)=>{for(let p=b-1;p>=0;p--)s.push(w>>>p&1)};o(4,4),o(n.length,r<=9?8:16);for(let w of n)o(w,8);let a=Hs(r,t)*8;o(0,Math.min(4,a-s.length)),o(0,(8-s.length%8)%8);for(let w=236;s.length<a;w^=253)o(w,8);let l=[];for(let w=0;w<s.length;w+=8)l.push(s.slice(w,w+8).reduce((b,p)=>b<<1|p,0));let c=Us[t][r],h=$s[t][r],u=Math.floor(Vs(r)/8),d=c-u%c,m=Math.floor(u/c),f=hl(h),g=[];for(let w=0,b=0;w<c;w++){let p=l.slice(b,b+m-h+(w<d?0:1));b+=p.length;let y=ul(p,f);w<d&&p.push(0),g.push(p.concat(y))}let x=[];for(let w=0;w<g[0].length;w++)for(let b=0;b<g.length;b++)(w!==m-h||b>=d)&&x.push(g[b][w]);let v=r*4+17,_=Array.from({length:v},()=>new Array(v).fill(!1)),C=Array.from({length:v},()=>new Array(v).fill(!1)),S=(w,b,p)=>{_[b][w]=p,C[b][w]=!0};for(let w=0;w<v;w++)S(6,w,w%2===0),S(w,6,w%2===0);let A=(w,b)=>{for(let p=-4;p<=4;p++)for(let y=-4;y<=4;y++){let M=Math.max(Math.abs(y),Math.abs(p)),E=w+y,N=b+p;E>=0&&E<v&&N>=0&&N<v&&S(E,N,M!==2&&M!==4)}};A(3,3),A(v-4,3),A(3,v-4);let k=[];if(r>1){let w=Math.floor(r/7)+2,b=Math.ceil((r*4+4)/(w*2-2))*2;k.push(6);for(let p=v-7;k.length<w;p-=b)k.splice(1,0,p)}for(let w=0;w<k.length;w++)for(let b=0;b<k.length;b++)if(!(w===0&&b===0||w===0&&b===k.length-1||w===k.length-1&&b===0))for(let p=-2;p<=2;p++)for(let y=-2;y<=2;y++)S(k[w]+y,k[b]+p,Math.max(Math.abs(y),Math.abs(p))!==1);let O=w=>{let b=cl[t]<<3|w,p=b;for(let E=0;E<10;E++)p=p<<1^(p>>>9)*1335;let y=(b<<10|p)^21522,M=E=>(y>>>E&1)!==0;for(let E=0;E<=5;E++)S(8,E,M(E));S(8,7,M(6)),S(8,8,M(7)),S(7,8,M(8));for(let E=9;E<15;E++)S(14-E,8,M(E));for(let E=0;E<8;E++)S(v-1-E,8,M(E));for(let E=8;E<15;E++)S(8,v-15+E,M(E));S(8,v-8,!0)};if(O(0),r>=7){let w=r;for(let p=0;p<12;p++)w=w<<1^(w>>>11)*7973;let b=r<<12|w;for(let p=0;p<18;p++){let y=(b>>>p&1)!==0,M=v-11+p%3,E=Math.floor(p/3);S(M,E,y),S(E,M,y)}}let P=0;for(let w=v-1;w>=1;w-=2){w===6&&(w=5);for(let b=0;b<v;b++)for(let p=0;p<2;p++){let y=w-p,E=(w+1&2)===0?v-1-b:b;!C[E][y]&&P<x.length*8&&(_[E][y]=(x[P>>>3]>>>7-(P&7)&1)!==0,P++)}}let R=w=>{for(let b=0;b<v;b++)for(let p=0;p<v;p++){if(C[b][p])continue;let y;switch(w){case 0:y=(p+b)%2===0;break;case 1:y=b%2===0;break;case 2:y=p%3===0;break;case 3:y=(p+b)%3===0;break;case 4:y=(Math.floor(p/3)+Math.floor(b/2))%2===0;break;case 5:y=p*b%2+p*b%3===0;break;case 6:y=(p*b%2+p*b%3)%2===0;break;default:y=((p+b)%2+p*b%3)%2===0}y&&(_[b][p]=!_[b][p])}},T=Number.isInteger(e.mask)?e.mask:-1;if(T<0){let w=1/0;for(let b=0;b<8;b++){R(b),O(b);let p=dl(_,v);p<w&&(w=p,T=b),R(b)}}return R(T),O(T),{version:r,size:v,mask:T,modules:_}}function dl(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 Bs(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",Xs=Object.freeze([Kt,"wss://dxr-signal.displayxr.workers.dev"]),Gs=["bad-room","bad-id","bad-version","bad-key","origin-not-allowed","blocked"];function Pe(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):Xs.includes(n)?[...Xs]:[],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)}`:""}`,m=R=>`${a[R]}/v1/connect?${d}`,f=null,g=!1,x=0,v=null,_=new Set,C=[],S=R=>A(R,a.length),A=(R,T)=>new Promise((w,b)=>{let p=!1,y=!1,M=!1,E=new r(m(l));f=E;let N=W=>{if(!p){p=!0;try{E.close()}catch{}b(W)}};E.onopen=()=>{M=!0,E.send(JSON.stringify({t:"join",v:1,room:c,id:h.id,max:h.maxPeers}))},E.onmessage=W=>{let I;try{I=JSON.parse(typeof W.data=="string"?W.data:String(W.data))}catch{return}switch(I.t){case"welcome":{x=0;let z=Array.isArray(I.peers)?I.peers.filter(K=>typeof K=="string"):[];clearInterval(v),v=setInterval(()=>k({t:"ping"}),s);let Ie=C;C=[];for(let K of Ie)k(K);if(R){let K=new Set(z);for(let ae of _)K.has(ae)||h.onPeerLeft?.(ae);_=K,h.onReconnect?.(z)}else _=new Set(z);p=!0,y=!0,w({id:I.id,peers:z,iceServers:Array.isArray(I.iceServers)?I.iceServers:void 0,max:I.max,tier:I.tier==="key"?"key":"anon",key:typeof I.key=="string"?I.key:void 0,turn:I.turn&&typeof I.turn=="object"?I.turn:void 0});break}case"full":g=!0,N(se("room-full",`this call is full (${I.max} participants)`));break;case"expired":{g=!0,clearInterval(v);let z=se("expired","this room has reached its lifetime on the signalling server");p?h.onDisconnect?.(z):N(z);break}case"error":if(!p&&Gs.includes(I.code))g=!0,N(se(I.code,I.message||I.code));else if(!p&&(I.code==="rate-limited"||I.code==="quota")){let z=se(I.code,I.message||I.code);z.retryMs=I.retryMs>0?I.retryMs:0,N(z)}else!p&&I.code==="id-taken"&&N(se("id-taken","peer id still held; retrying"));break;case"peer-joined":typeof I.id=="string"&&!_.has(I.id)&&(_.add(I.id),h.onPeerJoined?.(I.id));break;case"peer-left":typeof I.id=="string"&&(_.delete(I.id),h.onPeerLeft?.(I.id));break;case"signal":typeof I.from=="string"&&h.onSignal?.(I.from,I.data);break}},E.onerror=()=>{if(!M&&!p&&T>1){p=!0,l=(l+1)%a.length,A(R,T-1).then(w,b);return}N(se("signaling-unreachable",`cannot reach ${a[l]}`))},E.onclose=()=>{clearInterval(v),N(se("signaling-closed","signalling closed before joining")),y&&!g&&f===E&&O()}}),k=R=>{f&&f.readyState===1?f.send(JSON.stringify(R)):g||C.push(R)},O=()=>{h.onDisconnect?.();let R=()=>{g||S(!0).catch(T=>{if(g||T&&(T.code==="room-full"||Gs.includes(T.code))){h.onDisconnect?.(T);return}setTimeout(R,Math.max(Z(x++,{baseMs:500,maxMs:15e3}),T&&T.retryMs||0))})};setTimeout(R,Z(x++,{baseMs:300,maxMs:15e3}))};return{...await S(!1),send:(R,T)=>k({t:"signal",to:R,data:T}),leave:()=>{if(!g){g=!0,clearInterval(v);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"}),Ys=i=>typeof i=="string"&&Si[i.toLowerCase()]||i,Ks=Object.freeze({accent:"--dxr-accent",ink:"--dxr-ink",shell:"--dxr-shell",danger:"--dxr-danger",radius:"--dxr-radius",font:"--dxr-font"}),nt=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 Js(i){let e={...nt,...i&&typeof i=="object"?i:{}};return(t,n)=>{let r=typeof e[t]=="string"?e[t]:nt[t]||t;if(n)for(let[s,o]of Object.entries(n))r=r.split(`{${s}}`).join(String(o));return r}}var qs="dxr-call-style",ml=`
|
|
19
|
+
`,n=i.split(t),r=n.findIndex(m=>m.startsWith("m=video"));if(r<0)return i;let s=n.findIndex((m,f)=>f>r&&m.startsWith("m="));s<0&&(s=n.length);let o=n.slice(r,s),a=new Map,l=new Map;for(let m of o){let f=m.match(/^a=rtpmap:(\d+) ([\w-]+)\//);f&&a.set(f[1],f[2].toUpperCase());let g=m.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 m of e)for(let f of h)if(a.get(f)===m&&!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(m=>!u.includes(m));return n[r]=[...c.slice(0,3),...u,...d].join(" "),n.join(t)}var Cr=Object.freeze([{urls:"stun:stun.l.google.com:19302"}]),ca=4e3,ha=1e4,ua=2e4,da=8e3,fa=1e4,pa=.6;function Ye(i){let e=Number.isInteger(i)?i:ye;return Math.max(2,Math.min(hr,e))}function Rr(i,e){return i<e}var qe=class{constructor({signaling:e,id:t,maxPeers:n,iceServers:r,RTCPeerConnection:s,log:o,unreachableMs:a}={}){this.unreachableMs=a>0?a:fa,this.signaling=e,this.id=t,this.maxPeers=Ye(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:m,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:m,onGhost:f};let g=_=>(...C)=>this.ready?_(...C):this._pending.push(()=>_(...C));this.session=await this.signaling.join(e,{id:this.id,maxPeers:this.maxPeers,onPeerJoined:g(_=>this._onPeerJoined(_)),onPeerLeft:g(_=>this._onPeerLeftSignaling(_)),onSignal:g((_,C)=>this._onSignal(_,C)),onDisconnect:_=>m?.(_?"closed":"reconnecting",_),onPeerUnreachable:g(_=>f?.(_,!0)),onPeerReachable:g(_=>f?.(_,!1)),onReconnect:g(_=>{m?.("connected");for(let C of _)this._onPeerJoined(C)})}),!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 _=new Error(`@displayxr/inline3d/call: this call is full (${this.maxPeers} participants)`);throw _.code="room-full",_}this.ready=!0;for(let _ of x)this._onPeerJoined(_);let v=this._pending;this._pending=[];for(let _ of v)_();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),da)}_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,ua,()=>{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=Ge(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=Ge(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(wt(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,ca,()=>{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,ha,()=>{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(Be(this.sendFormat,e)*(t?pa:1)),r=Be("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 ma=Object.freeze(["0733:011a"]),ga=1280,_a={width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30},resizeMode:"none"};function Tr(i){let e=String(i||"").toLowerCase();return ma.some(t=>e.includes(`(${t})`))}function kr(i,e){let t=Math.min(ga,i),n=Math.max(2,Math.round(t*e/i/2)*2);return{width:t*2,height:n}}async function Ar(i){if(typeof MediaStreamTrackProcessor!="function"||typeof document>"u")return null;try{await i.applyConstraints(_a)}catch{return null}let e=i.getSettings();return!(e.width>0)||!(e.height>0)||Math.abs(e.width/e.height-16/9)>.01?null:va(i,e.width,e.height,e.frameRate)}function va(i,e,t,n){if(typeof MediaStreamTrackProcessor!="function"||typeof document>"u")return null;let{width:r,height:s}=kr(e,t),o=e,a=t,l=document.createElement("canvas");l.width=r,l.height=s;let c=l.getContext("2d",{alpha:!1});if(!c)return null;let h=l.captureStream(n>0?n:30),u=h.getVideoTracks()[0],d=new MediaStreamTrackProcessor({track:i}).readable.getReader(),m=!1,f=u.stop.bind(u);return u.stop=()=>{m=!0,d.cancel().catch(()=>{}),i.stop(),f()},(async()=>{for(;;){let{value:g,done:x}=await d.read();if(x)break;if(g.displayWidth>0&&g.displayHeight>0&&(g.displayWidth!==o||g.displayHeight!==a)){o=g.displayWidth,a=g.displayHeight;let v=kr(o,a);l.width=r=v.width,l.height=s=v.height}c.drawImage(g,0,0,r,s),g.close()}})().catch(()=>{}).finally(()=>{m||(u.stop(),u.dispatchEvent(new Event("ended")))}),{stream:h,track:u,width:r,height:s}}var bt="dxr-app:",xt=/^DisplayXR: (.+) \(3D\)$/,Or=/^3D Camera \(DisplayXR\)\s+-\s+(.+)$/;function St(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 Dr(i){let e="";try{e=typeof i=="string"?i:i&&typeof i=="object"?i.label:""}catch{return null}let t=typeof e=="string"?Or.exec(e.trim()):null,n=t?t[1].trim():"";return n?{appName:n}:null}function Pr(i){let e=typeof i=="string"?xt.exec(i.trim()):null;return e&&e[1].trim()||null}function ne(i){if(!i)return!1;if(typeof i=="string")return xt.test(i.trim())||i.startsWith(bt);if(typeof i!="object")return!1;let e=i;try{if(typeof e.label=="string"&&xt.test(e.label.trim())||typeof e.deviceId=="string"&&e.deviceId.startsWith(bt))return!0;let t=e.displayxrStereo||(typeof e.getSettings=="function"?(e.getSettings()||{}).displayxrStereo:null);if(St(t))return!0;if(typeof e.getSettings=="function"){let n=(e.getSettings()||{}).deviceId;if(typeof n=="string"&&n.startsWith(bt))return!0}}catch{}return!1}var Ke={width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},zn={width:{ideal:3840},height:{ideal:1080},frameRate:{ideal:30}},ya=Object.freeze({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),wa=2500,ba=500;function xa(){return Lr()?wa:0}function Lr(){return typeof navigator<"u"&&!!navigator.xr&&typeof window<"u"&&typeof window.XRDisplayLayer=="function"}function Sa(i,e){return new Promise(t=>{let n=0,r=()=>{clearTimeout(n);try{i.removeEventListener?.("devicechange",r)}catch{}t()};n=setTimeout(r,e);try{i.addEventListener?.("devicechange",r)}catch{}})}function Ma(i){return!!i&&(i.name==="NotReadableError"||i.name==="TrackStartError"||/in use|busy/i.test(i.message||""))}function Ea(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 Ca=/\b(hand[- ]?track|tracking camera|eye[- ]?track|depth camera|ultraleap|leap motion|infrared|ir camera)/i;function Ra(i){let e=(n,r)=>ne({label:String(n||""),deviceId:typeof r=="string"?r:""});if(i===!1)return e;let t=[Ca];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 be(i){return ne(String(i||""))?!1:/stereo|\b3d\b|\bsbs\b|dual/i.test(i||"")}async function Ir(i="auto",e={}){let t=e.mediaDevices||globalThis.navigator&&navigator.mediaDevices,n=e.log||(()=>{}),r=[],s=e.calibration||{},o=Ra(e.exclude);if(i&&typeof i=="object"&&typeof i.getVideoTracks=="function"){let p=i.getVideoTracks()[0],y=p?p.getSettings():{},b=e.format==="sbs"?"sbs":"mono";return{stream:i,format:b,width:y.width||0,height:y.height||0,deviceId:y.deviceId||null,label:p?p.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 p=>{let y=await t.getUserMedia({video:p,audio:!1}),b=y.getVideoTracks()[0],E=b?b.getSettings():{};if(!b||b.readyState==="ended"||!(E.width>0)||!(E.height>0))throw y.getTracks().forEach(P=>P.stop()),Object.assign(new Error("the camera opened but delivers no picture (0x0)"),{name:"NotReadableError"});let N=E.displayxrStereo&&E.displayxrStereo.layout==="side-by-side"?E.displayxrStereo:null;if(i!=="mono"&&Tr(b.label)){let P=await Ar(b);if(P)return n("camera-half-sbs",{label:b.label,width:P.width,height:P.height}),{...P,deviceId:E.deviceId||null,label:b.label,stereo:null,appShare:!1}}let z=ne({label:b.label||"",deviceId:E.deviceId||""})||St(E.displayxrStereo);return{stream:y,track:b,width:E.width,height:E.height,deviceId:E.deviceId||null,label:b.label||"",stereo:N,appShare:z}},l=(p,y)=>{r.push({label:p,error:`${y.name}: ${y.message}`,busy:Ma(y),denied:Ea(y)}),n("camera-skip",{label:p,error:y.name})},c=p=>p&&p.stream.getTracks().forEach(y=>y.stop()),h=async()=>{try{return(await t.enumerateDevices()).filter(p=>p.kind==="videoinput")}catch{return[]}},u=new Set,d=(p,y,b="excluded")=>{y&&u.has(y)||(y&&u.add(y),r.push({label:p,error:"excluded",excluded:!0,reason:b}),n("camera-skip",{label:p,error:"excluded",reason:b}))},m=p=>ne({label:p.label||"",deviceId:p.deviceId||""}),f=p=>m(p)?(d(p.label||"",p.deviceId,"app-share"),!0):!p.label||!o(p.label,p.deviceId)?!1:(d(p.label,p.deviceId),!0),g=p=>p.appShare?(c(p),d(p.label,p.deviceId,"app-share"),!0):o(p.label,p.deviceId)?(c(p),d(p.label,p.deviceId),!0):!1,x=!1,v=async p=>{let y=await a(p);return g(y)?(x=!0,null):y},_=async(p,y)=>{try{await p.track.applyConstraints(y);let b=p.track.getSettings();if(b.width>0&&b.height>0)return{...p,width:b.width,height:b.height}}catch{}return p},C=p=>!!p&&(!!p.stereo||Cn(p.width,p.height)),M=(p,y)=>({stream:p.stream,format:y,width:p.width,height:p.height,deviceId:p.deviceId,label:p.label,owned:!0,skipped:r,calibration:{rectified:!1,...y==="sbs"&&p.stereo?{rectified:!!p.stereo.rectified,...p.stereo.baselineMm>0?{baselineMm:p.stereo.baselineMm}:{},...p.stereo.horizontalFovDeg>0?{hfovDeg:p.stereo.horizontalFovDeg}:{}}:{},...s}});if(typeof i=="string"&&i.startsWith("label:")){let p=i.slice(6).trim().toLowerCase(),y=await h();if(p&&y.length&&y.every(E=>!E.label)){try{c(await a(!0))}catch(E){l("default",E)}y=await h()}let b=p?y.find(E=>E.deviceId&&!m(E)&&(E.label||"").toLowerCase().includes(p)):null;if(!b)throw Object.assign(new Error(`camera unavailable: no camera labelled "${p}"`),{code:Wn(r),skipped:r});n("camera-label",{label:b.label,needle:p}),i=b.deviceId}if(typeof i=="string"&&!["auto","stereo","mono"].includes(i)){let p;try{p=await a({deviceId:{exact:i},...zn})}catch(y){throw l(i,y),Object.assign(new Error(`camera unavailable: ${y.message}`),{code:Wn(r),skipped:r})}return C(p)?M(p,"sbs"):(c(p),M(await a({deviceId:{exact:i},...Ke}),"mono"))}let A=new Set,k=async p=>{for(let y of p){if(!y.deviceId||!be(y.label)||A.has(y.deviceId)||(A.add(y.deviceId),f(y)))continue;let b=null;try{b=await a({deviceId:{exact:y.deviceId},...zn})}catch(E){l(y.label,E);continue}if(!g(b)){if(C(b))return n("camera-sbs",{label:b.label,width:b.width,height:b.height,direct:!0}),b;c(b)}}return null},O=Number.isFinite(e.stereoWaitMs)?Math.max(0,e.stereoWaitMs):xa(),L=async p=>{if(!(p>0))return k(await h());let y=Date.now()+p;for(n("camera-wait-stereo",{ms:p});;){let b=y-Date.now();if(b<=0)break;await Sa(t,Math.min(ba,b));let E=await h(),N=await k(E);if(N)return N;if(E.some(z=>be(z.label)&&!m(z)))break}return n("camera-no-stereo-listed",{ms:p}),null},R=null;if(i!=="mono"){let p=await h(),y=await k(p);if(y||p.some(b=>b.label)&&!p.some(b=>be(b.label))&&(y=await L(O),y))return M(y,"sbs");if(p.length&&p.every(b=>!b.label)){let b=null;try{b=await v(!0)}catch(N){l("default",N)}if(b&&b.stereo)return M(b,"sbs");b&&b.deviceId&&A.add(b.deviceId);let E=await k(await h());if(E)return c(b),M(E,"sbs");if(b&&C(b))return M(b,"sbs");b&&(R=await _(b,Ke))}}if(!R&&!x){let p=await h(),b=p.filter(f).length>0&&p.find(E=>E.deviceId&&!u.has(E.deviceId))||null;if(b){b.deviceId&&A.add(b.deviceId);try{R=await a({deviceId:{exact:b.deviceId},...Ke}),g(R)&&(R=null)}catch(E){l(b.label,E)}}else try{R=await v(Ke)}catch(E){l("default",E)}}if(i==="mono"&&R)return M(R,"mono");if(R&&C(R))return M(R,"sbs");let T=[];try{T=(await t.enumerateDevices()).filter(p=>p.kind==="videoinput")}catch{}T.sort((p,y)=>Number(be(y.label))-Number(be(p.label)));let w=!Lr();for(let p of T){if(!p.deviceId||R&&p.deviceId===R.deviceId||R&&!w&&!be(p.label)||A.has(p.deviceId)||u.has(p.deviceId)||f(p))continue;let y=null;try{y=await a({deviceId:{exact:p.deviceId},...zn})}catch(b){l(p.label,b);continue}if(!g(y)){if(C(y)&&i!=="mono")return c(R),n("camera-sbs",{label:y.label,width:y.width,height:y.height}),M(y,"sbs");if(!R&&!C(y)){if(R=await _(y,Ke),i==="mono"||!w)return M(R,"mono");continue}c(y)}}if(R)return i==="stereo"&&n("camera-no-stereo",{fallback:R.label}),M(R,"mono");let S=Wn(r);throw Object.assign(new Error(S==="camera-busy"?"camera unavailable: in use by another app (e.g. eye tracking) or unable to deliver a picture":S==="permission-denied"?"camera access was denied":"no camera could be opened"),{code:S,skipped:r})}async function Hn(i={}){let e=i.mediaDevices||globalThis.navigator&&navigator.mediaDevices;try{return(await e.getUserMedia({audio:{...ya,...i.deviceId?{deviceId:{exact:i.deviceId}}:{}},video:!1})).getAudioTracks()[0]||null}catch(t){return(i.log||(()=>{}))("mic-skip",{error:t&&t.name}),null}}Ct();Re();var Hr="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 La=i=>String(i).replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),Te=i=>Math.round(i*1e3)/1e3;function $r(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:Te(e.convergencePx)],["BaselineMm",e.baselineMm===null?null:Te(e.baselineMm)],["HorizontalFovDeg",e.horizontalFovDeg===null?null:Te(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}="${La(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="${Hr}"${t}/></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`}function Bn(i){if(typeof i!="string"||!i.includes(Hr))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(/"/g,'"').replace(/</g,"<").replace(/&/g,"&")})}var Lt=i=>new TextEncoder().encode(i),Vn=i=>new TextDecoder().decode(i),Ur=i=>i.length>4&&i[0]===255&&i[1]===216;function*Vr(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 Br(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 Xr(i,e){if(!Ur(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 Vr(i)){if(h.marker===225&&Br(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(!Ur(i))return null;for(let e of Vr(i))if(e.marker===225&&Br(e.data,Pt))return Vn(e.data.subarray(Pt.length));return null}var Gr=i=>Bn(Xn(i)),V={EBML:440786851,Segment:408125543,Tags:307544935,Tag:29555,Targets:25536,SimpleTag:26568,TagName:17827,TagString:17543},Ia=i=>i.length>4&&i[0]===26&&i[1]===69&&i[2]===223&&i[3]===163;function qr(i){let e=[];for(let t=i;t>0;t=Math.floor(t/256))e.unshift(t%256);return e}function Yr(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 Je(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 ke(i,e){return[...qr(i),...Yr(e.length),...e]}function Fa(i){let e=[];for(let[n,r]of Object.entries(i))r!=null&&e.push(...ke(V.SimpleTag,[...ke(V.TagName,[...Lt(String(n))]),...ke(V.TagString,[...Lt(String(r))])]));let t=ke(V.Tag,[...ke(V.Targets,[]),...e]);return new Uint8Array(ke(V.Tags,t))}function Kr(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(Te(e.convergencePx)),DXR_BASELINE_MM:e.baselineMm===null?null:String(Te(e.baselineMm)),DXR_HFOV_DEG:e.horizontalFovDeg===null?null:String(Te(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 Na(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 Jr(i){if(!Ia(i))return null;let e=Je(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=Je(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 Zr(i,e){let t=Jr(i);if(!t)throw new TypeError("webmWithTags: not a WebM/Matroska file (no Segment)");let n=Fa(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=Yr(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 Qr(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=Je(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,(m,f,g)=>{m===V.TagName?u=Vn(i.subarray(f,g)):m===V.TagString&&(d=Vn(i.subarray(f,g)))}),u!==null&&(n[u]=d??"")})}),n}function ja(i){let e=Jr(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=Je(i,r+s.width);if(!o)break;let a=r+s.width+o.width;if(s.id===V.Tags&&!o.unknown&&(n={...n||{},...Qr(i,a,Math.min(t,a+o.size))}),o.unknown){n=n||za(i,t);break}r=a+o.size}return n}function za(i,e){let t=qr(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=Je(i,n+4);if(r&&!r.unknown&&n+4+r.width+r.size===e)return Qr(i,n+4+r.width,e)}return null}var es=i=>Na(ja(i));var ue="[inline3d/camera]",$s="inline3d-camera/1",ol=200,al=240,ll=66,cl=4e3,hl=4,ul=1500,dl=2e4,fl=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"],Gt=()=>typeof document<"u"&&document&&typeof document.createElement=="function",Ws=()=>{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())}`},pl=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":""}.${pl(t)}`}var re=(i,e,t={})=>Object.assign(new Error(`${ue} ${i}`),{code:e,...t});function Hs(i,e=cl){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 Us(i,e,t=al){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 Hs(this.video)}catch{return null}this._scratch=this._scratch||document.createElement("canvas");let e=Us(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:$s}}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 Hs(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((m,f)=>l.toBlob(g=>g?m(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=$r(h),c=new Blob([Xr(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-${Ws()}`,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||fl.find(w=>typeof MediaRecorder.isTypeSupported!="function"||MediaRecorder.isTypeSupported(w))||"";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}:{}},m=new MediaRecorder(u,d),f=[];m.ondataavailable=w=>w.data&&w.data.size&&f.push(w.data);let g=null,x=[],v=null,_=0,C=!!t&&this.format==="sbs"&&Gt()&&this.video;if(C){v=document.createElement("canvas");let w=()=>{_=requestAnimationFrame(w);let p=this.video,y=p.videoWidth,b=p.videoHeight;!y||!b||(p.readyState||0)<2||((v.width!==y/2||v.height!==b)&&(v.width=y/2,v.height=b),v.getContext("2d").drawImage(p,0,0,y/2,b,0,0,y/2,b))};w();let S=v.captureStream(a);for(let p of h)S.addTrack(p);g=new MediaRecorder(S,d),g.ondataavailable=p=>p.data&&p.data.size&&x.push(p.data)}let M=performance.now(),A=[],k=this.format==="sbs"?setInterval(()=>this.measureConvergence().then(w=>w!==null&&A.push(w)),1500):0;this.measureConvergence().then(w=>w!==null&&A.push(w)),m.start(s),g?.start(s),this.log("record-start",{mimeType:l,mono:C,audio:h.length});let O=(w,S)=>new Promise(p=>{if(!w||w.state==="inactive")return p(S);w.onstop=()=>p(S),w.stop()}),L=o||`clip-${Ws()}`,R=this;return{get state(){return m.state},get mimeType(){return m.mimeType||l},pause(){m.state==="recording"&&m.pause(),g&&g.state==="recording"&&g.pause()},resume(){m.state==="paused"&&m.resume(),g&&g.state==="paused"&&g.resume()},async stop(){clearInterval(k),_&&cancelAnimationFrame(_);let[w,S]=await Promise.all([O(m,f),O(g,x)]),p=m.mimeType||l||w[0]&&w[0].type||"video/webm",y=[...A].sort((Ie,K)=>Ie-K),b=y.length?y[Math.floor(y.length/2)]:null,E=R._meta(b),N=/webm|matroska/.test(p),z=async(Ie,K)=>{let ae=new Blob(Ie,{type:p});if(N&&ae.size)try{ae=new Blob([Zr(new Uint8Array(await ae.arrayBuffer()),Kr({...E,layout:K}))],{type:p})}catch(Di){R.log("record-tag-failed",{message:String(Di&&Di.message)})}return ae},P=await z(w,R.format),W={blob:P,type:p,layout:R.format,durationMs:Math.round(performance.now()-M),convergencePx:b,stereo:R.stereo,suggestedName:qt(L,R.format,p),tagged:N&&P.size>0};return g&&(W.mono=await z(S,"mono"),W.monoSuggestedName=qt(L,"mono",p)),R.log("record-stop",{bytes:P.size,mono:W.mono?W.mono.size:null,ms:W.durationMs,convergencePx:b,name:W.suggestedName}),W}}}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 Ir(t,{format:e.format,calibration:r,mediaDevices:e.mediaDevices,log:n||void 0,exclude:e.exclude,stereoWaitMs:e.stereoWaitMs});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 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 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=$e(),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=Se(),this._focus=ce(),this._scratch=null,this._luma=null,this.disparityPx=null,this._lastFrameAt=0,this._lastVideoTime=-1,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,frameAgeMs:this.frameAgeMs}}get frameAgeMs(){return this._lastFrameAt?Math.round(performance.now()-this._lastFrameAt):null}_noteFrame(e){if((e.readyState||0)<2)return;let t=e.currentTime;t!==this._lastVideoTime&&(this._lastVideoTime=t,this._lastFrameAt=performance.now())}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.buffer.width=0,this.buffer.height=0),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>=hl)return;let t=Math.min(dl,ul*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._noteFrame(e),this.route==="woven-sbs"?this._paintWoven():this._paintFlat(e))}_paintFlat(e){if(this.cursor?.idle(),!ml(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}=He(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 m=d.src==="L"?0:1,f=q(r,n,s,h,m),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 m=q(r,n,s,h,d);u.drawImage(e,d*r+m.sx,m.sy,m.sw,m.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?ll:ol))return;this._autoAt=n,this._scratch=this._scratch||document.createElement("canvas");let r=Us(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 Bs=[[-1,7,10,15,20,26,18,20,24,30,18],[-1,10,16,26,18,24,16,18,22,22,26]],Xs=[[-1,1,1,1,1,1,2,2,2,2,4],[-1,1,1,1,2,2,4,4,4,5,5]],gl=[1,0],yi=10;function Gs(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 Vs=(i,e)=>Math.floor(Gs(i)/8)-Bs[e][i]*Xs[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 _l(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 vl(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<=Vs(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=(w,S)=>{for(let p=S-1;p>=0;p--)s.push(w>>>p&1)};o(4,4),o(n.length,r<=9?8:16);for(let w of n)o(w,8);let a=Vs(r,t)*8;o(0,Math.min(4,a-s.length)),o(0,(8-s.length%8)%8);for(let w=236;s.length<a;w^=253)o(w,8);let l=[];for(let w=0;w<s.length;w+=8)l.push(s.slice(w,w+8).reduce((S,p)=>S<<1|p,0));let c=Xs[t][r],h=Bs[t][r],u=Math.floor(Gs(r)/8),d=c-u%c,m=Math.floor(u/c),f=_l(h),g=[];for(let w=0,S=0;w<c;w++){let p=l.slice(S,S+m-h+(w<d?0:1));S+=p.length;let y=vl(p,f);w<d&&p.push(0),g.push(p.concat(y))}let x=[];for(let w=0;w<g[0].length;w++)for(let S=0;S<g.length;S++)(w!==m-h||S>=d)&&x.push(g[S][w]);let v=r*4+17,_=Array.from({length:v},()=>new Array(v).fill(!1)),C=Array.from({length:v},()=>new Array(v).fill(!1)),M=(w,S,p)=>{_[S][w]=p,C[S][w]=!0};for(let w=0;w<v;w++)M(6,w,w%2===0),M(w,6,w%2===0);let A=(w,S)=>{for(let p=-4;p<=4;p++)for(let y=-4;y<=4;y++){let b=Math.max(Math.abs(y),Math.abs(p)),E=w+y,N=S+p;E>=0&&E<v&&N>=0&&N<v&&M(E,N,b!==2&&b!==4)}};A(3,3),A(v-4,3),A(3,v-4);let k=[];if(r>1){let w=Math.floor(r/7)+2,S=Math.ceil((r*4+4)/(w*2-2))*2;k.push(6);for(let p=v-7;k.length<w;p-=S)k.splice(1,0,p)}for(let w=0;w<k.length;w++)for(let S=0;S<k.length;S++)if(!(w===0&&S===0||w===0&&S===k.length-1||w===k.length-1&&S===0))for(let p=-2;p<=2;p++)for(let y=-2;y<=2;y++)M(k[w]+y,k[S]+p,Math.max(Math.abs(y),Math.abs(p))!==1);let O=w=>{let S=gl[t]<<3|w,p=S;for(let E=0;E<10;E++)p=p<<1^(p>>>9)*1335;let y=(S<<10|p)^21522,b=E=>(y>>>E&1)!==0;for(let E=0;E<=5;E++)M(8,E,b(E));M(8,7,b(6)),M(8,8,b(7)),M(7,8,b(8));for(let E=9;E<15;E++)M(14-E,8,b(E));for(let E=0;E<8;E++)M(v-1-E,8,b(E));for(let E=8;E<15;E++)M(8,v-15+E,b(E));M(8,v-8,!0)};if(O(0),r>=7){let w=r;for(let p=0;p<12;p++)w=w<<1^(w>>>11)*7973;let S=r<<12|w;for(let p=0;p<18;p++){let y=(S>>>p&1)!==0,b=v-11+p%3,E=Math.floor(p/3);M(b,E,y),M(E,b,y)}}let L=0;for(let w=v-1;w>=1;w-=2){w===6&&(w=5);for(let S=0;S<v;S++)for(let p=0;p<2;p++){let y=w-p,E=(w+1&2)===0?v-1-S:S;!C[E][y]&&L<x.length*8&&(_[E][y]=(x[L>>>3]>>>7-(L&7)&1)!==0,L++)}}let R=w=>{for(let S=0;S<v;S++)for(let p=0;p<v;p++){if(C[S][p])continue;let y;switch(w){case 0:y=(p+S)%2===0;break;case 1:y=S%2===0;break;case 2:y=p%3===0;break;case 3:y=(p+S)%3===0;break;case 4:y=(Math.floor(p/3)+Math.floor(S/2))%2===0;break;case 5:y=p*S%2+p*S%3===0;break;case 6:y=(p*S%2+p*S%3)%2===0;break;default:y=((p+S)%2+p*S%3)%2===0}y&&(_[S][p]=!_[S][p])}},T=Number.isInteger(e.mask)?e.mask:-1;if(T<0){let w=1/0;for(let S=0;S<8;S++){R(S),O(S);let p=yl(_,v);p<w&&(w=p,T=S),R(S)}}return R(T),O(T),{version:r,size:v,mask:T,modules:_}}function yl(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 qs(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",Ys=Object.freeze([Kt,"wss://dxr-signal.displayxr.workers.dev"]),Ks=["bad-room","bad-id","bad-version","bad-key","origin-not-allowed","blocked"];function Pe(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):Ys.includes(n)?[...Ys]:[],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)}`:""}`,m=R=>`${a[R]}/v1/connect?${d}`,f=null,g=!1,x=0,v=null,_=new Set,C=[],M=R=>A(R,a.length),A=(R,T)=>new Promise((w,S)=>{let p=!1,y=!1,b=!1,E=new r(m(l));f=E;let N=z=>{if(!p){p=!0;try{E.close()}catch{}S(z)}};E.onopen=()=>{b=!0,E.send(JSON.stringify({t:"join",v:1,room:c,id:h.id,max:h.maxPeers}))},E.onmessage=z=>{let P;try{P=JSON.parse(typeof z.data=="string"?z.data:String(z.data))}catch{return}switch(P.t){case"welcome":{x=0;let W=Array.isArray(P.peers)?P.peers.filter(K=>typeof K=="string"):[];clearInterval(v),v=setInterval(()=>k({t:"ping"}),s);let Ie=C;C=[];for(let K of Ie)k(K);if(R){let K=new Set(W);for(let ae of _)K.has(ae)||h.onPeerLeft?.(ae);_=K,h.onReconnect?.(W)}else _=new Set(W);p=!0,y=!0,w({id:P.id,peers:W,iceServers:Array.isArray(P.iceServers)?P.iceServers:void 0,max:P.max,tier:P.tier==="key"?"key":"anon",key:typeof P.key=="string"?P.key:void 0,turn:P.turn&&typeof P.turn=="object"?P.turn:void 0});break}case"full":g=!0,N(se("room-full",`this call is full (${P.max} participants)`));break;case"expired":{g=!0,clearInterval(v);let W=se("expired","this room has reached its lifetime on the signalling server");p?h.onDisconnect?.(W):N(W);break}case"error":if(!p&&Ks.includes(P.code))g=!0,N(se(P.code,P.message||P.code));else if(!p&&(P.code==="rate-limited"||P.code==="quota")){let W=se(P.code,P.message||P.code);W.retryMs=P.retryMs>0?P.retryMs:0,N(W)}else!p&&P.code==="id-taken"&&N(se("id-taken","peer id still held; retrying"));break;case"peer-joined":typeof P.id=="string"&&!_.has(P.id)&&(_.add(P.id),h.onPeerJoined?.(P.id));break;case"peer-left":typeof P.id=="string"&&(_.delete(P.id),h.onPeerLeft?.(P.id));break;case"signal":typeof P.from=="string"&&h.onSignal?.(P.from,P.data);break}},E.onerror=()=>{if(!b&&!p&&T>1){p=!0,l=(l+1)%a.length,A(R,T-1).then(w,S);return}N(se("signaling-unreachable",`cannot reach ${a[l]}`))},E.onclose=()=>{clearInterval(v),N(se("signaling-closed","signalling closed before joining")),y&&!g&&f===E&&O()}}),k=R=>{f&&f.readyState===1?f.send(JSON.stringify(R)):g||C.push(R)},O=()=>{h.onDisconnect?.();let R=()=>{g||M(!0).catch(T=>{if(g||T&&(T.code==="room-full"||Ks.includes(T.code))){h.onDisconnect?.(T);return}setTimeout(R,Math.max(Z(x++,{baseMs:500,maxMs:15e3}),T&&T.retryMs||0))})};setTimeout(R,Z(x++,{baseMs:300,maxMs:15e3}))};return{...await M(!1),send:(R,T)=>k({t:"signal",to:R,data:T}),leave:()=>{if(!g){g=!0,clearInterval(v);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"}),Zs=i=>typeof i=="string"&&Si[i.toLowerCase()]||i,Qs=Object.freeze({accent:"--dxr-accent",ink:"--dxr-ink",shell:"--dxr-shell",danger:"--dxr-danger",radius:"--dxr-radius",font:"--dxr-font"}),nt=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 eo(i){let e={...nt,...i&&typeof i=="object"?i:{}};return(t,n)=>{let r=typeof e[t]=="string"?e[t]:nt[t]||t;if(n)for(let[s,o]of Object.entries(n))r=r.split(`{${s}}`).join(String(o));return r}}var Js="dxr-call-style",xl=`
|
|
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);
|
|
@@ -102,4 +102,4 @@ output.color1 = getPickDepth();
|
|
|
102
102
|
.dxr-call-depth{display:flex;align-items:center;gap:6px;padding:0 8px;font-size:12px;opacity:.9;}
|
|
103
103
|
.dxr-call-depth input{width:110px;accent-color:var(--dxr-accent);}
|
|
104
104
|
.dxr-call-note{font-size:12px;opacity:.65;}
|
|
105
|
-
`;function Zs(i=document){if(i.getElementById(qs))return;let e=i.createElement("style");e.id=qs,e.textContent=ml,(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 L(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);Re();var eo="[inline3d/call]",gl="https://github.com/DisplayXR/displayxr-browser",to=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"}),Qs=new Set;function _l(i){Qs.has(i)||(Qs.add(i),console.warn(`${eo} option \`${i}\` is deprecated (removed in 1.31) \u2014 use ${to[i]}`))}function Mi(i={}){for(let _ of Object.keys(to))i[_]!==void 0&&_l(_);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 _=Ue(h);if(!_)throw new Error(`@displayxr/inline3d/call: room "${h}" is not a valid room id (16-64 base64url chars) or invite link`);h=_}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 m=e.accent!==void 0?e.accent:i.accent,f={};for(let[_,C]of Object.entries(Ks)){let S=_==="accent"?m:e[_];typeof S=="string"&&S?f[C]=_==="accent"?Ys(S):S:typeof S=="number"&&_==="radius"&&(f[C]=`${S}px`)}let g=t.base!==void 0?t.base:i.inviteBase,x=t.updateUrl!==void 0?t.updateUrl:i.updateUrl,v=n.browserUrl!==void 0?n.browserUrl:i.browserUrl;return{room:h,signaling:i.signaling||Pe(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:We(i.mono3D),maxPeers:Ye(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 v=="string"?v:gl,allow2D:n.allow2D===void 0?!0:!!n.allow2D},debug:!!i.debug,log:typeof i.log=="function"?i.log:i.debug?(_,C)=>console.log(`${eo} ${_} ${JSON.stringify(C)}`):null,_liftImporter:typeof i._liftImporter=="function"?i._liftImporter:void 0,_convGrab:typeof i._convGrab=="function"?i._convGrab:void 0}}var Yc=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:",vl=["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()),no=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},H=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",H(e("room")));let r=H(e("signaling"));r&&(t.signaling=Pe(r,H(e("key"))?{key:H(e("key"))}:{})),n("key",H(e("key"))),n("camera",H(e("camera"))),n("layout",H(e("layout"))),n("maxPeers",no(e("max-peers")));let s=H(e("ui"));oe(e("no-ui"))?t.ui=!1:s==="tiles"&&(t.ui="tiles"),oe(e("auto-join"))&&(t.autoJoin=!0);let o=H(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),H(e("cursor"))==="depth"&&(t.cursor="depth"),n("name",H(e("name")));let a={accent:H(e("accent")),tileAspect:H(e("tile-aspect"))==="fill"?"fill":no(e("tile-aspect"))};return(a.accent!==void 0||a.tileAspect!==void 0)&&(t.theme=Object.fromEntries(Object.entries(a).filter(([,l])=>l!==void 0))),H(e("invite-base"))&&(t.invite={base:H(e("invite-base"))}),H(e("browser-url"))&&(t.landing={browserUrl:H(e("browser-url"))}),oe(e("debug"))&&(t.debug=!0),t}var yl=typeof HTMLElement=="function"?HTMLElement:class{},Le=class i extends yl{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=vl.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!==Le&&console.warn(`${Ei} <${i}> is already defined by another class; leaving it`),!1):(e.define(i,Le),!0)}Ct();var wl=200,io=240,bl=new Set(["I420","I420A","I422","I444","NV12"]),it=()=>globalThis.performance?performance.now():Date.now();async function Ti(i,{eyeMax:e=io,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&&bl.has(h.format))try{let u=h.visibleRect?h.visibleRect.width:h.displayWidth,d=h.visibleRect?h.visibleRect.height:h.displayHeight,m=new Uint8Array(h.allocationSize()),f=await h.copyTo(m),g=it(),x=Math.max(1,Math.ceil(u/2/e)),v=Lr(m,f[0].offset,f[0].stride,u,d,x);return{img:v.img,w:v.w,h:v.h,scale:v.w/u,via:"videoframe",readMs:it()-g}}catch{return null}finally{h.close()}h&&h.close()}let s=it(),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:it()-s}}catch{return null}}function ro({intervalMs:i=wl,eyeMax:e=io,grab:t=Ti,now:n=it}={}){let r=ce(),s=Se(),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 m=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(m!==l)return null;let g=n(),x=f?r.measure(f.img,f.w,f.h,d):null,v=s.push(x?x.d/f.scale:null),_=u&&u.videoWidth;return{d:v,frac:v!==null&&_>0?v/(_/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{m===l&&(a=!1)}},reset(){l++,a=!1,o=-1/0,r.reset(),s.reset()}}}var so=i=>U(Ar(i))||U((Tr(i)||{}).appName)||null,rh=Object.freeze({width:2560,height:720,frameRate:30});function oo(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)||so(i&&i.label)||so(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]",xl=2e3,Sl=2500,Ml=500,Ai=.02,El=4,Cl=2,co=200,Rl=240,kl=66;async function ho(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 dt(n.wallOptions);return ho(r,i,n)}var Oi=class{constructor(e,t,n){this.o=n,this.t=Js(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"?Ue(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=Ve(Tn),this._convGate=Ve(ur,20),this._convMeter=ro({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,m)=>this.log(d,m),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 m=d.code==="camera-busy";if(this.error(m?"camera-busy":d.code||"no-camera",m?`${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=m?"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,"",vt(location.href,this.room))}catch{}this._setState("joining");let e=new qe({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 rt(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 rt(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()},Sl))}_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,yt(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=oo(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=yt(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 m=()=>r.removeEventListener?.("ended",d),f=this.content;if(this.content={track:r,stream:s,desc:h,off:f&&f.track===r?f.off:m},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(yt({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(),co)}_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 vt(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 dt()}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),Ml)}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 m=a.remote.muted?0:a.level||0;a.setSpeaking(m>Ai||a.remote.speaking),m>Ai&&(!t||m>t.lvl)&&(t={id:o,lvl:m})}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;Zs(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=L("div",{class:"dxr-call-banner dxr-call-hidden",part:"banner"},[L("span",{text:t("banner2D")}),L("a",{href:this.o.landing.browserUrl,target:"_blank",rel:"noopener",text:t("bannerLink")})]),n.grid=L("div",{class:"dxr-call-grid",part:"grid","data-layout":this.o.layout,"data-n":"0"}),n.panel=L("div",{class:"dxr-call-panel dxr-call-hidden",part:"lobby"}),n.selfSlot=L("div",{class:"dxr-call-self",part:"self"}),n.bar=L("div",{class:"dxr-call-bar",part:"bar"}),n.foot=L("div",{class:"dxr-call-foot"},[n.selfSlot,n.bar]),n.invite=L("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="")=>L("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=L("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,L("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=L("input",{type:"text",readOnly:!0,value:r,"aria-label":s("inviteLink")});o.addEventListener("focus",()=>o.select());let a=L("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=L("canvas",{"aria-label":s("qrLabel"),role:"img"});try{Bs(l,r,{px:4})}catch{l.style.display="none"}e.append(L("h3",{text:t}),L("p",{text:n}),L("div",{class:"dxr-call-invite"},[L("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,m=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()}`:""}`,v=L("button",{class:"dxr-call-btn dxr-call-btn--primary",type:"button",text:this.state==="left"?n("rejoin"):n(d?"join":"start")});v.addEventListener("click",()=>this.join().catch(()=>{}));let _=L("select",{class:"dxr-call-select","aria-label":n("cameraSelect")});this._fillCameras(_),_.addEventListener("change",()=>this.setCamera(_.value).catch(S=>this.error("camera-failed",S.message,S)));let C=!u||!u.videoTrack?L("button",{class:"dxr-call-btn",type:"button",text:n("retryCamera")}):null;C?.addEventListener("click",()=>this.retryCamera().catch(()=>{})),c.append(L("h3",{text:m}),L("p",{text:x}),L("div",{class:"dxr-call-row"},[this.state==="full"?null:v,C,_]))}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(L("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:gt,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)=>L("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 uo(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 Tl=(i,e)=>Math.max(.3,Math.min(4,i/e));function Al(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 ao(i,e,{eyeHalf:t=null,mirror:n=!1}={}){if(!Al(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 rt=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=$e(),this.autoTrack=Se(),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=Ve(Tn),this.convGate=Ve(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=L("canvas"),this.cover=L("div",{class:"dxr-call-cover dxr-call-hidden"}),this.badge=L("div",{class:"dxr-call-badge",part:"badge"}),this.plate=L("div",{class:"dxr-call-state",part:"plate",text:e.t("connecting")}),this.stage=L("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=uo(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=L("div",r,[this.stage,L("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=Tl(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())},xl)}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(L("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++>=Cl)&&(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++>=El)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||ao(this.canvas,this.video):ao(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}=He(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 m=this.call.o.autoConverge,f=m?this._senderFrac(performance.now()):null;f!==null&&(this.conv.measuredPx=f*r),(c||m&&f===null)&&this._sampleDisparity(e,t,n,c)}let h=this.conv.step(r),u=l.getContext("2d"),d=[];for(let m of[0,1]){let f=d[m]=q(r,n,s,h,m);u.drawImage(e,m*r+f.sx,f.sy,f.sw,f.sh,m*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?kl:co))return;this.autoAt=s,this.autoPending=!0;let o=this.autoGen;this.autoCanvas||(this.autoCanvas=document.createElement("canvas")),Ti(e,{eyeMax:Rl,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 rt{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(L("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=L("canvas"),this.badge=L("div",{class:"dxr-call-badge",part:"badge"}),this.plate=L("div",{class:"dxr-call-state dxr-call-hidden",part:"plate"}),this.stage=L("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=L("div",{class:"dxr-call-tile dxr-call-tile--self",part:"tile","data-dxr-peer":"self"},[this.stage,L("div",{class:"dxr-call-talk"})]),t.appendChild(this.el),this._box=null,this._rwP=null,this._unobserve=uo(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(L("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,frameAgeMs:null}}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)}},Ol="1.31",lo=new Set;function F(i,e,t){let n=()=>{lo.has(i)||(lo.add(i),console.warn(`${Y} \`${i}\` is internal and leaves '@displayxr/inline3d/call' in ${Ol} \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 bh=F("normalizeCallOptions","js/call/options.js",Mi),xh=F("newRoomId","js/call/wire.js",An),Sh=F("isValidRoomId","js/call/wire.js",we),Mh=F("buildInviteLink","js/call/wire.js",vt),Eh=F("normalizeHello","js/call/wire.js",On),Ch=F("makeHello","js/call/wire.js",Dn),Rh=F("routeFor","js/call/wire.js",Fn),kh=F("badgeFor","js/call/wire.js",Nn),Th=F("createLiveGate","js/call/wire.js",jn),Ah=F("convergenceShiftPx","js/camera/converge.js",ft),Oh=F("lowPass","js/camera/converge.js",mt),Dh=F("clampShift","js/camera/converge.js",pt),Ph=F("eyeCropRect","js/camera/geometry.js",q),Lh=F("mirrorSwapOps","js/camera/geometry.js",ve),Ih=F("mirrorSwapPixels","js/camera/geometry.js",Rn),Fh=F("maxBitrateKbps","js/call/wire.js",Be),Nh=F("measureFocusDisparity","js/camera/disparity.js",$n),jh=F("preferVideoCodecs","js/call/sdp.js",Ge),Wh=F("sortCodecCapabilities","js/call/sdp.js",wt),zh=F("VIDEO_CODEC_ORDER","js/call/sdp.js",Xe),Hh=F("MeshTransport","js/call/transport.js",qe),$h=F("clampMaxPeers","js/call/transport.js",Ye),Uh=F("qrEncode","js/call/qr.js",bi),Vh=F("roomKey","js/call/signaling.js",xi);var Bh=F("PLATE_TEXT","js/call/ui.js (CALL_STRINGS)",Object.freeze({unreachable:nt.unreachable,cameraBusy:nt.cameraBusy})),Xh=F("CALL_ACCENTS","js/call/ui.js",Si),Gh=F("normalizeMono3D","js/call/lift.js",We),qh=F("resolveLift","js/call/lift.js",nn),Yh=F("createLiftPool","js/call/lift.js",on),Kh=F("createFrameWatch","js/call/lift.js",sn),Jh=F("liftConvergenceFor","js/call/lift.js",je),Zh=F("liftPriorityFor","js/call/lift.js",st),Qh=F("setLiftPriority","js/call/lift.js",rn),eu=F("defaultLiftSpecifier","js/call/lift.js",tn),tu=F("LIFT_PRIORITY","js/call/lift.js",Ne);Jt();Pi(()=>new URL("./lift.js",import.meta.url).href);export{Ci as CALL_EVENT_PREFIX,Ws as CAMERA_SDK,Kt as DXR_SIGNAL_DEFAULT,Le as DxrCallElement,ho as addCall,vi as addCameraView,Ri as attrsToOpts,or as createInline3D,Jt as defineCallElement,Pe as dxrSignaling,rr as inline3DAvailable,Yt as isStereoCamera,ki as mountCall,_i as openCamera,Ue as parseInviteLink,Bn as parseStereoXmp,Vr as readJpegStereoMeta,Xn as readJpegXmp,Jr as readWebmStereoMeta,dt as sharedInline3D,qt as suggestedName};
|
|
105
|
+
`;function to(i=document){if(i.getElementById(Js))return;let e=i.createElement("style");e.id=Js,e.textContent=xl,(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 I(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);Re();var io="[inline3d/call]",Sl="https://github.com/DisplayXR/displayxr-browser",ro=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"}),no=new Set;function Ml(i){no.has(i)||(no.add(i),console.warn(`${io} option \`${i}\` is deprecated (removed in 1.31) \u2014 use ${ro[i]}`))}function Mi(i={}){for(let _ of Object.keys(ro))i[_]!==void 0&&Ml(_);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 _=Ue(h);if(!_)throw new Error(`@displayxr/inline3d/call: room "${h}" is not a valid room id (16-64 base64url chars) or invite link`);h=_}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 m=e.accent!==void 0?e.accent:i.accent,f={};for(let[_,C]of Object.entries(Qs)){let M=_==="accent"?m:e[_];typeof M=="string"&&M?f[C]=_==="accent"?Zs(M):M:typeof M=="number"&&_==="radius"&&(f[C]=`${M}px`)}let g=t.base!==void 0?t.base:i.inviteBase,x=t.updateUrl!==void 0?t.updateUrl:i.updateUrl,v=n.browserUrl!==void 0?n.browserUrl:i.browserUrl;return{room:h,signaling:i.signaling||Pe(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:ze(i.mono3D),maxPeers:Ye(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 v=="string"?v:Sl,allow2D:n.allow2D===void 0?!0:!!n.allow2D},debug:!!i.debug,log:typeof i.log=="function"?i.log:i.debug?(_,C)=>console.log(`${io} ${_} ${JSON.stringify(C)}`):null,_liftImporter:typeof i._liftImporter=="function"?i._liftImporter:void 0,_convGrab:typeof i._convGrab=="function"?i._convGrab:void 0}}var rh=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:",El=["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()),so=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},H=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",H(e("room")));let r=H(e("signaling"));r&&(t.signaling=Pe(r,H(e("key"))?{key:H(e("key"))}:{})),n("key",H(e("key"))),n("camera",H(e("camera"))),n("layout",H(e("layout"))),n("maxPeers",so(e("max-peers")));let s=H(e("ui"));oe(e("no-ui"))?t.ui=!1:s==="tiles"&&(t.ui="tiles"),oe(e("auto-join"))&&(t.autoJoin=!0);let o=H(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),H(e("cursor"))==="depth"&&(t.cursor="depth"),n("name",H(e("name")));let a={accent:H(e("accent")),tileAspect:H(e("tile-aspect"))==="fill"?"fill":so(e("tile-aspect"))};return(a.accent!==void 0||a.tileAspect!==void 0)&&(t.theme=Object.fromEntries(Object.entries(a).filter(([,l])=>l!==void 0))),H(e("invite-base"))&&(t.invite={base:H(e("invite-base"))}),H(e("browser-url"))&&(t.landing={browserUrl:H(e("browser-url"))}),oe(e("debug"))&&(t.debug=!0),t}var Cl=typeof HTMLElement=="function"?HTMLElement:class{},Le=class i extends Cl{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=El.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!==Le&&console.warn(`${Ei} <${i}> is already defined by another class; leaving it`),!1):(e.define(i,Le),!0)}Ct();var Rl=200,oo=240,kl=new Set(["I420","I420A","I422","I444","NV12"]),it=()=>globalThis.performance?performance.now():Date.now();async function Ti(i,{eyeMax:e=oo,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&&kl.has(h.format))try{let u=h.visibleRect?h.visibleRect.width:h.displayWidth,d=h.visibleRect?h.visibleRect.height:h.displayHeight,m=new Uint8Array(h.allocationSize()),f=await h.copyTo(m),g=it(),x=Math.max(1,Math.ceil(u/2/e)),v=Nr(m,f[0].offset,f[0].stride,u,d,x);return{img:v.img,w:v.w,h:v.h,scale:v.w/u,via:"videoframe",readMs:it()-g}}catch{return null}finally{h.close()}h&&h.close()}let s=it(),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:it()-s}}catch{return null}}function ao({intervalMs:i=Rl,eyeMax:e=oo,grab:t=Ti,now:n=it}={}){let r=ce(),s=Se(),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 m=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(m!==l)return null;let g=n(),x=f?r.measure(f.img,f.w,f.h,d):null,v=s.push(x?x.d/f.scale:null),_=u&&u.videoWidth;return{d:v,frac:v!==null&&_>0?v/(_/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{m===l&&(a=!1)}},reset(){l++,a=!1,o=-1/0,r.reset(),s.reset()}}}var lo=i=>U(Pr(i))||U((Dr(i)||{}).appName)||null,fh=Object.freeze({width:2560,height:720,frameRate:30});function co(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)||lo(i&&i.label)||lo(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]",Tl=2e3,Al=2500,Ol=500,Ai=.02,Dl=4,Pl=2,fo=200,Ll=240,Il=66;async function po(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 dt(n.wallOptions);return po(r,i,n)}var Oi=class{constructor(e,t,n){this.o=n,this.t=eo(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"?Ue(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=Ve(Tn),this._convGate=Ve(ur,20),this._convMeter=ao({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,m)=>this.log(d,m),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 m=d.code==="camera-busy";if(this.error(m?"camera-busy":d.code||"no-camera",m?`${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=m?"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,"",vt(location.href,this.room))}catch{}this._setState("joining");let e=new qe({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 rt(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 rt(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()},Al))}_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,yt(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=co(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=yt(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 m=()=>r.removeEventListener?.("ended",d),f=this.content;if(this.content={track:r,stream:s,desc:h,off:f&&f.track===r?f.off:m},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(yt({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(),fo)}_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 vt(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 dt()}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),Ol)}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 m=a.remote.muted?0:a.level||0;a.setSpeaking(m>Ai||a.remote.speaking),m>Ai&&(!t||m>t.lvl)&&(t={id:o,lvl:m})}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;to(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=I("div",{class:"dxr-call-banner dxr-call-hidden",part:"banner"},[I("span",{text:t("banner2D")}),I("a",{href:this.o.landing.browserUrl,target:"_blank",rel:"noopener",text:t("bannerLink")})]),n.grid=I("div",{class:"dxr-call-grid",part:"grid","data-layout":this.o.layout,"data-n":"0"}),n.panel=I("div",{class:"dxr-call-panel dxr-call-hidden",part:"lobby"}),n.selfSlot=I("div",{class:"dxr-call-self",part:"self"}),n.bar=I("div",{class:"dxr-call-bar",part:"bar"}),n.foot=I("div",{class:"dxr-call-foot"},[n.selfSlot,n.bar]),n.invite=I("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="")=>I("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=I("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,I("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=I("input",{type:"text",readOnly:!0,value:r,"aria-label":s("inviteLink")});o.addEventListener("focus",()=>o.select());let a=I("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=I("canvas",{"aria-label":s("qrLabel"),role:"img"});try{qs(l,r,{px:4})}catch{l.style.display="none"}e.append(I("h3",{text:t}),I("p",{text:n}),I("div",{class:"dxr-call-invite"},[I("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,m=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()}`:""}`,v=I("button",{class:"dxr-call-btn dxr-call-btn--primary",type:"button",text:this.state==="left"?n("rejoin"):n(d?"join":"start")});v.addEventListener("click",()=>this.join().catch(()=>{}));let _=I("select",{class:"dxr-call-select","aria-label":n("cameraSelect")});this._fillCameras(_),_.addEventListener("change",()=>this.setCamera(_.value).catch(M=>this.error("camera-failed",M.message,M)));let C=!u||!u.videoTrack?I("button",{class:"dxr-call-btn",type:"button",text:n("retryCamera")}):null;C?.addEventListener("click",()=>this.retryCamera().catch(()=>{})),c.append(I("h3",{text:m}),I("p",{text:x}),I("div",{class:"dxr-call-row"},[this.state==="full"?null:v,C,_]))}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(I("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:gt,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)=>I("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 mo(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 Fl=(i,e)=>Math.max(.3,Math.min(4,i/e));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 ho(i,e,{eyeHalf:t=null,mirror:n=!1}={}){if(!Nl(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 rt=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=$e(),this.autoTrack=Se(),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=Ve(Tn),this.convGate=Ve(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=I("canvas"),this.cover=I("div",{class:"dxr-call-cover dxr-call-hidden"}),this.badge=I("div",{class:"dxr-call-badge",part:"badge"}),this.plate=I("div",{class:"dxr-call-state",part:"plate",text:e.t("connecting")}),this.stage=I("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=mo(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=I("div",r,[this.stage,I("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=Fl(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())},Tl)}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(I("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++>=Pl)&&(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++>=Dl)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||ho(this.canvas,this.video):ho(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}=He(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 m=this.call.o.autoConverge,f=m?this._senderFrac(performance.now()):null;f!==null&&(this.conv.measuredPx=f*r),(c||m&&f===null)&&this._sampleDisparity(e,t,n,c)}let h=this.conv.step(r),u=l.getContext("2d"),d=[];for(let m of[0,1]){let f=d[m]=q(r,n,s,h,m);u.drawImage(e,m*r+f.sx,f.sy,f.sw,f.sh,m*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?Il:fo))return;this.autoAt=s,this.autoPending=!0;let o=this.autoGen;this.autoCanvas||(this.autoCanvas=document.createElement("canvas")),Ti(e,{eyeMax:Ll,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 rt{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(I("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=I("canvas"),this.badge=I("div",{class:"dxr-call-badge",part:"badge"}),this.plate=I("div",{class:"dxr-call-state dxr-call-hidden",part:"plate"}),this.stage=I("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=I("div",{class:"dxr-call-tile dxr-call-tile--self",part:"tile","data-dxr-peer":"self"},[this.stage,I("div",{class:"dxr-call-talk"})]),t.appendChild(this.el),this._box=null,this._rwP=null,this._unobserve=mo(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(I("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,frameAgeMs:null}}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)}},jl="1.31",uo=new Set;function F(i,e,t){let n=()=>{uo.has(i)||(uo.add(i),console.warn(`${Y} \`${i}\` is internal and leaves '@displayxr/inline3d/call' in ${jl} \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 Ah=F("normalizeCallOptions","js/call/options.js",Mi),Oh=F("newRoomId","js/call/wire.js",An),Dh=F("isValidRoomId","js/call/wire.js",we),Ph=F("buildInviteLink","js/call/wire.js",vt),Lh=F("normalizeHello","js/call/wire.js",On),Ih=F("makeHello","js/call/wire.js",Dn),Fh=F("routeFor","js/call/wire.js",Fn),Nh=F("badgeFor","js/call/wire.js",Nn),jh=F("createLiveGate","js/call/wire.js",jn),zh=F("convergenceShiftPx","js/camera/converge.js",ft),Wh=F("lowPass","js/camera/converge.js",mt),Hh=F("clampShift","js/camera/converge.js",pt),$h=F("eyeCropRect","js/camera/geometry.js",q),Uh=F("mirrorSwapOps","js/camera/geometry.js",ve),Vh=F("mirrorSwapPixels","js/camera/geometry.js",Rn),Bh=F("maxBitrateKbps","js/call/wire.js",Be),Xh=F("measureFocusDisparity","js/camera/disparity.js",$n),Gh=F("preferVideoCodecs","js/call/sdp.js",Ge),qh=F("sortCodecCapabilities","js/call/sdp.js",wt),Yh=F("VIDEO_CODEC_ORDER","js/call/sdp.js",Xe),Kh=F("MeshTransport","js/call/transport.js",qe),Jh=F("clampMaxPeers","js/call/transport.js",Ye),Zh=F("qrEncode","js/call/qr.js",bi),Qh=F("roomKey","js/call/signaling.js",xi);var eu=F("PLATE_TEXT","js/call/ui.js (CALL_STRINGS)",Object.freeze({unreachable:nt.unreachable,cameraBusy:nt.cameraBusy})),tu=F("CALL_ACCENTS","js/call/ui.js",Si),nu=F("normalizeMono3D","js/call/lift.js",ze),iu=F("resolveLift","js/call/lift.js",nn),ru=F("createLiftPool","js/call/lift.js",on),su=F("createFrameWatch","js/call/lift.js",sn),ou=F("liftConvergenceFor","js/call/lift.js",je),au=F("liftPriorityFor","js/call/lift.js",st),lu=F("setLiftPriority","js/call/lift.js",rn),cu=F("defaultLiftSpecifier","js/call/lift.js",tn),hu=F("LIFT_PRIORITY","js/call/lift.js",Ne);Jt();Pi(()=>new URL("./lift.js",import.meta.url).href);export{Ci as CALL_EVENT_PREFIX,$s as CAMERA_SDK,Kt as DXR_SIGNAL_DEFAULT,Le as DxrCallElement,po as addCall,vi as addCameraView,Ri as attrsToOpts,or as createInline3D,Jt as defineCallElement,Pe as dxrSignaling,rr as inline3DAvailable,Yt as isStereoCamera,ki as mountCall,_i as openCamera,Ue as parseInviteLink,Bn as parseStereoXmp,Gr as readJpegStereoMeta,Xn as readJpegXmp,es as readWebmStereoMeta,dt as sharedInline3D,qt as suggestedName};
|