@rr0/ufoathome 0.170.0 → 0.170.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./BeamSystem-DXTXXbc7.js","./LaserBeam-DJnJ5Okd.js","./BeamEditor-ihmgiAKc.js","./ParameterForm-DDUXscnR.js","./TimelineTracks-Cjs12pO0.js","./LaunchSimulation-ClGdZJHr.js","./LaunchPlume-DwOSrKP_.js","./LaunchEditor-B4e1HRMn.js","./ReentryEditor-7E16l_ix.js","./ContrailSystem-CcDlnjiD.js","./ContrailGrowth-DwHS8If9.js","./LanternEditor-CcBPfbIH.js","./trafficRuntime-cS8H9PlA.js"])))=>i.map(i=>d[i]);
2
- const CA="modulepreload",PA=function(o,t){return new URL(o,t).href},Qv={},$t=function(t,e,i){let n=Promise.resolve();if(e&&e.length>0){let r=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};const a=document.getElementsByTagName("link"),c=document.querySelector("meta[property=csp-nonce]"),l=c?.nonce||c?.getAttribute("nonce");n=r(e.map(h=>{if(h=PA(h,i),h in Qv)return;Qv[h]=!0;const u=h.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(!!i)for(let m=a.length-1;m>=0;m--){const g=a[m];if(g.href===h&&(!u||g.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${d}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":CA,u||(p.as="script"),p.crossOrigin="",p.href=h,l&&p.setAttribute("nonce",l),document.head.appendChild(p),u)return new Promise((m,g)=>{p.addEventListener("load",m),p.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${h}`)))})}))}function s(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return n.then(r=>{for(const a of r||[])a.status==="rejected"&&s(a.reason);return t().catch(s)})},$S=Math.PI/180,P0=111320;function ae(o,t,e,i){const n=P0*Math.cos(e*$S),s=(o-e)*P0;return{x:(t-i)*n,z:-s}}function Is(o,t,e,i){const n=P0*Math.cos(e*$S),s=-t,r=o;return{lat:e+s/P0,lng:i+r/n}}class Fl{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(t,e,i){const n=t.event.place?.[0],s=t.observerTrack;if(!n)return 0;const r=m=>{const g=s.getInterpolatedPoseAt(Math.max(0,m));if(!g||g.lat===void 0||g.lng===void 0)return;const M=ae(g.lat,g.lng,n.lat,n.lng);return{eastM:M.x,northM:-M.z,heading:g.headingDeg}},a=r(e-Fl.HALF_SPAN_MS),c=r(e+Fl.HALF_SPAN_MS),l=r(e);if(!a||!c||!l)return 0;const h=Math.hypot(c.eastM-a.eastM,c.northM-a.northM),u=2*Fl.HALF_SPAN_MS/1e3;if(h/u<Fl.MIN_SPEED_MS)return 0;const d=i.heightAt(c.eastM,c.northM)-i.heightAt(a.eastM,a.northM),f=Math.atan2(d,h)*180/Math.PI;if(l.heading===void 0)return f;const p=Math.atan2(c.eastM-a.eastM,c.northM-a.northM)*180/Math.PI;return f*Math.max(0,Math.cos((l.heading-p)*Math.PI/180))}}class Iu{static ISO=/^P(?:(\d+(?:[.,]\d+)?)W)?(?:(\d+(?:[.,]\d+)?)D)?(?:T(?:(\d+(?:[.,]\d+)?)H)?(?:(\d+(?:[.,]\d+)?)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;static seconds(t){const e=t.trim().toUpperCase(),i=Iu.ISO.exec(e);if(!i||e==="P"||e.endsWith("T"))return;const[,n,s,r,a,c]=i,l=u=>u===void 0?0:Number(u.replace(",",".")),h=l(n)*604800+l(s)*86400+l(r)*3600+l(a)*60+l(c);return Number.isFinite(h)?h:void 0}static parse(t){let e=t.trim();if(e==="")return;const i=e.slice(-1),n="?~%".includes(i)?i:"";n!==""&&(e=e.slice(0,-1).trim());const s=e.split("/");if(s.length>2)return;const r=s.map(u=>Iu.seconds(u));if(r.some(u=>u===void 0))return;const[a,c]=r,l=Math.min(a,c??a),h=Math.max(a,c??a);return{doubt:n,minSeconds:l,maxSeconds:h,chosenSeconds:(l+h)/2}}static isExact(t){const e=Iu.parse(t);return e!==void 0&&e.doubt===""&&e.minSeconds===e.maxSeconds}static format(t){const e=Math.max(0,Math.round(t*10)/10),i=Math.floor(e/3600),n=Math.floor(e%3600/60),s=Math.round(e%60*10)/10;return`PT${`${i>0?`${i}H`:""}${n>0?`${n}M`:""}${s>0||i===0&&n===0?`${s}S`:""}`}`}static say(t){const e=Math.round(t*10)/10;if(e<60)return`${e} s`;const i=Math.floor(e/3600),n=Math.floor(e%3600/60),s=Math.round(e%60*10)/10,r=[];return i>0&&r.push(`${i} h`),n>0&&r.push(`${n} min`),s>0&&r.push(`${s} s`),r.join(" ")}}class hi{static MOON_ANGULAR_WIDTH_DEG=.5237;static CANVAS_WIDTH_PX=640;static CANVAS_HEIGHT_PX=360;static angularWidthDeg(t){return 2*Math.atan(t.sizeM/(2*t.distanceM))*180/Math.PI}static inMoons(t){return t/hi.MOON_ANGULAR_WIDTH_DEG}static lerpAngular(t,e,i){if(!(!t||!e))return{widthDeg:t.widthDeg+(e.widthDeg-t.widthDeg)*i,heightDeg:t.heightDeg+(e.heightDeg-t.heightDeg)*i}}static sizeMAt(t,e){return 2*t*Math.tan(e*Math.PI/360)}static distanceMAt(t,e){return t/(2*Math.tan(e*Math.PI/360))}}function OA(o,t,e){if(!o||!t)return e<1?o:t;const i=((t.azimuthDeg-o.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((o.azimuthDeg+i*e)%360+360)%360,altitudeDeg:o.altitudeDeg+(t.altitudeDeg-o.altitudeDeg)*e}}function NA(o,t,e){const{bounds:i}=o;return t>=i.x&&t<=i.x+i.width&&e>=i.y&&e<=i.y+i.height}function Ss(o,t,e){return o+(t-o)*e}function ty(o){const t=/^#([0-9a-f]{6})$/i.exec(o);if(!t)return;const e=parseInt(t[1],16);return[e>>16&255,e>>8&255,e&255]}function LA(o){return`#${o.map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`}function kA(o,t,e){const i=ty(o),n=ty(t);return!i||!n?e<1?o:t:LA([Ss(i[0],n[0],e),Ss(i[1],n[1],e),Ss(i[2],n[2],e)])}function UA(o,t,e){const i={x:Ss(o.bounds.x,t.bounds.x,e),y:Ss(o.bounds.y,t.bounds.y,e),width:Ss(o.bounds.width,t.bounds.width,e),height:Ss(o.bounds.height,t.bounds.height,e)},n=Ss(o.angle,t.angle,e),s=Ss(o.transparency,t.transparency,e),r=Ss(o.haloScale,t.haloScale,e),a=Ss(o.blur??0,t.blur??0,e),c=Ss(o.brightness??0,t.brightness??0,e),l=kA(o.color,t.color,e),h=hi.lerpAngular(o.angular,t.angular,e),u=OA(o.aim,t.aim,e);return o.kind==="polygon"&&t.kind==="polygon"&&o.points.length===t.points.length?{...o,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:c,color:l,angular:h,aim:u,points:o.points.map((d,f)=>({x:Ss(d.x,t.points[f].x,e),y:Ss(d.y,t.points[f].y,e)}))}:{...e<1?o:t,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:c,color:l,angular:h,aim:u}}class go{static DEFAULT_COLOR="#e8e6df";static complete(t,e=[]){const i=new Map;return t.map((n,s)=>({keyframe:n,index:s})).sort((n,s)=>n.keyframe.t-s.keyframe.t).map(({keyframe:n,index:s})=>({t:n.t,shapes:(n.shapes??[]).map((r,a)=>{const c=`timeline.keyframes.${s}.shapes.${a}.shape`,l=go.completed(r,i.get(r.sourceId),c,e);return i.set(r.sourceId,l),{sourceId:r.sourceId,shape:l}})}))}static thin(t,e){const i=new Map,n=new Set;return t.map((s,r)=>({t:s.t,shapes:s.shapes.map(a=>{const c=i.get(a.sourceId);if(i.set(a.sourceId,a.shape),!c)return{sourceId:a.sourceId,shape:a.shape};const l=go.thinned(a.shape,c);if(e){const h=l;e(r,a.sourceId)?(delete h.bounds,delete h.points,n.add(a.sourceId)):n.delete(a.sourceId)&&(h.bounds=a.shape.bounds,a.shape.kind==="polygon"&&(h.points=a.shape.points),a.shape.aim&&(h.aim=a.shape.aim),a.shape.angular&&(h.angular=a.shape.angular))}return{sourceId:a.sourceId,shape:l}})}))}static thinned(t,e){const i=e,n={};for(const[s,r]of Object.entries(t))(typeof r=="object"&&r!==null&&!Array.isArray(r)&&"value"in r||r!==i[s]&&JSON.stringify(r)!==JSON.stringify(i[s]))&&(n[s]=r);return"bounds"in n&&(t.aim&&(n.aim=t.aim),t.angular&&(n.angular=t.angular)),n}static completed(t,e,i,n){const s=t.shape??{},r=e??go.firstAppearance(s,i,n),a={...r};s.bounds&&e&&(e.aim||e.angular)&&!s.aim&&!s.angular&&n.push({kind:"pixels-over-angles",path:i}),s.bounds&&(s.aim||delete a.aim,s.angular||delete a.angular);const c=s.kind??r.kind??"oval",l={...a,...s,kind:c};if(c==="polygon"&&!l.points){n.push({kind:"defaulted",path:`${i}.points`,expected:"rectangle"});const{width:h,height:u}=l.bounds;return{...l,points:[{x:0,y:0},{x:h,y:0},{x:h,y:u},{x:0,y:u}]}}return l}static firstAppearance(t,e,i){return t.kind||i.push({kind:"defaulted",path:`${e}.kind`,expected:'"oval"'}),t.color||i.push({kind:"defaulted",path:`${e}.color`,expected:`"${go.DEFAULT_COLOR}"`}),!t.bounds&&!t.aim&&i.push({kind:"unplaced",path:e}),!t.bounds&&!t.angular&&i.push({kind:"unsized",path:e}),{kind:t.kind??"oval",bounds:{...go.NEUTRAL_BOUNDS},color:go.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:hi.CANVAS_WIDTH_PX/2,y:hi.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Ud{keyframes=[];order=[];groups=[];span=0;addKeyframe(t,e){const i=this.findInsertIndex(t);if(this.keyframes[i]?.t===t){const n=new Set(e.map(s=>s.sourceId));this.keyframes[i]={t,shapes:[...this.keyframes[i].shapes.filter(s=>!n.has(s.sourceId)),...e]}}else this.keyframes.splice(i,0,{t,shapes:[...e]});for(const n of e)this.order.includes(n.sourceId)||this.order.push(n.sourceId)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getKeyframeAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e];return i?.t===t?i:void 0}getShapeAt(t,e){return this.getKeyframeAt(t)?.shapes.find(i=>i.sourceId===e)?.shape}getLatestShapeAt(t,e){let i=this.findInsertIndex(t);for(this.keyframes[i]?.t!==t&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return n.shape}}getInterpolatedShapeAt(t,e){const i=this.findShapeAtOrBefore(t,e);if(i?.t===t)return i.shape;const n=this.findShapeAtOrAfter(t,e);return i?n?UA(i.shape,n.shape,(t-i.t)/(n.t-i.t)):i.shape:n?.shape}findShapeAtOrBefore(t,e){let i=this.findInsertIndex(t);for(this.keyframes[i]?.t!==t&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}findShapeAtOrAfter(t,e){for(let i=this.findInsertIndex(t);i<this.keyframes.length;i++){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}hitTest(t,e,i,n){const s=this.sourceIds;for(let r=s.length-1;r>=0;r--){if(n?.has(s[r]))continue;const a=this.getInterpolatedShapeAt(t,s[r]);if(a&&NA(a,e,i))return{sourceId:s[r],shape:a}}}removeSource(t){for(let e=this.keyframes.length-1;e>=0;e--){const i=this.keyframes[e].shapes.filter(n=>n.sourceId!==t);i.length===0?this.keyframes.splice(e,1):i.length!==this.keyframes[e].shapes.length&&(this.keyframes[e]={t:this.keyframes[e].t,shapes:i})}this.order=this.order.filter(e=>e!==t),this.removeFromGroup(t)}removeShapeAt(t,e){const i=this.findInsertIndex(t),n=this.keyframes[i];if(n?.t!==t)return;const s=n.shapes.filter(r=>r.sourceId!==e);s.length===0?this.keyframes.splice(i,1):s.length!==n.shapes.length&&(this.keyframes[i]={t,shapes:s})}group(t,e){const i=new Set(t),n=[];for(const r of t){const a=this.topOf(r),c=a!==r&&this.leavesOf(a).every(l=>i.has(l))?a:r;c===r&&a!==r&&this.removeFromGroup(r),n.includes(c)||n.push(c)}if(n.length<2)return;const s=e??this.freshGroupId();return this.groups.push({id:s,members:n}),s}ungroup(t){const e=this.topOf(t);e!==t&&(this.groups=this.groups.filter(i=>i.id!==e))}groupMembers(t){const e=this.topOf(t);return e===t?void 0:this.leavesOf(e)}get allGroups(){return this.groups}setGroups(t,e=!0){this.groups=t.map(i=>({...i,members:[...i.members]})),e&&this.pruneGroups()}groupOf(t){return this.groups.find(e=>e.id===t)}leavesOf(t,e=new Set){const i=this.groupOf(t);return i?e.has(t)?[]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e))):[t]}parentOf(t){return this.groups.find(e=>e.members.includes(t))}topOf(t){let e=t;for(let i=this.parentOf(e),n=0;i&&n<100;i=this.parentOf(e),n++)e=i.id;return e}freshGroupId(){for(let t=this.groups.length+1;;t++){const e=`group-${t}`;if(!this.groupOf(e)&&!this.order.includes(e))return e}}removeFromGroup(t){const e=this.parentOf(t);e&&(e.members=e.members.filter(i=>i!==t),this.collapse())}pruneGroups(){const t=e=>this.order.includes(e)||this.groupOf(e)!==void 0;for(const e of this.groups)e.members=e.members.filter(t);this.collapse()}collapse(){for(let t=this.groups.find(e=>e.members.length<2);t;t=this.groups.find(e=>e.members.length<2)){const e=t;this.groups=this.groups.filter(i=>i!==e);for(const i of this.groups)i.members=i.members.flatMap(n=>n===e.id?e.members:[n])}}bringToFront(t){const e=this.order.indexOf(t);e!==-1&&(this.order.splice(e,1),this.order.push(t))}sendToBack(t){const e=this.order.indexOf(t);e!==-1&&(this.order.splice(e,1),this.order.unshift(t))}get duration(){const t=this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t;return Math.max(t,this.span)}get hasSpan(){return this.span>0}setSpan(t){this.span=Math.max(0,t)}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return this.span>0?{keyframes:this.keyframes,order:this.order,groups:this.groupsJson(),span:this.span}:{keyframes:this.keyframes,order:this.order,groups:this.groupsJson()}}groupsJson(){return this.groups.map(t=>({...t,members:[...t.members]}))}static fromJSON(t,e,i=!0){const n=new Ud;for(const s of go.complete(t.keyframes??[],e))n.addKeyframe(s.t,s.shapes);if(t.span!==void 0&&t.span>0&&(n.span=t.span),t.order){const s=n.order.filter(r=>!t.order.includes(r));n.order=[...t.order,...s]}return t.groups&&(n.groups=t.groups.filter(s=>typeof s?.id=="string"&&Array.isArray(s.members)).map(s=>({...s,members:[...s.members]})),i&&n.pruneGroups()),n}}function FA(o,t,e){return Math.max(t,Math.min(e,o))}function zA(o,t,e){const i=((t-o)%360+540)%360-180;return((o+i*e)%360+360)%360}function Kc(o,t,e){return o+(t-o)*e}function BA(o,t,e){return{lat:o.lat===void 0||t.lat===void 0?void 0:Kc(o.lat,t.lat,e),lng:o.lng===void 0||t.lng===void 0?void 0:Kc(o.lng,t.lng,e),elevationM:Kc(o.elevationM,t.elevationM,e),headingDeg:o.headingDeg===void 0||t.headingDeg===void 0?void 0:zA(o.headingDeg,t.headingDeg,e),pitchDeg:Kc(o.pitchDeg,t.pitchDeg,e),rollDeg:Kc(o.rollDeg??0,t.rollDeg??0,e),fovDeg:Kc(o.fovDeg,t.fovDeg,e),fNumber:o.fNumber,focusDistanceM:o.focusDistanceM,filter:o.filter}}class Mn{static at(t,e,i,n,s){const r=t[i],c=t[i+1]-r;if(c<=0)return e[i];const l=Mn.tangent(t,e,i,s),h=Mn.tangent(t,e,i+1,s),u=(n-r)/c,d=u*u,f=d*u;return(2*f-3*d+1)*e[i]+(f-2*d+u)*c*l+(-2*f+3*d)*e[i+1]+(f-d)*c*h}static SETTLE_MS=120;static ARRIVAL=.5;static gaze(t,e,i,n){const s=t[i],a=t[i+1]-s;if(a<=0)return e[i];const c=h=>h+1<e.length?e[h+1]===e[h]:!0,l=e[i+1]!==e[i];if(l&&c(i+1)){const h=Mn.tangent(t,e,i,!0),u=Mn.ARRIVAL*(e[i+1]-e[i])/a;return Mn.hermite(e[i],h,e[i+1],u,a,(n-s)/a)}return!l&&i>0&&e[i-1]!==e[i]?e[i]+Mn.settle(t,e,i,n-s,a):Mn.at(t,e,i,n,!0)}static settle(t,e,i,n,s){const r=t[i]-t[i-1];if(r<=0||n<=0)return 0;const a=Mn.ARRIVAL*(e[i]-e[i-1])/r,c=Math.min(Mn.SETTLE_MS,.4*r),l=Number.isFinite(s)?(1-Math.min(1,n/s))**2:1;return a*n*Math.exp(-n/c)*l}static hermite(t,e,i,n,s,r){const a=r*r,c=a*r;return(2*c-3*a+1)*t+(c-2*a+r)*s*e+(-2*c+3*a)*i+(c-a)*s*n}static BRAKE_S=.8;static paced(t,e,i,n){if(!i&&!n)return t;const s=e>0?Math.min(.5,Mn.BRAKE_S/e):.5;if(i&&n){const a=1/(1-s);return t<=s?a*t*t/(2*s):t>=1-s?1-a*(1-t)*(1-t)/(2*s):a*(t-s/2)}const r=a=>{const c=1/(1-s/2);if(a<=1-s)return c*a;const l=a-(1-s);return c*(1-s)+c*(l-l*l/(2*s))};return n?r(t):1-r(1-t)}static tangent(t,e,i,n){const s=t.length-1,r=f=>(e[f+1]-e[f])/(t[f+1]-t[f]||1);if(i===0)return n?0:r(0);if(i===s)return n?0:r(s-1);const a=r(i-1),c=r(i);if(a*c<=0)return 0;const l=t[i]-t[i-1],h=t[i+1]-t[i],u=2*h+l,d=h+2*l;return(u+d)/(u/a+d/c)}}class Zu{keyframes=[];addKeyframe(t,e){const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,pose:e}:this.keyframes.splice(i,0,{t,pose:e})}clear(){this.keyframes.length=0}removeKeyframeAt(t){const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getLatestPoseAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].pose:void 0}getInterpolatedPoseAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.pose;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];if(!i)return n?.pose;if(!n)return this.settledAfterEnd(e-1,t);const s=BA(i.pose,n.pose,FA((t-i.t)/(n.t-i.t),0,1));return this.humanly(e-1,t,s)}settledAfterEnd(t,e){const i=this.keyframes[t];if(t<1)return i.pose;const n=this.keyframes[t-1],s=[n.t,i.t],r=(h,u)=>h===void 0||u===void 0?0:Mn.settle(s,[h,u],1,e-i.t,1/0),a=n.pose.headingDeg===void 0||i.pose.headingDeg===void 0?void 0:((i.pose.headingDeg-n.pose.headingDeg)%360+540)%360-180,c=i.pose.headingDeg===void 0||a===void 0?i.pose.headingDeg:((i.pose.headingDeg+r(0,a))%360+360)%360,l=i.pose.pitchDeg+r(n.pose.pitchDeg,i.pose.pitchDeg);return c===i.pose.headingDeg&&l===i.pose.pitchDeg?i.pose:{...i.pose,headingDeg:c,pitchDeg:l}}humanly(t,e,i){const n=Math.max(0,t-1),s=Math.min(this.keyframes.length-1,t+2),r=this.keyframes.slice(n,s+1),a=t-n,c=r.map(y=>y.t),l=(y,w)=>{const b=r.map(E=>y(E.pose));if(!b.some(E=>E===void 0))return Mn.at(c,b,a,e,w)},h=y=>{const w=r.map(b=>y(b.pose));if(!w.some(b=>b===void 0))return Mn.gaze(c,w,a,e)},u=r.map(y=>y.pose.headingDeg);let d;if(u.every(y=>y!==void 0)){const y=[u[0]];for(let w=1;w<u.length;w++)y.push(y[w-1]+((u[w]-u[w-1])%360+540)%360-180);d=(Mn.gaze(c,y,a,e)%360+360)%360}const f=this.keyframes[t],p=this.keyframes[t+1],m=(y,w)=>y.lat===w.lat&&y.lng===w.lng&&y.elevationM===w.elevationM,g=!m(f.pose,p.pose),M=g&&t>0&&m(this.keyframes[t-1].pose,f.pose),v=g&&t+2<this.keyframes.length&&m(p.pose,this.keyframes[t+2].pose);let x;if(M||v){const y=Mn.paced((e-f.t)/(p.t-f.t),(p.t-f.t)/1e3,M,v),w=(b,E)=>b===void 0||E===void 0?void 0:b+(E-b)*y;x={lat:w(f.pose.lat,p.pose.lat),lng:w(f.pose.lng,p.pose.lng),elevationM:w(f.pose.elevationM,p.pose.elevationM)}}return{...i,lat:x?x.lat:l(y=>y.lat,!1)??i.lat,lng:x?x.lng:l(y=>y.lng,!1)??i.lng,elevationM:x?x.elevationM:l(y=>y.elevationM,!1)??i.elevationM,headingDeg:d??i.headingDeg,pitchDeg:h(y=>y.pitchDeg)??i.pitchDeg,rollDeg:l(y=>y.rollDeg??0,!0)??i.rollDeg,fovDeg:l(y=>y.fovDeg,!0)??i.fovDeg}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new Zu;for(const i of t.keyframes)e.addKeyframe(i.t,i.pose);return e}}class Mo{static MAX_CHANGE_PER_S=.05;points;followed;constructor(t){let e="none",i=0;this.points=t.map(({t:n,weather:s})=>(s.precipitationType!=="none"&&(e=s.precipitationType,i=s.precipitationIntensity),{t:n,lastFalling:e,lastFallingIntensity:i,intensity:s.precipitationType==="none"?0:s.precipitationIntensity,type:s.precipitationType})),this.followed=[];for(let n=0;n<this.points.length;n++){if(n===0){this.followed.push(this.points[0].intensity);continue}const s=this.points[n-1],r=this.points[n];this.followed.push(Mo.follow(this.followed[n-1],s.intensity,r.intensity,(r.t-s.t)/1e3,(r.t-s.t)/1e3))}}at(t){if(this.points.length===0||t<this.points[0].t)return;let e=this.points.length-1;for(;e>0&&this.points[e].t>t;)e--;const i=this.points[e],n=this.points[e+1],s=n?Mo.follow(this.followed[e],i.intensity,n.intensity,(n.t-i.t)/1e3,(t-i.t)/1e3):Mo.follow(this.followed[e],i.intensity,i.intensity,1,(t-i.t)/1e3);return{type:Mo.typeBetween(i,n,t,s),intensity:s,character:Mo.characterBetween(i,n,t)}}static characterBetween(t,e,i){return t.type==="none"?e&&e.type!=="none"?e.intensity:t.lastFallingIntensity:!e||e.type==="none"?t.intensity:t.intensity+(e.intensity-t.intensity)*(i-t.t)/(e.t-t.t||1)}static typeBetween(t,e,i,n){return t.type==="none"?e&&e.type!=="none"&&i>t.t?e.type:n>0?t.lastFalling:"none":e&&e.type==="none"&&n<=0?"none":t.type}static follow(t,e,i,n,s){const r=Mo.MAX_CHANGE_PER_S,a=n>0?(i-e)/n:0,c=u=>e+a*Math.min(Math.max(u,0),n);let l=t,h=0;for(let u=0;u<8&&h<s;u++){const d=c(h)-l;if(Math.abs(d)<1e-9){const x=h<n?a:0;if(Math.abs(x)<=r){const w=h<n?Math.min(s,n):s;l=c(w),h=w;continue}const y=Math.min(s,n);l+=Math.sign(x)*r*(y-h),h=y;continue}const f=Math.sign(d),p=h<n?a:0,m=r-f*p,g=m>0?h+Math.abs(d)/m:1/0,M=h<n?n:1/0,v=Math.min(s,g,M);l+=f*r*(v-h),h=v,v===g&&(l=c(h))}return Math.min(1,Math.max(0,l))}}const UM=1e3,HA=.65,GA=.05,yp={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function O0(o){if(o.cloudLayers!==void 0)return o.cloudLayers;const t=[],e=o.lowerCloudCover??o.cloudCover;return e>0&&t.push({id:"lower",type:"cumulus",baseM:o.cloudBaseM??UM,thicknessM:650,coverage:e,sizeM:1400,density:1,darkness:o.cloudDarkness}),(o.highCloudCover??0)>0&&t.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:o.highCloudCover,sizeM:2200,density:.35,darkness:o.cloudDarkness,iceCrystalAlignment:o.iceCrystalAlignment}),t}function Ei(o,t,e){return o+(t-o)*e}function FM(o,t,e){const i=((t-o)%360+540)%360-180;return((o+i*e)%360+360)%360}function VA(o,t,e){return Math.max(t,Math.min(e,o))}function WA(o=[],t=[],e){if(!(!o.length&&!t.length))return[...new Set([...o.map(i=>i.id),...t.map(i=>i.id)])].map(i=>{const n=o.find(c=>c.id===i),s=t.find(c=>c.id===i),r=n??{...s,density:0},a=s??{...n,density:0};return{...r,eastM:Ei(r.eastM,a.eastM,e),northM:Ei(r.northM,a.northM,e),baseM:Ei(r.baseM,a.baseM,e),thicknessM:Ei(r.thicknessM,a.thicknessM,e),widthM:Ei(r.widthM,a.widthM,e),depthM:Ei(r.depthM,a.depthM,e),rotationDeg:FM(r.rotationDeg,a.rotationDeg,e),density:Ei(r.density,a.density,e),darkness:Ei(r.darkness??0,a.darkness??0,e)}})}function XA(o,t,e){if(o.cloudLayers===void 0&&t.cloudLayers===void 0)return;const i=O0(o),n=O0(t);return e>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const a=i.find(u=>u.id===r),c=n.find(u=>u.id===r),l=a??{...c,coverage:0},h=c??{...a,coverage:0};return{...l,instances:WA(a?.instances,c?.instances,e),baseM:Ei(l.baseM,h.baseM,e),thicknessM:Ei(l.thicknessM,h.thicknessM,e),coverage:Ei(l.coverage,h.coverage,e),sizeM:Ei(l.sizeM,h.sizeM,e),density:Ei(l.density,h.density,e),darkness:Ei(l.darkness??o.cloudDarkness,h.darkness??t.cloudDarkness,e),iceCrystalAlignment:l.iceCrystalAlignment===void 0||h.iceCrystalAlignment===void 0?void 0:Ei(l.iceCrystalAlignment,h.iceCrystalAlignment,e),windSpeed:l.windSpeed===void 0&&h.windSpeed===void 0?void 0:Ei(l.windSpeed??o.windSpeed,h.windSpeed??t.windSpeed,e),windDirectionDeg:l.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:FM(l.windDirectionDeg??o.windDirectionDeg,h.windDirectionDeg??t.windDirectionDeg,e)}})}function YA(o,t,e){return{cloudLayers:XA(o,t,e),cloudCover:Ei(o.cloudCover,t.cloudCover,e),cloudDarkness:Ei(o.cloudDarkness,t.cloudDarkness,e),highCloudCover:o.highCloudCover===void 0||t.highCloudCover===void 0?void 0:Ei(o.highCloudCover,t.highCloudCover,e),iceCrystalAlignment:o.iceCrystalAlignment===void 0||t.iceCrystalAlignment===void 0?void 0:Ei(o.iceCrystalAlignment,t.iceCrystalAlignment,e),rareIceCrystals:o.rareIceCrystals===void 0||t.rareIceCrystals===void 0?void 0:Ei(o.rareIceCrystals,t.rareIceCrystals,e),lowerCloudCover:o.lowerCloudCover===void 0||t.lowerCloudCover===void 0?void 0:Ei(o.lowerCloudCover,t.lowerCloudCover,e),cloudBaseM:o.cloudBaseM===void 0||t.cloudBaseM===void 0?void 0:Ei(o.cloudBaseM,t.cloudBaseM,e),relativeHumidity:o.relativeHumidity===void 0||t.relativeHumidity===void 0?void 0:Ei(o.relativeHumidity,t.relativeHumidity,e),precipitationType:e<1?o.precipitationType:t.precipitationType,precipitationIntensity:Ei(o.precipitationIntensity,t.precipitationIntensity,e),windDirectionDeg:FM(o.windDirectionDeg,t.windDirectionDeg,e),windSpeed:Ei(o.windSpeed,t.windSpeed,e),storm:e<1?o.storm:t.storm}}class Ju{keyframes=[];ramp;addKeyframe(t,e){this.ramp=void 0;const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,weather:e}:this.keyframes.splice(i,0,{t,weather:e})}clear(){this.ramp=void 0,this.keyframes.length=0}removeKeyframeAt(t){this.ramp=void 0;const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getLatestWeatherAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].weather:void 0}getInterpolatedWeatherAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.weather;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];return i?n?YA(i.weather,n.weather,VA((t-i.t)/(n.t-i.t),0,1)):i.weather:n?.weather}getActualWeatherAt(t){const e=this.getInterpolatedWeatherAt(t);if(!e)return;const i=(this.ramp??=new Mo(this.keyframes)).at(t);if(!i)return e;const{type:n,intensity:s,character:r}=i,a=r>0?Math.min(1,s/r):n==="none"?0:1;return{...e,precipitationType:n,precipitationIntensity:r,precipitationAmount:a}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new Ju;for(const i of t.keyframes)e.addKeyframe(i.t,{...yp,...i.weather});return e}}class ju{keyframes=[];addKeyframe(t,e){const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,sound:e}:this.keyframes.splice(i,0,{t,sound:e})}clear(){this.keyframes.length=0}removeKeyframeAt(t){const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}getLatestSoundAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].sound:void 0}getInterpolatedSoundAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.sound;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];if(!i)return n?.sound;if(!n)return i.sound;const s=(t-i.t)/(n.t-i.t);return this.lerp(i.sound,n.sound,Math.max(0,Math.min(1,s)))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new ju;for(const i of t.keyframes)e.addKeyframe(i.t,i.sound);return e}lerp(t,e,i){return{kind:i<1?t.kind:e.kind,volume:t.volume+(e.volume-t.volume)*i,pitchHz:t.pitchHz+(e.pitchHz-t.pitchHz)*i,src:i<1?t.src:e.src}}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}}const $A=100,KA={kind:"none",volume:0,pitchHz:$A};class ea{static MAX_SPECKS=4;static BROADCAST_35MM={framesPerSecond:24,contrast:1.6,tint:[.99,.98,.92],softness:1.6/480,specksPerFrame:1.15,speckRadius:1.6/480,speckRadiusMax:4.5/480,weave:[.25/640,.6/480],grain:.008};static hash(t,e){const i=Math.sin(t*127.1+e*311.7)*43758.5453;return i-Math.floor(i)}static frameAt(t,e){return Math.floor(e*t.framesPerSecond/1e3)}static frame(t,e){const i=a=>ea.hash(e,a),n=a=>(i(a)+i(a+1)+i(a+2)-1.5)*2,s=Math.min(1,t.specksPerFrame/ea.MAX_SPECKS),r=[];for(let a=0;a<ea.MAX_SPECKS;a++){const c=10+a*6;if(i(c)>=s)continue;const l=i(c+3)**3;r.push({u:i(c+1),v:i(c+2),radius:t.speckRadius*.6+l*(t.speckRadiusMax-t.speckRadius*.6),kept:.25+.4*i(c+4)})}return{weave:[n(1)*t.weave[0],n(4)*t.weave[1]],specks:r,seed:i(7)}}}class zl{static DEFAULT_FOCAL_MM=50;static FOCAL_RANGE_MM={minMm:14,maxMm:135};static BODIES=[{id:"eos-450d",name:"Canon EOS 450D (APS-C)",widthMm:22.2,heightMm:14.8,pixelUm:5.2,year:2008},{id:"eos-60da",name:"Canon EOS 60Da (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.3,year:2012},{id:"eos-70d",name:"Canon EOS 70D (APS-C)",widthMm:22.5,heightMm:15,pixelUm:4.1,year:2013},{id:"eos-80d",name:"Canon EOS 80D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:3.7,year:2016},{id:"eos-7d",name:"Canon EOS 7D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.1,year:2009},{id:"eos-7d-ii",name:"Canon EOS 7D Mark II (APS-C)",widthMm:22.4,heightMm:15,pixelUm:4.1,year:2014},{id:"eos-5d",name:"Canon EOS 5D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:8.2,year:2005},{id:"eos-5d-ii",name:"Canon EOS 5D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:6.4,year:2008},{id:"eos-5d-iii",name:"Canon EOS 5D Mark III (full frame)",widthMm:36,heightMm:24,pixelUm:6.25,year:2012},{id:"eos-5d-iv",name:"Canon EOS 5D Mark IV (full frame)",widthMm:36,heightMm:24,pixelUm:5.36,year:2016},{id:"eos-6d",name:"Canon EOS 6D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:6.55,year:2012},{id:"eos-6d-ii",name:"Canon EOS 6D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:5.77,year:2017},{id:"nikon-d3",name:"Nikon D3 / D700 (full frame)",widthMm:36,heightMm:23.9,pixelUm:8.44,year:2007},{id:"nikon-d7000",name:"Nikon D7000 (DX)",widthMm:23.6,heightMm:15.6,pixelUm:4.78,year:2010},{id:"nikon-d7100",name:"Nikon D7100 / D7200 (DX)",widthMm:23.5,heightMm:15.6,pixelUm:3.9,year:2013},{id:"nikon-d500",name:"Nikon D500 / D7500 (DX)",widthMm:23.5,heightMm:15.7,pixelUm:4.2,year:2016}];static instruments(){return zl.BODIES.map(t=>({id:t.id,category:"dslr",name:t.name,projection:"rectilinear",frame:{widthMm:t.widthMm,heightMm:t.heightMm,focalLengthMm:zl.DEFAULT_FOCAL_MM,focalRangeMm:zl.FOCAL_RANGE_MM},fNumber:8,fNumberRange:{min:1.4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/8e3,max:3600},years:{from:t.year},apertureBlades:7,detailUm:t.pixelUm,medium:{kind:"sensor",iso:100}}))}static names(){return Object.fromEntries(zl.BODIES.map(t=>[t.id,t.name]))}}class dr{static DEFAULT_EYEPIECE_MM=26;static DEFAULT_APPARENT_FIELD_DEG=52;static FIELD_STOP_MM=2*dr.DEFAULT_EYEPIECE_MM*Math.tan(dr.DEFAULT_APPARENT_FIELD_DEG*Math.PI/360);static RANGE={min:26/40*.63,max:26/6*3};static BINOCULARS=[{id:"binoculars-zeiss-6x30",name:"Carl Zeiss 6x30",magnification:6,apertureMm:30,trueFieldDeg:5,fromYear:1960},{id:"binoculars-zeiss-dialyt-10x40",name:"Carl Zeiss Dialyt 10x40 B T*",magnification:10,apertureMm:40,trueFieldDeg:6.3,fromYear:1975},{id:"binoculars-jenoptem-10x50",name:"Jenoptem 10x50 W",magnification:10,apertureMm:50,trueFieldDeg:7.3,fromYear:1960},{id:"binoculars-swarovski-7x50-habicht",name:"Swarovski 7x50 SL Habicht",magnification:7,apertureMm:50,trueFieldDeg:6.6,fromYear:1960},{id:"binoculars-swarovski-7x50-slc",name:"Swarovski 7x50 SLC",magnification:7,apertureMm:50,trueFieldDeg:7.1,fromYear:1990},{id:"binoculars-nikon-10x42-edg",name:"Nikon 10x42 EDG",magnification:10,apertureMm:42,trueFieldDeg:6.5,fromYear:2011},{id:"binoculars-canon-15x50-is",name:"Canon 15x50 IS All Weather",magnification:15,apertureMm:50,trueFieldDeg:4.5,fromYear:2008},{id:"binoculars-celestron-15x70",name:"Celestron 15x70 SkyMaster",magnification:15,apertureMm:70,trueFieldDeg:4.4,fromYear:1990},{id:"binoculars-miyauchi-25x141",name:"Miyauchi BR-141 Galaxy 45 25x141",magnification:25,apertureMm:141,trueFieldDeg:2.6,fromYear:2e3}];static TELESCOPES=[{id:"telescope-generic-60-700",name:"Telescope 60/700",apertureMm:60,focalLengthMm:700},{id:"telescope-generic-60-1000",name:"Telescope 60/1000",apertureMm:60,focalLengthMm:1e3},{id:"telescope-celestron-onyx-80edf",name:"Celestron Onyx 80EDF",apertureMm:80,focalLengthMm:500,fromYear:2010},{id:"telescope-celestron-c5",name:"Celestron C5 f/10",apertureMm:125,focalLengthMm:1250,fromYear:1970},{id:"telescope-celestron-c8",name:"Celestron C8 f/10",apertureMm:203,focalLengthMm:2032,fromYear:1970},{id:"telescope-celestron-c11",name:"Celestron C11 f/10",apertureMm:280,focalLengthMm:2800,fromYear:1970},{id:"telescope-celestron-c14",name:"Celestron C14 f/11",apertureMm:355.6,focalLengthMm:3910,fromYear:1970},{id:"telescope-meade-etx-80",name:"Meade ETX 80 f/5",apertureMm:80,focalLengthMm:400,fromYear:1996},{id:"telescope-meade-etx-90",name:"Meade ETX 90 f/13.8",apertureMm:90,focalLengthMm:1242,fromYear:1996},{id:"telescope-meade-etx-125",name:"Meade ETX 125 f/15",apertureMm:127,focalLengthMm:1900,fromYear:1996},{id:"telescope-meade-lx200-8",name:"Meade LX200 8 in f/10",apertureMm:200,focalLengthMm:2e3,fromYear:1992},{id:"telescope-meade-lx200-10",name:"Meade LX200 10 in f/10",apertureMm:250,focalLengthMm:2500,fromYear:1992},{id:"telescope-meade-lx200-12",name:"Meade LX200 12 in f/10",apertureMm:305,focalLengthMm:3048,fromYear:1992},{id:"telescope-meade-lx200-14",name:"Meade LX200 14 in f/10",apertureMm:355,focalLengthMm:3556,fromYear:1992},{id:"telescope-meade-lx200-16",name:"Meade LX200 16 in f/10",apertureMm:406,focalLengthMm:4064,fromYear:1992}];static instruments(){const t=dr.BINOCULARS.map(n=>({id:n.id,category:"binoculars",name:n.name,projection:"rectilinear",visualAid:{apertureMm:n.apertureMm,magnification:n.magnification,trueFieldDeg:n.trueFieldDeg},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}})),e=dr.FIELD_STOP_MM,i=dr.TELESCOPES.map(n=>({id:n.id,category:"telescope",name:n.name,projection:"rectilinear",frame:{widthMm:e*16/9,heightMm:e,focalLengthMm:n.focalLengthMm,focalRangeMm:{minMm:n.focalLengthMm*dr.RANGE.min,maxMm:n.focalLengthMm*dr.RANGE.max}},visualAid:{apertureMm:n.apertureMm,eyepieceFocalMm:dr.DEFAULT_EYEPIECE_MM},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}}));return[...t,...i]}static names(){return Object.fromEntries(dr.instruments().map(t=>[t.id,t.name]))}}const $d=[{id:"eye",category:"eye",name:"Naked eye",projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",category:"camera",name:"Camera, unknown device",projection:"rectilinear",fNumber:8,fNumberRange:{min:2,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:8},apertureBlades:6},{id:"roamer-1-120",filmFormat:"120",category:"camera",name:"Roamer 1, 120 film",projection:"rectilinear",frame:{widthMm:74,heightMm:60,focalLengthMm:100},fNumber:11,exposureSeconds:1/50,years:{from:1930,to:1965},detailUm:40,medium:{kind:"negative",iso:125}},{id:"instamatic-126",filmFormat:"126",category:"camera",name:"Instamatic, 126 film",projection:"rectilinear",frame:{widthMm:28,heightMm:28,focalLengthMm:43},fNumber:11,exposureSeconds:1/90,years:{from:1963,to:1988},apertureBlades:5,detailUm:20,medium:{kind:"negative",iso:64}},{id:"slr-35mm-50",filmFormat:"135",category:"camera",name:"35 mm SLR, 50 mm lens",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:50},fNumber:8,fNumberRange:{min:2,max:16},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},years:{from:1959},apertureBlades:6,detailUm:20,medium:{kind:"negative",iso:100}},{id:"cine-35mm-broadcast",filmFormat:"35mm-cine",category:"camera",name:"35 mm film camera, seen on television",projection:"rectilinear",frame:{widthMm:21.3,heightMm:16,focalLengthMm:50,focalRangeMm:{minMm:18,maxMm:300}},fNumber:11,fNumberRange:{min:2,max:22},exposureSeconds:1/48,exposureRangeSeconds:{min:1/96,max:1/24},years:{from:1950,to:1995},apertureBlades:6,detailUm:15,medium:{kind:"negative",iso:100,print:ea.BROADCAST_35MM}},{id:"slr-35mm-zoom",filmFormat:"135",category:"camera",name:"35 mm SLR, 70-210 mm zoom",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:135,focalRangeMm:{minMm:70,maxMm:210}},fNumber:8,fNumberRange:{min:4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},apertureBlades:8,years:{from:1975},detailUm:20,medium:{kind:"negative",iso:100}},{id:"phone-landscape",category:"phone",name:"Phone, held sideways",projection:"rectilinear",frame:{widthMm:7.6,heightMm:5.7,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"phone-portrait",category:"phone",name:"Phone, held upright",projection:"rectilinear",frame:{widthMm:5.7,heightMm:7.6,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"dashcam",mounted:!0,category:"video",name:"Dashcam",projection:"equidistant",frame:{widthMm:5.76,heightMm:3.24,focalLengthMm:3.2},fNumber:2,exposureSeconds:1/30,exposureRangeSeconds:{min:1/1e4,max:1/30},years:{from:2008},apertureBlades:void 0,detailUm:3,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},{id:"cctv",mounted:!0,category:"video",name:"Security camera",projection:"rectilinear",frame:{widthMm:4.8,heightMm:3.6,focalLengthMm:3.6},fNumber:2,exposureSeconds:1/50,exposureRangeSeconds:{min:1/1e5,max:1/50},years:{from:1990},apertureBlades:void 0,detailUm:6,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},...zl.instruments(),...dr.instruments()];class Xi{static get default(){return $d[0]}static byId(t){return $d.find(e=>e.id===t)??this.default}static UNAIDED_FIELD_DEG=60;static UNAIDED_ASPECT=16/9;static fieldOfViewDeg(t){const e=t.frame;return e?Xi.fieldOf(t.projection,e.heightMm,e.focalLengthMm):t.visualAid?.trueFieldDeg??Xi.UNAIDED_FIELD_DEG}static fieldOf(t,e,i){return(t==="equidistant"?e/i:2*Math.atan(e/(2*i)))*180/Math.PI}static aspectOf(t){const e=t.frame;return e?e.widthMm/e.heightMm:Xi.UNAIDED_ASPECT}static frameWidthPx(t,e){return Math.round(e*Xi.aspectOf(t))}static CATEGORIES=["eye","camera","dslr","phone","video","binoculars","telescope"];static unavailability(t,e){const i=t.years;if(!(e===void 0||!i)){if(e<i.from)return{kind:"before",from:i.from};if(i.to!==void 0&&e>i.to)return{kind:"after",to:i.to}}}static availableAt(t){return t===void 0?$d:$d.filter(e=>!e.years||t>=e.years.from&&(e.years.to===void 0||t<=e.years.to))}static fieldOfViewDegAt(t,e){const i=t.frame;if(!(!i||e<=0))return Xi.fieldOf(t.projection,i.heightMm,e)}static focalLengthMmFor(t,e){const i=t.frame;if(!(!i||e<=0||e>=180))return t.projection==="equidistant"?i.heightMm/(e*Math.PI/180):i.heightMm/(2*Math.tan(e*Math.PI/360))}static bladesShowing(t,e){if(t.apertureBlades===void 0)return 0;const i=e??t.fNumber,n=t.fNumberRange?.min;if(i===void 0||n===void 0)return 1;const s=Math.max(0,Math.min(1,(i/n-1)/.3));return s*s*(3-2*s)}static starPointsOf(t,e){const i=t.apertureBlades;return i===void 0||i<3||Xi.bladesShowing(t,e)<.5?0:i%2===0?i:i*2}}class tr{constructor(t){this.entries=t}static empty(){return new tr(new Map)}get size(){return this.entries.size}at(t){return this.entries.get(t)}paths(){return[...this.entries.keys()]}set(t,e){e.basis==="stated"&&e.rationale===void 0&&e.how===void 0?this.entries.delete(t):this.entries.set(t,e)}clear(t){for(const e of this.entries.keys())(e===t||e.startsWith(`${t}.`))&&this.entries.delete(e)}static strip(t){const e=new tr(new Map);return{recording:tr.stripValue(t,[],e),provenance:e}}static restore(t,e){if(e.size===0)return t;const i={...t},n=new Set([i]);for(const s of e.paths()){const r=e.at(s),a=s.split("."),c=tr.writableHolderOf(i,a,n);if(!c)continue;const l=a[a.length-1],h=c[l];h!==void 0&&(r.of!==void 0&&JSON.stringify(r.of)!==JSON.stringify(h)||(c[l]={value:h,...r.basis==="stated"?{}:{basis:r.basis},...r.rationale===void 0?{}:{rationale:r.rationale},...r.how===void 0?{}:{how:r.how}}))}return i}static isWrapper(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"value"in t}static stripValue(t,e,i){return tr.isWrapper(t)?(i.set(e.join("."),{basis:t.basis??"stated",...t.rationale===void 0?{}:{rationale:t.rationale},...t.how===void 0?{}:{how:t.how},of:t.value}),tr.stripValue(t.value,e,i)):Array.isArray(t)?t.map((n,s)=>tr.stripValue(n,[...e,String(s)],i)):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([n,s])=>[n,tr.stripValue(s,[...e,n],i)])):t}static writableHolderOf(t,e,i){let n=t;for(const s of e.slice(0,-1)){const r=n[s];if(typeof r!="object"||r===null)return;if(i.has(r)){n=r;continue}const a=Array.isArray(r)?[...r]:{...r};i.add(a),n[s]=a,n=a}return n}}class Ps extends Error{}class xp{constructor(t){this.name=t}validate(t){return!0}}class KS extends xp{min;max;constructor(t,e,i){super(t),this.min=e,this.max=i}validate(t){if(typeof t!="number")throw new Ps(`${this.name} value must be a number, but was ${t}`);if(t<this.min||t>this.max)throw new Ps(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${t}`);return super.validate(t)}}class gi{name;min;max;duration;subUnit;validator;constructor(t,e,i,n,s=new KS(t,e,i)){this.name=t,this.min=e,this.max=i,this.subUnit=n,this.duration=n?(n.max-n.min+1)*n.duration:1,this.validator=s}validate(t){return this.validator.validate(t)}[Symbol.iterator](){let t=this.min;return{next:()=>{const e={done:t>this.max,value:t};return t++,e}}}}class zM{millisecond;second;minute;hour;day;month;year}class qA extends zM{}class qS extends qA{millisecond=new gi("millisecond",0,999,void 0);second=new gi("second",0,59,this.millisecond);minute=new gi("minute",0,59,this.second);hour=new gi("hour",0,23,this.minute);day=new gi("day",1,31,this.hour);month=new gi("month",1,12,this.day);year=new gi("year",0,9999,this.month)}const oe=new qS;class ZS extends KS{constructor(t=1,e=12){super("month",t,e)}}class Bl extends gi{static Month28=new Bl(28);static Month29=new Bl(29);static ThirtyDays=new Bl(30);static ThirtyOneDays=new Bl(31);constructor(t,e=new ZS(1,t)){super("month",1,t,oe.day,e)}static create(t,e){switch(t){case 1:case 3:case 5:case 7:case 8:case 10:case 12:return this.ThirtyOneDays;case 2:return e%4===0?this.Month29:this.Month28;case 4:case 6:case 9:case 11:return this.ThirtyDays;default:throw new Ps("Unsupported month",t,e)}}}class ia{static instance=new ia;render(t){return t.value.toString()}}class jn{unit;#t;constructor(t,e){this.unit=e,this.value=typeof t=="number"?t:t.value}get value(){return this.#t}set value(t){this.unit.validate(t),this.#t=t}get duration(){return this.value*this.unit.duration}#e(t){if(this.constructor.name!==t.constructor.name)throw new xp(`${this.unit.name} "${this.toString()}" cannot be compared with ${t.unit?.name} "${t.toString()}"`)}compare(t){return this.#e(t),this.value-t.value}isEqual(t){return this.compare(t)===0}isBefore(t){return this.compare(t)<0}isAfter(t){return this.compare(t)>0}previous(t=this.unit){const e=this.value-1;return new this.constructor(e,t)}next(t=this.unit){const e=this.value+1;return new this.constructor(e,t)}toString(t=ia.instance){return t.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Ct{static#t=new Map;static register(t,e){Ct.#t.set(t,e)}static get(t){const e=Ct.#t.get(t);if(!e)throw new Ps(`No default parser registered for ${t.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return e()}}class Ah extends jn{constructor(t=new Date().getFullYear(),e=oe.year){super(t,e)}static fromString(t,e=Ct.get(Ah)){return new Ah(e.parse(t))}}class Ma extends ia{static default=new Ma("0",2);constructor(t,e){super(),this.char=t,this.size=e}render(t){return super.render(t).padStart(this.size,this.char)}}class _h extends jn{constructor(t=new Date().getMonth()+1,e=oe.month){super(t,e)}static fromString(t,e=Ct.get(_h)){return new _h(e.parse(t))}toString(t=Ma.default){return super.toString(t)}}class Th extends jn{constructor(t=new Date().getDate(),e=oe.day){super(t,e)}static fromString(t,e=Ct.get(Th)){const i=e.parse(t);return new Th(i)}toString(t=Ma.default){return super.toString(t)}}class Rh extends jn{constructor(t=new Date().getHours(),e=oe.hour){super(t,e)}static fromString(t,e=Ct.get(Rh)){return new Rh(e.parse(t))}toString(t=Ma.default){return super.toString(t)}}class Ih extends jn{constructor(t=new Date().getMinutes(),e=oe.minute){super(t,e)}static fromString(t,e=Ct.get(Ih)){return new Ih(e.parse(t))}toString(t=Ma.default){return super.toString(t)}}class Dh extends jn{constructor(t=new Date().getSeconds(),e=oe.second){super(t,e)}static fromString(t,e=Ct.get(Dh)){return new Dh(e.parse(t),oe.second)}toString(t=Ma.default){return super.toString(t)}}class qo extends jn{static renderer=new Ma("0",3);constructor(t,e=oe.millisecond){super(t,e)}static parseFraction(t){return parseInt(t.padEnd(3,"0").substring(0,3),10)}toString(t=qo.renderer){return super.toString(t)}}class ZA{render(t){return t.toString()}}class JA extends ZA{render(t){const e=t.value,i=Math.abs(e),n=Math.floor(i/60),s=i%60;if(n===0&&s===0)return"Z";{const r=e<0?"-":"+",a=n.toString().padStart(2,"0"),c=s>0?":"+s.toString().padEnd(2,"0"):"";return r+a+c}}}class Wo{value;name="timeshift";renderer;constructor(t=0){this.value=t}static fromString(t,e=Ct.get(Wo),i=void 0){const n=e.parse(t,i);return new Wo(n)}toString(t=new JA){return t.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Kn{static timeshift(t,e){return t+(Kn.isDaylight(e)?60:0)}static isDaylight(t){const{year:e,month:i,day:n}=t,s=t.hour??12;if(![e,i,n].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=Kn.rule(e);if(!r)return!1;const a=Kn.rank(i,n,s);return a>=Kn.rank(r.start.month,r.start.day,2)&&a<Kn.rank(r.end.month,r.end.day,2)}static rule(t){if(t<1967)return;const e={month:10,day:Kn.sunday(t,10,-1)};return t>=2007?{start:{month:3,day:Kn.sunday(t,3,2)},end:{month:11,day:Kn.sunday(t,11,1)}}:t>=1987?{start:{month:4,day:Kn.sunday(t,4,1)},end:e}:t===1975?{start:{month:2,day:23},end:e}:t===1974?{start:{month:1,day:6},end:e}:{start:{month:4,day:Kn.sunday(t,4,-1)},end:e}}static sunday(t,e,i){const n=new Date(Date.UTC(2e3,e-1,1));n.setUTCFullYear(t);const s=1+(7-n.getUTCDay())%7;if(i>0)return s+7*(i-1);const r=[31,Kn.isLeap(t)?29:28,31,30,31,30,31,31,30,31,30,31][e-1];let a=s;for(;a+7<=r;)a+=7;return a}static isLeap(t){return t%4===0&&(t%100!==0||t%400===0)}static rank(t,e,i){return(t*100+e)*100+i}}const jA={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},QA={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},t3={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},e3={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},i3={name:"PT",timeshift:o=>Kn.timeshift(-480,o),title:"Pacific Time (US)"},n3={name:"MT",timeshift:o=>Kn.timeshift(-420,o),title:"Mountain Time (US)"},s3={name:"CT",timeshift:o=>Kn.timeshift(-360,o),title:"Central Time (US)"},r3={name:"ET",timeshift:o=>Kn.timeshift(-300,o),title:"Eastern Time (US)"},a3={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},o3={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},c3={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},l3={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},h3={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},u3={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},d3={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},f3={name:"Z",timeshift:"Z",title:"UTC"},p3={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},m3={name:"BST",timeshift:"+01",title:"British Summer Time"},g3={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},M3={name:"CET",timeshift:"+01",title:"Central European Time"},v3={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},y3={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},x3={name:"BJT",timeshift:"+08",title:"Beijing Time"},w3={name:"CST",timeshift:"-06",title:"Central Standard Time"},S3={name:"JST",timeshift:"+09",title:"Japan Standard Time"},b3={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},E3={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},A3={name:"LST",timeshift:"?",title:"Local Sideral Time"},ey=[u3,b3,h3,x3,m3,w3,o3,M3,g3,s3,a3,l3,c3,r3,p3,y3,S3,A3,t3,v3,e3,n3,E3,QA,jA,i3,d3,f3];class wp{static instance=new wp;renderComponent(t,e){return t[e].toString()}renderSecond(t){return this.renderComponent(t,"second")+(t.millisecond?"."+t.millisecond.toString():"")}render(t){const e=[];t.year&&e.push(this.renderComponent(t,"year")),t.month&&e.push(this.renderComponent(t,"month")),t.day&&e.push(this.renderComponent(t,"day"));const i=[];t.hour&&i.push(this.renderComponent(t,"hour")),t.minute&&i.push(this.renderComponent(t,"minute")),t.second&&i.push(this.renderSecond(t));const n=e.join("-"),s=t.timeshift?t.timeshift.toString():"",r=i.join(":")+s;return n+(r.length>0?"T"+r:"")}}class uc extends Ps{constructor(t="method is abstract"){super(t)}}class BM{units;constructor(t){this.units=t}newYear(t){throw new uc}newMonth(t){throw new uc}newDay(t){throw new uc}newHour(t){throw new uc}newMinute(t){throw new uc}newSecond(t){throw new uc}}class _3 extends zM{millisecond=new gi("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new gi("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new gi("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new gi("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new gi("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new gi("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new gi("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Fd=new _3;class Sp{static instance=new Sp;render(t){const e=br.toSpec(t);let i="P";const n=e.years;n&&(i+=n.toString()+"Y");const s=e.months;s&&(i+=s.toString(ia.instance)+"MM");const r=e.days;r&&(i+=r.toString(ia.instance)+"D");const a=e.hours;a&&(i+=a.toString(ia.instance)+"H");const c=e.minutes;c&&(i+=c.toString(ia.instance)+"M");const l=e.seconds;return l&&(i+=l.toString(ia.instance)+"S"),i}}class br extends jn{constructor(t={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof t=="number"?t:+(t.years?t.years*oe.year.duration:0)+(t.months?t.months*oe.month.duration:0)+(t.days?t.days*oe.day.duration:0)+(t.hours?t.hours*oe.hour.duration:0)+(t.minutes?t.minutes*oe.minute.duration:0)+(t.seconds?t.seconds*oe.second.duration:0)},new gi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(t,e=R3){let i=typeof t=="number"?t:t.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/oe.year.duration,a=Math.floor(r);a>0&&(s.years=e.newYear(n*a),i-=a*oe.year.duration);const c=i/oe.month.duration,l=Math.floor(c);l>0&&(s.months=e.newMonth(n*l),i-=l*oe.month.duration);const h=i/oe.day.duration,u=Math.floor(h);u>0&&(s.days=e.newDay(n*u),i-=u*oe.day.duration);const d=i/oe.hour.duration,f=Math.floor(d);f>0&&(s.hours=e.newHour(n*f),i-=f*oe.hour.duration);const p=i/oe.minute.duration,m=Math.floor(p);m>0&&(s.minutes=e.newMinute(n*m),i-=m*oe.minute.duration);const g=i/oe.second.duration,M=Math.floor(n*g);return M>0&&(s.seconds=e.newSecond(M)),s}static fromString(t,e=Ct.get(br)){return new br(e.parse(t))}static between(t,e){const i=e.getTime(),n=t.getTime();return new br(i-n)}toSpec(){return br.toSpec(this)}toString(t=Sp.instance){return t.render(this)}}class JS extends BM{constructor(t){super(t)}newYear(t){return new Ah(t,this.units.year)}newMonth(t){return new _h(t,this.units.month)}newDay(t){return new Th(t,this.units.day)}newHour(t){return new Rh(t,this.units.hour)}newMinute(t){return new Ih(t,this.units.minute)}newSecond(t){return new Dh(t,this.units.second)}newMillisecond(t){return new qo(t,this.units.millisecond)}newTimeshift(t){return new Wo(typeof t=="number"?t:t.value)}}const T3=new JS(oe),R3=new JS(Fd);class Cn{#t;#e;#i;#n;#s;#r;#a;#o;constructor(t={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:Cn.timeshiftOf(new Date)}){this.year=t.year,this.month=t.month,this.day=t.day,this.hour=t.hour,this.minute=t.minute,this.second=t.second,this.millisecond=t.millisecond,this.timeshift=t.timeshift}get year(){return this.#t}set year(t){const e=typeof t=="number";this.#t&&e?this.#t.value=t:this.#t=e?this.factory.newYear(t):!t||t.start||t instanceof jn?t:this.factory.newYear(t)}get month(){return this.#e}set month(t){const e=typeof t=="number";this.#e&&e?this.#e.value=t:this.#e=e?this.factory.newMonth(t):!t||t.start||t instanceof jn?t:this.factory.newMonth(t)}get day(){return this.#i}set day(t){const e=typeof t=="number";this.#i&&e?this.#i.value=t:this.#i=e?this.factory.newDay(t):!t||t.start||t instanceof jn?t:this.factory.newDay(t)}get hour(){return this.#n}set hour(t){const e=typeof t=="number";this.#n&&e?this.#n.value=t:this.#n=e?this.factory.newHour(t):!t||t.start||t instanceof jn?t:this.factory.newHour(t)}get minute(){return this.#s}set minute(t){const e=typeof t=="number";this.#s&&e?this.#s.value=t:this.#s=e?this.factory.newMinute(t):!t||t.start||t instanceof jn?t:this.factory.newMinute(t)}get second(){return this.#r}set second(t){const e=typeof t=="number";this.#r&&e?this.#r.value=t:this.#r=e?this.factory.newSecond(t):!t||t.start||t instanceof jn?t:this.factory.newSecond(t)}get millisecond(){return this.#a}set millisecond(t){const e=typeof t=="number";this.#a&&e?this.#a.value=t:this.#a=e||t&&!(t instanceof jn)?this.factory.newMillisecond(t):t}get timeshift(){return this.#o}set timeshift(t){const e=typeof t=="number";this.#o&&e?this.#o.value=t:this.#o=e||t&&!(t instanceof Wo)?this.factory.newTimeshift(t):t}get factory(){return T3}static fromString(t,e=Ct.get(Cn)){const{year:i,month:n,day:s,hour:r,minute:a,second:c,millisecond:l,timeshift:h}=e.parse(t);return new Cn({year:i,month:n,day:s,hour:r,minute:a,second:c,millisecond:l,timeshift:h})}static timeshiftOf(t){return-t.getTimezoneOffset()||0}static fromDate(t){return new Cn({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:Cn.timeshiftOf(t)})}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return Cn.fromString(i)}#c(t){if(this.constructor.name!==t.constructor.name)throw new xp(`Date "${this.toString()}" cannot be compared with "${t.toString()}"`)}compare(t){return this.#c(t),this.getTime()-t.getTime()}delta(t){const e=this.compare(t);return new br(e)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(t){return this.compare(t)===0}isBefore(t){return this.compare(t)<0}isAfter(t){return this.compare(t)>0}clone(){return new Cn(this.toSpec())}previous(){let t=this.clone();try{t.second=this.second.previous()}catch{try{t.minute=this.minute.previous()}catch{try{t.hour=this.hour.previous()}catch{try{t.day=this.day.previous()}catch{try{t.month=this.month.previous()}catch{t.year=this.year.previous()}}}}}return t}next(){let t=this.clone();try{t.second=this.second.next()}catch{try{t.minute=this.minute.next()}catch{try{t.hour=this.hour.next()}catch{try{t.day=this.day.next()}catch{try{t.month=this.month.next()}catch{t.year=this.year.next()}}}}}return t}toString(t=wp.instance){return t.render(this)}toSpec(){const t={},e=this.year?.toSpec();e&&(t.year=e);const i=this.month?.toSpec();i&&(t.month=i);const n=this.day?.toSpec();n&&(t.day=n);const s=this.hour?.toSpec();s&&(t.hour=s);const r=this.minute?.toSpec();r&&(t.minute=r);const a=this.second?.toSpec();a&&(t.second=a);const c=this.millisecond?.toSpec();c&&(t.millisecond=c);const l=this.timeshift?.toSpec();return l&&(t.timeshift=l),t}toJSON(){return this.toSpec()}}class HM{static instance=new HM;render(t){return(t.start?t.start.toString():"")+"/"+(t.end?t.end.toString():"")}}class Qu{constructor(t,e){this.start=t,this.end=e}_start;get start(){return this._start}set start(t){if(typeof t=="string"&&(t=Cn.fromString(t)),t&&!(t instanceof Cn)&&!(t instanceof br))throw new Ps("Interval start is not a level 0 date or duration: "+t);this._start=t}_end;get end(){return this._end}set end(t){if(typeof t=="string"&&(t=Cn.fromString(t)),t&&!(t instanceof Cn)&&!(t instanceof br))throw new Ps("Interval end is not a level 0 date or duration: "+t);this._end=t}static fromString(t,e=Ct.get(Qu)){const{start:i,end:n}=e.parse(t);return new Qu(i,n)}toString(t=HM.instance){return t.render(this)}[Symbol.iterator](){let t=this.start;return{next:()=>{const e={done:t>this.end,value:t};return t++,e}}}}class zd extends ia{static instance=new zd(Ma.default);constructor(t){super(),this.valueRenderer=t}render(t){return(this.valueRenderer?this.valueRenderer.render(t):super.render(t))+this.qualifier(t)}qualifier(t){return t.uncertain?t.approximate?"%":"?":t.approximate?"~":""}}class fa extends jn{#t;#e;constructor(t,e){super(t,e),this.#t=t.uncertain||!1,this.#e=t.approximate||!1}get uncertain(){return this.#t}set uncertain(t){return this.#t=t}get approximate(){return this.#e}set approximate(t){return this.#e=t}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(t){return this.isCertainAndPrecise()&&super.isEqual(t)}isBefore(t){return this.isCertainAndPrecise()&&super.isBefore(t)}isAfter(t){return this.isCertainAndPrecise()&&super.isAfter(t)}toString(t=zd.instance){return super.toString(t)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class jS extends qS{year=new gi("year",-9999,9999,this.month);yearExtended=new gi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const g0=new jS;class Do extends fa{constructor(t,e=g0.year){super(t,e)}static fromString(t,e=g0.year,i=Ct.get(Do)){const n=i.parse(t),s=n.value.start;if(t.startsWith("Y")&&(e=g0.yearExtended),s!==void 0){const r=new Do(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Do(Object.assign({...n},{value:Math.min(n.value.end,e.max)}));return{start:r,end:a}}else return new Do(n,e)}}class QS extends xp{monthValidator=new ZS;validate(t){switch(t){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(t)}}}class Co extends fa{constructor(t,e=new gi(oe.month.name,1,24,oe.day,new QS)){super(t,e)}static fromString(t,e=Ct.get(Co)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=oe.month;const r=new Co(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Co(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Co(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Po extends fa{constructor(t,e=oe.day){super(t,e)}static fromString(t,e=Ct.get(Po)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=oe.day;const r=new Po(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Po(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Po(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Oo extends fa{constructor(t,e=oe.hour){super(t,e)}static fromString(t,e=Ct.get(Oo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=oe.hour;const r=new Oo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Oo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Oo(i)}}class No extends fa{constructor(t,e=oe.minute){super(t,e)}static fromString(t,e=Ct.get(No)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.minute,r=new No(Object.assign({...i},{value:Math.max(n,s.min)})),a=new No(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new No(i)}toString(t=zd.instance){return super.toString(t)}}class Lo extends fa{constructor(t,e=oe.second){super(t,e)}static fromString(t,e=Ct.get(Lo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.second,r=new Lo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Lo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Lo(i)}}class Lc extends Wo{static fromString(t,e=Ct.get(Lc),i=void 0){return new Lc(e.parse(t,i))}}class tb extends BM{constructor(t){super(t)}newYear(t){return new Do(t,this.units.year)}newMonth(t){return new Co(t,this.units.month)}newDay(t){return new Po(t,this.units.day)}newHour(t){return new Oo(t,this.units.hour)}newMinute(t){return new No(t,this.units.minute)}newSecond(t){return new Lo(t,this.units.second)}newMillisecond(t){return new qo(t,this.units.millisecond)}newTimeshift(t){return new Lc(typeof t=="number"?t:t.value)}}const I3=new tb(g0),D3=new tb(Fd);class Rs extends Cn{constructor(t){super(t)}get factory(){return I3}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(t){return new Rs({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:Cn.timeshiftOf(t)})}static fromString(t,e=Ct.get(Rs)){const i=e.parse(t);return new Rs(i)}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return Rs.fromString(i)}clone(){return new Rs(this.toSpec())}}const gn=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class bp extends Sp{static instance=new bp;render(t){return super.render(t)}}class un extends fa{constructor(t){super(typeof t=="number"||t.hasOwnProperty("value")?t:{value:un.getValue(t,gn.year)+un.getValue(t,gn.month)+un.getValue(t,gn.day)+un.getValue(t,gn.hour)+un.getValue(t,gn.minute)+un.getValue(t,gn.second),uncertain:un.getBoolean(t,gn.uncertain),approximate:un.getBoolean(t,"approximate")},Fd.millisecond)}static getBoolean(t,e){return t[e]||t[gn.year+"s"]?.[e]||t[gn.month+"s"]?.[e]||t[gn.day+"s"]?.[e]||t[gn.hour+"s"]?.[e]||t[gn.minute+"s"]?.[e]||t[gn.second+"s"]?.[e]||!1}static getValue(t,e){let i=0,n=t[e+"s"];if(n instanceof fa?n=n.value:typeof t=="number"&&(n=t),n){const s=oe[e];i=n*s.duration}return i}static toSpec(t,e=D3){return{...br.toSpec(t,e),uncertain:t.uncertain||!1,approximate:t.approximate||!1}}static fromString(t,e=Ct.get(un)){const i=e.parse(t);return new un(i)}static between(t,e){const i=e.getTime(),n=t.getTime();return new un(i-n)}toString(t=bp.instance){return super.toString(t)}toSpec(){return un.toSpec(this)}}class td extends Qu{constructor(t,e){super(t,e)}get start(){return this._start}set start(t){if(typeof t=="string"&&(super.start=Rs.fromString(t)),t&&!(t instanceof Rs)&&!(t instanceof un))throw new Ps("Interval start is not a level 1 date or duration: "+t);this._start=t}get end(){return this._end}set end(t){if(typeof t=="string"&&(t=Rs.fromString(t)),t&&!(t instanceof Rs)&&!(t instanceof un))throw new Ps("Interval end is not a level 1 date or duration: "+t);this._end=t}static fromString(t,e=Ct.get(td)){const{start:i,end:n}=e.parse(t);return new td(i,n)}}class zh extends fa{uncertainComponent;approximateComponent;constructor(t,e){super(t,e),this.uncertainComponent=t.uncertainComponent||!1,this.approximateComponent=t.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(t){return super.uncertain=t}get approximate(){return super.approximate||this.approximateComponent}set approximate(t){return super.approximate=t}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class C3 extends jS{year=new gi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Wg=new C3;class Ua extends zh{constructor(t,e=Wg.year){super(t,e)}static fromString(t,e=Wg.year,i=Ct.get(Ua)){const n=i.parse(t),s=n.value.start;if(s!==void 0){const r=new Ua(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Ua(Object.assign({...n},{value:Math.min(n.value.end,e.max)})),c={start:r,end:a},l=n.value.estimate;return l&&(c.estimate=l),c}else return new Ua(n)}}class P3 extends QS{validate(t){switch(t){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(t)}}}class Fa extends zh{constructor(t,e=new gi(oe.month.name,1,41,oe.day,new P3)){super(t,e)}static fromString(t,e=Ct.get(Fa)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.month,r=new Fa(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Fa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Fa(i)}toString(t){return super.toString(t).padStart(2,"0")}}class za extends zh{constructor(t,e=oe.day){super(t,e)}static fromString(t,e=Ct.get(za)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.day,r=new za(Object.assign({...i},{value:Math.max(n,s.min)})),a=new za(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new za(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Ba extends zh{constructor(t,e=oe.hour){super(t,e)}static fromString(t,e=Ct.get(Ba)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.hour,r=new Ba(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Ba(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Ba(i)}}class Ha extends zh{constructor(t,e=oe.minute){super(t,e)}static fromString(t,e=Ct.get(Ha)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.minute,r=new Ha(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Ha(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Ha(i)}}class Ga extends zh{constructor(t,e=oe.second){super(t,e)}static fromString(t,e=oe.second,i=Ct.get(Ga)){const n=i.parse(t),s=n.value.start;if(s!==void 0){const r=new Ga(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Ga(Object.assign({...n},{value:Math.min(n.value.end,e.max)}));return{start:r,end:a}}else return new Ga(n,e)}}class eb extends Lc{}class O3 extends zd{qualifier(){return""}}class vo extends wp{static instance=new vo;static valueRenderer=new O3(Ma.default);static names=["year","month","day","hour","minute","second"];static qualifier(t,e){return t?e?"%":"?":e?"~":""}renderComponent(t,e){const i=t[e],n=vo.names.slice(vo.names.indexOf(e)+1).map(a=>t[a]).filter(Boolean),s=vo.qualifier(i.uncertainComponent,i.approximateComponent),r=vo.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(a=>a.approximate));return s+i.toString(vo.valueRenderer)+r}}class ib extends BM{constructor(t){super(t)}newYear(t){return new Ua(t,this.units.year)}newMonth(t){return new Fa(t,this.units.month)}newDay(t){return new za(t,this.units.day)}newHour(t){return new Ba(t,this.units.hour)}newMinute(t){return new Ha(t,this.units.minute)}newSecond(t){return new Ga(t,this.units.second)}newMillisecond(t){return new qo(t,this.units.millisecond)}newTimeshift(t){return new eb(typeof t=="number"?t:t.value)}}const N3=new ib(Wg),L3=new ib(Fd);class fs extends Rs{constructor(t){super(t)}toString(t=vo.instance){return super.toString(t)}get year(){return super.year}set year(t){super.year=t}get month(){return super.month}set month(t){super.month=t}get factory(){return N3}static fromDate(t){return new fs({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:Cn.timeshiftOf(t)})}static fromString(t,e=Ct.get(fs)){const i=e.parse(t);return new fs(i)}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return fs.fromString(i)}clone(){return new fs(this.toSpec())}}class ja{regExp;constructor(t,e){this.name=t,this.regExp=new RegExp(`^(?:${e})$`)}regexGroups(t){const e=this.regExp.exec(t);if(!e)throw new Ps(`Invalid ${this.name} "${t}"`);return e.groups}parseGroups(t){throw new uc(`${this.constructor.name} is abstract`)}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}class Hl extends bp{static instance=new Hl;static designators=[["years","Y"],["months","MM"],["days","D"],["hours","H"],["minutes","M"],["seconds","S"]];static qualifier(t,e){return t?e?"%":"?":e?"~":""}render(t){const e=Hl.qualifier(t.uncertainDuration,t.approximateDuration);if(!t.hasQualifiedComponent)return e+super.render(t);let i=e+"P";for(const[n,s]of Hl.designators){const r=t.components[n];r&&(i+=Hl.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+s)}return i}}class hn extends un{#t;constructor(t){if(super(typeof t=="number"?t:{value:hn.valueFromSpec(t),uncertain:t.uncertain===!0,approximate:t.approximate===!0},Fd.millisecond),typeof t!="number"){const e={};for(const i of hn.componentNames)t[i]instanceof fa&&(e[i]=t[i]);Object.keys(e).length>0&&(this.#t=e)}}static componentNames=["years","months","days","hours","minutes","seconds"];get components(){return this.#t}#e(t){return this.#t?Object.values(this.#t).some(e=>e[t]):!1}get uncertainDuration(){return super.uncertain}get approximateDuration(){return super.approximate}get uncertain(){return super.uncertain||this.#e("uncertain")}set uncertain(t){super.uncertain=t}get approximate(){return super.approximate||this.#e("approximate")}set approximate(t){super.approximate=t}get hasQualifiedComponent(){return this.#t?Object.values(this.#t).some(t=>t.uncertainComponent||t.approximateComponent):!1}static valueFromSpec(t){return hn.getValue(t,gn.year)+hn.getValue(t,gn.month)+hn.getValue(t,gn.day)+hn.getValue(t,gn.hour)+hn.getValue(t,gn.minute)+hn.getValue(t,gn.second)}static toSpec(t,e=L3){const i=un.toSpec(t,e);if(t instanceof hn&&t.hasQualifiedComponent)for(const n of hn.componentNames)delete i[n],t.components[n]&&(i[n]=t.components[n]);return i}static fromString(t,e=Ct.get(hn)){const i=e.parse(t);return new hn(i)}static between(t,e){const i=e.getTime(),n=t.getTime();return new hn(i-n)}toSpec(){return hn.toSpec(this)}toString(t=Hl.instance){return super.toString(t)}}class ed extends td{get start(){return this._start}set start(t){if(typeof t=="string"&&(super.start=fs.fromString(t)),t&&!(t instanceof fs)&&!(t instanceof hn))throw new Ps("Interval start is not a level 2 date or duration: "+t);this._start=t}get end(){return this._end}set end(t){if(typeof t=="string"&&(t=fs.fromString(t)),t&&!(t instanceof fs)&&!(t instanceof hn))throw new Ps("Interval end is not a level 2 date or duration: "+t);this._end=t}static fromString(t,e=Ct.get(ed)){const{start:i,end:n}=e.parse(t);return new ed(i,n)}}class N0 extends Set{constructor(t,e){super(t),this.exclusive=e}has(t){const e=t.toString().replace("..","/");for(const i of this)if(i.toString()===e)return!0;return!1}static fromString(t,e=Ct.get(N0)){const{exclusive:i,values:n}=e.parse(t);return new N0(n,i)}}class Qa extends ja{constructor(t,e){super(t,e)}static read(t){return{value:t?parseInt(t,10):void 0}}parseGroups(t){return Qa.read(t[this.name])}parse(t){if(t.startsWith("-"))throw new Ps(`${this.name} cannot be negative`);return super.parse(t)}}class U{static groupName(...t){return t.reduce((e,i)=>e?e+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(t,...e){return`(?<${t}>${e.join("")})`}static optional(t){return t+"?"}static nonCapturingGroup(...t){return`(?:${t.join("")})`}static optionalGroup(t,...e){return U.optional(U.group(t,...e))}static optionalNonCapturingGroup(...t){return U.optional(U.nonCapturingGroup(...t))}static numberGroup(t,e,i,n="\\d"){return U.group(t,`${i||""}[${n}]${e}`)}}const iy="yearValue";class id extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,iy),"{4}",void 0)}constructor(){super(iy,id.format())}}const ny="monthValue";class nd extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,ny),"{1,2}",void 0)}constructor(){super(ny,nd.format())}}const sy="dayValue";class oh extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,sy),"{1,2}",void 0)}constructor(){super(sy,oh.format())}}const ry="hourValue";class ch extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,ry),"{1,2}",void 0)}constructor(){super(ry,ch.format())}}const ay="minuteValue";class sd extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,ay),"{1,2}",void 0)}constructor(){super(ay,sd.format())}}const oy="secondValue";class rd extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,oy),"{1,2}",void 0)}constructor(){super(oy,rd.format())}}const cy="timeshiftValue",ly="shiftHour",hy="shiftMinute";class Ch extends ja{static format(t=""){return ey.map(e=>e.name).join("|")+"|"+U.nonCapturingGroup(U.group(t+ly,U.numberGroup(U.groupName(t,cy),"{2}","[+-]")),U.optionalNonCapturingGroup(":?",U.numberGroup(U.groupName(t,hy),"{2}",void 0)))}constructor(){super(cy,Ch.format())}parse(t,e){let i=0;const n=ey.find(s=>s.name===t);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(e??{})}catch(s){throw new Ps(`The time zone ${t} depends on the date: ${s.message}`)}t=n.timeshift}if(t!=="Z"){const s=this.regexGroups(t),r=s[ly];r&&(i+=parseInt(r,10)*60);const a=s[hy];a&&(i+=parseInt(a,10))}return i}}const uy="year",dy="month",fy="day",py="hour",my="minute",gy="second",My="millisecond",vy="timeshift";class vc extends ja{static format(t=""){return U.group(U.groupName(t,uy),id.format(t))+U.optionalNonCapturingGroup("-",U.group(U.groupName(t,dy),nd.format(t)),U.optionalNonCapturingGroup("-",U.group(U.groupName(t,fy),oh.format(t)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(t,py),ch.format(t)),":?",U.group(U.groupName(t,my),sd.format(t)),U.optionalNonCapturingGroup(":",U.group(U.groupName(t,gy),rd.format(t)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(t,My),"\\d+"))),"\\s*",U.optionalGroup(U.groupName(t,vy),Ch.format(t)))))}constructor(){super("date",vc.format())}parse(t){const e=this.regexGroups(t),i=e[uy],n=e[dy],s=e[fy],r=e[py],a=e[my],c=e[gy],l=e[My],h=e[vy],u=i?new Ah(id.read(i)):void 0,d=n?nd.read(n):void 0;return{year:u,month:d?new _h(d,Bl.create(d.value,u?.value)):void 0,day:s?new Th(oh.read(s)):void 0,hour:r?new Rh(ch.read(r)):void 0,minute:a?new Ih(sd.read(a)):void 0,second:c?new Dh(rd.read(c)):void 0,millisecond:l?qo.parseFraction(l):void 0,timeshift:h?Wo.fromString(h,new Ch,{year:u?.value,month:d?.value,day:s?oh.read(s).value:void 0,hour:r?ch.read(r).value:void 0}):void 0}}}const yy="years",Yp="months",k3="days",xy="hours",wy="minutes",Sy="seconds";class GM extends ja{static format(t=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,yy),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Yp),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,k3),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,xy),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,wy),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Sy),"+",void 0,"\\d"),"S")}constructor(){super("duration",GM.format())}parseGroups(t){return{years:t[yy],months:t[Yp],days:t[Yp],hours:t[xy],minutes:t[wy],seconds:t[Sy]}}}const $p="start",Kp="end";class VM extends ja{static format=U.group($p,vc.format($p))+"/"+U.group(Kp,vc.format(Kp));constructor(){super("interval",VM.format)}parse(t){const e=this.regexGroups(t),i=e[$p],n=e[Kp];return{start:i?Cn.fromString(i,new vc):void 0,end:n?Cn.fromString(n,new vc):void 0}}}class Ai extends Qa{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Ai.uncertainGroup+Ai.approximateGroup;constructor(t,e){super(t,e)}static qualifierFormat(t,e){return U.optionalGroup(t,`\\${e}`)}static formatSuffix(t){return this.qualifierFormat(U.groupName(Ai.uncertainGroup,t),"?")+this.qualifierFormat(U.groupName(Ai.approximateGroup,t),"~")+this.qualifierFormat(U.groupName(Ai.uncertainAndApproximateGroup,t),"%")}static numberFormat(t,e,i){return U.numberGroup(t,e,i,"\\dX")+this.formatSuffix(t)}getValueAndSign(t){let e=t[this.name],i;return e.charAt(0)==="-"?(i=-1,e=e.substring(1)):i=1,{valueStr:e,sign:i}}parseGroups(t){const{valueStr:e,sign:i}=this.getValueAndSign(t);let n=0,s;for(s=0;s<e.length;s++){const l=e[s];if(l==="X")break;n=n*10+parseInt(l,10)}if(s<e.length){let l=1;for(let d=0;d<e.length-s;d++)l*=10;const h=i*n*l,u=h+l-1;n={start:h,end:u}}else n*=i;const r=t[U.groupName(Ai.uncertainAndApproximateGroup,this.name)],a=t[U.groupName(Ai.approximateGroup,this.name)]||r,c=t[U.groupName(Ai.uncertainGroup,this.name)]||r;return{value:n,approximate:a?!!a:!1,uncertain:c?!!c:!1}}}const by="yearValue";class ad extends Ai{constructor(){super(by,ad.format())}static format(t=""){return"Y?"+Ai.numberFormat(U.groupName(t,by),"+","[-]?")}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}const Ey="monthValue";class od extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,Ey),"{1,2}",void 0)}constructor(){super(Ey,od.format())}}const Ay="dayValue";class cd extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,Ay),"{1,2}",void 0)}constructor(){super(Ay,cd.format())}}const _y="hourValue";class ld extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,_y),"{1,2}",void 0)}constructor(){super(_y,ld.format())}}const Ty="minuteValue";class hd extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,Ty),"{1,2}",void 0)}constructor(){super(Ty,hd.format())}}const Ry="secondValue";class ud extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,Ry),"{1,2}",void 0)}constructor(){super(Ry,ud.format())}}class dd extends Ch{}class Li extends ja{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(t=Li.format()){super("date",t)}static format(t=""){return U.group(U.groupName(t,Li.yearGroup),ad.format(t))+U.optionalNonCapturingGroup("-",U.group(U.groupName(t,Li.monthGroup),od.format(t)),U.optionalNonCapturingGroup("-",U.group(U.groupName(t,Li.dayGroup),cd.format(t)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(t,Li.hourGroup),ld.format(t)),":",U.group(U.groupName(t,Li.minuteGroup),hd.format(t)),U.optionalNonCapturingGroup(":",U.group(U.groupName(t,Li.secondGroup),ud.format(t)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(t,Li.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(t,Li.timeshiftGroup),dd.format(t)))))}parseGroups(t){const e=t[Li.millisecondGroup],i=e?qo.parseFraction(e):void 0,n=t[Li.secondGroup],s=n?Lo.fromString(n,new ud):void 0,r=t[Li.minuteGroup];let a;r&&(a=No.fromString(r,new hd),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[Li.hourGroup];let l;c&&(l=Oo.fromString(c,new ld),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=t[Li.dayGroup];let u;h&&(u=Po.fromString(h,new cd),u.uncertain=u.uncertain||l?.uncertain||!1,u.approximate=u.approximate||l?.approximate||!1);const d=t[Li.monthGroup];let f;d&&(f=Co.fromString(d,new od),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[Li.yearGroup];let m;p&&(m=Do.fromString(p,void 0,new ad),m.uncertain=m.uncertain||f?.uncertain||!1,m.approximate=m.approximate||f?.approximate||!1);const g=t[Li.timeshiftGroup],M=g?Lc.fromString(g,new dd,{year:m?.value,month:f?.value,day:u?.value,hour:l?.value}):void 0;return{year:m,month:f,day:u,hour:l,minute:a,second:s,millisecond:i,timeshift:M}}}const Iy="years",Dy="months",Cy="days",Py="hours",Oy="minutes",Ny="seconds";class yc extends Ai{static format(t=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Iy),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Dy),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Cy),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Py),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Oy),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Ny),"+",void 0,"\\d"),"S")+this.formatSuffix(t)}constructor(){super("duration",yc.format())}parseGroups(t){return{years:t[Iy],months:t[Dy],days:t[Cy],hours:t[Py],minutes:t[Oy],seconds:t[Ny],uncertain:!!t[Ai.uncertainGroup],approximate:!!t[Ai.approximateGroup]}}}const U3="dates",qp="start",Zp="end",Ly="durations",Jp="durationMin",jp="durationMax";class WM extends ja{static format=U.group(U3,U.optionalGroup(qp,U.group("openStart","\\.\\.")+"|"+Li.format(qp))+"/"+U.optionalGroup(Zp,U.group("openEnd","\\.\\.")+"|"+Li.format(Zp)))+"|"+U.group(Ly,U.group(Jp,yc.format(Jp))+"/"+U.group(jp,yc.format(jp)));constructor(t="interval",e=WM.format){super(t,e)}parseGroups(t){let e,i;if(t[Ly]){const s=t[Jp];e=un.fromString(s,new yc);const r=t[jp];i=un.fromString(r,new yc)}else{const s=t[qp];switch(s){case void 0:e=null;break;case"..":e=void 0;break;default:e=Rs.fromString(s,new Li)}const r=t[Zp];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=Rs.fromString(r,new Li)}}return{start:e,end:i}}}class Ve extends Ai{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=Ve.uncertainGroup+Ve.approximateGroup;constructor(t,e){super(t,e)}static numberFormat(t,e,i){return this.qualifierFormat(U.groupName(Ve.uncertainGroup,t),"?")+this.qualifierFormat(U.groupName(Ve.approximateGroup,t),"~")+this.qualifierFormat(U.groupName(Ve.uncertainAndApproximateGroup,t),"%")+Ai.numberFormat(t,e,i)}parseGroups(t){const e=super.parseGroups(t),i=t[U.groupName(Ve.uncertainAndApproximateGroup,this.name)];return(t[U.groupName(Ve.uncertainGroup,this.name)]||i)&&(e.uncertainComponent=!0),(t[U.groupName(Ve.approximateGroup,this.name)]||i)&&(e.approximateComponent=!0),e}}const Wh="yearValue",ky="exp",Uy="signif";class fd extends Ve{constructor(){super(Wh,fd.format())}static format(t=""){return"Y?"+U.nonCapturingGroup(U.group(U.groupName(t,ky),"[-]?\\d+E\\d+")+"|"+Ve.numberFormat(U.groupName(t,Wh),"+","[-]?")+U.optionalGroup(U.groupName(t,Uy),"S\\d+"))}parseGroups(t){const e=t[ky];if(e){const r=e.indexOf("E"),a=parseInt(e.substring(r+1),10),l=parseInt(e.substring(0,r),10)*Math.pow(10,a);t[Wh]=l.toString()}const i=t[Uy],n=t[Wh];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:c}=this.getValueAndSign(t);let l="";for(let h=0;h<a.length;h++)l+=h<r?a.charAt(h):"X";t[Wh]=(c<0?"-":"")+l}const s=super.parseGroups(t);return i&&(s.value.estimate=parseInt(n,10)),s}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}const Fy="monthValue";class pd extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,Fy),"{1,2}",void 0)}constructor(){super(Fy,pd.format())}}const zy="dayValue";class md extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,zy),"{1,2}",void 0)}constructor(){super(zy,md.format())}}const By="hourValue";class gd extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,By),"{1,2}",void 0)}constructor(){super(By,gd.format())}}const Hy="secondValue";class Md extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,Hy),"{1,2}",void 0)}constructor(){super(Hy,Md.format())}}const Gy="minuteValue";class vd extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,Gy),"{1,2}",void 0)}constructor(){super(Gy,vd.format())}}class F3 extends dd{}class $e extends ja{static yearGroup=Li.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",$e.format())}static format(t=""){return U.group(U.groupName(t,$e.yearGroup),fd.format(t))+U.optionalNonCapturingGroup("-",U.group(U.groupName(t,$e.monthGroup),pd.format(t)),U.optionalNonCapturingGroup("-",U.group(U.groupName(t,$e.dayGroup),md.format(t)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(t,$e.hourGroup),gd.format(t)),":",U.group(U.groupName(t,$e.minuteGroup),vd.format(t)),U.optionalNonCapturingGroup(":",U.group(U.groupName(t,$e.secondGroup),Md.format(t)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(t,$e.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(t,$e.timeshiftGroup),F3.format(t)))))}parseGroups(t){const e=t[$e.millisecondGroup],i=e?qo.parseFraction(e):void 0,n=t[$e.secondGroup];let s;n&&(s=Ga.fromString(n,void 0,new Md),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=t[$e.minuteGroup];let a;r&&(a=Ha.fromString(r,new vd),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[$e.hourGroup];let l;c&&(l=Ba.fromString(c,new gd),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=t[$e.dayGroup];let u;h&&(u=za.fromString(h,new md),u.uncertain=u.uncertain||l?.uncertain||!1,u.approximate=u.approximate||l?.approximate||!1);const d=t[$e.monthGroup];let f;d&&(f=Fa.fromString(d,new pd),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[$e.yearGroup];let m;p&&(m=Ua.fromString(p,void 0,new fd),m.uncertain=m.uncertain||f?.uncertain||!1,m.approximate=m.approximate||f?.approximate||!1);const g=t[$e.timeshiftGroup],M=g?eb.fromString(g,new dd,{year:m?.value,month:f?.value,day:u?.value,hour:l?.value}):void 0;return{year:m,month:f,day:u,hour:l,minute:a,second:s,millisecond:i,timeshift:M}}}const Vy="durationValue";class XM extends Ve{static format(t=""){return"^"+Ve.numberFormat(U.groupName(t,Vy),"+",void 0)}constructor(){super(Vy,XM.format())}}class z3 extends zM{millisecond=new gi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new gi("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new gi("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new gi("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new gi("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new gi("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new gi("year",0,Number.MAX_SAFE_INTEGER,this.month)}const qc=new z3;class te extends Ve{static yearsGroup="years";static monthsGroup="months";static isoMonthsGroup="isoMonths";static daysGroup="days";static hoursGroup="hours";static minutesGroup="minutes";static secondsGroup="seconds";static durationGroup="duration";static suffixGroup="durationSuffix";static componentParser=new XM;static componentFormat(t,e,i,n,s=""){const r=U.group(U.groupName(t,te.quantityGroup(e)),Ve.numberFormat(U.groupName(t,i),"+",void 0,"\\d"));return U.group(U.groupName(t,e),r,n,s)}static quantityGroup(t){return t+"Quantity"}static isoMonthsLookahead="(?=[?~%]?\\d+D|T)";constructor(){super("duration",te.format())}static format(t=""){const e=U.groupName(t,te.durationGroup);return this.qualifierFormat(U.groupName(Ve.uncertainGroup,e),"?")+this.qualifierFormat(U.groupName(Ve.approximateGroup,e),"~")+this.qualifierFormat(U.groupName(Ve.uncertainAndApproximateGroup,e),"%")+"P"+U.optional(te.componentFormat(t,te.yearsGroup,$e.yearGroup,"Y"))+U.optionalNonCapturingGroup(te.componentFormat(t,te.monthsGroup,$e.monthGroup,"MM")+"|"+te.componentFormat(t,te.isoMonthsGroup,"isoMonth","M",te.isoMonthsLookahead))+U.optional(te.componentFormat(t,te.daysGroup,$e.dayGroup,"D"))+"T?"+U.optional(te.componentFormat(t,te.hoursGroup,$e.hourGroup,"H"))+U.optional(te.componentFormat(t,te.minutesGroup,$e.minuteGroup,"M"))+U.optional(te.componentFormat(t,te.secondsGroup,$e.secondGroup,"S"))+U.optionalGroup(U.groupName(t,te.suffixGroup),"[?~%]")}static parseComponent(t,e,i){const n=te.componentParser.parse(t);return new e(n,i)}parseGroups(t){const e=t[te.quantityGroup(te.secondsGroup)];let i;e&&(i=te.parseComponent(e,Ga,qc.second),i.uncertain=!!t[U.groupName(Ve.uncertainGroup,te.secondsGroup)]||!1,i.approximate=!!t[U.groupName(Ve.approximateGroup,te.secondsGroup)]||!1);const n=t[te.quantityGroup(te.minutesGroup)];let s;n&&(s=te.parseComponent(n,Ha,qc.minute),s.uncertain=s.uncertain||i?.uncertain||!1,s.approximate=s.approximate||i?.approximate||!1);const r=t[te.quantityGroup(te.hoursGroup)];let a;r&&(a=te.parseComponent(r,Ba,qc.hour),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[te.quantityGroup(te.daysGroup)];let l;c&&(l=te.parseComponent(c,za,qc.day),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=t[te.quantityGroup(te.monthsGroup)]||t[te.quantityGroup(te.isoMonthsGroup)];let u;h&&(u=te.parseComponent(h,Fa,qc.month),u.uncertain=u.uncertain||l?.uncertain||!1,u.approximate=u.approximate||l?.approximate||!1);const d=t[te.quantityGroup(te.yearsGroup)];let f;d&&(f=te.parseComponent(d,Ua,qc.year),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[te.suffixGroup],m=!!t[U.groupName(Ve.uncertainAndApproximateGroup,te.durationGroup)]||p==="%",g=m||!!t[U.groupName(Ve.uncertainGroup,te.durationGroup)]||p==="?",M=m||!!t[U.groupName(Ve.approximateGroup,te.durationGroup)]||p==="~";return{years:f,months:u,days:l,hours:a,minutes:s,seconds:i,uncertain:g,approximate:M}}}const B3="dates",Qp="start",tm="end",Wy="durations",em="durationMin",im="durationMax";class Ep extends ja{static format=U.group(B3,U.optionalGroup(Qp,U.group("openStart","\\.\\.")+"|"+$e.format(Qp))+"/"+U.optionalGroup(tm,U.group("openEnd","\\.\\.")+"|"+$e.format(tm)))+"|"+U.group(Wy,U.group(em,te.format(em))+"/"+U.group(im,te.format(im)));constructor(t="interval",e=Ep.format){super(t,e)}parseGroups(t){let e,i;if(t[Wy]){const s=t[em];e=hn.fromString(s,new te);const r=t[im];i=hn.fromString(r,new te)}else{const s=t[Qp];switch(s){case void 0:e=null;break;case"..":e=void 0;break;default:e=fs.fromString(s,new $e)}const r=t[tm];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=fs.fromString(r,new $e)}}return{start:e,end:i}}}class H3{parse(t){t=t.trim();const e=t.startsWith("["),n=t.substring(1,t.length-1).split(","),s=[];for(const r of n){let a;r.includes("..")?a=ed.fromString(r.replace("..","/"),new Ep):a=fs.fromString(r,new $e),s.push(a)}return{values:s,exclusive:e}}}const nb=["spring","summer","autumn","winter"],Xg=21,G3=32,V3=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let W3;function X3(){return W3??=new $e}function Zc(o){return typeof o?.value=="number"?o.value:void 0}function Y3(o){const t=o.trim();if(/^\d{1,2}:/.test(t)){const r=V3.exec(t)?.groups;return r?{year:void 0,month:void 0,day:void 0,hour:Number(r.hour),minute:Number(r.minute),second:r.second?Number(r.second):void 0,raw:t}:void 0}let e;try{e=fs.fromString(t,X3())}catch{return}const i=Zc(e.year),n=Zc(e.month),s=n!==void 0&&n>=Xg&&n<=G3;if(!(e.timeshift||i!==void 0&&Math.abs(i)>9999)&&!(n!==void 0&&n>12&&!s)&&!(s&&(e.day||e.hour)))return{year:i,month:s?void 0:n,...s?{season:nb[(n-Xg)%4]}:{},day:Zc(e.day),hour:Zc(e.hour),minute:Zc(e.minute),second:Zc(e.second),raw:t}}function sb(o){if(o.raw!==void 0)return o.raw;if(o.year===void 0){if(o.hour===void 0)return"";let e=`${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`;return o.second!==void 0&&(e+=`:${String(o.second).padStart(2,"0")}`),e}let t=String(o.year).padStart(4,"0");return o.season!==void 0?`${t}-${Xg+nb.indexOf(o.season)}`:(o.month===void 0||(t+=`-${String(o.month).padStart(2,"0")}`,o.day===void 0)||(t+=`-${String(o.day).padStart(2,"0")}`,o.hour===void 0)||(t+=`T${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`,o.second!==void 0&&(t+=`:${String(o.second).padStart(2,"0")}`)),t)}function Yg(o){if(o.year!==void 0)return Date.UTC(o.year,(o.month??1)-1,o.day??1,o.hour??0,o.minute??0,o.second??0)}function Xy(o){return(((o.day??0)*24+(o.hour??0))*60+(o.minute??0))*6e4+(o.second??0)*1e3}const $3=["year","month","day","hour","minute"],K3=["day","hour","minute"];function Yy(o,t){return t.filter(e=>o[e]!==void 0).join(",")}function q3(o){if(o.durationSeconds!==void 0)return o.durationSeconds*1e3;const t=o.durationText===void 0?void 0:Iu.parse(o.durationText);if(t)return t.chosenSeconds*1e3;if(!o.time||!o.endTime)return;const e=o.time.year!==void 0&&o.endTime.year!==void 0,i=e?$3:K3,n=Yy(o.time,i);if(!(n===""||n!==Yy(o.endTime,i)))return e?Yg(o.endTime)-Yg(o.time):Xy(o.endTime)-Xy(o.time)}class Ap{constructor(t,e,i,n,s,r,a,c,l=[],h,u,d,f=[],p=[],m=[],g=[]){this.event=t,this.timeline=e,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=a,this.weather=c,this.decor=l,this.weatherSource=h,this.instrumentId=u,this.exposureSeconds=d,this.milestones=f,this.references=p,this.roads=m,this.traces=g}provenance=tr.empty();loadIssues=[];account;sources;interpretation;variants=[];skyEvents;snapshots;modules;sway;lightPollution;observerMap;iso;film;metering;lens;vehicle;events;eventsExpansion;sampleMs;get observerCount(){return 1+this.decor.filter(t=>t.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return Xi.byId(this.instrumentId)}static create(t,e,i){return new Ap({eventType:"sighting",time:t,place:e},new Ud,new Zu,new Ju,new ju,i)}}const Z3=0,J3=0;function ze(o,t){const e=o.observerTrack.getInterpolatedPoseAt(t);if(e)return e;const i=o.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:Z3,headingDeg:void 0,pitchDeg:J3,fovDeg:Xi.fieldOfViewDeg(o.instrument)}}function Xh(o,t){return o.weatherTrack.getInterpolatedWeatherAt(t)??o.weather??yp}function Yh(o,t){return o.weatherTrack.getActualWeatherAt(t)??o.weather??yp}function j3(o,t){return o.soundTrack.getInterpolatedSoundAt(t)??KA}class Qi{static toCurrent(t){const e=t.version,i=typeof e=="object"&&e!==null&&"value"in e?e.value:e;if(i!==void 0&&i!==1&&i!==2&&i!==3)return t;let n=t;return(i===void 0||i===1)&&(n=Qi.fromVersion1(n)),i!==3&&(n=Qi.fromVersion2(n)),Qi.fromVersion3(n)}static fromVersion3(t){const e={};for(const[i,n]of Object.entries(t))i==="frozen"?e.snapshots=n:e[i]=n;return e.version=4,e}static observerIdOf(t){return t.observer?.id??"observer"}static fromVersion2(t){const e={...t,version:3},i={...t.timeline??{keyframes:[]}},n=new Set,s=i.keyframes??[];for(const h of s)for(const u of h.shapes??[])n.add(u.sourceId);const r=[],a=h=>{let u=h;for(let d=r.length+1;u===void 0||n.has(u);d++)u=`group-${d}`;return n.add(u),u},c=Array.isArray(i.groups)?i.groups:[];for(const h of c)Array.isArray(h)?r.push({id:a(),members:[...h]}):typeof h=="object"&&h!==null&&r.push(h);const l=Array.isArray(t.events)?t.events.map(h=>({...h})):void 0;if(l){const h=Qi.observerIdOf(t),u=l.filter(M=>M.who==="phenomenon"),d=new Set(n);for(const M of u){const v=Qi.unwrapped(M.params?.parts);if(M.eventType==="appearance"&&Array.isArray(v))for(const x of v)x.sourceId&&d.add(x.sourceId)}for(const M of d)n.add(M);const f=M=>r.find(v=>v.members.includes(M)),p=M=>{const v=f(M);return v?p(v.id):M},m=[...new Set([...d].map(p))],g=m.length===1?m[0]:m.length>1?a("phenomenon"):"phenomenon";m.length>1&&r.push({id:g,members:m});for(const M of l)if(M.who===void 0||M.who==="observer")M.who=h;else if(M.who==="phenomenon"){M.who=g;const v=M.params;if(M.eventType!=="blink"||!v||!Array.isArray(v.parts))continue;const x=v.parts,{parts:y,...w}=v;M.params=w,M.who=Qi.groupFor(x,r,a)??g}e.events=l}return(r.length>0||c.length>0)&&(e.timeline={...i,groups:r}),e}static groupFor(t,e,i){if(t.length===1)return t[0];const n=l=>{const h=e.find(u=>u.id===l);return h?h.members.flatMap(n):[l]},s=e.find(l=>{const h=n(l.id);return h.length===t.length&&t.every(u=>h.includes(u))});if(s)return s.id;const r=new Set(t.map(l=>e.find(h=>h.members.includes(l))));if(r.size!==1)return;const[a]=r,c=i();if(a){const l=a.members.findIndex(h=>t.includes(h));a.members=a.members.filter(h=>!t.includes(h)),a.members.splice(l,0,c)}return e.push({id:c,members:[...t]}),c}static unwrapped(t){return Qi.isWrapped(t)?t.value:t}static fromVersion1(t){const e={...t,version:2};for(const i of["time","endTime"])t[i]!==void 0&&(e[i]=Qi.edtf(t[i]));if(Array.isArray(t.place)){const i=Qi.place(t.place);i===void 0?delete e.place:e.place=i}return e}static edtf(t){if(Qi.isWrapped(t)){const l=Qi.edtf(t.value);return l===void 0?void 0:{...t,value:l}}if(typeof t=="string")return t;const e=t,i=Object.values(e).find(l=>Qi.isWrapped(l)),n=Object.fromEntries(Object.entries(e).map(([l,h])=>[l,Qi.isWrapped(h)?h.value:h])),s=sb(n);if(s==="")return;if(!i)return s;const{basis:r,rationale:a,how:c}=i;return{value:s,...r===void 0?{}:{basis:r},...a===void 0?{}:{rationale:a},...c===void 0?{}:{how:c}}}static place(t){if(t.length===0)return;const e=t.map(l=>Qi.isWrapped(l)?l.value:l),i=e.find(l=>l.name)?.name,n={...i?{name:i}:{},locations:e.map(({lat:l,lng:h})=>({lat:l,lng:h}))},s=t.find(l=>Qi.isWrapped(l));if(!s)return n;const{basis:r,rationale:a,how:c}=s;return{value:n,...r===void 0?{}:{basis:r},...a===void 0?{}:{rationale:a},...c===void 0?{}:{how:c}}}static isWrapped(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"value"in t}}class Ic{static sessionDeclared=!1;static unlock(t){if(Ic.declarePlayback(),t.state!=="running")try{Promise.resolve(t.resume()).catch(()=>{});const e=t.createBufferSource();e.buffer=t.createBuffer(1,1,22050),e.connect(t.destination),e.start(0)}catch{}}static declarePlayback(){if(!(Ic.sessionDeclared||typeof navigator>"u")){Ic.sessionDeclared=!0;try{const t=navigator.audioSession;t&&(t.type="playback")}catch{}}}}const Q3=.08,$y=.15,Ky=2,t_=2e3;class e_{context;noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",t);return}}Ic.unlock(this.context),this.apply()}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}setPaused(t){t!==this.paused&&(this.paused=t,this.apply())}setVoices(t){this.requested=t,this.apply()}dispose(){for(const t of[...this.voices.keys()])this.release(t);this.context?.close(),this.context=void 0,this.master=void 0}masterOf(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}apply(){const t=this.context;if(!t)return;const e=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<t_),i=new Set(e.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of e){const s=this.voices.get(n.id)??this.build(t,n.id);this.retarget(t,s,n)}}build(t,e){const i=t.createGain();i.gain.value=0;const n=t.createBiquadFilter();n.type="lowpass",n.connect(i).connect(this.masterOf(t));const s=t.createOscillator();s.type="sawtooth";const r=t.createOscillator();r.type="sine";const a=t.createGain(),c=t.createBiquadFilter();c.type="lowpass",c.frequency.value=900,s.connect(c),r.connect(c),c.connect(a).connect(n);const l=()=>{const w=t.createBufferSource();return w.buffer=this.noise(t),w.loop=!0,w.loopStart=Math.random()*Ky*.5,w},h=l(),u=t.createBiquadFilter();u.type="bandpass",u.Q.value=4;const d=t.createGain();h.connect(u).connect(d).connect(n);const f=l(),p=t.createBiquadFilter();p.type="lowpass",p.frequency.value=600;const m=t.createGain();f.connect(p).connect(m).connect(n);const g=l(),M=t.createBiquadFilter();M.type="bandpass",M.frequency.value=1400,M.Q.value=.7;const v=t.createGain();g.connect(M).connect(v).connect(n);const x=[s,r,h,f,g];for(const w of x)w.start();const y={nodes:[i,n,a,c,u,d,p,m,M,v,...x],sources:x,firing:s,crank:r,knock:u,engineGain:a,knockGain:d,roadGain:m,windGain:v,cabin:n,output:i};return this.voices.set(e,y),y}retarget(t,e,{profile:i,state:n,noise:s,inside:r,windowsOpen:a,distanceM:c}){const l=t.currentTime,h=(v,x)=>v.setTargetAtTime(x,l,Q3),u=n.rpm/60,d=u*i.cylinders/2,f=Math.min(1,n.rpm/i.shiftUpRpm),p=Math.min(1.5,n.speedMps/30);h(e.firing.frequency,d),h(e.crank.frequency,u),h(e.knock.frequency,d*3),h(e.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*f)*.3),h(e.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(e.roadGain.gain,i.roadGain*p**1.5*.8);const m=!r||a;h(e.windGain.gain,p**2*(m?.5:.06));const g=r?a?3500:700:8e3/(1+c/60);h(e.cabin.frequency,g);const M=r?.5:Math.min(1,8/Math.max(c,1));h(e.output.gain,M*s)}release(t){const e=this.voices.get(t);if(!e)return;this.voices.delete(t);const i=this.context;i&&(e.output.gain.setTargetAtTime(0,i.currentTime,$y/3),setTimeout(()=>{for(const n of e.sources)try{n.stop()}catch{}for(const n of e.nodes)n.disconnect()},$y*1e3*3))}noise(t){if(this.noiseBuffer)return this.noiseBuffer;const e=t.createBuffer(1,t.sampleRate*Ky,t.sampleRate),i=e.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=e,e}}class kc{static MODES=["off","position","dipped","main","fog"];static DISPLAY_GAIN=.006;static TOE_IN_DEG=.6;static AUTO_BELOW_SUN_DEG=-1;static BEAMS={off:void 0,position:void 0,dipped:{candela:25e3,halfAngleDeg:24,pitchDeg:2.5,penumbra:1,color:"#fff2d8"},main:{candela:12e4,halfAngleDeg:14,pitchDeg:.4,penumbra:.85,color:"#fff6e6"},fog:{candela:9e3,halfAngleDeg:38,pitchDeg:5,penumbra:1,color:"#ffe9b0"}};static isMode(t){return typeof t=="string"&&kc.MODES.includes(t)}static at(t,e,i){if(!e||e.length===0)return t;let n=e[0];for(const s of e){if(s.t>i)break;n=s}return n.mode}static auto(t){return t<kc.AUTO_BELOW_SUN_DEG?"dipped":"off"}static lamps(t){return t!=="off"}}const qy=2;function L0(o){return o==="building"||o==="vehicle"}const rb={aircraft:{id:"poly-google-airliner"},tree:{id:"jungle-jim-tree-large-a"},observer:{id:"makehuman-farmer-40s"},entity:{id:"makehuman-farmer-40s"}},i_=["makehuman-farmer-40s","makehuman-man-overalls","makehuman-man-jacket","makehuman-old-man","makehuman-woman"];function Zy(o,t){let e=0;for(const i of t)e=e*31+i.charCodeAt(0)>>>0;return{id:o[e%o.length]}}const n_=["jungle-jim-tree-large-a","jungle-jim-tree-medium-a","jungle-jim-tree-large-b","jungle-jim-tree-medium-b","jungle-jim-tree-large-c","jungle-jim-tree-medium-c","jagobo-tree-maple-a","jagobo-tree-maple-b","jagobo-tree-aspen-a","jagobo-tree-aspen-b","nicholas-3d-tree-a","nicholas-3d-tree-b","nicholas-3d-tree-c"];function $g(o){return o.model?o.model:o.kind==="tree"&&o.id!==void 0?Zy(n_,o.id):(o.kind==="observer"||o.kind==="entity")&&o.id!==void 0?Zy(i_,o.id):rb[o.kind]}function ab(o,t){const e=kc.at(o.headlights,o.headlightKeyframes,t);return e!==void 0?e:YM(o,t)?"dipped":"off"}const s_=-.5;function r_(o){return o.kind==="streetlight"&&o.origin!==void 0&&o.lit===void 0&&!o.litKeyframes?.length}function YM(o,t,e){if(e!==void 0&&r_(o))return e<s_;const i=o.litKeyframes;if(!i||i.length===0)return o.lit??!1;let n=i[0];for(const s of i){if(s.t>t)break;n=s}return n.lit}function Jy(o,t){const e=o.observerKeyframes;if(!e||e.length===0)return{side:o.observerSide,facing:o.observerFacing};let i=e[0];for(const n of e){if(n.t>t)break;i=n}return{side:i.side,facing:i.facing}}function a_(o,t){const e=lh(o,t);return e.intensity<=0?!1:e.pattern.kind==="steady"?!0:ob(o,t,t+1)>.5}function lh(o,t){let e;for(const i of o.keyframes??[]){if(i.t>t)break;e=i}return{intensity:e?.intensity??o.intensity??1,pattern:e?.pattern??o.pattern}}function ob(o,t,e){const i=o.keyframes??[];if(i.length===0)return nm(o.pattern,t,e);const n=[t,...i.map(r=>r.t).filter(r=>r>t&&r<e),e];if(e<=t)return lh(o,t).intensity>0?nm(lh(o,t).pattern,t,e):0;let s=0;for(let r=0;r<n.length-1;r++){const a=lh(o,n[r]);a.intensity>0&&(s+=nm(a.pattern,n[r],n[r+1])*(n[r+1]-n[r]))}return s/(e-t)}function nm(o,t,e){if(o.kind==="steady")return 1;const{perMinute:i,dutyCycle:n,phase:s=0}=o,r=Math.min(Math.max(n,0),1);if(r===0||i<=0)return 0;const a=6e4/i,c=t/a+s,l=e/a+s;if(l<=c)return Math.min(Math.max(c-Math.floor(c),0),r)<r?1:0;const h=u=>Math.floor(u)*r+Math.min(u-Math.floor(u),r);return(h(l)-h(c))/(l-c)}function oa(o,t){const e=o.track,i={eastM:o.eastM,northM:o.northM,altitudeM:0,headingDeg:o.headingDeg};if(!e||e.length===0)return i;if(e.length===1||t<=e[0].t)return jy(e[0],o);const n=e[e.length-1];if(t>=n.t)return jy(n,o);for(let s=0;s<e.length-1;s++){const r=e[s],a=e[s+1];if(t<r.t||t>a.t)continue;const c=a.t-r.t,l=c===0?0:(t-r.t)/c;return{eastM:r.eastM+(a.eastM-r.eastM)*l,northM:r.northM+(a.northM-r.northM)*l,altitudeM:(r.altitudeM??0)+((a.altitudeM??0)-(r.altitudeM??0))*l,headingDeg:r.headingDeg??o.headingDeg}}return i}function o_(o,t){const e=(o.track??[]).filter(i=>i.gazeAzimuthDeg!==void 0);if(e.length!==0){if(t<=e[0].t)return e[0].gazeAzimuthDeg;for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];if(t>s.t)continue;const r=s.t-n.t,a=r===0?0:(t-n.t)/r,c=((s.gazeAzimuthDeg-n.gazeAzimuthDeg)%360+540)%360-180;return((n.gazeAzimuthDeg+c*a)%360+360)%360}return e[e.length-1].gazeAzimuthDeg}}function jy(o,t){return{eastM:o.eastM,northM:o.northM,altitudeM:o.altitudeM??0,headingDeg:o.headingDeg??t.headingDeg}}class yd{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(t){return yd.BY_KIND[t??"generic"]??yd.BY_KIND.generic}}class xc{constructor(t,e){this.samples=t,this.startMs=e}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(t,e,i,n){const s=xc.SAMPLE_MS,r=[];for(let l=i;l<=n+s/2;l+=s){const h=e(l-s/2),u=e(l+s/2);if(!h||!u)return;r.push(Math.hypot(u.eastM-h.eastM,u.northM-h.northM)/(s/1e3))}const a=[];let c=1;for(let l=0;l<r.length;l++){const h=r[l],u=(r[Math.min(l+1,r.length-1)]-r[Math.max(l-1,0)])/(2*s/1e3);if(h<xc.STANDING_MPS){c=1,a.push({speedMps:h,rpm:t.idleRpm,load:.1,gear:0});continue}const d=h*3.6,f=M=>d/t.kmhPer1000Rpm[M-1]*1e3;for(;c<t.kmhPer1000Rpm.length&&f(c)>t.shiftUpRpm;)c++;for(;c>1&&f(c)<t.shiftDownRpm;)c--;const p=Math.max(f(c),t.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),g=u>.15?Math.min(1,m+u/2.5):u<-.3?.05:m;a.push({speedMps:h,rpm:p,load:g,gear:c})}return new xc(a,i)}at(t){const e=(t-this.startMs)/xc.SAMPLE_MS,i=Math.min(Math.max(Math.floor(e),0),this.samples.length-1),n=this.samples[i],s=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(e-i,0),1);return{speedMps:n.speedMps+(s.speedMps-n.speedMps)*r,rpm:n.rpm+(s.rpm-n.rpm)*r,load:n.load+(s.load-n.load)*r,gear:r<.5?n.gear:s.gear}}}class k0{drives=new Map;at(t,e){const i=[],n=t.event.place?.[0],s=l=>{const h=t.observerTrack.getInterpolatedPoseAt(l),u=h?.lat??n?.lat,d=h?.lng??n?.lng;if(u===void 0||d===void 0||!n)return;const f=ae(u,d,n.lat,n.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3),a=t.vehicle;if(a){const l=yd.of(a.kind),h=this.drive(`observer:${a.kind}`,k0.trackKey(t),()=>xc.of(l,s,0,r));h&&i.push({id:"observer",profile:l,state:h.at(e),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const c=s(e);for(const l of t.decor){if(!l.engine||!c)continue;const h=yd.of(l.engine.kind),u=m=>{const g=oa(l,m);return{eastM:g.eastM,northM:g.northM}},d=this.drive(`decor:${l.id}`,k0.decorKey(l,r),()=>xc.of(h,u,0,r));if(!d)continue;const f=oa(l,e),p=Math.hypot(f.eastM-c.eastM,f.northM-c.northM,f.altitudeM);i.push({id:`decor:${l.id}`,profile:h,state:d.at(e),noise:l.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:p})}return i}drive(t,e,i){const n=this.drives.get(t);if(n&&n.key===e)return n.drive;const s=i();return this.drives.set(t,{key:e,drive:s}),s}static trackKey(t){return t.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(t,e){return`${e}|${t.eastM},${t.northM}|`+(t.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const Qy=864e5,t2=4e4;function c_(o){const t=Math.floor(o.getTime()/Qy);return{elapsedMs:o.getTime()-t*Qy,shiftM:{x:e2.unit(t,2654435761)*t2,z:e2.unit(t,2246822507)*t2}}}class e2{static unit(t,e){let i=Math.imul(t|0,e)^e;return i=Math.imul(i^i>>>15,739982445),i=Math.imul(i^i>>>12,695872825),i^=i>>>15,(i>>>0)/4294967295*2-1}}function i2(o,t,e,i,n,s,r){const a=i?.lat!==void 0&&i.lng!==void 0&&n?.lat!==void 0&&n.lng!==void 0?ae(n.lat,n.lng,i.lat,i.lng):{x:0,z:0};if(r){const h=t.getInterpolatedWeatherAt(0)??e,u=s===void 0?void 0:h.cloudLayers?.find(p=>p.id===s),d=(u?.windDirectionDeg??h.windDirectionDeg)*Math.PI/180,f=(u?.windSpeed??h.windSpeed)*r.elapsedMs/1e3;a.x+=r.shiftM.x-Math.sin(d)*f,a.z+=r.shiftM.z+Math.cos(d)*f}const c=Math.max(0,o),l=[0,...t.allKeyframes.map(h=>h.t).filter(h=>h>0&&h<c),c];for(let h=1;h<l.length;h++){const u=l[h-1],d=l[h]-u;if(d===0)continue;const f=32;for(let p=0;p<=f;p++){const m=t.getInterpolatedWeatherAt(u+d*p/f)??e,g=s===void 0?void 0:m.cloudLayers?.find(y=>y.id===s),M=(g?.windDirectionDeg??m.windDirectionDeg)*Math.PI/180,v=p===0||p===f?1:p%2===0?2:4,x=(g?.windSpeed??m.windSpeed)*d/1e3/f/3*v;a.x-=Math.sin(M)*x,a.z+=Math.cos(M)*x}}return a}const l_="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",h_=`
2
+ const CA="modulepreload",PA=function(o,t){return new URL(o,t).href},Qv={},$t=function(t,e,i){let n=Promise.resolve();if(e&&e.length>0){let r=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};const a=document.getElementsByTagName("link"),c=document.querySelector("meta[property=csp-nonce]"),l=c?.nonce||c?.getAttribute("nonce");n=r(e.map(h=>{if(h=PA(h,i),h in Qv)return;Qv[h]=!0;const u=h.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(!!i)for(let m=a.length-1;m>=0;m--){const g=a[m];if(g.href===h&&(!u||g.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${d}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":CA,u||(p.as="script"),p.crossOrigin="",p.href=h,l&&p.setAttribute("nonce",l),document.head.appendChild(p),u)return new Promise((m,g)=>{p.addEventListener("load",m),p.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${h}`)))})}))}function s(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return n.then(r=>{for(const a of r||[])a.status==="rejected"&&s(a.reason);return t().catch(s)})},$S=Math.PI/180,P0=111320;function ae(o,t,e,i){const n=P0*Math.cos(e*$S),s=(o-e)*P0;return{x:(t-i)*n,z:-s}}function Is(o,t,e,i){const n=P0*Math.cos(e*$S),s=-t,r=o;return{lat:e+s/P0,lng:i+r/n}}class Fl{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(t,e,i){const n=t.event.place?.[0],s=t.observerTrack;if(!n)return 0;const r=m=>{const g=s.getInterpolatedPoseAt(Math.max(0,m));if(!g||g.lat===void 0||g.lng===void 0)return;const M=ae(g.lat,g.lng,n.lat,n.lng);return{eastM:M.x,northM:-M.z,heading:g.headingDeg}},a=r(e-Fl.HALF_SPAN_MS),c=r(e+Fl.HALF_SPAN_MS),l=r(e);if(!a||!c||!l)return 0;const h=Math.hypot(c.eastM-a.eastM,c.northM-a.northM),u=2*Fl.HALF_SPAN_MS/1e3;if(h/u<Fl.MIN_SPEED_MS)return 0;const d=i.heightAt(c.eastM,c.northM)-i.heightAt(a.eastM,a.northM),f=Math.atan2(d,h)*180/Math.PI;if(l.heading===void 0)return f;const p=Math.atan2(c.eastM-a.eastM,c.northM-a.northM)*180/Math.PI;return f*Math.max(0,Math.cos((l.heading-p)*Math.PI/180))}}class Iu{static ISO=/^P(?:(\d+(?:[.,]\d+)?)W)?(?:(\d+(?:[.,]\d+)?)D)?(?:T(?:(\d+(?:[.,]\d+)?)H)?(?:(\d+(?:[.,]\d+)?)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;static seconds(t){const e=t.trim().toUpperCase(),i=Iu.ISO.exec(e);if(!i||e==="P"||e.endsWith("T"))return;const[,n,s,r,a,c]=i,l=u=>u===void 0?0:Number(u.replace(",",".")),h=l(n)*604800+l(s)*86400+l(r)*3600+l(a)*60+l(c);return Number.isFinite(h)?h:void 0}static parse(t){let e=t.trim();if(e==="")return;const i=e.slice(-1),n="?~%".includes(i)?i:"";n!==""&&(e=e.slice(0,-1).trim());const s=e.split("/");if(s.length>2)return;const r=s.map(u=>Iu.seconds(u));if(r.some(u=>u===void 0))return;const[a,c]=r,l=Math.min(a,c??a),h=Math.max(a,c??a);return{doubt:n,minSeconds:l,maxSeconds:h,chosenSeconds:(l+h)/2}}static isExact(t){const e=Iu.parse(t);return e!==void 0&&e.doubt===""&&e.minSeconds===e.maxSeconds}static format(t){const e=Math.max(0,Math.round(t*10)/10),i=Math.floor(e/3600),n=Math.floor(e%3600/60),s=Math.round(e%60*10)/10;return`PT${`${i>0?`${i}H`:""}${n>0?`${n}M`:""}${s>0||i===0&&n===0?`${s}S`:""}`}`}static say(t){const e=Math.round(t*10)/10;if(e<60)return`${e} s`;const i=Math.floor(e/3600),n=Math.floor(e%3600/60),s=Math.round(e%60*10)/10,r=[];return i>0&&r.push(`${i} h`),n>0&&r.push(`${n} min`),s>0&&r.push(`${s} s`),r.join(" ")}}class hi{static MOON_ANGULAR_WIDTH_DEG=.5237;static CANVAS_WIDTH_PX=640;static CANVAS_HEIGHT_PX=360;static angularWidthDeg(t){return 2*Math.atan(t.sizeM/(2*t.distanceM))*180/Math.PI}static inMoons(t){return t/hi.MOON_ANGULAR_WIDTH_DEG}static lerpAngular(t,e,i){if(!(!t||!e))return{widthDeg:t.widthDeg+(e.widthDeg-t.widthDeg)*i,heightDeg:t.heightDeg+(e.heightDeg-t.heightDeg)*i}}static sizeMAt(t,e){return 2*t*Math.tan(e*Math.PI/360)}static distanceMAt(t,e){return t/(2*Math.tan(e*Math.PI/360))}}function OA(o,t,e){if(!o||!t)return e<1?o:t;const i=((t.azimuthDeg-o.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((o.azimuthDeg+i*e)%360+360)%360,altitudeDeg:o.altitudeDeg+(t.altitudeDeg-o.altitudeDeg)*e}}function NA(o,t,e){const{bounds:i}=o;return t>=i.x&&t<=i.x+i.width&&e>=i.y&&e<=i.y+i.height}function Ss(o,t,e){return o+(t-o)*e}function ty(o){const t=/^#([0-9a-f]{6})$/i.exec(o);if(!t)return;const e=parseInt(t[1],16);return[e>>16&255,e>>8&255,e&255]}function LA(o){return`#${o.map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`}function kA(o,t,e){const i=ty(o),n=ty(t);return!i||!n?e<1?o:t:LA([Ss(i[0],n[0],e),Ss(i[1],n[1],e),Ss(i[2],n[2],e)])}function UA(o,t,e){const i={x:Ss(o.bounds.x,t.bounds.x,e),y:Ss(o.bounds.y,t.bounds.y,e),width:Ss(o.bounds.width,t.bounds.width,e),height:Ss(o.bounds.height,t.bounds.height,e)},n=Ss(o.angle,t.angle,e),s=Ss(o.transparency,t.transparency,e),r=Ss(o.haloScale,t.haloScale,e),a=Ss(o.blur??0,t.blur??0,e),c=Ss(o.brightness??0,t.brightness??0,e),l=kA(o.color,t.color,e),h=hi.lerpAngular(o.angular,t.angular,e),u=OA(o.aim,t.aim,e);return o.kind==="polygon"&&t.kind==="polygon"&&o.points.length===t.points.length?{...o,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:c,color:l,angular:h,aim:u,points:o.points.map((d,f)=>({x:Ss(d.x,t.points[f].x,e),y:Ss(d.y,t.points[f].y,e)}))}:{...e<1?o:t,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:c,color:l,angular:h,aim:u}}class go{static DEFAULT_COLOR="#e8e6df";static complete(t,e=[]){const i=new Map;return t.map((n,s)=>({keyframe:n,index:s})).sort((n,s)=>n.keyframe.t-s.keyframe.t).map(({keyframe:n,index:s})=>({t:n.t,shapes:(n.shapes??[]).map((r,a)=>{const c=`timeline.keyframes.${s}.shapes.${a}.shape`,l=go.completed(r,i.get(r.sourceId),c,e);return i.set(r.sourceId,l),{sourceId:r.sourceId,shape:l}})}))}static thin(t,e){const i=new Map,n=new Set;return t.map((s,r)=>({t:s.t,shapes:s.shapes.map(a=>{const c=i.get(a.sourceId);if(i.set(a.sourceId,a.shape),!c)return{sourceId:a.sourceId,shape:a.shape};const l=go.thinned(a.shape,c);if(e){const h=l;e(r,a.sourceId)?(delete h.bounds,delete h.points,n.add(a.sourceId)):n.delete(a.sourceId)&&(h.bounds=a.shape.bounds,a.shape.kind==="polygon"&&(h.points=a.shape.points),a.shape.aim&&(h.aim=a.shape.aim),a.shape.angular&&(h.angular=a.shape.angular))}return{sourceId:a.sourceId,shape:l}})}))}static thinned(t,e){const i=e,n={};for(const[s,r]of Object.entries(t))(typeof r=="object"&&r!==null&&!Array.isArray(r)&&"value"in r||r!==i[s]&&JSON.stringify(r)!==JSON.stringify(i[s]))&&(n[s]=r);return"bounds"in n&&(t.aim&&(n.aim=t.aim),t.angular&&(n.angular=t.angular)),n}static completed(t,e,i,n){const s=t.shape??{},r=e??go.firstAppearance(s,i,n),a={...r};s.bounds&&e&&(e.aim||e.angular)&&!s.aim&&!s.angular&&n.push({kind:"pixels-over-angles",path:i}),s.bounds&&(s.aim||delete a.aim,s.angular||delete a.angular);const c=s.kind??r.kind??"oval",l={...a,...s,kind:c};if(c==="polygon"&&!l.points){n.push({kind:"defaulted",path:`${i}.points`,expected:"rectangle"});const{width:h,height:u}=l.bounds;return{...l,points:[{x:0,y:0},{x:h,y:0},{x:h,y:u},{x:0,y:u}]}}return l}static firstAppearance(t,e,i){return t.kind||i.push({kind:"defaulted",path:`${e}.kind`,expected:'"oval"'}),t.color||i.push({kind:"defaulted",path:`${e}.color`,expected:`"${go.DEFAULT_COLOR}"`}),!t.bounds&&!t.aim&&i.push({kind:"unplaced",path:e}),!t.bounds&&!t.angular&&i.push({kind:"unsized",path:e}),{kind:t.kind??"oval",bounds:{...go.NEUTRAL_BOUNDS},color:go.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:hi.CANVAS_WIDTH_PX/2,y:hi.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Ud{keyframes=[];order=[];groups=[];span=0;addKeyframe(t,e){const i=this.findInsertIndex(t);if(this.keyframes[i]?.t===t){const n=new Set(e.map(s=>s.sourceId));this.keyframes[i]={t,shapes:[...this.keyframes[i].shapes.filter(s=>!n.has(s.sourceId)),...e]}}else this.keyframes.splice(i,0,{t,shapes:[...e]});for(const n of e)this.order.includes(n.sourceId)||this.order.push(n.sourceId)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getKeyframeAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e];return i?.t===t?i:void 0}getShapeAt(t,e){return this.getKeyframeAt(t)?.shapes.find(i=>i.sourceId===e)?.shape}getLatestShapeAt(t,e){let i=this.findInsertIndex(t);for(this.keyframes[i]?.t!==t&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return n.shape}}getInterpolatedShapeAt(t,e){const i=this.findShapeAtOrBefore(t,e);if(i?.t===t)return i.shape;const n=this.findShapeAtOrAfter(t,e);return i?n?UA(i.shape,n.shape,(t-i.t)/(n.t-i.t)):i.shape:n?.shape}findShapeAtOrBefore(t,e){let i=this.findInsertIndex(t);for(this.keyframes[i]?.t!==t&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}findShapeAtOrAfter(t,e){for(let i=this.findInsertIndex(t);i<this.keyframes.length;i++){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}hitTest(t,e,i,n){const s=this.sourceIds;for(let r=s.length-1;r>=0;r--){if(n?.has(s[r]))continue;const a=this.getInterpolatedShapeAt(t,s[r]);if(a&&NA(a,e,i))return{sourceId:s[r],shape:a}}}removeSource(t){for(let e=this.keyframes.length-1;e>=0;e--){const i=this.keyframes[e].shapes.filter(n=>n.sourceId!==t);i.length===0?this.keyframes.splice(e,1):i.length!==this.keyframes[e].shapes.length&&(this.keyframes[e]={t:this.keyframes[e].t,shapes:i})}this.order=this.order.filter(e=>e!==t),this.removeFromGroup(t)}removeShapeAt(t,e){const i=this.findInsertIndex(t),n=this.keyframes[i];if(n?.t!==t)return;const s=n.shapes.filter(r=>r.sourceId!==e);s.length===0?this.keyframes.splice(i,1):s.length!==n.shapes.length&&(this.keyframes[i]={t,shapes:s})}group(t,e){const i=new Set(t),n=[];for(const r of t){const a=this.topOf(r),c=a!==r&&this.leavesOf(a).every(l=>i.has(l))?a:r;c===r&&a!==r&&this.removeFromGroup(r),n.includes(c)||n.push(c)}if(n.length<2)return;const s=e??this.freshGroupId();return this.groups.push({id:s,members:n}),s}ungroup(t){const e=this.topOf(t);e!==t&&(this.groups=this.groups.filter(i=>i.id!==e))}groupMembers(t){const e=this.topOf(t);return e===t?void 0:this.leavesOf(e)}get allGroups(){return this.groups}setGroups(t,e=!0){this.groups=t.map(i=>({...i,members:[...i.members]})),e&&this.pruneGroups()}groupOf(t){return this.groups.find(e=>e.id===t)}leavesOf(t,e=new Set){const i=this.groupOf(t);return i?e.has(t)?[]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e))):[t]}parentOf(t){return this.groups.find(e=>e.members.includes(t))}topOf(t){let e=t;for(let i=this.parentOf(e),n=0;i&&n<100;i=this.parentOf(e),n++)e=i.id;return e}freshGroupId(){for(let t=this.groups.length+1;;t++){const e=`group-${t}`;if(!this.groupOf(e)&&!this.order.includes(e))return e}}removeFromGroup(t){const e=this.parentOf(t);e&&(e.members=e.members.filter(i=>i!==t),this.collapse())}pruneGroups(){const t=e=>this.order.includes(e)||this.groupOf(e)!==void 0;for(const e of this.groups)e.members=e.members.filter(t);this.collapse()}collapse(){for(let t=this.groups.find(e=>e.members.length<2);t;t=this.groups.find(e=>e.members.length<2)){const e=t;this.groups=this.groups.filter(i=>i!==e);for(const i of this.groups)i.members=i.members.flatMap(n=>n===e.id?e.members:[n])}}bringToFront(t){const e=this.order.indexOf(t);e!==-1&&(this.order.splice(e,1),this.order.push(t))}sendToBack(t){const e=this.order.indexOf(t);e!==-1&&(this.order.splice(e,1),this.order.unshift(t))}get duration(){const t=this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t;return Math.max(t,this.span)}get hasSpan(){return this.span>0}setSpan(t){this.span=Math.max(0,t)}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return this.span>0?{keyframes:this.keyframes,order:this.order,groups:this.groupsJson(),span:this.span}:{keyframes:this.keyframes,order:this.order,groups:this.groupsJson()}}groupsJson(){return this.groups.map(t=>({...t,members:[...t.members]}))}static fromJSON(t,e,i=!0){const n=new Ud;for(const s of go.complete(t.keyframes??[],e))n.addKeyframe(s.t,s.shapes);if(t.span!==void 0&&t.span>0&&(n.span=t.span),t.order){const s=n.order.filter(r=>!t.order.includes(r));n.order=[...t.order,...s]}return t.groups&&(n.groups=t.groups.filter(s=>typeof s?.id=="string"&&Array.isArray(s.members)).map(s=>({...s,members:[...s.members]})),i&&n.pruneGroups()),n}}function FA(o,t,e){return Math.max(t,Math.min(e,o))}function zA(o,t,e){const i=((t-o)%360+540)%360-180;return((o+i*e)%360+360)%360}function Kc(o,t,e){return o+(t-o)*e}function BA(o,t,e){return{lat:o.lat===void 0||t.lat===void 0?void 0:Kc(o.lat,t.lat,e),lng:o.lng===void 0||t.lng===void 0?void 0:Kc(o.lng,t.lng,e),elevationM:Kc(o.elevationM,t.elevationM,e),headingDeg:o.headingDeg===void 0||t.headingDeg===void 0?void 0:zA(o.headingDeg,t.headingDeg,e),pitchDeg:Kc(o.pitchDeg,t.pitchDeg,e),rollDeg:Kc(o.rollDeg??0,t.rollDeg??0,e),fovDeg:Kc(o.fovDeg,t.fovDeg,e),fNumber:o.fNumber,focusDistanceM:o.focusDistanceM,filter:o.filter}}class Mn{static at(t,e,i,n,s){const r=t[i],c=t[i+1]-r;if(c<=0)return e[i];const l=Mn.tangent(t,e,i,s),h=Mn.tangent(t,e,i+1,s),u=(n-r)/c,d=u*u,f=d*u;return(2*f-3*d+1)*e[i]+(f-2*d+u)*c*l+(-2*f+3*d)*e[i+1]+(f-d)*c*h}static SETTLE_MS=120;static ARRIVAL=.5;static gaze(t,e,i,n){const s=t[i],a=t[i+1]-s;if(a<=0)return e[i];const c=h=>h+1<e.length?e[h+1]===e[h]:!0,l=e[i+1]!==e[i];if(l&&c(i+1)){const h=Mn.tangent(t,e,i,!0),u=Mn.ARRIVAL*(e[i+1]-e[i])/a;return Mn.hermite(e[i],h,e[i+1],u,a,(n-s)/a)}return!l&&i>0&&e[i-1]!==e[i]?e[i]+Mn.settle(t,e,i,n-s,a):Mn.at(t,e,i,n,!0)}static settle(t,e,i,n,s){const r=t[i]-t[i-1];if(r<=0||n<=0)return 0;const a=Mn.ARRIVAL*(e[i]-e[i-1])/r,c=Math.min(Mn.SETTLE_MS,.4*r),l=Number.isFinite(s)?(1-Math.min(1,n/s))**2:1;return a*n*Math.exp(-n/c)*l}static hermite(t,e,i,n,s,r){const a=r*r,c=a*r;return(2*c-3*a+1)*t+(c-2*a+r)*s*e+(-2*c+3*a)*i+(c-a)*s*n}static BRAKE_S=.8;static paced(t,e,i,n){if(!i&&!n)return t;const s=e>0?Math.min(.5,Mn.BRAKE_S/e):.5;if(i&&n){const a=1/(1-s);return t<=s?a*t*t/(2*s):t>=1-s?1-a*(1-t)*(1-t)/(2*s):a*(t-s/2)}const r=a=>{const c=1/(1-s/2);if(a<=1-s)return c*a;const l=a-(1-s);return c*(1-s)+c*(l-l*l/(2*s))};return n?r(t):1-r(1-t)}static tangent(t,e,i,n){const s=t.length-1,r=f=>(e[f+1]-e[f])/(t[f+1]-t[f]||1);if(i===0)return n?0:r(0);if(i===s)return n?0:r(s-1);const a=r(i-1),c=r(i);if(a*c<=0)return 0;const l=t[i]-t[i-1],h=t[i+1]-t[i],u=2*h+l,d=h+2*l;return(u+d)/(u/a+d/c)}}class Zu{keyframes=[];addKeyframe(t,e){const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,pose:e}:this.keyframes.splice(i,0,{t,pose:e})}clear(){this.keyframes.length=0}removeKeyframeAt(t){const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getLatestPoseAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].pose:void 0}getInterpolatedPoseAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.pose;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];if(!i)return n?.pose;if(!n)return this.settledAfterEnd(e-1,t);const s=BA(i.pose,n.pose,FA((t-i.t)/(n.t-i.t),0,1));return this.humanly(e-1,t,s)}settledAfterEnd(t,e){const i=this.keyframes[t];if(t<1)return i.pose;const n=this.keyframes[t-1],s=[n.t,i.t],r=(h,u)=>h===void 0||u===void 0?0:Mn.settle(s,[h,u],1,e-i.t,1/0),a=n.pose.headingDeg===void 0||i.pose.headingDeg===void 0?void 0:((i.pose.headingDeg-n.pose.headingDeg)%360+540)%360-180,c=i.pose.headingDeg===void 0||a===void 0?i.pose.headingDeg:((i.pose.headingDeg+r(0,a))%360+360)%360,l=i.pose.pitchDeg+r(n.pose.pitchDeg,i.pose.pitchDeg);return c===i.pose.headingDeg&&l===i.pose.pitchDeg?i.pose:{...i.pose,headingDeg:c,pitchDeg:l}}humanly(t,e,i){const n=Math.max(0,t-1),s=Math.min(this.keyframes.length-1,t+2),r=this.keyframes.slice(n,s+1),a=t-n,c=r.map(y=>y.t),l=(y,w)=>{const b=r.map(E=>y(E.pose));if(!b.some(E=>E===void 0))return Mn.at(c,b,a,e,w)},h=y=>{const w=r.map(b=>y(b.pose));if(!w.some(b=>b===void 0))return Mn.gaze(c,w,a,e)},u=r.map(y=>y.pose.headingDeg);let d;if(u.every(y=>y!==void 0)){const y=[u[0]];for(let w=1;w<u.length;w++)y.push(y[w-1]+((u[w]-u[w-1])%360+540)%360-180);d=(Mn.gaze(c,y,a,e)%360+360)%360}const f=this.keyframes[t],p=this.keyframes[t+1],m=(y,w)=>y.lat===w.lat&&y.lng===w.lng&&y.elevationM===w.elevationM,g=!m(f.pose,p.pose),M=g&&t>0&&m(this.keyframes[t-1].pose,f.pose),v=g&&t+2<this.keyframes.length&&m(p.pose,this.keyframes[t+2].pose);let x;if(M||v){const y=Mn.paced((e-f.t)/(p.t-f.t),(p.t-f.t)/1e3,M,v),w=(b,E)=>b===void 0||E===void 0?void 0:b+(E-b)*y;x={lat:w(f.pose.lat,p.pose.lat),lng:w(f.pose.lng,p.pose.lng),elevationM:w(f.pose.elevationM,p.pose.elevationM)}}return{...i,lat:x?x.lat:l(y=>y.lat,!1)??i.lat,lng:x?x.lng:l(y=>y.lng,!1)??i.lng,elevationM:x?x.elevationM:l(y=>y.elevationM,!1)??i.elevationM,headingDeg:d??i.headingDeg,pitchDeg:h(y=>y.pitchDeg)??i.pitchDeg,rollDeg:l(y=>y.rollDeg??0,!0)??i.rollDeg,fovDeg:l(y=>y.fovDeg,!0)??i.fovDeg}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new Zu;for(const i of t.keyframes)e.addKeyframe(i.t,i.pose);return e}}class Mo{static MAX_CHANGE_PER_S=.05;points;followed;constructor(t){let e="none",i=0;this.points=t.map(({t:n,weather:s})=>(s.precipitationType!=="none"&&(e=s.precipitationType,i=s.precipitationIntensity),{t:n,lastFalling:e,lastFallingIntensity:i,intensity:s.precipitationType==="none"?0:s.precipitationIntensity,type:s.precipitationType})),this.followed=[];for(let n=0;n<this.points.length;n++){if(n===0){this.followed.push(this.points[0].intensity);continue}const s=this.points[n-1],r=this.points[n];this.followed.push(Mo.follow(this.followed[n-1],s.intensity,r.intensity,(r.t-s.t)/1e3,(r.t-s.t)/1e3))}}at(t){if(this.points.length===0||t<this.points[0].t)return;let e=this.points.length-1;for(;e>0&&this.points[e].t>t;)e--;const i=this.points[e],n=this.points[e+1],s=n?Mo.follow(this.followed[e],i.intensity,n.intensity,(n.t-i.t)/1e3,(t-i.t)/1e3):Mo.follow(this.followed[e],i.intensity,i.intensity,1,(t-i.t)/1e3);return{type:Mo.typeBetween(i,n,t,s),intensity:s,character:Mo.characterBetween(i,n,t)}}static characterBetween(t,e,i){return t.type==="none"?e&&e.type!=="none"?e.intensity:t.lastFallingIntensity:!e||e.type==="none"?t.intensity:t.intensity+(e.intensity-t.intensity)*(i-t.t)/(e.t-t.t||1)}static typeBetween(t,e,i,n){return t.type==="none"?e&&e.type!=="none"&&i>t.t?e.type:n>0?t.lastFalling:"none":e&&e.type==="none"&&n<=0?"none":t.type}static follow(t,e,i,n,s){const r=Mo.MAX_CHANGE_PER_S,a=n>0?(i-e)/n:0,c=u=>e+a*Math.min(Math.max(u,0),n);let l=t,h=0;for(let u=0;u<8&&h<s;u++){const d=c(h)-l;if(Math.abs(d)<1e-9){const x=h<n?a:0;if(Math.abs(x)<=r){const w=h<n?Math.min(s,n):s;l=c(w),h=w;continue}const y=Math.min(s,n);l+=Math.sign(x)*r*(y-h),h=y;continue}const f=Math.sign(d),p=h<n?a:0,m=r-f*p,g=m>0?h+Math.abs(d)/m:1/0,M=h<n?n:1/0,v=Math.min(s,g,M);l+=f*r*(v-h),h=v,v===g&&(l=c(h))}return Math.min(1,Math.max(0,l))}}const UM=1e3,HA=.65,GA=.05,yp={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function O0(o){if(o.cloudLayers!==void 0)return o.cloudLayers;const t=[],e=o.lowerCloudCover??o.cloudCover;return e>0&&t.push({id:"lower",type:"cumulus",baseM:o.cloudBaseM??UM,thicknessM:650,coverage:e,sizeM:1400,density:1,darkness:o.cloudDarkness}),(o.highCloudCover??0)>0&&t.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:o.highCloudCover,sizeM:2200,density:.35,darkness:o.cloudDarkness,iceCrystalAlignment:o.iceCrystalAlignment}),t}function Ei(o,t,e){return o+(t-o)*e}function FM(o,t,e){const i=((t-o)%360+540)%360-180;return((o+i*e)%360+360)%360}function VA(o,t,e){return Math.max(t,Math.min(e,o))}function WA(o=[],t=[],e){if(!(!o.length&&!t.length))return[...new Set([...o.map(i=>i.id),...t.map(i=>i.id)])].map(i=>{const n=o.find(c=>c.id===i),s=t.find(c=>c.id===i),r=n??{...s,density:0},a=s??{...n,density:0};return{...r,eastM:Ei(r.eastM,a.eastM,e),northM:Ei(r.northM,a.northM,e),baseM:Ei(r.baseM,a.baseM,e),thicknessM:Ei(r.thicknessM,a.thicknessM,e),widthM:Ei(r.widthM,a.widthM,e),depthM:Ei(r.depthM,a.depthM,e),rotationDeg:FM(r.rotationDeg,a.rotationDeg,e),density:Ei(r.density,a.density,e),darkness:Ei(r.darkness??0,a.darkness??0,e)}})}function XA(o,t,e){if(o.cloudLayers===void 0&&t.cloudLayers===void 0)return;const i=O0(o),n=O0(t);return e>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const a=i.find(u=>u.id===r),c=n.find(u=>u.id===r),l=a??{...c,coverage:0},h=c??{...a,coverage:0};return{...l,instances:WA(a?.instances,c?.instances,e),baseM:Ei(l.baseM,h.baseM,e),thicknessM:Ei(l.thicknessM,h.thicknessM,e),coverage:Ei(l.coverage,h.coverage,e),sizeM:Ei(l.sizeM,h.sizeM,e),density:Ei(l.density,h.density,e),darkness:Ei(l.darkness??o.cloudDarkness,h.darkness??t.cloudDarkness,e),iceCrystalAlignment:l.iceCrystalAlignment===void 0||h.iceCrystalAlignment===void 0?void 0:Ei(l.iceCrystalAlignment,h.iceCrystalAlignment,e),windSpeed:l.windSpeed===void 0&&h.windSpeed===void 0?void 0:Ei(l.windSpeed??o.windSpeed,h.windSpeed??t.windSpeed,e),windDirectionDeg:l.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:FM(l.windDirectionDeg??o.windDirectionDeg,h.windDirectionDeg??t.windDirectionDeg,e)}})}function YA(o,t,e){return{cloudLayers:XA(o,t,e),cloudCover:Ei(o.cloudCover,t.cloudCover,e),cloudDarkness:Ei(o.cloudDarkness,t.cloudDarkness,e),highCloudCover:o.highCloudCover===void 0||t.highCloudCover===void 0?void 0:Ei(o.highCloudCover,t.highCloudCover,e),iceCrystalAlignment:o.iceCrystalAlignment===void 0||t.iceCrystalAlignment===void 0?void 0:Ei(o.iceCrystalAlignment,t.iceCrystalAlignment,e),rareIceCrystals:o.rareIceCrystals===void 0||t.rareIceCrystals===void 0?void 0:Ei(o.rareIceCrystals,t.rareIceCrystals,e),lowerCloudCover:o.lowerCloudCover===void 0||t.lowerCloudCover===void 0?void 0:Ei(o.lowerCloudCover,t.lowerCloudCover,e),cloudBaseM:o.cloudBaseM===void 0||t.cloudBaseM===void 0?void 0:Ei(o.cloudBaseM,t.cloudBaseM,e),relativeHumidity:o.relativeHumidity===void 0||t.relativeHumidity===void 0?void 0:Ei(o.relativeHumidity,t.relativeHumidity,e),precipitationType:e<1?o.precipitationType:t.precipitationType,precipitationIntensity:Ei(o.precipitationIntensity,t.precipitationIntensity,e),windDirectionDeg:FM(o.windDirectionDeg,t.windDirectionDeg,e),windSpeed:Ei(o.windSpeed,t.windSpeed,e),storm:e<1?o.storm:t.storm}}class Ju{keyframes=[];ramp;addKeyframe(t,e){this.ramp=void 0;const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,weather:e}:this.keyframes.splice(i,0,{t,weather:e})}clear(){this.ramp=void 0,this.keyframes.length=0}removeKeyframeAt(t){this.ramp=void 0;const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getLatestWeatherAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].weather:void 0}getInterpolatedWeatherAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.weather;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];return i?n?YA(i.weather,n.weather,VA((t-i.t)/(n.t-i.t),0,1)):i.weather:n?.weather}getActualWeatherAt(t){const e=this.getInterpolatedWeatherAt(t);if(!e)return;const i=(this.ramp??=new Mo(this.keyframes)).at(t);if(!i)return e;const{type:n,intensity:s,character:r}=i,a=r>0?Math.min(1,s/r):n==="none"?0:1;return{...e,precipitationType:n,precipitationIntensity:r,precipitationAmount:a}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new Ju;for(const i of t.keyframes)e.addKeyframe(i.t,{...yp,...i.weather});return e}}class ju{keyframes=[];addKeyframe(t,e){const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,sound:e}:this.keyframes.splice(i,0,{t,sound:e})}clear(){this.keyframes.length=0}removeKeyframeAt(t){const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}getLatestSoundAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].sound:void 0}getInterpolatedSoundAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.sound;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];if(!i)return n?.sound;if(!n)return i.sound;const s=(t-i.t)/(n.t-i.t);return this.lerp(i.sound,n.sound,Math.max(0,Math.min(1,s)))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new ju;for(const i of t.keyframes)e.addKeyframe(i.t,i.sound);return e}lerp(t,e,i){return{kind:i<1?t.kind:e.kind,volume:t.volume+(e.volume-t.volume)*i,pitchHz:t.pitchHz+(e.pitchHz-t.pitchHz)*i,src:i<1?t.src:e.src}}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}}const $A=100,KA={kind:"none",volume:0,pitchHz:$A};class ea{static MAX_SPECKS=4;static BROADCAST_35MM={framesPerSecond:24,contrast:1.6,tint:[.99,.98,.92],softness:1.6/480,specksPerFrame:1.15,speckRadius:1.6/480,speckRadiusMax:4.5/480,weave:[.25/640,.6/480],grain:.008};static hash(t,e){const i=Math.sin(t*127.1+e*311.7)*43758.5453;return i-Math.floor(i)}static frameAt(t,e){return Math.floor(e*t.framesPerSecond/1e3)}static frame(t,e){const i=a=>ea.hash(e,a),n=a=>(i(a)+i(a+1)+i(a+2)-1.5)*2,s=Math.min(1,t.specksPerFrame/ea.MAX_SPECKS),r=[];for(let a=0;a<ea.MAX_SPECKS;a++){const c=10+a*6;if(i(c)>=s)continue;const l=i(c+3)**3;r.push({u:i(c+1),v:i(c+2),radius:t.speckRadius*.6+l*(t.speckRadiusMax-t.speckRadius*.6),kept:.25+.4*i(c+4)})}return{weave:[n(1)*t.weave[0],n(4)*t.weave[1]],specks:r,seed:i(7)}}}class zl{static DEFAULT_FOCAL_MM=50;static FOCAL_RANGE_MM={minMm:14,maxMm:135};static BODIES=[{id:"eos-450d",name:"Canon EOS 450D (APS-C)",widthMm:22.2,heightMm:14.8,pixelUm:5.2,year:2008},{id:"eos-60da",name:"Canon EOS 60Da (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.3,year:2012},{id:"eos-70d",name:"Canon EOS 70D (APS-C)",widthMm:22.5,heightMm:15,pixelUm:4.1,year:2013},{id:"eos-80d",name:"Canon EOS 80D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:3.7,year:2016},{id:"eos-7d",name:"Canon EOS 7D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.1,year:2009},{id:"eos-7d-ii",name:"Canon EOS 7D Mark II (APS-C)",widthMm:22.4,heightMm:15,pixelUm:4.1,year:2014},{id:"eos-5d",name:"Canon EOS 5D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:8.2,year:2005},{id:"eos-5d-ii",name:"Canon EOS 5D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:6.4,year:2008},{id:"eos-5d-iii",name:"Canon EOS 5D Mark III (full frame)",widthMm:36,heightMm:24,pixelUm:6.25,year:2012},{id:"eos-5d-iv",name:"Canon EOS 5D Mark IV (full frame)",widthMm:36,heightMm:24,pixelUm:5.36,year:2016},{id:"eos-6d",name:"Canon EOS 6D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:6.55,year:2012},{id:"eos-6d-ii",name:"Canon EOS 6D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:5.77,year:2017},{id:"nikon-d3",name:"Nikon D3 / D700 (full frame)",widthMm:36,heightMm:23.9,pixelUm:8.44,year:2007},{id:"nikon-d7000",name:"Nikon D7000 (DX)",widthMm:23.6,heightMm:15.6,pixelUm:4.78,year:2010},{id:"nikon-d7100",name:"Nikon D7100 / D7200 (DX)",widthMm:23.5,heightMm:15.6,pixelUm:3.9,year:2013},{id:"nikon-d500",name:"Nikon D500 / D7500 (DX)",widthMm:23.5,heightMm:15.7,pixelUm:4.2,year:2016}];static instruments(){return zl.BODIES.map(t=>({id:t.id,category:"dslr",name:t.name,projection:"rectilinear",frame:{widthMm:t.widthMm,heightMm:t.heightMm,focalLengthMm:zl.DEFAULT_FOCAL_MM,focalRangeMm:zl.FOCAL_RANGE_MM},fNumber:8,fNumberRange:{min:1.4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/8e3,max:3600},years:{from:t.year},apertureBlades:7,detailUm:t.pixelUm,medium:{kind:"sensor",iso:100}}))}static names(){return Object.fromEntries(zl.BODIES.map(t=>[t.id,t.name]))}}class dr{static DEFAULT_EYEPIECE_MM=26;static DEFAULT_APPARENT_FIELD_DEG=52;static FIELD_STOP_MM=2*dr.DEFAULT_EYEPIECE_MM*Math.tan(dr.DEFAULT_APPARENT_FIELD_DEG*Math.PI/360);static RANGE={min:26/40*.63,max:26/6*3};static BINOCULARS=[{id:"binoculars-zeiss-6x30",name:"Carl Zeiss 6x30",magnification:6,apertureMm:30,trueFieldDeg:5,fromYear:1960},{id:"binoculars-zeiss-dialyt-10x40",name:"Carl Zeiss Dialyt 10x40 B T*",magnification:10,apertureMm:40,trueFieldDeg:6.3,fromYear:1975},{id:"binoculars-jenoptem-10x50",name:"Jenoptem 10x50 W",magnification:10,apertureMm:50,trueFieldDeg:7.3,fromYear:1960},{id:"binoculars-swarovski-7x50-habicht",name:"Swarovski 7x50 SL Habicht",magnification:7,apertureMm:50,trueFieldDeg:6.6,fromYear:1960},{id:"binoculars-swarovski-7x50-slc",name:"Swarovski 7x50 SLC",magnification:7,apertureMm:50,trueFieldDeg:7.1,fromYear:1990},{id:"binoculars-nikon-10x42-edg",name:"Nikon 10x42 EDG",magnification:10,apertureMm:42,trueFieldDeg:6.5,fromYear:2011},{id:"binoculars-canon-15x50-is",name:"Canon 15x50 IS All Weather",magnification:15,apertureMm:50,trueFieldDeg:4.5,fromYear:2008},{id:"binoculars-celestron-15x70",name:"Celestron 15x70 SkyMaster",magnification:15,apertureMm:70,trueFieldDeg:4.4,fromYear:1990},{id:"binoculars-miyauchi-25x141",name:"Miyauchi BR-141 Galaxy 45 25x141",magnification:25,apertureMm:141,trueFieldDeg:2.6,fromYear:2e3}];static TELESCOPES=[{id:"telescope-generic-60-700",name:"Telescope 60/700",apertureMm:60,focalLengthMm:700},{id:"telescope-generic-60-1000",name:"Telescope 60/1000",apertureMm:60,focalLengthMm:1e3},{id:"telescope-celestron-onyx-80edf",name:"Celestron Onyx 80EDF",apertureMm:80,focalLengthMm:500,fromYear:2010},{id:"telescope-celestron-c5",name:"Celestron C5 f/10",apertureMm:125,focalLengthMm:1250,fromYear:1970},{id:"telescope-celestron-c8",name:"Celestron C8 f/10",apertureMm:203,focalLengthMm:2032,fromYear:1970},{id:"telescope-celestron-c11",name:"Celestron C11 f/10",apertureMm:280,focalLengthMm:2800,fromYear:1970},{id:"telescope-celestron-c14",name:"Celestron C14 f/11",apertureMm:355.6,focalLengthMm:3910,fromYear:1970},{id:"telescope-meade-etx-80",name:"Meade ETX 80 f/5",apertureMm:80,focalLengthMm:400,fromYear:1996},{id:"telescope-meade-etx-90",name:"Meade ETX 90 f/13.8",apertureMm:90,focalLengthMm:1242,fromYear:1996},{id:"telescope-meade-etx-125",name:"Meade ETX 125 f/15",apertureMm:127,focalLengthMm:1900,fromYear:1996},{id:"telescope-meade-lx200-8",name:"Meade LX200 8 in f/10",apertureMm:200,focalLengthMm:2e3,fromYear:1992},{id:"telescope-meade-lx200-10",name:"Meade LX200 10 in f/10",apertureMm:250,focalLengthMm:2500,fromYear:1992},{id:"telescope-meade-lx200-12",name:"Meade LX200 12 in f/10",apertureMm:305,focalLengthMm:3048,fromYear:1992},{id:"telescope-meade-lx200-14",name:"Meade LX200 14 in f/10",apertureMm:355,focalLengthMm:3556,fromYear:1992},{id:"telescope-meade-lx200-16",name:"Meade LX200 16 in f/10",apertureMm:406,focalLengthMm:4064,fromYear:1992}];static instruments(){const t=dr.BINOCULARS.map(n=>({id:n.id,category:"binoculars",name:n.name,projection:"rectilinear",visualAid:{apertureMm:n.apertureMm,magnification:n.magnification,trueFieldDeg:n.trueFieldDeg},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}})),e=dr.FIELD_STOP_MM,i=dr.TELESCOPES.map(n=>({id:n.id,category:"telescope",name:n.name,projection:"rectilinear",frame:{widthMm:e*16/9,heightMm:e,focalLengthMm:n.focalLengthMm,focalRangeMm:{minMm:n.focalLengthMm*dr.RANGE.min,maxMm:n.focalLengthMm*dr.RANGE.max}},visualAid:{apertureMm:n.apertureMm,eyepieceFocalMm:dr.DEFAULT_EYEPIECE_MM},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}}));return[...t,...i]}static names(){return Object.fromEntries(dr.instruments().map(t=>[t.id,t.name]))}}const $d=[{id:"eye",category:"eye",name:"Naked eye",projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",category:"camera",name:"Camera, unknown device",projection:"rectilinear",fNumber:8,fNumberRange:{min:2,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:8},apertureBlades:6},{id:"roamer-1-120",filmFormat:"120",category:"camera",name:"Roamer 1, 120 film",projection:"rectilinear",frame:{widthMm:74,heightMm:60,focalLengthMm:100},fNumber:11,exposureSeconds:1/50,years:{from:1930,to:1965},detailUm:40,medium:{kind:"negative",iso:125}},{id:"instamatic-126",filmFormat:"126",category:"camera",name:"Instamatic, 126 film",projection:"rectilinear",frame:{widthMm:28,heightMm:28,focalLengthMm:43},fNumber:11,exposureSeconds:1/90,years:{from:1963,to:1988},apertureBlades:5,detailUm:20,medium:{kind:"negative",iso:64}},{id:"slr-35mm-50",filmFormat:"135",category:"camera",name:"35 mm SLR, 50 mm lens",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:50},fNumber:8,fNumberRange:{min:2,max:16},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},years:{from:1959},apertureBlades:6,detailUm:20,medium:{kind:"negative",iso:100}},{id:"cine-35mm-broadcast",filmFormat:"35mm-cine",category:"camera",name:"35 mm film camera, seen on television",projection:"rectilinear",frame:{widthMm:21.3,heightMm:16,focalLengthMm:50,focalRangeMm:{minMm:18,maxMm:300}},fNumber:11,fNumberRange:{min:2,max:22},exposureSeconds:1/48,exposureRangeSeconds:{min:1/96,max:1/24},years:{from:1950,to:1995},apertureBlades:6,detailUm:15,medium:{kind:"negative",iso:100,print:ea.BROADCAST_35MM}},{id:"slr-35mm-zoom",filmFormat:"135",category:"camera",name:"35 mm SLR, 70-210 mm zoom",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:135,focalRangeMm:{minMm:70,maxMm:210}},fNumber:8,fNumberRange:{min:4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},apertureBlades:8,years:{from:1975},detailUm:20,medium:{kind:"negative",iso:100}},{id:"phone-landscape",category:"phone",name:"Phone, held sideways",projection:"rectilinear",frame:{widthMm:7.6,heightMm:5.7,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"phone-portrait",category:"phone",name:"Phone, held upright",projection:"rectilinear",frame:{widthMm:5.7,heightMm:7.6,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"dashcam",mounted:!0,category:"video",name:"Dashcam",projection:"equidistant",frame:{widthMm:5.76,heightMm:3.24,focalLengthMm:3.2},fNumber:2,exposureSeconds:1/30,exposureRangeSeconds:{min:1/1e4,max:1/30},years:{from:2008},apertureBlades:void 0,detailUm:3,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},{id:"cctv",mounted:!0,category:"video",name:"Security camera",projection:"rectilinear",frame:{widthMm:4.8,heightMm:3.6,focalLengthMm:3.6},fNumber:2,exposureSeconds:1/50,exposureRangeSeconds:{min:1/1e5,max:1/50},years:{from:1990},apertureBlades:void 0,detailUm:6,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},...zl.instruments(),...dr.instruments()];class Xi{static get default(){return $d[0]}static byId(t){return $d.find(e=>e.id===t)??this.default}static UNAIDED_FIELD_DEG=60;static UNAIDED_ASPECT=16/9;static fieldOfViewDeg(t){const e=t.frame;return e?Xi.fieldOf(t.projection,e.heightMm,e.focalLengthMm):t.visualAid?.trueFieldDeg??Xi.UNAIDED_FIELD_DEG}static fieldOf(t,e,i){return(t==="equidistant"?e/i:2*Math.atan(e/(2*i)))*180/Math.PI}static aspectOf(t){const e=t.frame;return e?e.widthMm/e.heightMm:Xi.UNAIDED_ASPECT}static frameWidthPx(t,e){return Math.round(e*Xi.aspectOf(t))}static CATEGORIES=["eye","camera","dslr","phone","video","binoculars","telescope"];static unavailability(t,e){const i=t.years;if(!(e===void 0||!i)){if(e<i.from)return{kind:"before",from:i.from};if(i.to!==void 0&&e>i.to)return{kind:"after",to:i.to}}}static availableAt(t){return t===void 0?$d:$d.filter(e=>!e.years||t>=e.years.from&&(e.years.to===void 0||t<=e.years.to))}static fieldOfViewDegAt(t,e){const i=t.frame;if(!(!i||e<=0))return Xi.fieldOf(t.projection,i.heightMm,e)}static focalLengthMmFor(t,e){const i=t.frame;if(!(!i||e<=0||e>=180))return t.projection==="equidistant"?i.heightMm/(e*Math.PI/180):i.heightMm/(2*Math.tan(e*Math.PI/360))}static bladesShowing(t,e){if(t.apertureBlades===void 0)return 0;const i=e??t.fNumber,n=t.fNumberRange?.min;if(i===void 0||n===void 0)return 1;const s=Math.max(0,Math.min(1,(i/n-1)/.3));return s*s*(3-2*s)}static starPointsOf(t,e){const i=t.apertureBlades;return i===void 0||i<3||Xi.bladesShowing(t,e)<.5?0:i%2===0?i:i*2}}class tr{constructor(t){this.entries=t}static empty(){return new tr(new Map)}get size(){return this.entries.size}at(t){return this.entries.get(t)}paths(){return[...this.entries.keys()]}set(t,e){e.basis==="stated"&&e.rationale===void 0&&e.how===void 0?this.entries.delete(t):this.entries.set(t,e)}clear(t){for(const e of this.entries.keys())(e===t||e.startsWith(`${t}.`))&&this.entries.delete(e)}static strip(t){const e=new tr(new Map);return{recording:tr.stripValue(t,[],e),provenance:e}}static restore(t,e){if(e.size===0)return t;const i={...t},n=new Set([i]);for(const s of e.paths()){const r=e.at(s),a=s.split("."),c=tr.writableHolderOf(i,a,n);if(!c)continue;const l=a[a.length-1],h=c[l];h!==void 0&&(r.of!==void 0&&JSON.stringify(r.of)!==JSON.stringify(h)||(c[l]={value:h,...r.basis==="stated"?{}:{basis:r.basis},...r.rationale===void 0?{}:{rationale:r.rationale},...r.how===void 0?{}:{how:r.how}}))}return i}static isWrapper(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"value"in t}static stripValue(t,e,i){return tr.isWrapper(t)?(i.set(e.join("."),{basis:t.basis??"stated",...t.rationale===void 0?{}:{rationale:t.rationale},...t.how===void 0?{}:{how:t.how},of:t.value}),tr.stripValue(t.value,e,i)):Array.isArray(t)?t.map((n,s)=>tr.stripValue(n,[...e,String(s)],i)):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([n,s])=>[n,tr.stripValue(s,[...e,n],i)])):t}static writableHolderOf(t,e,i){let n=t;for(const s of e.slice(0,-1)){const r=n[s];if(typeof r!="object"||r===null)return;if(i.has(r)){n=r;continue}const a=Array.isArray(r)?[...r]:{...r};i.add(a),n[s]=a,n=a}return n}}class Ps extends Error{}class xp{constructor(t){this.name=t}validate(t){return!0}}class KS extends xp{min;max;constructor(t,e,i){super(t),this.min=e,this.max=i}validate(t){if(typeof t!="number")throw new Ps(`${this.name} value must be a number, but was ${t}`);if(t<this.min||t>this.max)throw new Ps(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${t}`);return super.validate(t)}}class gi{name;min;max;duration;subUnit;validator;constructor(t,e,i,n,s=new KS(t,e,i)){this.name=t,this.min=e,this.max=i,this.subUnit=n,this.duration=n?(n.max-n.min+1)*n.duration:1,this.validator=s}validate(t){return this.validator.validate(t)}[Symbol.iterator](){let t=this.min;return{next:()=>{const e={done:t>this.max,value:t};return t++,e}}}}class zM{millisecond;second;minute;hour;day;month;year}class qA extends zM{}class qS extends qA{millisecond=new gi("millisecond",0,999,void 0);second=new gi("second",0,59,this.millisecond);minute=new gi("minute",0,59,this.second);hour=new gi("hour",0,23,this.minute);day=new gi("day",1,31,this.hour);month=new gi("month",1,12,this.day);year=new gi("year",0,9999,this.month)}const oe=new qS;class ZS extends KS{constructor(t=1,e=12){super("month",t,e)}}class Bl extends gi{static Month28=new Bl(28);static Month29=new Bl(29);static ThirtyDays=new Bl(30);static ThirtyOneDays=new Bl(31);constructor(t,e=new ZS(1,t)){super("month",1,t,oe.day,e)}static create(t,e){switch(t){case 1:case 3:case 5:case 7:case 8:case 10:case 12:return this.ThirtyOneDays;case 2:return e%4===0?this.Month29:this.Month28;case 4:case 6:case 9:case 11:return this.ThirtyDays;default:throw new Ps("Unsupported month",t,e)}}}class ia{static instance=new ia;render(t){return t.value.toString()}}class jn{unit;#t;constructor(t,e){this.unit=e,this.value=typeof t=="number"?t:t.value}get value(){return this.#t}set value(t){this.unit.validate(t),this.#t=t}get duration(){return this.value*this.unit.duration}#e(t){if(this.constructor.name!==t.constructor.name)throw new xp(`${this.unit.name} "${this.toString()}" cannot be compared with ${t.unit?.name} "${t.toString()}"`)}compare(t){return this.#e(t),this.value-t.value}isEqual(t){return this.compare(t)===0}isBefore(t){return this.compare(t)<0}isAfter(t){return this.compare(t)>0}previous(t=this.unit){const e=this.value-1;return new this.constructor(e,t)}next(t=this.unit){const e=this.value+1;return new this.constructor(e,t)}toString(t=ia.instance){return t.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Ct{static#t=new Map;static register(t,e){Ct.#t.set(t,e)}static get(t){const e=Ct.#t.get(t);if(!e)throw new Ps(`No default parser registered for ${t.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return e()}}class Ah extends jn{constructor(t=new Date().getFullYear(),e=oe.year){super(t,e)}static fromString(t,e=Ct.get(Ah)){return new Ah(e.parse(t))}}class Ma extends ia{static default=new Ma("0",2);constructor(t,e){super(),this.char=t,this.size=e}render(t){return super.render(t).padStart(this.size,this.char)}}class _h extends jn{constructor(t=new Date().getMonth()+1,e=oe.month){super(t,e)}static fromString(t,e=Ct.get(_h)){return new _h(e.parse(t))}toString(t=Ma.default){return super.toString(t)}}class Th extends jn{constructor(t=new Date().getDate(),e=oe.day){super(t,e)}static fromString(t,e=Ct.get(Th)){const i=e.parse(t);return new Th(i)}toString(t=Ma.default){return super.toString(t)}}class Rh extends jn{constructor(t=new Date().getHours(),e=oe.hour){super(t,e)}static fromString(t,e=Ct.get(Rh)){return new Rh(e.parse(t))}toString(t=Ma.default){return super.toString(t)}}class Ih extends jn{constructor(t=new Date().getMinutes(),e=oe.minute){super(t,e)}static fromString(t,e=Ct.get(Ih)){return new Ih(e.parse(t))}toString(t=Ma.default){return super.toString(t)}}class Dh extends jn{constructor(t=new Date().getSeconds(),e=oe.second){super(t,e)}static fromString(t,e=Ct.get(Dh)){return new Dh(e.parse(t),oe.second)}toString(t=Ma.default){return super.toString(t)}}class qo extends jn{static renderer=new Ma("0",3);constructor(t,e=oe.millisecond){super(t,e)}static parseFraction(t){return parseInt(t.padEnd(3,"0").substring(0,3),10)}toString(t=qo.renderer){return super.toString(t)}}class ZA{render(t){return t.toString()}}class JA extends ZA{render(t){const e=t.value,i=Math.abs(e),n=Math.floor(i/60),s=i%60;if(n===0&&s===0)return"Z";{const r=e<0?"-":"+",a=n.toString().padStart(2,"0"),c=s>0?":"+s.toString().padEnd(2,"0"):"";return r+a+c}}}class Wo{value;name="timeshift";renderer;constructor(t=0){this.value=t}static fromString(t,e=Ct.get(Wo),i=void 0){const n=e.parse(t,i);return new Wo(n)}toString(t=new JA){return t.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Kn{static timeshift(t,e){return t+(Kn.isDaylight(e)?60:0)}static isDaylight(t){const{year:e,month:i,day:n}=t,s=t.hour??12;if(![e,i,n].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=Kn.rule(e);if(!r)return!1;const a=Kn.rank(i,n,s);return a>=Kn.rank(r.start.month,r.start.day,2)&&a<Kn.rank(r.end.month,r.end.day,2)}static rule(t){if(t<1967)return;const e={month:10,day:Kn.sunday(t,10,-1)};return t>=2007?{start:{month:3,day:Kn.sunday(t,3,2)},end:{month:11,day:Kn.sunday(t,11,1)}}:t>=1987?{start:{month:4,day:Kn.sunday(t,4,1)},end:e}:t===1975?{start:{month:2,day:23},end:e}:t===1974?{start:{month:1,day:6},end:e}:{start:{month:4,day:Kn.sunday(t,4,-1)},end:e}}static sunday(t,e,i){const n=new Date(Date.UTC(2e3,e-1,1));n.setUTCFullYear(t);const s=1+(7-n.getUTCDay())%7;if(i>0)return s+7*(i-1);const r=[31,Kn.isLeap(t)?29:28,31,30,31,30,31,31,30,31,30,31][e-1];let a=s;for(;a+7<=r;)a+=7;return a}static isLeap(t){return t%4===0&&(t%100!==0||t%400===0)}static rank(t,e,i){return(t*100+e)*100+i}}const jA={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},QA={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},t3={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},e3={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},i3={name:"PT",timeshift:o=>Kn.timeshift(-480,o),title:"Pacific Time (US)"},n3={name:"MT",timeshift:o=>Kn.timeshift(-420,o),title:"Mountain Time (US)"},s3={name:"CT",timeshift:o=>Kn.timeshift(-360,o),title:"Central Time (US)"},r3={name:"ET",timeshift:o=>Kn.timeshift(-300,o),title:"Eastern Time (US)"},a3={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},o3={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},c3={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},l3={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},h3={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},u3={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},d3={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},f3={name:"Z",timeshift:"Z",title:"UTC"},p3={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},m3={name:"BST",timeshift:"+01",title:"British Summer Time"},g3={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},M3={name:"CET",timeshift:"+01",title:"Central European Time"},v3={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},y3={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},x3={name:"BJT",timeshift:"+08",title:"Beijing Time"},w3={name:"CST",timeshift:"-06",title:"Central Standard Time"},S3={name:"JST",timeshift:"+09",title:"Japan Standard Time"},b3={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},E3={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},A3={name:"LST",timeshift:"?",title:"Local Sideral Time"},ey=[u3,b3,h3,x3,m3,w3,o3,M3,g3,s3,a3,l3,c3,r3,p3,y3,S3,A3,t3,v3,e3,n3,E3,QA,jA,i3,d3,f3];class wp{static instance=new wp;renderComponent(t,e){return t[e].toString()}renderSecond(t){return this.renderComponent(t,"second")+(t.millisecond?"."+t.millisecond.toString():"")}render(t){const e=[];t.year&&e.push(this.renderComponent(t,"year")),t.month&&e.push(this.renderComponent(t,"month")),t.day&&e.push(this.renderComponent(t,"day"));const i=[];t.hour&&i.push(this.renderComponent(t,"hour")),t.minute&&i.push(this.renderComponent(t,"minute")),t.second&&i.push(this.renderSecond(t));const n=e.join("-"),s=t.timeshift?t.timeshift.toString():"",r=i.join(":")+s;return n+(r.length>0?"T"+r:"")}}class uc extends Ps{constructor(t="method is abstract"){super(t)}}class BM{units;constructor(t){this.units=t}newYear(t){throw new uc}newMonth(t){throw new uc}newDay(t){throw new uc}newHour(t){throw new uc}newMinute(t){throw new uc}newSecond(t){throw new uc}}class _3 extends zM{millisecond=new gi("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new gi("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new gi("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new gi("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new gi("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new gi("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new gi("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Fd=new _3;class Sp{static instance=new Sp;render(t){const e=br.toSpec(t);let i="P";const n=e.years;n&&(i+=n.toString()+"Y");const s=e.months;s&&(i+=s.toString(ia.instance)+"MM");const r=e.days;r&&(i+=r.toString(ia.instance)+"D");const a=e.hours;a&&(i+=a.toString(ia.instance)+"H");const c=e.minutes;c&&(i+=c.toString(ia.instance)+"M");const l=e.seconds;return l&&(i+=l.toString(ia.instance)+"S"),i}}class br extends jn{constructor(t={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof t=="number"?t:+(t.years?t.years*oe.year.duration:0)+(t.months?t.months*oe.month.duration:0)+(t.days?t.days*oe.day.duration:0)+(t.hours?t.hours*oe.hour.duration:0)+(t.minutes?t.minutes*oe.minute.duration:0)+(t.seconds?t.seconds*oe.second.duration:0)},new gi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(t,e=R3){let i=typeof t=="number"?t:t.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/oe.year.duration,a=Math.floor(r);a>0&&(s.years=e.newYear(n*a),i-=a*oe.year.duration);const c=i/oe.month.duration,l=Math.floor(c);l>0&&(s.months=e.newMonth(n*l),i-=l*oe.month.duration);const h=i/oe.day.duration,u=Math.floor(h);u>0&&(s.days=e.newDay(n*u),i-=u*oe.day.duration);const d=i/oe.hour.duration,f=Math.floor(d);f>0&&(s.hours=e.newHour(n*f),i-=f*oe.hour.duration);const p=i/oe.minute.duration,m=Math.floor(p);m>0&&(s.minutes=e.newMinute(n*m),i-=m*oe.minute.duration);const g=i/oe.second.duration,M=Math.floor(n*g);return M>0&&(s.seconds=e.newSecond(M)),s}static fromString(t,e=Ct.get(br)){return new br(e.parse(t))}static between(t,e){const i=e.getTime(),n=t.getTime();return new br(i-n)}toSpec(){return br.toSpec(this)}toString(t=Sp.instance){return t.render(this)}}class JS extends BM{constructor(t){super(t)}newYear(t){return new Ah(t,this.units.year)}newMonth(t){return new _h(t,this.units.month)}newDay(t){return new Th(t,this.units.day)}newHour(t){return new Rh(t,this.units.hour)}newMinute(t){return new Ih(t,this.units.minute)}newSecond(t){return new Dh(t,this.units.second)}newMillisecond(t){return new qo(t,this.units.millisecond)}newTimeshift(t){return new Wo(typeof t=="number"?t:t.value)}}const T3=new JS(oe),R3=new JS(Fd);class Cn{#t;#e;#i;#n;#s;#r;#a;#o;constructor(t={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:Cn.timeshiftOf(new Date)}){this.year=t.year,this.month=t.month,this.day=t.day,this.hour=t.hour,this.minute=t.minute,this.second=t.second,this.millisecond=t.millisecond,this.timeshift=t.timeshift}get year(){return this.#t}set year(t){const e=typeof t=="number";this.#t&&e?this.#t.value=t:this.#t=e?this.factory.newYear(t):!t||t.start||t instanceof jn?t:this.factory.newYear(t)}get month(){return this.#e}set month(t){const e=typeof t=="number";this.#e&&e?this.#e.value=t:this.#e=e?this.factory.newMonth(t):!t||t.start||t instanceof jn?t:this.factory.newMonth(t)}get day(){return this.#i}set day(t){const e=typeof t=="number";this.#i&&e?this.#i.value=t:this.#i=e?this.factory.newDay(t):!t||t.start||t instanceof jn?t:this.factory.newDay(t)}get hour(){return this.#n}set hour(t){const e=typeof t=="number";this.#n&&e?this.#n.value=t:this.#n=e?this.factory.newHour(t):!t||t.start||t instanceof jn?t:this.factory.newHour(t)}get minute(){return this.#s}set minute(t){const e=typeof t=="number";this.#s&&e?this.#s.value=t:this.#s=e?this.factory.newMinute(t):!t||t.start||t instanceof jn?t:this.factory.newMinute(t)}get second(){return this.#r}set second(t){const e=typeof t=="number";this.#r&&e?this.#r.value=t:this.#r=e?this.factory.newSecond(t):!t||t.start||t instanceof jn?t:this.factory.newSecond(t)}get millisecond(){return this.#a}set millisecond(t){const e=typeof t=="number";this.#a&&e?this.#a.value=t:this.#a=e||t&&!(t instanceof jn)?this.factory.newMillisecond(t):t}get timeshift(){return this.#o}set timeshift(t){const e=typeof t=="number";this.#o&&e?this.#o.value=t:this.#o=e||t&&!(t instanceof Wo)?this.factory.newTimeshift(t):t}get factory(){return T3}static fromString(t,e=Ct.get(Cn)){const{year:i,month:n,day:s,hour:r,minute:a,second:c,millisecond:l,timeshift:h}=e.parse(t);return new Cn({year:i,month:n,day:s,hour:r,minute:a,second:c,millisecond:l,timeshift:h})}static timeshiftOf(t){return-t.getTimezoneOffset()||0}static fromDate(t){return new Cn({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:Cn.timeshiftOf(t)})}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return Cn.fromString(i)}#c(t){if(this.constructor.name!==t.constructor.name)throw new xp(`Date "${this.toString()}" cannot be compared with "${t.toString()}"`)}compare(t){return this.#c(t),this.getTime()-t.getTime()}delta(t){const e=this.compare(t);return new br(e)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(t){return this.compare(t)===0}isBefore(t){return this.compare(t)<0}isAfter(t){return this.compare(t)>0}clone(){return new Cn(this.toSpec())}previous(){let t=this.clone();try{t.second=this.second.previous()}catch{try{t.minute=this.minute.previous()}catch{try{t.hour=this.hour.previous()}catch{try{t.day=this.day.previous()}catch{try{t.month=this.month.previous()}catch{t.year=this.year.previous()}}}}}return t}next(){let t=this.clone();try{t.second=this.second.next()}catch{try{t.minute=this.minute.next()}catch{try{t.hour=this.hour.next()}catch{try{t.day=this.day.next()}catch{try{t.month=this.month.next()}catch{t.year=this.year.next()}}}}}return t}toString(t=wp.instance){return t.render(this)}toSpec(){const t={},e=this.year?.toSpec();e&&(t.year=e);const i=this.month?.toSpec();i&&(t.month=i);const n=this.day?.toSpec();n&&(t.day=n);const s=this.hour?.toSpec();s&&(t.hour=s);const r=this.minute?.toSpec();r&&(t.minute=r);const a=this.second?.toSpec();a&&(t.second=a);const c=this.millisecond?.toSpec();c&&(t.millisecond=c);const l=this.timeshift?.toSpec();return l&&(t.timeshift=l),t}toJSON(){return this.toSpec()}}class HM{static instance=new HM;render(t){return(t.start?t.start.toString():"")+"/"+(t.end?t.end.toString():"")}}class Qu{constructor(t,e){this.start=t,this.end=e}_start;get start(){return this._start}set start(t){if(typeof t=="string"&&(t=Cn.fromString(t)),t&&!(t instanceof Cn)&&!(t instanceof br))throw new Ps("Interval start is not a level 0 date or duration: "+t);this._start=t}_end;get end(){return this._end}set end(t){if(typeof t=="string"&&(t=Cn.fromString(t)),t&&!(t instanceof Cn)&&!(t instanceof br))throw new Ps("Interval end is not a level 0 date or duration: "+t);this._end=t}static fromString(t,e=Ct.get(Qu)){const{start:i,end:n}=e.parse(t);return new Qu(i,n)}toString(t=HM.instance){return t.render(this)}[Symbol.iterator](){let t=this.start;return{next:()=>{const e={done:t>this.end,value:t};return t++,e}}}}class zd extends ia{static instance=new zd(Ma.default);constructor(t){super(),this.valueRenderer=t}render(t){return(this.valueRenderer?this.valueRenderer.render(t):super.render(t))+this.qualifier(t)}qualifier(t){return t.uncertain?t.approximate?"%":"?":t.approximate?"~":""}}class fa extends jn{#t;#e;constructor(t,e){super(t,e),this.#t=t.uncertain||!1,this.#e=t.approximate||!1}get uncertain(){return this.#t}set uncertain(t){return this.#t=t}get approximate(){return this.#e}set approximate(t){return this.#e=t}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(t){return this.isCertainAndPrecise()&&super.isEqual(t)}isBefore(t){return this.isCertainAndPrecise()&&super.isBefore(t)}isAfter(t){return this.isCertainAndPrecise()&&super.isAfter(t)}toString(t=zd.instance){return super.toString(t)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class jS extends qS{year=new gi("year",-9999,9999,this.month);yearExtended=new gi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const g0=new jS;class Do extends fa{constructor(t,e=g0.year){super(t,e)}static fromString(t,e=g0.year,i=Ct.get(Do)){const n=i.parse(t),s=n.value.start;if(t.startsWith("Y")&&(e=g0.yearExtended),s!==void 0){const r=new Do(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Do(Object.assign({...n},{value:Math.min(n.value.end,e.max)}));return{start:r,end:a}}else return new Do(n,e)}}class QS extends xp{monthValidator=new ZS;validate(t){switch(t){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(t)}}}class Co extends fa{constructor(t,e=new gi(oe.month.name,1,24,oe.day,new QS)){super(t,e)}static fromString(t,e=Ct.get(Co)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=oe.month;const r=new Co(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Co(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Co(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Po extends fa{constructor(t,e=oe.day){super(t,e)}static fromString(t,e=Ct.get(Po)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=oe.day;const r=new Po(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Po(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Po(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Oo extends fa{constructor(t,e=oe.hour){super(t,e)}static fromString(t,e=Ct.get(Oo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=oe.hour;const r=new Oo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Oo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Oo(i)}}class No extends fa{constructor(t,e=oe.minute){super(t,e)}static fromString(t,e=Ct.get(No)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.minute,r=new No(Object.assign({...i},{value:Math.max(n,s.min)})),a=new No(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new No(i)}toString(t=zd.instance){return super.toString(t)}}class Lo extends fa{constructor(t,e=oe.second){super(t,e)}static fromString(t,e=Ct.get(Lo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.second,r=new Lo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Lo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Lo(i)}}class Lc extends Wo{static fromString(t,e=Ct.get(Lc),i=void 0){return new Lc(e.parse(t,i))}}class tb extends BM{constructor(t){super(t)}newYear(t){return new Do(t,this.units.year)}newMonth(t){return new Co(t,this.units.month)}newDay(t){return new Po(t,this.units.day)}newHour(t){return new Oo(t,this.units.hour)}newMinute(t){return new No(t,this.units.minute)}newSecond(t){return new Lo(t,this.units.second)}newMillisecond(t){return new qo(t,this.units.millisecond)}newTimeshift(t){return new Lc(typeof t=="number"?t:t.value)}}const I3=new tb(g0),D3=new tb(Fd);class Rs extends Cn{constructor(t){super(t)}get factory(){return I3}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(t){return new Rs({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:Cn.timeshiftOf(t)})}static fromString(t,e=Ct.get(Rs)){const i=e.parse(t);return new Rs(i)}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return Rs.fromString(i)}clone(){return new Rs(this.toSpec())}}const gn=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class bp extends Sp{static instance=new bp;render(t){return super.render(t)}}class un extends fa{constructor(t){super(typeof t=="number"||t.hasOwnProperty("value")?t:{value:un.getValue(t,gn.year)+un.getValue(t,gn.month)+un.getValue(t,gn.day)+un.getValue(t,gn.hour)+un.getValue(t,gn.minute)+un.getValue(t,gn.second),uncertain:un.getBoolean(t,gn.uncertain),approximate:un.getBoolean(t,"approximate")},Fd.millisecond)}static getBoolean(t,e){return t[e]||t[gn.year+"s"]?.[e]||t[gn.month+"s"]?.[e]||t[gn.day+"s"]?.[e]||t[gn.hour+"s"]?.[e]||t[gn.minute+"s"]?.[e]||t[gn.second+"s"]?.[e]||!1}static getValue(t,e){let i=0,n=t[e+"s"];if(n instanceof fa?n=n.value:typeof t=="number"&&(n=t),n){const s=oe[e];i=n*s.duration}return i}static toSpec(t,e=D3){return{...br.toSpec(t,e),uncertain:t.uncertain||!1,approximate:t.approximate||!1}}static fromString(t,e=Ct.get(un)){const i=e.parse(t);return new un(i)}static between(t,e){const i=e.getTime(),n=t.getTime();return new un(i-n)}toString(t=bp.instance){return super.toString(t)}toSpec(){return un.toSpec(this)}}class td extends Qu{constructor(t,e){super(t,e)}get start(){return this._start}set start(t){if(typeof t=="string"&&(super.start=Rs.fromString(t)),t&&!(t instanceof Rs)&&!(t instanceof un))throw new Ps("Interval start is not a level 1 date or duration: "+t);this._start=t}get end(){return this._end}set end(t){if(typeof t=="string"&&(t=Rs.fromString(t)),t&&!(t instanceof Rs)&&!(t instanceof un))throw new Ps("Interval end is not a level 1 date or duration: "+t);this._end=t}static fromString(t,e=Ct.get(td)){const{start:i,end:n}=e.parse(t);return new td(i,n)}}class zh extends fa{uncertainComponent;approximateComponent;constructor(t,e){super(t,e),this.uncertainComponent=t.uncertainComponent||!1,this.approximateComponent=t.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(t){return super.uncertain=t}get approximate(){return super.approximate||this.approximateComponent}set approximate(t){return super.approximate=t}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class C3 extends jS{year=new gi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Wg=new C3;class Ua extends zh{constructor(t,e=Wg.year){super(t,e)}static fromString(t,e=Wg.year,i=Ct.get(Ua)){const n=i.parse(t),s=n.value.start;if(s!==void 0){const r=new Ua(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Ua(Object.assign({...n},{value:Math.min(n.value.end,e.max)})),c={start:r,end:a},l=n.value.estimate;return l&&(c.estimate=l),c}else return new Ua(n)}}class P3 extends QS{validate(t){switch(t){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(t)}}}class Fa extends zh{constructor(t,e=new gi(oe.month.name,1,41,oe.day,new P3)){super(t,e)}static fromString(t,e=Ct.get(Fa)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.month,r=new Fa(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Fa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Fa(i)}toString(t){return super.toString(t).padStart(2,"0")}}class za extends zh{constructor(t,e=oe.day){super(t,e)}static fromString(t,e=Ct.get(za)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.day,r=new za(Object.assign({...i},{value:Math.max(n,s.min)})),a=new za(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new za(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Ba extends zh{constructor(t,e=oe.hour){super(t,e)}static fromString(t,e=Ct.get(Ba)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.hour,r=new Ba(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Ba(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Ba(i)}}class Ha extends zh{constructor(t,e=oe.minute){super(t,e)}static fromString(t,e=Ct.get(Ha)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.minute,r=new Ha(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Ha(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Ha(i)}}class Ga extends zh{constructor(t,e=oe.second){super(t,e)}static fromString(t,e=oe.second,i=Ct.get(Ga)){const n=i.parse(t),s=n.value.start;if(s!==void 0){const r=new Ga(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Ga(Object.assign({...n},{value:Math.min(n.value.end,e.max)}));return{start:r,end:a}}else return new Ga(n,e)}}class eb extends Lc{}class O3 extends zd{qualifier(){return""}}class vo extends wp{static instance=new vo;static valueRenderer=new O3(Ma.default);static names=["year","month","day","hour","minute","second"];static qualifier(t,e){return t?e?"%":"?":e?"~":""}renderComponent(t,e){const i=t[e],n=vo.names.slice(vo.names.indexOf(e)+1).map(a=>t[a]).filter(Boolean),s=vo.qualifier(i.uncertainComponent,i.approximateComponent),r=vo.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(a=>a.approximate));return s+i.toString(vo.valueRenderer)+r}}class ib extends BM{constructor(t){super(t)}newYear(t){return new Ua(t,this.units.year)}newMonth(t){return new Fa(t,this.units.month)}newDay(t){return new za(t,this.units.day)}newHour(t){return new Ba(t,this.units.hour)}newMinute(t){return new Ha(t,this.units.minute)}newSecond(t){return new Ga(t,this.units.second)}newMillisecond(t){return new qo(t,this.units.millisecond)}newTimeshift(t){return new eb(typeof t=="number"?t:t.value)}}const N3=new ib(Wg),L3=new ib(Fd);class fs extends Rs{constructor(t){super(t)}toString(t=vo.instance){return super.toString(t)}get year(){return super.year}set year(t){super.year=t}get month(){return super.month}set month(t){super.month=t}get factory(){return N3}static fromDate(t){return new fs({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:Cn.timeshiftOf(t)})}static fromString(t,e=Ct.get(fs)){const i=e.parse(t);return new fs(i)}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return fs.fromString(i)}clone(){return new fs(this.toSpec())}}class ja{regExp;constructor(t,e){this.name=t,this.regExp=new RegExp(`^(?:${e})$`)}regexGroups(t){const e=this.regExp.exec(t);if(!e)throw new Ps(`Invalid ${this.name} "${t}"`);return e.groups}parseGroups(t){throw new uc(`${this.constructor.name} is abstract`)}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}class Hl extends bp{static instance=new Hl;static designators=[["years","Y"],["months","MM"],["days","D"],["hours","H"],["minutes","M"],["seconds","S"]];static qualifier(t,e){return t?e?"%":"?":e?"~":""}render(t){const e=Hl.qualifier(t.uncertainDuration,t.approximateDuration);if(!t.hasQualifiedComponent)return e+super.render(t);let i=e+"P";for(const[n,s]of Hl.designators){const r=t.components[n];r&&(i+=Hl.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+s)}return i}}class hn extends un{#t;constructor(t){if(super(typeof t=="number"?t:{value:hn.valueFromSpec(t),uncertain:t.uncertain===!0,approximate:t.approximate===!0},Fd.millisecond),typeof t!="number"){const e={};for(const i of hn.componentNames)t[i]instanceof fa&&(e[i]=t[i]);Object.keys(e).length>0&&(this.#t=e)}}static componentNames=["years","months","days","hours","minutes","seconds"];get components(){return this.#t}#e(t){return this.#t?Object.values(this.#t).some(e=>e[t]):!1}get uncertainDuration(){return super.uncertain}get approximateDuration(){return super.approximate}get uncertain(){return super.uncertain||this.#e("uncertain")}set uncertain(t){super.uncertain=t}get approximate(){return super.approximate||this.#e("approximate")}set approximate(t){super.approximate=t}get hasQualifiedComponent(){return this.#t?Object.values(this.#t).some(t=>t.uncertainComponent||t.approximateComponent):!1}static valueFromSpec(t){return hn.getValue(t,gn.year)+hn.getValue(t,gn.month)+hn.getValue(t,gn.day)+hn.getValue(t,gn.hour)+hn.getValue(t,gn.minute)+hn.getValue(t,gn.second)}static toSpec(t,e=L3){const i=un.toSpec(t,e);if(t instanceof hn&&t.hasQualifiedComponent)for(const n of hn.componentNames)delete i[n],t.components[n]&&(i[n]=t.components[n]);return i}static fromString(t,e=Ct.get(hn)){const i=e.parse(t);return new hn(i)}static between(t,e){const i=e.getTime(),n=t.getTime();return new hn(i-n)}toSpec(){return hn.toSpec(this)}toString(t=Hl.instance){return super.toString(t)}}class ed extends td{get start(){return this._start}set start(t){if(typeof t=="string"&&(super.start=fs.fromString(t)),t&&!(t instanceof fs)&&!(t instanceof hn))throw new Ps("Interval start is not a level 2 date or duration: "+t);this._start=t}get end(){return this._end}set end(t){if(typeof t=="string"&&(t=fs.fromString(t)),t&&!(t instanceof fs)&&!(t instanceof hn))throw new Ps("Interval end is not a level 2 date or duration: "+t);this._end=t}static fromString(t,e=Ct.get(ed)){const{start:i,end:n}=e.parse(t);return new ed(i,n)}}class N0 extends Set{constructor(t,e){super(t),this.exclusive=e}has(t){const e=t.toString().replace("..","/");for(const i of this)if(i.toString()===e)return!0;return!1}static fromString(t,e=Ct.get(N0)){const{exclusive:i,values:n}=e.parse(t);return new N0(n,i)}}class Qa extends ja{constructor(t,e){super(t,e)}static read(t){return{value:t?parseInt(t,10):void 0}}parseGroups(t){return Qa.read(t[this.name])}parse(t){if(t.startsWith("-"))throw new Ps(`${this.name} cannot be negative`);return super.parse(t)}}class U{static groupName(...t){return t.reduce((e,i)=>e?e+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(t,...e){return`(?<${t}>${e.join("")})`}static optional(t){return t+"?"}static nonCapturingGroup(...t){return`(?:${t.join("")})`}static optionalGroup(t,...e){return U.optional(U.group(t,...e))}static optionalNonCapturingGroup(...t){return U.optional(U.nonCapturingGroup(...t))}static numberGroup(t,e,i,n="\\d"){return U.group(t,`${i||""}[${n}]${e}`)}}const iy="yearValue";class id extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,iy),"{4}",void 0)}constructor(){super(iy,id.format())}}const ny="monthValue";class nd extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,ny),"{1,2}",void 0)}constructor(){super(ny,nd.format())}}const sy="dayValue";class oh extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,sy),"{1,2}",void 0)}constructor(){super(sy,oh.format())}}const ry="hourValue";class ch extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,ry),"{1,2}",void 0)}constructor(){super(ry,ch.format())}}const ay="minuteValue";class sd extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,ay),"{1,2}",void 0)}constructor(){super(ay,sd.format())}}const oy="secondValue";class rd extends Qa{static format(t=""){return U.numberGroup(U.groupName(t,oy),"{1,2}",void 0)}constructor(){super(oy,rd.format())}}const cy="timeshiftValue",ly="shiftHour",hy="shiftMinute";class Ch extends ja{static format(t=""){return ey.map(e=>e.name).join("|")+"|"+U.nonCapturingGroup(U.group(t+ly,U.numberGroup(U.groupName(t,cy),"{2}","[+-]")),U.optionalNonCapturingGroup(":?",U.numberGroup(U.groupName(t,hy),"{2}",void 0)))}constructor(){super(cy,Ch.format())}parse(t,e){let i=0;const n=ey.find(s=>s.name===t);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(e??{})}catch(s){throw new Ps(`The time zone ${t} depends on the date: ${s.message}`)}t=n.timeshift}if(t!=="Z"){const s=this.regexGroups(t),r=s[ly];r&&(i+=parseInt(r,10)*60);const a=s[hy];a&&(i+=parseInt(a,10))}return i}}const uy="year",dy="month",fy="day",py="hour",my="minute",gy="second",My="millisecond",vy="timeshift";class vc extends ja{static format(t=""){return U.group(U.groupName(t,uy),id.format(t))+U.optionalNonCapturingGroup("-",U.group(U.groupName(t,dy),nd.format(t)),U.optionalNonCapturingGroup("-",U.group(U.groupName(t,fy),oh.format(t)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(t,py),ch.format(t)),":?",U.group(U.groupName(t,my),sd.format(t)),U.optionalNonCapturingGroup(":",U.group(U.groupName(t,gy),rd.format(t)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(t,My),"\\d+"))),"\\s*",U.optionalGroup(U.groupName(t,vy),Ch.format(t)))))}constructor(){super("date",vc.format())}parse(t){const e=this.regexGroups(t),i=e[uy],n=e[dy],s=e[fy],r=e[py],a=e[my],c=e[gy],l=e[My],h=e[vy],u=i?new Ah(id.read(i)):void 0,d=n?nd.read(n):void 0;return{year:u,month:d?new _h(d,Bl.create(d.value,u?.value)):void 0,day:s?new Th(oh.read(s)):void 0,hour:r?new Rh(ch.read(r)):void 0,minute:a?new Ih(sd.read(a)):void 0,second:c?new Dh(rd.read(c)):void 0,millisecond:l?qo.parseFraction(l):void 0,timeshift:h?Wo.fromString(h,new Ch,{year:u?.value,month:d?.value,day:s?oh.read(s).value:void 0,hour:r?ch.read(r).value:void 0}):void 0}}}const yy="years",Yp="months",k3="days",xy="hours",wy="minutes",Sy="seconds";class GM extends ja{static format(t=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,yy),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Yp),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,k3),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,xy),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,wy),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Sy),"+",void 0,"\\d"),"S")}constructor(){super("duration",GM.format())}parseGroups(t){return{years:t[yy],months:t[Yp],days:t[Yp],hours:t[xy],minutes:t[wy],seconds:t[Sy]}}}const $p="start",Kp="end";class VM extends ja{static format=U.group($p,vc.format($p))+"/"+U.group(Kp,vc.format(Kp));constructor(){super("interval",VM.format)}parse(t){const e=this.regexGroups(t),i=e[$p],n=e[Kp];return{start:i?Cn.fromString(i,new vc):void 0,end:n?Cn.fromString(n,new vc):void 0}}}class Ai extends Qa{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Ai.uncertainGroup+Ai.approximateGroup;constructor(t,e){super(t,e)}static qualifierFormat(t,e){return U.optionalGroup(t,`\\${e}`)}static formatSuffix(t){return this.qualifierFormat(U.groupName(Ai.uncertainGroup,t),"?")+this.qualifierFormat(U.groupName(Ai.approximateGroup,t),"~")+this.qualifierFormat(U.groupName(Ai.uncertainAndApproximateGroup,t),"%")}static numberFormat(t,e,i){return U.numberGroup(t,e,i,"\\dX")+this.formatSuffix(t)}getValueAndSign(t){let e=t[this.name],i;return e.charAt(0)==="-"?(i=-1,e=e.substring(1)):i=1,{valueStr:e,sign:i}}parseGroups(t){const{valueStr:e,sign:i}=this.getValueAndSign(t);let n=0,s;for(s=0;s<e.length;s++){const l=e[s];if(l==="X")break;n=n*10+parseInt(l,10)}if(s<e.length){let l=1;for(let d=0;d<e.length-s;d++)l*=10;const h=i*n*l,u=h+l-1;n={start:h,end:u}}else n*=i;const r=t[U.groupName(Ai.uncertainAndApproximateGroup,this.name)],a=t[U.groupName(Ai.approximateGroup,this.name)]||r,c=t[U.groupName(Ai.uncertainGroup,this.name)]||r;return{value:n,approximate:a?!!a:!1,uncertain:c?!!c:!1}}}const by="yearValue";class ad extends Ai{constructor(){super(by,ad.format())}static format(t=""){return"Y?"+Ai.numberFormat(U.groupName(t,by),"+","[-]?")}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}const Ey="monthValue";class od extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,Ey),"{1,2}",void 0)}constructor(){super(Ey,od.format())}}const Ay="dayValue";class cd extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,Ay),"{1,2}",void 0)}constructor(){super(Ay,cd.format())}}const _y="hourValue";class ld extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,_y),"{1,2}",void 0)}constructor(){super(_y,ld.format())}}const Ty="minuteValue";class hd extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,Ty),"{1,2}",void 0)}constructor(){super(Ty,hd.format())}}const Ry="secondValue";class ud extends Ai{static format(t=""){return Ai.numberFormat(U.groupName(t,Ry),"{1,2}",void 0)}constructor(){super(Ry,ud.format())}}class dd extends Ch{}class Li extends ja{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(t=Li.format()){super("date",t)}static format(t=""){return U.group(U.groupName(t,Li.yearGroup),ad.format(t))+U.optionalNonCapturingGroup("-",U.group(U.groupName(t,Li.monthGroup),od.format(t)),U.optionalNonCapturingGroup("-",U.group(U.groupName(t,Li.dayGroup),cd.format(t)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(t,Li.hourGroup),ld.format(t)),":",U.group(U.groupName(t,Li.minuteGroup),hd.format(t)),U.optionalNonCapturingGroup(":",U.group(U.groupName(t,Li.secondGroup),ud.format(t)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(t,Li.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(t,Li.timeshiftGroup),dd.format(t)))))}parseGroups(t){const e=t[Li.millisecondGroup],i=e?qo.parseFraction(e):void 0,n=t[Li.secondGroup],s=n?Lo.fromString(n,new ud):void 0,r=t[Li.minuteGroup];let a;r&&(a=No.fromString(r,new hd),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[Li.hourGroup];let l;c&&(l=Oo.fromString(c,new ld),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=t[Li.dayGroup];let u;h&&(u=Po.fromString(h,new cd),u.uncertain=u.uncertain||l?.uncertain||!1,u.approximate=u.approximate||l?.approximate||!1);const d=t[Li.monthGroup];let f;d&&(f=Co.fromString(d,new od),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[Li.yearGroup];let m;p&&(m=Do.fromString(p,void 0,new ad),m.uncertain=m.uncertain||f?.uncertain||!1,m.approximate=m.approximate||f?.approximate||!1);const g=t[Li.timeshiftGroup],M=g?Lc.fromString(g,new dd,{year:m?.value,month:f?.value,day:u?.value,hour:l?.value}):void 0;return{year:m,month:f,day:u,hour:l,minute:a,second:s,millisecond:i,timeshift:M}}}const Iy="years",Dy="months",Cy="days",Py="hours",Oy="minutes",Ny="seconds";class yc extends Ai{static format(t=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Iy),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Dy),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Cy),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Py),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Oy),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(t,Ny),"+",void 0,"\\d"),"S")+this.formatSuffix(t)}constructor(){super("duration",yc.format())}parseGroups(t){return{years:t[Iy],months:t[Dy],days:t[Cy],hours:t[Py],minutes:t[Oy],seconds:t[Ny],uncertain:!!t[Ai.uncertainGroup],approximate:!!t[Ai.approximateGroup]}}}const U3="dates",qp="start",Zp="end",Ly="durations",Jp="durationMin",jp="durationMax";class WM extends ja{static format=U.group(U3,U.optionalGroup(qp,U.group("openStart","\\.\\.")+"|"+Li.format(qp))+"/"+U.optionalGroup(Zp,U.group("openEnd","\\.\\.")+"|"+Li.format(Zp)))+"|"+U.group(Ly,U.group(Jp,yc.format(Jp))+"/"+U.group(jp,yc.format(jp)));constructor(t="interval",e=WM.format){super(t,e)}parseGroups(t){let e,i;if(t[Ly]){const s=t[Jp];e=un.fromString(s,new yc);const r=t[jp];i=un.fromString(r,new yc)}else{const s=t[qp];switch(s){case void 0:e=null;break;case"..":e=void 0;break;default:e=Rs.fromString(s,new Li)}const r=t[Zp];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=Rs.fromString(r,new Li)}}return{start:e,end:i}}}class Ve extends Ai{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=Ve.uncertainGroup+Ve.approximateGroup;constructor(t,e){super(t,e)}static numberFormat(t,e,i){return this.qualifierFormat(U.groupName(Ve.uncertainGroup,t),"?")+this.qualifierFormat(U.groupName(Ve.approximateGroup,t),"~")+this.qualifierFormat(U.groupName(Ve.uncertainAndApproximateGroup,t),"%")+Ai.numberFormat(t,e,i)}parseGroups(t){const e=super.parseGroups(t),i=t[U.groupName(Ve.uncertainAndApproximateGroup,this.name)];return(t[U.groupName(Ve.uncertainGroup,this.name)]||i)&&(e.uncertainComponent=!0),(t[U.groupName(Ve.approximateGroup,this.name)]||i)&&(e.approximateComponent=!0),e}}const Wh="yearValue",ky="exp",Uy="signif";class fd extends Ve{constructor(){super(Wh,fd.format())}static format(t=""){return"Y?"+U.nonCapturingGroup(U.group(U.groupName(t,ky),"[-]?\\d+E\\d+")+"|"+Ve.numberFormat(U.groupName(t,Wh),"+","[-]?")+U.optionalGroup(U.groupName(t,Uy),"S\\d+"))}parseGroups(t){const e=t[ky];if(e){const r=e.indexOf("E"),a=parseInt(e.substring(r+1),10),l=parseInt(e.substring(0,r),10)*Math.pow(10,a);t[Wh]=l.toString()}const i=t[Uy],n=t[Wh];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:c}=this.getValueAndSign(t);let l="";for(let h=0;h<a.length;h++)l+=h<r?a.charAt(h):"X";t[Wh]=(c<0?"-":"")+l}const s=super.parseGroups(t);return i&&(s.value.estimate=parseInt(n,10)),s}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}const Fy="monthValue";class pd extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,Fy),"{1,2}",void 0)}constructor(){super(Fy,pd.format())}}const zy="dayValue";class md extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,zy),"{1,2}",void 0)}constructor(){super(zy,md.format())}}const By="hourValue";class gd extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,By),"{1,2}",void 0)}constructor(){super(By,gd.format())}}const Hy="secondValue";class Md extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,Hy),"{1,2}",void 0)}constructor(){super(Hy,Md.format())}}const Gy="minuteValue";class vd extends Ve{static format(t=""){return Ve.numberFormat(U.groupName(t,Gy),"{1,2}",void 0)}constructor(){super(Gy,vd.format())}}class F3 extends dd{}class $e extends ja{static yearGroup=Li.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",$e.format())}static format(t=""){return U.group(U.groupName(t,$e.yearGroup),fd.format(t))+U.optionalNonCapturingGroup("-",U.group(U.groupName(t,$e.monthGroup),pd.format(t)),U.optionalNonCapturingGroup("-",U.group(U.groupName(t,$e.dayGroup),md.format(t)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(t,$e.hourGroup),gd.format(t)),":",U.group(U.groupName(t,$e.minuteGroup),vd.format(t)),U.optionalNonCapturingGroup(":",U.group(U.groupName(t,$e.secondGroup),Md.format(t)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(t,$e.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(t,$e.timeshiftGroup),F3.format(t)))))}parseGroups(t){const e=t[$e.millisecondGroup],i=e?qo.parseFraction(e):void 0,n=t[$e.secondGroup];let s;n&&(s=Ga.fromString(n,void 0,new Md),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=t[$e.minuteGroup];let a;r&&(a=Ha.fromString(r,new vd),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[$e.hourGroup];let l;c&&(l=Ba.fromString(c,new gd),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=t[$e.dayGroup];let u;h&&(u=za.fromString(h,new md),u.uncertain=u.uncertain||l?.uncertain||!1,u.approximate=u.approximate||l?.approximate||!1);const d=t[$e.monthGroup];let f;d&&(f=Fa.fromString(d,new pd),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[$e.yearGroup];let m;p&&(m=Ua.fromString(p,void 0,new fd),m.uncertain=m.uncertain||f?.uncertain||!1,m.approximate=m.approximate||f?.approximate||!1);const g=t[$e.timeshiftGroup],M=g?eb.fromString(g,new dd,{year:m?.value,month:f?.value,day:u?.value,hour:l?.value}):void 0;return{year:m,month:f,day:u,hour:l,minute:a,second:s,millisecond:i,timeshift:M}}}const Vy="durationValue";class XM extends Ve{static format(t=""){return"^"+Ve.numberFormat(U.groupName(t,Vy),"+",void 0)}constructor(){super(Vy,XM.format())}}class z3 extends zM{millisecond=new gi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new gi("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new gi("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new gi("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new gi("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new gi("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new gi("year",0,Number.MAX_SAFE_INTEGER,this.month)}const qc=new z3;class te extends Ve{static yearsGroup="years";static monthsGroup="months";static isoMonthsGroup="isoMonths";static daysGroup="days";static hoursGroup="hours";static minutesGroup="minutes";static secondsGroup="seconds";static durationGroup="duration";static suffixGroup="durationSuffix";static componentParser=new XM;static componentFormat(t,e,i,n,s=""){const r=U.group(U.groupName(t,te.quantityGroup(e)),Ve.numberFormat(U.groupName(t,i),"+",void 0,"\\d"));return U.group(U.groupName(t,e),r,n,s)}static quantityGroup(t){return t+"Quantity"}static isoMonthsLookahead="(?=[?~%]?\\d+D|T)";constructor(){super("duration",te.format())}static format(t=""){const e=U.groupName(t,te.durationGroup);return this.qualifierFormat(U.groupName(Ve.uncertainGroup,e),"?")+this.qualifierFormat(U.groupName(Ve.approximateGroup,e),"~")+this.qualifierFormat(U.groupName(Ve.uncertainAndApproximateGroup,e),"%")+"P"+U.optional(te.componentFormat(t,te.yearsGroup,$e.yearGroup,"Y"))+U.optionalNonCapturingGroup(te.componentFormat(t,te.monthsGroup,$e.monthGroup,"MM")+"|"+te.componentFormat(t,te.isoMonthsGroup,"isoMonth","M",te.isoMonthsLookahead))+U.optional(te.componentFormat(t,te.daysGroup,$e.dayGroup,"D"))+"T?"+U.optional(te.componentFormat(t,te.hoursGroup,$e.hourGroup,"H"))+U.optional(te.componentFormat(t,te.minutesGroup,$e.minuteGroup,"M"))+U.optional(te.componentFormat(t,te.secondsGroup,$e.secondGroup,"S"))+U.optionalGroup(U.groupName(t,te.suffixGroup),"[?~%]")}static parseComponent(t,e,i){const n=te.componentParser.parse(t);return new e(n,i)}parseGroups(t){const e=t[te.quantityGroup(te.secondsGroup)];let i;e&&(i=te.parseComponent(e,Ga,qc.second),i.uncertain=!!t[U.groupName(Ve.uncertainGroup,te.secondsGroup)]||!1,i.approximate=!!t[U.groupName(Ve.approximateGroup,te.secondsGroup)]||!1);const n=t[te.quantityGroup(te.minutesGroup)];let s;n&&(s=te.parseComponent(n,Ha,qc.minute),s.uncertain=s.uncertain||i?.uncertain||!1,s.approximate=s.approximate||i?.approximate||!1);const r=t[te.quantityGroup(te.hoursGroup)];let a;r&&(a=te.parseComponent(r,Ba,qc.hour),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[te.quantityGroup(te.daysGroup)];let l;c&&(l=te.parseComponent(c,za,qc.day),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=t[te.quantityGroup(te.monthsGroup)]||t[te.quantityGroup(te.isoMonthsGroup)];let u;h&&(u=te.parseComponent(h,Fa,qc.month),u.uncertain=u.uncertain||l?.uncertain||!1,u.approximate=u.approximate||l?.approximate||!1);const d=t[te.quantityGroup(te.yearsGroup)];let f;d&&(f=te.parseComponent(d,Ua,qc.year),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[te.suffixGroup],m=!!t[U.groupName(Ve.uncertainAndApproximateGroup,te.durationGroup)]||p==="%",g=m||!!t[U.groupName(Ve.uncertainGroup,te.durationGroup)]||p==="?",M=m||!!t[U.groupName(Ve.approximateGroup,te.durationGroup)]||p==="~";return{years:f,months:u,days:l,hours:a,minutes:s,seconds:i,uncertain:g,approximate:M}}}const B3="dates",Qp="start",tm="end",Wy="durations",em="durationMin",im="durationMax";class Ep extends ja{static format=U.group(B3,U.optionalGroup(Qp,U.group("openStart","\\.\\.")+"|"+$e.format(Qp))+"/"+U.optionalGroup(tm,U.group("openEnd","\\.\\.")+"|"+$e.format(tm)))+"|"+U.group(Wy,U.group(em,te.format(em))+"/"+U.group(im,te.format(im)));constructor(t="interval",e=Ep.format){super(t,e)}parseGroups(t){let e,i;if(t[Wy]){const s=t[em];e=hn.fromString(s,new te);const r=t[im];i=hn.fromString(r,new te)}else{const s=t[Qp];switch(s){case void 0:e=null;break;case"..":e=void 0;break;default:e=fs.fromString(s,new $e)}const r=t[tm];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=fs.fromString(r,new $e)}}return{start:e,end:i}}}class H3{parse(t){t=t.trim();const e=t.startsWith("["),n=t.substring(1,t.length-1).split(","),s=[];for(const r of n){let a;r.includes("..")?a=ed.fromString(r.replace("..","/"),new Ep):a=fs.fromString(r,new $e),s.push(a)}return{values:s,exclusive:e}}}const nb=["spring","summer","autumn","winter"],Xg=21,G3=32,V3=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let W3;function X3(){return W3??=new $e}function Zc(o){return typeof o?.value=="number"?o.value:void 0}function Y3(o){const t=o.trim();if(/^\d{1,2}:/.test(t)){const r=V3.exec(t)?.groups;return r?{year:void 0,month:void 0,day:void 0,hour:Number(r.hour),minute:Number(r.minute),second:r.second?Number(r.second):void 0,raw:t}:void 0}let e;try{e=fs.fromString(t,X3())}catch{return}const i=Zc(e.year),n=Zc(e.month),s=n!==void 0&&n>=Xg&&n<=G3;if(!(e.timeshift||i!==void 0&&Math.abs(i)>9999)&&!(n!==void 0&&n>12&&!s)&&!(s&&(e.day||e.hour)))return{year:i,month:s?void 0:n,...s?{season:nb[(n-Xg)%4]}:{},day:Zc(e.day),hour:Zc(e.hour),minute:Zc(e.minute),second:Zc(e.second),raw:t}}function sb(o){if(o.raw!==void 0)return o.raw;if(o.year===void 0){if(o.hour===void 0)return"";let e=`${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`;return o.second!==void 0&&(e+=`:${String(o.second).padStart(2,"0")}`),e}let t=String(o.year).padStart(4,"0");return o.season!==void 0?`${t}-${Xg+nb.indexOf(o.season)}`:(o.month===void 0||(t+=`-${String(o.month).padStart(2,"0")}`,o.day===void 0)||(t+=`-${String(o.day).padStart(2,"0")}`,o.hour===void 0)||(t+=`T${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`,o.second!==void 0&&(t+=`:${String(o.second).padStart(2,"0")}`)),t)}function Yg(o){if(o.year!==void 0)return Date.UTC(o.year,(o.month??1)-1,o.day??1,o.hour??0,o.minute??0,o.second??0)}function Xy(o){return(((o.day??0)*24+(o.hour??0))*60+(o.minute??0))*6e4+(o.second??0)*1e3}const $3=["year","month","day","hour","minute"],K3=["day","hour","minute"];function Yy(o,t){return t.filter(e=>o[e]!==void 0).join(",")}function q3(o){if(o.durationSeconds!==void 0)return o.durationSeconds*1e3;const t=o.durationText===void 0?void 0:Iu.parse(o.durationText);if(t)return t.chosenSeconds*1e3;if(!o.time||!o.endTime)return;const e=o.time.year!==void 0&&o.endTime.year!==void 0,i=e?$3:K3,n=Yy(o.time,i);if(!(n===""||n!==Yy(o.endTime,i)))return e?Yg(o.endTime)-Yg(o.time):Xy(o.endTime)-Xy(o.time)}class Ap{constructor(t,e,i,n,s,r,a,c,l=[],h,u,d,f=[],p=[],m=[],g=[]){this.event=t,this.timeline=e,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=a,this.weather=c,this.decor=l,this.weatherSource=h,this.instrumentId=u,this.exposureSeconds=d,this.milestones=f,this.references=p,this.roads=m,this.traces=g}provenance=tr.empty();loadIssues=[];account;sources;interpretation;variants=[];skyEvents;snapshots;modules;sway;lightPollution;observerMap;iso;film;metering;lens;vehicle;events;eventsExpansion;sampleMs;get observerCount(){return 1+this.decor.filter(t=>t.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return Xi.byId(this.instrumentId)}static create(t,e,i){return new Ap({eventType:"sighting",time:t,place:e},new Ud,new Zu,new Ju,new ju,i)}}const Z3=0,J3=0;function Be(o,t){const e=o.observerTrack.getInterpolatedPoseAt(t);if(e)return e;const i=o.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:Z3,headingDeg:void 0,pitchDeg:J3,fovDeg:Xi.fieldOfViewDeg(o.instrument)}}function Xh(o,t){return o.weatherTrack.getInterpolatedWeatherAt(t)??o.weather??yp}function Yh(o,t){return o.weatherTrack.getActualWeatherAt(t)??o.weather??yp}function j3(o,t){return o.soundTrack.getInterpolatedSoundAt(t)??KA}class Qi{static toCurrent(t){const e=t.version,i=typeof e=="object"&&e!==null&&"value"in e?e.value:e;if(i!==void 0&&i!==1&&i!==2&&i!==3)return t;let n=t;return(i===void 0||i===1)&&(n=Qi.fromVersion1(n)),i!==3&&(n=Qi.fromVersion2(n)),Qi.fromVersion3(n)}static fromVersion3(t){const e={};for(const[i,n]of Object.entries(t))i==="frozen"?e.snapshots=n:e[i]=n;return e.version=4,e}static observerIdOf(t){return t.observer?.id??"observer"}static fromVersion2(t){const e={...t,version:3},i={...t.timeline??{keyframes:[]}},n=new Set,s=i.keyframes??[];for(const h of s)for(const u of h.shapes??[])n.add(u.sourceId);const r=[],a=h=>{let u=h;for(let d=r.length+1;u===void 0||n.has(u);d++)u=`group-${d}`;return n.add(u),u},c=Array.isArray(i.groups)?i.groups:[];for(const h of c)Array.isArray(h)?r.push({id:a(),members:[...h]}):typeof h=="object"&&h!==null&&r.push(h);const l=Array.isArray(t.events)?t.events.map(h=>({...h})):void 0;if(l){const h=Qi.observerIdOf(t),u=l.filter(M=>M.who==="phenomenon"),d=new Set(n);for(const M of u){const v=Qi.unwrapped(M.params?.parts);if(M.eventType==="appearance"&&Array.isArray(v))for(const x of v)x.sourceId&&d.add(x.sourceId)}for(const M of d)n.add(M);const f=M=>r.find(v=>v.members.includes(M)),p=M=>{const v=f(M);return v?p(v.id):M},m=[...new Set([...d].map(p))],g=m.length===1?m[0]:m.length>1?a("phenomenon"):"phenomenon";m.length>1&&r.push({id:g,members:m});for(const M of l)if(M.who===void 0||M.who==="observer")M.who=h;else if(M.who==="phenomenon"){M.who=g;const v=M.params;if(M.eventType!=="blink"||!v||!Array.isArray(v.parts))continue;const x=v.parts,{parts:y,...w}=v;M.params=w,M.who=Qi.groupFor(x,r,a)??g}e.events=l}return(r.length>0||c.length>0)&&(e.timeline={...i,groups:r}),e}static groupFor(t,e,i){if(t.length===1)return t[0];const n=l=>{const h=e.find(u=>u.id===l);return h?h.members.flatMap(n):[l]},s=e.find(l=>{const h=n(l.id);return h.length===t.length&&t.every(u=>h.includes(u))});if(s)return s.id;const r=new Set(t.map(l=>e.find(h=>h.members.includes(l))));if(r.size!==1)return;const[a]=r,c=i();if(a){const l=a.members.findIndex(h=>t.includes(h));a.members=a.members.filter(h=>!t.includes(h)),a.members.splice(l,0,c)}return e.push({id:c,members:[...t]}),c}static unwrapped(t){return Qi.isWrapped(t)?t.value:t}static fromVersion1(t){const e={...t,version:2};for(const i of["time","endTime"])t[i]!==void 0&&(e[i]=Qi.edtf(t[i]));if(Array.isArray(t.place)){const i=Qi.place(t.place);i===void 0?delete e.place:e.place=i}return e}static edtf(t){if(Qi.isWrapped(t)){const l=Qi.edtf(t.value);return l===void 0?void 0:{...t,value:l}}if(typeof t=="string")return t;const e=t,i=Object.values(e).find(l=>Qi.isWrapped(l)),n=Object.fromEntries(Object.entries(e).map(([l,h])=>[l,Qi.isWrapped(h)?h.value:h])),s=sb(n);if(s==="")return;if(!i)return s;const{basis:r,rationale:a,how:c}=i;return{value:s,...r===void 0?{}:{basis:r},...a===void 0?{}:{rationale:a},...c===void 0?{}:{how:c}}}static place(t){if(t.length===0)return;const e=t.map(l=>Qi.isWrapped(l)?l.value:l),i=e.find(l=>l.name)?.name,n={...i?{name:i}:{},locations:e.map(({lat:l,lng:h})=>({lat:l,lng:h}))},s=t.find(l=>Qi.isWrapped(l));if(!s)return n;const{basis:r,rationale:a,how:c}=s;return{value:n,...r===void 0?{}:{basis:r},...a===void 0?{}:{rationale:a},...c===void 0?{}:{how:c}}}static isWrapped(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"value"in t}}class Ic{static sessionDeclared=!1;static unlock(t){if(Ic.declarePlayback(),t.state!=="running")try{Promise.resolve(t.resume()).catch(()=>{});const e=t.createBufferSource();e.buffer=t.createBuffer(1,1,22050),e.connect(t.destination),e.start(0)}catch{}}static declarePlayback(){if(!(Ic.sessionDeclared||typeof navigator>"u")){Ic.sessionDeclared=!0;try{const t=navigator.audioSession;t&&(t.type="playback")}catch{}}}}const Q3=.08,$y=.15,Ky=2,t_=2e3;class e_{context;noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",t);return}}Ic.unlock(this.context),this.apply()}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}setPaused(t){t!==this.paused&&(this.paused=t,this.apply())}setVoices(t){this.requested=t,this.apply()}dispose(){for(const t of[...this.voices.keys()])this.release(t);this.context?.close(),this.context=void 0,this.master=void 0}masterOf(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}apply(){const t=this.context;if(!t)return;const e=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<t_),i=new Set(e.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of e){const s=this.voices.get(n.id)??this.build(t,n.id);this.retarget(t,s,n)}}build(t,e){const i=t.createGain();i.gain.value=0;const n=t.createBiquadFilter();n.type="lowpass",n.connect(i).connect(this.masterOf(t));const s=t.createOscillator();s.type="sawtooth";const r=t.createOscillator();r.type="sine";const a=t.createGain(),c=t.createBiquadFilter();c.type="lowpass",c.frequency.value=900,s.connect(c),r.connect(c),c.connect(a).connect(n);const l=()=>{const w=t.createBufferSource();return w.buffer=this.noise(t),w.loop=!0,w.loopStart=Math.random()*Ky*.5,w},h=l(),u=t.createBiquadFilter();u.type="bandpass",u.Q.value=4;const d=t.createGain();h.connect(u).connect(d).connect(n);const f=l(),p=t.createBiquadFilter();p.type="lowpass",p.frequency.value=600;const m=t.createGain();f.connect(p).connect(m).connect(n);const g=l(),M=t.createBiquadFilter();M.type="bandpass",M.frequency.value=1400,M.Q.value=.7;const v=t.createGain();g.connect(M).connect(v).connect(n);const x=[s,r,h,f,g];for(const w of x)w.start();const y={nodes:[i,n,a,c,u,d,p,m,M,v,...x],sources:x,firing:s,crank:r,knock:u,engineGain:a,knockGain:d,roadGain:m,windGain:v,cabin:n,output:i};return this.voices.set(e,y),y}retarget(t,e,{profile:i,state:n,noise:s,inside:r,windowsOpen:a,distanceM:c}){const l=t.currentTime,h=(v,x)=>v.setTargetAtTime(x,l,Q3),u=n.rpm/60,d=u*i.cylinders/2,f=Math.min(1,n.rpm/i.shiftUpRpm),p=Math.min(1.5,n.speedMps/30);h(e.firing.frequency,d),h(e.crank.frequency,u),h(e.knock.frequency,d*3),h(e.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*f)*.3),h(e.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(e.roadGain.gain,i.roadGain*p**1.5*.8);const m=!r||a;h(e.windGain.gain,p**2*(m?.5:.06));const g=r?a?3500:700:8e3/(1+c/60);h(e.cabin.frequency,g);const M=r?.5:Math.min(1,8/Math.max(c,1));h(e.output.gain,M*s)}release(t){const e=this.voices.get(t);if(!e)return;this.voices.delete(t);const i=this.context;i&&(e.output.gain.setTargetAtTime(0,i.currentTime,$y/3),setTimeout(()=>{for(const n of e.sources)try{n.stop()}catch{}for(const n of e.nodes)n.disconnect()},$y*1e3*3))}noise(t){if(this.noiseBuffer)return this.noiseBuffer;const e=t.createBuffer(1,t.sampleRate*Ky,t.sampleRate),i=e.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=e,e}}class kc{static MODES=["off","position","dipped","main","fog"];static DISPLAY_GAIN=.006;static TOE_IN_DEG=.6;static AUTO_BELOW_SUN_DEG=-1;static BEAMS={off:void 0,position:void 0,dipped:{candela:25e3,halfAngleDeg:24,pitchDeg:2.5,penumbra:1,color:"#fff2d8"},main:{candela:12e4,halfAngleDeg:14,pitchDeg:.4,penumbra:.85,color:"#fff6e6"},fog:{candela:9e3,halfAngleDeg:38,pitchDeg:5,penumbra:1,color:"#ffe9b0"}};static isMode(t){return typeof t=="string"&&kc.MODES.includes(t)}static at(t,e,i){if(!e||e.length===0)return t;let n=e[0];for(const s of e){if(s.t>i)break;n=s}return n.mode}static auto(t){return t<kc.AUTO_BELOW_SUN_DEG?"dipped":"off"}static lamps(t){return t!=="off"}}const qy=2;function L0(o){return o==="building"||o==="vehicle"}const rb={aircraft:{id:"poly-google-airliner"},tree:{id:"jungle-jim-tree-large-a"},observer:{id:"makehuman-farmer-40s"},entity:{id:"makehuman-farmer-40s"}},i_=["makehuman-farmer-40s","makehuman-man-overalls","makehuman-man-jacket","makehuman-old-man","makehuman-woman"];function Zy(o,t){let e=0;for(const i of t)e=e*31+i.charCodeAt(0)>>>0;return{id:o[e%o.length]}}const n_=["jungle-jim-tree-large-a","jungle-jim-tree-medium-a","jungle-jim-tree-large-b","jungle-jim-tree-medium-b","jungle-jim-tree-large-c","jungle-jim-tree-medium-c","jagobo-tree-maple-a","jagobo-tree-maple-b","jagobo-tree-aspen-a","jagobo-tree-aspen-b","nicholas-3d-tree-a","nicholas-3d-tree-b","nicholas-3d-tree-c"];function $g(o){return o.model?o.model:o.kind==="tree"&&o.id!==void 0?Zy(n_,o.id):(o.kind==="observer"||o.kind==="entity")&&o.id!==void 0?Zy(i_,o.id):rb[o.kind]}function ab(o,t){const e=kc.at(o.headlights,o.headlightKeyframes,t);return e!==void 0?e:YM(o,t)?"dipped":"off"}const s_=-.5;function r_(o){return o.kind==="streetlight"&&o.origin!==void 0&&o.lit===void 0&&!o.litKeyframes?.length}function YM(o,t,e){if(e!==void 0&&r_(o))return e<s_;const i=o.litKeyframes;if(!i||i.length===0)return o.lit??!1;let n=i[0];for(const s of i){if(s.t>t)break;n=s}return n.lit}function Jy(o,t){const e=o.observerKeyframes;if(!e||e.length===0)return{side:o.observerSide,facing:o.observerFacing};let i=e[0];for(const n of e){if(n.t>t)break;i=n}return{side:i.side,facing:i.facing}}function a_(o,t){const e=lh(o,t);return e.intensity<=0?!1:e.pattern.kind==="steady"?!0:ob(o,t,t+1)>.5}function lh(o,t){let e;for(const i of o.keyframes??[]){if(i.t>t)break;e=i}return{intensity:e?.intensity??o.intensity??1,pattern:e?.pattern??o.pattern}}function ob(o,t,e){const i=o.keyframes??[];if(i.length===0)return nm(o.pattern,t,e);const n=[t,...i.map(r=>r.t).filter(r=>r>t&&r<e),e];if(e<=t)return lh(o,t).intensity>0?nm(lh(o,t).pattern,t,e):0;let s=0;for(let r=0;r<n.length-1;r++){const a=lh(o,n[r]);a.intensity>0&&(s+=nm(a.pattern,n[r],n[r+1])*(n[r+1]-n[r]))}return s/(e-t)}function nm(o,t,e){if(o.kind==="steady")return 1;const{perMinute:i,dutyCycle:n,phase:s=0}=o,r=Math.min(Math.max(n,0),1);if(r===0||i<=0)return 0;const a=6e4/i,c=t/a+s,l=e/a+s;if(l<=c)return Math.min(Math.max(c-Math.floor(c),0),r)<r?1:0;const h=u=>Math.floor(u)*r+Math.min(u-Math.floor(u),r);return(h(l)-h(c))/(l-c)}function oa(o,t){const e=o.track,i={eastM:o.eastM,northM:o.northM,altitudeM:0,headingDeg:o.headingDeg};if(!e||e.length===0)return i;if(e.length===1||t<=e[0].t)return jy(e[0],o);const n=e[e.length-1];if(t>=n.t)return jy(n,o);for(let s=0;s<e.length-1;s++){const r=e[s],a=e[s+1];if(t<r.t||t>a.t)continue;const c=a.t-r.t,l=c===0?0:(t-r.t)/c;return{eastM:r.eastM+(a.eastM-r.eastM)*l,northM:r.northM+(a.northM-r.northM)*l,altitudeM:(r.altitudeM??0)+((a.altitudeM??0)-(r.altitudeM??0))*l,headingDeg:r.headingDeg??o.headingDeg}}return i}function o_(o,t){const e=(o.track??[]).filter(i=>i.gazeAzimuthDeg!==void 0);if(e.length!==0){if(t<=e[0].t)return e[0].gazeAzimuthDeg;for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];if(t>s.t)continue;const r=s.t-n.t,a=r===0?0:(t-n.t)/r,c=((s.gazeAzimuthDeg-n.gazeAzimuthDeg)%360+540)%360-180;return((n.gazeAzimuthDeg+c*a)%360+360)%360}return e[e.length-1].gazeAzimuthDeg}}function jy(o,t){return{eastM:o.eastM,northM:o.northM,altitudeM:o.altitudeM??0,headingDeg:o.headingDeg??t.headingDeg}}class yd{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(t){return yd.BY_KIND[t??"generic"]??yd.BY_KIND.generic}}class xc{constructor(t,e){this.samples=t,this.startMs=e}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(t,e,i,n){const s=xc.SAMPLE_MS,r=[];for(let l=i;l<=n+s/2;l+=s){const h=e(l-s/2),u=e(l+s/2);if(!h||!u)return;r.push(Math.hypot(u.eastM-h.eastM,u.northM-h.northM)/(s/1e3))}const a=[];let c=1;for(let l=0;l<r.length;l++){const h=r[l],u=(r[Math.min(l+1,r.length-1)]-r[Math.max(l-1,0)])/(2*s/1e3);if(h<xc.STANDING_MPS){c=1,a.push({speedMps:h,rpm:t.idleRpm,load:.1,gear:0});continue}const d=h*3.6,f=M=>d/t.kmhPer1000Rpm[M-1]*1e3;for(;c<t.kmhPer1000Rpm.length&&f(c)>t.shiftUpRpm;)c++;for(;c>1&&f(c)<t.shiftDownRpm;)c--;const p=Math.max(f(c),t.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),g=u>.15?Math.min(1,m+u/2.5):u<-.3?.05:m;a.push({speedMps:h,rpm:p,load:g,gear:c})}return new xc(a,i)}at(t){const e=(t-this.startMs)/xc.SAMPLE_MS,i=Math.min(Math.max(Math.floor(e),0),this.samples.length-1),n=this.samples[i],s=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(e-i,0),1);return{speedMps:n.speedMps+(s.speedMps-n.speedMps)*r,rpm:n.rpm+(s.rpm-n.rpm)*r,load:n.load+(s.load-n.load)*r,gear:r<.5?n.gear:s.gear}}}class k0{drives=new Map;at(t,e){const i=[],n=t.event.place?.[0],s=l=>{const h=t.observerTrack.getInterpolatedPoseAt(l),u=h?.lat??n?.lat,d=h?.lng??n?.lng;if(u===void 0||d===void 0||!n)return;const f=ae(u,d,n.lat,n.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3),a=t.vehicle;if(a){const l=yd.of(a.kind),h=this.drive(`observer:${a.kind}`,k0.trackKey(t),()=>xc.of(l,s,0,r));h&&i.push({id:"observer",profile:l,state:h.at(e),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const c=s(e);for(const l of t.decor){if(!l.engine||!c)continue;const h=yd.of(l.engine.kind),u=m=>{const g=oa(l,m);return{eastM:g.eastM,northM:g.northM}},d=this.drive(`decor:${l.id}`,k0.decorKey(l,r),()=>xc.of(h,u,0,r));if(!d)continue;const f=oa(l,e),p=Math.hypot(f.eastM-c.eastM,f.northM-c.northM,f.altitudeM);i.push({id:`decor:${l.id}`,profile:h,state:d.at(e),noise:l.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:p})}return i}drive(t,e,i){const n=this.drives.get(t);if(n&&n.key===e)return n.drive;const s=i();return this.drives.set(t,{key:e,drive:s}),s}static trackKey(t){return t.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(t,e){return`${e}|${t.eastM},${t.northM}|`+(t.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const Qy=864e5,t2=4e4;function c_(o){const t=Math.floor(o.getTime()/Qy);return{elapsedMs:o.getTime()-t*Qy,shiftM:{x:e2.unit(t,2654435761)*t2,z:e2.unit(t,2246822507)*t2}}}class e2{static unit(t,e){let i=Math.imul(t|0,e)^e;return i=Math.imul(i^i>>>15,739982445),i=Math.imul(i^i>>>12,695872825),i^=i>>>15,(i>>>0)/4294967295*2-1}}function i2(o,t,e,i,n,s,r){const a=i?.lat!==void 0&&i.lng!==void 0&&n?.lat!==void 0&&n.lng!==void 0?ae(n.lat,n.lng,i.lat,i.lng):{x:0,z:0};if(r){const h=t.getInterpolatedWeatherAt(0)??e,u=s===void 0?void 0:h.cloudLayers?.find(p=>p.id===s),d=(u?.windDirectionDeg??h.windDirectionDeg)*Math.PI/180,f=(u?.windSpeed??h.windSpeed)*r.elapsedMs/1e3;a.x+=r.shiftM.x-Math.sin(d)*f,a.z+=r.shiftM.z+Math.cos(d)*f}const c=Math.max(0,o),l=[0,...t.allKeyframes.map(h=>h.t).filter(h=>h>0&&h<c),c];for(let h=1;h<l.length;h++){const u=l[h-1],d=l[h]-u;if(d===0)continue;const f=32;for(let p=0;p<=f;p++){const m=t.getInterpolatedWeatherAt(u+d*p/f)??e,g=s===void 0?void 0:m.cloudLayers?.find(y=>y.id===s),M=(g?.windDirectionDeg??m.windDirectionDeg)*Math.PI/180,v=p===0||p===f?1:p%2===0?2:4,x=(g?.windSpeed??m.windSpeed)*d/1e3/f/3*v;a.x-=Math.sin(M)*x,a.z+=Math.cos(M)*x}}return a}const l_="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",h_=`
3
3
  <div class="stage" id="stage">
4
4
  <div class="frame" id="frame">
5
5
  <canvas id="scene-canvas"></canvas>
@@ -1762,12 +1762,12 @@ canvas[data-cursor="rotate"] {
1762
1762
  pointer-events: none;
1763
1763
  white-space: nowrap;
1764
1764
  }
1765
- `;class uh{constructor(t){this.points=t}static STATIONARY_M=5;static of(t){const e=[];for(const i of t.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||e.push({t:i.t,lat:n,lng:s,headingDeg:r})}if(e.length===0){const i=t.event.place?.[0];if(!i)return;e.push({t:0,lat:i.lat,lng:i.lng})}return new uh(e)}static TRAVEL_M=50;get travels(){return this.spanM>uh.TRAVEL_M}get moved(){return this.spanM>uh.STATIONARY_M}get spanM(){const t=this.box,e=(t.south+t.north)/2,i=(t.west+t.east)/2;return Math.max(Math.abs(ae(e,t.east,e,t.west).x),Math.abs(ae(t.north,i,t.south,i).z))}get center(){const t=this.box;return{lat:(t.south+t.north)/2,lng:(t.west+t.east)/2}}boundsAround(t,e){const{lat:i,lng:n}=this.center,s=Math.max(this.spanM*(1+e),t)/2;return{north:Is(0,-s,i,n).lat,south:Is(0,s,i,n).lat,east:Is(s,0,i,n).lng,west:Is(-s,0,i,n).lng}}get box(){const t=this.points.map(i=>i.lat),e=this.points.map(i=>i.lng);return{south:Math.min(...t),north:Math.max(...t),west:Math.min(...e),east:Math.max(...e)}}}class Zs{constructor(t,e){this.rotationPassed=t,this.scale=e}static SWAY_M=.012;static BREATH_M=.003;static DRIFT_YAW_DEG=.5;static DRIFT_PITCH_DEG=.4;static DRIFT_ROLL_DEG=.3;static GAZE_DRIFT_SHARE=.35;static HAND_HELD_S=.5;static HZ=[.11,.23,.17,.29,.37,.07];static of(t){if(t.instrument.mounted)return;const e=t.event.tags?.includes("paralysis")||(t.exposure??0)>Zs.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new Zs(Math.max(1-(t.instrument.stabilization??0),Zs.GAZE_DRIFT_SHARE),i)}offsetAt(t){const e=t/1e3,i=this.scale,n=(u,d)=>Math.sin(2*Math.PI*u*e+d),[s,r,a,c,l,h]=Zs.HZ;return{eastM:i*Zs.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*Zs.SWAY_M*(.6*n(a,2.2)+.4*n(l,.8)),upM:i*Zs.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*Zs.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*Zs.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*Zs.DRIFT_ROLL_DEG*n(s,2.9)}}}class ri{constructor(t,e){this.stretches=t,this.rotationPassed=e}static REFERENCE_SPEED_M_PER_S=1.4;static REFERENCE_STEP_HZ=1.9;static CADENCE_EXPONENT=.43;static RISE_M_PER_M_PER_S=.0175;static SWAY_M=.0175;static SLOWEST_WALK_M_PER_S=.2;static FASTEST_WALK_M_PER_S=2.2;static HEAD_ROLL_DEG=1.5;static HEAD_PITCH_DEG=1.25;static HEAD_YAW_DEG=1;static STOP_LURCH_M=.035;static STOP_PITCH_DEG=3;static START_LURCH_M=.015;static START_PITCH_DEG=1.2;static JOLT_HZ=1.4;static JOLT_DECAY_S=.35;static JOLT_LASTS_MS=1500;static STILL=Object.freeze({eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0});static of(t){const e=uh.of(t);if(!e||e.points.length<2)return;const i=[];let n=0;for(let s=1;s<e.points.length;s++){const r=e.points[s-1],a=e.points[s],c=(a.t-r.t)/1e3;if(c<=0)continue;const l=ae(a.lat,a.lng,r.lat,r.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/c,p=ri.stepHzFor(f);i.push({startMs:r.t,endMs:a.t,speedMPerS:f,eastUnit:d>0?h/d:0,northUnit:d>0?u/d:0,stepHz:p,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=p*c}for(let s=0;s<i.length;s++){const r=i[s-1],a=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=a===void 0||a.stepHz===0}if(i.some(s=>s.stepHz>0))return new ri(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const n=ri.of(t)?.offsetAt(e)??ri.STILL;return i?n:ri.add(n,Zs.of(t)?.offsetAt(e))}static stepHzFor(t){return t<ri.SLOWEST_WALK_M_PER_S||t>ri.FASTEST_WALK_M_PER_S?0:ri.REFERENCE_STEP_HZ*Math.pow(t/ri.REFERENCE_SPEED_M_PER_S,ri.CADENCE_EXPONENT)}offsetAt(t){return ri.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/ri.REFERENCE_SPEED_M_PER_S,n=(a,c,l,h)=>{if(a<0||a>ri.JOLT_LASTS_MS)return;const u=a/1e3,d=Math.exp(-u/ri.JOLT_DECAY_S)*Math.sin(2*Math.PI*ri.JOLT_HZ*u),f=h*c*i*d;return{eastM:f*e.eastUnit,northM:f*e.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-h*l*i*d*this.rotationPassed,yawDeg:0}},s=e.rampsOut?n(t-e.endMs,ri.STOP_LURCH_M,ri.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=e.rampsIn?n(t-e.startMs,ri.START_LURCH_M,ri.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(t,e){return e?{eastM:t.eastM+e.eastM,northM:t.northM+e.northM,upM:t.upM+e.upM,rollDeg:t.rollDeg+e.rollDeg,pitchDeg:t.pitchDeg+e.pitchDeg,yawDeg:t.yawDeg+e.yawDeg}:t}cycleAt(t){const e=this.stretches.find(c=>t>=c.startMs&&t<=c.endMs);if(!e||e.stepHz===0)return ri.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(e,t),r=ri.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*e.speedMPerS/ri.REFERENCE_SPEED_M_PER_S;return{eastM:r*e.northUnit,northM:-r*e.eastUnit,upM:ri.RISE_M_PER_M_PER_S*e.speedMPerS*s*Math.cos(n),rollDeg:ri.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:ri.HEAD_YAW_DEG*a*Math.cos(n/2)}}amplitudeAt(t,e){const i=1e3/t.stepHz,n=Math.min(i,(t.endMs-t.startMs)/2);if(n<=0)return 1;const s=e-t.startMs,r=t.endMs-e,a=Math.min(t.rampsIn?s/n:1,t.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class p_{constructor(t,e){this.timeline=t,this.onFrame=e}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;onEnded;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const t=()=>{if(this.state!=="playing")return;const e=performance.now();if(this.currentT+=(e-this.lastWallTime)*this.playbackRate,this.lastWallTime=e,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(t){this.currentT=Math.max(0,Math.min(t,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(t){const e=new Map;for(const i of this.timeline.sourceIds){const n=this.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}this.onFrame(t,e)}}const cb=["nw","n","ne","e","se","s","sw","w"],m_=24,Kd=8,g_=3,M_=8;function qd(o,t,e){const i=o.x-t.x,n=o.y-t.y,s=Math.cos(e),r=Math.sin(e);return{x:t.x+i*s-n*r,y:t.y+i*r+n*s}}function $h(o){return{x:o.x+o.width/2,y:o.y+o.height/2}}const v_={nw:{left:!0,top:!0},n:{top:!0},ne:{right:!0,top:!0},e:{right:!0},se:{right:!0,bottom:!0},s:{bottom:!0},sw:{left:!0,bottom:!0},w:{left:!0}};class zs{static handlePointsFor(t){const{x:e,y:i,width:n,height:s}=t.bounds,r={nw:{x:e,y:i},n:{x:e+n/2,y:i},ne:{x:e+n,y:i},e:{x:e+n,y:i+s/2},se:{x:e+n,y:i+s},s:{x:e+n/2,y:i+s},sw:{x:e,y:i+s},w:{x:e,y:i+s/2},rotate:{x:e+n/2,y:i-m_}},a=$h(t.bounds),c={};for(const l of Object.keys(r))c[l]=qd(r[l],a,t.angle);return c}static hitTestHandle(t,e,i=8,n=[...cb,"rotate"]){const s=zs.handlePointsFor(t);for(const r of n)if(Math.hypot(e.x-s[r].x,e.y-s[r].y)<=i)return r}static HANDLE_DIRECTION_DEG={e:0,se:45,s:90,sw:135,w:180,nw:225,n:270,ne:315};static resizeAxisFor(t,e){const n=((zs.HANDLE_DIRECTION_DEG[t]+e*180/Math.PI)%180+180)%180/45,s=["ew","nwse","ns","nesw"];return s[Math.round(n)%s.length]}static resizeBounds(t,e,i,n){const s=$h(t),r=qd(n,s,-e),{x:a,y:c,width:l,height:h}=t,u=v_[i];let d=a,f=c,p=a+l,m=c+h;return u.left&&(d=Math.min(r.x,p-Kd)),u.right&&(p=Math.max(r.x,d+Kd)),u.top&&(f=Math.min(r.y,m-Kd)),u.bottom&&(m=Math.max(r.y,f+Kd)),{x:d,y:f,width:p-d,height:m-f}}static resizeShape(t,e,i){if(e==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=t.bounds,r=zs.resizeBounds(t.bounds,t.angle,e,i);if(t.kind==="oval")return{...t,bounds:r};const a=n===0?1:r.width/n,c=s===0?1:r.height/s;return{...t,bounds:r,points:t.points.map(l=>({x:l.x*a,y:l.y*c}))}}static rotateShape(t,e){const i=$h(t.bounds),n=Math.atan2(e.y-i.y,e.x-i.x)+Math.PI/2;return{...t,angle:n}}static groupBoundsFor(t){const e=Math.min(...t.map(r=>r.x)),i=Math.min(...t.map(r=>r.y)),n=Math.max(...t.map(r=>r.x+r.width)),s=Math.max(...t.map(r=>r.y+r.height));return{x:e,y:i,width:n-e,height:s-i}}static vertexPointsFor(t){const e=$h(t.bounds);return t.points.map(i=>qd({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=M_){const n=zs.vertexPointsFor(t);let s,r=i;return n.forEach((a,c)=>{const l=Math.hypot(e.x-a.x,e.y-a.y);l<=r&&(r=l,s=c)}),s}static toLocalPoint(t,e){const i=$h(t.bounds),n=qd(e,i,-t.angle);return{x:n.x-t.bounds.x,y:n.y-t.bounds.y}}static moveVertex(t,e,i){const n=t.points.map((u,d)=>d===e?zs.toLocalPoint(t,i):u),s=Math.min(...n.map(u=>u.x)),r=Math.min(...n.map(u=>u.y)),a=Math.max(...n.map(u=>u.x)),c=Math.max(...n.map(u=>u.y)),l={x:t.bounds.x+s,y:t.bounds.y+r,width:a-s,height:c-r},h=n.map(u=>({x:u.x-s,y:u.y-r}));return{...t,bounds:l,points:h}}static insertVertexNear(t,e){const i=zs.toLocalPoint(t,e),{points:n}=t;let s=n.length-1,r=1/0;for(let c=0;c<n.length;c++){const l=n[c],h=n[(c+1)%n.length],u=zs.distanceToSegment(i,l,h);u<r&&(r=u,s=c)}const a=[...n.slice(0,s+1),i,...n.slice(s+1)];return{...t,points:a}}static distanceToSegment(t,e,i){const n=i.x-e.x,s=i.y-e.y,r=n*n+s*s,a=r===0?0:Math.max(0,Math.min(1,((t.x-e.x)*n+(t.y-e.y)*s)/r)),c=e.x+a*n,l=e.y+a*s;return Math.hypot(t.x-c,t.y-l)}static deleteVertex(t,e){return t.points.length<=g_?t:{...t,points:t.points.filter((i,n)=>n!==e)}}}const Kg=6,Zd=Kg/2,n2=20,s2=24,r2=9,a2=6,o2=7,c2=6,Cr=4;class Ph{constructor(t){this.ctx=t}starPoints=0;roll=0;clear(t,e){this.ctx.clearRect(0,0,t,e)}static paintExtent(t){const{x:e,y:i,width:n,height:s}=t.bounds,r=e+n/2,a=i+s/2,c=t.angle%(2*Math.PI)!==0,l=Math.hypot(n,s)/2,h=c?l:n/2,u=c?l:s/2,d=Math.max(n,s)/2,f=t.brightness??0,p=f>0?Math.max(d*(1+r2*f),c2*f)-d:0,m=f>0?d*(1+o2*f)-d:0,g=3*s2*(t.blur??0)+1.5*n2*t.haloScale,M=Math.max(p,m,0)+g+2;return{x:r-h-M,y:a-u-M,width:2*(h+M),height:2*(u+M)}}paintInto(t,e,i,n=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-e.x,-e.y);const s=t.selected?{...t,selected:!1}:t;n?this.paintGhost(s,1.5):this.paintShape(s),this.ctx.restore()}paintShape(t){this.ctx.save(),this.ctx.globalAlpha=1-t.transparency;const e=t.blur??0;e>0&&(this.ctx.filter=`blur(${(s2*e).toFixed(2)}px)`);const i=t.brightness??0;i>0&&this.paintDazzle(t,i),t.haloScale>0&&this.paintHalo(t),this.paintBase(t),this.ctx.restore(),t.selected&&this.paintSelectionHandles(t)}setStarPoints(t){this.starPoints=Math.max(0,Math.floor(t))}setRoll(t){this.roll=t}paintDazzle(t,e){const{x:i,y:n,width:s,height:r}=t.bounds,a=i+s/2,c=n+r/2,l=Math.max(s,r)/2,h=Math.max(l*(1+r2*e),c2*e);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const u=this.ctx.createRadialGradient(a,c,0,a,c,h);for(let d=0;d<=a2;d++){const f=d/a2,p=1/(1+24*f*f);this.ctx.globalAlpha=1,u.addColorStop(f,this.withAlpha(t.color,p*e*.55))}if(this.ctx.fillStyle=u,this.ctx.beginPath(),this.ctx.arc(a,c,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=l*(1+o2*e);this.ctx.lineWidth=Math.max(1,l*.12),this.ctx.lineCap="round";for(let f=0;f<this.starPoints;f++){const p=f/this.starPoints*Math.PI*2+this.roll,m=a+Math.cos(p)*d,g=c+Math.sin(p)*d,M=this.ctx.createLinearGradient(a,c,m,g);M.addColorStop(0,this.withAlpha(t.color,e*.55)),M.addColorStop(.35,this.withAlpha(t.color,e*.22)),M.addColorStop(1,this.withAlpha(t.color,0)),this.ctx.strokeStyle=M,this.ctx.beginPath(),this.ctx.moveTo(a,c),this.ctx.lineTo(m,g),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(t,e){if(e<=0)return t.color;const i=/^#([0-9a-f]{6})$/i.exec(t.color.trim());if(!i)return t.color;const n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*e);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(t,e){const i=Math.max(0,Math.min(1,e)),n=/^#([0-9a-f]{6})$/i.exec(t.trim());if(!n)return t;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&255}, ${i.toFixed(3)})`}paintBase(t){this.ctx.fillStyle=this.dazzledFill(t,t.brightness??0),this.tracePath(t),this.ctx.fill()}paintGhost(t,e){this.ctx.save(),this.tracePath(t),this.ctx.setLineDash([e*3,e*2]),this.ctx.lineWidth=e,this.ctx.strokeStyle=t.color,this.ctx.stroke(),this.ctx.restore()}tracePath(t){if(this.ctx.beginPath(),t.kind==="oval"){const{x:e,y:i,width:n,height:s}=t.bounds,r=n/2,a=s/2;this.ctx.ellipse(e+r,i+a,r,a,t.angle,0,2*Math.PI)}else{const{x:e,y:i,width:n,height:s}=t.bounds;this.ctx.save(),this.ctx.translate(e+n/2,i+s/2),this.ctx.rotate(t.angle),this.ctx.translate(-n/2,-s/2),t.points.forEach((r,a)=>{a===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(t){this.ctx.save(),this.ctx.shadowColor=t.color,this.ctx.shadowBlur=n2*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(zs.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of zs.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,Cr,Cr,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(zs.handlePointsFor(t))}paintSelectionOnly(t){this.paintSelectionHandles(t)}paintPictureFrame(t,e,i){const n=this.ctx;if(n.save(),t&&t.length===4){n.strokeStyle="#39f",n.lineWidth=1.5,n.setLineDash([6,4]),n.beginPath(),n.moveTo(t[0].x,t[0].y);for(const s of t.slice(1))n.lineTo(s.x,s.y);n.closePath(),n.stroke(),n.setLineDash([])}for(const s of e){const r=Ph.landmarkColour(s.residualDeg),a=s.selected?3:2;s.selected&&(n.strokeStyle="#fff",n.lineWidth=a+3,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Cr+2,Cr+2,0,0,2*Math.PI),n.stroke()),s.scene&&(n.strokeStyle=r,n.lineWidth=1,n.beginPath(),n.moveTo(s.picture.x,s.picture.y),n.lineTo(s.scene.x,s.scene.y),n.stroke(),n.fillStyle=r,n.beginPath(),n.ellipse(s.scene.x,s.scene.y,Cr,Cr,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=a,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Cr+2,Cr+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+Cr+5,s.picture.y-Cr-2,r)}i&&this.paintLabel(i,8,8,"#fff",13),n.restore()}paintGhosts(t,e,i){const n=this.ctx;n.save();const s=(c,l,h,u=[])=>{n.setLineDash(u),n.lineWidth=h+2,n.strokeStyle="rgba(0, 0, 0, 0.6)",c(),n.lineWidth=h,n.strokeStyle=l,c(),n.setLineDash([])},r=(c,l)=>()=>{n.beginPath(),n.arc(c.x,c.y,l,0,2*Math.PI),n.stroke()},a=(c,l,h)=>()=>{const[u,d]=h?[l,l]:[l,0];n.beginPath(),n.moveTo(c.x-u,c.y-d),n.lineTo(c.x+u,c.y+d),n.moveTo(c.x+d,c.y-u),n.lineTo(c.x-d,c.y+u),n.stroke()};for(const c of t)s(()=>{n.beginPath(),n.moveTo(c.ghost.x,c.ghost.y),n.lineTo(c.light.x,c.light.y),n.stroke()},"rgba(255, 255, 255, 0.85)",1,[4,4]),s(r(c.light,7),"#ffffff",1.5),s(r(c.ghost,Math.max(9,c.ghostRadius)),"#ffd23f",2);e&&s(a(e,8,!1),"#ffd23f",2),i&&s(a(i,5,!0),"rgba(255, 255, 255, 0.7)",1),n.restore()}static landmarkColour(t){return t===void 0?"#ffb000":t<=1?"#3c3":t<=3?"#ffb000":"#f33"}paintLabel(t,e,i,n,s=11){const r=this.ctx;r.save(),r.font=`${s}px system-ui, sans-serif`,r.textBaseline="top";const a=r.measureText(t).width;r.fillStyle="rgba(0, 0, 0, 0.6)",r.fillRect(e-3,i-2,a+6,s+4),r.fillStyle=n,r.fillText(t,e,i),r.restore()}paintGroupHandles(t){this.paintHandleFrame(zs.handlePointsFor({bounds:t,angle:0}),{includeRotate:!0})}paintOutline(t){this.ctx.strokeStyle="lightgray",this.ctx.beginPath(),this.ctx.moveTo(t.nw.x,t.nw.y),this.ctx.lineTo(t.ne.x,t.ne.y),this.ctx.lineTo(t.se.x,t.se.y),this.ctx.lineTo(t.sw.x,t.sw.y),this.ctx.closePath(),this.ctx.stroke()}paintHandleFrame(t,{includeRotate:e}){this.paintOutline(t),this.ctx.fillStyle="lightgray";for(const i of cb){const n=t[i];this.ctx.fillRect(n.x-Zd,n.y-Zd,Kg,Kg)}e&&(this.ctx.beginPath(),this.ctx.moveTo(t.n.x,t.n.y),this.ctx.lineTo(t.rotate.x,t.rotate.y),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.ellipse(t.rotate.x,t.rotate.y,Zd+1,Zd+1,0,0,2*Math.PI),this.ctx.fill())}}const l2=.05,h2=.08,u2=2,d2=3,y_=14,x_=.02;class w_{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",t);return}}Ic.unlock(this.context)}setSound(t){if(this.requested=t,!this.context)return;const e=this.keyFor(t);if(!e){this.silence();return}if(this.voice?.key!==e){this.stopVoice();const i=++this.voiceToken;e.startsWith("src:")?this.buildRecordedVoice(t.src,e,i):this.voice=this.buildSynthesizedVoice(t,e)}this.applyTo(this.voice,t)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(t){if(!(t.volume<=0))return t.src?`src:${t.src}`:t.kind==="none"?void 0:t.kind}applyTo(t,e){const i=this.context;if(!t||!i)return;const n=i.currentTime;t.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,e.volume))*t.gainScale,n,l2);for(const{param:s,ratio:r}of t.pitch)s.setTargetAtTime(Math.min(e.pitchHz*r,i.sampleRate/2-1),n,l2)}buildSynthesizedVoice(t,e){const i=this.context;if(i)switch(t.kind){case"hum":return this.buildHum(i,e);case"whistle":return this.buildWhistle(i,e);case"rumble":return this.buildRumble(i,e);case"crackle":return this.buildCrackle(i,e);default:return}}buildHum(t,e){const i=t.createOscillator();i.type="sawtooth";const n=t.createOscillator();n.type="sawtooth";const s=t.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=t.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:n.frequency,ratio:1.006},{param:s.frequency,ratio:6}]}}buildWhistle(t,e){const i=t.createOscillator();i.type="sine";const n=t.createOscillator();n.type="sine",n.frequency.value=5;const s=t.createGain(),r=t.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(t,e){const i=t.createBufferSource();i.buffer=this.brownNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=t.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(this.output(t)),i.start(),{key:e,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(t,e){const i=t.createBufferSource();i.buffer=this.whiteNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=t.createGain();s.gain.value=0;const r=t.createBufferSource();r.buffer=this.crackleEnvelope(t),r.loop=!0;const a=t.createGain();return a.gain.value=0,r.connect(a).connect(s.gain),i.connect(n).connect(s).connect(this.output(t)),i.start(),r.start(),{key:e,nodes:[n,s,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(t,e,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(t)}catch(c){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",c);return}if(i!==this.voiceToken||!this.context)return;const r=n.createBufferSource();r.buffer=s,r.loop=!0;const a=n.createGain();a.gain.value=0,r.connect(a).connect(this.output(n)),r.start(),this.voice={key:e,nodes:[a],sources:[r],volumeParam:a.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(t){const e=this.context;if(!e)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}whiteNoise(t){if(!this.noiseBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*u2),t.sampleRate),i=e.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=e}return this.noiseBuffer}brownNoise(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*u2),t.sampleRate),i=e.getChannelData(0);let n=0,s=0;for(let r=0;r<i.length;r++)n=(n+.02*(Math.random()*2-1))/1.02,i[r]=n,s=Math.max(s,Math.abs(n));if(s>0)for(let r=0;r<i.length;r++)i[r]/=s;return e}crackleEnvelope(t){if(!this.crackleBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*d2),t.sampleRate),i=e.getChannelData(0),n=Math.max(1,Math.floor(x_*t.sampleRate)),s=Math.round(d2*y_);for(let r=0;r<s;r++){const a=Math.floor(Math.random()*i.length),c=.4+Math.random()*.6;for(let l=0;l<n&&a+l<i.length;l++)i[a+l]=Math.max(i[a+l],c*(1-l/n))}this.crackleBuffer=e}return this.crackleBuffer}stopVoice(){const t=this.voice,e=this.context;if(this.voice=void 0,!t||!e)return;const i=e.currentTime;t.volumeParam.cancelScheduledValues(i),t.volumeParam.setTargetAtTime(0,i,h2/3);const n=i+h2;for(const s of t.sources){s.onended=()=>{s.disconnect();for(const r of t.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of t.nodes)r.disconnect()}}}}class Qt{static svg(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="currentColor"/></svg>`}static outline(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}static solid(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="currentColor" fill-rule="evenodd"/></svg>`}static BOOKMARK="M6 3.5h12a.5.5 0 0 1 .5.5v16.5L12 16.8l-6.5 3.7V4a.5.5 0 0 1 .5-.5z";static PICTURE="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z";static PICTURE_HILLS="M4.5 17.5l4.5-6 3 4 2.5-3 5 5z";static PIN="M12 21.5s-6.5-5.7-6.5-10.8a6.5 6.5 0 0 1 13 0c0 5.1-6.5 10.8-6.5 10.8z";static PIN_HOLE="M12 8.4a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8z";static MILESTONES_OFF=Qt.outline(Qt.BOOKMARK);static MILESTONES_ON=Qt.solid(Qt.BOOKMARK);static PICTURES_OFF=Qt.outline(`${Qt.PICTURE}${Qt.PICTURE_HILLS}`);static PICTURES_ON=Qt.solid(`${Qt.PICTURE}${Qt.PICTURE_HILLS}`);static TRACE_LINE="M3 19.5l2.2-2.2 1.4 1.4L4.4 20.9zM8 14.5l2.2-2.2 1.4 1.4-2.2 2.2zM13 9.5l2.2-2.2 1.4 1.4-2.2 2.2z";static TRACE_MARK="M18.5 2.5l3.5 3.5-3.5 3.5-3.5-3.5z";static TRACES_OFF=Qt.outline(`${Qt.TRACE_LINE}${Qt.TRACE_MARK}`);static TRACES_ON=Qt.solid(`${Qt.TRACE_LINE}${Qt.TRACE_MARK}`);static MAP_OFF=Qt.outline(`${Qt.PIN}${Qt.PIN_HOLE}`);static MAP_ON=Qt.solid(`${Qt.PIN}${Qt.PIN_HOLE}`);static SHARE=Qt.outline("M14 4l7 7-7 7v-4.2C8.6 13.8 5.4 15.6 3.5 19c.6-5.6 3.4-9.6 10.5-10.8V4z");static FOLDED=Qt.svg("M15.4 7.4 14 6l-6 6 6 6 1.4-1.4L10.8 12z");static UNFOLDED=Qt.svg("M8.6 16.6 10 18l6-6-6-6-1.4 1.4 4.6 4.6z");static PLAY=Qt.svg("M7.4 5v14l11-7z");static PAUSE=Qt.svg("M6 5h4v14H6zM14 5h4v14h-4z");static VOLUME=Qt.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zm12.5 2.5A4 4 0 0 0 12.5 8.5v7A4 4 0 0 0 14.5 12zM12.5 4.2v2.1a6.5 6.5 0 0 1 0 11.4v2.1a8.6 8.6 0 0 0 0-15.6z");static MUTED=Qt.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zM15 9.8l1.4-1.4 2.6 2.6 2.6-2.6 1.4 1.4-2.6 2.6 2.6 2.6-1.4 1.4-2.6-2.6-2.6 2.6-1.4-1.4 2.6-2.6z");static ENTER_FULLSCREEN=Qt.svg("M5 5h5v2H7v3H5V5zm9 0h5v5h-2V7h-3V5zM5 14h2v3h3v2H5v-5zm12 0h2v5h-5v-2h3v-3z");static EXIT_FULLSCREEN=Qt.svg("M8 5h2v5H5V8h3V5zm6 0h2v3h3v2h-5V5zM5 14h5v5H8v-3H5v-2zm9 0h5v2h-3v3h-2v-5z")}class Hr{static KINDS=["beams","launches","reentries"];static statedKinds(t){return Object.keys(t??{}).filter(e=>Array.isArray(t[e])&&t[e].length>0)}static isEmpty(t){return Hr.statedKinds(t).length===0}static written(t){const e=Hr.statedKinds(t);if(e.length===0)return;const i={};for(const n of e)i[n]=t[n];return i}static read(t,e){const i=e,n={};for(const r of Hr.statedKinds(t))n[r]=t[r];for(const r of Hr.KINDS){const a=[...t?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=e;if(i&&Hr.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:c,...l}=i;s=Hr.isReading(l)?l:void 0}return{skyEvents:Hr.written(n),interpretation:s}}static isReading(t){return(t.bodies?.length??0)>0||t.title!==void 0||(t.smoke?.length??0)>0}}function Du(o){return[...o].sort((t,e)=>t.t-e.t)}function sm(o,t){let e;for(const i of Du(o)){if(i.t>t)break;e=i}return e}const rm=Math.PI/180,Jd=180/Math.PI;class na{constructor(t,e,i){this.kind=t,this.canvasHeightPx=e,this.fovDeg=i;const n=i*rm/2;this.focalPx=t==="equidistant"?e/2/n:e/2/Math.tan(n)}focalPx;static of(t,e,i){return new na(t.projection,e,i)}degToPx(t){const e=t*rm;return this.kind==="equidistant"?this.focalPx*e:2*this.focalPx*Math.tan(e/2)}pxToDeg(t){return this.kind==="equidistant"?t/this.focalPx*Jd:2*Math.atan(t/(2*this.focalPx))*Jd}angleDegToRadiusPx(t){const e=t*rm;return this.kind==="equidistant"?this.focalPx*e:this.focalPx*Math.tan(e)}halfWidthAngleDeg(t){return this.radiusPxToAngleDeg(this.canvasHeightPx*t/2)}radiusPxToAngleDeg(t){return this.kind==="equidistant"?t/this.focalPx*Jd:Math.atan(t/this.focalPx)*Jd}ofBounds(t){return{widthDeg:this.pxToDeg(t.width),heightDeg:this.pxToDeg(t.height)}}toBoundsSize(t){return{width:this.degToPx(t.widthDeg),height:this.degToPx(t.heightDeg)}}widthPx(t){return this.degToPx(hi.angularWidthDeg(t))}}class dn{static fovOf(t,e){return ze(t,e)?.fovDeg??Xi.fieldOfViewDeg(t.instrument)}static toAngular(t){this.eachKeyframe(t,(e,i)=>{const n=i.ofBounds(e.bounds);return e.angular?.widthDeg===n.widthDeg&&e.angular.heightDeg===n.heightDeg?e:{...e,angular:n}})}static toBounds(t){this.eachKeyframe(t,(e,i)=>this.sizedFromAngle(e,i))}static sizedFromAngle(t,e){if(!t.angular)return t;const{width:i,height:n}=e.toBoundsSize(t.angular),s={x:t.bounds.x+(t.bounds.width-i)/2,y:t.bounds.y+(t.bounds.height-n)/2,width:i,height:n};if(t.kind!=="polygon")return{...t,bounds:s};const r=t.bounds.width===0?1:i/t.bounds.width,a=t.bounds.height===0?1:n/t.bounds.height;return{...t,bounds:s,points:t.points.map(c=>({x:c.x*r,y:c.y*a}))}}static toAim(t){this.eachKeyframe(t,(e,i,n)=>{const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);if(s&&Math.abs(s.x-e.bounds.x)<dn.UNMOVED_PX&&Math.abs(s.y-e.bounds.y)<dn.UNMOVED_PX)return e;const r=this.aimFrom(t,i,n,e.bounds);return r?{...e,aim:r}:e})}static UNMOVED_PX=.01;static aimOf(t,e,i){const n=na.of(t.instrument,hi.CANVAS_HEIGHT_PX,this.fovOf(t,e));return this.aimFrom(t,n,ze(t,e),i)}static aimFrom(t,e,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(t),r=e.radiusPxToAngleDeg(n.x+n.width/2-s.x),a=e.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+a}}static toPosition(t){this.eachKeyframe(t,(e,i,n)=>this.placedByAim(t,e,i,n))}static placedByAim(t,e,i,n){const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);return s?{...e,bounds:{...e.bounds,...s}}:e}static derivable(t){const e=new Set,i=new Map,n=new Map;return t.timeline.allKeyframes.forEach((s,r)=>{const a=ze(t,s.t),c=na.of(t.instrument,hi.CANVAS_HEIGHT_PX,this.fovOf(t,s.t));for(const{sourceId:l,shape:h}of s.shapes){const u=n.get(l),d=i.get(l);if(n.set(l,h),!u||!d){i.set(l,h);continue}const f=Object.fromEntries(Object.entries(h).filter(([g,M])=>g!=="bounds"&&g!=="points"&&JSON.stringify(M)!==JSON.stringify(u[g]))),p={...d,...f},m=this.placedByAim(t,this.sizedFromAngle(p,c),c,a);dn.near(m,h)?(e.add(`${r}:${l}`),i.set(l,p)):i.set(l,h)}}),(s,r)=>e.has(`${s}:${r}`)}static SAME_PX=1e-6;static near(t,e){const i=(r,a)=>Math.abs(r-a)<=dn.SAME_PX*Math.max(1,Math.abs(a)),n=t.bounds,s=e.bounds;return!i(n.x,s.x)||!i(n.y,s.y)||!i(n.width,s.width)||!i(n.height,s.height)?!1:e.kind!=="polygon"||t.kind!=="polygon"?!0:t.points.length===e.points.length&&t.points.every((r,a)=>i(r.x,e.points[a].x)&&i(r.y,e.points[a].y))}static positionOf(t,e,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(t),a=this.shortestArc(e.azimuthDeg-s.headingDeg),c=e.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,a)-i.width/2,y:r.y-this.offAxisPx(n,c)-i.height/2}}static frameCentre(t){return{x:Xi.frameWidthPx(t.instrument,hi.CANVAS_HEIGHT_PX)/2,y:hi.CANVAS_HEIGHT_PX/2}}static shortestArc(t){return(t%360+540)%360-180}static offAxisPx(t,e){return Math.abs(e)>=dn.OFF_CANVAS_DEG?Math.sign(e)*dn.OFF_CANVAS_PX:t.angleDegToRadiusPx(e)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(t,e,i){const n=Xi.frameWidthPx(e,hi.CANVAS_HEIGHT_PX)/2,s=Xi.frameWidthPx(t.instrument,hi.CANVAS_HEIGHT_PX)/2,r=hi.CANVAS_HEIGHT_PX/2;for(const a of[...t.timeline.allKeyframes]){const c=this.fovOf(t,a.t),l=i?.get(a.t)??c,h=na.of(e,hi.CANVAS_HEIGHT_PX,l),u=na.of(t.instrument,hi.CANVAS_HEIGHT_PX,c);t.timeline.addKeyframe(a.t,a.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,m=f.y+f.height/2-r,g=Math.hypot(p,m),M=g===0?1:u.angleDegToRadiusPx(h.radiusPxToAngleDeg(g))/g,v={...f,x:s+p*M-f.width/2,y:r+m*M-f.height/2};return{...d,shape:{...d.shape,bounds:v}}}))}this.toBounds(t)}static eachKeyframe(t,e){const{timeline:i}=t;for(const n of[...i.allKeyframes]){const s=ze(t,n.t),r=this.fovOf(t,n.t),a=na.of(t.instrument,hi.CANVAS_HEIGHT_PX,r);let c=!1;const l=n.shapes.map(h=>{const u=e(h.shape,a,s);return u===h.shape?h:(c=!0,{...h,shape:u})});c&&i.addKeyframe(n.t,l)}}}class hs{static isRelative(t){return t!==void 0&&typeof t.eastM=="number"&&typeof t.northM=="number"}static isAbsolute(t){return t!==void 0&&typeof t.lat=="number"&&typeof t.lng=="number"}static referenceOf(t,e){return e.references.find(i=>(i.id??void 0)===(t.relativeTo??void 0))}static resolve(t,e){if(hs.isRelative(t)){const i=hs.referenceOf(t,e);return i?{eastM:i.eastM+t.eastM,northM:i.northM+t.northM}:void 0}return hs.isAbsolute(t)&&e.origin?hs.toLocal(t,e.origin):void 0}static restated(t,e,i){if(hs.isRelative(t)){const s=hs.referenceOf(t,i);return s?hs.relative(e.eastM-s.eastM,e.northM-s.northM,t.relativeTo):void 0}if(!i.origin)return t;const n=hs.toGeo(e,i.origin);return{lat:hs.degrees(n.lat),lng:hs.degrees(n.lng)}}static relative(t,e,i){const n={eastM:hs.metres(t),northM:hs.metres(e)};return i!==void 0&&(n.relativeTo=i),n}static toLocal(t,e){const i=ae(t.lat,t.lng,e.lat,e.lng);return{eastM:i.x,northM:-i.z}}static toGeo(t,e){return Is(t.eastM,-t.northM,e.lat,e.lng)}static metres(t){return Math.round(t*100)/100}static degrees(t){return Math.round(t*1e7)/1e7}}class qn{static restatedDecor(t){const e=qn.originOf(t);return t.decor.map(i=>{let n=i;if(i.saidPosition){const s=qn.restated(i.saidPosition,i,qn.frameAt(t,0,e,i.id));JSON.stringify(s)!==JSON.stringify(i.saidPosition)&&(n={...i,saidPosition:s},s||delete n.saidPosition)}if(i.track?.some(s=>s.saidPosition)){const s=i.track.map(r=>{if(!r.saidPosition)return r;const a=qn.restated(r.saidPosition,r,qn.frameAt(t,r.t,e,i.id));if(JSON.stringify(a)===JSON.stringify(r.saidPosition))return r;const c={...r,saidPosition:a};return a||delete c.saidPosition,c});n={...n,track:s}}return n})}static restatedObserverTrack(t){const e=t.observerTrack.toJSON(),i=qn.originOf(t);return!i||!e.keyframes.some(n=>n.pose.saidPosition)?e:{...e,keyframes:e.keyframes.map(n=>{const{pose:s}=n;if(!s.saidPosition||s.lat===void 0||s.lng===void 0)return n;const r=hs.toLocal({lat:s.lat,lng:s.lng},i),a=qn.restated(s.saidPosition,r,qn.frameAt(t,n.t,i));if(JSON.stringify(a)===JSON.stringify(s.saidPosition))return n;const c={...s,saidPosition:a};return a||delete c.saidPosition,{...n,pose:c}})}}static restatedInterpretation(t){const e=t.interpretation;if(!e?.bodies.some(n=>n.track.some(s=>s.saidPosition)))return e;const i=qn.originOf(t);return{...e,bodies:e.bodies.map(n=>n.track.some(s=>s.saidPosition)?{...n,track:n.track.map(s=>{if(!s.saidPosition)return s;const r=s.eastM!==void 0&&s.northM!==void 0?qn.restated(s.saidPosition,{eastM:s.eastM,northM:s.northM},qn.frameAt(t,s.t,i)):void 0;if(JSON.stringify(r)===JSON.stringify(s.saidPosition))return s;const a={...s,saidPosition:r};return r||delete a.saidPosition,a})}:n)}}static originOf(t){const e=t.observerTrack.getInterpolatedPoseAt(0),i=t.event.place?.[0],n=e?.lat??i?.lat,s=e?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}static frameAt(t,e,i,n){const s=[{label:"",eastM:0,northM:0},...t.decor.filter(r=>r.id!==n).map(r=>{const{eastM:a,northM:c}=oa(r,e);return{id:r.id,label:r.id,eastM:a,northM:c}})];return{origin:i,references:s}}static restated(t,e,i){return hs.restated(t,{eastM:e.eastM,northM:e.northM},i)}}class S_ extends Error{constructor(t,e,i){super(typeof e=="number"&&Number.isInteger(e)&&e>i?`This ${t} file is in version ${e} of its format; this UFO@home reads up to version ${i}. Read it with a newer UFO@home.`:`This ${t} file states ${JSON.stringify(e)} as its format version, which is not a version.`),this.format=t,this.found=e,this.supported=i,this.name="FormatVersionError"}said(t){return t.replace("{found}",typeof this.found=="number"?String(this.found):JSON.stringify(this.found)).replace("{supported}",String(this.supported))}}class Gl{static CURRENT={sighting:4,case:1,interview:1};static SCHEMA_BASE="https://ufoathome.org/schema";static schemaUrl(t,e=Gl.CURRENT[t]){return`${Gl.SCHEMA_BASE}/${e}/${t}.schema.json`}static of(t){if(typeof t!="object"||t===null)return 1;const e=t.version;return e===void 0?1:typeof e=="object"&&e!==null&&"value"in e?e.value:e}static check(t,e){const i=Gl.of(t),n=Gl.CURRENT[e];if(typeof i!="number"||!Number.isInteger(i)||i<1||i>n)throw new S_(e,i,n);return t}}class ai{constructor(t,e,i){this.params=t,this.from=e,this.origin=t.path[0],this.cos0=Math.cos(t.path[0].lat*Math.PI/180),this.points=t.path.map(r=>this.local(r)),this.cumulative=[0];for(let r=1;r<this.points.length;r++){const a=this.points[r-1],c=this.points[r];this.cumulative.push(this.cumulative[r-1]+Math.hypot(c.e-a.e,c.n-a.n))}this.distances=[];let n=0;for(let r=e;r<=i+ai.BEYOND_MS;r+=ai.STEP_MS)this.distances.push(n),n+=this.speedAt(r)*ai.STEP_MS/1e3;this.shift=this.project(this.local(t.through))-this.distanceAt(t.through.t);const s=[];for(let r=e;r<=i;r+=ai.SAMPLE_MS)s.push({t:r,place:this.placeAt(r)});this.sampleOrigin=s[0].place,this.sampleCos=Math.cos(this.sampleOrigin.lat*Math.PI/180),this.samples=s.map(({t:r,place:a})=>({t:r,e:(a.lng-this.sampleOrigin.lng)*Math.PI/180*ai.R*this.sampleCos,n:(a.lat-this.sampleOrigin.lat)*Math.PI/180*ai.R}))}static R=63710088e-1;static STEP_MS=100;static SAMPLE_MS=2e3;static BEYOND_MS=8e4;origin;cos0;points;cumulative;distances;shift;samples;sampleOrigin;sampleCos;get start(){return this.sampleOrigin}stateAt(t){const e=this.samples,i=e.length-2;let n=0;for(;n<i&&e[n+1].t<t;)n++;const s=e[n],r=e[n+1],a=(t-s.t)/(r.t-s.t),c=p=>[n>0?p[n-1]:2*p[n]-p[n+1],p[n],p[n+1],n+2<p.length?p[n+2]:2*p[n+1]-p[n]],l=e.map(p=>p.e),h=e.map(p=>p.n),u=ai.catmull(c(l),a),d=ai.catmull(c(h),a),f=(Math.atan2(ai.slope(c(l),a),ai.slope(c(h),a))*180/Math.PI%360+360)%360;return{eastM:u,northM:d,roadDeg:f,lat:this.sampleOrigin.lat+d/ai.R*180/Math.PI,lng:this.sampleOrigin.lng+u/(ai.R*this.sampleCos)*180/Math.PI}}bearingAt(t,e){const i=this.local(this.placeAt(t)),n=this.local(e);return(Math.atan2(n.e-i.e,n.n-i.n)*180/Math.PI%360+360)%360}get sampleTimes(){return this.samples.map(t=>t.t)}placeAt(t){const e=this.along(this.distanceAt(t)+this.shift);return{lat:this.origin.lat+e.n/ai.R*180/Math.PI,lng:this.origin.lng+e.e/(ai.R*this.cos0)*180/Math.PI}}distanceAt(t){const e=Math.max(0,Math.min(this.distances.length-1,Math.round((t-this.from)/ai.STEP_MS)));return this.distances[e]}speedAt(t){const e=this.params.speedDivisors?ai.linear(this.params.speedDivisors.map(({t:i,divisor:n,step:s})=>({t:i,value:n,step:s})),t):1;return ai.linear(this.params.speeds.map(({t:i,kmh:n,step:s})=>({t:i,value:n,step:s})),t)/3.6/e}local(t){return{e:(t.lng-this.origin.lng)*Math.PI/180*ai.R*this.cos0,n:(t.lat-this.origin.lat)*Math.PI/180*ai.R}}along(t){const e=this.points;let i=0;for(;i<e.length-2&&this.cumulative[i+1]<t;)i++;const n=e[i],s=e[i+1],r=(t-this.cumulative[i])/(this.cumulative[i+1]-this.cumulative[i]);return{e:n.e+(s.e-n.e)*r,n:n.n+(s.n-n.n)*r}}project(t){let e=1/0,i=0;for(let n=0;n<this.points.length-1;n++){const s=this.points[n],r=this.points[n+1],a=r.e-s.e,c=r.n-s.n,l=Math.max(0,Math.min(1,((t.e-s.e)*a+(t.n-s.n)*c)/(a*a+c*c))),h=Math.hypot(s.e+a*l-t.e,s.n+c*l-t.n);h<e&&(e=h,i=this.cumulative[n]+l*Math.hypot(a,c))}return i}static linear(t,e){if(e<=t[0].t)return t[0].value;for(let i=0;i<t.length-1;i++){const n=t[i],s=t[i+1];if(s.step&&e<s.t)return n.value;if(e<=s.t)return n.value+(s.value-n.value)*(e-n.t)/(s.t-n.t)}return t[t.length-1].value}static catmull([t,e,i,n],s){return .5*(2*e+(i-t)*s+(2*t-5*e+4*i-n)*s*s+(3*e-t-3*i+n)*s**3)}static slope([t,e,i,n],s){return .5*(i-t+2*(2*t-5*e+4*i-n)*s+3*(3*e-t-3*i+n)*s*s)}}class je{constructor(t,e,i,n,s,r){this.drive=t,this.eye=e,this.lookAhead=i,this.lean=n,this.watch=s,this.times=t.sampleTimes;const a=i.pitchShare??1;this.aimed=[];for(const c of this.times){const l=t.bearingAt(c,i.target),h=this.aimed[this.aimed.length-1];this.aimed.push(h===void 0?l:h+je.signed(l-h))}this.pitched=this.times.map(c=>r(c)*a)}static STEP_MS=250;static DENSE_MS=50;static SETTLED_MS=700;static TURN_S=.4;static TURN_S_PER_DEG=.5/150;static ROAD_PITCH_DEG=-1;static SHOULDER={x:-.08,y:0,z:-.07};static TWIST_FROM_DEG=60;aimed;pitched;times;poses(t,e){const i=[];for(let u=t;u<e;u+=je.STEP_MS)i.push(u);i.push(e);const n=new Map(i.map(u=>{const d=this.sample(u);return[u,je.signed(d.headingDeg-d.roadDeg)]})),s=u=>n.get(i.reduce((d,f)=>Math.abs(f-u)<Math.abs(d-u)?f:d)),r=this.schedule(s,e),a=this.watch?.t,c=r.map(([u,d],f)=>{if(f===0)return 0;if(u===a&&this.lean)return this.lean.params.turnS;const p=this.sample(u);return je.turnS(this.target(r[f-1][1],p),this.target(d,p))}),l=new Set(i),h=r.map(([u],d)=>[u,c[d]]);this.lean&&h.push([this.lean.t,this.lean.params.turnS],[this.lean.t+this.lean.params.holdS*1e3,this.lean.params.turnS]);for(const[u,d]of h){const f=Math.round(u+d*1e3+je.SETTLED_MS)+je.DENSE_MS;for(let p=Math.round(u);p<f;p+=je.DENSE_MS)p>=t&&p<=e&&l.add(p)}return[...l].sort((u,d)=>u-d).map(u=>{const d=this.sample(u),[f,p]=this.gaze(r,c,d),m=this.drive.stateAt(u);return{t:u,headingDeg:f,pitchDeg:p,eye:this.eyeAt(u,je.signed(f-d.roadDeg)),roadDeg:m.roadDeg,lat:m.lat,lng:m.lng}})}schedule(t,e){const i=[],n=this.lookAhead,s=this.watch?.t??e;let r=0;for(;r<s;){if(Math.abs(t(r))<=n.glanceBeyondDeg){(i.length===0||i[i.length-1][1]!=="watch")&&i.push([r,"watch"]),r+=je.STEP_MS;continue}if(i.push([r,"glance"]),r+=n.glanceS*1e3,r>=s)break;i.push([r,"road"]),r+=n.roadS*1e3}if(!this.watch)return i;const a=this.watch.params;r=s,i.push([r,"mirror"]),r+=a.firstS*1e3;let c=0;for(;r<e;){const l=r<a.glancesUntil&&c%2===0?"glance":"road";i.push([r,l]),r+=(l==="glance"?a.glanceS:a.roadS)*1e3,i.push([r,"mirror"]),r+=a.mirrorS*1e3,c++}return i}sample(t){const e=this.times,i=e.length-2;let n=0;for(;n<i&&e[n+1]<t;)n++;const s=(t-e[n])/(e[n+1]-e[n]),r=a=>[n>0?a[n-1]:2*a[n]-a[n+1],a[n],a[n+1],n+2<a.length?a[n+2]:2*a[n+1]-a[n]];return{t,roadDeg:this.drive.stateAt(t).roadDeg,headingDeg:(ai.catmull(r(this.aimed),s)%360+360)%360,pitchDeg:ai.catmull(r(this.pitched),s),eye:this.eyeAt(t,0)}}target(t,e){const{roadDeg:i,headingDeg:n,pitchDeg:s,eye:r}=e;if(t==="glance")return[n,s];if(t==="watch"){const u=je.signed(n-i),d=this.lookAhead.keepDeg,f=u-d*Math.tanh(u/d),p=u?f/u:0;return[je.normalized(i+f),je.ROAD_PITCH_DEG+(s-je.ROAD_PITCH_DEG)*p]}if(t==="road"||!this.watch)return[i,je.ROAD_PITCH_DEG];const a=this.watch.params.mirror,c={x:a.x-r.x,y:a.y-r.y,z:a.z-r.z},l=Math.atan2(-c.x,-c.z)*180/Math.PI,h=Math.atan2(c.y,Math.hypot(c.x,c.z))*180/Math.PI;return[je.normalized(i-l),h]}gaze(t,e,i,n){const s=i.t;let r=n??0;if(n===void 0&&s>=t[0][0])for(let g=0;g<t.length;g++)t[g][0]<=s&&(r=g);const[a,c]=this.target(t[r][1],i);if(r===0)return[a,c];const l=e[r]*1e3,h=s-t[r][0];if(h>l+je.SETTLED_MS)return[a,c];const[u,d]=this.gaze(t,e,i,r-1);if(h<l){const g=h/l,M=-2*g**3+3*g*g+(g**3-g*g)*Mn.ARRIVAL;return[je.normalized(u+je.signed(a-u)*M),d+(c-d)*M]}const f=je.signed(a-u),p=h-l,m=Mn.ARRIVAL/l*p*Math.exp(-p/Math.min(Mn.SETTLE_MS,.4*l));return[je.normalized(a+f*m),c+(c-d)*m]}leanAt(t){if(!this.lean)return 0;const{holdS:e,turnS:i}=this.lean.params,n=(t-this.lean.t)/1e3;return n<0||n>e+i?0:je.smooth(Math.min(1,n/i,(e+i-n)/i))}eyeAt(t,e){const i=this.leanAt(t),n=this.lean?.params.offsetM??{x:0,y:0,z:0},s=je.smooth((Math.abs(e)-je.TWIST_FROM_DEG)/(180-je.TWIST_FROM_DEG)),r=je.SHOULDER;return{x:this.eye.x+n.x*i+r.x*s,y:this.eye.y+n.y*i+r.y*s,z:this.eye.z+n.z*i+r.z*s}}static turnS(t,e){return je.TURN_S+je.TURN_S_PER_DEG*Math.hypot(je.signed(e[0]-t[0]),e[1]-t[1])}static smooth(t){const e=Math.min(1,Math.max(0,t));return e*e*e*(10-15*e+6*e*e)}static signed(t){return((t+540)%360+360)%360-180}static normalized(t){return(t%360+360)%360}}const am=Math.PI/180;class Bt{constructor(t,e,i){this.body=t,this.ground=e,this.eyeAt=i;const n=[...t.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)Bt.collect(this.motionKeys,s.t,s.motions),Bt.collect(this.turnKeys,s.t,s.turns),Bt.collect(this.lightKeys,s.t,s.lights)}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,luminanceCdM2:0,transparency:0,haloScale:1};keys;motionKeys=new Map;turnKeys=new Map;lightKeys=new Map;static collect(t,e,i){for(const[n,s]of Object.entries(i??{})){const r=t.get(n)??[];r.push({t:e,value:s}),t.set(n,r)}}motionsAt(t){return Bt.channelsAt(this.motionKeys,t,0)}lightsAt(t){return this.lightKeys.size>0?Bt.channelsAt(this.lightKeys,t,void 0):void 0}static channelsAt(t,e,i){const n={};for(const[s,r]of t){let a=r.length-1;for(;a>=0&&r[a].t>e;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const c=r[a],l=r[Math.min(a+1,r.length-1)],h=l===c||l.t===c.t?0:Math.min(1,(e-c.t)/(l.t-c.t));n[s]=Bt.lerp(c.value,l.value,h)}return n}static eyeOf(t,e,i){const n=ze(t,0),s=ze(t,e),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ae(s.lat,s.lng,n.lat,n.lng):void 0,c=a?a.x:0,l=a?-a.z:0;return{eastM:c,northM:l,upM:i.heightAt(c,l)+Bt.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(t,e,i,n){const s=Bt.directionOf(e,i),r=l=>t.upM+s.upM*l-n.heightAt(t.eastM+s.eastM*l,t.northM+s.northM*l);let a=0,c=0;for(;c<Bt.MAX_RANGE_M;){if(c=a+Math.max(.5,a*.01),r(c)<=0){for(let l=0;l<30;l++){const h=(a+c)/2;r(h)<=0?c=h:a=h}return c}a=c}}static directionOf(t,e){const i=t*am,n=e*am;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(t){const e=this.keys;if(e.length===0||t<e[0].t)return;let i=0,n=e.length-1;for(;i<n;){const m=i+n+1>>1;e[m].t>t?n=m-1:i=m}const s=i,r=e[s];if(!r.present)return;const a=e[Math.min(s+1,e.length-1)],c=a===r||a.t===r.t?0:Math.min(1,(t-r.t)/(a.t-r.t)),l=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(t):void 0,h=l?l.eastM+Bt.lerp(r.carried.eastM,a.carried.eastM,c):Bt.lerp(r.eastM,a.eastM,c),u=l?l.northM+Bt.lerp(r.carried.northM,a.carried.northM,c):Bt.lerp(r.northM,a.northM,c),d={widthM:Bt.lerp(r.sizeM.widthM,a.sizeM.widthM,c),lengthM:Bt.lerp(r.sizeM.lengthM,a.sizeM.lengthM,c),heightM:Bt.lerp(r.sizeM.heightM,a.sizeM.heightM,c)},f={headingDeg:Bt.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,c),pitchDeg:Bt.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,c),rollDeg:Bt.lerp(r.attitude.rollDeg,a.attitude.rollDeg,c)};let p;if(l)p=l.upM+Bt.lerp(r.carried.upM,a.carried.upM,c);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const m=Bt.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,c);p=this.groundUnderFootprint(h,u,d,f.headingDeg)+m+d.heightM/2}else p=Bt.lerp(this.centreUpOf(r),this.centreUpOf(a),c);return{id:this.body.id,model:this.body.model,modelParameters:this.body.modelParameters,flicker:this.body.flicker,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:h,northM:u,upM:p,sizeM:d,attitude:f,appearance:{color:Bt.lerpColor(r.appearance.color,a.appearance.color,c),albedo:Bt.lerp(r.appearance.albedo,a.appearance.albedo,c),luminanceCdM2:Bt.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,c),transparency:Bt.lerp(r.appearance.transparency,a.appearance.transparency,c),haloScale:Bt.lerp(r.appearance.haloScale,a.appearance.haloScale,c)},flame:Bt.flameBetween(r.flame,a.flame,c),motions:this.motionsAt(t),...this.turnKeys.size>0?{turns:Bt.channelsAt(this.turnKeys,t,0)}:{},lights:this.lightsAt(t),throwsFlame:this.body.track.some(m=>m.flame!==void 0&&m.flame.luminanceCdM2>0)}}static flameBetween(t,e,i){if(!t||t.luminanceCdM2<=0)return i>=1&&e&&e.luminanceCdM2>0?e:void 0;const n=t,s=e??t,r={...i<1?n:s,lengthM:Bt.lerp(n.lengthM,s.lengthM,i),widthM:Bt.lerp(n.widthM,s.widthM,i),luminanceCdM2:Bt.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(t){if(!("upM"in t.vertical))return this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.vertical.aboveGroundM+t.sizeM.heightM/2;const e=t.vertical.fromGround;if(!e)return t.vertical.upM;const i=t.vertical.upM+this.ground.heightAt(e.eastM,e.northM);return Math.max(i,this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.sizeM.heightM/2)}groundUnderFootprint(t,e,i,n){const s=n*am,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let c=this.ground.heightAt(t,e);for(const[l,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const u=l*i.widthM/2,d=h*i.lengthM/2;c=Math.max(c,this.ground.heightAt(t+r.eastM*u+a.eastM*d,e+r.northM*u+a.northM*d))}return c}place(t,e){const i=[];let n;for(const s of t){const r=s.sizeM??n?.sizeM??Bt.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},c={color:s.appearance?.color??n?.appearance.color??Bt.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??Bt.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??Bt.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??Bt.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??Bt.DEFAULT_APPEARANCE.haloScale},l=this.positionOf(s,r,e)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!l)continue;const h=s.flame??n?.flame,u=s.present??n?.present??!0;if(n={t:s.t,...l,sizeM:r,attitude:a,appearance:c,flame:h,present:u},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const d=Bt.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:d.eastM*s.distanceM,northM:d.northM*s.distanceM,upM:d.upM*s.distanceM}}i.push(n)}return i}verticalOf(t,e){if(t.onGround)return{aboveGroundM:0};if(t.altitudeAboveGroundM!==void 0)return{aboveGroundM:t.altitudeAboveGroundM};if(t.altitudeM!==void 0)return{upM:t.altitudeM+e.heightM/2,fromGround:this.body.altitudeFrom}}positionOf(t,e,i){if(t.eastM!==void 0&&t.northM!==void 0)return{eastM:t.eastM,northM:t.northM,vertical:this.verticalOf(t,e)??{aboveGroundM:0}};if(t.azimuthDeg===void 0||t.altitudeDeg===void 0)return;const n=i(t.t);if(!n)return;const s=t.distanceM??(t.onGround?Bt.lineOfSightMeetsGround(n,t.azimuthDeg,t.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=Bt.directionOf(t.azimuthDeg,t.altitudeDeg),a=n.eastM+r.eastM*s,c=n.northM+r.northM*s;return{eastM:a,northM:c,vertical:this.verticalOf(t,e)??{upM:n.upM+r.upM*s}}}static lerp(t,e,i){return t+(e-t)*i}static lerpColor(t,e,i){const n=Bt.rgbOf(t),s=Bt.rgbOf(e);return!n||!s?i<1?t:e:"#"+n.map((r,a)=>Math.round(Bt.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(!e)return;const i=e[1].length===3?e[1].replace(/./g,"$&$&"):e[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(t,e,i){const n=((e-t)%360+540)%360-180;return((t+n*i)%360+360)%360}}class As{static ANONYMOUS_OBSERVER="observer";static observerId(t){return t.observer?.id??As.ANONYMOUS_OBSERVER}static shapeIds(t){const e=new Set(t.timeline.sourceIds);for(const i of t.events??[])if(i.eventType==="appearance")for(const n of i.params?.parts??[])e.add(n.sourceId);return[...e]}static ids(t){const e=new Map,i=(n,s)=>{n!==void 0&&e.set(n,[...e.get(n)??[],s])};i(As.observerId(t),"observer");for(const n of As.shapeIds(t))i(n,"shape");for(const n of t.timeline.allGroups)i(n.id,"group");for(const n of t.interpretation?.bodies??[])i(n.id,"body");for(const n of t.decor)i(n.id,"decor");return e}static kindOf(t,e){if(e===void 0)return;const i=As.ids(t).get(e);return i?.length===1?i[0]:void 0}static partOf(t){const e=t?.indexOf("/")??-1;if(!(t===void 0||e<=0||e===t.length-1))return{element:t.slice(0,e),part:t.slice(e+1)}}static hasPart(t,e,i){if(e==="body")return!0;if(e!=="decor")return!1;const n=t.decor.find(s=>s.id===i.element);return!!(n?.lights?.some(s=>s.id===i.part)||n?.groups?.some(s=>s.id===i.part))}static isObserver(t,e){return e.who===As.observerId(t)}static isPhenomenon(t,e){return e.who===void 0?!1:t.timeline.groupOf(e.who)!==void 0||As.shapeIds(t).includes(e.who)}static within(t,e){const i=new Set([e]),n=s=>{for(const r of t.timeline.groupOf(s)?.members??[])i.has(r)||(i.add(r),n(r))};return n(e),i}static renamed(t,e,i){if(e!==i)for(const n of t.events??[])n.who===e&&(n.who=i)}static issues(t){const e=[],i=As.ids(t);for(const[n,s]of i)s.length>1&&e.push({kind:"duplicate-id",id:n,path:s.join(", ")});return(t.events??[]).forEach((n,s)=>{const r=As.partOf(n.who);r&&i.get(r.element)?.length===1&&As.hasPart(t,i.get(r.element)[0],r)||(n.who===void 0||!i.has(n.who))&&e.push({kind:"unknown-who",id:n.who??"",path:`events.${s}.who`})}),e}}class xe{constructor(t,e,i){this.travel=t;const n=t.params,s=t.until??i;let r=xe.unit(n.from),a=xe.towards(r,xe.unit(n.towards));const c=e.map(h=>{const u=h.params,d=u.side==="left"?1:-1;return{from:h.t,to:h.until??h.t,radians:u.byDeg*Math.PI/180*(u.seenFrom==="craft"?-d:d)}}),l=xe.STEP_MS;for(let h=t.t;h<=s;h+=l){this.directions.push(xe.direction(r));for(const f of c){const p=f.to-f.from;if(p<=0)continue;const m=f.radians*(xe.smooth((h+l-f.from)/p)-xe.smooth((h-f.from)/p));m&&(a=xe.add(xe.scale(a,Math.cos(m)),xe.scale(xe.cross(a,r),Math.sin(m))))}const u=xe.speedAt(n.speeds,h)*l/1e3*Math.PI/180,d=xe.add(xe.scale(r,Math.cos(u)),xe.scale(a,Math.sin(u)));a=xe.add(xe.scale(a,Math.cos(u)),xe.scale(r,-Math.sin(u))),r=d}}static STEP_MS=5;directions=[];at(t){const e=Math.round((t-this.travel.t)/xe.STEP_MS);return this.directions[Math.max(0,Math.min(this.directions.length-1,e))]}sizeAt(t){const e=this.travel.params;return e.sizeBy!=="altitude"?e.sizeDeg:e.sizeDeg*Math.max(.1,Math.sin(Math.max(this.at(t).altitudeDeg,1)*Math.PI/180))}static speedAt(t,e){if(t.length===0)return 0;if(e<=t[0].t)return t[0].degPerS;for(let i=1;i<t.length;i++){const n=t[i-1],s=t[i];if(s.step&&e<s.t)return n.degPerS;if(e<s.t)return n.degPerS+(s.degPerS-n.degPerS)*xe.smooth((e-n.t)/(s.t-n.t))}return t[t.length-1].degPerS}static smooth(t){const e=Math.max(0,Math.min(1,t));return e*e*(3-2*e)}static unit(t){const e=t.azimuthDeg*Math.PI/180,i=t.altitudeDeg*Math.PI/180;return[Math.cos(i)*Math.sin(e),Math.cos(i)*Math.cos(e),Math.sin(i)]}static direction(t){return{azimuthDeg:(Math.atan2(t[0],t[1])*180/Math.PI%360+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,t[2])))*180/Math.PI}}static towards(t,e){const i=xe.add(e,xe.scale(t,-xe.dot(t,e))),n=Math.hypot(...i)||1;return xe.scale(i,1/n)}static toScreen(t,e,i){const[n,s,r]=xe.basis(e,i),a=xe.unit(t),c=xe.dot(a,n);return[xe.dot(a,s)/c,xe.dot(a,r)/c]}static fromScreen(t,e,i,n){const[s,r,a]=xe.basis(i,n),c=[s[0]+t*r[0]+e*a[0],s[1]+t*r[1]+e*a[1],s[2]+t*r[2]+e*a[2]],l=Math.hypot(...c);return xe.direction([c[0]/l,c[1]/l,c[2]/l])}static basis(t,e){const i=t*Math.PI/180,n=e*Math.PI/180;return[[Math.cos(n)*Math.sin(i),Math.cos(n)*Math.cos(i),Math.sin(n)],[Math.cos(i),-Math.sin(i),0],[-Math.sin(n)*Math.sin(i),-Math.sin(n)*Math.cos(i),Math.cos(n)]]}static dot(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}static cross(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}static add(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}static scale(t,e){return[t[0]*e,t[1]*e,t[2]*e]}}class yo{constructor(t,e){this.sighting=t,this.events=e}static FOV_DEG=60;keyframes(){const t=this.events.filter(c=>c.eventType==="look").sort((c,l)=>c.t-l.t),e=this.events.filter(c=>c.eventType==="walk").sort((c,l)=>c.t-l.t),i=this.events.filter(c=>c.eventType==="follow").sort((c,l)=>c.t-l.t);if(t.length===0&&e.length===0)return[];const n=new Set([0]);for(const c of[...t,...e,...i])n.add(c.t),c.until!==void 0&&n.add(c.until);const s=c=>{let l;for(const h of e){const u=h.params;if(c<=h.t)return l??u.from;if(h.until===void 0||c>=h.until)l=u.to;else return}return l??this.sighting.event.place?.[0]},r=c=>([...t].reverse().find(h=>h.t<=c)??t[0])?.params??{headingDeg:0,pitchDeg:0},a=[...n].sort((c,l)=>c-l).flatMap(c=>{const l=s(c);if(!l)return[];const h=r(c);return[{t:c,pose:yo.pose(l,h.headingDeg,h.pitchDeg,h.fovDeg)}]});for(const c of a)this.sighting.observerTrack.addKeyframe(c.t,c.pose);for(const c of i)this.follow(c,r(c.t));return[...this.sighting.observerTrack.allKeyframes]}follow(t,e){const i=t.params;if(this.followSky(t,e))return;const n=this.sighting.interpretation?.bodies.find(h=>h.id===i.target);if(!n)return;const s={heightAt:()=>0},r=h=>Bt.eyeOf(this.sighting,h,s),a=new Bt(n,s,r),c=t.until??1/0;let l=e;for(const h of n.track){if(h.t<=t.t||h.t>=c)continue;const u=a.at(h.t),d=r(h.t),f=this.sighting.observerTrack.getInterpolatedPoseAt(h.t);if(!u||!d||!f)continue;const p=u.eastM-d.eastM,m=u.northM-d.northM,g=u.upM-d.upM;l={headingDeg:(Math.atan2(p,m)*180/Math.PI%360+360)%360,pitchDeg:Math.atan2(g,Math.hypot(p,m))*180/Math.PI},this.sighting.observerTrack.addKeyframe(h.t,{...f,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}if(Number.isFinite(c)){const h=this.sighting.observerTrack.getInterpolatedPoseAt(c);h&&this.sighting.observerTrack.addKeyframe(c,{...h,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}}static FOLLOW_SKY_MS=25;static CATCH_UP_MS=900;static OVERHEAD_DEG=78;static HIGHEST_PITCH_DEG=88;followSky(t,e){const i=t.params,n=As.within(this.sighting,i.target),s=this.sighting.events??[],r=s.find(M=>M.eventType==="travel"&&M.who!==void 0&&n.has(M.who));if(!r)return!1;const a=this.sighting.event.durationSeconds!==void 0?this.sighting.event.durationSeconds*1e3:r.until??t.t,c=new xe(r,s.filter(M=>M.eventType==="turn"&&M.who!==void 0&&n.has(M.who)),a),l=t.until??a,h=(i.lagS??0)*1e3,u=(i.reactionS??0)*1e3,d=[],f=this.sighting.sampleMs??yo.FOLLOW_SKY_MS;for(let M=t.t;M<=l;M+=f)d.push(M);const p=d.map(M=>c.at(Math.max(r.t,M-h))),m=p.map(M=>M.azimuthDeg),g=p.flatMap((M,v)=>M.altitudeDeg>yo.OVERHEAD_DEG?[v]:[]);if(g.length>0){const M=Math.max(0,g[0]-1),v=Math.min(d.length-1,g[g.length-1]+1),x=m[M],y=(m[v]-x+540)%360-180;for(let w=M;w<=v;w++)m[w]=((x+y*xe.smooth((w-M)/(v-M)))%360+360)%360}return d.forEach((M,v)=>{const x=xe.smooth((M-t.t-u)/yo.CATCH_UP_MS),y=(m[v]-e.headingDeg+540)%360-180,w=Math.min(p[v].altitudeDeg,yo.HIGHEST_PITCH_DEG),b=this.sighting.observerTrack.getInterpolatedPoseAt(M)??this.sighting.observerTrack.getLatestPoseAt(M);if(!b)return;const E=S=>Math.round(S*100)/100;this.sighting.observerTrack.addKeyframe(M,{...b,headingDeg:E(((e.headingDeg+y*x)%360+360)%360),pitchDeg:E(e.pitchDeg+(w-e.pitchDeg)*x)})}),!0}static pose(t,e,i,n=yo.FOV_DEG){return{lat:t.lat,lng:t.lng,elevationM:0,headingDeg:e,pitchDeg:i,fovDeg:n}}}class ko{constructor(t,e,i,n){this.body=t,this.events=e,this.endMs=i,this.sampleMs=n}static SAMPLE_MS=250;track(){const t=new Map,e=l=>{const h=t.get(l.t);t.set(l.t,h?{...h,...l,motions:{...h.motions,...l.motions},...h.turns||l.turns?{turns:{...h.turns,...l.turns}}:{},...h.lights||l.lights?{lights:{...h.lights,...l.lights}}:{}}:l)};for(const l of this.body.track)e({...l});const i=[...this.events].sort((l,h)=>l.t-h.t),n=new Map,s=new Map,r=new Map;let a=0;for(const l of this.body.track){for(const[h,u]of Object.entries(l.motions??{}))n.set(h,u);for(const[h,u]of Object.entries(l.turns??{}))s.set(h,u);for(const[h,u]of Object.entries(l.lights??{}))r.set(h,u);l.attitude?.headingDeg!==void 0&&(a=l.attitude.headingDeg)}let c=this.startPlace();for(const l of i){const h=ko.partOf(l.who,this.body.id);if(h!==void 0&&(l.eventType==="light"||l.eventType==="blink")){for(const u of this.leavesOf(h))this.switchLight(u,l,r,e,d=>t.get(d)?.lights?.[u]);continue}if(h!==void 0){if(l.eventType!=="spin"&&l.eventType!=="turn")continue;const u=s.get(h)??0,d=l.until??l.t,f=l.eventType==="spin"?u+360*l.params.turnsPerS*(d-l.t)/1e3:l.params.headingDeg;e({t:l.t,turns:{[h]:u}}),e({t:d,turns:{[h]:f}}),s.set(h,f);continue}if((l.eventType==="motion"||l.eventType==="spin")&&l.params?.motion){const u=l.params,d=u.motion,f=n.get(d)??0,p=l.until??l.t,m=l.eventType==="motion"?u.to:f+u.turnsPerS*(p-l.t)/1e3;e({t:l.t,motions:{[d]:f}}),e({t:p,motions:{[d]:m}}),n.set(d,m)}else if(l.eventType==="rise"&&c){const u=l.params,d=l.until??l.t,f=u.angleDeg*Math.PI/180,p=(u.headingDeg??0)*Math.PI/180,m=c,g=M=>{const v=u.stops===!1?M*M:M*M*M*(10-15*M+6*M*M),x=u.distanceM*v;return{eastM:m.eastM+x*Math.sin(f)*Math.sin(p),northM:m.northM+x*Math.sin(f)*Math.cos(p),aboveGroundM:m.aboveGroundM+x*Math.cos(f)}};for(let M=l.t;M<d;M+=this.sampleMs??ko.SAMPLE_MS)e(ko.key(M,g((M-l.t)/(d-l.t))));c=g(1),e(ko.key(d,c))}else if(l.eventType==="turn"){const u=l.params;e({t:l.t,attitude:{headingDeg:a}}),e({t:l.until??l.t,attitude:{headingDeg:u.headingDeg}}),a=u.headingDeg}else l.eventType==="vanish"&&e({t:l.t,present:!1})}return[...t.values()].sort((l,h)=>l.t-h.t)}static ride(t,e,i){const n=e.params,s=e.until??1/0,r=new Map(t.track.map(a=>[a.t,{...a}]));for(const a of i.track){if(a.t<e.t||a.t>s||(a.present===!1&&r.set(a.t,{...r.get(a.t),t:a.t,present:!1}),a.eastM===void 0||a.northM===void 0))continue;const c=(a.onGround?0:a.altitudeAboveGroundM??0)+n.aboveM;r.set(a.t,{...r.get(a.t),t:a.t,eastM:a.eastM,northM:a.northM,altitudeAboveGroundM:c})}return[...r.values()].sort((a,c)=>a.t-c.t)}switchLight(t,e,i,n,s){const r=i.get(t)??0,a=e.eventType==="light"?e.until:e.until??this.endMs,c=(l,h)=>n({t:l,lights:{[t]:h}});if(e.t>0&&s(e.t-1)===void 0&&c(e.t-1,r),e.eventType==="light"){const l=e.params.cdM2;if(c(e.t,l),a===void 0){i.set(t,l);return}c(a-1,l)}else{const l=e.params;if(a===void 0)return;const h=l.cdM2??r;let u=e.t,d=!0;for(;u<a;){const f=Math.min(Math.round(u+1e3*(d?l.onS:l.offS)),a);if(f<=u)break;c(u,d?h:0),c(f-1,d?h:0),u=f,d=!d}}c(a,r),i.set(t,r)}leavesOf(t,e=new Set){const i=this.body.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}startPlace(){const t=this.body.track.find(e=>e.eastM!==void 0&&e.northM!==void 0);return t&&{eastM:t.eastM,northM:t.northM,aboveGroundM:t.onGround?0:t.altitudeAboveGroundM??0}}static key(t,e){return e.aboveGroundM<=0?{t,eastM:e.eastM,northM:e.northM,onGround:!0}:{t,eastM:e.eastM,northM:e.northM,altitudeAboveGroundM:e.aboveGroundM}}}class wd{constructor(t,e,i){this.object=t,this.events=e,this.endMs=i}lights(){const t=new Map,e=[...this.events].sort((i,n)=>i.t-n.t);for(const i of e){const n=wd.partOf(i.who,this.object.id);if(!(n===void 0||i.eventType!=="light"&&i.eventType!=="blink"))for(const s of this.leavesOf(n)){const r=this.object.lights?.find(a=>a.id===s);r&&t.set(s,this.switched(r,t.get(s)??[],i))}}return(this.object.lights??[]).map(i=>t.has(i.id)?{...i,keyframes:t.get(i.id)}:i)}switched(t,e,i){const n=wd.stateAt(t,e,i.t),s=i.eventType==="light"?i.until:i.until??this.endMs,r=[];if(i.eventType==="light")r.push({t:i.t,intensity:i.params.intensity,pattern:n.pattern});else{const c=i.params,l=c.onS+c.offS;if(s===void 0||l<=0)return e;const h=l*1e3,u=(-i.t/h%1+1)%1,d={kind:"flash",perMinute:60/l,dutyCycle:c.onS/l,...u?{phase:u}:{}},f=c.intensity??(n.intensity>0?n.intensity:t.intensity??1);r.push({t:i.t,intensity:f,pattern:d})}s!==void 0&&r.push({t:s,intensity:n.intensity,pattern:n.pattern});const a=new Set(r.map(c=>c.t));return[...e.filter(c=>!a.has(c.t)),...r].sort((c,l)=>c.t-l.t)}static stateAt(t,e,i){const n=e.filter(s=>s.t<=i).at(-1);return{intensity:n?.intensity??t.intensity??1,pattern:n?.pattern??t.pattern}}leavesOf(t,e=new Set){const i=this.object.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}}class dh{static observer(t){const e=t.allKeyframes,i=e.map(s=>dh.said(s.pose)),n=e.filter((s,r)=>r>0&&r<e.length-1&&i[r]===i[r-1]&&i[r]===i[r+1]);for(const s of n)t.removeKeyframeAt(s.t)}static said(t){return JSON.stringify(t,(e,i)=>typeof i=="number"?Math.round(i*1e10)/1e10:i)}static timeline(t){const e=new Map;for(const i of t.allKeyframes)for(const n of i.shapes){const s=e.get(n.sourceId)??[];s.push({t:i.t,said:dh.said(n.shape)}),e.set(n.sourceId,s)}for(const[i,n]of e){const s=n.filter((r,a)=>a>0&&a<n.length-1&&r.said===n[a-1].said&&r.said===n[a+1].said);for(const r of s)t.removeShapeAt(r.t,i)}}}class U0{constructor(t,e){this.end=e;const i=[...t].sort((n,s)=>n.t-s.t);this.rolls=i.filter(n=>n.eventType==="roll"),this.vibrations=i.filter(n=>n.eventType==="vibrate"),this.spirals=i.filter(n=>n.eventType==="spiral")}static SPIRAL_OPENS=4;static THINNEST=.08;rolls;vibrations;spirals;rollAt(t){let e=0,i=0;for(const n of this.rolls){if(t<n.t)break;const s=n.params,r=this.progress(n,t);i=e+(s.toDeg-e)*(s.andBack?Math.sin(Math.PI*xe.smooth(r)):xe.smooth(r)),s.andBack||(e=s.toDeg)}for(const n of this.spirals){if(t<n.t)break;const s=n.params;i=e+(s.clockwise?1:-1)*s.rollDeg*this.progress(n,t)}return i}acrossShareAt(t){return Math.max(U0.THINNEST,Math.abs(Math.cos(this.rollAt(t)*Math.PI/180)))}sidewaysAt(t,e){let i=0;for(const n of this.vibrations){const s=n.until??this.end;if(t<n.t||t>=s)continue;const r=n.params,a=xe.smooth((t-n.t)/(r.riseS*1e3))*Math.max(0,1-(t-n.t)/(s-n.t));i+=r.amplitudeShare*e*a*Math.sin(2*Math.PI*r.hz*(t-n.t)/1e3)}return i}spiralAt(t){const e=[...this.spirals].reverse().find(a=>a.t<=t);if(!e)return;const i=e.params,n=this.progress(e,t),s=Math.tan(i.radiusDeg*Math.PI/180)*xe.smooth(n*U0.SPIRAL_OPENS)*(1-i.shrink*xe.smooth(n)),r=-(i.clockwise?1:-1)*2*Math.PI*i.turns*n;return[s*(Math.cos(r)-1),s*Math.sin(r)]}progress(t,e){const i=t.until??this.end;return i<=t.t?1:Math.max(0,Math.min(1,(e-t.t)/(i-t.t)))}}class bs{constructor(t,e,i,n){this.sighting=t,this.stand=e;const s=i.filter(a=>a.eventType==="appearance").sort((a,c)=>a.t-c.t);this.vanishAt=i.find(a=>a.eventType==="vanish")?.t;const r=this.vanishAt??n;this.path=e.eventType==="travel"?new xe(e,i.filter(a=>a.eventType==="turn"),n):void 0,this.motion=this.path?new U0(i,e.until??n):void 0,this.looks=s.map((a,c)=>({t:a.t,until:a.until??s[c+1]?.t??r,parts:a.params.parts})),this.blinks=i.filter(a=>a.eventType==="blink").map(a=>({t:a.t,until:a.until??r,parts:a.who===void 0?[]:t.timeline.leavesOf(a.who),params:a.params}))}static SAMPLE_MS=2e3;static TRAVEL_SAMPLE_MS=25;static MOTION_MS=40;static SPIRAL_AHEAD_MS=20;static R=63710088e-1;looks;blinks;vanishAt;path;motion;timeline(){const t=new Map,e=(r,a)=>{const c=this.state(a,r);c&&(t.has(r)||t.set(r,new Map),t.get(r).set(a,c))},i=[...new Set(this.looks.flatMap(r=>r.parts.map(a=>a.sourceId)))];this.looks.forEach((r,a)=>{const c=this.looks[a+1];for(const l of i){if(!r.parts.some(d=>d.sourceId===l)){e(r.t,l),c?.parts.some(d=>d.sourceId===l)&&e(c.t-1,l);continue}const u=this.sighting.sampleMs??(this.path?bs.TRAVEL_SAMPLE_MS:bs.SAMPLE_MS);for(let d=r.t;d<r.until;d+=u)e(d,l);e(r.until-1,l)}});for(const r of this.blinks)for(const[a,c]of this.phases(r))for(const l of r.parts)e(a,l),e(c-1,l);if(this.vanishAt!==void 0)for(const r of i)e(this.vanishAt,r);const n=[...t.keys()].sort((r,a)=>r-a).map(r=>({t:r,shapes:[...t.get(r).values()]})),s=new Map;for(const r of n)for(const a of r.shapes){const c=a.shape.angle,l=s.get(a.sourceId);if(c===void 0)continue;const h=l===void 0?c:c+2*Math.PI*Math.round((l-c)/(2*Math.PI));a.shape.angle=Math.round(h*1e4)/1e4,s.set(a.sourceId,h)}return{keyframes:n,order:i,groups:[]}}phases(t){const e=[];let i=!0;for(let n=t.t;n<t.until;){const s=Math.min(n+(i?t.params.onS:t.params.offS)*1e3,t.until);e.push([n,s]),n=s,i=!i}return e}off(t,e){for(const i of this.blinks){if(e<i.t||e>=i.until||!i.parts.includes(t))continue;if(this.phases(i).findIndex(([s,r])=>e>=s&&e<r)%2===1)return i.params.off}}state(t,e){const i=[...this.looks].reverse().find(l=>l.t<=e)??this.looks[0],n=i?.parts.find(l=>l.sourceId===t),r=(n?i:this.looks.find(l=>l.t>e&&l.parts.some(h=>h.sourceId===t))??[...this.looks].reverse().find(l=>l.parts.some(h=>h.sourceId===t)))?.parts.find(l=>l.sourceId===t);if(!r)return;const a=!n||this.vanishAt!==void 0&&e>=this.vanishAt,c=a?void 0:this.off(t,e);return this.path?{sourceId:t,shape:this.onPath(r,e,c,a)}:{sourceId:t,shape:bs.shape(r,this.geometry(e),c,a)}}onPath(t,e,i,n){const s=this.path,r=this.sighting.observerTrack.getInterpolatedPoseAt(e)??this.sighting.observerTrack.getLatestPoseAt(e),a=r?.headingDeg??0,c=r?.pitchDeg??0,l=this.motion,h=S=>xe.toScreen(s.at(S),a,c),u=(S,A)=>{const _=Math.hypot(A[0]-S[0],A[1]-S[1])||1;return[(A[0]-S[0])/_,(A[1]-S[1])/_]};let d=h(e),[f,p]=u(h(e-bs.MOTION_MS),h(e+bs.MOTION_MS));const m=s.sizeAt(e),g=Math.tan(l.sidewaysAt(e,m)*Math.PI/180);d=[d[0]-g*p,d[1]+g*f];const M=l.spiralAt(e);if(M){const S=l.spiralAt(e+bs.SPIRAL_AHEAD_MS),A=h(e),_=h(e+bs.SPIRAL_AHEAD_MS);d=[d[0]+M[0],d[1]+M[1]],[f,p]=u([A[0]+M[0],A[1]+M[1]],[_[0]+S[0],_[1]+S[1]])}const v=l.acrossShareAt(e),x={...t,heightShare:(t.heightShare??t.widthShare)*v,...t.upShare===void 0?{}:{upShare:t.upShare*v}},y=Math.tan(m*(x.alongShare??0)*Math.PI/180),w=Math.tan(m*(x.upShare??0)*Math.PI/180),b=xe.fromScreen(d[0]+y*f-w*p,d[1]+y*p+w*f,a,c),E=bs.shape(x,{...b,sizeDeg:m},i,n,!0);return E.angle=Math.atan2(-p,f),E}geometry(t){const e=this.stand.params,i=this.sighting.observerTrack.getInterpolatedPoseAt(t)??this.sighting.observerTrack.getLatestPoseAt(t),n=i?.lat!==void 0&&i.lng!==void 0?{lat:i.lat,lng:i.lng}:this.sighting.event.place?.[0]??e.place;return bs.seenFrom(e,n,t)}static seenFrom(t,e,i){const n=(t.place.lng-e.lng)*Math.PI/180*bs.R*Math.cos(e.lat*Math.PI/180),s=(t.place.lat-e.lat)*Math.PI/180*bs.R,r=Math.hypot(n,s),a=ai.linear(t.metres.map(({t:l,widthM:h,step:u})=>({t:l,value:h,step:u})),i),c=ai.linear(t.metres.map(({t:l,heightM:h,step:u})=>({t:l,value:h,step:u})),i);return{azimuthDeg:(Math.atan2(n,s)*180/Math.PI%360+360)%360,altitudeDeg:Math.atan2(c,r)*180/Math.PI,sizeDeg:2*Math.atan(a/(2*r))*180/Math.PI}}static shape(t,e,i,n,s=!1){const r=e.sizeDeg,a=Math.max(t.minWidthDeg??0,r*t.widthShare),c=t.kind==="oval"&&t.heightShare===void 0?a:Math.max(t.minHeightDeg??0,r*(t.heightShare??t.widthShare)),l=s?e.altitudeDeg:e.altitudeDeg+r*(t.upShare??0),h=s?e.azimuthDeg:e.azimuthDeg+r*(t.alongShare??0)/Math.cos(l*Math.PI/180),u=(p,m)=>Math.round(p*10**m)/10**m,d=t.kind==="polygon"?{kind:"polygon",bounds:{x:300,y:170,width:100,height:100*c/a},points:(t.points??[]).map(p=>({x:u(p.x*100,2),y:u(p.y*100*c/a,2)}))}:{kind:"oval",bounds:{x:320,y:180,width:2,height:2}};Object.assign(d,{color:i?.color??t.color,angle:0,transparency:n?1:i?.transparency??t.transparency??0,haloScale:t.halo??0,selected:!1,...t.blur===void 0?{}:{blur:t.blur},...t.title===void 0?{}:{title:t.title},angular:{widthDeg:u(a,4),heightDeg:u(c,4)},aim:{azimuthDeg:u((h%360+360)%360,3),altitudeDeg:u(l,3)}});const f=i&&"brightness"in i?i.brightness:t.brightness;return f!=null&&(d.brightness=n?0:f),d}}class Pe{static STANDING_EYE_M=1.6;static METERS_PER_DEGREE=111320;static expand(t){Pe.expandBodies(t),Pe.expandObserver(t),Pe.expandFlights(t),Pe.expandDecorLights(t),Pe.expandPhenomenon(t)}static expandDecorLights(t){for(const e of t.decor){if(!e.lights?.length||e.lights.some(s=>s.keyframes?.length))continue;const i=(t.events??[]).filter(s=>wd.partOf(s.who,e.id)!==void 0);if(i.length===0)continue;const n=JSON.stringify(e.lights);e.lights=new wd(e,i,Pe.endOf(t)).lights(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorLights={...t.eventsExpansion.decorLights,[e.id]:{stated:n,expanded:JSON.stringify(e.lights)}}}}static writtenLights(t,e,i){const n=t.eventsExpansion?.decorLights?.[e];return n&&JSON.stringify(i)===n.expanded?JSON.parse(n.stated):i}static expandPhenomenon(t){if(t.timeline.allKeyframes.length>0)return;const e=Pe.stands(t);for(const i of e){const n=As.within(t,i.who),s=(t.events??[]).filter(a=>a.who!==void 0&&n.has(a.who)),r=new bs(t,i,s,i.until??Pe.endOf(t)).timeline();for(const a of Ud.fromJSON(r).allKeyframes)t.timeline.addKeyframe(a.t,a.shapes)}e.length!==0&&(dh.timeline(t.timeline),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.timelinePending=!0)}static stands(t){return(t.events??[]).filter(e=>(e.eventType==="stand"||e.eventType==="travel")&&As.isPhenomenon(t,e))}static shapesOf(t){const{groups:e,...i}=t.timeline.toJSON();return JSON.stringify(i)}static timelineWithoutShapes(t){const e=t.timeline.toJSON().groups??[];return e.length>0?{keyframes:[],groups:e}:{keyframes:[]}}static settle(t){t.eventsExpansion?.timelinePending&&(dn.toAngular(t),dn.toAim(t),t.eventsExpansion.timeline=Pe.shapesOf(t),t.eventsExpansion.timelinePending=!1)}static timelineIsExpanded(t){return t.eventsExpansion?.timeline!==void 0&&t.eventsExpansion.timeline===Pe.shapesOf(t)}static expandFlights(t){const e=t.observerTrack.allKeyframes[0]?.pose??t.event.place?.[0];if(e?.lat===void 0||e.lng===void 0)return;const i=Math.cos(e.lat*Math.PI/180);for(const n of t.events??[]){if(n.eventType!=="fly"||n.who===void 0)continue;const s=t.decor.find(m=>m.id===n.who);if(!s||s.track?.length)continue;const r=n.params,a=n.until??Pe.endOf(t),c=r.headingDeg*Math.PI/180,l=(r.from.lng-e.lng)*Math.PI/180*Pe.R*i,h=(r.from.lat-e.lat)*Math.PI/180*Pe.R,u=r.speeds.map(({t:m,kmh:g,step:M})=>({t:m,value:g/3.6,step:M})),d=r.heights.map(({t:m,altitudeM:g,step:M})=>({t:m,value:g,step:M})),f=m=>{const g=Math.sign(m-r.at.t)*Pe.FLY_STEP_MS;let M=0;for(let v=r.at.t;g!==0&&(g>0?v<m:v>m);v+=g){const x=g>0?Math.min(m,v+g):Math.max(m,v+g);M+=(ai.linear(u,v)+ai.linear(u,x))/2*(x-v)/1e3}return M},p=[];for(let m=n.t;m<=a;m+=ai.SAMPLE_MS){const g=r.at.metresBefore-f(m);p.push({t:m,eastM:l-Math.sin(c)*g,northM:h-Math.cos(c)*g,altitudeM:ai.linear(d,m),headingDeg:r.headingDeg})}s.track=p,s.eastM=p[0].eastM,s.northM=p[0].northM,s.headingDeg=r.headingDeg,t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorTracks[s.id]=JSON.stringify(p)}}static R=63710088e-1;static FLY_STEP_MS=100;static expandObserver(t){const e=(t.events??[]).filter(m=>As.isObserver(t,m)),i=e.find(m=>m.eventType==="drive"),n=e.find(m=>m.eventType==="lookAhead");if(t.observerTrack.allKeyframes.length>0)return;if(!i){new yo(t,e).keyframes().length>0&&(dh.observer(t.observerTrack),t.eventsExpansion={...t.eventsExpansion,observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:t.eventsExpansion?.decorTracks??{}});return}if(!n)return;const s=i.until??Pe.endOf(t),r=i.params,a=new ai(r,i.t,s),c=e.find(m=>m.eventType==="lean"),l=e.find(m=>m.eventType==="watch"),u=new je(a,r.eye,n.params,c&&{t:c.t,params:c.params},l&&{t:l.t,params:l.params},m=>{const g=Pe.stands(t).find(v=>v.eventType==="stand");if(!g)return Pe.phenomenonPitchAt(t,m);const M=a.stateAt(m);return bs.seenFrom(g.params,{lat:M.lat,lng:M.lng},m).altitudeDeg}).poses(i.t,s),d=u.map(m=>({t:m.t,pose:{lat:m.lat,lng:m.lng,elevationM:m.eye.y-Pe.STANDING_EYE_M,headingDeg:m.headingDeg,pitchDeg:m.pitchDeg,fovDeg:r.fovDeg??60}}));for(const m of d)t.observerTrack.addKeyframe(m.t,m.pose);dh.observer(t.observerTrack);const f={observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:{}},p=r.vehicle===void 0?void 0:t.decor.find(m=>m.id===r.vehicle);if(p&&!p.track?.length){const m=u[0],g=v=>Math.cos(v*Math.PI/180),M=u.map(v=>{const x=v.roadDeg*Math.PI/180,y=-v.eye.z,w=v.eye.x,b=(v.lng-m.lng)*Pe.METERS_PER_DEGREE*g(v.lat),E=(v.lat-m.lat)*Pe.METERS_PER_DEGREE;return{t:v.t,eastM:b-y*Math.sin(x)-w*Math.cos(x),northM:E-y*Math.cos(x)+w*Math.sin(x),altitudeM:0,headingDeg:v.roadDeg}});p.track=M,p.eastM=M[0].eastM,p.northM=M[0].northM,p.headingDeg=M[0].headingDeg,f.decorTracks[p.id]=JSON.stringify(M)}t.eventsExpansion={...t.eventsExpansion,...f}}static expandBodies(t){const e=t.interpretation?.bodies??[],i=n=>(t.events??[]).some(s=>s.who===n.id&&s.eventType==="ride");for(const n of[...e.filter(s=>!i(s)),...e.filter(i)]){const s=(t.events??[]).filter(h=>h.who===n.id||ko.partOf(h.who,n.id)!==void 0);if(s.length===0)continue;const r=Math.min(...s.map(h=>h.t));if(n.track.some(h=>h.t>r))continue;const a=JSON.stringify(n.track),c=s.find(h=>h.eventType==="ride"),l=c&&e.find(h=>h.id===c.params.in);n.track=c?l?ko.ride(n,c,l):n.track:new ko(n,s,Pe.endOf(t),t.sampleMs).track(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.bodies={...t.eventsExpansion.bodies,[n.id]:{stated:a,expanded:JSON.stringify(n.track)}}}}static writtenInterpretation(t,e){const i=t.eventsExpansion?.bodies;return!e||!i?e:{...e,bodies:e.bodies.map(n=>{const s=i[n.id];return s&&JSON.stringify(n.track)===s.expanded?{...n,track:JSON.parse(s.stated)}:n})}}static refresh(t){const e=t.observerTrack.allKeyframes.length===0||Pe.observerTrackIsExpanded(t),i=t.timeline.allKeyframes.length===0||Pe.timelineIsExpanded(t);Pe.again(t,e,i)}static reset(t){Pe.again(t,!0,Pe.stands(t).length>0)}static again(t,e,i){for(const s of t.interpretation?.bodies??[]){const r=t.eventsExpansion?.bodies?.[s.id];r&&JSON.stringify(s.track)===r.expanded&&(s.track=JSON.parse(r.stated))}for(const s of t.decor)s.lights&&(s.lights=Pe.writtenLights(t,s.id,s.lights));if(e){for(const s of Object.keys(t.eventsExpansion?.decorTracks??{})){const r=t.decor.find(a=>a.id===s);r&&delete r.track}t.observerTrack.clear()}const n=t.timeline.toJSON().groups??[];if(i){for(const s of[...t.timeline.sourceIds])t.timeline.removeSource(s);t.timeline.setGroups(n,!1)}t.eventsExpansion=void 0,Pe.expand(t),i&&t.timeline.pruneGroups(),i&&(dn.toBounds(t),dn.toPosition(t)),Pe.settle(t)}static bodiesAreExpanded(t){const e=t.eventsExpansion?.bodies??{};return(t.interpretation?.bodies??[]).every(i=>!e[i.id]||JSON.stringify(i.track)===e[i.id].expanded)}static observerTrackIsExpanded(t){return t.eventsExpansion?.observerTrack!==void 0&&t.eventsExpansion.observerTrack===JSON.stringify(t.observerTrack.toJSON())}static decorTrackIsExpanded(t,e,i){const n=t.eventsExpansion?.decorTracks[e];return n!==void 0&&n===JSON.stringify(i)}static phenomenonPitchAt(t,e){let i;for(const n of t.timeline.sourceIds){const s=t.timeline.getInterpolatedShapeAt(e,n),r=s?.aim?.altitudeDeg;if(!s||s.transparency>=1||r===void 0)continue;const a=(s.angular?.widthDeg??0)*(s.angular?.heightDeg??0);(!i||a>i.area)&&(i={area:a,altitude:r})}return i?.altitude??0}static endOf(t){return t.event.durationSeconds!==void 0?t.event.durationSeconds*1e3:Math.max(...(t.events??[]).map(e=>e.until??e.t))}}function b_(o){return tr.restore(E_(o),o.provenance)}function E_(o,t=!1){return dn.toAngular(o),dn.toAim(o),{version:4,id:o.id,time:F0.write(o.event.time),endTime:F0.write(o.event.endTime),durationSeconds:o.event.durationSeconds,durationText:o.event.durationText,utcOffsetHours:o.event.utcOffsetHours,timeZone:o.event.timeZone,place:lb.write(o.event.place),observer:o.observer,account:o.account,sources:o.sources?.length?o.sources:void 0,sway:o.sway,vehicle:o.vehicle,description:o.event.description,image:o.event.image,summary:o.event.summary,summaryTime:o.event.summaryTime,tags:o.event.tags,timeline:!t&&Pe.timelineIsExpanded(o)?Pe.timelineWithoutShapes(o):o.timeline.toJSON(),observerTrack:!t&&Pe.observerTrackIsExpanded(o)?void 0:qn.restatedObserverTrack(o),events:o.events?.length?o.events:void 0,weatherTrack:o.weatherTrack.toJSON(),soundTrack:o.soundTrack.toJSON(),weather:o.weather,decor:qn.restatedDecor(o).map(e=>{if(!t&&e.lights&&(e={...e,lights:Pe.writtenLights(o,e.id,e.lights)}),t||!Pe.decorTrackIsExpanded(o,e.id,e.track))return e;const{track:i,...n}=e;return n}),milestones:o.milestones.length>0?o.milestones:void 0,references:o.references.length>0?o.references:void 0,roads:o.roads.length>0?o.roads:void 0,traces:o.traces.length>0?o.traces:void 0,weatherSource:o.weatherSource,instrument:o.instrumentId,exposureSeconds:o.exposureSeconds,iso:o.iso,film:o.film,metering:o.metering,sampleMs:o.sampleMs,lens:o.lens,lightPollution:o.lightPollution,observerMap:o.observerMap,interpretation:t?qn.restatedInterpretation(o):Pe.writtenInterpretation(o,qn.restatedInterpretation(o)),variants:o.variants.length>0?o.variants:void 0,skyEvents:Hr.written(o.skyEvents),snapshots:o.snapshots,modules:o.modules?.length?o.modules:void 0}}function A_(o){Gl.check(o,"sighting");const t=Qi.toCurrent(o),{recording:e,provenance:i}=tr.strip(t),n=__(e);return n.provenance=i,n}function __(o){const t=[],e=new Ap({eventType:"sighting",time:F0.read(o.time),endTime:F0.read(o.endTime),durationSeconds:o.durationSeconds,durationText:o.durationText,utcOffsetHours:o.utcOffsetHours,timeZone:o.timeZone,place:lb.read(o.place),description:o.description,image:o.image,summary:o.summary,summaryTime:o.summaryTime,tags:o.tags},Ud.fromJSON(o.timeline,t,!1),o.observerTrack?Zu.fromJSON(o.observerTrack):new Zu,o.weatherTrack?Ju.fromJSON(o.weatherTrack):new Ju,o.soundTrack?ju.fromJSON(o.soundTrack):new ju,o.observer&&{id:o.observer.id,title:o.observer.title,lastName:o.observer.lastName,firstNames:o.observer.firstNames},o.id,o.weather,(o.decor??[]).map(n=>{if(!n.facade?.plain)return n;const{plain:s,...r}=n.facade;return{...n,facade:{...r,openings:"plain"}}}),o.weatherSource,o.instrument,o.exposureSeconds??o.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),Du(o.milestones??[]),o.references??[],o.roads??[],o.traces??[]);e.account=o.account,e.sources=o.sources,e.sway=o.sway,e.iso=o.iso,e.film=o.film,e.metering=o.metering,e.sampleMs=o.sampleMs,e.lens=o.lens,e.lightPollution=o.lightPollution,e.observerMap=o.observerMap,e.vehicle=o.vehicle,e.events=o.events?.map(n=>n.who===void 0?{...n,who:Qi.observerIdOf(o)}:n);const i=Hr.read(o.skyEvents,o.interpretation);return e.interpretation=i.interpretation,e.variants=Array.isArray(o.variants)?o.variants:[],e.skyEvents=i.skyEvents,e.snapshots=o.snapshots,e.modules=Array.isArray(o.modules)?o.modules.filter(n=>typeof n=="string"):void 0,e.loadIssues=t,Pe.expand(e),e.timeline.pruneGroups(),dn.toBounds(e),dn.toPosition(e),Pe.settle(e),e}class F0{static read(t){return t===void 0||t.trim()===""?void 0:Y3(t)}static write(t){if(t===void 0)return;const e=sb(t);return e===""?void 0:e}}class lb{static read(t){if(t?.locations?.length)return t.locations.map(({lat:e,lng:i})=>({lat:e,lng:i,...t.name===void 0?{}:{name:t.name}}))}static write(t){if(!t?.length)return;const e=t.find(i=>i.name)?.name;return{...e===void 0?{}:{name:e},locations:t.map(({lat:i,lng:n})=>({lat:i,lng:n}))}}}class Sd{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(t,e=Sd.EN){return e[t.kind].replace("{path}",t.path).replace("{expected}",t.expected??"").replace("{found}",t.found??"")}static warn(t,e){if(t.length===0)return;const i=t.map(n=>` ${Sd.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
1765
+ `;class uh{constructor(t){this.points=t}static STATIONARY_M=5;static of(t){const e=[];for(const i of t.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||e.push({t:i.t,lat:n,lng:s,headingDeg:r})}if(e.length===0){const i=t.event.place?.[0];if(!i)return;e.push({t:0,lat:i.lat,lng:i.lng})}return new uh(e)}static TRAVEL_M=50;get travels(){return this.spanM>uh.TRAVEL_M}get moved(){return this.spanM>uh.STATIONARY_M}get spanM(){const t=this.box,e=(t.south+t.north)/2,i=(t.west+t.east)/2;return Math.max(Math.abs(ae(e,t.east,e,t.west).x),Math.abs(ae(t.north,i,t.south,i).z))}get center(){const t=this.box;return{lat:(t.south+t.north)/2,lng:(t.west+t.east)/2}}boundsAround(t,e){const{lat:i,lng:n}=this.center,s=Math.max(this.spanM*(1+e),t)/2;return{north:Is(0,-s,i,n).lat,south:Is(0,s,i,n).lat,east:Is(s,0,i,n).lng,west:Is(-s,0,i,n).lng}}get box(){const t=this.points.map(i=>i.lat),e=this.points.map(i=>i.lng);return{south:Math.min(...t),north:Math.max(...t),west:Math.min(...e),east:Math.max(...e)}}}class Zs{constructor(t,e){this.rotationPassed=t,this.scale=e}static SWAY_M=.012;static BREATH_M=.003;static DRIFT_YAW_DEG=.5;static DRIFT_PITCH_DEG=.4;static DRIFT_ROLL_DEG=.3;static GAZE_DRIFT_SHARE=.35;static HAND_HELD_S=.5;static HZ=[.11,.23,.17,.29,.37,.07];static of(t){if(t.instrument.mounted)return;const e=t.event.tags?.includes("paralysis")||(t.exposure??0)>Zs.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new Zs(Math.max(1-(t.instrument.stabilization??0),Zs.GAZE_DRIFT_SHARE),i)}offsetAt(t){const e=t/1e3,i=this.scale,n=(u,d)=>Math.sin(2*Math.PI*u*e+d),[s,r,a,c,l,h]=Zs.HZ;return{eastM:i*Zs.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*Zs.SWAY_M*(.6*n(a,2.2)+.4*n(l,.8)),upM:i*Zs.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*Zs.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*Zs.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*Zs.DRIFT_ROLL_DEG*n(s,2.9)}}}class ri{constructor(t,e){this.stretches=t,this.rotationPassed=e}static REFERENCE_SPEED_M_PER_S=1.4;static REFERENCE_STEP_HZ=1.9;static CADENCE_EXPONENT=.43;static RISE_M_PER_M_PER_S=.0175;static SWAY_M=.0175;static SLOWEST_WALK_M_PER_S=.2;static FASTEST_WALK_M_PER_S=2.2;static HEAD_ROLL_DEG=1.5;static HEAD_PITCH_DEG=1.25;static HEAD_YAW_DEG=1;static STOP_LURCH_M=.035;static STOP_PITCH_DEG=3;static START_LURCH_M=.015;static START_PITCH_DEG=1.2;static JOLT_HZ=1.4;static JOLT_DECAY_S=.35;static JOLT_LASTS_MS=1500;static STILL=Object.freeze({eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0});static of(t){const e=uh.of(t);if(!e||e.points.length<2)return;const i=[];let n=0;for(let s=1;s<e.points.length;s++){const r=e.points[s-1],a=e.points[s],c=(a.t-r.t)/1e3;if(c<=0)continue;const l=ae(a.lat,a.lng,r.lat,r.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/c,p=ri.stepHzFor(f);i.push({startMs:r.t,endMs:a.t,speedMPerS:f,eastUnit:d>0?h/d:0,northUnit:d>0?u/d:0,stepHz:p,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=p*c}for(let s=0;s<i.length;s++){const r=i[s-1],a=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=a===void 0||a.stepHz===0}if(i.some(s=>s.stepHz>0))return new ri(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const n=ri.of(t)?.offsetAt(e)??ri.STILL;return i?n:ri.add(n,Zs.of(t)?.offsetAt(e))}static stepHzFor(t){return t<ri.SLOWEST_WALK_M_PER_S||t>ri.FASTEST_WALK_M_PER_S?0:ri.REFERENCE_STEP_HZ*Math.pow(t/ri.REFERENCE_SPEED_M_PER_S,ri.CADENCE_EXPONENT)}offsetAt(t){return ri.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/ri.REFERENCE_SPEED_M_PER_S,n=(a,c,l,h)=>{if(a<0||a>ri.JOLT_LASTS_MS)return;const u=a/1e3,d=Math.exp(-u/ri.JOLT_DECAY_S)*Math.sin(2*Math.PI*ri.JOLT_HZ*u),f=h*c*i*d;return{eastM:f*e.eastUnit,northM:f*e.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-h*l*i*d*this.rotationPassed,yawDeg:0}},s=e.rampsOut?n(t-e.endMs,ri.STOP_LURCH_M,ri.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=e.rampsIn?n(t-e.startMs,ri.START_LURCH_M,ri.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(t,e){return e?{eastM:t.eastM+e.eastM,northM:t.northM+e.northM,upM:t.upM+e.upM,rollDeg:t.rollDeg+e.rollDeg,pitchDeg:t.pitchDeg+e.pitchDeg,yawDeg:t.yawDeg+e.yawDeg}:t}cycleAt(t){const e=this.stretches.find(c=>t>=c.startMs&&t<=c.endMs);if(!e||e.stepHz===0)return ri.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(e,t),r=ri.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*e.speedMPerS/ri.REFERENCE_SPEED_M_PER_S;return{eastM:r*e.northUnit,northM:-r*e.eastUnit,upM:ri.RISE_M_PER_M_PER_S*e.speedMPerS*s*Math.cos(n),rollDeg:ri.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:ri.HEAD_YAW_DEG*a*Math.cos(n/2)}}amplitudeAt(t,e){const i=1e3/t.stepHz,n=Math.min(i,(t.endMs-t.startMs)/2);if(n<=0)return 1;const s=e-t.startMs,r=t.endMs-e,a=Math.min(t.rampsIn?s/n:1,t.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class p_{constructor(t,e){this.timeline=t,this.onFrame=e}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;onEnded;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const t=()=>{if(this.state!=="playing")return;const e=performance.now();if(this.currentT+=(e-this.lastWallTime)*this.playbackRate,this.lastWallTime=e,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(t){this.currentT=Math.max(0,Math.min(t,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(t){const e=new Map;for(const i of this.timeline.sourceIds){const n=this.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}this.onFrame(t,e)}}const cb=["nw","n","ne","e","se","s","sw","w"],m_=24,Kd=8,g_=3,M_=8;function qd(o,t,e){const i=o.x-t.x,n=o.y-t.y,s=Math.cos(e),r=Math.sin(e);return{x:t.x+i*s-n*r,y:t.y+i*r+n*s}}function $h(o){return{x:o.x+o.width/2,y:o.y+o.height/2}}const v_={nw:{left:!0,top:!0},n:{top:!0},ne:{right:!0,top:!0},e:{right:!0},se:{right:!0,bottom:!0},s:{bottom:!0},sw:{left:!0,bottom:!0},w:{left:!0}};class zs{static handlePointsFor(t){const{x:e,y:i,width:n,height:s}=t.bounds,r={nw:{x:e,y:i},n:{x:e+n/2,y:i},ne:{x:e+n,y:i},e:{x:e+n,y:i+s/2},se:{x:e+n,y:i+s},s:{x:e+n/2,y:i+s},sw:{x:e,y:i+s},w:{x:e,y:i+s/2},rotate:{x:e+n/2,y:i-m_}},a=$h(t.bounds),c={};for(const l of Object.keys(r))c[l]=qd(r[l],a,t.angle);return c}static hitTestHandle(t,e,i=8,n=[...cb,"rotate"]){const s=zs.handlePointsFor(t);for(const r of n)if(Math.hypot(e.x-s[r].x,e.y-s[r].y)<=i)return r}static HANDLE_DIRECTION_DEG={e:0,se:45,s:90,sw:135,w:180,nw:225,n:270,ne:315};static resizeAxisFor(t,e){const n=((zs.HANDLE_DIRECTION_DEG[t]+e*180/Math.PI)%180+180)%180/45,s=["ew","nwse","ns","nesw"];return s[Math.round(n)%s.length]}static resizeBounds(t,e,i,n){const s=$h(t),r=qd(n,s,-e),{x:a,y:c,width:l,height:h}=t,u=v_[i];let d=a,f=c,p=a+l,m=c+h;return u.left&&(d=Math.min(r.x,p-Kd)),u.right&&(p=Math.max(r.x,d+Kd)),u.top&&(f=Math.min(r.y,m-Kd)),u.bottom&&(m=Math.max(r.y,f+Kd)),{x:d,y:f,width:p-d,height:m-f}}static resizeShape(t,e,i){if(e==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=t.bounds,r=zs.resizeBounds(t.bounds,t.angle,e,i);if(t.kind==="oval")return{...t,bounds:r};const a=n===0?1:r.width/n,c=s===0?1:r.height/s;return{...t,bounds:r,points:t.points.map(l=>({x:l.x*a,y:l.y*c}))}}static rotateShape(t,e){const i=$h(t.bounds),n=Math.atan2(e.y-i.y,e.x-i.x)+Math.PI/2;return{...t,angle:n}}static groupBoundsFor(t){const e=Math.min(...t.map(r=>r.x)),i=Math.min(...t.map(r=>r.y)),n=Math.max(...t.map(r=>r.x+r.width)),s=Math.max(...t.map(r=>r.y+r.height));return{x:e,y:i,width:n-e,height:s-i}}static vertexPointsFor(t){const e=$h(t.bounds);return t.points.map(i=>qd({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=M_){const n=zs.vertexPointsFor(t);let s,r=i;return n.forEach((a,c)=>{const l=Math.hypot(e.x-a.x,e.y-a.y);l<=r&&(r=l,s=c)}),s}static toLocalPoint(t,e){const i=$h(t.bounds),n=qd(e,i,-t.angle);return{x:n.x-t.bounds.x,y:n.y-t.bounds.y}}static moveVertex(t,e,i){const n=t.points.map((u,d)=>d===e?zs.toLocalPoint(t,i):u),s=Math.min(...n.map(u=>u.x)),r=Math.min(...n.map(u=>u.y)),a=Math.max(...n.map(u=>u.x)),c=Math.max(...n.map(u=>u.y)),l={x:t.bounds.x+s,y:t.bounds.y+r,width:a-s,height:c-r},h=n.map(u=>({x:u.x-s,y:u.y-r}));return{...t,bounds:l,points:h}}static insertVertexNear(t,e){const i=zs.toLocalPoint(t,e),{points:n}=t;let s=n.length-1,r=1/0;for(let c=0;c<n.length;c++){const l=n[c],h=n[(c+1)%n.length],u=zs.distanceToSegment(i,l,h);u<r&&(r=u,s=c)}const a=[...n.slice(0,s+1),i,...n.slice(s+1)];return{...t,points:a}}static distanceToSegment(t,e,i){const n=i.x-e.x,s=i.y-e.y,r=n*n+s*s,a=r===0?0:Math.max(0,Math.min(1,((t.x-e.x)*n+(t.y-e.y)*s)/r)),c=e.x+a*n,l=e.y+a*s;return Math.hypot(t.x-c,t.y-l)}static deleteVertex(t,e){return t.points.length<=g_?t:{...t,points:t.points.filter((i,n)=>n!==e)}}}const Kg=6,Zd=Kg/2,n2=20,s2=24,r2=9,a2=6,o2=7,c2=6,Cr=4;class Ph{constructor(t){this.ctx=t}starPoints=0;roll=0;clear(t,e){this.ctx.clearRect(0,0,t,e)}static paintExtent(t){const{x:e,y:i,width:n,height:s}=t.bounds,r=e+n/2,a=i+s/2,c=t.angle%(2*Math.PI)!==0,l=Math.hypot(n,s)/2,h=c?l:n/2,u=c?l:s/2,d=Math.max(n,s)/2,f=t.brightness??0,p=f>0?Math.max(d*(1+r2*f),c2*f)-d:0,m=f>0?d*(1+o2*f)-d:0,g=3*s2*(t.blur??0)+1.5*n2*t.haloScale,M=Math.max(p,m,0)+g+2;return{x:r-h-M,y:a-u-M,width:2*(h+M),height:2*(u+M)}}paintInto(t,e,i,n=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-e.x,-e.y);const s=t.selected?{...t,selected:!1}:t;n?this.paintGhost(s,1.5):this.paintShape(s),this.ctx.restore()}paintShape(t){this.ctx.save(),this.ctx.globalAlpha=1-t.transparency;const e=t.blur??0;e>0&&(this.ctx.filter=`blur(${(s2*e).toFixed(2)}px)`);const i=t.brightness??0;i>0&&this.paintDazzle(t,i),t.haloScale>0&&this.paintHalo(t),this.paintBase(t),this.ctx.restore(),t.selected&&this.paintSelectionHandles(t)}setStarPoints(t){this.starPoints=Math.max(0,Math.floor(t))}setRoll(t){this.roll=t}paintDazzle(t,e){const{x:i,y:n,width:s,height:r}=t.bounds,a=i+s/2,c=n+r/2,l=Math.max(s,r)/2,h=Math.max(l*(1+r2*e),c2*e);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const u=this.ctx.createRadialGradient(a,c,0,a,c,h);for(let d=0;d<=a2;d++){const f=d/a2,p=1/(1+24*f*f);this.ctx.globalAlpha=1,u.addColorStop(f,this.withAlpha(t.color,p*e*.55))}if(this.ctx.fillStyle=u,this.ctx.beginPath(),this.ctx.arc(a,c,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=l*(1+o2*e);this.ctx.lineWidth=Math.max(1,l*.12),this.ctx.lineCap="round";for(let f=0;f<this.starPoints;f++){const p=f/this.starPoints*Math.PI*2+this.roll,m=a+Math.cos(p)*d,g=c+Math.sin(p)*d,M=this.ctx.createLinearGradient(a,c,m,g);M.addColorStop(0,this.withAlpha(t.color,e*.55)),M.addColorStop(.35,this.withAlpha(t.color,e*.22)),M.addColorStop(1,this.withAlpha(t.color,0)),this.ctx.strokeStyle=M,this.ctx.beginPath(),this.ctx.moveTo(a,c),this.ctx.lineTo(m,g),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(t,e){if(e<=0)return t.color;const i=/^#([0-9a-f]{6})$/i.exec(t.color.trim());if(!i)return t.color;const n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*e);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(t,e){const i=Math.max(0,Math.min(1,e)),n=/^#([0-9a-f]{6})$/i.exec(t.trim());if(!n)return t;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&255}, ${i.toFixed(3)})`}paintBase(t){this.ctx.fillStyle=this.dazzledFill(t,t.brightness??0),this.tracePath(t),this.ctx.fill()}paintGhost(t,e){this.ctx.save(),this.tracePath(t),this.ctx.setLineDash([e*3,e*2]),this.ctx.lineWidth=e,this.ctx.strokeStyle=t.color,this.ctx.stroke(),this.ctx.restore()}tracePath(t){if(this.ctx.beginPath(),t.kind==="oval"){const{x:e,y:i,width:n,height:s}=t.bounds,r=n/2,a=s/2;this.ctx.ellipse(e+r,i+a,r,a,t.angle,0,2*Math.PI)}else{const{x:e,y:i,width:n,height:s}=t.bounds;this.ctx.save(),this.ctx.translate(e+n/2,i+s/2),this.ctx.rotate(t.angle),this.ctx.translate(-n/2,-s/2),t.points.forEach((r,a)=>{a===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(t){this.ctx.save(),this.ctx.shadowColor=t.color,this.ctx.shadowBlur=n2*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(zs.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of zs.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,Cr,Cr,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(zs.handlePointsFor(t))}paintSelectionOnly(t){this.paintSelectionHandles(t)}paintPictureFrame(t,e,i){const n=this.ctx;if(n.save(),t&&t.length===4){n.strokeStyle="#39f",n.lineWidth=1.5,n.setLineDash([6,4]),n.beginPath(),n.moveTo(t[0].x,t[0].y);for(const s of t.slice(1))n.lineTo(s.x,s.y);n.closePath(),n.stroke(),n.setLineDash([])}for(const s of e){const r=Ph.landmarkColour(s.residualDeg),a=s.selected?3:2;s.selected&&(n.strokeStyle="#fff",n.lineWidth=a+3,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Cr+2,Cr+2,0,0,2*Math.PI),n.stroke()),s.scene&&(n.strokeStyle=r,n.lineWidth=1,n.beginPath(),n.moveTo(s.picture.x,s.picture.y),n.lineTo(s.scene.x,s.scene.y),n.stroke(),n.fillStyle=r,n.beginPath(),n.ellipse(s.scene.x,s.scene.y,Cr,Cr,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=a,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Cr+2,Cr+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+Cr+5,s.picture.y-Cr-2,r)}i&&this.paintLabel(i,8,8,"#fff",13),n.restore()}paintGhosts(t,e,i){const n=this.ctx;n.save();const s=(c,l,h,u=[])=>{n.setLineDash(u),n.lineWidth=h+2,n.strokeStyle="rgba(0, 0, 0, 0.6)",c(),n.lineWidth=h,n.strokeStyle=l,c(),n.setLineDash([])},r=(c,l)=>()=>{n.beginPath(),n.arc(c.x,c.y,l,0,2*Math.PI),n.stroke()},a=(c,l,h)=>()=>{const[u,d]=h?[l,l]:[l,0];n.beginPath(),n.moveTo(c.x-u,c.y-d),n.lineTo(c.x+u,c.y+d),n.moveTo(c.x+d,c.y-u),n.lineTo(c.x-d,c.y+u),n.stroke()};for(const c of t)s(()=>{n.beginPath(),n.moveTo(c.ghost.x,c.ghost.y),n.lineTo(c.light.x,c.light.y),n.stroke()},"rgba(255, 255, 255, 0.85)",1,[4,4]),s(r(c.light,7),"#ffffff",1.5),s(r(c.ghost,Math.max(9,c.ghostRadius)),"#ffd23f",2);e&&s(a(e,8,!1),"#ffd23f",2),i&&s(a(i,5,!0),"rgba(255, 255, 255, 0.7)",1),n.restore()}static landmarkColour(t){return t===void 0?"#ffb000":t<=1?"#3c3":t<=3?"#ffb000":"#f33"}paintLabel(t,e,i,n,s=11){const r=this.ctx;r.save(),r.font=`${s}px system-ui, sans-serif`,r.textBaseline="top";const a=r.measureText(t).width;r.fillStyle="rgba(0, 0, 0, 0.6)",r.fillRect(e-3,i-2,a+6,s+4),r.fillStyle=n,r.fillText(t,e,i),r.restore()}paintGroupHandles(t){this.paintHandleFrame(zs.handlePointsFor({bounds:t,angle:0}),{includeRotate:!0})}paintOutline(t){this.ctx.strokeStyle="lightgray",this.ctx.beginPath(),this.ctx.moveTo(t.nw.x,t.nw.y),this.ctx.lineTo(t.ne.x,t.ne.y),this.ctx.lineTo(t.se.x,t.se.y),this.ctx.lineTo(t.sw.x,t.sw.y),this.ctx.closePath(),this.ctx.stroke()}paintHandleFrame(t,{includeRotate:e}){this.paintOutline(t),this.ctx.fillStyle="lightgray";for(const i of cb){const n=t[i];this.ctx.fillRect(n.x-Zd,n.y-Zd,Kg,Kg)}e&&(this.ctx.beginPath(),this.ctx.moveTo(t.n.x,t.n.y),this.ctx.lineTo(t.rotate.x,t.rotate.y),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.ellipse(t.rotate.x,t.rotate.y,Zd+1,Zd+1,0,0,2*Math.PI),this.ctx.fill())}}const l2=.05,h2=.08,u2=2,d2=3,y_=14,x_=.02;class w_{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",t);return}}Ic.unlock(this.context)}setSound(t){if(this.requested=t,!this.context)return;const e=this.keyFor(t);if(!e){this.silence();return}if(this.voice?.key!==e){this.stopVoice();const i=++this.voiceToken;e.startsWith("src:")?this.buildRecordedVoice(t.src,e,i):this.voice=this.buildSynthesizedVoice(t,e)}this.applyTo(this.voice,t)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(t){if(!(t.volume<=0))return t.src?`src:${t.src}`:t.kind==="none"?void 0:t.kind}applyTo(t,e){const i=this.context;if(!t||!i)return;const n=i.currentTime;t.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,e.volume))*t.gainScale,n,l2);for(const{param:s,ratio:r}of t.pitch)s.setTargetAtTime(Math.min(e.pitchHz*r,i.sampleRate/2-1),n,l2)}buildSynthesizedVoice(t,e){const i=this.context;if(i)switch(t.kind){case"hum":return this.buildHum(i,e);case"whistle":return this.buildWhistle(i,e);case"rumble":return this.buildRumble(i,e);case"crackle":return this.buildCrackle(i,e);default:return}}buildHum(t,e){const i=t.createOscillator();i.type="sawtooth";const n=t.createOscillator();n.type="sawtooth";const s=t.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=t.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:n.frequency,ratio:1.006},{param:s.frequency,ratio:6}]}}buildWhistle(t,e){const i=t.createOscillator();i.type="sine";const n=t.createOscillator();n.type="sine",n.frequency.value=5;const s=t.createGain(),r=t.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(t,e){const i=t.createBufferSource();i.buffer=this.brownNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=t.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(this.output(t)),i.start(),{key:e,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(t,e){const i=t.createBufferSource();i.buffer=this.whiteNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=t.createGain();s.gain.value=0;const r=t.createBufferSource();r.buffer=this.crackleEnvelope(t),r.loop=!0;const a=t.createGain();return a.gain.value=0,r.connect(a).connect(s.gain),i.connect(n).connect(s).connect(this.output(t)),i.start(),r.start(),{key:e,nodes:[n,s,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(t,e,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(t)}catch(c){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",c);return}if(i!==this.voiceToken||!this.context)return;const r=n.createBufferSource();r.buffer=s,r.loop=!0;const a=n.createGain();a.gain.value=0,r.connect(a).connect(this.output(n)),r.start(),this.voice={key:e,nodes:[a],sources:[r],volumeParam:a.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(t){const e=this.context;if(!e)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}whiteNoise(t){if(!this.noiseBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*u2),t.sampleRate),i=e.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=e}return this.noiseBuffer}brownNoise(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*u2),t.sampleRate),i=e.getChannelData(0);let n=0,s=0;for(let r=0;r<i.length;r++)n=(n+.02*(Math.random()*2-1))/1.02,i[r]=n,s=Math.max(s,Math.abs(n));if(s>0)for(let r=0;r<i.length;r++)i[r]/=s;return e}crackleEnvelope(t){if(!this.crackleBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*d2),t.sampleRate),i=e.getChannelData(0),n=Math.max(1,Math.floor(x_*t.sampleRate)),s=Math.round(d2*y_);for(let r=0;r<s;r++){const a=Math.floor(Math.random()*i.length),c=.4+Math.random()*.6;for(let l=0;l<n&&a+l<i.length;l++)i[a+l]=Math.max(i[a+l],c*(1-l/n))}this.crackleBuffer=e}return this.crackleBuffer}stopVoice(){const t=this.voice,e=this.context;if(this.voice=void 0,!t||!e)return;const i=e.currentTime;t.volumeParam.cancelScheduledValues(i),t.volumeParam.setTargetAtTime(0,i,h2/3);const n=i+h2;for(const s of t.sources){s.onended=()=>{s.disconnect();for(const r of t.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of t.nodes)r.disconnect()}}}}class Qt{static svg(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="currentColor"/></svg>`}static outline(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}static solid(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="currentColor" fill-rule="evenodd"/></svg>`}static BOOKMARK="M6 3.5h12a.5.5 0 0 1 .5.5v16.5L12 16.8l-6.5 3.7V4a.5.5 0 0 1 .5-.5z";static PICTURE="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z";static PICTURE_HILLS="M4.5 17.5l4.5-6 3 4 2.5-3 5 5z";static PIN="M12 21.5s-6.5-5.7-6.5-10.8a6.5 6.5 0 0 1 13 0c0 5.1-6.5 10.8-6.5 10.8z";static PIN_HOLE="M12 8.4a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8z";static MILESTONES_OFF=Qt.outline(Qt.BOOKMARK);static MILESTONES_ON=Qt.solid(Qt.BOOKMARK);static PICTURES_OFF=Qt.outline(`${Qt.PICTURE}${Qt.PICTURE_HILLS}`);static PICTURES_ON=Qt.solid(`${Qt.PICTURE}${Qt.PICTURE_HILLS}`);static TRACE_LINE="M3 19.5l2.2-2.2 1.4 1.4L4.4 20.9zM8 14.5l2.2-2.2 1.4 1.4-2.2 2.2zM13 9.5l2.2-2.2 1.4 1.4-2.2 2.2z";static TRACE_MARK="M18.5 2.5l3.5 3.5-3.5 3.5-3.5-3.5z";static TRACES_OFF=Qt.outline(`${Qt.TRACE_LINE}${Qt.TRACE_MARK}`);static TRACES_ON=Qt.solid(`${Qt.TRACE_LINE}${Qt.TRACE_MARK}`);static MAP_OFF=Qt.outline(`${Qt.PIN}${Qt.PIN_HOLE}`);static MAP_ON=Qt.solid(`${Qt.PIN}${Qt.PIN_HOLE}`);static SHARE=Qt.outline("M14 4l7 7-7 7v-4.2C8.6 13.8 5.4 15.6 3.5 19c.6-5.6 3.4-9.6 10.5-10.8V4z");static FOLDED=Qt.svg("M15.4 7.4 14 6l-6 6 6 6 1.4-1.4L10.8 12z");static UNFOLDED=Qt.svg("M8.6 16.6 10 18l6-6-6-6-1.4 1.4 4.6 4.6z");static PLAY=Qt.svg("M7.4 5v14l11-7z");static PAUSE=Qt.svg("M6 5h4v14H6zM14 5h4v14h-4z");static VOLUME=Qt.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zm12.5 2.5A4 4 0 0 0 12.5 8.5v7A4 4 0 0 0 14.5 12zM12.5 4.2v2.1a6.5 6.5 0 0 1 0 11.4v2.1a8.6 8.6 0 0 0 0-15.6z");static MUTED=Qt.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zM15 9.8l1.4-1.4 2.6 2.6 2.6-2.6 1.4 1.4-2.6 2.6 2.6 2.6-1.4 1.4-2.6-2.6-2.6 2.6-1.4-1.4 2.6-2.6z");static ENTER_FULLSCREEN=Qt.svg("M5 5h5v2H7v3H5V5zm9 0h5v5h-2V7h-3V5zM5 14h2v3h3v2H5v-5zm12 0h2v5h-5v-2h3v-3z");static EXIT_FULLSCREEN=Qt.svg("M8 5h2v5H5V8h3V5zm6 0h2v3h3v2h-5V5zM5 14h5v5H8v-3H5v-2zm9 0h5v2h-3v3h-2v-5z")}class Hr{static KINDS=["beams","launches","reentries"];static statedKinds(t){return Object.keys(t??{}).filter(e=>Array.isArray(t[e])&&t[e].length>0)}static isEmpty(t){return Hr.statedKinds(t).length===0}static written(t){const e=Hr.statedKinds(t);if(e.length===0)return;const i={};for(const n of e)i[n]=t[n];return i}static read(t,e){const i=e,n={};for(const r of Hr.statedKinds(t))n[r]=t[r];for(const r of Hr.KINDS){const a=[...t?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=e;if(i&&Hr.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:c,...l}=i;s=Hr.isReading(l)?l:void 0}return{skyEvents:Hr.written(n),interpretation:s}}static isReading(t){return(t.bodies?.length??0)>0||t.title!==void 0||(t.smoke?.length??0)>0}}function Du(o){return[...o].sort((t,e)=>t.t-e.t)}function sm(o,t){let e;for(const i of Du(o)){if(i.t>t)break;e=i}return e}const rm=Math.PI/180,Jd=180/Math.PI;class na{constructor(t,e,i){this.kind=t,this.canvasHeightPx=e,this.fovDeg=i;const n=i*rm/2;this.focalPx=t==="equidistant"?e/2/n:e/2/Math.tan(n)}focalPx;static of(t,e,i){return new na(t.projection,e,i)}degToPx(t){const e=t*rm;return this.kind==="equidistant"?this.focalPx*e:2*this.focalPx*Math.tan(e/2)}pxToDeg(t){return this.kind==="equidistant"?t/this.focalPx*Jd:2*Math.atan(t/(2*this.focalPx))*Jd}angleDegToRadiusPx(t){const e=t*rm;return this.kind==="equidistant"?this.focalPx*e:this.focalPx*Math.tan(e)}halfWidthAngleDeg(t){return this.radiusPxToAngleDeg(this.canvasHeightPx*t/2)}radiusPxToAngleDeg(t){return this.kind==="equidistant"?t/this.focalPx*Jd:Math.atan(t/this.focalPx)*Jd}ofBounds(t){return{widthDeg:this.pxToDeg(t.width),heightDeg:this.pxToDeg(t.height)}}toBoundsSize(t){return{width:this.degToPx(t.widthDeg),height:this.degToPx(t.heightDeg)}}widthPx(t){return this.degToPx(hi.angularWidthDeg(t))}}class dn{static fovOf(t,e){return Be(t,e)?.fovDeg??Xi.fieldOfViewDeg(t.instrument)}static toAngular(t){this.eachKeyframe(t,(e,i)=>{const n=i.ofBounds(e.bounds);return e.angular?.widthDeg===n.widthDeg&&e.angular.heightDeg===n.heightDeg?e:{...e,angular:n}})}static toBounds(t){this.eachKeyframe(t,(e,i)=>this.sizedFromAngle(e,i))}static sizedFromAngle(t,e){if(!t.angular)return t;const{width:i,height:n}=e.toBoundsSize(t.angular),s={x:t.bounds.x+(t.bounds.width-i)/2,y:t.bounds.y+(t.bounds.height-n)/2,width:i,height:n};if(t.kind!=="polygon")return{...t,bounds:s};const r=t.bounds.width===0?1:i/t.bounds.width,a=t.bounds.height===0?1:n/t.bounds.height;return{...t,bounds:s,points:t.points.map(c=>({x:c.x*r,y:c.y*a}))}}static toAim(t){this.eachKeyframe(t,(e,i,n)=>{const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);if(s&&Math.abs(s.x-e.bounds.x)<dn.UNMOVED_PX&&Math.abs(s.y-e.bounds.y)<dn.UNMOVED_PX)return e;const r=this.aimFrom(t,i,n,e.bounds);return r?{...e,aim:r}:e})}static UNMOVED_PX=.01;static aimOf(t,e,i){const n=na.of(t.instrument,hi.CANVAS_HEIGHT_PX,this.fovOf(t,e));return this.aimFrom(t,n,Be(t,e),i)}static aimFrom(t,e,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(t),r=e.radiusPxToAngleDeg(n.x+n.width/2-s.x),a=e.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+a}}static toPosition(t){this.eachKeyframe(t,(e,i,n)=>this.placedByAim(t,e,i,n))}static placedByAim(t,e,i,n){const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);return s?{...e,bounds:{...e.bounds,...s}}:e}static derivable(t){const e=new Set,i=new Map,n=new Map;return t.timeline.allKeyframes.forEach((s,r)=>{const a=Be(t,s.t),c=na.of(t.instrument,hi.CANVAS_HEIGHT_PX,this.fovOf(t,s.t));for(const{sourceId:l,shape:h}of s.shapes){const u=n.get(l),d=i.get(l);if(n.set(l,h),!u||!d){i.set(l,h);continue}const f=Object.fromEntries(Object.entries(h).filter(([g,M])=>g!=="bounds"&&g!=="points"&&JSON.stringify(M)!==JSON.stringify(u[g]))),p={...d,...f},m=this.placedByAim(t,this.sizedFromAngle(p,c),c,a);dn.near(m,h)?(e.add(`${r}:${l}`),i.set(l,p)):i.set(l,h)}}),(s,r)=>e.has(`${s}:${r}`)}static SAME_PX=1e-6;static near(t,e){const i=(r,a)=>Math.abs(r-a)<=dn.SAME_PX*Math.max(1,Math.abs(a)),n=t.bounds,s=e.bounds;return!i(n.x,s.x)||!i(n.y,s.y)||!i(n.width,s.width)||!i(n.height,s.height)?!1:e.kind!=="polygon"||t.kind!=="polygon"?!0:t.points.length===e.points.length&&t.points.every((r,a)=>i(r.x,e.points[a].x)&&i(r.y,e.points[a].y))}static positionOf(t,e,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(t),a=this.shortestArc(e.azimuthDeg-s.headingDeg),c=e.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,a)-i.width/2,y:r.y-this.offAxisPx(n,c)-i.height/2}}static frameCentre(t){return{x:Xi.frameWidthPx(t.instrument,hi.CANVAS_HEIGHT_PX)/2,y:hi.CANVAS_HEIGHT_PX/2}}static shortestArc(t){return(t%360+540)%360-180}static offAxisPx(t,e){return Math.abs(e)>=dn.OFF_CANVAS_DEG?Math.sign(e)*dn.OFF_CANVAS_PX:t.angleDegToRadiusPx(e)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(t,e,i){const n=Xi.frameWidthPx(e,hi.CANVAS_HEIGHT_PX)/2,s=Xi.frameWidthPx(t.instrument,hi.CANVAS_HEIGHT_PX)/2,r=hi.CANVAS_HEIGHT_PX/2;for(const a of[...t.timeline.allKeyframes]){const c=this.fovOf(t,a.t),l=i?.get(a.t)??c,h=na.of(e,hi.CANVAS_HEIGHT_PX,l),u=na.of(t.instrument,hi.CANVAS_HEIGHT_PX,c);t.timeline.addKeyframe(a.t,a.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,m=f.y+f.height/2-r,g=Math.hypot(p,m),M=g===0?1:u.angleDegToRadiusPx(h.radiusPxToAngleDeg(g))/g,v={...f,x:s+p*M-f.width/2,y:r+m*M-f.height/2};return{...d,shape:{...d.shape,bounds:v}}}))}this.toBounds(t)}static eachKeyframe(t,e){const{timeline:i}=t;for(const n of[...i.allKeyframes]){const s=Be(t,n.t),r=this.fovOf(t,n.t),a=na.of(t.instrument,hi.CANVAS_HEIGHT_PX,r);let c=!1;const l=n.shapes.map(h=>{const u=e(h.shape,a,s);return u===h.shape?h:(c=!0,{...h,shape:u})});c&&i.addKeyframe(n.t,l)}}}class hs{static isRelative(t){return t!==void 0&&typeof t.eastM=="number"&&typeof t.northM=="number"}static isAbsolute(t){return t!==void 0&&typeof t.lat=="number"&&typeof t.lng=="number"}static referenceOf(t,e){return e.references.find(i=>(i.id??void 0)===(t.relativeTo??void 0))}static resolve(t,e){if(hs.isRelative(t)){const i=hs.referenceOf(t,e);return i?{eastM:i.eastM+t.eastM,northM:i.northM+t.northM}:void 0}return hs.isAbsolute(t)&&e.origin?hs.toLocal(t,e.origin):void 0}static restated(t,e,i){if(hs.isRelative(t)){const s=hs.referenceOf(t,i);return s?hs.relative(e.eastM-s.eastM,e.northM-s.northM,t.relativeTo):void 0}if(!i.origin)return t;const n=hs.toGeo(e,i.origin);return{lat:hs.degrees(n.lat),lng:hs.degrees(n.lng)}}static relative(t,e,i){const n={eastM:hs.metres(t),northM:hs.metres(e)};return i!==void 0&&(n.relativeTo=i),n}static toLocal(t,e){const i=ae(t.lat,t.lng,e.lat,e.lng);return{eastM:i.x,northM:-i.z}}static toGeo(t,e){return Is(t.eastM,-t.northM,e.lat,e.lng)}static metres(t){return Math.round(t*100)/100}static degrees(t){return Math.round(t*1e7)/1e7}}class qn{static restatedDecor(t){const e=qn.originOf(t);return t.decor.map(i=>{let n=i;if(i.saidPosition){const s=qn.restated(i.saidPosition,i,qn.frameAt(t,0,e,i.id));JSON.stringify(s)!==JSON.stringify(i.saidPosition)&&(n={...i,saidPosition:s},s||delete n.saidPosition)}if(i.track?.some(s=>s.saidPosition)){const s=i.track.map(r=>{if(!r.saidPosition)return r;const a=qn.restated(r.saidPosition,r,qn.frameAt(t,r.t,e,i.id));if(JSON.stringify(a)===JSON.stringify(r.saidPosition))return r;const c={...r,saidPosition:a};return a||delete c.saidPosition,c});n={...n,track:s}}return n})}static restatedObserverTrack(t){const e=t.observerTrack.toJSON(),i=qn.originOf(t);return!i||!e.keyframes.some(n=>n.pose.saidPosition)?e:{...e,keyframes:e.keyframes.map(n=>{const{pose:s}=n;if(!s.saidPosition||s.lat===void 0||s.lng===void 0)return n;const r=hs.toLocal({lat:s.lat,lng:s.lng},i),a=qn.restated(s.saidPosition,r,qn.frameAt(t,n.t,i));if(JSON.stringify(a)===JSON.stringify(s.saidPosition))return n;const c={...s,saidPosition:a};return a||delete c.saidPosition,{...n,pose:c}})}}static restatedInterpretation(t){const e=t.interpretation;if(!e?.bodies.some(n=>n.track.some(s=>s.saidPosition)))return e;const i=qn.originOf(t);return{...e,bodies:e.bodies.map(n=>n.track.some(s=>s.saidPosition)?{...n,track:n.track.map(s=>{if(!s.saidPosition)return s;const r=s.eastM!==void 0&&s.northM!==void 0?qn.restated(s.saidPosition,{eastM:s.eastM,northM:s.northM},qn.frameAt(t,s.t,i)):void 0;if(JSON.stringify(r)===JSON.stringify(s.saidPosition))return s;const a={...s,saidPosition:r};return r||delete a.saidPosition,a})}:n)}}static originOf(t){const e=t.observerTrack.getInterpolatedPoseAt(0),i=t.event.place?.[0],n=e?.lat??i?.lat,s=e?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}static frameAt(t,e,i,n){const s=[{label:"",eastM:0,northM:0},...t.decor.filter(r=>r.id!==n).map(r=>{const{eastM:a,northM:c}=oa(r,e);return{id:r.id,label:r.id,eastM:a,northM:c}})];return{origin:i,references:s}}static restated(t,e,i){return hs.restated(t,{eastM:e.eastM,northM:e.northM},i)}}class S_ extends Error{constructor(t,e,i){super(typeof e=="number"&&Number.isInteger(e)&&e>i?`This ${t} file is in version ${e} of its format; this UFO@home reads up to version ${i}. Read it with a newer UFO@home.`:`This ${t} file states ${JSON.stringify(e)} as its format version, which is not a version.`),this.format=t,this.found=e,this.supported=i,this.name="FormatVersionError"}said(t){return t.replace("{found}",typeof this.found=="number"?String(this.found):JSON.stringify(this.found)).replace("{supported}",String(this.supported))}}class Gl{static CURRENT={sighting:4,case:1,interview:1};static SCHEMA_BASE="https://ufoathome.org/schema";static schemaUrl(t,e=Gl.CURRENT[t]){return`${Gl.SCHEMA_BASE}/${e}/${t}.schema.json`}static of(t){if(typeof t!="object"||t===null)return 1;const e=t.version;return e===void 0?1:typeof e=="object"&&e!==null&&"value"in e?e.value:e}static check(t,e){const i=Gl.of(t),n=Gl.CURRENT[e];if(typeof i!="number"||!Number.isInteger(i)||i<1||i>n)throw new S_(e,i,n);return t}}class ai{constructor(t,e,i){this.params=t,this.from=e,this.origin=t.path[0],this.cos0=Math.cos(t.path[0].lat*Math.PI/180),this.points=t.path.map(r=>this.local(r)),this.cumulative=[0];for(let r=1;r<this.points.length;r++){const a=this.points[r-1],c=this.points[r];this.cumulative.push(this.cumulative[r-1]+Math.hypot(c.e-a.e,c.n-a.n))}this.distances=[];let n=0;for(let r=e;r<=i+ai.BEYOND_MS;r+=ai.STEP_MS)this.distances.push(n),n+=this.speedAt(r)*ai.STEP_MS/1e3;this.shift=this.project(this.local(t.through))-this.distanceAt(t.through.t);const s=[];for(let r=e;r<=i;r+=ai.SAMPLE_MS)s.push({t:r,place:this.placeAt(r)});this.sampleOrigin=s[0].place,this.sampleCos=Math.cos(this.sampleOrigin.lat*Math.PI/180),this.samples=s.map(({t:r,place:a})=>({t:r,e:(a.lng-this.sampleOrigin.lng)*Math.PI/180*ai.R*this.sampleCos,n:(a.lat-this.sampleOrigin.lat)*Math.PI/180*ai.R}))}static R=63710088e-1;static STEP_MS=100;static SAMPLE_MS=2e3;static BEYOND_MS=8e4;origin;cos0;points;cumulative;distances;shift;samples;sampleOrigin;sampleCos;get start(){return this.sampleOrigin}stateAt(t){const e=this.samples,i=e.length-2;let n=0;for(;n<i&&e[n+1].t<t;)n++;const s=e[n],r=e[n+1],a=(t-s.t)/(r.t-s.t),c=p=>[n>0?p[n-1]:2*p[n]-p[n+1],p[n],p[n+1],n+2<p.length?p[n+2]:2*p[n+1]-p[n]],l=e.map(p=>p.e),h=e.map(p=>p.n),u=ai.catmull(c(l),a),d=ai.catmull(c(h),a),f=(Math.atan2(ai.slope(c(l),a),ai.slope(c(h),a))*180/Math.PI%360+360)%360;return{eastM:u,northM:d,roadDeg:f,lat:this.sampleOrigin.lat+d/ai.R*180/Math.PI,lng:this.sampleOrigin.lng+u/(ai.R*this.sampleCos)*180/Math.PI}}bearingAt(t,e){const i=this.local(this.placeAt(t)),n=this.local(e);return(Math.atan2(n.e-i.e,n.n-i.n)*180/Math.PI%360+360)%360}get sampleTimes(){return this.samples.map(t=>t.t)}placeAt(t){const e=this.along(this.distanceAt(t)+this.shift);return{lat:this.origin.lat+e.n/ai.R*180/Math.PI,lng:this.origin.lng+e.e/(ai.R*this.cos0)*180/Math.PI}}distanceAt(t){const e=Math.max(0,Math.min(this.distances.length-1,Math.round((t-this.from)/ai.STEP_MS)));return this.distances[e]}speedAt(t){const e=this.params.speedDivisors?ai.linear(this.params.speedDivisors.map(({t:i,divisor:n,step:s})=>({t:i,value:n,step:s})),t):1;return ai.linear(this.params.speeds.map(({t:i,kmh:n,step:s})=>({t:i,value:n,step:s})),t)/3.6/e}local(t){return{e:(t.lng-this.origin.lng)*Math.PI/180*ai.R*this.cos0,n:(t.lat-this.origin.lat)*Math.PI/180*ai.R}}along(t){const e=this.points;let i=0;for(;i<e.length-2&&this.cumulative[i+1]<t;)i++;const n=e[i],s=e[i+1],r=(t-this.cumulative[i])/(this.cumulative[i+1]-this.cumulative[i]);return{e:n.e+(s.e-n.e)*r,n:n.n+(s.n-n.n)*r}}project(t){let e=1/0,i=0;for(let n=0;n<this.points.length-1;n++){const s=this.points[n],r=this.points[n+1],a=r.e-s.e,c=r.n-s.n,l=Math.max(0,Math.min(1,((t.e-s.e)*a+(t.n-s.n)*c)/(a*a+c*c))),h=Math.hypot(s.e+a*l-t.e,s.n+c*l-t.n);h<e&&(e=h,i=this.cumulative[n]+l*Math.hypot(a,c))}return i}static linear(t,e){if(e<=t[0].t)return t[0].value;for(let i=0;i<t.length-1;i++){const n=t[i],s=t[i+1];if(s.step&&e<s.t)return n.value;if(e<=s.t)return n.value+(s.value-n.value)*(e-n.t)/(s.t-n.t)}return t[t.length-1].value}static catmull([t,e,i,n],s){return .5*(2*e+(i-t)*s+(2*t-5*e+4*i-n)*s*s+(3*e-t-3*i+n)*s**3)}static slope([t,e,i,n],s){return .5*(i-t+2*(2*t-5*e+4*i-n)*s+3*(3*e-t-3*i+n)*s*s)}}class je{constructor(t,e,i,n,s,r){this.drive=t,this.eye=e,this.lookAhead=i,this.lean=n,this.watch=s,this.times=t.sampleTimes;const a=i.pitchShare??1;this.aimed=[];for(const c of this.times){const l=t.bearingAt(c,i.target),h=this.aimed[this.aimed.length-1];this.aimed.push(h===void 0?l:h+je.signed(l-h))}this.pitched=this.times.map(c=>r(c)*a)}static STEP_MS=250;static DENSE_MS=50;static SETTLED_MS=700;static TURN_S=.4;static TURN_S_PER_DEG=.5/150;static ROAD_PITCH_DEG=-1;static SHOULDER={x:-.08,y:0,z:-.07};static TWIST_FROM_DEG=60;aimed;pitched;times;poses(t,e){const i=[];for(let u=t;u<e;u+=je.STEP_MS)i.push(u);i.push(e);const n=new Map(i.map(u=>{const d=this.sample(u);return[u,je.signed(d.headingDeg-d.roadDeg)]})),s=u=>n.get(i.reduce((d,f)=>Math.abs(f-u)<Math.abs(d-u)?f:d)),r=this.schedule(s,e),a=this.watch?.t,c=r.map(([u,d],f)=>{if(f===0)return 0;if(u===a&&this.lean)return this.lean.params.turnS;const p=this.sample(u);return je.turnS(this.target(r[f-1][1],p),this.target(d,p))}),l=new Set(i),h=r.map(([u],d)=>[u,c[d]]);this.lean&&h.push([this.lean.t,this.lean.params.turnS],[this.lean.t+this.lean.params.holdS*1e3,this.lean.params.turnS]);for(const[u,d]of h){const f=Math.round(u+d*1e3+je.SETTLED_MS)+je.DENSE_MS;for(let p=Math.round(u);p<f;p+=je.DENSE_MS)p>=t&&p<=e&&l.add(p)}return[...l].sort((u,d)=>u-d).map(u=>{const d=this.sample(u),[f,p]=this.gaze(r,c,d),m=this.drive.stateAt(u);return{t:u,headingDeg:f,pitchDeg:p,eye:this.eyeAt(u,je.signed(f-d.roadDeg)),roadDeg:m.roadDeg,lat:m.lat,lng:m.lng}})}schedule(t,e){const i=[],n=this.lookAhead,s=this.watch?.t??e;let r=0;for(;r<s;){if(Math.abs(t(r))<=n.glanceBeyondDeg){(i.length===0||i[i.length-1][1]!=="watch")&&i.push([r,"watch"]),r+=je.STEP_MS;continue}if(i.push([r,"glance"]),r+=n.glanceS*1e3,r>=s)break;i.push([r,"road"]),r+=n.roadS*1e3}if(!this.watch)return i;const a=this.watch.params;r=s,i.push([r,"mirror"]),r+=a.firstS*1e3;let c=0;for(;r<e;){const l=r<a.glancesUntil&&c%2===0?"glance":"road";i.push([r,l]),r+=(l==="glance"?a.glanceS:a.roadS)*1e3,i.push([r,"mirror"]),r+=a.mirrorS*1e3,c++}return i}sample(t){const e=this.times,i=e.length-2;let n=0;for(;n<i&&e[n+1]<t;)n++;const s=(t-e[n])/(e[n+1]-e[n]),r=a=>[n>0?a[n-1]:2*a[n]-a[n+1],a[n],a[n+1],n+2<a.length?a[n+2]:2*a[n+1]-a[n]];return{t,roadDeg:this.drive.stateAt(t).roadDeg,headingDeg:(ai.catmull(r(this.aimed),s)%360+360)%360,pitchDeg:ai.catmull(r(this.pitched),s),eye:this.eyeAt(t,0)}}target(t,e){const{roadDeg:i,headingDeg:n,pitchDeg:s,eye:r}=e;if(t==="glance")return[n,s];if(t==="watch"){const u=je.signed(n-i),d=this.lookAhead.keepDeg,f=u-d*Math.tanh(u/d),p=u?f/u:0;return[je.normalized(i+f),je.ROAD_PITCH_DEG+(s-je.ROAD_PITCH_DEG)*p]}if(t==="road"||!this.watch)return[i,je.ROAD_PITCH_DEG];const a=this.watch.params.mirror,c={x:a.x-r.x,y:a.y-r.y,z:a.z-r.z},l=Math.atan2(-c.x,-c.z)*180/Math.PI,h=Math.atan2(c.y,Math.hypot(c.x,c.z))*180/Math.PI;return[je.normalized(i-l),h]}gaze(t,e,i,n){const s=i.t;let r=n??0;if(n===void 0&&s>=t[0][0])for(let g=0;g<t.length;g++)t[g][0]<=s&&(r=g);const[a,c]=this.target(t[r][1],i);if(r===0)return[a,c];const l=e[r]*1e3,h=s-t[r][0];if(h>l+je.SETTLED_MS)return[a,c];const[u,d]=this.gaze(t,e,i,r-1);if(h<l){const g=h/l,M=-2*g**3+3*g*g+(g**3-g*g)*Mn.ARRIVAL;return[je.normalized(u+je.signed(a-u)*M),d+(c-d)*M]}const f=je.signed(a-u),p=h-l,m=Mn.ARRIVAL/l*p*Math.exp(-p/Math.min(Mn.SETTLE_MS,.4*l));return[je.normalized(a+f*m),c+(c-d)*m]}leanAt(t){if(!this.lean)return 0;const{holdS:e,turnS:i}=this.lean.params,n=(t-this.lean.t)/1e3;return n<0||n>e+i?0:je.smooth(Math.min(1,n/i,(e+i-n)/i))}eyeAt(t,e){const i=this.leanAt(t),n=this.lean?.params.offsetM??{x:0,y:0,z:0},s=je.smooth((Math.abs(e)-je.TWIST_FROM_DEG)/(180-je.TWIST_FROM_DEG)),r=je.SHOULDER;return{x:this.eye.x+n.x*i+r.x*s,y:this.eye.y+n.y*i+r.y*s,z:this.eye.z+n.z*i+r.z*s}}static turnS(t,e){return je.TURN_S+je.TURN_S_PER_DEG*Math.hypot(je.signed(e[0]-t[0]),e[1]-t[1])}static smooth(t){const e=Math.min(1,Math.max(0,t));return e*e*e*(10-15*e+6*e*e)}static signed(t){return((t+540)%360+360)%360-180}static normalized(t){return(t%360+360)%360}}const am=Math.PI/180;class Bt{constructor(t,e,i){this.body=t,this.ground=e,this.eyeAt=i;const n=[...t.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)Bt.collect(this.motionKeys,s.t,s.motions),Bt.collect(this.turnKeys,s.t,s.turns),Bt.collect(this.lightKeys,s.t,s.lights)}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,luminanceCdM2:0,transparency:0,haloScale:1};keys;motionKeys=new Map;turnKeys=new Map;lightKeys=new Map;static collect(t,e,i){for(const[n,s]of Object.entries(i??{})){const r=t.get(n)??[];r.push({t:e,value:s}),t.set(n,r)}}motionsAt(t){return Bt.channelsAt(this.motionKeys,t,0)}lightsAt(t){return this.lightKeys.size>0?Bt.channelsAt(this.lightKeys,t,void 0):void 0}static channelsAt(t,e,i){const n={};for(const[s,r]of t){let a=r.length-1;for(;a>=0&&r[a].t>e;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const c=r[a],l=r[Math.min(a+1,r.length-1)],h=l===c||l.t===c.t?0:Math.min(1,(e-c.t)/(l.t-c.t));n[s]=Bt.lerp(c.value,l.value,h)}return n}static eyeOf(t,e,i){const n=Be(t,0),s=Be(t,e),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ae(s.lat,s.lng,n.lat,n.lng):void 0,c=a?a.x:0,l=a?-a.z:0;return{eastM:c,northM:l,upM:i.heightAt(c,l)+Bt.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(t,e,i,n){const s=Bt.directionOf(e,i),r=l=>t.upM+s.upM*l-n.heightAt(t.eastM+s.eastM*l,t.northM+s.northM*l);let a=0,c=0;for(;c<Bt.MAX_RANGE_M;){if(c=a+Math.max(.5,a*.01),r(c)<=0){for(let l=0;l<30;l++){const h=(a+c)/2;r(h)<=0?c=h:a=h}return c}a=c}}static directionOf(t,e){const i=t*am,n=e*am;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(t){const e=this.keys;if(e.length===0||t<e[0].t)return;let i=0,n=e.length-1;for(;i<n;){const m=i+n+1>>1;e[m].t>t?n=m-1:i=m}const s=i,r=e[s];if(!r.present)return;const a=e[Math.min(s+1,e.length-1)],c=a===r||a.t===r.t?0:Math.min(1,(t-r.t)/(a.t-r.t)),l=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(t):void 0,h=l?l.eastM+Bt.lerp(r.carried.eastM,a.carried.eastM,c):Bt.lerp(r.eastM,a.eastM,c),u=l?l.northM+Bt.lerp(r.carried.northM,a.carried.northM,c):Bt.lerp(r.northM,a.northM,c),d={widthM:Bt.lerp(r.sizeM.widthM,a.sizeM.widthM,c),lengthM:Bt.lerp(r.sizeM.lengthM,a.sizeM.lengthM,c),heightM:Bt.lerp(r.sizeM.heightM,a.sizeM.heightM,c)},f={headingDeg:Bt.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,c),pitchDeg:Bt.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,c),rollDeg:Bt.lerp(r.attitude.rollDeg,a.attitude.rollDeg,c)};let p;if(l)p=l.upM+Bt.lerp(r.carried.upM,a.carried.upM,c);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const m=Bt.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,c);p=this.groundUnderFootprint(h,u,d,f.headingDeg)+m+d.heightM/2}else p=Bt.lerp(this.centreUpOf(r),this.centreUpOf(a),c);return{id:this.body.id,model:this.body.model,modelParameters:this.body.modelParameters,flicker:this.body.flicker,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:h,northM:u,upM:p,sizeM:d,attitude:f,appearance:{color:Bt.lerpColor(r.appearance.color,a.appearance.color,c),albedo:Bt.lerp(r.appearance.albedo,a.appearance.albedo,c),luminanceCdM2:Bt.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,c),transparency:Bt.lerp(r.appearance.transparency,a.appearance.transparency,c),haloScale:Bt.lerp(r.appearance.haloScale,a.appearance.haloScale,c)},flame:Bt.flameBetween(r.flame,a.flame,c),motions:this.motionsAt(t),...this.turnKeys.size>0?{turns:Bt.channelsAt(this.turnKeys,t,0)}:{},lights:this.lightsAt(t),throwsFlame:this.body.track.some(m=>m.flame!==void 0&&m.flame.luminanceCdM2>0)}}static flameBetween(t,e,i){if(!t||t.luminanceCdM2<=0)return i>=1&&e&&e.luminanceCdM2>0?e:void 0;const n=t,s=e??t,r={...i<1?n:s,lengthM:Bt.lerp(n.lengthM,s.lengthM,i),widthM:Bt.lerp(n.widthM,s.widthM,i),luminanceCdM2:Bt.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(t){if(!("upM"in t.vertical))return this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.vertical.aboveGroundM+t.sizeM.heightM/2;const e=t.vertical.fromGround;if(!e)return t.vertical.upM;const i=t.vertical.upM+this.ground.heightAt(e.eastM,e.northM);return Math.max(i,this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.sizeM.heightM/2)}groundUnderFootprint(t,e,i,n){const s=n*am,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let c=this.ground.heightAt(t,e);for(const[l,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const u=l*i.widthM/2,d=h*i.lengthM/2;c=Math.max(c,this.ground.heightAt(t+r.eastM*u+a.eastM*d,e+r.northM*u+a.northM*d))}return c}place(t,e){const i=[];let n;for(const s of t){const r=s.sizeM??n?.sizeM??Bt.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},c={color:s.appearance?.color??n?.appearance.color??Bt.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??Bt.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??Bt.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??Bt.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??Bt.DEFAULT_APPEARANCE.haloScale},l=this.positionOf(s,r,e)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!l)continue;const h=s.flame??n?.flame,u=s.present??n?.present??!0;if(n={t:s.t,...l,sizeM:r,attitude:a,appearance:c,flame:h,present:u},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const d=Bt.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:d.eastM*s.distanceM,northM:d.northM*s.distanceM,upM:d.upM*s.distanceM}}i.push(n)}return i}verticalOf(t,e){if(t.onGround)return{aboveGroundM:0};if(t.altitudeAboveGroundM!==void 0)return{aboveGroundM:t.altitudeAboveGroundM};if(t.altitudeM!==void 0)return{upM:t.altitudeM+e.heightM/2,fromGround:this.body.altitudeFrom}}positionOf(t,e,i){if(t.eastM!==void 0&&t.northM!==void 0)return{eastM:t.eastM,northM:t.northM,vertical:this.verticalOf(t,e)??{aboveGroundM:0}};if(t.azimuthDeg===void 0||t.altitudeDeg===void 0)return;const n=i(t.t);if(!n)return;const s=t.distanceM??(t.onGround?Bt.lineOfSightMeetsGround(n,t.azimuthDeg,t.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=Bt.directionOf(t.azimuthDeg,t.altitudeDeg),a=n.eastM+r.eastM*s,c=n.northM+r.northM*s;return{eastM:a,northM:c,vertical:this.verticalOf(t,e)??{upM:n.upM+r.upM*s}}}static lerp(t,e,i){return t+(e-t)*i}static lerpColor(t,e,i){const n=Bt.rgbOf(t),s=Bt.rgbOf(e);return!n||!s?i<1?t:e:"#"+n.map((r,a)=>Math.round(Bt.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(!e)return;const i=e[1].length===3?e[1].replace(/./g,"$&$&"):e[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(t,e,i){const n=((e-t)%360+540)%360-180;return((t+n*i)%360+360)%360}}class As{static ANONYMOUS_OBSERVER="observer";static observerId(t){return t.observer?.id??As.ANONYMOUS_OBSERVER}static shapeIds(t){const e=new Set(t.timeline.sourceIds);for(const i of t.events??[])if(i.eventType==="appearance")for(const n of i.params?.parts??[])e.add(n.sourceId);return[...e]}static ids(t){const e=new Map,i=(n,s)=>{n!==void 0&&e.set(n,[...e.get(n)??[],s])};i(As.observerId(t),"observer");for(const n of As.shapeIds(t))i(n,"shape");for(const n of t.timeline.allGroups)i(n.id,"group");for(const n of t.interpretation?.bodies??[])i(n.id,"body");for(const n of t.decor)i(n.id,"decor");return e}static kindOf(t,e){if(e===void 0)return;const i=As.ids(t).get(e);return i?.length===1?i[0]:void 0}static partOf(t){const e=t?.indexOf("/")??-1;if(!(t===void 0||e<=0||e===t.length-1))return{element:t.slice(0,e),part:t.slice(e+1)}}static hasPart(t,e,i){if(e==="body")return!0;if(e!=="decor")return!1;const n=t.decor.find(s=>s.id===i.element);return!!(n?.lights?.some(s=>s.id===i.part)||n?.groups?.some(s=>s.id===i.part))}static isObserver(t,e){return e.who===As.observerId(t)}static isPhenomenon(t,e){return e.who===void 0?!1:t.timeline.groupOf(e.who)!==void 0||As.shapeIds(t).includes(e.who)}static within(t,e){const i=new Set([e]),n=s=>{for(const r of t.timeline.groupOf(s)?.members??[])i.has(r)||(i.add(r),n(r))};return n(e),i}static renamed(t,e,i){if(e!==i)for(const n of t.events??[])n.who===e&&(n.who=i)}static issues(t){const e=[],i=As.ids(t);for(const[n,s]of i)s.length>1&&e.push({kind:"duplicate-id",id:n,path:s.join(", ")});return(t.events??[]).forEach((n,s)=>{const r=As.partOf(n.who);r&&i.get(r.element)?.length===1&&As.hasPart(t,i.get(r.element)[0],r)||(n.who===void 0||!i.has(n.who))&&e.push({kind:"unknown-who",id:n.who??"",path:`events.${s}.who`})}),e}}class xe{constructor(t,e,i){this.travel=t;const n=t.params,s=t.until??i;let r=xe.unit(n.from),a=xe.towards(r,xe.unit(n.towards));const c=e.map(h=>{const u=h.params,d=u.side==="left"?1:-1;return{from:h.t,to:h.until??h.t,radians:u.byDeg*Math.PI/180*(u.seenFrom==="craft"?-d:d)}}),l=xe.STEP_MS;for(let h=t.t;h<=s;h+=l){this.directions.push(xe.direction(r));for(const f of c){const p=f.to-f.from;if(p<=0)continue;const m=f.radians*(xe.smooth((h+l-f.from)/p)-xe.smooth((h-f.from)/p));m&&(a=xe.add(xe.scale(a,Math.cos(m)),xe.scale(xe.cross(a,r),Math.sin(m))))}const u=xe.speedAt(n.speeds,h)*l/1e3*Math.PI/180,d=xe.add(xe.scale(r,Math.cos(u)),xe.scale(a,Math.sin(u)));a=xe.add(xe.scale(a,Math.cos(u)),xe.scale(r,-Math.sin(u))),r=d}}static STEP_MS=5;directions=[];at(t){const e=Math.round((t-this.travel.t)/xe.STEP_MS);return this.directions[Math.max(0,Math.min(this.directions.length-1,e))]}sizeAt(t){const e=this.travel.params;return e.sizeBy!=="altitude"?e.sizeDeg:e.sizeDeg*Math.max(.1,Math.sin(Math.max(this.at(t).altitudeDeg,1)*Math.PI/180))}static speedAt(t,e){if(t.length===0)return 0;if(e<=t[0].t)return t[0].degPerS;for(let i=1;i<t.length;i++){const n=t[i-1],s=t[i];if(s.step&&e<s.t)return n.degPerS;if(e<s.t)return n.degPerS+(s.degPerS-n.degPerS)*xe.smooth((e-n.t)/(s.t-n.t))}return t[t.length-1].degPerS}static smooth(t){const e=Math.max(0,Math.min(1,t));return e*e*(3-2*e)}static unit(t){const e=t.azimuthDeg*Math.PI/180,i=t.altitudeDeg*Math.PI/180;return[Math.cos(i)*Math.sin(e),Math.cos(i)*Math.cos(e),Math.sin(i)]}static direction(t){return{azimuthDeg:(Math.atan2(t[0],t[1])*180/Math.PI%360+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,t[2])))*180/Math.PI}}static towards(t,e){const i=xe.add(e,xe.scale(t,-xe.dot(t,e))),n=Math.hypot(...i)||1;return xe.scale(i,1/n)}static toScreen(t,e,i){const[n,s,r]=xe.basis(e,i),a=xe.unit(t),c=xe.dot(a,n);return[xe.dot(a,s)/c,xe.dot(a,r)/c]}static fromScreen(t,e,i,n){const[s,r,a]=xe.basis(i,n),c=[s[0]+t*r[0]+e*a[0],s[1]+t*r[1]+e*a[1],s[2]+t*r[2]+e*a[2]],l=Math.hypot(...c);return xe.direction([c[0]/l,c[1]/l,c[2]/l])}static basis(t,e){const i=t*Math.PI/180,n=e*Math.PI/180;return[[Math.cos(n)*Math.sin(i),Math.cos(n)*Math.cos(i),Math.sin(n)],[Math.cos(i),-Math.sin(i),0],[-Math.sin(n)*Math.sin(i),-Math.sin(n)*Math.cos(i),Math.cos(n)]]}static dot(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}static cross(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}static add(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}static scale(t,e){return[t[0]*e,t[1]*e,t[2]*e]}}class yo{constructor(t,e){this.sighting=t,this.events=e}static FOV_DEG=60;keyframes(){const t=this.events.filter(c=>c.eventType==="look").sort((c,l)=>c.t-l.t),e=this.events.filter(c=>c.eventType==="walk").sort((c,l)=>c.t-l.t),i=this.events.filter(c=>c.eventType==="follow").sort((c,l)=>c.t-l.t);if(t.length===0&&e.length===0)return[];const n=new Set([0]);for(const c of[...t,...e,...i])n.add(c.t),c.until!==void 0&&n.add(c.until);const s=c=>{let l;for(const h of e){const u=h.params;if(c<=h.t)return l??u.from;if(h.until===void 0||c>=h.until)l=u.to;else return}return l??this.sighting.event.place?.[0]},r=c=>([...t].reverse().find(h=>h.t<=c)??t[0])?.params??{headingDeg:0,pitchDeg:0},a=[...n].sort((c,l)=>c-l).flatMap(c=>{const l=s(c);if(!l)return[];const h=r(c);return[{t:c,pose:yo.pose(l,h.headingDeg,h.pitchDeg,h.fovDeg)}]});for(const c of a)this.sighting.observerTrack.addKeyframe(c.t,c.pose);for(const c of i)this.follow(c,r(c.t));return[...this.sighting.observerTrack.allKeyframes]}follow(t,e){const i=t.params;if(this.followSky(t,e))return;const n=this.sighting.interpretation?.bodies.find(h=>h.id===i.target);if(!n)return;const s={heightAt:()=>0},r=h=>Bt.eyeOf(this.sighting,h,s),a=new Bt(n,s,r),c=t.until??1/0;let l=e;for(const h of n.track){if(h.t<=t.t||h.t>=c)continue;const u=a.at(h.t),d=r(h.t),f=this.sighting.observerTrack.getInterpolatedPoseAt(h.t);if(!u||!d||!f)continue;const p=u.eastM-d.eastM,m=u.northM-d.northM,g=u.upM-d.upM;l={headingDeg:(Math.atan2(p,m)*180/Math.PI%360+360)%360,pitchDeg:Math.atan2(g,Math.hypot(p,m))*180/Math.PI},this.sighting.observerTrack.addKeyframe(h.t,{...f,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}if(Number.isFinite(c)){const h=this.sighting.observerTrack.getInterpolatedPoseAt(c);h&&this.sighting.observerTrack.addKeyframe(c,{...h,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}}static FOLLOW_SKY_MS=25;static CATCH_UP_MS=900;static OVERHEAD_DEG=78;static HIGHEST_PITCH_DEG=88;followSky(t,e){const i=t.params,n=As.within(this.sighting,i.target),s=this.sighting.events??[],r=s.find(M=>M.eventType==="travel"&&M.who!==void 0&&n.has(M.who));if(!r)return!1;const a=this.sighting.event.durationSeconds!==void 0?this.sighting.event.durationSeconds*1e3:r.until??t.t,c=new xe(r,s.filter(M=>M.eventType==="turn"&&M.who!==void 0&&n.has(M.who)),a),l=t.until??a,h=(i.lagS??0)*1e3,u=(i.reactionS??0)*1e3,d=[],f=this.sighting.sampleMs??yo.FOLLOW_SKY_MS;for(let M=t.t;M<=l;M+=f)d.push(M);const p=d.map(M=>c.at(Math.max(r.t,M-h))),m=p.map(M=>M.azimuthDeg),g=p.flatMap((M,v)=>M.altitudeDeg>yo.OVERHEAD_DEG?[v]:[]);if(g.length>0){const M=Math.max(0,g[0]-1),v=Math.min(d.length-1,g[g.length-1]+1),x=m[M],y=(m[v]-x+540)%360-180;for(let w=M;w<=v;w++)m[w]=((x+y*xe.smooth((w-M)/(v-M)))%360+360)%360}return d.forEach((M,v)=>{const x=xe.smooth((M-t.t-u)/yo.CATCH_UP_MS),y=(m[v]-e.headingDeg+540)%360-180,w=Math.min(p[v].altitudeDeg,yo.HIGHEST_PITCH_DEG),b=this.sighting.observerTrack.getInterpolatedPoseAt(M)??this.sighting.observerTrack.getLatestPoseAt(M);if(!b)return;const E=S=>Math.round(S*100)/100;this.sighting.observerTrack.addKeyframe(M,{...b,headingDeg:E(((e.headingDeg+y*x)%360+360)%360),pitchDeg:E(e.pitchDeg+(w-e.pitchDeg)*x)})}),!0}static pose(t,e,i,n=yo.FOV_DEG){return{lat:t.lat,lng:t.lng,elevationM:0,headingDeg:e,pitchDeg:i,fovDeg:n}}}class ko{constructor(t,e,i,n){this.body=t,this.events=e,this.endMs=i,this.sampleMs=n}static SAMPLE_MS=250;track(){const t=new Map,e=l=>{const h=t.get(l.t);t.set(l.t,h?{...h,...l,motions:{...h.motions,...l.motions},...h.turns||l.turns?{turns:{...h.turns,...l.turns}}:{},...h.lights||l.lights?{lights:{...h.lights,...l.lights}}:{}}:l)};for(const l of this.body.track)e({...l});const i=[...this.events].sort((l,h)=>l.t-h.t),n=new Map,s=new Map,r=new Map;let a=0;for(const l of this.body.track){for(const[h,u]of Object.entries(l.motions??{}))n.set(h,u);for(const[h,u]of Object.entries(l.turns??{}))s.set(h,u);for(const[h,u]of Object.entries(l.lights??{}))r.set(h,u);l.attitude?.headingDeg!==void 0&&(a=l.attitude.headingDeg)}let c=this.startPlace();for(const l of i){const h=ko.partOf(l.who,this.body.id);if(h!==void 0&&(l.eventType==="light"||l.eventType==="blink")){for(const u of this.leavesOf(h))this.switchLight(u,l,r,e,d=>t.get(d)?.lights?.[u]);continue}if(h!==void 0){if(l.eventType!=="spin"&&l.eventType!=="turn")continue;const u=s.get(h)??0,d=l.until??l.t,f=l.eventType==="spin"?u+360*l.params.turnsPerS*(d-l.t)/1e3:l.params.headingDeg;e({t:l.t,turns:{[h]:u}}),e({t:d,turns:{[h]:f}}),s.set(h,f);continue}if((l.eventType==="motion"||l.eventType==="spin")&&l.params?.motion){const u=l.params,d=u.motion,f=n.get(d)??0,p=l.until??l.t,m=l.eventType==="motion"?u.to:f+u.turnsPerS*(p-l.t)/1e3;e({t:l.t,motions:{[d]:f}}),e({t:p,motions:{[d]:m}}),n.set(d,m)}else if(l.eventType==="rise"&&c){const u=l.params,d=l.until??l.t,f=u.angleDeg*Math.PI/180,p=(u.headingDeg??0)*Math.PI/180,m=c,g=M=>{const v=u.stops===!1?M*M:M*M*M*(10-15*M+6*M*M),x=u.distanceM*v;return{eastM:m.eastM+x*Math.sin(f)*Math.sin(p),northM:m.northM+x*Math.sin(f)*Math.cos(p),aboveGroundM:m.aboveGroundM+x*Math.cos(f)}};for(let M=l.t;M<d;M+=this.sampleMs??ko.SAMPLE_MS)e(ko.key(M,g((M-l.t)/(d-l.t))));c=g(1),e(ko.key(d,c))}else if(l.eventType==="turn"){const u=l.params;e({t:l.t,attitude:{headingDeg:a}}),e({t:l.until??l.t,attitude:{headingDeg:u.headingDeg}}),a=u.headingDeg}else l.eventType==="vanish"&&e({t:l.t,present:!1})}return[...t.values()].sort((l,h)=>l.t-h.t)}static ride(t,e,i){const n=e.params,s=e.until??1/0,r=new Map(t.track.map(a=>[a.t,{...a}]));for(const a of i.track){if(a.t<e.t||a.t>s||(a.present===!1&&r.set(a.t,{...r.get(a.t),t:a.t,present:!1}),a.eastM===void 0||a.northM===void 0))continue;const c=(a.onGround?0:a.altitudeAboveGroundM??0)+n.aboveM;r.set(a.t,{...r.get(a.t),t:a.t,eastM:a.eastM,northM:a.northM,altitudeAboveGroundM:c})}return[...r.values()].sort((a,c)=>a.t-c.t)}switchLight(t,e,i,n,s){const r=i.get(t)??0,a=e.eventType==="light"?e.until:e.until??this.endMs,c=(l,h)=>n({t:l,lights:{[t]:h}});if(e.t>0&&s(e.t-1)===void 0&&c(e.t-1,r),e.eventType==="light"){const l=e.params.cdM2;if(c(e.t,l),a===void 0){i.set(t,l);return}c(a-1,l)}else{const l=e.params;if(a===void 0)return;const h=l.cdM2??r;let u=e.t,d=!0;for(;u<a;){const f=Math.min(Math.round(u+1e3*(d?l.onS:l.offS)),a);if(f<=u)break;c(u,d?h:0),c(f-1,d?h:0),u=f,d=!d}}c(a,r),i.set(t,r)}leavesOf(t,e=new Set){const i=this.body.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}startPlace(){const t=this.body.track.find(e=>e.eastM!==void 0&&e.northM!==void 0);return t&&{eastM:t.eastM,northM:t.northM,aboveGroundM:t.onGround?0:t.altitudeAboveGroundM??0}}static key(t,e){return e.aboveGroundM<=0?{t,eastM:e.eastM,northM:e.northM,onGround:!0}:{t,eastM:e.eastM,northM:e.northM,altitudeAboveGroundM:e.aboveGroundM}}}class wd{constructor(t,e,i){this.object=t,this.events=e,this.endMs=i}lights(){const t=new Map,e=[...this.events].sort((i,n)=>i.t-n.t);for(const i of e){const n=wd.partOf(i.who,this.object.id);if(!(n===void 0||i.eventType!=="light"&&i.eventType!=="blink"))for(const s of this.leavesOf(n)){const r=this.object.lights?.find(a=>a.id===s);r&&t.set(s,this.switched(r,t.get(s)??[],i))}}return(this.object.lights??[]).map(i=>t.has(i.id)?{...i,keyframes:t.get(i.id)}:i)}switched(t,e,i){const n=wd.stateAt(t,e,i.t),s=i.eventType==="light"?i.until:i.until??this.endMs,r=[];if(i.eventType==="light")r.push({t:i.t,intensity:i.params.intensity,pattern:n.pattern});else{const c=i.params,l=c.onS+c.offS;if(s===void 0||l<=0)return e;const h=l*1e3,u=(-i.t/h%1+1)%1,d={kind:"flash",perMinute:60/l,dutyCycle:c.onS/l,...u?{phase:u}:{}},f=c.intensity??(n.intensity>0?n.intensity:t.intensity??1);r.push({t:i.t,intensity:f,pattern:d})}s!==void 0&&r.push({t:s,intensity:n.intensity,pattern:n.pattern});const a=new Set(r.map(c=>c.t));return[...e.filter(c=>!a.has(c.t)),...r].sort((c,l)=>c.t-l.t)}static stateAt(t,e,i){const n=e.filter(s=>s.t<=i).at(-1);return{intensity:n?.intensity??t.intensity??1,pattern:n?.pattern??t.pattern}}leavesOf(t,e=new Set){const i=this.object.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}}class dh{static observer(t){const e=t.allKeyframes,i=e.map(s=>dh.said(s.pose)),n=e.filter((s,r)=>r>0&&r<e.length-1&&i[r]===i[r-1]&&i[r]===i[r+1]);for(const s of n)t.removeKeyframeAt(s.t)}static said(t){return JSON.stringify(t,(e,i)=>typeof i=="number"?Math.round(i*1e10)/1e10:i)}static timeline(t){const e=new Map;for(const i of t.allKeyframes)for(const n of i.shapes){const s=e.get(n.sourceId)??[];s.push({t:i.t,said:dh.said(n.shape)}),e.set(n.sourceId,s)}for(const[i,n]of e){const s=n.filter((r,a)=>a>0&&a<n.length-1&&r.said===n[a-1].said&&r.said===n[a+1].said);for(const r of s)t.removeShapeAt(r.t,i)}}}class U0{constructor(t,e){this.end=e;const i=[...t].sort((n,s)=>n.t-s.t);this.rolls=i.filter(n=>n.eventType==="roll"),this.vibrations=i.filter(n=>n.eventType==="vibrate"),this.spirals=i.filter(n=>n.eventType==="spiral")}static SPIRAL_OPENS=4;static THINNEST=.08;rolls;vibrations;spirals;rollAt(t){let e=0,i=0;for(const n of this.rolls){if(t<n.t)break;const s=n.params,r=this.progress(n,t);i=e+(s.toDeg-e)*(s.andBack?Math.sin(Math.PI*xe.smooth(r)):xe.smooth(r)),s.andBack||(e=s.toDeg)}for(const n of this.spirals){if(t<n.t)break;const s=n.params;i=e+(s.clockwise?1:-1)*s.rollDeg*this.progress(n,t)}return i}acrossShareAt(t){return Math.max(U0.THINNEST,Math.abs(Math.cos(this.rollAt(t)*Math.PI/180)))}sidewaysAt(t,e){let i=0;for(const n of this.vibrations){const s=n.until??this.end;if(t<n.t||t>=s)continue;const r=n.params,a=xe.smooth((t-n.t)/(r.riseS*1e3))*Math.max(0,1-(t-n.t)/(s-n.t));i+=r.amplitudeShare*e*a*Math.sin(2*Math.PI*r.hz*(t-n.t)/1e3)}return i}spiralAt(t){const e=[...this.spirals].reverse().find(a=>a.t<=t);if(!e)return;const i=e.params,n=this.progress(e,t),s=Math.tan(i.radiusDeg*Math.PI/180)*xe.smooth(n*U0.SPIRAL_OPENS)*(1-i.shrink*xe.smooth(n)),r=-(i.clockwise?1:-1)*2*Math.PI*i.turns*n;return[s*(Math.cos(r)-1),s*Math.sin(r)]}progress(t,e){const i=t.until??this.end;return i<=t.t?1:Math.max(0,Math.min(1,(e-t.t)/(i-t.t)))}}class bs{constructor(t,e,i,n){this.sighting=t,this.stand=e;const s=i.filter(a=>a.eventType==="appearance").sort((a,c)=>a.t-c.t);this.vanishAt=i.find(a=>a.eventType==="vanish")?.t;const r=this.vanishAt??n;this.path=e.eventType==="travel"?new xe(e,i.filter(a=>a.eventType==="turn"),n):void 0,this.motion=this.path?new U0(i,e.until??n):void 0,this.looks=s.map((a,c)=>({t:a.t,until:a.until??s[c+1]?.t??r,parts:a.params.parts})),this.blinks=i.filter(a=>a.eventType==="blink").map(a=>({t:a.t,until:a.until??r,parts:a.who===void 0?[]:t.timeline.leavesOf(a.who),params:a.params}))}static SAMPLE_MS=2e3;static TRAVEL_SAMPLE_MS=25;static MOTION_MS=40;static SPIRAL_AHEAD_MS=20;static R=63710088e-1;looks;blinks;vanishAt;path;motion;timeline(){const t=new Map,e=(r,a)=>{const c=this.state(a,r);c&&(t.has(r)||t.set(r,new Map),t.get(r).set(a,c))},i=[...new Set(this.looks.flatMap(r=>r.parts.map(a=>a.sourceId)))];this.looks.forEach((r,a)=>{const c=this.looks[a+1];for(const l of i){if(!r.parts.some(d=>d.sourceId===l)){e(r.t,l),c?.parts.some(d=>d.sourceId===l)&&e(c.t-1,l);continue}const u=this.sighting.sampleMs??(this.path?bs.TRAVEL_SAMPLE_MS:bs.SAMPLE_MS);for(let d=r.t;d<r.until;d+=u)e(d,l);e(r.until-1,l)}});for(const r of this.blinks)for(const[a,c]of this.phases(r))for(const l of r.parts)e(a,l),e(c-1,l);if(this.vanishAt!==void 0)for(const r of i)e(this.vanishAt,r);const n=[...t.keys()].sort((r,a)=>r-a).map(r=>({t:r,shapes:[...t.get(r).values()]})),s=new Map;for(const r of n)for(const a of r.shapes){const c=a.shape.angle,l=s.get(a.sourceId);if(c===void 0)continue;const h=l===void 0?c:c+2*Math.PI*Math.round((l-c)/(2*Math.PI));a.shape.angle=Math.round(h*1e4)/1e4,s.set(a.sourceId,h)}return{keyframes:n,order:i,groups:[]}}phases(t){const e=[];let i=!0;for(let n=t.t;n<t.until;){const s=Math.min(n+(i?t.params.onS:t.params.offS)*1e3,t.until);e.push([n,s]),n=s,i=!i}return e}off(t,e){for(const i of this.blinks){if(e<i.t||e>=i.until||!i.parts.includes(t))continue;if(this.phases(i).findIndex(([s,r])=>e>=s&&e<r)%2===1)return i.params.off}}state(t,e){const i=[...this.looks].reverse().find(l=>l.t<=e)??this.looks[0],n=i?.parts.find(l=>l.sourceId===t),r=(n?i:this.looks.find(l=>l.t>e&&l.parts.some(h=>h.sourceId===t))??[...this.looks].reverse().find(l=>l.parts.some(h=>h.sourceId===t)))?.parts.find(l=>l.sourceId===t);if(!r)return;const a=!n||this.vanishAt!==void 0&&e>=this.vanishAt,c=a?void 0:this.off(t,e);return this.path?{sourceId:t,shape:this.onPath(r,e,c,a)}:{sourceId:t,shape:bs.shape(r,this.geometry(e),c,a)}}onPath(t,e,i,n){const s=this.path,r=this.sighting.observerTrack.getInterpolatedPoseAt(e)??this.sighting.observerTrack.getLatestPoseAt(e),a=r?.headingDeg??0,c=r?.pitchDeg??0,l=this.motion,h=S=>xe.toScreen(s.at(S),a,c),u=(S,A)=>{const _=Math.hypot(A[0]-S[0],A[1]-S[1])||1;return[(A[0]-S[0])/_,(A[1]-S[1])/_]};let d=h(e),[f,p]=u(h(e-bs.MOTION_MS),h(e+bs.MOTION_MS));const m=s.sizeAt(e),g=Math.tan(l.sidewaysAt(e,m)*Math.PI/180);d=[d[0]-g*p,d[1]+g*f];const M=l.spiralAt(e);if(M){const S=l.spiralAt(e+bs.SPIRAL_AHEAD_MS),A=h(e),_=h(e+bs.SPIRAL_AHEAD_MS);d=[d[0]+M[0],d[1]+M[1]],[f,p]=u([A[0]+M[0],A[1]+M[1]],[_[0]+S[0],_[1]+S[1]])}const v=l.acrossShareAt(e),x={...t,heightShare:(t.heightShare??t.widthShare)*v,...t.upShare===void 0?{}:{upShare:t.upShare*v}},y=Math.tan(m*(x.alongShare??0)*Math.PI/180),w=Math.tan(m*(x.upShare??0)*Math.PI/180),b=xe.fromScreen(d[0]+y*f-w*p,d[1]+y*p+w*f,a,c),E=bs.shape(x,{...b,sizeDeg:m},i,n,!0);return E.angle=Math.atan2(-p,f),E}geometry(t){const e=this.stand.params,i=this.sighting.observerTrack.getInterpolatedPoseAt(t)??this.sighting.observerTrack.getLatestPoseAt(t),n=i?.lat!==void 0&&i.lng!==void 0?{lat:i.lat,lng:i.lng}:this.sighting.event.place?.[0]??e.place;return bs.seenFrom(e,n,t)}static seenFrom(t,e,i){const n=(t.place.lng-e.lng)*Math.PI/180*bs.R*Math.cos(e.lat*Math.PI/180),s=(t.place.lat-e.lat)*Math.PI/180*bs.R,r=Math.hypot(n,s),a=ai.linear(t.metres.map(({t:l,widthM:h,step:u})=>({t:l,value:h,step:u})),i),c=ai.linear(t.metres.map(({t:l,heightM:h,step:u})=>({t:l,value:h,step:u})),i);return{azimuthDeg:(Math.atan2(n,s)*180/Math.PI%360+360)%360,altitudeDeg:Math.atan2(c,r)*180/Math.PI,sizeDeg:2*Math.atan(a/(2*r))*180/Math.PI}}static shape(t,e,i,n,s=!1){const r=e.sizeDeg,a=Math.max(t.minWidthDeg??0,r*t.widthShare),c=t.kind==="oval"&&t.heightShare===void 0?a:Math.max(t.minHeightDeg??0,r*(t.heightShare??t.widthShare)),l=s?e.altitudeDeg:e.altitudeDeg+r*(t.upShare??0),h=s?e.azimuthDeg:e.azimuthDeg+r*(t.alongShare??0)/Math.cos(l*Math.PI/180),u=(p,m)=>Math.round(p*10**m)/10**m,d=t.kind==="polygon"?{kind:"polygon",bounds:{x:300,y:170,width:100,height:100*c/a},points:(t.points??[]).map(p=>({x:u(p.x*100,2),y:u(p.y*100*c/a,2)}))}:{kind:"oval",bounds:{x:320,y:180,width:2,height:2}};Object.assign(d,{color:i?.color??t.color,angle:0,transparency:n?1:i?.transparency??t.transparency??0,haloScale:t.halo??0,selected:!1,...t.blur===void 0?{}:{blur:t.blur},...t.title===void 0?{}:{title:t.title},angular:{widthDeg:u(a,4),heightDeg:u(c,4)},aim:{azimuthDeg:u((h%360+360)%360,3),altitudeDeg:u(l,3)}});const f=i&&"brightness"in i?i.brightness:t.brightness;return f!=null&&(d.brightness=n?0:f),d}}class Pe{static STANDING_EYE_M=1.6;static METERS_PER_DEGREE=111320;static expand(t){Pe.expandBodies(t),Pe.expandObserver(t),Pe.expandFlights(t),Pe.expandDecorLights(t),Pe.expandPhenomenon(t)}static expandDecorLights(t){for(const e of t.decor){if(!e.lights?.length||e.lights.some(s=>s.keyframes?.length))continue;const i=(t.events??[]).filter(s=>wd.partOf(s.who,e.id)!==void 0);if(i.length===0)continue;const n=JSON.stringify(e.lights);e.lights=new wd(e,i,Pe.endOf(t)).lights(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorLights={...t.eventsExpansion.decorLights,[e.id]:{stated:n,expanded:JSON.stringify(e.lights)}}}}static writtenLights(t,e,i){const n=t.eventsExpansion?.decorLights?.[e];return n&&JSON.stringify(i)===n.expanded?JSON.parse(n.stated):i}static expandPhenomenon(t){if(t.timeline.allKeyframes.length>0)return;const e=Pe.stands(t);for(const i of e){const n=As.within(t,i.who),s=(t.events??[]).filter(a=>a.who!==void 0&&n.has(a.who)),r=new bs(t,i,s,i.until??Pe.endOf(t)).timeline();for(const a of Ud.fromJSON(r).allKeyframes)t.timeline.addKeyframe(a.t,a.shapes)}e.length!==0&&(dh.timeline(t.timeline),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.timelinePending=!0)}static stands(t){return(t.events??[]).filter(e=>(e.eventType==="stand"||e.eventType==="travel")&&As.isPhenomenon(t,e))}static shapesOf(t){const{groups:e,...i}=t.timeline.toJSON();return JSON.stringify(i)}static timelineWithoutShapes(t){const e=t.timeline.toJSON().groups??[];return e.length>0?{keyframes:[],groups:e}:{keyframes:[]}}static settle(t){t.eventsExpansion?.timelinePending&&(dn.toAngular(t),dn.toAim(t),t.eventsExpansion.timeline=Pe.shapesOf(t),t.eventsExpansion.timelinePending=!1)}static timelineIsExpanded(t){return t.eventsExpansion?.timeline!==void 0&&t.eventsExpansion.timeline===Pe.shapesOf(t)}static expandFlights(t){const e=t.observerTrack.allKeyframes[0]?.pose??t.event.place?.[0];if(e?.lat===void 0||e.lng===void 0)return;const i=Math.cos(e.lat*Math.PI/180);for(const n of t.events??[]){if(n.eventType!=="fly"||n.who===void 0)continue;const s=t.decor.find(m=>m.id===n.who);if(!s||s.track?.length)continue;const r=n.params,a=n.until??Pe.endOf(t),c=r.headingDeg*Math.PI/180,l=(r.from.lng-e.lng)*Math.PI/180*Pe.R*i,h=(r.from.lat-e.lat)*Math.PI/180*Pe.R,u=r.speeds.map(({t:m,kmh:g,step:M})=>({t:m,value:g/3.6,step:M})),d=r.heights.map(({t:m,altitudeM:g,step:M})=>({t:m,value:g,step:M})),f=m=>{const g=Math.sign(m-r.at.t)*Pe.FLY_STEP_MS;let M=0;for(let v=r.at.t;g!==0&&(g>0?v<m:v>m);v+=g){const x=g>0?Math.min(m,v+g):Math.max(m,v+g);M+=(ai.linear(u,v)+ai.linear(u,x))/2*(x-v)/1e3}return M},p=[];for(let m=n.t;m<=a;m+=ai.SAMPLE_MS){const g=r.at.metresBefore-f(m);p.push({t:m,eastM:l-Math.sin(c)*g,northM:h-Math.cos(c)*g,altitudeM:ai.linear(d,m),headingDeg:r.headingDeg})}s.track=p,s.eastM=p[0].eastM,s.northM=p[0].northM,s.headingDeg=r.headingDeg,t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorTracks[s.id]=JSON.stringify(p)}}static R=63710088e-1;static FLY_STEP_MS=100;static expandObserver(t){const e=(t.events??[]).filter(m=>As.isObserver(t,m)),i=e.find(m=>m.eventType==="drive"),n=e.find(m=>m.eventType==="lookAhead");if(t.observerTrack.allKeyframes.length>0)return;if(!i){new yo(t,e).keyframes().length>0&&(dh.observer(t.observerTrack),t.eventsExpansion={...t.eventsExpansion,observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:t.eventsExpansion?.decorTracks??{}});return}if(!n)return;const s=i.until??Pe.endOf(t),r=i.params,a=new ai(r,i.t,s),c=e.find(m=>m.eventType==="lean"),l=e.find(m=>m.eventType==="watch"),u=new je(a,r.eye,n.params,c&&{t:c.t,params:c.params},l&&{t:l.t,params:l.params},m=>{const g=Pe.stands(t).find(v=>v.eventType==="stand");if(!g)return Pe.phenomenonPitchAt(t,m);const M=a.stateAt(m);return bs.seenFrom(g.params,{lat:M.lat,lng:M.lng},m).altitudeDeg}).poses(i.t,s),d=u.map(m=>({t:m.t,pose:{lat:m.lat,lng:m.lng,elevationM:m.eye.y-Pe.STANDING_EYE_M,headingDeg:m.headingDeg,pitchDeg:m.pitchDeg,fovDeg:r.fovDeg??60}}));for(const m of d)t.observerTrack.addKeyframe(m.t,m.pose);dh.observer(t.observerTrack);const f={observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:{}},p=r.vehicle===void 0?void 0:t.decor.find(m=>m.id===r.vehicle);if(p&&!p.track?.length){const m=u[0],g=v=>Math.cos(v*Math.PI/180),M=u.map(v=>{const x=v.roadDeg*Math.PI/180,y=-v.eye.z,w=v.eye.x,b=(v.lng-m.lng)*Pe.METERS_PER_DEGREE*g(v.lat),E=(v.lat-m.lat)*Pe.METERS_PER_DEGREE;return{t:v.t,eastM:b-y*Math.sin(x)-w*Math.cos(x),northM:E-y*Math.cos(x)+w*Math.sin(x),altitudeM:0,headingDeg:v.roadDeg}});p.track=M,p.eastM=M[0].eastM,p.northM=M[0].northM,p.headingDeg=M[0].headingDeg,f.decorTracks[p.id]=JSON.stringify(M)}t.eventsExpansion={...t.eventsExpansion,...f}}static expandBodies(t){const e=t.interpretation?.bodies??[],i=n=>(t.events??[]).some(s=>s.who===n.id&&s.eventType==="ride");for(const n of[...e.filter(s=>!i(s)),...e.filter(i)]){const s=(t.events??[]).filter(h=>h.who===n.id||ko.partOf(h.who,n.id)!==void 0);if(s.length===0)continue;const r=Math.min(...s.map(h=>h.t));if(n.track.some(h=>h.t>r))continue;const a=JSON.stringify(n.track),c=s.find(h=>h.eventType==="ride"),l=c&&e.find(h=>h.id===c.params.in);n.track=c?l?ko.ride(n,c,l):n.track:new ko(n,s,Pe.endOf(t),t.sampleMs).track(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.bodies={...t.eventsExpansion.bodies,[n.id]:{stated:a,expanded:JSON.stringify(n.track)}}}}static writtenInterpretation(t,e){const i=t.eventsExpansion?.bodies;return!e||!i?e:{...e,bodies:e.bodies.map(n=>{const s=i[n.id];return s&&JSON.stringify(n.track)===s.expanded?{...n,track:JSON.parse(s.stated)}:n})}}static refresh(t){const e=t.observerTrack.allKeyframes.length===0||Pe.observerTrackIsExpanded(t),i=t.timeline.allKeyframes.length===0||Pe.timelineIsExpanded(t);Pe.again(t,e,i)}static reset(t){Pe.again(t,!0,Pe.stands(t).length>0)}static again(t,e,i){for(const s of t.interpretation?.bodies??[]){const r=t.eventsExpansion?.bodies?.[s.id];r&&JSON.stringify(s.track)===r.expanded&&(s.track=JSON.parse(r.stated))}for(const s of t.decor)s.lights&&(s.lights=Pe.writtenLights(t,s.id,s.lights));if(e){for(const s of Object.keys(t.eventsExpansion?.decorTracks??{})){const r=t.decor.find(a=>a.id===s);r&&delete r.track}t.observerTrack.clear()}const n=t.timeline.toJSON().groups??[];if(i){for(const s of[...t.timeline.sourceIds])t.timeline.removeSource(s);t.timeline.setGroups(n,!1)}t.eventsExpansion=void 0,Pe.expand(t),i&&t.timeline.pruneGroups(),i&&(dn.toBounds(t),dn.toPosition(t)),Pe.settle(t)}static bodiesAreExpanded(t){const e=t.eventsExpansion?.bodies??{};return(t.interpretation?.bodies??[]).every(i=>!e[i.id]||JSON.stringify(i.track)===e[i.id].expanded)}static observerTrackIsExpanded(t){return t.eventsExpansion?.observerTrack!==void 0&&t.eventsExpansion.observerTrack===JSON.stringify(t.observerTrack.toJSON())}static decorTrackIsExpanded(t,e,i){const n=t.eventsExpansion?.decorTracks[e];return n!==void 0&&n===JSON.stringify(i)}static phenomenonPitchAt(t,e){let i;for(const n of t.timeline.sourceIds){const s=t.timeline.getInterpolatedShapeAt(e,n),r=s?.aim?.altitudeDeg;if(!s||s.transparency>=1||r===void 0)continue;const a=(s.angular?.widthDeg??0)*(s.angular?.heightDeg??0);(!i||a>i.area)&&(i={area:a,altitude:r})}return i?.altitude??0}static endOf(t){return t.event.durationSeconds!==void 0?t.event.durationSeconds*1e3:Math.max(...(t.events??[]).map(e=>e.until??e.t))}}function b_(o){return tr.restore(E_(o),o.provenance)}function E_(o,t=!1){return dn.toAngular(o),dn.toAim(o),{version:4,id:o.id,time:F0.write(o.event.time),endTime:F0.write(o.event.endTime),durationSeconds:o.event.durationSeconds,durationText:o.event.durationText,utcOffsetHours:o.event.utcOffsetHours,timeZone:o.event.timeZone,place:lb.write(o.event.place),observer:o.observer,account:o.account,sources:o.sources?.length?o.sources:void 0,sway:o.sway,vehicle:o.vehicle,description:o.event.description,image:o.event.image,summary:o.event.summary,summaryTime:o.event.summaryTime,tags:o.event.tags,timeline:!t&&Pe.timelineIsExpanded(o)?Pe.timelineWithoutShapes(o):o.timeline.toJSON(),observerTrack:!t&&Pe.observerTrackIsExpanded(o)?void 0:qn.restatedObserverTrack(o),events:o.events?.length?o.events:void 0,weatherTrack:o.weatherTrack.toJSON(),soundTrack:o.soundTrack.toJSON(),weather:o.weather,decor:qn.restatedDecor(o).map(e=>{if(!t&&e.lights&&(e={...e,lights:Pe.writtenLights(o,e.id,e.lights)}),t||!Pe.decorTrackIsExpanded(o,e.id,e.track))return e;const{track:i,...n}=e;return n}),milestones:o.milestones.length>0?o.milestones:void 0,references:o.references.length>0?o.references:void 0,roads:o.roads.length>0?o.roads:void 0,traces:o.traces.length>0?o.traces:void 0,weatherSource:o.weatherSource,instrument:o.instrumentId,exposureSeconds:o.exposureSeconds,iso:o.iso,film:o.film,metering:o.metering,sampleMs:o.sampleMs,lens:o.lens,lightPollution:o.lightPollution,observerMap:o.observerMap,interpretation:t?qn.restatedInterpretation(o):Pe.writtenInterpretation(o,qn.restatedInterpretation(o)),variants:o.variants.length>0?o.variants:void 0,skyEvents:Hr.written(o.skyEvents),snapshots:o.snapshots,modules:o.modules?.length?o.modules:void 0}}function A_(o){Gl.check(o,"sighting");const t=Qi.toCurrent(o),{recording:e,provenance:i}=tr.strip(t),n=__(e);return n.provenance=i,n}function __(o){const t=[],e=new Ap({eventType:"sighting",time:F0.read(o.time),endTime:F0.read(o.endTime),durationSeconds:o.durationSeconds,durationText:o.durationText,utcOffsetHours:o.utcOffsetHours,timeZone:o.timeZone,place:lb.read(o.place),description:o.description,image:o.image,summary:o.summary,summaryTime:o.summaryTime,tags:o.tags},Ud.fromJSON(o.timeline,t,!1),o.observerTrack?Zu.fromJSON(o.observerTrack):new Zu,o.weatherTrack?Ju.fromJSON(o.weatherTrack):new Ju,o.soundTrack?ju.fromJSON(o.soundTrack):new ju,o.observer&&{id:o.observer.id,title:o.observer.title,lastName:o.observer.lastName,firstNames:o.observer.firstNames},o.id,o.weather,(o.decor??[]).map(n=>{if(!n.facade?.plain)return n;const{plain:s,...r}=n.facade;return{...n,facade:{...r,openings:"plain"}}}),o.weatherSource,o.instrument,o.exposureSeconds??o.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),Du(o.milestones??[]),o.references??[],o.roads??[],o.traces??[]);e.account=o.account,e.sources=o.sources,e.sway=o.sway,e.iso=o.iso,e.film=o.film,e.metering=o.metering,e.sampleMs=o.sampleMs,e.lens=o.lens,e.lightPollution=o.lightPollution,e.observerMap=o.observerMap,e.vehicle=o.vehicle,e.events=o.events?.map(n=>n.who===void 0?{...n,who:Qi.observerIdOf(o)}:n);const i=Hr.read(o.skyEvents,o.interpretation);return e.interpretation=i.interpretation,e.variants=Array.isArray(o.variants)?o.variants:[],e.skyEvents=i.skyEvents,e.snapshots=o.snapshots,e.modules=Array.isArray(o.modules)?o.modules.filter(n=>typeof n=="string"):void 0,e.loadIssues=t,Pe.expand(e),e.timeline.pruneGroups(),dn.toBounds(e),dn.toPosition(e),Pe.settle(e),e}class F0{static read(t){return t===void 0||t.trim()===""?void 0:Y3(t)}static write(t){if(t===void 0)return;const e=sb(t);return e===""?void 0:e}}class lb{static read(t){if(t?.locations?.length)return t.locations.map(({lat:e,lng:i})=>({lat:e,lng:i,...t.name===void 0?{}:{name:t.name}}))}static write(t){if(!t?.length)return;const e=t.find(i=>i.name)?.name;return{...e===void 0?{}:{name:e},locations:t.map(({lat:i,lng:n})=>({lat:i,lng:n}))}}}class Sd{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(t,e=Sd.EN){return e[t.kind].replace("{path}",t.path).replace("{expected}",t.expected??"").replace("{found}",t.found??"")}static warn(t,e){if(t.length===0)return;const i=t.map(n=>` ${Sd.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
1766
1766
  ${i.join(`
1767
1767
  `)}`)}}class fr{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!fr.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:fr.typeOf(t)});return}for(const[s,r]of Object.entries(t)){const a=i?`${i}.${s}`:s,c=e[s];c?this.field(r,c,a,n):n.push({kind:"unknown-key",path:a})}}field(t,e,i,n){if(fr.isStated(t)){this.field(t.value,e,i,n);return}if(!(e.loose||t===void 0||t===null))switch(e.type){case"enum":(typeof t!="string"||!e.values?.includes(t))&&n.push({kind:"not-in-list",path:i,expected:(e.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(t)});return;case"object":e.fields?this.object(t,e.fields,i,n):fr.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:fr.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=fr.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:fr.typeOf(t)});return;default:typeof t!==e.type&&n.push({kind:"wrong-type",path:i,expected:e.type,found:fr.typeOf(t)})}}static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return fr.isObject(t)&&"value"in t&&Object.keys(t).every(e=>e==="value"||e==="basis"||e==="rationale")}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class vr{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(t,e){const i=Number.isFinite(e)?Math.max(0,e):0,n=Math.max(0,t-i*1e3),s=Math.max(0,t-n);return{fromMs:n,toMs:t,ms:s,seconds:s/1e3}}static instants(t,e,i,n,s){if(!(n>0))return 1;const r=s>0?vr.travelDegOver(t,e,i,i+n*1e3)/s/vr.PIXELS_PER_INSTANT:0,a=vr.flashesOver(t,n)*vr.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(vr.MAX_INSTANTS,c)}static travelDegOver(t,e,i,n){let s=0;for(const r of t){if(!r.track||r.track.length<2)continue;const a=vr.directionAt(r,e,i),c=vr.directionAt(r,e,n),l=Math.min(1,Math.max(-1,a.x*c.x+a.y*c.y+a.z*c.z));s=Math.max(s,Math.acos(l)*180/Math.PI)}return s}static flashesOver(t,e){let i=0;for(const n of t)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*e}static directionAt(t,e,i){const n=oa(t,i),s=n.eastM,r=n.altitudeM-e,a=n.northM,c=Math.hypot(s,r,a);return c===0?{x:0,y:1,z:0}:{x:s/c,y:r/c,z:a/c}}}function qg(o,t){for(const e of o){const i=e.toLowerCase().split("-")[0];if(t.includes(i))return i}return"en"}class wc{static preferencesFor(t){const e=navigator.languages??[],i=this.declaredFor(t);return i?[i,...e]:e}static declaredFor(t){for(let e=t;e;){const i=e.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=e.getRootNode();e=n instanceof ShadowRoot?n.host:void 0}}}Ct.register(Cn,()=>new vc);Ct.register(Th,()=>new oh);Ct.register(br,()=>new GM);Ct.register(Rh,()=>new ch);Ct.register(Qu,()=>new VM);Ct.register(Ih,()=>new sd);Ct.register(_h,()=>new nd);Ct.register(Dh,()=>new rd);Ct.register(Wo,()=>new Ch);Ct.register(Ah,()=>new id);Ct.register(Rs,()=>new Li);Ct.register(Po,()=>new cd);Ct.register(un,()=>new yc);Ct.register(Oo,()=>new ld);Ct.register(td,()=>new WM);Ct.register(No,()=>new hd);Ct.register(Co,()=>new od);Ct.register(Lo,()=>new ud);Ct.register(Lc,()=>new dd);Ct.register(Do,()=>new ad);Ct.register(fs,()=>new $e);Ct.register(za,()=>new md);Ct.register(hn,()=>new te);Ct.register(Ba,()=>new gd);Ct.register(ed,()=>new Ep);Ct.register(Ha,()=>new vd);Ct.register(Fa,()=>new pd);Ct.register(Ga,()=>new Md);Ct.register(N0,()=>new H3);Ct.register(Ua,()=>new fd);class wr{constructor(t){this.preferences=t}read(t){var e,i;if(t===void 0)return;if(typeof t=="string")return t===""?void 0:t;for(const s of this.preferences){const r=(e=t[s])!==null&&e!==void 0?e:t[wr.base(s)];if(r)return r}const n=new Set(this.preferences.map(s=>wr.base(s)));for(const[s,r]of Object.entries(t))if(r&&n.has(wr.base(s)))return r;return(i=Object.values(t).find(s=>s))!==null&&i!==void 0?i:void 0}write(t,e,i){var n,s;const r=e?.trim()?e.trim():void 0;if(t===void 0||typeof t=="string")return r;const a={...t},c=(s=(n=Object.keys(a).find(l=>l===i))!==null&&n!==void 0?n:Object.keys(a).find(l=>wr.base(l)===wr.base(i)))!==null&&s!==void 0?s:i;return r===void 0?delete a[c]:a[c]=r,Object.keys(a).length===0?void 0:a}static base(t){return t.toLowerCase().split("-")[0]}}wr.any=new wr([]);var f2;(function(o){o.abductee="abductee",o.actor="actor",o.artist="artist",o.anthropologist="anthropologist",o.archeologist="archeologist",o.astronaut="astronaut",o.astronomer="astronomer",o.astrologist="astrologist",o.astrophysicist="astrophysicist",o.banker="banker",o.barman="barman",o.biologist="biologist",o.biochemist="biochemist",o.biophysicist="biophysicist",o.bishop="bishop",o.businessman="businessman",o.botanist="botanist",o.cameraman="cameraman",o.chemist="chemist",o.contactee="contactee",o.cryptozoologist="cryptozoologist",o.dentist="dentist",o.director="director",o.diplomat="diplomat",o.diver="diver",o.electronics="electronics",o.engineer="engineer",o.ethnologist="ethnologist",o.exobiologist="exobiologist",o.farmer="farmer",o.firefighter="firefighter",o.flightAttendant="flightAttendant",o.geologist="geologist",o.geophysicist="geophysicist",o.geographer="geographer",o.historian="historian",o.houseWife="houseWife",o.hypnotherapist="hypnotherapist",o.illusionist="illusionist",o.journalist="journalist",o.judge="judge",o.lawyer="lawyer",o.leader="leader",o.librarian="librarian",o.logger="logger",o.mathematician="mathematician",o.mechanic="mechanic",o.meteorologist="meteorologist",o.military="military",o.musician="musician",o.neurologist="neurologist",o.neuroscientist="neuroscientist",o.neuropsychiatrist="neuropsychiatrist",o.nurse="nurse",o.oceanographer="oceanographer",o.painter="painter",o.parapsychologist="parapsychologist",o.philosopher="philosopher",o.photographer="photographer",o.physician="physician",o.physicist="physicist",o.pilot="pilot",o.politician="politician",o.policeman="policeman",o.priest="priest",o.producer="producer",o.prospector="prospector",o.psychologist="psychologist",o.psychiatrist="psychiatrist",o.radioastronomer="radioastronomer",o.radioamateur="radioamateur",o.salesman="salesman",o.sailor="sailor",o.sociologist="sociologist",o.softwareEngineer="softwareEngineer",o.stuntman="stuntman",o.taxiDriver="taxiDriver",o.teacher="teacher",o.telegrapher="telegrapher",o.truckDriver="truckDriver",o.ufologist="ufologist",o.ufoWitness="ufoWitness",o.ufoWitness2="ufoWitness2",o.worker="worker",o.writer="writer"})(f2||(f2={}));var p2;(function(o){o.neutral="neutral",o.male="male",o.female="female"})(p2||(p2={}));class T_ extends Error{constructor(t,e){super(t),this.cause=e}}class $M extends T_{constructor(t=$M.defaultMessage,e){super(t,e)}}$M.defaultMessage="Assertion failed";var m2;(function(o){o.country="country",o.region="region",o.department="department",o.city="city",o.company="company"})(m2||(m2={}));var g2;(function(o){o.at="at",o.au="au",o.ar="ar",o.be="be",o.br="br",o.ca="ca",o.ch="ch",o.cn="cn",o.cl="cl",o.co="co",o.cy="cy",o.de="de",o.dk="dk",o.do="do",o.dz="dz",o.gr="gr",o.ec="ec",o.eg="eg",o.es="es",o.fi="fi",o.fr="fr",o.ga="ga",o.ge="ge",o.hu="hu",o.in="in",o.ie="ie",o.ir="ir",o.il="il",o.it="it",o.jp="jp",o.kr="kr",o.ma="ma",o.mx="mx",o.my="my",o.mz="mz",o.nl="nl",o.no="no",o.nz="nz",o.pa="pa",o.pe="pe",o.ph="ph",o.pl="pl",o.pt="pt",o.ro="ro",o.ru="ru",o.sc="sc",o.tr="tr",o.ua="ua",o.uk="uk",o.us="us",o.sa="sa",o.se="se",o.su="su",o.tn="tn",o.tw="tw",o.ve="ve",o.za="za"})(g2||(g2={}));const R_=["en","fr","es","it"];class _r{static catalog(t){const e=new Map;return{load(i){const n=_r.languageOf(i);let s=e.get(n);return s||(s=t[n](),e.set(n,s),s.catch(()=>e.delete(n))),s}}}static none(){return new Proxy({},{get:()=>""})}static blank(){const t=new Proxy(()=>t,{get:(e,i)=>i===Symbol.toPrimitive?()=>"":i===Symbol.iterator?function*(){}:i==="toString"||i==="valueOf"?()=>"":i==="then"?void 0:t,apply:()=>t,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{}});return t}static languageOf(t){const e=t.toLowerCase().split("-")[0];return R_.includes(e)?e:"en"}}const Zg=["en","fr","es","it"],I_={en:()=>$t(()=>import("./UfoMessages_en-9jQrxDPT.js"),[],import.meta.url).then(o=>o.ufoMessages_en),fr:()=>$t(()=>import("./UfoMessages_fr-D9BCRY2m.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>$t(()=>import("./UfoMessages_es-DreLXcIR.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>$t(()=>import("./UfoMessages_it-C8r0jnJP.js"),[],import.meta.url).then(o=>o.ufoMessages_it)},D_=_r.catalog(I_),C_=_r.catalog({en:()=>$t(()=>import("./SceneNames_en-DWTnafrN.js"),[],import.meta.url).then(o=>o.sceneNames_en),fr:()=>$t(()=>import("./SceneNames_fr-CUIrnsZp.js"),[],import.meta.url).then(o=>o.sceneNames_fr),es:()=>$t(()=>import("./SceneNames_es-hgd9srr_.js"),[],import.meta.url).then(o=>o.sceneNames_es),it:()=>$t(()=>import("./SceneNames_it-D5ayHc7C.js"),[],import.meta.url).then(o=>o.sceneNames_it)});function P_(o){return C_.load(o)}const hb=Math.PI/180,O_=180/Math.PI,N_=256,ub=19,L_=1.25;function db(o,t){return 156543.03392*Math.cos(o*hb)/2**t}function fb(o,t){return db(o,t)*N_}function k_(o,t){let e=0;for(;e<ub&&fb(o,e+1)>=t;)e++;return e}function pb(o,t){return fb(o,t)}function U_(o,t){const e=t*L_;let i=0;for(;i<ub&&db(o,i)>e;)i++;return i}function M0(o){const t=o*hb;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function mb(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:M0(t)*i}}function gb(o,t,e){const i=M0(o.north),n=M0(o.south);return{x:(t-o.west)/(o.east-o.west),y:(M0(e)-i)/(n-i)}}function F_(o,t,e){const{x:i,y:n}=mb(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function z_(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=M2(o.y,t);return{south:M2(o.y+1,t),north:n,west:e,east:i}}function M2(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*O_}function Mb(o,t,e,i){const n=F_(o,t,e),s=Math.floor(i/2),r=[];for(let l=-s;l<=s;l++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+l,z:e});const a=r.map(z_),c={south:Math.min(...a.map(l=>l.south)),north:Math.max(...a.map(l=>l.north)),west:Math.min(...a.map(l=>l.west)),east:Math.max(...a.map(l=>l.east))};return{tiles:r,bounds:c}}const B_="#2ec4ff";class dc{constructor(t){this.ctx=t}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(t,e){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-t,s.y-e);r>s.radius||r>n||(i=s,n=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(t){const{ctx:e}=this;e.save(),this.targets=[],e.clearRect(0,0,this.width,this.height),this.paintGround(t),this.paintNight(t.nightFraction),this.paintPath(t),this.paintTraces(t),t.position?(this.paintCone(t,t.position),this.paintDecor(t),this.paintMarkers(t),this.paintObserver(t,t.position)):(this.paintDecor(t),this.paintMarkers(t)),this.paintNorth(),this.paintFooter(t.bounds,t.attribution),e.restore()}toCanvas(t,e,i){const n=gb(t,i,e);return{x:n.x*this.width,y:n.y*this.height}}paintGround(t){const{ctx:e}=this;e.fillStyle="#1d2321",e.fillRect(0,0,this.width,this.height);const i=t.imagery;if(!i)return;const n=this.toCanvas(t.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(t.bounds,i.bounds.south,i.bounds.east);e.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(t=0){if(t<=0)return;const{ctx:e}=this;e.save(),e.fillStyle=`rgba(6, 12, 30, ${Math.min(t,1)*.78})`,e.fillRect(0,0,this.width,this.height),e.restore()}paintDecor(t){const{ctx:e}=this;for(const i of t.decor){const n=this.toCanvas(t.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:n.x,y:n.y,radius:7}),e.beginPath(),e.rect(n.x-3.5,n.y-3.5,7,7),e.fillStyle="rgba(120, 220, 255, 0.85)",e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.7)",e.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),e.lineWidth=3,e.strokeStyle="rgba(0, 0, 0, 0.6)",e.stroke(),e.lineWidth=1.5,e.strokeStyle="rgba(120, 220, 255, 0.9)",e.stroke()}}paintPath(t){if(!t.path.moved)return;const{ctx:e}=this,i=t.path.points.map(n=>this.toCanvas(t.bounds,n.lat,n.lng));e.beginPath(),e.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))e.lineTo(n.x,n.y);e.lineJoin="round",e.lineCap="round",e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=5,e.stroke(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=2,e.stroke()}paintTraces(t){const{ctx:e}=this;for(const i of t.traces??[]){const n=i.points.map(r=>this.toCanvas(t.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??B_;if(i.kind==="point")e.beginPath(),e.moveTo(n[0].x,n[0].y-6),e.lineTo(n[0].x+6,n[0].y),e.lineTo(n[0].x,n[0].y+6),e.lineTo(n[0].x-6,n[0].y),e.closePath(),e.fillStyle=s,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))e.lineTo(r.x,r.y);i.kind==="polygon"&&e.closePath(),e.lineJoin="round",e.setLineDash([]),e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=4.5,e.stroke(),e.setLineDash([9,5]),e.strokeStyle=s,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(i.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let r=n[0];if(i.kind==="line"&&t.position){const a=this.toCanvas(t.bounds,t.position.lat,t.position.lng);r=n.reduce((c,l)=>Math.hypot(l.x-a.x,l.y-a.y)>Math.hypot(c.x-a.x,c.y-a.y)?l:c)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(t,e){const{headingDeg:i,coneHalfAngleDeg:n}=t;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(t.bounds,e.lat,e.lng),a=Math.hypot(this.width,this.height),c=(i-90)*Math.PI/180,l=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,a,c-l,c+l),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=h,s.fill(),s.restore()}paintMarkers(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const i of[...t.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(t.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:n.x,y:n.y,radius:dc.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,dc.MARKER_RADIUS_PX,0,Math.PI*2),e.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",e.fill(),e.lineWidth=2,e.strokeStyle="rgba(255, 255, 255, 0.9)",e.stroke(),e.fillStyle=i.current?"#1d2321":"#fff",e.fillText(i.label,n.x,n.y)}}paintObserver(t,e){const{ctx:i}=this,n=this.toCanvas(t.bounds,e.lat,e.lng);t.observerLabel&&this.targets.push({kind:"observer",label:t.observerLabel,lat:e.lat,lng:e.lng,x:n.x,y:n.y,radius:8});const s=t.markers.some(r=>{if(!r.current)return!1;const a=ae(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=dc.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?dc.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),s||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=s?3:2.5,i.strokeStyle=s?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:t}=this,e=this.width-14,i=16;t.beginPath(),t.moveTo(e,i-9),t.lineTo(e-4.5,i+5),t.lineTo(e,i+2),t.lineTo(e+4.5,i+5),t.closePath(),t.fillStyle="rgba(255, 255, 255, 0.92)",t.strokeStyle="rgba(0, 0, 0, 0.6)",t.lineWidth=1,t.fill(),t.stroke(),t.font="bold 9px sans-serif",t.textAlign="center",t.textBaseline="top",t.strokeText("N",e,i+6),t.fillText("N",e,i+6)}paintFooter(t,e){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=e?this.wrap(e,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const f of n.slice().reverse())this.paintOutlinedText(f,this.width-6,s),s-=11;const r=(t.south+t.north)/2,c=Math.abs(ae(r,t.east,r,t.west).x)/this.width,l=dc.SCALE_STEPS_M.find(f=>f/c<=this.width/3);if(l===void 0)return;const h=l/c,u=8,d=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(u,d),i.lineTo(u+h,d),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(l>=1e3?`${l/1e3} km`:`${l} m`,u,d-3)}paintOutlinedText(t,e,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(t,e,i),n.fillStyle="#fff",n.fillText(t,e,i)}wrap(t,e){const i=[];let n="";for(const s of t.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>e?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class fi{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(t,e){return fi.including(t.boundsAround(fi.MIN_SPAN_M,fi.MARGIN),e)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(t,e,i){const n=Math.min(fi.MAX_ZOOM,Math.max(fi.MIN_ZOOM,this.zoom*i)),s=this.centerX+(t-.5)/this.zoom,r=this.centerY+(e-.5)/this.zoom;this.centerX=s-(t-.5)/n,this.centerY=r-(e-.5)/n,this.zoom=n}panBy(t,e){this.centerX-=t/this.zoom,this.centerY-=e/this.zoom}refit(t,e){if(!this.changed)return;const i=this.boundsWithin(t),n=fi.mercatorY01(e.north),s=fi.mercatorY01(e.south),r=fi.mercatorY01(i.north),a=fi.mercatorY01(i.south);this.zoom=(e.east-e.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-e.west)/(e.east-e.west),this.centerY=((r+a)/2-n)/(s-n)}keepInView(t,e,i){if(!this.changed)return!1;const n=this.boundsWithin(t),s=fi.mercatorY01(n.north),r=fi.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(fi.mercatorY01(e.lat)-s)/(r-s);return a>=i&&a<=1-i&&c>=i&&c<=1-i?!1:(this.panBy(.5-a,.5-c),!0)}boundsWithin(t){if(!this.changed)return t;const e=.5/this.zoom,i=fi.mercatorY01(t.north),n=fi.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:fi.latitudeAt(i+(this.centerY-e)*(n-i)),south:fi.latitudeAt(i+(this.centerY+e)*(n-i))}}static including(t,e,i=3){const n=(t.north+t.south)/2,s=(t.east+t.west)/2,r=ae(n,t.east,n,s).x;let a=r;for(const c of e){const{x:l,z:h}=ae(c.lat,c.lng,n,s),u=Math.max(Math.abs(l),Math.abs(h));u<=r*i&&(a=Math.max(a,u*1.15))}return a<=r?t:{north:Is(0,-a,n,s).lat,south:Is(0,a,n,s).lat,east:Is(a,0,n,s).lng,west:Is(-a,0,n,s).lng}}static expand(t,e){const i=t.east-t.west,n=t.north-t.south;return{west:t.west-i*e,east:t.east+i*e,south:t.south-n*e,north:t.north+n*e}}static pointAt(t,e,i){const n=fi.mercatorY01(t.north),s=fi.mercatorY01(t.south);return{lat:fi.latitudeAt(n+i*(s-n)),lng:t.west+e*(t.east-t.west)}}static mercatorY01(t){const e=t*Math.PI/180;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}static latitudeAt(t){return Math.atan(Math.sinh(Math.PI*(1-2*t)))*180/Math.PI}}const $s=256,v2=3,H_=32768;class vb{fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(t,e){const i=(t.south+t.north)/2,n=(t.west+t.east)/2,s=Math.abs(ae(i,t.east,i,t.west).x),r=Math.abs(ae(t.north,n,t.south,n).z),a=k_(i,Math.max(s,r)),{tiles:c}=Mb(n,i,a,v2),l=v2*$s,h=new Float32Array(l*l),u=c[0];await Promise.all(c.map(f=>this.decodeTileInto(f,u,h,l)));const d=new Float32Array(e.width*e.height);for(let f=0;f<e.height;f++){const p=t.north+(t.south-t.north)*(f/(e.height-1));for(let m=0;m<e.width;m++){const g=t.west+(t.east-t.west)*(m/(e.width-1));d[f*e.width+m]=this.sampleAt(p,g,a,u,h,l)}}return{heights:d,width:e.width,height:e.height,bounds:t}}async decodeTileInto(t,e,i,n){const s=this.tileUrlTemplate.replace("{z}",String(t.z)).replace("{x}",String(t.x)).replace("{y}",String(t.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const a=await createImageBitmap(await r.blob()),c=document.createElement("canvas");c.width=$s,c.height=$s;const l=c.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(a,0,0);const{data:h}=l.getImageData(0,0,$s,$s),u=(t.x-e.x)*$s,d=(t.y-e.y)*$s;for(let f=0;f<$s;f++)for(let p=0;p<$s;p++){const m=(f*$s+p)*4,g=h[m]*256+h[m+1]+h[m+2]/256-H_,M=u+p,v=d+f;i[v*n+M]=g}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=mb(e,t,i),l=(a-n.x)*$s,h=(c-n.y)*$s,u=Math.max(0,Math.min(r-1,Math.floor(l))),d=Math.max(0,Math.min(r-1,Math.floor(h))),f=Math.min(r-1,u+1),p=Math.min(r-1,d+1),m=l-u,g=h-d,M=s[d*r+u],v=s[d*r+f],x=s[p*r+u],y=s[p*r+f],w=M+(v-M)*m,b=x+(y-x)*m;return w+(b-w)*g}}class _p{constructor(t,e,i,n){this.width=t,this.height=e,this.samples=i,this.values=n}at(t,e,i=0){return this.values[(e*this.width+t)*this.samples+i]}static parse(t){const e=new DataView(t);if(t.byteLength<8||e.getUint16(0)!==18761||e.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=e.getUint32(4,!0),n=e.getUint16(i,!0),s=new Map;for(let M=0;M<n;M++){const v=i+2+M*12;s.set(e.getUint16(v,!0),{type:e.getUint16(v+2,!0),count:e.getUint32(v+4,!0),value:e.getUint32(v+8,!0)})}const r=(M,v)=>{const x=s.get(M);if(x===void 0){if(v===void 0)throw new Error(`TIFF without tag ${M}`);return v}return x.type===3?x.value&65535:x.value},a=M=>{const v=s.get(M);if(v===void 0)throw new Error(`TIFF without tag ${M}`);const x=v.type===3?2:4,y=[];if(v.count*x<=4){const w=new DataView(new ArrayBuffer(4));w.setUint32(0,v.value,!0);for(let b=0;b<v.count;b++)y.push(x===2?w.getUint16(b*2,!0):w.getUint32(0,!0))}else for(let w=0;w<v.count;w++)y.push(x===2?e.getUint16(v.value+w*2,!0):e.getUint32(v.value+w*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const c=r(256),l=r(257),h=r(277,1),u=a(258)[0],d=r(339,1)===3;if(!(d&&u===32||!d&&u===8))throw new Error(`Unsupported TIFF samples: ${u} bits`);const f=a(273),p=a(279),m=new Uint8Array(c*l*h*(u/8));let g=0;for(let M=0;M<f.length&&g<m.length;M++){const v=Math.min(p[M],m.length-g);m.set(new Uint8Array(t,f[M],v),g),g+=v}if(g<m.length)throw new Error("Truncated TIFF");return new _p(c,l,h,d?new Float32Array(m.buffer):m)}}class no extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class G_{constructor(t,e,i,n,s){this.heights=t,this.plants=e,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(t,e){const i=Math.floor(t/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-e/this.metresPerPixel);if(i<0||n<0||i>=this.size||n>=this.size)return;const s=n*this.size+i;if(!(this.plants[s]||this.buildings[s]))return this.heights[s]}tallestStructureNear(t,e,i){let n;const s=Math.ceil(i/this.metresPerPixel);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const c=this.structureAt(t+a*this.metresPerPixel,e+r*this.metresPerPixel);c!==void 0&&(n===void 0||c>n)&&(n=c)}return n}}class Le{static covers(t,e){return t>=41.2&&t<=51.3&&e>=-5.4&&e<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??Le.WMS,this.wfs=t.wfsEndpoint??Le.WFS}static radius(t){return Math.min(t,Le.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,Le.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=Le.lidarRadius(e),n=Math.ceil(2*i/Le.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,Le.HEIGHT_LAYER),this.raster(t,i,n,Le.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new no("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===Le.NO_DATA))throw new no("no-coverage","No LiDAR HD survey here yet");const c=new Uint8Array(n*n),l=new Uint8Array(n*n);for(let u=0;u<n*n;u++){const d=r.values[u*r.samples],f=r.values[u*r.samples+1],p=r.values[u*r.samples+2];c[u]=f>d&&f>p?1:0,l[u]=d>120&&f<90&&p<90?1:0}const h=2*i/n;return{size:n,metresPerPixel:h,heights:a,vegetation:c,building:l,structures:new G_(a,c,l,n,h)}}async laserDate(t){return Le.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return Le.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",t))}static latest(t){return t.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(t,e,i,n){const r=[n.lng-1e-4,n.lat-1e-4,n.lng+1e-4,n.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(t,e){const i=Le.radius(e),n=Math.min(Le.MAX_PHOTO_PIXELS,Math.ceil(2*i/Le.METRES_PER_PIXEL)),s=await this.raster(t,i,n,Le.PHOTO_LAYER);if(s.samples<3)throw new no("unreachable","The photograph came in a layout this does not read");return{size:n,metresPerPixel:2*i/n,samples:s.samples,values:s.values}}async vectors(t,e,i){const n=Le.radius(e),s=n/Le.METRES_PER_DEGREE,r=n/(Le.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),c=`BBOX(geometrie,${[t.lng-r,t.lat-s,t.lng+r,t.lat+s].map(M=>M.toFixed(6)).join(",")},'EPSG:4326')`,[l,h,u,d,f,p]=await Promise.all([this.features("construction_lineaire",`${c} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${c} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${c} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",c,"voltage,geometrie"),i?this.features("batiment",c,Le.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",c,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(p,f,[t.lng-r,t.lat-s,t.lng+r,t.lat+s]):[],g=[...f,...m];return{bridges:l,elevatedRoads:h,elevatedRailways:u,lines:d,buildings:g,zones:p,mapDate:Le.latest(g.map(M=>M.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(t,e,i){const[n,s,r,a]=i,c=Le.MAX_WHOLE_M/Le.METRES_PER_DEGREE;let l;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,m]=Le.extent(u);if(d>=n&&f>=s&&p<=r&&m<=a)continue;const g=[Math.max(d,n-c),Math.max(f,s-c),Math.min(p,r+c),Math.min(m,a+c)];l=l?[Math.min(l[0],g[0]),Math.min(l[1],g[1]),Math.max(l[2],g[2]),Math.max(l[3],g[3])]:g}if(!l)return[];const h=new Set(e.map(u=>u.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${l.map(d=>d.toFixed(6)).join(",")},'EPSG:4326')`,Le.BUILDING_PROPERTIES,1e3)).filter(d=>!h.has(d.properties.cleabs))}catch{return[]}}static extent(t){let e=1/0,i=1/0,n=-1/0,s=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(e=Math.min(e,a[0]),n=Math.max(n,a[0]),i=Math.min(i,a[1]),s=Math.max(s,a[1])):Array.isArray(a)&&a.forEach(r)};return r(t.geometry.coordinates),[e,i,n,s]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,c=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const l of c)n.push(l.map(h=>({lat:h[1],lng:h[0]})))}return n}async waterSurfaces(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${e} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${e} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${e} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(t,e,i,n){const s=e/Le.METRES_PER_DEGREE,r=e/(Le.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-s,t.lng-r,t.lat+s,t.lng+r].map(l=>l.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let c;try{c=await this.fetchImpl(`${this.wms}?${a}`)}catch(l){throw new no("unreachable",l instanceof Error?l.message:String(l))}if(!c.ok)throw new no("unreachable",`The survey answered ${c.status}`);try{return _p.parse(await c.arrayBuffer())}catch(l){throw new no("unreachable",l instanceof Error?l.message:String(l))}}async features(t,e,i,n=200){const s=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:t.includes(":")?t:`BDTOPO_V3:${t}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(n),CQL_FILTER:e,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(c){throw new no("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new no("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class xo{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(t,e){if(t.length<2||e.length<2)return!1;const i=e[0],n=e.map(a=>ae(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>ae(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const c=s[a],l=s[a+1],h=Math.hypot(l.x-c.x,l.z-c.z);if(h<1e-6)continue;const u=Math.max(1,Math.ceil(h/xo.SAMPLE_M)),d=Math.atan2(l.x-c.x,-(l.z-c.z));for(let f=0;f<=u;f++){const p=f/u,m=xo.nearest(n,c.x+(l.x-c.x)*p,c.z+(l.z-c.z)*p);m.distanceM>xo.NEAR_M||xo.angleBetween(d,m.heading)<=xo.ALIGNED_DEG&&(r+=h/u)}}return r>=xo.LONG_ENOUGH_M}static nearest(t,e,i){let n={distanceM:1/0,heading:0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.z-r.z,h=c*c+l*l,u=h<1e-9?0:Math.max(0,Math.min(1,((e-r.x)*c+(i-r.z)*l)/h)),d=Math.hypot(e-(r.x+c*u),i-(r.z+l*u));d<n.distanceM&&(n={distanceM:d,heading:Math.atan2(c,-l)})}return n}static angleBetween(t,e){const i=Math.abs((t-e)*180/Math.PI%180);return Math.min(i,180-i)}}class Ce{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??Ce.WMS,this.timeoutMs=t.timeoutMs??Ce.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??Ce.MAX_WINDOW_M,this.geoplatform=new Le({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,i){const n={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!Le.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(ae(n.lat,t.east,n.lat,t.west).x),r=Math.abs(ae(t.north,n.lng,t.south,n.lng).z);e=this.finer(e,s,r);const a={x:s/Math.max(1,e.width-1),y:r/Math.max(1,e.height-1)},c={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},l={south:t.south-c.y/Ce.METRES_PER_DEGREE,north:t.north+c.y/Ce.METRES_PER_DEGREE,west:t.west-c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},h=m=>Math.min(Ce.MAX_PIXELS,Math.max(Ce.MIN_PIXELS,Math.ceil(m/Ce.METRES_PER_PIXEL))),u={width:h(s+2*c.x),height:h(r+2*c.y)},d={x:(s+2*c.x)/u.width,y:(r+2*c.y)/u.height};let f=new Error("No layer of the IGN's relief answered");const p=Math.max(d.x,d.y)>Ce.COARSE_METRES_PER_PIXEL;for(const m of p?[...Ce.LAYERS].reverse():Ce.LAYERS)try{const g=await this.heights(l,u,m);m===Ce.LAYERS[0]&&await this.layBridgeDecks(g,l,u,i?.route);const M=this.sample(g,e,t,l,d,a);if(M)return{heights:M,width:e.width,height:e.height,bounds:t};f=new Error(`${m} does not cover this place`)}catch(g){f=g}throw f}finer(t,e,i){if(t.width<Ce.MESH_FROM_VERTICES||t.height<Ce.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/Ce.FINE_SPACING_M),c=Math.max(r-1,Math.min(Ce.MAX_SEGMENTS,a));return c%2===0?c:c+1};return{width:n(e,t.width)+1,height:n(i,t.height)+1}}async raster(t,e,i){const n=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[t.south,t.west,t.north,t.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.height),FORMAT:"image/geotiff"}),s=await this.fetchImpl(`${this.wms}?${n}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`The IGN's relief answered ${s.status}`);return _p.parse(await s.arrayBuffer())}async heights(t,e,i){const n=await this.raster(t,e,i);if(n.samples!==1||!(n.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return n}async layBridgeDecks(t,e,i,n){if(!(!n||n.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(s=>s>Ce.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>xo.follows(n,a));if(s.length===0)return;const r=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,i,s),this.layRouteDecks(t,r,e,s)}catch{}}async layClassifiedDecks(t,e,i,n){try{const s=await this.raster(e,i,Ce.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(g,[M,v,x])=>s.values[g*s.samples]===M&&s.values[g*s.samples+1]===v&&s.values[g*s.samples+2]===x,a=t.width,c=t.height,l=new Uint8Array(a*c);let h=!1;for(let g=0;g<l.length;g++)r(g,Ce.DECK)&&(l[g]=1,h=!0);if(!h)return;const u=Ce.DECK_END_PIXELS,d=[];for(let g=0;g<l.length;g++){if(l[g]!==1)continue;const M=g%a,v=(g-M)/a;for(let x=-u;x<=u;x++)for(let y=-u;y<=u;y++){const w=M+y,b=v+x;if(w<0||b<0||w>=a||b>=c)continue;const E=b*a+w;l[E]===0&&r(E,Ce.NO_CLASS)&&d.push(E)}}for(const g of d)l[g]=1;const f=this.paint(n,e,a,c),p=this.touching(l,f,a,c);if(p.every(g=>g===0))return;const m=await this.heights(e,i,Ce.SURFACE_LAYER);if(m.width!==a||m.height!==c)return;for(let g=0;g<p.length;g++){if(p[g]===0)continue;const M=m.values[g];Number.isFinite(M)&&M>Ce.NO_DATA_BELOW&&M>t.values[g]&&(t.values[g]=M)}}catch{}}layRouteDecks(t,e,i,n){const{width:s,height:r}=t,a=(i.north+i.south)/2,c=(i.east-i.west)*Ce.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),l=(i.north-i.south)*Ce.METRES_PER_DEGREE,h=c/s,u=l/r,d=M=>({x:(M.lng-i.west)/(i.east-i.west)*c,y:(i.north-M.lat)/(i.north-i.south)*l}),f=(M,v)=>{const x=Math.floor(M/h),y=Math.floor(v/u);if(x<0||y<0||x>=s||y>=r)return;const w=e[y*s+x];return Number.isFinite(w)&&w>Ce.NO_DATA_BELOW?w:void 0},p=Ce.DECK_HALF_WIDTH_M,m=Ce.DECK_APPROACH_M,g=(M,v)=>{const x=Math.hypot(M.x-v.x,M.y-v.y)||1,y={x:(M.x-v.x)/x,y:(M.y-v.y)/x},w=[0,m/2,m].map(b=>f(M.x+y.x*b,M.y+y.y*b)).filter(b=>b!==void 0);return w.length>0?Math.max(...w):void 0};for(const M of Ce.chains(n.map(v=>v.map(d)))){const v=[0];for(let I=1;I<M.length;I++)v.push(v[I-1]+Math.hypot(M[I].x-M[I-1].x,M[I].y-M[I-1].y));const x=v[v.length-1];if(x<1||x>Ce.DECK_STRAIGHT_MAX_M)continue;const y=g(M[0],M[1]),w=g(M[M.length-1],M[M.length-2]);if(y===void 0||w===void 0)continue;const b=p+m,E=Math.max(0,Math.floor((Math.min(...M.map(I=>I.x))-b)/h)),S=Math.min(s-1,Math.ceil((Math.max(...M.map(I=>I.x))+b)/h)),A=Math.max(0,Math.floor((Math.min(...M.map(I=>I.y))-b)/u)),_=Math.min(r-1,Math.ceil((Math.max(...M.map(I=>I.y))+b)/u));for(let I=A;I<=_;I++)for(let D=E;D<=S;D++){const P=Ce.nearestAlong(M,v,{x:(D+.5)*h,y:(I+.5)*u});if(P.distance>p||P.s<-m||P.s>x+m)continue;const L=y+(w-y)*Math.min(1,Math.max(0,P.s/x)),O=I*s+D;e[O]>=L||(t.values[O]=L)}}}static chains(t){const e=t.filter(s=>s.length>=2).map(s=>[...s]),i=[],n=(s,r)=>Math.hypot(s.x-r.x,s.y-r.y)<=1;for(;e.length>0;){let s=e.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<e.length;a++){const c=e[a],l=s[0],h=s[s.length-1];if(n(h,c[0]))s=[...s,...c.slice(1)];else if(n(h,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else if(n(l,c[c.length-1]))s=[...c.slice(0,-1),...s];else if(n(l,c[0]))s=[...[...c].reverse().slice(0,-1),...s];else continue;e.splice(a,1),r=!0;break}}i.push(s)}return i}static nearestAlong(t,e,i){let n={s:0,distance:1/0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.y-r.y,h=c*c+l*l;if(h<1e-9)continue;let u=((i.x-r.x)*c+(i.y-r.y)*l)/h;s>0&&(u=Math.max(0,u)),s<t.length-2&&(u=Math.min(1,u));const d=Math.hypot(i.x-(r.x+c*u),i.y-(r.y+l*u));d<n.distance&&(n={s:e[s]+u*Math.sqrt(h),distance:d})}return n}paint(t,e,i,n){const s=new Uint8Array(i*n),r=c=>(c-e.west)/(e.east-e.west)*i,a=c=>(e.north-c)/(e.north-e.south)*n;for(const c of t)for(let l=0;l<c.length-1;l++){const h=r(c[l].lng),u=a(c[l].lat),d=r(c[l+1].lng),f=a(c[l+1].lat),p=Math.max(1,Math.ceil(Math.hypot(d-h,f-u)*2));for(let m=0;m<=p;m++){const g=Math.floor(h+(d-h)*m/p),M=Math.floor(u+(f-u)*m/p);for(let v=-1;v<=1;v++)for(let x=-1;x<=1;x++){const y=g+x,w=M+v;y>=0&&w>=0&&y<i&&w<n&&(s[w*i+y]=1)}}}return s}touching(t,e,i,n){const s=new Uint8Array(t.length),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++){if(t[a]===0||r[a]===1)continue;const c=[],l=[a];r[a]=1;let h=!1;for(;l.length>0;){const u=l.pop();c.push(u),e[u]===1&&(h=!0);const d=u%i,f=(u-d)/i;for(let p=-1;p<=1;p++)for(let m=-1;m<=1;m++){const g=d+m,M=f+p;if(g<0||M<0||g>=i||M>=n)continue;const v=M*i+g;t[v]===1&&r[v]===0&&(r[v]=1,l.push(v))}}if(h)for(const u of c)s[u]=1}return s}sample(t,e,i,n,s,r){const{width:a,height:c}=e,l=new Float32Array(a*c),h=new Uint8Array(a*c),u=Math.min(r.x,this.maxWindowM)/s.x,d=Math.min(r.y,this.maxWindowM)/s.y;let f=0;for(let p=0;p<c;p++){const m=i.north+(i.south-i.north)*(c===1?.5:p/(c-1)),g=(n.north-m)/(n.north-n.south)*t.height-.5;for(let M=0;M<a;M++){const x=(i.west+(i.east-i.west)*(a===1?.5:M/(a-1))-n.west)/(n.east-n.west)*t.width-.5,y=u>1||d>1?this.tent(t,x,g,Math.max(1,u),Math.max(1,d)):this.bilinear(t,x,g),w=p*a+M;y===void 0?f++:(l[w]=y,h[w]=1)}}if(!(f===a*c||f/(a*c)>Ce.MAX_HOLE_SHARE))return this.fill(l,h,a,c),l}tent(t,e,i,n,s){let r=0,a=0,c=0;const l=Math.max(0,Math.ceil(i-s)),h=Math.min(t.height-1,Math.floor(i+s)),u=Math.max(0,Math.ceil(e-n)),d=Math.min(t.width-1,Math.floor(e+n));for(let f=l;f<=h;f++){const p=1-Math.abs(f-i)/s;if(!(p<=0))for(let m=u;m<=d;m++){const g=p*(1-Math.abs(m-e)/n);if(g<=0)continue;c+=g;const M=t.at(m,f);!Number.isFinite(M)||M<Ce.NO_DATA_BELOW||(r+=g*M,a+=g)}}return c>0&&a>=c*.5?r/a:void 0}bilinear(t,e,i){const n=Math.max(0,Math.min(t.width-1,Math.floor(e))),s=Math.max(0,Math.min(t.height-1,Math.floor(i))),r=Math.min(t.width-1,n+1),a=Math.min(t.height-1,s+1),c=Math.max(0,Math.min(1,e-n)),l=Math.max(0,Math.min(1,i-s)),h=t.at(n,s),u=t.at(r,s),d=t.at(n,a),f=t.at(r,a);for(const g of[h,u,d,f])if(!Number.isFinite(g)||g<Ce.NO_DATA_BELOW)return;const p=h+(u-h)*c,m=d+(f-d)*c;return p+(m-p)*l}fill(t,e,i,n){let s=e.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let c=0;c<i;c++){const l=a*i+c;if(e[l])continue;let h=0,u=0;for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){const p=a+d,m=c+f;p<0||m<0||p>=n||m>=i||!e[p*i+m]||(h+=t[p*i+m],u++)}u>0&&r.push([l,h/u])}if(r.length===0)return;for(const[a,c]of r)t[a]=c,e[a]=1;s-=r.length}}}class V_{providers;constructor(...t){this.providers=t}async getElevationGrid(t,e,i){let n=new Error("No source of relief to ask");for(const s of this.providers)try{return await s.getElevationGrid(t,e,i)}catch(r){n=r}throw n}}const v0=256,W_=5;async function yb(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(ae(n,o.east,n,o.west).x),a=Math.abs(ae(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:l,gridSize:h}=X_(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=Mb(s,n,l,h),f=h*v0,p=document.createElement("canvas");p.width=f,p.height=f;const m=p.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const g=u[0];await Promise.all(u.map(async y=>{const w=e(y),b=await i(w);if(!b.ok)throw new Error(`Imagery tile fetch failed (${b.status}): ${w}`);const E=await createImageBitmap(await b.blob());m.drawImage(E,(y.x-g.x)*v0,(y.y-g.y)*v0)}));const M=Math.min(Math.max(t.width,t.height),f);if(M===f)return{source:p,width:f,height:f,bounds:d};const v=document.createElement("canvas");v.width=M,v.height=M;const x=v.getContext("2d");if(!x)throw new Error("2D canvas context unavailable");return x.drawImage(p,0,0,f,f,0,0,M,M),{source:v,width:M,height:M,bounds:d}}function X_(o,t,e){let i=U_(o,t/Math.max(1,e)),n=y2(o,i,t);for(;n>W_&&i>0;)i--,n=y2(o,i,t);return{zoom:i,gridSize:n,mPerPixel:pb(o,i)/v0}}function y2(o,t,e){const i=Math.ceil(e/2/pb(o,t));return Math.max(3,2*i+1)}class xb{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(t,e){return yb(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class _s{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(t,e=_s.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!i)return[...e];const[n,s,r,a]=i.slice(1).map(Number),c=(n+r)/2,l=(s+a)/2,h=_s.FRANCE;return c>=h.south&&c<=h.north&&l>=h.west&&l<=h.east?[_s.FRANCE_ENDPOINT,...e.filter(d=>d!==_s.FRANCE_ENDPOINT)]:[...e]}fetchImpl;endpoints;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.endpoints=t.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(t){return this.queued(()=>this.ask(t))}queued(t){const e=_s.queue.then(t,t);return _s.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??_s.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(_s.HANG_MS)});if(s.ok)return await s.json();if(e=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){e=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,_s.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class wo{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;client;constructor(t={}){this.client=new _s(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${wo.DRIVABLE.join("|")})$"](${e});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(t){const e=[];for(const i of t.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||e.push({id:`osm-${i.id??e.length}`,name:s.name,surface:wo.surfaceOf(s),widthM:wo.widthOf(s),...wo.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return e}static paintOf(t){const e=t.highway??"",i=t.junction==="roundabout"||t.junction==="circular",n=t.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(e==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(t.lanes??"",10),c=Number.parseInt(t.maxspeed??"",10),l=i?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(s||r)?"dual":e?"road":void 0;return{...l?{kind:l}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||e==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{}}}static widthOf(t){const e=Number.parseFloat(t.width??t.est_width??"");if(Number.isFinite(e)&&e>0)return e;const i=Number.parseInt(t.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:wo.WIDTH_M[t.highway]??wo.DEFAULT_WIDTH_M}static surfaceOf(t){const e=t.surface;return e==="dirt"||e==="earth"||e==="mud"?"dirt":e==="gravel"||e==="fine_gravel"||e==="compacted"||e==="ground"||e==="sand"||e==="unpaved"?"gravel":e?"paved":t.highway==="track"?"gravel":"paved"}}const om="https://ufoathome.org/roads/index.json";class Vl{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Vl.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRoads(t);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(t){let e;try{e=await this.load()}catch{return}const i=e.find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.ways)?(this.attributionRead=s.attribution,this.contemporaryRead=s.contemporary,s.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
1768
- `);let e=Vl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Vl.shared.set(t,e),e.then(i=>{i.length===0&&Vl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.0")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==om?[e,om]:[om]).map(i=>i+t)}}class Ao{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,n)=>Ao.wayOf(i,n))}static wayOf(t,e){if(t.geometry.type!=="LineString")return[];const i=t.geometry.coordinates.map(([d,f])=>({lat:f,lng:d}));if(i.length<2)return[];const n=String(t.properties.nature??""),s=Ao.BY_NATURE[n]??Ao.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),l=Ao.DIRECTIONS[String(t.properties.sens_de_circulation??"")],h=Ao.KINDS[n],u=[t.properties.cpx_toponyme_route_nommee,t.properties.nom_voie_ban_gauche,t.properties.nom_voie_ban_droite].find(d=>typeof d=="string"&&d.length>0);return[{id:String(t.properties.cleabs??`ign-${e}`),...u?{name:u}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...t.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...l?{direction:l}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{},points:i}]}}class Y_{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(t){if(Ao.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class bd{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,n)=>bd.surfacesOf(i,n))}static surfacesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(t.properties.cleabs??`ign-water-${e}`);return s.flatMap((a,c)=>{const l=a.map(h=>bd.open(h.map(u=>({lat:u[1],lng:u[0]})))).filter(h=>h.length>=3);return l.length>0?[{id:s.length>1?`${r}-${c}`:r,rings:l}]:[]})}static open(t){const e=t[0],i=t[t.length-1];return t.length>1&&e.lat===i.lat&&e.lng===i.lng?t.slice(0,-1):t}}class fc{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new _s(t)}async getWater(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${e});way["waterway"="riverbank"](${e});)->.w;(relation["natural"="water"](${e});relation["waterway"="riverbank"](${e});)->.r;.w out geom;.r out body;way(r.r)(${e});out geom;`;return fc.surfacesFrom(await this.client.query(i))}static surfacesFrom(t){const e=t.elements??[],i=new Map;for(const r of e)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const n=[],s=new Set;for(const r of e){if(r.type!=="relation")continue;const a=l=>(r.members??[]).filter(h=>h.type==="way"&&h.role===l&&h.ref!==void 0&&i.has(h.ref)).map(h=>(s.add(h.ref),i.get(h.ref))),c=fc.rings(a("inner"));for(const[l,h]of fc.rings(a("outer")).entries()){const u=c.filter(d=>fc.contains(h,d[0]));n.push({id:`osm-r${r.id}-${l}`,rings:[h,...u]})}}for(const r of e)if(!(r.type!=="way"||!r.tags||r.id===void 0||s.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of fc.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(t){const e=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=t.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!e(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const c=i[a],l=s[s.length-1];if(e(l,c[0]))s=[...s,...c.slice(1)];else if(e(l,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&e(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(t,e){let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n],a=t[s];r.lat>e.lat!=a.lat>e.lat&&e.lng<(a.lng-r.lng)*(e.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class $_{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(bd.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const cm="https://ufoathome.org/water/index.json";class Wl{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Wl.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getWater(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.surfaces)?(this.attributionRead=s.attribution,s.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
1769
- `);let e=Wl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Wl.shared.set(t,e),e.then(i=>{i.length===0&&Wl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==cm?[e,cm]:[cm]).map(i=>i+t)}}class vs{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=vs.key(t);let i=vs.asked.get(e);return i===void 0&&(i=this.recalled(e,t),vs.asked.set(e,i),i.catch(()=>vs.asked.delete(e))),structuredClone(await i)}static forget(){vs.asked.clear()}static key(t){return`v${vs.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await vs.openCache(),n=vs.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<vs.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&vs.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-vs.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(vs.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class _o{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>_o.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=_o.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=_o.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=_o.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const m=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>_o.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:m}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class zn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(t={}){this.client=new _s(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${zn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${zn.ROUTES})$"];out body;`;return zn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=zn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(M=>ae(M.lat,M.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(M=>M.service===!!r.service);for(const M of zn.samples(a)){u++;const v=zn.waysAt(d,M);if(v.length===0)continue;const[x]=v;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const y of new Set(v.flatMap(w=>w.services)))h.set(y,(h.get(y)??0)+1)}const f=M=>[...M.entries()].sort((v,x)=>x[1]-v[1])[0]?.[0],p=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(l)),g=[...h.entries()].filter(([,M])=>M*4>=u).sort((M,v)=>v[1]-M[1]||M[0].localeCompare(v[0])).map(([M])=>M);return{...r,...p?{name:p}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=zn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=zn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=zn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>ae(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=zn.SAMPLE_M/2;a<n;a+=zn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(zn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=zn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class Xl{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new _s(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Xl.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${zn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=zn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=zn.voltageOf(r),l=Xl.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=Xl.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:Xl.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class K_{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(t){if(!_o.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class cn{constructor(t,e=Date.now){this.railways=t,this.now=e}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(t){const e=cn.key(t);let i=cn.asked.get(e)??cn.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},cn.asked.set(e,i),n.catch(()=>cn.asked.delete(e))}return structuredClone(await i.answer)}static forget(){cn.asked.clear(),cn.failedAt=-1/0}static key(t){return`v${cn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of cn.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await cn.openCache(),n=cn.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<cn.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-cn.failedAt<cn.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(cn.failedAt=this.now(),s)return s;throw a}return i&&cn.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-cn.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(cn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const lm="https://ufoathome.org/railways/index.json";class Yl{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Yl.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
1770
- `);let e=Yl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Yl.shared.set(t,e),e.then(i=>{i.length===0&&Yl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==lm?[e,lm]:[lm]).map(i=>i+t)}}function wb(){return{elevation:Sb(),imagery:bb(),roads:q_(),water:Z_(),railways:J_()}}function Sb(){return new V_(new Ce,new vb)}function bb(){return new xb}function q_(){return new Vl({fallback:new Y_(new Ao,new wo)})}function Z_(){return new Wl({fallback:new vs(new $_(new bd,new fc))})}function J_(){return new Yl({fallback:new cn(new K_(new _o,new Xl))})}const j_=new Set,fh="show-observer-map",ph="hide-milestones",Sc="minified";class He extends HTMLElement{static get observedAttributes(){return["src",fh,ph,Sc]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new fi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Ap.create();issues=[];issueCheck=0;sightingAudio=new w_;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>He.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");He.setIcon(this.moreButton,t?Qt.UNFOLDED:Qt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<He.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=fi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=fi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},He.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=fi.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${f_}</style>${d_}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Ph(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new dc(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===fh&&this.applyObserverMapDefault(),t===ph&&this.setMilestonesShown(!this.hasAttribute(ph)),t===Sc){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Sc)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(Ab)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const t=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",t),t&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(t){this.sightingData=await xd.recording(t)}get sightingData(){return b_(this.currentSighting)}set sightingData(t){const e=Qi.toCurrent(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=A_(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await $t(async()=>{const{default:r}=await import("./sightingSchema-B1hstz7u.js");return{default:r}},[],import.meta.url);n=new fr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],Sd.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(Q_,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=(this.messages?.recordingIssues??"").replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=Sd.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;!this.referenceOpacityTouched&&t.length>0&&(this.referenceOpacityInput.value=String(t[0].opacity));for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),He.setIcon(this.referencesButton,i?Qt.PICTURES_ON:Qt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),He.setIcon(this.tracesButton,this.tracesShownState?Qt.TRACES_ON:Qt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?Du(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=He.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=He.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?sm(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new Ph(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=He.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?sm(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=vr.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<He.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(He.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/He.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/He.EXPOSURE_STEP_PX),s=Math.min(He.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=Xi.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}onFrame(t,e){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:j_;this.canvasRenderer.setStarPoints(Xi.starPointsOf(this.sighting.instrument,ze(this.sighting,t)?.fNumber));const n=(ze(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?zs.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(j3(this.currentSighting,t))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:t}}))}shifted(t,e){return e.x===0&&e.y===0?t:{...t,bounds:{...t.bounds,x:t.bounds.x+e.x,y:t.bounds.y+e.y}}}createPlayer(){const t=new p_(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*He.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?Qt.PLAY:Qt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){He.icons.get(t)!==e&&(He.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},He.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),He.setIcon(this.playPauseButton,t?Qt.PAUSE:Qt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(fh),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;He.setIcon(this.observerMapButton,t?Qt.MAP_ON:Qt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=uh.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=fi.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?fi.expand(t,He.OBSERVER_MAP_IMAGERY_AHEAD):t,n=fi.IMAGERY_PX*(e?1+2*He.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapSnapshotImagery,r=s?void 0:bb();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?fi.expand(t,He.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(t){t!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=He.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=ze(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},He.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?sm(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?Du(this.currentSighting.milestones):[]){const a=ze(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?na.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(Xi.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,Du(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",He.setIcon(this.milestonesButton,this.milestonesShown?Qt.MILESTONES_ON:Qt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=ze(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=oa(i,t),{lat:s,lng:r}=Is(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const n=ze(this.currentSighting,this.currentTime),s=na.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return ri.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=He.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),He.setIcon(this.miniMuteButton,this.mutedState?Qt.MUTED:Qt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){He.setIcon(this.muteButton,Qt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}He.setIcon(this.muteButton,this.mutedState?Qt.MUTED:Qt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;He.setIcon(this.fullscreenButton,t?Qt.EXIT_FULLSCREEN:Qt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new wr(wc.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=qg(wc.preferencesFor(this),Zg);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await D_.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=q3(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?Yg(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return so(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?w2(x2(this.realStartMs+i)):so(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?so(t):so(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return so(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return so(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?so(this.currentSighting.timeline.duration):this.canShowClockTime?w2(x2(this.realStartMs+this.realDurationMs)):so(this.realDurationMs)}}function x2(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function w2(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function so(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Jg="rr0-ufo";function Eb(){customElements.get(Jg)||customElements.define(Jg,He)}const Q_="recordingissues",Ab="minifiedreset";/**
1768
+ `);let e=Vl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Vl.shared.set(t,e),e.then(i=>{i.length===0&&Vl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.1")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==om?[e,om]:[om]).map(i=>i+t)}}class Ao{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,n)=>Ao.wayOf(i,n))}static wayOf(t,e){if(t.geometry.type!=="LineString")return[];const i=t.geometry.coordinates.map(([d,f])=>({lat:f,lng:d}));if(i.length<2)return[];const n=String(t.properties.nature??""),s=Ao.BY_NATURE[n]??Ao.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),l=Ao.DIRECTIONS[String(t.properties.sens_de_circulation??"")],h=Ao.KINDS[n],u=[t.properties.cpx_toponyme_route_nommee,t.properties.nom_voie_ban_gauche,t.properties.nom_voie_ban_droite].find(d=>typeof d=="string"&&d.length>0);return[{id:String(t.properties.cleabs??`ign-${e}`),...u?{name:u}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...t.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...l?{direction:l}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{},points:i}]}}class Y_{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(t){if(Ao.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class bd{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,n)=>bd.surfacesOf(i,n))}static surfacesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(t.properties.cleabs??`ign-water-${e}`);return s.flatMap((a,c)=>{const l=a.map(h=>bd.open(h.map(u=>({lat:u[1],lng:u[0]})))).filter(h=>h.length>=3);return l.length>0?[{id:s.length>1?`${r}-${c}`:r,rings:l}]:[]})}static open(t){const e=t[0],i=t[t.length-1];return t.length>1&&e.lat===i.lat&&e.lng===i.lng?t.slice(0,-1):t}}class fc{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new _s(t)}async getWater(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${e});way["waterway"="riverbank"](${e});)->.w;(relation["natural"="water"](${e});relation["waterway"="riverbank"](${e});)->.r;.w out geom;.r out body;way(r.r)(${e});out geom;`;return fc.surfacesFrom(await this.client.query(i))}static surfacesFrom(t){const e=t.elements??[],i=new Map;for(const r of e)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const n=[],s=new Set;for(const r of e){if(r.type!=="relation")continue;const a=l=>(r.members??[]).filter(h=>h.type==="way"&&h.role===l&&h.ref!==void 0&&i.has(h.ref)).map(h=>(s.add(h.ref),i.get(h.ref))),c=fc.rings(a("inner"));for(const[l,h]of fc.rings(a("outer")).entries()){const u=c.filter(d=>fc.contains(h,d[0]));n.push({id:`osm-r${r.id}-${l}`,rings:[h,...u]})}}for(const r of e)if(!(r.type!=="way"||!r.tags||r.id===void 0||s.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of fc.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(t){const e=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=t.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!e(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const c=i[a],l=s[s.length-1];if(e(l,c[0]))s=[...s,...c.slice(1)];else if(e(l,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&e(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(t,e){let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n],a=t[s];r.lat>e.lat!=a.lat>e.lat&&e.lng<(a.lng-r.lng)*(e.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class $_{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(bd.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const cm="https://ufoathome.org/water/index.json";class Wl{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Wl.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getWater(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.surfaces)?(this.attributionRead=s.attribution,s.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
1769
+ `);let e=Wl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Wl.shared.set(t,e),e.then(i=>{i.length===0&&Wl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.1")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==cm?[e,cm]:[cm]).map(i=>i+t)}}class vs{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=vs.key(t);let i=vs.asked.get(e);return i===void 0&&(i=this.recalled(e,t),vs.asked.set(e,i),i.catch(()=>vs.asked.delete(e))),structuredClone(await i)}static forget(){vs.asked.clear()}static key(t){return`v${vs.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await vs.openCache(),n=vs.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<vs.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&vs.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-vs.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(vs.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class _o{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>_o.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=_o.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=_o.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=_o.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const m=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>_o.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:m}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class zn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(t={}){this.client=new _s(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${zn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${zn.ROUTES})$"];out body;`;return zn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=zn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(M=>ae(M.lat,M.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(M=>M.service===!!r.service);for(const M of zn.samples(a)){u++;const v=zn.waysAt(d,M);if(v.length===0)continue;const[x]=v;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const y of new Set(v.flatMap(w=>w.services)))h.set(y,(h.get(y)??0)+1)}const f=M=>[...M.entries()].sort((v,x)=>x[1]-v[1])[0]?.[0],p=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(l)),g=[...h.entries()].filter(([,M])=>M*4>=u).sort((M,v)=>v[1]-M[1]||M[0].localeCompare(v[0])).map(([M])=>M);return{...r,...p?{name:p}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=zn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=zn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=zn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>ae(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=zn.SAMPLE_M/2;a<n;a+=zn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(zn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=zn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class Xl{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new _s(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Xl.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${zn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=zn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=zn.voltageOf(r),l=Xl.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=Xl.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:Xl.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class K_{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(t){if(!_o.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class cn{constructor(t,e=Date.now){this.railways=t,this.now=e}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(t){const e=cn.key(t);let i=cn.asked.get(e)??cn.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},cn.asked.set(e,i),n.catch(()=>cn.asked.delete(e))}return structuredClone(await i.answer)}static forget(){cn.asked.clear(),cn.failedAt=-1/0}static key(t){return`v${cn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of cn.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await cn.openCache(),n=cn.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<cn.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-cn.failedAt<cn.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(cn.failedAt=this.now(),s)return s;throw a}return i&&cn.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-cn.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(cn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const lm="https://ufoathome.org/railways/index.json";class Yl{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Yl.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
1770
+ `);let e=Yl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Yl.shared.set(t,e),e.then(i=>{i.length===0&&Yl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.170.1")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==lm?[e,lm]:[lm]).map(i=>i+t)}}function wb(){return{elevation:Sb(),imagery:bb(),roads:q_(),water:Z_(),railways:J_()}}function Sb(){return new V_(new Ce,new vb)}function bb(){return new xb}function q_(){return new Vl({fallback:new Y_(new Ao,new wo)})}function Z_(){return new Wl({fallback:new vs(new $_(new bd,new fc))})}function J_(){return new Yl({fallback:new cn(new K_(new _o,new Xl))})}const j_=new Set,fh="show-observer-map",ph="hide-milestones",Sc="minified";class Ge extends HTMLElement{static get observedAttributes(){return["src",fh,ph,Sc]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new fi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Ap.create();issues=[];issueCheck=0;sightingAudio=new w_;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>Ge.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Ge.setIcon(this.moreButton,t?Qt.UNFOLDED:Qt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Ge.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=fi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=fi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ge.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=fi.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${f_}</style>${d_}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Ph(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new dc(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===fh&&this.applyObserverMapDefault(),t===ph&&this.setMilestonesShown(!this.hasAttribute(ph)),t===Sc){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Sc)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(Ab)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const t=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",t),t&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(t){this.sightingData=await xd.recording(t)}get sightingData(){return b_(this.currentSighting)}set sightingData(t){const e=Qi.toCurrent(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=A_(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await $t(async()=>{const{default:r}=await import("./sightingSchema-B1hstz7u.js");return{default:r}},[],import.meta.url);n=new fr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],Sd.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(Q_,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=(this.messages?.recordingIssues??"").replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=Sd.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;!this.referenceOpacityTouched&&t.length>0&&(this.referenceOpacityInput.value=String(t[0].opacity));for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ge.setIcon(this.referencesButton,i?Qt.PICTURES_ON:Qt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Ge.setIcon(this.tracesButton,this.tracesShownState?Qt.TRACES_ON:Qt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?Du(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Ge.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Ge.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?sm(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new Ph(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=Ge.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?sm(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=vr.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ge.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ge.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ge.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ge.EXPOSURE_STEP_PX),s=Math.min(Ge.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=Xi.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}onFrame(t,e){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:j_;this.canvasRenderer.setStarPoints(Xi.starPointsOf(this.sighting.instrument,Be(this.sighting,t)?.fNumber));const n=(Be(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?zs.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(j3(this.currentSighting,t))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:t}}))}shifted(t,e){return e.x===0&&e.y===0?t:{...t,bounds:{...t.bounds,x:t.bounds.x+e.x,y:t.bounds.y+e.y}}}createPlayer(){const t=new p_(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*Ge.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?Qt.PLAY:Qt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ge.icons.get(t)!==e&&(Ge.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Ge.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),Ge.setIcon(this.playPauseButton,t?Qt.PAUSE:Qt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(fh),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;Ge.setIcon(this.observerMapButton,t?Qt.MAP_ON:Qt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=uh.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=fi.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?fi.expand(t,Ge.OBSERVER_MAP_IMAGERY_AHEAD):t,n=fi.IMAGERY_PX*(e?1+2*Ge.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapSnapshotImagery,r=s?void 0:bb();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?fi.expand(t,Ge.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(t){t!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=Ge.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=Be(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},Ge.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?sm(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?Du(this.currentSighting.milestones):[]){const a=Be(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?na.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(Xi.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,Du(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",Ge.setIcon(this.milestonesButton,this.milestonesShown?Qt.MILESTONES_ON:Qt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=Be(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=oa(i,t),{lat:s,lng:r}=Is(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const n=Be(this.currentSighting,this.currentTime),s=na.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return ri.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=Ge.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Ge.setIcon(this.miniMuteButton,this.mutedState?Qt.MUTED:Qt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){Ge.setIcon(this.muteButton,Qt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Ge.setIcon(this.muteButton,this.mutedState?Qt.MUTED:Qt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ge.setIcon(this.fullscreenButton,t?Qt.EXIT_FULLSCREEN:Qt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new wr(wc.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=qg(wc.preferencesFor(this),Zg);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await D_.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=q3(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?Yg(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return so(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?w2(x2(this.realStartMs+i)):so(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?so(t):so(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return so(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return so(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?so(this.currentSighting.timeline.duration):this.canShowClockTime?w2(x2(this.realStartMs+this.realDurationMs)):so(this.realDurationMs)}}function x2(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function w2(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function so(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Jg="rr0-ufo";function Eb(){customElements.get(Jg)||customElements.define(Jg,Ge)}const Q_="recordingissues",Ab="minifiedreset";/**
1771
1771
  * @license
1772
1772
  * Copyright 2010-2026 Three.js Authors
1773
1773
  * SPDX-License-Identifier: MIT
@@ -5882,7 +5882,7 @@ void main() {
5882
5882
 
5883
5883
  }
5884
5884
 
5885
- }`;class NC{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){const i=new Jb(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(t){if(this.texture!==null&&this.mesh===null){const e=t.cameras[0].viewport,i=new Te({vertexShader:PC,fragmentShader:OC,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new vt(new ss(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class LC extends Zo{constructor(t,e){super();const i=this;let n=null,s=1,r=null,a="local-floor",c=1,l=null,h=null,u=null,d=null,f=null,p=null;const m=typeof XRWebGLBinding<"u",g=new NC,M={},v=e.getContextAttributes();let x=null,y=null;const w=[],b=[],E=new tt;let S=null;const A=new Bn;A.viewport=new Ae;const _=new Bn;_.viewport=new Ae;const I=[A,_],D=new D4;let P=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let ct=w[Z];return ct===void 0&&(ct=new ym,w[Z]=ct),ct.getTargetRaySpace()},this.getControllerGrip=function(Z){let ct=w[Z];return ct===void 0&&(ct=new ym,w[Z]=ct),ct.getGripSpace()},this.getHand=function(Z){let ct=w[Z];return ct===void 0&&(ct=new ym,w[Z]=ct),ct.getHandSpace()};function O(Z){const ct=b.indexOf(Z.inputSource);if(ct===-1)return;const ot=w[ct];ot!==void 0&&(ot.update(Z.inputSource,Z.frame,l||r),ot.dispatchEvent({type:Z.type,data:Z.inputSource}))}function k(){n.removeEventListener("select",O),n.removeEventListener("selectstart",O),n.removeEventListener("selectend",O),n.removeEventListener("squeeze",O),n.removeEventListener("squeezestart",O),n.removeEventListener("squeezeend",O),n.removeEventListener("end",k),n.removeEventListener("inputsourceschange",H);for(let Z=0;Z<w.length;Z++){const ct=b[Z];ct!==null&&(b[Z]=null,w[Z].disconnect(ct))}P=null,L=null,g.reset();for(const Z in M)delete M[Z];t.setRenderTarget(x),f=null,d=null,u=null,n=null,y=null,Pt.stop(),i.isPresenting=!1,t.setPixelRatio(S),t.setSize(E.width,E.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){s=Z,i.isPresenting===!0&&Ft("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){a=Z,i.isPresenting===!0&&Ft("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||r},this.setReferenceSpace=function(Z){l=Z},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(n,e)),u},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function(Z){if(n=Z,n!==null){if(x=t.getRenderTarget(),n.addEventListener("select",O),n.addEventListener("selectstart",O),n.addEventListener("selectend",O),n.addEventListener("squeeze",O),n.addEventListener("squeezestart",O),n.addEventListener("squeezeend",O),n.addEventListener("end",k),n.addEventListener("inputsourceschange",H),v.xrCompatible!==!0&&await e.makeXRCompatible(),S=t.getPixelRatio(),t.getSize(E),m&&"createProjectionLayer"in XRWebGLBinding.prototype){let ot=null,V=null,Ot=null;v.depth&&(Ot=v.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,ot=v.stencil?bc:Ka,V=v.stencil?_d:rr);const Wt={colorFormat:e.RGBA8,depthFormat:Ot,scaleFactor:s};u=this.getBinding(),d=u.createProjectionLayer(Wt),n.updateRenderState({layers:[d]}),t.setPixelRatio(1),t.setSize(d.textureWidth,d.textureHeight,!1),y=new qe(d.textureWidth,d.textureHeight,{format:$i,type:Qn,depthTexture:new Yo(d.textureWidth,d.textureHeight,V,void 0,void 0,void 0,void 0,void 0,void 0,ot),stencilBuffer:v.stencil,colorSpace:t.outputColorSpace,samples:v.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const ot={antialias:v.antialias,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(n,e,ot),n.updateRenderState({baseLayer:f}),t.setPixelRatio(1),t.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new qe(f.framebufferWidth,f.framebufferHeight,{format:$i,type:Qn,colorSpace:t.outputColorSpace,stencilBuffer:v.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(c),l=null,r=await n.requestReferenceSpace(a),Pt.setContext(n),Pt.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function H(Z){for(let ct=0;ct<Z.removed.length;ct++){const ot=Z.removed[ct],V=b.indexOf(ot);V>=0&&(b[V]=null,w[V].disconnect(ot))}for(let ct=0;ct<Z.added.length;ct++){const ot=Z.added[ct];let V=b.indexOf(ot);if(V===-1){for(let Wt=0;Wt<w.length;Wt++)if(Wt>=b.length){b.push(ot),V=Wt;break}else if(b[Wt]===null){b[Wt]=ot,V=Wt;break}if(V===-1)break}const Ot=w[V];Ot&&Ot.connect(ot)}}const W=new R,Q=new R;function q(Z,ct,ot){W.setFromMatrixPosition(ct.matrixWorld),Q.setFromMatrixPosition(ot.matrixWorld);const V=W.distanceTo(Q),Ot=ct.projectionMatrix.elements,Wt=ot.projectionMatrix.elements,Nt=Ot[14]/(Ot[10]-1),Tt=Ot[14]/(Ot[10]+1),jt=(Ot[9]+1)/Ot[5],ie=(Ot[9]-1)/Ot[5],ne=(Ot[8]-1)/Ot[0],ei=(Wt[8]+1)/Wt[0],ii=Nt*ne,Fi=Nt*ei,Ni=V/(-ne+ei),zi=Ni*-ne;if(ct.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(zi),Z.translateZ(Ni),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),Ot[10]===-1)Z.projectionMatrix.copy(ct.projectionMatrix),Z.projectionMatrixInverse.copy(ct.projectionMatrixInverse);else{const an=Nt+Ni,z=Tt+Ni,Ms=ii-zi,ni=Fi+(V-zi),N=jt*Tt/z*an,T=ie*Tt/z*an;Z.projectionMatrix.makePerspective(Ms,ni,N,T,an,z),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function nt(Z,ct){ct===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(ct.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(n===null)return;let ct=Z.near,ot=Z.far;g.texture!==null&&(g.depthNear>0&&(ct=g.depthNear),g.depthFar>0&&(ot=g.depthFar)),D.near=_.near=A.near=ct,D.far=_.far=A.far=ot,(P!==D.near||L!==D.far)&&(n.updateRenderState({depthNear:D.near,depthFar:D.far}),P=D.near,L=D.far),D.layers.mask=Z.layers.mask|6,A.layers.mask=D.layers.mask&-5,_.layers.mask=D.layers.mask&-3;const V=Z.parent,Ot=D.cameras;nt(D,V);for(let Wt=0;Wt<Ot.length;Wt++)nt(Ot[Wt],V);Ot.length===2?q(D,A,_):D.projectionMatrix.copy(A.projectionMatrix),at(Z,D,V)};function at(Z,ct,ot){ot===null?Z.matrix.copy(ct.matrixWorld):(Z.matrix.copy(ot.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(ct.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(ct.projectionMatrix),Z.projectionMatrixInverse.copy(ct.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=kh*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return D},this.getFoveation=function(){if(!(d===null&&f===null))return c},this.setFoveation=function(Z){c=Z,d!==null&&(d.fixedFoveation=Z),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=Z)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(D)},this.getCameraTexture=function(Z){return M[Z]};let zt=null;function Zt(Z,ct){if(h=ct.getViewerPose(l||r),p=ct,h!==null){const ot=h.views;f!==null&&(t.setRenderTargetFramebuffer(y,f.framebuffer),t.setRenderTarget(y));let V=!1;ot.length!==D.cameras.length&&(D.cameras.length=0,V=!0);for(let Tt=0;Tt<ot.length;Tt++){const jt=ot[Tt];let ie=null;if(f!==null)ie=f.getViewport(jt);else{const ei=u.getViewSubImage(d,jt);ie=ei.viewport,Tt===0&&(t.setRenderTargetTextures(y,ei.colorTexture,ei.depthStencilTexture),t.setRenderTarget(y))}let ne=I[Tt];ne===void 0&&(ne=new Bn,ne.layers.enable(Tt),ne.viewport=new Ae,I[Tt]=ne),ne.matrix.fromArray(jt.transform.matrix),ne.matrix.decompose(ne.position,ne.quaternion,ne.scale),ne.projectionMatrix.fromArray(jt.projectionMatrix),ne.projectionMatrixInverse.copy(ne.projectionMatrix).invert(),ne.viewport.set(ie.x,ie.y,ie.width,ie.height),Tt===0&&(D.matrix.copy(ne.matrix),D.matrix.decompose(D.position,D.quaternion,D.scale)),V===!0&&D.cameras.push(ne)}const Ot=n.enabledFeatures;if(Ot&&Ot.includes("depth-sensing")&&n.depthUsage=="gpu-optimized"&&m){u=i.getBinding();const Tt=u.getDepthInformation(ot[0]);Tt&&Tt.isValid&&Tt.texture&&g.init(Tt,n.renderState)}if(Ot&&Ot.includes("camera-access")&&m){t.state.unbindTexture(),u=i.getBinding();for(let Tt=0;Tt<ot.length;Tt++){const jt=ot[Tt].camera;if(jt){let ie=M[jt];ie||(ie=new Jb,M[jt]=ie);const ne=u.getCameraImage(jt);ie.sourceTexture=ne}}}}for(let ot=0;ot<w.length;ot++){const V=b[ot],Ot=w[ot];V!==null&&Ot!==void 0&&Ot.update(V,ct,l||r)}zt&&zt(Z,ct),ct.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ct}),p=null}const Pt=new pE;Pt.setAnimationLoop(Zt),this.setAnimationLoop=function(Z){zt=Z},this.dispose=function(){}}}const kC=new Vt,xE=new ue;xE.set(-1,0,0,0,1,0,0,0,1);function UC(o,t){function e(g,M){g.matrixAutoUpdate===!0&&g.updateMatrix(),M.value.copy(g.matrix)}function i(g,M){M.color.getRGB(g.fogColor.value,aE(o)),M.isFog?(g.fogNear.value=M.near,g.fogFar.value=M.far):M.isFogExp2&&(g.fogDensity.value=M.density)}function n(g,M,v,x,y){M.isNodeMaterial?M.uniformsNeedUpdate=!1:M.isMeshBasicMaterial?s(g,M):M.isMeshLambertMaterial?(s(g,M),M.envMap&&(g.envMapIntensity.value=M.envMapIntensity)):M.isMeshToonMaterial?(s(g,M),u(g,M)):M.isMeshPhongMaterial?(s(g,M),h(g,M),M.envMap&&(g.envMapIntensity.value=M.envMapIntensity)):M.isMeshStandardMaterial?(s(g,M),d(g,M),M.isMeshPhysicalMaterial&&f(g,M,y)):M.isMeshMatcapMaterial?(s(g,M),p(g,M)):M.isMeshDepthMaterial?s(g,M):M.isMeshDistanceMaterial?(s(g,M),m(g,M)):M.isMeshNormalMaterial?s(g,M):M.isLineBasicMaterial?(r(g,M),M.isLineDashedMaterial&&a(g,M)):M.isPointsMaterial?c(g,M,v,x):M.isSpriteMaterial?l(g,M):M.isShadowMaterial?(g.color.value.copy(M.color),g.opacity.value=M.opacity):M.isShaderMaterial&&(M.uniformsNeedUpdate=!1)}function s(g,M){g.opacity.value=M.opacity,M.color&&g.diffuse.value.copy(M.color),M.emissive&&g.emissive.value.copy(M.emissive).multiplyScalar(M.emissiveIntensity),M.map&&(g.map.value=M.map,e(M.map,g.mapTransform)),M.alphaMap&&(g.alphaMap.value=M.alphaMap,e(M.alphaMap,g.alphaMapTransform)),M.bumpMap&&(g.bumpMap.value=M.bumpMap,e(M.bumpMap,g.bumpMapTransform),g.bumpScale.value=M.bumpScale,M.side===Ci&&(g.bumpScale.value*=-1)),M.normalMap&&(g.normalMap.value=M.normalMap,e(M.normalMap,g.normalMapTransform),g.normalScale.value.copy(M.normalScale),M.side===Ci&&g.normalScale.value.negate()),M.displacementMap&&(g.displacementMap.value=M.displacementMap,e(M.displacementMap,g.displacementMapTransform),g.displacementScale.value=M.displacementScale,g.displacementBias.value=M.displacementBias),M.emissiveMap&&(g.emissiveMap.value=M.emissiveMap,e(M.emissiveMap,g.emissiveMapTransform)),M.specularMap&&(g.specularMap.value=M.specularMap,e(M.specularMap,g.specularMapTransform)),M.alphaTest>0&&(g.alphaTest.value=M.alphaTest);const v=t.get(M),x=v.envMap,y=v.envMapRotation;x&&(g.envMap.value=x,g.envMapRotation.value.setFromMatrix4(kC.makeRotationFromEuler(y)).transpose(),x.isCubeTexture&&x.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(xE),g.reflectivity.value=M.reflectivity,g.ior.value=M.ior,g.refractionRatio.value=M.refractionRatio),M.lightMap&&(g.lightMap.value=M.lightMap,g.lightMapIntensity.value=M.lightMapIntensity,e(M.lightMap,g.lightMapTransform)),M.aoMap&&(g.aoMap.value=M.aoMap,g.aoMapIntensity.value=M.aoMapIntensity,e(M.aoMap,g.aoMapTransform))}function r(g,M){g.diffuse.value.copy(M.color),g.opacity.value=M.opacity,M.map&&(g.map.value=M.map,e(M.map,g.mapTransform))}function a(g,M){g.dashSize.value=M.dashSize,g.totalSize.value=M.dashSize+M.gapSize,g.scale.value=M.scale}function c(g,M,v,x){g.diffuse.value.copy(M.color),g.opacity.value=M.opacity,g.size.value=M.size*v,g.scale.value=x*.5,M.map&&(g.map.value=M.map,e(M.map,g.uvTransform)),M.alphaMap&&(g.alphaMap.value=M.alphaMap,e(M.alphaMap,g.alphaMapTransform)),M.alphaTest>0&&(g.alphaTest.value=M.alphaTest)}function l(g,M){g.diffuse.value.copy(M.color),g.opacity.value=M.opacity,g.rotation.value=M.rotation,M.map&&(g.map.value=M.map,e(M.map,g.mapTransform)),M.alphaMap&&(g.alphaMap.value=M.alphaMap,e(M.alphaMap,g.alphaMapTransform)),M.alphaTest>0&&(g.alphaTest.value=M.alphaTest)}function h(g,M){g.specular.value.copy(M.specular),g.shininess.value=Math.max(M.shininess,1e-4)}function u(g,M){M.gradientMap&&(g.gradientMap.value=M.gradientMap)}function d(g,M){g.metalness.value=M.metalness,M.metalnessMap&&(g.metalnessMap.value=M.metalnessMap,e(M.metalnessMap,g.metalnessMapTransform)),g.roughness.value=M.roughness,M.roughnessMap&&(g.roughnessMap.value=M.roughnessMap,e(M.roughnessMap,g.roughnessMapTransform)),M.envMap&&(g.envMapIntensity.value=M.envMapIntensity)}function f(g,M,v){g.ior.value=M.ior,M.sheen>0&&(g.sheenColor.value.copy(M.sheenColor).multiplyScalar(M.sheen),g.sheenRoughness.value=M.sheenRoughness,M.sheenColorMap&&(g.sheenColorMap.value=M.sheenColorMap,e(M.sheenColorMap,g.sheenColorMapTransform)),M.sheenRoughnessMap&&(g.sheenRoughnessMap.value=M.sheenRoughnessMap,e(M.sheenRoughnessMap,g.sheenRoughnessMapTransform))),M.clearcoat>0&&(g.clearcoat.value=M.clearcoat,g.clearcoatRoughness.value=M.clearcoatRoughness,M.clearcoatMap&&(g.clearcoatMap.value=M.clearcoatMap,e(M.clearcoatMap,g.clearcoatMapTransform)),M.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=M.clearcoatRoughnessMap,e(M.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),M.clearcoatNormalMap&&(g.clearcoatNormalMap.value=M.clearcoatNormalMap,e(M.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(M.clearcoatNormalScale),M.side===Ci&&g.clearcoatNormalScale.value.negate())),M.dispersion>0&&(g.dispersion.value=M.dispersion),M.iridescence>0&&(g.iridescence.value=M.iridescence,g.iridescenceIOR.value=M.iridescenceIOR,g.iridescenceThicknessMinimum.value=M.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=M.iridescenceThicknessRange[1],M.iridescenceMap&&(g.iridescenceMap.value=M.iridescenceMap,e(M.iridescenceMap,g.iridescenceMapTransform)),M.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=M.iridescenceThicknessMap,e(M.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),M.transmission>0&&(g.transmission.value=M.transmission,g.transmissionSamplerMap.value=v.texture,g.transmissionSamplerSize.value.set(v.width,v.height),M.transmissionMap&&(g.transmissionMap.value=M.transmissionMap,e(M.transmissionMap,g.transmissionMapTransform)),g.thickness.value=M.thickness,M.thicknessMap&&(g.thicknessMap.value=M.thicknessMap,e(M.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=M.attenuationDistance,g.attenuationColor.value.copy(M.attenuationColor)),M.anisotropy>0&&(g.anisotropyVector.value.set(M.anisotropy*Math.cos(M.anisotropyRotation),M.anisotropy*Math.sin(M.anisotropyRotation)),M.anisotropyMap&&(g.anisotropyMap.value=M.anisotropyMap,e(M.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=M.specularIntensity,g.specularColor.value.copy(M.specularColor),M.specularColorMap&&(g.specularColorMap.value=M.specularColorMap,e(M.specularColorMap,g.specularColorMapTransform)),M.specularIntensityMap&&(g.specularIntensityMap.value=M.specularIntensityMap,e(M.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,M){M.matcap&&(g.matcap.value=M.matcap)}function m(g,M){const v=t.get(M).light;g.referencePosition.value.setFromMatrixPosition(v.matrixWorld),g.nearDistance.value=v.shadow.camera.near,g.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function FC(o,t,e,i){let n={},s={},r=[];const a=o.getParameter(o.MAX_UNIFORM_BUFFER_BINDINGS);function c(y,w){const b=w.program;i.uniformBlockBinding(y,b)}function l(y,w){let b=n[y.id];b===void 0&&(g(y),b=h(y),n[y.id]=b,y.addEventListener("dispose",v));const E=w.program;i.updateUBOMapping(y,E);const S=t.render.frame;s[y.id]!==S&&(d(y),s[y.id]=S)}function h(y){const w=u();y.__bindingPointIndex=w;const b=o.createBuffer(),E=y.__size,S=y.usage;return o.bindBuffer(o.UNIFORM_BUFFER,b),o.bufferData(o.UNIFORM_BUFFER,E,S),o.bindBuffer(o.UNIFORM_BUFFER,null),o.bindBufferBase(o.UNIFORM_BUFFER,w,b),b}function u(){for(let y=0;y<a;y++)if(r.indexOf(y)===-1)return r.push(y),y;return ce("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(y){const w=n[y.id],b=y.uniforms,E=y.__cache;o.bindBuffer(o.UNIFORM_BUFFER,w);for(let S=0,A=b.length;S<A;S++){const _=b[S];if(Array.isArray(_))for(let I=0,D=_.length;I<D;I++)f(_[I],S,I,E);else f(_,S,0,E)}o.bindBuffer(o.UNIFORM_BUFFER,null)}function f(y,w,b,E){if(m(y,w,b,E)===!0){const S=y.__offset,A=y.value;if(Array.isArray(A)){let _=0;for(let I=0;I<A.length;I++){const D=A[I],P=M(D);p(D,y.__data,_),typeof D!="number"&&typeof D!="boolean"&&!D.isMatrix3&&!ArrayBuffer.isView(D)&&(_+=P.storage/Float32Array.BYTES_PER_ELEMENT)}}else p(A,y.__data,0);o.bufferSubData(o.UNIFORM_BUFFER,S,y.__data)}}function p(y,w,b){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,b)}function m(y,w,b,E){const S=y.value,A=w+"_"+b;if(E[A]===void 0)return typeof S=="number"||typeof S=="boolean"?E[A]=S:ArrayBuffer.isView(S)?E[A]=S.slice():E[A]=S.clone(),!0;{const _=E[A];if(typeof S=="number"||typeof S=="boolean"){if(_!==S)return E[A]=S,!0}else{if(ArrayBuffer.isView(S))return!0;if(_.equals(S)===!1)return _.copy(S),!0}}return!1}function g(y){const w=y.uniforms;let b=0;const E=16;for(let A=0,_=w.length;A<_;A++){const I=Array.isArray(w[A])?w[A]:[w[A]];for(let D=0,P=I.length;D<P;D++){const L=I[D],O=Array.isArray(L.value)?L.value:[L.value];for(let k=0,H=O.length;k<H;k++){const W=O[k],Q=M(W),q=b%E,nt=q%Q.boundary,at=q+nt;b+=nt,at!==0&&E-at<Q.storage&&(b+=E-at),L.__data=new Float32Array(Q.storage/Float32Array.BYTES_PER_ELEMENT),L.__offset=b,b+=Q.storage}}}const S=b%E;return S>0&&(b+=E-S),y.__size=b,y.__cache={},this}function M(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?Ft("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):Ft("WebGLRenderer: Unsupported uniform value type.",y),w}function v(y){const w=y.target;w.removeEventListener("dispose",v);const b=r.indexOf(w.__bindingPointIndex);r.splice(b,1),o.deleteBuffer(n[w.id]),delete n[w.id],delete s[w.id]}function x(){for(const y in n)o.deleteBuffer(n[y]);r=[],n={},s={}}return{bind:c,update:l,dispose:x}}const zC=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Or=null;function BC(){return Or===null&&(Or=new ms(zC,16,16,Bc,We),Or.name="DFG_LUT",Or.minFilter=ge,Or.magFilter=ge,Or.wrapS=Yi,Or.wrapT=Yi,Or.generateMipmaps=!1,Or.needsUpdate=!0),Or}class HC{constructor(t={}){const{canvas:e=LT(),context:i=null,depth:n=!0,stencil:s=!1,alpha:r=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Qn}=t;this.isWebGLRenderer=!0;let p;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=r;const m=f,g=new Set([tv,QM,jM]),M=new Set([Qn,rr,Ad,_d,ZM,JM]),v=new Uint32Array(4),x=new Int32Array(4),y=new R;let w=null,b=null;const E=[],S=[];let A=null;this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ua,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const _=this;let I=!1,D=null,P=null,L=null,O=null;this._outputColorSpace=Pn;let k=0,H=0,W=null,Q=-1,q=null;const nt=new Ae,at=new Ae;let zt=null;const Zt=new rt(0);let Pt=0,Z=e.width,ct=e.height,ot=1,V=null,Ot=null;const Wt=new Ae(0,0,Z,ct),Nt=new Ae(0,0,Z,ct);let Tt=!1;const jt=new Rp;let ie=!1,ne=!1;const ei=new Vt,ii=new R,Fi=new Ae,Ni={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let zi=!1;function an(){return W===null?ot:1}let z=i;function Ms(C,B){return e.getContext(C,B)}try{const C={alpha:!0,depth:n,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Bd}`),e.addEventListener("webglcontextlost",Bi,!1),e.addEventListener("webglcontextrestored",xi,!1),e.addEventListener("webglcontextcreationerror",Rr,!1),z===null){const B="webgl2";if(z=Ms(B,C),z===null)throw Ms(B)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(C){throw ce("WebGLRenderer: "+C.message),C}let ni,N,T,G,$,J,ht,ft,j,it,mt,Xt,xt,gt,Jt,se,Se,F,dt,et,Mt,Et,st;function Gt(){ni=new BD(z),ni.init(),Mt=new CC(z,ni),N=new PD(z,ni,t,Mt),T=new IC(z,ni),N.reversedDepthBuffer&&d&&T.buffers.depth.setReversed(!0),P=z.createFramebuffer(),L=z.createFramebuffer(),O=z.createFramebuffer(),G=new VD(z),$=new mC,J=new DC(z,ni,T,$,N,Mt,G),ht=new zD(_),ft=new $4(z),Et=new DD(z,ft),j=new HD(z,ft,G,Et),it=new XD(z,j,ft,Et,G),F=new WD(z,N,J),Jt=new OD($),mt=new pC(_,ht,ni,N,Et,Jt),Xt=new UC(_,$),xt=new MC,gt=new bC(ni),Se=new ID(_,ht,T,it,p,c),se=new RC(_,it,N),st=new FC(z,G,N,T),dt=new CD(z,ni,G),et=new GD(z,ni,G),G.programs=mt.programs,_.capabilities=N,_.extensions=ni,_.properties=$,_.renderLists=xt,_.shadowMap=se,_.state=T,_.info=G}Gt(),m!==Qn&&(A=new $D(m,e.width,e.height,a,n,s));const Lt=new LC(_,z);this.xr=Lt,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){const C=ni.get("WEBGL_lose_context");C&&C.loseContext()},this.forceContextRestore=function(){const C=ni.get("WEBGL_lose_context");C&&C.restoreContext()},this.getPixelRatio=function(){return ot},this.setPixelRatio=function(C){C!==void 0&&(ot=C,this.setSize(Z,ct,!1))},this.getSize=function(C){return C.set(Z,ct)},this.setSize=function(C,B,K=!0){if(Lt.isPresenting){Ft("WebGLRenderer: Can't change size while VR device is presenting.");return}Z=C,ct=B,e.width=Math.floor(C*ot),e.height=Math.floor(B*ot),K===!0&&(e.style.width=C+"px",e.style.height=B+"px"),A!==null&&A.setSize(e.width,e.height),this.setViewport(0,0,C,B)},this.getDrawingBufferSize=function(C){return C.set(Z*ot,ct*ot).floor()},this.setDrawingBufferSize=function(C,B,K){Z=C,ct=B,ot=K,e.width=Math.floor(C*K),e.height=Math.floor(B*K),this.setViewport(0,0,C,B)},this.setEffects=function(C){if(m===Qn){ce("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(C){for(let B=0;B<C.length;B++)if(C[B].isOutputPass===!0){Ft("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(C||[])},this.getCurrentViewport=function(C){return C.copy(nt)},this.getViewport=function(C){return C.copy(Wt)},this.setViewport=function(C,B,K,X){C.isVector4?Wt.set(C.x,C.y,C.z,C.w):Wt.set(C,B,K,X),T.viewport(nt.copy(Wt).multiplyScalar(ot).round())},this.getScissor=function(C){return C.copy(Nt)},this.setScissor=function(C,B,K,X){C.isVector4?Nt.set(C.x,C.y,C.z,C.w):Nt.set(C,B,K,X),T.scissor(at.copy(Nt).multiplyScalar(ot).round())},this.getScissorTest=function(){return Tt},this.setScissorTest=function(C){T.setScissorTest(Tt=C)},this.setOpaqueSort=function(C){V=C},this.setTransparentSort=function(C){Ot=C},this.getClearColor=function(C){return C.copy(Se.getClearColor())},this.setClearColor=function(){Se.setClearColor(...arguments)},this.getClearAlpha=function(){return Se.getClearAlpha()},this.setClearAlpha=function(){Se.setClearAlpha(...arguments)},this.clear=function(C=!0,B=!0,K=!0){let X=0;if(C){let Y=!1;if(W!==null){const bt=W.texture.format;Y=g.has(bt)}if(Y){const bt=W.texture.type,Rt=M.has(bt),St=Se.getClearColor(),kt=Se.getClearAlpha(),Yt=St.r,be=St.g,Ie=St.b;Rt?(v[0]=Yt,v[1]=be,v[2]=Ie,v[3]=kt,z.clearBufferuiv(z.COLOR,0,v)):(x[0]=Yt,x[1]=be,x[2]=Ie,x[3]=kt,z.clearBufferiv(z.COLOR,0,x))}else X|=z.COLOR_BUFFER_BIT}B&&(X|=z.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),K&&(X|=z.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),X!==0&&z.clear(X)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(C){C.setRenderer(this),D=C},this.dispose=function(){e.removeEventListener("webglcontextlost",Bi,!1),e.removeEventListener("webglcontextrestored",xi,!1),e.removeEventListener("webglcontextcreationerror",Rr,!1),Se.dispose(),xt.dispose(),gt.dispose(),$.dispose(),ht.dispose(),it.dispose(),Et.dispose(),st.dispose(),mt.dispose(),Lt.dispose(),Lt.removeEventListener("sessionstart",Xv),Lt.removeEventListener("sessionend",Yv),jo.stop()};function Bi(C){C.preventDefault(),K0("WebGLRenderer: Context Lost."),I=!0}function xi(){K0("WebGLRenderer: Context Restored."),I=!1;const C=G.autoReset,B=se.enabled,K=se.autoUpdate,X=se.needsUpdate,Y=se.type;Gt(),G.autoReset=C,se.enabled=B,se.autoUpdate=K,se.needsUpdate=X,se.type=Y}function Rr(C){ce("WebGLRenderer: A WebGL context could not be created. Reason: ",C.statusMessage)}function Ir(C){const B=C.target;B.removeEventListener("dispose",Ir),EA(B)}function EA(C){AA(C),$.remove(C)}function AA(C){const B=$.get(C).programs;B!==void 0&&(B.forEach(function(K){mt.releaseProgram(K)}),C.isShaderMaterial&&mt.releaseShaderCache(C))}this.renderBufferDirect=function(C,B,K,X,Y,bt){B===null&&(B=Ni);const Rt=Y.isMesh&&Y.matrixWorld.determinantAffine()<0,St=RA(C,B,K,X,Y);T.setMaterial(X,Rt);let kt=K.index,Yt=1;if(X.wireframe===!0){if(kt=j.getWireframeAttribute(K),kt===void 0)return;Yt=2}const be=K.drawRange,Ie=K.attributes.position;let Kt=be.start*Yt,di=(be.start+be.count)*Yt;bt!==null&&(Kt=Math.max(Kt,bt.start*Yt),di=Math.min(di,(bt.start+bt.count)*Yt)),kt!==null?(Kt=Math.max(Kt,0),di=Math.min(di,kt.count)):Ie!=null&&(Kt=Math.max(Kt,0),di=Math.min(di,Ie.count));const qi=di-Kt;if(qi<0||qi===1/0)return;Et.setup(Y,X,St,K,kt);let Hi,Mi=dt;if(kt!==null&&(Hi=ft.get(kt),Mi=et,Mi.setIndex(Hi)),Y.isMesh)X.wireframe===!0?(T.setLineWidth(X.wireframeLinewidth*an()),Mi.setMode(z.LINES)):Mi.setMode(z.TRIANGLES);else if(Y.isLine){let Gn=X.linewidth;Gn===void 0&&(Gn=1),T.setLineWidth(Gn*an()),Y.isLineSegments?Mi.setMode(z.LINES):Y.isLineLoop?Mi.setMode(z.LINE_LOOP):Mi.setMode(z.LINE_STRIP)}else Y.isPoints?Mi.setMode(z.POINTS):Y.isSprite&&Mi.setMode(z.TRIANGLES);if(Y.isBatchedMesh)if(ni.get("WEBGL_multi_draw"))Mi.renderMultiDraw(Y._multiDrawStarts,Y._multiDrawCounts,Y._multiDrawCount);else{const Gn=Y._multiDrawStarts,_t=Y._multiDrawCounts,Os=Y._multiDrawCount,Be=kt?ft.get(kt).bytesPerElement:1,Ys=$.get(X).currentProgram.getUniforms();for(let Dr=0;Dr<Os;Dr++)Ys.setValue(z,"_gl_DrawID",Dr),Mi.render(Gn[Dr]/Be,_t[Dr])}else if(Y.isInstancedMesh)Mi.renderInstances(Kt,qi,Y.count);else if(K.isInstancedBufferGeometry){const Gn=K._maxInstanceCount!==void 0?K._maxInstanceCount:1/0,_t=Math.min(K.instanceCount,Gn);Mi.renderInstances(Kt,qi,_t)}else Mi.render(Kt,qi)};function Wv(C,B,K){C.transparent===!0&&C.side===xn&&C.forceSinglePass===!1?(C.side=Ci,C.needsUpdate=!0,Yd(C,B,K),C.side=pa,C.needsUpdate=!0,Yd(C,B,K),C.side=xn):Yd(C,B,K)}this.compile=function(C,B,K=null){K===null&&(K=C),b=gt.get(K),b.init(B),S.push(b),K.traverseVisible(function(Y){Y.isLight&&Y.layers.test(B.layers)&&(b.pushLight(Y),Y.castShadow&&b.pushShadow(Y))}),C!==K&&C.traverseVisible(function(Y){Y.isLight&&Y.layers.test(B.layers)&&(b.pushLight(Y),Y.castShadow&&b.pushShadow(Y))}),b.setupLights();const X=new Set;return C.traverse(function(Y){if(!(Y.isMesh||Y.isPoints||Y.isLine||Y.isSprite))return;const bt=Y.material;if(bt)if(Array.isArray(bt))for(let Rt=0;Rt<bt.length;Rt++){const St=bt[Rt];Wv(St,K,Y),X.add(St)}else Wv(bt,K,Y),X.add(bt)}),b=S.pop(),X},this.compileAsync=function(C,B,K=null){const X=this.compile(C,B,K);return new Promise(Y=>{function bt(){if(X.forEach(function(Rt){$.get(Rt).currentProgram.isReady()&&X.delete(Rt)}),X.size===0){Y(C);return}setTimeout(bt,10)}ni.get("KHR_parallel_shader_compile")!==null?bt():setTimeout(bt,10)})};let Wp=null;function _A(C){Wp&&Wp(C)}function Xv(){jo.stop()}function Yv(){jo.start()}const jo=new pE;jo.setAnimationLoop(_A),typeof self<"u"&&jo.setContext(self),this.setAnimationLoop=function(C){Wp=C,Lt.setAnimationLoop(C),C===null?jo.stop():jo.start()},Lt.addEventListener("sessionstart",Xv),Lt.addEventListener("sessionend",Yv),this.render=function(C,B){if(B!==void 0&&B.isCamera!==!0){ce("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(I===!0)return;D!==null&&D.renderStart(C,B);const K=Lt.enabled===!0&&Lt.isPresenting===!0,X=A!==null&&(W===null||K)&&A.begin(_,W);if(C.matrixWorldAutoUpdate===!0&&C.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),Lt.enabled===!0&&Lt.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(Lt.cameraAutoUpdate===!0&&Lt.updateCamera(B),B=Lt.getCamera()),C.isScene===!0&&C.onBeforeRender(_,C,B,W),b=gt.get(C,S.length),b.init(B),b.state.textureUnits=J.getTextureUnits(),S.push(b),ei.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),jt.setFromProjectionMatrix(ei,ca,B.reversedDepth),ne=this.localClippingEnabled,ie=Jt.init(this.clippingPlanes,ne),w=xt.get(C,E.length),w.init(),E.push(w),Lt.enabled===!0&&Lt.isPresenting===!0){const Rt=_.xr.getDepthSensingMesh();Rt!==null&&Xp(Rt,B,-1/0,_.sortObjects)}Xp(C,B,0,_.sortObjects),w.finish(),_.sortObjects===!0&&w.sort(V,Ot,B.reversedDepth),zi=Lt.enabled===!1||Lt.isPresenting===!1||Lt.hasDepthSensing()===!1,zi&&Se.addToRenderList(w,C),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ie===!0&&Jt.beginShadows();const Y=b.state.shadowsArray;if(se.render(Y,C,B),ie===!0&&Jt.endShadows(),(X&&A.hasRenderPass())===!1){const Rt=w.opaque,St=w.transmissive;if(b.setupLights(),B.isArrayCamera){const kt=B.cameras;if(St.length>0)for(let Yt=0,be=kt.length;Yt<be;Yt++){const Ie=kt[Yt];Kv(Rt,St,C,Ie)}zi&&Se.render(C);for(let Yt=0,be=kt.length;Yt<be;Yt++){const Ie=kt[Yt];$v(w,C,Ie,Ie.viewport)}}else St.length>0&&Kv(Rt,St,C,B),zi&&Se.render(C),$v(w,C,B)}W!==null&&H===0&&(J.updateMultisampleRenderTarget(W),J.updateRenderTargetMipmap(W)),X&&A.end(_),C.isScene===!0&&C.onAfterRender(_,C,B),Et.resetDefaultState(),Q=-1,q=null,S.pop(),S.length>0?(b=S[S.length-1],J.setTextureUnits(b.state.textureUnits),ie===!0&&Jt.setGlobalState(_.clippingPlanes,b.state.camera)):b=null,E.pop(),E.length>0?w=E[E.length-1]:w=null,D!==null&&D.renderEnd()};function Xp(C,B,K,X){if(C.visible===!1)return;if(C.layers.test(B.layers)){if(C.isGroup)K=C.renderOrder;else if(C.isLOD)C.autoUpdate===!0&&C.update(B);else if(C.isLightProbeGrid)b.pushLightProbeGrid(C);else if(C.isLight)b.pushLight(C),C.castShadow&&b.pushShadow(C);else if(C.isSprite){if(!C.frustumCulled||jt.intersectsSprite(C)){X&&Fi.setFromMatrixPosition(C.matrixWorld).applyMatrix4(ei);const Rt=it.update(C),St=C.material;St.visible&&w.push(C,Rt,St,K,Fi.z,null)}}else if((C.isMesh||C.isLine||C.isPoints)&&(!C.frustumCulled||jt.intersectsObject(C))){const Rt=it.update(C),St=C.material;if(X&&(C.boundingSphere!==void 0?(C.boundingSphere===null&&C.computeBoundingSphere(),Fi.copy(C.boundingSphere.center)):(Rt.boundingSphere===null&&Rt.computeBoundingSphere(),Fi.copy(Rt.boundingSphere.center)),Fi.applyMatrix4(C.matrixWorld).applyMatrix4(ei)),Array.isArray(St)){const kt=Rt.groups;for(let Yt=0,be=kt.length;Yt<be;Yt++){const Ie=kt[Yt],Kt=St[Ie.materialIndex];Kt&&Kt.visible&&w.push(C,Rt,Kt,K,Fi.z,Ie)}}else St.visible&&w.push(C,Rt,St,K,Fi.z,null)}}const bt=C.children;for(let Rt=0,St=bt.length;Rt<St;Rt++)Xp(bt[Rt],B,K,X)}function $v(C,B,K,X){const{opaque:Y,transmissive:bt,transparent:Rt}=C;b.setupLightsView(K),ie===!0&&Jt.setGlobalState(_.clippingPlanes,K),X&&T.viewport(nt.copy(X)),Y.length>0&&Xd(Y,B,K),bt.length>0&&Xd(bt,B,K),Rt.length>0&&Xd(Rt,B,K),T.buffers.depth.setTest(!0),T.buffers.depth.setMask(!0),T.buffers.color.setMask(!0),T.setPolygonOffset(!1)}function Kv(C,B,K,X){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;if(b.state.transmissionRenderTarget[X.id]===void 0){const Kt=ni.has("EXT_color_buffer_half_float")||ni.has("EXT_color_buffer_float");b.state.transmissionRenderTarget[X.id]=new qe(1,1,{generateMipmaps:!0,type:Kt?We:Qn,minFilter:Vs,samples:Math.max(4,N.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ue.workingColorSpace})}const bt=b.state.transmissionRenderTarget[X.id],Rt=X.viewport||nt;bt.setSize(Rt.z*_.transmissionResolutionScale,Rt.w*_.transmissionResolutionScale);const St=_.getRenderTarget(),kt=_.getActiveCubeFace(),Yt=_.getActiveMipmapLevel();_.setRenderTarget(bt),_.getClearColor(Zt),Pt=_.getClearAlpha(),Pt<1&&_.setClearColor(16777215,.5),_.clear(),zi&&Se.render(K);const be=_.toneMapping;_.toneMapping=ua;const Ie=X.viewport;if(X.viewport!==void 0&&(X.viewport=void 0),b.setupLightsView(X),ie===!0&&Jt.setGlobalState(_.clippingPlanes,X),Xd(C,K,X),J.updateMultisampleRenderTarget(bt),J.updateRenderTargetMipmap(bt),ni.has("WEBGL_multisampled_render_to_texture")===!1){let Kt=!1;for(let di=0,qi=B.length;di<qi;di++){const Hi=B[di],{object:Mi,geometry:Gn,material:_t,group:Os}=Hi;if(_t.side===xn&&Mi.layers.test(X.layers)){const Be=_t.side;_t.side=Ci,_t.needsUpdate=!0,qv(Mi,K,X,Gn,_t,Os),_t.side=Be,_t.needsUpdate=!0,Kt=!0}}Kt===!0&&(J.updateMultisampleRenderTarget(bt),J.updateRenderTargetMipmap(bt))}_.setRenderTarget(St,kt,Yt),_.setClearColor(Zt,Pt),Ie!==void 0&&(X.viewport=Ie),_.toneMapping=be}function Xd(C,B,K){const X=B.isScene===!0?B.overrideMaterial:null;for(let Y=0,bt=C.length;Y<bt;Y++){const Rt=C[Y],{object:St,geometry:kt,group:Yt}=Rt;let be=Rt.material;be.allowOverride===!0&&X!==null&&(be=X),St.layers.test(K.layers)&&qv(St,B,K,kt,be,Yt)}}function qv(C,B,K,X,Y,bt){C.onBeforeRender(_,B,K,X,Y,bt),C.modelViewMatrix.multiplyMatrices(K.matrixWorldInverse,C.matrixWorld),C.normalMatrix.getNormalMatrix(C.modelViewMatrix),Y.onBeforeRender(_,B,K,X,C,bt),Y.transparent===!0&&Y.side===xn&&Y.forceSinglePass===!1?(Y.side=Ci,Y.needsUpdate=!0,_.renderBufferDirect(K,B,X,Y,C,bt),Y.side=pa,Y.needsUpdate=!0,_.renderBufferDirect(K,B,X,Y,C,bt),Y.side=xn):_.renderBufferDirect(K,B,X,Y,C,bt),C.onAfterRender(_,B,K,X,Y,bt)}function Yd(C,B,K){B.isScene!==!0&&(B=Ni);const X=$.get(C),Y=b.state.lights,bt=b.state.shadowsArray,Rt=Y.state.version,St=mt.getParameters(C,Y.state,bt,B,K,b.state.lightProbeGridArray),kt=mt.getProgramCacheKey(St);let Yt=X.programs;X.environment=C.isMeshStandardMaterial||C.isMeshLambertMaterial||C.isMeshPhongMaterial?B.environment:null,X.fog=B.fog;const be=C.isMeshStandardMaterial||C.isMeshLambertMaterial&&!C.envMap||C.isMeshPhongMaterial&&!C.envMap;X.envMap=ht.get(C.envMap||X.environment,be),X.envMapRotation=X.environment!==null&&C.envMap===null?B.environmentRotation:C.envMapRotation,Yt===void 0&&(C.addEventListener("dispose",Ir),Yt=new Map,X.programs=Yt);let Ie=Yt.get(kt);if(Ie!==void 0){if(X.currentProgram===Ie&&X.lightsStateVersion===Rt)return Jv(C,St),Ie}else St.uniforms=mt.getUniforms(C),D!==null&&C.isNodeMaterial&&D.build(C,K,St),C.onBeforeCompile(St,_),Ie=mt.acquireProgram(St,kt),Yt.set(kt,Ie),X.uniforms=St.uniforms;const Kt=X.uniforms;return(!C.isShaderMaterial&&!C.isRawShaderMaterial||C.clipping===!0)&&(Kt.clippingPlanes=Jt.uniform),Jv(C,St),X.needsLights=DA(C),X.lightsStateVersion=Rt,X.needsLights&&(Kt.ambientLightColor.value=Y.state.ambient,Kt.lightProbe.value=Y.state.probe,Kt.directionalLights.value=Y.state.directional,Kt.directionalLightShadows.value=Y.state.directionalShadow,Kt.spotLights.value=Y.state.spot,Kt.spotLightShadows.value=Y.state.spotShadow,Kt.rectAreaLights.value=Y.state.rectArea,Kt.ltc_1.value=Y.state.rectAreaLTC1,Kt.ltc_2.value=Y.state.rectAreaLTC2,Kt.pointLights.value=Y.state.point,Kt.pointLightShadows.value=Y.state.pointShadow,Kt.hemisphereLights.value=Y.state.hemi,Kt.directionalShadowMatrix.value=Y.state.directionalShadowMatrix,Kt.spotLightMatrix.value=Y.state.spotLightMatrix,Kt.spotLightMap.value=Y.state.spotLightMap,Kt.pointShadowMatrix.value=Y.state.pointShadowMatrix),X.lightProbeGrid=b.state.lightProbeGridArray.length>0,X.currentProgram=Ie,X.uniformsList=null,Ie}function Zv(C){if(C.uniformsList===null){const B=C.currentProgram.getUniforms();C.uniformsList=A0.seqWithValue(B.seq,C.uniforms)}return C.uniformsList}function Jv(C,B){const K=$.get(C);K.outputColorSpace=B.outputColorSpace,K.batching=B.batching,K.batchingColor=B.batchingColor,K.instancing=B.instancing,K.instancingColor=B.instancingColor,K.instancingMorph=B.instancingMorph,K.skinning=B.skinning,K.morphTargets=B.morphTargets,K.morphNormals=B.morphNormals,K.morphColors=B.morphColors,K.morphTargetsCount=B.morphTargetsCount,K.numClippingPlanes=B.numClippingPlanes,K.numIntersection=B.numClipIntersection,K.vertexAlphas=B.vertexAlphas,K.vertexTangents=B.vertexTangents,K.toneMapping=B.toneMapping}function TA(C,B){if(C.length===0)return null;if(C.length===1)return C[0].texture!==null?C[0]:null;y.setFromMatrixPosition(B.matrixWorld);for(let K=0,X=C.length;K<X;K++){const Y=C[K];if(Y.texture!==null&&Y.boundingBox.containsPoint(y))return Y}return null}function RA(C,B,K,X,Y){B.isScene!==!0&&(B=Ni),J.resetTextureUnits();const bt=B.fog,Rt=X.isMeshStandardMaterial||X.isMeshLambertMaterial||X.isMeshPhongMaterial?B.environment:null,St=W===null?_.outputColorSpace:W.isXRRenderTarget===!0?W.texture.colorSpace:Ue.workingColorSpace,kt=X.isMeshStandardMaterial||X.isMeshLambertMaterial&&!X.envMap||X.isMeshPhongMaterial&&!X.envMap,Yt=ht.get(X.envMap||Rt,kt),be=X.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,Ie=!!K.attributes.tangent&&(!!X.normalMap||X.anisotropy>0),Kt=!!K.morphAttributes.position,di=!!K.morphAttributes.normal,qi=!!K.morphAttributes.color;let Hi=ua;X.toneMapped&&(W===null||W.isXRRenderTarget===!0)&&(Hi=_.toneMapping);const Mi=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Gn=Mi!==void 0?Mi.length:0,_t=$.get(X),Os=b.state.lights;if(ie===!0&&(ne===!0||C!==q)){const wi=C===q&&X.id===Q;Jt.setState(X,C,wi)}let Be=!1;X.version===_t.__version?(_t.needsLights&&_t.lightsStateVersion!==Os.state.version||_t.outputColorSpace!==St||Y.isBatchedMesh&&_t.batching===!1||!Y.isBatchedMesh&&_t.batching===!0||Y.isBatchedMesh&&_t.batchingColor===!0&&Y.colorTexture===null||Y.isBatchedMesh&&_t.batchingColor===!1&&Y.colorTexture!==null||Y.isInstancedMesh&&_t.instancing===!1||!Y.isInstancedMesh&&_t.instancing===!0||Y.isSkinnedMesh&&_t.skinning===!1||!Y.isSkinnedMesh&&_t.skinning===!0||Y.isInstancedMesh&&_t.instancingColor===!0&&Y.instanceColor===null||Y.isInstancedMesh&&_t.instancingColor===!1&&Y.instanceColor!==null||Y.isInstancedMesh&&_t.instancingMorph===!0&&Y.morphTexture===null||Y.isInstancedMesh&&_t.instancingMorph===!1&&Y.morphTexture!==null||_t.envMap!==Yt||X.fog===!0&&_t.fog!==bt||_t.numClippingPlanes!==void 0&&(_t.numClippingPlanes!==Jt.numPlanes||_t.numIntersection!==Jt.numIntersection)||_t.vertexAlphas!==be||_t.vertexTangents!==Ie||_t.morphTargets!==Kt||_t.morphNormals!==di||_t.morphColors!==qi||_t.toneMapping!==Hi||_t.morphTargetsCount!==Gn||!!_t.lightProbeGrid!=b.state.lightProbeGridArray.length>0)&&(Be=!0):(Be=!0,_t.__version=X.version);let Ys=_t.currentProgram;Be===!0&&(Ys=Yd(X,B,Y),D&&X.isNodeMaterial&&D.onUpdateProgram(X,Ys,_t));let Dr=!1,to=!1,Yc=!1;const vi=Ys.getUniforms(),Zi=_t.uniforms;if(T.useProgram(Ys.program)&&(Dr=!0,to=!0,Yc=!0),X.id!==Q&&(Q=X.id,to=!0),_t.needsLights){const wi=TA(b.state.lightProbeGridArray,Y);_t.lightProbeGrid!==wi&&(_t.lightProbeGrid=wi,to=!0)}if(Dr||q!==C){T.buffers.depth.getReversed()&&C.reversedDepth!==!0&&(C._reversedDepth=!0,C.updateProjectionMatrix()),vi.setValue(z,"projectionMatrix",C.projectionMatrix),vi.setValue(z,"viewMatrix",C.matrixWorldInverse);const io=vi.map.cameraPosition;io!==void 0&&io.setValue(z,ii.setFromMatrixPosition(C.matrixWorld)),N.logarithmicDepthBuffer&&vi.setValue(z,"logDepthBufFC",2/(Math.log(C.far+1)/Math.LN2)),(X.isMeshPhongMaterial||X.isMeshToonMaterial||X.isMeshLambertMaterial||X.isMeshBasicMaterial||X.isMeshStandardMaterial||X.isShaderMaterial)&&vi.setValue(z,"isOrthographic",C.isOrthographicCamera===!0),q!==C&&(q=C,to=!0,Yc=!0)}if(_t.needsLights&&(Os.state.directionalShadowMap.length>0&&vi.setValue(z,"directionalShadowMap",Os.state.directionalShadowMap,J),Os.state.spotShadowMap.length>0&&vi.setValue(z,"spotShadowMap",Os.state.spotShadowMap,J),Os.state.pointShadowMap.length>0&&vi.setValue(z,"pointShadowMap",Os.state.pointShadowMap,J)),Y.isSkinnedMesh){vi.setOptional(z,Y,"bindMatrix"),vi.setOptional(z,Y,"bindMatrixInverse");const wi=Y.skeleton;wi&&(wi.boneTexture===null&&wi.computeBoneTexture(),vi.setValue(z,"boneTexture",wi.boneTexture,J))}Y.isBatchedMesh&&(vi.setOptional(z,Y,"batchingTexture"),vi.setValue(z,"batchingTexture",Y._matricesTexture,J),vi.setOptional(z,Y,"batchingIdTexture"),vi.setValue(z,"batchingIdTexture",Y._indirectTexture,J),vi.setOptional(z,Y,"batchingColorTexture"),Y._colorsTexture!==null&&vi.setValue(z,"batchingColorTexture",Y._colorsTexture,J));const eo=K.morphAttributes;if((eo.position!==void 0||eo.normal!==void 0||eo.color!==void 0)&&F.update(Y,K,Ys),(to||_t.receiveShadow!==Y.receiveShadow)&&(_t.receiveShadow=Y.receiveShadow,vi.setValue(z,"receiveShadow",Y.receiveShadow)),(X.isMeshStandardMaterial||X.isMeshLambertMaterial||X.isMeshPhongMaterial)&&X.envMap===null&&B.environment!==null&&(Zi.envMapIntensity.value=B.environmentIntensity),Zi.dfgLUT!==void 0&&(Zi.dfgLUT.value=BC()),to){if(vi.setValue(z,"toneMappingExposure",_.toneMappingExposure),_t.needsLights&&IA(Zi,Yc),bt&&X.fog===!0&&Xt.refreshFogUniforms(Zi,bt),Xt.refreshMaterialUniforms(Zi,X,ot,ct,b.state.transmissionRenderTarget[C.id]),_t.needsLights&&_t.lightProbeGrid){const wi=_t.lightProbeGrid;Zi.probesSH.value=wi.texture,Zi.probesMin.value.copy(wi.boundingBox.min),Zi.probesMax.value.copy(wi.boundingBox.max),Zi.probesResolution.value.copy(wi.resolution)}A0.upload(z,Zv(_t),Zi,J)}if(X.isShaderMaterial&&X.uniformsNeedUpdate===!0&&(A0.upload(z,Zv(_t),Zi,J),X.uniformsNeedUpdate=!1),X.isSpriteMaterial&&vi.setValue(z,"center",Y.center),vi.setValue(z,"modelViewMatrix",Y.modelViewMatrix),vi.setValue(z,"normalMatrix",Y.normalMatrix),vi.setValue(z,"modelMatrix",Y.matrixWorld),X.uniformsGroups!==void 0){const wi=X.uniformsGroups;for(let io=0,$c=wi.length;io<$c;io++){const jv=wi[io];st.update(jv,Ys),st.bind(jv,Ys)}}return Ys}function IA(C,B){C.ambientLightColor.needsUpdate=B,C.lightProbe.needsUpdate=B,C.directionalLights.needsUpdate=B,C.directionalLightShadows.needsUpdate=B,C.pointLights.needsUpdate=B,C.pointLightShadows.needsUpdate=B,C.spotLights.needsUpdate=B,C.spotLightShadows.needsUpdate=B,C.rectAreaLights.needsUpdate=B,C.hemisphereLights.needsUpdate=B}function DA(C){return C.isMeshLambertMaterial||C.isMeshToonMaterial||C.isMeshPhongMaterial||C.isMeshStandardMaterial||C.isShadowMaterial||C.isShaderMaterial&&C.lights===!0}this.getActiveCubeFace=function(){return k},this.getActiveMipmapLevel=function(){return H},this.getRenderTarget=function(){return W},this.setRenderTargetTextures=function(C,B,K){const X=$.get(C);X.__autoAllocateDepthBuffer=C.resolveDepthBuffer===!1,X.__autoAllocateDepthBuffer===!1&&(X.__useRenderToTexture=!1),$.get(C.texture).__webglTexture=B,$.get(C.depthTexture).__webglTexture=X.__autoAllocateDepthBuffer?void 0:K,X.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(C,B){const K=$.get(C);K.__webglFramebuffer=B,K.__useDefaultFramebuffer=B===void 0},this.setRenderTarget=function(C,B=0,K=0){W=C,k=B,H=K;let X=null,Y=!1,bt=!1;if(C){const St=$.get(C);if(St.__useDefaultFramebuffer!==void 0){T.bindFramebuffer(z.FRAMEBUFFER,St.__webglFramebuffer),nt.copy(C.viewport),at.copy(C.scissor),zt=C.scissorTest,T.viewport(nt),T.scissor(at),T.setScissorTest(zt),Q=-1;return}else if(St.__webglFramebuffer===void 0)J.setupRenderTarget(C);else if(St.__hasExternalTextures)J.rebindTextures(C,$.get(C.texture).__webglTexture,$.get(C.depthTexture).__webglTexture);else if(C.depthBuffer){const be=C.depthTexture;if(St.__boundDepthTexture!==be){if(be!==null&&$.has(be)&&(C.width!==be.image.width||C.height!==be.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");J.setupDepthRenderbuffer(C)}}const kt=C.texture;(kt.isData3DTexture||kt.isDataArrayTexture||kt.isCompressedArrayTexture)&&(bt=!0);const Yt=$.get(C).__webglFramebuffer;C.isWebGLCubeRenderTarget?(Array.isArray(Yt[B])?X=Yt[B][K]:X=Yt[B],Y=!0):C.samples>0&&J.useMultisampledRTT(C)===!1?X=$.get(C).__webglMultisampledFramebuffer:Array.isArray(Yt)?X=Yt[K]:X=Yt,nt.copy(C.viewport),at.copy(C.scissor),zt=C.scissorTest}else nt.copy(Wt).multiplyScalar(ot).floor(),at.copy(Nt).multiplyScalar(ot).floor(),zt=Tt;if(K!==0&&(X=P),T.bindFramebuffer(z.FRAMEBUFFER,X)&&T.drawBuffers(C,X),T.viewport(nt),T.scissor(at),T.setScissorTest(zt),Y){const St=$.get(C.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+B,St.__webglTexture,K)}else if(bt){const St=B;for(let kt=0;kt<C.textures.length;kt++){const Yt=$.get(C.textures[kt]);z.framebufferTextureLayer(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0+kt,Yt.__webglTexture,K,St)}}else if(C!==null&&K!==0){const St=$.get(C.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,St.__webglTexture,K)}Q=-1},this.readRenderTargetPixels=function(C,B,K,X,Y,bt,Rt,St=0){if(!(C&&C.isWebGLRenderTarget)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let kt=$.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&Rt!==void 0&&(kt=kt[Rt]),kt){T.bindFramebuffer(z.FRAMEBUFFER,kt);try{const Yt=C.textures[St],be=Yt.format,Ie=Yt.type;if(C.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+St),!N.textureFormatReadable(be)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!N.textureTypeReadable(Ie)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}B>=0&&B<=C.width-X&&K>=0&&K<=C.height-Y&&z.readPixels(B,K,X,Y,Mt.convert(be),Mt.convert(Ie),bt)}finally{const Yt=W!==null?$.get(W).__webglFramebuffer:null;T.bindFramebuffer(z.FRAMEBUFFER,Yt)}}},this.readRenderTargetPixelsAsync=async function(C,B,K,X,Y,bt,Rt,St=0){if(!(C&&C.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let kt=$.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&Rt!==void 0&&(kt=kt[Rt]),kt)if(B>=0&&B<=C.width-X&&K>=0&&K<=C.height-Y){T.bindFramebuffer(z.FRAMEBUFFER,kt);const Yt=C.textures[St],be=Yt.format,Ie=Yt.type;if(C.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+St),!N.textureFormatReadable(be))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!N.textureTypeReadable(Ie))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Kt=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,Kt),z.bufferData(z.PIXEL_PACK_BUFFER,bt.byteLength,z.STREAM_READ),z.readPixels(B,K,X,Y,Mt.convert(be),Mt.convert(Ie),0);const di=W!==null?$.get(W).__webglFramebuffer:null;T.bindFramebuffer(z.FRAMEBUFFER,di);const qi=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await kT(z,qi,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,Kt),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,bt),z.deleteBuffer(Kt),z.deleteSync(qi),bt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(C,B=null,K=0){const X=Math.pow(2,-K),Y=Math.floor(C.image.width*X),bt=Math.floor(C.image.height*X),Rt=B!==null?B.x:0,St=B!==null?B.y:0;J.setTexture2D(C,0),z.copyTexSubImage2D(z.TEXTURE_2D,K,0,0,Rt,St,Y,bt),T.unbindTexture()},this.copyTextureToTexture=function(C,B,K=null,X=null,Y=0,bt=0){let Rt,St,kt,Yt,be,Ie,Kt,di,qi;const Hi=C.isCompressedTexture?C.mipmaps[bt]:C.image;if(K!==null)Rt=K.max.x-K.min.x,St=K.max.y-K.min.y,kt=K.isBox3?K.max.z-K.min.z:1,Yt=K.min.x,be=K.min.y,Ie=K.isBox3?K.min.z:0;else{const Zi=Math.pow(2,-Y);Rt=Math.floor(Hi.width*Zi),St=Math.floor(Hi.height*Zi),C.isDataArrayTexture?kt=Hi.depth:C.isData3DTexture?kt=Math.floor(Hi.depth*Zi):kt=1,Yt=0,be=0,Ie=0}X!==null?(Kt=X.x,di=X.y,qi=X.z):(Kt=0,di=0,qi=0);const Mi=Mt.convert(B.format),Gn=Mt.convert(B.type);let _t;B.isData3DTexture?(J.setTexture3D(B,0),_t=z.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(J.setTexture2DArray(B,0),_t=z.TEXTURE_2D_ARRAY):(J.setTexture2D(B,0),_t=z.TEXTURE_2D),T.activeTexture(z.TEXTURE0),T.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,B.flipY),T.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),T.pixelStorei(z.UNPACK_ALIGNMENT,B.unpackAlignment);const Os=T.getParameter(z.UNPACK_ROW_LENGTH),Be=T.getParameter(z.UNPACK_IMAGE_HEIGHT),Ys=T.getParameter(z.UNPACK_SKIP_PIXELS),Dr=T.getParameter(z.UNPACK_SKIP_ROWS),to=T.getParameter(z.UNPACK_SKIP_IMAGES);T.pixelStorei(z.UNPACK_ROW_LENGTH,Hi.width),T.pixelStorei(z.UNPACK_IMAGE_HEIGHT,Hi.height),T.pixelStorei(z.UNPACK_SKIP_PIXELS,Yt),T.pixelStorei(z.UNPACK_SKIP_ROWS,be),T.pixelStorei(z.UNPACK_SKIP_IMAGES,Ie);const Yc=C.isDataArrayTexture||C.isData3DTexture,vi=B.isDataArrayTexture||B.isData3DTexture;if(C.isDepthTexture){const Zi=$.get(C),eo=$.get(B),wi=$.get(Zi.__renderTarget),io=$.get(eo.__renderTarget);T.bindFramebuffer(z.READ_FRAMEBUFFER,wi.__webglFramebuffer),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,io.__webglFramebuffer);for(let $c=0;$c<kt;$c++)Yc&&(z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,$.get(C).__webglTexture,Y,Ie+$c),z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,$.get(B).__webglTexture,bt,qi+$c)),z.blitFramebuffer(Yt,be,Rt,St,Kt,di,Rt,St,z.DEPTH_BUFFER_BIT,z.NEAREST);T.bindFramebuffer(z.READ_FRAMEBUFFER,null),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if(Y!==0||C.isRenderTargetTexture||$.has(C)){const Zi=$.get(C),eo=$.get(B);T.bindFramebuffer(z.READ_FRAMEBUFFER,L),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,O);for(let wi=0;wi<kt;wi++)Yc?z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Zi.__webglTexture,Y,Ie+wi):z.framebufferTexture2D(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,Zi.__webglTexture,Y),vi?z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,eo.__webglTexture,bt,qi+wi):z.framebufferTexture2D(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,eo.__webglTexture,bt),Y!==0?z.blitFramebuffer(Yt,be,Rt,St,Kt,di,Rt,St,z.COLOR_BUFFER_BIT,z.NEAREST):vi?z.copyTexSubImage3D(_t,bt,Kt,di,qi+wi,Yt,be,Rt,St):z.copyTexSubImage2D(_t,bt,Kt,di,Yt,be,Rt,St);T.bindFramebuffer(z.READ_FRAMEBUFFER,null),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else vi?C.isDataTexture||C.isData3DTexture?z.texSubImage3D(_t,bt,Kt,di,qi,Rt,St,kt,Mi,Gn,Hi.data):B.isCompressedArrayTexture?z.compressedTexSubImage3D(_t,bt,Kt,di,qi,Rt,St,kt,Mi,Hi.data):z.texSubImage3D(_t,bt,Kt,di,qi,Rt,St,kt,Mi,Gn,Hi):C.isDataTexture?z.texSubImage2D(z.TEXTURE_2D,bt,Kt,di,Rt,St,Mi,Gn,Hi.data):C.isCompressedTexture?z.compressedTexSubImage2D(z.TEXTURE_2D,bt,Kt,di,Hi.width,Hi.height,Mi,Hi.data):z.texSubImage2D(z.TEXTURE_2D,bt,Kt,di,Rt,St,Mi,Gn,Hi);T.pixelStorei(z.UNPACK_ROW_LENGTH,Os),T.pixelStorei(z.UNPACK_IMAGE_HEIGHT,Be),T.pixelStorei(z.UNPACK_SKIP_PIXELS,Ys),T.pixelStorei(z.UNPACK_SKIP_ROWS,Dr),T.pixelStorei(z.UNPACK_SKIP_IMAGES,to),bt===0&&B.generateMipmaps&&z.generateMipmap(_t),T.unbindTexture()},this.initRenderTarget=function(C){$.get(C).__webglFramebuffer===void 0&&J.setupRenderTarget(C)},this.initTexture=function(C){C.isCubeTexture?J.setTextureCube(C,0):C.isData3DTexture?J.setTexture3D(C,0):C.isDataArrayTexture||C.isCompressedArrayTexture?J.setTexture2DArray(C,0):J.setTexture2D(C,0),T.unbindTexture()},this.resetState=function(){k=0,H=0,W=null,T.reset(),Et.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ca}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=Ue._getDrawingBufferColorSpace(t),e.unpackColorSpace=Ue._getUnpackColorSpace()}}const GC=`
5885
+ }`;class NC{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){const i=new Jb(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(t){if(this.texture!==null&&this.mesh===null){const e=t.cameras[0].viewport,i=new Te({vertexShader:PC,fragmentShader:OC,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new vt(new ss(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class LC extends Zo{constructor(t,e){super();const i=this;let n=null,s=1,r=null,a="local-floor",c=1,l=null,h=null,u=null,d=null,f=null,p=null;const m=typeof XRWebGLBinding<"u",g=new NC,M={},v=e.getContextAttributes();let x=null,y=null;const w=[],b=[],E=new tt;let S=null;const A=new Bn;A.viewport=new Ae;const _=new Bn;_.viewport=new Ae;const I=[A,_],D=new D4;let P=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let ct=w[Z];return ct===void 0&&(ct=new ym,w[Z]=ct),ct.getTargetRaySpace()},this.getControllerGrip=function(Z){let ct=w[Z];return ct===void 0&&(ct=new ym,w[Z]=ct),ct.getGripSpace()},this.getHand=function(Z){let ct=w[Z];return ct===void 0&&(ct=new ym,w[Z]=ct),ct.getHandSpace()};function O(Z){const ct=b.indexOf(Z.inputSource);if(ct===-1)return;const ot=w[ct];ot!==void 0&&(ot.update(Z.inputSource,Z.frame,l||r),ot.dispatchEvent({type:Z.type,data:Z.inputSource}))}function k(){n.removeEventListener("select",O),n.removeEventListener("selectstart",O),n.removeEventListener("selectend",O),n.removeEventListener("squeeze",O),n.removeEventListener("squeezestart",O),n.removeEventListener("squeezeend",O),n.removeEventListener("end",k),n.removeEventListener("inputsourceschange",H);for(let Z=0;Z<w.length;Z++){const ct=b[Z];ct!==null&&(b[Z]=null,w[Z].disconnect(ct))}P=null,L=null,g.reset();for(const Z in M)delete M[Z];t.setRenderTarget(x),f=null,d=null,u=null,n=null,y=null,Pt.stop(),i.isPresenting=!1,t.setPixelRatio(S),t.setSize(E.width,E.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){s=Z,i.isPresenting===!0&&Ft("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){a=Z,i.isPresenting===!0&&Ft("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||r},this.setReferenceSpace=function(Z){l=Z},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(n,e)),u},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function(Z){if(n=Z,n!==null){if(x=t.getRenderTarget(),n.addEventListener("select",O),n.addEventListener("selectstart",O),n.addEventListener("selectend",O),n.addEventListener("squeeze",O),n.addEventListener("squeezestart",O),n.addEventListener("squeezeend",O),n.addEventListener("end",k),n.addEventListener("inputsourceschange",H),v.xrCompatible!==!0&&await e.makeXRCompatible(),S=t.getPixelRatio(),t.getSize(E),m&&"createProjectionLayer"in XRWebGLBinding.prototype){let ot=null,V=null,Ot=null;v.depth&&(Ot=v.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,ot=v.stencil?bc:Ka,V=v.stencil?_d:rr);const Wt={colorFormat:e.RGBA8,depthFormat:Ot,scaleFactor:s};u=this.getBinding(),d=u.createProjectionLayer(Wt),n.updateRenderState({layers:[d]}),t.setPixelRatio(1),t.setSize(d.textureWidth,d.textureHeight,!1),y=new qe(d.textureWidth,d.textureHeight,{format:$i,type:Qn,depthTexture:new Yo(d.textureWidth,d.textureHeight,V,void 0,void 0,void 0,void 0,void 0,void 0,ot),stencilBuffer:v.stencil,colorSpace:t.outputColorSpace,samples:v.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const ot={antialias:v.antialias,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(n,e,ot),n.updateRenderState({baseLayer:f}),t.setPixelRatio(1),t.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new qe(f.framebufferWidth,f.framebufferHeight,{format:$i,type:Qn,colorSpace:t.outputColorSpace,stencilBuffer:v.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(c),l=null,r=await n.requestReferenceSpace(a),Pt.setContext(n),Pt.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function H(Z){for(let ct=0;ct<Z.removed.length;ct++){const ot=Z.removed[ct],V=b.indexOf(ot);V>=0&&(b[V]=null,w[V].disconnect(ot))}for(let ct=0;ct<Z.added.length;ct++){const ot=Z.added[ct];let V=b.indexOf(ot);if(V===-1){for(let Wt=0;Wt<w.length;Wt++)if(Wt>=b.length){b.push(ot),V=Wt;break}else if(b[Wt]===null){b[Wt]=ot,V=Wt;break}if(V===-1)break}const Ot=w[V];Ot&&Ot.connect(ot)}}const W=new R,Q=new R;function q(Z,ct,ot){W.setFromMatrixPosition(ct.matrixWorld),Q.setFromMatrixPosition(ot.matrixWorld);const V=W.distanceTo(Q),Ot=ct.projectionMatrix.elements,Wt=ot.projectionMatrix.elements,Nt=Ot[14]/(Ot[10]-1),Tt=Ot[14]/(Ot[10]+1),jt=(Ot[9]+1)/Ot[5],ie=(Ot[9]-1)/Ot[5],ne=(Ot[8]-1)/Ot[0],ei=(Wt[8]+1)/Wt[0],ii=Nt*ne,Fi=Nt*ei,Ni=V/(-ne+ei),zi=Ni*-ne;if(ct.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(zi),Z.translateZ(Ni),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),Ot[10]===-1)Z.projectionMatrix.copy(ct.projectionMatrix),Z.projectionMatrixInverse.copy(ct.projectionMatrixInverse);else{const an=Nt+Ni,z=Tt+Ni,Ms=ii-zi,ni=Fi+(V-zi),N=jt*Tt/z*an,T=ie*Tt/z*an;Z.projectionMatrix.makePerspective(Ms,ni,N,T,an,z),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function nt(Z,ct){ct===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(ct.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(n===null)return;let ct=Z.near,ot=Z.far;g.texture!==null&&(g.depthNear>0&&(ct=g.depthNear),g.depthFar>0&&(ot=g.depthFar)),D.near=_.near=A.near=ct,D.far=_.far=A.far=ot,(P!==D.near||L!==D.far)&&(n.updateRenderState({depthNear:D.near,depthFar:D.far}),P=D.near,L=D.far),D.layers.mask=Z.layers.mask|6,A.layers.mask=D.layers.mask&-5,_.layers.mask=D.layers.mask&-3;const V=Z.parent,Ot=D.cameras;nt(D,V);for(let Wt=0;Wt<Ot.length;Wt++)nt(Ot[Wt],V);Ot.length===2?q(D,A,_):D.projectionMatrix.copy(A.projectionMatrix),at(Z,D,V)};function at(Z,ct,ot){ot===null?Z.matrix.copy(ct.matrixWorld):(Z.matrix.copy(ot.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(ct.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(ct.projectionMatrix),Z.projectionMatrixInverse.copy(ct.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=kh*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return D},this.getFoveation=function(){if(!(d===null&&f===null))return c},this.setFoveation=function(Z){c=Z,d!==null&&(d.fixedFoveation=Z),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=Z)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(D)},this.getCameraTexture=function(Z){return M[Z]};let zt=null;function Zt(Z,ct){if(h=ct.getViewerPose(l||r),p=ct,h!==null){const ot=h.views;f!==null&&(t.setRenderTargetFramebuffer(y,f.framebuffer),t.setRenderTarget(y));let V=!1;ot.length!==D.cameras.length&&(D.cameras.length=0,V=!0);for(let Tt=0;Tt<ot.length;Tt++){const jt=ot[Tt];let ie=null;if(f!==null)ie=f.getViewport(jt);else{const ei=u.getViewSubImage(d,jt);ie=ei.viewport,Tt===0&&(t.setRenderTargetTextures(y,ei.colorTexture,ei.depthStencilTexture),t.setRenderTarget(y))}let ne=I[Tt];ne===void 0&&(ne=new Bn,ne.layers.enable(Tt),ne.viewport=new Ae,I[Tt]=ne),ne.matrix.fromArray(jt.transform.matrix),ne.matrix.decompose(ne.position,ne.quaternion,ne.scale),ne.projectionMatrix.fromArray(jt.projectionMatrix),ne.projectionMatrixInverse.copy(ne.projectionMatrix).invert(),ne.viewport.set(ie.x,ie.y,ie.width,ie.height),Tt===0&&(D.matrix.copy(ne.matrix),D.matrix.decompose(D.position,D.quaternion,D.scale)),V===!0&&D.cameras.push(ne)}const Ot=n.enabledFeatures;if(Ot&&Ot.includes("depth-sensing")&&n.depthUsage=="gpu-optimized"&&m){u=i.getBinding();const Tt=u.getDepthInformation(ot[0]);Tt&&Tt.isValid&&Tt.texture&&g.init(Tt,n.renderState)}if(Ot&&Ot.includes("camera-access")&&m){t.state.unbindTexture(),u=i.getBinding();for(let Tt=0;Tt<ot.length;Tt++){const jt=ot[Tt].camera;if(jt){let ie=M[jt];ie||(ie=new Jb,M[jt]=ie);const ne=u.getCameraImage(jt);ie.sourceTexture=ne}}}}for(let ot=0;ot<w.length;ot++){const V=b[ot],Ot=w[ot];V!==null&&Ot!==void 0&&Ot.update(V,ct,l||r)}zt&&zt(Z,ct),ct.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ct}),p=null}const Pt=new pE;Pt.setAnimationLoop(Zt),this.setAnimationLoop=function(Z){zt=Z},this.dispose=function(){}}}const kC=new Vt,xE=new ue;xE.set(-1,0,0,0,1,0,0,0,1);function UC(o,t){function e(g,M){g.matrixAutoUpdate===!0&&g.updateMatrix(),M.value.copy(g.matrix)}function i(g,M){M.color.getRGB(g.fogColor.value,aE(o)),M.isFog?(g.fogNear.value=M.near,g.fogFar.value=M.far):M.isFogExp2&&(g.fogDensity.value=M.density)}function n(g,M,v,x,y){M.isNodeMaterial?M.uniformsNeedUpdate=!1:M.isMeshBasicMaterial?s(g,M):M.isMeshLambertMaterial?(s(g,M),M.envMap&&(g.envMapIntensity.value=M.envMapIntensity)):M.isMeshToonMaterial?(s(g,M),u(g,M)):M.isMeshPhongMaterial?(s(g,M),h(g,M),M.envMap&&(g.envMapIntensity.value=M.envMapIntensity)):M.isMeshStandardMaterial?(s(g,M),d(g,M),M.isMeshPhysicalMaterial&&f(g,M,y)):M.isMeshMatcapMaterial?(s(g,M),p(g,M)):M.isMeshDepthMaterial?s(g,M):M.isMeshDistanceMaterial?(s(g,M),m(g,M)):M.isMeshNormalMaterial?s(g,M):M.isLineBasicMaterial?(r(g,M),M.isLineDashedMaterial&&a(g,M)):M.isPointsMaterial?c(g,M,v,x):M.isSpriteMaterial?l(g,M):M.isShadowMaterial?(g.color.value.copy(M.color),g.opacity.value=M.opacity):M.isShaderMaterial&&(M.uniformsNeedUpdate=!1)}function s(g,M){g.opacity.value=M.opacity,M.color&&g.diffuse.value.copy(M.color),M.emissive&&g.emissive.value.copy(M.emissive).multiplyScalar(M.emissiveIntensity),M.map&&(g.map.value=M.map,e(M.map,g.mapTransform)),M.alphaMap&&(g.alphaMap.value=M.alphaMap,e(M.alphaMap,g.alphaMapTransform)),M.bumpMap&&(g.bumpMap.value=M.bumpMap,e(M.bumpMap,g.bumpMapTransform),g.bumpScale.value=M.bumpScale,M.side===Ci&&(g.bumpScale.value*=-1)),M.normalMap&&(g.normalMap.value=M.normalMap,e(M.normalMap,g.normalMapTransform),g.normalScale.value.copy(M.normalScale),M.side===Ci&&g.normalScale.value.negate()),M.displacementMap&&(g.displacementMap.value=M.displacementMap,e(M.displacementMap,g.displacementMapTransform),g.displacementScale.value=M.displacementScale,g.displacementBias.value=M.displacementBias),M.emissiveMap&&(g.emissiveMap.value=M.emissiveMap,e(M.emissiveMap,g.emissiveMapTransform)),M.specularMap&&(g.specularMap.value=M.specularMap,e(M.specularMap,g.specularMapTransform)),M.alphaTest>0&&(g.alphaTest.value=M.alphaTest);const v=t.get(M),x=v.envMap,y=v.envMapRotation;x&&(g.envMap.value=x,g.envMapRotation.value.setFromMatrix4(kC.makeRotationFromEuler(y)).transpose(),x.isCubeTexture&&x.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(xE),g.reflectivity.value=M.reflectivity,g.ior.value=M.ior,g.refractionRatio.value=M.refractionRatio),M.lightMap&&(g.lightMap.value=M.lightMap,g.lightMapIntensity.value=M.lightMapIntensity,e(M.lightMap,g.lightMapTransform)),M.aoMap&&(g.aoMap.value=M.aoMap,g.aoMapIntensity.value=M.aoMapIntensity,e(M.aoMap,g.aoMapTransform))}function r(g,M){g.diffuse.value.copy(M.color),g.opacity.value=M.opacity,M.map&&(g.map.value=M.map,e(M.map,g.mapTransform))}function a(g,M){g.dashSize.value=M.dashSize,g.totalSize.value=M.dashSize+M.gapSize,g.scale.value=M.scale}function c(g,M,v,x){g.diffuse.value.copy(M.color),g.opacity.value=M.opacity,g.size.value=M.size*v,g.scale.value=x*.5,M.map&&(g.map.value=M.map,e(M.map,g.uvTransform)),M.alphaMap&&(g.alphaMap.value=M.alphaMap,e(M.alphaMap,g.alphaMapTransform)),M.alphaTest>0&&(g.alphaTest.value=M.alphaTest)}function l(g,M){g.diffuse.value.copy(M.color),g.opacity.value=M.opacity,g.rotation.value=M.rotation,M.map&&(g.map.value=M.map,e(M.map,g.mapTransform)),M.alphaMap&&(g.alphaMap.value=M.alphaMap,e(M.alphaMap,g.alphaMapTransform)),M.alphaTest>0&&(g.alphaTest.value=M.alphaTest)}function h(g,M){g.specular.value.copy(M.specular),g.shininess.value=Math.max(M.shininess,1e-4)}function u(g,M){M.gradientMap&&(g.gradientMap.value=M.gradientMap)}function d(g,M){g.metalness.value=M.metalness,M.metalnessMap&&(g.metalnessMap.value=M.metalnessMap,e(M.metalnessMap,g.metalnessMapTransform)),g.roughness.value=M.roughness,M.roughnessMap&&(g.roughnessMap.value=M.roughnessMap,e(M.roughnessMap,g.roughnessMapTransform)),M.envMap&&(g.envMapIntensity.value=M.envMapIntensity)}function f(g,M,v){g.ior.value=M.ior,M.sheen>0&&(g.sheenColor.value.copy(M.sheenColor).multiplyScalar(M.sheen),g.sheenRoughness.value=M.sheenRoughness,M.sheenColorMap&&(g.sheenColorMap.value=M.sheenColorMap,e(M.sheenColorMap,g.sheenColorMapTransform)),M.sheenRoughnessMap&&(g.sheenRoughnessMap.value=M.sheenRoughnessMap,e(M.sheenRoughnessMap,g.sheenRoughnessMapTransform))),M.clearcoat>0&&(g.clearcoat.value=M.clearcoat,g.clearcoatRoughness.value=M.clearcoatRoughness,M.clearcoatMap&&(g.clearcoatMap.value=M.clearcoatMap,e(M.clearcoatMap,g.clearcoatMapTransform)),M.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=M.clearcoatRoughnessMap,e(M.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),M.clearcoatNormalMap&&(g.clearcoatNormalMap.value=M.clearcoatNormalMap,e(M.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(M.clearcoatNormalScale),M.side===Ci&&g.clearcoatNormalScale.value.negate())),M.dispersion>0&&(g.dispersion.value=M.dispersion),M.iridescence>0&&(g.iridescence.value=M.iridescence,g.iridescenceIOR.value=M.iridescenceIOR,g.iridescenceThicknessMinimum.value=M.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=M.iridescenceThicknessRange[1],M.iridescenceMap&&(g.iridescenceMap.value=M.iridescenceMap,e(M.iridescenceMap,g.iridescenceMapTransform)),M.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=M.iridescenceThicknessMap,e(M.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),M.transmission>0&&(g.transmission.value=M.transmission,g.transmissionSamplerMap.value=v.texture,g.transmissionSamplerSize.value.set(v.width,v.height),M.transmissionMap&&(g.transmissionMap.value=M.transmissionMap,e(M.transmissionMap,g.transmissionMapTransform)),g.thickness.value=M.thickness,M.thicknessMap&&(g.thicknessMap.value=M.thicknessMap,e(M.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=M.attenuationDistance,g.attenuationColor.value.copy(M.attenuationColor)),M.anisotropy>0&&(g.anisotropyVector.value.set(M.anisotropy*Math.cos(M.anisotropyRotation),M.anisotropy*Math.sin(M.anisotropyRotation)),M.anisotropyMap&&(g.anisotropyMap.value=M.anisotropyMap,e(M.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=M.specularIntensity,g.specularColor.value.copy(M.specularColor),M.specularColorMap&&(g.specularColorMap.value=M.specularColorMap,e(M.specularColorMap,g.specularColorMapTransform)),M.specularIntensityMap&&(g.specularIntensityMap.value=M.specularIntensityMap,e(M.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,M){M.matcap&&(g.matcap.value=M.matcap)}function m(g,M){const v=t.get(M).light;g.referencePosition.value.setFromMatrixPosition(v.matrixWorld),g.nearDistance.value=v.shadow.camera.near,g.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function FC(o,t,e,i){let n={},s={},r=[];const a=o.getParameter(o.MAX_UNIFORM_BUFFER_BINDINGS);function c(y,w){const b=w.program;i.uniformBlockBinding(y,b)}function l(y,w){let b=n[y.id];b===void 0&&(g(y),b=h(y),n[y.id]=b,y.addEventListener("dispose",v));const E=w.program;i.updateUBOMapping(y,E);const S=t.render.frame;s[y.id]!==S&&(d(y),s[y.id]=S)}function h(y){const w=u();y.__bindingPointIndex=w;const b=o.createBuffer(),E=y.__size,S=y.usage;return o.bindBuffer(o.UNIFORM_BUFFER,b),o.bufferData(o.UNIFORM_BUFFER,E,S),o.bindBuffer(o.UNIFORM_BUFFER,null),o.bindBufferBase(o.UNIFORM_BUFFER,w,b),b}function u(){for(let y=0;y<a;y++)if(r.indexOf(y)===-1)return r.push(y),y;return ce("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(y){const w=n[y.id],b=y.uniforms,E=y.__cache;o.bindBuffer(o.UNIFORM_BUFFER,w);for(let S=0,A=b.length;S<A;S++){const _=b[S];if(Array.isArray(_))for(let I=0,D=_.length;I<D;I++)f(_[I],S,I,E);else f(_,S,0,E)}o.bindBuffer(o.UNIFORM_BUFFER,null)}function f(y,w,b,E){if(m(y,w,b,E)===!0){const S=y.__offset,A=y.value;if(Array.isArray(A)){let _=0;for(let I=0;I<A.length;I++){const D=A[I],P=M(D);p(D,y.__data,_),typeof D!="number"&&typeof D!="boolean"&&!D.isMatrix3&&!ArrayBuffer.isView(D)&&(_+=P.storage/Float32Array.BYTES_PER_ELEMENT)}}else p(A,y.__data,0);o.bufferSubData(o.UNIFORM_BUFFER,S,y.__data)}}function p(y,w,b){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,b)}function m(y,w,b,E){const S=y.value,A=w+"_"+b;if(E[A]===void 0)return typeof S=="number"||typeof S=="boolean"?E[A]=S:ArrayBuffer.isView(S)?E[A]=S.slice():E[A]=S.clone(),!0;{const _=E[A];if(typeof S=="number"||typeof S=="boolean"){if(_!==S)return E[A]=S,!0}else{if(ArrayBuffer.isView(S))return!0;if(_.equals(S)===!1)return _.copy(S),!0}}return!1}function g(y){const w=y.uniforms;let b=0;const E=16;for(let A=0,_=w.length;A<_;A++){const I=Array.isArray(w[A])?w[A]:[w[A]];for(let D=0,P=I.length;D<P;D++){const L=I[D],O=Array.isArray(L.value)?L.value:[L.value];for(let k=0,H=O.length;k<H;k++){const W=O[k],Q=M(W),q=b%E,nt=q%Q.boundary,at=q+nt;b+=nt,at!==0&&E-at<Q.storage&&(b+=E-at),L.__data=new Float32Array(Q.storage/Float32Array.BYTES_PER_ELEMENT),L.__offset=b,b+=Q.storage}}}const S=b%E;return S>0&&(b+=E-S),y.__size=b,y.__cache={},this}function M(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?Ft("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):Ft("WebGLRenderer: Unsupported uniform value type.",y),w}function v(y){const w=y.target;w.removeEventListener("dispose",v);const b=r.indexOf(w.__bindingPointIndex);r.splice(b,1),o.deleteBuffer(n[w.id]),delete n[w.id],delete s[w.id]}function x(){for(const y in n)o.deleteBuffer(n[y]);r=[],n={},s={}}return{bind:c,update:l,dispose:x}}const zC=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Or=null;function BC(){return Or===null&&(Or=new ms(zC,16,16,Bc,We),Or.name="DFG_LUT",Or.minFilter=ge,Or.magFilter=ge,Or.wrapS=Yi,Or.wrapT=Yi,Or.generateMipmaps=!1,Or.needsUpdate=!0),Or}class HC{constructor(t={}){const{canvas:e=LT(),context:i=null,depth:n=!0,stencil:s=!1,alpha:r=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Qn}=t;this.isWebGLRenderer=!0;let p;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=r;const m=f,g=new Set([tv,QM,jM]),M=new Set([Qn,rr,Ad,_d,ZM,JM]),v=new Uint32Array(4),x=new Int32Array(4),y=new R;let w=null,b=null;const E=[],S=[];let A=null;this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ua,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const _=this;let I=!1,D=null,P=null,L=null,O=null;this._outputColorSpace=Pn;let k=0,H=0,W=null,Q=-1,q=null;const nt=new Ae,at=new Ae;let zt=null;const Zt=new rt(0);let Pt=0,Z=e.width,ct=e.height,ot=1,V=null,Ot=null;const Wt=new Ae(0,0,Z,ct),Nt=new Ae(0,0,Z,ct);let Tt=!1;const jt=new Rp;let ie=!1,ne=!1;const ei=new Vt,ii=new R,Fi=new Ae,Ni={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let zi=!1;function an(){return W===null?ot:1}let z=i;function Ms(C,B){return e.getContext(C,B)}try{const C={alpha:!0,depth:n,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Bd}`),e.addEventListener("webglcontextlost",Bi,!1),e.addEventListener("webglcontextrestored",xi,!1),e.addEventListener("webglcontextcreationerror",Rr,!1),z===null){const B="webgl2";if(z=Ms(B,C),z===null)throw Ms(B)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(C){throw ce("WebGLRenderer: "+C.message),C}let ni,N,T,G,$,J,ht,ft,j,it,mt,Xt,xt,gt,Jt,se,Se,F,dt,et,Mt,Et,st;function Gt(){ni=new BD(z),ni.init(),Mt=new CC(z,ni),N=new PD(z,ni,t,Mt),T=new IC(z,ni),N.reversedDepthBuffer&&d&&T.buffers.depth.setReversed(!0),P=z.createFramebuffer(),L=z.createFramebuffer(),O=z.createFramebuffer(),G=new VD(z),$=new mC,J=new DC(z,ni,T,$,N,Mt,G),ht=new zD(_),ft=new $4(z),Et=new DD(z,ft),j=new HD(z,ft,G,Et),it=new XD(z,j,ft,Et,G),F=new WD(z,N,J),Jt=new OD($),mt=new pC(_,ht,ni,N,Et,Jt),Xt=new UC(_,$),xt=new MC,gt=new bC(ni),Se=new ID(_,ht,T,it,p,c),se=new RC(_,it,N),st=new FC(z,G,N,T),dt=new CD(z,ni,G),et=new GD(z,ni,G),G.programs=mt.programs,_.capabilities=N,_.extensions=ni,_.properties=$,_.renderLists=xt,_.shadowMap=se,_.state=T,_.info=G}Gt(),m!==Qn&&(A=new $D(m,e.width,e.height,a,n,s));const Lt=new LC(_,z);this.xr=Lt,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){const C=ni.get("WEBGL_lose_context");C&&C.loseContext()},this.forceContextRestore=function(){const C=ni.get("WEBGL_lose_context");C&&C.restoreContext()},this.getPixelRatio=function(){return ot},this.setPixelRatio=function(C){C!==void 0&&(ot=C,this.setSize(Z,ct,!1))},this.getSize=function(C){return C.set(Z,ct)},this.setSize=function(C,B,K=!0){if(Lt.isPresenting){Ft("WebGLRenderer: Can't change size while VR device is presenting.");return}Z=C,ct=B,e.width=Math.floor(C*ot),e.height=Math.floor(B*ot),K===!0&&(e.style.width=C+"px",e.style.height=B+"px"),A!==null&&A.setSize(e.width,e.height),this.setViewport(0,0,C,B)},this.getDrawingBufferSize=function(C){return C.set(Z*ot,ct*ot).floor()},this.setDrawingBufferSize=function(C,B,K){Z=C,ct=B,ot=K,e.width=Math.floor(C*K),e.height=Math.floor(B*K),this.setViewport(0,0,C,B)},this.setEffects=function(C){if(m===Qn){ce("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(C){for(let B=0;B<C.length;B++)if(C[B].isOutputPass===!0){Ft("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(C||[])},this.getCurrentViewport=function(C){return C.copy(nt)},this.getViewport=function(C){return C.copy(Wt)},this.setViewport=function(C,B,K,X){C.isVector4?Wt.set(C.x,C.y,C.z,C.w):Wt.set(C,B,K,X),T.viewport(nt.copy(Wt).multiplyScalar(ot).round())},this.getScissor=function(C){return C.copy(Nt)},this.setScissor=function(C,B,K,X){C.isVector4?Nt.set(C.x,C.y,C.z,C.w):Nt.set(C,B,K,X),T.scissor(at.copy(Nt).multiplyScalar(ot).round())},this.getScissorTest=function(){return Tt},this.setScissorTest=function(C){T.setScissorTest(Tt=C)},this.setOpaqueSort=function(C){V=C},this.setTransparentSort=function(C){Ot=C},this.getClearColor=function(C){return C.copy(Se.getClearColor())},this.setClearColor=function(){Se.setClearColor(...arguments)},this.getClearAlpha=function(){return Se.getClearAlpha()},this.setClearAlpha=function(){Se.setClearAlpha(...arguments)},this.clear=function(C=!0,B=!0,K=!0){let X=0;if(C){let Y=!1;if(W!==null){const bt=W.texture.format;Y=g.has(bt)}if(Y){const bt=W.texture.type,Rt=M.has(bt),St=Se.getClearColor(),kt=Se.getClearAlpha(),Yt=St.r,be=St.g,Ie=St.b;Rt?(v[0]=Yt,v[1]=be,v[2]=Ie,v[3]=kt,z.clearBufferuiv(z.COLOR,0,v)):(x[0]=Yt,x[1]=be,x[2]=Ie,x[3]=kt,z.clearBufferiv(z.COLOR,0,x))}else X|=z.COLOR_BUFFER_BIT}B&&(X|=z.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),K&&(X|=z.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),X!==0&&z.clear(X)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(C){C.setRenderer(this),D=C},this.dispose=function(){e.removeEventListener("webglcontextlost",Bi,!1),e.removeEventListener("webglcontextrestored",xi,!1),e.removeEventListener("webglcontextcreationerror",Rr,!1),Se.dispose(),xt.dispose(),gt.dispose(),$.dispose(),ht.dispose(),it.dispose(),Et.dispose(),st.dispose(),mt.dispose(),Lt.dispose(),Lt.removeEventListener("sessionstart",Xv),Lt.removeEventListener("sessionend",Yv),jo.stop()};function Bi(C){C.preventDefault(),K0("WebGLRenderer: Context Lost."),I=!0}function xi(){K0("WebGLRenderer: Context Restored."),I=!1;const C=G.autoReset,B=se.enabled,K=se.autoUpdate,X=se.needsUpdate,Y=se.type;Gt(),G.autoReset=C,se.enabled=B,se.autoUpdate=K,se.needsUpdate=X,se.type=Y}function Rr(C){ce("WebGLRenderer: A WebGL context could not be created. Reason: ",C.statusMessage)}function Ir(C){const B=C.target;B.removeEventListener("dispose",Ir),EA(B)}function EA(C){AA(C),$.remove(C)}function AA(C){const B=$.get(C).programs;B!==void 0&&(B.forEach(function(K){mt.releaseProgram(K)}),C.isShaderMaterial&&mt.releaseShaderCache(C))}this.renderBufferDirect=function(C,B,K,X,Y,bt){B===null&&(B=Ni);const Rt=Y.isMesh&&Y.matrixWorld.determinantAffine()<0,St=RA(C,B,K,X,Y);T.setMaterial(X,Rt);let kt=K.index,Yt=1;if(X.wireframe===!0){if(kt=j.getWireframeAttribute(K),kt===void 0)return;Yt=2}const be=K.drawRange,Ie=K.attributes.position;let Kt=be.start*Yt,di=(be.start+be.count)*Yt;bt!==null&&(Kt=Math.max(Kt,bt.start*Yt),di=Math.min(di,(bt.start+bt.count)*Yt)),kt!==null?(Kt=Math.max(Kt,0),di=Math.min(di,kt.count)):Ie!=null&&(Kt=Math.max(Kt,0),di=Math.min(di,Ie.count));const qi=di-Kt;if(qi<0||qi===1/0)return;Et.setup(Y,X,St,K,kt);let Hi,Mi=dt;if(kt!==null&&(Hi=ft.get(kt),Mi=et,Mi.setIndex(Hi)),Y.isMesh)X.wireframe===!0?(T.setLineWidth(X.wireframeLinewidth*an()),Mi.setMode(z.LINES)):Mi.setMode(z.TRIANGLES);else if(Y.isLine){let Gn=X.linewidth;Gn===void 0&&(Gn=1),T.setLineWidth(Gn*an()),Y.isLineSegments?Mi.setMode(z.LINES):Y.isLineLoop?Mi.setMode(z.LINE_LOOP):Mi.setMode(z.LINE_STRIP)}else Y.isPoints?Mi.setMode(z.POINTS):Y.isSprite&&Mi.setMode(z.TRIANGLES);if(Y.isBatchedMesh)if(ni.get("WEBGL_multi_draw"))Mi.renderMultiDraw(Y._multiDrawStarts,Y._multiDrawCounts,Y._multiDrawCount);else{const Gn=Y._multiDrawStarts,_t=Y._multiDrawCounts,Os=Y._multiDrawCount,He=kt?ft.get(kt).bytesPerElement:1,Ys=$.get(X).currentProgram.getUniforms();for(let Dr=0;Dr<Os;Dr++)Ys.setValue(z,"_gl_DrawID",Dr),Mi.render(Gn[Dr]/He,_t[Dr])}else if(Y.isInstancedMesh)Mi.renderInstances(Kt,qi,Y.count);else if(K.isInstancedBufferGeometry){const Gn=K._maxInstanceCount!==void 0?K._maxInstanceCount:1/0,_t=Math.min(K.instanceCount,Gn);Mi.renderInstances(Kt,qi,_t)}else Mi.render(Kt,qi)};function Wv(C,B,K){C.transparent===!0&&C.side===xn&&C.forceSinglePass===!1?(C.side=Ci,C.needsUpdate=!0,Yd(C,B,K),C.side=pa,C.needsUpdate=!0,Yd(C,B,K),C.side=xn):Yd(C,B,K)}this.compile=function(C,B,K=null){K===null&&(K=C),b=gt.get(K),b.init(B),S.push(b),K.traverseVisible(function(Y){Y.isLight&&Y.layers.test(B.layers)&&(b.pushLight(Y),Y.castShadow&&b.pushShadow(Y))}),C!==K&&C.traverseVisible(function(Y){Y.isLight&&Y.layers.test(B.layers)&&(b.pushLight(Y),Y.castShadow&&b.pushShadow(Y))}),b.setupLights();const X=new Set;return C.traverse(function(Y){if(!(Y.isMesh||Y.isPoints||Y.isLine||Y.isSprite))return;const bt=Y.material;if(bt)if(Array.isArray(bt))for(let Rt=0;Rt<bt.length;Rt++){const St=bt[Rt];Wv(St,K,Y),X.add(St)}else Wv(bt,K,Y),X.add(bt)}),b=S.pop(),X},this.compileAsync=function(C,B,K=null){const X=this.compile(C,B,K);return new Promise(Y=>{function bt(){if(X.forEach(function(Rt){$.get(Rt).currentProgram.isReady()&&X.delete(Rt)}),X.size===0){Y(C);return}setTimeout(bt,10)}ni.get("KHR_parallel_shader_compile")!==null?bt():setTimeout(bt,10)})};let Wp=null;function _A(C){Wp&&Wp(C)}function Xv(){jo.stop()}function Yv(){jo.start()}const jo=new pE;jo.setAnimationLoop(_A),typeof self<"u"&&jo.setContext(self),this.setAnimationLoop=function(C){Wp=C,Lt.setAnimationLoop(C),C===null?jo.stop():jo.start()},Lt.addEventListener("sessionstart",Xv),Lt.addEventListener("sessionend",Yv),this.render=function(C,B){if(B!==void 0&&B.isCamera!==!0){ce("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(I===!0)return;D!==null&&D.renderStart(C,B);const K=Lt.enabled===!0&&Lt.isPresenting===!0,X=A!==null&&(W===null||K)&&A.begin(_,W);if(C.matrixWorldAutoUpdate===!0&&C.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),Lt.enabled===!0&&Lt.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(Lt.cameraAutoUpdate===!0&&Lt.updateCamera(B),B=Lt.getCamera()),C.isScene===!0&&C.onBeforeRender(_,C,B,W),b=gt.get(C,S.length),b.init(B),b.state.textureUnits=J.getTextureUnits(),S.push(b),ei.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),jt.setFromProjectionMatrix(ei,ca,B.reversedDepth),ne=this.localClippingEnabled,ie=Jt.init(this.clippingPlanes,ne),w=xt.get(C,E.length),w.init(),E.push(w),Lt.enabled===!0&&Lt.isPresenting===!0){const Rt=_.xr.getDepthSensingMesh();Rt!==null&&Xp(Rt,B,-1/0,_.sortObjects)}Xp(C,B,0,_.sortObjects),w.finish(),_.sortObjects===!0&&w.sort(V,Ot,B.reversedDepth),zi=Lt.enabled===!1||Lt.isPresenting===!1||Lt.hasDepthSensing()===!1,zi&&Se.addToRenderList(w,C),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ie===!0&&Jt.beginShadows();const Y=b.state.shadowsArray;if(se.render(Y,C,B),ie===!0&&Jt.endShadows(),(X&&A.hasRenderPass())===!1){const Rt=w.opaque,St=w.transmissive;if(b.setupLights(),B.isArrayCamera){const kt=B.cameras;if(St.length>0)for(let Yt=0,be=kt.length;Yt<be;Yt++){const Ie=kt[Yt];Kv(Rt,St,C,Ie)}zi&&Se.render(C);for(let Yt=0,be=kt.length;Yt<be;Yt++){const Ie=kt[Yt];$v(w,C,Ie,Ie.viewport)}}else St.length>0&&Kv(Rt,St,C,B),zi&&Se.render(C),$v(w,C,B)}W!==null&&H===0&&(J.updateMultisampleRenderTarget(W),J.updateRenderTargetMipmap(W)),X&&A.end(_),C.isScene===!0&&C.onAfterRender(_,C,B),Et.resetDefaultState(),Q=-1,q=null,S.pop(),S.length>0?(b=S[S.length-1],J.setTextureUnits(b.state.textureUnits),ie===!0&&Jt.setGlobalState(_.clippingPlanes,b.state.camera)):b=null,E.pop(),E.length>0?w=E[E.length-1]:w=null,D!==null&&D.renderEnd()};function Xp(C,B,K,X){if(C.visible===!1)return;if(C.layers.test(B.layers)){if(C.isGroup)K=C.renderOrder;else if(C.isLOD)C.autoUpdate===!0&&C.update(B);else if(C.isLightProbeGrid)b.pushLightProbeGrid(C);else if(C.isLight)b.pushLight(C),C.castShadow&&b.pushShadow(C);else if(C.isSprite){if(!C.frustumCulled||jt.intersectsSprite(C)){X&&Fi.setFromMatrixPosition(C.matrixWorld).applyMatrix4(ei);const Rt=it.update(C),St=C.material;St.visible&&w.push(C,Rt,St,K,Fi.z,null)}}else if((C.isMesh||C.isLine||C.isPoints)&&(!C.frustumCulled||jt.intersectsObject(C))){const Rt=it.update(C),St=C.material;if(X&&(C.boundingSphere!==void 0?(C.boundingSphere===null&&C.computeBoundingSphere(),Fi.copy(C.boundingSphere.center)):(Rt.boundingSphere===null&&Rt.computeBoundingSphere(),Fi.copy(Rt.boundingSphere.center)),Fi.applyMatrix4(C.matrixWorld).applyMatrix4(ei)),Array.isArray(St)){const kt=Rt.groups;for(let Yt=0,be=kt.length;Yt<be;Yt++){const Ie=kt[Yt],Kt=St[Ie.materialIndex];Kt&&Kt.visible&&w.push(C,Rt,Kt,K,Fi.z,Ie)}}else St.visible&&w.push(C,Rt,St,K,Fi.z,null)}}const bt=C.children;for(let Rt=0,St=bt.length;Rt<St;Rt++)Xp(bt[Rt],B,K,X)}function $v(C,B,K,X){const{opaque:Y,transmissive:bt,transparent:Rt}=C;b.setupLightsView(K),ie===!0&&Jt.setGlobalState(_.clippingPlanes,K),X&&T.viewport(nt.copy(X)),Y.length>0&&Xd(Y,B,K),bt.length>0&&Xd(bt,B,K),Rt.length>0&&Xd(Rt,B,K),T.buffers.depth.setTest(!0),T.buffers.depth.setMask(!0),T.buffers.color.setMask(!0),T.setPolygonOffset(!1)}function Kv(C,B,K,X){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;if(b.state.transmissionRenderTarget[X.id]===void 0){const Kt=ni.has("EXT_color_buffer_half_float")||ni.has("EXT_color_buffer_float");b.state.transmissionRenderTarget[X.id]=new qe(1,1,{generateMipmaps:!0,type:Kt?We:Qn,minFilter:Vs,samples:Math.max(4,N.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ue.workingColorSpace})}const bt=b.state.transmissionRenderTarget[X.id],Rt=X.viewport||nt;bt.setSize(Rt.z*_.transmissionResolutionScale,Rt.w*_.transmissionResolutionScale);const St=_.getRenderTarget(),kt=_.getActiveCubeFace(),Yt=_.getActiveMipmapLevel();_.setRenderTarget(bt),_.getClearColor(Zt),Pt=_.getClearAlpha(),Pt<1&&_.setClearColor(16777215,.5),_.clear(),zi&&Se.render(K);const be=_.toneMapping;_.toneMapping=ua;const Ie=X.viewport;if(X.viewport!==void 0&&(X.viewport=void 0),b.setupLightsView(X),ie===!0&&Jt.setGlobalState(_.clippingPlanes,X),Xd(C,K,X),J.updateMultisampleRenderTarget(bt),J.updateRenderTargetMipmap(bt),ni.has("WEBGL_multisampled_render_to_texture")===!1){let Kt=!1;for(let di=0,qi=B.length;di<qi;di++){const Hi=B[di],{object:Mi,geometry:Gn,material:_t,group:Os}=Hi;if(_t.side===xn&&Mi.layers.test(X.layers)){const He=_t.side;_t.side=Ci,_t.needsUpdate=!0,qv(Mi,K,X,Gn,_t,Os),_t.side=He,_t.needsUpdate=!0,Kt=!0}}Kt===!0&&(J.updateMultisampleRenderTarget(bt),J.updateRenderTargetMipmap(bt))}_.setRenderTarget(St,kt,Yt),_.setClearColor(Zt,Pt),Ie!==void 0&&(X.viewport=Ie),_.toneMapping=be}function Xd(C,B,K){const X=B.isScene===!0?B.overrideMaterial:null;for(let Y=0,bt=C.length;Y<bt;Y++){const Rt=C[Y],{object:St,geometry:kt,group:Yt}=Rt;let be=Rt.material;be.allowOverride===!0&&X!==null&&(be=X),St.layers.test(K.layers)&&qv(St,B,K,kt,be,Yt)}}function qv(C,B,K,X,Y,bt){C.onBeforeRender(_,B,K,X,Y,bt),C.modelViewMatrix.multiplyMatrices(K.matrixWorldInverse,C.matrixWorld),C.normalMatrix.getNormalMatrix(C.modelViewMatrix),Y.onBeforeRender(_,B,K,X,C,bt),Y.transparent===!0&&Y.side===xn&&Y.forceSinglePass===!1?(Y.side=Ci,Y.needsUpdate=!0,_.renderBufferDirect(K,B,X,Y,C,bt),Y.side=pa,Y.needsUpdate=!0,_.renderBufferDirect(K,B,X,Y,C,bt),Y.side=xn):_.renderBufferDirect(K,B,X,Y,C,bt),C.onAfterRender(_,B,K,X,Y,bt)}function Yd(C,B,K){B.isScene!==!0&&(B=Ni);const X=$.get(C),Y=b.state.lights,bt=b.state.shadowsArray,Rt=Y.state.version,St=mt.getParameters(C,Y.state,bt,B,K,b.state.lightProbeGridArray),kt=mt.getProgramCacheKey(St);let Yt=X.programs;X.environment=C.isMeshStandardMaterial||C.isMeshLambertMaterial||C.isMeshPhongMaterial?B.environment:null,X.fog=B.fog;const be=C.isMeshStandardMaterial||C.isMeshLambertMaterial&&!C.envMap||C.isMeshPhongMaterial&&!C.envMap;X.envMap=ht.get(C.envMap||X.environment,be),X.envMapRotation=X.environment!==null&&C.envMap===null?B.environmentRotation:C.envMapRotation,Yt===void 0&&(C.addEventListener("dispose",Ir),Yt=new Map,X.programs=Yt);let Ie=Yt.get(kt);if(Ie!==void 0){if(X.currentProgram===Ie&&X.lightsStateVersion===Rt)return Jv(C,St),Ie}else St.uniforms=mt.getUniforms(C),D!==null&&C.isNodeMaterial&&D.build(C,K,St),C.onBeforeCompile(St,_),Ie=mt.acquireProgram(St,kt),Yt.set(kt,Ie),X.uniforms=St.uniforms;const Kt=X.uniforms;return(!C.isShaderMaterial&&!C.isRawShaderMaterial||C.clipping===!0)&&(Kt.clippingPlanes=Jt.uniform),Jv(C,St),X.needsLights=DA(C),X.lightsStateVersion=Rt,X.needsLights&&(Kt.ambientLightColor.value=Y.state.ambient,Kt.lightProbe.value=Y.state.probe,Kt.directionalLights.value=Y.state.directional,Kt.directionalLightShadows.value=Y.state.directionalShadow,Kt.spotLights.value=Y.state.spot,Kt.spotLightShadows.value=Y.state.spotShadow,Kt.rectAreaLights.value=Y.state.rectArea,Kt.ltc_1.value=Y.state.rectAreaLTC1,Kt.ltc_2.value=Y.state.rectAreaLTC2,Kt.pointLights.value=Y.state.point,Kt.pointLightShadows.value=Y.state.pointShadow,Kt.hemisphereLights.value=Y.state.hemi,Kt.directionalShadowMatrix.value=Y.state.directionalShadowMatrix,Kt.spotLightMatrix.value=Y.state.spotLightMatrix,Kt.spotLightMap.value=Y.state.spotLightMap,Kt.pointShadowMatrix.value=Y.state.pointShadowMatrix),X.lightProbeGrid=b.state.lightProbeGridArray.length>0,X.currentProgram=Ie,X.uniformsList=null,Ie}function Zv(C){if(C.uniformsList===null){const B=C.currentProgram.getUniforms();C.uniformsList=A0.seqWithValue(B.seq,C.uniforms)}return C.uniformsList}function Jv(C,B){const K=$.get(C);K.outputColorSpace=B.outputColorSpace,K.batching=B.batching,K.batchingColor=B.batchingColor,K.instancing=B.instancing,K.instancingColor=B.instancingColor,K.instancingMorph=B.instancingMorph,K.skinning=B.skinning,K.morphTargets=B.morphTargets,K.morphNormals=B.morphNormals,K.morphColors=B.morphColors,K.morphTargetsCount=B.morphTargetsCount,K.numClippingPlanes=B.numClippingPlanes,K.numIntersection=B.numClipIntersection,K.vertexAlphas=B.vertexAlphas,K.vertexTangents=B.vertexTangents,K.toneMapping=B.toneMapping}function TA(C,B){if(C.length===0)return null;if(C.length===1)return C[0].texture!==null?C[0]:null;y.setFromMatrixPosition(B.matrixWorld);for(let K=0,X=C.length;K<X;K++){const Y=C[K];if(Y.texture!==null&&Y.boundingBox.containsPoint(y))return Y}return null}function RA(C,B,K,X,Y){B.isScene!==!0&&(B=Ni),J.resetTextureUnits();const bt=B.fog,Rt=X.isMeshStandardMaterial||X.isMeshLambertMaterial||X.isMeshPhongMaterial?B.environment:null,St=W===null?_.outputColorSpace:W.isXRRenderTarget===!0?W.texture.colorSpace:Ue.workingColorSpace,kt=X.isMeshStandardMaterial||X.isMeshLambertMaterial&&!X.envMap||X.isMeshPhongMaterial&&!X.envMap,Yt=ht.get(X.envMap||Rt,kt),be=X.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,Ie=!!K.attributes.tangent&&(!!X.normalMap||X.anisotropy>0),Kt=!!K.morphAttributes.position,di=!!K.morphAttributes.normal,qi=!!K.morphAttributes.color;let Hi=ua;X.toneMapped&&(W===null||W.isXRRenderTarget===!0)&&(Hi=_.toneMapping);const Mi=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Gn=Mi!==void 0?Mi.length:0,_t=$.get(X),Os=b.state.lights;if(ie===!0&&(ne===!0||C!==q)){const wi=C===q&&X.id===Q;Jt.setState(X,C,wi)}let He=!1;X.version===_t.__version?(_t.needsLights&&_t.lightsStateVersion!==Os.state.version||_t.outputColorSpace!==St||Y.isBatchedMesh&&_t.batching===!1||!Y.isBatchedMesh&&_t.batching===!0||Y.isBatchedMesh&&_t.batchingColor===!0&&Y.colorTexture===null||Y.isBatchedMesh&&_t.batchingColor===!1&&Y.colorTexture!==null||Y.isInstancedMesh&&_t.instancing===!1||!Y.isInstancedMesh&&_t.instancing===!0||Y.isSkinnedMesh&&_t.skinning===!1||!Y.isSkinnedMesh&&_t.skinning===!0||Y.isInstancedMesh&&_t.instancingColor===!0&&Y.instanceColor===null||Y.isInstancedMesh&&_t.instancingColor===!1&&Y.instanceColor!==null||Y.isInstancedMesh&&_t.instancingMorph===!0&&Y.morphTexture===null||Y.isInstancedMesh&&_t.instancingMorph===!1&&Y.morphTexture!==null||_t.envMap!==Yt||X.fog===!0&&_t.fog!==bt||_t.numClippingPlanes!==void 0&&(_t.numClippingPlanes!==Jt.numPlanes||_t.numIntersection!==Jt.numIntersection)||_t.vertexAlphas!==be||_t.vertexTangents!==Ie||_t.morphTargets!==Kt||_t.morphNormals!==di||_t.morphColors!==qi||_t.toneMapping!==Hi||_t.morphTargetsCount!==Gn||!!_t.lightProbeGrid!=b.state.lightProbeGridArray.length>0)&&(He=!0):(He=!0,_t.__version=X.version);let Ys=_t.currentProgram;He===!0&&(Ys=Yd(X,B,Y),D&&X.isNodeMaterial&&D.onUpdateProgram(X,Ys,_t));let Dr=!1,to=!1,Yc=!1;const vi=Ys.getUniforms(),Zi=_t.uniforms;if(T.useProgram(Ys.program)&&(Dr=!0,to=!0,Yc=!0),X.id!==Q&&(Q=X.id,to=!0),_t.needsLights){const wi=TA(b.state.lightProbeGridArray,Y);_t.lightProbeGrid!==wi&&(_t.lightProbeGrid=wi,to=!0)}if(Dr||q!==C){T.buffers.depth.getReversed()&&C.reversedDepth!==!0&&(C._reversedDepth=!0,C.updateProjectionMatrix()),vi.setValue(z,"projectionMatrix",C.projectionMatrix),vi.setValue(z,"viewMatrix",C.matrixWorldInverse);const io=vi.map.cameraPosition;io!==void 0&&io.setValue(z,ii.setFromMatrixPosition(C.matrixWorld)),N.logarithmicDepthBuffer&&vi.setValue(z,"logDepthBufFC",2/(Math.log(C.far+1)/Math.LN2)),(X.isMeshPhongMaterial||X.isMeshToonMaterial||X.isMeshLambertMaterial||X.isMeshBasicMaterial||X.isMeshStandardMaterial||X.isShaderMaterial)&&vi.setValue(z,"isOrthographic",C.isOrthographicCamera===!0),q!==C&&(q=C,to=!0,Yc=!0)}if(_t.needsLights&&(Os.state.directionalShadowMap.length>0&&vi.setValue(z,"directionalShadowMap",Os.state.directionalShadowMap,J),Os.state.spotShadowMap.length>0&&vi.setValue(z,"spotShadowMap",Os.state.spotShadowMap,J),Os.state.pointShadowMap.length>0&&vi.setValue(z,"pointShadowMap",Os.state.pointShadowMap,J)),Y.isSkinnedMesh){vi.setOptional(z,Y,"bindMatrix"),vi.setOptional(z,Y,"bindMatrixInverse");const wi=Y.skeleton;wi&&(wi.boneTexture===null&&wi.computeBoneTexture(),vi.setValue(z,"boneTexture",wi.boneTexture,J))}Y.isBatchedMesh&&(vi.setOptional(z,Y,"batchingTexture"),vi.setValue(z,"batchingTexture",Y._matricesTexture,J),vi.setOptional(z,Y,"batchingIdTexture"),vi.setValue(z,"batchingIdTexture",Y._indirectTexture,J),vi.setOptional(z,Y,"batchingColorTexture"),Y._colorsTexture!==null&&vi.setValue(z,"batchingColorTexture",Y._colorsTexture,J));const eo=K.morphAttributes;if((eo.position!==void 0||eo.normal!==void 0||eo.color!==void 0)&&F.update(Y,K,Ys),(to||_t.receiveShadow!==Y.receiveShadow)&&(_t.receiveShadow=Y.receiveShadow,vi.setValue(z,"receiveShadow",Y.receiveShadow)),(X.isMeshStandardMaterial||X.isMeshLambertMaterial||X.isMeshPhongMaterial)&&X.envMap===null&&B.environment!==null&&(Zi.envMapIntensity.value=B.environmentIntensity),Zi.dfgLUT!==void 0&&(Zi.dfgLUT.value=BC()),to){if(vi.setValue(z,"toneMappingExposure",_.toneMappingExposure),_t.needsLights&&IA(Zi,Yc),bt&&X.fog===!0&&Xt.refreshFogUniforms(Zi,bt),Xt.refreshMaterialUniforms(Zi,X,ot,ct,b.state.transmissionRenderTarget[C.id]),_t.needsLights&&_t.lightProbeGrid){const wi=_t.lightProbeGrid;Zi.probesSH.value=wi.texture,Zi.probesMin.value.copy(wi.boundingBox.min),Zi.probesMax.value.copy(wi.boundingBox.max),Zi.probesResolution.value.copy(wi.resolution)}A0.upload(z,Zv(_t),Zi,J)}if(X.isShaderMaterial&&X.uniformsNeedUpdate===!0&&(A0.upload(z,Zv(_t),Zi,J),X.uniformsNeedUpdate=!1),X.isSpriteMaterial&&vi.setValue(z,"center",Y.center),vi.setValue(z,"modelViewMatrix",Y.modelViewMatrix),vi.setValue(z,"normalMatrix",Y.normalMatrix),vi.setValue(z,"modelMatrix",Y.matrixWorld),X.uniformsGroups!==void 0){const wi=X.uniformsGroups;for(let io=0,$c=wi.length;io<$c;io++){const jv=wi[io];st.update(jv,Ys),st.bind(jv,Ys)}}return Ys}function IA(C,B){C.ambientLightColor.needsUpdate=B,C.lightProbe.needsUpdate=B,C.directionalLights.needsUpdate=B,C.directionalLightShadows.needsUpdate=B,C.pointLights.needsUpdate=B,C.pointLightShadows.needsUpdate=B,C.spotLights.needsUpdate=B,C.spotLightShadows.needsUpdate=B,C.rectAreaLights.needsUpdate=B,C.hemisphereLights.needsUpdate=B}function DA(C){return C.isMeshLambertMaterial||C.isMeshToonMaterial||C.isMeshPhongMaterial||C.isMeshStandardMaterial||C.isShadowMaterial||C.isShaderMaterial&&C.lights===!0}this.getActiveCubeFace=function(){return k},this.getActiveMipmapLevel=function(){return H},this.getRenderTarget=function(){return W},this.setRenderTargetTextures=function(C,B,K){const X=$.get(C);X.__autoAllocateDepthBuffer=C.resolveDepthBuffer===!1,X.__autoAllocateDepthBuffer===!1&&(X.__useRenderToTexture=!1),$.get(C.texture).__webglTexture=B,$.get(C.depthTexture).__webglTexture=X.__autoAllocateDepthBuffer?void 0:K,X.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(C,B){const K=$.get(C);K.__webglFramebuffer=B,K.__useDefaultFramebuffer=B===void 0},this.setRenderTarget=function(C,B=0,K=0){W=C,k=B,H=K;let X=null,Y=!1,bt=!1;if(C){const St=$.get(C);if(St.__useDefaultFramebuffer!==void 0){T.bindFramebuffer(z.FRAMEBUFFER,St.__webglFramebuffer),nt.copy(C.viewport),at.copy(C.scissor),zt=C.scissorTest,T.viewport(nt),T.scissor(at),T.setScissorTest(zt),Q=-1;return}else if(St.__webglFramebuffer===void 0)J.setupRenderTarget(C);else if(St.__hasExternalTextures)J.rebindTextures(C,$.get(C.texture).__webglTexture,$.get(C.depthTexture).__webglTexture);else if(C.depthBuffer){const be=C.depthTexture;if(St.__boundDepthTexture!==be){if(be!==null&&$.has(be)&&(C.width!==be.image.width||C.height!==be.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");J.setupDepthRenderbuffer(C)}}const kt=C.texture;(kt.isData3DTexture||kt.isDataArrayTexture||kt.isCompressedArrayTexture)&&(bt=!0);const Yt=$.get(C).__webglFramebuffer;C.isWebGLCubeRenderTarget?(Array.isArray(Yt[B])?X=Yt[B][K]:X=Yt[B],Y=!0):C.samples>0&&J.useMultisampledRTT(C)===!1?X=$.get(C).__webglMultisampledFramebuffer:Array.isArray(Yt)?X=Yt[K]:X=Yt,nt.copy(C.viewport),at.copy(C.scissor),zt=C.scissorTest}else nt.copy(Wt).multiplyScalar(ot).floor(),at.copy(Nt).multiplyScalar(ot).floor(),zt=Tt;if(K!==0&&(X=P),T.bindFramebuffer(z.FRAMEBUFFER,X)&&T.drawBuffers(C,X),T.viewport(nt),T.scissor(at),T.setScissorTest(zt),Y){const St=$.get(C.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+B,St.__webglTexture,K)}else if(bt){const St=B;for(let kt=0;kt<C.textures.length;kt++){const Yt=$.get(C.textures[kt]);z.framebufferTextureLayer(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0+kt,Yt.__webglTexture,K,St)}}else if(C!==null&&K!==0){const St=$.get(C.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,St.__webglTexture,K)}Q=-1},this.readRenderTargetPixels=function(C,B,K,X,Y,bt,Rt,St=0){if(!(C&&C.isWebGLRenderTarget)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let kt=$.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&Rt!==void 0&&(kt=kt[Rt]),kt){T.bindFramebuffer(z.FRAMEBUFFER,kt);try{const Yt=C.textures[St],be=Yt.format,Ie=Yt.type;if(C.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+St),!N.textureFormatReadable(be)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!N.textureTypeReadable(Ie)){ce("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}B>=0&&B<=C.width-X&&K>=0&&K<=C.height-Y&&z.readPixels(B,K,X,Y,Mt.convert(be),Mt.convert(Ie),bt)}finally{const Yt=W!==null?$.get(W).__webglFramebuffer:null;T.bindFramebuffer(z.FRAMEBUFFER,Yt)}}},this.readRenderTargetPixelsAsync=async function(C,B,K,X,Y,bt,Rt,St=0){if(!(C&&C.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let kt=$.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&Rt!==void 0&&(kt=kt[Rt]),kt)if(B>=0&&B<=C.width-X&&K>=0&&K<=C.height-Y){T.bindFramebuffer(z.FRAMEBUFFER,kt);const Yt=C.textures[St],be=Yt.format,Ie=Yt.type;if(C.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+St),!N.textureFormatReadable(be))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!N.textureTypeReadable(Ie))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Kt=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,Kt),z.bufferData(z.PIXEL_PACK_BUFFER,bt.byteLength,z.STREAM_READ),z.readPixels(B,K,X,Y,Mt.convert(be),Mt.convert(Ie),0);const di=W!==null?$.get(W).__webglFramebuffer:null;T.bindFramebuffer(z.FRAMEBUFFER,di);const qi=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await kT(z,qi,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,Kt),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,bt),z.deleteBuffer(Kt),z.deleteSync(qi),bt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(C,B=null,K=0){const X=Math.pow(2,-K),Y=Math.floor(C.image.width*X),bt=Math.floor(C.image.height*X),Rt=B!==null?B.x:0,St=B!==null?B.y:0;J.setTexture2D(C,0),z.copyTexSubImage2D(z.TEXTURE_2D,K,0,0,Rt,St,Y,bt),T.unbindTexture()},this.copyTextureToTexture=function(C,B,K=null,X=null,Y=0,bt=0){let Rt,St,kt,Yt,be,Ie,Kt,di,qi;const Hi=C.isCompressedTexture?C.mipmaps[bt]:C.image;if(K!==null)Rt=K.max.x-K.min.x,St=K.max.y-K.min.y,kt=K.isBox3?K.max.z-K.min.z:1,Yt=K.min.x,be=K.min.y,Ie=K.isBox3?K.min.z:0;else{const Zi=Math.pow(2,-Y);Rt=Math.floor(Hi.width*Zi),St=Math.floor(Hi.height*Zi),C.isDataArrayTexture?kt=Hi.depth:C.isData3DTexture?kt=Math.floor(Hi.depth*Zi):kt=1,Yt=0,be=0,Ie=0}X!==null?(Kt=X.x,di=X.y,qi=X.z):(Kt=0,di=0,qi=0);const Mi=Mt.convert(B.format),Gn=Mt.convert(B.type);let _t;B.isData3DTexture?(J.setTexture3D(B,0),_t=z.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(J.setTexture2DArray(B,0),_t=z.TEXTURE_2D_ARRAY):(J.setTexture2D(B,0),_t=z.TEXTURE_2D),T.activeTexture(z.TEXTURE0),T.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,B.flipY),T.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),T.pixelStorei(z.UNPACK_ALIGNMENT,B.unpackAlignment);const Os=T.getParameter(z.UNPACK_ROW_LENGTH),He=T.getParameter(z.UNPACK_IMAGE_HEIGHT),Ys=T.getParameter(z.UNPACK_SKIP_PIXELS),Dr=T.getParameter(z.UNPACK_SKIP_ROWS),to=T.getParameter(z.UNPACK_SKIP_IMAGES);T.pixelStorei(z.UNPACK_ROW_LENGTH,Hi.width),T.pixelStorei(z.UNPACK_IMAGE_HEIGHT,Hi.height),T.pixelStorei(z.UNPACK_SKIP_PIXELS,Yt),T.pixelStorei(z.UNPACK_SKIP_ROWS,be),T.pixelStorei(z.UNPACK_SKIP_IMAGES,Ie);const Yc=C.isDataArrayTexture||C.isData3DTexture,vi=B.isDataArrayTexture||B.isData3DTexture;if(C.isDepthTexture){const Zi=$.get(C),eo=$.get(B),wi=$.get(Zi.__renderTarget),io=$.get(eo.__renderTarget);T.bindFramebuffer(z.READ_FRAMEBUFFER,wi.__webglFramebuffer),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,io.__webglFramebuffer);for(let $c=0;$c<kt;$c++)Yc&&(z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,$.get(C).__webglTexture,Y,Ie+$c),z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,$.get(B).__webglTexture,bt,qi+$c)),z.blitFramebuffer(Yt,be,Rt,St,Kt,di,Rt,St,z.DEPTH_BUFFER_BIT,z.NEAREST);T.bindFramebuffer(z.READ_FRAMEBUFFER,null),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if(Y!==0||C.isRenderTargetTexture||$.has(C)){const Zi=$.get(C),eo=$.get(B);T.bindFramebuffer(z.READ_FRAMEBUFFER,L),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,O);for(let wi=0;wi<kt;wi++)Yc?z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Zi.__webglTexture,Y,Ie+wi):z.framebufferTexture2D(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,Zi.__webglTexture,Y),vi?z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,eo.__webglTexture,bt,qi+wi):z.framebufferTexture2D(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,eo.__webglTexture,bt),Y!==0?z.blitFramebuffer(Yt,be,Rt,St,Kt,di,Rt,St,z.COLOR_BUFFER_BIT,z.NEAREST):vi?z.copyTexSubImage3D(_t,bt,Kt,di,qi+wi,Yt,be,Rt,St):z.copyTexSubImage2D(_t,bt,Kt,di,Yt,be,Rt,St);T.bindFramebuffer(z.READ_FRAMEBUFFER,null),T.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else vi?C.isDataTexture||C.isData3DTexture?z.texSubImage3D(_t,bt,Kt,di,qi,Rt,St,kt,Mi,Gn,Hi.data):B.isCompressedArrayTexture?z.compressedTexSubImage3D(_t,bt,Kt,di,qi,Rt,St,kt,Mi,Hi.data):z.texSubImage3D(_t,bt,Kt,di,qi,Rt,St,kt,Mi,Gn,Hi):C.isDataTexture?z.texSubImage2D(z.TEXTURE_2D,bt,Kt,di,Rt,St,Mi,Gn,Hi.data):C.isCompressedTexture?z.compressedTexSubImage2D(z.TEXTURE_2D,bt,Kt,di,Hi.width,Hi.height,Mi,Hi.data):z.texSubImage2D(z.TEXTURE_2D,bt,Kt,di,Rt,St,Mi,Gn,Hi);T.pixelStorei(z.UNPACK_ROW_LENGTH,Os),T.pixelStorei(z.UNPACK_IMAGE_HEIGHT,He),T.pixelStorei(z.UNPACK_SKIP_PIXELS,Ys),T.pixelStorei(z.UNPACK_SKIP_ROWS,Dr),T.pixelStorei(z.UNPACK_SKIP_IMAGES,to),bt===0&&B.generateMipmaps&&z.generateMipmap(_t),T.unbindTexture()},this.initRenderTarget=function(C){$.get(C).__webglFramebuffer===void 0&&J.setupRenderTarget(C)},this.initTexture=function(C){C.isCubeTexture?J.setTextureCube(C,0):C.isData3DTexture?J.setTexture3D(C,0):C.isDataArrayTexture||C.isCompressedArrayTexture?J.setTexture2DArray(C,0):J.setTexture2D(C,0),T.unbindTexture()},this.resetState=function(){k=0,H=0,W=null,T.reset(),Et.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ca}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=Ue._getDrawingBufferColorSpace(t),e.unpackColorSpace=Ue._getUnpackColorSpace()}}const GC=`
5886
5886
  varying vec3 vDir;
5887
5887
  varying vec3 vWorldDir;
5888
5888
 
@@ -6895,7 +6895,7 @@ void main() {`).replace(Gr.ANCHOR,`float sigma = max(${Ht.MIN_SIGMA_PX.toFixed(2
6895
6895
  diffuseColor.a *= 1.0 + level * ${zu.PER_LEVEL.toFixed(2)};
6896
6896
  }
6897
6897
  #endif
6898
- ${he.alphatest_fragment}`)}}class le{static WIDTH=160;static HEIGHT=90;static BLEACHING_CD_M2_S=22e7;static REGENERATION_S=110;static SPREAD_DEG=.5;static JUMP_MS=2e3;static POSITIVE_FADE_S=1.5;static POSITIVE_GAIN=20;static FLIGHT=[{ageS:0,rgb:[1,1,1]},{ageS:.6,rgb:[.35,1.05,.95]},{ageS:1.4,rgb:[.55,.6,3.6]},{ageS:2.4,rgb:[1.7,.6,1.5]},{ageS:3.5,rgb:[1.9,.75,.25]}];texture;left=new Float32Array(le.WIDTH*le.HEIGHT).fill(1);glow=new Float32Array(le.WIDTH*le.HEIGHT);age=new Float32Array(le.WIDTH*le.HEIGHT);bytes=le.freshBytes();lastMs;bleached=!1;constructor(){this.texture=new ms(this.bytes,le.WIDTH,le.HEIGHT,$i,We),this.texture.minFilter=ge,this.texture.magFilter=ge,this.texture.needsUpdate=!0}get any(){return this.bleached}advance(t,e,i){const n=this.lastMs===void 0?1/0:t-this.lastMs;if(this.lastMs=t,n===0)return!1;const s=le.SPREAD_DEG*Math.PI/180,r=e.map(u=>({x:u.ndcX*i.width/2,y:u.ndcY*i.height/2,peak:u.lux/(2*Math.PI*s*s)})).filter(u=>u.peak>=le.FAINTEST_CD_M2);if(n<0||n>le.JUMP_MS)return this.previous=r,this.reset();if(!this.bleached&&e.length===0)return this.previous=void 0,!1;const a=this.previous?.length===r.length?this.previous:void 0,c=a?Math.max(0,...r.map((u,d)=>Math.hypot(u.x-a[d].x,u.y-a[d].y))):0,l=Math.min(le.MAX_STEPS,Math.max(1,Math.ceil(c/(le.SPREAD_DEG/3)))),h=n/1e3/l;for(let u=1;u<=l;u++){const d=u/l;this.bleach(a?r.map((f,p)=>({...f,x:a[p].x+(f.x-a[p].x)*d,y:a[p].y+(f.y-a[p].y)*d})):r,h,i)}return this.previous=r,this.texture.needsUpdate=!0,!0}static FAINTEST_CD_M2=le.BLEACHING_CD_M2_S/le.REGENERATION_S*1e-4;static MAX_STEPS=64;previous;bleach(t,e,i){const n=le.WIDTH,s=le.HEIGHT,r=le.SPREAD_DEG,a=1/le.REGENERATION_S,c=this.light.fill(0);for(const h of t){const u=Math.max(0,Math.floor(((h.x-5*r)/i.width+.5)*n)),d=Math.min(n-1,Math.ceil(((h.x+5*r)/i.width+.5)*n)),f=Math.max(0,Math.floor(((h.y-5*r)/i.height+.5)*s)),p=Math.min(s-1,Math.ceil(((h.y+5*r)/i.height+.5)*s));for(let m=f;m<=p;m++){const g=((m+.5)/s*2-1)*i.height/2;for(let M=u;M<=d;M++){const x=(((M+.5)/n*2-1)*i.width/2-h.x)**2+(g-h.y)**2;x<25*r*r&&(c[m*n+M]+=h.peak*Math.exp(-x/(2*r*r)))}}}let l=!1;for(let h=0;h<s;h++)for(let u=0;u<n;u++){const d=h*n+u,f=c[d],p=this.left[d],m=this.glow[d];if(f===0&&p>=.9995&&m<le.GLOW_SEEN)continue;const g=a+f/le.BLEACHING_CD_M2_S,M=a/g,v=M+(p-M)*Math.exp(-g*e);this.left[d]=v;const x=Math.max(0,p-v)*le.POSITIVE_GAIN,y=m*Math.exp(-e/le.POSITIVE_FADE_S),w=y+x;this.age[d]=w>0?y*(this.age[d]+e)/w:0,this.glow[d]=w;const b=le.flightAt(this.age[d]),E=d*4;this.bytes[E]=Nn.toHalfFloat(v);for(let S=0;S<3;S++)this.bytes[E+1+S]=Nn.toHalfFloat(w*b[S]);(v<.995||w>=le.GLOW_SEEN)&&(l=!0)}this.bleached=l}light=new Float32Array(le.WIDTH*le.HEIGHT);static GLOW_SEEN=.002;static flightAt(t){const e=le.FLIGHT;for(let i=1;i<e.length;i++){if(t>e[i].ageS)continue;const n=(t-e[i-1].ageS)/(e[i].ageS-e[i-1].ageS),s=e[i-1].rgb,r=e[i].rgb;return[s[0]+(r[0]-s[0])*n,s[1]+(r[1]-s[1])*n,s[2]+(r[2]-s[2])*n]}return e[e.length-1].rgb}static freshBytes(){const t=new Uint16Array(le.WIDTH*le.HEIGHT*4),e=Nn.toHalfFloat(1);for(let i=0;i<t.length;i+=4)t[i]=e;return t}leftAt(t,e){const i=Math.min(le.WIDTH-1,Math.max(0,Math.floor((t+1)/2*le.WIDTH))),n=Math.min(le.HEIGHT-1,Math.max(0,Math.floor((e+1)/2*le.HEIGHT)));return this.left[n*le.WIDTH+i]}get atMs(){return this.lastMs}replay(t,e,i,n,s){const r=new Map,a=d=>{let f=r.get(d);return f||r.set(d,f=i(d)),f};s!==this.snapshotsOf&&(this.snapshots.clear(),this.snapshotsOf=s);let c=t;for(const d of this.snapshots.keys())d<=e&&d>c&&(c=d);c>t?this.restore(c):this.reset(),this.previous=void 0,this.lastMs=c;let l=c,h=0;const u=d=>{const f=d%le.REPLAY_STRIDE_MS===0&&a(d).length>0?le.REPLAY_STRIDE_MS:le.SNAPSHOT_MS;d%f!==0||this.snapshots.has(d)||(h>0&&this.rest(h),h=0,this.snapshots.set(d,{left:this.left.slice(),glow:this.glow.slice(),age:this.age.slice(),bleached:this.bleached}))};for(;l<e;){u(l);const d=Math.min(e,(Math.floor(l/le.REPLAY_STRIDE_MS)+1)*le.REPLAY_STRIDE_MS);if(a(d).length===0&&a(l).length===0){h+=d-l,l=d;continue}h>0&&this.rest(h),h=0;const f=Math.min(e,(Math.floor(l/le.REPLAY_STEP_MS)+1)*le.REPLAY_STEP_MS);this.lastMs=l,this.advance(f,a(f),n),l=f}h>0&&this.rest(h),this.lastMs=e}static SNAPSHOT_MS=5e3;snapshots=new Map;snapshotsOf;restore(t){const e=this.snapshots.get(t);this.left.set(e.left),this.glow.set(e.glow),this.age.set(e.age),this.bleached=e.bleached;for(let i=0;i<this.left.length;i++){const n=i*4,s=le.flightAt(this.age[i]);this.bytes[n]=Nn.toHalfFloat(this.left[i]);for(let r=0;r<3;r++)this.bytes[n+1+r]=Nn.toHalfFloat(this.glow[i]*s[r])}this.texture.needsUpdate=!0}static REPLAY_STEP_MS=100;static REPLAY_STRIDE_MS=1e3;rest(t){this.previous=void 0,this.bleached&&(this.bleach([],t/1e3,{width:1,height:1}),this.texture.needsUpdate=!0)}reset(){return this.bleached?(this.left.fill(1),this.glow.fill(0),this.age.fill(0),this.bytes.set(le.freshBytes()),this.bleached=!1,this.texture.needsUpdate=!0,!0):!1}dispose(){this.texture.dispose()}}class cs{constructor(t,e,i=cs.NO_SHADOW){this.parent=t,this.sceneUnitsPerLux=e,this.shadow=i}static NEAR=4;static FAR=2;static FAR_DISTANCE=1e3;static SYSTEMS={BodySystem:"emitters: the bodies that glow whole, the named lights of a model (a craft's lights), and their flames",MeteorSystem:"emitters: the heads of meteors, far, from their magnitude",ReentrySystem:"emitters: the heads of re-entries, far, from their magnitude",PhenomenonSystem:"none yet: a phenomenon states no luminance, only a colour as seen and a 0..1 dazzle, which say nothing of the light it gives",BeamSystem:"none: a laser beam is a thread of scattered light, too faint to light the ground; where it ends lit is in the sky",PlumeSystem:"none: a launch plume is lit by the Sun, it gives out no light of its own",CloudSystem:"none: clouds are lit, they do not give out light",LayeredCloudSystem:"none: clouds are lit, they do not give out light",DecorSystem:"own lights: the streetlamps, with shadows for the nearest (SceneRenderer.addStreetlightLight); NOT YET its lesser lamps (traffic lights, a car's rear lights), drawn lit but lighting nothing",RoadSystem:"own lights: the lamps it places along a street are the decor's streetlamps (see DecorSystem)",RailwaySystem:"none: rails mirror the lamps, they give out no light",ContrailSystem:"none: a contrail is lit by the Sun, it gives out no light",WaterSystem:"none: water mirrors, it gives out no light",TraceSystem:"none: a trace on the ground is lit, it gives out no light",ReferenceSystem:"none: a photograph laid over the scene, not in it",MirrorSystem:"none: a mirror shows the scene's light, it gives out none",HeadlightSystem:"own lights: a vehicle's headlamps are spot lights, aimed",FlameEffect:"emitters: through BodySystem, which states each flame",LensFlareEffect:"none: a dazzle in the eye, nothing in the world",IceHaloEffect:"none: sunlight bent by ice, seen, not cast on the ground",RainbowEffect:"none: sunlight bent by drops, seen, not cast on the ground",SkyGlowEffect:"none: the Milky Way and the zodiacal light are in the sky's own light (ScatteredSky)",RainSystem:"none: rain gives out no light",SatelliteField:"none: a satellite is a speck of reflected sunlight, far too faint to light anything"};near;far;nearBy=new Map;farBy=new Map;static NO_SHADOW={halfExtentM:0,depthHalfRangeM:0,biasM:0,normalBiasM:0,mapSize:0};set(t,e,i=[]){this.nearBy.set(t,e.filter(n=>n.candela>0)),this.farBy.set(t,i.filter(n=>Math.max(...n.lux)>0))}cast(t){const e=[...this.nearBy.values()].flat(),i=[...this.farBy.values()].flat(),n=this.sceneUnitsPerLux();if(e.length>0||this.near){this.near??=this.build(cs.NEAR,()=>new dE(16777215,0,0,2));const s=a=>t?a.candela/Math.max(a.position.distanceToSquared(t),1e-6):a.candela,r=e.sort((a,c)=>s(c)-s(a));this.near.forEach((a,c)=>{const l=r[c];if(!l){a.intensity=0;return}a.position.copy(l.position);const h=cs.luminanceOf(l.colour);a.color.setRGB(l.colour[0]/h,l.colour[1]/h,l.colour[2]/h),a.intensity=l.candela*n})}if(i.length>0||this.far){this.far??=this.buildFar();const s=i.sort((r,a)=>cs.luminanceOf(a.lux)-cs.luminanceOf(r.lux));this.far.forEach((r,a)=>{const c=s[a];if(r.castShadow&&(r.shadow.autoUpdate=c!==void 0),!c){r.intensity=0;return}r.position.copy(c.direction).multiplyScalar(cs.FAR_DISTANCE).add(t??cs.ORIGIN),r.target.position.copy(t??cs.ORIGIN),r.target.updateMatrixWorld();const l=cs.luminanceOf(c.lux);r.color.setRGB(c.lux[0]/l,c.lux[1]/l,c.lux[2]/l),r.intensity=l*n})}}static SKY_LIGHTING_MAGNITUDE=-8;get farEmitters(){return[...this.farBy.values()].flat()}get brightestInSky(){let t;for(const e of[...this.farBy.values()].flat())e.sky.magnitude<(t?.magnitude??cs.SKY_LIGHTING_MAGNITUDE)&&(t=e.sky);return t}get all(){return[...this.near??[],...this.far??[]]}buildFar(){const t=this.build(cs.FAR,()=>new j0(16777215,0)),e=this.shadow;if(e.mapSize>0){const i=t[0].shadow;t[0].castShadow=!0,i.mapSize.set(e.mapSize,e.mapSize);const n=i.camera;n.left=-e.halfExtentM,n.right=e.halfExtentM,n.top=e.halfExtentM,n.bottom=-e.halfExtentM,n.near=cs.FAR_DISTANCE-e.depthHalfRangeM,n.far=cs.FAR_DISTANCE+e.depthHalfRangeM,n.updateProjectionMatrix(),i.bias=-e.biasM/(2*e.depthHalfRangeM),i.normalBias=e.normalBiasM,i.autoUpdate=!1}return t}build(t,e){return Array.from({length:t},()=>{const i=e();return i.name="emitter-light",this.parent.add(i),i instanceof j0&&this.parent.add(i.target),i})}static luminanceOf(t){return .2126*t[0]+.7152*t[1]+.0722*t[2]||1}static ORIGIN=new R}class mr{static MAX_STRENGTH=32;static MID_GREY=.18;static shown(t,e){const i=Math.min(1,Math.max(0,t));return e<.001?i:Math.log(1+e*i)/Math.log(1+e)}static strengthFor(t){if(!(t>0)||t>=mr.MID_GREY)return 0;if(mr.shown(t,mr.MAX_STRENGTH)<=mr.MID_GREY)return mr.MAX_STRENGTH;let e=0,i=mr.MAX_STRENGTH;for(let n=0;n<40;n++){const s=(e+i)/2;mr.shown(t,s)<mr.MID_GREY?e=s:i=s}return(e+i)/2}}const PO=[{name:"Sirius",raHours:6.7525,decDeg:-16.7161,mag:-1.44},{name:"Canopus",raHours:6.3992,decDeg:-52.6957,mag:-.62},{name:"Arcturus",raHours:14.261,decDeg:19.1824,mag:-.05},{name:"Rigil Kentaurus",raHours:14.6608,decDeg:-60.834,mag:-.01},{name:"Vega",raHours:18.6156,decDeg:38.7837,mag:.03},{name:"Capella",raHours:5.2782,decDeg:45.998,mag:.08},{name:"Rigel",raHours:5.2423,decDeg:-8.2016,mag:.18},{name:"Procyon",raHours:7.655,decDeg:5.225,mag:.4},{name:"Achernar",raHours:1.6286,decDeg:-57.2368,mag:.45},{name:"Betelgeuse",raHours:5.9195,decDeg:7.4071,mag:.45},{name:"Hadar",raHours:14.0637,decDeg:-60.373,mag:.61},{name:"Altair",raHours:19.8464,decDeg:8.8683,mag:.76},{name:"Acrux",raHours:12.4433,decDeg:-63.0991,mag:.77},{name:"Aldebaran",raHours:4.5987,decDeg:16.5093,mag:.87},{name:"Spica",raHours:13.4199,decDeg:-11.1613,mag:.98},{name:"Antares",raHours:16.4901,decDeg:-26.432,mag:1.06},{name:"Pollux",raHours:7.7553,decDeg:28.0262,mag:1.16},{name:"Fomalhaut",raHours:22.9608,decDeg:-29.6222,mag:1.17},{name:"Mimosa",raHours:12.7954,decDeg:-59.6888,mag:1.25},{name:"Deneb",raHours:20.6905,decDeg:45.2803,mag:1.25},{name:"Toliman",raHours:14.6603,decDeg:-60.8383,mag:1.35},{name:"Regulus",raHours:10.1395,decDeg:11.9672,mag:1.36},{name:"Adhara",raHours:6.9771,decDeg:-28.9721,mag:1.5},{name:"Castor",raHours:7.5766,decDeg:31.8883,mag:1.58},{name:"Gacrux",raHours:12.5194,decDeg:-57.1132,mag:1.59},{name:"Shaula",raHours:17.5601,decDeg:-37.1038,mag:1.62},{name:"Bellatrix",raHours:5.4189,decDeg:6.3497,mag:1.64},{name:"Elnath",raHours:5.4382,decDeg:28.6075,mag:1.65},{name:"Miaplacidus",raHours:9.22,decDeg:-69.7172,mag:1.67},{name:"Alnilam",raHours:5.6036,decDeg:-1.2019,mag:1.69},{name:"Alnair",raHours:22.1372,decDeg:-46.961,mag:1.73},{name:"Alnitak",raHours:5.6793,decDeg:-1.9426,mag:1.74},{name:"γ² Velorum",raHours:8.1589,decDeg:-47.3366,mag:1.75},{name:"Alioth",raHours:12.9005,decDeg:55.9598,mag:1.76},{name:"Mirfak",raHours:3.4054,decDeg:49.8612,mag:1.79},{name:"Kaus Australis",raHours:18.4029,decDeg:-34.3846,mag:1.79},{name:"Dubhe",raHours:11.0622,decDeg:61.751,mag:1.81},{name:"Wezen",raHours:7.1399,decDeg:-26.3932,mag:1.83},{name:"Alkaid",raHours:13.7924,decDeg:49.3133,mag:1.85},{name:"Avior",raHours:8.3752,decDeg:-59.5095,mag:1.86},{name:"Sargas",raHours:17.622,decDeg:-42.9978,mag:1.86},{name:"Menkalinan",raHours:5.9921,decDeg:44.9474,mag:1.9},{name:"Atria",raHours:16.8111,decDeg:-69.0277,mag:1.91},{name:"Alhena",raHours:6.6285,decDeg:16.3993,mag:1.93},{name:"Alsephina",raHours:8.7451,decDeg:-54.7088,mag:1.93},{name:"Peacock",raHours:20.4275,decDeg:-56.7351,mag:1.94},{name:"Polaris",raHours:2.5297,decDeg:89.2641,mag:1.97},{name:"Mirzam",raHours:6.3783,decDeg:-17.9559,mag:1.98},{name:"Alphard",raHours:9.4598,decDeg:-8.6586,mag:1.99},{name:"Hamal",raHours:2.1196,decDeg:23.4624,mag:2.01},{name:"Algieba",raHours:10.3329,decDeg:19.8415,mag:2.01},{name:"Diphda",raHours:.7265,decDeg:-17.9866,mag:2.04},{name:"Nunki",raHours:18.9211,decDeg:-26.2967,mag:2.05},{name:"Menkent",raHours:14.1114,decDeg:-36.37,mag:2.06},{name:"Alpheratz",raHours:.1398,decDeg:29.0904,mag:2.07},{name:"Mirach",raHours:1.1622,decDeg:35.6206,mag:2.07},{name:"Saiph",raHours:5.7959,decDeg:-9.6696,mag:2.07},{name:"Kochab",raHours:14.8451,decDeg:74.1555,mag:2.07},{name:"Tiaki",raHours:22.7111,decDeg:-46.8846,mag:2.07},{name:"Rasalhague",raHours:17.5822,decDeg:12.56,mag:2.08},{name:"Algol",raHours:3.1361,decDeg:40.9556,mag:2.09},{name:"Almach",raHours:2.065,decDeg:42.3297,mag:2.1},{name:"Denebola",raHours:11.8177,decDeg:14.5721,mag:2.14},{name:"Cih",raHours:.9451,decDeg:60.7167,mag:2.15},{name:"γ Centauri",raHours:12.692,decDeg:-48.9599,mag:2.2},{name:"Naos",raHours:8.0597,decDeg:-40.0031,mag:2.21},{name:"Aspidiske",raHours:9.2848,decDeg:-59.2752,mag:2.21},{name:"Alphecca",raHours:15.5781,decDeg:26.7147,mag:2.22},{name:"Suhail",raHours:9.1333,decDeg:-43.4326,mag:2.23},{name:"Mizar",raHours:13.3987,decDeg:54.9254,mag:2.23},{name:"Sadr",raHours:20.3705,decDeg:40.2567,mag:2.23},{name:"Schedar",raHours:.6751,decDeg:56.5373,mag:2.24},{name:"Eltanin",raHours:17.9434,decDeg:51.4889,mag:2.24},{name:"Mintaka",raHours:5.5334,decDeg:-.2991,mag:2.25},{name:"Caph",raHours:.1529,decDeg:59.1498,mag:2.28},{name:"ε Centauri",raHours:13.6648,decDeg:-53.4664,mag:2.29},{name:"Dschubba",raHours:16.0056,decDeg:-22.6217,mag:2.29},{name:"Larawag",raHours:16.8361,decDeg:-34.2932,mag:2.29},{name:"α Lupi",raHours:14.6988,decDeg:-47.3882,mag:2.3},{name:"η Centauri",raHours:14.5918,decDeg:-42.1578,mag:2.33},{name:"Merak",raHours:11.0307,decDeg:56.3824,mag:2.34},{name:"Izar",raHours:14.7498,decDeg:27.0742,mag:2.35},{name:"Enif",raHours:21.7364,decDeg:9.875,mag:2.38},{name:"κ Scorpii",raHours:17.7081,decDeg:-39.03,mag:2.39},{name:"Ankaa",raHours:.4381,decDeg:-42.306,mag:2.4},{name:"Phecda",raHours:11.8972,decDeg:53.6948,mag:2.41},{name:"Sabik",raHours:17.173,decDeg:-15.7249,mag:2.43},{name:"Scheat",raHours:23.0629,decDeg:28.0828,mag:2.44},{name:"Aludra",raHours:7.4016,decDeg:-29.3031,mag:2.45},{name:"Alderamin",raHours:21.3096,decDeg:62.5856,mag:2.45},{name:"Markeb",raHours:9.3686,decDeg:-55.0107,mag:2.47},{name:"Aljanah",raHours:20.7702,decDeg:33.9703,mag:2.48},{name:"Markab",raHours:23.0793,decDeg:15.2053,mag:2.49},{name:"Menkar",raHours:3.038,decDeg:4.0897,mag:2.54},{name:"ζ Ophiuchi",raHours:16.6193,decDeg:-10.5671,mag:2.54},{name:"ζ Centauri",raHours:13.9257,decDeg:-47.2884,mag:2.55},{name:"Zosma",raHours:11.2351,decDeg:20.5237,mag:2.56},{name:"Acrab",raHours:16.0906,decDeg:-19.8055,mag:2.56},{name:"Arneb",raHours:5.5455,decDeg:-17.8223,mag:2.58},{name:"δ Centauri",raHours:12.1393,decDeg:-50.7224,mag:2.58},{name:"Gienah",raHours:12.2634,decDeg:-17.5419,mag:2.58},{name:"Ascella",raHours:19.0435,decDeg:-29.8801,mag:2.6},{name:"Zubeneschamali",raHours:15.2834,decDeg:-9.3829,mag:2.61},{name:"Unukalhai",raHours:15.7378,decDeg:6.4256,mag:2.63},{name:"Sheratan",raHours:1.9107,decDeg:20.808,mag:2.64},{name:"Phact",raHours:5.6608,decDeg:-34.0741,mag:2.65},{name:"Mahasim",raHours:5.9954,decDeg:37.2126,mag:2.65},{name:"Kraz",raHours:12.5731,decDeg:-23.3968,mag:2.65},{name:"Ruchbah",raHours:1.4302,decDeg:60.2353,mag:2.66},{name:"Muphrid",raHours:13.9114,decDeg:18.3977,mag:2.68},{name:"β Lupi",raHours:14.9755,decDeg:-43.134,mag:2.68},{name:"Hassaleh",raHours:4.9499,decDeg:33.1661,mag:2.69},{name:"μ Velorum",raHours:10.7795,decDeg:-49.4203,mag:2.69},{name:"α Muscae",raHours:12.6197,decDeg:-69.1356,mag:2.69},{name:"Lesath",raHours:17.5127,decDeg:-37.2958,mag:2.7},{name:"π Puppis",raHours:7.2857,decDeg:-37.0975,mag:2.71},{name:"Kaus Media",raHours:18.3499,decDeg:-29.8281,mag:2.72},{name:"Tarazed",raHours:19.771,decDeg:10.6133,mag:2.72},{name:"Yed Prior",raHours:16.2391,decDeg:-3.6943,mag:2.73},{name:"Athebyne",raHours:16.3999,decDeg:61.5142,mag:2.73},{name:"θ Carinae",raHours:10.7159,decDeg:-64.3945,mag:2.74},{name:"Porrima",raHours:12.6943,decDeg:-1.4494,mag:2.74},{name:"Hatysa",raHours:5.5906,decDeg:-5.9099,mag:2.75},{name:"ι Centauri",raHours:13.3433,decDeg:-36.7123,mag:2.75},{name:"Zubenelgenubi",raHours:14.848,decDeg:-16.0418,mag:2.75},{name:"Cebalrai",raHours:17.7245,decDeg:4.5673,mag:2.76},{name:"Cursa",raHours:5.1308,decDeg:-5.0864,mag:2.78},{name:"Kornephoros",raHours:16.5037,decDeg:21.4896,mag:2.78},{name:"Rasalgethi",raHours:17.2441,decDeg:14.3903,mag:2.78},{name:"Imai",raHours:12.2524,decDeg:-58.7489,mag:2.79},{name:"Rastaban",raHours:17.5072,decDeg:52.3014,mag:2.79},{name:"γ Lupi",raHours:15.5857,decDeg:-41.1668,mag:2.8},{name:"Nihal",raHours:5.4708,decDeg:-20.7594,mag:2.81},{name:"ζ Herculis",raHours:16.6881,decDeg:31.6027,mag:2.81},{name:"β Hydri",raHours:.4279,decDeg:-77.2542,mag:2.82},{name:"Paikauhale",raHours:16.598,decDeg:-28.216,mag:2.82},{name:"Kaus Borealis",raHours:18.4662,decDeg:-25.4217,mag:2.82},{name:"Algenib",raHours:.2206,decDeg:15.1836,mag:2.83},{name:"Tureis",raHours:8.1257,decDeg:-24.3043,mag:2.83},{name:"β Trianguli Australis",raHours:15.9191,decDeg:-63.4307,mag:2.83},{name:"ζ Persei",raHours:3.9022,decDeg:31.8836,mag:2.84},{name:"β Arae",raHours:17.4217,decDeg:-55.5299,mag:2.84},{name:"α Arae",raHours:17.5307,decDeg:-49.8761,mag:2.84},{name:"Alcyone",raHours:3.7914,decDeg:24.1051,mag:2.85},{name:"Vindemiatrix",raHours:13.0363,decDeg:10.9591,mag:2.85},{name:"Deneb Algedi",raHours:21.784,decDeg:-16.1273,mag:2.85},{name:"Castor B",raHours:7.5768,decDeg:31.8905,mag:2.85},{name:"α Hydri",raHours:1.9795,decDeg:-61.5699,mag:2.86},{name:"Fawaris",raHours:19.7496,decDeg:45.1308,mag:2.86},{name:"Tejat",raHours:6.3827,decDeg:22.5136,mag:2.87},{name:"γ Trianguli Australis",raHours:15.3152,decDeg:-68.6795,mag:2.87},{name:"α Tucanae",raHours:22.3084,decDeg:-60.2596,mag:2.87},{name:"Acamar",raHours:2.971,decDeg:-40.3047,mag:2.88},{name:"Albaldah",raHours:19.1627,decDeg:-21.0236,mag:2.88},{name:"Gomeisa",raHours:7.4525,decDeg:8.2893,mag:2.89},{name:"Cor Caroli",raHours:12.9338,decDeg:38.3184,mag:2.89},{name:"Fang",raHours:15.9809,decDeg:-26.1141,mag:2.89},{name:"ε Persei",raHours:3.9642,decDeg:40.0102,mag:2.9},{name:"Alniyat",raHours:16.3531,decDeg:-25.5928,mag:2.9},{name:"Sadalsuud",raHours:21.526,decDeg:-5.5712,mag:2.9},{name:"γ Persei",raHours:3.0799,decDeg:53.5064,mag:2.91},{name:"υ Carinae",raHours:9.785,decDeg:-65.072,mag:2.92},{name:"Matar",raHours:22.7167,decDeg:30.2212,mag:2.93},{name:"τ Puppis",raHours:6.8323,decDeg:-50.6146,mag:2.94},{name:"Algorab",raHours:12.4977,decDeg:-16.5154,mag:2.94},{name:"Sadalmelik",raHours:22.0964,decDeg:-.3199,mag:2.95},{name:"Zaurak",raHours:3.9672,decDeg:-13.5085,mag:2.97},{name:"Tianguan",raHours:5.6274,decDeg:21.1425,mag:2.97},{name:"Ras Elased Australis",raHours:9.7642,decDeg:23.7743,mag:2.97},{name:"Alnasl",raHours:18.0968,decDeg:-30.4241,mag:2.98},{name:"γ Hydrae",raHours:13.3154,decDeg:-23.1715,mag:2.99},{name:"ι¹ Scorpii",raHours:17.7931,decDeg:-40.127,mag:2.99},{name:"Okab",raHours:19.0902,decDeg:13.8635,mag:2.99},{name:"β Trianguli",raHours:2.1591,decDeg:34.9873,mag:3},{name:"ψ Ursae Majoris",raHours:11.1611,decDeg:44.4985,mag:3},{name:"Pherkad",raHours:15.3455,decDeg:71.834,mag:3},{name:"Xamidimura",raHours:16.8645,decDeg:-38.0474,mag:3},{name:"Aldhanab",raHours:21.8988,decDeg:-37.3649,mag:3}];class Ge{static GROUND_RADIUS_M=900;static EARTH_RADIUS_M=6371e3;static MAX_GROUND_VISIBILITY_M=3e4;static REBUILD_DISTANCE_M=150;static ROADS_MAX_RADIUS_M=5e3;static STILL_OBSERVER_M=60;static PATCH_WHOLE_SHARE=700/900;static MAX_DECOR_TERRAIN_M=3e3;static groundRadiusFor(t){const e=Math.sqrt(2*Ge.EARTH_RADIUS_M*Math.max(t,0));return Math.max(Ge.GROUND_RADIUS_M,Math.min(e,Ge.MAX_GROUND_VISIBILITY_M))}static AIRBORNE_FROM_M=300;static SHARP_GROUND_HEIGHTS=4;static SHARP_GROUND_MIN_M=6e3;static SHARP_GROUND_MAX_M=12e3;static patchRadiusFor(t,e){if(e<Ge.AIRBORNE_FROM_M)return t;const i=Math.min(Ge.SHARP_GROUND_MAX_M,Math.max(Ge.SHARP_GROUND_MIN_M,e*Ge.SHARP_GROUND_HEIGHTS));return Math.min(t,i)}static LOOK_PATCH_SHARE=.4;static LOOK_WITHIN_SHARE=.6;static LOOK_DOWN_FROM_DEG=3;static lookPatchFor(t,e,i){if(t<Ge.AIRBORNE_FROM_M||e>-3)return;const n=t/Math.tan(-e*Math.PI/180);if(!(n<=i*Ge.LOOK_WITHIN_SHARE||n>Ge.MAX_GROUND_VISIBILITY_M))return{distanceM:n,radiusM:Math.max(Ge.SHARP_GROUND_MIN_M,n*Ge.LOOK_PATCH_SHARE)}}static rebuildDistanceFor(t){return Ge.REBUILD_DISTANCE_M*(t/Ge.GROUND_RADIUS_M)}static decorReachFor(t,e){if(e&&e.length>=2){const s=e[0];for(const r of e){const a=ae(r.lat,r.lng,s.lat,s.lng);if(Math.hypot(a.x,a.z)>Ge.STILL_OBSERVER_M)return 0}}let i=0;for(const s of t){if(s.kind==="aircraft"||s.kind==="observer"||s.track)continue;const r=Math.max(s.sizeM?.widthM??0,s.sizeM?.lengthM??0)/2;i=Math.max(i,Math.hypot(s.eastM,s.northM)+r)}const n=Math.ceil(i/Ge.PATCH_WHOLE_SHARE/100)*100;return n>Ge.GROUND_RADIUS_M*Ge.PATCH_WHOLE_SHARE?Math.min(n,Ge.MAX_DECOR_TERRAIN_M):0}static FAR_RING_RADIUS_M=Ge.MAX_GROUND_VISIBILITY_M;static OVERLOOK_M=20;static needsFarRing(t,e,i){return t>=Ge.FAR_RING_RADIUS_M?!1:e>=Ge.OVERLOOK_M||i>t}static beamReachFor(t,e){let i=0;for(const n of t)for(const s of[...n.path,...(n.moves??[]).flatMap(r=>r.path)]){const r=ae(s.lat,s.lng,e.lat,e.lng);i=Math.max(i,Math.hypot(r.x,r.z))}return i}}class bh{static GREEN_FROM=.22;static GREEN_FULL=.5;static CONTRAST=.5;static install(t,e=!1){const i=new tt;t.userData.grassOrigin=i,t.onBeforeCompile=n=>{n.uniforms.uGrassContrast={value:bh.CONTRAST},n.uniforms.uGrassOrigin={value:i},n.vertexShader=n.vertexShader.replace("#include <common>",`#include <common>
6898
+ ${he.alphatest_fragment}`)}}class le{static WIDTH=160;static HEIGHT=90;static BLEACHING_CD_M2_S=22e7;static REGENERATION_S=110;static SPREAD_DEG=.5;static JUMP_MS=2e3;static POSITIVE_FADE_S=1.5;static POSITIVE_GAIN=20;static FLIGHT=[{ageS:0,rgb:[1,1,1]},{ageS:.6,rgb:[.35,1.05,.95]},{ageS:1.4,rgb:[.55,.6,3.6]},{ageS:2.4,rgb:[1.7,.6,1.5]},{ageS:3.5,rgb:[1.9,.75,.25]}];texture;left=new Float32Array(le.WIDTH*le.HEIGHT).fill(1);glow=new Float32Array(le.WIDTH*le.HEIGHT);age=new Float32Array(le.WIDTH*le.HEIGHT);bytes=le.freshBytes();lastMs;bleached=!1;constructor(){this.texture=new ms(this.bytes,le.WIDTH,le.HEIGHT,$i,We),this.texture.minFilter=ge,this.texture.magFilter=ge,this.texture.needsUpdate=!0}get any(){return this.bleached}advance(t,e,i){const n=this.lastMs===void 0?1/0:t-this.lastMs;if(this.lastMs=t,n===0)return!1;const s=le.SPREAD_DEG*Math.PI/180,r=e.map(u=>({x:u.ndcX*i.width/2,y:u.ndcY*i.height/2,peak:u.lux/(2*Math.PI*s*s)})).filter(u=>u.peak>=le.FAINTEST_CD_M2);if(n<0||n>le.JUMP_MS)return this.previous=r,this.reset();if(!this.bleached&&e.length===0)return this.previous=void 0,!1;const a=this.previous?.length===r.length?this.previous:void 0,c=a?Math.max(0,...r.map((u,d)=>Math.hypot(u.x-a[d].x,u.y-a[d].y))):0,l=Math.min(le.MAX_STEPS,Math.max(1,Math.ceil(c/(le.SPREAD_DEG/3)))),h=n/1e3/l;for(let u=1;u<=l;u++){const d=u/l;this.bleach(a?r.map((f,p)=>({...f,x:a[p].x+(f.x-a[p].x)*d,y:a[p].y+(f.y-a[p].y)*d})):r,h,i)}return this.previous=r,this.texture.needsUpdate=!0,!0}static FAINTEST_CD_M2=le.BLEACHING_CD_M2_S/le.REGENERATION_S*1e-4;static MAX_STEPS=64;previous;bleach(t,e,i){const n=le.WIDTH,s=le.HEIGHT,r=le.SPREAD_DEG,a=1/le.REGENERATION_S,c=this.light.fill(0);for(const h of t){const u=Math.max(0,Math.floor(((h.x-5*r)/i.width+.5)*n)),d=Math.min(n-1,Math.ceil(((h.x+5*r)/i.width+.5)*n)),f=Math.max(0,Math.floor(((h.y-5*r)/i.height+.5)*s)),p=Math.min(s-1,Math.ceil(((h.y+5*r)/i.height+.5)*s));for(let m=f;m<=p;m++){const g=((m+.5)/s*2-1)*i.height/2;for(let M=u;M<=d;M++){const x=(((M+.5)/n*2-1)*i.width/2-h.x)**2+(g-h.y)**2;x<25*r*r&&(c[m*n+M]+=h.peak*Math.exp(-x/(2*r*r)))}}}let l=!1;for(let h=0;h<s;h++)for(let u=0;u<n;u++){const d=h*n+u,f=c[d],p=this.left[d],m=this.glow[d];if(f===0&&p>=.9995&&m<le.GLOW_SEEN)continue;const g=a+f/le.BLEACHING_CD_M2_S,M=a/g,v=M+(p-M)*Math.exp(-g*e);this.left[d]=v;const x=Math.max(0,p-v)*le.POSITIVE_GAIN,y=m*Math.exp(-e/le.POSITIVE_FADE_S),w=y+x;this.age[d]=w>0?y*(this.age[d]+e)/w:0,this.glow[d]=w;const b=le.flightAt(this.age[d]),E=d*4;this.bytes[E]=Nn.toHalfFloat(v);for(let S=0;S<3;S++)this.bytes[E+1+S]=Nn.toHalfFloat(w*b[S]);(v<.995||w>=le.GLOW_SEEN)&&(l=!0)}this.bleached=l}light=new Float32Array(le.WIDTH*le.HEIGHT);static GLOW_SEEN=.002;static flightAt(t){const e=le.FLIGHT;for(let i=1;i<e.length;i++){if(t>e[i].ageS)continue;const n=(t-e[i-1].ageS)/(e[i].ageS-e[i-1].ageS),s=e[i-1].rgb,r=e[i].rgb;return[s[0]+(r[0]-s[0])*n,s[1]+(r[1]-s[1])*n,s[2]+(r[2]-s[2])*n]}return e[e.length-1].rgb}static freshBytes(){const t=new Uint16Array(le.WIDTH*le.HEIGHT*4),e=Nn.toHalfFloat(1);for(let i=0;i<t.length;i+=4)t[i]=e;return t}leftAt(t,e){const i=Math.min(le.WIDTH-1,Math.max(0,Math.floor((t+1)/2*le.WIDTH))),n=Math.min(le.HEIGHT-1,Math.max(0,Math.floor((e+1)/2*le.HEIGHT)));return this.left[n*le.WIDTH+i]}get atMs(){return this.lastMs}replay(t,e,i,n,s){const r=new Map,a=d=>{let f=r.get(d);return f||r.set(d,f=i(d)),f};s!==this.snapshotsOf&&(this.snapshots.clear(),this.snapshotsOf=s);let c=t;for(const d of this.snapshots.keys())d<=e&&d>c&&(c=d);c>t?this.restore(c):this.reset(),this.previous=void 0,this.lastMs=c;let l=c,h=0;const u=d=>{const f=d%le.REPLAY_STRIDE_MS===0&&a(d).length>0?le.REPLAY_STRIDE_MS:le.SNAPSHOT_MS;d%f!==0||this.snapshots.has(d)||(h>0&&this.rest(h),h=0,this.snapshots.set(d,{left:this.left.slice(),glow:this.glow.slice(),age:this.age.slice(),bleached:this.bleached}))};for(;l<e;){u(l);const d=Math.min(e,(Math.floor(l/le.REPLAY_STRIDE_MS)+1)*le.REPLAY_STRIDE_MS);if(a(d).length===0&&a(l).length===0){h+=d-l,l=d;continue}h>0&&this.rest(h),h=0;const f=Math.min(e,(Math.floor(l/le.REPLAY_STEP_MS)+1)*le.REPLAY_STEP_MS);this.lastMs=l,this.advance(f,a(f),n),l=f}h>0&&this.rest(h),this.lastMs=e}static SNAPSHOT_MS=5e3;snapshots=new Map;snapshotsOf;restore(t){const e=this.snapshots.get(t);this.left.set(e.left),this.glow.set(e.glow),this.age.set(e.age),this.bleached=e.bleached;for(let i=0;i<this.left.length;i++){const n=i*4,s=le.flightAt(this.age[i]);this.bytes[n]=Nn.toHalfFloat(this.left[i]);for(let r=0;r<3;r++)this.bytes[n+1+r]=Nn.toHalfFloat(this.glow[i]*s[r])}this.texture.needsUpdate=!0}static REPLAY_STEP_MS=100;static REPLAY_STRIDE_MS=1e3;rest(t){this.previous=void 0,this.bleached&&(this.bleach([],t/1e3,{width:1,height:1}),this.texture.needsUpdate=!0)}reset(){return this.bleached?(this.left.fill(1),this.glow.fill(0),this.age.fill(0),this.bytes.set(le.freshBytes()),this.bleached=!1,this.texture.needsUpdate=!0,!0):!1}dispose(){this.texture.dispose()}}class cs{constructor(t,e,i=cs.NO_SHADOW){this.parent=t,this.sceneUnitsPerLux=e,this.shadow=i}static NEAR=4;static FAR=2;static FAR_DISTANCE=1e3;static SYSTEMS={BodySystem:"emitters: the bodies that glow whole, the named lights of a model (a craft's lights), and their flames",MeteorSystem:"emitters: the heads of meteors, far, from their magnitude",ReentrySystem:"emitters: the heads of re-entries, far, from their magnitude",PhenomenonSystem:"none yet: a phenomenon states no luminance, only a colour as seen and a 0..1 dazzle, which say nothing of the light it gives",BeamSystem:"none: a laser beam is a thread of scattered light, too faint to light the ground; where it ends lit is in the sky",PlumeSystem:"none: a launch plume is lit by the Sun, it gives out no light of its own",CloudSystem:"none: clouds are lit, they do not give out light",LayeredCloudSystem:"none: clouds are lit, they do not give out light",DecorSystem:"own lights: the streetlamps, with shadows for the nearest (SceneRenderer.addStreetlightLight); NOT YET its lesser lamps (traffic lights, a car's rear lights), drawn lit but lighting nothing",RoadSystem:"own lights: the lamps it places along a street are the decor's streetlamps (see DecorSystem)",RailwaySystem:"none: rails mirror the lamps, they give out no light",ContrailSystem:"none: a contrail is lit by the Sun, it gives out no light",WaterSystem:"none: water mirrors, it gives out no light",TraceSystem:"none: a trace on the ground is lit, it gives out no light",ReferenceSystem:"none: a photograph laid over the scene, not in it",MirrorSystem:"none: a mirror shows the scene's light, it gives out none",HeadlightSystem:"own lights: a vehicle's headlamps are spot lights, aimed",FlameEffect:"emitters: through BodySystem, which states each flame",LensFlareEffect:"none: a dazzle in the eye, nothing in the world",IceHaloEffect:"none: sunlight bent by ice, seen, not cast on the ground",RainbowEffect:"none: sunlight bent by drops, seen, not cast on the ground",SkyGlowEffect:"none: the Milky Way and the zodiacal light are in the sky's own light (ScatteredSky)",RainSystem:"none: rain gives out no light",SatelliteField:"none: a satellite is a speck of reflected sunlight, far too faint to light anything"};near;far;nearBy=new Map;farBy=new Map;static NO_SHADOW={halfExtentM:0,depthHalfRangeM:0,biasM:0,normalBiasM:0,mapSize:0};set(t,e,i=[]){this.nearBy.set(t,e.filter(n=>n.candela>0)),this.farBy.set(t,i.filter(n=>Math.max(...n.lux)>0))}cast(t){const e=[...this.nearBy.values()].flat(),i=[...this.farBy.values()].flat(),n=this.sceneUnitsPerLux();if(e.length>0||this.near){this.near??=this.build(cs.NEAR,()=>new dE(16777215,0,0,2));const s=a=>t?a.candela/Math.max(a.position.distanceToSquared(t),1e-6):a.candela,r=e.sort((a,c)=>s(c)-s(a));this.near.forEach((a,c)=>{const l=r[c];if(!l){a.intensity=0;return}a.position.copy(l.position);const h=cs.luminanceOf(l.colour);a.color.setRGB(l.colour[0]/h,l.colour[1]/h,l.colour[2]/h),a.intensity=l.candela*n})}if(i.length>0||this.far){this.far??=this.buildFar();const s=i.sort((r,a)=>cs.luminanceOf(a.lux)-cs.luminanceOf(r.lux));this.far.forEach((r,a)=>{const c=s[a];if(r.castShadow&&(r.shadow.autoUpdate=c!==void 0),!c){r.intensity=0;return}r.position.copy(c.direction).multiplyScalar(cs.FAR_DISTANCE).add(t??cs.ORIGIN),r.target.position.copy(t??cs.ORIGIN),r.target.updateMatrixWorld();const l=cs.luminanceOf(c.lux);r.color.setRGB(c.lux[0]/l,c.lux[1]/l,c.lux[2]/l),r.intensity=l*n})}}static SKY_LIGHTING_MAGNITUDE=-8;get farEmitters(){return[...this.farBy.values()].flat()}get brightestInSky(){let t;for(const e of[...this.farBy.values()].flat())e.sky.magnitude<(t?.magnitude??cs.SKY_LIGHTING_MAGNITUDE)&&(t=e.sky);return t}get all(){return[...this.near??[],...this.far??[]]}buildFar(){const t=this.build(cs.FAR,()=>new j0(16777215,0)),e=this.shadow;if(e.mapSize>0){const i=t[0].shadow;t[0].castShadow=!0,i.mapSize.set(e.mapSize,e.mapSize);const n=i.camera;n.left=-e.halfExtentM,n.right=e.halfExtentM,n.top=e.halfExtentM,n.bottom=-e.halfExtentM,n.near=cs.FAR_DISTANCE-e.depthHalfRangeM,n.far=cs.FAR_DISTANCE+e.depthHalfRangeM,n.updateProjectionMatrix(),i.bias=-e.biasM/(2*e.depthHalfRangeM),i.normalBias=e.normalBiasM,i.autoUpdate=!1}return t}build(t,e){return Array.from({length:t},()=>{const i=e();return i.name="emitter-light",this.parent.add(i),i instanceof j0&&this.parent.add(i.target),i})}static luminanceOf(t){return .2126*t[0]+.7152*t[1]+.0722*t[2]||1}static ORIGIN=new R}class mr{static MAX_STRENGTH=32;static MID_GREY=.18;static shown(t,e){const i=Math.min(1,Math.max(0,t));return e<.001?i:Math.log(1+e*i)/Math.log(1+e)}static strengthFor(t){if(!(t>0)||t>=mr.MID_GREY)return 0;if(mr.shown(t,mr.MAX_STRENGTH)<=mr.MID_GREY)return mr.MAX_STRENGTH;let e=0,i=mr.MAX_STRENGTH;for(let n=0;n<40;n++){const s=(e+i)/2;mr.shown(t,s)<mr.MID_GREY?e=s:i=s}return(e+i)/2}}const PO=[{name:"Sirius",raHours:6.7525,decDeg:-16.7161,mag:-1.44},{name:"Canopus",raHours:6.3992,decDeg:-52.6957,mag:-.62},{name:"Arcturus",raHours:14.261,decDeg:19.1824,mag:-.05},{name:"Rigil Kentaurus",raHours:14.6608,decDeg:-60.834,mag:-.01},{name:"Vega",raHours:18.6156,decDeg:38.7837,mag:.03},{name:"Capella",raHours:5.2782,decDeg:45.998,mag:.08},{name:"Rigel",raHours:5.2423,decDeg:-8.2016,mag:.18},{name:"Procyon",raHours:7.655,decDeg:5.225,mag:.4},{name:"Achernar",raHours:1.6286,decDeg:-57.2368,mag:.45},{name:"Betelgeuse",raHours:5.9195,decDeg:7.4071,mag:.45},{name:"Hadar",raHours:14.0637,decDeg:-60.373,mag:.61},{name:"Altair",raHours:19.8464,decDeg:8.8683,mag:.76},{name:"Acrux",raHours:12.4433,decDeg:-63.0991,mag:.77},{name:"Aldebaran",raHours:4.5987,decDeg:16.5093,mag:.87},{name:"Spica",raHours:13.4199,decDeg:-11.1613,mag:.98},{name:"Antares",raHours:16.4901,decDeg:-26.432,mag:1.06},{name:"Pollux",raHours:7.7553,decDeg:28.0262,mag:1.16},{name:"Fomalhaut",raHours:22.9608,decDeg:-29.6222,mag:1.17},{name:"Mimosa",raHours:12.7954,decDeg:-59.6888,mag:1.25},{name:"Deneb",raHours:20.6905,decDeg:45.2803,mag:1.25},{name:"Toliman",raHours:14.6603,decDeg:-60.8383,mag:1.35},{name:"Regulus",raHours:10.1395,decDeg:11.9672,mag:1.36},{name:"Adhara",raHours:6.9771,decDeg:-28.9721,mag:1.5},{name:"Castor",raHours:7.5766,decDeg:31.8883,mag:1.58},{name:"Gacrux",raHours:12.5194,decDeg:-57.1132,mag:1.59},{name:"Shaula",raHours:17.5601,decDeg:-37.1038,mag:1.62},{name:"Bellatrix",raHours:5.4189,decDeg:6.3497,mag:1.64},{name:"Elnath",raHours:5.4382,decDeg:28.6075,mag:1.65},{name:"Miaplacidus",raHours:9.22,decDeg:-69.7172,mag:1.67},{name:"Alnilam",raHours:5.6036,decDeg:-1.2019,mag:1.69},{name:"Alnair",raHours:22.1372,decDeg:-46.961,mag:1.73},{name:"Alnitak",raHours:5.6793,decDeg:-1.9426,mag:1.74},{name:"γ² Velorum",raHours:8.1589,decDeg:-47.3366,mag:1.75},{name:"Alioth",raHours:12.9005,decDeg:55.9598,mag:1.76},{name:"Mirfak",raHours:3.4054,decDeg:49.8612,mag:1.79},{name:"Kaus Australis",raHours:18.4029,decDeg:-34.3846,mag:1.79},{name:"Dubhe",raHours:11.0622,decDeg:61.751,mag:1.81},{name:"Wezen",raHours:7.1399,decDeg:-26.3932,mag:1.83},{name:"Alkaid",raHours:13.7924,decDeg:49.3133,mag:1.85},{name:"Avior",raHours:8.3752,decDeg:-59.5095,mag:1.86},{name:"Sargas",raHours:17.622,decDeg:-42.9978,mag:1.86},{name:"Menkalinan",raHours:5.9921,decDeg:44.9474,mag:1.9},{name:"Atria",raHours:16.8111,decDeg:-69.0277,mag:1.91},{name:"Alhena",raHours:6.6285,decDeg:16.3993,mag:1.93},{name:"Alsephina",raHours:8.7451,decDeg:-54.7088,mag:1.93},{name:"Peacock",raHours:20.4275,decDeg:-56.7351,mag:1.94},{name:"Polaris",raHours:2.5297,decDeg:89.2641,mag:1.97},{name:"Mirzam",raHours:6.3783,decDeg:-17.9559,mag:1.98},{name:"Alphard",raHours:9.4598,decDeg:-8.6586,mag:1.99},{name:"Hamal",raHours:2.1196,decDeg:23.4624,mag:2.01},{name:"Algieba",raHours:10.3329,decDeg:19.8415,mag:2.01},{name:"Diphda",raHours:.7265,decDeg:-17.9866,mag:2.04},{name:"Nunki",raHours:18.9211,decDeg:-26.2967,mag:2.05},{name:"Menkent",raHours:14.1114,decDeg:-36.37,mag:2.06},{name:"Alpheratz",raHours:.1398,decDeg:29.0904,mag:2.07},{name:"Mirach",raHours:1.1622,decDeg:35.6206,mag:2.07},{name:"Saiph",raHours:5.7959,decDeg:-9.6696,mag:2.07},{name:"Kochab",raHours:14.8451,decDeg:74.1555,mag:2.07},{name:"Tiaki",raHours:22.7111,decDeg:-46.8846,mag:2.07},{name:"Rasalhague",raHours:17.5822,decDeg:12.56,mag:2.08},{name:"Algol",raHours:3.1361,decDeg:40.9556,mag:2.09},{name:"Almach",raHours:2.065,decDeg:42.3297,mag:2.1},{name:"Denebola",raHours:11.8177,decDeg:14.5721,mag:2.14},{name:"Cih",raHours:.9451,decDeg:60.7167,mag:2.15},{name:"γ Centauri",raHours:12.692,decDeg:-48.9599,mag:2.2},{name:"Naos",raHours:8.0597,decDeg:-40.0031,mag:2.21},{name:"Aspidiske",raHours:9.2848,decDeg:-59.2752,mag:2.21},{name:"Alphecca",raHours:15.5781,decDeg:26.7147,mag:2.22},{name:"Suhail",raHours:9.1333,decDeg:-43.4326,mag:2.23},{name:"Mizar",raHours:13.3987,decDeg:54.9254,mag:2.23},{name:"Sadr",raHours:20.3705,decDeg:40.2567,mag:2.23},{name:"Schedar",raHours:.6751,decDeg:56.5373,mag:2.24},{name:"Eltanin",raHours:17.9434,decDeg:51.4889,mag:2.24},{name:"Mintaka",raHours:5.5334,decDeg:-.2991,mag:2.25},{name:"Caph",raHours:.1529,decDeg:59.1498,mag:2.28},{name:"ε Centauri",raHours:13.6648,decDeg:-53.4664,mag:2.29},{name:"Dschubba",raHours:16.0056,decDeg:-22.6217,mag:2.29},{name:"Larawag",raHours:16.8361,decDeg:-34.2932,mag:2.29},{name:"α Lupi",raHours:14.6988,decDeg:-47.3882,mag:2.3},{name:"η Centauri",raHours:14.5918,decDeg:-42.1578,mag:2.33},{name:"Merak",raHours:11.0307,decDeg:56.3824,mag:2.34},{name:"Izar",raHours:14.7498,decDeg:27.0742,mag:2.35},{name:"Enif",raHours:21.7364,decDeg:9.875,mag:2.38},{name:"κ Scorpii",raHours:17.7081,decDeg:-39.03,mag:2.39},{name:"Ankaa",raHours:.4381,decDeg:-42.306,mag:2.4},{name:"Phecda",raHours:11.8972,decDeg:53.6948,mag:2.41},{name:"Sabik",raHours:17.173,decDeg:-15.7249,mag:2.43},{name:"Scheat",raHours:23.0629,decDeg:28.0828,mag:2.44},{name:"Aludra",raHours:7.4016,decDeg:-29.3031,mag:2.45},{name:"Alderamin",raHours:21.3096,decDeg:62.5856,mag:2.45},{name:"Markeb",raHours:9.3686,decDeg:-55.0107,mag:2.47},{name:"Aljanah",raHours:20.7702,decDeg:33.9703,mag:2.48},{name:"Markab",raHours:23.0793,decDeg:15.2053,mag:2.49},{name:"Menkar",raHours:3.038,decDeg:4.0897,mag:2.54},{name:"ζ Ophiuchi",raHours:16.6193,decDeg:-10.5671,mag:2.54},{name:"ζ Centauri",raHours:13.9257,decDeg:-47.2884,mag:2.55},{name:"Zosma",raHours:11.2351,decDeg:20.5237,mag:2.56},{name:"Acrab",raHours:16.0906,decDeg:-19.8055,mag:2.56},{name:"Arneb",raHours:5.5455,decDeg:-17.8223,mag:2.58},{name:"δ Centauri",raHours:12.1393,decDeg:-50.7224,mag:2.58},{name:"Gienah",raHours:12.2634,decDeg:-17.5419,mag:2.58},{name:"Ascella",raHours:19.0435,decDeg:-29.8801,mag:2.6},{name:"Zubeneschamali",raHours:15.2834,decDeg:-9.3829,mag:2.61},{name:"Unukalhai",raHours:15.7378,decDeg:6.4256,mag:2.63},{name:"Sheratan",raHours:1.9107,decDeg:20.808,mag:2.64},{name:"Phact",raHours:5.6608,decDeg:-34.0741,mag:2.65},{name:"Mahasim",raHours:5.9954,decDeg:37.2126,mag:2.65},{name:"Kraz",raHours:12.5731,decDeg:-23.3968,mag:2.65},{name:"Ruchbah",raHours:1.4302,decDeg:60.2353,mag:2.66},{name:"Muphrid",raHours:13.9114,decDeg:18.3977,mag:2.68},{name:"β Lupi",raHours:14.9755,decDeg:-43.134,mag:2.68},{name:"Hassaleh",raHours:4.9499,decDeg:33.1661,mag:2.69},{name:"μ Velorum",raHours:10.7795,decDeg:-49.4203,mag:2.69},{name:"α Muscae",raHours:12.6197,decDeg:-69.1356,mag:2.69},{name:"Lesath",raHours:17.5127,decDeg:-37.2958,mag:2.7},{name:"π Puppis",raHours:7.2857,decDeg:-37.0975,mag:2.71},{name:"Kaus Media",raHours:18.3499,decDeg:-29.8281,mag:2.72},{name:"Tarazed",raHours:19.771,decDeg:10.6133,mag:2.72},{name:"Yed Prior",raHours:16.2391,decDeg:-3.6943,mag:2.73},{name:"Athebyne",raHours:16.3999,decDeg:61.5142,mag:2.73},{name:"θ Carinae",raHours:10.7159,decDeg:-64.3945,mag:2.74},{name:"Porrima",raHours:12.6943,decDeg:-1.4494,mag:2.74},{name:"Hatysa",raHours:5.5906,decDeg:-5.9099,mag:2.75},{name:"ι Centauri",raHours:13.3433,decDeg:-36.7123,mag:2.75},{name:"Zubenelgenubi",raHours:14.848,decDeg:-16.0418,mag:2.75},{name:"Cebalrai",raHours:17.7245,decDeg:4.5673,mag:2.76},{name:"Cursa",raHours:5.1308,decDeg:-5.0864,mag:2.78},{name:"Kornephoros",raHours:16.5037,decDeg:21.4896,mag:2.78},{name:"Rasalgethi",raHours:17.2441,decDeg:14.3903,mag:2.78},{name:"Imai",raHours:12.2524,decDeg:-58.7489,mag:2.79},{name:"Rastaban",raHours:17.5072,decDeg:52.3014,mag:2.79},{name:"γ Lupi",raHours:15.5857,decDeg:-41.1668,mag:2.8},{name:"Nihal",raHours:5.4708,decDeg:-20.7594,mag:2.81},{name:"ζ Herculis",raHours:16.6881,decDeg:31.6027,mag:2.81},{name:"β Hydri",raHours:.4279,decDeg:-77.2542,mag:2.82},{name:"Paikauhale",raHours:16.598,decDeg:-28.216,mag:2.82},{name:"Kaus Borealis",raHours:18.4662,decDeg:-25.4217,mag:2.82},{name:"Algenib",raHours:.2206,decDeg:15.1836,mag:2.83},{name:"Tureis",raHours:8.1257,decDeg:-24.3043,mag:2.83},{name:"β Trianguli Australis",raHours:15.9191,decDeg:-63.4307,mag:2.83},{name:"ζ Persei",raHours:3.9022,decDeg:31.8836,mag:2.84},{name:"β Arae",raHours:17.4217,decDeg:-55.5299,mag:2.84},{name:"α Arae",raHours:17.5307,decDeg:-49.8761,mag:2.84},{name:"Alcyone",raHours:3.7914,decDeg:24.1051,mag:2.85},{name:"Vindemiatrix",raHours:13.0363,decDeg:10.9591,mag:2.85},{name:"Deneb Algedi",raHours:21.784,decDeg:-16.1273,mag:2.85},{name:"Castor B",raHours:7.5768,decDeg:31.8905,mag:2.85},{name:"α Hydri",raHours:1.9795,decDeg:-61.5699,mag:2.86},{name:"Fawaris",raHours:19.7496,decDeg:45.1308,mag:2.86},{name:"Tejat",raHours:6.3827,decDeg:22.5136,mag:2.87},{name:"γ Trianguli Australis",raHours:15.3152,decDeg:-68.6795,mag:2.87},{name:"α Tucanae",raHours:22.3084,decDeg:-60.2596,mag:2.87},{name:"Acamar",raHours:2.971,decDeg:-40.3047,mag:2.88},{name:"Albaldah",raHours:19.1627,decDeg:-21.0236,mag:2.88},{name:"Gomeisa",raHours:7.4525,decDeg:8.2893,mag:2.89},{name:"Cor Caroli",raHours:12.9338,decDeg:38.3184,mag:2.89},{name:"Fang",raHours:15.9809,decDeg:-26.1141,mag:2.89},{name:"ε Persei",raHours:3.9642,decDeg:40.0102,mag:2.9},{name:"Alniyat",raHours:16.3531,decDeg:-25.5928,mag:2.9},{name:"Sadalsuud",raHours:21.526,decDeg:-5.5712,mag:2.9},{name:"γ Persei",raHours:3.0799,decDeg:53.5064,mag:2.91},{name:"υ Carinae",raHours:9.785,decDeg:-65.072,mag:2.92},{name:"Matar",raHours:22.7167,decDeg:30.2212,mag:2.93},{name:"τ Puppis",raHours:6.8323,decDeg:-50.6146,mag:2.94},{name:"Algorab",raHours:12.4977,decDeg:-16.5154,mag:2.94},{name:"Sadalmelik",raHours:22.0964,decDeg:-.3199,mag:2.95},{name:"Zaurak",raHours:3.9672,decDeg:-13.5085,mag:2.97},{name:"Tianguan",raHours:5.6274,decDeg:21.1425,mag:2.97},{name:"Ras Elased Australis",raHours:9.7642,decDeg:23.7743,mag:2.97},{name:"Alnasl",raHours:18.0968,decDeg:-30.4241,mag:2.98},{name:"γ Hydrae",raHours:13.3154,decDeg:-23.1715,mag:2.99},{name:"ι¹ Scorpii",raHours:17.7931,decDeg:-40.127,mag:2.99},{name:"Okab",raHours:19.0902,decDeg:13.8635,mag:2.99},{name:"β Trianguli",raHours:2.1591,decDeg:34.9873,mag:3},{name:"ψ Ursae Majoris",raHours:11.1611,decDeg:44.4985,mag:3},{name:"Pherkad",raHours:15.3455,decDeg:71.834,mag:3},{name:"Xamidimura",raHours:16.8645,decDeg:-38.0474,mag:3},{name:"Aldhanab",raHours:21.8988,decDeg:-37.3649,mag:3}];class ze{static GROUND_RADIUS_M=900;static EARTH_RADIUS_M=6371e3;static MAX_GROUND_VISIBILITY_M=3e4;static REBUILD_DISTANCE_M=150;static ROADS_MAX_RADIUS_M=5e3;static STILL_OBSERVER_M=60;static PATCH_WHOLE_SHARE=700/900;static MAX_DECOR_TERRAIN_M=3e3;static groundRadiusFor(t){const e=Math.sqrt(2*ze.EARTH_RADIUS_M*Math.max(t,0));return Math.max(ze.GROUND_RADIUS_M,Math.min(e,ze.MAX_GROUND_VISIBILITY_M))}static AIRBORNE_FROM_M=300;static SHARP_GROUND_HEIGHTS=4;static SHARP_GROUND_MIN_M=6e3;static SHARP_GROUND_MAX_M=12e3;static patchRadiusFor(t,e){if(e<ze.AIRBORNE_FROM_M)return t;const i=Math.min(ze.SHARP_GROUND_MAX_M,Math.max(ze.SHARP_GROUND_MIN_M,e*ze.SHARP_GROUND_HEIGHTS));return Math.min(t,i)}static LOOK_PATCH_SHARE=.4;static LOOK_WITHIN_SHARE=.6;static LOOK_DOWN_FROM_DEG=3;static lookPatchFor(t,e,i){if(t<ze.AIRBORNE_FROM_M||e>-3)return;const n=t/Math.tan(-e*Math.PI/180);if(!(n<=i*ze.LOOK_WITHIN_SHARE||n>ze.MAX_GROUND_VISIBILITY_M))return{distanceM:n,radiusM:Math.max(ze.SHARP_GROUND_MIN_M,n*ze.LOOK_PATCH_SHARE)}}static rebuildDistanceFor(t){return ze.REBUILD_DISTANCE_M*(t/ze.GROUND_RADIUS_M)}static decorReachFor(t,e){if(e&&e.length>=2){const s=e[0];for(const r of e){const a=ae(r.lat,r.lng,s.lat,s.lng);if(Math.hypot(a.x,a.z)>ze.STILL_OBSERVER_M)return 0}}let i=0;for(const s of t){if(s.kind==="aircraft"||s.kind==="observer"||s.track)continue;const r=Math.max(s.sizeM?.widthM??0,s.sizeM?.lengthM??0)/2;i=Math.max(i,Math.hypot(s.eastM,s.northM)+r)}const n=Math.ceil(i/ze.PATCH_WHOLE_SHARE/100)*100;return n>ze.GROUND_RADIUS_M*ze.PATCH_WHOLE_SHARE?Math.min(n,ze.MAX_DECOR_TERRAIN_M):0}static FAR_RING_RADIUS_M=ze.MAX_GROUND_VISIBILITY_M;static OVERLOOK_M=20;static needsFarRing(t,e,i){return t>=ze.FAR_RING_RADIUS_M?!1:e>=ze.OVERLOOK_M||i>t}static beamReachFor(t,e){let i=0;for(const n of t)for(const s of[...n.path,...(n.moves??[]).flatMap(r=>r.path)]){const r=ae(s.lat,s.lng,e.lat,e.lng);i=Math.max(i,Math.hypot(r.x,r.z))}return i}}class bh{static GREEN_FROM=.22;static GREEN_FULL=.5;static CONTRAST=.5;static install(t,e=!1){const i=new tt;t.userData.grassOrigin=i,t.onBeforeCompile=n=>{n.uniforms.uGrassContrast={value:bh.CONTRAST},n.uniforms.uGrassOrigin={value:i},n.vertexShader=n.vertexShader.replace("#include <common>",`#include <common>
6899
6899
  varying vec2 vGrassPatchXZ;
6900
6900
  uniform vec2 uGrassOrigin;`).replace("#include <begin_vertex>",`#include <begin_vertex>
6901
6901
  vGrassPatchXZ = position.xz + uGrassOrigin;`),n.fragmentShader=n.fragmentShader.replace("#include <common>",`#include <common>
@@ -6925,7 +6925,7 @@ float grassNoise(vec2 p) {
6925
6925
  + (grassNoise(vGrassPatchXZ * 21.0) - 0.5) * 0.6 * (1.0 - smoothstep(2.5, 12.0, eye));
6926
6926
  float d = grain * uGrassContrast * grass;
6927
6927
  diffuseColor.rgb *= vec3(1.0 + d * 1.1, 1.0 + d, 1.0 + d * 1.25);
6928
- }`)},t.customProgramCacheKey=()=>e?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class kr{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(t,e,i){const n=i&&i.length>=2?kr.alongRoute(t,i):void 0;let s=0;for(const r of e){const a=kr.fill(t,r).filter(h=>!n?.[h]);if(a.length===0)continue;const c=a.map(h=>t.heights[h]).filter(Number.isFinite).sort((h,u)=>h-u);if(c.length===0)continue;const l=c[Math.floor((c.length-1)*kr.LEVEL_QUANTILE)];for(const h of a)t.heights[h]>l&&(t.heights[h]=l,s++)}return s}static fill(t,e){const{width:i,height:n,bounds:s}=t,r=d=>(d-s.west)/(s.east-s.west)*(i-1),a=d=>(s.north-d)/(s.north-s.south)*(n-1),c=[];for(const d of e.rings)for(let f=0;f<d.length;f++){const p=d[f],m=d[(f+1)%d.length],g={r0:a(p.lat),c0:r(p.lng),r1:a(m.lat),c1:r(m.lng)};g.r0!==g.r1&&c.push(g)}const l=[];if(c.length===0)return l;const h=Math.max(0,Math.ceil(Math.min(...c.map(d=>Math.min(d.r0,d.r1))))),u=Math.min(n-1,Math.floor(Math.max(...c.map(d=>Math.max(d.r0,d.r1)))));for(let d=h;d<=u;d++){const f=[];for(const{r0:p,c0:m,r1:g,c1:M}of c)p<=d!=g<=d&&f.push(m+(M-m)*(d-p)/(g-p));f.sort((p,m)=>p-m);for(let p=0;p+1<f.length;p+=2){const m=Math.max(0,Math.ceil(f[p])),g=Math.min(i-1,Math.floor(f[p+1]));for(let M=m;M<=g;M++)l.push(d*i+M)}}return l}static alongRoute(t,e){const{width:i,height:n,bounds:s}=t,r=(s.east-s.west)*kr.METRES_PER_DEGREE*Math.cos((s.north+s.south)/2*Math.PI/180)/(i-1),a=(s.north-s.south)*kr.METRES_PER_DEGREE/(n-1),c=Math.ceil(kr.ROUTE_CLEARANCE_M/r),l=Math.ceil(kr.ROUTE_CLEARANCE_M/a),h=new Uint8Array(i*n),u=f=>(f-s.west)/(s.east-s.west)*(i-1),d=f=>(s.north-f)/(s.north-s.south)*(n-1);for(let f=0;f+1<e.length;f++){const[p,m,g,M]=[u(e[f].lng),d(e[f].lat),u(e[f+1].lng),d(e[f+1].lat)];if(Math.max(p,g)<-c||Math.min(p,g)>i-1+c||Math.max(m,M)<-l||Math.min(m,M)>n-1+l)continue;const v=Math.max(1,Math.ceil(Math.hypot(g-p,M-m)*2));for(let x=0;x<=v;x++){const y=Math.round(p+(g-p)*x/v),w=Math.round(m+(M-m)*x/v);for(let b=-l;b<=l;b++)for(let E=-c;E<=c;E++){const S=w+b,A=y+E;S<0||A<0||S>=n||A>=i||Math.hypot(E*r,b*a)<=kr.ROUTE_CLEARANCE_M&&(h[S*i+A]=1)}}}return h}}const OO=64,fw=OO+1,pw=2048,NO=900,LO=700/900,kO=0,UO=.01,FO=1500;function Bu(o,t,e){return{north:Is(0,-e,o,t).lat,south:Is(0,e,o,t).lat,east:Is(e,0,o,t).lng,west:Is(-e,0,o,t).lng}}async function ng(o,t,e,i=NO,n,s){const r=i,a=i*LO,c=Bu(o,t,r),l={width:fw,height:fw},h=s?void 0:e.water?.getWater(c).catch(P=>(console.warn("Water unavailable, drawing none:",P),[])),[u,d]=await Promise.all([e.elevation.getElevationGrid(c,l,n),e.imagery.getImageryTexture(c,{width:pw,height:pw})]);let f;const p=h?await Promise.race([h,new Promise(P=>{f=setTimeout(()=>P(void 0),FO)})]):void 0;if(clearTimeout(f),u.width!==u.height||u.width<3||u.heights.length!==u.width*u.height)throw new Error("The ground came as a grid that is not square");cp.fill(u.heights,u.width),p&&p.length>0&&kr.flatten(u,p,n?.route);const m=u.width,g=m-1,M=Math.floor(m/2),v=u.heights[M*m+M],x=s?.referenceElevationM??v,y=new Float32Array(m*m*3),w=new Float32Array(m*m*2),b=new Float32Array(m*m*4);for(let P=0;P<m;P++){const L=P/(m-1),O=c.north+(c.south-c.north)*L;for(let k=0;k<m;k++){const H=k/(m-1),W=c.west+(c.east-c.west)*H,{x:Q,z:q}=ae(O,W,o,t),nt=u.heights[P*m+k],at=Math.max(Math.abs(Q),Math.abs(q)),zt=s&&at<s.innerM?0:1-zO((at-a)/(r-a),0,1),Zt=kO+UO+(nt-x),Pt=P*m+k;y[Pt*3]=Q,y[Pt*3+1]=Zt,y[Pt*3+2]=q;const Z=gb(d.bounds,W,O);w[Pt*2]=Z.x,w[Pt*2+1]=Z.y,b[Pt*4]=1,b[Pt*4+1]=1,b[Pt*4+2]=1,b[Pt*4+3]=zt}}const E=m*m>65535?new Uint32Array(g*g*6):new Uint16Array(g*g*6);let S=0;for(let P=0;P<g;P++)for(let L=0;L<g;L++){const O=P*m+L,k=O+1,H=O+m,W=H+1;E[S++]=O,E[S++]=H,E[S++]=k,E[S++]=k,E[S++]=H,E[S++]=W}const A=new ye;A.setAttribute("position",new Me(y,3)),A.setAttribute("uv",new Me(w,2)),A.setAttribute("color",new Me(b,4)),A.setIndex(new Me(E,1)),A.computeVertexNormals();const _=new Jo(d.source);_.flipY=!1,_.colorSpace=Pn,_.anisotropy=8;const I=new or({map:_,color:new rt(1,1,1),vertexColors:!0,transparent:!0,fog:!0});s||bh.install(I);const D=new vt(A,I);return D.receiveShadow=!s,D.castShadow=!s,{mesh:D,attribution:e.imagery.attribution,originElevationM:Number.isFinite(v)?v:void 0,...p?{water:p}:h?{waterLater:h}:{}}}class cp{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(t,e){const i=s=>!Number.isFinite(s)||s<cp.LOWEST_GROUND_M;let n=0;for(let s=0;s<t.length;s++)i(t[s])&&n++;for(let s=0;n>0&&s<cp.MAX_PASSES;s++){const r=[];for(let a=0;a<e;a++)for(let c=0;c<e;c++){const l=a*e+c;if(!i(t[l]))continue;let h=0,u=0;for(const[d,f]of[[-1,0],[1,0],[0,-1],[0,1]]){const p=a+d,m=c+f;if(p<0||m<0||p>=e||m>=e)continue;const g=t[p*e+m];i(g)||(h+=g,u++)}u>0&&r.push([l,h/u])}for(const[a,c]of r)t[a]=c;if(n-=r.length,r.length===0)break}if(n>0)for(let s=0;s<t.length;s++)i(t[s])&&(t[s]=0)}}function zO(o,t,e){return Math.max(t,Math.min(e,o))}class ve{static STEP_M=8;stepM=ve.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new tt;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new Xe;surveyed=new Xe;stated=new Xe;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(t){this.stepM=Number.isFinite(t)&&t>0?Math.min(ve.STEP_M,Math.max(1.5,t/2)):ve.STEP_M}set(t,e,i,n,s,r=1/0,a){const c=ve.within(t,e,i,r);ve.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(e,i);const l=new Map,h=c.map(f=>f.points.map(p=>ae(p.lat,p.lng,e,i))),u=c.map((f,p)=>this.streetOf(f,h[p],a));for(const[f,p]of c.entries()){const m=l.get(p.surface)??ve.batchFor(p.surface);l.set(p.surface,m);const g=u[f];this.appendPath(h[f],p.widthM,n,m,g?{lateralAt:(M,v,x,y)=>g(M,v,x,y).carriageway}:{})}for(const[f,p]of l){const m=this.meshOf(f,p,s);m&&this.surveyed.add(m)}const d=this.sidewalks(c,h,u,n);if(d.indices.length>0){const f=this.meshOf("paved",d,!1,ve.SIDEWALK_ALBEDO,!1);f&&(f.name="roads sidewalks",this.surveyed.add(f))}this.paint(c,e,i,n,s)}paint(t,e,i,n,s){if(!t.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(ve.markingsModule??=$t(()=>import("./RoadMarkings-C3oJCHLk.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const c={positions:[],indices:[]};if(a.lay(t,e,i,(u,d,f)=>this.appendPath(u,d,n,c,{offsetM:f.offsetM,liftM:ve.LIFT_M+f.liftM,minHalfM:f.minHalfM}))>0&&c.indices.length>0){const u=this.meshOf("paved",c,s,ve.MARKINGS_ALBEDO,!1);u&&(u.name="roads markings",u.renderOrder=ve.MARKINGS_RENDER_ORDER,u.material.polygonOffsetFactor=-4,u.material.polygonOffsetUnits=-4,this.surveyed.add(u))}const h=a.barrierGeometry(a.barriers(t,e,i),n);if(h.indices.length>0){const u=this.meshOf("paved",h,s,ve.BARRIER_ALBEDO,!1);u&&(u.name="roads barriers",u.material.polygonOffset=!1,u.castShadow=!0,this.surveyed.add(u))}this.onMarkings?.()})}onMarkings;anchorGrain(t,e){if(this.grainReference){const n=ae(this.grainReference.lat,this.grainReference.lng,t,e);Math.hypot(n.x,n.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:t,lng:e};const i=ae(this.grainReference.lat,this.grainReference.lng,t,e);this.grainOrigin.set(-i.x,-i.z)}static within(t,e,i,n){if(!Number.isFinite(n))return t;const s=n*1.1+100;return t.filter(r=>{let a;for(const c of r.points){const l=ae(c.lat,c.lng,e,i);if(Math.hypot(l.x,l.z)<=s||a&&Math.hypot((l.x+a.x)/2,(l.z+a.z)/2)<=s)return!0;a=l}return!1})}streetOf(t,e,i){if(!t.urban||t.surface!=="paved")return;const n=ve.surveyedAcross(t);if(!i||!i.near(e))return()=>n;const s=new Map,r=(f,p,m,g)=>{const M=`${f.toFixed(2)}:${p.toFixed(2)}`;let v=s.get(M);return v||(v=i.across(f,p,m,g),s.set(M,v)),v},a=this.rungsOf(e),c=a.flatMap(f=>{const p=r(f.x,f.z,f.dirX,f.dirZ);return p.leftM!==void 0&&p.rightM!==void 0?[(p.leftM-p.rightM)/2]:[]}).sort((f,p)=>f-p),l=i.lampsAlong(e);if(c.length===0&&l.length===0)return()=>n;const h=c.length>0?c[Math.floor((c.length-1)/2)]:0,u=ve.clearOf(l,t.widthM/2,Math.max(-2.5,Math.min(ve.STREET_MIDDLE_MOST_M,h))),d={rungs:a,across:(f,p,m,g)=>ve.betweenWalls(t,u,r(f,p,m,g).leftM,r(f,p,m,g).rightM)};return this.laidStreets.push(d),(f,p,m,g)=>{const M=r(f,p,m,g);return ve.betweenWalls(t,u,M.leftM,M.rightM)}}static clearOf(t,e,i){const n=r=>t.every(a=>Math.abs(a-r)>=e+ve.LAMP_CLEARANCE_M);if(n(i))return i;const s=ve.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*s;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=s&&n(a))return a;return i}atKerb(t,e){let i;for(const d of this.laidStreets)for(const f of d.rungs){const p=Math.hypot(t-f.x,e-f.z);p<=ve.KERB_REACH_M&&(!i||p<i.distance)&&(i={rung:f,across:d.across(f.x,f.z,f.dirX,f.dirZ),distance:p})}if(!i)return{x:t,z:e};const{rung:n,across:s}=i,r=(t-n.x)*-n.dirZ+(e-n.z)*n.dirX,a=(t-n.x)*n.dirX+(e-n.z)*n.dirZ,l=(r>=s.carriageway.offsetM?s.left:s.right)??s.left??s.right;if(!l)return{x:t,z:e};const h=Math.sign(l.outerM-l.kerbM),u=l.kerbM+h*Math.min(ve.LAMP_FROM_KERB_M,Math.abs(l.outerM-l.kerbM)/2);return{x:n.x+n.dirX*a-n.dirZ*u,z:n.z+n.dirZ*a+n.dirX*u}}rungsOf(t){const e=this.resample(t);return e.map((i,n)=>{const s=e[Math.max(0,n-1)],r=e[Math.min(e.length-1,n+1)],a=r.x-s.x,c=r.z-s.z,l=Math.hypot(a,c);return l<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/l,dirZ:c/l}})}static surveyedAcross(t){const e=t.widthM/2,i={offsetM:0,halfM:e};return t.widthM<ve.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:e,outerM:e+ve.SIDEWALK_WIDTH_M},right:{kerbM:-e,outerM:-e-ve.SIDEWALK_WIDTH_M}}}static betweenWalls(t,e,i,n){const s=t.widthM/2,r={offsetM:e,halfM:s},a=e+s,c=e-s,l=i??a+ve.SIDEWALK_WIDTH_M,h=-(n??-c+ve.SIDEWALK_WIDTH_M);return{carriageway:r,...l-a>=ve.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:l}}:{},...c-h>=ve.SIDEWALK_NONE_M?{right:{kerbM:c,outerM:h}}:{}}}sidewalks(t,e,i,n){const s={positions:[],indices:[]},r=new Ur(t,e);return t.forEach((a,c)=>{const l=i[c];if(!l)return;const h=(u,d)=>r.onAnotherCarriageway(u,d,c);for(const u of["left","right"]){const d=(f,p,m,g)=>{const M=l(f,p,m,g)[u];return M&&{offsetM:(M.kerbM+M.outerM)/2,halfM:Math.abs(M.outerM-M.kerbM)/2}};this.appendPath(e[c],0,n,s,{lateralAt:d,liftM:ve.LIFT_M+ve.SIDEWALK_KERB_M,minHalfM:0,skip:h}),this.appendKerb(e[c],n,s,(f,p,m,g)=>l(f,p,m,g)[u]?.kerbM,u==="left",h)}}),s}setStated(t,e){ve.empty(this.stated);const i=new Map;for(const n of t){const s=i.get(n.surface)??ve.batchFor(n.surface);i.set(n.surface,s),this.appendPath(n.path.map(r=>({x:r.eastM,z:-r.northM})),n.widthM,e,s)}for(const[n,s]of i){const r=this.meshOf(n,s,!1);r&&this.stated.add(r)}}clear(){ve.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(t){for(const e of[...t.children]){t.remove(e);const i=e;i.geometry?.dispose(),i.material?.dispose()}}dispose(){ve.empty(this.surveyed),ve.empty(this.stated)}appendPath(t,e,i,n,s={}){const r=this.resample(t);if(r.length<2)return;const a=Math.max(s.minHalfM??.5,e/2),c=s.liftM??ve.LIFT_M,l=s.offsetM??0,h=n.positions.length/3,u=[],d=[],f=[];for(let m=0;m<r.length;m++){const g=r[Math.max(0,m-1)],M=r[Math.min(r.length-1,m+1)];let v=M.x-g.x,x=M.z-g.z;const y=Math.hypot(v,x);y<1e-6?(v=1,x=0):(v/=y,x/=y);const w=s.lateralAt?s.lateralAt(r[m].x,r[m].z,v,x):{offsetM:l,halfM:a},b=w?Math.max(s.minHalfM??.5,w.halfM):a,E=w?.offsetM??l,S=-x*b,A=v*b,_={x:r[m].x+-x*E,z:r[m].z+v*E};u.push(w!==void 0&&w.halfM>0&&!s.skip?.(_.x,_.z)),d.push([{x:_.x+S,z:_.z+A},_,{x:_.x-S,z:_.z-A}]),f.push(b)}const p=d.map(m=>m.map(g=>i(g.x,g.z)));for(let m=0;m<d.length-1;m++)for(let g=0;g<3;g++){const M=d[m][g],v=d[m+1][g],x=i((M.x+v.x)/2,(M.z+v.z)/2)-(p[m][g]+p[m+1][g])/2;x>0&&(p[m][g]+=x,p[m+1][g]+=x)}for(let m=0;m<d.length;m++){for(let g=0;g<3;g++)n.positions.push(d[m][g].x,p[m][g]+c,d[m][g].z);n.edges?.push(f[m],f[m],0,f[m],-f[m],f[m])}for(let m=0;m<r.length-1;m++){if(!u[m]||!u[m+1])continue;const g=h+m*3;n.indices.push(g,g+3,g+1,g+1,g+3,g+4),n.indices.push(g+1,g+4,g+2,g+2,g+4,g+5)}}appendKerb(t,e,i,n,s,r){const a=this.resample(t);if(a.length<2)return;const c=i.positions.length/3,l=[];for(let h=0;h<a.length;h++){const u=a[Math.max(0,h-1)],d=a[Math.min(a.length-1,h+1)];let f=d.x-u.x,p=d.z-u.z;const m=Math.hypot(f,p);m<1e-6?(f=1,p=0):(f/=m,p/=m);const g=n(a[h].x,a[h].z,f,p),M=a[h].x+-p*(g??0),v=a[h].z+f*(g??0);l.push(g!==void 0&&!r(M,v));const x=e(M,v)+ve.LIFT_M;i.positions.push(M,x,v,M,x+ve.SIDEWALK_KERB_M,v)}for(let h=0;h<a.length-1;h++){if(!l[h]||!l[h+1])continue;const u=c+h*2;s?i.indices.push(u,u+1,u+2,u+1,u+3,u+2):i.indices.push(u,u+2,u+1,u+1,u+2,u+3)}}static batchFor(t){return t==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(t,e,i,n,s=!0){if(e.indices.length===0)return;const r=new ye;r.setAttribute("position",new Me(new Float32Array(e.positions),3));const a=e.edges!==void 0&&e.edges.length*3===e.positions.length*2;a&&r.setAttribute("aEdge",new Me(new Float32Array(e.edges),2)),r.setIndex(new Me(new Uint32Array(e.indices),1)),r.computeVertexNormals();const c=n??ve.ALBEDO[t],l=new or({color:new rt(c[0],c[1],c[2]),transparent:i,opacity:i?ve.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});s&&this.addGrain(l,ve.GRAIN_CONTRAST[t],a);const h=new vt(r,l);return h.name=`roads ${t}`,h.renderOrder=ve.RENDER_ORDER,h.receiveShadow=!0,h.castShadow=!1,h}addGrain(t,e,i=!1){const n=this.grainOrigin;t.onBeforeCompile=s=>{s.uniforms.uRoadOrigin={value:n},s.uniforms.uRoadContrast={value:e},i&&(s.defines={...s.defines,ROAD_VERGE:""}),s.vertexShader=s.vertexShader.replace("#include <common>",`#include <common>
6928
+ }`)},t.customProgramCacheKey=()=>e?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class kr{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(t,e,i){const n=i&&i.length>=2?kr.alongRoute(t,i):void 0;let s=0;for(const r of e){const a=kr.fill(t,r).filter(h=>!n?.[h]);if(a.length===0)continue;const c=a.map(h=>t.heights[h]).filter(Number.isFinite).sort((h,u)=>h-u);if(c.length===0)continue;const l=c[Math.floor((c.length-1)*kr.LEVEL_QUANTILE)];for(const h of a)t.heights[h]>l&&(t.heights[h]=l,s++)}return s}static fill(t,e){const{width:i,height:n,bounds:s}=t,r=d=>(d-s.west)/(s.east-s.west)*(i-1),a=d=>(s.north-d)/(s.north-s.south)*(n-1),c=[];for(const d of e.rings)for(let f=0;f<d.length;f++){const p=d[f],m=d[(f+1)%d.length],g={r0:a(p.lat),c0:r(p.lng),r1:a(m.lat),c1:r(m.lng)};g.r0!==g.r1&&c.push(g)}const l=[];if(c.length===0)return l;const h=Math.max(0,Math.ceil(Math.min(...c.map(d=>Math.min(d.r0,d.r1))))),u=Math.min(n-1,Math.floor(Math.max(...c.map(d=>Math.max(d.r0,d.r1)))));for(let d=h;d<=u;d++){const f=[];for(const{r0:p,c0:m,r1:g,c1:M}of c)p<=d!=g<=d&&f.push(m+(M-m)*(d-p)/(g-p));f.sort((p,m)=>p-m);for(let p=0;p+1<f.length;p+=2){const m=Math.max(0,Math.ceil(f[p])),g=Math.min(i-1,Math.floor(f[p+1]));for(let M=m;M<=g;M++)l.push(d*i+M)}}return l}static alongRoute(t,e){const{width:i,height:n,bounds:s}=t,r=(s.east-s.west)*kr.METRES_PER_DEGREE*Math.cos((s.north+s.south)/2*Math.PI/180)/(i-1),a=(s.north-s.south)*kr.METRES_PER_DEGREE/(n-1),c=Math.ceil(kr.ROUTE_CLEARANCE_M/r),l=Math.ceil(kr.ROUTE_CLEARANCE_M/a),h=new Uint8Array(i*n),u=f=>(f-s.west)/(s.east-s.west)*(i-1),d=f=>(s.north-f)/(s.north-s.south)*(n-1);for(let f=0;f+1<e.length;f++){const[p,m,g,M]=[u(e[f].lng),d(e[f].lat),u(e[f+1].lng),d(e[f+1].lat)];if(Math.max(p,g)<-c||Math.min(p,g)>i-1+c||Math.max(m,M)<-l||Math.min(m,M)>n-1+l)continue;const v=Math.max(1,Math.ceil(Math.hypot(g-p,M-m)*2));for(let x=0;x<=v;x++){const y=Math.round(p+(g-p)*x/v),w=Math.round(m+(M-m)*x/v);for(let b=-l;b<=l;b++)for(let E=-c;E<=c;E++){const S=w+b,A=y+E;S<0||A<0||S>=n||A>=i||Math.hypot(E*r,b*a)<=kr.ROUTE_CLEARANCE_M&&(h[S*i+A]=1)}}}return h}}const OO=64,fw=OO+1,pw=2048,NO=900,LO=700/900,kO=0,UO=.01,FO=1500;function Bu(o,t,e){return{north:Is(0,-e,o,t).lat,south:Is(0,e,o,t).lat,east:Is(e,0,o,t).lng,west:Is(-e,0,o,t).lng}}async function ng(o,t,e,i=NO,n,s){const r=i,a=i*LO,c=Bu(o,t,r),l={width:fw,height:fw},h=s||i>ze.ROADS_MAX_RADIUS_M?void 0:e.water?.getWater(c).catch(P=>(console.warn("Water unavailable, drawing none:",P),[])),[u,d]=await Promise.all([e.elevation.getElevationGrid(c,l,n),e.imagery.getImageryTexture(c,{width:pw,height:pw})]);let f;const p=h?await Promise.race([h,new Promise(P=>{f=setTimeout(()=>P(void 0),FO)})]):void 0;if(clearTimeout(f),u.width!==u.height||u.width<3||u.heights.length!==u.width*u.height)throw new Error("The ground came as a grid that is not square");cp.fill(u.heights,u.width),p&&p.length>0&&kr.flatten(u,p,n?.route);const m=u.width,g=m-1,M=Math.floor(m/2),v=u.heights[M*m+M],x=s?.referenceElevationM??v,y=new Float32Array(m*m*3),w=new Float32Array(m*m*2),b=new Float32Array(m*m*4);for(let P=0;P<m;P++){const L=P/(m-1),O=c.north+(c.south-c.north)*L;for(let k=0;k<m;k++){const H=k/(m-1),W=c.west+(c.east-c.west)*H,{x:Q,z:q}=ae(O,W,o,t),nt=u.heights[P*m+k],at=Math.max(Math.abs(Q),Math.abs(q)),zt=s&&at<s.innerM?0:1-zO((at-a)/(r-a),0,1),Zt=kO+UO+(nt-x),Pt=P*m+k;y[Pt*3]=Q,y[Pt*3+1]=Zt,y[Pt*3+2]=q;const Z=gb(d.bounds,W,O);w[Pt*2]=Z.x,w[Pt*2+1]=Z.y,b[Pt*4]=1,b[Pt*4+1]=1,b[Pt*4+2]=1,b[Pt*4+3]=zt}}const E=m*m>65535?new Uint32Array(g*g*6):new Uint16Array(g*g*6);let S=0;for(let P=0;P<g;P++)for(let L=0;L<g;L++){const O=P*m+L,k=O+1,H=O+m,W=H+1;E[S++]=O,E[S++]=H,E[S++]=k,E[S++]=k,E[S++]=H,E[S++]=W}const A=new ye;A.setAttribute("position",new Me(y,3)),A.setAttribute("uv",new Me(w,2)),A.setAttribute("color",new Me(b,4)),A.setIndex(new Me(E,1)),A.computeVertexNormals();const _=new Jo(d.source);_.flipY=!1,_.colorSpace=Pn,_.anisotropy=8;const I=new or({map:_,color:new rt(1,1,1),vertexColors:!0,transparent:!0,fog:!0});s||bh.install(I);const D=new vt(A,I);return D.receiveShadow=!s,D.castShadow=!s,{mesh:D,attribution:e.imagery.attribution,originElevationM:Number.isFinite(v)?v:void 0,...p?{water:p}:h?{waterLater:h}:{}}}class cp{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(t,e){const i=s=>!Number.isFinite(s)||s<cp.LOWEST_GROUND_M;let n=0;for(let s=0;s<t.length;s++)i(t[s])&&n++;for(let s=0;n>0&&s<cp.MAX_PASSES;s++){const r=[];for(let a=0;a<e;a++)for(let c=0;c<e;c++){const l=a*e+c;if(!i(t[l]))continue;let h=0,u=0;for(const[d,f]of[[-1,0],[1,0],[0,-1],[0,1]]){const p=a+d,m=c+f;if(p<0||m<0||p>=e||m>=e)continue;const g=t[p*e+m];i(g)||(h+=g,u++)}u>0&&r.push([l,h/u])}for(const[a,c]of r)t[a]=c;if(n-=r.length,r.length===0)break}if(n>0)for(let s=0;s<t.length;s++)i(t[s])&&(t[s]=0)}}function zO(o,t,e){return Math.max(t,Math.min(e,o))}class ve{static STEP_M=8;stepM=ve.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new tt;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new Xe;surveyed=new Xe;stated=new Xe;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(t){this.stepM=Number.isFinite(t)&&t>0?Math.min(ve.STEP_M,Math.max(1.5,t/2)):ve.STEP_M}set(t,e,i,n,s,r=1/0,a){const c=ve.within(t,e,i,r);ve.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(e,i);const l=new Map,h=c.map(f=>f.points.map(p=>ae(p.lat,p.lng,e,i))),u=c.map((f,p)=>this.streetOf(f,h[p],a));for(const[f,p]of c.entries()){const m=l.get(p.surface)??ve.batchFor(p.surface);l.set(p.surface,m);const g=u[f];this.appendPath(h[f],p.widthM,n,m,g?{lateralAt:(M,v,x,y)=>g(M,v,x,y).carriageway}:{})}for(const[f,p]of l){const m=this.meshOf(f,p,s);m&&this.surveyed.add(m)}const d=this.sidewalks(c,h,u,n);if(d.indices.length>0){const f=this.meshOf("paved",d,!1,ve.SIDEWALK_ALBEDO,!1);f&&(f.name="roads sidewalks",this.surveyed.add(f))}this.paint(c,e,i,n,s)}paint(t,e,i,n,s){if(!t.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(ve.markingsModule??=$t(()=>import("./RoadMarkings-C3oJCHLk.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const c={positions:[],indices:[]};if(a.lay(t,e,i,(u,d,f)=>this.appendPath(u,d,n,c,{offsetM:f.offsetM,liftM:ve.LIFT_M+f.liftM,minHalfM:f.minHalfM}))>0&&c.indices.length>0){const u=this.meshOf("paved",c,s,ve.MARKINGS_ALBEDO,!1);u&&(u.name="roads markings",u.renderOrder=ve.MARKINGS_RENDER_ORDER,u.material.polygonOffsetFactor=-4,u.material.polygonOffsetUnits=-4,this.surveyed.add(u))}const h=a.barrierGeometry(a.barriers(t,e,i),n);if(h.indices.length>0){const u=this.meshOf("paved",h,s,ve.BARRIER_ALBEDO,!1);u&&(u.name="roads barriers",u.material.polygonOffset=!1,u.castShadow=!0,this.surveyed.add(u))}this.onMarkings?.()})}onMarkings;anchorGrain(t,e){if(this.grainReference){const n=ae(this.grainReference.lat,this.grainReference.lng,t,e);Math.hypot(n.x,n.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:t,lng:e};const i=ae(this.grainReference.lat,this.grainReference.lng,t,e);this.grainOrigin.set(-i.x,-i.z)}static within(t,e,i,n){if(!Number.isFinite(n))return t;const s=n*1.1+100;return t.filter(r=>{let a;for(const c of r.points){const l=ae(c.lat,c.lng,e,i);if(Math.hypot(l.x,l.z)<=s||a&&Math.hypot((l.x+a.x)/2,(l.z+a.z)/2)<=s)return!0;a=l}return!1})}streetOf(t,e,i){if(!t.urban||t.surface!=="paved")return;const n=ve.surveyedAcross(t);if(!i||!i.near(e))return()=>n;const s=new Map,r=(f,p,m,g)=>{const M=`${f.toFixed(2)}:${p.toFixed(2)}`;let v=s.get(M);return v||(v=i.across(f,p,m,g),s.set(M,v)),v},a=this.rungsOf(e),c=a.flatMap(f=>{const p=r(f.x,f.z,f.dirX,f.dirZ);return p.leftM!==void 0&&p.rightM!==void 0?[(p.leftM-p.rightM)/2]:[]}).sort((f,p)=>f-p),l=i.lampsAlong(e);if(c.length===0&&l.length===0)return()=>n;const h=c.length>0?c[Math.floor((c.length-1)/2)]:0,u=ve.clearOf(l,t.widthM/2,Math.max(-2.5,Math.min(ve.STREET_MIDDLE_MOST_M,h))),d={rungs:a,across:(f,p,m,g)=>ve.betweenWalls(t,u,r(f,p,m,g).leftM,r(f,p,m,g).rightM)};return this.laidStreets.push(d),(f,p,m,g)=>{const M=r(f,p,m,g);return ve.betweenWalls(t,u,M.leftM,M.rightM)}}static clearOf(t,e,i){const n=r=>t.every(a=>Math.abs(a-r)>=e+ve.LAMP_CLEARANCE_M);if(n(i))return i;const s=ve.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*s;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=s&&n(a))return a;return i}atKerb(t,e){let i;for(const d of this.laidStreets)for(const f of d.rungs){const p=Math.hypot(t-f.x,e-f.z);p<=ve.KERB_REACH_M&&(!i||p<i.distance)&&(i={rung:f,across:d.across(f.x,f.z,f.dirX,f.dirZ),distance:p})}if(!i)return{x:t,z:e};const{rung:n,across:s}=i,r=(t-n.x)*-n.dirZ+(e-n.z)*n.dirX,a=(t-n.x)*n.dirX+(e-n.z)*n.dirZ,l=(r>=s.carriageway.offsetM?s.left:s.right)??s.left??s.right;if(!l)return{x:t,z:e};const h=Math.sign(l.outerM-l.kerbM),u=l.kerbM+h*Math.min(ve.LAMP_FROM_KERB_M,Math.abs(l.outerM-l.kerbM)/2);return{x:n.x+n.dirX*a-n.dirZ*u,z:n.z+n.dirZ*a+n.dirX*u}}rungsOf(t){const e=this.resample(t);return e.map((i,n)=>{const s=e[Math.max(0,n-1)],r=e[Math.min(e.length-1,n+1)],a=r.x-s.x,c=r.z-s.z,l=Math.hypot(a,c);return l<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/l,dirZ:c/l}})}static surveyedAcross(t){const e=t.widthM/2,i={offsetM:0,halfM:e};return t.widthM<ve.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:e,outerM:e+ve.SIDEWALK_WIDTH_M},right:{kerbM:-e,outerM:-e-ve.SIDEWALK_WIDTH_M}}}static betweenWalls(t,e,i,n){const s=t.widthM/2,r={offsetM:e,halfM:s},a=e+s,c=e-s,l=i??a+ve.SIDEWALK_WIDTH_M,h=-(n??-c+ve.SIDEWALK_WIDTH_M);return{carriageway:r,...l-a>=ve.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:l}}:{},...c-h>=ve.SIDEWALK_NONE_M?{right:{kerbM:c,outerM:h}}:{}}}sidewalks(t,e,i,n){const s={positions:[],indices:[]},r=new Ur(t,e);return t.forEach((a,c)=>{const l=i[c];if(!l)return;const h=(u,d)=>r.onAnotherCarriageway(u,d,c);for(const u of["left","right"]){const d=(f,p,m,g)=>{const M=l(f,p,m,g)[u];return M&&{offsetM:(M.kerbM+M.outerM)/2,halfM:Math.abs(M.outerM-M.kerbM)/2}};this.appendPath(e[c],0,n,s,{lateralAt:d,liftM:ve.LIFT_M+ve.SIDEWALK_KERB_M,minHalfM:0,skip:h}),this.appendKerb(e[c],n,s,(f,p,m,g)=>l(f,p,m,g)[u]?.kerbM,u==="left",h)}}),s}setStated(t,e){ve.empty(this.stated);const i=new Map;for(const n of t){const s=i.get(n.surface)??ve.batchFor(n.surface);i.set(n.surface,s),this.appendPath(n.path.map(r=>({x:r.eastM,z:-r.northM})),n.widthM,e,s)}for(const[n,s]of i){const r=this.meshOf(n,s,!1);r&&this.stated.add(r)}}clear(){ve.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(t){for(const e of[...t.children]){t.remove(e);const i=e;i.geometry?.dispose(),i.material?.dispose()}}dispose(){ve.empty(this.surveyed),ve.empty(this.stated)}appendPath(t,e,i,n,s={}){const r=this.resample(t);if(r.length<2)return;const a=Math.max(s.minHalfM??.5,e/2),c=s.liftM??ve.LIFT_M,l=s.offsetM??0,h=n.positions.length/3,u=[],d=[],f=[];for(let m=0;m<r.length;m++){const g=r[Math.max(0,m-1)],M=r[Math.min(r.length-1,m+1)];let v=M.x-g.x,x=M.z-g.z;const y=Math.hypot(v,x);y<1e-6?(v=1,x=0):(v/=y,x/=y);const w=s.lateralAt?s.lateralAt(r[m].x,r[m].z,v,x):{offsetM:l,halfM:a},b=w?Math.max(s.minHalfM??.5,w.halfM):a,E=w?.offsetM??l,S=-x*b,A=v*b,_={x:r[m].x+-x*E,z:r[m].z+v*E};u.push(w!==void 0&&w.halfM>0&&!s.skip?.(_.x,_.z)),d.push([{x:_.x+S,z:_.z+A},_,{x:_.x-S,z:_.z-A}]),f.push(b)}const p=d.map(m=>m.map(g=>i(g.x,g.z)));for(let m=0;m<d.length-1;m++)for(let g=0;g<3;g++){const M=d[m][g],v=d[m+1][g],x=i((M.x+v.x)/2,(M.z+v.z)/2)-(p[m][g]+p[m+1][g])/2;x>0&&(p[m][g]+=x,p[m+1][g]+=x)}for(let m=0;m<d.length;m++){for(let g=0;g<3;g++)n.positions.push(d[m][g].x,p[m][g]+c,d[m][g].z);n.edges?.push(f[m],f[m],0,f[m],-f[m],f[m])}for(let m=0;m<r.length-1;m++){if(!u[m]||!u[m+1])continue;const g=h+m*3;n.indices.push(g,g+3,g+1,g+1,g+3,g+4),n.indices.push(g+1,g+4,g+2,g+2,g+4,g+5)}}appendKerb(t,e,i,n,s,r){const a=this.resample(t);if(a.length<2)return;const c=i.positions.length/3,l=[];for(let h=0;h<a.length;h++){const u=a[Math.max(0,h-1)],d=a[Math.min(a.length-1,h+1)];let f=d.x-u.x,p=d.z-u.z;const m=Math.hypot(f,p);m<1e-6?(f=1,p=0):(f/=m,p/=m);const g=n(a[h].x,a[h].z,f,p),M=a[h].x+-p*(g??0),v=a[h].z+f*(g??0);l.push(g!==void 0&&!r(M,v));const x=e(M,v)+ve.LIFT_M;i.positions.push(M,x,v,M,x+ve.SIDEWALK_KERB_M,v)}for(let h=0;h<a.length-1;h++){if(!l[h]||!l[h+1])continue;const u=c+h*2;s?i.indices.push(u,u+1,u+2,u+1,u+3,u+2):i.indices.push(u,u+2,u+1,u+1,u+2,u+3)}}static batchFor(t){return t==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(t,e,i,n,s=!0){if(e.indices.length===0)return;const r=new ye;r.setAttribute("position",new Me(new Float32Array(e.positions),3));const a=e.edges!==void 0&&e.edges.length*3===e.positions.length*2;a&&r.setAttribute("aEdge",new Me(new Float32Array(e.edges),2)),r.setIndex(new Me(new Uint32Array(e.indices),1)),r.computeVertexNormals();const c=n??ve.ALBEDO[t],l=new or({color:new rt(c[0],c[1],c[2]),transparent:i,opacity:i?ve.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});s&&this.addGrain(l,ve.GRAIN_CONTRAST[t],a);const h=new vt(r,l);return h.name=`roads ${t}`,h.renderOrder=ve.RENDER_ORDER,h.receiveShadow=!0,h.castShadow=!1,h}addGrain(t,e,i=!1){const n=this.grainOrigin;t.onBeforeCompile=s=>{s.uniforms.uRoadOrigin={value:n},s.uniforms.uRoadContrast={value:e},i&&(s.defines={...s.defines,ROAD_VERGE:""}),s.vertexShader=s.vertexShader.replace("#include <common>",`#include <common>
6929
6929
  varying vec2 vRoadXZ;
6930
6930
  uniform vec2 uRoadOrigin;
6931
6931
  #ifdef ROAD_VERGE
@@ -6972,7 +6972,7 @@ float roadNoise(vec2 p) {
6972
6972
  if (fromEdge < reach) discard;
6973
6973
  }
6974
6974
  #endif
6975
- }`)},t.customProgramCacheKey=()=>i?"rr0-road-grain-verge":"rr0-road-grain"}resample(t){const e=[];for(let n=0;n<t.length-1;n++){const s=t[n],r=t[n+1],a=Math.hypot(r.x-s.x,r.z-s.z),c=Math.max(1,Math.ceil(a/this.stepM));for(let l=0;l<c;l++){const h=l/c;e.push({x:s.x+(r.x-s.x)*h,z:s.z+(r.z-s.z)*h})}}const i=t[t.length-1];return i&&e.push({x:i.x,z:i.z}),e}}class Ur{static CELL_M=40;cells=new Map;constructor(t,e){e.forEach((i,n)=>{const s=t[n].widthM/2+.3;for(let r=1;r<i.length;r++){const a=i[r-1].x,c=i[r-1].z,l=i[r].x-a,h=i[r].z-c,u={way:n,ax:a,az:c,dx:l,dz:h,length2:l*l+h*h,reach:s},d=Math.floor((Math.min(a,i[r].x)-s)/Ur.CELL_M),f=Math.floor((Math.max(a,i[r].x)+s)/Ur.CELL_M),p=Math.floor((Math.min(c,i[r].z)-s)/Ur.CELL_M),m=Math.floor((Math.max(c,i[r].z)+s)/Ur.CELL_M);for(let g=d;g<=f;g++)for(let M=p;M<=m;M++){const v=Ur.key(g,M),x=this.cells.get(v);x?x.push(u):this.cells.set(v,[u])}}})}static key(t,e){return(t+5e4)*100003+(e+5e4)}onAnotherCarriageway(t,e,i){const n=this.cells.get(Ur.key(Math.floor(t/Ur.CELL_M),Math.floor(e/Ur.CELL_M)));if(!n)return!1;for(const s of n){if(s.way===i)continue;const r=s.length2===0?0:Math.max(0,Math.min(1,((t-s.ax)*s.dx+(e-s.az)*s.dz)/s.length2));if(Math.hypot(t-(s.ax+s.dx*r),e-(s.az+s.dz*r))<s.reach)return!0}return!1}}class Si{constructor(t,e=[]){this.lamps=e;for(const i of t){const n=Math.hypot(i.halfAlongM,i.halfAcrossM),s=Math.floor((i.x-n)/Si.CELL_M),r=Math.floor((i.x+n)/Si.CELL_M),a=Math.floor((i.z-n)/Si.CELL_M),c=Math.floor((i.z+n)/Si.CELL_M);for(let l=s;l<=r;l++)for(let h=a;h<=c;h++){const u=Si.key(l,h),d=this.cells.get(u);d?d.push(i):this.cells.set(u,[i])}}}static REACH_M=16;static NEAREST_M=1;static SAMPLES_M=[-3,0,3];static CELL_M=32;cells=new Map;across(t,e,i,n){const s=[],r=[];for(const a of Si.SAMPLES_M){const c=t+i*a,l=e+n*a,h=this.wall(c,l,-n,i),u=this.wall(c,l,n,-i);h!==void 0&&s.push(h),u!==void 0&&r.push(u)}return{leftM:Si.agreed(s),rightM:Si.agreed(r)}}lampsAlong(t){const e=[];for(const i of this.lamps){let n;for(let s=1;s<t.length;s++){const r=t[s-1].x,a=t[s-1].z,c=t[s].x-r,l=t[s].z-a,h=c*c+l*l;if(h===0)continue;const u=((i.x-r)*c+(i.z-a)*l)/h;if(u<0||u>1)continue;const d=Math.sqrt(h),f=((i.x-r)*-l+(i.z-a)*c)/d;(!n||Math.abs(f)<n.distance)&&(n={distance:Math.abs(f),lateral:f})}n&&n.distance<=Si.REACH_M&&e.push(n.lateral)}return e}near(t){if(t.length===0)return!1;if(this.lampsAlong(t).length>0)return!0;const e=Si.REACH_M+Math.max(...Si.SAMPLES_M.map(Math.abs)),i=t.map(s=>s.x),n=t.map(s=>s.z);for(let s=Math.floor((Math.min(...i)-e)/Si.CELL_M);s<=Math.floor((Math.max(...i)+e)/Si.CELL_M);s++)for(let r=Math.floor((Math.min(...n)-e)/Si.CELL_M);r<=Math.floor((Math.max(...n)+e)/Si.CELL_M);r++)if(this.cells.has(Si.key(s,r)))return!0;return!1}static agreed(t){if(!(t.length<2))return t.sort((e,i)=>e-i),t[Math.floor((t.length-1)/2)]}wall(t,e,i,n){let s;const r=new Set,a=Si.CELL_M/2;for(let c=0;c<=Si.REACH_M+a;c+=a){const l=this.cells.get(Si.key(Math.floor((t+i*c)/Si.CELL_M),Math.floor((e+n*c)/Si.CELL_M)));for(const h of l??[]){if(r.has(h))continue;r.add(h);const u=Si.hit(h,t,e,i,n);u!==void 0&&u<=Si.REACH_M&&(s===void 0||u<s)&&(s=u)}}return s!==void 0&&s>=Si.NEAREST_M?s:void 0}static hit(t,e,i,n,s){const r=e-t.x,a=i-t.z,c=[r*t.alongX+a*t.alongZ,-r*t.alongZ+a*t.alongX],l=[n*t.alongX+s*t.alongZ,-n*t.alongZ+s*t.alongX],h=[t.halfAlongM,t.halfAcrossM];let u=-1/0,d=1/0;for(let f=0;f<2;f++){if(Math.abs(l[f])<1e-9){if(Math.abs(c[f])>h[f])return;continue}const p=(-h[f]-c[f])/l[f],m=(h[f]-c[f])/l[f];u=Math.max(u,Math.min(p,m)),d=Math.min(d,Math.max(p,m))}if(!(d<u||d<0||u<0))return u}static key(t,e){return(t+5e4)*100003+(e+5e4)}}class nA extends Error{constructor(t,e,i,n){super(`Module "${t}" gives "${i}" at ${e}, which module "${n}" already gives`),this.moduleId=t,this.point=e,this.sourceId=i,this.ownerId=n,this.name="ModuleConflictError"}}class BO{constructor(t){this.id=t}sources=[];owners=new Map;ownerOf(t){return this.owners.get(t)}conflict(t,e){for(const i of e){const n=this.owners.get(i.id);if(n!==void 0&&n!==t)return{sourceId:i.id,ownerId:n}}}provide(t,e){const i=this.conflict(t,e);if(i)throw new nA(t,this.id,i.sourceId,i.ownerId);this.withdraw(t);const n=t===Re.BUILT_IN?this.sources.findIndex(s=>this.owners.get(s.id)!==Re.BUILT_IN):-1;n<0?this.sources.push(...e):this.sources.splice(n,0,...e);for(const s of e)this.owners.set(s.id,t);return this.sources}withdraw(t){for(let e=this.sources.length-1;e>=0;e--){const i=this.sources[e].id;this.owners.get(i)===t&&(this.sources.splice(e,1),this.owners.delete(i))}}}class Re{static BUILT_IN="ufoathome";static changes=new EventTarget;static points=new Map;static modules=new Map;static point(t){let e=Re.points.get(t);return e||(e=new BO(t),Re.points.set(t,e)),e}static install(t){if(t.id===Re.BUILT_IN)throw new Error(`"${Re.BUILT_IN}" is the id of the built-in module`);const e=Re.contributionsOf(t);for(const[s,r]of e){const a=Re.point(s).conflict(t.id,r);if(a)throw new nA(t.id,s,a.sourceId,a.ownerId)}const i=new Set(e.map(([s])=>s)),n=Re.modules.get(t.id);if(n)for(const[s]of Re.contributionsOf(n))i.add(s);for(const s of i)Re.point(s).withdraw(t.id);for(const[s,r]of e)Re.point(s).provide(t.id,r);Re.modules.set(t.id,t);for(const s of i)Re.announce(s)}static uninstall(t){const e=Re.modules.get(t);if(e){Re.modules.delete(t);for(const[i]of Re.contributionsOf(e))Re.point(i).withdraw(t),Re.announce(i)}}static installed(){return[...Re.modules.values()]}static contributionsOf(t){return Object.entries(t.contributes).filter(e=>Array.isArray(e[1])&&e[1].length>0)}static announce(t){Re.changes.dispatchEvent(new CustomEvent("change",{detail:t}))}}const HO=_r.catalog({en:()=>$t(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(o=>o.beamKindMessages_en),fr:()=>$t(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(o=>o.beamKindMessages_fr),es:()=>$t(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(o=>o.beamKindMessages_es),it:()=>$t(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(o=>o.beamKindMessages_it)}),mw={key:"beams",messages:HO,pickKind:"beam",simulation:()=>$t(async()=>{const{BeamSystem:o}=await import("./BeamSystem-DXTXXbc7.js");return{BeamSystem:o}},__vite__mapDeps([0,1]),import.meta.url).then(({BeamSystem:o})=>()=>new o),editor:()=>$t(async()=>{const{BeamEditor:o}=await import("./BeamEditor-ihmgiAKc.js");return{BeamEditor:o}},__vite__mapDeps([2,3,1,4]),import.meta.url).then(({BeamEditor:o})=>(t,e,i)=>new o(t,e,i)),reachM:(o,t)=>Ge.beamReachFor(o,t),describe:(o,t,{texts:e,name:i,distance:n})=>({name:i,detail:e.detail.replace("{name}",i).replace("{wavelength}",String(o.wavelengthNm)).replace("{power}",o.powerW.toLocaleString()).replace("{distance}",n(t.distanceM??0))})},GO=_r.catalog({en:()=>$t(()=>import("./LaunchKindMessages_en-Batvnyw3.js"),[],import.meta.url).then(o=>o.launchKindMessages_en),fr:()=>$t(()=>import("./LaunchKindMessages_fr-CoojboIk.js"),[],import.meta.url).then(o=>o.launchKindMessages_fr),es:()=>$t(()=>import("./LaunchKindMessages_es-KYyQ9gbu.js"),[],import.meta.url).then(o=>o.launchKindMessages_es),it:()=>$t(()=>import("./LaunchKindMessages_it-9HA3cjgP.js"),[],import.meta.url).then(o=>o.launchKindMessages_it)}),gw={key:"launches",messages:GO,pickKind:"plume",simulation:()=>$t(async()=>{const{LaunchSimulation:o}=await import("./LaunchSimulation-ClGdZJHr.js");return{LaunchSimulation:o}},__vite__mapDeps([5,6]),import.meta.url).then(({LaunchSimulation:o})=>()=>new o),editor:()=>$t(async()=>{const{LaunchEditor:o}=await import("./LaunchEditor-B4e1HRMn.js");return{LaunchEditor:o}},__vite__mapDeps([7,3,6,4]),import.meta.url).then(({LaunchEditor:o})=>(t,e,i)=>new o(t,e,i)),describe:(o,t,{said:e,texts:i,distance:n})=>{const s=t.detail,r=e.read(o.title)||o.vehicle?.mission||i.name,a=s.release===void 0||s.release==="burn"?void 0:o.jets?.find((l,h)=>`jet:${l.id??h}`===s.release),c=s.release===void 0||s.release==="burn"?i.ascent:a?.kind==="vent"?i.vent:i.burn;return{name:r,detail:i.detail.replace("{name}",r).replace("{part}",c).replace("{distance}",n(s.centre.distanceKm*1e3)).replace("{height}",Math.round(s.heightKm??0).toLocaleString())}}},VO=_r.catalog({en:()=>$t(()=>import("./ReentryKindMessages_en-Cbgk3paQ.js"),[],import.meta.url).then(o=>o.reentryKindMessages_en),fr:()=>$t(()=>import("./ReentryKindMessages_fr-D9r9x2bK.js"),[],import.meta.url).then(o=>o.reentryKindMessages_fr),es:()=>$t(()=>import("./ReentryKindMessages_es-DwgJQanC.js"),[],import.meta.url).then(o=>o.reentryKindMessages_es),it:()=>$t(()=>import("./ReentryKindMessages_it-DQ-J5YpD.js"),[],import.meta.url).then(o=>o.reentryKindMessages_it)}),Mw={key:"reentries",messages:VO,pickKind:"reentry",pickedAfterSatellites:!0,simulation:()=>$t(async()=>{const{ReentrySimulation:o}=await import("./ReentrySimulation-CrhMgBEf.js");return{ReentrySimulation:o}},[],import.meta.url).then(({ReentrySimulation:o})=>()=>new o),editor:()=>$t(async()=>{const{ReentryEditor:o}=await import("./ReentryEditor-7E16l_ix.js");return{ReentryEditor:o}},__vite__mapDeps([8,3,4]),import.meta.url).then(({ReentryEditor:o})=>(t,e,i)=>new o(t,e,i)),describe:(o,t,{said:e,texts:i})=>{const n=t.detail,s=(o.title?e.read(o.title):"")||o.object?.name||i.name,r=n.view.head,a=6371,c=Math.sqrt(a**2+r.distanceKm**2+2*a*r.distanceKm*Math.sin(r.altitudeDeg*Math.PI/180))-a;return{name:(n.view.fragmentId.includes(".")?i.fragment:i.piece).replace("{name}",s).replace("{mag}",n.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(c).toLocaleString()).replace("{distance}",Math.round(r.distanceKm).toLocaleString())}}},vM=Re.point("skyEvents").provide(Re.BUILT_IN,[{id:gw.key,name:"Launches",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>gw},{id:mw.key,name:"Beams",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>mw},{id:Mw.key,name:"Fireballs",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Mw}]);class Wa{static built=new WeakMap;static of(t){let e=Wa.built.get(t);return e||(e=t.create(),Wa.built.set(t,e)),e}static eventsOf(t,e){const i=t?.[e.key];return Array.isArray(i)?i:[]}}const WO=18,XO=.55,YO=.5,$O=.4,KO=2,qO=`
6975
+ }`)},t.customProgramCacheKey=()=>i?"rr0-road-grain-verge":"rr0-road-grain"}resample(t){const e=[];for(let n=0;n<t.length-1;n++){const s=t[n],r=t[n+1],a=Math.hypot(r.x-s.x,r.z-s.z),c=Math.max(1,Math.ceil(a/this.stepM));for(let l=0;l<c;l++){const h=l/c;e.push({x:s.x+(r.x-s.x)*h,z:s.z+(r.z-s.z)*h})}}const i=t[t.length-1];return i&&e.push({x:i.x,z:i.z}),e}}class Ur{static CELL_M=40;cells=new Map;constructor(t,e){e.forEach((i,n)=>{const s=t[n].widthM/2+.3;for(let r=1;r<i.length;r++){const a=i[r-1].x,c=i[r-1].z,l=i[r].x-a,h=i[r].z-c,u={way:n,ax:a,az:c,dx:l,dz:h,length2:l*l+h*h,reach:s},d=Math.floor((Math.min(a,i[r].x)-s)/Ur.CELL_M),f=Math.floor((Math.max(a,i[r].x)+s)/Ur.CELL_M),p=Math.floor((Math.min(c,i[r].z)-s)/Ur.CELL_M),m=Math.floor((Math.max(c,i[r].z)+s)/Ur.CELL_M);for(let g=d;g<=f;g++)for(let M=p;M<=m;M++){const v=Ur.key(g,M),x=this.cells.get(v);x?x.push(u):this.cells.set(v,[u])}}})}static key(t,e){return(t+5e4)*100003+(e+5e4)}onAnotherCarriageway(t,e,i){const n=this.cells.get(Ur.key(Math.floor(t/Ur.CELL_M),Math.floor(e/Ur.CELL_M)));if(!n)return!1;for(const s of n){if(s.way===i)continue;const r=s.length2===0?0:Math.max(0,Math.min(1,((t-s.ax)*s.dx+(e-s.az)*s.dz)/s.length2));if(Math.hypot(t-(s.ax+s.dx*r),e-(s.az+s.dz*r))<s.reach)return!0}return!1}}class Si{constructor(t,e=[]){this.lamps=e;for(const i of t){const n=Math.hypot(i.halfAlongM,i.halfAcrossM),s=Math.floor((i.x-n)/Si.CELL_M),r=Math.floor((i.x+n)/Si.CELL_M),a=Math.floor((i.z-n)/Si.CELL_M),c=Math.floor((i.z+n)/Si.CELL_M);for(let l=s;l<=r;l++)for(let h=a;h<=c;h++){const u=Si.key(l,h),d=this.cells.get(u);d?d.push(i):this.cells.set(u,[i])}}}static REACH_M=16;static NEAREST_M=1;static SAMPLES_M=[-3,0,3];static CELL_M=32;cells=new Map;across(t,e,i,n){const s=[],r=[];for(const a of Si.SAMPLES_M){const c=t+i*a,l=e+n*a,h=this.wall(c,l,-n,i),u=this.wall(c,l,n,-i);h!==void 0&&s.push(h),u!==void 0&&r.push(u)}return{leftM:Si.agreed(s),rightM:Si.agreed(r)}}lampsAlong(t){const e=[];for(const i of this.lamps){let n;for(let s=1;s<t.length;s++){const r=t[s-1].x,a=t[s-1].z,c=t[s].x-r,l=t[s].z-a,h=c*c+l*l;if(h===0)continue;const u=((i.x-r)*c+(i.z-a)*l)/h;if(u<0||u>1)continue;const d=Math.sqrt(h),f=((i.x-r)*-l+(i.z-a)*c)/d;(!n||Math.abs(f)<n.distance)&&(n={distance:Math.abs(f),lateral:f})}n&&n.distance<=Si.REACH_M&&e.push(n.lateral)}return e}near(t){if(t.length===0)return!1;if(this.lampsAlong(t).length>0)return!0;const e=Si.REACH_M+Math.max(...Si.SAMPLES_M.map(Math.abs)),i=t.map(s=>s.x),n=t.map(s=>s.z);for(let s=Math.floor((Math.min(...i)-e)/Si.CELL_M);s<=Math.floor((Math.max(...i)+e)/Si.CELL_M);s++)for(let r=Math.floor((Math.min(...n)-e)/Si.CELL_M);r<=Math.floor((Math.max(...n)+e)/Si.CELL_M);r++)if(this.cells.has(Si.key(s,r)))return!0;return!1}static agreed(t){if(!(t.length<2))return t.sort((e,i)=>e-i),t[Math.floor((t.length-1)/2)]}wall(t,e,i,n){let s;const r=new Set,a=Si.CELL_M/2;for(let c=0;c<=Si.REACH_M+a;c+=a){const l=this.cells.get(Si.key(Math.floor((t+i*c)/Si.CELL_M),Math.floor((e+n*c)/Si.CELL_M)));for(const h of l??[]){if(r.has(h))continue;r.add(h);const u=Si.hit(h,t,e,i,n);u!==void 0&&u<=Si.REACH_M&&(s===void 0||u<s)&&(s=u)}}return s!==void 0&&s>=Si.NEAREST_M?s:void 0}static hit(t,e,i,n,s){const r=e-t.x,a=i-t.z,c=[r*t.alongX+a*t.alongZ,-r*t.alongZ+a*t.alongX],l=[n*t.alongX+s*t.alongZ,-n*t.alongZ+s*t.alongX],h=[t.halfAlongM,t.halfAcrossM];let u=-1/0,d=1/0;for(let f=0;f<2;f++){if(Math.abs(l[f])<1e-9){if(Math.abs(c[f])>h[f])return;continue}const p=(-h[f]-c[f])/l[f],m=(h[f]-c[f])/l[f];u=Math.max(u,Math.min(p,m)),d=Math.min(d,Math.max(p,m))}if(!(d<u||d<0||u<0))return u}static key(t,e){return(t+5e4)*100003+(e+5e4)}}class nA extends Error{constructor(t,e,i,n){super(`Module "${t}" gives "${i}" at ${e}, which module "${n}" already gives`),this.moduleId=t,this.point=e,this.sourceId=i,this.ownerId=n,this.name="ModuleConflictError"}}class BO{constructor(t){this.id=t}sources=[];owners=new Map;ownerOf(t){return this.owners.get(t)}conflict(t,e){for(const i of e){const n=this.owners.get(i.id);if(n!==void 0&&n!==t)return{sourceId:i.id,ownerId:n}}}provide(t,e){const i=this.conflict(t,e);if(i)throw new nA(t,this.id,i.sourceId,i.ownerId);this.withdraw(t);const n=t===Re.BUILT_IN?this.sources.findIndex(s=>this.owners.get(s.id)!==Re.BUILT_IN):-1;n<0?this.sources.push(...e):this.sources.splice(n,0,...e);for(const s of e)this.owners.set(s.id,t);return this.sources}withdraw(t){for(let e=this.sources.length-1;e>=0;e--){const i=this.sources[e].id;this.owners.get(i)===t&&(this.sources.splice(e,1),this.owners.delete(i))}}}class Re{static BUILT_IN="ufoathome";static changes=new EventTarget;static points=new Map;static modules=new Map;static point(t){let e=Re.points.get(t);return e||(e=new BO(t),Re.points.set(t,e)),e}static install(t){if(t.id===Re.BUILT_IN)throw new Error(`"${Re.BUILT_IN}" is the id of the built-in module`);const e=Re.contributionsOf(t);for(const[s,r]of e){const a=Re.point(s).conflict(t.id,r);if(a)throw new nA(t.id,s,a.sourceId,a.ownerId)}const i=new Set(e.map(([s])=>s)),n=Re.modules.get(t.id);if(n)for(const[s]of Re.contributionsOf(n))i.add(s);for(const s of i)Re.point(s).withdraw(t.id);for(const[s,r]of e)Re.point(s).provide(t.id,r);Re.modules.set(t.id,t);for(const s of i)Re.announce(s)}static uninstall(t){const e=Re.modules.get(t);if(e){Re.modules.delete(t);for(const[i]of Re.contributionsOf(e))Re.point(i).withdraw(t),Re.announce(i)}}static installed(){return[...Re.modules.values()]}static contributionsOf(t){return Object.entries(t.contributes).filter(e=>Array.isArray(e[1])&&e[1].length>0)}static announce(t){Re.changes.dispatchEvent(new CustomEvent("change",{detail:t}))}}const HO=_r.catalog({en:()=>$t(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(o=>o.beamKindMessages_en),fr:()=>$t(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(o=>o.beamKindMessages_fr),es:()=>$t(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(o=>o.beamKindMessages_es),it:()=>$t(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(o=>o.beamKindMessages_it)}),mw={key:"beams",messages:HO,pickKind:"beam",simulation:()=>$t(async()=>{const{BeamSystem:o}=await import("./BeamSystem-DXTXXbc7.js");return{BeamSystem:o}},__vite__mapDeps([0,1]),import.meta.url).then(({BeamSystem:o})=>()=>new o),editor:()=>$t(async()=>{const{BeamEditor:o}=await import("./BeamEditor-ihmgiAKc.js");return{BeamEditor:o}},__vite__mapDeps([2,3,1,4]),import.meta.url).then(({BeamEditor:o})=>(t,e,i)=>new o(t,e,i)),reachM:(o,t)=>ze.beamReachFor(o,t),describe:(o,t,{texts:e,name:i,distance:n})=>({name:i,detail:e.detail.replace("{name}",i).replace("{wavelength}",String(o.wavelengthNm)).replace("{power}",o.powerW.toLocaleString()).replace("{distance}",n(t.distanceM??0))})},GO=_r.catalog({en:()=>$t(()=>import("./LaunchKindMessages_en-Batvnyw3.js"),[],import.meta.url).then(o=>o.launchKindMessages_en),fr:()=>$t(()=>import("./LaunchKindMessages_fr-CoojboIk.js"),[],import.meta.url).then(o=>o.launchKindMessages_fr),es:()=>$t(()=>import("./LaunchKindMessages_es-KYyQ9gbu.js"),[],import.meta.url).then(o=>o.launchKindMessages_es),it:()=>$t(()=>import("./LaunchKindMessages_it-9HA3cjgP.js"),[],import.meta.url).then(o=>o.launchKindMessages_it)}),gw={key:"launches",messages:GO,pickKind:"plume",simulation:()=>$t(async()=>{const{LaunchSimulation:o}=await import("./LaunchSimulation-ClGdZJHr.js");return{LaunchSimulation:o}},__vite__mapDeps([5,6]),import.meta.url).then(({LaunchSimulation:o})=>()=>new o),editor:()=>$t(async()=>{const{LaunchEditor:o}=await import("./LaunchEditor-B4e1HRMn.js");return{LaunchEditor:o}},__vite__mapDeps([7,3,6,4]),import.meta.url).then(({LaunchEditor:o})=>(t,e,i)=>new o(t,e,i)),describe:(o,t,{said:e,texts:i,distance:n})=>{const s=t.detail,r=e.read(o.title)||o.vehicle?.mission||i.name,a=s.release===void 0||s.release==="burn"?void 0:o.jets?.find((l,h)=>`jet:${l.id??h}`===s.release),c=s.release===void 0||s.release==="burn"?i.ascent:a?.kind==="vent"?i.vent:i.burn;return{name:r,detail:i.detail.replace("{name}",r).replace("{part}",c).replace("{distance}",n(s.centre.distanceKm*1e3)).replace("{height}",Math.round(s.heightKm??0).toLocaleString())}}},VO=_r.catalog({en:()=>$t(()=>import("./ReentryKindMessages_en-Cbgk3paQ.js"),[],import.meta.url).then(o=>o.reentryKindMessages_en),fr:()=>$t(()=>import("./ReentryKindMessages_fr-D9r9x2bK.js"),[],import.meta.url).then(o=>o.reentryKindMessages_fr),es:()=>$t(()=>import("./ReentryKindMessages_es-DwgJQanC.js"),[],import.meta.url).then(o=>o.reentryKindMessages_es),it:()=>$t(()=>import("./ReentryKindMessages_it-DQ-J5YpD.js"),[],import.meta.url).then(o=>o.reentryKindMessages_it)}),Mw={key:"reentries",messages:VO,pickKind:"reentry",pickedAfterSatellites:!0,simulation:()=>$t(async()=>{const{ReentrySimulation:o}=await import("./ReentrySimulation-CrhMgBEf.js");return{ReentrySimulation:o}},[],import.meta.url).then(({ReentrySimulation:o})=>()=>new o),editor:()=>$t(async()=>{const{ReentryEditor:o}=await import("./ReentryEditor-7E16l_ix.js");return{ReentryEditor:o}},__vite__mapDeps([8,3,4]),import.meta.url).then(({ReentryEditor:o})=>(t,e,i)=>new o(t,e,i)),describe:(o,t,{said:e,texts:i})=>{const n=t.detail,s=(o.title?e.read(o.title):"")||o.object?.name||i.name,r=n.view.head,a=6371,c=Math.sqrt(a**2+r.distanceKm**2+2*a*r.distanceKm*Math.sin(r.altitudeDeg*Math.PI/180))-a;return{name:(n.view.fragmentId.includes(".")?i.fragment:i.piece).replace("{name}",s).replace("{mag}",n.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(c).toLocaleString()).replace("{distance}",Math.round(r.distanceKm).toLocaleString())}}},vM=Re.point("skyEvents").provide(Re.BUILT_IN,[{id:gw.key,name:"Launches",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>gw},{id:mw.key,name:"Beams",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>mw},{id:Mw.key,name:"Fireballs",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Mw}]);class Wa{static built=new WeakMap;static of(t){let e=Wa.built.get(t);return e||(e=t.create(),Wa.built.set(t,e)),e}static eventsOf(t,e){const i=t?.[e.key];return Array.isArray(i)?i:[]}}const WO=18,XO=.55,YO=.5,$O=.4,KO=2,qO=`
6976
6976
  attribute float aSpeed;
6977
6977
  uniform float uTime;
6978
6978
  uniform float uOverallSpeed;
@@ -7984,7 +7984,7 @@ ${l.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
7984
7984
  gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
7985
7985
  }
7986
7986
  `,transparent:!0,depthWrite:!1,side:xn,fog:!1,blending:Uc,blendSrc:Fc,blendDst:Ed})}static wallReflectance(t,e,i){const n=i(t,1,e);return 2*n/(1+n)}setSurroundings(t){this.uniforms.uSurroundings.value=t}static reflectedResponse(t,e){return Ut.respond(e*Ut.relativeOfResponse(Math.max(t,1e-5)))}}class xs{static SIZE=64;static MOVE_M=.01;holder=new Pi;cameras=[];faces=[];target=new qe(xs.SIZE,xs.SIZE);white=new ps({color:new rt(1,1,1),side:xn});scene=new Ws;cabin;meshes=0;eye=new R;scratch=new R;constructor(){const t=[[new R(1,0,0),new R(0,1,0)],[new R(-1,0,0),new R(0,1,0)],[new R(0,1,0),new R(0,0,1)],[new R(0,-1,0),new R(0,0,-1)],[new R(0,0,1),new R(0,1,0)],[new R(0,0,-1),new R(0,1,0)]];for(const[e,i]of t){const n=new Bn(90,1,.02,20);n.up.copy(i),n.lookAt(e),this.holder.add(n),this.cameras.push(n),this.faces.push(new Uint8Array(xs.SIZE*xs.SIZE*4))}this.scene.background=new rt(0,0,0)}get any(){return this.cabin!==void 0}update(t,e,i){if(!e){this.forget();return}e.updateWorldMatrix(!0,!0);const n=this.scratch.copy(i);e.worldToLocal(n);let s=0;e.traverse(r=>{r.isMesh&&s++}),!(e===this.cabin&&s===this.meshes&&n.distanceTo(this.eye)<xs.MOVE_M)&&(this.cabin=e,this.meshes=s,this.eye.copy(n),this.draw(t,e))}hides(t){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let e=0;e<6;e++){const i=this.cameras[e],n=this.scratch.copy(t).transformDirection(i.matrixWorldInverse);if(n.z>=0)continue;const s=n.x/-n.z,r=n.y/-n.z;if(Math.abs(s)>1||Math.abs(r)>1)continue;const a=Math.min(xs.SIZE-1,Math.floor((s+1)/2*xs.SIZE)),c=Math.min(xs.SIZE-1,Math.floor((r+1)/2*xs.SIZE));return this.faces[e][(c*xs.SIZE+a)*4]>127}return!1}forget(){this.holder.removeFromParent(),this.cabin=void 0,this.meshes=0}dispose(){this.forget(),this.target.dispose(),this.white.dispose()}draw(t,e){e.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];e.traverse(r=>{const a=r;if(!a.isMesh||!a.visible||(Array.isArray(a.material)?a.material:[a.material]).every(h=>h instanceof $a))return;const l=new vt(a.geometry,this.white);l.matrixAutoUpdate=!1,l.matrix.copy(a.matrixWorld),l.matrixWorld.copy(a.matrixWorld),i.push(l)});for(const r of i)this.scene.add(r);const n=t.getRenderTarget(),s=t.shadowMap.autoUpdate;t.shadowMap.autoUpdate=!1;for(let r=0;r<6;r++){const a=this.cameras[r];a.updateMatrixWorld(!0),t.setRenderTarget(this.target),t.clear(),t.render(this.scene,a),t.readRenderTargetPixels(this.target,0,0,xs.SIZE,xs.SIZE,this.faces[r])}t.setRenderTarget(n),t.shadowMap.autoUpdate=s;for(const r of i)r.removeFromParent()}}const hg="https://ufoathome.org/models/index.json";class Wu{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??L8()}async entries(t){const e=await this.load();return t?e.filter(i=>[i.kind].flat().includes(t)):e}async entry(t){return(await this.load()).find(e=>e.id===t)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const t=this.indexUrls.join(`
7987
- `);let e=Wu.shared.get(t);return e||(e=this.fetchFirstAvailable(),Wu.shared.set(t,e),e.then(i=>{i.length===0&&Wu.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function L8(){const o=`?v=${encodeURIComponent("0.170.0")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==hg?[t,hg]:[hg]).map(e=>e+o)}const k8=Re.point("decorModels").provide(Re.BUILT_IN,[{id:"ufoathome",name:"UFO@home",credit:"3D models re-hosted by UFO@home, each under its own author's licence",creditUrl:"https://ufoathome.org/models/",create:()=>new Wu}]);class uA{constructor(t,e=k8){this.preferredId=t,this.sources=e}attribution="3D models, each under its own author's licence";built=new Map;catalogues(){const t=this.sources.find(i=>i.id===this.preferredId)??this.sources[0];return(t?[t,...this.sources.filter(i=>i!==t)]:[]).map(i=>{let n=this.built.get(i);return n||(n=i.create(),this.built.set(i,n)),n})}entries(t){const e=this.catalogues()[0];return e?e.entries(t):Promise.resolve([])}async entry(t){for(const e of this.catalogues()){const i=await e.entry(t).catch(()=>{});if(i)return i}}async moduleOf(t){const e=Re.point("decorModels");for(const i of this.sources){const n=e.ownerOf(i.id);if(!(n===void 0||n===Re.BUILT_IN)&&await this.catalogueOf(i).entry(t).catch(()=>{}))return n}}catalogueOf(t){return this.catalogues(),this.built.get(t)}}async function ug(o){const{GLTFLoader:t}=await $t(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-BVVGHFvY.js");return{GLTFLoader:i}},[],import.meta.url),e=new t;return new Promise((i,n)=>{e.load(o,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${o}: ${s instanceof Error?s.message:String(s)}`)))})}const dA=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class Hs{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new vt(new ss(2,2),new Te({uniforms:{uColor:{value:new rt(0,0,0)},uRadius:{value:1}},vertexShader:Hs.VERTEX,fragmentShader:Hs.FRAGMENT,transparent:!0,depthWrite:!1,blending:En,toneMapped:!1})),this.mesh.name=t,this.mesh.frustumCulled=!1,this.mesh.renderOrder=e,this.mesh.visible=!1}shine(t,e,i){this.mesh.visible=!0,this.mesh.position.set(t.x,t.y,t.z),this.mesh.material.uniforms.uRadius.value=e,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(t,e,i,n){const s=Math.max(t,n*Hs.MIN_ANGLE_RAD),r=Hs.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Hs.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/(Hs.MAX_SHARE*Hs.FILL*Math.PI))}static VERTEX=`
7987
+ `);let e=Wu.shared.get(t);return e||(e=this.fetchFirstAvailable(),Wu.shared.set(t,e),e.then(i=>{i.length===0&&Wu.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function L8(){const o=`?v=${encodeURIComponent("0.170.1")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==hg?[t,hg]:[hg]).map(e=>e+o)}const k8=Re.point("decorModels").provide(Re.BUILT_IN,[{id:"ufoathome",name:"UFO@home",credit:"3D models re-hosted by UFO@home, each under its own author's licence",creditUrl:"https://ufoathome.org/models/",create:()=>new Wu}]);class uA{constructor(t,e=k8){this.preferredId=t,this.sources=e}attribution="3D models, each under its own author's licence";built=new Map;catalogues(){const t=this.sources.find(i=>i.id===this.preferredId)??this.sources[0];return(t?[t,...this.sources.filter(i=>i!==t)]:[]).map(i=>{let n=this.built.get(i);return n||(n=i.create(),this.built.set(i,n)),n})}entries(t){const e=this.catalogues()[0];return e?e.entries(t):Promise.resolve([])}async entry(t){for(const e of this.catalogues()){const i=await e.entry(t).catch(()=>{});if(i)return i}}async moduleOf(t){const e=Re.point("decorModels");for(const i of this.sources){const n=e.ownerOf(i.id);if(!(n===void 0||n===Re.BUILT_IN)&&await this.catalogueOf(i).entry(t).catch(()=>{}))return n}}catalogueOf(t){return this.catalogues(),this.built.get(t)}}async function ug(o){const{GLTFLoader:t}=await $t(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-BVVGHFvY.js");return{GLTFLoader:i}},[],import.meta.url),e=new t;return new Promise((i,n)=>{e.load(o,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${o}: ${s instanceof Error?s.message:String(s)}`)))})}const dA=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class Hs{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new vt(new ss(2,2),new Te({uniforms:{uColor:{value:new rt(0,0,0)},uRadius:{value:1}},vertexShader:Hs.VERTEX,fragmentShader:Hs.FRAGMENT,transparent:!0,depthWrite:!1,blending:En,toneMapped:!1})),this.mesh.name=t,this.mesh.frustumCulled=!1,this.mesh.renderOrder=e,this.mesh.visible=!1}shine(t,e,i){this.mesh.visible=!0,this.mesh.position.set(t.x,t.y,t.z),this.mesh.material.uniforms.uRadius.value=e,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(t,e,i,n){const s=Math.max(t,n*Hs.MIN_ANGLE_RAD),r=Hs.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Hs.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/(Hs.MAX_SHARE*Hs.FILL*Math.PI))}static VERTEX=`
7988
7988
  uniform float uRadius;
7989
7989
  varying vec2 vOffset;
7990
7990
  void main() {
@@ -8593,7 +8593,7 @@ void main() {`).replace("#include <opaque_fragment>",`
8593
8593
  vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
8594
8594
  gl_FragColor = vec4(light, 1.0);
8595
8595
  }
8596
- `,transparent:!0,blending:En,depthWrite:!1,side:Ci,fog:!1});this.object=new vt(new rn(Ov.RADIUS,128,32,0,Math.PI*2,0,ke.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<ke.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=Nn.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=Nn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class up{constructor(t){this.generator=t}static SIZE=128;target=new Pd(up.SIZE,{type:We,generateMipmaps:!0,minFilter:Vs,magFilter:ge});camera=new Mv(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,i,n=[]){const s=t.shadowMap.autoUpdate;let r=!1;e.traverse(c=>{const l=c;l.isLight&&l.castShadow&&l.shadow&&!l.shadow.map&&(r=!0)}),t.shadowMap.autoUpdate=r?s:!1;const a=n.map(c=>c.visible);for(const c of n)c.visible=!1;this.camera.position.copy(i),this.camera.update(t,e),n.forEach((c,l)=>{c.visible=a[l]}),t.shadowMap.autoUpdate=s,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class Zn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){Zn.install(),this.generator=new W1(t),this.eye=new up(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],l,h=Zn.REFRESH_MS){for(const g of[...this.probes.keys()])n.some(M=>M.id===g&&M.shiny)||(this.probes.get(g).dispose(),this.probes.delete(g));const u=[{probe:this.eye}];for(const g of n){if(!g.shiny)continue;let M=this.probes.get(g.id);M||(M=new up(this.generator),this.probes.set(g.id,M)),u.push({probe:M,reflector:g})}const d=performance.now(),f=()=>u.filter(({probe:g})=>g.capturedVersion!==a),p=f().filter(({probe:g})=>d-g.capturedAtMs>=h);if(p.length>0){const g=p.reduce((M,v)=>v.probe.capturedAtMs<M.probe.capturedAtMs?v:M);if(g.reflector){const M=g.reflector.holder.getWorldPosition(this.scratch);g.probe.capture(t,e,M,[g.reflector.holder,...s]),Zn.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,i,[...s,...c]),l?.(g.probe.sharp),Zn.decor=g.probe.filtered;for(const M of r)Zn.reflectOn(M,g.probe);for(const M of n)M.shiny||Zn.reflectOn(M.holder,g.probe)}g.probe.capturedVersion=a}const m=f();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:g})=>h-(d-g.capturedAtMs))))}scratch=new R;static reflectOn(t,e={filtered:Zn.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof $a?e.sharp&&s.setSurroundings(e.sharp):s instanceof Ro&&e.filtered&&s.envMap!==e.filtered&&(s.envMap=e.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(Zn.installed)return;Zn.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!he.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}he.lights_fragment_maps=he.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const gA=0,z8=1,B8=2,zw=2,dg=1.25,Bw=1,ts=32,wn=ts/4,MA=65535,I0=Math.pow(2,-24),Nv=Symbol("SKIP_GENERATION"),vA={strategy:gA,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Nv]:!1};function Wi(o,t,e){return e.min.x=t[o],e.min.y=t[o+1],e.min.z=t[o+2],e.max.x=t[o+3],e.max.y=t[o+4],e.max.z=t[o+5],e}function AM(o){let t=-1,e=-1/0;for(let i=0;i<3;i++){const n=o[i+3]-o[i];n>e&&(e=n,t=i)}return t}function Hw(o,t){t.set(o)}function Gw(o,t,e){let i,n;for(let s=0;s<3;s++){const r=s+3;i=o[s],n=t[s],e[s]=i<n?i:n,i=o[r],n=t[r],e[r]=i>n?i:n}}function Vf(o,t,e){for(let i=0;i<3;i++){const n=t[o+2*i],s=t[o+2*i+1],r=n-s,a=n+s;r<e[i]&&(e[i]=r),a>e[i+3]&&(e[i+3]=a)}}function fu(o){const t=o[3]-o[0],e=o[4]-o[1],i=o[5]-o[2];return 2*(t*e+e*i+i*t)}function nn(o,t){return t[o+15]===MA}function Ln(o,t){return t[o+6]}function es(o,t){return t[o+14]}function Sn(o){return o+wn}function bn(o,t){const e=t[o+6];return o+e*wn}function Lv(o,t){return t[o+7]}function fg(o,t,e,i,n){let s=1/0,r=1/0,a=1/0,c=-1/0,l=-1/0,h=-1/0,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,g=-1/0;const M=o.offset||0;for(let v=(t-M)*6,x=(t+e-M)*6;v<x;v+=6){const y=o[v+0],w=o[v+1],b=y-w,E=y+w;b<s&&(s=b),E>c&&(c=E),y<u&&(u=y),y>p&&(p=y);const S=o[v+2],A=o[v+3],_=S-A,I=S+A;_<r&&(r=_),I>l&&(l=I),S<d&&(d=S),S>m&&(m=S);const D=o[v+4],P=o[v+5],L=D-P,O=D+P;L<a&&(a=L),O>h&&(h=O),D<f&&(f=D),D>g&&(g=D)}i[0]=s,i[1]=r,i[2]=a,i[3]=c,i[4]=l,i[5]=h,n[0]=u,n[1]=d,n[2]=f,n[3]=p,n[4]=m,n[5]=g}const Pa=32,H8=(o,t)=>o.candidate-t.candidate,po=new Array(Pa).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Wf=new Float32Array(6);function G8(o,t,e,i,n,s){let r=-1,a=0;if(s===gA)r=AM(t),r!==-1&&(a=(t[r]+t[r+3])/2);else if(s===z8)r=AM(o),r!==-1&&(a=V8(e,i,n,r));else if(s===B8){const c=fu(o);let l=dg*n;const h=e.offset||0,u=(i-h)*6,d=(i+n-h)*6;for(let f=0;f<3;f++){const p=t[f],M=(t[f+3]-p)/Pa;if(n<Pa/4){const v=[...po];v.length=n;let x=0;for(let w=u;w<d;w+=6,x++){const b=v[x];b.candidate=e[w+2*f],b.count=0;const{bounds:E,leftCacheBounds:S,rightCacheBounds:A}=b;for(let _=0;_<3;_++)A[_]=1/0,A[_+3]=-1/0,S[_]=1/0,S[_+3]=-1/0,E[_]=1/0,E[_+3]=-1/0;Vf(w,e,E)}v.sort(H8);let y=n;for(let w=0;w<y;w++){const b=v[w];for(;w+1<y&&v[w+1].candidate===b.candidate;)v.splice(w+1,1),y--}for(let w=u;w<d;w+=6){const b=e[w+2*f];for(let E=0;E<y;E++){const S=v[E];b>=S.candidate?Vf(w,e,S.rightCacheBounds):(Vf(w,e,S.leftCacheBounds),S.count++)}}for(let w=0;w<y;w++){const b=v[w],E=b.count,S=n-b.count,A=b.leftCacheBounds,_=b.rightCacheBounds;let I=0;E!==0&&(I=fu(A)/c);let D=0;S!==0&&(D=fu(_)/c);const P=Bw+dg*(I*E+D*S);P<l&&(r=f,l=P,a=b.candidate)}}else{for(let y=0;y<Pa;y++){const w=po[y];w.count=0,w.candidate=p+M+y*M;const b=w.bounds;for(let E=0;E<3;E++)b[E]=1/0,b[E+3]=-1/0}for(let y=u;y<d;y+=6){let E=~~((e[y+2*f]-p)/M);E>=Pa&&(E=Pa-1);const S=po[E];S.count++,Vf(y,e,S.bounds)}const v=po[Pa-1];Hw(v.bounds,v.rightCacheBounds);for(let y=Pa-2;y>=0;y--){const w=po[y],b=po[y+1];Gw(w.bounds,b.rightCacheBounds,w.rightCacheBounds)}let x=0;for(let y=0;y<Pa-1;y++){const w=po[y],b=w.count,E=w.bounds,A=po[y+1].rightCacheBounds;b!==0&&(x===0?Hw(E,Wf):Gw(E,Wf,Wf)),x+=b;let _=0,I=0;x!==0&&(_=fu(Wf)/c);const D=n-x;D!==0&&(I=fu(A)/c);const P=Bw+dg*(_*x+I*D);P<l&&(r=f,l=P,a=w.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${s} used.`);return{axis:r,pos:a}}function V8(o,t,e,i){let n=0;const s=o.offset;for(let r=t,a=t+e;r<a;r++)n+=o[(r-s)*6+i*2];return n/e}class pg{constructor(){this.boundingData=new Float32Array(6)}}function W8(o,t,e,i,n,s){let r=i,a=i+n-1;const c=s.pos,l=s.axis*2,h=e.offset||0;for(;;){for(;r<=a&&e[(r-h)*6+l]<c;)r++;for(;r<=a&&e[(a-h)*6+l]>=c;)a--;if(r<a){for(let u=0;u<t;u++){let d=o[r*t+u];o[r*t+u]=o[a*t+u],o[a*t+u]=d}for(let u=0;u<6;u++){const d=r-h,f=a-h,p=e[d*6+u];e[d*6+u]=e[f*6+u],e[f*6+u]=p}r++,a--}else return r}}let yA,D0,_M,xA;const X8=Math.pow(2,32);function TM(o){return"count"in o?1:1+TM(o.left)+TM(o.right)}function Y8(o,t,e){return yA=new Float32Array(e),D0=new Uint32Array(e),_M=new Uint16Array(e),xA=new Uint8Array(e),RM(o,t)}function RM(o,t){const e=o/4,i=o/2,n="count"in t,s=t.boundingData;for(let r=0;r<6;r++)yA[e+r]=s[r];if(n)return t.buffer?(xA.set(new Uint8Array(t.buffer),o),o+t.buffer.byteLength):(D0[e+6]=t.offset,_M[i+14]=t.count,_M[i+15]=MA,o+ts);{const{left:r,right:a,splitAxis:c}=t,l=o+ts;let h=RM(l,r);const u=o/ts,f=h/ts-u;if(f>X8)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return D0[e+6]=f,D0[e+7]=c,RM(h,a)}}function $8(o,t,e,i,n,s){const{maxDepth:r,verbose:a,targetLeafSize:c,_strictLeafSize:l=1/0,strategy:h,onProgress:u}=n,d=o.primitiveBuffer,f=o.primitiveBufferStride,p=new Float32Array(6);let m=!1;const g=new pg;return fg(t,e,i,g.boundingData,p),v(g,e,i,p),g;function M(x){u&&u((x-s.offset)/s.count)}function v(x,y,w,b=null,E=0){!m&&E>=r&&(m=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`));const S=w>l;if(w<=c&&!S||E>=r)return M(y+w),x.offset=y,x.count=w,x;const A=G8(x.boundingData,b,t,y,w,h);let _=A.axis===-1?-1:W8(d,f,t,y,w,A);if(A.axis===-1||_===y||_===y+w){if(!S)return M(y+w),x.offset=y,x.count=w,x;A.axis=Math.max(0,AM(x.boundingData)),_=y+Math.max(1,Math.floor(w/2))}x.splitAxis=A.axis;const I=new pg,D=y,P=_-y;x.left=I,fg(t,D,P,I.boundingData,p),v(I,D,P,p,E+1);const L=new pg,O=_,k=w-P;return x.right=L,fg(t,O,k,L.boundingData,p),v(L,O,k,p,E+1),x}}function K8(o,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=o.getRootRanges(t.range),n=i[0],s=i[i.length-1],r={offset:n.offset,count:s.offset+s.count-n.offset},a=new Float32Array(6*r.count);a.offset=r.offset,o.computePrimitiveBounds(r.offset,r.count,a),o._roots=i.map(c=>{const l=$8(o,a,c.offset,c.count,t,r),h=TM(l),u=new e(ts*h);return Y8(0,l,u),u})}class kv{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class q8{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const Oi=new q8;let Ho,nh;const El=[],Xf=new kv(()=>new Ke);function Z8(o,t,e,i,n,s){Ho=Xf.getPrimitive(),nh=Xf.getPrimitive(),El.push(Ho,nh),Oi.setBuffer(o._roots[t]);const r=IM(0,o.geometry,e,i,n,s);Oi.clearBuffer(),Xf.releasePrimitive(Ho),Xf.releasePrimitive(nh),El.pop(),El.pop();const a=El.length;return a>0&&(nh=El[a-1],Ho=El[a-2]),r}function IM(o,t,e,i,n=null,s=0,r=0){const{float32Array:a,uint16Array:c,uint32Array:l}=Oi;let h=o*2;if(nn(h,c)){const d=Ln(o,l),f=es(h,c);return Wi(o,a,Ho),i(d,f,!1,r,s+o/wn,Ho)}else{let _=function(D){const{uint16Array:P,uint32Array:L}=Oi;let O=D*2;for(;!nn(O,P);)D=Sn(D),O=D*2;return Ln(D,L)},I=function(D){const{uint16Array:P,uint32Array:L}=Oi;let O=D*2;for(;!nn(O,P);)D=bn(D,L),O=D*2;return Ln(D,L)+es(O,P)};const d=Sn(o),f=bn(o,l);let p=d,m=f,g,M,v,x;if(n&&(v=Ho,x=nh,Wi(p,a,v),Wi(m,a,x),g=n(v),M=n(x),M<g)){p=f,m=d;const D=g;g=M,M=D,v=x}v||(v=Ho,Wi(p,a,v));const y=nn(p*2,c),w=e(v,y,g,r+1,s+p/wn);let b;if(w===zw){const D=_(p),L=I(p)-D;b=i(D,L,!0,r+1,s+p/wn,v)}else b=w&&IM(p,t,e,i,n,s,r+1);if(b)return!0;x=nh,Wi(m,a,x);const E=nn(m*2,c),S=e(x,E,M,r+1,s+m/wn);let A;if(S===zw){const D=_(m),L=I(m)-D;A=i(D,L,!0,r+1,s+m/wn,x)}else A=S&&IM(m,t,e,i,n,s,r+1);return!!A}}const Yu=new Oi.constructor,dp=new Oi.constructor,Eo=new kv(()=>new Ke),Al=new Ke,_l=new Ke,mg=new Ke,gg=new Ke;let Mg=!1;function J8(o,t,e,i){if(Mg)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Mg=!0;const n=o._roots,s=t._roots;let r,a=0,c=0;const l=new Vt().copy(e).invert();for(let h=0,u=n.length;h<u;h++){Yu.setBuffer(n[h]),c=0;const d=Eo.getPrimitive();Wi(0,Yu.float32Array,d),d.applyMatrix4(l);for(let f=0,p=s.length;f<p&&(dp.setBuffer(s[f]),r=ur(0,0,e,l,i,a,c,0,0,d),dp.clearBuffer(),c+=s[f].byteLength/ts,!r);f++);if(Eo.releasePrimitive(d),Yu.clearBuffer(),a+=n[h].byteLength/ts,r)break}return Mg=!1,r}function ur(o,t,e,i,n,s=0,r=0,a=0,c=0,l=null,h=!1){let u,d;h?(u=dp,d=Yu):(u=Yu,d=dp);const f=u.float32Array,p=u.uint32Array,m=u.uint16Array,g=d.float32Array,M=d.uint32Array,v=d.uint16Array,x=o*2,y=t*2,w=nn(x,m),b=nn(y,v);let E=!1;if(b&&w)h?E=n(Ln(t,M),es(t*2,v),Ln(o,p),es(o*2,m),c,r+t/wn,a,s+o/wn):E=n(Ln(o,p),es(o*2,m),Ln(t,M),es(t*2,v),a,s+o/wn,c,r+t/wn);else if(b){const S=Eo.getPrimitive();Wi(t,g,S),S.applyMatrix4(e);const A=Sn(o),_=bn(o,p);Wi(A,f,Al),Wi(_,f,_l);const I=S.intersectsBox(Al),D=S.intersectsBox(_l);E=I&&ur(t,A,i,e,n,r,s,c,a+1,S,!h)||D&&ur(t,_,i,e,n,r,s,c,a+1,S,!h),Eo.releasePrimitive(S)}else{const S=Sn(t),A=bn(t,M);Wi(S,g,mg),Wi(A,g,gg);const _=l.intersectsBox(mg),I=l.intersectsBox(gg);if(_&&I)E=ur(o,S,e,i,n,s,r,a,c+1,l,h)||ur(o,A,e,i,n,s,r,a,c+1,l,h);else if(_)if(w)E=ur(o,S,e,i,n,s,r,a,c+1,l,h);else{const D=Eo.getPrimitive();D.copy(mg).applyMatrix4(e);const P=Sn(o),L=bn(o,p);Wi(P,f,Al),Wi(L,f,_l);const O=D.intersectsBox(Al),k=D.intersectsBox(_l);E=O&&ur(S,P,i,e,n,r,s,c,a+1,D,!h)||k&&ur(S,L,i,e,n,r,s,c,a+1,D,!h),Eo.releasePrimitive(D)}else if(I)if(w)E=ur(o,A,e,i,n,s,r,a,c+1,l,h);else{const D=Eo.getPrimitive();D.copy(gg).applyMatrix4(e);const P=Sn(o),L=bn(o,p);Wi(P,f,Al),Wi(L,f,_l);const O=D.intersectsBox(Al),k=D.intersectsBox(_l);E=O&&ur(A,P,i,e,n,r,s,c,a+1,D,!h)||k&&ur(A,L,i,e,n,r,s,c,a+1,D,!h),Eo.releasePrimitive(D)}}return E}const vg=new class{constructor(){let o=null,t=null,e=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(s,r)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=r,this.buffer=o=s._roots[r],this.uint16Array=e=new Uint16Array(o),this.uint32Array=t=new Uint32Array(o)},this.reset=()=>{this.root=null,this.buffer=o=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=s=>{let r=s*2;for(;!nn(r,e);)s=Sn(s),r=s*2;return Ln(s,t)},this.getRangeEnd=s=>{let r=s*2;for(;!nn(r,e);)s=bn(s,t),r=s*2;return Ln(s,t)+es(r,e)};const n=(s,r,a)=>{const c=r*2,l=nn(c,e);if(!s(a,l,r)&&!l){const u=Sn(r),d=bn(r,t);n(s,u,a+1),n(s,d,a+1)}};this.traverseBuffer=s=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{n(s,0,0)}finally{i=!1}},this.traverse=s=>{this.traverseBuffer((r,a,c)=>{if(a){const l=c*2,h=t[c+6],u=e[l+14];return s(r,a,new Float32Array(o,c*4,6),h,u)}else{const l=Lv(c,t);return s(r,a,new Float32Array(o,c*4,6),l)}})}}},Vw=new Ke,Tl=new Float32Array(6);class j8{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...vA,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),K8(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,n){let s=1/0,r=1/0,a=1/0,c=-1/0,l=-1/0,h=-1/0;for(let u=t,d=t+e;u<d;u++){this.writePrimitiveBounds(u,Tl,0);const[f,p,m,g,M,v]=Tl;f<s&&(s=f),g>c&&(c=g),p<r&&(r=p),M>l&&(l=M),m<a&&(a=m),v>h&&(h=v)}return i[n+0]=s,i[n+1]=r,i[n+2]=a,i[n+3]=c,i[n+4]=l,i[n+5]=h,i}computePrimitiveBounds(t,e,i){const n=i.offset||0;for(let s=t,r=t+e;s<r;s++){this.writePrimitiveBounds(s,Tl,0);const[a,c,l,h,u,d]=Tl,f=(a+h)/2,p=(c+u)/2,m=(l+d)/2,g=(h-a)/2,M=(u-c)/2,v=(d-l)/2,x=(s-n)*6;i[x+0]=f,i[x+1]=g+(Math.abs(f)+g)*I0,i[x+2]=p,i[x+3]=M+(Math.abs(p)+M)*I0,i[x+4]=m,i[x+5]=v+(Math.abs(m)+v)*I0}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,n=e.length;i<n;i++)e[i]+=t;else{const i=this._roots;for(let n=0;n<i.length;n++){const s=i[n],r=new Uint32Array(s),a=new Uint16Array(s),c=s.byteLength/ts;for(let l=0;l<c;l++){const h=wn*l,u=2*h;nn(u,a)&&(r[h+6]+=t)}}}}traverse(t,e=0){vg.setBVH(this,e),vg.traverse(t),vg.reset()}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const n=t[e],s=new Uint32Array(n),r=new Uint16Array(n),a=new Float32Array(n),c=n.byteLength/ts;for(let l=c-1;l>=0;l--){const h=l*wn,u=h*2;if(nn(u,r)){const f=Ln(h,s),p=es(u,r);this.writePrimitiveRangeBounds(f,p,Tl,0),a.set(Tl,h)}else{const f=Sn(h),p=bn(h,s);for(let m=0;m<3;m++){const g=a[f+m],M=a[f+m+3],v=a[p+m],x=a[p+m+3];a[h+m]=g<v?g:v,a[h+m+3]=M>x?M:x}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{Wi(0,new Float32Array(i),Vw),t.union(Vw)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:n,intersectsPrimitive:s,scratchPrimitive:r,iterate:a}=t;if(n&&s){const u=n;n=(d,f,p,m,g)=>u(d,f,p,m,g)?!0:a(d,f,this,s,p,m,r)}else n||(s?n=(u,d,f,p)=>a(u,d,this,s,f,p,r):n=(u,d,f)=>f);let c=!1,l=0;const h=this._roots;for(let u=0,d=h.length;u<d;u++){const f=h[u];if(c=Z8(this,u,i,n,e,l),c)break;l+=f.byteLength/ts}return c}bvhcast(t,e,i){let{intersectsRanges:n}=i;return J8(this,t,e,n)}}function Q8(){return typeof SharedArrayBuffer<"u"}function Uv(o){return o.index?o.index.count:o.attributes.position.count}function Hp(o){return Uv(o)/3}function t9(o,t=ArrayBuffer){return o>65535?new Uint32Array(new t(4*o)):new Uint16Array(new t(2*o))}function e9(o,t){if(!o.index){const e=o.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=t9(e,i);o.setIndex(new Me(n,1));for(let s=0;s<e;s++)n[s]=s}}function i9(o,t,e){const i=Uv(o)/e,n=t||o.drawRange,s=n.start/e,r=(n.start+n.count)/e,a=Math.max(0,s),c=Math.min(i,r)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function n9(o,t){return o.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function Ww(o,t,e){const i=i9(o,t,e),n=n9(o,e);if(!n.length)return[i];const s=[],r=i.offset,a=i.offset+i.count,c=Uv(o)/e,l=[];for(const d of n){const{offset:f,count:p}=d,m=f,g=isFinite(p)?p:c-f,M=f+g;m<a&&M>r&&(l.push({pos:Math.max(r,m),isStart:!0}),l.push({pos:Math.min(a,M),isStart:!1}))}l.sort((d,f)=>d.pos!==f.pos?d.pos-f.pos:d.type==="end"?-1:1);let h=0,u=null;for(const d of l){const f=d.pos;h!==0&&f!==u&&s.push({offset:u,count:f-u}),h+=d.isStart?1:-1,u=f}return s}function s9(o,t){const e=o[o.length-1],i=e.offset+e.count>2**16,n=o.reduce((l,h)=>l+h.count,0),s=i?4:2,r=t?new SharedArrayBuffer(n*s):new ArrayBuffer(n*s),a=i?new Uint32Array(r):new Uint16Array(r);let c=0;for(let l=0;l<o.length;l++){const{offset:h,count:u}=o[l];for(let d=0;d<u;d++)a[c+d]=h+d;c+=u}return a}class r9 extends j8{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!Q8())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...vA,...e},e[Nv]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const n=Ww(e,t.range,i),s=s9(n,t.useSharedArrayBuffer);this._indirectBuffer=s}else e9(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new Ke))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Ww(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Ja{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,n=-1/0;for(let s=0,r=t.length;s<r;s++){const c=t[s][e];i=c<i?c:i,n=c>n?c:n}this.min=i,this.max=n}setFromPoints(t,e){let i=1/0,n=-1/0;for(let s=0,r=e.length;s<r;s++){const a=e[s],c=t.dot(a);i=c<i?c:i,n=c>n?c:n}this.min=i,this.max=n}isSeparated(t){return this.min>t.max||t.min>this.max}}Ja.prototype.setFromBox=(function(){const o=new R;return function(e,i){const n=i.min,s=i.max;let r=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let l=0;l<=1;l++)for(let h=0;h<=1;h++){o.x=n.x*c+s.x*(1-c),o.y=n.y*l+s.y*(1-l),o.z=n.z*h+s.z*(1-h);const u=e.dot(o);r=Math.min(u,r),a=Math.max(u,a)}this.min=r,this.max=a}})();const a9=(function(){const o=new R,t=new R,e=new R;return function(n,s,r){const a=n.start,c=o,l=s.start,h=t;e.subVectors(a,l),o.subVectors(n.end,n.start),t.subVectors(s.end,s.start);const u=e.dot(h),d=h.dot(c),f=h.dot(h),p=e.dot(c),g=c.dot(c)*f-d*d;let M,v;g!==0?M=(u*d-p*f)/g:M=0,v=(u+M*d)/f,r.x=M,r.y=v}})(),Fv=(function(){const o=new tt,t=new R,e=new R;return function(n,s,r,a){a9(n,s,o);let c=o.x,l=o.y;if(c>=0&&c<=1&&l>=0&&l<=1){n.at(c,r),s.at(l,a);return}else if(c>=0&&c<=1){l<0?s.at(0,a):s.at(1,a),n.closestPointToPoint(a,!0,r);return}else if(l>=0&&l<=1){c<0?n.at(0,r):n.at(1,r),s.closestPointToPoint(r,!0,a);return}else{let h;c<0?h=n.start:h=n.end;let u;l<0?u=s.start:u=s.end;const d=t,f=e;if(n.closestPointToPoint(u,!0,t),s.closestPointToPoint(h,!0,e),d.distanceToSquared(u)<=f.distanceToSquared(h)){r.copy(d),a.copy(u);return}else{r.copy(h),a.copy(f);return}}}})(),o9=(function(){const o=new R,t=new R,e=new yr,i=new qa;return function(s,r){const{radius:a,center:c}=s,{a:l,b:h,c:u}=r;if(i.start=l,i.end=h,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a||(i.start=l,i.end=u,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a)||(i.start=h,i.end=u,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a))return!0;const m=r.getPlane(e);if(Math.abs(m.distanceToPoint(c))<=a){const M=m.projectPoint(c,t);if(r.containsPoint(M))return!0}return!1}})(),c9=["x","y","z"],Na=1e-15,Xw=Na*Na;function qs(o){return Math.abs(o)<Na}class Ar extends On{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new R),this.satBounds=new Array(4).fill().map(()=>new Ja),this.points=[this.a,this.b,this.c],this.plane=new yr,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new qa,this.needsUpdate=!0}intersectsSphere(t){return o9(t,this)}update(){const t=this.a,e=this.b,i=this.c,n=this.points,s=this.satAxes,r=this.satBounds,a=s[0],c=r[0];this.getNormal(a),c.setFromPoints(a,n);const l=s[1],h=r[1];l.subVectors(t,e),h.setFromPoints(l,n);const u=s[2],d=r[2];u.subVectors(e,i),d.setFromPoints(u,n);const f=s[3],p=r[3];f.subVectors(i,t),p.setFromPoints(f,n);const m=l.length(),g=u.length(),M=f.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,m<Na?g<Na||M<Na?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):g<Na?M<Na?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):M<Na&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(a,t),this.needsUpdate=!1}}Ar.prototype.closestPointToSegment=(function(){const o=new R,t=new R,e=new qa;return function(n,s=null,r=null){const{start:a,end:c}=n,l=this.points;let h,u=1/0;for(let d=0;d<3;d++){const f=(d+1)%3;e.start.copy(l[d]),e.end.copy(l[f]),Fv(e,n,o,t),h=o.distanceToSquared(t),h<u&&(u=h,s&&s.copy(o),r&&r.copy(t))}return this.closestPointToPoint(a,o),h=a.distanceToSquared(o),h<u&&(u=h,s&&s.copy(o),r&&r.copy(a)),this.closestPointToPoint(c,o),h=c.distanceToSquared(o),h<u&&(u=h,s&&s.copy(o),r&&r.copy(c)),Math.sqrt(u)}})();Ar.prototype.intersectsTriangle=(function(){const o=new Ar,t=new Ja,e=new Ja,i=new R,n=new R,s=new R,r=new R,a=new qa,c=new qa,l=new R,h=new tt,u=new tt;function d(x,y,w,b){const E=i;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?E.copy(x.plane.normal):E.copy(y.plane.normal);const S=x.satBounds,A=x.satAxes;for(let D=1;D<4;D++){const P=S[D],L=A[D];if(t.setFromPoints(L,y.points),P.isSeparated(t)||(r.copy(E).cross(L),t.setFromPoints(r,x.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}const _=y.satBounds,I=y.satAxes;for(let D=1;D<4;D++){const P=_[D],L=I[D];if(t.setFromPoints(L,x.points),P.isSeparated(t)||(r.crossVectors(E,L),t.setFromPoints(r,x.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}return w&&(b||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),w.start.set(0,0,0),w.end.set(0,0,0)),!0}function f(x,y,w,b,E,S,A,_,I,D,P){let L=A/(A-_);D.x=b+(E-b)*L,P.start.subVectors(y,x).multiplyScalar(L).add(x),L=A/(A-I),D.y=b+(S-b)*L,P.end.subVectors(w,x).multiplyScalar(L).add(x)}function p(x,y,w,b,E,S,A,_,I,D,P){if(E>0)f(x.c,x.a,x.b,b,y,w,I,A,_,D,P);else if(S>0)f(x.b,x.a,x.c,w,y,b,_,A,I,D,P);else if(_*I>0||A!=0)f(x.a,x.b,x.c,y,w,b,A,_,I,D,P);else if(_!=0)f(x.b,x.a,x.c,w,y,b,_,A,I,D,P);else if(I!=0)f(x.c,x.a,x.b,b,y,w,I,A,_,D,P);else return!0;return!1}function m(x,y,w,b){const E=y.degenerateSegment,S=x.plane.distanceToPoint(E.start),A=x.plane.distanceToPoint(E.end);return qs(S)?qs(A)?d(x,y,w,b):(w&&(w.start.copy(E.start),w.end.copy(E.start)),x.containsPoint(E.start)):qs(A)?(w&&(w.start.copy(E.end),w.end.copy(E.end)),x.containsPoint(E.end)):x.plane.intersectLine(E,i)!=null?(w&&(w.start.copy(i),w.end.copy(i)),x.containsPoint(i)):!1}function g(x,y,w){const b=y.a;return qs(x.plane.distanceToPoint(b))&&x.containsPoint(b)?(w&&(w.start.copy(b),w.end.copy(b)),!0):!1}function M(x,y,w){const b=x.degenerateSegment,E=y.a;return b.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<Xw?(w&&(w.start.copy(E),w.end.copy(E)),!0):!1}function v(x,y,w,b){if(x.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=x.degenerateSegment,S=y.degenerateSegment,A=n,_=s;E.delta(A),S.delta(_);const I=i.subVectors(S.start,E.start),D=A.x*_.y-A.y*_.x;if(qs(D))return!1;const P=(I.x*_.y-I.y*_.x)/D,L=-(A.x*I.y-A.y*I.x)/D;if(P<0||P>1||L<0||L>1)return!1;const O=E.start.z+A.z*P,k=S.start.z+_.z*L;return qs(O-k)?(w&&(w.start.copy(E.start).addScaledVector(A,P),w.end.copy(E.start).addScaledVector(A,P)),!0):!1}else return y.isDegenerateIntoPoint?M(x,y,w):m(y,x,w,b);else{if(x.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(x.a)<Xw?(w&&(w.start.copy(x.a),w.end.copy(x.a)),!0):!1:y.isDegenerateIntoSegment?M(y,x,w):g(y,x,w);if(y.isDegenerateIntoPoint)return g(x,y,w);if(y.isDegenerateIntoSegment)return m(x,y,w,b)}}return function(y,w=null,b=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(o.copy(y),o.update(),y=o);const E=v(this,y,w,b);if(E!==void 0)return E;const S=this.plane,A=y.plane;let _=A.distanceToPoint(this.a),I=A.distanceToPoint(this.b),D=A.distanceToPoint(this.c);qs(_)&&(_=0),qs(I)&&(I=0),qs(D)&&(D=0);const P=_*I,L=_*D;if(P>0&&L>0)return!1;let O=S.distanceToPoint(y.a),k=S.distanceToPoint(y.b),H=S.distanceToPoint(y.c);qs(O)&&(O=0),qs(k)&&(k=0),qs(H)&&(H=0);const W=O*k,Q=O*H;if(W>0&&Q>0)return!1;n.copy(S.normal),s.copy(A.normal);const q=n.cross(s);let nt=0,at=Math.abs(q.x);const zt=Math.abs(q.y);zt>at&&(at=zt,nt=1),Math.abs(q.z)>at&&(nt=2);const Pt=c9[nt],Z=this.a[Pt],ct=this.b[Pt],ot=this.c[Pt],V=y.a[Pt],Ot=y.b[Pt],Wt=y.c[Pt];if(p(this,Z,ct,ot,P,L,_,I,D,h,a))return d(this,y,w,b);if(p(y,V,Ot,Wt,W,Q,O,k,H,u,c))return d(this,y,w,b);if(h.y<h.x){const Nt=h.y;h.y=h.x,h.x=Nt,l.copy(a.start),a.start.copy(a.end),a.end.copy(l)}if(u.y<u.x){const Nt=u.y;u.y=u.x,u.x=Nt,l.copy(c.start),c.start.copy(c.end),c.end.copy(l)}return h.y<u.x||u.y<h.x?!1:(w&&(u.x>h.x?w.start.copy(c.start):w.start.copy(a.start),u.y<h.y?w.end.copy(c.end):w.end.copy(a.end)),!0)}})();Ar.prototype.distanceToPoint=(function(){const o=new R;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();Ar.prototype.distanceToTriangle=(function(){const o=new R,t=new R,e=["a","b","c"],i=new qa,n=new qa;return function(r,a=null,c=null){const l=a||c?i:null;if(this.intersectsTriangle(r,l,!0))return(a||c)&&(a&&l.getCenter(a),c&&l.getCenter(c)),0;let h=1/0;for(let u=0;u<3;u++){let d;const f=e[u],p=r[f];this.closestPointToPoint(p,o),d=p.distanceToSquared(o),d<h&&(h=d,a&&a.copy(o),c&&c.copy(p));const m=this[f];r.closestPointToPoint(m,o),d=m.distanceToSquared(o),d<h&&(h=d,a&&a.copy(m),c&&c.copy(o))}for(let u=0;u<3;u++){const d=e[u],f=e[(u+1)%3];i.set(this[d],this[f]);for(let p=0;p<3;p++){const m=e[p],g=e[(p+1)%3];n.set(r[m],r[g]),Fv(i,n,o,t);const M=o.distanceToSquared(t);M<h&&(h=M,a&&a.copy(o),c&&c.copy(t))}}return Math.sqrt(h)}})();class gs{constructor(t,e,i){this.isOrientedBox=!0,this.min=new R,this.max=new R,this.matrix=new Vt,this.invMatrix=new Vt,this.points=new Array(8).fill().map(()=>new R),this.satAxes=new Array(3).fill().map(()=>new R),this.satBounds=new Array(3).fill().map(()=>new Ja),this.alignedSatBounds=new Array(3).fill().map(()=>new Ja),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}gs.prototype.update=(function(){return function(){const t=this.matrix,e=this.min,i=this.max,n=this.points;for(let l=0;l<=1;l++)for(let h=0;h<=1;h++)for(let u=0;u<=1;u++){const d=1*l|2*h|4*u,f=n[d];f.x=l?i.x:e.x,f.y=h?i.y:e.y,f.z=u?i.z:e.z,f.applyMatrix4(t)}const s=this.satBounds,r=this.satAxes,a=n[0];for(let l=0;l<3;l++){const h=r[l],u=s[l],d=1<<l,f=n[d];h.subVectors(a,f),u.setFromPoints(h,n)}const c=this.alignedSatBounds;c[0].setFromPointsField(n,"x"),c[1].setFromPointsField(n,"y"),c[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();gs.prototype.intersectsBox=(function(){const o=new Ja;return function(e){this.needsUpdate&&this.update();const i=e.min,n=e.max,s=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(o.min=i.x,o.max=n.x,a[0].isSeparated(o)||(o.min=i.y,o.max=n.y,a[1].isSeparated(o))||(o.min=i.z,o.max=n.z,a[2].isSeparated(o)))return!1;for(let c=0;c<3;c++){const l=r[c],h=s[c];if(o.setFromBox(l,e),h.isSeparated(o))return!1}return!0}})();gs.prototype.intersectsTriangle=(function(){const o=new Ar,t=new Array(3),e=new Ja,i=new Ja,n=new R;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(o.copy(r),o.update(),r=o);const a=this.satBounds,c=this.satAxes;t[0]=r.a,t[1]=r.b,t[2]=r.c;for(let d=0;d<3;d++){const f=a[d],p=c[d];if(e.setFromPoints(p,t),f.isSeparated(e))return!1}const l=r.satBounds,h=r.satAxes,u=this.points;for(let d=0;d<3;d++){const f=l[d],p=h[d];if(e.setFromPoints(p,u),f.isSeparated(e))return!1}for(let d=0;d<3;d++){const f=c[d];for(let p=0;p<4;p++){const m=h[p];if(n.crossVectors(f,m),e.setFromPoints(n,t),i.setFromPoints(n,u),e.isSeparated(i))return!1}}return!0}})();gs.prototype.closestPointToPoint=(function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}})();gs.prototype.distanceToPoint=(function(){const o=new R;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();gs.prototype.distanceToBox=(function(){const o=["x","y","z"],t=new Array(12).fill().map(()=>new qa),e=new Array(12).fill().map(()=>new qa),i=new R,n=new R;return function(r,a=0,c=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(c||l)&&(r.getCenter(n),this.closestPointToPoint(n,i),r.closestPointToPoint(i,n),c&&c.copy(i),l&&l.copy(n)),0;const h=a*a,u=r.min,d=r.max,f=this.points;let p=1/0;for(let g=0;g<8;g++){const M=f[g];n.copy(M).clamp(u,d);const v=M.distanceToSquared(n);if(v<p&&(p=v,c&&c.copy(M),l&&l.copy(n),v<h))return Math.sqrt(v)}let m=0;for(let g=0;g<3;g++)for(let M=0;M<=1;M++)for(let v=0;v<=1;v++){const x=(g+1)%3,y=(g+2)%3,w=M<<x|v<<y,b=1<<g|M<<x|v<<y,E=f[w],S=f[b];t[m].set(E,S);const _=o[g],I=o[x],D=o[y],P=e[m],L=P.start,O=P.end;L[_]=u[_],L[I]=M?u[I]:d[I],L[D]=v?u[D]:d[I],O[_]=d[_],O[I]=M?u[I]:d[I],O[D]=v?u[D]:d[I],m++}for(let g=0;g<=1;g++)for(let M=0;M<=1;M++)for(let v=0;v<=1;v++){n.x=g?d.x:u.x,n.y=M?d.y:u.y,n.z=v?d.z:u.z,this.closestPointToPoint(n,i);const x=n.distanceToSquared(i);if(x<p&&(p=x,c&&c.copy(i),l&&l.copy(n),x<h))return Math.sqrt(x)}for(let g=0;g<12;g++){const M=t[g];for(let v=0;v<12;v++){const x=e[v];Fv(M,x,i,n);const y=i.distanceToSquared(n);if(y<p&&(p=y,c&&c.copy(i),l&&l.copy(n),y<h))return Math.sqrt(y)}}return Math.sqrt(p)}})();class l9 extends kv{constructor(){super(()=>new Ar)}}const nr=new l9,pu=new R,yg=new R;function h9(o,t,e={},i=0,n=1/0){const s=i*i,r=n*n;let a=1/0,c=null;if(o.shapecast({boundsTraverseOrder:h=>(pu.copy(t).clamp(h.min,h.max),pu.distanceToSquared(t)),intersectsBounds:(h,u,d)=>d<a&&d<r,intersectsTriangle:(h,u)=>{h.closestPointToPoint(t,pu);const d=t.distanceToSquared(pu);return d<a&&(yg.copy(pu),a=d,c=u),d<s}}),a===1/0)return null;const l=Math.sqrt(a);return e.point?e.point.copy(yg):e.point=yg.clone(),e.distance=l,e.faceIndex=c,e}const Yf=parseInt(Bd)>=169,u9=parseInt(Bd)<=161,rc=new R,ac=new R,oc=new R,$f=new tt,Kf=new tt,qf=new tt,Yw=new R,$w=new R,Kw=new R,mu=new R;function d9(o,t,e,i,n,s,r,a){let c;if(s===Ci?c=o.intersectTriangle(i,e,t,!0,n):c=o.intersectTriangle(t,e,i,s!==xn,n),c===null)return null;const l=o.origin.distanceTo(n);return l<r||l>a?null:{distance:l,point:n.clone()}}function qw(o,t,e,i,n,s,r,a,c,l,h){rc.fromBufferAttribute(t,s),ac.fromBufferAttribute(t,r),oc.fromBufferAttribute(t,a);const u=d9(o,rc,ac,oc,mu,c,l,h);if(u){if(i){$f.fromBufferAttribute(i,s),Kf.fromBufferAttribute(i,r),qf.fromBufferAttribute(i,a),u.uv=new tt;const f=On.getInterpolation(mu,rc,ac,oc,$f,Kf,qf,u.uv);Yf||(u.uv=f)}if(n){$f.fromBufferAttribute(n,s),Kf.fromBufferAttribute(n,r),qf.fromBufferAttribute(n,a),u.uv1=new tt;const f=On.getInterpolation(mu,rc,ac,oc,$f,Kf,qf,u.uv1);Yf||(u.uv1=f),u9&&(u.uv2=u.uv1)}if(e){Yw.fromBufferAttribute(e,s),$w.fromBufferAttribute(e,r),Kw.fromBufferAttribute(e,a),u.normal=new R;const f=On.getInterpolation(mu,rc,ac,oc,Yw,$w,Kw,u.normal);u.normal.dot(o.direction)>0&&u.normal.multiplyScalar(-1),Yf||(u.normal=f)}const d={a:s,b:r,c:a,normal:new R,materialIndex:0};if(On.getNormal(rc,ac,oc,d.normal),u.face=d,u.faceIndex=s,Yf){const f=new R;On.getBarycoord(mu,rc,ac,oc,f),u.barycoord=f}}return u}function Zw(o){return o&&o.isMaterial?o.side:o}function Gp(o,t,e,i,n,s,r){const a=i*3;let c=a+0,l=a+1,h=a+2;const{index:u,groups:d}=o;o.index&&(c=u.getX(c),l=u.getX(l),h=u.getX(h));const{position:f,normal:p,uv:m,uv1:g}=o.attributes;if(Array.isArray(t)){const M=i*3;for(let v=0,x=d.length;v<x;v++){const{start:y,count:w,materialIndex:b}=d[v];if(M>=y&&M<y+w){const E=Zw(t[b]),S=qw(e,f,p,m,g,c,l,h,E,s,r);if(S)if(S.faceIndex=i,S.face.materialIndex=b,n)n.push(S);else return S}}}else{const M=Zw(t),v=qw(e,f,p,m,g,c,l,h,M,s,r);if(v)if(v.faceIndex=i,v.face.materialIndex=0,n)n.push(v);else return v}return null}function fn(o,t,e,i){const n=o.a,s=o.b,r=o.c;let a=t,c=t+1,l=t+2;e&&(a=e.getX(a),c=e.getX(c),l=e.getX(l)),n.x=i.getX(a),n.y=i.getY(a),n.z=i.getZ(a),s.x=i.getX(c),s.y=i.getY(c),s.z=i.getZ(c),r.x=i.getX(l),r.y=i.getY(l),r.z=i.getZ(l)}function f9(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++)Gp(c,t,e,h,s,r,a)}function p9(o,t,e,i,n,s,r){const{geometry:a,_indirectBuffer:c}=o;let l=1/0,h=null;for(let u=i,d=i+n;u<d;u++){let f;f=Gp(a,t,e,u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function m9(o,t,e,i,n,s,r){const{geometry:a}=e,{index:c}=a,l=a.attributes.position;for(let h=o,u=t+o;h<u;h++){let d;if(d=h,fn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function g9(o,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=o.geometry,i=e.index?e.index.array:null,n=e.attributes.position;let s,r,a,c,l=0;const h=o._roots;for(let d=0,f=h.length;d<f;d++)s=h[d],r=new Uint32Array(s),a=new Uint16Array(s),c=new Float32Array(s),u(0,l),l+=s.byteLength;function u(d,f,p=!1){const m=d*2;if(nn(m,a)){const g=Ln(d,r),M=es(m,a);let v=1/0,x=1/0,y=1/0,w=-1/0,b=-1/0,E=-1/0;for(let S=3*g,A=3*(g+M);S<A;S++){let _=i[S];const I=n.getX(_),D=n.getY(_),P=n.getZ(_);I<v&&(v=I),I>w&&(w=I),D<x&&(x=D),D>b&&(b=D),P<y&&(y=P),P>E&&(E=P)}return c[d+0]!==v||c[d+1]!==x||c[d+2]!==y||c[d+3]!==w||c[d+4]!==b||c[d+5]!==E?(c[d+0]=v,c[d+1]=x,c[d+2]=y,c[d+3]=w,c[d+4]=b,c[d+5]=E,!0):!1}else{const g=Sn(d),M=bn(d,r);let v=p,x=!1,y=!1;if(t){if(!v){const _=g/wn+f/ts,I=M/wn+f/ts;x=t.has(_),y=t.has(I),v=!x&&!y}}else x=!0,y=!0;const w=v||x,b=v||y;let E=!1;w&&(E=u(g,f,v));let S=!1;b&&(S=u(M,f,v));const A=E||S;if(A)for(let _=0;_<3;_++){const I=g+_,D=M+_,P=c[I],L=c[I+3],O=c[D],k=c[D+3];c[d+_]=P<O?P:O,c[d+_+3]=L>k?L:k}return A}}}function Ko(o,t,e,i,n){let s,r,a,c,l,h;const u=1/e.direction.x,d=1/e.direction.y,f=1/e.direction.z,p=e.origin.x,m=e.origin.y,g=e.origin.z;let M=t[o],v=t[o+3],x=t[o+1],y=t[o+3+1],w=t[o+2],b=t[o+3+2];return u>=0?(s=(M-p)*u,r=(v-p)*u):(s=(v-p)*u,r=(M-p)*u),d>=0?(a=(x-m)*d,c=(y-m)*d):(a=(y-m)*d,c=(x-m)*d),s>c||a>r||((a>s||isNaN(s))&&(s=a),(c<r||isNaN(r))&&(r=c),f>=0?(l=(w-g)*f,h=(b-g)*f):(l=(b-g)*f,h=(w-g)*f),s>h||l>r)?!1:((l>s||s!==s)&&(s=l),(h<r||r!==r)&&(r=h),s<=n&&r>=i)}function M9(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++){let d=l?l[h]:h;Gp(c,t,e,d,s,r,a)}}function v9(o,t,e,i,n,s,r){const{geometry:a,_indirectBuffer:c}=o;let l=1/0,h=null;for(let u=i,d=i+n;u<d;u++){let f;f=Gp(a,t,e,c?c[u]:u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function y9(o,t,e,i,n,s,r){const{geometry:a}=e,{index:c}=a,l=a.attributes.position;for(let h=o,u=t+o;h<u;h++){let d;if(d=e.resolveTriangleIndex(h),fn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function x9(o,t,e,i,n,s,r){Oi.setBuffer(o._roots[t]),DM(0,o,e,i,n,s,r),Oi.clearBuffer()}function DM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Oi,h=o*2;if(nn(h,c)){const d=Ln(o,l),f=es(h,c);f9(t,e,i,d,f,n,s,r)}else{const d=Sn(o);Ko(d,a,i,s,r)&&DM(d,t,e,i,n,s,r);const f=bn(o,l);Ko(f,a,i,s,r)&&DM(f,t,e,i,n,s,r)}}const w9=["x","y","z"];function S9(o,t,e,i,n,s){Oi.setBuffer(o._roots[t]);const r=CM(0,o,e,i,n,s);return Oi.clearBuffer(),r}function CM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Oi;let l=o*2;if(nn(l,a)){const u=Ln(o,c),d=es(l,a);return p9(t,e,i,u,d,n,s)}else{const u=Lv(o,c),d=w9[u],p=i.direction[d]>=0;let m,g;p?(m=Sn(o),g=bn(o,c)):(m=bn(o,c),g=Sn(o));const v=Ko(m,r,i,n,s)?CM(m,t,e,i,n,s):null;if(v){const w=v.point[d];if(p?w<=r[g+u]:w>=r[g+u+3])return v}const y=Ko(g,r,i,n,s)?CM(g,t,e,i,n,s):null;return v&&y?v.distance<=y.distance?v:y:v||y||null}}const Zf=new Ke,Rl=new Ar,Il=new Ar,gu=new Vt,Jw=new gs,Jf=new gs;function b9(o,t,e,i){Oi.setBuffer(o._roots[t]);const n=PM(0,o,e,i);return Oi.clearBuffer(),n}function PM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Oi;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),Jw.set(e.boundingBox.min,e.boundingBox.max,i),n=Jw),nn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Ln(o,a),g=es(c,r);if(gu.copy(i).invert(),e.boundsTree)return Wi(o,s,Jf),Jf.matrix.copy(gu),Jf.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:v=>Jf.intersectsBox(v),intersectsTriangle:v=>{v.a.applyMatrix4(i),v.b.applyMatrix4(i),v.c.applyMatrix4(i),v.needsUpdate=!0;for(let x=m*3,y=(g+m)*3;x<y;x+=3)if(fn(Il,x,u,d),Il.needsUpdate=!0,v.intersectsTriangle(Il))return!0;return!1}});{const M=Hp(e);for(let v=m*3,x=(g+m)*3;v<x;v+=3){fn(Rl,v,u,d),Rl.a.applyMatrix4(gu),Rl.b.applyMatrix4(gu),Rl.c.applyMatrix4(gu),Rl.needsUpdate=!0;for(let y=0,w=M*3;y<w;y+=3)if(fn(Il,y,f,p),Il.needsUpdate=!0,Rl.intersectsTriangle(Il))return!0}}}else{const h=Sn(o),u=bn(o,a);return Wi(h,s,Zf),!!(n.intersectsBox(Zf)&&PM(h,t,e,i,n)||(Wi(u,s,Zf),n.intersectsBox(Zf)&&PM(u,t,e,i,n)))}}const jf=new Vt,xg=new gs,Mu=new gs,E9=new R,A9=new R,_9=new R,T9=new R;function R9(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),xg.set(t.boundingBox.min,t.boundingBox.max,e),xg.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=nr.getPrimitive(),f=nr.getPrimitive();let p=E9,m=A9,g=null,M=null;n&&(g=_9,M=T9);let v=1/0,x=null,y=null;return jf.copy(e).invert(),Mu.matrix.copy(jf),o.shapecast({boundsTraverseOrder:w=>xg.distanceToBox(w),intersectsBounds:(w,b,E)=>E<v&&E<r?(b&&(Mu.min.copy(w.min),Mu.max.copy(w.max),Mu.needsUpdate=!0),!0):!1,intersectsRange:(w,b)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:S=>Mu.distanceToBox(S),intersectsBounds:(S,A,_)=>_<v&&_<r,intersectsRange:(S,A)=>{for(let _=S,I=S+A;_<I;_++){fn(f,3*_,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let D=w,P=w+b;D<P;D++){fn(d,3*D,l,c),d.needsUpdate=!0;const L=d.distanceToTriangle(f,p,g);if(L<v&&(m.copy(p),M&&M.copy(g),v=L,x=D,y=_),L<s)return!0}}}});{const E=Hp(t);for(let S=0,A=E;S<A;S++){fn(f,3*S,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=w,I=w+b;_<I;_++){fn(d,3*_,l,c),d.needsUpdate=!0;const D=d.distanceToTriangle(f,p,g);if(D<v&&(m.copy(p),M&&M.copy(g),v=D,x=_,y=S),D<s)return!0}}}}}),nr.releasePrimitive(d),nr.releasePrimitive(f),v===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=v,i.faceIndex=x,n&&(n.point?n.point.copy(M):n.point=M.clone(),n.point.applyMatrix4(jf),m.applyMatrix4(jf),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function I9(o,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=o.geometry,i=e.index?e.index.array:null,n=e.attributes.position;let s,r,a,c,l=0;const h=o._roots;for(let d=0,f=h.length;d<f;d++)s=h[d],r=new Uint32Array(s),a=new Uint16Array(s),c=new Float32Array(s),u(0,l),l+=s.byteLength;function u(d,f,p=!1){const m=d*2;if(nn(m,a)){const g=Ln(d,r),M=es(m,a);let v=1/0,x=1/0,y=1/0,w=-1/0,b=-1/0,E=-1/0;for(let S=g,A=g+M;S<A;S++){const _=3*o.resolveTriangleIndex(S);for(let I=0;I<3;I++){let D=_+I;D=i?i[D]:D;const P=n.getX(D),L=n.getY(D),O=n.getZ(D);P<v&&(v=P),P>w&&(w=P),L<x&&(x=L),L>b&&(b=L),O<y&&(y=O),O>E&&(E=O)}}return c[d+0]!==v||c[d+1]!==x||c[d+2]!==y||c[d+3]!==w||c[d+4]!==b||c[d+5]!==E?(c[d+0]=v,c[d+1]=x,c[d+2]=y,c[d+3]=w,c[d+4]=b,c[d+5]=E,!0):!1}else{const g=Sn(d),M=bn(d,r);let v=p,x=!1,y=!1;if(t){if(!v){const _=g/wn+f/ts,I=M/wn+f/ts;x=t.has(_),y=t.has(I),v=!x&&!y}}else x=!0,y=!0;const w=v||x,b=v||y;let E=!1;w&&(E=u(g,f,v));let S=!1;b&&(S=u(M,f,v));const A=E||S;if(A)for(let _=0;_<3;_++){const I=g+_,D=M+_,P=c[I],L=c[I+3],O=c[D],k=c[D+3];c[d+_]=P<O?P:O,c[d+_+3]=L>k?L:k}return A}}}function D9(o,t,e,i,n,s,r){Oi.setBuffer(o._roots[t]),OM(0,o,e,i,n,s,r),Oi.clearBuffer()}function OM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Oi,h=o*2;if(nn(h,c)){const d=Ln(o,l),f=es(h,c);M9(t,e,i,d,f,n,s,r)}else{const d=Sn(o);Ko(d,a,i,s,r)&&OM(d,t,e,i,n,s,r);const f=bn(o,l);Ko(f,a,i,s,r)&&OM(f,t,e,i,n,s,r)}}const C9=["x","y","z"];function P9(o,t,e,i,n,s){Oi.setBuffer(o._roots[t]);const r=NM(0,o,e,i,n,s);return Oi.clearBuffer(),r}function NM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Oi;let l=o*2;if(nn(l,a)){const u=Ln(o,c),d=es(l,a);return v9(t,e,i,u,d,n,s)}else{const u=Lv(o,c),d=C9[u],p=i.direction[d]>=0;let m,g;p?(m=Sn(o),g=bn(o,c)):(m=bn(o,c),g=Sn(o));const v=Ko(m,r,i,n,s)?NM(m,t,e,i,n,s):null;if(v){const w=v.point[d];if(p?w<=r[g+u]:w>=r[g+u+3])return v}const y=Ko(g,r,i,n,s)?NM(g,t,e,i,n,s):null;return v&&y?v.distance<=y.distance?v:y:v||y||null}}const Qf=new Ke,Dl=new Ar,Cl=new Ar,vu=new Vt,jw=new gs,t0=new gs;function O9(o,t,e,i){Oi.setBuffer(o._roots[t]);const n=LM(0,o,e,i);return Oi.clearBuffer(),n}function LM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Oi;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),jw.set(e.boundingBox.min,e.boundingBox.max,i),n=jw),nn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Ln(o,a),g=es(c,r);if(vu.copy(i).invert(),e.boundsTree)return Wi(o,s,t0),t0.matrix.copy(vu),t0.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:v=>t0.intersectsBox(v),intersectsTriangle:v=>{v.a.applyMatrix4(i),v.b.applyMatrix4(i),v.c.applyMatrix4(i),v.needsUpdate=!0;for(let x=m,y=g+m;x<y;x++)if(fn(Cl,3*t.resolveTriangleIndex(x),u,d),Cl.needsUpdate=!0,v.intersectsTriangle(Cl))return!0;return!1}});{const M=Hp(e);for(let v=m,x=g+m;v<x;v++){const y=t.resolveTriangleIndex(v);fn(Dl,3*y,u,d),Dl.a.applyMatrix4(vu),Dl.b.applyMatrix4(vu),Dl.c.applyMatrix4(vu),Dl.needsUpdate=!0;for(let w=0,b=M*3;w<b;w+=3)if(fn(Cl,w,f,p),Cl.needsUpdate=!0,Dl.intersectsTriangle(Cl))return!0}}}else{const h=Sn(o),u=bn(o,a);return Wi(h,s,Qf),!!(n.intersectsBox(Qf)&&LM(h,t,e,i,n)||(Wi(u,s,Qf),n.intersectsBox(Qf)&&LM(u,t,e,i,n)))}}const e0=new Vt,wg=new gs,yu=new gs,N9=new R,L9=new R,k9=new R,U9=new R;function F9(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),wg.set(t.boundingBox.min,t.boundingBox.max,e),wg.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=nr.getPrimitive(),f=nr.getPrimitive();let p=N9,m=L9,g=null,M=null;n&&(g=k9,M=U9);let v=1/0,x=null,y=null;return e0.copy(e).invert(),yu.matrix.copy(e0),o.shapecast({boundsTraverseOrder:w=>wg.distanceToBox(w),intersectsBounds:(w,b,E)=>E<v&&E<r?(b&&(yu.min.copy(w.min),yu.max.copy(w.max),yu.needsUpdate=!0),!0):!1,intersectsRange:(w,b)=>{if(t.boundsTree){const E=t.boundsTree;return E.shapecast({boundsTraverseOrder:S=>yu.distanceToBox(S),intersectsBounds:(S,A,_)=>_<v&&_<r,intersectsRange:(S,A)=>{for(let _=S,I=S+A;_<I;_++){const D=E.resolveTriangleIndex(_);fn(f,3*D,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let P=w,L=w+b;P<L;P++){const O=o.resolveTriangleIndex(P);fn(d,3*O,l,c),d.needsUpdate=!0;const k=d.distanceToTriangle(f,p,g);if(k<v&&(m.copy(p),M&&M.copy(g),v=k,x=P,y=_),k<s)return!0}}}})}else{const E=Hp(t);for(let S=0,A=E;S<A;S++){fn(f,3*S,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=w,I=w+b;_<I;_++){const D=o.resolveTriangleIndex(_);fn(d,3*D,l,c),d.needsUpdate=!0;const P=d.distanceToTriangle(f,p,g);if(P<v&&(m.copy(p),M&&M.copy(g),v=P,x=_,y=S),P<s)return!0}}}}}),nr.releasePrimitive(d),nr.releasePrimitive(f),v===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=v,i.faceIndex=x,n&&(n.point?n.point.copy(M):n.point=M.clone(),n.point.applyMatrix4(e0),m.applyMatrix4(e0),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function Qw(o,t,e){return o===null?null:(o.point.applyMatrix4(t.matrixWorld),o.distance=o.point.distanceTo(e.ray.origin),o.object=t,o)}const i0=new gs,n0=new Xc,tS=new R,eS=new Vt,iS=new R,Sg=["getX","getY","getZ"];class fp extends r9{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,n=t._roots,s=t._indirectBuffer,r=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(a.roots=n.map(c=>c.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=s?s.slice():null):(a.roots=n,a.index=r?r.array:null,a.indirectBuffer=s),a}static deserialize(t,e,i={}){i={setIndex:!0,indirect:!!t.indirectBuffer,...i};const{index:n,roots:s,indirectBuffer:r}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),c(s));const a=new fp(e,{...i,[Nv]:!0});if(a._roots=s,a._indirectBuffer=r||null,i.setIndex){const l=e.getIndex();if(l===null){const h=new Me(t.index,1,!1);e.setIndex(h)}else l.array!==n&&(l.array.set(n),l.needsUpdate=!0)}return a;function c(l){for(let h=0;h<l.length;h++){const u=l[h],d=new Uint32Array(u),f=new Uint16Array(u);for(let p=0,m=u.byteLength/ts;p<m;p++){const g=wn*p,M=2*g;nn(M,f)||(d[g+6]=d[g+6]/wn-p)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,a=n.index?n.index.array:null,l=(s?s[t]:t)*3;let h=l+0,u=l+1,d=l+2;a&&(h=a[h],u=a[u],d=a[d]);for(let f=0;f<3;f++){const p=r[Sg[f]](h),m=r[Sg[f]](u),g=r[Sg[f]](d);let M=p;m<M&&(M=m),g<M&&(M=g);let v=p;m>v&&(v=m),g>v&&(v=g),e[i+f]=M,e[i+f+3]=v}return e}computePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,a=n.index?n.index.array:null,c=r.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,h=r.offset||0;let u=3;r.isInterleavedBufferAttribute&&(u=r.data.stride);const d=["getX","getY","getZ"],f=i.offset;for(let p=t,m=t+e;p<m;p++){const M=(s?s[p]:p)*3,v=(p-f)*6;let x=M+0,y=M+1,w=M+2;a&&(x=a[x],y=a[y],w=a[w]),c||(x=x*u+h,y=y*u+h,w=w*u+h);for(let b=0;b<3;b++){let E,S,A;c?(E=r[d[b]](x),S=r[d[b]](y),A=r[d[b]](w)):(E=l[x+b],S=l[y+b],A=l[w+b]);let _=E;S<_&&(_=S),A<_&&(_=A);let I=E;S>I&&(I=S),A>I&&(I=A);const D=(I-_)/2,P=b*2;i[v+P+0]=_+D,i[v+P+1]=D+(Math.abs(_)+D)*I0}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(n===void 0)return;eS.copy(t.matrixWorld).invert(),n0.copy(e.ray).applyMatrix4(eS),iS.setFromMatrixScale(t.matrixWorld),tS.copy(n0.direction).multiply(iS);const s=tS.length(),r=e.near/s,a=e.far/s;if(e.firstHitOnly===!0){let c=this.raycastFirst(n0,n,r,a);c=Qw(c,t,e),c&&i.push(c)}else{const c=this.raycast(n0,n,r,a);for(let l=0,h=c.length;l<h;l++){const u=Qw(c[l],t,e);u&&i.push(u)}}return i}refit(t=null){return(this.indirect?I9:g9)(this,t)}raycast(t,e=pa,i=0,n=1/0){const s=this._roots,r=[],a=this.indirect?D9:x9;for(let c=0,l=s.length;c<l;c++)a(this,c,e,t,r,i,n);return r}raycastFirst(t,e=pa,i=0,n=1/0){const s=this._roots;let r=null;const a=this.indirect?P9:S9;for(let c=0,l=s.length;c<l;c++){const h=a(this,c,e,t,i,n);h!=null&&(r==null||h.distance<r.distance)&&(r=h)}return r}intersectsGeometry(t,e){let i=!1;const n=this._roots,s=this.indirect?O9:b9;for(let r=0,a=n.length;r<a&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=nr.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?y9:m9});return nr.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=nr.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,l=this.indirect?p=>{const m=this.resolveTriangleIndex(p);fn(r,m*3,a,c)}:p=>{fn(r,p*3,a,c)},h=nr.getPrimitive(),u=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?p=>{const m=t.resolveTriangleIndex(p);fn(h,m*3,u,d)}:p=>{fn(h,p*3,u,d)};if(s){if(!(t instanceof fp))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const p=(m,g,M,v,x,y,w,b)=>{for(let E=M,S=M+v;E<S;E++){f(E),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let A=m,_=m+g;A<_;A++)if(l(A),r.needsUpdate=!0,s(r,h,A,E,x,y,w,b))return!0}return!1};if(n){const m=n;n=function(g,M,v,x,y,w,b,E){return m(g,M,v,x,y,w,b,E)?!0:p(g,M,v,x,y,w,b,E)}}else n=p}return super.bvhcast(t,e,{intersectsRanges:n})}intersectsBox(t,e){return i0.set(t.min,t.max,e),i0.needsUpdate=!0,this.shapecast({intersectsBounds:i=>i0.intersectsBox(i),intersectsTriangle:i=>i0.intersectsTriangle(i)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},n={},s=0,r=1/0){return(this.indirect?F9:R9)(this,t,e,i,n,s,r)}closestPointToPoint(t,e={},i=0,n=1/0){return h9(this,t,e,i,n)}}class Fr{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new ar;static install(){if(Fr.installed)return;Fr.installed=!0;const t=vt.prototype.raycast;vt.prototype.raycast=function(e,i){const n=Fr.treeOf(this,e);n!==null&&(n?n.raycastObject3D(this,e,i):t.call(this,e,i))}}static treeOf(t,e){const i=t.geometry,n=i?.attributes.position;if(!(n instanceof Me)||t.material===void 0||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh||i.morphAttributes.position)return;const s=i.index;if((s?s.count:n.count)/3<Fr.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const r=Fr.sphere.copy(i.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(r))return null;const a=Fr.trees.get(i);if(a){if(!a.bvh)return;if(a.position===n&&a.positionVersion===n.version&&a.index===s&&a.indexVersion===(s?.version??0))return a.bvh;Fr.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const c=new fp(i,{indirect:!0});return Fr.trees.set(i,{bvh:c,position:n,positionVersion:n.version,index:s,indexVersion:s?.version??0}),c}}function z9(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.rareIceCrystals===t.rareIceCrystals&&o.lowerCloudCover===t.lowerCloudCover&&o.relativeHumidity===t.relativeHumidity&&o.precipitationType===t.precipitationType&&o.precipitationIntensity===t.precipitationIntensity&&o.precipitationAmount===t.precipitationAmount&&o.windDirectionDeg===t.windDirectionDeg&&o.windSpeed===t.windSpeed&&o.storm===t.storm}const s0=900,bg=1,nS=4,Eg=5,r0=.5,a0=Ge.GROUND_RADIUS_M;function sS(o){return Ge.groundRadiusFor(o)}const Ag=.5,_g=850,o0=.03,B9=.015,as=850,Pl=300,_a=120,H9=700,Tg=.03,G9=3.5,c0=20,Rg=.04,V9=.26,rS=4,Ig=1.5,aS=-1,W9=.01,C0=-4,X9=2,Y9=20,l0=2600,$9=.97,K9=.38,xu=C0,q9=8,Z9=2,oS=1500,J9=.7,j9=.3,Q9=.32,tN=.65,cS=2.4,eN=.9,iN=400,nN=[0,45,90,135,180,225,270,315],sN=2,rN=16,lS=4e3,hS=880,h0=40,uS=60,aN=10,dS=1,oN=Ge.REBUILD_DISTANCE_M,fS=.265,pS=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*fS,Math.sin(e)*fS]})],Dg=700,Cg=250/UM,cN=12,mS=5,Pg=6,cc=[.92,.92,.95],Og=[.15,.15,.19],Ng={snow:{fallSpeedMPerS:2,size:.3,color:new rt(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new rt(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Ul=0,Lg=0,lN=150,kg=3e3,wu=20,hN=15,gS=Ul,uN=40,MS=1,dN=9;function Ug(o){return MS+(dN-MS)*o}const vS=new rt(.75,.82,.92),fN=10,pN=.5;function yS(o){return zr(o/fN,pN,1)}const lc=200,xS=.18,wS=.32,mN=.35,SS=new rt(.85,.9,.98),bS=5,ES=.85,AS=.01;function gN(o,t,e=1){return Math.round(o*(AS+(1-AS)*t)*e)}function MN(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.lowerCloudCover===t.lowerCloudCover}const _S=230,TS=.7,RS=.05,vN=.6,yN=.7,xN=.15,IS=.35,wN=3,SN=1/12,bN=.5,Nr=new rt(.82,.86,1),EN=2500,AN=1.6,Fg=15,_N={Venus:new rt(1,.96,.85),Mars:new rt(1,.55,.4),Jupiter:new rt(.95,.87,.72),Saturn:new rt(.92,.86,.68)};class lt{renderer;scene=new Ws;phenomena=new Mr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new Xe;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(t,e){if(this.skyHoldUntilMs===null)return t;this.arrivalsPending++;let i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=e===void 0?void 0:setTimeout(n,e);return e!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+e),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),e+20))),t.finally(()=>{clearTimeout(s),n()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+lS,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),lS+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new ve;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new tt;decorModelProvider=new uA;decorModelToken=0;decorModelCredits=new Map;emitterLights=new cs(this.scene,()=>this.relativeScale,{halfExtentM:_a,depthHalfRangeM:Pl,biasM:Tg,normalBiasM:Rg,mapSize:1024});bodySystem=new re(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale,t=>this.emitterLights.set("bodies",t));bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??lt.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*lt.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;skyEventsStated;skyEventsStart;skyEventLayers=new Map;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new j0(16777215,0);celestialLightTarget=new Pi;skyLight=new _4(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new E0;weather=yp;observerElevationM=0;siteElevationM=0;air=new er;groundRadius=a0;terrainRadius=a0;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new R;cloudFieldOffset=new R;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new R;rainLastVerticalFacing=-1;rainViewportSize=new tt;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new j0(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new E0;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new E0;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=pi.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;eclipsedSun=new Ld;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=wb()){zu.install(),Fr.install(),this.renderer=new HC({canvas:t,antialias:!0}),this.resolution=new Qe(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Cu,this.camera=new Bn(60,t.width/Math.max(t.height,1),.1,s0*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=e,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-_a,this.celestialLight.shadow.camera.right=_a,this.celestialLight.shadow.camera.top=_a,this.celestialLight.shadow.camera.bottom=-_a,this.celestialLight.shadow.camera.near=as-Pl,this.celestialLight.shadow.camera.far=as+Pl,this.celestialLight.shadow.bias=-Tg/(2*Pl),this.celestialLight.shadow.normalBias=Rg,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Nr),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new de(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(t,e){this.cssSize.width=t,this.cssSize.height=e,this.renderer.setSize(t,e,!1),this.camera.aspect=t/Math.max(e,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(t){t!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=t,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(t,e={}){this.cloudOffsetM.set(t.x,0,t.z),this.cloudLayerOffsetsM=e,this.layeredClouds?.setOffsets(t,e),this.cloudFieldOffset.set(t.x*Cg,0,t.z*Cg);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){this.updateLookPatch(t);const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*Je,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Je;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Je,e,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(sS(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/a0),this.camera.far=Math.max(s0*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),t.lat!==void 0&&t.lng!==void 0&&this.placeTerrain(t.lat,t.lng,0,0),this.poseElevationM=t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+t.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==t.fovDeg&&(this.camera.fov=t.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(t){this.stopTerrainFade(),this.terrainProviders=t,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.dropLookPatch(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=lt.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return Ge.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=ae(a.lat,a.lng,t,e);r.position.x=c.x-i,r.position.z=c.z+n};if(this.terrainMesh&&this.terrainMeshOrigin&&s(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&s(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;s(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}this.lookPatch&&s(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=dS+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=Ge.lookPatchFor(t.elevationM??0,t.pitchDeg,this.terrainRadius);if(!e){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const i=(t.headingDeg??0)*Math.PI/180,n=t.lat+e.distanceM*Math.cos(i)/111320,s=t.lng+e.distanceM*Math.sin(i)/(111320*Math.cos(t.lat*Math.PI/180)),r=this.lookPatchAsked;if(r){const l=ae(n,s,r.lat,r.lng);if(Math.hypot(l.x,l.z)<r.radiusM*lt.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:n,lng:s,radiusM:e.radiusM};const a=++this.lookPatchToken,c=this.terrainProviders;ng(n,s,{elevation:c.elevation,imagery:c.imagery},e.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:l})=>{if(a!==this.lookPatchToken||this.terrainProviders!==c||!this.terrainMesh){this.disposeMesh(l);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),l.renderOrder=lt.LOOK_PATCH_RENDER_ORDER,l.position.y=this.terrainMesh.position.y;const h=l.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:l,origin:{lat:n,lng:s},radiusM:e.radiusM};const u=ae(n,s,t.lat,t.lng);l.position.x=u.x,l.position.z=u.z,this.scene.add(l),this.compileNextFrameOffThread(),this.render()},l=>console.warn("No sharp ground under what is looked at:",l))}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:i},this.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),lt.TERRAIN_PATIENCE_MS)}return}const u=n.nearest(t,e);u&&(t=u.lat,e=u.lng,s=u.radiusM)}const r=s??Math.max(Ge.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=ae(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<oN*(r/a0))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(ae(t,e,c.lat,c.lng).x,ae(t,e,c.lat,c.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(ng(t,e,this.terrainProviders,r,{route:this.observerRoute}),lt.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const g=this.terrainMesh,M=this.terrainMeshOrigin,v=M?ae(t,e,M.lat,M.lng):void 0;g&&v&&Math.hypot(v.x,v.z)<=a&&(u.position.y=g.position.y+this.groundYOfPatch(g,v.x,v.z)),g&&M&&v&&Math.hypot(v.x,v.z)<=a?this.crossfadeTerrain(u,g,M):this.disposeMesh(this.terrainMesh),u.renderOrder=dS,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,r),this.buildWater(t,e,r,p,m),this.buildRailways(t,e,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,r,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,c=this.skyEventReachM({lat:t,lng:e});if(!Ge.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:m}=ae(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,m)<i*lt.FAR_RING_KEPT_SHARE)return}const l=this.terrainProviders.patches,h=l?.farRingOf?.(t,e);if(l&&!h){this.dropFarRing();return}const u=h?.radiusM??Ge.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(ng(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*lt.FAR_RING_OPEN_SHARE,referenceElevationM:s}),lt.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=lt.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-lt.FAR_RING_DROP_M;const m=p.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=u,this.scene.add(p),p.position.x=n.position.x,p.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}dropLookPatch(){this.lookPatchToken++,this.lookPatchAsked=void 0,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0)}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(t,e,i){if(this.grassReference){const r=ae(this.grassReference.lat,this.grassReference.lng,e,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:i};const n=ae(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const n=t.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/lt.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=Ge.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRoads(s.ways,t,e,n.contemporary);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(Bu(t,e,i)),lt.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:r},this.drapeRoads(r,t,e,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(t,e,i,n,s){const r=this.terrainProviders.water;if(!r||i>lt.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,t,e,i),lt.ROADS_PATIENCE_MS).catch(c=>console.warn("Water not drawn:",c));return}const a=this.waterSurfaces;if(a&&a.lat===t&&a.lng===e&&a.radiusM===i){this.drapeWater(a.surfaces,t,e,i);return}a&&Math.hypot(ae(t,e,a.lat,a.lng).x,ae(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(Bu(t,e,i))).then(c=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:c},this.drapeWater(c,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(c=>{console.warn("Water unavailable, drawing none:",c)})}async drapeWater(t,e,i,n){if(t.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n,this.patchSpacingM(r)),Zn.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=$t(async()=>{const{WaterSystem:t}=await import("./WaterSystem-DI_NBDfH.js");return{WaterSystem:t}},[],import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,i){const n=this.terrainProviders.railways;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRailways(s.lines,t,e,i);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(Bu(t,e,i)).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:r},this.drapeRailways(r,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(t,e,i,n){if(!this.railwaySystem&&!t.some(a=>a.level>=0))return;const s=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.setGroundSpacing(this.patchSpacingM(r)),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n),Zn.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=$t(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-DZQr_rS_.js");return{RailwaySystem:t}},[],import.meta.url).then(({RailwaySystem:t})=>{const e=new t;return this.scene.add(e.group),this.railwaySystem=e,e})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(t){t!==this.statedRoads&&(this.statedRoads=t,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const t=this.terrainMesh;t&&(this.roadSystem.group.position.copy(t.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(t)),this.roadSystem.setStated(this.statedRoads,(e,i)=>this.groundYOfPatch(t,e,i)))}setTraces(t,e=new Map){t===this.traces&&e===this.traceLabels||(this.traces=t,this.traceLabels=e,!(t.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(t){t!==this.tracesShown&&(this.tracesShown=t,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=$t(async()=>{const{TraceSystem:t}=await import("./TraceSystem-D7pxye9d.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(Eg);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(e,n,s)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=ut.naturalSize(n.kind,n.floors),r=(n.headingDeg??0)*Math.PI/180;return{x:i.x+n.eastM,z:i.z-n.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(n.sizeM?.lengthM??s.lengthM)/2,halfAcrossM:(n.sizeM?.widthM??s.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ae(i.lat,i.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="streetlight"&&!n.lamp?.supposed&&!n.track).map(n=>({x:i.x+n.eastM,z:i.z-n.northM}))}lampNudges=new Map;lampsToKerb(t,e){this.lampNudges.clear();const i=this.decorOriginInRoads(t,e);for(const n of this.decorObjects){if(n.kind!=="streetlight"||!n.lamp?.supposed||n.track)continue;const s=i.x+n.eastM,r=i.z-n.northM,a=this.roadSystem.atKerb(s,r);(a.x!==s||a.z!==r)&&this.lampNudges.set(n.id,{eastM:a.x-s,northM:-(a.z-r)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((i,n)=>{const s=e[n];if(i.id!==s.id||(i.track?.length??-1)!==(s.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(s)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==s[a])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,i=this.terrainProviders.roads;if(!e||!i)return;const n=this.wallsOf(t,e.lat,e.lng),s=this.roadWalls;s?.lat===e.lat&&s.lng===e.lng&&s.walls.length===n.length&&s.walls.every((a,c)=>a.what===n[c].what&&Math.hypot(a.x-n[c].x,a.z-n[c].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,i.contemporary)}wallsOf(t,e,i){const n=this.decorOriginInRoads(e,i);return t.filter(s=>s.kind==="building"||s.kind==="streetlight").map(s=>({what:`${s.kind}:${s.lamp?.supposed?"s":""}${s.headingDeg??0}:${s.sizeM?.widthM??""}:${s.sizeM?.lengthM??""}`,x:n.x+s.eastM,z:n.z-s.northM}))}roadWalls;drapeRoads(t,e,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(t,e,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius,new Si(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,i]=this.sunArriving,n=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?vn.LENS_K:vn.K)*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(t){this.compassHovered!==t&&(this.compassHovered=t,this.updateCompassVisibility())}setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassHovered||this.compassForced;if(this.compassSprites.some(e=>e.visible!==t)){for(const e of this.compassSprites)e.visible=t;this.developingExposure&&!this.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(t){if(z9(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!MN(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=er.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:Bo.steppedOpticalDepth(t.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),n?this.buildPrecipitation():s&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||n||s)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=t.storm&&t.cloudDarkness>=bN,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(lt.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ut.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,q9);for(const i of t){const n=ut.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,n,e.indexOf(i)<Z9,i.lamp),i.model&&i.id.startsWith(Ii.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=lt.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=$t(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-CcDlnjiD.js");return{ContrailSystem:t}},__vite__mapDeps([9,10]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),i=this.lastAstronomy?.sun,n=lt.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=ds.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=ke.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*l*c[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(t,e=!1,i){if(this.skyEventsStart=i,t===this.skyEventsStated&&!e)return;this.skyEventsStated=t;let n=!1;const s=new Set;for(const r of vM){const a=Wa.of(r);s.add(a.key);const c=Wa.eventsOf(t,a);let l=this.skyEventLayers.get(a.key);if(l?.kind!==a&&l&&(this.disposeSkyEventLayer(a.key,l),l=void 0),!(!l&&c.length===0)){if(!l)l={kind:a,events:c},this.skyEventLayers.set(a.key,l);else if(l.events===c)continue;l.events=c,n||=a.reachM!==void 0,this.loadSkyEventSimulation(l)}}for(const[r,a]of this.skyEventLayers)s.has(r)||(this.disposeSkyEventLayer(r,a),n||=a.kind.reachM!==void 0);n&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(t){if(t.simulation){this.updateSkyEvents(),this.render();return}t.loading??=t.kind.simulation().then(e=>{if(this.skyEventLayers.get(t.kind.key)!==t)return;const i=e();(i.inSky?this.celestialGroup:this.scene).add(i.object),t.simulation=i,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(t.loading)}disposeSkyEventLayer(t,e){e.simulation?.dispose(),this.skyEventLayers.delete(t),this.skyEventLight(t,[]),this.skyEventGlare(t,[])}skyEventLight(t,e){this.emitterLights.set(`skyEvent:${t}`,[],e.map(i=>this.farEmitterOf(i.position,i.magnitude)).filter(i=>i!==void 0)),this.refreshSkyFlare()}skyEventGlare(t,e){const i=`skyEvent:${t}:`,n=new Set;for(const s of e){const r=i+s.key,{x:a,y:c,z:l}=yi(s.position.altitudeDeg,s.position.azimuthDeg,as),[h,u,d]=this.arrivingIlluminance(s.position,s.magnitude,this.cloudTransmission(s.position));this.setGlare(r,a,c,l,[h*s.fade,u*s.fade,d*s.fade],0,lt.POINT_VEIL_HOLD_DEG),n.add(r)}for(const s of[...this.glareSprites.keys()])s.startsWith(i)&&!n.has(s)&&this.disposeGlare(s)}skyEventReachM(t){let e=0;for(const i of this.skyEventLayers.values())i.events.length>0&&i.kind.reachM&&(e=Math.max(e,i.kind.reachM(i.events,t)));return e}skyEventDrawnCount(t){return this.skyEventLayers.get(t)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const t=this.decorReferencePose;if(this.skyEventLayers.size===0||t?.lat===void 0||t.lng===void 0)return;const e=this.decorCurrentPose,i={lat:e?.lat??t.lat,lng:e?.lng??t.lng,heightM:this.siteElevationM+(e?.lat!==void 0?e.elevationM??0:t.elevationM??0)},n=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,s=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):T0(-90,this.instrumentMagnitudeGain);let r;for(const[a,c]of this.skyEventLayers)c.simulation&&(r??={observer:i,date:n,magnitudeLimit:s,cloudTransmission:l=>this.cloudTransmission(l),arrivingIlluminance:(l,h,u)=>this.arrivingIlluminance(l,h,u),transmittanceFromSpace:l=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,l.altitudeDeg),reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(l,h,u)=>this.transmittanceTo(l,h,u),groundYAt:(l,h)=>this.groundYUnder(l,h),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*Je)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*Je)*this.weather.windSpeed}},c.simulation.update(c.events,this.decorTime,{...r,lightFrom:l=>this.skyEventLight(a,l),glareFrom:l=>this.skyEventGlare(a,l)}));this.render()}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?yi(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}holdUntil(t){this.awaitArrival(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,i=this.groundYUnder(t,e),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(t+s*n,e-r)-i}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*Je)/Math.cos(t.lat*Je)}bodyMaskedByDecor(t,e){const i=this.decorGroups.get(e);return i?this.bodySystem.maskedShare(t,i):void 0}setBodies(t,e=0,i=t.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,c=this.scatteredSky,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*l}))),this.bodySystem.set(t,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(u,d)=>this.groundYUnder(u,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(u,d,f)=>this.transmittanceTo(u,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},e,c?Object.assign((u,d)=>c.relativeOfLuminance(u,d),{recorded:c.recorded}):void 0,i),this.bodySystem.setSmoke(n,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,c,l)=>(a*e+(c+l)/2*s)/Math.PI;return[r(t.r,i.r,n.r),r(t.g,i.g,n.g),r(t.b,i.b,n.b)]}bodyOutline(t,e){return this.bodySystem.outlineOf(t,e)}documentUrl;modelUrl(t){return t.url?this.documentRelative(t.url):void 0}documentRelative(t){if(t.startsWith("data:"))return t;const e=this.documentUrl??(typeof location>"u"?void 0:location.href);return e?new URL(t,e).href:t}async loadBodyModel(t){const e=t.url?void 0:t.id?await this.decorModelProvider.entry(t.id):void 0,i=this.modelUrl(t)??e?.url,n=t.credit??e?.credit;if(!(!i||!n))return{scene:await ug(i),credit:n,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg,bindings:e?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const i=this.loadedDecorModels.get(t.id);return!i||i.ref!==JSON.stringify($g(t))||!ut.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=fA(i.scene);n.traverse(s=>{s instanceof vt&&(s.userData.sharedModel=!0)}),ut.applyModelParameters(n,t.modelParameters,i.bindings),ut.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(n),this.decorModelCredits.set(t.id,i.credit)}mirrors=new Es;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?rb[t.kind]:$g(t);if(!(!n||!ut.usesModel(t)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const c=i||t.kind==="tree"?await this.standInScene(r):await ug(r);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const l=this.decorGroups.get(t.id);if(!l)return;!i&&t.kind!=="tree"&&(re.glaze(c),Zn.reflectOn(c));const h={ref:JSON.stringify(n),scene:c,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(t.id,h),this.applyLoadedDecorModel(t,l,h),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${t.id}":`,s)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=ug(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||Zn.reflectOn(i),i)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,i=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=i;const n=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?ae(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&L0(p.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.lng,s?0:this.gaitOffset.eastM,s?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),s||(n.x-=this.gaitOffset.eastM,n.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let a=0,c;if(s){const p=oa(s,i),m=ut.occupantView(s,p.headingDeg),g=-(p.headingDeg??0)*Je,M=m.x*Math.cos(g)+m.z*Math.sin(g),v=-m.x*Math.sin(g)+m.z*Math.cos(g),x=p.eastM+n.x,y=-p.northM+n.z;r.x=-(x+M),r.z=-(y+v),this.camera.position.y=this.groundYUnder(x,y)+m.eyeY,c=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Je,-(m.headingDeg+this.indoorLookYawDeg)*Je,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const l=this.findCabin(i,n,r);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const m=this.decorGroups.get(p.id);if(!m)continue;const g=oa(p,i),M=this.lampNudges.get(p.id),v=g.eastM+(M?.eastM??0)+n.x+r.x,x=-(g.northM+(M?.northM??0))+n.z+r.z,y=this.terrainMesh,w=`${y?.geometry.uuid}:${(v-(y?.position.x??0)).toFixed(3)}:${(x-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${h}`;if(m.userData.footprintKey!==w){if(p.kind==="wire"){const P=ut.wireGround(p,v,x,g.headingDeg,(L,O)=>this.groundYUnder(L,O));m.userData.footprintGroundY=P.startY,ut.shearWire(m,ut.sizeOf(p).lengthM,P.dropM)}else if(p.kind==="crossing"){const P=this.groundYUnder(v,x),L=-(g.headingDeg??0)*Je,O=Math.cos(L),k=Math.sin(L);m.userData.footprintGroundY=P,Ee.drape(ut.bodyOf(m),(H,W)=>this.groundYUnder(v+H*O+W*k,x-H*k+W*O)-P)}else m.userData.footprintGroundY=this.groundUnderFootprint(p,v,x,g.headingDeg,g.altitudeM);m.userData.footprintKey=w}const E=g.altitudeM>lt.AIRBORNE_M&&Math.hypot(v,x)<lt.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY,S=p.id.startsWith(Ii.ID_PREFIX)?lt.trafficHeight(g.altitudeM,m.userData.footprintGroundY):E+g.altitudeM;if(m.position.set(v,S,x),p.kind==="crop"){const P=Math.hypot(v,x);m.visible=P<=lN}const A=this.decorPresence.get(p.id),_=A!==void 0&&(i<A.fromMs||i>A.untilMs);A&&(m.visible=!_);const I=this.decorSunlight.get(p.id);I&&!_&&this.lightFromAbove(m,I),g.headingDeg!==void 0&&(m.rotation.y=-g.headingDeg*Je);const D=o_(p,i);if(D!==void 0&&lt.turnHead(m,g.headingDeg??0,D),p.kind==="crop"&&m.visible){const P=this.terrainMesh,L=[P?.geometry.uuid,v-(P?.position.x??0),x-(P?.position.z??0),m.position.y-(P?.position.y??0),g.headingDeg,g.altitudeM].map(O=>typeof O=="number"?O.toFixed(4):O).join(":");m.userData.cropGroundKey!==L&&(ut.fitCropToGround(m,(O,k)=>this.groundYUnder(O,k)+g.altitudeM),m.userData.cropGroundKey=L)}if(!_){const P=m.position.distanceTo(this.camera.position);a=Math.max(a,P),P<lt.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(s&&c!==void 0){const p=this.decorGroups.get(s.id);p&&(this.camera.position.y=p.position.y+c)}this.updateContrails(),this.updateSkyEvents();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,f=Math.max(s0*1.2,this.groundRadius*2.5,a*1.2,u*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const i=this.terrainYUnder(t,e);let n=i;for(const s of this.terraces){const r=t-s.x,a=e-s.z,c=r*s.cos-a*s.sin,l=r*s.sin+a*s.cos;if(Math.abs(c)<=s.halfWidthM&&Math.abs(l)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(c))/s.bankM)),u=h*h*(3-2*h);n=Math.max(n,u*s.levelY+(1-u)*Math.min(s.levelY,i))}}return n}placeTerraces(t,e,i){this.terraces=[];const n=this.terrainMesh;for(const s of this.decorObjects){if(s.kind!=="terrace")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=oa(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=ut.sizeOf(s),u=-(a.headingDeg??0)*Je,d=Math.cos(u),f=Math.sin(u),p=`${n?.geometry.uuid}:${(c-(n?.position.x??0)).toFixed(3)}:${(l-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(c,0,l),a.headingDeg!==void 0&&(r.rotation.y=u),r.userData.terraceKey!==p&&(r.userData.terraceLevelY=ut.fitTerrace(r,s,(m,g)=>this.terrainYUnder(c+m*d+g*f,l-m*f+g*d)),r.userData.terraceKey=p),this.terraces.push({x:c,z:l,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(t,e){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):Lg}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((t%360+360)%360/(360/n))%n;let r=this.horizonByBearing[s];return Number.isNaN(r)&&(r=this.horizonByBearing[s]=this.marchHorizon(s*360/n)),r}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+lt.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=t*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,c=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let u=l;u<=c;u=Math.max(u+l,u*1.02)){const d=i.x+s*u,f=i.z+r*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):a.position.y+this.groundYOfPatch(a,d-a.position.x,f-a.position.z),m=u*u/(2*lt.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(p-m-i.y,u))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,i){const n=t.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return Lg;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=zr((e-r)/(a-r)*(s-1),0,s-1),u=zr((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return Lg;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,m=u-f,g=(w,b)=>n.getY(w*s+b),M=g(f,d),v=g(f,d+1),x=g(f+1,d),y=g(f+1,d+1);return p+m<=1?M+(v-M)*p+(x-M)*m:y+(x-y)*(1-p)+(v-y)*(1-m)}groundUnderFootprint(t,e,i,n,s=0){return ut.groundUnderFootprint(t,e,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=Cs.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,n,s){const r=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:n??t.iso,autoExposure:t.autoExposure===!0&&n===void 0,maxIso:t.maxIso,metering:s??t.metering??"average",exposureSeconds:e,fNumber:i,development:t.development,exposureFollowMs:t.exposureFollowMs,print:t.print,monochrome:t.monochrome}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),i=t?Cs.NONE:this.perception??Cs.NONE;if(Di.uColorVision.value.set(...i.colorMatrix),Di.uContrast.value=i.contrastGain,!t){Di.uMedium.value=0;return}const n=t.kind==="sensor"&&t.development==="computational";Di.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:n?4:3;const s=t.autoExposure?this.frameLight:void 0,r=t.autoExposure||this.skyUnknown?s?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),c=r===void 0?void 0:r+a.mean,l=d=>.065*t.exposureSeconds*d*this.filterTransmittance/(t.fNumber*t.fNumber*e);let h=c!==void 0&&c>0?1/(e*c):void 0;h!==void 0&&t.metering==="highlights"&&a.brightest>0&&(h=Math.min(h,lt.HIGHLIGHT_KEPT_AT/(.18*e*a.brightest))),h!==void 0&&t.metering==="highlights"&&s&&s.brightest>0&&(h=Math.min(h,lt.ZONE_KEPT_AT/(.18*e*s.brightest)));const u=h!==void 0?Math.min(h,t.maxIso!==void 0?l(t.maxIso):1/0):l(t.iso);Di.uMediumExposure.value=u,Di.uPhoneStrength.value=n&&c!==void 0&&c>0?mr.strengthFor(mr.MID_GREY*u*e*c):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,i=2*Math.atan(Math.tan(e/2)*t.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),s=new R;let r=0,a=0;for(const{position:c,luminanceCdM2:l,solidAngleSr:h}of this.bodySystem.metered.values())s.copy(c).project(t),s.z<1&&Math.abs(s.x)<=1&&Math.abs(s.y)<=1&&(r+=l*h,a=Math.max(a,l*Math.min(1,h/(lt.HIGHLIGHT_SHARE*n))**2));return{mean:r/n,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new tt;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&ut.setLights(s,n.lights,t,s.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(s),this.camera.position),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=n.kind==="vehicle"?ab(n,t):void 0,c=a!==void 0?kc.lamps(a):YM(n,t,this.lastAstronomy?.sun.altitudeDeg);ut.setLit(r,n.kind,c,this.relativeScale,n.lamp);const l=this.streetlightLights.get(n.id);l&&(l.visible=c),a!==void 0&&(this.headlightSettings.set(n.id,a),this.aimDecorBeam(n,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=$t(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-B0Ubhwxs.js");return{HeadlightSystem:t}},[],import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const n=new R(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=ut.sizeOf(t).lengthM,r=e.getWorldPosition(new R).addScaledVector(n,s/2-j9);r.y+=J9;const a=ut.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*Q9,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(t){this.observerHeadlights=t,t&&this.loadHeadlights(),this.headlightSystem&&(t?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const t=this.observerHeadlights;if(!t||!this.headlightSystem?.has("observer"))return;const e=t.setting==="auto"?this.lastAstronomy?kc.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new R(Math.sin(i),0,-Math.cos(i)),s=new R(n.x*cS,this.camera.position.y-eN,n.z*cS);this.headlightSystem.aim("observer",e,s,n,tN,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=ut.bodyOf(e),r=s.children.find(l=>l.userData.emissive);if(!r)return;const a=oS*ut.lampShare(n),c=new dE(16764006,a*this.relativeScale,iN);n?.colorTemperatureK&&c.color.setRGB(...ut.lampHue(n)),c.userData.candela=a,c.position.copy(r.position).multiply(s.scale),c.castShadow=i,c.shadow.mapSize.set(512,512),c.shadow.bias=-.002,e.add(c),this.streetlightLights.set(t,c)}applyWindowGlow(){const t=this.lastAstronomy;ut.setLitWindowShare(t?Un.share(t.sun.altitudeDeg,t.localHour):0)}setAstronomy(t){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-t.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=t,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(t)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=t.sun,this.buildSky(t.sun),this.buildGround();const e=this.magnitudeLimitOf(t);this.buildStars(t.stars,e),this.placeBodies(t,e),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.applySkyColours(t),this.syncAnimationLoop(),this.render()}static relativeSkyOf(t,e){const i=r=>{const a=Ts.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Ut.relativeOfResponse(a)/a;return[r[0]*c,r[1]*c,r[2]*c]},n=i(t.zenith),s=i(t.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=tn.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,rS,new rt(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<C0){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=rS/as*(180/Math.PI),n=i/e.sunRadiusDeg,s=yi(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=yi(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos(zr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?zr(e.separationDeg*n*Je/a,0,2):0,l=Math.sin(a),[h,u]=a>1e-9?[Math.sin((1-c)*a)/l,Math.sin(c*a)/l]:[1,0],d={x:s.x*h+r.x*u,y:s.y*h+r.y*u,z:s.z*h+r.z*u},f=e.moonRadiusDeg*n;this.eclipseDiscs={sun:new R(s.x,s.y,s.z).normalize(),moon:new R(d.x,d.y,d.z).normalize(),sunRadiusRad:i*Je,moonRadiusRad:f*Je};const p=.01,m=(v,x)=>yi(t.sun.altitudeDeg+v,t.sun.azimuthDeg+x,1),g={x:m(p,0).x-m(-p,0).x,y:m(p,0).y-m(-p,0).y,z:m(p,0).z-m(-p,0).z},M={x:m(0,p).x-m(0,-p).x,y:m(0,p).y-m(0,-p).y,z:m(0,p).z-m(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:g,right:M}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new ih(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(t){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(t,this.magnitudeLimitOf(t)),this.applyDazzleStrength(),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.updateSkyEvents());const e=this.scatteredSky?.ambient??lt.relativeSkyOf(Q1(t.sun.altitudeDeg),this.relativeScale),i=e,n=this.lightUnderClouds(t),s=r=>n?[0,1,2].map(a=>r[a]*n.through+n.radiance[a]*(1-n.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=s(i.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Ht.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??oS)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,i.zenith),this.applyAir(),this.buildLunarDiffraction(t.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(t){const e=this.scatteredSky?.ready?this.scatteredSky:void 0;if(t.altitudeDeg<-.5||!e){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,n=(i===void 0?qt.DEFAULT_AEROSOL_OPTICAL_DEPTH:Bo.opticalDepth(i))*qt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=ke.aureoleScale(n,ke.airMass(t.altitudeDeg))*s,c=ke.coronaScale(r),l=ke.illuminanceOf(t.magnitude),h=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),c.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new Ov,this.celestialGroup.add(this.lunarDiffraction.object));const u=ke.profile(ke.HAZE_COARSE_MODE),d=ke.profile(ke.CLOUD_DROPLETS),f=hP(t.altitudeDeg),p=new Float32Array(ke.STEPS*3);let m=0;for(let x=0;x<ke.STEPS;x++){const y=x*3,w=[0,1,2].map(E=>l*f[E]*(a*u[y+E]+c*d[y+E])),b=Ts.shown(w,Ts.luminanceOf(w),(E,S)=>e.relativeOfLuminance(E,S));p.set(b,y),m=Math.max(m,Ts.response(b))}const{x:g,y:M,z:v}=yi(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:g,y:M,z:v}:void 0,p)}applyAir(){this.scene.fog instanceof Oc||(this.scene.fog=new Oc),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+e,Math.hypot(t-n.x,e-n.y,i-n.z))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(t,e){return Math.max(t,e)}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,lt.UMBRA_PATH_M),s=.2126*e+.7152*i+.0722*n;return s>0?[(.4124*e+.3576*i+.1805*n)/s,1,(.0193*e+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:tn.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?tn.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},flare:this.skyFlare}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?rN:sN),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(t){if(t.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new s8(_g),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):T0(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}get plumePuffCount(){return this.skyEventDrawnCount("launches")}get reentryCount(){return this.skyEventDrawnCount("reentries")}flightScreenPoint(t){const e=`${Ii.ID_PREFIX}${t}-`;for(const[i,n]of this.decorGroups){if(!n.visible||!i.startsWith(e))continue;const s=this.screenPointOf(new R().copy(n.position).sub(this.camera.position).normalize());if(s&&Math.abs(s.ndcX)<=1&&Math.abs(s.ndcY)<=1&&!this.groundHides(s.ndcX,s.ndcY))return s}}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(o0*this.camera.fov*Math.PI/180);let s,r=n;const a=new R;for(const[c,l]of this.decorGroups){if(!l.visible||!c.startsWith(Ii.ID_PREFIX))continue;a.copy(l.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,s=c)}return s&&!this.groundHides(t,e)?s:void 0}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(o0*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(t,e)?void 0:n}updateCelestialLight(t,e){const i=this.relativeScale,n=t.sun.altitudeDeg>=xu,s=!n&&t.moon.altitudeDeg>=xu,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Je)),l=this.siteElevationM+this.observerElevationM;let h=r,u=n||s?Fw.directFraction(r.altitudeDeg,l):0;n&&u<=0&&t.moon.altitudeDeg>=xu&&(h=t.moon,u=Fw.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Je)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),m=Math.max(0,1/(1+.1125*p)-f),g=[0,0,0];if(n||s){const b=ke.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let I=0;I<3;I++)g[I]=b*E[I]*m*c,this.cloudBeam[I]=b*E[I];const{x:S,y:A,z:_}=yi(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(S,A,_),u>0){const I=ke.illuminanceOf(h.magnitude)*i,D=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),P=h===r?f:this.cloudTransmission(h);for(let L=0;L<3;L++)a[L]=I*D[L]*P*u}}else this.cloudBeam.fill(0);const M=this.surroundings;if(M)this.skyLight.color.setRGB(M.up[0]*i,M.up[1]*i,M.up[2]*i),this.skyLight.groundColor.setRGB(M.down[0]*i,M.down[1]*i,M.down[2]*i);else{const b=this.skyCloudTransmission(),E=e.skyIrradiance,S=[0,1,2].map(_=>E[_]*b+g[_]);this.skyLight.color.setRGB(S[0],S[1],S[2]);const A=ee.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(S[0]+a[0]*d),A*(S[1]+a[1]*d),A*(S[2]+a[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||u<=0){this.celestialLight.intensity=0;return}const{x:v,y:x,z:y}=yi(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(v,x,y),this.celestialLight.shadow.normalBias=Rg*zr(x/V9,.1,1),this.placeShadowFrustum();const w=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/w,a[1]/w,a[2]/w),this.celestialLight.intensity=w,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(t,e){const i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=ds.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=ke.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=lt.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)n[l]=Math.max(0,a*r[l]*s*c-this.sceneSunBeam[l])}}t.traverse(s=>{const r=s.material;if(!(r instanceof or||r instanceof Ro)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=lt.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new R(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,t);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(t,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*i},c=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(n,a(n)).addScaledVector(s,a(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(c).addScaledVector(t,this.shadowLightDistanceM)}fitShadowToCabin(t){if(t===this.cabinShadow)return;this.cabinShadow=t;const e=this.celestialLight.shadow;if(!t){this.shadowHalfExtentM=-1;return}const i=e.camera,n=G9;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=c0+5,i.near=this.shadowLightDistanceM-c0,i.far=this.shadowLightDistanceM+c0,i.updateProjectionMatrix(),e.bias=-.004/(2*c0),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==lt.CABIN_SKY_SHARE&&(r.envMapIntensity=lt.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(H9,Math.max(_a,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const i=this.celestialLight.shadow,n=i.camera;n.left=-e,n.right=e,n.top=e,n.bottom=-e;const s=Math.max(Pl,e*(Pl/_a));this.shadowLightDistanceM=Math.max(as,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-Tg/(2*s);const r=e>2*_a?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=_a;shadowLightDistanceM=as;shadowUp=new R(0,1,0);shadowAxisX=new R;shadowAxisY=new R;shadowWorld=new R;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*Je,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)t+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),e+=s}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new R(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Ut.semiSaturation(Ut.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new Rn,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem&&(this.meteorSystem.update(t),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(e=>this.farEmitterOf(e,e.magnitude)).filter(e=>e!==void 0)),this.refreshSkyFlare())}farEmitterOf(t,e){if(!(t.altitudeDeg>0)||!Number.isFinite(e))return;const i=Math.max(this.relativeScale,1e-30),n=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:s,y:r,z:a}=yi(t.altitudeDeg,t.azimuthDeg,1);return{direction:new R(s,r,a),lux:[n[0]/i,n[1]/i,n[2]/i],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const i=Xi.starPointsOf(t,e);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(t){const e=At.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return T0(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(t,e=!1,i=0){const n=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(e,n,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const t=this.compileOffThread().then(()=>{this.compiling===t&&(this.compiling=void 0,this.render())});this.compiling=t;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+lt.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of t){const a=e.get(r)?.currentProgram;(!a||a.isReady())&&t.delete(r)}t.size===0||performance.now()>i?n():setTimeout(s,10)};s()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e);const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(t,e,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"&&s.kind!=="vehicle"||s.observerSide!==void 0&&L0(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=oa(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=ut.sizeOf(s),u=Math.max(h.widthM,h.lengthM)/2;Math.hypot(c,l)<u&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<u&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new Zn(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(c=>c.mesh)],i=[...this.starTiers.map(c=>c.points),...[...this.bodyMeshes.values()].filter(c=>c instanceof Bs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(c=>c!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(c=>c.name.startsWith("body:")),...[this.meteorSystem?.object].filter(c=>c!==void 0),...[...this.skyEventLayers.values()].filter(c=>c.simulation?.hiddenFromEye).map(c=>c.simulation.object)],n=this.relativeScale,s=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,c=>this.measureSurroundings(c,n,s,r),t?0:Zn.REFRESH_MS);a===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},a))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,lt.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,n){const s=this.lastAstronomy;if(!s)return;this.probeIrradiance??=new jl,this.framePhotograph={texture:t,scale:e,atMs:n};const r=[s.sun,s.moon].filter(a=>a.altitudeDeg>-2).map(a=>yi(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,r,a=>{const c=p=>p.map(m=>m/e),l=this.surroundings,h={up:c(a.up),down:c(a.down)},u=(p,m)=>p.some((g,M)=>Math.abs(g-m[M])>.03*Math.max(Math.abs(g),Math.abs(m[M]),1e-12)),d=!l||u(l.up,h.up)||u(l.down,h.down);d&&(this.surroundings=h),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(lt.adaptingLuminance(Math.exp(a.logAverage)/e,h.down))??!1;if(!d&&!f){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=xu?t.sun:t.moon.altitudeDeg>=xu?t.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*n,e.up[1]*n,e.up[2]*n]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new pr;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?yi(e.altitudeDeg,e.azimuthDeg,1):void 0,n=this.medium.exposureFollowMs??lt.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,i,s=>{const r={mean:s.mean/t.scale,brightest:s.brightest/t.scale},a=this.frameLight,c=t.atMs,l=a?c-a.atMs:1/0,h=l<0||l>lt.EXPOSURE_JUMP_MS,u=h||l===0&&a?.jumped?1:1-Math.exp(-l/n),d=(m,g)=>m>0&&g>0?m*(g/m)**u:g,f={mean:d(a?.mean??0,r.mean),brightest:d(a?.brightest??0,r.brightest),atMs:c,jumped:h||l===0&&(a?.jumped??!1)};this.frameLight=f;const p=(m,g)=>Math.abs(m-g)>.01*Math.max(m,g);(!a||p(a.mean,f.mean)||p(a.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Di.uRetinaOn.value=0,this.medium)return;const t=[];for(const a of this.emitterLights.farEmitters){const c=this.screenPointOf(a.direction);!c||Math.abs(c.ndcX)>1.2||Math.abs(c.ndcY)>1.2||t.push({ndcX:c.ndcX,ndcY:c.ndcY,lux:Ts.luminanceOf(a.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),i=e.x/Math.max(e.y,1),n={width:this.camera.fov*i,height:this.camera.fov},s=this.retina?.atMs;if((s===void 0||this.recordingTimeMs<s||this.recordingTimeMs-s>le.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new le,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),n,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new le,this.retina.advance(this.recordingTimeMs,t,n)}this.retina.any&&(Di.uRetina.value=this.retina.texture,Di.uRetinaOn.value=1,Di.uRetinaViewport.value.copy(e))}retinaSize=new tt;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const i=this.retinaHistory?.(t);if(!i||i.views.length===0)return[];const n=i.pose,s=this.historicQuaternion.setFromEuler(this.historicEuler.set((n?.pitchDeg??0)*Je,-(n?.headingDeg??0)*Je,(n?.rollDeg??0)*Je,"YXZ")).invert(),r=n?.fovDeg??this.camera.fov,a=[];for(const c of i.views){const l=this.farEmitterOf(c.head,c.magnitude);if(!l)continue;const h=this.screenPointIn(this.historicDirection.copy(l.direction).applyQuaternion(s),r,e);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||a.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:Ts.luminanceOf(l.lux)})}return a}historicQuaternion=new is;historicEuler=new ma;historicDirection=new R;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<lt.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(t){this.recordingTimeMs=t}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(t){const e=[];for(const i of t)i.traverse(n=>{n.userData.emissive===!0&&e.push(n)});return e}surroundings;animate(t,e){const i=Math.min(e/1e3,SN);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),ut.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,c)=>this.directionAtScreenPoint(r,a,c),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[EM]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},Es.INTERVAL_MS)),Di.uRodShare.value=this.scatteredSky?.rodShare??0,Di.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Di.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),s,r=>{this.lensFlare&&(this.lensFlare.mesh.visible=r?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof Bs&&e.userData.pointSource||e instanceof vt&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(s=>s.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Eg),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(mA),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new ps({blending:Uc,blendSrc:sa,blendDst:sa,blendSrcAlpha:sa,blendDstAlpha:sa,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(this.references.layer),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}setReferences(t,e){const i=t.map(n=>{const s=this.documentRelative(n.src);return s===n.src?n:{...n,src:s}});if(this.references){this.references.set(i,void 0,e);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:e},this.referencesLoading??=$t(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-Vgg3SwB1.js");return{ReferenceSystem:n}},[],import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=s,s.onFrame=()=>this.render(),this.referenceClock&&s.setTime(this.referenceClock);for(const[a,c]of this.referenceViews)s.setView(a,c);s.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&s.set(r.references,void 0,r.observerAt),this.render(),s})}setReferencesTime(t){this.referenceClock=t,this.references?.setTime(t)}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new R)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.y1<-1))return;const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const s=e?this.narrowTo(t,e):t,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse)),a=this.phenomena.furthestM;let c=0;for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const u=l.kind!=="crop"&&this.mayHide(h,t,r,a);lt.markDecorDepth(h,u),u&&c++}c>0&&(t.layers.set(bg),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(EM),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}phenomenaFrustum=new Rp;phenomenaViewProjection=new Vt;occluderSphere=new ar;localBounds=new WeakMap;mayHide(t,e,i,n){let s=0;t.traverse(()=>s++);let r=this.localBounds.get(t);if(!r||r.objects!==s){t.updateMatrixWorld(!0);const c=new Ke().setFromObject(t);if(c.isEmpty())return!1;r={sphere:c.getBoundingSphere(new ar).applyMatrix4(new Vt().copy(t.matrixWorld).invert()),objects:s},this.localBounds.set(t,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(t.matrixWorld);return a.center.distanceTo(e.position)-a.radius>n?!1:i.intersectsSphere(a)}narrowTo(t,e){const i=this.renderer.getDrawingBufferSize(new tt),n=lt.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),s=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*i.x-n)),r=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*i.y-n)),a=Math.min(i.x,Math.ceil((Math.min(1,e.x1)+1)/2*i.x+n)),c=Math.min(i.y,Math.ceil((Math.min(1,e.y1)+1)/2*i.y+n)),l=this.narrowCamera.copy(t);return l.setViewOffset(i.x,i.y,s,i.y-c,Math.max(1,a-s),Math.max(1,c-r)),l.updateMatrixWorld(),l}narrowCamera=new Bn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new ps({colorWrite:!1,side:xn});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const n=t.getObjectByName("head");if(!n)return;const s=((i-e)%360+540)%360-180,r=Math.max(-85,Math.min(lt.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*Je}static isSolidSurface(t){if(!(t instanceof vt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==En}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof vt))return;e&&lt.isSolidSurface(i)?i.layers.enable(bg):i.layers.disable(bg)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new tt),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new JC(e,i)),this.exposureAccumulation.resize(e,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+lt.EXPOSURE_BUDGET_MS,s=lt.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let r=0;do{this.restateAt(t,this.exposureInstantsDone);const a=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((c,l)=>{c.visible=a[l]})}e.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Di.uRodShare.value=this.scatteredSky?.rodShare??0,Di.uHasOverlay.value=1,Di.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Ws,n=new Xs(-1,1,1,-1,0,2),s=h0/(hS*Math.tan(uS*Je/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new R).sub(this.camera.position).normalize(),l=this.screenPointOf(c);if(!l)continue;const h=new eu(a.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(s/this.camera.aspect,s,1),i.add(h)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,n)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new Ke,i=new R,n=this.camera.getWorldDirection(new R),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(e.setFromObject(a),e.isEmpty())||e.distanceToPoint(this.camera.position)<lt.MAP_SUBJECT_NEAREST_M)continue;let c=1/0,l=-1/0,h=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const g=(m.ndcX+1)/2,M=(1-m.ndcY)/2;c=Math.min(c,g),l=Math.max(l,g),h=Math.min(h,M),u=Math.max(u,M)}c=Math.max(c,0),l=Math.min(l,1),h=Math.max(h,0),u=Math.min(u,1),l>=c&&u>=h&&t.push({x:c,y:h,width:l-c,height:u-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}usableDepthOfFieldPass(){const t=this.lensOptics;if(!t)return;const e=this.renderer.getDrawingBufferSize(new tt),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new Gu(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.depthOfFieldPass}setLensGhosts(t){JSON.stringify(t)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=t,t.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(t,e){return this.ghostPass?.holdsPictureAt(this.renderer,t,e)??!1}pickGhostAt(t,e){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,t,e,this.ghostOptics,Di.uMediumExposure.value)}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new tt);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Ji(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new tt);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new Pv(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new tt);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new Ri(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){this.aimStraightAtScreenPoint(t,e,i),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,n=>{const s=lt.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!s||s.distance>=n-.001||this.mirrors.isMirror(s.object)})}aimStraightAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new tt(e,i),this.camera);return}const s=n.directionFor(e,i,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(s.x,s.y,s.z).applyQuaternion(this.camera.quaternion).normalize(),t.camera=this.camera}pickCloudAt(t,e){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(t,e))}cloudDirectionAt(t,e){return this.directionAtScreenPoint(t,e,new R)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);return this.screenPointIn(e,this.camera.fov,n)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Ri.ndcFor(t,e,i);if(t.z>=0)return;const n=Math.tan(e/2*Je);return{ndcX:t.x/-t.z/(i*n),ndcY:t.y/-t.z/n}}screenPointScratch=new R;screenPointQuaternion=new is;screenPointSize=new tt;updateLensFlarePosition(){const t=this.lensFlare;if(!t)return;if(!this.sunVisible){t.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){t.mesh.visible=!1;return}const e=this.sunVisibleFraction();if(e<=0){t.mesh.visible=!1;return}t.mesh.visible=!0,this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;t.uniforms.uResolution.value.set(n,s),t.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const t=this.lensFlare;if(!t||!t.mesh.visible)return;const e=this.sunDiscRadiance.map(l=>Math.max(0,l-lt.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const i=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,n=Math.PI*i*i,s=t.uniforms.uLensPosition.value,r=t.uniforms.uTanHalfFov.value,a=this.camera.aspect,c=pi.offFrameShare(Math.atan(Math.hypot(s.x*a,s.y)*r)*180/Math.PI,Math.atan(Math.hypot(a,1)*r)*180/Math.PI);if(!(c<=0))return{x:s.x,y:s.y,radius:i,flux:[e[0]*n*c,e[1]*n*c,e[2]*n*c]}}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!i)return;const n=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),t.uniforms.uResolution.value.set(n.x,n.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(nS),this.camera.layers.set(nS),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of pS)this.isSunOccluded(e[0],e[1])||t++;return t/pS.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,i=0){const n=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&n.length===0)return!1;const s=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),r=s.length();if(s.normalize(),e!==0||i!==0){const l=Math.PI/180,h=this.sunOcclusionRightScratch.set(s.z,0,-s.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const u=this.sunOcclusionUpScratch.crossVectors(h,s).normalize();s.addScaledVector(h,e*l).addScaledVector(u,i*l).normalize()}if(this.groundBlocks(this.camera.position,s,r)||this.cabinMask.hides(s))return!0;const a=this.cabinMask.any?n.filter(l=>!this.cabinGroups.includes(l)):n;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,s);const c=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(l=>!(l.object.material instanceof $a));return c!==void 0&&c.distance<r}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let t=!1;for(const e of this.glareSprites.values()){if(!e.mesh.visible)continue;t||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),t=!0);const i=e.mesh.getWorldPosition(this.veilTargetScratch),n=e.mesh.material.uniforms.uSourceDeg.value,s=n>.05?lt.VEIL_SAMPLES:lt.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,c]of s)this.isOccludedToward(i,a*n,c*n)||r++;e.share=r/s.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new xs;veilTargetScratch=new R;groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const g=(s.position.y-t.y)/e.y;if(g>n&&g<i){const M=t.x+e.x*g-s.position.x,v=t.z+e.z*g-s.position.z;if(Math.hypot(M,v)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const l=[r.position.x+a.getX(0),r.position.x+a.getX(c-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((c-1)*c)],u=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(c-1);if(!(u>0))return!1;let d=n,f=i;for(const[g,M,v]of[[t.x,e.x,l],[t.z,e.z,h]]){const x=Math.min(v[0],v[1]),y=Math.max(v[0],v[1]);if(Math.abs(M)<1e-12){if(g<x||g>y)return!1;continue}const w=(x-g)/M,b=(y-g)/M;d=Math.max(d,Math.min(w,b)),f=Math.min(f,Math.max(w,b))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),m=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let g=0;g<=m;g++){const M=d+(f-d)*g/m,v=t.x+e.x*M,x=t.y+e.y*M,y=t.z+e.z*M;if(x<=this.groundYUnder(v,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=r0;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const c=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(l=>lt.isSolidSurface(l.object));c&&(r.occludesSourceIds?.includes(i)?n=n===void 0?c.distance:Math.max(n,c.distance):s=s===void 0?c.distance:Math.min(s,c.distance))}return{behindM:n,inFrontM:s}}pickBodyAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.origin,n=this.raycaster.ray.direction,s=W9*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new R).sub(i);return{key:h,direction:d.clone().normalize(),radiusRad:Math.atan2(u.scale.x/2,d.length())}}),a=this.eclipseDiscs,c=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],l=lt.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...c],s);if(l)return this.groundHides(t,e)?void 0:l}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(t,e)?i:void 0}static nearestBody(t,e,i){let n,s=1/0,r=1/0,a=!1;for(const c of e){const l=Math.acos(zr(c.direction.dot(t),-1,1))-c.radiusRad;if(l>i)continue;const h=l<=0,u=s<=0,d=c.inFront===!0;(h!==u?h:h?d!==a?d:c.radiusRad<r:l<s)&&(n=c.key,s=l,r=c.radiusRad,a=d)}return n}pickInterpretationBodyAt(t,e){const i=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=B9*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?lt.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const u=new Ke,d=new R;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new R).length()/2,m=d.clone().sub(s),g=m.length();if(g===0||m.dot(n)<=0||c!==void 0&&c<g-p)continue;const M=Math.acos(Math.min(1,m.normalize().dot(n))),v=Math.atan(p/g);if(v>r){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||c!==void 0&&c<x.distance)continue}else if(M>r)continue;v<h&&(h=v,l=f.name.slice(5))}return l}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(o0*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const c=a.direction.dot(i);c>r&&(r=c,s={star:a.star,altitudeDeg:a.altitudeDeg})}return s&&this.groundHides(t,e)?void 0:s}groundHides(t,e){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,1/0,r0)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let a=0;a<8;a++){const c=this.bodyCornerScratch.set(a&1?e.max.x:e.min.x,a&2?e.max.y:e.min.y,a&4?e.max.z:e.min.z),l=this.screenPointOf(c.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),s=Math.max(s,l.ndcX),n=Math.min(n,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new Ke;bodyCornerScratch=new R;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;const i=this.bodyBoxScratch.setFromObject(e);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-1/0;for(let c=0;c<8;c++){const l=this.bodyCornerScratch.set(c&1?i.max.x:i.min.x,c&2?i.max.y:i.min.y,c&4?i.max.z:i.min.z),h=this.screenPointOf(l.sub(this.camera.position).normalize());if(!h)return;n=Math.min(n,h.ndcX),r=Math.max(r,h.ndcX),s=Math.min(s,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:n,minY:s,maxX:r,maxY:a}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,i,n=0){const s=this.decorGroups.get(t);if(!s)return;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(s.position.y+n)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(t){const e=this.decorGroups.get(t);return e?Math.hypot(e.position.x-this.camera.position.x,e.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(t){const e=this.decorGroups.get(t);return e?e.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Je/2):0}decorGrabHeightAt(t,e,i){const n=this.decorGroups.get(t);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.decorHitScratch.set(this.camera.position.x-n.position.x,0,this.camera.position.z-n.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,n.position),c=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return c?Math.min(Math.max(c.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new yr;decorHitScratch=new R;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&(s.transparent&&s.opacity<lt.SEE_THROUGH_BELOW||s instanceof $a))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=lt.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray;i.group.updateMatrixWorld();const s=new Xc().copy(n).applyMatrix4(new Vt().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(d,f)=>{const p=new R(d,0,f).applyMatrix4(r);return this.groundYUnder(p.x,p.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,lt.RAILWAY_PICK_ABOVE_M))return;const c=lt.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-lt.RAILWAY_GROUND_MARGIN_M,r0))return;const l=i.group.worldToLocal(c.point.clone()),h=i.lineAt(l.x,l.z);if(!h)return;const u=i.contactHeightM(h);return{line:h,distanceM:c.distance,...u!==void 0?{contactM:u}:{}}}pickSkyEventAt(t,e,i=()=>!0){const n=[...this.skyEventLayers.values()].filter(l=>l.simulation?.pick&&l.simulation.drawnCount>0&&i(l.kind,l.simulation));if(n.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray,r={toleranceRad:lt.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(o0*this.camera.fov*Math.PI/180),skyLightTowards:l=>this.skyLightTowards(l)};let a;for(const l of n){const h=l.simulation.pick(s.origin,s.direction,r);h&&(!a||(h.distanceM??1/0)<(a.distanceM??1/0))&&(a={kind:l.kind.key,...h})}if(!a)return;if(a.distanceM===void 0)return this.groundHides(t,e)?void 0:a;if(this.terrainMesh&&this.groundBlocks(s.origin,s.direction,a.distanceM-1,r0))return;const c=lt.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(c&&c.distance<a.distanceM))return a}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(t.x,t.y,t.z)||1,s=Math.max(0,Math.min(1,t.y/n));return i(e.horizon)+(i(e.zenith)-i(e.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0;for(const t of this.skyEventLayers.values())t.simulation?.dispose();this.skyEventLayers.clear(),this.skyEventsStated=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())ut.dispose(t);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new R;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<lt.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new rn(s0,32,16),i=e.attributes.position,n=e.getAttribute("color")??new fe(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=PE(i.getX(r),i.getY(r),i.getZ(r)),l=oP(a,c,t.azimuthDeg,t.altitudeDeg);n.setXYZ(r,l[0],l[1],l[2])}if(n.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",n);const s=new ps({vertexColors:!0,side:Ci,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new vt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=sS(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new lv(this.groundRadius,48),i=new or({color:new rt(Ag,Ag,Ag),fog:!0});Oc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new vt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(e?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=yi(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,e);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-Oe.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*$9);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Oe.iceAlphaAt(i,l0,r,this.cloudFieldOffset)*K9),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<C0){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:c}=yi(e.altitudeDeg,e.azimuthDeg,as),l=this.cloudTransmission(e),h=this.arrivingIlluminance(e,s,l),u=lt.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/as)**2,p=[0,1,2].map(g=>u[g]*h[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const m=p.map(g=>Math.min(lt.BRIGHTEST_RELATIVE,g));d instanceof vt||(this.disposeMesh(d),d=new vt(new rn(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(m[0],m[1],m[2]),d.scale.setScalar(i)}else{if(!(d instanceof Bs)){this.disposeMesh(d);const m=new ye;m.setAttribute("position",new Me(new Float32Array(3),3)),m.setAttribute("color",new Me(new Float32Array(3),3)),d=new Bs(m,Ht.material(yh[yh.length-1].size,!1)),Ht.track(d),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)}const f=d.geometry.getAttribute("color"),p=t.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*h[0]*p,u[1]*h[1]*p,u[2]*h[2]*p),f.needsUpdate=!0}if(d.position.set(r,a,c),this.setHitArea(t,r,a,c,i),t==="sun"&&(this.sunArriving=h),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,r,a,c,h,i/as*(180/Math.PI),lt.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,a*f+this.celestialGroup.position.y,c*f),this.lensFlare||(this.lensFlare=n8(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(t,e){const i="moon";if(t.magnitude>e||t.altitudeDeg<C0){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=yi(t.altitudeDeg,t.azimuthDeg,as),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),l=t.radiusDeg??jr.MEAN_RADIUS_DEG,h=as*Math.tan(l*Je),u=Math.max(zr(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/as)**2,d=new rt(...c.map(m=>Math.min(lt.BRIGHTEST_RELATIVE,m/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(zr(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof eu?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=CS(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new eu(new b0({map:CS(t.phase),color:d,fog:!1,blending:En,depthWrite:!1})),p.userData.phaseKey=f,this.celestialGroup.add(p),this.bodyMeshes.set(i,p)),p.scale.set(h*2,h*2,1),p.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,c,l)}bentLight(t,e,i=X9){const[n,s,r]=this.arrivingIlluminance(t,e,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(t,e){return lt.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new rt;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Ht.CONE_SOLID_ANGLE/e)}pointScratch=new tt;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),s=ke.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Ts.luminanceOf([t.r,t.g,t.b]);return e>0?[t.r/e,t.g/e,t.b/e]:[1,1,1]}setHitArea(t,e,i,n,s){let r=this.hitAreas.get(t);if(!r){const c=new b0({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new eu(c),this.celestialGroup.add(r),this.hitAreas.set(t,r)}r.position.set(e,i,n);const a=s*2;r.scale.set(a,a,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,i,n,s,r,a=0){if(vn.radiusDeg(vn.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new vn(`veil:${t}`),this.celestialGroup.add(c.mesh),this.glareSprites.set(t,c)),c.shine({x:e,y:i,z:n},s,r,a)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const i=t&&`comet:${t.id}`;if(!t||!i||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=ql(t.magnitude,e),s=tg(n);this.cometKey=i,this.setBodyMesh(i,t.position,Ig*(.5+.5*n),new rt(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new Fs(as),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Gi,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const i=this.highCloudCover(),n=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(n?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),i===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:l0},0);return}const s=this.lowerCloudCover(),r=we.deckLitUntilDeg(we.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?de.SUN_MAGNITUDE:e.magnitude),l=we.strength(i,s,a.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=yi(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},a.altitudeDeg,l,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??l0},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??HA,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new Ec,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=t.altitudeDeg>0,s=n?t:e,r=this.lowerCloudCover(),a=this.bentLight(s,n?de.SUN_MAGNITUDE:e.magnitude,Y9),c=Us.strength(i,r,s.altitudeDeg)*a.scale;if(c<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:l,y:h,z:u}=yi(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},c,a.tint,n)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new So,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=gr.galactic(i,n),r=lt.directionOf(s.centre),a=lt.directionOf(s.rotation),c=lt.directionOf(s.pole),l=new ue().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),h=lt.directionOf(gr.eclipticPole(i,n)),u=lt.directionOf(t.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:lt.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new R(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=yi(t.altitudeDeg,t.azimuthDeg,1);return new R(e,i,n).normalize()}buildNovae(t,e){const i=new Set;for(const n of t){if(n.magnitude>e)continue;const s=`nova:${n.id}`;i.add(s);const r=ql(n.magnitude,e),a=tg(r);this.setBodyMesh(s,n.position,Ig*(.5+.5*r),new rt(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of t){if(n.magnitude>e)continue;i.add(n.body);const s=ql(n.magnitude,e),r=tg(s),a=_N[n.body]??new rt(1,1,1),c=new rt(a.r*r,a.g*r,a.b*r),l=Ig*(.5+.5*s);this.setBodyMesh(n.body,n.position,l,c,n.magnitude)}for(const n of[...this.bodyMeshes.keys()])i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n))}buildStars(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=t,r=new xr(n,s),a=zg(1337),c=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(d<aS)continue;const{x:p,y:m,z:g}=yi(d,f,_g);c.push({x:p,y:m,z:g,brightness:ql(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(M=>M*ke.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of PO){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<aS)continue;const{x:f,y:p,z:m}=yi(u,d,_g);this.namedStars.push({star:h,direction:new R(f,p,m).normalize(),altitudeDeg:u})}this.starTiers=yh.map((h,u)=>{const d=c.filter(w=>xv(w.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),m=new Float32Array(d.length*3),g=new Float32Array(d.length),M=new Float32Array(d.length);d.forEach((w,b)=>{f[b*3]=w.x,f[b*3+1]=w.y,f[b*3+2]=w.z,p[b]=w.brightness,m.set(w.illuminance,b*3),g[b]=w.phase,M[b]=w.speedFactor});const v=new ye;v.setAttribute("position",new Me(f,3)),v.setAttribute("seed",new Me(g.map(w=>w/(2*Math.PI)),1));const x=new Me(new Float32Array(d.length*3),3);v.setAttribute("color",x);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=v):(y=new Bs(v,Ht.material(h.size)),Ht.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:x,brightness:p,illuminance:m,phase:g,speedFactor:M}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Ht.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;for(const i of this.starTiers){const n=i.colorAttribute.array;for(let s=0;s<i.brightness.length;s++)n[s*3]=i.illuminance[s*3]*e,n[s*3+1]=i.illuminance[s*3+1]*e,n[s*3+2]=i.illuminance[s*3+2]*e;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new vh(this.celestialGroup,Dg,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new rt(cc[0]+(Og[0]-cc[0])*e,cc[1]+(Og[1]-cc[1])*e,cc[2]+(Og[2]-cc[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=K1(i,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=n,this.cloudUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=q1(Dg);this.cloudMesh=new vt(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:i}=K1(new rt(...cc),t,l0,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new vt(q1(Dg*1.04),e),this.cirrusMesh.renderOrder=mS-1,this.celestialGroup.add(this.cirrusMesh)}disposeCirrus(){this.cirrusMesh&&(this.cirrusMesh.removeFromParent(),this.cirrusMesh.geometry.dispose()),this.cirrusMaterial?.dispose(),this.cirrusMesh=void 0,this.cirrusMaterial=void 0,this.cirrusUniforms=void 0}syncCloudLayer(){this.layeredClouds?.update(this.weather,this.observerElevationM+1.6);const t=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(t)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,t)}faceCloudDeck(t,e){const i=e<0;t.scale.y=i?-1:1,t.renderOrder=i?vh.deckOrder(!0,0,1):mS}cloudLayerOffset(){const e=((this.weather.cloudBaseM??UM)-this.observerElevationM)*Cg;return Math.sign(e||1)*Math.max(Math.abs(e),cN)}updateCloudLighting(t,e){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,a]=this.cloudBeam.map(u=>u/Math.PI),c=this.lightningLevel*Fg*this.relativeScale/Math.PI,l=new rt(e[0]+Nr.r*c,e[1]+Nr.g*c,e[2]+Nr.b*c);this.layeredClouds?.setLighting(n.clone(),new rt(s,r,a),l,l);const h=Math.max(0,n.y);for(const u of i)u.sunDir.value.copy(n),u.sunColor.value.setRGB(s*h,r*h,a*h),u.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return gN(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,kg],[this.rainSplashSystem?.points,lc],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:Ng[this.weather.precipitationType].poolSize]];for(const[e,i]of t)e&&i!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=yS(Ug(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const t=this.weather.precipitationType;if(t==="none")return;if(t==="rain"){this.buildRain();return}const e=Ng[t],i=e.poolSize,n=zg(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),c=new Float32Array(i),l=new Float32Array(i),h=new Float32Array(i),u=new Float32Array(i),d=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let x=0;x<i;x++){const y=n()*Math.PI*2,w=n()*e.radiusM;s[x*3]=Math.cos(y)*w,s[x*3+1]=Ul+n()*(e.topYM-Ul),s[x*3+2]=Math.sin(y)*w,r[x]=n()*Math.PI*2,a[x]=.7+n()*.6,c[x]=.6+n()*.8,l[x]=.4+n()*1.2}const m=new ye;m.setAttribute("position",new Me(s,3)),m.setDrawRange(0,this.precipitationCount(i));const g={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new rt(...this.baseFogColor)},uTexture:{value:TN(t)},uNearFocusDistance:{value:bS},uHazeDistance:{value:e.radiusM*ES}},M=new Te({uniforms:g,vertexShader:ON,fragmentShader:NN,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const v=new Bs(m,M);v.renderOrder=Pg,this.scene.add(v),this.precipitationPoints=v,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const i=this.weather.precipitationType;if(i==="none"||i==="rain")return;const n=Ng[i];if(this.precipitationUniforms?.uColor.value.copy(lt.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*Je,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,c=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,m=this.precipitationBounceDuration,g=this.precipitationBounceVelX,M=this.precipitationBounceVelZ,v=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&m&&g&&M;for(let y=0,w=0;y<c.length;y+=3,w++){if(x&&f[w]>0){if(f[w]-=e,f[w]<=0){const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(S)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(S)*A,f[w]=0}else{const S=1-f[w]/m[w];c[y+1]=Ul+Math.sin(Math.PI*S)*p[w],c[y]=u0(c[y]+(r+g[w])*e,n.radiusM),c[y+2]=u0(c[y+2]+(a+M[w])*e,n.radiusM)}continue}let b=0,E=0;if(v){const S=vN*u[w],A=yN*d[w];b=Math.sin(t*S*Math.PI*2+l[w])*A,E=Math.sin(t*S*Math.PI*2+l[w]+Math.PI/2)*A}if(c[y]+=(r+b)*e,c[y+1]-=n.fallSpeedMPerS*h[w]*e,c[y+2]+=(a+E)*e,c[y]=u0(c[y],n.radiusM),c[y+2]=u0(c[y+2],n.radiusM),c[y+1]<Ul){if(x){p[w]=IS*(.2+Math.random()*1.6),m[w]=xN*(.5+Math.random()),f[w]=m[w];const _=Math.random()*Math.PI*2,I=wN*(p[w]/IS);g[w]=Math.cos(_)*I,M[w]=Math.sin(_)*I,c[y+1]=Ul;continue}const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(S)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(S)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=Ug(this.weather.precipitationIntensity);this.rainSystem=t8({count:kg,radiusM:wu,heightM:hN,bottomYM:gS,overallSpeed:uN,color:vS.clone(),opacity:.85,visibleCount:this.precipitationCount(kg),speedStreak:yS(t),pixelSize:_S,seed:9001,nearFocusDistanceM:bS,hazeDistanceM:wu*ES,hazeColor:new rt(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=Pg,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=zg(4242),e=new Float32Array(lc*3),i=new Float32Array(lc),n=new Float32Array(lc),s=new Float32Array(lc);for(let h=0;h<lc;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*wu;e[h*3]=Math.cos(u)*d,e[h*3+1]=gS,e[h*3+2]=Math.sin(u)*d,n[h]=DS(xS,wS),i[h]=t()*n[h],s[h]=i[h]/n[h]}const r=new ye;r.setAttribute("position",new Me(e,3));const a=new Me(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(lc));const c=new Te({uniforms:{uMaxSize:{value:mN},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:SS.clone()},uTexture:{value:DN()}},vertexShader:CN,fragmentShader:PN,transparent:!0,depthWrite:!1}),l=new Bs(r,c);l.renderOrder=Pg,this.scene.add(l),this.rainSplashSystem={points:l,positions:e,life:i,duration:n,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*Je;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-Ug(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(lt.litBySky(vS,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(lt.litBySky(SS,this.baseFogColor));const n=this.weather.windDirectionDeg*Je,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=wu,c=h=>(h%(a*2)+a*3)%(a*2)-a;e.uniforms.uWindOffset.value.set(c(e.uniforms.uWindOffset.value.x+s*t),c(e.uniforms.uWindOffset.value.y+r*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=TS+(1-TS)*(1-l),u=RS+(1-RS)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=_S*h*(.5+.5*u)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=e,a=r.array;for(let c=0,l=0;c<i.length;c+=3,l++){if(n[l]+=t,n[l]>=s[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*wu;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=DS(xS,wS),n[l]=0}a[l]=n[l]/s[l]}e.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,i=0;if(this.lightningArmed)for(const c of this.lightningFlashes){if(c.t>t)break;const l=mn.brightnessAt(c,t);l>i&&(e=c,i=l)}const n=e?Math.min(1,Math.max(.1,(EN/e.distanceM)**2)):0,s=i*n*(e?.cloudToGround?1:.6);if(s===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const c=this.scene.fog,l=s*Fg*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+Nr.r*l,this.airlight[1]+Nr.g*l,this.airlight[2]+Nr.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*AN;r.setRGB(1+c*Nr.r,1+c*Nr.g,1+c*Nr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*Fg*this.relativeScale,e){const{x:c,y:l,z:h}=yi(25,e.azimuthDeg,as);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new bo(as*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=nN.map(t=>{const e=Pc.point(t,this.compassPoints),i=new b0({map:LN(e),depthTest:!1,fog:!1}),n=new eu(i),{x:s,y:r,z:a}=yi(0,t,hS);return n.position.set(s,r,a),n.scale.set(h0,h0,1),n.renderOrder=aN,n.layers.set(Eg),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=uS*Math.PI/360,i=h0*Math.tan(t)/Math.tan(e);for(const n of this.compassSprites)n.scale.set(i,i,1)}disposeCompassLabels(){for(const t of this.compassSprites)t.removeFromParent(),t.material.map?.dispose(),t.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const t of this.starTiers)this.disposeMesh(t.points);this.starTiers=[]}disposeMesh(t){if(!t)return;t.removeFromParent(),"geometry"in t&&t.geometry.dispose();const e=t.material;for(const i of Array.isArray(e)?e:[e]){const n=i.map;n&&n.dispose(),i.dispose()}}}const Je=Math.PI/180;function zr(o,t,e){return Math.max(t,Math.min(e,o))}function DS(o,t){return o+Math.random()*(t-o)}function u0(o,t){return(o%(t*2)+t*3)%(t*2)-t}let d0,f0;function TN(o){switch(o){case"snow":return RN();case"hail":return IN()}}function RN(){if(d0)return d0;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),d0=new Jo(t),d0}function IN(){if(f0)return f0;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),f0=new Jo(t),f0}let p0;function DN(){if(p0)return p0;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),p0=new Jo(t),p0}const CN=`
8596
+ `,transparent:!0,blending:En,depthWrite:!1,side:Ci,fog:!1});this.object=new vt(new rn(Ov.RADIUS,128,32,0,Math.PI*2,0,ke.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<ke.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=Nn.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=Nn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class up{constructor(t){this.generator=t}static SIZE=128;target=new Pd(up.SIZE,{type:We,generateMipmaps:!0,minFilter:Vs,magFilter:ge});camera=new Mv(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,i,n=[]){const s=t.shadowMap.autoUpdate;let r=!1;e.traverse(c=>{const l=c;l.isLight&&l.castShadow&&l.shadow&&!l.shadow.map&&(r=!0)}),t.shadowMap.autoUpdate=r?s:!1;const a=n.map(c=>c.visible);for(const c of n)c.visible=!1;this.camera.position.copy(i),this.camera.update(t,e),n.forEach((c,l)=>{c.visible=a[l]}),t.shadowMap.autoUpdate=s,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class Zn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){Zn.install(),this.generator=new W1(t),this.eye=new up(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],l,h=Zn.REFRESH_MS){for(const g of[...this.probes.keys()])n.some(M=>M.id===g&&M.shiny)||(this.probes.get(g).dispose(),this.probes.delete(g));const u=[{probe:this.eye}];for(const g of n){if(!g.shiny)continue;let M=this.probes.get(g.id);M||(M=new up(this.generator),this.probes.set(g.id,M)),u.push({probe:M,reflector:g})}const d=performance.now(),f=()=>u.filter(({probe:g})=>g.capturedVersion!==a),p=f().filter(({probe:g})=>d-g.capturedAtMs>=h);if(p.length>0){const g=p.reduce((M,v)=>v.probe.capturedAtMs<M.probe.capturedAtMs?v:M);if(g.reflector){const M=g.reflector.holder.getWorldPosition(this.scratch);g.probe.capture(t,e,M,[g.reflector.holder,...s]),Zn.reflectOn(g.reflector.holder,g.probe)}else{g.probe.capture(t,e,i,[...s,...c]),l?.(g.probe.sharp),Zn.decor=g.probe.filtered;for(const M of r)Zn.reflectOn(M,g.probe);for(const M of n)M.shiny||Zn.reflectOn(M.holder,g.probe)}g.probe.capturedVersion=a}const m=f();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:g})=>h-(d-g.capturedAtMs))))}scratch=new R;static reflectOn(t,e={filtered:Zn.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof $a?e.sharp&&s.setSurroundings(e.sharp):s instanceof Ro&&e.filtered&&s.envMap!==e.filtered&&(s.envMap=e.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(Zn.installed)return;Zn.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!he.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}he.lights_fragment_maps=he.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const gA=0,z8=1,B8=2,zw=2,dg=1.25,Bw=1,ts=32,wn=ts/4,MA=65535,I0=Math.pow(2,-24),Nv=Symbol("SKIP_GENERATION"),vA={strategy:gA,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Nv]:!1};function Wi(o,t,e){return e.min.x=t[o],e.min.y=t[o+1],e.min.z=t[o+2],e.max.x=t[o+3],e.max.y=t[o+4],e.max.z=t[o+5],e}function AM(o){let t=-1,e=-1/0;for(let i=0;i<3;i++){const n=o[i+3]-o[i];n>e&&(e=n,t=i)}return t}function Hw(o,t){t.set(o)}function Gw(o,t,e){let i,n;for(let s=0;s<3;s++){const r=s+3;i=o[s],n=t[s],e[s]=i<n?i:n,i=o[r],n=t[r],e[r]=i>n?i:n}}function Vf(o,t,e){for(let i=0;i<3;i++){const n=t[o+2*i],s=t[o+2*i+1],r=n-s,a=n+s;r<e[i]&&(e[i]=r),a>e[i+3]&&(e[i+3]=a)}}function fu(o){const t=o[3]-o[0],e=o[4]-o[1],i=o[5]-o[2];return 2*(t*e+e*i+i*t)}function nn(o,t){return t[o+15]===MA}function Ln(o,t){return t[o+6]}function es(o,t){return t[o+14]}function Sn(o){return o+wn}function bn(o,t){const e=t[o+6];return o+e*wn}function Lv(o,t){return t[o+7]}function fg(o,t,e,i,n){let s=1/0,r=1/0,a=1/0,c=-1/0,l=-1/0,h=-1/0,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,g=-1/0;const M=o.offset||0;for(let v=(t-M)*6,x=(t+e-M)*6;v<x;v+=6){const y=o[v+0],w=o[v+1],b=y-w,E=y+w;b<s&&(s=b),E>c&&(c=E),y<u&&(u=y),y>p&&(p=y);const S=o[v+2],A=o[v+3],_=S-A,I=S+A;_<r&&(r=_),I>l&&(l=I),S<d&&(d=S),S>m&&(m=S);const D=o[v+4],P=o[v+5],L=D-P,O=D+P;L<a&&(a=L),O>h&&(h=O),D<f&&(f=D),D>g&&(g=D)}i[0]=s,i[1]=r,i[2]=a,i[3]=c,i[4]=l,i[5]=h,n[0]=u,n[1]=d,n[2]=f,n[3]=p,n[4]=m,n[5]=g}const Pa=32,H8=(o,t)=>o.candidate-t.candidate,po=new Array(Pa).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Wf=new Float32Array(6);function G8(o,t,e,i,n,s){let r=-1,a=0;if(s===gA)r=AM(t),r!==-1&&(a=(t[r]+t[r+3])/2);else if(s===z8)r=AM(o),r!==-1&&(a=V8(e,i,n,r));else if(s===B8){const c=fu(o);let l=dg*n;const h=e.offset||0,u=(i-h)*6,d=(i+n-h)*6;for(let f=0;f<3;f++){const p=t[f],M=(t[f+3]-p)/Pa;if(n<Pa/4){const v=[...po];v.length=n;let x=0;for(let w=u;w<d;w+=6,x++){const b=v[x];b.candidate=e[w+2*f],b.count=0;const{bounds:E,leftCacheBounds:S,rightCacheBounds:A}=b;for(let _=0;_<3;_++)A[_]=1/0,A[_+3]=-1/0,S[_]=1/0,S[_+3]=-1/0,E[_]=1/0,E[_+3]=-1/0;Vf(w,e,E)}v.sort(H8);let y=n;for(let w=0;w<y;w++){const b=v[w];for(;w+1<y&&v[w+1].candidate===b.candidate;)v.splice(w+1,1),y--}for(let w=u;w<d;w+=6){const b=e[w+2*f];for(let E=0;E<y;E++){const S=v[E];b>=S.candidate?Vf(w,e,S.rightCacheBounds):(Vf(w,e,S.leftCacheBounds),S.count++)}}for(let w=0;w<y;w++){const b=v[w],E=b.count,S=n-b.count,A=b.leftCacheBounds,_=b.rightCacheBounds;let I=0;E!==0&&(I=fu(A)/c);let D=0;S!==0&&(D=fu(_)/c);const P=Bw+dg*(I*E+D*S);P<l&&(r=f,l=P,a=b.candidate)}}else{for(let y=0;y<Pa;y++){const w=po[y];w.count=0,w.candidate=p+M+y*M;const b=w.bounds;for(let E=0;E<3;E++)b[E]=1/0,b[E+3]=-1/0}for(let y=u;y<d;y+=6){let E=~~((e[y+2*f]-p)/M);E>=Pa&&(E=Pa-1);const S=po[E];S.count++,Vf(y,e,S.bounds)}const v=po[Pa-1];Hw(v.bounds,v.rightCacheBounds);for(let y=Pa-2;y>=0;y--){const w=po[y],b=po[y+1];Gw(w.bounds,b.rightCacheBounds,w.rightCacheBounds)}let x=0;for(let y=0;y<Pa-1;y++){const w=po[y],b=w.count,E=w.bounds,A=po[y+1].rightCacheBounds;b!==0&&(x===0?Hw(E,Wf):Gw(E,Wf,Wf)),x+=b;let _=0,I=0;x!==0&&(_=fu(Wf)/c);const D=n-x;D!==0&&(I=fu(A)/c);const P=Bw+dg*(_*x+I*D);P<l&&(r=f,l=P,a=w.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${s} used.`);return{axis:r,pos:a}}function V8(o,t,e,i){let n=0;const s=o.offset;for(let r=t,a=t+e;r<a;r++)n+=o[(r-s)*6+i*2];return n/e}class pg{constructor(){this.boundingData=new Float32Array(6)}}function W8(o,t,e,i,n,s){let r=i,a=i+n-1;const c=s.pos,l=s.axis*2,h=e.offset||0;for(;;){for(;r<=a&&e[(r-h)*6+l]<c;)r++;for(;r<=a&&e[(a-h)*6+l]>=c;)a--;if(r<a){for(let u=0;u<t;u++){let d=o[r*t+u];o[r*t+u]=o[a*t+u],o[a*t+u]=d}for(let u=0;u<6;u++){const d=r-h,f=a-h,p=e[d*6+u];e[d*6+u]=e[f*6+u],e[f*6+u]=p}r++,a--}else return r}}let yA,D0,_M,xA;const X8=Math.pow(2,32);function TM(o){return"count"in o?1:1+TM(o.left)+TM(o.right)}function Y8(o,t,e){return yA=new Float32Array(e),D0=new Uint32Array(e),_M=new Uint16Array(e),xA=new Uint8Array(e),RM(o,t)}function RM(o,t){const e=o/4,i=o/2,n="count"in t,s=t.boundingData;for(let r=0;r<6;r++)yA[e+r]=s[r];if(n)return t.buffer?(xA.set(new Uint8Array(t.buffer),o),o+t.buffer.byteLength):(D0[e+6]=t.offset,_M[i+14]=t.count,_M[i+15]=MA,o+ts);{const{left:r,right:a,splitAxis:c}=t,l=o+ts;let h=RM(l,r);const u=o/ts,f=h/ts-u;if(f>X8)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return D0[e+6]=f,D0[e+7]=c,RM(h,a)}}function $8(o,t,e,i,n,s){const{maxDepth:r,verbose:a,targetLeafSize:c,_strictLeafSize:l=1/0,strategy:h,onProgress:u}=n,d=o.primitiveBuffer,f=o.primitiveBufferStride,p=new Float32Array(6);let m=!1;const g=new pg;return fg(t,e,i,g.boundingData,p),v(g,e,i,p),g;function M(x){u&&u((x-s.offset)/s.count)}function v(x,y,w,b=null,E=0){!m&&E>=r&&(m=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`));const S=w>l;if(w<=c&&!S||E>=r)return M(y+w),x.offset=y,x.count=w,x;const A=G8(x.boundingData,b,t,y,w,h);let _=A.axis===-1?-1:W8(d,f,t,y,w,A);if(A.axis===-1||_===y||_===y+w){if(!S)return M(y+w),x.offset=y,x.count=w,x;A.axis=Math.max(0,AM(x.boundingData)),_=y+Math.max(1,Math.floor(w/2))}x.splitAxis=A.axis;const I=new pg,D=y,P=_-y;x.left=I,fg(t,D,P,I.boundingData,p),v(I,D,P,p,E+1);const L=new pg,O=_,k=w-P;return x.right=L,fg(t,O,k,L.boundingData,p),v(L,O,k,p,E+1),x}}function K8(o,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=o.getRootRanges(t.range),n=i[0],s=i[i.length-1],r={offset:n.offset,count:s.offset+s.count-n.offset},a=new Float32Array(6*r.count);a.offset=r.offset,o.computePrimitiveBounds(r.offset,r.count,a),o._roots=i.map(c=>{const l=$8(o,a,c.offset,c.count,t,r),h=TM(l),u=new e(ts*h);return Y8(0,l,u),u})}class kv{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class q8{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const Oi=new q8;let Ho,nh;const El=[],Xf=new kv(()=>new Ke);function Z8(o,t,e,i,n,s){Ho=Xf.getPrimitive(),nh=Xf.getPrimitive(),El.push(Ho,nh),Oi.setBuffer(o._roots[t]);const r=IM(0,o.geometry,e,i,n,s);Oi.clearBuffer(),Xf.releasePrimitive(Ho),Xf.releasePrimitive(nh),El.pop(),El.pop();const a=El.length;return a>0&&(nh=El[a-1],Ho=El[a-2]),r}function IM(o,t,e,i,n=null,s=0,r=0){const{float32Array:a,uint16Array:c,uint32Array:l}=Oi;let h=o*2;if(nn(h,c)){const d=Ln(o,l),f=es(h,c);return Wi(o,a,Ho),i(d,f,!1,r,s+o/wn,Ho)}else{let _=function(D){const{uint16Array:P,uint32Array:L}=Oi;let O=D*2;for(;!nn(O,P);)D=Sn(D),O=D*2;return Ln(D,L)},I=function(D){const{uint16Array:P,uint32Array:L}=Oi;let O=D*2;for(;!nn(O,P);)D=bn(D,L),O=D*2;return Ln(D,L)+es(O,P)};const d=Sn(o),f=bn(o,l);let p=d,m=f,g,M,v,x;if(n&&(v=Ho,x=nh,Wi(p,a,v),Wi(m,a,x),g=n(v),M=n(x),M<g)){p=f,m=d;const D=g;g=M,M=D,v=x}v||(v=Ho,Wi(p,a,v));const y=nn(p*2,c),w=e(v,y,g,r+1,s+p/wn);let b;if(w===zw){const D=_(p),L=I(p)-D;b=i(D,L,!0,r+1,s+p/wn,v)}else b=w&&IM(p,t,e,i,n,s,r+1);if(b)return!0;x=nh,Wi(m,a,x);const E=nn(m*2,c),S=e(x,E,M,r+1,s+m/wn);let A;if(S===zw){const D=_(m),L=I(m)-D;A=i(D,L,!0,r+1,s+m/wn,x)}else A=S&&IM(m,t,e,i,n,s,r+1);return!!A}}const Yu=new Oi.constructor,dp=new Oi.constructor,Eo=new kv(()=>new Ke),Al=new Ke,_l=new Ke,mg=new Ke,gg=new Ke;let Mg=!1;function J8(o,t,e,i){if(Mg)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Mg=!0;const n=o._roots,s=t._roots;let r,a=0,c=0;const l=new Vt().copy(e).invert();for(let h=0,u=n.length;h<u;h++){Yu.setBuffer(n[h]),c=0;const d=Eo.getPrimitive();Wi(0,Yu.float32Array,d),d.applyMatrix4(l);for(let f=0,p=s.length;f<p&&(dp.setBuffer(s[f]),r=ur(0,0,e,l,i,a,c,0,0,d),dp.clearBuffer(),c+=s[f].byteLength/ts,!r);f++);if(Eo.releasePrimitive(d),Yu.clearBuffer(),a+=n[h].byteLength/ts,r)break}return Mg=!1,r}function ur(o,t,e,i,n,s=0,r=0,a=0,c=0,l=null,h=!1){let u,d;h?(u=dp,d=Yu):(u=Yu,d=dp);const f=u.float32Array,p=u.uint32Array,m=u.uint16Array,g=d.float32Array,M=d.uint32Array,v=d.uint16Array,x=o*2,y=t*2,w=nn(x,m),b=nn(y,v);let E=!1;if(b&&w)h?E=n(Ln(t,M),es(t*2,v),Ln(o,p),es(o*2,m),c,r+t/wn,a,s+o/wn):E=n(Ln(o,p),es(o*2,m),Ln(t,M),es(t*2,v),a,s+o/wn,c,r+t/wn);else if(b){const S=Eo.getPrimitive();Wi(t,g,S),S.applyMatrix4(e);const A=Sn(o),_=bn(o,p);Wi(A,f,Al),Wi(_,f,_l);const I=S.intersectsBox(Al),D=S.intersectsBox(_l);E=I&&ur(t,A,i,e,n,r,s,c,a+1,S,!h)||D&&ur(t,_,i,e,n,r,s,c,a+1,S,!h),Eo.releasePrimitive(S)}else{const S=Sn(t),A=bn(t,M);Wi(S,g,mg),Wi(A,g,gg);const _=l.intersectsBox(mg),I=l.intersectsBox(gg);if(_&&I)E=ur(o,S,e,i,n,s,r,a,c+1,l,h)||ur(o,A,e,i,n,s,r,a,c+1,l,h);else if(_)if(w)E=ur(o,S,e,i,n,s,r,a,c+1,l,h);else{const D=Eo.getPrimitive();D.copy(mg).applyMatrix4(e);const P=Sn(o),L=bn(o,p);Wi(P,f,Al),Wi(L,f,_l);const O=D.intersectsBox(Al),k=D.intersectsBox(_l);E=O&&ur(S,P,i,e,n,r,s,c,a+1,D,!h)||k&&ur(S,L,i,e,n,r,s,c,a+1,D,!h),Eo.releasePrimitive(D)}else if(I)if(w)E=ur(o,A,e,i,n,s,r,a,c+1,l,h);else{const D=Eo.getPrimitive();D.copy(gg).applyMatrix4(e);const P=Sn(o),L=bn(o,p);Wi(P,f,Al),Wi(L,f,_l);const O=D.intersectsBox(Al),k=D.intersectsBox(_l);E=O&&ur(A,P,i,e,n,r,s,c,a+1,D,!h)||k&&ur(A,L,i,e,n,r,s,c,a+1,D,!h),Eo.releasePrimitive(D)}}return E}const vg=new class{constructor(){let o=null,t=null,e=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(s,r)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=r,this.buffer=o=s._roots[r],this.uint16Array=e=new Uint16Array(o),this.uint32Array=t=new Uint32Array(o)},this.reset=()=>{this.root=null,this.buffer=o=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=s=>{let r=s*2;for(;!nn(r,e);)s=Sn(s),r=s*2;return Ln(s,t)},this.getRangeEnd=s=>{let r=s*2;for(;!nn(r,e);)s=bn(s,t),r=s*2;return Ln(s,t)+es(r,e)};const n=(s,r,a)=>{const c=r*2,l=nn(c,e);if(!s(a,l,r)&&!l){const u=Sn(r),d=bn(r,t);n(s,u,a+1),n(s,d,a+1)}};this.traverseBuffer=s=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{n(s,0,0)}finally{i=!1}},this.traverse=s=>{this.traverseBuffer((r,a,c)=>{if(a){const l=c*2,h=t[c+6],u=e[l+14];return s(r,a,new Float32Array(o,c*4,6),h,u)}else{const l=Lv(c,t);return s(r,a,new Float32Array(o,c*4,6),l)}})}}},Vw=new Ke,Tl=new Float32Array(6);class j8{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...vA,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),K8(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,n){let s=1/0,r=1/0,a=1/0,c=-1/0,l=-1/0,h=-1/0;for(let u=t,d=t+e;u<d;u++){this.writePrimitiveBounds(u,Tl,0);const[f,p,m,g,M,v]=Tl;f<s&&(s=f),g>c&&(c=g),p<r&&(r=p),M>l&&(l=M),m<a&&(a=m),v>h&&(h=v)}return i[n+0]=s,i[n+1]=r,i[n+2]=a,i[n+3]=c,i[n+4]=l,i[n+5]=h,i}computePrimitiveBounds(t,e,i){const n=i.offset||0;for(let s=t,r=t+e;s<r;s++){this.writePrimitiveBounds(s,Tl,0);const[a,c,l,h,u,d]=Tl,f=(a+h)/2,p=(c+u)/2,m=(l+d)/2,g=(h-a)/2,M=(u-c)/2,v=(d-l)/2,x=(s-n)*6;i[x+0]=f,i[x+1]=g+(Math.abs(f)+g)*I0,i[x+2]=p,i[x+3]=M+(Math.abs(p)+M)*I0,i[x+4]=m,i[x+5]=v+(Math.abs(m)+v)*I0}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,n=e.length;i<n;i++)e[i]+=t;else{const i=this._roots;for(let n=0;n<i.length;n++){const s=i[n],r=new Uint32Array(s),a=new Uint16Array(s),c=s.byteLength/ts;for(let l=0;l<c;l++){const h=wn*l,u=2*h;nn(u,a)&&(r[h+6]+=t)}}}}traverse(t,e=0){vg.setBVH(this,e),vg.traverse(t),vg.reset()}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const n=t[e],s=new Uint32Array(n),r=new Uint16Array(n),a=new Float32Array(n),c=n.byteLength/ts;for(let l=c-1;l>=0;l--){const h=l*wn,u=h*2;if(nn(u,r)){const f=Ln(h,s),p=es(u,r);this.writePrimitiveRangeBounds(f,p,Tl,0),a.set(Tl,h)}else{const f=Sn(h),p=bn(h,s);for(let m=0;m<3;m++){const g=a[f+m],M=a[f+m+3],v=a[p+m],x=a[p+m+3];a[h+m]=g<v?g:v,a[h+m+3]=M>x?M:x}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{Wi(0,new Float32Array(i),Vw),t.union(Vw)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:n,intersectsPrimitive:s,scratchPrimitive:r,iterate:a}=t;if(n&&s){const u=n;n=(d,f,p,m,g)=>u(d,f,p,m,g)?!0:a(d,f,this,s,p,m,r)}else n||(s?n=(u,d,f,p)=>a(u,d,this,s,f,p,r):n=(u,d,f)=>f);let c=!1,l=0;const h=this._roots;for(let u=0,d=h.length;u<d;u++){const f=h[u];if(c=Z8(this,u,i,n,e,l),c)break;l+=f.byteLength/ts}return c}bvhcast(t,e,i){let{intersectsRanges:n}=i;return J8(this,t,e,n)}}function Q8(){return typeof SharedArrayBuffer<"u"}function Uv(o){return o.index?o.index.count:o.attributes.position.count}function Hp(o){return Uv(o)/3}function t9(o,t=ArrayBuffer){return o>65535?new Uint32Array(new t(4*o)):new Uint16Array(new t(2*o))}function e9(o,t){if(!o.index){const e=o.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=t9(e,i);o.setIndex(new Me(n,1));for(let s=0;s<e;s++)n[s]=s}}function i9(o,t,e){const i=Uv(o)/e,n=t||o.drawRange,s=n.start/e,r=(n.start+n.count)/e,a=Math.max(0,s),c=Math.min(i,r)-a;return{offset:Math.floor(a),count:Math.floor(c)}}function n9(o,t){return o.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function Ww(o,t,e){const i=i9(o,t,e),n=n9(o,e);if(!n.length)return[i];const s=[],r=i.offset,a=i.offset+i.count,c=Uv(o)/e,l=[];for(const d of n){const{offset:f,count:p}=d,m=f,g=isFinite(p)?p:c-f,M=f+g;m<a&&M>r&&(l.push({pos:Math.max(r,m),isStart:!0}),l.push({pos:Math.min(a,M),isStart:!1}))}l.sort((d,f)=>d.pos!==f.pos?d.pos-f.pos:d.type==="end"?-1:1);let h=0,u=null;for(const d of l){const f=d.pos;h!==0&&f!==u&&s.push({offset:u,count:f-u}),h+=d.isStart?1:-1,u=f}return s}function s9(o,t){const e=o[o.length-1],i=e.offset+e.count>2**16,n=o.reduce((l,h)=>l+h.count,0),s=i?4:2,r=t?new SharedArrayBuffer(n*s):new ArrayBuffer(n*s),a=i?new Uint32Array(r):new Uint16Array(r);let c=0;for(let l=0;l<o.length;l++){const{offset:h,count:u}=o[l];for(let d=0;d<u;d++)a[c+d]=h+d;c+=u}return a}class r9 extends j8{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!Q8())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...vA,...e},e[Nv]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const n=Ww(e,t.range,i),s=s9(n,t.useSharedArrayBuffer);this._indirectBuffer=s}else e9(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new Ke))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Ww(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Ja{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,n=-1/0;for(let s=0,r=t.length;s<r;s++){const c=t[s][e];i=c<i?c:i,n=c>n?c:n}this.min=i,this.max=n}setFromPoints(t,e){let i=1/0,n=-1/0;for(let s=0,r=e.length;s<r;s++){const a=e[s],c=t.dot(a);i=c<i?c:i,n=c>n?c:n}this.min=i,this.max=n}isSeparated(t){return this.min>t.max||t.min>this.max}}Ja.prototype.setFromBox=(function(){const o=new R;return function(e,i){const n=i.min,s=i.max;let r=1/0,a=-1/0;for(let c=0;c<=1;c++)for(let l=0;l<=1;l++)for(let h=0;h<=1;h++){o.x=n.x*c+s.x*(1-c),o.y=n.y*l+s.y*(1-l),o.z=n.z*h+s.z*(1-h);const u=e.dot(o);r=Math.min(u,r),a=Math.max(u,a)}this.min=r,this.max=a}})();const a9=(function(){const o=new R,t=new R,e=new R;return function(n,s,r){const a=n.start,c=o,l=s.start,h=t;e.subVectors(a,l),o.subVectors(n.end,n.start),t.subVectors(s.end,s.start);const u=e.dot(h),d=h.dot(c),f=h.dot(h),p=e.dot(c),g=c.dot(c)*f-d*d;let M,v;g!==0?M=(u*d-p*f)/g:M=0,v=(u+M*d)/f,r.x=M,r.y=v}})(),Fv=(function(){const o=new tt,t=new R,e=new R;return function(n,s,r,a){a9(n,s,o);let c=o.x,l=o.y;if(c>=0&&c<=1&&l>=0&&l<=1){n.at(c,r),s.at(l,a);return}else if(c>=0&&c<=1){l<0?s.at(0,a):s.at(1,a),n.closestPointToPoint(a,!0,r);return}else if(l>=0&&l<=1){c<0?n.at(0,r):n.at(1,r),s.closestPointToPoint(r,!0,a);return}else{let h;c<0?h=n.start:h=n.end;let u;l<0?u=s.start:u=s.end;const d=t,f=e;if(n.closestPointToPoint(u,!0,t),s.closestPointToPoint(h,!0,e),d.distanceToSquared(u)<=f.distanceToSquared(h)){r.copy(d),a.copy(u);return}else{r.copy(h),a.copy(f);return}}}})(),o9=(function(){const o=new R,t=new R,e=new yr,i=new qa;return function(s,r){const{radius:a,center:c}=s,{a:l,b:h,c:u}=r;if(i.start=l,i.end=h,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a||(i.start=l,i.end=u,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a)||(i.start=h,i.end=u,i.closestPointToPoint(c,!0,o).distanceTo(c)<=a))return!0;const m=r.getPlane(e);if(Math.abs(m.distanceToPoint(c))<=a){const M=m.projectPoint(c,t);if(r.containsPoint(M))return!0}return!1}})(),c9=["x","y","z"],Na=1e-15,Xw=Na*Na;function qs(o){return Math.abs(o)<Na}class Ar extends On{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new R),this.satBounds=new Array(4).fill().map(()=>new Ja),this.points=[this.a,this.b,this.c],this.plane=new yr,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new qa,this.needsUpdate=!0}intersectsSphere(t){return o9(t,this)}update(){const t=this.a,e=this.b,i=this.c,n=this.points,s=this.satAxes,r=this.satBounds,a=s[0],c=r[0];this.getNormal(a),c.setFromPoints(a,n);const l=s[1],h=r[1];l.subVectors(t,e),h.setFromPoints(l,n);const u=s[2],d=r[2];u.subVectors(e,i),d.setFromPoints(u,n);const f=s[3],p=r[3];f.subVectors(i,t),p.setFromPoints(f,n);const m=l.length(),g=u.length(),M=f.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,m<Na?g<Na||M<Na?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):g<Na?M<Na?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):M<Na&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(a,t),this.needsUpdate=!1}}Ar.prototype.closestPointToSegment=(function(){const o=new R,t=new R,e=new qa;return function(n,s=null,r=null){const{start:a,end:c}=n,l=this.points;let h,u=1/0;for(let d=0;d<3;d++){const f=(d+1)%3;e.start.copy(l[d]),e.end.copy(l[f]),Fv(e,n,o,t),h=o.distanceToSquared(t),h<u&&(u=h,s&&s.copy(o),r&&r.copy(t))}return this.closestPointToPoint(a,o),h=a.distanceToSquared(o),h<u&&(u=h,s&&s.copy(o),r&&r.copy(a)),this.closestPointToPoint(c,o),h=c.distanceToSquared(o),h<u&&(u=h,s&&s.copy(o),r&&r.copy(c)),Math.sqrt(u)}})();Ar.prototype.intersectsTriangle=(function(){const o=new Ar,t=new Ja,e=new Ja,i=new R,n=new R,s=new R,r=new R,a=new qa,c=new qa,l=new R,h=new tt,u=new tt;function d(x,y,w,b){const E=i;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?E.copy(x.plane.normal):E.copy(y.plane.normal);const S=x.satBounds,A=x.satAxes;for(let D=1;D<4;D++){const P=S[D],L=A[D];if(t.setFromPoints(L,y.points),P.isSeparated(t)||(r.copy(E).cross(L),t.setFromPoints(r,x.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}const _=y.satBounds,I=y.satAxes;for(let D=1;D<4;D++){const P=_[D],L=I[D];if(t.setFromPoints(L,x.points),P.isSeparated(t)||(r.crossVectors(E,L),t.setFromPoints(r,x.points),e.setFromPoints(r,y.points),t.isSeparated(e)))return!1}return w&&(b||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),w.start.set(0,0,0),w.end.set(0,0,0)),!0}function f(x,y,w,b,E,S,A,_,I,D,P){let L=A/(A-_);D.x=b+(E-b)*L,P.start.subVectors(y,x).multiplyScalar(L).add(x),L=A/(A-I),D.y=b+(S-b)*L,P.end.subVectors(w,x).multiplyScalar(L).add(x)}function p(x,y,w,b,E,S,A,_,I,D,P){if(E>0)f(x.c,x.a,x.b,b,y,w,I,A,_,D,P);else if(S>0)f(x.b,x.a,x.c,w,y,b,_,A,I,D,P);else if(_*I>0||A!=0)f(x.a,x.b,x.c,y,w,b,A,_,I,D,P);else if(_!=0)f(x.b,x.a,x.c,w,y,b,_,A,I,D,P);else if(I!=0)f(x.c,x.a,x.b,b,y,w,I,A,_,D,P);else return!0;return!1}function m(x,y,w,b){const E=y.degenerateSegment,S=x.plane.distanceToPoint(E.start),A=x.plane.distanceToPoint(E.end);return qs(S)?qs(A)?d(x,y,w,b):(w&&(w.start.copy(E.start),w.end.copy(E.start)),x.containsPoint(E.start)):qs(A)?(w&&(w.start.copy(E.end),w.end.copy(E.end)),x.containsPoint(E.end)):x.plane.intersectLine(E,i)!=null?(w&&(w.start.copy(i),w.end.copy(i)),x.containsPoint(i)):!1}function g(x,y,w){const b=y.a;return qs(x.plane.distanceToPoint(b))&&x.containsPoint(b)?(w&&(w.start.copy(b),w.end.copy(b)),!0):!1}function M(x,y,w){const b=x.degenerateSegment,E=y.a;return b.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<Xw?(w&&(w.start.copy(E),w.end.copy(E)),!0):!1}function v(x,y,w,b){if(x.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=x.degenerateSegment,S=y.degenerateSegment,A=n,_=s;E.delta(A),S.delta(_);const I=i.subVectors(S.start,E.start),D=A.x*_.y-A.y*_.x;if(qs(D))return!1;const P=(I.x*_.y-I.y*_.x)/D,L=-(A.x*I.y-A.y*I.x)/D;if(P<0||P>1||L<0||L>1)return!1;const O=E.start.z+A.z*P,k=S.start.z+_.z*L;return qs(O-k)?(w&&(w.start.copy(E.start).addScaledVector(A,P),w.end.copy(E.start).addScaledVector(A,P)),!0):!1}else return y.isDegenerateIntoPoint?M(x,y,w):m(y,x,w,b);else{if(x.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(x.a)<Xw?(w&&(w.start.copy(x.a),w.end.copy(x.a)),!0):!1:y.isDegenerateIntoSegment?M(y,x,w):g(y,x,w);if(y.isDegenerateIntoPoint)return g(x,y,w);if(y.isDegenerateIntoSegment)return m(x,y,w,b)}}return function(y,w=null,b=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(o.copy(y),o.update(),y=o);const E=v(this,y,w,b);if(E!==void 0)return E;const S=this.plane,A=y.plane;let _=A.distanceToPoint(this.a),I=A.distanceToPoint(this.b),D=A.distanceToPoint(this.c);qs(_)&&(_=0),qs(I)&&(I=0),qs(D)&&(D=0);const P=_*I,L=_*D;if(P>0&&L>0)return!1;let O=S.distanceToPoint(y.a),k=S.distanceToPoint(y.b),H=S.distanceToPoint(y.c);qs(O)&&(O=0),qs(k)&&(k=0),qs(H)&&(H=0);const W=O*k,Q=O*H;if(W>0&&Q>0)return!1;n.copy(S.normal),s.copy(A.normal);const q=n.cross(s);let nt=0,at=Math.abs(q.x);const zt=Math.abs(q.y);zt>at&&(at=zt,nt=1),Math.abs(q.z)>at&&(nt=2);const Pt=c9[nt],Z=this.a[Pt],ct=this.b[Pt],ot=this.c[Pt],V=y.a[Pt],Ot=y.b[Pt],Wt=y.c[Pt];if(p(this,Z,ct,ot,P,L,_,I,D,h,a))return d(this,y,w,b);if(p(y,V,Ot,Wt,W,Q,O,k,H,u,c))return d(this,y,w,b);if(h.y<h.x){const Nt=h.y;h.y=h.x,h.x=Nt,l.copy(a.start),a.start.copy(a.end),a.end.copy(l)}if(u.y<u.x){const Nt=u.y;u.y=u.x,u.x=Nt,l.copy(c.start),c.start.copy(c.end),c.end.copy(l)}return h.y<u.x||u.y<h.x?!1:(w&&(u.x>h.x?w.start.copy(c.start):w.start.copy(a.start),u.y<h.y?w.end.copy(c.end):w.end.copy(a.end)),!0)}})();Ar.prototype.distanceToPoint=(function(){const o=new R;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();Ar.prototype.distanceToTriangle=(function(){const o=new R,t=new R,e=["a","b","c"],i=new qa,n=new qa;return function(r,a=null,c=null){const l=a||c?i:null;if(this.intersectsTriangle(r,l,!0))return(a||c)&&(a&&l.getCenter(a),c&&l.getCenter(c)),0;let h=1/0;for(let u=0;u<3;u++){let d;const f=e[u],p=r[f];this.closestPointToPoint(p,o),d=p.distanceToSquared(o),d<h&&(h=d,a&&a.copy(o),c&&c.copy(p));const m=this[f];r.closestPointToPoint(m,o),d=m.distanceToSquared(o),d<h&&(h=d,a&&a.copy(m),c&&c.copy(o))}for(let u=0;u<3;u++){const d=e[u],f=e[(u+1)%3];i.set(this[d],this[f]);for(let p=0;p<3;p++){const m=e[p],g=e[(p+1)%3];n.set(r[m],r[g]),Fv(i,n,o,t);const M=o.distanceToSquared(t);M<h&&(h=M,a&&a.copy(o),c&&c.copy(t))}}return Math.sqrt(h)}})();class gs{constructor(t,e,i){this.isOrientedBox=!0,this.min=new R,this.max=new R,this.matrix=new Vt,this.invMatrix=new Vt,this.points=new Array(8).fill().map(()=>new R),this.satAxes=new Array(3).fill().map(()=>new R),this.satBounds=new Array(3).fill().map(()=>new Ja),this.alignedSatBounds=new Array(3).fill().map(()=>new Ja),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}gs.prototype.update=(function(){return function(){const t=this.matrix,e=this.min,i=this.max,n=this.points;for(let l=0;l<=1;l++)for(let h=0;h<=1;h++)for(let u=0;u<=1;u++){const d=1*l|2*h|4*u,f=n[d];f.x=l?i.x:e.x,f.y=h?i.y:e.y,f.z=u?i.z:e.z,f.applyMatrix4(t)}const s=this.satBounds,r=this.satAxes,a=n[0];for(let l=0;l<3;l++){const h=r[l],u=s[l],d=1<<l,f=n[d];h.subVectors(a,f),u.setFromPoints(h,n)}const c=this.alignedSatBounds;c[0].setFromPointsField(n,"x"),c[1].setFromPointsField(n,"y"),c[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();gs.prototype.intersectsBox=(function(){const o=new Ja;return function(e){this.needsUpdate&&this.update();const i=e.min,n=e.max,s=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(o.min=i.x,o.max=n.x,a[0].isSeparated(o)||(o.min=i.y,o.max=n.y,a[1].isSeparated(o))||(o.min=i.z,o.max=n.z,a[2].isSeparated(o)))return!1;for(let c=0;c<3;c++){const l=r[c],h=s[c];if(o.setFromBox(l,e),h.isSeparated(o))return!1}return!0}})();gs.prototype.intersectsTriangle=(function(){const o=new Ar,t=new Array(3),e=new Ja,i=new Ja,n=new R;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(o.copy(r),o.update(),r=o);const a=this.satBounds,c=this.satAxes;t[0]=r.a,t[1]=r.b,t[2]=r.c;for(let d=0;d<3;d++){const f=a[d],p=c[d];if(e.setFromPoints(p,t),f.isSeparated(e))return!1}const l=r.satBounds,h=r.satAxes,u=this.points;for(let d=0;d<3;d++){const f=l[d],p=h[d];if(e.setFromPoints(p,u),f.isSeparated(e))return!1}for(let d=0;d<3;d++){const f=c[d];for(let p=0;p<4;p++){const m=h[p];if(n.crossVectors(f,m),e.setFromPoints(n,t),i.setFromPoints(n,u),e.isSeparated(i))return!1}}return!0}})();gs.prototype.closestPointToPoint=(function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}})();gs.prototype.distanceToPoint=(function(){const o=new R;return function(e){return this.closestPointToPoint(e,o),e.distanceTo(o)}})();gs.prototype.distanceToBox=(function(){const o=["x","y","z"],t=new Array(12).fill().map(()=>new qa),e=new Array(12).fill().map(()=>new qa),i=new R,n=new R;return function(r,a=0,c=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(c||l)&&(r.getCenter(n),this.closestPointToPoint(n,i),r.closestPointToPoint(i,n),c&&c.copy(i),l&&l.copy(n)),0;const h=a*a,u=r.min,d=r.max,f=this.points;let p=1/0;for(let g=0;g<8;g++){const M=f[g];n.copy(M).clamp(u,d);const v=M.distanceToSquared(n);if(v<p&&(p=v,c&&c.copy(M),l&&l.copy(n),v<h))return Math.sqrt(v)}let m=0;for(let g=0;g<3;g++)for(let M=0;M<=1;M++)for(let v=0;v<=1;v++){const x=(g+1)%3,y=(g+2)%3,w=M<<x|v<<y,b=1<<g|M<<x|v<<y,E=f[w],S=f[b];t[m].set(E,S);const _=o[g],I=o[x],D=o[y],P=e[m],L=P.start,O=P.end;L[_]=u[_],L[I]=M?u[I]:d[I],L[D]=v?u[D]:d[I],O[_]=d[_],O[I]=M?u[I]:d[I],O[D]=v?u[D]:d[I],m++}for(let g=0;g<=1;g++)for(let M=0;M<=1;M++)for(let v=0;v<=1;v++){n.x=g?d.x:u.x,n.y=M?d.y:u.y,n.z=v?d.z:u.z,this.closestPointToPoint(n,i);const x=n.distanceToSquared(i);if(x<p&&(p=x,c&&c.copy(i),l&&l.copy(n),x<h))return Math.sqrt(x)}for(let g=0;g<12;g++){const M=t[g];for(let v=0;v<12;v++){const x=e[v];Fv(M,x,i,n);const y=i.distanceToSquared(n);if(y<p&&(p=y,c&&c.copy(i),l&&l.copy(n),y<h))return Math.sqrt(y)}}return Math.sqrt(p)}})();class l9 extends kv{constructor(){super(()=>new Ar)}}const nr=new l9,pu=new R,yg=new R;function h9(o,t,e={},i=0,n=1/0){const s=i*i,r=n*n;let a=1/0,c=null;if(o.shapecast({boundsTraverseOrder:h=>(pu.copy(t).clamp(h.min,h.max),pu.distanceToSquared(t)),intersectsBounds:(h,u,d)=>d<a&&d<r,intersectsTriangle:(h,u)=>{h.closestPointToPoint(t,pu);const d=t.distanceToSquared(pu);return d<a&&(yg.copy(pu),a=d,c=u),d<s}}),a===1/0)return null;const l=Math.sqrt(a);return e.point?e.point.copy(yg):e.point=yg.clone(),e.distance=l,e.faceIndex=c,e}const Yf=parseInt(Bd)>=169,u9=parseInt(Bd)<=161,rc=new R,ac=new R,oc=new R,$f=new tt,Kf=new tt,qf=new tt,Yw=new R,$w=new R,Kw=new R,mu=new R;function d9(o,t,e,i,n,s,r,a){let c;if(s===Ci?c=o.intersectTriangle(i,e,t,!0,n):c=o.intersectTriangle(t,e,i,s!==xn,n),c===null)return null;const l=o.origin.distanceTo(n);return l<r||l>a?null:{distance:l,point:n.clone()}}function qw(o,t,e,i,n,s,r,a,c,l,h){rc.fromBufferAttribute(t,s),ac.fromBufferAttribute(t,r),oc.fromBufferAttribute(t,a);const u=d9(o,rc,ac,oc,mu,c,l,h);if(u){if(i){$f.fromBufferAttribute(i,s),Kf.fromBufferAttribute(i,r),qf.fromBufferAttribute(i,a),u.uv=new tt;const f=On.getInterpolation(mu,rc,ac,oc,$f,Kf,qf,u.uv);Yf||(u.uv=f)}if(n){$f.fromBufferAttribute(n,s),Kf.fromBufferAttribute(n,r),qf.fromBufferAttribute(n,a),u.uv1=new tt;const f=On.getInterpolation(mu,rc,ac,oc,$f,Kf,qf,u.uv1);Yf||(u.uv1=f),u9&&(u.uv2=u.uv1)}if(e){Yw.fromBufferAttribute(e,s),$w.fromBufferAttribute(e,r),Kw.fromBufferAttribute(e,a),u.normal=new R;const f=On.getInterpolation(mu,rc,ac,oc,Yw,$w,Kw,u.normal);u.normal.dot(o.direction)>0&&u.normal.multiplyScalar(-1),Yf||(u.normal=f)}const d={a:s,b:r,c:a,normal:new R,materialIndex:0};if(On.getNormal(rc,ac,oc,d.normal),u.face=d,u.faceIndex=s,Yf){const f=new R;On.getBarycoord(mu,rc,ac,oc,f),u.barycoord=f}}return u}function Zw(o){return o&&o.isMaterial?o.side:o}function Gp(o,t,e,i,n,s,r){const a=i*3;let c=a+0,l=a+1,h=a+2;const{index:u,groups:d}=o;o.index&&(c=u.getX(c),l=u.getX(l),h=u.getX(h));const{position:f,normal:p,uv:m,uv1:g}=o.attributes;if(Array.isArray(t)){const M=i*3;for(let v=0,x=d.length;v<x;v++){const{start:y,count:w,materialIndex:b}=d[v];if(M>=y&&M<y+w){const E=Zw(t[b]),S=qw(e,f,p,m,g,c,l,h,E,s,r);if(S)if(S.faceIndex=i,S.face.materialIndex=b,n)n.push(S);else return S}}}else{const M=Zw(t),v=qw(e,f,p,m,g,c,l,h,M,s,r);if(v)if(v.faceIndex=i,v.face.materialIndex=0,n)n.push(v);else return v}return null}function fn(o,t,e,i){const n=o.a,s=o.b,r=o.c;let a=t,c=t+1,l=t+2;e&&(a=e.getX(a),c=e.getX(c),l=e.getX(l)),n.x=i.getX(a),n.y=i.getY(a),n.z=i.getZ(a),s.x=i.getX(c),s.y=i.getY(c),s.z=i.getZ(c),r.x=i.getX(l),r.y=i.getY(l),r.z=i.getZ(l)}function f9(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++)Gp(c,t,e,h,s,r,a)}function p9(o,t,e,i,n,s,r){const{geometry:a,_indirectBuffer:c}=o;let l=1/0,h=null;for(let u=i,d=i+n;u<d;u++){let f;f=Gp(a,t,e,u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function m9(o,t,e,i,n,s,r){const{geometry:a}=e,{index:c}=a,l=a.attributes.position;for(let h=o,u=t+o;h<u;h++){let d;if(d=h,fn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function g9(o,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=o.geometry,i=e.index?e.index.array:null,n=e.attributes.position;let s,r,a,c,l=0;const h=o._roots;for(let d=0,f=h.length;d<f;d++)s=h[d],r=new Uint32Array(s),a=new Uint16Array(s),c=new Float32Array(s),u(0,l),l+=s.byteLength;function u(d,f,p=!1){const m=d*2;if(nn(m,a)){const g=Ln(d,r),M=es(m,a);let v=1/0,x=1/0,y=1/0,w=-1/0,b=-1/0,E=-1/0;for(let S=3*g,A=3*(g+M);S<A;S++){let _=i[S];const I=n.getX(_),D=n.getY(_),P=n.getZ(_);I<v&&(v=I),I>w&&(w=I),D<x&&(x=D),D>b&&(b=D),P<y&&(y=P),P>E&&(E=P)}return c[d+0]!==v||c[d+1]!==x||c[d+2]!==y||c[d+3]!==w||c[d+4]!==b||c[d+5]!==E?(c[d+0]=v,c[d+1]=x,c[d+2]=y,c[d+3]=w,c[d+4]=b,c[d+5]=E,!0):!1}else{const g=Sn(d),M=bn(d,r);let v=p,x=!1,y=!1;if(t){if(!v){const _=g/wn+f/ts,I=M/wn+f/ts;x=t.has(_),y=t.has(I),v=!x&&!y}}else x=!0,y=!0;const w=v||x,b=v||y;let E=!1;w&&(E=u(g,f,v));let S=!1;b&&(S=u(M,f,v));const A=E||S;if(A)for(let _=0;_<3;_++){const I=g+_,D=M+_,P=c[I],L=c[I+3],O=c[D],k=c[D+3];c[d+_]=P<O?P:O,c[d+_+3]=L>k?L:k}return A}}}function Ko(o,t,e,i,n){let s,r,a,c,l,h;const u=1/e.direction.x,d=1/e.direction.y,f=1/e.direction.z,p=e.origin.x,m=e.origin.y,g=e.origin.z;let M=t[o],v=t[o+3],x=t[o+1],y=t[o+3+1],w=t[o+2],b=t[o+3+2];return u>=0?(s=(M-p)*u,r=(v-p)*u):(s=(v-p)*u,r=(M-p)*u),d>=0?(a=(x-m)*d,c=(y-m)*d):(a=(y-m)*d,c=(x-m)*d),s>c||a>r||((a>s||isNaN(s))&&(s=a),(c<r||isNaN(r))&&(r=c),f>=0?(l=(w-g)*f,h=(b-g)*f):(l=(b-g)*f,h=(w-g)*f),s>h||l>r)?!1:((l>s||s!==s)&&(s=l),(h<r||r!==r)&&(r=h),s<=n&&r>=i)}function M9(o,t,e,i,n,s,r,a){const{geometry:c,_indirectBuffer:l}=o;for(let h=i,u=i+n;h<u;h++){let d=l?l[h]:h;Gp(c,t,e,d,s,r,a)}}function v9(o,t,e,i,n,s,r){const{geometry:a,_indirectBuffer:c}=o;let l=1/0,h=null;for(let u=i,d=i+n;u<d;u++){let f;f=Gp(a,t,e,c?c[u]:u,null,s,r),f&&f.distance<l&&(h=f,l=f.distance)}return h}function y9(o,t,e,i,n,s,r){const{geometry:a}=e,{index:c}=a,l=a.attributes.position;for(let h=o,u=t+o;h<u;h++){let d;if(d=e.resolveTriangleIndex(h),fn(r,d*3,c,l),r.needsUpdate=!0,i(r,d,n,s))return!0}return!1}function x9(o,t,e,i,n,s,r){Oi.setBuffer(o._roots[t]),DM(0,o,e,i,n,s,r),Oi.clearBuffer()}function DM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Oi,h=o*2;if(nn(h,c)){const d=Ln(o,l),f=es(h,c);f9(t,e,i,d,f,n,s,r)}else{const d=Sn(o);Ko(d,a,i,s,r)&&DM(d,t,e,i,n,s,r);const f=bn(o,l);Ko(f,a,i,s,r)&&DM(f,t,e,i,n,s,r)}}const w9=["x","y","z"];function S9(o,t,e,i,n,s){Oi.setBuffer(o._roots[t]);const r=CM(0,o,e,i,n,s);return Oi.clearBuffer(),r}function CM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Oi;let l=o*2;if(nn(l,a)){const u=Ln(o,c),d=es(l,a);return p9(t,e,i,u,d,n,s)}else{const u=Lv(o,c),d=w9[u],p=i.direction[d]>=0;let m,g;p?(m=Sn(o),g=bn(o,c)):(m=bn(o,c),g=Sn(o));const v=Ko(m,r,i,n,s)?CM(m,t,e,i,n,s):null;if(v){const w=v.point[d];if(p?w<=r[g+u]:w>=r[g+u+3])return v}const y=Ko(g,r,i,n,s)?CM(g,t,e,i,n,s):null;return v&&y?v.distance<=y.distance?v:y:v||y||null}}const Zf=new Ke,Rl=new Ar,Il=new Ar,gu=new Vt,Jw=new gs,Jf=new gs;function b9(o,t,e,i){Oi.setBuffer(o._roots[t]);const n=PM(0,o,e,i);return Oi.clearBuffer(),n}function PM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Oi;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),Jw.set(e.boundingBox.min,e.boundingBox.max,i),n=Jw),nn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Ln(o,a),g=es(c,r);if(gu.copy(i).invert(),e.boundsTree)return Wi(o,s,Jf),Jf.matrix.copy(gu),Jf.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:v=>Jf.intersectsBox(v),intersectsTriangle:v=>{v.a.applyMatrix4(i),v.b.applyMatrix4(i),v.c.applyMatrix4(i),v.needsUpdate=!0;for(let x=m*3,y=(g+m)*3;x<y;x+=3)if(fn(Il,x,u,d),Il.needsUpdate=!0,v.intersectsTriangle(Il))return!0;return!1}});{const M=Hp(e);for(let v=m*3,x=(g+m)*3;v<x;v+=3){fn(Rl,v,u,d),Rl.a.applyMatrix4(gu),Rl.b.applyMatrix4(gu),Rl.c.applyMatrix4(gu),Rl.needsUpdate=!0;for(let y=0,w=M*3;y<w;y+=3)if(fn(Il,y,f,p),Il.needsUpdate=!0,Rl.intersectsTriangle(Il))return!0}}}else{const h=Sn(o),u=bn(o,a);return Wi(h,s,Zf),!!(n.intersectsBox(Zf)&&PM(h,t,e,i,n)||(Wi(u,s,Zf),n.intersectsBox(Zf)&&PM(u,t,e,i,n)))}}const jf=new Vt,xg=new gs,Mu=new gs,E9=new R,A9=new R,_9=new R,T9=new R;function R9(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),xg.set(t.boundingBox.min,t.boundingBox.max,e),xg.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=nr.getPrimitive(),f=nr.getPrimitive();let p=E9,m=A9,g=null,M=null;n&&(g=_9,M=T9);let v=1/0,x=null,y=null;return jf.copy(e).invert(),Mu.matrix.copy(jf),o.shapecast({boundsTraverseOrder:w=>xg.distanceToBox(w),intersectsBounds:(w,b,E)=>E<v&&E<r?(b&&(Mu.min.copy(w.min),Mu.max.copy(w.max),Mu.needsUpdate=!0),!0):!1,intersectsRange:(w,b)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:S=>Mu.distanceToBox(S),intersectsBounds:(S,A,_)=>_<v&&_<r,intersectsRange:(S,A)=>{for(let _=S,I=S+A;_<I;_++){fn(f,3*_,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let D=w,P=w+b;D<P;D++){fn(d,3*D,l,c),d.needsUpdate=!0;const L=d.distanceToTriangle(f,p,g);if(L<v&&(m.copy(p),M&&M.copy(g),v=L,x=D,y=_),L<s)return!0}}}});{const E=Hp(t);for(let S=0,A=E;S<A;S++){fn(f,3*S,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=w,I=w+b;_<I;_++){fn(d,3*_,l,c),d.needsUpdate=!0;const D=d.distanceToTriangle(f,p,g);if(D<v&&(m.copy(p),M&&M.copy(g),v=D,x=_,y=S),D<s)return!0}}}}}),nr.releasePrimitive(d),nr.releasePrimitive(f),v===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=v,i.faceIndex=x,n&&(n.point?n.point.copy(M):n.point=M.clone(),n.point.applyMatrix4(jf),m.applyMatrix4(jf),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function I9(o,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=o.geometry,i=e.index?e.index.array:null,n=e.attributes.position;let s,r,a,c,l=0;const h=o._roots;for(let d=0,f=h.length;d<f;d++)s=h[d],r=new Uint32Array(s),a=new Uint16Array(s),c=new Float32Array(s),u(0,l),l+=s.byteLength;function u(d,f,p=!1){const m=d*2;if(nn(m,a)){const g=Ln(d,r),M=es(m,a);let v=1/0,x=1/0,y=1/0,w=-1/0,b=-1/0,E=-1/0;for(let S=g,A=g+M;S<A;S++){const _=3*o.resolveTriangleIndex(S);for(let I=0;I<3;I++){let D=_+I;D=i?i[D]:D;const P=n.getX(D),L=n.getY(D),O=n.getZ(D);P<v&&(v=P),P>w&&(w=P),L<x&&(x=L),L>b&&(b=L),O<y&&(y=O),O>E&&(E=O)}}return c[d+0]!==v||c[d+1]!==x||c[d+2]!==y||c[d+3]!==w||c[d+4]!==b||c[d+5]!==E?(c[d+0]=v,c[d+1]=x,c[d+2]=y,c[d+3]=w,c[d+4]=b,c[d+5]=E,!0):!1}else{const g=Sn(d),M=bn(d,r);let v=p,x=!1,y=!1;if(t){if(!v){const _=g/wn+f/ts,I=M/wn+f/ts;x=t.has(_),y=t.has(I),v=!x&&!y}}else x=!0,y=!0;const w=v||x,b=v||y;let E=!1;w&&(E=u(g,f,v));let S=!1;b&&(S=u(M,f,v));const A=E||S;if(A)for(let _=0;_<3;_++){const I=g+_,D=M+_,P=c[I],L=c[I+3],O=c[D],k=c[D+3];c[d+_]=P<O?P:O,c[d+_+3]=L>k?L:k}return A}}}function D9(o,t,e,i,n,s,r){Oi.setBuffer(o._roots[t]),OM(0,o,e,i,n,s,r),Oi.clearBuffer()}function OM(o,t,e,i,n,s,r){const{float32Array:a,uint16Array:c,uint32Array:l}=Oi,h=o*2;if(nn(h,c)){const d=Ln(o,l),f=es(h,c);M9(t,e,i,d,f,n,s,r)}else{const d=Sn(o);Ko(d,a,i,s,r)&&OM(d,t,e,i,n,s,r);const f=bn(o,l);Ko(f,a,i,s,r)&&OM(f,t,e,i,n,s,r)}}const C9=["x","y","z"];function P9(o,t,e,i,n,s){Oi.setBuffer(o._roots[t]);const r=NM(0,o,e,i,n,s);return Oi.clearBuffer(),r}function NM(o,t,e,i,n,s){const{float32Array:r,uint16Array:a,uint32Array:c}=Oi;let l=o*2;if(nn(l,a)){const u=Ln(o,c),d=es(l,a);return v9(t,e,i,u,d,n,s)}else{const u=Lv(o,c),d=C9[u],p=i.direction[d]>=0;let m,g;p?(m=Sn(o),g=bn(o,c)):(m=bn(o,c),g=Sn(o));const v=Ko(m,r,i,n,s)?NM(m,t,e,i,n,s):null;if(v){const w=v.point[d];if(p?w<=r[g+u]:w>=r[g+u+3])return v}const y=Ko(g,r,i,n,s)?NM(g,t,e,i,n,s):null;return v&&y?v.distance<=y.distance?v:y:v||y||null}}const Qf=new Ke,Dl=new Ar,Cl=new Ar,vu=new Vt,jw=new gs,t0=new gs;function O9(o,t,e,i){Oi.setBuffer(o._roots[t]);const n=LM(0,o,e,i);return Oi.clearBuffer(),n}function LM(o,t,e,i,n=null){const{float32Array:s,uint16Array:r,uint32Array:a}=Oi;let c=o*2;if(n===null&&(e.boundingBox||e.computeBoundingBox(),jw.set(e.boundingBox.min,e.boundingBox.max,i),n=jw),nn(c,r)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,m=Ln(o,a),g=es(c,r);if(vu.copy(i).invert(),e.boundsTree)return Wi(o,s,t0),t0.matrix.copy(vu),t0.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:v=>t0.intersectsBox(v),intersectsTriangle:v=>{v.a.applyMatrix4(i),v.b.applyMatrix4(i),v.c.applyMatrix4(i),v.needsUpdate=!0;for(let x=m,y=g+m;x<y;x++)if(fn(Cl,3*t.resolveTriangleIndex(x),u,d),Cl.needsUpdate=!0,v.intersectsTriangle(Cl))return!0;return!1}});{const M=Hp(e);for(let v=m,x=g+m;v<x;v++){const y=t.resolveTriangleIndex(v);fn(Dl,3*y,u,d),Dl.a.applyMatrix4(vu),Dl.b.applyMatrix4(vu),Dl.c.applyMatrix4(vu),Dl.needsUpdate=!0;for(let w=0,b=M*3;w<b;w+=3)if(fn(Cl,w,f,p),Cl.needsUpdate=!0,Dl.intersectsTriangle(Cl))return!0}}}else{const h=Sn(o),u=bn(o,a);return Wi(h,s,Qf),!!(n.intersectsBox(Qf)&&LM(h,t,e,i,n)||(Wi(u,s,Qf),n.intersectsBox(Qf)&&LM(u,t,e,i,n)))}}const e0=new Vt,wg=new gs,yu=new gs,N9=new R,L9=new R,k9=new R,U9=new R;function F9(o,t,e,i={},n={},s=0,r=1/0){t.boundingBox||t.computeBoundingBox(),wg.set(t.boundingBox.min,t.boundingBox.max,e),wg.needsUpdate=!0;const a=o.geometry,c=a.attributes.position,l=a.index,h=t.attributes.position,u=t.index,d=nr.getPrimitive(),f=nr.getPrimitive();let p=N9,m=L9,g=null,M=null;n&&(g=k9,M=U9);let v=1/0,x=null,y=null;return e0.copy(e).invert(),yu.matrix.copy(e0),o.shapecast({boundsTraverseOrder:w=>wg.distanceToBox(w),intersectsBounds:(w,b,E)=>E<v&&E<r?(b&&(yu.min.copy(w.min),yu.max.copy(w.max),yu.needsUpdate=!0),!0):!1,intersectsRange:(w,b)=>{if(t.boundsTree){const E=t.boundsTree;return E.shapecast({boundsTraverseOrder:S=>yu.distanceToBox(S),intersectsBounds:(S,A,_)=>_<v&&_<r,intersectsRange:(S,A)=>{for(let _=S,I=S+A;_<I;_++){const D=E.resolveTriangleIndex(_);fn(f,3*D,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let P=w,L=w+b;P<L;P++){const O=o.resolveTriangleIndex(P);fn(d,3*O,l,c),d.needsUpdate=!0;const k=d.distanceToTriangle(f,p,g);if(k<v&&(m.copy(p),M&&M.copy(g),v=k,x=P,y=_),k<s)return!0}}}})}else{const E=Hp(t);for(let S=0,A=E;S<A;S++){fn(f,3*S,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let _=w,I=w+b;_<I;_++){const D=o.resolveTriangleIndex(_);fn(d,3*D,l,c),d.needsUpdate=!0;const P=d.distanceToTriangle(f,p,g);if(P<v&&(m.copy(p),M&&M.copy(g),v=P,x=_,y=S),P<s)return!0}}}}}),nr.releasePrimitive(d),nr.releasePrimitive(f),v===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=v,i.faceIndex=x,n&&(n.point?n.point.copy(M):n.point=M.clone(),n.point.applyMatrix4(e0),m.applyMatrix4(e0),n.distance=m.sub(n.point).length(),n.faceIndex=y),i)}function Qw(o,t,e){return o===null?null:(o.point.applyMatrix4(t.matrixWorld),o.distance=o.point.distanceTo(e.ray.origin),o.object=t,o)}const i0=new gs,n0=new Xc,tS=new R,eS=new Vt,iS=new R,Sg=["getX","getY","getZ"];class fp extends r9{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,n=t._roots,s=t._indirectBuffer,r=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(a.roots=n.map(c=>c.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=s?s.slice():null):(a.roots=n,a.index=r?r.array:null,a.indirectBuffer=s),a}static deserialize(t,e,i={}){i={setIndex:!0,indirect:!!t.indirectBuffer,...i};const{index:n,roots:s,indirectBuffer:r}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),c(s));const a=new fp(e,{...i,[Nv]:!0});if(a._roots=s,a._indirectBuffer=r||null,i.setIndex){const l=e.getIndex();if(l===null){const h=new Me(t.index,1,!1);e.setIndex(h)}else l.array!==n&&(l.array.set(n),l.needsUpdate=!0)}return a;function c(l){for(let h=0;h<l.length;h++){const u=l[h],d=new Uint32Array(u),f=new Uint16Array(u);for(let p=0,m=u.byteLength/ts;p<m;p++){const g=wn*p,M=2*g;nn(M,f)||(d[g+6]=d[g+6]/wn-p)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,a=n.index?n.index.array:null,l=(s?s[t]:t)*3;let h=l+0,u=l+1,d=l+2;a&&(h=a[h],u=a[u],d=a[d]);for(let f=0;f<3;f++){const p=r[Sg[f]](h),m=r[Sg[f]](u),g=r[Sg[f]](d);let M=p;m<M&&(M=m),g<M&&(M=g);let v=p;m>v&&(v=m),g>v&&(v=g),e[i+f]=M,e[i+f+3]=v}return e}computePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,a=n.index?n.index.array:null,c=r.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,h=r.offset||0;let u=3;r.isInterleavedBufferAttribute&&(u=r.data.stride);const d=["getX","getY","getZ"],f=i.offset;for(let p=t,m=t+e;p<m;p++){const M=(s?s[p]:p)*3,v=(p-f)*6;let x=M+0,y=M+1,w=M+2;a&&(x=a[x],y=a[y],w=a[w]),c||(x=x*u+h,y=y*u+h,w=w*u+h);for(let b=0;b<3;b++){let E,S,A;c?(E=r[d[b]](x),S=r[d[b]](y),A=r[d[b]](w)):(E=l[x+b],S=l[y+b],A=l[w+b]);let _=E;S<_&&(_=S),A<_&&(_=A);let I=E;S>I&&(I=S),A>I&&(I=A);const D=(I-_)/2,P=b*2;i[v+P+0]=_+D,i[v+P+1]=D+(Math.abs(_)+D)*I0}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(n===void 0)return;eS.copy(t.matrixWorld).invert(),n0.copy(e.ray).applyMatrix4(eS),iS.setFromMatrixScale(t.matrixWorld),tS.copy(n0.direction).multiply(iS);const s=tS.length(),r=e.near/s,a=e.far/s;if(e.firstHitOnly===!0){let c=this.raycastFirst(n0,n,r,a);c=Qw(c,t,e),c&&i.push(c)}else{const c=this.raycast(n0,n,r,a);for(let l=0,h=c.length;l<h;l++){const u=Qw(c[l],t,e);u&&i.push(u)}}return i}refit(t=null){return(this.indirect?I9:g9)(this,t)}raycast(t,e=pa,i=0,n=1/0){const s=this._roots,r=[],a=this.indirect?D9:x9;for(let c=0,l=s.length;c<l;c++)a(this,c,e,t,r,i,n);return r}raycastFirst(t,e=pa,i=0,n=1/0){const s=this._roots;let r=null;const a=this.indirect?P9:S9;for(let c=0,l=s.length;c<l;c++){const h=a(this,c,e,t,i,n);h!=null&&(r==null||h.distance<r.distance)&&(r=h)}return r}intersectsGeometry(t,e){let i=!1;const n=this._roots,s=this.indirect?O9:b9;for(let r=0,a=n.length;r<a&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=nr.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?y9:m9});return nr.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=nr.getPrimitive(),a=this.geometry.index,c=this.geometry.attributes.position,l=this.indirect?p=>{const m=this.resolveTriangleIndex(p);fn(r,m*3,a,c)}:p=>{fn(r,p*3,a,c)},h=nr.getPrimitive(),u=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?p=>{const m=t.resolveTriangleIndex(p);fn(h,m*3,u,d)}:p=>{fn(h,p*3,u,d)};if(s){if(!(t instanceof fp))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const p=(m,g,M,v,x,y,w,b)=>{for(let E=M,S=M+v;E<S;E++){f(E),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let A=m,_=m+g;A<_;A++)if(l(A),r.needsUpdate=!0,s(r,h,A,E,x,y,w,b))return!0}return!1};if(n){const m=n;n=function(g,M,v,x,y,w,b,E){return m(g,M,v,x,y,w,b,E)?!0:p(g,M,v,x,y,w,b,E)}}else n=p}return super.bvhcast(t,e,{intersectsRanges:n})}intersectsBox(t,e){return i0.set(t.min,t.max,e),i0.needsUpdate=!0,this.shapecast({intersectsBounds:i=>i0.intersectsBox(i),intersectsTriangle:i=>i0.intersectsTriangle(i)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},n={},s=0,r=1/0){return(this.indirect?F9:R9)(this,t,e,i,n,s,r)}closestPointToPoint(t,e={},i=0,n=1/0){return h9(this,t,e,i,n)}}class Fr{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new ar;static install(){if(Fr.installed)return;Fr.installed=!0;const t=vt.prototype.raycast;vt.prototype.raycast=function(e,i){const n=Fr.treeOf(this,e);n!==null&&(n?n.raycastObject3D(this,e,i):t.call(this,e,i))}}static treeOf(t,e){const i=t.geometry,n=i?.attributes.position;if(!(n instanceof Me)||t.material===void 0||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh||i.morphAttributes.position)return;const s=i.index;if((s?s.count:n.count)/3<Fr.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const r=Fr.sphere.copy(i.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(r))return null;const a=Fr.trees.get(i);if(a){if(!a.bvh)return;if(a.position===n&&a.positionVersion===n.version&&a.index===s&&a.indexVersion===(s?.version??0))return a.bvh;Fr.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const c=new fp(i,{indirect:!0});return Fr.trees.set(i,{bvh:c,position:n,positionVersion:n.version,index:s,indexVersion:s?.version??0}),c}}function z9(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.rareIceCrystals===t.rareIceCrystals&&o.lowerCloudCover===t.lowerCloudCover&&o.relativeHumidity===t.relativeHumidity&&o.precipitationType===t.precipitationType&&o.precipitationIntensity===t.precipitationIntensity&&o.precipitationAmount===t.precipitationAmount&&o.windDirectionDeg===t.windDirectionDeg&&o.windSpeed===t.windSpeed&&o.storm===t.storm}const s0=900,bg=1,nS=4,Eg=5,r0=.5,a0=ze.GROUND_RADIUS_M;function sS(o){return ze.groundRadiusFor(o)}const Ag=.5,_g=850,o0=.03,B9=.015,as=850,Pl=300,_a=120,H9=700,Tg=.03,G9=3.5,c0=20,Rg=.04,V9=.26,rS=4,Ig=1.5,aS=-1,W9=.01,C0=-4,X9=2,Y9=20,l0=2600,$9=.97,K9=.38,xu=C0,q9=8,Z9=2,oS=1500,J9=.7,j9=.3,Q9=.32,tN=.65,cS=2.4,eN=.9,iN=400,nN=[0,45,90,135,180,225,270,315],sN=2,rN=16,lS=4e3,hS=880,h0=40,uS=60,aN=10,dS=1,oN=ze.REBUILD_DISTANCE_M,fS=.265,pS=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*fS,Math.sin(e)*fS]})],Dg=700,Cg=250/UM,cN=12,mS=5,Pg=6,cc=[.92,.92,.95],Og=[.15,.15,.19],Ng={snow:{fallSpeedMPerS:2,size:.3,color:new rt(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new rt(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Ul=0,Lg=0,lN=150,kg=3e3,wu=20,hN=15,gS=Ul,uN=40,MS=1,dN=9;function Ug(o){return MS+(dN-MS)*o}const vS=new rt(.75,.82,.92),fN=10,pN=.5;function yS(o){return zr(o/fN,pN,1)}const lc=200,xS=.18,wS=.32,mN=.35,SS=new rt(.85,.9,.98),bS=5,ES=.85,AS=.01;function gN(o,t,e=1){return Math.round(o*(AS+(1-AS)*t)*e)}function MN(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.lowerCloudCover===t.lowerCloudCover}const _S=230,TS=.7,RS=.05,vN=.6,yN=.7,xN=.15,IS=.35,wN=3,SN=1/12,bN=.5,Nr=new rt(.82,.86,1),EN=2500,AN=1.6,Fg=15,_N={Venus:new rt(1,.96,.85),Mars:new rt(1,.55,.4),Jupiter:new rt(.95,.87,.72),Saturn:new rt(.92,.86,.68)};class lt{renderer;scene=new Ws;phenomena=new Mr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new Xe;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(t,e){if(this.skyHoldUntilMs===null)return t;this.arrivalsPending++;let i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=e===void 0?void 0:setTimeout(n,e);return e!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+e),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),e+20))),t.finally(()=>{clearTimeout(s),n()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+lS,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),lS+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new ve;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new tt;decorModelProvider=new uA;decorModelToken=0;decorModelCredits=new Map;emitterLights=new cs(this.scene,()=>this.relativeScale,{halfExtentM:_a,depthHalfRangeM:Pl,biasM:Tg,normalBiasM:Rg,mapSize:1024});bodySystem=new re(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale,t=>this.emitterLights.set("bodies",t));bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??lt.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*lt.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;skyEventsStated;skyEventsStart;skyEventLayers=new Map;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new j0(16777215,0);celestialLightTarget=new Pi;skyLight=new _4(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new E0;weather=yp;observerElevationM=0;siteElevationM=0;air=new er;groundRadius=a0;terrainRadius=a0;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new R;cloudFieldOffset=new R;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new R;rainLastVerticalFacing=-1;rainViewportSize=new tt;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new j0(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new E0;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new E0;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=pi.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;eclipsedSun=new Ld;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=wb()){zu.install(),Fr.install(),this.renderer=new HC({canvas:t,antialias:!0}),this.resolution=new Qe(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Cu,this.camera=new Bn(60,t.width/Math.max(t.height,1),.1,s0*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=e,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-_a,this.celestialLight.shadow.camera.right=_a,this.celestialLight.shadow.camera.top=_a,this.celestialLight.shadow.camera.bottom=-_a,this.celestialLight.shadow.camera.near=as-Pl,this.celestialLight.shadow.camera.far=as+Pl,this.celestialLight.shadow.bias=-Tg/(2*Pl),this.celestialLight.shadow.normalBias=Rg,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Nr),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new de(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(t,e){this.cssSize.width=t,this.cssSize.height=e,this.renderer.setSize(t,e,!1),this.camera.aspect=t/Math.max(e,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(t){t!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=t,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(t,e={}){this.cloudOffsetM.set(t.x,0,t.z),this.cloudLayerOffsetsM=e,this.layeredClouds?.setOffsets(t,e),this.cloudFieldOffset.set(t.x*Cg,0,t.z*Cg);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){this.updateLookPatch(t);const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*Je,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Je;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Je,e,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(sS(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/a0),this.camera.far=Math.max(s0*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),t.lat!==void 0&&t.lng!==void 0&&this.placeTerrain(t.lat,t.lng,0,0),this.poseElevationM=t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+t.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==t.fovDeg&&(this.camera.fov=t.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(t){this.stopTerrainFade(),this.terrainProviders=t,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.dropLookPatch(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=lt.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return ze.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=ae(a.lat,a.lng,t,e);r.position.x=c.x-i,r.position.z=c.z+n};if(this.terrainMesh&&this.terrainMeshOrigin&&s(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&s(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;s(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}this.lookPatch&&s(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=dS+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=ze.lookPatchFor(t.elevationM??0,t.pitchDeg,this.terrainRadius);if(!e){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const i=(t.headingDeg??0)*Math.PI/180,n=t.lat+e.distanceM*Math.cos(i)/111320,s=t.lng+e.distanceM*Math.sin(i)/(111320*Math.cos(t.lat*Math.PI/180)),r=this.lookPatchAsked;if(r){const l=ae(n,s,r.lat,r.lng);if(Math.hypot(l.x,l.z)<r.radiusM*lt.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:n,lng:s,radiusM:e.radiusM};const a=++this.lookPatchToken,c=this.terrainProviders;ng(n,s,{elevation:c.elevation,imagery:c.imagery},e.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:l})=>{if(a!==this.lookPatchToken||this.terrainProviders!==c||!this.terrainMesh){this.disposeMesh(l);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),l.renderOrder=lt.LOOK_PATCH_RENDER_ORDER,l.position.y=this.terrainMesh.position.y;const h=l.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:l,origin:{lat:n,lng:s},radiusM:e.radiusM};const u=ae(n,s,t.lat,t.lng);l.position.x=u.x,l.position.z=u.z,this.scene.add(l),this.compileNextFrameOffThread(),this.render()},l=>console.warn("No sharp ground under what is looked at:",l))}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:i},this.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),lt.TERRAIN_PATIENCE_MS)}return}const u=n.nearest(t,e);u&&(t=u.lat,e=u.lng,s=u.radiusM)}const r=s??Math.max(ze.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=ae(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<oN*(r/a0))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(ae(t,e,c.lat,c.lng).x,ae(t,e,c.lat,c.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(ng(t,e,this.terrainProviders,r,{route:this.observerRoute}),lt.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const g=this.terrainMesh,M=this.terrainMeshOrigin,v=M?ae(t,e,M.lat,M.lng):void 0;g&&v&&Math.hypot(v.x,v.z)<=a&&(u.position.y=g.position.y+this.groundYOfPatch(g,v.x,v.z)),g&&M&&v&&Math.hypot(v.x,v.z)<=a?this.crossfadeTerrain(u,g,M):this.disposeMesh(this.terrainMesh),u.renderOrder=dS,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,r),this.buildWater(t,e,r,p,m),this.buildRailways(t,e,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,r,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,c=this.skyEventReachM({lat:t,lng:e});if(!ze.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:m}=ae(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,m)<i*lt.FAR_RING_KEPT_SHARE)return}const l=this.terrainProviders.patches,h=l?.farRingOf?.(t,e);if(l&&!h){this.dropFarRing();return}const u=h?.radiusM??ze.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(ng(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*lt.FAR_RING_OPEN_SHARE,referenceElevationM:s}),lt.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=lt.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-lt.FAR_RING_DROP_M;const m=p.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=u,this.scene.add(p),p.position.x=n.position.x,p.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}dropLookPatch(){this.lookPatchToken++,this.lookPatchAsked=void 0,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0)}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(t,e,i){if(this.grassReference){const r=ae(this.grassReference.lat,this.grassReference.lng,e,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:i};const n=ae(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const n=t.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/lt.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=ze.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRoads(s.ways,t,e,n.contemporary);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(Bu(t,e,i)),lt.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:r},this.drapeRoads(r,t,e,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(t,e,i,n,s){const r=this.terrainProviders.water;if(!r||i>lt.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,t,e,i),lt.ROADS_PATIENCE_MS).catch(c=>console.warn("Water not drawn:",c));return}const a=this.waterSurfaces;if(a&&a.lat===t&&a.lng===e&&a.radiusM===i){this.drapeWater(a.surfaces,t,e,i);return}a&&Math.hypot(ae(t,e,a.lat,a.lng).x,ae(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(Bu(t,e,i))).then(c=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:c},this.drapeWater(c,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(c=>{console.warn("Water unavailable, drawing none:",c)})}async drapeWater(t,e,i,n){if(t.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n,this.patchSpacingM(r)),Zn.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=$t(async()=>{const{WaterSystem:t}=await import("./WaterSystem-DI_NBDfH.js");return{WaterSystem:t}},[],import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,i){const n=this.terrainProviders.railways;if(!n||i>lt.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRailways(s.lines,t,e,i);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(Bu(t,e,i)).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:r},this.drapeRailways(r,t,e,i)}),lt.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(t,e,i,n){if(!this.railwaySystem&&!t.some(a=>a.level>=0))return;const s=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.setGroundSpacing(this.patchSpacingM(r)),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n),Zn.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=$t(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-DZQr_rS_.js");return{RailwaySystem:t}},[],import.meta.url).then(({RailwaySystem:t})=>{const e=new t;return this.scene.add(e.group),this.railwaySystem=e,e})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(t){t!==this.statedRoads&&(this.statedRoads=t,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const t=this.terrainMesh;t&&(this.roadSystem.group.position.copy(t.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(t)),this.roadSystem.setStated(this.statedRoads,(e,i)=>this.groundYOfPatch(t,e,i)))}setTraces(t,e=new Map){t===this.traces&&e===this.traceLabels||(this.traces=t,this.traceLabels=e,!(t.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(t){t!==this.tracesShown&&(this.tracesShown=t,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=$t(async()=>{const{TraceSystem:t}=await import("./TraceSystem-D7pxye9d.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(Eg);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(e,n,s)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=ut.naturalSize(n.kind,n.floors),r=(n.headingDeg??0)*Math.PI/180;return{x:i.x+n.eastM,z:i.z-n.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(n.sizeM?.lengthM??s.lengthM)/2,halfAcrossM:(n.sizeM?.widthM??s.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ae(i.lat,i.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="streetlight"&&!n.lamp?.supposed&&!n.track).map(n=>({x:i.x+n.eastM,z:i.z-n.northM}))}lampNudges=new Map;lampsToKerb(t,e){this.lampNudges.clear();const i=this.decorOriginInRoads(t,e);for(const n of this.decorObjects){if(n.kind!=="streetlight"||!n.lamp?.supposed||n.track)continue;const s=i.x+n.eastM,r=i.z-n.northM,a=this.roadSystem.atKerb(s,r);(a.x!==s||a.z!==r)&&this.lampNudges.set(n.id,{eastM:a.x-s,northM:-(a.z-r)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((i,n)=>{const s=e[n];if(i.id!==s.id||(i.track?.length??-1)!==(s.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(s)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==s[a])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,i=this.terrainProviders.roads;if(!e||!i)return;const n=this.wallsOf(t,e.lat,e.lng),s=this.roadWalls;s?.lat===e.lat&&s.lng===e.lng&&s.walls.length===n.length&&s.walls.every((a,c)=>a.what===n[c].what&&Math.hypot(a.x-n[c].x,a.z-n[c].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,i.contemporary)}wallsOf(t,e,i){const n=this.decorOriginInRoads(e,i);return t.filter(s=>s.kind==="building"||s.kind==="streetlight").map(s=>({what:`${s.kind}:${s.lamp?.supposed?"s":""}${s.headingDeg??0}:${s.sizeM?.widthM??""}:${s.sizeM?.lengthM??""}`,x:n.x+s.eastM,z:n.z-s.northM}))}roadWalls;drapeRoads(t,e,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(t,e,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius,new Si(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,i]=this.sunArriving,n=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?vn.LENS_K:vn.K)*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(t){this.compassHovered!==t&&(this.compassHovered=t,this.updateCompassVisibility())}setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassHovered||this.compassForced;if(this.compassSprites.some(e=>e.visible!==t)){for(const e of this.compassSprites)e.visible=t;this.developingExposure&&!this.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(t){if(z9(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!MN(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=er.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:Bo.steppedOpticalDepth(t.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),n?this.buildPrecipitation():s&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||n||s)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=t.storm&&t.cloudDarkness>=bN,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(lt.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=lt.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ut.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,q9);for(const i of t){const n=ut.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,n,e.indexOf(i)<Z9,i.lamp),i.model&&i.id.startsWith(Ii.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=lt.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=$t(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-CcDlnjiD.js");return{ContrailSystem:t}},__vite__mapDeps([9,10]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),i=this.lastAstronomy?.sun,n=lt.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=ds.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=ke.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*l*c[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(t,e=!1,i){if(this.skyEventsStart=i,t===this.skyEventsStated&&!e)return;this.skyEventsStated=t;let n=!1;const s=new Set;for(const r of vM){const a=Wa.of(r);s.add(a.key);const c=Wa.eventsOf(t,a);let l=this.skyEventLayers.get(a.key);if(l?.kind!==a&&l&&(this.disposeSkyEventLayer(a.key,l),l=void 0),!(!l&&c.length===0)){if(!l)l={kind:a,events:c},this.skyEventLayers.set(a.key,l);else if(l.events===c)continue;l.events=c,n||=a.reachM!==void 0,this.loadSkyEventSimulation(l)}}for(const[r,a]of this.skyEventLayers)s.has(r)||(this.disposeSkyEventLayer(r,a),n||=a.kind.reachM!==void 0);n&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(t){if(t.simulation){this.updateSkyEvents(),this.render();return}t.loading??=t.kind.simulation().then(e=>{if(this.skyEventLayers.get(t.kind.key)!==t)return;const i=e();(i.inSky?this.celestialGroup:this.scene).add(i.object),t.simulation=i,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(t.loading)}disposeSkyEventLayer(t,e){e.simulation?.dispose(),this.skyEventLayers.delete(t),this.skyEventLight(t,[]),this.skyEventGlare(t,[])}skyEventLight(t,e){this.emitterLights.set(`skyEvent:${t}`,[],e.map(i=>this.farEmitterOf(i.position,i.magnitude)).filter(i=>i!==void 0)),this.refreshSkyFlare()}skyEventGlare(t,e){const i=`skyEvent:${t}:`,n=new Set;for(const s of e){const r=i+s.key,{x:a,y:c,z:l}=yi(s.position.altitudeDeg,s.position.azimuthDeg,as),[h,u,d]=this.arrivingIlluminance(s.position,s.magnitude,this.cloudTransmission(s.position));this.setGlare(r,a,c,l,[h*s.fade,u*s.fade,d*s.fade],0,lt.POINT_VEIL_HOLD_DEG),n.add(r)}for(const s of[...this.glareSprites.keys()])s.startsWith(i)&&!n.has(s)&&this.disposeGlare(s)}skyEventReachM(t){let e=0;for(const i of this.skyEventLayers.values())i.events.length>0&&i.kind.reachM&&(e=Math.max(e,i.kind.reachM(i.events,t)));return e}skyEventDrawnCount(t){return this.skyEventLayers.get(t)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const t=this.decorReferencePose;if(this.skyEventLayers.size===0||t?.lat===void 0||t.lng===void 0)return;const e=this.decorCurrentPose,i={lat:e?.lat??t.lat,lng:e?.lng??t.lng,heightM:this.siteElevationM+(e?.lat!==void 0?e.elevationM??0:t.elevationM??0)},n=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,s=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):T0(-90,this.instrumentMagnitudeGain);let r;for(const[a,c]of this.skyEventLayers)c.simulation&&(r??={observer:i,date:n,magnitudeLimit:s,cloudTransmission:l=>this.cloudTransmission(l),arrivingIlluminance:(l,h,u)=>this.arrivingIlluminance(l,h,u),transmittanceFromSpace:l=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,l.altitudeDeg),reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(l,h,u)=>this.transmittanceTo(l,h,u),groundYAt:(l,h)=>this.groundYUnder(l,h),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*Je)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*Je)*this.weather.windSpeed}},c.simulation.update(c.events,this.decorTime,{...r,lightFrom:l=>this.skyEventLight(a,l),glareFrom:l=>this.skyEventGlare(a,l)}));this.render()}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?yi(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}holdUntil(t){this.awaitArrival(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,i=this.groundYUnder(t,e),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(t+s*n,e-r)-i}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*Je)/Math.cos(t.lat*Je)}bodyMaskedByDecor(t,e){const i=this.decorGroups.get(e);return i?this.bodySystem.maskedShare(t,i):void 0}setBodies(t,e=0,i=t.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,c=this.scatteredSky,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*l}))),this.bodySystem.set(t,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(u,d)=>this.groundYUnder(u,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(u,d,f)=>this.transmittanceTo(u,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},e,c?Object.assign((u,d)=>c.relativeOfLuminance(u,d),{recorded:c.recorded}):void 0,i),this.bodySystem.setSmoke(n,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,c,l)=>(a*e+(c+l)/2*s)/Math.PI;return[r(t.r,i.r,n.r),r(t.g,i.g,n.g),r(t.b,i.b,n.b)]}bodyOutline(t,e){return this.bodySystem.outlineOf(t,e)}documentUrl;modelUrl(t){return t.url?this.documentRelative(t.url):void 0}documentRelative(t){if(t.startsWith("data:"))return t;const e=this.documentUrl??(typeof location>"u"?void 0:location.href);return e?new URL(t,e).href:t}async loadBodyModel(t){const e=t.url?void 0:t.id?await this.decorModelProvider.entry(t.id):void 0,i=this.modelUrl(t)??e?.url,n=t.credit??e?.credit;if(!(!i||!n))return{scene:await ug(i),credit:n,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg,bindings:e?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const i=this.loadedDecorModels.get(t.id);return!i||i.ref!==JSON.stringify($g(t))||!ut.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=fA(i.scene);n.traverse(s=>{s instanceof vt&&(s.userData.sharedModel=!0)}),ut.applyModelParameters(n,t.modelParameters,i.bindings),ut.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(n),this.decorModelCredits.set(t.id,i.credit)}mirrors=new Es;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?rb[t.kind]:$g(t);if(!(!n||!ut.usesModel(t)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const c=i||t.kind==="tree"?await this.standInScene(r):await ug(r);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const l=this.decorGroups.get(t.id);if(!l)return;!i&&t.kind!=="tree"&&(re.glaze(c),Zn.reflectOn(c));const h={ref:JSON.stringify(n),scene:c,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(t.id,h),this.applyLoadedDecorModel(t,l,h),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${t.id}":`,s)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=ug(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||Zn.reflectOn(i),i)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,i=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=i;const n=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?ae(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&L0(p.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.lng,s?0:this.gaitOffset.eastM,s?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),s||(n.x-=this.gaitOffset.eastM,n.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let a=0,c;if(s){const p=oa(s,i),m=ut.occupantView(s,p.headingDeg),g=-(p.headingDeg??0)*Je,M=m.x*Math.cos(g)+m.z*Math.sin(g),v=-m.x*Math.sin(g)+m.z*Math.cos(g),x=p.eastM+n.x,y=-p.northM+n.z;r.x=-(x+M),r.z=-(y+v),this.camera.position.y=this.groundYUnder(x,y)+m.eyeY,c=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Je,-(m.headingDeg+this.indoorLookYawDeg)*Je,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const l=this.findCabin(i,n,r);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const m=this.decorGroups.get(p.id);if(!m)continue;const g=oa(p,i),M=this.lampNudges.get(p.id),v=g.eastM+(M?.eastM??0)+n.x+r.x,x=-(g.northM+(M?.northM??0))+n.z+r.z,y=this.terrainMesh,w=`${y?.geometry.uuid}:${(v-(y?.position.x??0)).toFixed(3)}:${(x-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${g.headingDeg}:${g.altitudeM}:${h}`;if(m.userData.footprintKey!==w){if(p.kind==="wire"){const P=ut.wireGround(p,v,x,g.headingDeg,(L,O)=>this.groundYUnder(L,O));m.userData.footprintGroundY=P.startY,ut.shearWire(m,ut.sizeOf(p).lengthM,P.dropM)}else if(p.kind==="crossing"){const P=this.groundYUnder(v,x),L=-(g.headingDeg??0)*Je,O=Math.cos(L),k=Math.sin(L);m.userData.footprintGroundY=P,Ee.drape(ut.bodyOf(m),(H,W)=>this.groundYUnder(v+H*O+W*k,x-H*k+W*O)-P)}else m.userData.footprintGroundY=this.groundUnderFootprint(p,v,x,g.headingDeg,g.altitudeM);m.userData.footprintKey=w}const E=g.altitudeM>lt.AIRBORNE_M&&Math.hypot(v,x)<lt.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY,S=p.id.startsWith(Ii.ID_PREFIX)?lt.trafficHeight(g.altitudeM,m.userData.footprintGroundY):E+g.altitudeM;if(m.position.set(v,S,x),p.kind==="crop"){const P=Math.hypot(v,x);m.visible=P<=lN}const A=this.decorPresence.get(p.id),_=A!==void 0&&(i<A.fromMs||i>A.untilMs);A&&(m.visible=!_);const I=this.decorSunlight.get(p.id);I&&!_&&this.lightFromAbove(m,I),g.headingDeg!==void 0&&(m.rotation.y=-g.headingDeg*Je);const D=o_(p,i);if(D!==void 0&&lt.turnHead(m,g.headingDeg??0,D),p.kind==="crop"&&m.visible){const P=this.terrainMesh,L=[P?.geometry.uuid,v-(P?.position.x??0),x-(P?.position.z??0),m.position.y-(P?.position.y??0),g.headingDeg,g.altitudeM].map(O=>typeof O=="number"?O.toFixed(4):O).join(":");m.userData.cropGroundKey!==L&&(ut.fitCropToGround(m,(O,k)=>this.groundYUnder(O,k)+g.altitudeM),m.userData.cropGroundKey=L)}if(!_){const P=m.position.distanceTo(this.camera.position);a=Math.max(a,P),P<lt.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(s&&c!==void 0){const p=this.decorGroups.get(s.id);p&&(this.camera.position.y=p.position.y+c)}this.updateContrails(),this.updateSkyEvents();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,f=Math.max(s0*1.2,this.groundRadius*2.5,a*1.2,u*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const i=this.terrainYUnder(t,e);let n=i;for(const s of this.terraces){const r=t-s.x,a=e-s.z,c=r*s.cos-a*s.sin,l=r*s.sin+a*s.cos;if(Math.abs(c)<=s.halfWidthM&&Math.abs(l)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(c))/s.bankM)),u=h*h*(3-2*h);n=Math.max(n,u*s.levelY+(1-u)*Math.min(s.levelY,i))}}return n}placeTerraces(t,e,i){this.terraces=[];const n=this.terrainMesh;for(const s of this.decorObjects){if(s.kind!=="terrace")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=oa(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=ut.sizeOf(s),u=-(a.headingDeg??0)*Je,d=Math.cos(u),f=Math.sin(u),p=`${n?.geometry.uuid}:${(c-(n?.position.x??0)).toFixed(3)}:${(l-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(c,0,l),a.headingDeg!==void 0&&(r.rotation.y=u),r.userData.terraceKey!==p&&(r.userData.terraceLevelY=ut.fitTerrace(r,s,(m,g)=>this.terrainYUnder(c+m*d+g*f,l-m*f+g*d)),r.userData.terraceKey=p),this.terraces.push({x:c,z:l,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(t,e){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):Lg}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((t%360+360)%360/(360/n))%n;let r=this.horizonByBearing[s];return Number.isNaN(r)&&(r=this.horizonByBearing[s]=this.marchHorizon(s*360/n)),r}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+lt.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=t*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,c=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let u=l;u<=c;u=Math.max(u+l,u*1.02)){const d=i.x+s*u,f=i.z+r*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):a.position.y+this.groundYOfPatch(a,d-a.position.x,f-a.position.z),m=u*u/(2*lt.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(p-m-i.y,u))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,i){const n=t.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return Lg;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=zr((e-r)/(a-r)*(s-1),0,s-1),u=zr((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return Lg;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,m=u-f,g=(w,b)=>n.getY(w*s+b),M=g(f,d),v=g(f,d+1),x=g(f+1,d),y=g(f+1,d+1);return p+m<=1?M+(v-M)*p+(x-M)*m:y+(x-y)*(1-p)+(v-y)*(1-m)}groundUnderFootprint(t,e,i,n,s=0){return ut.groundUnderFootprint(t,e,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=Cs.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,n,s){const r=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:n??t.iso,autoExposure:t.autoExposure===!0&&n===void 0,maxIso:t.maxIso,metering:s??t.metering??"average",exposureSeconds:e,fNumber:i,development:t.development,exposureFollowMs:t.exposureFollowMs,print:t.print,monochrome:t.monochrome}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),i=t?Cs.NONE:this.perception??Cs.NONE;if(Di.uColorVision.value.set(...i.colorMatrix),Di.uContrast.value=i.contrastGain,!t){Di.uMedium.value=0;return}const n=t.kind==="sensor"&&t.development==="computational";Di.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:n?4:3;const s=t.autoExposure?this.frameLight:void 0,r=t.autoExposure||this.skyUnknown?s?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),c=r===void 0?void 0:r+a.mean,l=d=>.065*t.exposureSeconds*d*this.filterTransmittance/(t.fNumber*t.fNumber*e);let h=c!==void 0&&c>0?1/(e*c):void 0;h!==void 0&&t.metering==="highlights"&&a.brightest>0&&(h=Math.min(h,lt.HIGHLIGHT_KEPT_AT/(.18*e*a.brightest))),h!==void 0&&t.metering==="highlights"&&s&&s.brightest>0&&(h=Math.min(h,lt.ZONE_KEPT_AT/(.18*e*s.brightest)));const u=h!==void 0?Math.min(h,t.maxIso!==void 0?l(t.maxIso):1/0):l(t.iso);Di.uMediumExposure.value=u,Di.uPhoneStrength.value=n&&c!==void 0&&c>0?mr.strengthFor(mr.MID_GREY*u*e*c):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,i=2*Math.atan(Math.tan(e/2)*t.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),s=new R;let r=0,a=0;for(const{position:c,luminanceCdM2:l,solidAngleSr:h}of this.bodySystem.metered.values())s.copy(c).project(t),s.z<1&&Math.abs(s.x)<=1&&Math.abs(s.y)<=1&&(r+=l*h,a=Math.max(a,l*Math.min(1,h/(lt.HIGHLIGHT_SHARE*n))**2));return{mean:r/n,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new tt;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&ut.setLights(s,n.lights,t,s.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(s),this.camera.position),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=n.kind==="vehicle"?ab(n,t):void 0,c=a!==void 0?kc.lamps(a):YM(n,t,this.lastAstronomy?.sun.altitudeDeg);ut.setLit(r,n.kind,c,this.relativeScale,n.lamp);const l=this.streetlightLights.get(n.id);l&&(l.visible=c),a!==void 0&&(this.headlightSettings.set(n.id,a),this.aimDecorBeam(n,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=$t(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-B0Ubhwxs.js");return{HeadlightSystem:t}},[],import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const n=new R(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=ut.sizeOf(t).lengthM,r=e.getWorldPosition(new R).addScaledVector(n,s/2-j9);r.y+=J9;const a=ut.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*Q9,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(t){this.observerHeadlights=t,t&&this.loadHeadlights(),this.headlightSystem&&(t?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const t=this.observerHeadlights;if(!t||!this.headlightSystem?.has("observer"))return;const e=t.setting==="auto"?this.lastAstronomy?kc.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new R(Math.sin(i),0,-Math.cos(i)),s=new R(n.x*cS,this.camera.position.y-eN,n.z*cS);this.headlightSystem.aim("observer",e,s,n,tN,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=ut.bodyOf(e),r=s.children.find(l=>l.userData.emissive);if(!r)return;const a=oS*ut.lampShare(n),c=new dE(16764006,a*this.relativeScale,iN);n?.colorTemperatureK&&c.color.setRGB(...ut.lampHue(n)),c.userData.candela=a,c.position.copy(r.position).multiply(s.scale),c.castShadow=i,c.shadow.mapSize.set(512,512),c.shadow.bias=-.002,e.add(c),this.streetlightLights.set(t,c)}applyWindowGlow(){const t=this.lastAstronomy;ut.setLitWindowShare(t?Un.share(t.sun.altitudeDeg,t.localHour):0)}setAstronomy(t){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-t.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=t,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(t)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=t.sun,this.buildSky(t.sun),this.buildGround();const e=this.magnitudeLimitOf(t);this.buildStars(t.stars,e),this.placeBodies(t,e),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.applySkyColours(t),this.syncAnimationLoop(),this.render()}static relativeSkyOf(t,e){const i=r=>{const a=Ts.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Ut.relativeOfResponse(a)/a;return[r[0]*c,r[1]*c,r[2]*c]},n=i(t.zenith),s=i(t.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=tn.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,rS,new rt(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<C0){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=rS/as*(180/Math.PI),n=i/e.sunRadiusDeg,s=yi(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=yi(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos(zr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?zr(e.separationDeg*n*Je/a,0,2):0,l=Math.sin(a),[h,u]=a>1e-9?[Math.sin((1-c)*a)/l,Math.sin(c*a)/l]:[1,0],d={x:s.x*h+r.x*u,y:s.y*h+r.y*u,z:s.z*h+r.z*u},f=e.moonRadiusDeg*n;this.eclipseDiscs={sun:new R(s.x,s.y,s.z).normalize(),moon:new R(d.x,d.y,d.z).normalize(),sunRadiusRad:i*Je,moonRadiusRad:f*Je};const p=.01,m=(v,x)=>yi(t.sun.altitudeDeg+v,t.sun.azimuthDeg+x,1),g={x:m(p,0).x-m(-p,0).x,y:m(p,0).y-m(-p,0).y,z:m(p,0).z-m(-p,0).z},M={x:m(0,p).x-m(0,-p).x,y:m(0,p).y-m(0,-p).y,z:m(0,p).z-m(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:g,right:M}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new ih(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(t){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(t,this.magnitudeLimitOf(t)),this.applyDazzleStrength(),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.updateSkyEvents());const e=this.scatteredSky?.ambient??lt.relativeSkyOf(Q1(t.sun.altitudeDeg),this.relativeScale),i=e,n=this.lightUnderClouds(t),s=r=>n?[0,1,2].map(a=>r[a]*n.through+n.radiance[a]*(1-n.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=s(i.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Ht.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??oS)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,i.zenith),this.applyAir(),this.buildLunarDiffraction(t.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(t){const e=this.scatteredSky?.ready?this.scatteredSky:void 0;if(t.altitudeDeg<-.5||!e){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,n=(i===void 0?qt.DEFAULT_AEROSOL_OPTICAL_DEPTH:Bo.opticalDepth(i))*qt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=ke.aureoleScale(n,ke.airMass(t.altitudeDeg))*s,c=ke.coronaScale(r),l=ke.illuminanceOf(t.magnitude),h=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),c.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new Ov,this.celestialGroup.add(this.lunarDiffraction.object));const u=ke.profile(ke.HAZE_COARSE_MODE),d=ke.profile(ke.CLOUD_DROPLETS),f=hP(t.altitudeDeg),p=new Float32Array(ke.STEPS*3);let m=0;for(let x=0;x<ke.STEPS;x++){const y=x*3,w=[0,1,2].map(E=>l*f[E]*(a*u[y+E]+c*d[y+E])),b=Ts.shown(w,Ts.luminanceOf(w),(E,S)=>e.relativeOfLuminance(E,S));p.set(b,y),m=Math.max(m,Ts.response(b))}const{x:g,y:M,z:v}=yi(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:g,y:M,z:v}:void 0,p)}applyAir(){this.scene.fog instanceof Oc||(this.scene.fog=new Oc),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+e,Math.hypot(t-n.x,e-n.y,i-n.z))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(t,e){return Math.max(t,e)}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,lt.UMBRA_PATH_M),s=.2126*e+.7152*i+.0722*n;return s>0?[(.4124*e+.3576*i+.1805*n)/s,1,(.0193*e+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:tn.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?tn.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},flare:this.skyFlare}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?rN:sN),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(t){if(t.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new s8(_g),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):T0(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}get plumePuffCount(){return this.skyEventDrawnCount("launches")}get reentryCount(){return this.skyEventDrawnCount("reentries")}flightScreenPoint(t){const e=`${Ii.ID_PREFIX}${t}-`;for(const[i,n]of this.decorGroups){if(!n.visible||!i.startsWith(e))continue;const s=this.screenPointOf(new R().copy(n.position).sub(this.camera.position).normalize());if(s&&Math.abs(s.ndcX)<=1&&Math.abs(s.ndcY)<=1&&!this.groundHides(s.ndcX,s.ndcY))return s}}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(o0*this.camera.fov*Math.PI/180);let s,r=n;const a=new R;for(const[c,l]of this.decorGroups){if(!l.visible||!c.startsWith(Ii.ID_PREFIX))continue;a.copy(l.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,s=c)}return s&&!this.groundHides(t,e)?s:void 0}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(o0*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(t,e)?void 0:n}updateCelestialLight(t,e){const i=this.relativeScale,n=t.sun.altitudeDeg>=xu,s=!n&&t.moon.altitudeDeg>=xu,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Je)),l=this.siteElevationM+this.observerElevationM;let h=r,u=n||s?Fw.directFraction(r.altitudeDeg,l):0;n&&u<=0&&t.moon.altitudeDeg>=xu&&(h=t.moon,u=Fw.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Je)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),m=Math.max(0,1/(1+.1125*p)-f),g=[0,0,0];if(n||s){const b=ke.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let I=0;I<3;I++)g[I]=b*E[I]*m*c,this.cloudBeam[I]=b*E[I];const{x:S,y:A,z:_}=yi(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(S,A,_),u>0){const I=ke.illuminanceOf(h.magnitude)*i,D=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),P=h===r?f:this.cloudTransmission(h);for(let L=0;L<3;L++)a[L]=I*D[L]*P*u}}else this.cloudBeam.fill(0);const M=this.surroundings;if(M)this.skyLight.color.setRGB(M.up[0]*i,M.up[1]*i,M.up[2]*i),this.skyLight.groundColor.setRGB(M.down[0]*i,M.down[1]*i,M.down[2]*i);else{const b=this.skyCloudTransmission(),E=e.skyIrradiance,S=[0,1,2].map(_=>E[_]*b+g[_]);this.skyLight.color.setRGB(S[0],S[1],S[2]);const A=ee.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(S[0]+a[0]*d),A*(S[1]+a[1]*d),A*(S[2]+a[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||u<=0){this.celestialLight.intensity=0;return}const{x:v,y:x,z:y}=yi(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(v,x,y),this.celestialLight.shadow.normalBias=Rg*zr(x/V9,.1,1),this.placeShadowFrustum();const w=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/w,a[1]/w,a[2]/w),this.celestialLight.intensity=w,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(t,e){const i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=ds.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=ke.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=lt.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)n[l]=Math.max(0,a*r[l]*s*c-this.sceneSunBeam[l])}}t.traverse(s=>{const r=s.material;if(!(r instanceof or||r instanceof Ro)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=lt.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new R(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,t);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(t,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*i},c=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(n,a(n)).addScaledVector(s,a(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(c).addScaledVector(t,this.shadowLightDistanceM)}fitShadowToCabin(t){if(t===this.cabinShadow)return;this.cabinShadow=t;const e=this.celestialLight.shadow;if(!t){this.shadowHalfExtentM=-1;return}const i=e.camera,n=G9;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=c0+5,i.near=this.shadowLightDistanceM-c0,i.far=this.shadowLightDistanceM+c0,i.updateProjectionMatrix(),e.bias=-.004/(2*c0),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==lt.CABIN_SKY_SHARE&&(r.envMapIntensity=lt.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(H9,Math.max(_a,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const i=this.celestialLight.shadow,n=i.camera;n.left=-e,n.right=e,n.top=e,n.bottom=-e;const s=Math.max(Pl,e*(Pl/_a));this.shadowLightDistanceM=Math.max(as,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-Tg/(2*s);const r=e>2*_a?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=_a;shadowLightDistanceM=as;shadowUp=new R(0,1,0);shadowAxisX=new R;shadowAxisY=new R;shadowWorld=new R;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*Je,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)t+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),e+=s}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new R(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Ut.semiSaturation(Ut.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new Rn,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem&&(this.meteorSystem.update(t),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(e=>this.farEmitterOf(e,e.magnitude)).filter(e=>e!==void 0)),this.refreshSkyFlare())}farEmitterOf(t,e){if(!(t.altitudeDeg>0)||!Number.isFinite(e))return;const i=Math.max(this.relativeScale,1e-30),n=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:s,y:r,z:a}=yi(t.altitudeDeg,t.azimuthDeg,1);return{direction:new R(s,r,a),lux:[n[0]/i,n[1]/i,n[2]/i],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const i=Xi.starPointsOf(t,e);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(t){const e=At.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return T0(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(t,e=!1,i=0){const n=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(e,n,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const t=this.compileOffThread().then(()=>{this.compiling===t&&(this.compiling=void 0,this.render())});this.compiling=t;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+lt.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of t){const a=e.get(r)?.currentProgram;(!a||a.isReady())&&t.delete(r)}t.size===0||performance.now()>i?n():setTimeout(s,10)};s()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e);const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(t,e,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"&&s.kind!=="vehicle"||s.observerSide!==void 0&&L0(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=oa(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=ut.sizeOf(s),u=Math.max(h.widthM,h.lengthM)/2;Math.hypot(c,l)<u&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<u&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new Zn(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(c=>c.mesh)],i=[...this.starTiers.map(c=>c.points),...[...this.bodyMeshes.values()].filter(c=>c instanceof Bs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(c=>c!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(c=>c.name.startsWith("body:")),...[this.meteorSystem?.object].filter(c=>c!==void 0),...[...this.skyEventLayers.values()].filter(c=>c.simulation?.hiddenFromEye).map(c=>c.simulation.object)],n=this.relativeScale,s=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,c=>this.measureSurroundings(c,n,s,r),t?0:Zn.REFRESH_MS);a===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},a))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,lt.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,n){const s=this.lastAstronomy;if(!s)return;this.probeIrradiance??=new jl,this.framePhotograph={texture:t,scale:e,atMs:n};const r=[s.sun,s.moon].filter(a=>a.altitudeDeg>-2).map(a=>yi(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,r,a=>{const c=p=>p.map(m=>m/e),l=this.surroundings,h={up:c(a.up),down:c(a.down)},u=(p,m)=>p.some((g,M)=>Math.abs(g-m[M])>.03*Math.max(Math.abs(g),Math.abs(m[M]),1e-12)),d=!l||u(l.up,h.up)||u(l.down,h.down);d&&(this.surroundings=h),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(lt.adaptingLuminance(Math.exp(a.logAverage)/e,h.down))??!1;if(!d&&!f){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=xu?t.sun:t.moon.altitudeDeg>=xu?t.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*n,e.up[1]*n,e.up[2]*n]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new pr;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?yi(e.altitudeDeg,e.azimuthDeg,1):void 0,n=this.medium.exposureFollowMs??lt.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,i,s=>{const r={mean:s.mean/t.scale,brightest:s.brightest/t.scale},a=this.frameLight,c=t.atMs,l=a?c-a.atMs:1/0,h=l<0||l>lt.EXPOSURE_JUMP_MS,u=h||l===0&&a?.jumped?1:1-Math.exp(-l/n),d=(m,g)=>m>0&&g>0?m*(g/m)**u:g,f={mean:d(a?.mean??0,r.mean),brightest:d(a?.brightest??0,r.brightest),atMs:c,jumped:h||l===0&&(a?.jumped??!1)};this.frameLight=f;const p=(m,g)=>Math.abs(m-g)>.01*Math.max(m,g);(!a||p(a.mean,f.mean)||p(a.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Di.uRetinaOn.value=0,this.medium)return;const t=[];for(const a of this.emitterLights.farEmitters){const c=this.screenPointOf(a.direction);!c||Math.abs(c.ndcX)>1.2||Math.abs(c.ndcY)>1.2||t.push({ndcX:c.ndcX,ndcY:c.ndcY,lux:Ts.luminanceOf(a.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),i=e.x/Math.max(e.y,1),n={width:this.camera.fov*i,height:this.camera.fov},s=this.retina?.atMs;if((s===void 0||this.recordingTimeMs<s||this.recordingTimeMs-s>le.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new le,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),n,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new le,this.retina.advance(this.recordingTimeMs,t,n)}this.retina.any&&(Di.uRetina.value=this.retina.texture,Di.uRetinaOn.value=1,Di.uRetinaViewport.value.copy(e))}retinaSize=new tt;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const i=this.retinaHistory?.(t);if(!i||i.views.length===0)return[];const n=i.pose,s=this.historicQuaternion.setFromEuler(this.historicEuler.set((n?.pitchDeg??0)*Je,-(n?.headingDeg??0)*Je,(n?.rollDeg??0)*Je,"YXZ")).invert(),r=n?.fovDeg??this.camera.fov,a=[];for(const c of i.views){const l=this.farEmitterOf(c.head,c.magnitude);if(!l)continue;const h=this.screenPointIn(this.historicDirection.copy(l.direction).applyQuaternion(s),r,e);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||a.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:Ts.luminanceOf(l.lux)})}return a}historicQuaternion=new is;historicEuler=new ma;historicDirection=new R;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<lt.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(t){this.recordingTimeMs=t}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(t){const e=[];for(const i of t)i.traverse(n=>{n.userData.emissive===!0&&e.push(n)});return e}surroundings;animate(t,e){const i=Math.min(e/1e3,SN);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),ut.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,c)=>this.directionAtScreenPoint(r,a,c),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[EM]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},Es.INTERVAL_MS)),Di.uRodShare.value=this.scatteredSky?.rodShare??0,Di.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Di.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),s,r=>{this.lensFlare&&(this.lensFlare.mesh.visible=r?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof Bs&&e.userData.pointSource||e instanceof vt&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(s=>s.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Eg),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(mA),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new ps({blending:Uc,blendSrc:sa,blendDst:sa,blendSrcAlpha:sa,blendDstAlpha:sa,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(this.references.layer),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}setReferences(t,e){const i=t.map(n=>{const s=this.documentRelative(n.src);return s===n.src?n:{...n,src:s}});if(this.references){this.references.set(i,void 0,e);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:e},this.referencesLoading??=$t(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-Vgg3SwB1.js");return{ReferenceSystem:n}},[],import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=s,s.onFrame=()=>this.render(),this.referenceClock&&s.setTime(this.referenceClock);for(const[a,c]of this.referenceViews)s.setView(a,c);s.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&s.set(r.references,void 0,r.observerAt),this.render(),s})}setReferencesTime(t){this.referenceClock=t,this.references?.setTime(t)}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new R)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.y1<-1))return;const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const s=e?this.narrowTo(t,e):t,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse)),a=this.phenomena.furthestM;let c=0;for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const u=l.kind!=="crop"&&this.mayHide(h,t,r,a);lt.markDecorDepth(h,u),u&&c++}c>0&&(t.layers.set(bg),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(EM),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}phenomenaFrustum=new Rp;phenomenaViewProjection=new Vt;occluderSphere=new ar;localBounds=new WeakMap;mayHide(t,e,i,n){let s=0;t.traverse(()=>s++);let r=this.localBounds.get(t);if(!r||r.objects!==s){t.updateMatrixWorld(!0);const c=new Ke().setFromObject(t);if(c.isEmpty())return!1;r={sphere:c.getBoundingSphere(new ar).applyMatrix4(new Vt().copy(t.matrixWorld).invert()),objects:s},this.localBounds.set(t,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(t.matrixWorld);return a.center.distanceTo(e.position)-a.radius>n?!1:i.intersectsSphere(a)}narrowTo(t,e){const i=this.renderer.getDrawingBufferSize(new tt),n=lt.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),s=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*i.x-n)),r=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*i.y-n)),a=Math.min(i.x,Math.ceil((Math.min(1,e.x1)+1)/2*i.x+n)),c=Math.min(i.y,Math.ceil((Math.min(1,e.y1)+1)/2*i.y+n)),l=this.narrowCamera.copy(t);return l.setViewOffset(i.x,i.y,s,i.y-c,Math.max(1,a-s),Math.max(1,c-r)),l.updateMatrixWorld(),l}narrowCamera=new Bn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new ps({colorWrite:!1,side:xn});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const n=t.getObjectByName("head");if(!n)return;const s=((i-e)%360+540)%360-180,r=Math.max(-85,Math.min(lt.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*Je}static isSolidSurface(t){if(!(t instanceof vt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==En}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof vt))return;e&&lt.isSolidSurface(i)?i.layers.enable(bg):i.layers.disable(bg)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new tt),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new JC(e,i)),this.exposureAccumulation.resize(e,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+lt.EXPOSURE_BUDGET_MS,s=lt.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let r=0;do{this.restateAt(t,this.exposureInstantsDone);const a=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((c,l)=>{c.visible=a[l]})}e.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Di.uRodShare.value=this.scatteredSky?.rodShare??0,Di.uHasOverlay.value=1,Di.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Ws,n=new Xs(-1,1,1,-1,0,2),s=h0/(hS*Math.tan(uS*Je/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new R).sub(this.camera.position).normalize(),l=this.screenPointOf(c);if(!l)continue;const h=new eu(a.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(s/this.camera.aspect,s,1),i.add(h)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,n)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new Ke,i=new R,n=this.camera.getWorldDirection(new R),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(e.setFromObject(a),e.isEmpty())||e.distanceToPoint(this.camera.position)<lt.MAP_SUBJECT_NEAREST_M)continue;let c=1/0,l=-1/0,h=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const g=(m.ndcX+1)/2,M=(1-m.ndcY)/2;c=Math.min(c,g),l=Math.max(l,g),h=Math.min(h,M),u=Math.max(u,M)}c=Math.max(c,0),l=Math.min(l,1),h=Math.max(h,0),u=Math.min(u,1),l>=c&&u>=h&&t.push({x:c,y:h,width:l-c,height:u-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}usableDepthOfFieldPass(){const t=this.lensOptics;if(!t)return;const e=this.renderer.getDrawingBufferSize(new tt),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new Gu(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.depthOfFieldPass}setLensGhosts(t){JSON.stringify(t)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=t,t.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(t,e){return this.ghostPass?.holdsPictureAt(this.renderer,t,e)??!1}pickGhostAt(t,e){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,t,e,this.ghostOptics,Di.uMediumExposure.value)}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new tt);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new Ji(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new tt);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new Pv(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new tt);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new Ri(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){this.aimStraightAtScreenPoint(t,e,i),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,n=>{const s=lt.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!s||s.distance>=n-.001||this.mirrors.isMirror(s.object)})}aimStraightAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new tt(e,i),this.camera);return}const s=n.directionFor(e,i,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(s.x,s.y,s.z).applyQuaternion(this.camera.quaternion).normalize(),t.camera=this.camera}pickCloudAt(t,e){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(t,e))}cloudDirectionAt(t,e){return this.directionAtScreenPoint(t,e,new R)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);return this.screenPointIn(e,this.camera.fov,n)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Ri.ndcFor(t,e,i);if(t.z>=0)return;const n=Math.tan(e/2*Je);return{ndcX:t.x/-t.z/(i*n),ndcY:t.y/-t.z/n}}screenPointScratch=new R;screenPointQuaternion=new is;screenPointSize=new tt;updateLensFlarePosition(){const t=this.lensFlare;if(!t)return;if(!this.sunVisible){t.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){t.mesh.visible=!1;return}const e=this.sunVisibleFraction();if(e<=0){t.mesh.visible=!1;return}t.mesh.visible=!0,this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;t.uniforms.uResolution.value.set(n,s),t.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const t=this.lensFlare;if(!t||!t.mesh.visible)return;const e=this.sunDiscRadiance.map(l=>Math.max(0,l-lt.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const i=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,n=Math.PI*i*i,s=t.uniforms.uLensPosition.value,r=t.uniforms.uTanHalfFov.value,a=this.camera.aspect,c=pi.offFrameShare(Math.atan(Math.hypot(s.x*a,s.y)*r)*180/Math.PI,Math.atan(Math.hypot(a,1)*r)*180/Math.PI);if(!(c<=0))return{x:s.x,y:s.y,radius:i,flux:[e[0]*n*c,e[1]*n*c,e[2]*n*c]}}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!i)return;const n=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),t.uniforms.uResolution.value.set(n.x,n.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(nS),this.camera.layers.set(nS),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of pS)this.isSunOccluded(e[0],e[1])||t++;return t/pS.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,i=0){const n=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&n.length===0)return!1;const s=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),r=s.length();if(s.normalize(),e!==0||i!==0){const l=Math.PI/180,h=this.sunOcclusionRightScratch.set(s.z,0,-s.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const u=this.sunOcclusionUpScratch.crossVectors(h,s).normalize();s.addScaledVector(h,e*l).addScaledVector(u,i*l).normalize()}if(this.groundBlocks(this.camera.position,s,r)||this.cabinMask.hides(s))return!0;const a=this.cabinMask.any?n.filter(l=>!this.cabinGroups.includes(l)):n;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,s);const c=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(l=>!(l.object.material instanceof $a));return c!==void 0&&c.distance<r}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let t=!1;for(const e of this.glareSprites.values()){if(!e.mesh.visible)continue;t||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),t=!0);const i=e.mesh.getWorldPosition(this.veilTargetScratch),n=e.mesh.material.uniforms.uSourceDeg.value,s=n>.05?lt.VEIL_SAMPLES:lt.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,c]of s)this.isOccludedToward(i,a*n,c*n)||r++;e.share=r/s.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new xs;veilTargetScratch=new R;groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const g=(s.position.y-t.y)/e.y;if(g>n&&g<i){const M=t.x+e.x*g-s.position.x,v=t.z+e.z*g-s.position.z;if(Math.hypot(M,v)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const l=[r.position.x+a.getX(0),r.position.x+a.getX(c-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((c-1)*c)],u=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(c-1);if(!(u>0))return!1;let d=n,f=i;for(const[g,M,v]of[[t.x,e.x,l],[t.z,e.z,h]]){const x=Math.min(v[0],v[1]),y=Math.max(v[0],v[1]);if(Math.abs(M)<1e-12){if(g<x||g>y)return!1;continue}const w=(x-g)/M,b=(y-g)/M;d=Math.max(d,Math.min(w,b)),f=Math.min(f,Math.max(w,b))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),m=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let g=0;g<=m;g++){const M=d+(f-d)*g/m,v=t.x+e.x*M,x=t.y+e.y*M,y=t.z+e.z*M;if(x<=this.groundYUnder(v,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=r0;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const c=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(l=>lt.isSolidSurface(l.object));c&&(r.occludesSourceIds?.includes(i)?n=n===void 0?c.distance:Math.max(n,c.distance):s=s===void 0?c.distance:Math.min(s,c.distance))}return{behindM:n,inFrontM:s}}pickBodyAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.origin,n=this.raycaster.ray.direction,s=W9*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new R).sub(i);return{key:h,direction:d.clone().normalize(),radiusRad:Math.atan2(u.scale.x/2,d.length())}}),a=this.eclipseDiscs,c=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],l=lt.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...c],s);if(l)return this.groundHides(t,e)?void 0:l}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(t,e)?i:void 0}static nearestBody(t,e,i){let n,s=1/0,r=1/0,a=!1;for(const c of e){const l=Math.acos(zr(c.direction.dot(t),-1,1))-c.radiusRad;if(l>i)continue;const h=l<=0,u=s<=0,d=c.inFront===!0;(h!==u?h:h?d!==a?d:c.radiusRad<r:l<s)&&(n=c.key,s=l,r=c.radiusRad,a=d)}return n}pickInterpretationBodyAt(t,e){const i=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=B9*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?lt.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const u=new Ke,d=new R;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new R).length()/2,m=d.clone().sub(s),g=m.length();if(g===0||m.dot(n)<=0||c!==void 0&&c<g-p)continue;const M=Math.acos(Math.min(1,m.normalize().dot(n))),v=Math.atan(p/g);if(v>r){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||c!==void 0&&c<x.distance)continue}else if(M>r)continue;v<h&&(h=v,l=f.name.slice(5))}return l}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(o0*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const c=a.direction.dot(i);c>r&&(r=c,s={star:a.star,altitudeDeg:a.altitudeDeg})}return s&&this.groundHides(t,e)?void 0:s}groundHides(t,e){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,1/0,r0)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let a=0;a<8;a++){const c=this.bodyCornerScratch.set(a&1?e.max.x:e.min.x,a&2?e.max.y:e.min.y,a&4?e.max.z:e.min.z),l=this.screenPointOf(c.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),s=Math.max(s,l.ndcX),n=Math.min(n,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new Ke;bodyCornerScratch=new R;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;const i=this.bodyBoxScratch.setFromObject(e);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-1/0;for(let c=0;c<8;c++){const l=this.bodyCornerScratch.set(c&1?i.max.x:i.min.x,c&2?i.max.y:i.min.y,c&4?i.max.z:i.min.z),h=this.screenPointOf(l.sub(this.camera.position).normalize());if(!h)return;n=Math.min(n,h.ndcX),r=Math.max(r,h.ndcX),s=Math.min(s,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:n,minY:s,maxX:r,maxY:a}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,i,n=0){const s=this.decorGroups.get(t);if(!s)return;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(s.position.y+n)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(t){const e=this.decorGroups.get(t);return e?Math.hypot(e.position.x-this.camera.position.x,e.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(t){const e=this.decorGroups.get(t);return e?e.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Je/2):0}decorGrabHeightAt(t,e,i){const n=this.decorGroups.get(t);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.decorHitScratch.set(this.camera.position.x-n.position.x,0,this.camera.position.z-n.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,n.position),c=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return c?Math.min(Math.max(c.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new yr;decorHitScratch=new R;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&(s.transparent&&s.opacity<lt.SEE_THROUGH_BELOW||s instanceof $a))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=lt.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray;i.group.updateMatrixWorld();const s=new Xc().copy(n).applyMatrix4(new Vt().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(d,f)=>{const p=new R(d,0,f).applyMatrix4(r);return this.groundYUnder(p.x,p.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,lt.RAILWAY_PICK_ABOVE_M))return;const c=lt.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!c||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,c.distance-lt.RAILWAY_GROUND_MARGIN_M,r0))return;const l=i.group.worldToLocal(c.point.clone()),h=i.lineAt(l.x,l.z);if(!h)return;const u=i.contactHeightM(h);return{line:h,distanceM:c.distance,...u!==void 0?{contactM:u}:{}}}pickSkyEventAt(t,e,i=()=>!0){const n=[...this.skyEventLayers.values()].filter(l=>l.simulation?.pick&&l.simulation.drawnCount>0&&i(l.kind,l.simulation));if(n.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray,r={toleranceRad:lt.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(o0*this.camera.fov*Math.PI/180),skyLightTowards:l=>this.skyLightTowards(l)};let a;for(const l of n){const h=l.simulation.pick(s.origin,s.direction,r);h&&(!a||(h.distanceM??1/0)<(a.distanceM??1/0))&&(a={kind:l.kind.key,...h})}if(!a)return;if(a.distanceM===void 0)return this.groundHides(t,e)?void 0:a;if(this.terrainMesh&&this.groundBlocks(s.origin,s.direction,a.distanceM-1,r0))return;const c=lt.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(c&&c.distance<a.distanceM))return a}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(t.x,t.y,t.z)||1,s=Math.max(0,Math.min(1,t.y/n));return i(e.horizon)+(i(e.zenith)-i(e.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0;for(const t of this.skyEventLayers.values())t.simulation?.dispose();this.skyEventLayers.clear(),this.skyEventsStated=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())ut.dispose(t);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new R;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<lt.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new rn(s0,32,16),i=e.attributes.position,n=e.getAttribute("color")??new fe(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=PE(i.getX(r),i.getY(r),i.getZ(r)),l=oP(a,c,t.azimuthDeg,t.altitudeDeg);n.setXYZ(r,l[0],l[1],l[2])}if(n.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",n);const s=new ps({vertexColors:!0,side:Ci,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new vt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=sS(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new lv(this.groundRadius,48),i=new or({color:new rt(Ag,Ag,Ag),fog:!0});Oc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new vt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(e?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=yi(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,e);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-Oe.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*$9);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Oe.iceAlphaAt(i,l0,r,this.cloudFieldOffset)*K9),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<C0){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:c}=yi(e.altitudeDeg,e.azimuthDeg,as),l=this.cloudTransmission(e),h=this.arrivingIlluminance(e,s,l),u=lt.unitLuminance(n);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/as)**2,p=[0,1,2].map(g=>u[g]*h[g]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const m=p.map(g=>Math.min(lt.BRIGHTEST_RELATIVE,g));d instanceof vt||(this.disposeMesh(d),d=new vt(new rn(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(m[0],m[1],m[2]),d.scale.setScalar(i)}else{if(!(d instanceof Bs)){this.disposeMesh(d);const m=new ye;m.setAttribute("position",new Me(new Float32Array(3),3)),m.setAttribute("color",new Me(new Float32Array(3),3)),d=new Bs(m,Ht.material(yh[yh.length-1].size,!1)),Ht.track(d),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)}const f=d.geometry.getAttribute("color"),p=t.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*h[0]*p,u[1]*h[1]*p,u[2]*h[2]*p),f.needsUpdate=!0}if(d.position.set(r,a,c),this.setHitArea(t,r,a,c,i),t==="sun"&&(this.sunArriving=h),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,r,a,c,h,i/as*(180/Math.PI),lt.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,a*f+this.celestialGroup.position.y,c*f),this.lensFlare||(this.lensFlare=n8(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(t,e){const i="moon";if(t.magnitude>e||t.altitudeDeg<C0){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=yi(t.altitudeDeg,t.azimuthDeg,as),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),l=t.radiusDeg??jr.MEAN_RADIUS_DEG,h=as*Math.tan(l*Je),u=Math.max(zr(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/as)**2,d=new rt(...c.map(m=>Math.min(lt.BRIGHTEST_RELATIVE,m/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(zr(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof eu?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=CS(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new eu(new b0({map:CS(t.phase),color:d,fog:!1,blending:En,depthWrite:!1})),p.userData.phaseKey=f,this.celestialGroup.add(p),this.bodyMeshes.set(i,p)),p.scale.set(h*2,h*2,1),p.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,c,l)}bentLight(t,e,i=X9){const[n,s,r]=this.arrivingIlluminance(t,e,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(t,e){return lt.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new rt;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Ht.CONE_SOLID_ANGLE/e)}pointScratch=new tt;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),s=ke.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Ts.luminanceOf([t.r,t.g,t.b]);return e>0?[t.r/e,t.g/e,t.b/e]:[1,1,1]}setHitArea(t,e,i,n,s){let r=this.hitAreas.get(t);if(!r){const c=new b0({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new eu(c),this.celestialGroup.add(r),this.hitAreas.set(t,r)}r.position.set(e,i,n);const a=s*2;r.scale.set(a,a,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,i,n,s,r,a=0){if(vn.radiusDeg(vn.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new vn(`veil:${t}`),this.celestialGroup.add(c.mesh),this.glareSprites.set(t,c)),c.shine({x:e,y:i,z:n},s,r,a)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const i=t&&`comet:${t.id}`;if(!t||!i||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=ql(t.magnitude,e),s=tg(n);this.cometKey=i,this.setBodyMesh(i,t.position,Ig*(.5+.5*n),new rt(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new Fs(as),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Gi,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const i=this.highCloudCover(),n=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(n?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),i===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:l0},0);return}const s=this.lowerCloudCover(),r=we.deckLitUntilDeg(we.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?de.SUN_MAGNITUDE:e.magnitude),l=we.strength(i,s,a.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=yi(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},a.altitudeDeg,l,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??l0},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??HA,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new Ec,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=t.altitudeDeg>0,s=n?t:e,r=this.lowerCloudCover(),a=this.bentLight(s,n?de.SUN_MAGNITUDE:e.magnitude,Y9),c=Us.strength(i,r,s.altitudeDeg)*a.scale;if(c<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:l,y:h,z:u}=yi(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},c,a.tint,n)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new So,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=gr.galactic(i,n),r=lt.directionOf(s.centre),a=lt.directionOf(s.rotation),c=lt.directionOf(s.pole),l=new ue().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),h=lt.directionOf(gr.eclipticPole(i,n)),u=lt.directionOf(t.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:lt.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new R(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=yi(t.altitudeDeg,t.azimuthDeg,1);return new R(e,i,n).normalize()}buildNovae(t,e){const i=new Set;for(const n of t){if(n.magnitude>e)continue;const s=`nova:${n.id}`;i.add(s);const r=ql(n.magnitude,e),a=tg(r);this.setBodyMesh(s,n.position,Ig*(.5+.5*r),new rt(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of t){if(n.magnitude>e)continue;i.add(n.body);const s=ql(n.magnitude,e),r=tg(s),a=_N[n.body]??new rt(1,1,1),c=new rt(a.r*r,a.g*r,a.b*r),l=Ig*(.5+.5*s);this.setBodyMesh(n.body,n.position,l,c,n.magnitude)}for(const n of[...this.bodyMeshes.keys()])i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n))}buildStars(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=t,r=new xr(n,s),a=zg(1337),c=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(d<aS)continue;const{x:p,y:m,z:g}=yi(d,f,_g);c.push({x:p,y:m,z:g,brightness:ql(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(M=>M*ke.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of PO){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<aS)continue;const{x:f,y:p,z:m}=yi(u,d,_g);this.namedStars.push({star:h,direction:new R(f,p,m).normalize(),altitudeDeg:u})}this.starTiers=yh.map((h,u)=>{const d=c.filter(w=>xv(w.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),m=new Float32Array(d.length*3),g=new Float32Array(d.length),M=new Float32Array(d.length);d.forEach((w,b)=>{f[b*3]=w.x,f[b*3+1]=w.y,f[b*3+2]=w.z,p[b]=w.brightness,m.set(w.illuminance,b*3),g[b]=w.phase,M[b]=w.speedFactor});const v=new ye;v.setAttribute("position",new Me(f,3)),v.setAttribute("seed",new Me(g.map(w=>w/(2*Math.PI)),1));const x=new Me(new Float32Array(d.length*3),3);v.setAttribute("color",x);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=v):(y=new Bs(v,Ht.material(h.size)),Ht.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:x,brightness:p,illuminance:m,phase:g,speedFactor:M}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Ht.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;for(const i of this.starTiers){const n=i.colorAttribute.array;for(let s=0;s<i.brightness.length;s++)n[s*3]=i.illuminance[s*3]*e,n[s*3+1]=i.illuminance[s*3+1]*e,n[s*3+2]=i.illuminance[s*3+2]*e;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new vh(this.celestialGroup,Dg,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new rt(cc[0]+(Og[0]-cc[0])*e,cc[1]+(Og[1]-cc[1])*e,cc[2]+(Og[2]-cc[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=K1(i,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=n,this.cloudUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=q1(Dg);this.cloudMesh=new vt(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:i}=K1(new rt(...cc),t,l0,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new vt(q1(Dg*1.04),e),this.cirrusMesh.renderOrder=mS-1,this.celestialGroup.add(this.cirrusMesh)}disposeCirrus(){this.cirrusMesh&&(this.cirrusMesh.removeFromParent(),this.cirrusMesh.geometry.dispose()),this.cirrusMaterial?.dispose(),this.cirrusMesh=void 0,this.cirrusMaterial=void 0,this.cirrusUniforms=void 0}syncCloudLayer(){this.layeredClouds?.update(this.weather,this.observerElevationM+1.6);const t=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(t)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,t)}faceCloudDeck(t,e){const i=e<0;t.scale.y=i?-1:1,t.renderOrder=i?vh.deckOrder(!0,0,1):mS}cloudLayerOffset(){const e=((this.weather.cloudBaseM??UM)-this.observerElevationM)*Cg;return Math.sign(e||1)*Math.max(Math.abs(e),cN)}updateCloudLighting(t,e){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,a]=this.cloudBeam.map(u=>u/Math.PI),c=this.lightningLevel*Fg*this.relativeScale/Math.PI,l=new rt(e[0]+Nr.r*c,e[1]+Nr.g*c,e[2]+Nr.b*c);this.layeredClouds?.setLighting(n.clone(),new rt(s,r,a),l,l);const h=Math.max(0,n.y);for(const u of i)u.sunDir.value.copy(n),u.sunColor.value.setRGB(s*h,r*h,a*h),u.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return gN(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,kg],[this.rainSplashSystem?.points,lc],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:Ng[this.weather.precipitationType].poolSize]];for(const[e,i]of t)e&&i!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=yS(Ug(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const t=this.weather.precipitationType;if(t==="none")return;if(t==="rain"){this.buildRain();return}const e=Ng[t],i=e.poolSize,n=zg(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),c=new Float32Array(i),l=new Float32Array(i),h=new Float32Array(i),u=new Float32Array(i),d=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let x=0;x<i;x++){const y=n()*Math.PI*2,w=n()*e.radiusM;s[x*3]=Math.cos(y)*w,s[x*3+1]=Ul+n()*(e.topYM-Ul),s[x*3+2]=Math.sin(y)*w,r[x]=n()*Math.PI*2,a[x]=.7+n()*.6,c[x]=.6+n()*.8,l[x]=.4+n()*1.2}const m=new ye;m.setAttribute("position",new Me(s,3)),m.setDrawRange(0,this.precipitationCount(i));const g={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new rt(...this.baseFogColor)},uTexture:{value:TN(t)},uNearFocusDistance:{value:bS},uHazeDistance:{value:e.radiusM*ES}},M=new Te({uniforms:g,vertexShader:ON,fragmentShader:NN,transparent:!0,depthWrite:!1});this.precipitationUniforms=g;const v=new Bs(m,M);v.renderOrder=Pg,this.scene.add(v),this.precipitationPoints=v,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const i=this.weather.precipitationType;if(i==="none"||i==="rain")return;const n=Ng[i];if(this.precipitationUniforms?.uColor.value.copy(lt.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*Je,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,c=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,m=this.precipitationBounceDuration,g=this.precipitationBounceVelX,M=this.precipitationBounceVelZ,v=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&m&&g&&M;for(let y=0,w=0;y<c.length;y+=3,w++){if(x&&f[w]>0){if(f[w]-=e,f[w]<=0){const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(S)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(S)*A,f[w]=0}else{const S=1-f[w]/m[w];c[y+1]=Ul+Math.sin(Math.PI*S)*p[w],c[y]=u0(c[y]+(r+g[w])*e,n.radiusM),c[y+2]=u0(c[y+2]+(a+M[w])*e,n.radiusM)}continue}let b=0,E=0;if(v){const S=vN*u[w],A=yN*d[w];b=Math.sin(t*S*Math.PI*2+l[w])*A,E=Math.sin(t*S*Math.PI*2+l[w]+Math.PI/2)*A}if(c[y]+=(r+b)*e,c[y+1]-=n.fallSpeedMPerS*h[w]*e,c[y+2]+=(a+E)*e,c[y]=u0(c[y],n.radiusM),c[y+2]=u0(c[y+2],n.radiusM),c[y+1]<Ul){if(x){p[w]=IS*(.2+Math.random()*1.6),m[w]=xN*(.5+Math.random()),f[w]=m[w];const _=Math.random()*Math.PI*2,I=wN*(p[w]/IS);g[w]=Math.cos(_)*I,M[w]=Math.sin(_)*I,c[y+1]=Ul;continue}const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[y]=Math.cos(S)*A,c[y+1]=n.topYM,c[y+2]=Math.sin(S)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=Ug(this.weather.precipitationIntensity);this.rainSystem=t8({count:kg,radiusM:wu,heightM:hN,bottomYM:gS,overallSpeed:uN,color:vS.clone(),opacity:.85,visibleCount:this.precipitationCount(kg),speedStreak:yS(t),pixelSize:_S,seed:9001,nearFocusDistanceM:bS,hazeDistanceM:wu*ES,hazeColor:new rt(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=Pg,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=zg(4242),e=new Float32Array(lc*3),i=new Float32Array(lc),n=new Float32Array(lc),s=new Float32Array(lc);for(let h=0;h<lc;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*wu;e[h*3]=Math.cos(u)*d,e[h*3+1]=gS,e[h*3+2]=Math.sin(u)*d,n[h]=DS(xS,wS),i[h]=t()*n[h],s[h]=i[h]/n[h]}const r=new ye;r.setAttribute("position",new Me(e,3));const a=new Me(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(lc));const c=new Te({uniforms:{uMaxSize:{value:mN},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:SS.clone()},uTexture:{value:DN()}},vertexShader:CN,fragmentShader:PN,transparent:!0,depthWrite:!1}),l=new Bs(r,c);l.renderOrder=Pg,this.scene.add(l),this.rainSplashSystem={points:l,positions:e,life:i,duration:n,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*Je;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-Ug(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(lt.litBySky(vS,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(lt.litBySky(SS,this.baseFogColor));const n=this.weather.windDirectionDeg*Je,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=wu,c=h=>(h%(a*2)+a*3)%(a*2)-a;e.uniforms.uWindOffset.value.set(c(e.uniforms.uWindOffset.value.x+s*t),c(e.uniforms.uWindOffset.value.y+r*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=TS+(1-TS)*(1-l),u=RS+(1-RS)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=_S*h*(.5+.5*u)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=e,a=r.array;for(let c=0,l=0;c<i.length;c+=3,l++){if(n[l]+=t,n[l]>=s[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*wu;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=DS(xS,wS),n[l]=0}a[l]=n[l]/s[l]}e.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,i=0;if(this.lightningArmed)for(const c of this.lightningFlashes){if(c.t>t)break;const l=mn.brightnessAt(c,t);l>i&&(e=c,i=l)}const n=e?Math.min(1,Math.max(.1,(EN/e.distanceM)**2)):0,s=i*n*(e?.cloudToGround?1:.6);if(s===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const c=this.scene.fog,l=s*Fg*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+Nr.r*l,this.airlight[1]+Nr.g*l,this.airlight[2]+Nr.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*AN;r.setRGB(1+c*Nr.r,1+c*Nr.g,1+c*Nr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*Fg*this.relativeScale,e){const{x:c,y:l,z:h}=yi(25,e.azimuthDeg,as);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new bo(as*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=nN.map(t=>{const e=Pc.point(t,this.compassPoints),i=new b0({map:LN(e),depthTest:!1,fog:!1}),n=new eu(i),{x:s,y:r,z:a}=yi(0,t,hS);return n.position.set(s,r,a),n.scale.set(h0,h0,1),n.renderOrder=aN,n.layers.set(Eg),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=uS*Math.PI/360,i=h0*Math.tan(t)/Math.tan(e);for(const n of this.compassSprites)n.scale.set(i,i,1)}disposeCompassLabels(){for(const t of this.compassSprites)t.removeFromParent(),t.material.map?.dispose(),t.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const t of this.starTiers)this.disposeMesh(t.points);this.starTiers=[]}disposeMesh(t){if(!t)return;t.removeFromParent(),"geometry"in t&&t.geometry.dispose();const e=t.material;for(const i of Array.isArray(e)?e:[e]){const n=i.map;n&&n.dispose(),i.dispose()}}}const Je=Math.PI/180;function zr(o,t,e){return Math.max(t,Math.min(e,o))}function DS(o,t){return o+Math.random()*(t-o)}function u0(o,t){return(o%(t*2)+t*3)%(t*2)-t}let d0,f0;function TN(o){switch(o){case"snow":return RN();case"hail":return IN()}}function RN(){if(d0)return d0;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),d0=new Jo(t),d0}function IN(){if(f0)return f0;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),f0=new Jo(t),f0}let p0;function DN(){if(p0)return p0;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),p0=new Jo(t),p0}const CN=`
8597
8597
  uniform float uMaxSize;
8598
8598
  uniform float uScale;
8599
8599
  attribute float aLife;
@@ -8659,7 +8659,7 @@ void main() {
8659
8659
  gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
8660
8660
  }
8661
8661
  `;function CS(o){const e=document.createElement("canvas");e.width=128,e.height=128;const i=e.getContext("2d"),n=128/2-2,s=128/2,r=128/2,a="#010101",c="#f4f1e2";i.fillStyle=a,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const l=zr(o.illuminatedFraction,0,1),h=o.phaseFraction<.5,u=n*Math.abs(1-2*l),d=l<.5;return i.save(),i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.clip(),i.fillStyle=c,i.beginPath(),h?(i.arc(s,r,n,-Math.PI/2,Math.PI/2,!1),i.ellipse(s,r,u,n,0,Math.PI/2,-Math.PI/2,d)):(i.arc(s,r,n,Math.PI/2,-Math.PI/2,!1),i.ellipse(s,r,u,n,0,-Math.PI/2,Math.PI/2,d)),i.fill(),i.restore(),new Jo(e)}function LN(o){const t=document.createElement("canvas");t.width=128,t.height=128;const e=t.getContext("2d");return e.fillStyle="rgba(0, 0, 0, 0.55)",e.beginPath(),e.arc(64,64,60,0,Math.PI*2),e.fill(),e.fillStyle="#ffffff",e.font="bold 52px sans-serif",e.textAlign="center",e.textBaseline="middle",e.fillText(o,64,68),new Jo(t)}function zg(o){let t=o;return function(){t|=0,t=t+1831565813|0;let i=Math.imul(t^t>>>15,1|t);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}class pp{constructor(t,e){this.source=t,this.create=e}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=480;paint(t,e){this.disposed||(this.wanted={t,canvas:e},this.pumping||this.pump())}recordingChanged(t){this.scene&&(this.scene.sightingData=t)}dispose(){this.disposed=!0,this.scene?.remove(),this.scene=void 0}ensureScene(){if(this.scene)return this.scene;const t=this.create();return t.setAttribute("max-pixel-ratio","1"),t.setAttribute("always-live",""),Object.assign(t.style,{position:"fixed",left:"-10000px",top:"0",width:`${pp.SCENE_WIDTH_PX}px`,visibility:"hidden",pointerEvents:"none"}),document.body.appendChild(t),t.documentUrl=this.source.documentUrl,t.accountInTheRound=this.source.accountInTheRound,t.sightingData=this.source.sightingData,this.scene=t,t}async pump(){this.pumping=!0;try{for(;this.wanted&&!this.disposed;){const{t,canvas:e}=this.wanted;this.wanted=void 0;const i=this.ensureScene();i.interpretation!==this.source.interpretation&&(i.interpretation=this.source.interpretation),i.compareAccount!==this.source.compareAccount&&(i.compareAccount=this.source.compareAccount),i.showAt(t);for(let n=0;n<pp.PATIENCE_FRAMES&&!this.wanted&&!this.disposed&&(await new Promise(s=>requestAnimationFrame(()=>s())),!this.wanted);n++)if(i.snapshotTo(e)){e.dataset.ready="true";break}}}finally{this.pumping=!1}}}class mi{static held=new Map;static loaded=new Map;static generation=0;static address(t,e){const i=e??(typeof location>"u"?"http://localhost/":location.href);return new URL(t,i).href}static hold(t,e){mi.held.set(t,e),mi.loaded.delete(t),mi.generation++}static release(){if(mi.held.size!==0){for(const t of mi.held.keys())mi.loaded.delete(t);mi.held.clear(),mi.generation++}}static bytes(t,e=fetch.bind(globalThis)){const i=mi.held.get(t);if(i)return Promise.resolve(i);let n=mi.loaded.get(t);return n||(n=e(t).then(async s=>{if(!s.ok)throw new Error(`Frozen data not found (${s.status}): ${t}`);return new Uint8Array(await s.arrayBuffer())}),mi.loaded.set(t,n),n.catch(()=>mi.loaded.delete(t))),n}static async json(t){return JSON.parse(new TextDecoder().decode(await mi.bytes(t)))}static async zip(t){const e=await mi.bytes(t),{unzipSync:i}=await $t(async()=>{const{unzipSync:n}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:n}},[],import.meta.url);return i(e)}}class da{static SAME_BOUNDS_DEG=1e-9;loaded=!1;ready;list=[];constructor(t){this.ready=t.then(e=>{this.list=e},()=>{}).finally(()=>{this.loaded=!0})}nearest(t,e){let i,n=1/0;for(const s of this.list){if(s.far)continue;const{x:r,z:a}=ae(s.lat,s.lng,t,e),c=Math.hypot(r,a);c<n&&(n=c,i=s)}return i}farRingOf(t,e){return this.list.find(i=>i.far&&Math.abs(i.lat-t)<=da.SAME_BOUNDS_DEG&&Math.abs(i.lng-e)<=da.SAME_BOUNDS_DEG)}static boundsOf(t){return Bu(t.lat,t.lng,t.radiusM)}static sameBounds(t,e){const i=(n,s)=>Math.abs(n-s)<=da.SAME_BOUNDS_DEG;return i(t.north,e.north)&&i(t.south,e.south)&&i(t.east,e.east)&&i(t.west,e.west)}static contains(t,e){return t.north>=e.north&&t.south<=e.south&&t.east>=e.east&&t.west<=e.west}static samePatches(t,e){return t.length===e.length&&t.every((i,n)=>i.lat===e[n].lat&&i.lng===e[n].lng&&i.radiusM===e[n].radiusM&&i.far===e[n].far)}}class mp{static async encode(t){const{zipSync:e,strToU8:i}=await $t(async()=>{const{zipSync:r,strToU8:a}=await import("./browser-_Ncw3Jhn.js");return{zipSync:r,strToU8:a}},[],import.meta.url),n={},s={version:1,takenOn:t.takenOn,attribution:t.attribution,patches:t.patches.map((r,a)=>{const c=`${a}.f32`;return n[c]=mp.byPlane(r.grid.heights),{lat:r.lat,lng:r.lng,radiusM:r.radiusM,...r.far?{far:r.far}:{},bounds:r.grid.bounds,width:r.grid.width,height:r.grid.height,file:c}})};return n["index.json"]=i(JSON.stringify(s,null,1)),e(n,{level:9})}static decode(t){const e=t["index.json"];if(!e)throw new Error("A relief annex without its index");const i=JSON.parse(new TextDecoder().decode(e));return{takenOn:i.takenOn,attribution:i.attribution,patches:i.patches.flatMap(n=>{const s=t[n.file];if(!s||s.length!==n.width*n.height*4)return[];const r={heights:mp.fromPlanes(s),width:n.width,height:n.height,bounds:n.bounds};return[{lat:n.lat,lng:n.lng,radiusM:n.radiusM,...n.far?{far:n.far}:{},grid:r}]})}}static byPlane(t){const e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=t.length,n=new Uint8Array(e.length);for(let s=0;s<i;s++)for(let r=0;r<4;r++)n[r*i+s]=e[s*4+r];return n}static fromPlanes(t){const e=t.length/4,i=new Uint8Array(t.length);for(let n=0;n<e;n++)for(let s=0;s<4;s++)i[n*4+s]=t[s*e+n];return new Float32Array(i.buffer)}}class zv{constructor(t){this.annex=t}async getElevationGrid(t,e,i){const{patches:n}=await this.annex,s=n.find(a=>da.sameBounds(da.boundsOf(a),t));if(s)return{...s.grid,heights:new Float32Array(s.grid.heights)};const r=n.find(a=>da.contains(a.grid.bounds,t));if(r)return zv.resample(r.grid,t,e);throw new Error("The snapshots relief does not hold this ground")}static resample(t,e,i){const{width:n,height:s}=i,r=new Float32Array(n*s),a=t.bounds.east-t.bounds.west,c=t.bounds.north-t.bounds.south;for(let l=0;l<s;l++){const h=e.north-(e.north-e.south)*(s>1?l/(s-1):0),u=Math.min(t.height-1,Math.max(0,(t.bounds.north-h)/c*(t.height-1))),d=Math.floor(u),f=Math.min(t.height-1,d+1),p=u-d;for(let m=0;m<n;m++){const g=e.west+(e.east-e.west)*(n>1?m/(n-1):0),M=Math.min(t.width-1,Math.max(0,(g-t.bounds.west)/a*(t.width-1))),v=Math.floor(M),x=Math.min(t.width-1,v+1),y=M-v,w=(S,A)=>t.heights[S*t.width+A],b=w(d,v)*(1-y)+w(d,x)*y,E=w(f,v)*(1-y)+w(f,x)*y;r[l*n+m]=b*(1-p)+E*p}}return{heights:r,width:n,height:s,bounds:e}}}function wA(o,t){return o.find(e=>e.id===t)??o[0]}class kN{attribution;fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis);const e=t.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${e}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${e})`}async getImageryTexture(t,e){return yb(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}Re.point("elevation").provide(Re.BUILT_IN,[{id:"ign-mnt",name:"IGN LiDAR HD / RGE ALTI",credit:"Relief © IGN, LiDAR HD and RGE ALTI (Licence Ouverte 2.0) in France; © AWS Open Data (SRTM, ETOPO1) elsewhere",creditUrl:"https://geoservices.ign.fr/lidarhd",create:()=>Sb()},{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new vb}]);const SA=Re.point("imagery").provide(Re.BUILT_IN,[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:o=>new xb({fetchImpl:o})},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:o=>new kN({fetchImpl:o})}]);class PS{static async encode(t){const{zipSync:e,strToU8:i}=await $t(async()=>{const{zipSync:c,strToU8:l}=await import("./browser-_Ncw3Jhn.js");return{zipSync:c,strToU8:l}},[],import.meta.url),n={},s={};let r=0;for(const[c,l]of t.tiles){const h=`tiles/${r++}`;n[h]=l.bytes,s[c]={file:h,type:l.type}}const a={version:1,takenOn:t.takenOn,source:t.source,attribution:t.attribution,patches:t.patches,map:t.map,tiles:s};return n["index.json"]=i(JSON.stringify(a,null,1)),e(n,{level:0})}static decode(t){const e=t["index.json"];if(!e)throw new Error("An imagery annex without its index");const i=JSON.parse(new TextDecoder().decode(e)),n=new Map;for(const[s,{file:r,type:a}]of Object.entries(i.tiles)){const c=t[r];c&&n.set(s,{bytes:c,type:a})}return{takenOn:i.takenOn,source:i.source,attribution:i.attribution,patches:i.patches,map:i.map,tiles:n}}}class Vp{constructor(t,e=""){this.annex=t,this.attributionStated=e}provider;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}async getImageryTexture(t,e){return(await(this.provider??=this.annex.then(n=>(this.attributionRead=n.attribution,wA(SA,n.source).create(Vp.fetchFrom(n.tiles)))))).getImageryTexture(t,e)}static fetchFrom(t){return async e=>{const i=typeof e=="string"?e:e instanceof URL?e.href:e.url,n=t.get(i);return n?new Response(n.bytes,{status:200,headers:{"content-type":n.type}}):new Response(null,{status:404})}}}class UN{constructor(t,e=""){this.annex=t,this.attributionStated=e}picture;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}getImagery(){return this.picture??=this.annex.then(t=>{if(!t.map)throw new Error("An imagery annex that holds no map");return this.attributionRead=t.attribution,wA(SA,t.source).create(Vp.fetchFrom(t.tiles)).getImageryTexture(t.map.bounds,{width:t.map.pixels,height:t.map.pixels})})}}class Bv{constructor(t){this.annex=t}attributionRead;contemporaryRead;async itemsFor(t){const e=await this.annex;return this.attributionRead=e.attribution,this.contemporaryRead=e.contemporary,e.patches.find(i=>da.sameBounds(da.boundsOf(i),t))?.items??[]}}class FN{constructor(t,e=""){this.attributionStated=e,this.reader=new Bv(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRoads(t){return this.reader.itemsFor(t)}}class zN{constructor(t,e=""){this.attributionStated=e,this.reader=new Bv(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}getWater(t){return this.reader.itemsFor(t)}}class BN{constructor(t,e=""){this.attributionStated=e,this.reader=new Bv(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRailways(t){return this.reader.itemsFor(t)}}class gp{static providers(t,e,i){const n=f=>hh.held(t,f),s=n("relief"),r=n("imagery"),a=n("roads"),c=n("water"),l=n("railways");if(!s&&!r&&!a&&!c&&!l)return i;const h=f=>mi.address(f.src,e),u=[],d={...i};if(s){const f=mi.zip(h(s)).then(p=>mp.decode(p));d.elevation=new zv(f),u.push(f.then(p=>p.patches))}if(r){const f=mi.zip(h(r)).then(p=>PS.decode(p));d.imagery=new Vp(f,r.attribution),u.push(f.then(p=>p.patches))}if(a){const f=mi.json(h(a));d.roads=new FN(f,a.attribution),u.push(f.then(p=>p.patches))}if(c){const f=mi.json(h(c));d.water=new zN(f,c.attribution),u.push(f.then(p=>p.patches))}if(l){const f=mi.json(h(l));d.railways=new BN(f,l.attribution),u.push(f.then(p=>p.patches))}return d.patches=new da(gp.firstRead(u)),d}static map(t,e){const i=mi.zip(mi.address(t.src,e)).then(n=>PS.decode(n));return new UN(i,t.attribution)}static async firstRead(t){for(const e of t)try{const i=await e;if(i.length>0)return i.map(({lat:n,lng:s,radiusM:r,far:a})=>({lat:n,lng:s,radiusM:r,...a?{far:a}:{}}))}catch{}return[]}}const Ol="https://en.wikipedia.org/wiki/Kodachrome",hc="https://en.wikipedia.org/wiki/Kodacolor_(still_photography)",HN="https://en.wikipedia.org/wiki/Kodak_Tri-X",Nl="https://en.wikipedia.org/wiki/List_of_discontinued_photographic_films",Ta="https://www.kodak.com/en/motion/page/chronology-of-film/",ks=(o,t)=>[{format:"135",from:o,to:t},{format:"120",from:o,to:t}],Ra=(o,t)=>[{format:"35mm-cine",from:o,to:t}],OS=[{id:"kodacolor",name:"Kodacolor",kind:"negative",iso:32,formats:ks(1942,1963),source:hc},{id:"kodacolor-x",name:"Kodacolor-X",kind:"negative",iso:80,formats:[...ks(1963,1974),{format:"126",from:1963,to:1974}],source:hc},{id:"kodacolor-ii",name:"Kodacolor II",kind:"negative",iso:100,formats:[...ks(1973),{format:"126",from:1973}],source:hc},{id:"kodacolor-400",name:"Kodacolor 400",kind:"negative",iso:400,formats:ks(1977),source:hc},{id:"kodacolor-vr-100",name:"Kodacolor VR 100",kind:"negative",iso:100,formats:ks(1982,1986),source:hc},{id:"kodacolor-vr-200",name:"Kodacolor VR 200",kind:"negative",iso:200,formats:[...ks(1982,1986),{format:"126",from:1982,to:1986}],source:hc},{id:"kodacolor-vr-400",name:"Kodacolor VR 400",kind:"negative",iso:400,formats:ks(1982,1986),source:hc},{id:"agfacolor-cn17",name:"Agfacolor CN17",kind:"negative",iso:40,formats:ks(1956,1971),source:Nl},{id:"agfacolor-cns",name:"Agfacolor CNS",kind:"negative",iso:80,formats:[...ks(1968,1975),{format:"126",from:1968,to:1975}],source:Nl},{id:"agfacolor-cns-2",name:"Agfacolor CNS 2",kind:"negative",iso:80,formats:[...ks(1971,1982),{format:"126",from:1971,to:1982}],source:Nl},{id:"agfacolor-cns-400",name:"Agfacolor CNS 400",kind:"negative",iso:400,formats:ks(1978,1984),source:Nl},{id:"kodachrome",name:"Kodachrome",kind:"slide",iso:10,formats:[{format:"135",from:1936,to:1962}],source:Ol},{id:"kodachrome-ii",name:"Kodachrome II",kind:"slide",iso:25,formats:[{format:"135",from:1961,to:1974}],source:Ol},{id:"kodachrome-x",name:"Kodachrome-X",kind:"slide",iso:64,formats:[{format:"135",from:1962,to:1974},{format:"126",from:1963,to:1974}],source:Ol},{id:"kodachrome-25",name:"Kodachrome 25",kind:"slide",iso:25,formats:[{format:"135",from:1974,to:2001}],source:Ol},{id:"kodachrome-64",name:"Kodachrome 64",kind:"slide",iso:64,formats:[{format:"135",from:1974,to:2009},{format:"126",from:1974,to:1993}],source:Ol},{id:"kodachrome-200",name:"Kodachrome 200",kind:"slide",iso:200,formats:[{format:"135",from:1988,to:2007}],source:Ol},{id:"agfachrome-ct18",name:"Agfachrome CT18",kind:"slide",iso:50,formats:[...ks(1958,1984),{format:"126",from:1958,to:1984}],source:Nl},{id:"agfachrome-ct21",name:"Agfachrome CT21",kind:"slide",iso:100,formats:[{format:"135",from:1974,to:1984}],source:Nl},{id:"tri-x",name:"Kodak Tri-X",kind:"negative",monochrome:!0,iso:400,formats:ks(1954),source:HN},{id:"eastman-5247-1950",name:"Eastman Color Negative 5247 (1950)",kind:"negative",iso:16,formats:Ra(1950,1952),source:Ta},{id:"eastman-5248-1952",name:"Eastman Color Negative 5248 (1952)",kind:"negative",iso:16,formats:Ra(1952,1959),source:Ta},{id:"eastman-5250",name:"Eastman Color Negative 5250",kind:"negative",iso:32,formats:Ra(1959,1962),source:Ta},{id:"eastman-5251",name:"Eastman Color Negative 5251",kind:"negative",iso:50,light:"tungsten",formats:Ra(1962,1968),source:Ta},{id:"eastman-5254",name:"Eastman Color Negative 5254",kind:"negative",iso:100,light:"tungsten",formats:Ra(1968,1976),source:Ta},{id:"eastman-5247-1974",name:"Eastman Color Negative II 5247 (1974)",kind:"negative",iso:64,formats:Ra(1974,1983),source:Ta},{id:"eastman-5294",name:"Eastman High Speed Negative 5294",kind:"negative",iso:400,light:"tungsten",formats:Ra(1983),source:Ta},{id:"eastman-5297",name:"Eastman High Speed Daylight 5297",kind:"negative",iso:250,formats:Ra(1986,1997),source:Ta},{id:"eastman-5245",name:"Eastman EXR 50D 5245",kind:"negative",iso:50,formats:Ra(1989),source:Ta}];class kd{static byId(t){return OS.find(e=>e.id===t)}static forInstrument(t){return OS.filter(e=>e.formats.some(i=>i.format===t.filmFormat))}static gap(t,e,i){const n=t.formats.find(s=>s.format===e.filmFormat);if(!(!n||i===void 0)){if(i<n.from)return{kind:"before",from:n.from};if(n.to!==void 0&&i>n.to)return{kind:"after",to:n.to}}}static possible(t,e){return kd.forInstrument(t).filter(i=>kd.gap(i,t,e)===void 0)}static mediumOf(t,e){return!t||!e?t:{...t,kind:e.kind,iso:e.iso,monochrome:e.monochrome}}}class sh{constructor(t){this.annex=t}static SAME_PLACE_DEG=1e-6;static SAME_TIME_MS=1e3;async between(t,e,i){let n;try{n=await this.annex}catch{return{status:"failed"}}const s=c=>Math.abs(c.lat-t.lat)<=sh.SAME_PLACE_DEG&&Math.abs(c.lng-t.lng)<=sh.SAME_PLACE_DEG,a=n.answers.find(c=>s(c)&&Math.abs(c.startMs-e)<=sh.SAME_TIME_MS&&Math.abs(c.endMs-i)<=sh.SAME_TIME_MS)??n.answers.find(c=>c.startMs<=e&&c.endMs>=i);return a?a.answer:{status:"failed"}}}const Bg=7.5,Hg=9;class Br{static cache=new Map;static load(t){let e=Br.cache.get(t);return e||(e=fetch(t).then(i=>i.arrayBuffer()).then(i=>Br.parse(i)),Br.cache.set(t,e)),e}static upTo(t,e){const i=t.filter((r,a)=>a===0||t[a-1].magnitudeLimit<e);if(i.length<=1)return Br.load(t[0].url);const n=i.map(r=>r.url).join(`
8662
- `);let s=Br.cache.get(n);return s||(s=Promise.all(i.map(r=>Br.load(r.url))).then(r=>r.reduce((a,c)=>Br.concat(a,c))),Br.cache.set(n,s)),s}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*i,e),dec:new Float32Array(t,1*i,e),mag:new Float32Array(t,2*i,e),ci:new Float32Array(t,3*i,e)}}static concat(t,e){const i=(n,s)=>{const r=new Float32Array(n.length+s.length);return r.set(n,0),r.set(s,n.length),r};return{count:t.count+e.count,ra:i(t.ra,e.ra),dec:i(t.dec,e.dec),mag:i(t.mag,e.mag),ci:i(t.ci,e.ci)}}}class si{constructor(t){if(this.heights=t,t.length!==si.WIDTH*si.HEIGHT)throw new Error(`a lunar relief has ${si.WIDTH*si.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*si.SAMPLES_PER_DEGREE;static HEIGHT=180*si.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const i=si.SAMPLES_PER_DEGREE,n=(e%360+360)%360*i-.5,s=(90-t)*i-.5,r=Math.floor(n),a=Math.floor(s),c=n-r,l=s-a,h=(f,p)=>{const m=(f%si.WIDTH+si.WIDTH)%si.WIDTH,g=Math.min(si.HEIGHT-1,Math.max(0,p));return this.heights[g*si.WIDTH+m]},u=h(r,a)*(1-c)+h(r+1,a)*c,d=h(r,a+1)*(1-c)+h(r+1,a+1)*c;return(u*(1-l)+d*l)*si.UNIT_KM}static inBand(t,e){const i=Math.PI/180,n=Math.acos(Math.cos(t*i)*Math.cos(e*i))*180/Math.PI;return n>=si.BAND_FROM_DEG&&n<=si.BAND_TO_DEG}static withBump(t,e,i,n=.4){const s=new Int8Array(si.WIDTH*si.HEIGHT),r=si.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),c=Math.floor(e*r),l=Math.floor((90-t)*r);for(let h=-a;h<=a;h++)for(let u=-a;u<=a;u++)Math.hypot(u,h)<=a&&(s[(l+h)*si.WIDTH+(c+u+si.WIDTH)%si.WIDTH]=Math.round(i/si.UNIT_KM));return new si(s)}static smooth(){return new si(new Int8Array(si.WIDTH*si.HEIGHT))}}class Qs{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,i,n=Qs.SAMPLES){const{s,u:r,w:a,distanceKm:c}=Qs.frame(t,e),l=Math.PI/180,h=new Float32Array(n),u=si.REFERENCE_RADIUS_KM;for(let d=0;d<n;d++){const f=d/n*2*Math.PI,p=Math.cos(f),m=Math.sin(f),g=p*r[0]+m*a[0],M=p*r[1]+m*a[1],v=p*r[2]+m*a[2];let x=0;for(let y=Qs.SEARCH_FROM_DEG;y<=Qs.SEARCH_TO_DEG;y+=Qs.SEARCH_STEP_DEG){const w=Math.cos(y*l),b=Math.sin(y*l),E=w*s[0]+b*g,S=w*s[1]+b*M,A=w*s[2]+b*v,_=Math.asin(Math.max(-1,Math.min(1,A)))/l,I=Math.atan2(S,E)/l,D=u+i.heightKm(_,I),P=Math.atan2(D*b,c-D*w);P>x&&(x=P)}h[d]=x/l}return{radiusDeg:h,meanRadiusDeg:Math.asin(u/c)/l}}static frame(t,e){const i=new $o(e.lat,e.lng,e.elevationM),n=Za(t),s=oM(t,i,!1),r=new Fe(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*Qs.AU_KM,c=Qs.bodyFixed(t),l=c(r),h=Math.hypot(l[0],l[1],l[2]),u=[l[0]/h,l[1]/h,l[2]/h],d=hO(t,i),f=Rv(d),p=Ya(d,new Fe(-r.x,-r.y,-r.z,n.t)),m=Math.asin(p.z/Math.hypot(p.x,p.y,p.z)),g=Math.atan2(-p.y,p.x),M=new Fe(-Math.sin(m)*Math.cos(g),Math.sin(m)*Math.sin(g),Math.cos(m),n.t),v=new Fe(-Math.sin(g),-Math.cos(g),0,n.t);return{s:u,u:c(Ya(f,M)),w:c(Ya(f,v)),distanceKm:a}}static surfacePoint(t,e,i,n){const{s,u:r,w:a}=Qs.frame(t,e),c=Math.PI/180,l=[0,1,2].map(u=>Math.cos(i*c)*r[u]+Math.sin(i*c)*a[u]),h=[0,1,2].map(u=>Math.cos(n*c)*s[u]+Math.sin(n*c)*l[u]);return{latDeg:Math.asin(h[2])/c,lonDeg:Math.atan2(h[1],h[0])/c}}static radiusAt(t,e){const i=t.radiusDeg.length,n=(e/360*i%i+i)%i,s=Math.floor(n),r=n-s;return t.radiusDeg[s]*(1-r)+t.radiusDeg[(s+1)%i]*r}static uncoveredFraction(t,e,i){const n=t.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const c=a/n*2*Math.PI,l=Math.cos(c),h=Math.sin(c),u=l*i.upDeg+h*i.rightDeg,d=u*u-s+e*e;if(d<=0)continue;const f=Math.sqrt(d),p=u+f;if(p<=0)continue;const m=Math.max(0,u-f),g=Math.max(m,t.radiusDeg[a]);p>g&&(r+=.5*(p*p-g*g))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=_O(pt.Moon,t),i=Math.PI/180,n=e.ra*15*i,s=e.dec*i,r=e.spin*i,a=(l,[h,u,d])=>[Math.cos(l)*h+Math.sin(l)*u,-Math.sin(l)*h+Math.cos(l)*u,d],c=(l,[h,u,d])=>[h,Math.cos(l)*u+Math.sin(l)*d,-Math.sin(l)*u+Math.cos(l)*d];return l=>a(r,c(Math.PI/2-s,a(Math.PI/2+n,[l.x,l.y,l.z])))}static subObserverPoint(t,e){const i=new $o(e.lat,e.lng,e.elevationM),n=Za(t),s=oM(t,i,!1),r=Qs.bodyFixed(t)(new Fe(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class $u{static cache=new Map;static load(t){let e=$u.cache.get(t);return e||(e=$u.fetchRelief(t).catch(()=>{}),$u.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let i=new Uint8Array(await e.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const n=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(n).arrayBuffer())}return new si(new Int8Array(i.buffer,i.byteOffset,i.length))}}const Hv=_r.catalog({en:()=>$t(()=>import("./PerceptionMessages_en-B2O6DR64.js"),[],import.meta.url).then(o=>o.perceptionMessages_en),fr:()=>$t(()=>import("./PerceptionMessages_fr-B59TnGBC.js"),[],import.meta.url).then(o=>o.perceptionMessages_fr),es:()=>$t(()=>import("./PerceptionMessages_es-BmkP6OqD.js"),[],import.meta.url).then(o=>o.perceptionMessages_es),it:()=>$t(()=>import("./PerceptionMessages_it-DPlxRmxu.js"),[],import.meta.url).then(o=>o.perceptionMessages_it)});class Mp{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=Mp.ID;messages=Hv;sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",kind:"choice",default:"normal",choices:[{id:"normal"},{id:"protan"},{id:"deutan"},{id:"tritan"}]},{id:"severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=Mp.MATRICES[String(t.type)];if(!e)return Cs.NONE;const i=Number(t.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:e.map((r,a)=>Cs.IDENTITY[a]+(r-Cs.IDENTITY[a])*n),contrastGain:1}}}class Gv{static ID="fatigue";id=Gv.ID;messages=Hv;sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return Cs.NONE}}class mc{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=mc.ID;messages=Hv;sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",kind:"number",default:0,min:0,max:mc.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),i=Math.max(0,Math.min(mc.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(i===0)return Cs.NONE;const n=i/mc.MEASURED_LEVEL*mc.MEASURED_LOSS_DB;return{colorMatrix:Cs.IDENTITY,contrastGain:10**(-n/20)}}}const GN=o=>o.sources[0]??o.id,VN=Re.point("perception").provide(Re.BUILT_IN,[new Mp,new mc,new Gv].map(o=>({id:o.id,name:o.id,credit:GN(o),creditUrl:"https://ufoathome.org/docs/sources/",create:()=>o})));class gc{static built=new WeakMap;static get ALL(){return VN.map(t=>{let e=gc.built.get(t);return e||(e=t.create(),gc.built.set(t,e)),e})}static byId(t){return gc.ALL.find(e=>e.id===t)}static perceptionOf(t){return gc.ALL.reduce((e,i)=>Cs.combine(e,i.perceive(t?.[i.id]??{})),Cs.NONE)}static compact(t){const e={},i=gc.ALL;for(const[n,s]of Object.entries(t))!i.some(r=>r.id===n)&&Object.keys(s??{}).length>0&&(e[n]=s);for(const n of i){const s=t[n.id]??{},r=Object.fromEntries(n.settings.filter(a=>s[a.id]!==void 0&&s[a.id]!==a.default).map(a=>[a.id,s[a.id]]));Object.keys(r).length>0&&(e[n.id]=r)}return Object.keys(e).length>0?e:void 0}}class Mc{static NONE={id:"none",name:"No filter",opticalDensity:0};static SOLAR_VISUAL={id:"solar-visual",name:"Solar filter for the eye (OD 5)",opticalDensity:5,usableWith:["eye","binoculars","telescope"]};static SOLAR_PHOTO={id:"solar-photo",name:"Solar film for a camera (OD 3.8)",opticalDensity:3.8,usableWith:["camera","dslr","phone","telescope"]};static ALL=[Mc.NONE,Mc.SOLAR_VISUAL,Mc.SOLAR_PHOTO];static usableWith(t,e){return!t.usableWith||t.usableWith.includes(e.category)}static byId(t){return Mc.ALL.find(e=>e.id===t)??Mc.NONE}static transmittance(t){return 10**-t.opticalDensity}static magnitudes(t){return 2.5*t.opticalDensity}}class NS{names;constructor(t){this.names=t??_r.blank(),this.loaded=t!==void 0}loaded;body(t){return this.names.bodies[t]??t}star(t){return this.names.stars[t.name]??t.name}comet(t){return this.names.comets[t.id]??t.name}nova(t){return this.names.novae[t.id]??t.name}satelliteClass(t){return this.names.satelliteClasses[t.id]??t.name}shower(t){return this.names.showers[t.id]??t.name}lightRig(t){return this.names.lightRigs[t.id]??t.name}instrument(t){return this.names.instruments[t.id]??t.name}decorKind(t){return this.names.decorKinds[t]}point(t){return Pc.point(t,this.loaded?this.names.compassPoints:void 0)}towards(t){return Pc.towards(t,this.loaded?this.names:void 0)}}class Vr{static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const i=t.name??Vr.kind(t,e);return t.services?.length?`${i} — ${t.services.join(", ")}`:i}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,i,n){const{line:s}=t,r=[];s.name&&r.push(Vr.kind(s,e).toLocaleLowerCase(n)),r.push(s.tracks>1?e.tracks.replace("{count}",String(s.tracks)):e.singleTrack);const a=s.voltageV?Vr.voltage(s.voltageV,n):void 0;if(t.contactM!==void 0){const c=t.contactM.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?e.overheadVoltage.replace("{voltage}",a):e.overhead).replace("{height}",c))}else s.electrification==="third_rail"?r.push(a?e.thirdRailVoltage.replace("{voltage}",a):e.thirdRail):s.electrification==="none"&&r.push(e.notElectrified);return s.gaugeMm===Vr.METRE_GAUGE_MM?r.push(e.metreGauge):s.gaugeMm!==Vr.STANDARD_GAUGE_MM&&r.push(e.gauge.replace("{mm}",s.gaugeMm.toLocaleString(n))),r.push(e.distance.replace("{distance}",i(t.distanceM))),s.services?.length?`${Vr.name(s,e)}; ${r.join(", ")}`:`${Vr.name(s,e)} — ${r.join(", ")}`}}class Ku{constructor(t,e){this.element=t,this.onChange=e,t.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(t,e,i=!0){const n=Ku.resolve(t,e);if(this.url=n,!n||!i){this.release();return}this.element.src=n,this.element.hidden=!1;const s=this.shown;this.shown=!0,s||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const i=new URL(t.trim(),e??location.href);return i.protocol!=="https:"&&i.protocol!=="http:"?void 0:i.origin===Ku.PUBLISHED_ORIGIN&&Ku.isDevelopmentHost(location.hostname)?location.origin+i.pathname:i.href}catch{return}}static PUBLISHED_ORIGIN="https://ufoathome.org";static isDevelopmentHost(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}}const WN="Global Meteor Network",XN="https://globalmeteornetwork.org/data/",YN="“Thunder” by Jerimee",$N="https://creativecommons.org/licenses/by/3.0/",KN="CC BY 3.0";class Yn{static fill(t,e){t.innerHTML="";const i=d=>t.appendChild(d),n=e.currentTerrainAttribution;n&&i(Yn.text(n));const s=e.currentRoadAttribution;s&&i(Yn.text(s));const r=e.currentWaterAttribution;r&&i(Yn.text(r));const a=e.currentRailwayAttribution;a&&i(Yn.text(a));const c=e.ufoElement.observerMapCredit;c&&!n?.includes(c)&&i(Yn.text(c));for(const d of e.decorModelCredits){const f=d.author?` — ${d.author}`:"",p=document.createElement("li");d.sourceUrl?p.append(Yn.link(d.sourceUrl,d.title),document.createTextNode(`${f} (${d.license})`)):p.textContent=`${d.title}${f} (${d.license})`,i(p)}for(const d of e.ufoElement.sighting.references){if(!d.credit)continue;const f=document.createElement("li");d.creditUrl?f.appendChild(Yn.link(d.creditUrl,d.credit)):f.textContent=d.credit,i(f)}if(e.ufoElement.sighting.traces.length>0){const d=new wr(wc.preferencesFor(e)),f=new Set(e.ufoElement.sighting.traces.map(p=>d.read(p.source)).filter(p=>!!p));for(const p of f)i(Yn.text(p))}const l=e.satelliteState;if(l.status==="ready"&&l.credit){const d=document.createElement("li");d.appendChild(Yn.link(l.creditUrl??"",l.credit)),i(d)}if(e.fireballState.status==="ready"&&e.fireballState.records.length>0){const d=document.createElement("li");d.append(Yn.link(XN,WN),document.createTextNode(" (CC BY 4.0)")),i(d)}const h=e.aircraftState;if(h.status==="ready"&&h.shown>0){const d=document.createElement("li");if(d.appendChild(Yn.link(h.creditUrl,h.credit)),i(d),h.trailCredit){const f=document.createElement("li");f.appendChild(Yn.link(h.trailCredit.creditUrl,h.trailCredit.credit)),i(f)}}const u=Yn.text(`${YN} (`);u.append(Yn.link($N,KN),document.createTextNode(")")),i(u)}static text(t){const e=document.createElement("li");return e.textContent=t,e}static link(t,e){const i=document.createElement("a");return i.href=t,i.target="_blank",i.rel="noopener",i.textContent=e,i}}const qN=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,ZN=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,LS=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,JN=20,jN=1;class rh{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}Ic.unlock(this.context)}setAmbient(t,e,i){if(this.requested={type:t,intensity:e,windSpeed:i},!this.context)return;this.paused&&(t="none",e=0,i=0);const n=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=n==="hail"?Math.min(1,e*1.3+.2):n==="rain"?e:0,n!==this.ambientKey){this.ambientKey=n;const r=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,n!=="none"&&this.startLoop(qN,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,c=>{this.ambientSource=c?.source,this.ambientGain=c?.gain,c&&(c.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/JN,1);const s=i>jN;if(s!==this.windActive){this.windActive=s;const r=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,s&&this.startLoop(ZN,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,c=>{this.windSource=c?.source,this.windGain=c?.gain,c&&(c.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(t){if(t===this.paused)return;this.paused=t;const{type:e,intensity:i,windSpeed:n}=this.requested;this.setAmbient(e,i,n)}playThunder(){!this.context||this.paused||this.playOneShot(LS,.9)}playDetonation(t){const e=this.context;if(!e||this.paused)return;const i=Math.min(1,Math.max(0,t)),n=e.createBufferSource();n.buffer=this.crackBuffer(e);const s=e.createBiquadFilter();s.type="lowpass",s.frequency.value=rh.CRACK_CUTOFF_HZ;const r=e.createGain();r.gain.value=i,n.connect(s).connect(r).connect(this.output(e)),n.start(),this.playOneShot(LS,i,rh.DETONATION_RATE)}static DETONATION_RATE=.8;static CRACK_CUTOFF_HZ=2500;static CRACK_DECAY_S=.25;crackBuffer(t){if(this.crack?.sampleRate===t.sampleRate)return this.crack;const e=Math.round(t.sampleRate*rh.CRACK_DECAY_S*6),i=t.createBuffer(1,e,t.sampleRate),n=i.getChannelData(0);for(let s=0;s<e;s++){const r=s/t.sampleRate;n[s]=(Math.random()*2-1)*Math.min(1,r/.005)*Math.exp(-r/rh.CRACK_DECAY_S)}return this.crack=i,i}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,i,n){if(e!==i()){t?.source.stop();return}n(t)}async startLoop(t,e){const i=this.context;if(i)try{const n=await this.getBuffer(t),s=i.createBufferSource();s.buffer=n,s.loop=!0;const r=i.createGain();return r.gain.value=e,s.connect(r).connect(this.output(i)),s.start(),{source:s,gain:r}}catch(n){console.warn("Weather ambient sound failed to load, staying silent:",n);return}}async playOneShot(t,e,i=1){const n=this.context;if(n)try{const s=await this.getBuffer(t),r=n.createBufferSource();r.buffer=s,r.playbackRate.value=i;const a=n.createGain();a.gain.value=e,r.connect(a).connect(this.output(n)),r.start()}catch(s){console.warn("Thunder sound failed to load:",s)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}class Oa{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:i}=t,[n,s]=this.perifocalAxes(),r=Math.sqrt(Oa.SUN_GM_AU3_PER_DAY2*(1+e)/i);this.perihelionPosition=this.scale(n,i),this.perihelionVelocity=this.scale(s,r),this.inverseSemiMajorAxis=(1-e)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,i=this.universalAnomaly(e),n=this.inverseSemiMajorAxis*i*i,s=this.elements.perihelionAu,r=1-i*i/s*Oa.stumpffC(n),a=e-i*i*i/Math.sqrt(Oa.SUN_GM_AU3_PER_DAY2)*Oa.stumpffS(n);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(t){const e=this.positionAt(t);return Math.hypot(e.x,e.y,e.z)}universalAnomaly(t){if(t===0)return 0;const e=Math.sign(t),i=Math.sqrt(Oa.SUN_GM_AU3_PER_DAY2)*Math.abs(t),n=a=>{const c=this.inverseSemiMajorAxis*a*a,l=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*l)*a*a*a*Oa.stumpffS(c)+l*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<Oa.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){const c=(r+s)/2;n(c)<i?r=c:s=c}return e*(r+s)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,n=Math.cos(t),s=Math.sin(t),r=Math.cos(e),a=Math.sin(e),c=Math.cos(i),l=Math.sin(i);return[{x:n*r-s*a*c,y:s*r+n*a*c,z:a*l},{x:-n*a-s*r*c,y:-s*a+n*r*c,z:r*l}]}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}static stumpffC(t){if(Math.abs(t)<1e-6)return 1/2-t/24+t*t/720;if(t>0)return(1-Math.cos(Math.sqrt(t)))/t;const e=Math.sqrt(-t);return(Math.cosh(e)-1)/-t}static stumpffS(t){if(Math.abs(t)<1e-6)return 1/6-t/120+t*t/5040;if(t>0){const i=Math.sqrt(t);return(i-Math.sin(i))/(i*i*i)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const bA=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class QN{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(t){const e=this.julianDayOf(t);return bA.filter(i=>Math.abs(e-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(i=>this.appearanceOf(i,t,e)).sort((i,n)=>i.magnitude-n.magnitude)[0]}static appearanceOf(t,e,i){const n=ui(e),s=this.earthPositionAt(n),r=this.apparentPositionOf(t,2451545+n.tt,s),a=this.subtract(r,s),c=this.length(r),l=this.length(a),h=this.tailEndAt(t,r,s,c,n,e,i),u=this.horizontalOf(a,n,e,i);return{apparition:t,position:u,...h,heliocentricDistanceAu:c,earthDistanceAu:l,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(t,c,l)}}static magnitudeAt(t,e,i){const n=t.absoluteMagnitude+5*Math.log10(i)+2.5*t.activityExponent*Math.log10(e);return Math.max(n,t.peakMagnitude)}static tailEndAt(t,e,i,n,s,r,a){if(t.tailLengthAu===void 0)return{};const c=1+t.tailLengthAu/n,l=this.subtract({x:e.x*c,y:e.y*c,z:e.z*c},i),h=this.subtract(e,i);return{tailEnd:this.horizontalOf(l,s,r,a),tailLengthDeg:this.angleBetween(h,l)}}static apparentPositionOf(t,e,i){const n=this.orbitOf(t);let s=n.positionAt(e);for(let r=0;r<2;r++){const a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(e-a)}return s}static horizontalOf(t,e,i,n){const s=Ya(aO(),new Fe(t.x,t.y,t.z,e)),r=Ya(jE(e),s),a=oM(e,new $o(n.lat,n.lng,n.elevationM),!0),c=new Fe(r.x-a.x,r.y-a.y,r.z-a.z,e),l=zp(c);return Cv(l.ra,l.dec,i,n)}static earthPositionAt(t){return Ya(rO(),Vo(pt.Earth,t))}static julianDayOf(t){return 2451545+ui(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const i=new Oa(t.orbit);return this.orbits.set(t.id,i),i}static subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}static length(t){return Math.hypot(t.x,t.y,t.z)}static angleBetween(t,e){const i=(t.x*e.x+t.y*e.y+t.z*e.z)/(this.length(t)*this.length(e)||1);return Math.acos(Math.min(1,Math.max(-1,i)))*180/Math.PI}}const Gg=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class kS{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return Gg.filter(i=>this.magnitudeAt(i,e)!==void 0)}static appearancesAt(t,e){const i=this.julianDayOf(t),n=[];for(const s of Gg){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:xr.ofJ2000(s.raHours,s.decDeg,t,e),magnitude:r})}return n.sort((s,r)=>s.magnitude-r.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return Gg.find(e=>e.id===t)}static magnitudeAt(t,e){const i=t.lightCurve,n=e-t.startJd;if(i.length===0||n<i[0][0]||n>i[i.length-1][0])return;let s=1;for(;s<i.length-1&&i[s][0]<n;)s++;const[r,a]=i[s-1]??i[0],[c,l]=i[s]??i[0];if(c===r)return a;const h=Math.min(1,Math.max(0,(n-r)/(c-r)));return a+h*(l-a)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const tL=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],vp=6.5;class Vg{static activeAt(t){return tL.flatMap(e=>{const i=this.nearness(e,t);return i<=0?[]:[{shower:e,zhr:e.peakZhr*i,nearness:i}]})}static nearness(t,e){const i=this.dayOfYear(e),n=this.dayOfYear(this.asDate(t.start)),s=this.dayOfYear(this.asDate(t.peak)),r=this.dayOfYear(this.asDate(t.end)),a=this.wrappedDelta(i,s),c=this.wrappedDelta(s,n),l=this.wrappedDelta(r,s);return a<0?a<-c?0:1+a/c:a>0?a>l?0:1-a/l:1}static observedRatePerHour(t,e,i,n=vp){if(e<=0)return 0;const s=vp-n;return t*Math.sin(e*Math.PI/180)/Math.pow(i,s)}static radiantPosition(t,e,i){return xr.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,i)}static dayOfYear(t){const e=Date.UTC(t.getUTCFullYear(),0,1);return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-e)/864e5)+1}static asDate(t){return new Date(Date.UTC(2001,t.month-1,t.day))}static wrappedDelta(t,e){const i=t-e;return i>182?i-365:i<-182?i+365:i}}class Vi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const i=ui(t),n=new Lp(0,UP(t).elon-90,1),s=Ya(uO(i),Dv(n,i)),r=zp(s);return Cv(r.ra,r.dec,t,e)}static observedRatePerHour(t,e=vp){const i=Vi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),n=vp-e;return(Vi.QUIET_RATE_PER_HOUR+i)/Math.pow(Vi.POPULATION_INDEX,n)}static schedule(t){const e=new Bp(t.seed^1542469173);return ir.schedule(t).map(i=>{const n=Vi.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=Vi.turnAround(n,e.between(0,360)),a={x:n.x*Math.cos(s)+r.x*Math.sin(s),y:n.y*Math.cos(s)+r.y*Math.sin(s),z:n.z*Math.cos(s)+r.z*Math.sin(s)};return{...i,radiant:Vi.toHorizontal(a),bearingDeg:Vi.bearingFrom(a,n)}})}static turnAround(t,e){const[i,n]=Vi.basisAround(t),s=e*Math.PI/180;return{x:i.x*Math.cos(s)+n.x*Math.sin(s),y:i.y*Math.cos(s)+n.y*Math.sin(s),z:i.z*Math.cos(s)+n.z*Math.sin(s)}}static bearingFrom(t,e){const[i,n]=Vi.basisAround(t),s=t.x*e.x+t.y*e.y+t.z*e.z,r=Vi.normalise({x:e.x-t.x*s,y:e.y-t.y*s,z:e.z-t.z*s});return(Math.atan2(r.x*n.x+r.y*n.y+r.z*n.z,r.x*i.x+r.y*i.y+r.z*i.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=Vi.normalise(Vi.cross(t,e));return[i,Vi.normalise(Vi.cross(t,i))]}static toHorizontal(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,t.y/e)))*180/Math.PI,azimuthDeg:(Math.atan2(t.x,-t.z)*180/Math.PI%360+360)%360}}static appearanceOf(t){const e=Vi.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Vi.turnAround(e,t.bearingDeg),n=t.fromRadiantDeg*Math.PI/180;return Vi.toHorizontal({x:e.x*Math.cos(n)+i.x*Math.sin(n),y:e.y*Math.cos(n)+i.y*Math.sin(n),z:e.z*Math.cos(n)+i.z*Math.sin(n)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180,n=Math.cos(e);return{x:n*Math.sin(i),y:Math.sin(e),z:-n*Math.cos(i)}}static cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}static normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}static TYPICAL_VELOCITY_KM_S=40}const US="https://ufoathome.org/tle/index.json";class $n{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??$n.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/tle/index.json",location.href).href),t.includes(US)||t.push(US),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${$n.FIRST_SNAPSHOT}T00:00:00Z`)-$n.MAX_ELEMENT_AGE_DAYS*$n.DAY_MS;if(t.getTime()<e)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(n=>t.getTime()>=Date.parse(n.from)-$n.MAX_ELEMENT_AGE_DAYS*$n.DAY_MS&&t.getTime()<=Date.parse(n.to)+$n.MAX_ELEMENT_AGE_DAYS*$n.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:i,base:n}=e,s=[],r=[];for(const a of Object.keys(i.kinds)){const c=await this.kindAt(a,t,i,n);s.push(...c),r.push(this.coverageOf(a,t,i,c.length>0))}return{objects:s,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(t,e,i,n){const s=e.getTime(),r=i.binDays*$n.DAY_MS,a=Math.floor(s/r),c=s-a*r<r/2?a-1:a+1,l=new Set(i.kinds[t].bins),h=[a,c].map(m=>new Date(m*r).toISOString().slice(0,10)).filter(m=>l.has(m));if(h.length===0)return[];const[u,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,n).href),...h.map(m=>this.binary(new URL(`${t}/${m}.bin`,n).href))]),f=new Map;for(const m of d)for(const g of $n.decode(m,i.recordBytes)){const M=f.get(g.norad);(!M||Math.abs(g.epochMs-s)<Math.abs(M.epochMs-s))&&f.set(g.norad,g)}const p=[];for(const m of f.values()){const g=Math.abs(m.epochMs-s)/$n.DAY_MS;if(g>$n.MAX_ELEMENT_AGE_DAYS)continue;const M=u[m.norad]??{name:String(m.norad)};M.launch&&Date.parse(`${M.launch}T00:00:00Z`)>s||p.push({norad:m.norad,name:M.name,kind:t,launch:M.launch,stdMag:M.stdMag,elements:m,ageDays:g})}return p}coverageOf(t,e,i,n){const{from:s,to:r}=i.kinds[t],a=e.getTime(),c=$n.MAX_ELEMENT_AGE_DAYS*$n.DAY_MS,l=n?"covered":a<Date.parse(s)-c?"before":a>Date.parse(r)+c?"after":"gap";return{kind:t,status:l,from:s,to:r}}static decode(t,e){const i=new DataView(t),n=[];for(let s=0;s+e<=t.byteLength;s+=e)n.push({norad:i.getUint32(s,!0),epochMs:i.getFloat64(s+4,!0),bstar:i.getFloat32(s+12,!0),inclinationDeg:i.getFloat32(s+16,!0),raanDeg:i.getFloat32(s+20,!0),eccentricity:i.getFloat32(s+24,!0),argOfPerigeeDeg:i.getFloat32(s+28,!0),meanAnomalyDeg:i.getFloat32(s+32,!0),meanMotion:i.getFloat64(s+36,!0)});return n}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;return{index:await e.json(),base:t}}catch{}})(),this.index}json(t){return this.cached(t,async e=>e.json())}binary(t){return this.cached(t,async e=>e.arrayBuffer())}cached(t,e){let i=this.files.get(t);return i||(i=this.fetchImpl(t).then(n=>{if(!n.ok)throw new Error(`${t}: ${n.status}`);return e(n)}),i.catch(()=>this.files.delete(t)),this.files.set(t,i)),i}}class eL{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const i=hi.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(e.inFrontM!==void 0){const i=hi.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?i:Math.min(this.upperM,i)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:hi.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:hi.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class Nc{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*Nc.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const i=Nc.degOver(t)/e;return i<1?1:Math.min(Nc.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Fn{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return Nc.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return Fn.visualAidGrasp(t,e.focalLengthMm);const i=e.exposureSeconds??t.exposureSeconds,n=e.fNumber??t.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return Fn.EYE;const s=e.focalLengthMm??t.frame?.focalLengthMm??Fn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=Fn.resolutionArcsec(t,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,Fn.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(t,e){const i=t.visualAid,n=Fn.EYE,s=e??t.frame?.focalLengthMm,r=i.magnification??(s!==void 0&&i.eyepieceFocalMm?s/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,n.apertureMm*r);return{apertureMm:Math.max(a,n.apertureMm),exposureSeconds:n.exposureSeconds,resolutionArcsec:n.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/n.apertureMm))}}static resolutionArcsec(t,e,i){const s=(t.detailUm??Fn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*Fn.ARCSEC_PER_RADIAN,r=1.22*Fn.WAVELENGTH_M/(i/1e3)*Fn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(t){return t/Fn.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const i=Fn.graspOf(t,e),n=Fn.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,a=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*a)}static gainFor(t,e){const i=e.fieldOfViewDeg===void 0?void 0:Xi.focalLengthMmFor(t,e.fieldOfViewDeg);return Fn.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:i,exposureSeconds:e.exposureSeconds})}}const FS=111320,Su=Math.PI/180,iL=1.02,nL=1;class qu{static of(t,e){const i=qu.sightings(t,e);if(i.length<2)return;const n=qu.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,c=Math.tan(r.widthDeg/2*Su)===0?0:Math.tan(s.widthDeg/2*Su)/Math.tan(r.widthDeg/2*Su);if(c<iL)return;const l=a/(c-1),h=hi.sizeMAt(l,s.widthDeg),u=i.map(d=>({t:d.t,m:hi.distanceMAt(h,d.widthDeg)}));return{widthM:h,distanceM:u,nearestM:Math.min(...u.map(d=>d.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===e)?.shape,s=n?.angular?.widthDeg,r=ze(t,i.t);return s===void 0||s<=0||r?.lat===void 0||r.lng===void 0?[]:[{t:i.t,widthDeg:s,lat:r.lat,lng:r.lng,sightAzimuthDeg:n?.aim?.azimuthDeg??r.headingDeg}]}).sort((i,n)=>i.t-n.t)}static baseline(t){let e;for(const i of t)for(const n of t){if(i.t>=n.t)continue;const s=qu.closedAlongSight(i,n),[r,a,c]=s>=0?[n,i,s]:[i,n,-s];c<nL||r.widthDeg<=a.widthDeg||(!e||c>e.closedM)&&(e={near:r,far:a,closedM:c})}return e}static closedAlongSight(t,e){const i=(e.lat-t.lat)*FS,n=(e.lng-t.lng)*FS*Math.cos(t.lat*Su),s=(t.sightAzimuthDeg??0)*Su;return i*Math.cos(s)+n*Math.sin(s)}}class ls{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(t){if(t.statedM!==void 0&&t.statedM>0)return{distanceM:ls.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:ls.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:ls.atLeastNearest(t.derivedM),basis:"derived"};const e=ls.largest(t.range?.minM,t.crossing?.behindM),i=ls.smallest(t.range?.maxM,t.crossing?.inFrontM),n=e===void 0?void 0:e*ls.MARGIN,s=i===void 0?void 0:i/ls.MARGIN;return n!==void 0&&s!==void 0?{distanceM:ls.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:ls.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<ls.CONVENTIONAL_M?{distanceM:ls.atLeastNearest(s),basis:"bounded"}:{distanceM:ls.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(ls.NEAREST_M,t)}static largest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.min(...e)}}class It{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=4;static DEFAULT_CRUMBLING={perS:1.2,lifeS:4,magnitudeDrop:3,dropBack:.3,spreadKmS:1,sinkKmS:.6,trainS:2.5};static DEFAULT_BURST={perS:12,lifeS:3.5,magnitudeDrop:3.5,dropBack:.5,spreadKmS:1.5,sinkKmS:.9,trainS:2};static FLARE_MAGNITUDES=.5;static shedsOf(t){return t.sheds?t.sheds:[It.DEFAULT_CRUMBLING,...It.flareBursts(t)]}static flareBursts(t){const e=t.lightCurve??[],i=[];for(let n=1;n<e.length-1;n++){const s=e[n];e[n-1].absoluteMagnitude-s.absoluteMagnitude<It.FLARE_MAGNITUDES||e[n+1].absoluteMagnitude-s.absoluteMagnitude<It.FLARE_MAGNITUDES||i.push({...It.DEFAULT_BURST,fromT:s.t-1e3,untilT:s.t+1500})}return i}static FADE_MS=1e3;static FADED_MAGNITUDE=8;static TRAIN_POINTS=8;static leadAt(t,e){const i=t.track;if(i.length<2||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-2&&i[n+1].t<e;)n++;const s=i[n],r=i[n+1],a=r.t-s.t,c=a>0?(e-s.t)/a:0,[l,h]=It.alongGreatCircle(s,r,c);return{lat:l,lng:h,heightM:(s.altitudeKm+(r.altitudeKm-s.altitudeKm)*c)*1e3}}static mayDazzle(t){const e=Math.max(1,Math.min(...t.track.map(n=>n.altitudeKm))),i=5*Math.log10(e/It.STANDARD_DISTANCE_KM);return t.fragments.some(n=>Math.min(n.absoluteMagnitude,...(n.lightCurve??[]).map(r=>r.absoluteMagnitude))+i<=It.DAZZLING_MAGNITUDE)}static detonationsOf(t,e){const i=[];for(const n of t)n.fragments.forEach((s,r)=>{const a=It.piecesOf(n).find(l=>l.id===(s.id??String(r)));if(!a)return;const c=(s.lightCurve??[]).filter((l,h,u)=>(h===0||u[h-1].absoluteMagnitude>=l.absoluteMagnitude)&&(h===u.length-1||u[h+1].absoluteMagnitude>l.absoluteMagnitude)).map(l=>({t:l.t,magnitude:l.absoluteMagnitude}));c.push({t:a.untilT,magnitude:a.magnitudeAt(a.untilT)});for(const l of c){if(l.magnitude>It.DETONATING_MAGNITUDE||l.t<a.fromT||l.t>a.untilT)continue;const h=It.pieceAt(n,a,l.t);if(!h||h.heightM>It.AUDIBLE_BELOW_KM*1e3||i.some(d=>d.flashT===l.t&&d.reentryId===n.id))continue;const u=It.seenFrom(e,h).distanceKm;i.push({reentryId:n.id,flashT:l.t,t:l.t+u/It.SOUND_KM_S*1e3,distanceKm:u,loudness:Math.min(1,(.3+(It.DETONATING_MAGNITUDE-l.magnitude)/15)*Math.min(1,30/u))})}});return i.sort((n,s)=>n.t-s.t)}static DETONATING_MAGNITUDE=-12;static AUDIBLE_BELOW_KM=50;static SOUND_KM_S=.31;static DAZZLING_MAGNITUDE=-11;static absoluteMagnitudeAt(t,e){const i=t.lightCurve;if(!i||i.length===0)return t.absoluteMagnitude;if(e<=i[0].t)return i[0].absoluteMagnitude;for(let n=1;n<i.length;n++){const s=i[n-1],r=i[n];if(e<=r.t)return s.absoluteMagnitude+(r.absoluteMagnitude-s.absoluteMagnitude)*(e-s.t)/Math.max(r.t-s.t,1)}return i[i.length-1].absoluteMagnitude}static viewsAt(t,e,i){const n=[];for(const s of t)for(const r of It.piecesOf(s)){if(e<r.fromT||e>r.untilT)continue;const a=It.pieceAt(s,r,e);if(!a)continue;const c=It.seenFrom(i,a);if(c.altitudeDeg<0)continue;const l=Math.min(It.FADE_MS,(r.untilT-r.fromT)/4),h=l>0?Math.min(1,(e-r.fromT)/l,(r.untilT-e)/l):1,u=r.magnitudeAt(e)+5*Math.log10(c.distanceKm/It.STANDARD_DISTANCE_KM),d=u+(1-h)*Math.max(0,It.FADED_MAGNITUDE-u),f=[c];for(let p=1;p<=It.TRAIN_POINTS;p++){const m=Math.min(r.trainMs*p/It.TRAIN_POINTS,e-r.fromT),g=It.pieceAt(s,r,e-m);if(!g||(f.push(It.seenFrom(i,g)),m>=e-r.fromT))break}n.push({reentryId:s.id,fragmentId:r.id,head:c,magnitude:d,fade:h,color:r.color,train:f})}return n}static piecesOf(t){const e=It.pieces.get(t);if(e)return e;const i=t.track[0]?.t??0,n=t.track[t.track.length-1]?.t??0,s=[];return t.fragments.forEach((r,a)=>{const c=(r.lagS??0)*1e3,l={id:r.id??String(a),fromT:r.fromT??i,untilT:r.untilT??n,lagMsAt:()=>c,acrossKmAt:()=>0,belowKmAt:()=>0,magnitudeAt:h=>It.absoluteMagnitudeAt(r,h),color:r.color??It.DEFAULT_COLOR,trainMs:(r.trainS??It.DEFAULT_TRAIN_S)*1e3};s.push(l),It.shedsOf(r).forEach((h,u)=>s.push(...It.shedPieces(l,h,u)))}),It.pieces.set(t,s),s}static pieces=new WeakMap;static shedPieces(t,e,i=0){const n=e.fromT??t.fromT,s=Math.min(e.untilT??t.untilT,t.untilT);if(!(e.perS>0)||s<=n)return[];const r=Math.floor((s-n)/1e3*e.perS),a=e.spreadKmS??.3,c=e.sinkKmS??.3,l=e.trainS!==void 0?e.trainS*1e3:t.trainMs*(2/3),h=[];for(let u=0;u<r;u++){const d=E=>It.hash(`${t.id}/${i}/${u}/${E}`),f=n+(u+d(1))/e.perS*1e3,p=e.lifeS*(.4+1.2*d(2))*1e3,m=e.magnitudeDrop*(.5-.5*Math.log(1-.999*d(3))),g=e.dropBack*(.5+d(4)),M=a*(2*d(5)-1),v=c*(.5+d(6)),x=t.lagMsAt(f),y=t.acrossKmAt(f),w=t.belowKmAt(f),b=E=>Math.max(0,E-f)/1e3;h.push({id:`${t.id}.${i}.${u}`,fromT:f,untilT:Math.min(f+p,It.endOf(t)),lagMsAt:E=>x+1e3*It.lagOfBraking(2*g,b(E)),acrossKmAt:E=>y+M*b(E),belowKmAt:E=>w+v*b(E),magnitudeAt:E=>t.magnitudeAt(Math.min(E,t.untilT))+m,color:t.color,trainMs:l})}return h}static lagOfBraking(t,e){return t<=0||e<=0?0:e-(1-Math.exp(-t*e))/t}static endOf(t){return t.untilT}static hash(t){let e=2166136261;for(let i=0;i<t.length;i++)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return(e>>>0)/4294967296}static pieceAt(t,e,i){const n=i-e.lagMsAt(i),s=It.leadAt(t,n);if(!s)return;const r=e.acrossKmAt(i),a=s.heightM-e.belowKmAt(i)*1e3;if(r===0)return{...s,heightM:a};const c=It.leadAt(t,n-1e3)??s;return{...It.across(c,s,r),heightM:a}}static across(t,e,i){const n=It.DEG,s=t.lat*n,r=e.lat*n,a=(e.lng-t.lng)*n,c=Math.atan2(Math.sin(a)*Math.cos(r),Math.cos(s)*Math.sin(r)-Math.sin(s)*Math.cos(r)*Math.cos(a))+Math.PI/2,l=i/6371,h=Math.asin(Math.sin(r)*Math.cos(l)+Math.cos(r)*Math.sin(l)*Math.cos(c)),u=e.lng*n+Math.atan2(Math.sin(c)*Math.sin(l)*Math.cos(r),Math.cos(l)-Math.sin(r)*Math.sin(h));return{lat:h/n,lng:u/n}}static seenFrom(t,e){const i=It.ecef(t),n=It.ecef(e),s=n[0]-i[0],r=n[1]-i[1],a=n[2]-i[2],c=t.lat*It.DEG,l=t.lng*It.DEG,h=-Math.sin(l)*s+Math.cos(l)*r,u=-Math.sin(c)*Math.cos(l)*s-Math.sin(c)*Math.sin(l)*r+Math.cos(c)*a,d=Math.cos(c)*Math.cos(l)*s+Math.cos(c)*Math.sin(l)*r+Math.sin(c)*a,f=Math.hypot(h,u,d);return{altitudeDeg:Math.asin(d/f)/It.DEG,azimuthDeg:(Math.atan2(h,u)/It.DEG+360)%360,distanceKm:f/1e3}}static ecef(t){const e=t.lat*It.DEG,i=t.lng*It.DEG,n=Math.sin(e),s=It.A/Math.sqrt(1-It.E2*n*n);return[(s+t.heightM)*Math.cos(e)*Math.cos(i),(s+t.heightM)*Math.cos(e)*Math.sin(i),(s*(1-It.E2)+t.heightM)*n]}static alongGreatCircle(t,e,i){const n=h=>{const u=h.lat*It.DEG,d=h.lng*It.DEG;return[Math.cos(u)*Math.cos(d),Math.cos(u)*Math.sin(d),Math.sin(u)]},s=n(t),r=n(e),a=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),c=Math.acos(a);let l;if(c<1e-12)l=s;else{const h=Math.sin((1-i)*c)/Math.sin(c),u=Math.sin(i*c)/Math.sin(c);l=[s[0]*h+r[0]*u,s[1]*h+r[1]*u,s[2]*h+r[2]*u]}return[Math.atan2(l[2],Math.hypot(l[0],l[1]))/It.DEG,Math.atan2(l[1],l[0])/It.DEG]}}class ah{static typed=new Map;static of(t){return ah.typed.get(t)}static set(t,e){const i=e.trim();i===""?ah.typed.delete(t):ah.typed.set(t,i)}static forget(){ah.typed.clear()}}class Vv{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=Vv.FIRST_DAY}}class zS{constructor(t,e,i){this.citation=t,this.covers=e,this.load=i}loading;mayCover(t){return this.covers(t)}async between(t,e,i,n){try{return await(await this.provider()).between(t,e,i,n)}catch{return{status:"failed"}}}async describe(t,e){try{return await(await this.provider()).describe?.(t,e)}catch{return}}provider(){if(!this.loading){const t=this.load();this.loading=t,t.catch(()=>{this.loading===t&&(this.loading=void 0)})}return this.loading}}const sL="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",rL="Aircraft positions: Flightradar24 API (https://fr24api.flightradar24.com/)",BS="flightradar24",aL=Re.point("aircraft").provide(Re.BUILT_IN,[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new zS(sL,o=>Vv.mayCover(o),async()=>new(await $t(async()=>{const{AdsbLolArchiveProvider:o}=await import("./AdsbLolArchiveProvider-C0eoxzdX.js");return{AdsbLolArchiveProvider:o}},[],import.meta.url)).AdsbLolArchiveProvider)},{id:BS,name:"Flightradar24",credit:"Flightradar24, on your own subscription",creditUrl:"https://fr24api.flightradar24.com/",keyUrl:"https://fr24api.flightradar24.com/key-management",create:()=>new zS(rL,o=>o>=Date.UTC(2016,4,11)&&o<=Date.now(),async()=>new(await $t(async()=>{const{Flightradar24Provider:o}=await import("./Flightradar24Provider-mKDmwMzz.js");return{Flightradar24Provider:o}},[],import.meta.url)).Flightradar24Provider({token:()=>ah.of(BS)}))}]);class Dn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,i){const n=Dn.positionAt(t,i);if(!n)return;const s=It.seenFrom(e,n.geo);if(!(s.altitudeDeg<0))return{track:t,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:Dn.angularRate(t,e,i)}}static viewsAt(t,e,i){return t.flatMap(n=>Dn.seenFrom(n,e,i)??[])}static groundDistanceKm(t,e){const i=Math.PI/180,n=Math.sin((e.lat-t.lat)*i/2)**2+Math.cos(t.lat*i)*Math.cos(e.lat*i)*Math.sin((e.lng-t.lng)*i/2)**2;return 2*Dn.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const i=t.points;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=e;)n++;const s=i[n],r=i[n+1]??s,a=r.t-s.t;if(a>Dn.MAX_GAP_S*1e3)return;const c=a>0?(e-s.t)/a:0,l=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*c,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*c,lng:Dn.wrapLongitude(s.lng+h*c),heightM:l*Dn.FT_TO_M},altitudeFt:l,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(t,e,i){const n=Dn.positionAt(t,i-500),s=Dn.positionAt(t,i+500);if(!n||!s)return;const r=Dn.unit(It.seenFrom(e,n.geo)),a=Dn.unit(It.seenFrom(e,s.geo)),c=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(c)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(i),Math.cos(e)*Math.cos(i),Math.sin(e)]}}const HS="https://ufoathome.org/fireballs/index.json";class Qr{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Qr.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/fireballs/index.json",location.href).href),t.includes(HS)||t.push(HS),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=Qr.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!Qr.mayCover(e))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...n].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...n].filter(r=>i.index.months.includes(r)).map(r=>this.monthOf(r,i.base)))).flat().filter(r=>r.t>=t&&r.t<=e):void 0}static seenFrom(t,e){const i=Qr.peakFraction(t),n={lat:t.from[0]+(t.to[0]-t.from[0])*i,lng:t.from[1]+(t.to[1]-t.from[1])*i,heightM:t.peakHeightKm*1e3},s=It.seenFrom(e,n);if(!(s.altitudeDeg<0))return{record:t,peak:s,magnitude:t.peakMagnitude+5*Math.log10(s.distanceKm/It.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const i=t.t-e,n=i+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:i,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:n,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:Qr.COLOR,trainS:Qr.TRAIN_S}]}}static peakFraction(t){const e=t.from[2]-t.to[2];return Math.abs(e)<1e-6?.5:Math.min(1,Math.max(0,(t.from[2]-t.peakHeightKm)/e))}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(e.ok)return{index:await e.json(),base:t}}catch{}})(),this.index}monthOf(t,e){let i=this.months.get(t);return i||(i=this.fetchImpl(new URL(`${t}.json`,e).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(t,i)),i}}const Ll=Math.PI/180,bu=180/Math.PI;class _i{constructor(t,e){this.timeline=t,this.tolerance=e}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;static lawsOf(t,e){return{direction(i,n,s){const r=t.law({kind:"heading",value:i.azimuthDeg},e),a=Math.abs(((n.azimuthDeg-i.azimuthDeg)%360+540)%360-180),c=t.law({kind:"elevation",value:i.altitudeDeg},e),l=Math.max(_i.DIRECTION_TOLERANCE_DEG,s);return a>(r.high??i.azimuthDeg)-i.azimuthDeg+l||n.altitudeDeg>(c.high??i.altitudeDeg)+l||n.altitudeDeg<(c.low??i.altitudeDeg)-l},size(i,n){const s=t.law({kind:"angularSize",value:i},e);return n<(s.low??i)/_i.SIZE_TOLERANCE||n>(s.high??i)*_i.SIZE_TOLERANCE}}}at(t,e,i,n){const s=[];for(const r of e){const a=_i.projectionOf(r,i,n?.(r));if(a)for(const c of r.explains){const l=this.timeline.getInterpolatedShapeAt(t,c);!l||l.transparency>=1||s.push({..._i.compare(c,r.id,{aim:l.aim,angular:l.angular},a,this.tolerance),title:l.title})}}return s}static compare(t,e,i,n,s){const r=[],a=i.aim?_i.separationDeg(i.aim,n.aim):void 0;if(a!==void 0){const u=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;(s?s.direction(i.aim,n.aim,u):a>Math.max(_i.DIRECTION_TOLERANCE_DEG,u))&&r.push("direction")}const c=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,l=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0,h=(u,d)=>s?s.size(d,d*u):!_i.withinSize(u);return c!==void 0&&h(c,i.angular.widthDeg)&&r.push("width"),l!==void 0&&h(l,i.angular.heightDeg)&&r.push("height"),{sourceId:t,bodyId:e,stated:i,predicted:n,separationDeg:a,widthRatio:c,heightRatio:l,disagreements:r}}static projectionOf(t,e,i){const n=i&&i.length>0?i:_i.outlineOf(t),s=i&&i.length>0?_i.centreOf(i):t,r=_i.normalized({eastM:s.eastM-e.eastM,northM:s.northM-e.northM,upM:s.upM-e.upM});if(!r)return;const a=_i.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},c=_i.cross(a,r);let l=1/0,h=-1/0,u=1/0,d=-1/0;for(const f of n){const p={eastM:f.eastM-e.eastM,northM:f.northM-e.northM,upM:f.upM-e.upM},m=_i.dot(p,r);if(m<=0)return;const g=Math.atan2(_i.dot(p,a),m),M=Math.atan2(_i.dot(p,c),m);l=Math.min(l,g),h=Math.max(h,g),u=Math.min(u,M),d=Math.max(d,M)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*bu+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*bu},angular:{widthDeg:(h-l)*bu,heightDeg:(d-u)*bu}}}static centreOf(t){const e=i=>(Math.min(...t.map(n=>n[i]))+Math.max(...t.map(n=>n[i])))/2;return{eastM:e("eastM"),northM:e("northM"),upM:e("upM")}}static separationDeg(t,e){const i=t.altitudeDeg*Ll,n=e.altitudeDeg*Ll,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((t.azimuthDeg-e.azimuthDeg)*Ll);return Math.acos(Math.max(-1,Math.min(1,s)))*bu}static withinSize(t){return t<=_i.SIZE_TOLERANCE&&t>=1/_i.SIZE_TOLERANCE}static outlineOf(t){const e=t.sizeM.widthM/2,i=t.sizeM.lengthM/2,n=t.sizeM.heightM/2,s=[],r=t.model.url===void 0?t.model.id:void 0;if(r!==void 0&&r!=="box"&&dA.includes(r))for(let u=0;u<=_i.RINGS;u++){const d=u/_i.RINGS*Math.PI;for(let f=0;f<_i.SEGMENTS;f++){const p=f/_i.SEGMENTS*2*Math.PI;s.push([e*Math.sin(d)*Math.cos(p),i*Math.sin(d)*Math.sin(p),n*Math.cos(d)])}}else for(const u of[-e,e])for(const d of[-i,i])for(const f of[-n,n])s.push([u,d,f]);const c=t.attitude.headingDeg*Ll,l=t.attitude.pitchDeg*Ll,h=t.attitude.rollDeg*Ll;return s.map(([u,d,f])=>{const p=u*Math.cos(h)+f*Math.sin(h),m=-u*Math.sin(h)+f*Math.cos(h),g=d*Math.cos(l)-m*Math.sin(l),M=d*Math.sin(l)+m*Math.cos(l);return{eastM:t.eastM+p*Math.cos(c)+g*Math.sin(c),northM:t.northM-p*Math.sin(c)+g*Math.cos(c),upM:t.upM+M}})}static dot(t,e){return t.eastM*e.eastM+t.northM*e.northM+t.upM*e.upM}static cross(t,e){return{eastM:t.northM*e.upM-t.upM*e.northM,northM:t.upM*e.eastM-t.eastM*e.upM,upM:t.eastM*e.northM-t.northM*e.eastM}}static normalized(t){const e=Math.hypot(t.eastM,t.northM,t.upM);return e>1e-9?{eastM:t.eastM/e,northM:t.northM/e,upM:t.upM/e}:void 0}}class ta{static built=new WeakMap;static of(t){let e=ta.built.get(t);return e||(e=t.create(),ta.built.set(t,e)),e}static itemsOf(t,e){const i=t?.[e];return Array.isArray(i)?i:[]}static computes(t,e){return e.some(i=>ta.itemsOf(t,i.key).length>0)}static expand(t,e){if(!t||!ta.computes(t,e))return t;const i=e.flatMap(n=>ta.itemsOf(t,n.key).flatMap(s=>n.bodiesOf(s)));return{...t,bodies:[...t.bodies,...i]}}static computedPart(t,e){const i={};for(const n of e){const s=ta.itemsOf(t,n.key);s.length>0&&(i[n.key]=[...s])}return i}static saysNothing(t,e){return t.bodies.length===0&&t.title===void 0&&t.smoke===void 0&&e.every(i=>t[i.key]===void 0)}}const oL=_r.catalog({en:()=>$t(()=>import("./FlareKindMessages_en-BroHgiwr.js"),[],import.meta.url).then(o=>o.flareKindMessages_en),fr:()=>$t(()=>import("./FlareKindMessages_fr-Dy5SlSna.js"),[],import.meta.url).then(o=>o.flareKindMessages_fr),es:()=>$t(()=>import("./FlareKindMessages_es-SraQyQ3Y.js"),[],import.meta.url).then(o=>o.flareKindMessages_es),it:()=>$t(()=>import("./FlareKindMessages_it-CF39wmrC.js"),[],import.meta.url).then(o=>o.flareKindMessages_it)});class ws{static MJU_7={massKg:.37,burnedKg:.26,dragAreaM2:1.2*.0508*.2032,ejectionMS:30,burnS:4.5,luminousIntensityCd:2e4,flameSizeM:1.5,color:"#ffd9a0"};static SAMPLE_MS=100;static STEP_S=.002;static G=9.81;static expand(t){const e=t?.flares;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>ws.bodiesOf(i))]}}static bodiesOf(t){const e={...ws.MJU_7,...t.flare},i=[],n=t.aircraft;if(n.model||n.sound){const s=t.releases.map(h=>h.t),r=Math.min(n.t,...s)-12e4,a=Math.max(n.t,...s)+12e4,c=n.model?{color:"#30333a",albedo:.15}:{transparency:1},l=h=>{const u=ws.aircraftAt(n,h);return{t:h,eastM:u.x,northM:u.y,altitudeM:u.z,attitude:{headingDeg:n.headingDeg},sizeM:n.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:c}};i.push({id:`${t.id}-aircraft`,title:t.title,model:n.model??{id:"sphere"},track:[l(r),l(a)],sound:n.sound})}return n.glow&&i.push(ws.glowBody(t,n.glow)),t.releases.forEach((s,r)=>i.push(ws.flareBody(t,e,s,r))),i}static aircraftAt(t,e){const i=t.headingDeg*Math.PI/180,n=(e-t.t)/1e3*t.speedMS;return{x:t.eastM+Math.sin(i)*n,y:t.northM+Math.cos(i)*n,z:t.altitudeM}}static burnShare(t,e){if(e<0||e>=t.burnS)return 0;if(e<.2)return e/.2;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static trajectory(t,e,i,n=ws.SAMPLE_MS){const s=t.aircraft,r=s.headingDeg*Math.PI/180,c={...ws.aircraftAt(s,i),vx:Math.sin(r)*s.speedMS,vy:Math.cos(r)*s.speedMS,vz:-e.ejectionMS},l=(t.wind?.towardDeg??0)*Math.PI/180,h=t.wind?.speedMS??0,u=Math.sin(l)*h,d=Math.cos(l)*h,f=s.originElevationM??1e3,p=[{t:i,x:c.x,y:c.y,z:c.z}],m=ws.STEP_S,g=Math.round(n/1e3/m),M=Math.ceil(e.burnS/m);for(let v=1;v<=M;v++){const x=v*m,y=e.massKg-e.burnedKg*Math.min(1,x/e.burnS),w=1.225*Math.exp(-(c.z+f)/8500),b=c.vx-u,E=c.vy-d,S=c.vz,A=Math.hypot(b,E,S),_=.5*w*e.dragAreaM2*A/y;c.vx=(c.vx+_*m*u)/(1+_*m),c.vy=(c.vy+_*m*d)/(1+_*m),c.vz=(c.vz-ws.G*m)/(1+_*m),c.x+=c.vx*m,c.y+=c.vy*m,c.z+=c.vz*m,(v%g===0||v===M)&&p.push({t:i+Math.round(x*1e3),x:c.x,y:c.y,z:c.z})}return p}static glowBody(t,e){const i=e.sizeM/2,n=e.luminousIntensityCd/(Math.PI*i*i),s=[{t:e.fromT,lit:!0}];if(e.onS&&e.offS)for(let l=e.fromT,h=!0;l<e.untilT;h=!h)l+=(h?e.onS:e.offS)*1e3,l<e.untilT&&s.push({t:l,lit:!h});const r=(l,h)=>{const u=ws.aircraftAt(t.aircraft,l);return{t:l,eastM:u.x,northM:u.y,altitudeM:u.z,appearance:{color:e.color,luminanceCdM2:h?n:0}}},a=[];s.forEach(({t:l,lit:h},u)=>{u>0&&a.push(r(l-1,!h)),a.push(r(l,h))}),a[0]={...a[0],sizeM:{widthM:e.sizeM,lengthM:e.sizeM,heightM:e.sizeM},present:!0};const c=s[s.length-1];return a.push(r(e.untilT,c.lit),{t:e.untilT+1,present:!1}),{id:`${t.id}-glow`,title:t.title,explains:e.explains,model:{id:"sphere"},track:a}}static flareBody(t,e,i,n){const s=e.flameSizeM,r=s/2,a=e.luminousIntensityCd/(Math.PI*r*r),c=ws.trajectory(t,e,i.t),l=c.map((h,u)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...u===0?{sizeM:{widthM:s,lengthM:s,heightM:s},present:!0}:{},appearance:{color:e.color,luminanceCdM2:a*ws.burnShare(e,(h.t-i.t)/1e3),...u===0?{haloScale:1}:{}}}));return l.push({t:c[c.length-1].t+1,present:!1}),{id:`${t.id}-flare-${n+1}`,title:t.title,explains:i.explains,model:{id:"sphere"},track:l}}}const GS={key:"flares",messages:oL,bodiesOf:o=>ws.bodiesOf(o)},cL=_r.catalog({en:()=>$t(()=>import("./LanternKindMessages_en-fUfoRYC0.js"),[],import.meta.url).then(o=>o.lanternKindMessages_en),fr:()=>$t(()=>import("./LanternKindMessages_fr-CDem7PTY.js"),[],import.meta.url).then(o=>o.lanternKindMessages_fr),es:()=>$t(()=>import("./LanternKindMessages_es-Chyc607D.js"),[],import.meta.url).then(o=>o.lanternKindMessages_es),it:()=>$t(()=>import("./LanternKindMessages_it-yOojym1u.js"),[],import.meta.url).then(o=>o.lanternKindMessages_it)});class De{static COMMON={envelopeVolumeM3:.19,massKg:.065,fuelKg:.03,burnS:600,insideExcessK:150,dragAreaM2:.25,luminousIntensityCd:10,widthM:.6,heightM:1,color:"#ff8a24",shape:"classic",paperColor:"#ffffff"};static FLAME_CDM2=5e3;static TITLE={en:"Sky lantern",fr:"Lanterne céleste",es:"Farolillo volador",it:"Lanterna volante"};static FLICKER=.15;static INSIDE_SHARE=2;static PAPER_FULL_CDM2=De.COMMON.luminousIntensityCd/(Math.PI*De.COMMON.widthM/2*De.COMMON.heightM/2);static SAMPLE_MS=1e3;static STEP_S=.05;static COOLING_S=20;static TURBULENCE={horizontalMS:.8,verticalMS:.3,timescaleS:30};static G=9.81;static R_AIR=287.05;static LAPSE=.0065;static expand(t){const e=t?.lanterns;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>De.bodiesOf(i))]}}static bodiesOf(t){return De.releasesOf(t).map((e,i)=>De.lanternBody(t,e,i))}static releasesOf(t){const e=[...t.releases??[]],i=t.group;if(!i||!(i.count>0))return e;const n=De.randomFrom(i.seed??1),s=c=>c.min+(c.max-c.min)*n(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let c=0;c<i.count;c++){const l=i.fromT+r*c+(n()-.5)*r,h=a*Math.sqrt(n()),u=2*Math.PI*n();e.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,l))),explains:i.explains,eastM:Math.round(h*Math.sin(u)*10)/10,northM:Math.round(h*Math.cos(u)*10)/10,burnedS:i.burnedS,seed:Math.floor(n()*4294967296),lantern:{burnS:Math.round(s(i.burnS??{min:480,max:900})),insideExcessK:Math.round(s(i.insideExcessK??{min:125,max:175}))}})}return e}static randomFrom(t){let e=t>>>0;return()=>{e=e+1831565813>>>0;let i=e;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}static typeOf(t,e){return{...De.COMMON,...t.lantern,...e.lantern}}static heatShare(t,e){if(e<0||e>=t.burnS)return 0;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static windAt(t,e){const i=De.componentsOf(t.wind),n=t.windAloft;if(!n)return i;const s=De.componentsOf(n),r=Math.max(0,Math.min(1,e/n.atM));return{x:i.x+(s.x-i.x)*r,y:i.y+(s.y-i.y)*r}}static trajectory(t,e,i=De.SAMPLE_MS){const n=De.typeOf(t,e),s=t.site,r=s.altitudeM??0,a=Math.max(0,e.burnedS??0),c=s.originElevationM??0,l=(t.airTemperatureC??10)+273.15,h={x:s.eastM+(e.eastM??0),y:s.northM+(e.northM??0),z:e.altitudeM??r,vx:0,vy:0,vz:0,excessK:n.insideExcessK*De.heatShare(n,a)},u=De.STEP_S,d=Math.max(1,Math.round(i/1e3/u)),f=Math.ceil(Math.max(0,n.burnS-a)/u),p=[{t:e.t,x:h.x,y:h.y,z:h.z,light:De.heatShare(n,a),tiltDeg:0,tiltTowardDeg:0}],m=De.gusts(t.turbulence??De.TURBULENCE,De.seedOf(e),u);for(let g=1;g<=f;g++){const M=g*u,v=a+M,x=De.heatShare(n,v);h.excessK+=(n.insideExcessK*x-h.excessK)*Math.min(1,u/De.COOLING_S);const y=h.z-r,w=l-De.LAPSE*Math.max(0,y),b=101325*Math.exp(-(h.z+c)/8400),E=b/(De.R_AIR*w),S=b/(De.R_AIR*(w+h.excessK)),A=n.massKg-n.fuelKg*Math.min(1,v/n.burnS),_=(E-S)*n.envelopeVolumeM3*De.G,I=A+S*n.envelopeVolumeM3+.5*E*n.envelopeVolumeM3,D=De.windAt(t,y),P=m(),L={x:D.x+P.x,y:D.y+P.y,z:P.z},O=h.vx-L.x,k=h.vy-L.y,H=h.vz-L.z,W=.5*E*n.dragAreaM2*Math.hypot(O,k,H)/I;h.vx=(h.vx+W*u*L.x)/(1+W*u),h.vy=(h.vy+W*u*L.y)/(1+W*u),h.vz=(h.vz+W*u*L.z+(_-A*De.G)/I*u)/(1+W*u);const Q=h.z<=r&&h.vz<=0;if(Q&&(h.vx=0,h.vy=0,h.vz=0),h.x+=h.vx*u,h.y+=h.vy*u,h.z=Math.max(r,h.z+h.vz*u),g%d===0||g===f){const q=L.x-h.vx,nt=L.y-h.vy,at=.5*E*n.dragAreaM2*Math.hypot(q,nt,L.z-h.vz)*Math.hypot(q,nt);p.push({t:e.t+Math.round(M*1e3),x:h.x,y:h.y,z:h.z,light:x,tiltDeg:Q?0:Math.atan2(at,A*De.G)*180/Math.PI,tiltTowardDeg:(Math.atan2(q,nt)*180/Math.PI+360)%360})}}return p}static seedOf(t){return t.seed!==void 0?t.seed:Math.round(t.t)*2654435761+Math.round((t.eastM??0)*100)*40503+Math.round((t.northM??0)*100)>>>0}static gusts(t,e,i){const n=De.randomFrom(e),s=()=>Math.sqrt(-2*Math.log(Math.max(1e-12,n())))*Math.cos(2*Math.PI*n()),r=t.timescaleS>0?Math.exp(-i/t.timescaleS):0,a=Math.sqrt(1-r*r),c={x:t.horizontalMS*s(),y:t.horizontalMS*s(),z:t.verticalMS*s()};return()=>(c.x=r*c.x+a*t.horizontalMS*s(),c.y=r*c.y+a*t.horizontalMS*s(),c.z=r*c.z+a*t.verticalMS*s(),c)}static componentsOf(t){if(!t)return{x:0,y:0};const e=t.towardDeg*Math.PI/180;return{x:Math.sin(e)*t.speedMS,y:Math.cos(e)*t.speedMS}}static lanternBody(t,e,i){const n=De.typeOf(t,e),s=n.luminousIntensityCd/(Math.PI*n.widthM/2*n.heightM/2),r=De.trajectory(t,e),a={widthM:n.widthM,lengthM:n.widthM,heightM:n.heightM},c=De.through(n.color,n.paperColor),l=r.map((h,u)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...u===0?{sizeM:a,present:!0}:{},attitude:{headingDeg:Math.round(h.tiltTowardDeg),pitchDeg:-Math.round(h.tiltDeg*10)/10},appearance:{color:c,luminanceCdM2:s*h.light,...u===0?{albedo:.6,haloScale:1}:{}},lights:De.lightsOf(s*h.light)}));return l.push({t:r[r.length-1].t+1,present:!1}),{id:`${t.id}-lantern-${i+1}`,title:De.TITLE,explains:e.explains,model:{id:`ufoathome-sky-lantern-${n.shape}`},modelParameters:{paperColor:n.paperColor},flicker:De.FLICKER,altitudeFrom:{eastM:r[0].x,northM:r[0].y},track:l}}static lightsOf(t){return{paper:t,"paper-inside":t*De.INSIDE_SHARE,flame:t>0?De.FLAME_CDM2*t/De.PAPER_FULL_CDM2:0}}static through(t,e){const i=c=>[1,3,5].map(l=>parseInt(c.slice(l,l+2),16)/255),n=i(t),s=i(e),r=n.map((c,l)=>c*s[l]),a=Math.max(...n)/(Math.max(...r)||1);return"#"+r.map(c=>Math.round(Math.min(1,c*a)*255).toString(16).padStart(2,"0")).join("")}}const VS={key:"lanterns",messages:cL,bodiesOf:o=>De.bodiesOf(o),editor:()=>$t(async()=>{const{LanternEditor:o}=await import("./LanternEditor-CcBPfbIH.js");return{LanternEditor:o}},__vite__mapDeps([11,3]),import.meta.url).then(({LanternEditor:o})=>(t,e,i)=>new o(t,e,i))},lL=Re.point("interpretations").provide(Re.BUILT_IN,[{id:GS.key,name:"Decoy flares",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>GS},{id:VS.key,name:"Sky lanterns",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>VS}]);class WS{static kinds(){return lL.map(t=>ta.of(t))}}Eb();const hL="satellites-change",uL="fireballs-change",dL="references-change",fL="aircraft-change",pL="rr0-confrontation",XS="comet:",YS="nova:",mL=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,gL=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,ML=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,vL=-18,yL={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},m0={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class _e extends HTMLElement{creditsButton;set ownCredits(t){this.creditsButton.hidden=!t}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",fh,ph,Sc]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;flightMark;markedFlight;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new R;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new $n;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Qr;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=aL[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return _e.trafficRuntimeLoading??=$t(()=>import("./trafficRuntime-cS8H9PlA.js"),__vite__mapDeps([12,10]),import.meta.url).then(t=>_e.trafficRuntime=t),_e.trafficRuntimeLoading.catch(()=>{_e.trafficRuntimeLoading=void 0}),_e.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new rh;vehicleAudio=new e_;aircraftAudio;vehicleHearing=new k0;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=t=>{if(this.lastHover={clientX:t.clientX,clientY:t.clientY,altKey:t.altKey},this.ghostMissedSinceMs=void 0,this.hoverFrame!==void 0&&t.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=t.altKey,this.hoverAt(this.lastHover),this.hoverFrame===void 0&&(this.hoverFrame=requestAnimationFrame(()=>{this.hoverFrame=void 0,this.hoverPending&&this.lastHover&&this.hoverAt(this.lastHover),this.hoverPending=!1}))};ghostMissedSinceMs;static GHOST_KEPT_MS=600;ghostStillUnder(t,e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return!0;const n=(t.clientX-i.left)/i.width*2-1,s=1-(t.clientY-i.top)/i.height*2;return this.sceneRenderer.ghostsReadableAt(n,s)?this.sceneRenderer.pickGhostAt(n,s)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=e,e-this.ghostMissedSinceMs>_e.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;hoverAt(t){if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,i=e.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(t.clientX-i.left)/i.width*e.width,s=(t.clientY-i.top)/i.height*e.height;if(this.ufoElement.hasVisibleShapeAt(n,s)){this.hoverTooltip.hidden=!0;return}const r=(t.clientX-i.left)/i.width*2-1,a=-((t.clientY-i.top)/i.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(r,a))return;const c=this.pickAt(r,a,!0,t.altKey);c?this.showHoverTooltip(t,t.altKey&&c.detail?c.detail():c.name):this.hoverTooltip.hidden=!0,this.showGhostPath(c?.path,i)}showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),n=d=>({x:e.left-i.left+(d.x+1)/2*e.width,y:e.top-i.top+(1-d.y)/2*e.height}),s=n(t.from),r=n(t.to),a=n({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[c,l,h,u]=Array.from(this.ghostPath.children);for(const d of[c,l])d.setAttribute("x1",String(s.x)),d.setAttribute("y1",String(s.y)),d.setAttribute("x2",String(r.x)),d.setAttribute("y2",String(r.y));h.setAttribute("cx",String(a.x)),h.setAttribute("cy",String(a.y)),u.setAttribute("cx",String(r.x)),u.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,i=!0,n=!1){const s=this.naming,r=s.names;if(n&&this.sceneRenderer.pickDropAt(t,e)){const b=r.ghostTooltip,E=b.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:E,detail:()=>b.dropDetail.replace("{name}",E)}}const a=this.sceneRenderer.pickBodyAt(t,e);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const c=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,l=c?this.interpretationShown?.bodies.find(b=>b.id===c):void 0,h=l?this.said.read(l.title)||(l.model.id==="figure"?s.decorKind("entity"):void 0):void 0;if(c!==void 0&&h)return{kind:"body",id:c,name:h};const u=this.skyEventPickAt(t,e,(b,E)=>!E.inSky);if(u)return u;const d=i?this.ghostPick(t,e):void 0;if(d)return d;if(this.sceneRenderer.pickAfterimageAt(t,e)){const b=this.naming.names.afterimageTooltip;return{kind:"afterimage",name:b.name,detail:()=>b.detail.replace("{name}",b.name)}}const f=this.pickDecorAt(t,e),p=f?this.ufoElement.sighting.decor.find(b=>b.id===f):void 0;if(p){const b=this.said.read(p.title)||s.decorKind(p.kind);return{kind:"decor",id:p.id,name:b,detail:()=>this.decorTooltip(p,b)}}const m=this.sceneRenderer.pickRailwayAt(t,e);if(m){const b=r.railwayTooltip;return{kind:"railway",id:m.line.id,name:Vr.name(m.line,b),detail:()=>Vr.detail(m,b,E=>this.distanceText(E))}}const g=this.trafficTooltipAt(t,e);if(g)return{kind:"traffic",name:g};const M=this.skyEventPickAt(t,e,(b,E)=>E.inSky===!0&&!b.pickedAfterSatellites);if(M)return M;const v=this.sceneRenderer.pickSatelliteAt(t,e);if(v)return{kind:"satellite",name:r.satelliteTooltip.replace("{name}",v.name).replace("{mag}",v.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(v.heightKm).toLocaleString())};const x=this.skyEventPickAt(t,e,(b,E)=>E.inSky===!0&&b.pickedAfterSatellites===!0);if(x)return x;const y=this.sceneRenderer.pickOpticsAt(t,e);if(y){const b=r.opticsTooltips[y.id].replace("{angle}",String(Math.round(y.angleDeg??0)));return{kind:"optics",id:y.id,name:b.split(" — ")[0],detail:()=>b}}const w=this.sceneRenderer.pickStarAt(t,e);if(w){const b=w.star.mag,E=w.altitudeDeg,S=E<0?r.starTooltipBelow:r.starTooltip,A=s.star(w.star);return{kind:"star",name:A,detail:()=>S.replace("{name}",A).replace("{mag}",b.toLocaleString(void 0,{maximumFractionDigits:Math.abs(b)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(E))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(t,e){const i=this.ufoElement.canvasElement,n={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},s=`${Math.round(t/n.x)}:${Math.round(e/n.y)}`,r=performance.now(),a=this.ghostLights.get(s);if(a&&r-a.atMs<_e.GHOST_LIGHT_KEPT_MS)return a.light;let c=this.shiningDecorNear(t,e,2*Math.max(n.x,n.y)),l;if(!c)for(const[h,u]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const d=this.pickAt(t+h*n.x,e+u*n.y,!1);if(d?.kind==="star")l??=d;else if(d){c=d;break}}return c??=this.shiningDecorNear(t,e,6*Math.max(n.x,n.y)),c??=l,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(s,{light:c??null,atMs:r}),c??null}ghostPick(t,e){const i=this.sceneRenderer.pickGhostAt(t,e);if(!i)return;const n=this.naming.names.ghostTooltip,s=this.lightOfGhost(i.source.x,i.source.y)??void 0,r=(s?.kind==="star"?s.name.split(" — ")[0]:s?.name)??n.unnamed,a=i.ghost,l=(pi.scatters(a)?n.halo:a.cause==="glass"?n.double:n.ghost).replace("{name}",r),h=a.scale<0?n.opposite:a.scale===1?n.around:n.sameSide;return{kind:"ghost",id:s?.id,name:l,detail:()=>n.detail.replace("{name}",l).replace("{cause}",n.causes[a.cause??"lens"]).replace("{where}",h),path:{from:{x:a.scale*i.source.x,y:a.scale*i.source.y},to:i.source}}}shiningDecorNear(t,e,i){let n;for(const s of this.ufoElement.sighting.decor){if(!(s.kind==="streetlight"||s.kind==="trafficlight"||(s.lights?.length??0)>0||s.kind==="vehicle"&&s.lit))continue;const a=this.sceneRenderer.decorScreenBox(s.id);if(!a)continue;const c=Math.hypot(Math.max(a.minX-t,0,t-a.maxX),Math.max(a.minY-e,0,e-a.maxY));if(c>i||n&&c>=n.distance)continue;const l=this.said.read(s.title)||this.naming.decorKind(s.kind);n={distance:c,pick:{kind:"decor",id:s.id,name:l}}}return n?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const i=new _c(n=>{if(!pi.records(t.instrument)||!pi.falling(t.lens))return 0;const s=Yh(t,n*1e3),r=ze(t,n*1e3);return(s.precipitationAmount??1)*pi.impactRate(s,t.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:s.windDirectionDeg,windSpeedMS:s.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:i}}return this.glassWetting.wetting}glassWetting;get skyEventsShown(){return this.skyEventsOf(this.ufoElement.sighting)}skyEventsStartDate;skyEventsMerged;skyEventsOf(t){const e=t.skyEvents,i=this.fireballs?.reentries,n=this.skyEventsMerged;if(n&&n.stated===e&&n.fireballs===i)return n.shown;const s=i?.length?{...e,reentries:[...e?.reentries??[],...i]}:e;return this.skyEventsMerged={stated:e,fireballs:i,shown:s},s}skyEventTexts=new Map;skyEventTextsLanguage;loadSkyEventTexts(t){const e=qg(wc.preferencesFor(this),Zg);e!==this.skyEventTextsLanguage&&(this.skyEventTexts.clear(),this.skyEventTextsLanguage=e);for(const i of t)this.skyEventTexts.has(i)||i.messages.load(e).then(n=>{this.skyEventTextsLanguage===e&&this.skyEventTexts.set(i,n)},()=>{})}skyEventPickAt(t,e,i){const n=this.skyEventsShown;if(!n)return;const s=this.sceneRenderer.pickSkyEventAt(t,e,i),r=s?vM.map(d=>Wa.of(d)).find(d=>d.key===s.kind):void 0,a=s&&r?Wa.eventsOf(n,r).find(d=>d.id===s.id):void 0;if(!s||!r||!a)return;const c=this.skyEventTexts.get(r);if(!c){this.loadSkyEventTexts([r]);return}const l=this.said.read(a.title)||c.name,h=r.describe?.(a,s,{said:this.said,texts:c,name:l,distance:d=>this.distanceText(d)}),u=h?.detail??(s.distanceM!==void 0?`${l}, ${this.distanceText(s.distanceM)}`:void 0);return{kind:r.pickKind??"skyEvent",id:a.id,name:h?.name??l,...u!==void 0?{detail:()=>u}:{}}}distanceText(t){return t>=1e3?`${(t/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${t.toLocaleString(void 0,{maximumFractionDigits:t<10?1:0})} m`}decorTooltip(t,e){const i=l=>l.toLocaleString(void 0,{maximumFractionDigits:l<10?1:0}),n=ut.sizeOf(t),s=this.sceneRenderer.decorDistanceM(t.id),r=s===void 0?"":this.distanceText(s);return this.naming.names.decorTooltip.replace("{name}",e).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(t){const e=t.startsWith(XS)?t.slice(XS.length):void 0,i=e?bA.find(s=>s.id===e):void 0;if(i)return this.naming.comet(i);const n=t.startsWith(YS)?kS.byId(t.slice(YS.length)):void 0;return n?this.naming.nova(n):this.naming.body(t)}get naming(){return this.sceneNaming}sceneNaming=new NS;namesLanguage;ready=Promise.resolve();async loadSceneNames(){const t=qg(wc.preferencesFor(this),Zg);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await P_(t);t===this.namesLanguage&&this.applySceneNaming(new NS(e))}setBusy(t,e=""){this.busyElement.hidden=!t,this.busyNote.textContent=t?e:"",this.busyElement.setAttribute("aria-label",e),this.busyElement.setAttribute("aria-busy",String(t))}renderLoaderText(t,e){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,c)=>{c>0&&s.append(" ");const l=document.createElement("span");l.className="scene-loader-word",l.setAttribute("aria-hidden","true");for(const h of a){const u=document.createElement("span");u.className="scene-loader-letter",u.style.setProperty("--i",String(i++)),u.textContent=h,l.append(u)}s.append(l),i++})};n(this.loaderNotVideo,t),i+=6,n(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t,t.loaded&&(this.creditsButton.title=t.names.credits,this.creditsButton.setAttribute("aria-label",t.names.credits),this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names.compassPoints))}showHoverTooltip(t,e){const i=this.hoverTooltip;i.textContent=e,i.hidden=!1,typeof i.showPopover=="function"&&!i.matches(":popover-open")&&i.showPopover();const{innerWidth:n,innerHeight:s}=window,r=12,a=4,c=Math.min(t.clientX+r,n-i.offsetWidth-a),l=t.clientY+r,h=l+i.offsetHeight+a>s?t.clientY-r-i.offsetHeight:l;i.style.left=`${Math.max(a,c)}px`,i.style.top=`${Math.max(a,h)}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};hearDetonations(t,e,i,n){const s=`${i.lat.toFixed(4)},${i.lng.toFixed(4)}`,r=this.detonationsFor;(!r||s!==r.key||t.length!==r.reentries.length||t.some((l,h)=>l!==r.reentries[h]))&&(this.detonationsFor={reentries:[...t],key:s,detonations:t.length?It.detonationsOf(t,i):[]});const a=this.detonationsFor.detonations;if(n)return;const c=this.lastDetonationT;if(this.lastDetonationT=e,!(c===void 0||e<c||e-c>_e.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const l of a)l.t>c&&l.t<=e&&this.weatherAudio.playDetonation(l.loudness)}detonates(t){const e=[...t.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],i=ze(t,0),n=t.event.place?.[0],s=i?.lat??n?.lat,r=i?.lng??n?.lng;return e.length>0&&s!==void 0&&r!==void 0&&It.detonationsOf(e,{lat:s,lng:r,heightM:this.altitudeOf(i)}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(t){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),mn.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(Yh(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const t=this.ufoElement.level;this.weatherAudio.setLevel(t),this.vehicleAudio.setLevel(t),this.aircraftAudio?.setLevel(t)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=t=>{if(this.lastTimeMs=t.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const e=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&e-this.lastPlayingHoverMs>=_e.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=e,this.ghostStillUnder(this.lastHover,e)&&this.hoverAt(this.lastHover))}this.placeFlightMark(),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(t,t),this.weatherAudio.setPaused(!t),this.vehicleAudio.setPaused(!t),this.aircraftAudio?.setPaused(!t),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${u_}</style>${h_}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new lt(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(dL));const e=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new Ku(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=s=>{this.holding=s,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.flightMark=this.shadow.getElementById("flight-mark"),this.ufoElement=document.createElement(Jg),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapSnapshotSource=s=>this.snapshotMapOf(s),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",s=>this.lookToward(s.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),n=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",s=>{s.newState==="open"&&Yn.fill(n,this)}),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(Ab,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=s=>s.vehicle!==void 0||s.decor.some(r=>r.engine!==void 0)||s.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1)||this.detonates(s),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of _e.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new wr(wc.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const i=t.vehicle;return i?{setting:kc.at(i.headlights??"auto",i.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}:void 0}travelHeadingAt(t,e){const i=ze(t,e);if(!i)return 0;for(const n of[400,-400]){const s=ze(t,e+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=ae(s.lat,s.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(n<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const i=e.flatMap(s=>s.pose.lat!==void 0&&s.pose.lng!==void 0?[{lat:s.pose.lat,lng:s.pose.lng}]:[]),n=i.length>=2?i:void 0;return this.routeCache={track:t,count:e.length,route:n},n}traceLabels(t){const e=wc.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const i=new Map;for(const n of t){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:t,language:e,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){Re.changes.addEventListener("change",this.onModulesChanged),this.saidTexts=void 0,this.ready=this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of _e.GESTURES)document.addEventListener(e,this.handlePageGesture,!0);const t=this.getAttribute("src");t&&this.loadFromSrc(t)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(t=>{if(t[t.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){Re.changes.removeEventListener("change",this.onModulesChanged),this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of _e.GESTURES)document.removeEventListener(t,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&i!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&i!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&i!==e){const n=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(n)&&n>0?n:Math.min(window.devicePixelRatio||1,2))}(t===fh||t===ph||t===Sc)&&i!==e&&this.forwardPlayerAttributes(),t===Sc&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const t of[fh,ph,Sc]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.sceneRenderer.setCompassForced(t)}lookToward(t){const e=ze(this.ufoElement.sighting,this.lastTimeMs);if(t.kind==="observer"||e?.lat===void 0||e.lng===void 0||e.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:i,z:n}=ae(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(i,n)<1)return this.setLookOffset(0,0);const s=(Math.atan2(i,-n)*180/Math.PI+360)%360;this.setLookOffset(((s-e.headingDeg)%360+540)%360-180,-e.pitchDeg)}setLookOffset(t,e){this.sceneRenderer.setLookOffset(t,e),this.ufoElement.setLookOffset(t,e),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(t,e){this.sceneRenderer.setIndoorLook(t,e)}setCloudRendering(t){this.sceneRenderer.setCloudRendering(t)}setWeather(t){this.sceneRenderer.setWeather(t),this.weatherAudio.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed)}pickCloudAt(t,e){return this.sceneRenderer.pickCloudAt(t,e)}cloudDirectionAt(t,e){return this.sceneRenderer.cloudDirectionAt(t,e)}pickDecorAt(t,e){return this.sceneRenderer.pickDecorAt(t,e)}decorScreenBox(t){return this.sceneRenderer.decorScreenBox(t)}decorDrawnOffset(t){return this.sceneRenderer.decorDrawnOffset(t)}decorGroundPointAt(t,e,i,n=0){return this.sceneRenderer.decorGroundPointAt(t,e,i,n)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,i){return this.sceneRenderer.decorGrabHeightAt(t,e,i)}bodyScreenBox(t){return this.sceneRenderer.bodyScreenBox(t)}pickPlacedBodyAt(t,e){return this.sceneRenderer.pickPlacedBodyAt(t,e)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(t){const e=xd.recording(t);this.holdForNewScene(e);const i=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(t,e,i=!0){this.poster.show(t,e,i)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,t&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=t||e,this.ufoElement.controlsHeld=t||e,this.ufoElement.holdClock(t)}holdForNewScene(t){this.sceneRenderer.holdForNewScene(t)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(t){this.sceneRenderer.documentUrl=t}get sightingData(){return this.ufoElement.sightingData}set sightingData(t){const e=Qi.toCurrent(t);this.ufoElement.sightingData=e,this.requireModules(e.modules),this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?ta.expand(this.ufoElement.sighting.interpretation,WS.kinds()):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}onModulesChanged=t=>{t.detail==="skyEvents"&&this.sceneRenderer.setSkyEvents(this.skyEventsShown,!0,this.skyEventsStartDate)};requireModules(t){if(!t?.length)return;const e=this.documentUrl,i=$t(async()=>{const{ModuleSession:n}=await import("./ModuleSession-BXMnu0b2.js");return{ModuleSession:n}},[],import.meta.url).then(({ModuleSession:n})=>n.shared.require(t,e)).then(()=>this.sceneRenderer.setDecorModelProvider(new uA));this.sceneRenderer.holdUntil(i)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(t.width/e);return t.height!==i&&(t.height=i),this.seekPreview??=new pp(this,()=>document.createElement(kM))}showAt(t){this.ufoElement.currentTime=t,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(t){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const e=t.getContext("2d");return e?(e.imageSmoothingQuality="high",e.drawImage(this.sceneCanvas,0,0,t.width,t.height),!0):!1}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}directionAt(t,e){return this.sceneRenderer.directionAt(t,e)}referenceFailure(t){return this.sceneRenderer.referenceFailure(t)}applyReferenceView(t){this.sceneRenderer.setReferencesShown(t.shown);for(const e of this.ufoElement.sighting.references){const i=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:i?i.shown?i.opacity:0:t.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(t){this.liveTerrainProviders=t,this.snapshotKey=void 0,this.applySnapshots(this.ufoElement.sighting.snapshots)}liveTerrainProviders;snapshotKey="none";applySnapshots(t){const e=hh.isEmpty(t)?"none":`${JSON.stringify(t)}
8662
+ `);let s=Br.cache.get(n);return s||(s=Promise.all(i.map(r=>Br.load(r.url))).then(r=>r.reduce((a,c)=>Br.concat(a,c))),Br.cache.set(n,s)),s}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*i,e),dec:new Float32Array(t,1*i,e),mag:new Float32Array(t,2*i,e),ci:new Float32Array(t,3*i,e)}}static concat(t,e){const i=(n,s)=>{const r=new Float32Array(n.length+s.length);return r.set(n,0),r.set(s,n.length),r};return{count:t.count+e.count,ra:i(t.ra,e.ra),dec:i(t.dec,e.dec),mag:i(t.mag,e.mag),ci:i(t.ci,e.ci)}}}class si{constructor(t){if(this.heights=t,t.length!==si.WIDTH*si.HEIGHT)throw new Error(`a lunar relief has ${si.WIDTH*si.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*si.SAMPLES_PER_DEGREE;static HEIGHT=180*si.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const i=si.SAMPLES_PER_DEGREE,n=(e%360+360)%360*i-.5,s=(90-t)*i-.5,r=Math.floor(n),a=Math.floor(s),c=n-r,l=s-a,h=(f,p)=>{const m=(f%si.WIDTH+si.WIDTH)%si.WIDTH,g=Math.min(si.HEIGHT-1,Math.max(0,p));return this.heights[g*si.WIDTH+m]},u=h(r,a)*(1-c)+h(r+1,a)*c,d=h(r,a+1)*(1-c)+h(r+1,a+1)*c;return(u*(1-l)+d*l)*si.UNIT_KM}static inBand(t,e){const i=Math.PI/180,n=Math.acos(Math.cos(t*i)*Math.cos(e*i))*180/Math.PI;return n>=si.BAND_FROM_DEG&&n<=si.BAND_TO_DEG}static withBump(t,e,i,n=.4){const s=new Int8Array(si.WIDTH*si.HEIGHT),r=si.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),c=Math.floor(e*r),l=Math.floor((90-t)*r);for(let h=-a;h<=a;h++)for(let u=-a;u<=a;u++)Math.hypot(u,h)<=a&&(s[(l+h)*si.WIDTH+(c+u+si.WIDTH)%si.WIDTH]=Math.round(i/si.UNIT_KM));return new si(s)}static smooth(){return new si(new Int8Array(si.WIDTH*si.HEIGHT))}}class Qs{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,i,n=Qs.SAMPLES){const{s,u:r,w:a,distanceKm:c}=Qs.frame(t,e),l=Math.PI/180,h=new Float32Array(n),u=si.REFERENCE_RADIUS_KM;for(let d=0;d<n;d++){const f=d/n*2*Math.PI,p=Math.cos(f),m=Math.sin(f),g=p*r[0]+m*a[0],M=p*r[1]+m*a[1],v=p*r[2]+m*a[2];let x=0;for(let y=Qs.SEARCH_FROM_DEG;y<=Qs.SEARCH_TO_DEG;y+=Qs.SEARCH_STEP_DEG){const w=Math.cos(y*l),b=Math.sin(y*l),E=w*s[0]+b*g,S=w*s[1]+b*M,A=w*s[2]+b*v,_=Math.asin(Math.max(-1,Math.min(1,A)))/l,I=Math.atan2(S,E)/l,D=u+i.heightKm(_,I),P=Math.atan2(D*b,c-D*w);P>x&&(x=P)}h[d]=x/l}return{radiusDeg:h,meanRadiusDeg:Math.asin(u/c)/l}}static frame(t,e){const i=new $o(e.lat,e.lng,e.elevationM),n=Za(t),s=oM(t,i,!1),r=new Fe(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*Qs.AU_KM,c=Qs.bodyFixed(t),l=c(r),h=Math.hypot(l[0],l[1],l[2]),u=[l[0]/h,l[1]/h,l[2]/h],d=hO(t,i),f=Rv(d),p=Ya(d,new Fe(-r.x,-r.y,-r.z,n.t)),m=Math.asin(p.z/Math.hypot(p.x,p.y,p.z)),g=Math.atan2(-p.y,p.x),M=new Fe(-Math.sin(m)*Math.cos(g),Math.sin(m)*Math.sin(g),Math.cos(m),n.t),v=new Fe(-Math.sin(g),-Math.cos(g),0,n.t);return{s:u,u:c(Ya(f,M)),w:c(Ya(f,v)),distanceKm:a}}static surfacePoint(t,e,i,n){const{s,u:r,w:a}=Qs.frame(t,e),c=Math.PI/180,l=[0,1,2].map(u=>Math.cos(i*c)*r[u]+Math.sin(i*c)*a[u]),h=[0,1,2].map(u=>Math.cos(n*c)*s[u]+Math.sin(n*c)*l[u]);return{latDeg:Math.asin(h[2])/c,lonDeg:Math.atan2(h[1],h[0])/c}}static radiusAt(t,e){const i=t.radiusDeg.length,n=(e/360*i%i+i)%i,s=Math.floor(n),r=n-s;return t.radiusDeg[s]*(1-r)+t.radiusDeg[(s+1)%i]*r}static uncoveredFraction(t,e,i){const n=t.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const c=a/n*2*Math.PI,l=Math.cos(c),h=Math.sin(c),u=l*i.upDeg+h*i.rightDeg,d=u*u-s+e*e;if(d<=0)continue;const f=Math.sqrt(d),p=u+f;if(p<=0)continue;const m=Math.max(0,u-f),g=Math.max(m,t.radiusDeg[a]);p>g&&(r+=.5*(p*p-g*g))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=_O(pt.Moon,t),i=Math.PI/180,n=e.ra*15*i,s=e.dec*i,r=e.spin*i,a=(l,[h,u,d])=>[Math.cos(l)*h+Math.sin(l)*u,-Math.sin(l)*h+Math.cos(l)*u,d],c=(l,[h,u,d])=>[h,Math.cos(l)*u+Math.sin(l)*d,-Math.sin(l)*u+Math.cos(l)*d];return l=>a(r,c(Math.PI/2-s,a(Math.PI/2+n,[l.x,l.y,l.z])))}static subObserverPoint(t,e){const i=new $o(e.lat,e.lng,e.elevationM),n=Za(t),s=oM(t,i,!1),r=Qs.bodyFixed(t)(new Fe(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class $u{static cache=new Map;static load(t){let e=$u.cache.get(t);return e||(e=$u.fetchRelief(t).catch(()=>{}),$u.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let i=new Uint8Array(await e.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const n=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(n).arrayBuffer())}return new si(new Int8Array(i.buffer,i.byteOffset,i.length))}}const Hv=_r.catalog({en:()=>$t(()=>import("./PerceptionMessages_en-B2O6DR64.js"),[],import.meta.url).then(o=>o.perceptionMessages_en),fr:()=>$t(()=>import("./PerceptionMessages_fr-B59TnGBC.js"),[],import.meta.url).then(o=>o.perceptionMessages_fr),es:()=>$t(()=>import("./PerceptionMessages_es-BmkP6OqD.js"),[],import.meta.url).then(o=>o.perceptionMessages_es),it:()=>$t(()=>import("./PerceptionMessages_it-DPlxRmxu.js"),[],import.meta.url).then(o=>o.perceptionMessages_it)});class Mp{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=Mp.ID;messages=Hv;sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",kind:"choice",default:"normal",choices:[{id:"normal"},{id:"protan"},{id:"deutan"},{id:"tritan"}]},{id:"severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=Mp.MATRICES[String(t.type)];if(!e)return Cs.NONE;const i=Number(t.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:e.map((r,a)=>Cs.IDENTITY[a]+(r-Cs.IDENTITY[a])*n),contrastGain:1}}}class Gv{static ID="fatigue";id=Gv.ID;messages=Hv;sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return Cs.NONE}}class mc{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=mc.ID;messages=Hv;sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",kind:"number",default:0,min:0,max:mc.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),i=Math.max(0,Math.min(mc.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(i===0)return Cs.NONE;const n=i/mc.MEASURED_LEVEL*mc.MEASURED_LOSS_DB;return{colorMatrix:Cs.IDENTITY,contrastGain:10**(-n/20)}}}const GN=o=>o.sources[0]??o.id,VN=Re.point("perception").provide(Re.BUILT_IN,[new Mp,new mc,new Gv].map(o=>({id:o.id,name:o.id,credit:GN(o),creditUrl:"https://ufoathome.org/docs/sources/",create:()=>o})));class gc{static built=new WeakMap;static get ALL(){return VN.map(t=>{let e=gc.built.get(t);return e||(e=t.create(),gc.built.set(t,e)),e})}static byId(t){return gc.ALL.find(e=>e.id===t)}static perceptionOf(t){return gc.ALL.reduce((e,i)=>Cs.combine(e,i.perceive(t?.[i.id]??{})),Cs.NONE)}static compact(t){const e={},i=gc.ALL;for(const[n,s]of Object.entries(t))!i.some(r=>r.id===n)&&Object.keys(s??{}).length>0&&(e[n]=s);for(const n of i){const s=t[n.id]??{},r=Object.fromEntries(n.settings.filter(a=>s[a.id]!==void 0&&s[a.id]!==a.default).map(a=>[a.id,s[a.id]]));Object.keys(r).length>0&&(e[n.id]=r)}return Object.keys(e).length>0?e:void 0}}class Mc{static NONE={id:"none",name:"No filter",opticalDensity:0};static SOLAR_VISUAL={id:"solar-visual",name:"Solar filter for the eye (OD 5)",opticalDensity:5,usableWith:["eye","binoculars","telescope"]};static SOLAR_PHOTO={id:"solar-photo",name:"Solar film for a camera (OD 3.8)",opticalDensity:3.8,usableWith:["camera","dslr","phone","telescope"]};static ALL=[Mc.NONE,Mc.SOLAR_VISUAL,Mc.SOLAR_PHOTO];static usableWith(t,e){return!t.usableWith||t.usableWith.includes(e.category)}static byId(t){return Mc.ALL.find(e=>e.id===t)??Mc.NONE}static transmittance(t){return 10**-t.opticalDensity}static magnitudes(t){return 2.5*t.opticalDensity}}class NS{names;constructor(t){this.names=t??_r.blank(),this.loaded=t!==void 0}loaded;body(t){return this.names.bodies[t]??t}star(t){return this.names.stars[t.name]??t.name}comet(t){return this.names.comets[t.id]??t.name}nova(t){return this.names.novae[t.id]??t.name}satelliteClass(t){return this.names.satelliteClasses[t.id]??t.name}shower(t){return this.names.showers[t.id]??t.name}lightRig(t){return this.names.lightRigs[t.id]??t.name}instrument(t){return this.names.instruments[t.id]??t.name}decorKind(t){return this.names.decorKinds[t]}point(t){return Pc.point(t,this.loaded?this.names.compassPoints:void 0)}towards(t){return Pc.towards(t,this.loaded?this.names:void 0)}}class Vr{static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const i=t.name??Vr.kind(t,e);return t.services?.length?`${i} — ${t.services.join(", ")}`:i}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,i,n){const{line:s}=t,r=[];s.name&&r.push(Vr.kind(s,e).toLocaleLowerCase(n)),r.push(s.tracks>1?e.tracks.replace("{count}",String(s.tracks)):e.singleTrack);const a=s.voltageV?Vr.voltage(s.voltageV,n):void 0;if(t.contactM!==void 0){const c=t.contactM.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?e.overheadVoltage.replace("{voltage}",a):e.overhead).replace("{height}",c))}else s.electrification==="third_rail"?r.push(a?e.thirdRailVoltage.replace("{voltage}",a):e.thirdRail):s.electrification==="none"&&r.push(e.notElectrified);return s.gaugeMm===Vr.METRE_GAUGE_MM?r.push(e.metreGauge):s.gaugeMm!==Vr.STANDARD_GAUGE_MM&&r.push(e.gauge.replace("{mm}",s.gaugeMm.toLocaleString(n))),r.push(e.distance.replace("{distance}",i(t.distanceM))),s.services?.length?`${Vr.name(s,e)}; ${r.join(", ")}`:`${Vr.name(s,e)} — ${r.join(", ")}`}}class Ku{constructor(t,e){this.element=t,this.onChange=e,t.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(t,e,i=!0){const n=Ku.resolve(t,e);if(this.url=n,!n||!i){this.release();return}this.element.src=n,this.element.hidden=!1;const s=this.shown;this.shown=!0,s||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const i=new URL(t.trim(),e??location.href);return i.protocol!=="https:"&&i.protocol!=="http:"?void 0:i.origin===Ku.PUBLISHED_ORIGIN&&Ku.isDevelopmentHost(location.hostname)?location.origin+i.pathname:i.href}catch{return}}static PUBLISHED_ORIGIN="https://ufoathome.org";static isDevelopmentHost(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}}const WN="Global Meteor Network",XN="https://globalmeteornetwork.org/data/",YN="“Thunder” by Jerimee",$N="https://creativecommons.org/licenses/by/3.0/",KN="CC BY 3.0";class Yn{static fill(t,e){t.innerHTML="";const i=d=>t.appendChild(d),n=e.currentTerrainAttribution;n&&i(Yn.text(n));const s=e.currentRoadAttribution;s&&i(Yn.text(s));const r=e.currentWaterAttribution;r&&i(Yn.text(r));const a=e.currentRailwayAttribution;a&&i(Yn.text(a));const c=e.ufoElement.observerMapCredit;c&&!n?.includes(c)&&i(Yn.text(c));for(const d of e.decorModelCredits){const f=d.author?` — ${d.author}`:"",p=document.createElement("li");d.sourceUrl?p.append(Yn.link(d.sourceUrl,d.title),document.createTextNode(`${f} (${d.license})`)):p.textContent=`${d.title}${f} (${d.license})`,i(p)}for(const d of e.ufoElement.sighting.references){if(!d.credit)continue;const f=document.createElement("li");d.creditUrl?f.appendChild(Yn.link(d.creditUrl,d.credit)):f.textContent=d.credit,i(f)}if(e.ufoElement.sighting.traces.length>0){const d=new wr(wc.preferencesFor(e)),f=new Set(e.ufoElement.sighting.traces.map(p=>d.read(p.source)).filter(p=>!!p));for(const p of f)i(Yn.text(p))}const l=e.satelliteState;if(l.status==="ready"&&l.credit){const d=document.createElement("li");d.appendChild(Yn.link(l.creditUrl??"",l.credit)),i(d)}if(e.fireballState.status==="ready"&&e.fireballState.records.length>0){const d=document.createElement("li");d.append(Yn.link(XN,WN),document.createTextNode(" (CC BY 4.0)")),i(d)}const h=e.aircraftState;if(h.status==="ready"&&h.shown>0){const d=document.createElement("li");if(d.appendChild(Yn.link(h.creditUrl,h.credit)),i(d),h.trailCredit){const f=document.createElement("li");f.appendChild(Yn.link(h.trailCredit.creditUrl,h.trailCredit.credit)),i(f)}}const u=Yn.text(`${YN} (`);u.append(Yn.link($N,KN),document.createTextNode(")")),i(u)}static text(t){const e=document.createElement("li");return e.textContent=t,e}static link(t,e){const i=document.createElement("a");return i.href=t,i.target="_blank",i.rel="noopener",i.textContent=e,i}}const qN=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,ZN=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,LS=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,JN=20,jN=1;class rh{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}Ic.unlock(this.context)}setAmbient(t,e,i){if(this.requested={type:t,intensity:e,windSpeed:i},!this.context)return;this.paused&&(t="none",e=0,i=0);const n=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=n==="hail"?Math.min(1,e*1.3+.2):n==="rain"?e:0,n!==this.ambientKey){this.ambientKey=n;const r=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,n!=="none"&&this.startLoop(qN,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,c=>{this.ambientSource=c?.source,this.ambientGain=c?.gain,c&&(c.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/JN,1);const s=i>jN;if(s!==this.windActive){this.windActive=s;const r=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,s&&this.startLoop(ZN,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,c=>{this.windSource=c?.source,this.windGain=c?.gain,c&&(c.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(t){if(t===this.paused)return;this.paused=t;const{type:e,intensity:i,windSpeed:n}=this.requested;this.setAmbient(e,i,n)}playThunder(){!this.context||this.paused||this.playOneShot(LS,.9)}playDetonation(t){const e=this.context;if(!e||this.paused)return;const i=Math.min(1,Math.max(0,t)),n=e.createBufferSource();n.buffer=this.crackBuffer(e);const s=e.createBiquadFilter();s.type="lowpass",s.frequency.value=rh.CRACK_CUTOFF_HZ;const r=e.createGain();r.gain.value=i,n.connect(s).connect(r).connect(this.output(e)),n.start(),this.playOneShot(LS,i,rh.DETONATION_RATE)}static DETONATION_RATE=.8;static CRACK_CUTOFF_HZ=2500;static CRACK_DECAY_S=.25;crackBuffer(t){if(this.crack?.sampleRate===t.sampleRate)return this.crack;const e=Math.round(t.sampleRate*rh.CRACK_DECAY_S*6),i=t.createBuffer(1,e,t.sampleRate),n=i.getChannelData(0);for(let s=0;s<e;s++){const r=s/t.sampleRate;n[s]=(Math.random()*2-1)*Math.min(1,r/.005)*Math.exp(-r/rh.CRACK_DECAY_S)}return this.crack=i,i}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,i,n){if(e!==i()){t?.source.stop();return}n(t)}async startLoop(t,e){const i=this.context;if(i)try{const n=await this.getBuffer(t),s=i.createBufferSource();s.buffer=n,s.loop=!0;const r=i.createGain();return r.gain.value=e,s.connect(r).connect(this.output(i)),s.start(),{source:s,gain:r}}catch(n){console.warn("Weather ambient sound failed to load, staying silent:",n);return}}async playOneShot(t,e,i=1){const n=this.context;if(n)try{const s=await this.getBuffer(t),r=n.createBufferSource();r.buffer=s,r.playbackRate.value=i;const a=n.createGain();a.gain.value=e,r.connect(a).connect(this.output(n)),r.start()}catch(s){console.warn("Thunder sound failed to load:",s)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}class Oa{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:i}=t,[n,s]=this.perifocalAxes(),r=Math.sqrt(Oa.SUN_GM_AU3_PER_DAY2*(1+e)/i);this.perihelionPosition=this.scale(n,i),this.perihelionVelocity=this.scale(s,r),this.inverseSemiMajorAxis=(1-e)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,i=this.universalAnomaly(e),n=this.inverseSemiMajorAxis*i*i,s=this.elements.perihelionAu,r=1-i*i/s*Oa.stumpffC(n),a=e-i*i*i/Math.sqrt(Oa.SUN_GM_AU3_PER_DAY2)*Oa.stumpffS(n);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(t){const e=this.positionAt(t);return Math.hypot(e.x,e.y,e.z)}universalAnomaly(t){if(t===0)return 0;const e=Math.sign(t),i=Math.sqrt(Oa.SUN_GM_AU3_PER_DAY2)*Math.abs(t),n=a=>{const c=this.inverseSemiMajorAxis*a*a,l=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*l)*a*a*a*Oa.stumpffS(c)+l*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<Oa.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){const c=(r+s)/2;n(c)<i?r=c:s=c}return e*(r+s)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,n=Math.cos(t),s=Math.sin(t),r=Math.cos(e),a=Math.sin(e),c=Math.cos(i),l=Math.sin(i);return[{x:n*r-s*a*c,y:s*r+n*a*c,z:a*l},{x:-n*a-s*r*c,y:-s*a+n*r*c,z:r*l}]}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}static stumpffC(t){if(Math.abs(t)<1e-6)return 1/2-t/24+t*t/720;if(t>0)return(1-Math.cos(Math.sqrt(t)))/t;const e=Math.sqrt(-t);return(Math.cosh(e)-1)/-t}static stumpffS(t){if(Math.abs(t)<1e-6)return 1/6-t/120+t*t/5040;if(t>0){const i=Math.sqrt(t);return(i-Math.sin(i))/(i*i*i)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const bA=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class QN{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(t){const e=this.julianDayOf(t);return bA.filter(i=>Math.abs(e-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(i=>this.appearanceOf(i,t,e)).sort((i,n)=>i.magnitude-n.magnitude)[0]}static appearanceOf(t,e,i){const n=ui(e),s=this.earthPositionAt(n),r=this.apparentPositionOf(t,2451545+n.tt,s),a=this.subtract(r,s),c=this.length(r),l=this.length(a),h=this.tailEndAt(t,r,s,c,n,e,i),u=this.horizontalOf(a,n,e,i);return{apparition:t,position:u,...h,heliocentricDistanceAu:c,earthDistanceAu:l,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(t,c,l)}}static magnitudeAt(t,e,i){const n=t.absoluteMagnitude+5*Math.log10(i)+2.5*t.activityExponent*Math.log10(e);return Math.max(n,t.peakMagnitude)}static tailEndAt(t,e,i,n,s,r,a){if(t.tailLengthAu===void 0)return{};const c=1+t.tailLengthAu/n,l=this.subtract({x:e.x*c,y:e.y*c,z:e.z*c},i),h=this.subtract(e,i);return{tailEnd:this.horizontalOf(l,s,r,a),tailLengthDeg:this.angleBetween(h,l)}}static apparentPositionOf(t,e,i){const n=this.orbitOf(t);let s=n.positionAt(e);for(let r=0;r<2;r++){const a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(e-a)}return s}static horizontalOf(t,e,i,n){const s=Ya(aO(),new Fe(t.x,t.y,t.z,e)),r=Ya(jE(e),s),a=oM(e,new $o(n.lat,n.lng,n.elevationM),!0),c=new Fe(r.x-a.x,r.y-a.y,r.z-a.z,e),l=zp(c);return Cv(l.ra,l.dec,i,n)}static earthPositionAt(t){return Ya(rO(),Vo(pt.Earth,t))}static julianDayOf(t){return 2451545+ui(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const i=new Oa(t.orbit);return this.orbits.set(t.id,i),i}static subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}static length(t){return Math.hypot(t.x,t.y,t.z)}static angleBetween(t,e){const i=(t.x*e.x+t.y*e.y+t.z*e.z)/(this.length(t)*this.length(e)||1);return Math.acos(Math.min(1,Math.max(-1,i)))*180/Math.PI}}const Gg=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class kS{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return Gg.filter(i=>this.magnitudeAt(i,e)!==void 0)}static appearancesAt(t,e){const i=this.julianDayOf(t),n=[];for(const s of Gg){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:xr.ofJ2000(s.raHours,s.decDeg,t,e),magnitude:r})}return n.sort((s,r)=>s.magnitude-r.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return Gg.find(e=>e.id===t)}static magnitudeAt(t,e){const i=t.lightCurve,n=e-t.startJd;if(i.length===0||n<i[0][0]||n>i[i.length-1][0])return;let s=1;for(;s<i.length-1&&i[s][0]<n;)s++;const[r,a]=i[s-1]??i[0],[c,l]=i[s]??i[0];if(c===r)return a;const h=Math.min(1,Math.max(0,(n-r)/(c-r)));return a+h*(l-a)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const tL=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],vp=6.5;class Vg{static activeAt(t){return tL.flatMap(e=>{const i=this.nearness(e,t);return i<=0?[]:[{shower:e,zhr:e.peakZhr*i,nearness:i}]})}static nearness(t,e){const i=this.dayOfYear(e),n=this.dayOfYear(this.asDate(t.start)),s=this.dayOfYear(this.asDate(t.peak)),r=this.dayOfYear(this.asDate(t.end)),a=this.wrappedDelta(i,s),c=this.wrappedDelta(s,n),l=this.wrappedDelta(r,s);return a<0?a<-c?0:1+a/c:a>0?a>l?0:1-a/l:1}static observedRatePerHour(t,e,i,n=vp){if(e<=0)return 0;const s=vp-n;return t*Math.sin(e*Math.PI/180)/Math.pow(i,s)}static radiantPosition(t,e,i){return xr.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,i)}static dayOfYear(t){const e=Date.UTC(t.getUTCFullYear(),0,1);return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-e)/864e5)+1}static asDate(t){return new Date(Date.UTC(2001,t.month-1,t.day))}static wrappedDelta(t,e){const i=t-e;return i>182?i-365:i<-182?i+365:i}}class Vi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const i=ui(t),n=new Lp(0,UP(t).elon-90,1),s=Ya(uO(i),Dv(n,i)),r=zp(s);return Cv(r.ra,r.dec,t,e)}static observedRatePerHour(t,e=vp){const i=Vi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),n=vp-e;return(Vi.QUIET_RATE_PER_HOUR+i)/Math.pow(Vi.POPULATION_INDEX,n)}static schedule(t){const e=new Bp(t.seed^1542469173);return ir.schedule(t).map(i=>{const n=Vi.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=Vi.turnAround(n,e.between(0,360)),a={x:n.x*Math.cos(s)+r.x*Math.sin(s),y:n.y*Math.cos(s)+r.y*Math.sin(s),z:n.z*Math.cos(s)+r.z*Math.sin(s)};return{...i,radiant:Vi.toHorizontal(a),bearingDeg:Vi.bearingFrom(a,n)}})}static turnAround(t,e){const[i,n]=Vi.basisAround(t),s=e*Math.PI/180;return{x:i.x*Math.cos(s)+n.x*Math.sin(s),y:i.y*Math.cos(s)+n.y*Math.sin(s),z:i.z*Math.cos(s)+n.z*Math.sin(s)}}static bearingFrom(t,e){const[i,n]=Vi.basisAround(t),s=t.x*e.x+t.y*e.y+t.z*e.z,r=Vi.normalise({x:e.x-t.x*s,y:e.y-t.y*s,z:e.z-t.z*s});return(Math.atan2(r.x*n.x+r.y*n.y+r.z*n.z,r.x*i.x+r.y*i.y+r.z*i.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=Vi.normalise(Vi.cross(t,e));return[i,Vi.normalise(Vi.cross(t,i))]}static toHorizontal(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,t.y/e)))*180/Math.PI,azimuthDeg:(Math.atan2(t.x,-t.z)*180/Math.PI%360+360)%360}}static appearanceOf(t){const e=Vi.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Vi.turnAround(e,t.bearingDeg),n=t.fromRadiantDeg*Math.PI/180;return Vi.toHorizontal({x:e.x*Math.cos(n)+i.x*Math.sin(n),y:e.y*Math.cos(n)+i.y*Math.sin(n),z:e.z*Math.cos(n)+i.z*Math.sin(n)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180,n=Math.cos(e);return{x:n*Math.sin(i),y:Math.sin(e),z:-n*Math.cos(i)}}static cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}static normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}static TYPICAL_VELOCITY_KM_S=40}const US="https://ufoathome.org/tle/index.json";class $n{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??$n.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/tle/index.json",location.href).href),t.includes(US)||t.push(US),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${$n.FIRST_SNAPSHOT}T00:00:00Z`)-$n.MAX_ELEMENT_AGE_DAYS*$n.DAY_MS;if(t.getTime()<e)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(n=>t.getTime()>=Date.parse(n.from)-$n.MAX_ELEMENT_AGE_DAYS*$n.DAY_MS&&t.getTime()<=Date.parse(n.to)+$n.MAX_ELEMENT_AGE_DAYS*$n.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:i,base:n}=e,s=[],r=[];for(const a of Object.keys(i.kinds)){const c=await this.kindAt(a,t,i,n);s.push(...c),r.push(this.coverageOf(a,t,i,c.length>0))}return{objects:s,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(t,e,i,n){const s=e.getTime(),r=i.binDays*$n.DAY_MS,a=Math.floor(s/r),c=s-a*r<r/2?a-1:a+1,l=new Set(i.kinds[t].bins),h=[a,c].map(m=>new Date(m*r).toISOString().slice(0,10)).filter(m=>l.has(m));if(h.length===0)return[];const[u,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,n).href),...h.map(m=>this.binary(new URL(`${t}/${m}.bin`,n).href))]),f=new Map;for(const m of d)for(const g of $n.decode(m,i.recordBytes)){const M=f.get(g.norad);(!M||Math.abs(g.epochMs-s)<Math.abs(M.epochMs-s))&&f.set(g.norad,g)}const p=[];for(const m of f.values()){const g=Math.abs(m.epochMs-s)/$n.DAY_MS;if(g>$n.MAX_ELEMENT_AGE_DAYS)continue;const M=u[m.norad]??{name:String(m.norad)};M.launch&&Date.parse(`${M.launch}T00:00:00Z`)>s||p.push({norad:m.norad,name:M.name,kind:t,launch:M.launch,stdMag:M.stdMag,elements:m,ageDays:g})}return p}coverageOf(t,e,i,n){const{from:s,to:r}=i.kinds[t],a=e.getTime(),c=$n.MAX_ELEMENT_AGE_DAYS*$n.DAY_MS,l=n?"covered":a<Date.parse(s)-c?"before":a>Date.parse(r)+c?"after":"gap";return{kind:t,status:l,from:s,to:r}}static decode(t,e){const i=new DataView(t),n=[];for(let s=0;s+e<=t.byteLength;s+=e)n.push({norad:i.getUint32(s,!0),epochMs:i.getFloat64(s+4,!0),bstar:i.getFloat32(s+12,!0),inclinationDeg:i.getFloat32(s+16,!0),raanDeg:i.getFloat32(s+20,!0),eccentricity:i.getFloat32(s+24,!0),argOfPerigeeDeg:i.getFloat32(s+28,!0),meanAnomalyDeg:i.getFloat32(s+32,!0),meanMotion:i.getFloat64(s+36,!0)});return n}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;return{index:await e.json(),base:t}}catch{}})(),this.index}json(t){return this.cached(t,async e=>e.json())}binary(t){return this.cached(t,async e=>e.arrayBuffer())}cached(t,e){let i=this.files.get(t);return i||(i=this.fetchImpl(t).then(n=>{if(!n.ok)throw new Error(`${t}: ${n.status}`);return e(n)}),i.catch(()=>this.files.delete(t)),this.files.set(t,i)),i}}class eL{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const i=hi.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(e.inFrontM!==void 0){const i=hi.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?i:Math.min(this.upperM,i)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:hi.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:hi.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class Nc{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*Nc.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const i=Nc.degOver(t)/e;return i<1?1:Math.min(Nc.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Fn{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return Nc.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return Fn.visualAidGrasp(t,e.focalLengthMm);const i=e.exposureSeconds??t.exposureSeconds,n=e.fNumber??t.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return Fn.EYE;const s=e.focalLengthMm??t.frame?.focalLengthMm??Fn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=Fn.resolutionArcsec(t,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,Fn.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(t,e){const i=t.visualAid,n=Fn.EYE,s=e??t.frame?.focalLengthMm,r=i.magnification??(s!==void 0&&i.eyepieceFocalMm?s/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,n.apertureMm*r);return{apertureMm:Math.max(a,n.apertureMm),exposureSeconds:n.exposureSeconds,resolutionArcsec:n.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/n.apertureMm))}}static resolutionArcsec(t,e,i){const s=(t.detailUm??Fn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*Fn.ARCSEC_PER_RADIAN,r=1.22*Fn.WAVELENGTH_M/(i/1e3)*Fn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(t){return t/Fn.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const i=Fn.graspOf(t,e),n=Fn.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,a=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*a)}static gainFor(t,e){const i=e.fieldOfViewDeg===void 0?void 0:Xi.focalLengthMmFor(t,e.fieldOfViewDeg);return Fn.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:i,exposureSeconds:e.exposureSeconds})}}const FS=111320,Su=Math.PI/180,iL=1.02,nL=1;class qu{static of(t,e){const i=qu.sightings(t,e);if(i.length<2)return;const n=qu.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,c=Math.tan(r.widthDeg/2*Su)===0?0:Math.tan(s.widthDeg/2*Su)/Math.tan(r.widthDeg/2*Su);if(c<iL)return;const l=a/(c-1),h=hi.sizeMAt(l,s.widthDeg),u=i.map(d=>({t:d.t,m:hi.distanceMAt(h,d.widthDeg)}));return{widthM:h,distanceM:u,nearestM:Math.min(...u.map(d=>d.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===e)?.shape,s=n?.angular?.widthDeg,r=Be(t,i.t);return s===void 0||s<=0||r?.lat===void 0||r.lng===void 0?[]:[{t:i.t,widthDeg:s,lat:r.lat,lng:r.lng,sightAzimuthDeg:n?.aim?.azimuthDeg??r.headingDeg}]}).sort((i,n)=>i.t-n.t)}static baseline(t){let e;for(const i of t)for(const n of t){if(i.t>=n.t)continue;const s=qu.closedAlongSight(i,n),[r,a,c]=s>=0?[n,i,s]:[i,n,-s];c<nL||r.widthDeg<=a.widthDeg||(!e||c>e.closedM)&&(e={near:r,far:a,closedM:c})}return e}static closedAlongSight(t,e){const i=(e.lat-t.lat)*FS,n=(e.lng-t.lng)*FS*Math.cos(t.lat*Su),s=(t.sightAzimuthDeg??0)*Su;return i*Math.cos(s)+n*Math.sin(s)}}class ls{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(t){if(t.statedM!==void 0&&t.statedM>0)return{distanceM:ls.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:ls.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:ls.atLeastNearest(t.derivedM),basis:"derived"};const e=ls.largest(t.range?.minM,t.crossing?.behindM),i=ls.smallest(t.range?.maxM,t.crossing?.inFrontM),n=e===void 0?void 0:e*ls.MARGIN,s=i===void 0?void 0:i/ls.MARGIN;return n!==void 0&&s!==void 0?{distanceM:ls.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:ls.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<ls.CONVENTIONAL_M?{distanceM:ls.atLeastNearest(s),basis:"bounded"}:{distanceM:ls.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(ls.NEAREST_M,t)}static largest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.min(...e)}}class It{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=4;static DEFAULT_CRUMBLING={perS:1.2,lifeS:4,magnitudeDrop:3,dropBack:.3,spreadKmS:1,sinkKmS:.6,trainS:2.5};static DEFAULT_BURST={perS:12,lifeS:3.5,magnitudeDrop:3.5,dropBack:.5,spreadKmS:1.5,sinkKmS:.9,trainS:2};static FLARE_MAGNITUDES=.5;static shedsOf(t){return t.sheds?t.sheds:[It.DEFAULT_CRUMBLING,...It.flareBursts(t)]}static flareBursts(t){const e=t.lightCurve??[],i=[];for(let n=1;n<e.length-1;n++){const s=e[n];e[n-1].absoluteMagnitude-s.absoluteMagnitude<It.FLARE_MAGNITUDES||e[n+1].absoluteMagnitude-s.absoluteMagnitude<It.FLARE_MAGNITUDES||i.push({...It.DEFAULT_BURST,fromT:s.t-1e3,untilT:s.t+1500})}return i}static FADE_MS=1e3;static FADED_MAGNITUDE=8;static TRAIN_POINTS=8;static leadAt(t,e){const i=t.track;if(i.length<2||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-2&&i[n+1].t<e;)n++;const s=i[n],r=i[n+1],a=r.t-s.t,c=a>0?(e-s.t)/a:0,[l,h]=It.alongGreatCircle(s,r,c);return{lat:l,lng:h,heightM:(s.altitudeKm+(r.altitudeKm-s.altitudeKm)*c)*1e3}}static mayDazzle(t){const e=Math.max(1,Math.min(...t.track.map(n=>n.altitudeKm))),i=5*Math.log10(e/It.STANDARD_DISTANCE_KM);return t.fragments.some(n=>Math.min(n.absoluteMagnitude,...(n.lightCurve??[]).map(r=>r.absoluteMagnitude))+i<=It.DAZZLING_MAGNITUDE)}static detonationsOf(t,e){const i=[];for(const n of t)n.fragments.forEach((s,r)=>{const a=It.piecesOf(n).find(l=>l.id===(s.id??String(r)));if(!a)return;const c=(s.lightCurve??[]).filter((l,h,u)=>(h===0||u[h-1].absoluteMagnitude>=l.absoluteMagnitude)&&(h===u.length-1||u[h+1].absoluteMagnitude>l.absoluteMagnitude)).map(l=>({t:l.t,magnitude:l.absoluteMagnitude}));c.push({t:a.untilT,magnitude:a.magnitudeAt(a.untilT)});for(const l of c){if(l.magnitude>It.DETONATING_MAGNITUDE||l.t<a.fromT||l.t>a.untilT)continue;const h=It.pieceAt(n,a,l.t);if(!h||h.heightM>It.AUDIBLE_BELOW_KM*1e3||i.some(d=>d.flashT===l.t&&d.reentryId===n.id))continue;const u=It.seenFrom(e,h).distanceKm;i.push({reentryId:n.id,flashT:l.t,t:l.t+u/It.SOUND_KM_S*1e3,distanceKm:u,loudness:Math.min(1,(.3+(It.DETONATING_MAGNITUDE-l.magnitude)/15)*Math.min(1,30/u))})}});return i.sort((n,s)=>n.t-s.t)}static DETONATING_MAGNITUDE=-12;static AUDIBLE_BELOW_KM=50;static SOUND_KM_S=.31;static DAZZLING_MAGNITUDE=-11;static absoluteMagnitudeAt(t,e){const i=t.lightCurve;if(!i||i.length===0)return t.absoluteMagnitude;if(e<=i[0].t)return i[0].absoluteMagnitude;for(let n=1;n<i.length;n++){const s=i[n-1],r=i[n];if(e<=r.t)return s.absoluteMagnitude+(r.absoluteMagnitude-s.absoluteMagnitude)*(e-s.t)/Math.max(r.t-s.t,1)}return i[i.length-1].absoluteMagnitude}static viewsAt(t,e,i){const n=[];for(const s of t)for(const r of It.piecesOf(s)){if(e<r.fromT||e>r.untilT)continue;const a=It.pieceAt(s,r,e);if(!a)continue;const c=It.seenFrom(i,a);if(c.altitudeDeg<0)continue;const l=Math.min(It.FADE_MS,(r.untilT-r.fromT)/4),h=l>0?Math.min(1,(e-r.fromT)/l,(r.untilT-e)/l):1,u=r.magnitudeAt(e)+5*Math.log10(c.distanceKm/It.STANDARD_DISTANCE_KM),d=u+(1-h)*Math.max(0,It.FADED_MAGNITUDE-u),f=[c];for(let p=1;p<=It.TRAIN_POINTS;p++){const m=Math.min(r.trainMs*p/It.TRAIN_POINTS,e-r.fromT),g=It.pieceAt(s,r,e-m);if(!g||(f.push(It.seenFrom(i,g)),m>=e-r.fromT))break}n.push({reentryId:s.id,fragmentId:r.id,head:c,magnitude:d,fade:h,color:r.color,train:f})}return n}static piecesOf(t){const e=It.pieces.get(t);if(e)return e;const i=t.track[0]?.t??0,n=t.track[t.track.length-1]?.t??0,s=[];return t.fragments.forEach((r,a)=>{const c=(r.lagS??0)*1e3,l={id:r.id??String(a),fromT:r.fromT??i,untilT:r.untilT??n,lagMsAt:()=>c,acrossKmAt:()=>0,belowKmAt:()=>0,magnitudeAt:h=>It.absoluteMagnitudeAt(r,h),color:r.color??It.DEFAULT_COLOR,trainMs:(r.trainS??It.DEFAULT_TRAIN_S)*1e3};s.push(l),It.shedsOf(r).forEach((h,u)=>s.push(...It.shedPieces(l,h,u)))}),It.pieces.set(t,s),s}static pieces=new WeakMap;static shedPieces(t,e,i=0){const n=e.fromT??t.fromT,s=Math.min(e.untilT??t.untilT,t.untilT);if(!(e.perS>0)||s<=n)return[];const r=Math.floor((s-n)/1e3*e.perS),a=e.spreadKmS??.3,c=e.sinkKmS??.3,l=e.trainS!==void 0?e.trainS*1e3:t.trainMs*(2/3),h=[];for(let u=0;u<r;u++){const d=E=>It.hash(`${t.id}/${i}/${u}/${E}`),f=n+(u+d(1))/e.perS*1e3,p=e.lifeS*(.4+1.2*d(2))*1e3,m=e.magnitudeDrop*(.5-.5*Math.log(1-.999*d(3))),g=e.dropBack*(.5+d(4)),M=a*(2*d(5)-1),v=c*(.5+d(6)),x=t.lagMsAt(f),y=t.acrossKmAt(f),w=t.belowKmAt(f),b=E=>Math.max(0,E-f)/1e3;h.push({id:`${t.id}.${i}.${u}`,fromT:f,untilT:Math.min(f+p,It.endOf(t)),lagMsAt:E=>x+1e3*It.lagOfBraking(2*g,b(E)),acrossKmAt:E=>y+M*b(E),belowKmAt:E=>w+v*b(E),magnitudeAt:E=>t.magnitudeAt(Math.min(E,t.untilT))+m,color:t.color,trainMs:l})}return h}static lagOfBraking(t,e){return t<=0||e<=0?0:e-(1-Math.exp(-t*e))/t}static endOf(t){return t.untilT}static hash(t){let e=2166136261;for(let i=0;i<t.length;i++)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return(e>>>0)/4294967296}static pieceAt(t,e,i){const n=i-e.lagMsAt(i),s=It.leadAt(t,n);if(!s)return;const r=e.acrossKmAt(i),a=s.heightM-e.belowKmAt(i)*1e3;if(r===0)return{...s,heightM:a};const c=It.leadAt(t,n-1e3)??s;return{...It.across(c,s,r),heightM:a}}static across(t,e,i){const n=It.DEG,s=t.lat*n,r=e.lat*n,a=(e.lng-t.lng)*n,c=Math.atan2(Math.sin(a)*Math.cos(r),Math.cos(s)*Math.sin(r)-Math.sin(s)*Math.cos(r)*Math.cos(a))+Math.PI/2,l=i/6371,h=Math.asin(Math.sin(r)*Math.cos(l)+Math.cos(r)*Math.sin(l)*Math.cos(c)),u=e.lng*n+Math.atan2(Math.sin(c)*Math.sin(l)*Math.cos(r),Math.cos(l)-Math.sin(r)*Math.sin(h));return{lat:h/n,lng:u/n}}static seenFrom(t,e){const i=It.ecef(t),n=It.ecef(e),s=n[0]-i[0],r=n[1]-i[1],a=n[2]-i[2],c=t.lat*It.DEG,l=t.lng*It.DEG,h=-Math.sin(l)*s+Math.cos(l)*r,u=-Math.sin(c)*Math.cos(l)*s-Math.sin(c)*Math.sin(l)*r+Math.cos(c)*a,d=Math.cos(c)*Math.cos(l)*s+Math.cos(c)*Math.sin(l)*r+Math.sin(c)*a,f=Math.hypot(h,u,d);return{altitudeDeg:Math.asin(d/f)/It.DEG,azimuthDeg:(Math.atan2(h,u)/It.DEG+360)%360,distanceKm:f/1e3}}static ecef(t){const e=t.lat*It.DEG,i=t.lng*It.DEG,n=Math.sin(e),s=It.A/Math.sqrt(1-It.E2*n*n);return[(s+t.heightM)*Math.cos(e)*Math.cos(i),(s+t.heightM)*Math.cos(e)*Math.sin(i),(s*(1-It.E2)+t.heightM)*n]}static alongGreatCircle(t,e,i){const n=h=>{const u=h.lat*It.DEG,d=h.lng*It.DEG;return[Math.cos(u)*Math.cos(d),Math.cos(u)*Math.sin(d),Math.sin(u)]},s=n(t),r=n(e),a=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),c=Math.acos(a);let l;if(c<1e-12)l=s;else{const h=Math.sin((1-i)*c)/Math.sin(c),u=Math.sin(i*c)/Math.sin(c);l=[s[0]*h+r[0]*u,s[1]*h+r[1]*u,s[2]*h+r[2]*u]}return[Math.atan2(l[2],Math.hypot(l[0],l[1]))/It.DEG,Math.atan2(l[1],l[0])/It.DEG]}}class ah{static typed=new Map;static of(t){return ah.typed.get(t)}static set(t,e){const i=e.trim();i===""?ah.typed.delete(t):ah.typed.set(t,i)}static forget(){ah.typed.clear()}}class Vv{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=Vv.FIRST_DAY}}class zS{constructor(t,e,i){this.citation=t,this.covers=e,this.load=i}loading;mayCover(t){return this.covers(t)}async between(t,e,i,n){try{return await(await this.provider()).between(t,e,i,n)}catch{return{status:"failed"}}}async describe(t,e){try{return await(await this.provider()).describe?.(t,e)}catch{return}}provider(){if(!this.loading){const t=this.load();this.loading=t,t.catch(()=>{this.loading===t&&(this.loading=void 0)})}return this.loading}}const sL="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",rL="Aircraft positions: Flightradar24 API (https://fr24api.flightradar24.com/)",BS="flightradar24",aL=Re.point("aircraft").provide(Re.BUILT_IN,[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new zS(sL,o=>Vv.mayCover(o),async()=>new(await $t(async()=>{const{AdsbLolArchiveProvider:o}=await import("./AdsbLolArchiveProvider-C0eoxzdX.js");return{AdsbLolArchiveProvider:o}},[],import.meta.url)).AdsbLolArchiveProvider)},{id:BS,name:"Flightradar24",credit:"Flightradar24, on your own subscription",creditUrl:"https://fr24api.flightradar24.com/",keyUrl:"https://fr24api.flightradar24.com/key-management",create:()=>new zS(rL,o=>o>=Date.UTC(2016,4,11)&&o<=Date.now(),async()=>new(await $t(async()=>{const{Flightradar24Provider:o}=await import("./Flightradar24Provider-mKDmwMzz.js");return{Flightradar24Provider:o}},[],import.meta.url)).Flightradar24Provider({token:()=>ah.of(BS)}))}]);class Dn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,i){const n=Dn.positionAt(t,i);if(!n)return;const s=It.seenFrom(e,n.geo);if(!(s.altitudeDeg<0))return{track:t,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:Dn.angularRate(t,e,i)}}static viewsAt(t,e,i){return t.flatMap(n=>Dn.seenFrom(n,e,i)??[])}static groundDistanceKm(t,e){const i=Math.PI/180,n=Math.sin((e.lat-t.lat)*i/2)**2+Math.cos(t.lat*i)*Math.cos(e.lat*i)*Math.sin((e.lng-t.lng)*i/2)**2;return 2*Dn.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const i=t.points;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=e;)n++;const s=i[n],r=i[n+1]??s,a=r.t-s.t;if(a>Dn.MAX_GAP_S*1e3)return;const c=a>0?(e-s.t)/a:0,l=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*c,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*c,lng:Dn.wrapLongitude(s.lng+h*c),heightM:l*Dn.FT_TO_M},altitudeFt:l,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(t,e,i){const n=Dn.positionAt(t,i-500),s=Dn.positionAt(t,i+500);if(!n||!s)return;const r=Dn.unit(It.seenFrom(e,n.geo)),a=Dn.unit(It.seenFrom(e,s.geo)),c=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(c)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(i),Math.cos(e)*Math.cos(i),Math.sin(e)]}}const HS="https://ufoathome.org/fireballs/index.json";class Qr{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Qr.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/fireballs/index.json",location.href).href),t.includes(HS)||t.push(HS),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=Qr.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!Qr.mayCover(e))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...n].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...n].filter(r=>i.index.months.includes(r)).map(r=>this.monthOf(r,i.base)))).flat().filter(r=>r.t>=t&&r.t<=e):void 0}static seenFrom(t,e){const i=Qr.peakFraction(t),n={lat:t.from[0]+(t.to[0]-t.from[0])*i,lng:t.from[1]+(t.to[1]-t.from[1])*i,heightM:t.peakHeightKm*1e3},s=It.seenFrom(e,n);if(!(s.altitudeDeg<0))return{record:t,peak:s,magnitude:t.peakMagnitude+5*Math.log10(s.distanceKm/It.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const i=t.t-e,n=i+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:i,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:n,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:Qr.COLOR,trainS:Qr.TRAIN_S}]}}static peakFraction(t){const e=t.from[2]-t.to[2];return Math.abs(e)<1e-6?.5:Math.min(1,Math.max(0,(t.from[2]-t.peakHeightKm)/e))}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(e.ok)return{index:await e.json(),base:t}}catch{}})(),this.index}monthOf(t,e){let i=this.months.get(t);return i||(i=this.fetchImpl(new URL(`${t}.json`,e).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(t,i)),i}}const Ll=Math.PI/180,bu=180/Math.PI;class _i{constructor(t,e){this.timeline=t,this.tolerance=e}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;static lawsOf(t,e){return{direction(i,n,s){const r=t.law({kind:"heading",value:i.azimuthDeg},e),a=Math.abs(((n.azimuthDeg-i.azimuthDeg)%360+540)%360-180),c=t.law({kind:"elevation",value:i.altitudeDeg},e),l=Math.max(_i.DIRECTION_TOLERANCE_DEG,s);return a>(r.high??i.azimuthDeg)-i.azimuthDeg+l||n.altitudeDeg>(c.high??i.altitudeDeg)+l||n.altitudeDeg<(c.low??i.altitudeDeg)-l},size(i,n){const s=t.law({kind:"angularSize",value:i},e);return n<(s.low??i)/_i.SIZE_TOLERANCE||n>(s.high??i)*_i.SIZE_TOLERANCE}}}at(t,e,i,n){const s=[];for(const r of e){const a=_i.projectionOf(r,i,n?.(r));if(a)for(const c of r.explains){const l=this.timeline.getInterpolatedShapeAt(t,c);!l||l.transparency>=1||s.push({..._i.compare(c,r.id,{aim:l.aim,angular:l.angular},a,this.tolerance),title:l.title})}}return s}static compare(t,e,i,n,s){const r=[],a=i.aim?_i.separationDeg(i.aim,n.aim):void 0;if(a!==void 0){const u=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;(s?s.direction(i.aim,n.aim,u):a>Math.max(_i.DIRECTION_TOLERANCE_DEG,u))&&r.push("direction")}const c=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,l=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0,h=(u,d)=>s?s.size(d,d*u):!_i.withinSize(u);return c!==void 0&&h(c,i.angular.widthDeg)&&r.push("width"),l!==void 0&&h(l,i.angular.heightDeg)&&r.push("height"),{sourceId:t,bodyId:e,stated:i,predicted:n,separationDeg:a,widthRatio:c,heightRatio:l,disagreements:r}}static projectionOf(t,e,i){const n=i&&i.length>0?i:_i.outlineOf(t),s=i&&i.length>0?_i.centreOf(i):t,r=_i.normalized({eastM:s.eastM-e.eastM,northM:s.northM-e.northM,upM:s.upM-e.upM});if(!r)return;const a=_i.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},c=_i.cross(a,r);let l=1/0,h=-1/0,u=1/0,d=-1/0;for(const f of n){const p={eastM:f.eastM-e.eastM,northM:f.northM-e.northM,upM:f.upM-e.upM},m=_i.dot(p,r);if(m<=0)return;const g=Math.atan2(_i.dot(p,a),m),M=Math.atan2(_i.dot(p,c),m);l=Math.min(l,g),h=Math.max(h,g),u=Math.min(u,M),d=Math.max(d,M)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*bu+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*bu},angular:{widthDeg:(h-l)*bu,heightDeg:(d-u)*bu}}}static centreOf(t){const e=i=>(Math.min(...t.map(n=>n[i]))+Math.max(...t.map(n=>n[i])))/2;return{eastM:e("eastM"),northM:e("northM"),upM:e("upM")}}static separationDeg(t,e){const i=t.altitudeDeg*Ll,n=e.altitudeDeg*Ll,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((t.azimuthDeg-e.azimuthDeg)*Ll);return Math.acos(Math.max(-1,Math.min(1,s)))*bu}static withinSize(t){return t<=_i.SIZE_TOLERANCE&&t>=1/_i.SIZE_TOLERANCE}static outlineOf(t){const e=t.sizeM.widthM/2,i=t.sizeM.lengthM/2,n=t.sizeM.heightM/2,s=[],r=t.model.url===void 0?t.model.id:void 0;if(r!==void 0&&r!=="box"&&dA.includes(r))for(let u=0;u<=_i.RINGS;u++){const d=u/_i.RINGS*Math.PI;for(let f=0;f<_i.SEGMENTS;f++){const p=f/_i.SEGMENTS*2*Math.PI;s.push([e*Math.sin(d)*Math.cos(p),i*Math.sin(d)*Math.sin(p),n*Math.cos(d)])}}else for(const u of[-e,e])for(const d of[-i,i])for(const f of[-n,n])s.push([u,d,f]);const c=t.attitude.headingDeg*Ll,l=t.attitude.pitchDeg*Ll,h=t.attitude.rollDeg*Ll;return s.map(([u,d,f])=>{const p=u*Math.cos(h)+f*Math.sin(h),m=-u*Math.sin(h)+f*Math.cos(h),g=d*Math.cos(l)-m*Math.sin(l),M=d*Math.sin(l)+m*Math.cos(l);return{eastM:t.eastM+p*Math.cos(c)+g*Math.sin(c),northM:t.northM-p*Math.sin(c)+g*Math.cos(c),upM:t.upM+M}})}static dot(t,e){return t.eastM*e.eastM+t.northM*e.northM+t.upM*e.upM}static cross(t,e){return{eastM:t.northM*e.upM-t.upM*e.northM,northM:t.upM*e.eastM-t.eastM*e.upM,upM:t.eastM*e.northM-t.northM*e.eastM}}static normalized(t){const e=Math.hypot(t.eastM,t.northM,t.upM);return e>1e-9?{eastM:t.eastM/e,northM:t.northM/e,upM:t.upM/e}:void 0}}class ta{static built=new WeakMap;static of(t){let e=ta.built.get(t);return e||(e=t.create(),ta.built.set(t,e)),e}static itemsOf(t,e){const i=t?.[e];return Array.isArray(i)?i:[]}static computes(t,e){return e.some(i=>ta.itemsOf(t,i.key).length>0)}static expand(t,e){if(!t||!ta.computes(t,e))return t;const i=e.flatMap(n=>ta.itemsOf(t,n.key).flatMap(s=>n.bodiesOf(s)));return{...t,bodies:[...t.bodies,...i]}}static computedPart(t,e){const i={};for(const n of e){const s=ta.itemsOf(t,n.key);s.length>0&&(i[n.key]=[...s])}return i}static saysNothing(t,e){return t.bodies.length===0&&t.title===void 0&&t.smoke===void 0&&e.every(i=>t[i.key]===void 0)}}const oL=_r.catalog({en:()=>$t(()=>import("./FlareKindMessages_en-BroHgiwr.js"),[],import.meta.url).then(o=>o.flareKindMessages_en),fr:()=>$t(()=>import("./FlareKindMessages_fr-Dy5SlSna.js"),[],import.meta.url).then(o=>o.flareKindMessages_fr),es:()=>$t(()=>import("./FlareKindMessages_es-SraQyQ3Y.js"),[],import.meta.url).then(o=>o.flareKindMessages_es),it:()=>$t(()=>import("./FlareKindMessages_it-CF39wmrC.js"),[],import.meta.url).then(o=>o.flareKindMessages_it)});class ws{static MJU_7={massKg:.37,burnedKg:.26,dragAreaM2:1.2*.0508*.2032,ejectionMS:30,burnS:4.5,luminousIntensityCd:2e4,flameSizeM:1.5,color:"#ffd9a0"};static SAMPLE_MS=100;static STEP_S=.002;static G=9.81;static expand(t){const e=t?.flares;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>ws.bodiesOf(i))]}}static bodiesOf(t){const e={...ws.MJU_7,...t.flare},i=[],n=t.aircraft;if(n.model||n.sound){const s=t.releases.map(h=>h.t),r=Math.min(n.t,...s)-12e4,a=Math.max(n.t,...s)+12e4,c=n.model?{color:"#30333a",albedo:.15}:{transparency:1},l=h=>{const u=ws.aircraftAt(n,h);return{t:h,eastM:u.x,northM:u.y,altitudeM:u.z,attitude:{headingDeg:n.headingDeg},sizeM:n.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:c}};i.push({id:`${t.id}-aircraft`,title:t.title,model:n.model??{id:"sphere"},track:[l(r),l(a)],sound:n.sound})}return n.glow&&i.push(ws.glowBody(t,n.glow)),t.releases.forEach((s,r)=>i.push(ws.flareBody(t,e,s,r))),i}static aircraftAt(t,e){const i=t.headingDeg*Math.PI/180,n=(e-t.t)/1e3*t.speedMS;return{x:t.eastM+Math.sin(i)*n,y:t.northM+Math.cos(i)*n,z:t.altitudeM}}static burnShare(t,e){if(e<0||e>=t.burnS)return 0;if(e<.2)return e/.2;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static trajectory(t,e,i,n=ws.SAMPLE_MS){const s=t.aircraft,r=s.headingDeg*Math.PI/180,c={...ws.aircraftAt(s,i),vx:Math.sin(r)*s.speedMS,vy:Math.cos(r)*s.speedMS,vz:-e.ejectionMS},l=(t.wind?.towardDeg??0)*Math.PI/180,h=t.wind?.speedMS??0,u=Math.sin(l)*h,d=Math.cos(l)*h,f=s.originElevationM??1e3,p=[{t:i,x:c.x,y:c.y,z:c.z}],m=ws.STEP_S,g=Math.round(n/1e3/m),M=Math.ceil(e.burnS/m);for(let v=1;v<=M;v++){const x=v*m,y=e.massKg-e.burnedKg*Math.min(1,x/e.burnS),w=1.225*Math.exp(-(c.z+f)/8500),b=c.vx-u,E=c.vy-d,S=c.vz,A=Math.hypot(b,E,S),_=.5*w*e.dragAreaM2*A/y;c.vx=(c.vx+_*m*u)/(1+_*m),c.vy=(c.vy+_*m*d)/(1+_*m),c.vz=(c.vz-ws.G*m)/(1+_*m),c.x+=c.vx*m,c.y+=c.vy*m,c.z+=c.vz*m,(v%g===0||v===M)&&p.push({t:i+Math.round(x*1e3),x:c.x,y:c.y,z:c.z})}return p}static glowBody(t,e){const i=e.sizeM/2,n=e.luminousIntensityCd/(Math.PI*i*i),s=[{t:e.fromT,lit:!0}];if(e.onS&&e.offS)for(let l=e.fromT,h=!0;l<e.untilT;h=!h)l+=(h?e.onS:e.offS)*1e3,l<e.untilT&&s.push({t:l,lit:!h});const r=(l,h)=>{const u=ws.aircraftAt(t.aircraft,l);return{t:l,eastM:u.x,northM:u.y,altitudeM:u.z,appearance:{color:e.color,luminanceCdM2:h?n:0}}},a=[];s.forEach(({t:l,lit:h},u)=>{u>0&&a.push(r(l-1,!h)),a.push(r(l,h))}),a[0]={...a[0],sizeM:{widthM:e.sizeM,lengthM:e.sizeM,heightM:e.sizeM},present:!0};const c=s[s.length-1];return a.push(r(e.untilT,c.lit),{t:e.untilT+1,present:!1}),{id:`${t.id}-glow`,title:t.title,explains:e.explains,model:{id:"sphere"},track:a}}static flareBody(t,e,i,n){const s=e.flameSizeM,r=s/2,a=e.luminousIntensityCd/(Math.PI*r*r),c=ws.trajectory(t,e,i.t),l=c.map((h,u)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...u===0?{sizeM:{widthM:s,lengthM:s,heightM:s},present:!0}:{},appearance:{color:e.color,luminanceCdM2:a*ws.burnShare(e,(h.t-i.t)/1e3),...u===0?{haloScale:1}:{}}}));return l.push({t:c[c.length-1].t+1,present:!1}),{id:`${t.id}-flare-${n+1}`,title:t.title,explains:i.explains,model:{id:"sphere"},track:l}}}const GS={key:"flares",messages:oL,bodiesOf:o=>ws.bodiesOf(o)},cL=_r.catalog({en:()=>$t(()=>import("./LanternKindMessages_en-fUfoRYC0.js"),[],import.meta.url).then(o=>o.lanternKindMessages_en),fr:()=>$t(()=>import("./LanternKindMessages_fr-CDem7PTY.js"),[],import.meta.url).then(o=>o.lanternKindMessages_fr),es:()=>$t(()=>import("./LanternKindMessages_es-Chyc607D.js"),[],import.meta.url).then(o=>o.lanternKindMessages_es),it:()=>$t(()=>import("./LanternKindMessages_it-yOojym1u.js"),[],import.meta.url).then(o=>o.lanternKindMessages_it)});class De{static COMMON={envelopeVolumeM3:.19,massKg:.065,fuelKg:.03,burnS:600,insideExcessK:150,dragAreaM2:.25,luminousIntensityCd:10,widthM:.6,heightM:1,color:"#ff8a24",shape:"classic",paperColor:"#ffffff"};static FLAME_CDM2=5e3;static TITLE={en:"Sky lantern",fr:"Lanterne céleste",es:"Farolillo volador",it:"Lanterna volante"};static FLICKER=.15;static INSIDE_SHARE=2;static PAPER_FULL_CDM2=De.COMMON.luminousIntensityCd/(Math.PI*De.COMMON.widthM/2*De.COMMON.heightM/2);static SAMPLE_MS=1e3;static STEP_S=.05;static COOLING_S=20;static TURBULENCE={horizontalMS:.8,verticalMS:.3,timescaleS:30};static G=9.81;static R_AIR=287.05;static LAPSE=.0065;static expand(t){const e=t?.lanterns;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>De.bodiesOf(i))]}}static bodiesOf(t){return De.releasesOf(t).map((e,i)=>De.lanternBody(t,e,i))}static releasesOf(t){const e=[...t.releases??[]],i=t.group;if(!i||!(i.count>0))return e;const n=De.randomFrom(i.seed??1),s=c=>c.min+(c.max-c.min)*n(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let c=0;c<i.count;c++){const l=i.fromT+r*c+(n()-.5)*r,h=a*Math.sqrt(n()),u=2*Math.PI*n();e.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,l))),explains:i.explains,eastM:Math.round(h*Math.sin(u)*10)/10,northM:Math.round(h*Math.cos(u)*10)/10,burnedS:i.burnedS,seed:Math.floor(n()*4294967296),lantern:{burnS:Math.round(s(i.burnS??{min:480,max:900})),insideExcessK:Math.round(s(i.insideExcessK??{min:125,max:175}))}})}return e}static randomFrom(t){let e=t>>>0;return()=>{e=e+1831565813>>>0;let i=e;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}static typeOf(t,e){return{...De.COMMON,...t.lantern,...e.lantern}}static heatShare(t,e){if(e<0||e>=t.burnS)return 0;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static windAt(t,e){const i=De.componentsOf(t.wind),n=t.windAloft;if(!n)return i;const s=De.componentsOf(n),r=Math.max(0,Math.min(1,e/n.atM));return{x:i.x+(s.x-i.x)*r,y:i.y+(s.y-i.y)*r}}static trajectory(t,e,i=De.SAMPLE_MS){const n=De.typeOf(t,e),s=t.site,r=s.altitudeM??0,a=Math.max(0,e.burnedS??0),c=s.originElevationM??0,l=(t.airTemperatureC??10)+273.15,h={x:s.eastM+(e.eastM??0),y:s.northM+(e.northM??0),z:e.altitudeM??r,vx:0,vy:0,vz:0,excessK:n.insideExcessK*De.heatShare(n,a)},u=De.STEP_S,d=Math.max(1,Math.round(i/1e3/u)),f=Math.ceil(Math.max(0,n.burnS-a)/u),p=[{t:e.t,x:h.x,y:h.y,z:h.z,light:De.heatShare(n,a),tiltDeg:0,tiltTowardDeg:0}],m=De.gusts(t.turbulence??De.TURBULENCE,De.seedOf(e),u);for(let g=1;g<=f;g++){const M=g*u,v=a+M,x=De.heatShare(n,v);h.excessK+=(n.insideExcessK*x-h.excessK)*Math.min(1,u/De.COOLING_S);const y=h.z-r,w=l-De.LAPSE*Math.max(0,y),b=101325*Math.exp(-(h.z+c)/8400),E=b/(De.R_AIR*w),S=b/(De.R_AIR*(w+h.excessK)),A=n.massKg-n.fuelKg*Math.min(1,v/n.burnS),_=(E-S)*n.envelopeVolumeM3*De.G,I=A+S*n.envelopeVolumeM3+.5*E*n.envelopeVolumeM3,D=De.windAt(t,y),P=m(),L={x:D.x+P.x,y:D.y+P.y,z:P.z},O=h.vx-L.x,k=h.vy-L.y,H=h.vz-L.z,W=.5*E*n.dragAreaM2*Math.hypot(O,k,H)/I;h.vx=(h.vx+W*u*L.x)/(1+W*u),h.vy=(h.vy+W*u*L.y)/(1+W*u),h.vz=(h.vz+W*u*L.z+(_-A*De.G)/I*u)/(1+W*u);const Q=h.z<=r&&h.vz<=0;if(Q&&(h.vx=0,h.vy=0,h.vz=0),h.x+=h.vx*u,h.y+=h.vy*u,h.z=Math.max(r,h.z+h.vz*u),g%d===0||g===f){const q=L.x-h.vx,nt=L.y-h.vy,at=.5*E*n.dragAreaM2*Math.hypot(q,nt,L.z-h.vz)*Math.hypot(q,nt);p.push({t:e.t+Math.round(M*1e3),x:h.x,y:h.y,z:h.z,light:x,tiltDeg:Q?0:Math.atan2(at,A*De.G)*180/Math.PI,tiltTowardDeg:(Math.atan2(q,nt)*180/Math.PI+360)%360})}}return p}static seedOf(t){return t.seed!==void 0?t.seed:Math.round(t.t)*2654435761+Math.round((t.eastM??0)*100)*40503+Math.round((t.northM??0)*100)>>>0}static gusts(t,e,i){const n=De.randomFrom(e),s=()=>Math.sqrt(-2*Math.log(Math.max(1e-12,n())))*Math.cos(2*Math.PI*n()),r=t.timescaleS>0?Math.exp(-i/t.timescaleS):0,a=Math.sqrt(1-r*r),c={x:t.horizontalMS*s(),y:t.horizontalMS*s(),z:t.verticalMS*s()};return()=>(c.x=r*c.x+a*t.horizontalMS*s(),c.y=r*c.y+a*t.horizontalMS*s(),c.z=r*c.z+a*t.verticalMS*s(),c)}static componentsOf(t){if(!t)return{x:0,y:0};const e=t.towardDeg*Math.PI/180;return{x:Math.sin(e)*t.speedMS,y:Math.cos(e)*t.speedMS}}static lanternBody(t,e,i){const n=De.typeOf(t,e),s=n.luminousIntensityCd/(Math.PI*n.widthM/2*n.heightM/2),r=De.trajectory(t,e),a={widthM:n.widthM,lengthM:n.widthM,heightM:n.heightM},c=De.through(n.color,n.paperColor),l=r.map((h,u)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...u===0?{sizeM:a,present:!0}:{},attitude:{headingDeg:Math.round(h.tiltTowardDeg),pitchDeg:-Math.round(h.tiltDeg*10)/10},appearance:{color:c,luminanceCdM2:s*h.light,...u===0?{albedo:.6,haloScale:1}:{}},lights:De.lightsOf(s*h.light)}));return l.push({t:r[r.length-1].t+1,present:!1}),{id:`${t.id}-lantern-${i+1}`,title:De.TITLE,explains:e.explains,model:{id:`ufoathome-sky-lantern-${n.shape}`},modelParameters:{paperColor:n.paperColor},flicker:De.FLICKER,altitudeFrom:{eastM:r[0].x,northM:r[0].y},track:l}}static lightsOf(t){return{paper:t,"paper-inside":t*De.INSIDE_SHARE,flame:t>0?De.FLAME_CDM2*t/De.PAPER_FULL_CDM2:0}}static through(t,e){const i=c=>[1,3,5].map(l=>parseInt(c.slice(l,l+2),16)/255),n=i(t),s=i(e),r=n.map((c,l)=>c*s[l]),a=Math.max(...n)/(Math.max(...r)||1);return"#"+r.map(c=>Math.round(Math.min(1,c*a)*255).toString(16).padStart(2,"0")).join("")}}const VS={key:"lanterns",messages:cL,bodiesOf:o=>De.bodiesOf(o),editor:()=>$t(async()=>{const{LanternEditor:o}=await import("./LanternEditor-CcBPfbIH.js");return{LanternEditor:o}},__vite__mapDeps([11,3]),import.meta.url).then(({LanternEditor:o})=>(t,e,i)=>new o(t,e,i))},lL=Re.point("interpretations").provide(Re.BUILT_IN,[{id:GS.key,name:"Decoy flares",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>GS},{id:VS.key,name:"Sky lanterns",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>VS}]);class WS{static kinds(){return lL.map(t=>ta.of(t))}}Eb();const hL="satellites-change",uL="fireballs-change",dL="references-change",fL="aircraft-change",pL="rr0-confrontation",XS="comet:",YS="nova:",mL=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,gL=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,ML=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,vL=-18,yL={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},m0={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class _e extends HTMLElement{creditsButton;set ownCredits(t){this.creditsButton.hidden=!t}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",fh,ph,Sc]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;flightMark;markedFlight;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new R;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new $n;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Qr;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=aL[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return _e.trafficRuntimeLoading??=$t(()=>import("./trafficRuntime-cS8H9PlA.js"),__vite__mapDeps([12,10]),import.meta.url).then(t=>_e.trafficRuntime=t),_e.trafficRuntimeLoading.catch(()=>{_e.trafficRuntimeLoading=void 0}),_e.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new rh;vehicleAudio=new e_;aircraftAudio;vehicleHearing=new k0;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=t=>{if(this.lastHover={clientX:t.clientX,clientY:t.clientY,altKey:t.altKey},this.ghostMissedSinceMs=void 0,this.hoverFrame!==void 0&&t.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=t.altKey,this.hoverAt(this.lastHover),this.hoverFrame===void 0&&(this.hoverFrame=requestAnimationFrame(()=>{this.hoverFrame=void 0,this.hoverPending&&this.lastHover&&this.hoverAt(this.lastHover),this.hoverPending=!1}))};ghostMissedSinceMs;static GHOST_KEPT_MS=600;ghostStillUnder(t,e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return!0;const n=(t.clientX-i.left)/i.width*2-1,s=1-(t.clientY-i.top)/i.height*2;return this.sceneRenderer.ghostsReadableAt(n,s)?this.sceneRenderer.pickGhostAt(n,s)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=e,e-this.ghostMissedSinceMs>_e.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;hoverAt(t){if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,i=e.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(t.clientX-i.left)/i.width*e.width,s=(t.clientY-i.top)/i.height*e.height;if(this.ufoElement.hasVisibleShapeAt(n,s)){this.hoverTooltip.hidden=!0;return}const r=(t.clientX-i.left)/i.width*2-1,a=-((t.clientY-i.top)/i.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(r,a))return;const c=this.pickAt(r,a,!0,t.altKey);c?this.showHoverTooltip(t,t.altKey&&c.detail?c.detail():c.name):this.hoverTooltip.hidden=!0,this.showGhostPath(c?.path,i)}showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),n=d=>({x:e.left-i.left+(d.x+1)/2*e.width,y:e.top-i.top+(1-d.y)/2*e.height}),s=n(t.from),r=n(t.to),a=n({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[c,l,h,u]=Array.from(this.ghostPath.children);for(const d of[c,l])d.setAttribute("x1",String(s.x)),d.setAttribute("y1",String(s.y)),d.setAttribute("x2",String(r.x)),d.setAttribute("y2",String(r.y));h.setAttribute("cx",String(a.x)),h.setAttribute("cy",String(a.y)),u.setAttribute("cx",String(r.x)),u.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,i=!0,n=!1){const s=this.naming,r=s.names;if(n&&this.sceneRenderer.pickDropAt(t,e)){const b=r.ghostTooltip,E=b.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:E,detail:()=>b.dropDetail.replace("{name}",E)}}const a=this.sceneRenderer.pickBodyAt(t,e);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const c=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,l=c?this.interpretationShown?.bodies.find(b=>b.id===c):void 0,h=l?this.said.read(l.title)||(l.model.id==="figure"?s.decorKind("entity"):void 0):void 0;if(c!==void 0&&h)return{kind:"body",id:c,name:h};const u=this.skyEventPickAt(t,e,(b,E)=>!E.inSky);if(u)return u;const d=i?this.ghostPick(t,e):void 0;if(d)return d;if(this.sceneRenderer.pickAfterimageAt(t,e)){const b=this.naming.names.afterimageTooltip;return{kind:"afterimage",name:b.name,detail:()=>b.detail.replace("{name}",b.name)}}const f=this.pickDecorAt(t,e),p=f?this.ufoElement.sighting.decor.find(b=>b.id===f):void 0;if(p){const b=this.said.read(p.title)||s.decorKind(p.kind);return{kind:"decor",id:p.id,name:b,detail:()=>this.decorTooltip(p,b)}}const m=this.sceneRenderer.pickRailwayAt(t,e);if(m){const b=r.railwayTooltip;return{kind:"railway",id:m.line.id,name:Vr.name(m.line,b),detail:()=>Vr.detail(m,b,E=>this.distanceText(E))}}const g=this.trafficTooltipAt(t,e);if(g)return{kind:"traffic",name:g};const M=this.skyEventPickAt(t,e,(b,E)=>E.inSky===!0&&!b.pickedAfterSatellites);if(M)return M;const v=this.sceneRenderer.pickSatelliteAt(t,e);if(v)return{kind:"satellite",name:r.satelliteTooltip.replace("{name}",v.name).replace("{mag}",v.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(v.heightKm).toLocaleString())};const x=this.skyEventPickAt(t,e,(b,E)=>E.inSky===!0&&b.pickedAfterSatellites===!0);if(x)return x;const y=this.sceneRenderer.pickOpticsAt(t,e);if(y){const b=r.opticsTooltips[y.id].replace("{angle}",String(Math.round(y.angleDeg??0)));return{kind:"optics",id:y.id,name:b.split(" — ")[0],detail:()=>b}}const w=this.sceneRenderer.pickStarAt(t,e);if(w){const b=w.star.mag,E=w.altitudeDeg,S=E<0?r.starTooltipBelow:r.starTooltip,A=s.star(w.star);return{kind:"star",name:A,detail:()=>S.replace("{name}",A).replace("{mag}",b.toLocaleString(void 0,{maximumFractionDigits:Math.abs(b)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(E))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(t,e){const i=this.ufoElement.canvasElement,n={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},s=`${Math.round(t/n.x)}:${Math.round(e/n.y)}`,r=performance.now(),a=this.ghostLights.get(s);if(a&&r-a.atMs<_e.GHOST_LIGHT_KEPT_MS)return a.light;let c=this.shiningDecorNear(t,e,2*Math.max(n.x,n.y)),l;if(!c)for(const[h,u]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const d=this.pickAt(t+h*n.x,e+u*n.y,!1);if(d?.kind==="star")l??=d;else if(d){c=d;break}}return c??=this.shiningDecorNear(t,e,6*Math.max(n.x,n.y)),c??=l,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(s,{light:c??null,atMs:r}),c??null}ghostPick(t,e){const i=this.sceneRenderer.pickGhostAt(t,e);if(!i)return;const n=this.naming.names.ghostTooltip,s=this.lightOfGhost(i.source.x,i.source.y)??void 0,r=(s?.kind==="star"?s.name.split(" — ")[0]:s?.name)??n.unnamed,a=i.ghost,l=(pi.scatters(a)?n.halo:a.cause==="glass"?n.double:n.ghost).replace("{name}",r),h=a.scale<0?n.opposite:a.scale===1?n.around:n.sameSide;return{kind:"ghost",id:s?.id,name:l,detail:()=>n.detail.replace("{name}",l).replace("{cause}",n.causes[a.cause??"lens"]).replace("{where}",h),path:{from:{x:a.scale*i.source.x,y:a.scale*i.source.y},to:i.source}}}shiningDecorNear(t,e,i){let n;for(const s of this.ufoElement.sighting.decor){if(!(s.kind==="streetlight"||s.kind==="trafficlight"||(s.lights?.length??0)>0||s.kind==="vehicle"&&s.lit))continue;const a=this.sceneRenderer.decorScreenBox(s.id);if(!a)continue;const c=Math.hypot(Math.max(a.minX-t,0,t-a.maxX),Math.max(a.minY-e,0,e-a.maxY));if(c>i||n&&c>=n.distance)continue;const l=this.said.read(s.title)||this.naming.decorKind(s.kind);n={distance:c,pick:{kind:"decor",id:s.id,name:l}}}return n?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const i=new _c(n=>{if(!pi.records(t.instrument)||!pi.falling(t.lens))return 0;const s=Yh(t,n*1e3),r=Be(t,n*1e3);return(s.precipitationAmount??1)*pi.impactRate(s,t.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:s.windDirectionDeg,windSpeedMS:s.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:i}}return this.glassWetting.wetting}glassWetting;get skyEventsShown(){return this.skyEventsOf(this.ufoElement.sighting)}skyEventsStartDate;skyEventsMerged;skyEventsOf(t){const e=t.skyEvents,i=this.fireballs?.reentries,n=this.skyEventsMerged;if(n&&n.stated===e&&n.fireballs===i)return n.shown;const s=i?.length?{...e,reentries:[...e?.reentries??[],...i]}:e;return this.skyEventsMerged={stated:e,fireballs:i,shown:s},s}skyEventTexts=new Map;skyEventTextsLanguage;loadSkyEventTexts(t){const e=qg(wc.preferencesFor(this),Zg);e!==this.skyEventTextsLanguage&&(this.skyEventTexts.clear(),this.skyEventTextsLanguage=e);for(const i of t)this.skyEventTexts.has(i)||i.messages.load(e).then(n=>{this.skyEventTextsLanguage===e&&this.skyEventTexts.set(i,n)},()=>{})}skyEventPickAt(t,e,i){const n=this.skyEventsShown;if(!n)return;const s=this.sceneRenderer.pickSkyEventAt(t,e,i),r=s?vM.map(d=>Wa.of(d)).find(d=>d.key===s.kind):void 0,a=s&&r?Wa.eventsOf(n,r).find(d=>d.id===s.id):void 0;if(!s||!r||!a)return;const c=this.skyEventTexts.get(r);if(!c){this.loadSkyEventTexts([r]);return}const l=this.said.read(a.title)||c.name,h=r.describe?.(a,s,{said:this.said,texts:c,name:l,distance:d=>this.distanceText(d)}),u=h?.detail??(s.distanceM!==void 0?`${l}, ${this.distanceText(s.distanceM)}`:void 0);return{kind:r.pickKind??"skyEvent",id:a.id,name:h?.name??l,...u!==void 0?{detail:()=>u}:{}}}distanceText(t){return t>=1e3?`${(t/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${t.toLocaleString(void 0,{maximumFractionDigits:t<10?1:0})} m`}decorTooltip(t,e){const i=l=>l.toLocaleString(void 0,{maximumFractionDigits:l<10?1:0}),n=ut.sizeOf(t),s=this.sceneRenderer.decorDistanceM(t.id),r=s===void 0?"":this.distanceText(s);return this.naming.names.decorTooltip.replace("{name}",e).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(t){const e=t.startsWith(XS)?t.slice(XS.length):void 0,i=e?bA.find(s=>s.id===e):void 0;if(i)return this.naming.comet(i);const n=t.startsWith(YS)?kS.byId(t.slice(YS.length)):void 0;return n?this.naming.nova(n):this.naming.body(t)}get naming(){return this.sceneNaming}sceneNaming=new NS;namesLanguage;ready=Promise.resolve();async loadSceneNames(){const t=qg(wc.preferencesFor(this),Zg);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await P_(t);t===this.namesLanguage&&this.applySceneNaming(new NS(e))}setBusy(t,e=""){this.busyElement.hidden=!t,this.busyNote.textContent=t?e:"",this.busyElement.setAttribute("aria-label",e),this.busyElement.setAttribute("aria-busy",String(t))}renderLoaderText(t,e){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,c)=>{c>0&&s.append(" ");const l=document.createElement("span");l.className="scene-loader-word",l.setAttribute("aria-hidden","true");for(const h of a){const u=document.createElement("span");u.className="scene-loader-letter",u.style.setProperty("--i",String(i++)),u.textContent=h,l.append(u)}s.append(l),i++})};n(this.loaderNotVideo,t),i+=6,n(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t,t.loaded&&(this.creditsButton.title=t.names.credits,this.creditsButton.setAttribute("aria-label",t.names.credits),this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names.compassPoints))}showHoverTooltip(t,e){const i=this.hoverTooltip;i.textContent=e,i.hidden=!1,typeof i.showPopover=="function"&&!i.matches(":popover-open")&&i.showPopover();const{innerWidth:n,innerHeight:s}=window,r=12,a=4,c=Math.min(t.clientX+r,n-i.offsetWidth-a),l=t.clientY+r,h=l+i.offsetHeight+a>s?t.clientY-r-i.offsetHeight:l;i.style.left=`${Math.max(a,c)}px`,i.style.top=`${Math.max(a,h)}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};hearDetonations(t,e,i,n){const s=`${i.lat.toFixed(4)},${i.lng.toFixed(4)}`,r=this.detonationsFor;(!r||s!==r.key||t.length!==r.reentries.length||t.some((l,h)=>l!==r.reentries[h]))&&(this.detonationsFor={reentries:[...t],key:s,detonations:t.length?It.detonationsOf(t,i):[]});const a=this.detonationsFor.detonations;if(n)return;const c=this.lastDetonationT;if(this.lastDetonationT=e,!(c===void 0||e<c||e-c>_e.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const l of a)l.t>c&&l.t<=e&&this.weatherAudio.playDetonation(l.loudness)}detonates(t){const e=[...t.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],i=Be(t,0),n=t.event.place?.[0],s=i?.lat??n?.lat,r=i?.lng??n?.lng;return e.length>0&&s!==void 0&&r!==void 0&&It.detonationsOf(e,{lat:s,lng:r,heightM:this.altitudeOf(i)}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(t){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),mn.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(Yh(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const t=this.ufoElement.level;this.weatherAudio.setLevel(t),this.vehicleAudio.setLevel(t),this.aircraftAudio?.setLevel(t)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=t=>{if(this.lastTimeMs=t.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const e=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&e-this.lastPlayingHoverMs>=_e.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=e,this.ghostStillUnder(this.lastHover,e)&&this.hoverAt(this.lastHover))}this.placeFlightMark(),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(t,t),this.weatherAudio.setPaused(!t),this.vehicleAudio.setPaused(!t),this.aircraftAudio?.setPaused(!t),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${u_}</style>${h_}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new lt(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(dL));const e=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new Ku(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=s=>{this.holding=s,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.flightMark=this.shadow.getElementById("flight-mark"),this.ufoElement=document.createElement(Jg),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapSnapshotSource=s=>this.snapshotMapOf(s),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",s=>this.lookToward(s.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),n=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",s=>{s.newState==="open"&&Yn.fill(n,this)}),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(Ab,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=s=>s.vehicle!==void 0||s.decor.some(r=>r.engine!==void 0)||s.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1)||this.detonates(s),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of _e.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new wr(wc.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const i=t.vehicle;return i?{setting:kc.at(i.headlights??"auto",i.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}:void 0}travelHeadingAt(t,e){const i=Be(t,e);if(!i)return 0;for(const n of[400,-400]){const s=Be(t,e+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=ae(s.lat,s.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(n<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const i=e.flatMap(s=>s.pose.lat!==void 0&&s.pose.lng!==void 0?[{lat:s.pose.lat,lng:s.pose.lng}]:[]),n=i.length>=2?i:void 0;return this.routeCache={track:t,count:e.length,route:n},n}traceLabels(t){const e=wc.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const i=new Map;for(const n of t){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:t,language:e,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){Re.changes.addEventListener("change",this.onModulesChanged),this.saidTexts=void 0,this.ready=this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of _e.GESTURES)document.addEventListener(e,this.handlePageGesture,!0);const t=this.getAttribute("src");t&&this.loadFromSrc(t)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(t=>{if(t[t.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){Re.changes.removeEventListener("change",this.onModulesChanged),this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of _e.GESTURES)document.removeEventListener(t,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&i!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&i!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&i!==e){const n=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(n)&&n>0?n:Math.min(window.devicePixelRatio||1,2))}(t===fh||t===ph||t===Sc)&&i!==e&&this.forwardPlayerAttributes(),t===Sc&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const t of[fh,ph,Sc]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.sceneRenderer.setCompassForced(t)}lookToward(t){const e=Be(this.ufoElement.sighting,this.lastTimeMs);if(t.kind==="observer"||e?.lat===void 0||e.lng===void 0||e.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:i,z:n}=ae(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(i,n)<1)return this.setLookOffset(0,0);const s=(Math.atan2(i,-n)*180/Math.PI+360)%360;this.setLookOffset(((s-e.headingDeg)%360+540)%360-180,-e.pitchDeg)}setLookOffset(t,e){this.sceneRenderer.setLookOffset(t,e),this.ufoElement.setLookOffset(t,e),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(t,e){this.sceneRenderer.setIndoorLook(t,e)}setCloudRendering(t){this.sceneRenderer.setCloudRendering(t)}setWeather(t){this.sceneRenderer.setWeather(t),this.weatherAudio.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed)}pickCloudAt(t,e){return this.sceneRenderer.pickCloudAt(t,e)}cloudDirectionAt(t,e){return this.sceneRenderer.cloudDirectionAt(t,e)}pickDecorAt(t,e){return this.sceneRenderer.pickDecorAt(t,e)}decorScreenBox(t){return this.sceneRenderer.decorScreenBox(t)}decorDrawnOffset(t){return this.sceneRenderer.decorDrawnOffset(t)}decorGroundPointAt(t,e,i,n=0){return this.sceneRenderer.decorGroundPointAt(t,e,i,n)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,i){return this.sceneRenderer.decorGrabHeightAt(t,e,i)}bodyScreenBox(t){return this.sceneRenderer.bodyScreenBox(t)}pickPlacedBodyAt(t,e){return this.sceneRenderer.pickPlacedBodyAt(t,e)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(t){const e=xd.recording(t);this.holdForNewScene(e);const i=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(t,e,i=!0){this.poster.show(t,e,i)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,t&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=t||e,this.ufoElement.controlsHeld=t||e,this.ufoElement.holdClock(t)}holdForNewScene(t){this.sceneRenderer.holdForNewScene(t)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(t){this.sceneRenderer.documentUrl=t}get sightingData(){return this.ufoElement.sightingData}set sightingData(t){const e=Qi.toCurrent(t);this.ufoElement.sightingData=e,this.requireModules(e.modules),this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?ta.expand(this.ufoElement.sighting.interpretation,WS.kinds()):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}onModulesChanged=t=>{t.detail==="skyEvents"&&this.sceneRenderer.setSkyEvents(this.skyEventsShown,!0,this.skyEventsStartDate)};requireModules(t){if(!t?.length)return;const e=this.documentUrl,i=$t(async()=>{const{ModuleSession:n}=await import("./ModuleSession-BXMnu0b2.js");return{ModuleSession:n}},[],import.meta.url).then(({ModuleSession:n})=>n.shared.require(t,e)).then(()=>this.sceneRenderer.setDecorModelProvider(new uA));this.sceneRenderer.holdUntil(i)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(t.width/e);return t.height!==i&&(t.height=i),this.seekPreview??=new pp(this,()=>document.createElement(kM))}showAt(t){this.ufoElement.currentTime=t,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(t){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const e=t.getContext("2d");return e?(e.imageSmoothingQuality="high",e.drawImage(this.sceneCanvas,0,0,t.width,t.height),!0):!1}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}directionAt(t,e){return this.sceneRenderer.directionAt(t,e)}referenceFailure(t){return this.sceneRenderer.referenceFailure(t)}applyReferenceView(t){this.sceneRenderer.setReferencesShown(t.shown);for(const e of this.ufoElement.sighting.references){const i=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:i?i.shown?i.opacity:0:t.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(t){this.liveTerrainProviders=t,this.snapshotKey=void 0,this.applySnapshots(this.ufoElement.sighting.snapshots)}liveTerrainProviders;snapshotKey="none";applySnapshots(t){const e=hh.isEmpty(t)?"none":`${JSON.stringify(t)}
8663
8663
  ${this.documentUrl??""}
8664
8664
  ${mi.generation}`;if(e===this.snapshotKey)return;const i=this.snapshotKey!==void 0&&this.traffic?.set!==void 0;this.snapshotKey=e,this.sceneRenderer.setTerrainProviders(gp.providers(t,this.documentUrl,this.liveTerrainProviders??wb())),this.ufoElement.observerMapSnapshot=this.snapshotMapOf(t),i&&(this.traffic=void 0,this.decorMemo=void 0)}snapshotMapOf(t){const e=hh.held(t,"map");if(!e)return;const i=`${mi.address(e.src,this.documentUrl)}
8665
- ${mi.generation}`;return this.snapshotMap?.key!==i&&(this.snapshotMap={key:i,imagery:gp.map(e,this.documentUrl)}),this.snapshotMap.imagery}snapshotMap;setDecorModelProvider(t){this.sceneRenderer.setDecorModelProvider(t)}get decorModelCredits(){return[...new Map(this.sceneRenderer.currentDecorModelCredits.map(e=>[`${e.title}|${e.author??""}|${e.license}|${e.sourceUrl??""}`,e])).values()]}applyFrameFormat(){const t=this.ufoElement.sighting.instrument,e=hi.CANVAS_HEIGHT_PX,i=Xi.frameWidthPx(t,e);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${e}`)}resizeToStage(){const t=this.frameElement.getBoundingClientRect(),e=Math.max(1,Math.round(t.width)),i=Math.max(1,Math.round(t.height));this.sceneCanvas.width=e,this.sceneCanvas.height=i,this.sceneRenderer.resize(e,i)}async loadStars(){const t=[{magnitudeLimit:Bg,url:this.getAttribute("star-catalog-src")??gL},{magnitudeLimit:Hg,url:this.getAttribute("deep-star-catalog-src")??ML}],e=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=e>Bg?Hg:Bg;const n=await Br.upTo(t,e);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=Hg||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const t=this.ufoElement.sighting,e=Fn.gainFor(t.instrument,{fNumber:ze(t,0)?.fNumber,fieldOfViewDeg:dn.fovOf(t,0),exposureSeconds:t.exposure});return T0(vL,e)}updateAstronomy(t){this.ensureStarsDeepEnough(),this.applySceneAt(t);const e=vr.windowEndingAt(t,this.exposureSeconds()),i=e.seconds,n=this.degreesPerPixelAt(t),s=Nc.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(t).length,vr.instants(this.decorWithTraffic(this.ufoElement.sighting),ze(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(e.fromMs+e.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-1)*s/r),stepMs:e.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(t){const e=this.sceneCanvas.height;return e<=0?0:dn.fovOf(this.ufoElement.sighting,t)/e}roadGradeAt(t,e){return t.observerTrack.allKeyframes.length<2?0:Fl.at(t,e,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(t,e){const i=this.ufoElement.sighting;e||this.sceneRenderer.setRecordingTime(t),this.setWeather(Yh(i,t)),this.sceneRenderer.setInstrument(i.instrument,ze(i,t)?.fNumber),this.sceneRenderer.setLightPollution(i.lightPollution),e||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,t)),e||this.pushAircraftSound(i,t),this.updateMeteorShower(i,t),this.updateLightning(i,t,e!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(i),t)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??_e.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(t)),this.sceneRenderer.setContrails(this.traffic?.contrails??_e.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(t));const n=ze(i,t);this.sceneRenderer.setReferences(i.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0),e||this.sceneRenderer.setReferencesTime({t,playing:this.ufoElement.playbackState==="playing",timeScale:this.ufoElement.playbackRate});const s=ze(i,0),r=Xh(i,0),a=wl(i.event.time??{},n?.lng??m0.lng,i.event.utcOffsetHours),c=i.weatherSource!==void 0&&a?c_(a):void 0,l=Object.fromEntries(O0(Xh(i,t)).map(I=>[I.id,i2(t,i.weatherTrack,r,s,n,I.id,I.instances?.length?void 0:c)]));this.sceneRenderer.setCloudOffset(i2(t,i.weatherTrack,r,s,n,void 0,c),l),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,t)}:m0),this.sceneRenderer.setLensOptics(this.lensOpticsAt(t)),this.sceneRenderer.setInstrumentGain(Fn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:dn.fovOf(i,t),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,Mc.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(kd.mediumOf(i.instrument.medium,kd.byId(i.film)),i.exposure,n?.fNumber??i.instrument.fNumber,i.iso,i.metering),this.sceneRenderer.setLensGhosts(pi.optics(i.instrument,n?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(t/1e3))),this.sceneRenderer.setPerception(gc.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(ri.bodyAt(i,t,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(ze(i,0),n,t),this.placeBodiesAt(t,e===void 0),this.sceneRenderer.updateDecorLitState(t,e?.stepMs??0),this.applySnapshots(i.snapshots),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,t)),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng,()=>{this.placeBodiesAt(this.lastTimeMs,!0),this.sceneRenderer.render()}),this.sceneRenderer.setStatedRoads(i.roads),this.sceneRenderer.setTraces(i.traces,this.traceLabels(i.traces)),this.pushPhenomenaAt(t);const h=n?.lat??m0.lat,u=n?.lng??m0.lng,d=wl(i.event.time??{},u,i.event.utcOffsetHours),f={lat:h,lng:u,elevationM:this.altitudeOf(n)};this.pushSatellitesAt(d,t,f),this.ensureFireballs(d);const p=this.skyEventsOf(i),m=p?.reentries??[];this.hearDetonations(m,t,{lat:h,lng:u,heightM:f.elevationM},e!==void 0);const g=m.filter(I=>It.mayDazzle(I));if(this.sceneRenderer.setRetinaHistory(g.length===0?void 0:I=>{const D=ze(i,I),P={lat:D?.lat??h,lng:D?.lng??u,heightM:D?this.altitudeOf(D):f.elevationM};return{views:It.viewsAt(g,I,P),pose:D}},i),this.skyEventsStartDate=d,this.sceneRenderer.setSkyEvents(p,!1,d),p&&this.loadSkyEventTexts(vM.map(I=>Wa.of(I)).filter(I=>Wa.eventsOf(p,I).length>0&&!this.skyEventTexts.has(I))),e&&!e.sky)return;if(this.sceneRenderer.setSkyUnknown(!d),!d){this.sceneRenderer.setAstronomy(yL);return}const M=new Date(d.getTime()+t),v=Math.max(1,Math.round(.25*this.degreesPerPixelAt(t)/Nc.DEG_PER_SECOND*1e3)),x=Math.max(1e-8,this.degreesPerPixelAt(t)*.1),y=`${Math.floor(M.getTime()/v)}|${Math.round(h/x)}|${Math.round(u/x)}|${Math.round(f.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(y===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=y;const w=zf("Sun",M,f),b=zf("Moon",M,f);let E=tn.separationOf(w,b)<1?tn.viewAt(M,f):void 0;if(E){const I=tn.offsetOf(w,b,E.separationDeg);if(E.obscuration>_e.LIMB_FROM_OBSCURATION){const D=this.limbFor(M,f);D&&(E={...E,obscuration:1-Qs.uncoveredFraction(D,E.sunRadiusDeg,I),limb:D})}E={...E,horizonShare:tn.horizonShare(E,I,w.altitudeDeg,w.azimuthDeg,jr.distanceKm(M,f))}}const S={...w,magnitude:ig("Sun",M)-2.5*Math.log10(tn.beamFraction(E))};this.lastSun={altitudeDeg:S.altitudeDeg,azimuthDeg:S.azimuthDeg};const A={...b,phase:RO(M),magnitude:ig("Moon",M),radiusDeg:jr.apparentRadiusDeg(M,f)},_=TO.map(I=>({body:I,position:zf(I,M,f),magnitude:ig(I,M)}));this.sceneRenderer.setAstronomy({sun:S,moon:A,planets:_,comet:this.cometAt(M,f),novae:kS.appearancesAt(M,f).map(({outburst:I,position:D,magnitude:P})=>({id:I.id,position:D,magnitude:P})),stars:this.starCatalog?{catalog:this.starCatalog,date:M,observer:f}:void 0,frame:{date:M,observer:f},localHour:((M.getUTCHours()+M.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(u/15)))%24+24)%24,eclipse:E}),this.ufoElement.setSunAltitude(S.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(t,e){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,$u.load(mL).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(t.getTime()-i.atMs)<5e3&&i.lat===e.lat&&i.lng===e.lng&&i.elevationM===e.elevationM)return i.profile;const n=Qs.profile(t,e,this.limbRelief);return this.limbCache={profile:n,atMs:t.getTime(),lat:e.lat,lng:e.lng,elevationM:e.elevationM},n}pushSatellitesAt(t,e,i){if(this.ensureSatellites(t),!t||!this.satellites){this.sceneRenderer.setSatellites([]);return}const n=new Date(t.getTime()+e),s=[];for(const r of this.satellites.passes.positionsAt(n,i,-1))r.magnitude!==void 0&&s.push({norad:r.object.norad,name:r.object.name,position:{altitudeDeg:r.altitudeDeg,azimuthDeg:r.azimuthDeg},magnitude:r.magnitude,heightKm:r.heightKm});this.sceneRenderer.setSatellites(s)}ensureFireballs(t){const e=this.ufoElement.sighting,i=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=t?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!Qr.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,_e.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(c=>Qr.asReentry(c,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(uL)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(t){const e=this.ensureTraffic(t);if(!e||e.objects.length===0)return t.decor;const i=this.decorMemo;if(i&&i.base===t.decor&&i.traffic===e.objects)return i.merged;const n=[...t.decor,...e.objects];return this.decorMemo={base:t.decor,traffic:e.objects,merged:n},n}seatedDecor(t,e){if(!t.some(r=>r.observerKeyframes?.length))return t;const i=t.map(r=>{if(!r.observerKeyframes?.length)return"";const a=Jy(r,e);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===t&&n.seats===i)return n.seated;const s=t.map(r=>{if(!r.observerKeyframes?.length)return r;const a=Jy(r,e);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:t,seats:i,seated:s},s}ensureTraffic(t){const e=ze(t,0),i=e?.lng===void 0?void 0:wl(t.event.time??{},e.lng,t.event.utcOffsetHours),n=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||e?.lat===void 0||e.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${e.lat.toFixed(3)},${e.lng.toFixed(3)}|${Math.round(e.elevationM??0)}|${Math.round(this.sceneRenderer.groundAltitudeM)}`;if(this.traffic?.key===r)return this.traffic.set;if(this.upperAirHeardLive=void 0,r===""||s===void 0||e?.lat===void 0||e.lng===void 0){this.traffic={key:r,status:"outside"};return}let a=_e.aircraftProviders.get(this.aircraftSource.id);if(a||_e.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const c={key:r,status:"loading",startMs:s,observer:{lat:e.lat,lng:e.lng}};this.traffic=c;const l={lat:e.lat,lng:e.lng,heightM:this.sceneRenderer.groundAltitudeM},h=Dn.MAX_GAP_S*1e3,u=_e.SOUND_LOOKBACK_MS,d={lat:e.lat,lng:e.lng,elevationM:this.altitudeOf(e)},f=(p,m)=>p.TrafficDecor.from(c.tracks??[],l,s,p.TrafficDecor.MAX_OBJECTS,{models:m,sunElevationAt:g=>this.sunElevationAt(g,d)});a.between(l,s-u,s+n+h).then(async p=>{if(this.traffic!==c)return;if(p.status!=="found"){c.status=p.status==="outside"?"outside":"unavailable",p.status==="failed"&&(c.problem=p.problem,c.creditsSpent=p.creditsSpent),this.announceTraffic();return}let m;try{m=await _e.loadTrafficRuntime()}catch{this.traffic===c&&(c.status="unavailable",this.announceTraffic());return}this.traffic===c&&(c.status="ready",c.tracks=p.tracks,c.partial=p.partial,c.creditsSpent=p.creditsSpent,c.set=f(m),this.startAircraftSound(c,m),this.announceTraffic(),this.describeTraffic(a,c,m,f),c.set.shown>0&&(this.readUpperAir(c,m,s-u,s+n+h),this.readTrailTraffic(a,c,m,l,s-_e.TRAIL_LOOKBACK_MS,s+n+h)))})}trafficSunlight(t){const e=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return e;for(const[r,a]of n.presence){if(t<a.fromMs||t>a.untilMs)continue;const c=n.flights.get(r),l=c?Dn.positionAt(c,i.startMs+t):void 0;l&&e.set(r,{heightM:l.geo.heightM,sunElevationDeg:ds.sunElevationDeg(s,i.observer,l.geo)})}return e}trafficTooltipAt(t,e){const i=this.sceneRenderer.pickTrafficAt(t,e),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming;return _e.trafficRuntime?.TrafficTooltip.text(n,s.names.trafficTooltip,a=>s.towards(a))}trafficInfoAt(t){const e=this.traffic,i=e?.set?.flights.get(t);if(!e||!i||e.startMs===void 0||!e.observer)return;const n=_e.trafficRuntime;if(!n)return;const s=e.descriptions?.get(Ii.keyOf(i)),r=ze(this.ufoElement.sighting,this.lastTimeMs),a={lat:e.observer.lat,lng:e.observer.lng,heightM:this.altitudeOf(r)},c=n.AmbientNoise.dbA(Yh(this.ufoElement.sighting,this.lastTimeMs)),l=n.TrafficInfos.at(i,s,a,e.startMs+this.lastTimeMs,{ambientDbA:c}),h=l&&this.contrailAt(t,this.lastTimeMs);return l&&h?{...l,contrail:h}:l}contrailAt(t,e){const i=this.traffic?.contrails?.find(s=>s.id===t);if(!i)return;let n;for(const s of i.points){if(s.tMs>e)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(t,e){this.aircraftAudio??=this.newAircraftAudio(e),this.sortOutAudible(t,e)}sortOutAudible(t,e){!t.set||!t.observer||(t.audible=e.TrafficSound.candidates(t.set.flights,t.descriptions??new Map,Ii.keyOf,{...t.observer,heightM:this.sceneRenderer.groundAltitudeM},{ambientDbA:e.AmbientNoise.BASE_DB_A}))}pushAircraftSound(t,e){this.startDecorAircraftSound(t),this.startBodySound();const i=this.aircraftAudio;if(!i)return;const n=_e.trafficRuntime;if(!n){i.setVoices([]);return}const s=ze(t,e),r=Yh(t,e),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},c=this.trafficVoices(e,s,a,n),l=t.event.place?.[0],h={lat:s?.lat??l?.lat,lng:s?.lng??l?.lng};h.lat!==void 0&&h.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,c.push(...this.decorAircraftHearing.voices(t,e,{lat:h.lat,lng:h.lng,heightM:s?.elevationM??0},a,u=>this.decorModelSounds.get(u.model?.id??""))),c.push(...this.bodyVoices(t,e,a,n)),c.sort((u,d)=>d.levelDbA-u.levelDbA),c.length=Math.min(c.length,4)),i.setVoices(c,s?.headingDeg??0)}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(t=>t.sound)||(_e.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(_e.trafficRuntime):_e.loadTrafficRuntime().catch(()=>{}))}bodyVoices(t,e,i,n){const s=this.interpretationShown,r=t.event.place?.[0];if(!s||!r||!s.bodies.some(f=>f.sound))return[];const a=this.sceneRenderer.bodyGround,c=f=>Bt.eyeOf(t,f,a),l=c(e);if(!l)return[];const h=new Map,u=(f,p)=>{let m=h.get(f.id);return m||h.set(f.id,m=new Bt(f,a,c)),m.at(p)};this.bodyHearing??=new n.BodyHearing;const d=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(s.bodies,u,l,r,e,d,i)}trafficVoices(t,e,i,n){const s=this.traffic,r=s?.set;if(!s||!r||!s.audible||s.startMs===void 0||!s.observer)return[];const a={lat:s.observer.lat,lng:s.observer.lng,heightM:this.altitudeOf(e)};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,Ii.keyOf,a,s.startMs+t,i)}startDecorAircraftSound(t){const e=t.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(e.length!==0){for(const i of e){const n=i.model?.id;!n||i.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.sceneRenderer.entryOfDecorModel(n).then(s=>{this.decorModelSounds.set(n,s?.parameters?.sound)}))}if(this.aircraftAudio||_e.trafficRuntime){!this.aircraftAudio&&_e.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(_e.trafficRuntime));return}_e.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(t){const e=new t.AircraftAudio;return e.setLevel(this.ufoElement.level),this.interacted&&e.resume(),e.setPaused(this.ufoElement.playbackState!=="playing"),e}get aircraftFlights(){const t=this.traffic;if(!t?.tracks||t.startMs===void 0||!t.observer)return[];const e=t.startMs,i=this.observerAt(this.lastTimeMs,t.observer),n=new Set([...t.set?.flights.values()??[]].map(a=>Ii.keyOf(a))),s=t.nearestPassKm??=new Map(t.tracks.map(a=>[Ii.keyOf(a),Math.min(...a.points.map(c=>Dn.groundDistanceKm(t.observer,c)))])),r=this.ufoElement.seekableDuration;return[...t.tracks].sort((a,c)=>s.get(Ii.keyOf(a))-s.get(Ii.keyOf(c))).map(a=>{const c=Ii.keyOf(a),l=t.descriptions?.get(c),h=t.models?.get(c),u=Dn.seenFrom(a,i,e+this.lastTimeMs),d=a.points.find(f=>f.t>=e)?.t;return{key:c,type:h?.basis==="type"?h.name:l?.type,registration:l?.registration,sky:u?.sky,altitudeFt:u?.altitudeFt,firstMs:d!==void 0&&d-e<=r?d-e:void 0,drawn:n.has(c)}})}lookAtFlight(t,e=this.lastTimeMs){const i=this.traffic,n=ze(this.ufoElement.sighting,e),s=i?.tracks?.find(a=>Ii.keyOf(a)===t);if(!i?.observer||i.startMs===void 0||!s||n?.headingDeg===void 0)return!1;const r=Dn.seenFrom(s,this.observerAt(e,i.observer),i.startMs+e);return r?(this.setLookOffset(((r.sky.azimuthDeg-n.headingDeg)%360+540)%360-180,r.sky.altitudeDeg-(n.pitchDeg??0)),!0):!1}markFlight(t){this.markedFlight=t,this.placeFlightMark()}placeFlightMark(){const t=this.markedFlight,e=t===void 0?void 0:this.sceneRenderer.flightScreenPoint(t);if(this.flightMark.toggleAttribute("hidden",!e),!e)return;const i=this.sceneCanvas.getBoundingClientRect(),n=this.stageElement.getBoundingClientRect(),s=i.left-n.left+(e.ndcX+1)/2*i.width,r=i.top-n.top+(1-e.ndcY)/2*i.height;for(const a of Array.from(this.flightMark.children))a.setAttribute("cx",String(s)),a.setAttribute("cy",String(r))}altitudeOf(t){return this.sceneRenderer.groundAltitudeM+(t?.elevationM??0)}observerAt(t,e){const i=ze(this.ufoElement.sighting,t);return{lat:i?.lat??e.lat,lng:i?.lng??e.lng,heightM:this.altitudeOf(i)}}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(fL)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(t,e,i,n){if(!t.describe||!e.set||!e.tracks)return;const s=new Set([...e.set.flights.values()].map(l=>Ii.keyOf(l))),r=e.tracks.filter(l=>s.has(Ii.keyOf(l))&&l.points.length>0),a=new Map,c=new Map;await Promise.all(r.map(async l=>{const h=new Date(l.points[0].t).toISOString().slice(0,10),u=await t.describe(l,h).catch(()=>{});u&&(c.set(Ii.keyOf(l),u),a.set(Ii.keyOf(l),i.AircraftModels.of(u)))})),!(this.traffic!==e||a.size===0)&&(e.descriptions=c,e.models=a,e.set=n(i,a),this.planContrails(e,i),this.sortOutAudible(e,i),this.announceTraffic())}async readTrailTraffic(t,e,i,n,s,r){if(e.startMs===void 0)return;const a=await t.between(n,s,r).catch(()=>{});if(this.traffic!==e||a?.status!=="found")return;const c=a.tracks.filter(u=>u.points.some(d=>d.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),l=new Map(e.models??[]);if(t.describe&&await Promise.all(c.filter(u=>u.points.length>0&&!l.has(Ii.keyOf(u))).map(async u=>{const d=await t.describe(u,new Date(u.points[0].t).toISOString().slice(0,10)).catch(()=>{});d&&l.set(Ii.keyOf(u),i.AircraftModels.of(d))})),this.traffic!==e||e.startMs===void 0)return;const h=i.TrafficDecor.from(c,n,e.startMs,_e.TRAIL_MAX_AIRCRAFT,{models:l});e.trailSet=_e.alignTrailIds(h,e.set),e.models=new Map([...l,...e.models??[]]),this.planContrails(e,i),this.announceTraffic()}static alignTrailIds(t,e){if(!e)return t;const i=new Map;for(const[a,c]of e.flights){const l=e.presence.get(a);if(l)for(const[h,u]of t.flights){const d=t.presence.get(h);!d||Ii.keyOf(u)!==Ii.keyOf(c)||d.fromMs<=l.untilMs&&l.fromMs<=d.untilMs&&i.set(h,a)}}const n=a=>i.get(a)??`${a}-trail`,s=new Set(i.values()),r=e.objects.filter(a=>!s.has(a.id));return{...t,objects:[...t.objects.map(a=>({...a,id:n(a.id)})),...r],presence:new Map([...[...t.presence].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.presence.get(a.id)])]),flights:new Map([...[...t.flights].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.flights.get(a.id)])])}}async readUpperAir(t,e,i,n){if(!t.observer)return;const s=hh.held(this.ufoElement.sighting.snapshots,"upperAir");let r;if(s){const l=mi.address(s.src,this.documentUrl);r=_e.upperAirProviders.get(l),r||_e.upperAirProviders.set(l,r=new sh(mi.json(l)))}else{const l=this.upperAirSource??e.UPPER_AIR_SOURCES[0];r=_e.upperAirProviders.get(l.id),r||_e.upperAirProviders.set(l.id,r=l.create())}const a={lat:t.observer.lat,lng:t.observer.lng},c=await r.between(a,i,n);this.traffic!==t||c.status!=="found"||(s||(this.upperAirHeardLive={...a,startMs:i,endMs:n,answer:c}),t.air=c.samples,t.airSource=c.source,this.planContrails(t,e),this.announceTraffic())}planContrails(t,e){const i=t.trailSet??t.set;!i||!t.air||t.startMs===void 0||(t.contrails=e.AircraftContrails.plan(i,t.models,t.air,t.startMs))}contrailSunlight(t){const e=new Map,i=this.traffic,n=i?.trailSet??i?.set,s=this.lastSun;if(!i||!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return e;for(const r of i.contrails){const a=n.presence.get(r.id),c=n.flights.get(r.id);if(!a||!c)continue;const l=Dn.positionAt(c,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,t)));l&&e.set(r.id,{heightM:l.geo.heightM,sunElevationDeg:ds.sunElevationDeg(s,i.observer,l.geo)})}return e}sunElevationAt(t,e){const i=zf("Sun",new Date(t.t),e);return ds.sunElevationDeg(i,e,t)}upperAirSource;upperAirHeardLive;get upperAirHeard(){return this.upperAirHeardLive}setUpperAirSource(t){t.id!==this.upperAirSource?.id&&(this.upperAirSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(t,e=!1){!e&&t.id===this.aircraftSource.id||(this.aircraftSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const t=this.traffic?.contrails?.length?this.upperAirSource??_e.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:t&&{credit:t.credit,creditUrl:t.creditUrl},status:this.traffic?.status??"none",problem:this.traffic?.problem,partial:this.traffic?.partial,creditsSpent:this.traffic?.creditsSpent,total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(t){const e=t?String(t.getTime()):"";if(e===this.satellitesFor)return;this.satellitesFor=e,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!t){this.satelliteStatus="none";return}this.satelliteStatus="loading";const n=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(hL)))},s=_e.tleArchive;(async()=>{if(!await s.covers(t))return n("outside");const[r,a]=await Promise.all([s.at(t),$t(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new a.SatellitePasses(r.objects)},n("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>n("unavailable"))}get satelliteState(){const t=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:t?.coverage,credit:t?.credit,creditUrl:t?.creditUrl}}burningCandidates(){return{reentries:this.ufoElement.sighting.skyEvents?.reentries??[],fireballs:this.fireballs?.reentries??[]}}trafficCandidates(){const t=this.traffic;if(!(t?.status!=="ready"||!t.tracks||t.startMs===void 0))return{tracks:t.tracks,startMs:t.startMs,describe:e=>t.descriptions?.get(Ii.keyOf(e))}}satellitePositionsAt(t){const e=this.satellites,i=this.ufoElement.sighting,n=ze(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!(!e||r===void 0||a===void 0))return e.passes.positionsAt(t,{lat:r,lng:a,elevationM:this.altitudeOf(n)})}satellitePassesDuring(t){const e=this.satellites,i=this.ufoElement.sighting,n=ze(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!e||r===void 0||a===void 0)return[];const c=wl(i.event.time??{},a,i.event.utcOffsetHours);if(!c)return[];const l=Math.min(Math.max(t,0),4*36e5),h={lat:r,lng:a,elevationM:this.altitudeOf(n)},u=JSON.stringify([this.satellitesFor,c.getTime(),r,a,h.elevationM,l]);if(this.satellitePassesMemo?.key===u)return this.satellitePassesMemo.passes;const d=Math.max(10,Math.ceil(l/1e3/600)),f=e.passes.passesDuring(c,new Date(c.getTime()+l),h,d);return this.satellitePassesMemo={key:u,passes:f},f}cometAt(t,e){const i=QN.brightestAt(t,e);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}pushPhenomenaAt(t){const e=this.ufoElement.sighting;e!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=e);const i=e.timeline,n=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,r=this.projectionAt(t),a=new Map,c=new Map,l=new Set;for(const p of i.sourceIds){const m=i.getInterpolatedShapeAt(t,p);if(!m)continue;const g={...m,bounds:{...m.bounds,x:m.bounds.x+s.x,y:m.bounds.y+s.y}};a.set(p,g);const M=m.aim?this.sceneRenderer.screenPointOf(Mr.directionOf(m.aim,this.directionScratch)):{ndcX:(g.bounds.x+g.bounds.width/2)/n.width*2-1,ndcY:-((g.bounds.y+g.bounds.height/2)/n.height*2-1)},v=M!==void 0&&Math.abs(M.ndcX)<=1&&Math.abs(M.ndcY)<=1,x=v?this.sceneRenderer.decorDistancesAt(M.ndcX,M.ndcY,p):{};l.add(p),(v||m.aim)&&l.delete(p);const y=m.angular?.widthDeg??r.pxToDeg(m.bounds.width),w=this.sizeEstimateOf(p);w.add(y,x);const b=qu.of(e,p);c.set(p,ls.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:b&&y>0?hi.distanceMAt(b.widthM,y):void 0,range:w.distanceRangeAt(y),crossing:x}))}for(const[p,m]of a)for(const[g,M]of a){if(g===p||M.transparency>=1||M.bounds.width*M.bounds.height<=m.bounds.width*m.bounds.height||!(m.bounds.x>=M.bounds.x&&m.bounds.y>=M.bounds.y&&m.bounds.x+m.bounds.width<=M.bounds.x+M.bounds.width&&m.bounds.y+m.bounds.height<=M.bounds.y+M.bounds.height))continue;const x=c.get(g);x&&c.set(p,{distanceM:x.distanceM*.999,basis:x.basis});break}this.depths=c;const h=i.sourceIds,u=[];for(const[p,m]of a)u.push({sourceId:p,shape:m,distanceM:c.get(p).distanceM,renderOrder:h.indexOf(p),aim:m.aim,hidden:l.has(p)||this.interpretationShown!==void 0&&(!this.comparing||m.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const d=ze(e,t),f=(d?.rollDeg??0)+ri.bodyAt(e,t,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(u,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:Xi.starPointsOf(e.instrument,d?.fNumber),rollRad:f*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(t){this.interpretationShown=ta.expand(t,WS.kinds()),this.ufoElement.playerTitle=t?.title,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}redrawSky(){this.updateAstronomy(this.lastTimeMs)}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(t){this.inTheRound=t}get compareAccount(){return this.comparing}set compareAccount(t){t!==this.comparing&&(this.comparing=t,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())}get confrontation(){return this.confrontationReadings}groundAlong(t,e,i){const n=this.sceneRenderer.bodyGround,s=Bt.eyeOf(this.ufoElement.sighting,i,n);return s?Bt.lineOfSightMeetsGround(s,t,e,n):void 0}bodyMaskedBy(t,e){return this.sceneRenderer.bodyMaskedByDecor(t,e)}bodyReading(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=d=>Bt.eyeOf(n,d,i),r=new Bt(t,i,s).at(e),a=s(e);if(!r||!a)return;const c=r.eastM-a.eastM,l=r.northM-a.northM,h=r.upM-a.upM,u=Math.hypot(c,l);return{azimuthDeg:(Math.atan2(c,l)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,u)*180/Math.PI,distanceM:Math.hypot(u,h),eastM:r.eastM,northM:r.northM,aboveGroundM:r.upM-r.sizeM.heightM/2-i.heightAt(r.eastM,r.northM),sizeM:r.sizeM,attitude:r.attitude,appearance:r.appearance}}bodyProjectionAt(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=c=>Bt.eyeOf(n,c,i),r=new Bt(t,i,s).at(e),a=s(e);return r&&a?_i.projectionOf(r,a):void 0}directionToBody(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=p=>Bt.eyeOf(n,p,i),r=new Bt(t,i,s),a=r.at(e)?e:t.track[0]?.t,c=a===void 0?void 0:r.at(a),l=a===void 0?void 0:s(a);if(!c||!l)return;const h=c.eastM-l.eastM,u=c.northM-l.northM,d=c.upM-l.upM,f=Math.hypot(h,u);if(!(f===0&&d===0))return{azimuthDeg:(Math.atan2(h,u)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(d,f)*180/Math.PI}}placeBodiesAt(t,e){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,c=p=>Bt.eyeOf(n,p,a);i&&(s=i.bodies.map(p=>new Bt(p,a,c).at(t)).filter(p=>p!==void 0));const l=Xh(n,t),h=l.windDirectionDeg*Math.PI/180,u={x:l.windSpeed*Math.sin(h),z:-l.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(s,t/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],u);const d=i&&this.comparing?c(t):void 0;if(d&&(r=new _i(n.timeline,this.confrontationTolerance).at(t,s,d,p=>p.outlineNode?this.sceneRenderer.bodyOutline?.(p.id,p.outlineNode):void 0)),this.confrontationReadings=r,!e)return;const f=JSON.stringify(r);f!==this.confrontationSignature&&(this.confrontationSignature=f,this.dispatchEvent(new CustomEvent(pL,{detail:r})))}setDistanceHypothesis(t,e){e===void 0||!(e>0)?this.distanceHypotheses.delete(t):this.distanceHypotheses.set(t,e),this.updateAstronomy(this.lastTimeMs)}depthOf(t){return this.depths.get(t)}sizeRangeOf(t){return this.sizeEstimateOf(t).sizeRange}distanceRangeAt(t,e){const i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(e,t);if(!i)return{};const n=i.angular?.widthDeg??this.projectionAt(e).pxToDeg(i.bounds.width);return this.sizeEstimateOf(t).distanceRangeAt(n)}sizeContradictory(t){return this.sizeEstimateOf(t).contradictory}updateMeteorShower(t,e){this.ensureMeteorSchedule(t),this.sceneRenderer.updateMeteors(e)}updateLightning(t,e,i){if(this.ensureLightningSchedule(t),this.sceneRenderer.updateLightning(e),i)return;const n=this.lastLightningT;if(this.lastLightningT=e,n===void 0||e<n||this.ufoElement.playbackState!=="playing")return;const s=this.lightningFlashes.filter(r=>r.t>n&&r.t<=e).pop();s&&Xh(t,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(t){const e=Xh(t,0).precipitationIntensity,i=`${this.meteorInputsOf(t)}|${e}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const n=t.event.time,s=t.event.place?.[0],r=n?.year!==void 0?wl(n,s?.lng??0,t.event.utcOffsetHours):void 0,a=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,c=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=mn.schedule({durationMs:a,seed:c,intensity:e}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(t){const e=this.meteorInputsOf(t);e!==this.meteorScheduleFor&&(this.meteorScheduleFor=e,this.scheduleMeteors(t))}meteorInputsOf(t){const e=t.event.place?.[0],i=t.event.time;return JSON.stringify([e?.lat,e?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,t.event.utcOffsetHours,t.event.durationSeconds,t.timeline.duration])}scheduleMeteors(t){const e=t.event.place?.[0],i=t.event.time,n=e?.lat!==void 0&&e.lng!==void 0&&i?.year!==void 0?wl(i,e.lng,t.event.utcOffsetHours):void 0;if(!n||e?.lat===void 0||e.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:e.lat,lng:e.lng,elevationM:0},r=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,a=Math.round(n.getTime()/1e3)+Math.round(e.lat*1e3),c=Vi.schedule({ratePerHour:Vi.observedRatePerHour(Vi.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:Vi.TYPICAL_VELOCITY_KM_S,seed:a}),l=Vg.activeAt(n).map(u=>{const d=Vg.radiantPosition(u.shower,n,s);return{entry:u,position:d,rate:Vg.observedRatePerHour(u.zhr,d.altitudeDeg,u.shower.populationIndex)}}).sort((u,d)=>d.rate-u.rate)[0];if(!l||l.rate<=0){this.sceneRenderer.setMeteorShower(c,0,0);return}const h=ir.schedule({ratePerHour:l.rate,durationMs:r,velocityKmS:l.entry.shower.velocityKmS,seed:a+1});this.sceneRenderer.setMeteorShower([...h,...c],l.position.altitudeDeg,l.position.azimuthDeg)}groundHides(t,e){return this.sceneRenderer.groundHidesDirection(t,e)}get groundKey(){return this.sceneRenderer.groundKey}meteorByRank(t,e=Number.POSITIVE_INFINITY){this.ensureMeteorSchedule(this.ufoElement.sighting);const i=[...this.sceneRenderer.meteorSchedule].filter(r=>r.t+r.durationMs<=this.ufoElement.seekableDuration).filter(r=>ir.magnitudeOf(r)<=e).filter(r=>{const a=this.sceneRenderer.meteorMidpoint(r);return a!==void 0&&!this.sceneRenderer.groundHidesDirection(a.altitudeDeg,a.azimuthDeg)}).sort((r,a)=>a.brightness-r.brightness);if(i.length===0)return;const n=i[t%i.length],s=this.sceneRenderer.meteorMidpoint(n);if(s)return{t:Math.round(n.t+n.durationMs*.45),...s}}lensOpticsAt(t){const e=this.ufoElement.sighting,i=e.instrument,n=i.frame,s=ze(e,t),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=Xi.focalLengthMmFor(i,dn.fovOf(e,t));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(t){const e=this.ufoElement.sighting;return na.of(e.instrument,hi.CANVAS_HEIGHT_PX,dn.fovOf(e,t))}sizeEstimateOf(t){let e=this.sizeEstimates.get(t);return e||(e=new eL,this.sizeEstimates.set(t,e)),e}}const kM="rr0-scene";function xL(){Eb(),customElements.get(kM)||customElements.define(kM,_e)}xL();export{Ci as $,Ic as A,ye as B,rt as C,B_ as D,eu as E,fe as F,Xe as G,ps as H,LL as I,xn as J,OL as K,ww as L,Re as M,kc as N,En as O,F1 as P,IL as Q,It as R,ku as S,Ii as T,c4 as U,tt as V,DL as W,Pn as X,ge as Y,kn as Z,$t as _,Dn as a,yh as a$,rn as a0,ss as a1,Pi as a2,Sd as a3,dr as a4,zl as a5,sL as a6,Vv as a7,rL as a8,wL as a9,TL as aA,qb as aB,RL as aC,Bn as aD,Xs as aE,Kb as aF,Mx as aG,w5 as aH,fA as aI,G0 as aJ,k1 as aK,hE as aL,pv as aM,mv as aN,Ue as aO,pa as aP,Hd as aQ,_r as aR,Hr as aS,qt as aT,yn as aU,ha as aV,yi as aW,$o as aX,Nd as aY,pt as aZ,OP as a_,bL as aa,SL as ab,Gd as ac,NL as ad,CL as ae,X0 as af,dE as ag,j0 as ah,_L as ai,is as aj,J2 as ak,PL as al,kL as am,Yb as an,Vs as ao,jd as ap,dm as aq,wT as ar,ti as as,Xo as at,r1 as au,Yi as av,va as aw,T5 as ax,li as ay,AL as az,vb as b,Ht as b0,ql as b1,xv as b2,Ut as b3,De as b4,Xh as b5,ta as b6,WS as b7,hs as b8,wr as b9,fv as ba,Go as bb,ma as bc,ms as bd,ns as be,Bh as bf,Ki as bg,u4 as c,vt as d,Ro as e,yb as f,ae as g,Me as h,or as i,UL as j,q0 as k,Is as l,Ke as m,ar as n,R as o,Te as p,Xr as q,oa as r,wt as s,Ae as t,qa as u,Vt as v,EL as w,Bs as x,b0 as y,Jo as z};
8665
+ ${mi.generation}`;return this.snapshotMap?.key!==i&&(this.snapshotMap={key:i,imagery:gp.map(e,this.documentUrl)}),this.snapshotMap.imagery}snapshotMap;setDecorModelProvider(t){this.sceneRenderer.setDecorModelProvider(t)}get decorModelCredits(){return[...new Map(this.sceneRenderer.currentDecorModelCredits.map(e=>[`${e.title}|${e.author??""}|${e.license}|${e.sourceUrl??""}`,e])).values()]}applyFrameFormat(){const t=this.ufoElement.sighting.instrument,e=hi.CANVAS_HEIGHT_PX,i=Xi.frameWidthPx(t,e);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${e}`)}resizeToStage(){const t=this.frameElement.getBoundingClientRect(),e=Math.max(1,Math.round(t.width)),i=Math.max(1,Math.round(t.height));this.sceneCanvas.width=e,this.sceneCanvas.height=i,this.sceneRenderer.resize(e,i)}async loadStars(){const t=[{magnitudeLimit:Bg,url:this.getAttribute("star-catalog-src")??gL},{magnitudeLimit:Hg,url:this.getAttribute("deep-star-catalog-src")??ML}],e=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=e>Bg?Hg:Bg;const n=await Br.upTo(t,e);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=Hg||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const t=this.ufoElement.sighting,e=Fn.gainFor(t.instrument,{fNumber:Be(t,0)?.fNumber,fieldOfViewDeg:dn.fovOf(t,0),exposureSeconds:t.exposure});return T0(vL,e)}updateAstronomy(t){this.ensureStarsDeepEnough(),this.applySceneAt(t);const e=vr.windowEndingAt(t,this.exposureSeconds()),i=e.seconds,n=this.degreesPerPixelAt(t),s=Nc.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(t).length,vr.instants(this.decorWithTraffic(this.ufoElement.sighting),Be(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(e.fromMs+e.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-1)*s/r),stepMs:e.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(t){const e=this.sceneCanvas.height;return e<=0?0:dn.fovOf(this.ufoElement.sighting,t)/e}roadGradeAt(t,e){return t.observerTrack.allKeyframes.length<2?0:Fl.at(t,e,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(t,e){const i=this.ufoElement.sighting;e||this.sceneRenderer.setRecordingTime(t),this.setWeather(Yh(i,t)),this.sceneRenderer.setInstrument(i.instrument,Be(i,t)?.fNumber),this.sceneRenderer.setLightPollution(i.lightPollution),e||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,t)),e||this.pushAircraftSound(i,t),this.updateMeteorShower(i,t),this.updateLightning(i,t,e!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(i),t)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??_e.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(t)),this.sceneRenderer.setContrails(this.traffic?.contrails??_e.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(t));const n=Be(i,t);this.sceneRenderer.setReferences(i.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0),e||this.sceneRenderer.setReferencesTime({t,playing:this.ufoElement.playbackState==="playing",timeScale:this.ufoElement.playbackRate});const s=Be(i,0),r=Xh(i,0),a=wl(i.event.time??{},n?.lng??m0.lng,i.event.utcOffsetHours),c=i.weatherSource!==void 0&&a?c_(a):void 0,l=Object.fromEntries(O0(Xh(i,t)).map(I=>[I.id,i2(t,i.weatherTrack,r,s,n,I.id,I.instances?.length?void 0:c)]));this.sceneRenderer.setCloudOffset(i2(t,i.weatherTrack,r,s,n,void 0,c),l),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,t)}:m0),this.sceneRenderer.setLensOptics(this.lensOpticsAt(t)),this.sceneRenderer.setInstrumentGain(Fn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:dn.fovOf(i,t),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,Mc.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(kd.mediumOf(i.instrument.medium,kd.byId(i.film)),i.exposure,n?.fNumber??i.instrument.fNumber,i.iso,i.metering),this.sceneRenderer.setLensGhosts(pi.optics(i.instrument,n?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(t/1e3))),this.sceneRenderer.setPerception(gc.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(ri.bodyAt(i,t,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(Be(i,0),n,t),this.placeBodiesAt(t,e===void 0),this.sceneRenderer.updateDecorLitState(t,e?.stepMs??0),this.applySnapshots(i.snapshots),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,t)),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng,()=>{this.placeBodiesAt(this.lastTimeMs,!0),this.sceneRenderer.render()}),this.sceneRenderer.setStatedRoads(i.roads),this.sceneRenderer.setTraces(i.traces,this.traceLabels(i.traces)),this.pushPhenomenaAt(t);const h=n?.lat??m0.lat,u=n?.lng??m0.lng,d=wl(i.event.time??{},u,i.event.utcOffsetHours),f={lat:h,lng:u,elevationM:this.altitudeOf(n)};this.pushSatellitesAt(d,t,f),this.ensureFireballs(d);const p=this.skyEventsOf(i),m=p?.reentries??[];this.hearDetonations(m,t,{lat:h,lng:u,heightM:f.elevationM},e!==void 0);const g=m.filter(I=>It.mayDazzle(I));if(this.sceneRenderer.setRetinaHistory(g.length===0?void 0:I=>{const D=Be(i,I),P={lat:D?.lat??h,lng:D?.lng??u,heightM:D?this.altitudeOf(D):f.elevationM};return{views:It.viewsAt(g,I,P),pose:D}},i),this.skyEventsStartDate=d,this.sceneRenderer.setSkyEvents(p,!1,d),p&&this.loadSkyEventTexts(vM.map(I=>Wa.of(I)).filter(I=>Wa.eventsOf(p,I).length>0&&!this.skyEventTexts.has(I))),e&&!e.sky)return;if(this.sceneRenderer.setSkyUnknown(!d),!d){this.sceneRenderer.setAstronomy(yL);return}const M=new Date(d.getTime()+t),v=Math.max(1,Math.round(.25*this.degreesPerPixelAt(t)/Nc.DEG_PER_SECOND*1e3)),x=Math.max(1e-8,this.degreesPerPixelAt(t)*.1),y=`${Math.floor(M.getTime()/v)}|${Math.round(h/x)}|${Math.round(u/x)}|${Math.round(f.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(y===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=y;const w=zf("Sun",M,f),b=zf("Moon",M,f);let E=tn.separationOf(w,b)<1?tn.viewAt(M,f):void 0;if(E){const I=tn.offsetOf(w,b,E.separationDeg);if(E.obscuration>_e.LIMB_FROM_OBSCURATION){const D=this.limbFor(M,f);D&&(E={...E,obscuration:1-Qs.uncoveredFraction(D,E.sunRadiusDeg,I),limb:D})}E={...E,horizonShare:tn.horizonShare(E,I,w.altitudeDeg,w.azimuthDeg,jr.distanceKm(M,f))}}const S={...w,magnitude:ig("Sun",M)-2.5*Math.log10(tn.beamFraction(E))};this.lastSun={altitudeDeg:S.altitudeDeg,azimuthDeg:S.azimuthDeg};const A={...b,phase:RO(M),magnitude:ig("Moon",M),radiusDeg:jr.apparentRadiusDeg(M,f)},_=TO.map(I=>({body:I,position:zf(I,M,f),magnitude:ig(I,M)}));this.sceneRenderer.setAstronomy({sun:S,moon:A,planets:_,comet:this.cometAt(M,f),novae:kS.appearancesAt(M,f).map(({outburst:I,position:D,magnitude:P})=>({id:I.id,position:D,magnitude:P})),stars:this.starCatalog?{catalog:this.starCatalog,date:M,observer:f}:void 0,frame:{date:M,observer:f},localHour:((M.getUTCHours()+M.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(u/15)))%24+24)%24,eclipse:E}),this.ufoElement.setSunAltitude(S.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(t,e){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,$u.load(mL).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(t.getTime()-i.atMs)<5e3&&i.lat===e.lat&&i.lng===e.lng&&i.elevationM===e.elevationM)return i.profile;const n=Qs.profile(t,e,this.limbRelief);return this.limbCache={profile:n,atMs:t.getTime(),lat:e.lat,lng:e.lng,elevationM:e.elevationM},n}pushSatellitesAt(t,e,i){if(this.ensureSatellites(t),!t||!this.satellites){this.sceneRenderer.setSatellites([]);return}const n=new Date(t.getTime()+e),s=[];for(const r of this.satellites.passes.positionsAt(n,i,-1))r.magnitude!==void 0&&s.push({norad:r.object.norad,name:r.object.name,position:{altitudeDeg:r.altitudeDeg,azimuthDeg:r.azimuthDeg},magnitude:r.magnitude,heightKm:r.heightKm});this.sceneRenderer.setSatellites(s)}ensureFireballs(t){const e=this.ufoElement.sighting,i=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=t?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!Qr.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,_e.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(c=>Qr.asReentry(c,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(uL)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(t){const e=this.ensureTraffic(t);if(!e||e.objects.length===0)return t.decor;const i=this.decorMemo;if(i&&i.base===t.decor&&i.traffic===e.objects)return i.merged;const n=[...t.decor,...e.objects];return this.decorMemo={base:t.decor,traffic:e.objects,merged:n},n}seatedDecor(t,e){if(!t.some(r=>r.observerKeyframes?.length))return t;const i=t.map(r=>{if(!r.observerKeyframes?.length)return"";const a=Jy(r,e);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===t&&n.seats===i)return n.seated;const s=t.map(r=>{if(!r.observerKeyframes?.length)return r;const a=Jy(r,e);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:t,seats:i,seated:s},s}ensureTraffic(t){const e=Be(t,0),i=e?.lng===void 0?void 0:wl(t.event.time??{},e.lng,t.event.utcOffsetHours),n=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||e?.lat===void 0||e.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${e.lat.toFixed(3)},${e.lng.toFixed(3)}|${Math.round(e.elevationM??0)}|${Math.round(this.sceneRenderer.groundAltitudeM)}`;if(this.traffic?.key===r)return this.traffic.set;if(this.upperAirHeardLive=void 0,r===""||s===void 0||e?.lat===void 0||e.lng===void 0){this.traffic={key:r,status:"outside"};return}let a=_e.aircraftProviders.get(this.aircraftSource.id);if(a||_e.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const c={key:r,status:"loading",startMs:s,observer:{lat:e.lat,lng:e.lng}};this.traffic=c;const l={lat:e.lat,lng:e.lng,heightM:this.sceneRenderer.groundAltitudeM},h=Dn.MAX_GAP_S*1e3,u=_e.SOUND_LOOKBACK_MS,d={lat:e.lat,lng:e.lng,elevationM:this.altitudeOf(e)},f=(p,m)=>p.TrafficDecor.from(c.tracks??[],l,s,p.TrafficDecor.MAX_OBJECTS,{models:m,sunElevationAt:g=>this.sunElevationAt(g,d)});a.between(l,s-u,s+n+h).then(async p=>{if(this.traffic!==c)return;if(p.status!=="found"){c.status=p.status==="outside"?"outside":"unavailable",p.status==="failed"&&(c.problem=p.problem,c.creditsSpent=p.creditsSpent),this.announceTraffic();return}let m;try{m=await _e.loadTrafficRuntime()}catch{this.traffic===c&&(c.status="unavailable",this.announceTraffic());return}this.traffic===c&&(c.status="ready",c.tracks=p.tracks,c.partial=p.partial,c.creditsSpent=p.creditsSpent,c.set=f(m),this.startAircraftSound(c,m),this.announceTraffic(),this.describeTraffic(a,c,m,f),c.set.shown>0&&(this.readUpperAir(c,m,s-u,s+n+h),this.readTrailTraffic(a,c,m,l,s-_e.TRAIL_LOOKBACK_MS,s+n+h)))})}trafficSunlight(t){const e=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return e;for(const[r,a]of n.presence){if(t<a.fromMs||t>a.untilMs)continue;const c=n.flights.get(r),l=c?Dn.positionAt(c,i.startMs+t):void 0;l&&e.set(r,{heightM:l.geo.heightM,sunElevationDeg:ds.sunElevationDeg(s,i.observer,l.geo)})}return e}trafficTooltipAt(t,e){const i=this.sceneRenderer.pickTrafficAt(t,e),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming;return _e.trafficRuntime?.TrafficTooltip.text(n,s.names.trafficTooltip,a=>s.towards(a))}trafficInfoAt(t){const e=this.traffic,i=e?.set?.flights.get(t);if(!e||!i||e.startMs===void 0||!e.observer)return;const n=_e.trafficRuntime;if(!n)return;const s=e.descriptions?.get(Ii.keyOf(i)),r=Be(this.ufoElement.sighting,this.lastTimeMs),a={lat:e.observer.lat,lng:e.observer.lng,heightM:this.altitudeOf(r)},c=n.AmbientNoise.dbA(Yh(this.ufoElement.sighting,this.lastTimeMs)),l=n.TrafficInfos.at(i,s,a,e.startMs+this.lastTimeMs,{ambientDbA:c}),h=l&&this.contrailAt(t,this.lastTimeMs);return l&&h?{...l,contrail:h}:l}contrailAt(t,e){const i=this.traffic?.contrails?.find(s=>s.id===t);if(!i)return;let n;for(const s of i.points){if(s.tMs>e)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(t,e){this.aircraftAudio??=this.newAircraftAudio(e),this.sortOutAudible(t,e)}sortOutAudible(t,e){!t.set||!t.observer||(t.audible=e.TrafficSound.candidates(t.set.flights,t.descriptions??new Map,Ii.keyOf,{...t.observer,heightM:this.sceneRenderer.groundAltitudeM},{ambientDbA:e.AmbientNoise.BASE_DB_A}))}pushAircraftSound(t,e){this.startDecorAircraftSound(t),this.startBodySound();const i=this.aircraftAudio;if(!i)return;const n=_e.trafficRuntime;if(!n){i.setVoices([]);return}const s=Be(t,e),r=Yh(t,e),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},c=this.trafficVoices(e,s,a,n),l=t.event.place?.[0],h={lat:s?.lat??l?.lat,lng:s?.lng??l?.lng};h.lat!==void 0&&h.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,c.push(...this.decorAircraftHearing.voices(t,e,{lat:h.lat,lng:h.lng,heightM:s?.elevationM??0},a,u=>this.decorModelSounds.get(u.model?.id??""))),c.push(...this.bodyVoices(t,e,a,n)),c.sort((u,d)=>d.levelDbA-u.levelDbA),c.length=Math.min(c.length,4)),i.setVoices(c,s?.headingDeg??0)}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(t=>t.sound)||(_e.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(_e.trafficRuntime):_e.loadTrafficRuntime().catch(()=>{}))}bodyVoices(t,e,i,n){const s=this.interpretationShown,r=t.event.place?.[0];if(!s||!r||!s.bodies.some(f=>f.sound))return[];const a=this.sceneRenderer.bodyGround,c=f=>Bt.eyeOf(t,f,a),l=c(e);if(!l)return[];const h=new Map,u=(f,p)=>{let m=h.get(f.id);return m||h.set(f.id,m=new Bt(f,a,c)),m.at(p)};this.bodyHearing??=new n.BodyHearing;const d=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(s.bodies,u,l,r,e,d,i)}trafficVoices(t,e,i,n){const s=this.traffic,r=s?.set;if(!s||!r||!s.audible||s.startMs===void 0||!s.observer)return[];const a={lat:s.observer.lat,lng:s.observer.lng,heightM:this.altitudeOf(e)};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,Ii.keyOf,a,s.startMs+t,i)}startDecorAircraftSound(t){const e=t.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(e.length!==0){for(const i of e){const n=i.model?.id;!n||i.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.sceneRenderer.entryOfDecorModel(n).then(s=>{this.decorModelSounds.set(n,s?.parameters?.sound)}))}if(this.aircraftAudio||_e.trafficRuntime){!this.aircraftAudio&&_e.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(_e.trafficRuntime));return}_e.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(t){const e=new t.AircraftAudio;return e.setLevel(this.ufoElement.level),this.interacted&&e.resume(),e.setPaused(this.ufoElement.playbackState!=="playing"),e}get aircraftFlights(){const t=this.traffic;if(!t?.tracks||t.startMs===void 0||!t.observer)return[];const e=t.startMs,i=this.observerAt(this.lastTimeMs,t.observer),n=new Set([...t.set?.flights.values()??[]].map(a=>Ii.keyOf(a))),s=t.nearestPassKm??=new Map(t.tracks.map(a=>[Ii.keyOf(a),Math.min(...a.points.map(c=>Dn.groundDistanceKm(t.observer,c)))])),r=this.ufoElement.seekableDuration;return[...t.tracks].sort((a,c)=>s.get(Ii.keyOf(a))-s.get(Ii.keyOf(c))).map(a=>{const c=Ii.keyOf(a),l=t.descriptions?.get(c),h=t.models?.get(c),u=Dn.seenFrom(a,i,e+this.lastTimeMs),d=a.points.find(f=>f.t>=e)?.t;return{key:c,type:h?.basis==="type"?h.name:l?.type,registration:l?.registration,sky:u?.sky,altitudeFt:u?.altitudeFt,firstMs:d!==void 0&&d-e<=r?d-e:void 0,drawn:n.has(c)}})}lookAtFlight(t,e=this.lastTimeMs){const i=this.traffic,n=Be(this.ufoElement.sighting,e),s=i?.tracks?.find(a=>Ii.keyOf(a)===t);if(!i?.observer||i.startMs===void 0||!s||n?.headingDeg===void 0)return!1;const r=Dn.seenFrom(s,this.observerAt(e,i.observer),i.startMs+e);return r?(this.setLookOffset(((r.sky.azimuthDeg-n.headingDeg)%360+540)%360-180,r.sky.altitudeDeg-(n.pitchDeg??0)),!0):!1}markFlight(t){this.markedFlight=t,this.placeFlightMark()}placeFlightMark(){const t=this.markedFlight,e=t===void 0?void 0:this.sceneRenderer.flightScreenPoint(t);if(this.flightMark.toggleAttribute("hidden",!e),!e)return;const i=this.sceneCanvas.getBoundingClientRect(),n=this.stageElement.getBoundingClientRect(),s=i.left-n.left+(e.ndcX+1)/2*i.width,r=i.top-n.top+(1-e.ndcY)/2*i.height;for(const a of Array.from(this.flightMark.children))a.setAttribute("cx",String(s)),a.setAttribute("cy",String(r))}altitudeOf(t){return this.sceneRenderer.groundAltitudeM+(t?.elevationM??0)}observerAt(t,e){const i=Be(this.ufoElement.sighting,t);return{lat:i?.lat??e.lat,lng:i?.lng??e.lng,heightM:this.altitudeOf(i)}}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(fL)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(t,e,i,n){if(!t.describe||!e.set||!e.tracks)return;const s=new Set([...e.set.flights.values()].map(l=>Ii.keyOf(l))),r=e.tracks.filter(l=>s.has(Ii.keyOf(l))&&l.points.length>0),a=new Map,c=new Map;await Promise.all(r.map(async l=>{const h=new Date(l.points[0].t).toISOString().slice(0,10),u=await t.describe(l,h).catch(()=>{});u&&(c.set(Ii.keyOf(l),u),a.set(Ii.keyOf(l),i.AircraftModels.of(u)))})),!(this.traffic!==e||a.size===0)&&(e.descriptions=c,e.models=a,e.set=n(i,a),this.planContrails(e,i),this.sortOutAudible(e,i),this.announceTraffic())}async readTrailTraffic(t,e,i,n,s,r){if(e.startMs===void 0)return;const a=await t.between(n,s,r).catch(()=>{});if(this.traffic!==e||a?.status!=="found")return;const c=a.tracks.filter(u=>u.points.some(d=>d.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),l=new Map(e.models??[]);if(t.describe&&await Promise.all(c.filter(u=>u.points.length>0&&!l.has(Ii.keyOf(u))).map(async u=>{const d=await t.describe(u,new Date(u.points[0].t).toISOString().slice(0,10)).catch(()=>{});d&&l.set(Ii.keyOf(u),i.AircraftModels.of(d))})),this.traffic!==e||e.startMs===void 0)return;const h=i.TrafficDecor.from(c,n,e.startMs,_e.TRAIL_MAX_AIRCRAFT,{models:l});e.trailSet=_e.alignTrailIds(h,e.set),e.models=new Map([...l,...e.models??[]]),this.planContrails(e,i),this.announceTraffic()}static alignTrailIds(t,e){if(!e)return t;const i=new Map;for(const[a,c]of e.flights){const l=e.presence.get(a);if(l)for(const[h,u]of t.flights){const d=t.presence.get(h);!d||Ii.keyOf(u)!==Ii.keyOf(c)||d.fromMs<=l.untilMs&&l.fromMs<=d.untilMs&&i.set(h,a)}}const n=a=>i.get(a)??`${a}-trail`,s=new Set(i.values()),r=e.objects.filter(a=>!s.has(a.id));return{...t,objects:[...t.objects.map(a=>({...a,id:n(a.id)})),...r],presence:new Map([...[...t.presence].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.presence.get(a.id)])]),flights:new Map([...[...t.flights].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.flights.get(a.id)])])}}async readUpperAir(t,e,i,n){if(!t.observer)return;const s=hh.held(this.ufoElement.sighting.snapshots,"upperAir");let r;if(s){const l=mi.address(s.src,this.documentUrl);r=_e.upperAirProviders.get(l),r||_e.upperAirProviders.set(l,r=new sh(mi.json(l)))}else{const l=this.upperAirSource??e.UPPER_AIR_SOURCES[0];r=_e.upperAirProviders.get(l.id),r||_e.upperAirProviders.set(l.id,r=l.create())}const a={lat:t.observer.lat,lng:t.observer.lng},c=await r.between(a,i,n);this.traffic!==t||c.status!=="found"||(s||(this.upperAirHeardLive={...a,startMs:i,endMs:n,answer:c}),t.air=c.samples,t.airSource=c.source,this.planContrails(t,e),this.announceTraffic())}planContrails(t,e){const i=t.trailSet??t.set;!i||!t.air||t.startMs===void 0||(t.contrails=e.AircraftContrails.plan(i,t.models,t.air,t.startMs))}contrailSunlight(t){const e=new Map,i=this.traffic,n=i?.trailSet??i?.set,s=this.lastSun;if(!i||!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return e;for(const r of i.contrails){const a=n.presence.get(r.id),c=n.flights.get(r.id);if(!a||!c)continue;const l=Dn.positionAt(c,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,t)));l&&e.set(r.id,{heightM:l.geo.heightM,sunElevationDeg:ds.sunElevationDeg(s,i.observer,l.geo)})}return e}sunElevationAt(t,e){const i=zf("Sun",new Date(t.t),e);return ds.sunElevationDeg(i,e,t)}upperAirSource;upperAirHeardLive;get upperAirHeard(){return this.upperAirHeardLive}setUpperAirSource(t){t.id!==this.upperAirSource?.id&&(this.upperAirSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(t,e=!1){!e&&t.id===this.aircraftSource.id||(this.aircraftSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const t=this.traffic?.contrails?.length?this.upperAirSource??_e.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:t&&{credit:t.credit,creditUrl:t.creditUrl},status:this.traffic?.status??"none",problem:this.traffic?.problem,partial:this.traffic?.partial,creditsSpent:this.traffic?.creditsSpent,total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(t){const e=t?String(t.getTime()):"";if(e===this.satellitesFor)return;this.satellitesFor=e,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!t){this.satelliteStatus="none";return}this.satelliteStatus="loading";const n=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(hL)))},s=_e.tleArchive;(async()=>{if(!await s.covers(t))return n("outside");const[r,a]=await Promise.all([s.at(t),$t(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new a.SatellitePasses(r.objects)},n("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>n("unavailable"))}get satelliteState(){const t=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:t?.coverage,credit:t?.credit,creditUrl:t?.creditUrl}}burningCandidates(){return{reentries:this.ufoElement.sighting.skyEvents?.reentries??[],fireballs:this.fireballs?.reentries??[]}}trafficCandidates(){const t=this.traffic;if(!(t?.status!=="ready"||!t.tracks||t.startMs===void 0))return{tracks:t.tracks,startMs:t.startMs,describe:e=>t.descriptions?.get(Ii.keyOf(e))}}satellitePositionsAt(t){const e=this.satellites,i=this.ufoElement.sighting,n=Be(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!(!e||r===void 0||a===void 0))return e.passes.positionsAt(t,{lat:r,lng:a,elevationM:this.altitudeOf(n)})}satellitePassesDuring(t){const e=this.satellites,i=this.ufoElement.sighting,n=Be(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!e||r===void 0||a===void 0)return[];const c=wl(i.event.time??{},a,i.event.utcOffsetHours);if(!c)return[];const l=Math.min(Math.max(t,0),4*36e5),h={lat:r,lng:a,elevationM:this.altitudeOf(n)},u=JSON.stringify([this.satellitesFor,c.getTime(),r,a,h.elevationM,l]);if(this.satellitePassesMemo?.key===u)return this.satellitePassesMemo.passes;const d=Math.max(10,Math.ceil(l/1e3/600)),f=e.passes.passesDuring(c,new Date(c.getTime()+l),h,d);return this.satellitePassesMemo={key:u,passes:f},f}cometAt(t,e){const i=QN.brightestAt(t,e);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}pushPhenomenaAt(t){const e=this.ufoElement.sighting;e!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=e);const i=e.timeline,n=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,r=this.projectionAt(t),a=new Map,c=new Map,l=new Set;for(const p of i.sourceIds){const m=i.getInterpolatedShapeAt(t,p);if(!m)continue;const g={...m,bounds:{...m.bounds,x:m.bounds.x+s.x,y:m.bounds.y+s.y}};a.set(p,g);const M=m.aim?this.sceneRenderer.screenPointOf(Mr.directionOf(m.aim,this.directionScratch)):{ndcX:(g.bounds.x+g.bounds.width/2)/n.width*2-1,ndcY:-((g.bounds.y+g.bounds.height/2)/n.height*2-1)},v=M!==void 0&&Math.abs(M.ndcX)<=1&&Math.abs(M.ndcY)<=1,x=v?this.sceneRenderer.decorDistancesAt(M.ndcX,M.ndcY,p):{};l.add(p),(v||m.aim)&&l.delete(p);const y=m.angular?.widthDeg??r.pxToDeg(m.bounds.width),w=this.sizeEstimateOf(p);w.add(y,x);const b=qu.of(e,p);c.set(p,ls.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:b&&y>0?hi.distanceMAt(b.widthM,y):void 0,range:w.distanceRangeAt(y),crossing:x}))}for(const[p,m]of a)for(const[g,M]of a){if(g===p||M.transparency>=1||M.bounds.width*M.bounds.height<=m.bounds.width*m.bounds.height||!(m.bounds.x>=M.bounds.x&&m.bounds.y>=M.bounds.y&&m.bounds.x+m.bounds.width<=M.bounds.x+M.bounds.width&&m.bounds.y+m.bounds.height<=M.bounds.y+M.bounds.height))continue;const x=c.get(g);x&&c.set(p,{distanceM:x.distanceM*.999,basis:x.basis});break}this.depths=c;const h=i.sourceIds,u=[];for(const[p,m]of a)u.push({sourceId:p,shape:m,distanceM:c.get(p).distanceM,renderOrder:h.indexOf(p),aim:m.aim,hidden:l.has(p)||this.interpretationShown!==void 0&&(!this.comparing||m.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const d=Be(e,t),f=(d?.rollDeg??0)+ri.bodyAt(e,t,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(u,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:Xi.starPointsOf(e.instrument,d?.fNumber),rollRad:f*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(t){this.interpretationShown=ta.expand(t,WS.kinds()),this.ufoElement.playerTitle=t?.title,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}redrawSky(){this.updateAstronomy(this.lastTimeMs)}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(t){this.inTheRound=t}get compareAccount(){return this.comparing}set compareAccount(t){t!==this.comparing&&(this.comparing=t,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())}get confrontation(){return this.confrontationReadings}groundAlong(t,e,i){const n=this.sceneRenderer.bodyGround,s=Bt.eyeOf(this.ufoElement.sighting,i,n);return s?Bt.lineOfSightMeetsGround(s,t,e,n):void 0}bodyMaskedBy(t,e){return this.sceneRenderer.bodyMaskedByDecor(t,e)}bodyReading(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=d=>Bt.eyeOf(n,d,i),r=new Bt(t,i,s).at(e),a=s(e);if(!r||!a)return;const c=r.eastM-a.eastM,l=r.northM-a.northM,h=r.upM-a.upM,u=Math.hypot(c,l);return{azimuthDeg:(Math.atan2(c,l)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,u)*180/Math.PI,distanceM:Math.hypot(u,h),eastM:r.eastM,northM:r.northM,aboveGroundM:r.upM-r.sizeM.heightM/2-i.heightAt(r.eastM,r.northM),sizeM:r.sizeM,attitude:r.attitude,appearance:r.appearance}}bodyProjectionAt(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=c=>Bt.eyeOf(n,c,i),r=new Bt(t,i,s).at(e),a=s(e);return r&&a?_i.projectionOf(r,a):void 0}directionToBody(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=p=>Bt.eyeOf(n,p,i),r=new Bt(t,i,s),a=r.at(e)?e:t.track[0]?.t,c=a===void 0?void 0:r.at(a),l=a===void 0?void 0:s(a);if(!c||!l)return;const h=c.eastM-l.eastM,u=c.northM-l.northM,d=c.upM-l.upM,f=Math.hypot(h,u);if(!(f===0&&d===0))return{azimuthDeg:(Math.atan2(h,u)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(d,f)*180/Math.PI}}placeBodiesAt(t,e){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,c=p=>Bt.eyeOf(n,p,a);i&&(s=i.bodies.map(p=>new Bt(p,a,c).at(t)).filter(p=>p!==void 0));const l=Xh(n,t),h=l.windDirectionDeg*Math.PI/180,u={x:l.windSpeed*Math.sin(h),z:-l.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(s,t/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],u);const d=i&&this.comparing?c(t):void 0;if(d&&(r=new _i(n.timeline,this.confrontationTolerance).at(t,s,d,p=>p.outlineNode?this.sceneRenderer.bodyOutline?.(p.id,p.outlineNode):void 0)),this.confrontationReadings=r,!e)return;const f=JSON.stringify(r);f!==this.confrontationSignature&&(this.confrontationSignature=f,this.dispatchEvent(new CustomEvent(pL,{detail:r})))}setDistanceHypothesis(t,e){e===void 0||!(e>0)?this.distanceHypotheses.delete(t):this.distanceHypotheses.set(t,e),this.updateAstronomy(this.lastTimeMs)}depthOf(t){return this.depths.get(t)}sizeRangeOf(t){return this.sizeEstimateOf(t).sizeRange}distanceRangeAt(t,e){const i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(e,t);if(!i)return{};const n=i.angular?.widthDeg??this.projectionAt(e).pxToDeg(i.bounds.width);return this.sizeEstimateOf(t).distanceRangeAt(n)}sizeContradictory(t){return this.sizeEstimateOf(t).contradictory}updateMeteorShower(t,e){this.ensureMeteorSchedule(t),this.sceneRenderer.updateMeteors(e)}updateLightning(t,e,i){if(this.ensureLightningSchedule(t),this.sceneRenderer.updateLightning(e),i)return;const n=this.lastLightningT;if(this.lastLightningT=e,n===void 0||e<n||this.ufoElement.playbackState!=="playing")return;const s=this.lightningFlashes.filter(r=>r.t>n&&r.t<=e).pop();s&&Xh(t,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(t){const e=Xh(t,0).precipitationIntensity,i=`${this.meteorInputsOf(t)}|${e}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const n=t.event.time,s=t.event.place?.[0],r=n?.year!==void 0?wl(n,s?.lng??0,t.event.utcOffsetHours):void 0,a=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,c=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=mn.schedule({durationMs:a,seed:c,intensity:e}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(t){const e=this.meteorInputsOf(t);e!==this.meteorScheduleFor&&(this.meteorScheduleFor=e,this.scheduleMeteors(t))}meteorInputsOf(t){const e=t.event.place?.[0],i=t.event.time;return JSON.stringify([e?.lat,e?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,t.event.utcOffsetHours,t.event.durationSeconds,t.timeline.duration])}scheduleMeteors(t){const e=t.event.place?.[0],i=t.event.time,n=e?.lat!==void 0&&e.lng!==void 0&&i?.year!==void 0?wl(i,e.lng,t.event.utcOffsetHours):void 0;if(!n||e?.lat===void 0||e.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:e.lat,lng:e.lng,elevationM:0},r=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,a=Math.round(n.getTime()/1e3)+Math.round(e.lat*1e3),c=Vi.schedule({ratePerHour:Vi.observedRatePerHour(Vi.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:Vi.TYPICAL_VELOCITY_KM_S,seed:a}),l=Vg.activeAt(n).map(u=>{const d=Vg.radiantPosition(u.shower,n,s);return{entry:u,position:d,rate:Vg.observedRatePerHour(u.zhr,d.altitudeDeg,u.shower.populationIndex)}}).sort((u,d)=>d.rate-u.rate)[0];if(!l||l.rate<=0){this.sceneRenderer.setMeteorShower(c,0,0);return}const h=ir.schedule({ratePerHour:l.rate,durationMs:r,velocityKmS:l.entry.shower.velocityKmS,seed:a+1});this.sceneRenderer.setMeteorShower([...h,...c],l.position.altitudeDeg,l.position.azimuthDeg)}groundHides(t,e){return this.sceneRenderer.groundHidesDirection(t,e)}get groundKey(){return this.sceneRenderer.groundKey}meteorByRank(t,e=Number.POSITIVE_INFINITY){this.ensureMeteorSchedule(this.ufoElement.sighting);const i=[...this.sceneRenderer.meteorSchedule].filter(r=>r.t+r.durationMs<=this.ufoElement.seekableDuration).filter(r=>ir.magnitudeOf(r)<=e).filter(r=>{const a=this.sceneRenderer.meteorMidpoint(r);return a!==void 0&&!this.sceneRenderer.groundHidesDirection(a.altitudeDeg,a.azimuthDeg)}).sort((r,a)=>a.brightness-r.brightness);if(i.length===0)return;const n=i[t%i.length],s=this.sceneRenderer.meteorMidpoint(n);if(s)return{t:Math.round(n.t+n.durationMs*.45),...s}}lensOpticsAt(t){const e=this.ufoElement.sighting,i=e.instrument,n=i.frame,s=Be(e,t),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=Xi.focalLengthMmFor(i,dn.fovOf(e,t));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(t){const e=this.ufoElement.sighting;return na.of(e.instrument,hi.CANVAS_HEIGHT_PX,dn.fovOf(e,t))}sizeEstimateOf(t){let e=this.sizeEstimates.get(t);return e||(e=new eL,this.sizeEstimates.set(t,e)),e}}const kM="rr0-scene";function xL(){Eb(),customElements.get(kM)||customElements.define(kM,_e)}xL();export{Ci as $,Ic as A,ye as B,rt as C,B_ as D,eu as E,fe as F,Xe as G,ps as H,LL as I,xn as J,OL as K,ww as L,Re as M,kc as N,En as O,F1 as P,IL as Q,It as R,ku as S,Ii as T,c4 as U,tt as V,DL as W,Pn as X,ge as Y,kn as Z,$t as _,Dn as a,yh as a$,rn as a0,ss as a1,Pi as a2,Sd as a3,dr as a4,zl as a5,sL as a6,Vv as a7,rL as a8,wL as a9,TL as aA,qb as aB,RL as aC,Bn as aD,Xs as aE,Kb as aF,Mx as aG,w5 as aH,fA as aI,G0 as aJ,k1 as aK,hE as aL,pv as aM,mv as aN,Ue as aO,pa as aP,Hd as aQ,_r as aR,Hr as aS,qt as aT,yn as aU,ha as aV,yi as aW,$o as aX,Nd as aY,pt as aZ,OP as a_,bL as aa,SL as ab,Gd as ac,NL as ad,CL as ae,X0 as af,dE as ag,j0 as ah,_L as ai,is as aj,J2 as ak,PL as al,kL as am,Yb as an,Vs as ao,jd as ap,dm as aq,wT as ar,ti as as,Xo as at,r1 as au,Yi as av,va as aw,T5 as ax,li as ay,AL as az,vb as b,Ht as b0,ql as b1,xv as b2,Ut as b3,De as b4,Xh as b5,ta as b6,WS as b7,hs as b8,wr as b9,fv as ba,Go as bb,ma as bc,ms as bd,ns as be,Bh as bf,Ki as bg,u4 as c,vt as d,Ro as e,yb as f,ae as g,Me as h,or as i,UL as j,q0 as k,Is as l,Ke as m,ar as n,R as o,Te as p,Xr as q,oa as r,wt as s,Ae as t,qa as u,Vt as v,EL as w,Bs as x,b0 as y,Jo as z};