@rr0/ufoathome 0.150.0 → 0.150.2

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.
@@ -331,8 +331,8 @@ ${e} :is(select:not([multiple]):not([size]), .rr0-select) {
331
331
  <button id="copy" class="share-copy" type="button">Copy</button>
332
332
  </div>
333
333
  </dialog>
334
- `;class Wc extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Wc.TAG)||customElements.define(Wc.TAG,Wc)}subject;messages=ng;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;freeze;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=TE;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.freeze=e("freeze"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.freeze.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=e==="en"?ng:await gE(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.freeze.checked;this.linkField.value=t?Jr.frozenLink(e.link(),"0.150.0"):e.link(),this.fitLink();const n=`<script type="module" src="${t?Jr.frozen(e.module,"0.150.0"):Jr.current(e.module,import.meta.url,rh.home())}"><\/script>
335
- ${e.element()}`;this.embedMarkup.value=n,this.codeEditor&&(this.codeEditor.text=n)}applyMessages(){const e=this.messages,t=(i,n)=>{this.shadow.getElementById(i).textContent=n};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("freeze-label",e.freeze.replace("{version}","0.150.0")),this.freeze.parentElement.title=e.freezeHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=ae(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([0,1]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages.embed),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages.copied,window.setTimeout(()=>this.copyButton.textContent=this.messages.copy,1500)}catch{t.select()}}}class vs{constructor(e){this.preferences=e}read(e){if(e===void 0||typeof e=="string")return e===""?void 0:e;for(const i of this.preferences){const n=e[i]??e[vs.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>vs.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(vs.base(i)))return n;return Object.values(e).find(i=>i)??void 0}write(e,t,i){const n=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return n;const s={...e},r=Object.keys(s).find(a=>a===i)??Object.keys(s).find(a=>vs.base(a)===vs.base(i))??i;return n===void 0?delete s[r]:s[r]=n,Object.keys(s).length===0?void 0:s}static base(e){return e.toLowerCase().split("-")[0]}}function Id(l,e){for(const t of l){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class Zs{static preferencesFor(e){const t=navigator.languages??[],i=this.declaredFor(e);return i?[i,...t]:t}static declaredFor(e){for(let t=e;t;){const i=t.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=t.getRootNode();t=n instanceof ShadowRoot?n.host:void 0}}}class hs{static ISO=/^P(?:(\d+(?:[.,]\d+)?)W)?(?:(\d+(?:[.,]\d+)?)D)?(?:T(?:(\d+(?:[.,]\d+)?)H)?(?:(\d+(?:[.,]\d+)?)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;static seconds(e){const t=e.trim().toUpperCase(),i=hs.ISO.exec(t);if(!i||t==="P"||t.endsWith("T"))return;const[,n,s,r,a,o]=i,c=d=>d===void 0?0:Number(d.replace(",",".")),h=c(n)*604800+c(s)*86400+c(r)*3600+c(a)*60+c(o);return Number.isFinite(h)?h:void 0}static parse(e){let t=e.trim();if(t==="")return;const i=t.slice(-1),n="?~%".includes(i)?i:"";n!==""&&(t=t.slice(0,-1).trim());const s=t.split("/");if(s.length>2)return;const r=s.map(d=>hs.seconds(d));if(r.some(d=>d===void 0))return;const[a,o]=r,c=Math.min(a,o??a),h=Math.max(a,o??a);return{doubt:n,minSeconds:c,maxSeconds:h,chosenSeconds:(c+h)/2}}static isExact(e){const t=hs.parse(e);return t!==void 0&&t.doubt===""&&t.minSeconds===t.maxSeconds}static format(e){const t=Math.max(0,Math.round(e*10)/10),i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=Math.round(t%60*10)/10;return`PT${`${i>0?`${i}H`:""}${n>0?`${n}M`:""}${s>0||i===0&&n===0?`${s}S`:""}`}`}static say(e){const t=Math.round(e*10)/10;if(t<60)return`${t} s`;const i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=Math.round(t%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 At{static MOON_ANGULAR_WIDTH_DEG=.5237;static CANVAS_WIDTH_PX=640;static CANVAS_HEIGHT_PX=360;static angularWidthDeg(e){return 2*Math.atan(e.sizeM/(2*e.distanceM))*180/Math.PI}static inMoons(e){return e/At.MOON_ANGULAR_WIDTH_DEG}static lerpAngular(e,t,i){if(!(!e||!t))return{widthDeg:e.widthDeg+(t.widthDeg-e.widthDeg)*i,heightDeg:e.heightDeg+(t.heightDeg-e.heightDeg)*i}}static sizeMAt(e,t){return 2*e*Math.tan(t*Math.PI/360)}static distanceMAt(e,t){return e/(2*Math.tan(t*Math.PI/360))}}function IE(l,e,t){if(!l||!e)return t<1?l:e;const i=((e.azimuthDeg-l.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((l.azimuthDeg+i*t)%360+360)%360,altitudeDeg:l.altitudeDeg+(e.altitudeDeg-l.altitudeDeg)*t}}function dx(l,e="#39ff14"){return{kind:"oval",bounds:l,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function ux(l,e,t="#39ff14"){return{kind:"polygon",bounds:l,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function _E(l,e="#39ff14"){const{width:t,height:i}=l;return ux(l,[{x:0,y:0},{x:t,y:0},{x:t,y:i},{x:0,y:i}],e)}const RE={oval:dx,polygon:_E};function i1(l,e){return{...RE[e.presetId](l,e.color),transparency:e.transparency,haloScale:e.haloScale,blur:e.blur,brightness:e.brightness}}function DE(l,e,t){const{bounds:i}=l;return e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height}function px(l,e,t){const i=l.bounds.width,n=l.bounds.height;return{...l,bounds:{x:e-i/2,y:t-n/2,width:i,height:n}}}function Ds(l,e,t){return l+(e-l)*t}function n1(l){const e=/^#([0-9a-f]{6})$/i.exec(l);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function kE(l){return`#${l.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function CE(l,e,t){const i=n1(l),n=n1(e);return!i||!n?t<1?l:e:kE([Ds(i[0],n[0],t),Ds(i[1],n[1],t),Ds(i[2],n[2],t)])}function LE(l,e,t){const i={x:Ds(l.bounds.x,e.bounds.x,t),y:Ds(l.bounds.y,e.bounds.y,t),width:Ds(l.bounds.width,e.bounds.width,t),height:Ds(l.bounds.height,e.bounds.height,t)},n=Ds(l.angle,e.angle,t),s=Ds(l.transparency,e.transparency,t),r=Ds(l.haloScale,e.haloScale,t),a=Ds(l.blur??0,e.blur??0,t),o=Ds(l.brightness??0,e.brightness??0,t),c=CE(l.color,e.color,t),h=At.lerpAngular(l.angular,e.angular,t),d=IE(l.aim,e.aim,t);return l.kind==="polygon"&&e.kind==="polygon"&&l.points.length===e.points.length?{...l,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:o,color:c,angular:h,aim:d,points:l.points.map((u,p)=>({x:Ds(u.x,e.points[p].x,t),y:Ds(u.y,e.points[p].y,t)}))}:{...t<1?l:e,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:o,color:c,angular:h,aim:d}}class Ia{static DEFAULT_COLOR="#e8e6df";static complete(e,t=[]){const i=new Map;return e.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 o=`timeline.keyframes.${s}.shapes.${a}.shape`,c=Ia.completed(r,i.get(r.sourceId),o,t);return i.set(r.sourceId,c),{sourceId:r.sourceId,shape:c}})}))}static thin(e,t){const i=new Map,n=new Set;return e.map((s,r)=>({t:s.t,shapes:s.shapes.map(a=>{const o=i.get(a.sourceId);if(i.set(a.sourceId,a.shape),!o)return{sourceId:a.sourceId,shape:a.shape};const c=Ia.thinned(a.shape,o);if(t){const h=c;t(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:c}})}))}static thinned(e,t){const i=t,n={};for(const[s,r]of Object.entries(e))(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&&(e.aim&&(n.aim=e.aim),e.angular&&(n.angular=e.angular)),n}static completed(e,t,i,n){const s=e.shape??{},r=t??Ia.firstAppearance(s,i,n),a={...r};s.bounds&&t&&(t.aim||t.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 o=s.kind??r.kind??"oval",c={...a,...s,kind:o};if(o==="polygon"&&!c.points){n.push({kind:"defaulted",path:`${i}.points`,expected:"rectangle"});const{width:h,height:d}=c.bounds;return{...c,points:[{x:0,y:0},{x:h,y:0},{x:h,y:d},{x:0,y:d}]}}return c}static firstAppearance(e,t,i){return e.kind||i.push({kind:"defaulted",path:`${t}.kind`,expected:'"oval"'}),e.color||i.push({kind:"defaulted",path:`${t}.color`,expected:`"${Ia.DEFAULT_COLOR}"`}),!e.bounds&&!e.aim&&i.push({kind:"unplaced",path:t}),!e.bounds&&!e.angular&&i.push({kind:"unsized",path:t}),{kind:e.kind??"oval",bounds:{...Ia.NEUTRAL_BOUNDS},color:Ia.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:At.CANVAS_WIDTH_PX/2,y:At.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Yf{keyframes=[];order=[];groups=[];span=0;addKeyframe(e,t){const i=this.findInsertIndex(e);if(this.keyframes[i]?.t===e){const n=new Set(t.map(s=>s.sourceId));this.keyframes[i]={t:e,shapes:[...this.keyframes[i].shapes.filter(s=>!n.has(s.sourceId)),...t]}}else this.keyframes.splice(i,0,{t:e,shapes:[...t]});for(const n of t)this.order.includes(n.sourceId)||this.order.push(n.sourceId)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getKeyframeAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t];return i?.t===e?i:void 0}getShapeAt(e,t){return this.getKeyframeAt(e)?.shapes.find(i=>i.sourceId===t)?.shape}getLatestShapeAt(e,t){let i=this.findInsertIndex(e);for(this.keyframes[i]?.t!==e&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return n.shape}}getInterpolatedShapeAt(e,t){const i=this.findShapeAtOrBefore(e,t);if(i?.t===e)return i.shape;const n=this.findShapeAtOrAfter(e,t);return i?n?LE(i.shape,n.shape,(e-i.t)/(n.t-i.t)):i.shape:n?.shape}findShapeAtOrBefore(e,t){let i=this.findInsertIndex(e);for(this.keyframes[i]?.t!==e&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}findShapeAtOrAfter(e,t){for(let i=this.findInsertIndex(e);i<this.keyframes.length;i++){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}hitTest(e,t,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(e,s[r]);if(a&&DE(a,t,i))return{sourceId:s[r],shape:a}}}removeSource(e){for(let t=this.keyframes.length-1;t>=0;t--){const i=this.keyframes[t].shapes.filter(n=>n.sourceId!==e);i.length===0?this.keyframes.splice(t,1):i.length!==this.keyframes[t].shapes.length&&(this.keyframes[t]={t:this.keyframes[t].t,shapes:i})}this.order=this.order.filter(t=>t!==e),this.removeFromGroup(e)}removeShapeAt(e,t){const i=this.findInsertIndex(e),n=this.keyframes[i];if(n?.t!==e)return;const s=n.shapes.filter(r=>r.sourceId!==t);s.length===0?this.keyframes.splice(i,1):s.length!==n.shapes.length&&(this.keyframes[i]={t:e,shapes:s})}group(e){if(!(e.length<2)){for(const t of e)this.removeFromGroup(t);this.groups.push([...e])}}ungroup(e){const t=this.groups.findIndex(i=>i.includes(e));t!==-1&&this.groups.splice(t,1)}groupMembers(e){return this.groups.find(t=>t.includes(e))}removeFromGroup(e){const t=this.groups.findIndex(n=>n.includes(e));if(t===-1)return;const i=this.groups[t].filter(n=>n!==e);i.length<2?this.groups.splice(t,1):this.groups[t]=i}bringToFront(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.push(e))}sendToBack(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.unshift(e))}get duration(){const e=this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t;return Math.max(e,this.span)}get hasSpan(){return this.span>0}setSpan(e){this.span=Math.max(0,e)}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return this.span>0?{keyframes:this.keyframes,order:this.order,groups:this.groups,span:this.span}:{keyframes:this.keyframes,order:this.order,groups:this.groups}}static fromJSON(e,t){const i=new Yf;for(const n of Ia.complete(e.keyframes??[],t))i.addKeyframe(n.t,n.shapes);if(e.span!==void 0&&e.span>0&&(i.span=e.span),e.order){const n=i.order.filter(s=>!e.order.includes(s));i.order=[...e.order,...n]}return e.groups&&(i.groups=e.groups.map(n=>n.filter(s=>i.order.includes(s))).filter(n=>n.length>=2)),i}}function OE(l,e,t){return Math.max(e,Math.min(t,l))}function PE(l,e,t){const i=((e-l)%360+540)%360-180;return((l+i*t)%360+360)%360}function ql(l,e,t){return l+(e-l)*t}function NE(l,e,t){return{lat:l.lat===void 0||e.lat===void 0?void 0:ql(l.lat,e.lat,t),lng:l.lng===void 0||e.lng===void 0?void 0:ql(l.lng,e.lng,t),elevationM:ql(l.elevationM,e.elevationM,t),headingDeg:l.headingDeg===void 0||e.headingDeg===void 0?void 0:PE(l.headingDeg,e.headingDeg,t),pitchDeg:ql(l.pitchDeg,e.pitchDeg,t),rollDeg:ql(l.rollDeg??0,e.rollDeg??0,t),fovDeg:ql(l.fovDeg,e.fovDeg,t),fNumber:l.fNumber,focusDistanceM:l.focusDistanceM,filter:l.filter}}class Zn{static at(e,t,i,n,s){const r=e[i],o=e[i+1]-r;if(o<=0)return t[i];const c=Zn.tangent(e,t,i,s),h=Zn.tangent(e,t,i+1,s),d=(n-r)/o,u=d*d,p=u*d;return(2*p-3*u+1)*t[i]+(p-2*u+d)*o*c+(-2*p+3*u)*t[i+1]+(p-u)*o*h}static SETTLE_MS=120;static ARRIVAL=.5;static gaze(e,t,i,n){const s=e[i],a=e[i+1]-s;if(a<=0)return t[i];const o=h=>h+1<t.length?t[h+1]===t[h]:!0,c=t[i+1]!==t[i];if(c&&o(i+1)){const h=Zn.tangent(e,t,i,!0),d=Zn.ARRIVAL*(t[i+1]-t[i])/a;return Zn.hermite(t[i],h,t[i+1],d,a,(n-s)/a)}return!c&&i>0&&t[i-1]!==t[i]?t[i]+Zn.settle(e,t,i,n-s,a):Zn.at(e,t,i,n,!0)}static settle(e,t,i,n,s){const r=e[i]-e[i-1];if(r<=0||n<=0)return 0;const a=Zn.ARRIVAL*(t[i]-t[i-1])/r,o=Math.min(Zn.SETTLE_MS,.4*r),c=Number.isFinite(s)?(1-Math.min(1,n/s))**2:1;return a*n*Math.exp(-n/o)*c}static hermite(e,t,i,n,s,r){const a=r*r,o=a*r;return(2*o-3*a+1)*e+(o-2*a+r)*s*t+(-2*o+3*a)*i+(o-a)*s*n}static BRAKE_S=.8;static paced(e,t,i,n){if(!i&&!n)return e;const s=t>0?Math.min(.5,Zn.BRAKE_S/t):.5;if(i&&n){const a=1/(1-s);return e<=s?a*e*e/(2*s):e>=1-s?1-a*(1-e)*(1-e)/(2*s):a*(e-s/2)}const r=a=>{const o=1/(1-s/2);if(a<=1-s)return o*a;const c=a-(1-s);return o*(1-s)+o*(c-c*c/(2*s))};return n?r(e):1-r(1-e)}static tangent(e,t,i,n){const s=e.length-1,r=p=>(t[p+1]-t[p])/(e[p+1]-e[p]||1);if(i===0)return n?0:r(0);if(i===s)return n?0:r(s-1);const a=r(i-1),o=r(i);if(a*o<=0)return 0;const c=e[i]-e[i-1],h=e[i+1]-e[i],d=2*h+c,u=h+2*c;return(d+u)/(d/a+u/o)}}class _d{keyframes=[];addKeyframe(e,t){const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,pose:t}:this.keyframes.splice(i,0,{t:e,pose:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getLatestPoseAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].pose:void 0}getInterpolatedPoseAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.pose;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return n?.pose;if(!n)return this.settledAfterEnd(t-1,e);const s=NE(i.pose,n.pose,OE((e-i.t)/(n.t-i.t),0,1));return this.humanly(t-1,e,s)}settledAfterEnd(e,t){const i=this.keyframes[e];if(e<1)return i.pose;const n=this.keyframes[e-1],s=[n.t,i.t],r=(h,d)=>h===void 0||d===void 0?0:Zn.settle(s,[h,d],1,t-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,o=i.pose.headingDeg===void 0||a===void 0?i.pose.headingDeg:((i.pose.headingDeg+r(0,a))%360+360)%360,c=i.pose.pitchDeg+r(n.pose.pitchDeg,i.pose.pitchDeg);return o===i.pose.headingDeg&&c===i.pose.pitchDeg?i.pose:{...i.pose,headingDeg:o,pitchDeg:c}}humanly(e,t,i){const n=Math.max(0,e-1),s=Math.min(this.keyframes.length-1,e+2),r=this.keyframes.slice(n,s+1),a=e-n,o=r.map(b=>b.t),c=(b,M)=>{const S=r.map(E=>b(E.pose));if(!S.some(E=>E===void 0))return Zn.at(o,S,a,t,M)},h=b=>{const M=r.map(S=>b(S.pose));if(!M.some(S=>S===void 0))return Zn.gaze(o,M,a,t)},d=r.map(b=>b.pose.headingDeg);let u;if(d.every(b=>b!==void 0)){const b=[d[0]];for(let M=1;M<d.length;M++)b.push(b[M-1]+((d[M]-d[M-1])%360+540)%360-180);u=(Zn.gaze(o,b,a,t)%360+360)%360}const p=this.keyframes[e],f=this.keyframes[e+1],m=(b,M)=>b.lat===M.lat&&b.lng===M.lng&&b.elevationM===M.elevationM,v=!m(p.pose,f.pose),g=v&&e>0&&m(this.keyframes[e-1].pose,p.pose),y=v&&e+2<this.keyframes.length&&m(f.pose,this.keyframes[e+2].pose);let w;if(g||y){const b=Zn.paced((t-p.t)/(f.t-p.t),(f.t-p.t)/1e3,g,y),M=(S,E)=>S===void 0||E===void 0?void 0:S+(E-S)*b;w={lat:M(p.pose.lat,f.pose.lat),lng:M(p.pose.lng,f.pose.lng),elevationM:M(p.pose.elevationM,f.pose.elevationM)}}return{...i,lat:w?w.lat:c(b=>b.lat,!1)??i.lat,lng:w?w.lng:c(b=>b.lng,!1)??i.lng,elevationM:w?w.elevationM:c(b=>b.elevationM,!1)??i.elevationM,headingDeg:u??i.headingDeg,pitchDeg:h(b=>b.pitchDeg)??i.pitchDeg,rollDeg:c(b=>b.rollDeg??0,!0)??i.rollDeg,fovDeg:c(b=>b.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(e){const t=new _d;for(const i of e.keyframes)t.addKeyframe(i.t,i.pose);return t}}class so{static MAX_CHANGE_PER_S=.05;points;followed;constructor(e){let t="none",i=0;this.points=e.map(({t:n,weather:s})=>(s.precipitationType!=="none"&&(t=s.precipitationType,i=s.precipitationIntensity),{t:n,lastFalling:t,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(so.follow(this.followed[n-1],s.intensity,r.intensity,(r.t-s.t)/1e3,(r.t-s.t)/1e3))}}at(e){if(this.points.length===0||e<this.points[0].t)return;let t=this.points.length-1;for(;t>0&&this.points[t].t>e;)t--;const i=this.points[t],n=this.points[t+1],s=n?so.follow(this.followed[t],i.intensity,n.intensity,(n.t-i.t)/1e3,(e-i.t)/1e3):so.follow(this.followed[t],i.intensity,i.intensity,1,(e-i.t)/1e3);return{type:so.typeBetween(i,n,e,s),intensity:s,character:so.characterBetween(i,n,e)}}static characterBetween(e,t,i){return e.type==="none"?t&&t.type!=="none"?t.intensity:e.lastFallingIntensity:!t||t.type==="none"?e.intensity:e.intensity+(t.intensity-e.intensity)*(i-e.t)/(t.t-e.t||1)}static typeBetween(e,t,i,n){return e.type==="none"?t&&t.type!=="none"&&i>e.t?t.type:n>0?e.lastFalling:"none":t&&t.type==="none"&&n<=0?"none":e.type}static follow(e,t,i,n,s){const r=so.MAX_CHANGE_PER_S,a=n>0?(i-t)/n:0,o=d=>t+a*Math.min(Math.max(d,0),n);let c=e,h=0;for(let d=0;d<8&&h<s;d++){const u=o(h)-c;if(Math.abs(u)<1e-9){const w=h<n?a:0;if(Math.abs(w)<=r){const M=h<n?Math.min(s,n):s;c=o(M),h=M;continue}const b=Math.min(s,n);c+=Math.sign(w)*r*(b-h),h=b;continue}const p=Math.sign(u),f=h<n?a:0,m=r-p*f,v=m>0?h+Math.abs(u)/m:1/0,g=h<n?n:1/0,y=Math.min(s,v,g);c+=p*r*(y-h),h=y,y===v&&(c=o(h))}return Math.min(1,Math.max(0,c))}}const zv=1e3,kp=.65,fx=.05,qf={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function xo(l){if(l.cloudLayers!==void 0)return l.cloudLayers;const e=[],t=l.lowerCloudCover??l.cloudCover;return t>0&&e.push({id:"lower",type:"cumulus",baseM:l.cloudBaseM??zv,thicknessM:650,coverage:t,sizeM:1400,density:1,darkness:l.cloudDarkness}),(l.highCloudCover??0)>0&&e.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:l.highCloudCover,sizeM:2200,density:.35,darkness:l.cloudDarkness,iceCrystalAlignment:l.iceCrystalAlignment}),e}function Ii(l,e,t){return l+(e-l)*t}function Bv(l,e,t){const i=((e-l)%360+540)%360-180;return((l+i*t)%360+360)%360}function FE(l,e,t){return Math.max(e,Math.min(t,l))}function UE(l=[],e=[],t){if(!(!l.length&&!e.length))return[...new Set([...l.map(i=>i.id),...e.map(i=>i.id)])].map(i=>{const n=l.find(o=>o.id===i),s=e.find(o=>o.id===i),r=n??{...s,density:0},a=s??{...n,density:0};return{...r,eastM:Ii(r.eastM,a.eastM,t),northM:Ii(r.northM,a.northM,t),baseM:Ii(r.baseM,a.baseM,t),thicknessM:Ii(r.thicknessM,a.thicknessM,t),widthM:Ii(r.widthM,a.widthM,t),depthM:Ii(r.depthM,a.depthM,t),rotationDeg:Bv(r.rotationDeg,a.rotationDeg,t),density:Ii(r.density,a.density,t),darkness:Ii(r.darkness??0,a.darkness??0,t)}})}function zE(l,e,t){if(l.cloudLayers===void 0&&e.cloudLayers===void 0)return;const i=xo(l),n=xo(e);return t>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const a=i.find(d=>d.id===r),o=n.find(d=>d.id===r),c=a??{...o,coverage:0},h=o??{...a,coverage:0};return{...c,instances:UE(a?.instances,o?.instances,t),baseM:Ii(c.baseM,h.baseM,t),thicknessM:Ii(c.thicknessM,h.thicknessM,t),coverage:Ii(c.coverage,h.coverage,t),sizeM:Ii(c.sizeM,h.sizeM,t),density:Ii(c.density,h.density,t),darkness:Ii(c.darkness??l.cloudDarkness,h.darkness??e.cloudDarkness,t),iceCrystalAlignment:c.iceCrystalAlignment===void 0||h.iceCrystalAlignment===void 0?void 0:Ii(c.iceCrystalAlignment,h.iceCrystalAlignment,t),windSpeed:c.windSpeed===void 0&&h.windSpeed===void 0?void 0:Ii(c.windSpeed??l.windSpeed,h.windSpeed??e.windSpeed,t),windDirectionDeg:c.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:Bv(c.windDirectionDeg??l.windDirectionDeg,h.windDirectionDeg??e.windDirectionDeg,t)}})}function BE(l,e,t){return{cloudLayers:zE(l,e,t),cloudCover:Ii(l.cloudCover,e.cloudCover,t),cloudDarkness:Ii(l.cloudDarkness,e.cloudDarkness,t),highCloudCover:l.highCloudCover===void 0||e.highCloudCover===void 0?void 0:Ii(l.highCloudCover,e.highCloudCover,t),iceCrystalAlignment:l.iceCrystalAlignment===void 0||e.iceCrystalAlignment===void 0?void 0:Ii(l.iceCrystalAlignment,e.iceCrystalAlignment,t),rareIceCrystals:l.rareIceCrystals===void 0||e.rareIceCrystals===void 0?void 0:Ii(l.rareIceCrystals,e.rareIceCrystals,t),lowerCloudCover:l.lowerCloudCover===void 0||e.lowerCloudCover===void 0?void 0:Ii(l.lowerCloudCover,e.lowerCloudCover,t),cloudBaseM:l.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:Ii(l.cloudBaseM,e.cloudBaseM,t),relativeHumidity:l.relativeHumidity===void 0||e.relativeHumidity===void 0?void 0:Ii(l.relativeHumidity,e.relativeHumidity,t),precipitationType:t<1?l.precipitationType:e.precipitationType,precipitationIntensity:Ii(l.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:Bv(l.windDirectionDeg,e.windDirectionDeg,t),windSpeed:Ii(l.windSpeed,e.windSpeed,t),storm:t<1?l.storm:e.storm}}class Rd{keyframes=[];ramp;addKeyframe(e,t){this.ramp=void 0;const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,weather:t}:this.keyframes.splice(i,0,{t:e,weather:t})}clear(){this.ramp=void 0,this.keyframes.length=0}removeKeyframeAt(e){this.ramp=void 0;const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getLatestWeatherAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].weather:void 0}getInterpolatedWeatherAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.weather;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];return i?n?BE(i.weather,n.weather,FE((e-i.t)/(n.t-i.t),0,1)):i.weather:n?.weather}getActualWeatherAt(e){const t=this.getInterpolatedWeatherAt(e);if(!t)return;const i=(this.ramp??=new so(this.keyframes)).at(e);if(!i)return t;const{type:n,intensity:s,character:r}=i,a=r>0?Math.min(1,s/r):n==="none"?0:1;return{...t,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(e){const t=new Rd;for(const i of e.keyframes)t.addKeyframe(i.t,{...qf,...i.weather});return t}}class Dd{keyframes=[];addKeyframe(e,t){const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,sound:t}:this.keyframes.splice(i,0,{t:e,sound:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}getLatestSoundAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].sound:void 0}getInterpolatedSoundAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.sound;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return n?.sound;if(!n)return i.sound;const s=(e-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(e){const t=new Dd;for(const i of e.keyframes)t.addKeyframe(i.t,i.sound);return t}lerp(e,t,i){return{kind:i<1?e.kind:t.kind,volume:e.volume+(t.volume-e.volume)*i,pitchHz:e.pitchHz+(t.pitchHz-e.pitchHz)*i,src:i<1?e.src:t.src}}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}}const HE=["none","hum","whistle","rumble","crackle"],GE=100,VE={kind:"none",volume:0,pitchHz:GE};class _c{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 _c.BODIES.map(e=>({id:e.id,category:"dslr",name:e.name,projection:"rectilinear",frame:{widthMm:e.widthMm,heightMm:e.heightMm,focalLengthMm:_c.DEFAULT_FOCAL_MM,focalRangeMm:_c.FOCAL_RANGE_MM},fNumber:8,fNumberRange:{min:1.4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/8e3,max:3600},years:{from:e.year},apertureBlades:7,detailUm:e.pixelUm,medium:{kind:"sensor",iso:100}}))}static names(){return Object.fromEntries(_c.BODIES.map(e=>[e.id,e.name]))}}class br{static DEFAULT_EYEPIECE_MM=26;static DEFAULT_APPARENT_FIELD_DEG=52;static FIELD_STOP_MM=2*br.DEFAULT_EYEPIECE_MM*Math.tan(br.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 e=br.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}}:{}})),t=br.FIELD_STOP_MM,i=br.TELESCOPES.map(n=>({id:n.id,category:"telescope",name:n.name,projection:"rectilinear",frame:{widthMm:t*16/9,heightMm:t,focalLengthMm:n.focalLengthMm,focalRangeMm:{minMm:n.focalLengthMm*br.RANGE.min,maxMm:n.focalLengthMm*br.RANGE.max}},visualAid:{apertureMm:n.apertureMm,eyepieceFocalMm:br.DEFAULT_EYEPIECE_MM},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}}));return[...e,...i]}static names(){return Object.fromEntries(br.instruments().map(e=>[e.id,e.name]))}}const Qh=[{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",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",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",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:"slr-35mm-zoom",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"}},{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"}},..._c.instruments(),...br.instruments()];class hi{static get default(){return Qh[0]}static byId(e){return Qh.find(t=>t.id===e)??this.default}static UNAIDED_FIELD_DEG=60;static UNAIDED_ASPECT=16/9;static fieldOfViewDeg(e){const t=e.frame;return t?2*Math.atan(t.heightMm/(2*t.focalLengthMm))*180/Math.PI:e.visualAid?.trueFieldDeg??hi.UNAIDED_FIELD_DEG}static aspectOf(e){const t=e.frame;return t?t.widthMm/t.heightMm:hi.UNAIDED_ASPECT}static frameWidthPx(e,t){return Math.round(t*hi.aspectOf(e))}static CATEGORIES=["eye","camera","dslr","phone","binoculars","telescope"];static unavailability(e,t){const i=e.years;if(!(t===void 0||!i)){if(t<i.from)return{kind:"before",from:i.from};if(i.to!==void 0&&t>i.to)return{kind:"after",to:i.to}}}static availableAt(e){return e===void 0?Qh:Qh.filter(t=>!t.years||e>=t.years.from&&(t.years.to===void 0||e<=t.years.to))}static fieldOfViewDegAt(e,t){const i=e.frame;if(!(!i||t<=0))return 2*Math.atan(i.heightMm/(2*t))*180/Math.PI}static focalLengthMmFor(e,t){const i=e.frame;if(!(!i||t<=0||t>=180))return i.heightMm/(2*Math.tan(t*Math.PI/360))}static bladesShowing(e,t){const i=t??e.fNumber;if(i===void 0||e.apertureBlades===void 0)return 0;const n=e.fNumberRange;return!n||n.max<=n.min?1:Math.max(0,Math.min(1,(i-n.min)/(n.max-n.min)))}static starPointsOf(e){const t=e.apertureBlades;return t===void 0||t<3?0:t%2===0?t:t*2}}class Nl extends Error{}class jf{constructor(e){this.name=e}validate(e){return!0}}class mx extends jf{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new Nl(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new Nl(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class gn{name;min;max;duration;subUnit;validator;constructor(e,t,i,n,s=new mx(e,t,i)){this.name=e,this.min=t,this.max=i,this.subUnit=n,this.duration=n?(n.max-n.min+1)*n.duration:1,this.validator=s}validate(e){return this.validator.validate(e)}[Symbol.iterator](){let e=this.min;return{next:()=>{const t={done:e>this.max,value:e};return e++,t}}}}class gx{millisecond;second;minute;hour;day;month;year}class WE extends gx{}class vx extends WE{millisecond=new gn("millisecond",0,999,void 0);second=new gn("second",0,59,this.millisecond);minute=new gn("minute",0,59,this.second);hour=new gn("hour",0,23,this.minute);day=new gn("day",1,31,this.hour);month=new gn("month",1,12,this.day);year=new gn("year",0,9999,this.month)}const ot=new vx;class $E extends mx{constructor(e=1,t=12){super("month",e,t)}}class aa{static instance=new aa;render(e){return e.value.toString()}}class es{unit;#e;constructor(e,t){this.unit=t,this.value=typeof e=="number"?e:e.value}get value(){return this.#e}set value(e){this.unit.validate(e),this.#e=e}get duration(){return this.value*this.unit.duration}#t(e){if(this.constructor.name!==e.constructor.name)throw new jf(`${this.unit.name} "${this.toString()}" cannot be compared with ${e.unit?.name} "${e.toString()}"`)}compare(e){return this.#t(e),this.value-e.value}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}previous(e=this.unit){const t=this.value-1;return new this.constructor(t,e)}next(e=this.unit){const t=this.value+1;return new this.constructor(t,e)}toString(e=aa.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class wi{static#e=new Map;static register(e,t){wi.#e.set(e,t)}static get(e){const t=wi.#e.get(e);if(!t)throw new Nl(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class Cp extends es{constructor(e=new Date().getFullYear(),t=ot.year){super(e,t)}static fromString(e,t=wi.get(Cp)){return new Cp(t.parse(e))}}class fa extends aa{static default=new fa("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class Lp extends es{constructor(e=new Date().getMonth()+1,t=ot.month){super(e,t)}static fromString(e,t=wi.get(Lp)){return new Lp(t.parse(e))}toString(e=fa.default){return super.toString(e)}}class Op extends es{constructor(e=new Date().getDate(),t=ot.day){super(e,t)}static fromString(e,t=wi.get(Op)){const i=t.parse(e);return new Op(i)}toString(e=fa.default){return super.toString(e)}}class Pp extends es{constructor(e=new Date().getHours(),t=ot.hour){super(e,t)}static fromString(e,t=wi.get(Pp)){return new Pp(t.parse(e))}toString(e=fa.default){return super.toString(e)}}class Np extends es{constructor(e=new Date().getMinutes(),t=ot.minute){super(e,t)}static fromString(e,t=wi.get(Np)){return new Np(t.parse(e))}toString(e=fa.default){return super.toString(e)}}class Fp extends es{constructor(e=new Date().getSeconds(),t=ot.second){super(e,t)}static fromString(e,t=wi.get(Fp)){return new Fp(t.parse(e),ot.second)}toString(e=fa.default){return super.toString(e)}}class $l extends es{static renderer=new fa("0",3);constructor(e,t=ot.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=$l.renderer){return super.toString(e)}}class KE{render(e){return e.toString()}}class XE extends KE{render(e){const t=e.value,i=Math.abs(t),n=Math.floor(i/60),s=i%60;if(n===0&&s===0)return"Z";{const r=t<0?"-":"+",a=n.toString().padStart(2,"0"),o=s>0?":"+s.toString().padEnd(2,"0"):"";return r+a+o}}}class ah{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=wi.get(ah),i=void 0){const n=t.parse(e,i);return new ah(n)}toString(e=new XE){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class qn{static timeshift(e,t){return e+(qn.isDaylight(t)?60:0)}static isDaylight(e){const{year:t,month:i,day:n}=e,s=e.hour??12;if(![t,i,n].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=qn.rule(t);if(!r)return!1;const a=qn.rank(i,n,s);return a>=qn.rank(r.start.month,r.start.day,2)&&a<qn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:qn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:qn.sunday(e,3,2)},end:{month:11,day:qn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:qn.sunday(e,4,1)},end:t}:e===1975?{start:{month:2,day:23},end:t}:e===1974?{start:{month:1,day:6},end:t}:{start:{month:4,day:qn.sunday(e,4,-1)},end:t}}static sunday(e,t,i){const n=new Date(Date.UTC(2e3,t-1,1));n.setUTCFullYear(e);const s=1+(7-n.getUTCDay())%7;if(i>0)return s+7*(i-1);const r=[31,qn.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let a=s;for(;a+7<=r;)a+=7;return a}static isLeap(e){return e%4===0&&(e%100!==0||e%400===0)}static rank(e,t,i){return(e*100+t)*100+i}}const YE={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},qE={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},jE={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},ZE={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},JE={name:"PT",timeshift:l=>qn.timeshift(-480,l),title:"Pacific Time (US)"},QE={name:"MT",timeshift:l=>qn.timeshift(-420,l),title:"Mountain Time (US)"},eA={name:"CT",timeshift:l=>qn.timeshift(-360,l),title:"Central Time (US)"},tA={name:"ET",timeshift:l=>qn.timeshift(-300,l),title:"Eastern Time (US)"},iA={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},nA={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},sA={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},rA={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},aA={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},oA={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},lA={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},cA={name:"Z",timeshift:"Z",title:"UTC"},hA={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},dA={name:"BST",timeshift:"+01",title:"British Summer Time"},uA={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},pA={name:"CET",timeshift:"+01",title:"Central European Time"},fA={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},mA={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},gA={name:"BJT",timeshift:"+08",title:"Beijing Time"},vA={name:"CST",timeshift:"-06",title:"Central Standard Time"},bA={name:"JST",timeshift:"+09",title:"Japan Standard Time"},yA={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},wA={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},MA={name:"LST",timeshift:"?",title:"Local Sideral Time"},s1=[oA,yA,aA,gA,dA,vA,nA,pA,uA,eA,iA,rA,sA,tA,hA,mA,bA,MA,jE,fA,ZE,QE,wA,qE,YE,JE,lA,cA];class Zf{static instance=new Zf;renderComponent(e,t){return e[t].toString()}renderSecond(e){return this.renderComponent(e,"second")+(e.millisecond?"."+e.millisecond.toString():"")}render(e){const t=[];e.year&&t.push(this.renderComponent(e,"year")),e.month&&t.push(this.renderComponent(e,"month")),e.day&&t.push(this.renderComponent(e,"day"));const i=[];e.hour&&i.push(this.renderComponent(e,"hour")),e.minute&&i.push(this.renderComponent(e,"minute")),e.second&&i.push(this.renderSecond(e));const n=t.join("-"),s=e.timeshift?e.timeshift.toString():"",r=i.join(":")+s;return n+(r.length>0?"T"+r:"")}}class Wo extends Nl{constructor(e="method is abstract"){super(e)}}class Hv{units;constructor(e){this.units=e}newYear(e){throw new Wo}newMonth(e){throw new Wo}newDay(e){throw new Wo}newHour(e){throw new Wo}newMinute(e){throw new Wo}newSecond(e){throw new Wo}}class xA extends gx{millisecond=new gn("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new gn("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new gn("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new gn("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new gn("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new gn("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new gn("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Gv=new xA;class Vv{static instance=new Vv;render(e){const t=tl.toSpec(e);let i="P";const n=t.years;n&&(i+=n.toString()+"Y");const s=t.months;s&&(i+=s.toString(aa.instance)+"MM");const r=t.days;r&&(i+=r.toString(aa.instance)+"D");const a=t.hours;a&&(i+=a.toString(aa.instance)+"H");const o=t.minutes;o&&(i+=o.toString(aa.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(aa.instance)+"S"),i}}class tl extends es{constructor(e={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 e=="number"?e:+(e.years?e.years*ot.year.duration:0)+(e.months?e.months*ot.month.duration:0)+(e.days?e.days*ot.day.duration:0)+(e.hours?e.hours*ot.hour.duration:0)+(e.minutes?e.minutes*ot.minute.duration:0)+(e.seconds?e.seconds*ot.second.duration:0)},new gn("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=EA){let i=typeof e=="number"?e:e.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/ot.year.duration,a=Math.floor(r);a>0&&(s.years=t.newYear(n*a),i-=a*ot.year.duration);const o=i/ot.month.duration,c=Math.floor(o);c>0&&(s.months=t.newMonth(n*c),i-=c*ot.month.duration);const h=i/ot.day.duration,d=Math.floor(h);d>0&&(s.days=t.newDay(n*d),i-=d*ot.day.duration);const u=i/ot.hour.duration,p=Math.floor(u);p>0&&(s.hours=t.newHour(n*p),i-=p*ot.hour.duration);const f=i/ot.minute.duration,m=Math.floor(f);m>0&&(s.minutes=t.newMinute(n*m),i-=m*ot.minute.duration);const v=i/ot.second.duration,g=Math.floor(n*v);return g>0&&(s.seconds=t.newSecond(g)),s}static fromString(e,t=wi.get(tl)){return new tl(t.parse(e))}static between(e,t){const i=t.getTime(),n=e.getTime();return new tl(i-n)}toSpec(){return tl.toSpec(this)}toString(e=Vv.instance){return e.render(this)}}class bx extends Hv{constructor(e){super(e)}newYear(e){return new Cp(e,this.units.year)}newMonth(e){return new Lp(e,this.units.month)}newDay(e){return new Op(e,this.units.day)}newHour(e){return new Pp(e,this.units.hour)}newMinute(e){return new Np(e,this.units.minute)}newSecond(e){return new Fp(e,this.units.second)}newMillisecond(e){return new $l(e,this.units.millisecond)}newTimeshift(e){return new ah(typeof e=="number"?e:e.value)}}const SA=new bx(ot),EA=new bx(Gv);class Sr{#e;#t;#i;#n;#s;#r;#a;#o;constructor(e={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:Sr.timeshiftOf(new Date)}){this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.millisecond=e.millisecond,this.timeshift=e.timeshift}get year(){return this.#e}set year(e){const t=typeof e=="number";this.#e&&t?this.#e.value=e:this.#e=t?this.factory.newYear(e):!e||e.start||e instanceof es?e:this.factory.newYear(e)}get month(){return this.#t}set month(e){const t=typeof e=="number";this.#t&&t?this.#t.value=e:this.#t=t?this.factory.newMonth(e):!e||e.start||e instanceof es?e:this.factory.newMonth(e)}get day(){return this.#i}set day(e){const t=typeof e=="number";this.#i&&t?this.#i.value=e:this.#i=t?this.factory.newDay(e):!e||e.start||e instanceof es?e:this.factory.newDay(e)}get hour(){return this.#n}set hour(e){const t=typeof e=="number";this.#n&&t?this.#n.value=e:this.#n=t?this.factory.newHour(e):!e||e.start||e instanceof es?e:this.factory.newHour(e)}get minute(){return this.#s}set minute(e){const t=typeof e=="number";this.#s&&t?this.#s.value=e:this.#s=t?this.factory.newMinute(e):!e||e.start||e instanceof es?e:this.factory.newMinute(e)}get second(){return this.#r}set second(e){const t=typeof e=="number";this.#r&&t?this.#r.value=e:this.#r=t?this.factory.newSecond(e):!e||e.start||e instanceof es?e:this.factory.newSecond(e)}get millisecond(){return this.#a}set millisecond(e){const t=typeof e=="number";this.#a&&t?this.#a.value=e:this.#a=t||e&&!(e instanceof es)?this.factory.newMillisecond(e):e}get timeshift(){return this.#o}set timeshift(e){const t=typeof e=="number";this.#o&&t?this.#o.value=e:this.#o=t||e&&!(e instanceof ah)?this.factory.newTimeshift(e):e}get factory(){return SA}static fromString(e,t=wi.get(Sr)){const{year:i,month:n,day:s,hour:r,minute:a,second:o,millisecond:c,timeshift:h}=t.parse(e);return new Sr({year:i,month:n,day:s,hour:r,minute:a,second:o,millisecond:c,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new Sr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sr.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Sr.fromString(i)}#l(e){if(this.constructor.name!==e.constructor.name)throw new jf(`Date "${this.toString()}" cannot be compared with "${e.toString()}"`)}compare(e){return this.#l(e),this.getTime()-e.getTime()}delta(e){const t=this.compare(e);return new tl(t)}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(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}clone(){return new Sr(this.toSpec())}previous(){let e=this.clone();try{e.second=this.second.previous()}catch{try{e.minute=this.minute.previous()}catch{try{e.hour=this.hour.previous()}catch{try{e.day=this.day.previous()}catch{try{e.month=this.month.previous()}catch{e.year=this.year.previous()}}}}}return e}next(){let e=this.clone();try{e.second=this.second.next()}catch{try{e.minute=this.minute.next()}catch{try{e.hour=this.hour.next()}catch{try{e.day=this.day.next()}catch{try{e.month=this.month.next()}catch{e.year=this.year.next()}}}}}return e}toString(e=Zf.instance){return e.render(this)}toSpec(){const e={},t=this.year?.toSpec();t&&(e.year=t);const i=this.month?.toSpec();i&&(e.month=i);const n=this.day?.toSpec();n&&(e.day=n);const s=this.hour?.toSpec();s&&(e.hour=s);const r=this.minute?.toSpec();r&&(e.minute=r);const a=this.second?.toSpec();a&&(e.second=a);const o=this.millisecond?.toSpec();o&&(e.millisecond=o);const c=this.timeshift?.toSpec();return c&&(e.timeshift=c),e}toJSON(){return this.toSpec()}}class jd extends aa{static instance=new jd(fa.default);constructor(e){super(),this.valueRenderer=e}render(e){return(this.valueRenderer?this.valueRenderer.render(e):super.render(e))+this.qualifier(e)}qualifier(e){return e.uncertain?e.approximate?"%":"?":e.approximate?"~":""}}class Kl extends es{#e;#t;constructor(e,t){super(e,t),this.#e=e.uncertain||!1,this.#t=e.approximate||!1}get uncertain(){return this.#e}set uncertain(e){return this.#e=e}get approximate(){return this.#t}set approximate(e){return this.#t=e}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(e){return this.isCertainAndPrecise()&&super.isEqual(e)}isBefore(e){return this.isCertainAndPrecise()&&super.isBefore(e)}isAfter(e){return this.isCertainAndPrecise()&&super.isAfter(e)}toString(e=jd.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class yx extends vx{year=new gn("year",-9999,9999,this.month);yearExtended=new gn("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const pp=new yx;class il extends Kl{constructor(e,t=pp.year){super(e,t)}static fromString(e,t=pp.year,i=wi.get(il)){const n=i.parse(e),s=n.value.start;if(e.startsWith("Y")&&(t=pp.yearExtended),s!==void 0){const r=new il(Object.assign({...n},{value:Math.max(s,t.min)})),a=new il(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:a}}else return new il(n,t)}}class wx extends jf{monthValidator=new $E;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class nl extends Kl{constructor(e,t=new gn(ot.month.name,1,24,ot.day,new wx)){super(e,t)}static fromString(e,t=wi.get(nl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=ot.month;const r=new nl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new nl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new nl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class sl extends Kl{constructor(e,t=ot.day){super(e,t)}static fromString(e,t=wi.get(sl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=ot.day;const r=new sl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new sl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new sl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class rl extends Kl{constructor(e,t=ot.hour){super(e,t)}static fromString(e,t=wi.get(rl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=ot.hour;const r=new rl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new rl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new rl(i)}}class al extends Kl{constructor(e,t=ot.minute){super(e,t)}static fromString(e,t=wi.get(al)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.minute,r=new al(Object.assign({...i},{value:Math.max(n,s.min)})),a=new al(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new al(i)}toString(e=jd.instance){return super.toString(e)}}class ol extends Kl{constructor(e,t=ot.second){super(e,t)}static fromString(e,t=wi.get(ol)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.second,r=new ol(Object.assign({...i},{value:Math.max(n,s.min)})),a=new ol(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new ol(i)}}class oh extends ah{static fromString(e,t=wi.get(oh),i=void 0){return new oh(t.parse(e,i))}}class Mx extends Hv{constructor(e){super(e)}newYear(e){return new il(e,this.units.year)}newMonth(e){return new nl(e,this.units.month)}newDay(e){return new sl(e,this.units.day)}newHour(e){return new rl(e,this.units.hour)}newMinute(e){return new al(e,this.units.minute)}newSecond(e){return new ol(e,this.units.second)}newMillisecond(e){return new $l(e,this.units.millisecond)}newTimeshift(e){return new oh(typeof e=="number"?e:e.value)}}const AA=new Mx(pp);new Mx(Gv);class $o extends Sr{constructor(e){super(e)}get factory(){return AA}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(e){return new $o({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sr.timeshiftOf(e)})}static fromString(e,t=wi.get($o)){const i=t.parse(e);return new $o(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return $o.fromString(i)}clone(){return new $o(this.toSpec())}}class Mh extends Kl{uncertainComponent;approximateComponent;constructor(e,t){super(e,t),this.uncertainComponent=e.uncertainComponent||!1,this.approximateComponent=e.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(e){return super.uncertain=e}get approximate(){return super.approximate||this.approximateComponent}set approximate(e){return super.approximate=e}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 TA extends yx{year=new gn("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const sg=new TA;class ll extends Mh{constructor(e,t=sg.year){super(e,t)}static fromString(e,t=sg.year,i=wi.get(ll)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new ll(Object.assign({...n},{value:Math.max(s,t.min)})),a=new ll(Object.assign({...n},{value:Math.min(n.value.end,t.max)})),o={start:r,end:a},c=n.value.estimate;return c&&(o.estimate=c),o}else return new ll(n)}}class IA extends wx{validate(e){switch(e){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(e)}}}class cl extends Mh{constructor(e,t=new gn(ot.month.name,1,41,ot.day,new IA)){super(e,t)}static fromString(e,t=wi.get(cl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.month,r=new cl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new cl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new cl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class hl extends Mh{constructor(e,t=ot.day){super(e,t)}static fromString(e,t=wi.get(hl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.day,r=new hl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new hl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new hl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class dl extends Mh{constructor(e,t=ot.hour){super(e,t)}static fromString(e,t=wi.get(dl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.hour,r=new dl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new dl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new dl(i)}}class ul extends Mh{constructor(e,t=ot.minute){super(e,t)}static fromString(e,t=wi.get(ul)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.minute,r=new ul(Object.assign({...i},{value:Math.max(n,s.min)})),a=new ul(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new ul(i)}}class pl extends Mh{constructor(e,t=ot.second){super(e,t)}static fromString(e,t=ot.second,i=wi.get(pl)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new pl(Object.assign({...n},{value:Math.max(s,t.min)})),a=new pl(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:a}}else return new pl(n,t)}}class xx extends oh{}class _A extends jd{qualifier(){return""}}class ro extends Zf{static instance=new ro;static valueRenderer=new _A(fa.default);static names=["year","month","day","hour","minute","second"];static qualifier(e,t){return e?t?"%":"?":t?"~":""}renderComponent(e,t){const i=e[t],n=ro.names.slice(ro.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),s=ro.qualifier(i.uncertainComponent,i.approximateComponent),r=ro.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(a=>a.approximate));return s+i.toString(ro.valueRenderer)+r}}class Sx extends Hv{constructor(e){super(e)}newYear(e){return new ll(e,this.units.year)}newMonth(e){return new cl(e,this.units.month)}newDay(e){return new hl(e,this.units.day)}newHour(e){return new dl(e,this.units.hour)}newMinute(e){return new ul(e,this.units.minute)}newSecond(e){return new pl(e,this.units.second)}newMillisecond(e){return new $l(e,this.units.millisecond)}newTimeshift(e){return new xx(typeof e=="number"?e:e.value)}}const RA=new Sx(sg);new Sx(Gv);class Ko extends $o{constructor(e){super(e)}toString(e=ro.instance){return super.toString(e)}get year(){return super.year}set year(e){super.year=e}get month(){return super.month}set month(e){super.month=e}get factory(){return RA}static fromDate(e){return new Ko({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sr.timeshiftOf(e)})}static fromString(e,t=wi.get(Ko)){const i=t.parse(e);return new Ko(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Ko.fromString(i)}clone(){return new Ko(this.toSpec())}}class Jf{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new Nl(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Wo(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class Wv extends Jf{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return Wv.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new Nl(`${this.name} cannot be negative`);return super.parse(e)}}class ce{static groupName(...e){return e.reduce((t,i)=>t?t+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(e,...t){return`(?<${e}>${t.join("")})`}static optional(e){return e+"?"}static nonCapturingGroup(...e){return`(?:${e.join("")})`}static optionalGroup(e,...t){return ce.optional(ce.group(e,...t))}static optionalNonCapturingGroup(...e){return ce.optional(ce.nonCapturingGroup(...e))}static numberGroup(e,t,i,n="\\d"){return ce.group(e,`${i||""}[${n}]${t}`)}}const r1="timeshiftValue",a1="shiftHour",o1="shiftMinute";class $v extends Jf{static format(e=""){return s1.map(t=>t.name).join("|")+"|"+ce.nonCapturingGroup(ce.group(e+a1,ce.numberGroup(ce.groupName(e,r1),"{2}","[+-]")),ce.optionalNonCapturingGroup(":?",ce.numberGroup(ce.groupName(e,o1),"{2}",void 0)))}constructor(){super(r1,$v.format())}parse(e,t){let i=0;const n=s1.find(s=>s.name===e);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(t??{})}catch(s){throw new Nl(`The time zone ${e} depends on the date: ${s.message}`)}e=n.timeshift}if(e!=="Z"){const s=this.regexGroups(e),r=s[a1];r&&(i+=parseInt(r,10)*60);const a=s[o1];a&&(i+=parseInt(a,10))}return i}}class Wi extends Wv{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Wi.uncertainGroup+Wi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return ce.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(ce.groupName(Wi.uncertainGroup,e),"?")+this.qualifierFormat(ce.groupName(Wi.approximateGroup,e),"~")+this.qualifierFormat(ce.groupName(Wi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return ce.numberGroup(e,t,i,"\\dX")+this.formatSuffix(e)}getValueAndSign(e){let t=e[this.name],i;return t.charAt(0)==="-"?(i=-1,t=t.substring(1)):i=1,{valueStr:t,sign:i}}parseGroups(e){const{valueStr:t,sign:i}=this.getValueAndSign(e);let n=0,s;for(s=0;s<t.length;s++){const c=t[s];if(c==="X")break;n=n*10+parseInt(c,10)}if(s<t.length){let c=1;for(let u=0;u<t.length-s;u++)c*=10;const h=i*n*c,d=h+c-1;n={start:h,end:d}}else n*=i;const r=e[ce.groupName(Wi.uncertainAndApproximateGroup,this.name)],a=e[ce.groupName(Wi.approximateGroup,this.name)]||r,o=e[ce.groupName(Wi.uncertainGroup,this.name)]||r;return{value:n,approximate:a?!!a:!1,uncertain:o?!!o:!1}}}const l1="yearValue";class Up extends Wi{constructor(){super(l1,Up.format())}static format(e=""){return"Y?"+Wi.numberFormat(ce.groupName(e,l1),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const c1="monthValue";class zp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,c1),"{1,2}",void 0)}constructor(){super(c1,zp.format())}}const h1="dayValue";class Bp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,h1),"{1,2}",void 0)}constructor(){super(h1,Bp.format())}}const d1="hourValue";class Hp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,d1),"{1,2}",void 0)}constructor(){super(d1,Hp.format())}}const u1="minuteValue";class Gp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,u1),"{1,2}",void 0)}constructor(){super(u1,Gp.format())}}const p1="secondValue";class Vp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,p1),"{1,2}",void 0)}constructor(){super(p1,Vp.format())}}class Wp extends $v{}class wn extends Jf{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(e=wn.format()){super("date",e)}static format(e=""){return ce.group(ce.groupName(e,wn.yearGroup),Up.format(e))+ce.optionalNonCapturingGroup("-",ce.group(ce.groupName(e,wn.monthGroup),zp.format(e)),ce.optionalNonCapturingGroup("-",ce.group(ce.groupName(e,wn.dayGroup),Bp.format(e)),ce.optionalNonCapturingGroup("[T ]",ce.group(ce.groupName(e,wn.hourGroup),Hp.format(e)),":",ce.group(ce.groupName(e,wn.minuteGroup),Gp.format(e)),ce.optionalNonCapturingGroup(":",ce.group(ce.groupName(e,wn.secondGroup),Vp.format(e)),ce.optionalNonCapturingGroup("[.,]",ce.group(ce.groupName(e,wn.millisecondGroup),"\\d+"))),ce.optionalGroup(ce.groupName(e,wn.timeshiftGroup),Wp.format(e)))))}parseGroups(e){const t=e[wn.millisecondGroup],i=t?$l.parseFraction(t):void 0,n=e[wn.secondGroup],s=n?ol.fromString(n,new Vp):void 0,r=e[wn.minuteGroup];let a;r&&(a=al.fromString(r,new Gp),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const o=e[wn.hourGroup];let c;o&&(c=rl.fromString(o,new Hp),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[wn.dayGroup];let d;h&&(d=sl.fromString(h,new Bp),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[wn.monthGroup];let p;u&&(p=nl.fromString(u,new zp),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[wn.yearGroup];let m;f&&(m=il.fromString(f,void 0,new Up),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const v=e[wn.timeshiftGroup],g=v?oh.fromString(v,new Wp,{year:m?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:m,month:p,day:d,hour:c,minute:a,second:s,millisecond:i,timeshift:g}}}class ln extends Wi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=ln.uncertainGroup+ln.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(ce.groupName(ln.uncertainGroup,e),"?")+this.qualifierFormat(ce.groupName(ln.approximateGroup,e),"~")+this.qualifierFormat(ce.groupName(ln.uncertainAndApproximateGroup,e),"%")+Wi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[ce.groupName(ln.uncertainAndApproximateGroup,this.name)];return(e[ce.groupName(ln.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[ce.groupName(ln.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const Ih="yearValue",f1="exp",m1="signif";class $p extends ln{constructor(){super(Ih,$p.format())}static format(e=""){return"Y?"+ce.nonCapturingGroup(ce.group(ce.groupName(e,f1),"[-]?\\d+E\\d+")+"|"+ln.numberFormat(ce.groupName(e,Ih),"+","[-]?")+ce.optionalGroup(ce.groupName(e,m1),"S\\d+"))}parseGroups(e){const t=e[f1];if(t){const r=t.indexOf("E"),a=parseInt(t.substring(r+1),10),c=parseInt(t.substring(0,r),10)*Math.pow(10,a);e[Ih]=c.toString()}const i=e[m1],n=e[Ih];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:o}=this.getValueAndSign(e);let c="";for(let h=0;h<a.length;h++)c+=h<r?a.charAt(h):"X";e[Ih]=(o<0?"-":"")+c}const s=super.parseGroups(e);return i&&(s.value.estimate=parseInt(n,10)),s}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const g1="monthValue";class Kp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,g1),"{1,2}",void 0)}constructor(){super(g1,Kp.format())}}const v1="dayValue";class Xp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,v1),"{1,2}",void 0)}constructor(){super(v1,Xp.format())}}const b1="hourValue";class Yp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,b1),"{1,2}",void 0)}constructor(){super(b1,Yp.format())}}const y1="secondValue";class qp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,y1),"{1,2}",void 0)}constructor(){super(y1,qp.format())}}const w1="minuteValue";class jp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,w1),"{1,2}",void 0)}constructor(){super(w1,jp.format())}}class DA extends Wp{}class Mn extends Jf{static yearGroup=wn.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",Mn.format())}static format(e=""){return ce.group(ce.groupName(e,Mn.yearGroup),$p.format(e))+ce.optionalNonCapturingGroup("-",ce.group(ce.groupName(e,Mn.monthGroup),Kp.format(e)),ce.optionalNonCapturingGroup("-",ce.group(ce.groupName(e,Mn.dayGroup),Xp.format(e)),ce.optionalNonCapturingGroup("[T ]",ce.group(ce.groupName(e,Mn.hourGroup),Yp.format(e)),":",ce.group(ce.groupName(e,Mn.minuteGroup),jp.format(e)),ce.optionalNonCapturingGroup(":",ce.group(ce.groupName(e,Mn.secondGroup),qp.format(e)),ce.optionalNonCapturingGroup("[.,]",ce.group(ce.groupName(e,Mn.millisecondGroup),"\\d+"))),ce.optionalGroup(ce.groupName(e,Mn.timeshiftGroup),DA.format(e)))))}parseGroups(e){const t=e[Mn.millisecondGroup],i=t?$l.parseFraction(t):void 0,n=e[Mn.secondGroup];let s;n&&(s=pl.fromString(n,void 0,new qp),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=e[Mn.minuteGroup];let a;r&&(a=ul.fromString(r,new jp),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const o=e[Mn.hourGroup];let c;o&&(c=dl.fromString(o,new Yp),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[Mn.dayGroup];let d;h&&(d=hl.fromString(h,new Xp),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[Mn.monthGroup];let p;u&&(p=cl.fromString(u,new Kp),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[Mn.yearGroup];let m;f&&(m=ll.fromString(f,void 0,new $p),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const v=e[Mn.timeshiftGroup],g=v?xx.fromString(v,new Wp,{year:m?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:m,month:p,day:d,hour:c,minute:a,second:s,millisecond:i,timeshift:g}}}const Ex=["spring","summer","autumn","winter"],rg=21,kA=32,CA=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let LA;function OA(){return LA??=new Mn}function jl(l){return typeof l?.value=="number"?l.value:void 0}function fp(l){const e=l.trim();if(/^\d{1,2}:/.test(e)){const r=CA.exec(e)?.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:e}:void 0}let t;try{t=Ko.fromString(e,OA())}catch{return}const i=jl(t.year),n=jl(t.month),s=n!==void 0&&n>=rg&&n<=kA;if(!(t.timeshift||i!==void 0&&Math.abs(i)>9999)&&!(n!==void 0&&n>12&&!s)&&!(s&&(t.day||t.hour)))return{year:i,month:s?void 0:n,...s?{season:Ex[(n-rg)%4]}:{},day:jl(t.day),hour:jl(t.hour),minute:jl(t.minute),second:jl(t.second),raw:e}}function fl(l){if(l.raw!==void 0)return l.raw;if(l.year===void 0){if(l.hour===void 0)return"";let t=`${String(l.hour).padStart(2,"0")}:${String(l.minute??0).padStart(2,"0")}`;return l.second!==void 0&&(t+=`:${String(l.second).padStart(2,"0")}`),t}let e=String(l.year).padStart(4,"0");return l.season!==void 0?`${e}-${rg+Ex.indexOf(l.season)}`:(l.month===void 0||(e+=`-${String(l.month).padStart(2,"0")}`,l.day===void 0)||(e+=`-${String(l.day).padStart(2,"0")}`,l.hour===void 0)||(e+=`T${String(l.hour).padStart(2,"0")}:${String(l.minute??0).padStart(2,"0")}`,l.second!==void 0&&(e+=`:${String(l.second).padStart(2,"0")}`)),e)}function ag(l){if(l.year!==void 0)return Date.UTC(l.year,(l.month??1)-1,l.day??1,l.hour??0,l.minute??0,l.second??0)}function M1(l){return(((l.day??0)*24+(l.hour??0))*60+(l.minute??0))*6e4+(l.second??0)*1e3}const PA=["year","month","day","hour","minute"],NA=["day","hour","minute"];function x1(l,e){return e.filter(t=>l[t]!==void 0).join(",")}function lh(l){if(l.durationSeconds!==void 0)return l.durationSeconds*1e3;const e=l.durationText===void 0?void 0:hs.parse(l.durationText);if(e)return e.chosenSeconds*1e3;if(!l.time||!l.endTime)return;const t=l.time.year!==void 0&&l.endTime.year!==void 0,i=t?PA:NA,n=x1(l.time,i);if(!(n===""||n!==x1(l.endTime,i)))return t?ag(l.endTime)-ag(l.time):M1(l.endTime)-M1(l.time)}function FA(l){if(l.durationSeconds===void 0&&!(!l.time||!l.endTime))return lh(l)===void 0?"imprecise":void 0}class Qf{constructor(e,t,i,n,s,r,a,o,c=[],h,d,u,p=[],f=[],m=[],v=[]){this.event=e,this.timeline=t,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=a,this.weather=o,this.decor=c,this.weatherSource=h,this.instrumentId=d,this.exposureSeconds=u,this.milestones=p,this.references=f,this.roads=m,this.traces=v}provenance=us.empty();loadIssues=[];account;sources;interpretation;variants=[];skyEvents;frozen;sway;lightPollution;observerMap;iso;metering;lens;vehicle;get observerCount(){return 1+this.decor.filter(e=>e.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return hi.byId(this.instrumentId)}static create(e,t,i){return new Qf({eventType:"sighting",time:e,place:t},new Yf,new _d,new Rd,new Dd,i)}}const UA=0,zA=0;function pt(l,e){const t=l.observerTrack.getInterpolatedPoseAt(e);if(t)return t;const i=l.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:UA,headingDeg:void 0,pitchDeg:zA,fovDeg:hi.fieldOfViewDeg(l.instrument)}}function en(l,e){return l.weatherTrack.getInterpolatedWeatherAt(e)??l.weather??qf}function _h(l,e){return l.weatherTrack.getActualWeatherAt(e)??l.weather??qf}function Kv(l,e){return l.soundTrack.getInterpolatedSoundAt(e)??VE}class kd{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===_i.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,n,s){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",a={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:_i.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new kd(a,new URL("case.json",s).href),c=o.tracks[0];return c.recording=e,c.base={url:n},c.event.id=o.proposedId(c),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(n=>n.kind==="observer");return i.find(n=>n.event.id!==void 0&&t.includes(n.event.id))??i.find(n=>n.recording?.id!==void 0&&t.includes(n.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===_i.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const n=t.find(s=>s.event.id===i)??t.find(s=>s.recording?.id===i);return n?[n]:[]})}addInterview(e,t,i,n,s){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const c={type:"event",eventType:_i.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...s!==void 0?{medium:s}:{},...n!==void 0&&n.length>0?{by:n}:{},...i!==void 0?{title:i}:{}};return this.json.events=[...this.json.events??[],c],this.caseChanged=!0,c}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}keep(e,t,i=!1){e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title)}replaceJson(e){const i=(e.events??[]).filter(s=>s.eventType===_i.SIGHTING_EVENT&&typeof s.url=="string"&&s.url!=="").map(s=>{const r=new URL(s.url,this.url).href,a=s.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(c=>c.url===r);return o?(o.event=s,o.kind=a,o):{event:s,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const n=new Map;for(const[s,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===_i.INTERVIEW_EVENT&&(s.id!==void 0&&o.id===s.id||s.url!==void 0&&o.url===s.url));a&&n.set(a,r)}this.transcripts.clear();for(const[s,r]of n)this.transcripts.set(s,r);this.json=e,this.caseChanged=!0}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))||[...this.transcripts.values()].some(e=>this.transcriptChanged(e))}markExported(e){if(this.caseChanged=!1,!!e){for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording));for(const t of this.transcripts.values())t.loaded=t.text}}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}static ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;eventIds(e){return new Set((this.json.events??[]).filter(t=>t!==e?.event).map(t=>t.id).filter(t=>t!==void 0))}proposedId(e){const t=a=>(a??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,n=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),s=this.eventIds(e);if(n!==""){let a=n;for(let o=2;s.has(a);o++)a=`${n}-${o}`;return a}let r=1;for(;s.has(`sighting-${r}`);)r++;return`sighting-${r}`}ensureId(e){return e.event.id===void 0&&(e.event.id=this.proposedId(e),this.caseChanged=!0),e.event.id}setId(e,t){const i=e.event.id,n=a=>a===i||a===e.recording?.id,s=(this.json.events??[]).filter(a=>a.eventType===_i.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&n(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&n(o)));if(t==="")return i===void 0?"ok":s.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!kd.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of s){const o=[a.interpretationOf].flat().map(c=>n(c)?t:c);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(c=>c!==void 0&&n(c)?t:c);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return _i.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,n){const s=e.recording;if(!s)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),a=new Set(this.tracks.map(D=>D.event.url)),o=new Set(this.tracks.map(D=>D.recording?.id));let c=this.tracks.filter(D=>D.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${c}.json`)||o.has(`${s.id??r}-interpretation-${c}`);)c++;const h=`interpretation-${r}-${c}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:m,description:v,sources:g,tags:y,timeline:w,milestones:b,interpretation:M,...S}=structuredClone(s),E={version:1,id:`${s.id??r}-interpretation-${c}`,...S,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},x={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...n!==void 0&&n.length>0?{by:n}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],x],this.caseChanged=!0;const T={event:x,url:new URL(x.url,this.url).href,kind:"reading",recording:E};return this.tracks.push(T),T}idsOf(e){return[e.event.id,e.recording?.id].filter(t=>t!==void 0)}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(n=>n!==void 0&&t.includes(n)))}addObservation(e,t,i,n){const s=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=n?"interpretation":"observer";let c=`${o}-${a}.json`,h=e.id??a;for(let m=2;s.has(c)||r.has(h);m++)c=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...n?{interpretationOf:this.ensureId(n.account)}:{},...t!==void 0?{time:t}:{},...n?.by&&n.by.length>0?{by:n.by}:{},...i!==void 0?{title:i}:{},url:u+c};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:n?"reading":"observer",recording:d};return this.tracks.push(f),n||(p.id=this.proposedId(f)),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(n=>n!==e.event),this.caseChanged=!0,{deleted:!0})}deleteReading(e){if(e.kind!=="reading")return!1;const t=this.tracks.indexOf(e);return t<0?!1:(this.tracks.splice(t,1),this.json.events=(this.json.events??[]).filter(i=>i!==e.event),this.caseChanged=!0,!0)}files(e=!0,t=!1){const i=this.url.replace(/[^/]*$/,""),n=o=>o.startsWith(i)?o.slice(i.length):o,s=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:n(o.url),content:JSON.stringify(o.recording,null,2)+`
334
+ `;class Wc extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Wc.TAG)||customElements.define(Wc.TAG,Wc)}subject;messages=ng;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;freeze;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=TE;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.freeze=e("freeze"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.freeze.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=e==="en"?ng:await gE(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.freeze.checked;this.linkField.value=t?Jr.frozenLink(e.link(),"0.150.2"):e.link(),this.fitLink();const n=`<script type="module" src="${t?Jr.frozen(e.module,"0.150.2"):Jr.current(e.module,import.meta.url,rh.home())}"><\/script>
335
+ ${e.element()}`;this.embedMarkup.value=n,this.codeEditor&&(this.codeEditor.text=n)}applyMessages(){const e=this.messages,t=(i,n)=>{this.shadow.getElementById(i).textContent=n};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("freeze-label",e.freeze.replace("{version}","0.150.2")),this.freeze.parentElement.title=e.freezeHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=ae(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([0,1]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages.embed),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages.copied,window.setTimeout(()=>this.copyButton.textContent=this.messages.copy,1500)}catch{t.select()}}}class vs{constructor(e){this.preferences=e}read(e){if(e===void 0||typeof e=="string")return e===""?void 0:e;for(const i of this.preferences){const n=e[i]??e[vs.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>vs.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(vs.base(i)))return n;return Object.values(e).find(i=>i)??void 0}write(e,t,i){const n=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return n;const s={...e},r=Object.keys(s).find(a=>a===i)??Object.keys(s).find(a=>vs.base(a)===vs.base(i))??i;return n===void 0?delete s[r]:s[r]=n,Object.keys(s).length===0?void 0:s}static base(e){return e.toLowerCase().split("-")[0]}}function Id(l,e){for(const t of l){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class Zs{static preferencesFor(e){const t=navigator.languages??[],i=this.declaredFor(e);return i?[i,...t]:t}static declaredFor(e){for(let t=e;t;){const i=t.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=t.getRootNode();t=n instanceof ShadowRoot?n.host:void 0}}}class hs{static ISO=/^P(?:(\d+(?:[.,]\d+)?)W)?(?:(\d+(?:[.,]\d+)?)D)?(?:T(?:(\d+(?:[.,]\d+)?)H)?(?:(\d+(?:[.,]\d+)?)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;static seconds(e){const t=e.trim().toUpperCase(),i=hs.ISO.exec(t);if(!i||t==="P"||t.endsWith("T"))return;const[,n,s,r,a,o]=i,c=d=>d===void 0?0:Number(d.replace(",",".")),h=c(n)*604800+c(s)*86400+c(r)*3600+c(a)*60+c(o);return Number.isFinite(h)?h:void 0}static parse(e){let t=e.trim();if(t==="")return;const i=t.slice(-1),n="?~%".includes(i)?i:"";n!==""&&(t=t.slice(0,-1).trim());const s=t.split("/");if(s.length>2)return;const r=s.map(d=>hs.seconds(d));if(r.some(d=>d===void 0))return;const[a,o]=r,c=Math.min(a,o??a),h=Math.max(a,o??a);return{doubt:n,minSeconds:c,maxSeconds:h,chosenSeconds:(c+h)/2}}static isExact(e){const t=hs.parse(e);return t!==void 0&&t.doubt===""&&t.minSeconds===t.maxSeconds}static format(e){const t=Math.max(0,Math.round(e*10)/10),i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=Math.round(t%60*10)/10;return`PT${`${i>0?`${i}H`:""}${n>0?`${n}M`:""}${s>0||i===0&&n===0?`${s}S`:""}`}`}static say(e){const t=Math.round(e*10)/10;if(t<60)return`${t} s`;const i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=Math.round(t%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 Tt{static MOON_ANGULAR_WIDTH_DEG=.5237;static CANVAS_WIDTH_PX=640;static CANVAS_HEIGHT_PX=360;static angularWidthDeg(e){return 2*Math.atan(e.sizeM/(2*e.distanceM))*180/Math.PI}static inMoons(e){return e/Tt.MOON_ANGULAR_WIDTH_DEG}static lerpAngular(e,t,i){if(!(!e||!t))return{widthDeg:e.widthDeg+(t.widthDeg-e.widthDeg)*i,heightDeg:e.heightDeg+(t.heightDeg-e.heightDeg)*i}}static sizeMAt(e,t){return 2*e*Math.tan(t*Math.PI/360)}static distanceMAt(e,t){return e/(2*Math.tan(t*Math.PI/360))}}function IE(l,e,t){if(!l||!e)return t<1?l:e;const i=((e.azimuthDeg-l.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((l.azimuthDeg+i*t)%360+360)%360,altitudeDeg:l.altitudeDeg+(e.altitudeDeg-l.altitudeDeg)*t}}function dx(l,e="#39ff14"){return{kind:"oval",bounds:l,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function ux(l,e,t="#39ff14"){return{kind:"polygon",bounds:l,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function _E(l,e="#39ff14"){const{width:t,height:i}=l;return ux(l,[{x:0,y:0},{x:t,y:0},{x:t,y:i},{x:0,y:i}],e)}const RE={oval:dx,polygon:_E};function i1(l,e){return{...RE[e.presetId](l,e.color),transparency:e.transparency,haloScale:e.haloScale,blur:e.blur,brightness:e.brightness}}function DE(l,e,t){const{bounds:i}=l;return e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height}function px(l,e,t){const i=l.bounds.width,n=l.bounds.height;return{...l,bounds:{x:e-i/2,y:t-n/2,width:i,height:n}}}function Ds(l,e,t){return l+(e-l)*t}function n1(l){const e=/^#([0-9a-f]{6})$/i.exec(l);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function kE(l){return`#${l.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function CE(l,e,t){const i=n1(l),n=n1(e);return!i||!n?t<1?l:e:kE([Ds(i[0],n[0],t),Ds(i[1],n[1],t),Ds(i[2],n[2],t)])}function LE(l,e,t){const i={x:Ds(l.bounds.x,e.bounds.x,t),y:Ds(l.bounds.y,e.bounds.y,t),width:Ds(l.bounds.width,e.bounds.width,t),height:Ds(l.bounds.height,e.bounds.height,t)},n=Ds(l.angle,e.angle,t),s=Ds(l.transparency,e.transparency,t),r=Ds(l.haloScale,e.haloScale,t),a=Ds(l.blur??0,e.blur??0,t),o=Ds(l.brightness??0,e.brightness??0,t),c=CE(l.color,e.color,t),h=Tt.lerpAngular(l.angular,e.angular,t),d=IE(l.aim,e.aim,t);return l.kind==="polygon"&&e.kind==="polygon"&&l.points.length===e.points.length?{...l,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:o,color:c,angular:h,aim:d,points:l.points.map((u,p)=>({x:Ds(u.x,e.points[p].x,t),y:Ds(u.y,e.points[p].y,t)}))}:{...t<1?l:e,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:o,color:c,angular:h,aim:d}}class Ia{static DEFAULT_COLOR="#e8e6df";static complete(e,t=[]){const i=new Map;return e.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 o=`timeline.keyframes.${s}.shapes.${a}.shape`,c=Ia.completed(r,i.get(r.sourceId),o,t);return i.set(r.sourceId,c),{sourceId:r.sourceId,shape:c}})}))}static thin(e,t){const i=new Map,n=new Set;return e.map((s,r)=>({t:s.t,shapes:s.shapes.map(a=>{const o=i.get(a.sourceId);if(i.set(a.sourceId,a.shape),!o)return{sourceId:a.sourceId,shape:a.shape};const c=Ia.thinned(a.shape,o);if(t){const h=c;t(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:c}})}))}static thinned(e,t){const i=t,n={};for(const[s,r]of Object.entries(e))(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&&(e.aim&&(n.aim=e.aim),e.angular&&(n.angular=e.angular)),n}static completed(e,t,i,n){const s=e.shape??{},r=t??Ia.firstAppearance(s,i,n),a={...r};s.bounds&&t&&(t.aim||t.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 o=s.kind??r.kind??"oval",c={...a,...s,kind:o};if(o==="polygon"&&!c.points){n.push({kind:"defaulted",path:`${i}.points`,expected:"rectangle"});const{width:h,height:d}=c.bounds;return{...c,points:[{x:0,y:0},{x:h,y:0},{x:h,y:d},{x:0,y:d}]}}return c}static firstAppearance(e,t,i){return e.kind||i.push({kind:"defaulted",path:`${t}.kind`,expected:'"oval"'}),e.color||i.push({kind:"defaulted",path:`${t}.color`,expected:`"${Ia.DEFAULT_COLOR}"`}),!e.bounds&&!e.aim&&i.push({kind:"unplaced",path:t}),!e.bounds&&!e.angular&&i.push({kind:"unsized",path:t}),{kind:e.kind??"oval",bounds:{...Ia.NEUTRAL_BOUNDS},color:Ia.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:Tt.CANVAS_WIDTH_PX/2,y:Tt.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Yf{keyframes=[];order=[];groups=[];span=0;addKeyframe(e,t){const i=this.findInsertIndex(e);if(this.keyframes[i]?.t===e){const n=new Set(t.map(s=>s.sourceId));this.keyframes[i]={t:e,shapes:[...this.keyframes[i].shapes.filter(s=>!n.has(s.sourceId)),...t]}}else this.keyframes.splice(i,0,{t:e,shapes:[...t]});for(const n of t)this.order.includes(n.sourceId)||this.order.push(n.sourceId)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getKeyframeAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t];return i?.t===e?i:void 0}getShapeAt(e,t){return this.getKeyframeAt(e)?.shapes.find(i=>i.sourceId===t)?.shape}getLatestShapeAt(e,t){let i=this.findInsertIndex(e);for(this.keyframes[i]?.t!==e&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return n.shape}}getInterpolatedShapeAt(e,t){const i=this.findShapeAtOrBefore(e,t);if(i?.t===e)return i.shape;const n=this.findShapeAtOrAfter(e,t);return i?n?LE(i.shape,n.shape,(e-i.t)/(n.t-i.t)):i.shape:n?.shape}findShapeAtOrBefore(e,t){let i=this.findInsertIndex(e);for(this.keyframes[i]?.t!==e&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}findShapeAtOrAfter(e,t){for(let i=this.findInsertIndex(e);i<this.keyframes.length;i++){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}hitTest(e,t,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(e,s[r]);if(a&&DE(a,t,i))return{sourceId:s[r],shape:a}}}removeSource(e){for(let t=this.keyframes.length-1;t>=0;t--){const i=this.keyframes[t].shapes.filter(n=>n.sourceId!==e);i.length===0?this.keyframes.splice(t,1):i.length!==this.keyframes[t].shapes.length&&(this.keyframes[t]={t:this.keyframes[t].t,shapes:i})}this.order=this.order.filter(t=>t!==e),this.removeFromGroup(e)}removeShapeAt(e,t){const i=this.findInsertIndex(e),n=this.keyframes[i];if(n?.t!==e)return;const s=n.shapes.filter(r=>r.sourceId!==t);s.length===0?this.keyframes.splice(i,1):s.length!==n.shapes.length&&(this.keyframes[i]={t:e,shapes:s})}group(e){if(!(e.length<2)){for(const t of e)this.removeFromGroup(t);this.groups.push([...e])}}ungroup(e){const t=this.groups.findIndex(i=>i.includes(e));t!==-1&&this.groups.splice(t,1)}groupMembers(e){return this.groups.find(t=>t.includes(e))}removeFromGroup(e){const t=this.groups.findIndex(n=>n.includes(e));if(t===-1)return;const i=this.groups[t].filter(n=>n!==e);i.length<2?this.groups.splice(t,1):this.groups[t]=i}bringToFront(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.push(e))}sendToBack(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.unshift(e))}get duration(){const e=this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t;return Math.max(e,this.span)}get hasSpan(){return this.span>0}setSpan(e){this.span=Math.max(0,e)}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return this.span>0?{keyframes:this.keyframes,order:this.order,groups:this.groups,span:this.span}:{keyframes:this.keyframes,order:this.order,groups:this.groups}}static fromJSON(e,t){const i=new Yf;for(const n of Ia.complete(e.keyframes??[],t))i.addKeyframe(n.t,n.shapes);if(e.span!==void 0&&e.span>0&&(i.span=e.span),e.order){const n=i.order.filter(s=>!e.order.includes(s));i.order=[...e.order,...n]}return e.groups&&(i.groups=e.groups.map(n=>n.filter(s=>i.order.includes(s))).filter(n=>n.length>=2)),i}}function OE(l,e,t){return Math.max(e,Math.min(t,l))}function PE(l,e,t){const i=((e-l)%360+540)%360-180;return((l+i*t)%360+360)%360}function ql(l,e,t){return l+(e-l)*t}function NE(l,e,t){return{lat:l.lat===void 0||e.lat===void 0?void 0:ql(l.lat,e.lat,t),lng:l.lng===void 0||e.lng===void 0?void 0:ql(l.lng,e.lng,t),elevationM:ql(l.elevationM,e.elevationM,t),headingDeg:l.headingDeg===void 0||e.headingDeg===void 0?void 0:PE(l.headingDeg,e.headingDeg,t),pitchDeg:ql(l.pitchDeg,e.pitchDeg,t),rollDeg:ql(l.rollDeg??0,e.rollDeg??0,t),fovDeg:ql(l.fovDeg,e.fovDeg,t),fNumber:l.fNumber,focusDistanceM:l.focusDistanceM,filter:l.filter}}class Zn{static at(e,t,i,n,s){const r=e[i],o=e[i+1]-r;if(o<=0)return t[i];const c=Zn.tangent(e,t,i,s),h=Zn.tangent(e,t,i+1,s),d=(n-r)/o,u=d*d,p=u*d;return(2*p-3*u+1)*t[i]+(p-2*u+d)*o*c+(-2*p+3*u)*t[i+1]+(p-u)*o*h}static SETTLE_MS=120;static ARRIVAL=.5;static gaze(e,t,i,n){const s=e[i],a=e[i+1]-s;if(a<=0)return t[i];const o=h=>h+1<t.length?t[h+1]===t[h]:!0,c=t[i+1]!==t[i];if(c&&o(i+1)){const h=Zn.tangent(e,t,i,!0),d=Zn.ARRIVAL*(t[i+1]-t[i])/a;return Zn.hermite(t[i],h,t[i+1],d,a,(n-s)/a)}return!c&&i>0&&t[i-1]!==t[i]?t[i]+Zn.settle(e,t,i,n-s,a):Zn.at(e,t,i,n,!0)}static settle(e,t,i,n,s){const r=e[i]-e[i-1];if(r<=0||n<=0)return 0;const a=Zn.ARRIVAL*(t[i]-t[i-1])/r,o=Math.min(Zn.SETTLE_MS,.4*r),c=Number.isFinite(s)?(1-Math.min(1,n/s))**2:1;return a*n*Math.exp(-n/o)*c}static hermite(e,t,i,n,s,r){const a=r*r,o=a*r;return(2*o-3*a+1)*e+(o-2*a+r)*s*t+(-2*o+3*a)*i+(o-a)*s*n}static BRAKE_S=.8;static paced(e,t,i,n){if(!i&&!n)return e;const s=t>0?Math.min(.5,Zn.BRAKE_S/t):.5;if(i&&n){const a=1/(1-s);return e<=s?a*e*e/(2*s):e>=1-s?1-a*(1-e)*(1-e)/(2*s):a*(e-s/2)}const r=a=>{const o=1/(1-s/2);if(a<=1-s)return o*a;const c=a-(1-s);return o*(1-s)+o*(c-c*c/(2*s))};return n?r(e):1-r(1-e)}static tangent(e,t,i,n){const s=e.length-1,r=p=>(t[p+1]-t[p])/(e[p+1]-e[p]||1);if(i===0)return n?0:r(0);if(i===s)return n?0:r(s-1);const a=r(i-1),o=r(i);if(a*o<=0)return 0;const c=e[i]-e[i-1],h=e[i+1]-e[i],d=2*h+c,u=h+2*c;return(d+u)/(d/a+u/o)}}class _d{keyframes=[];addKeyframe(e,t){const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,pose:t}:this.keyframes.splice(i,0,{t:e,pose:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getLatestPoseAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].pose:void 0}getInterpolatedPoseAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.pose;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return n?.pose;if(!n)return this.settledAfterEnd(t-1,e);const s=NE(i.pose,n.pose,OE((e-i.t)/(n.t-i.t),0,1));return this.humanly(t-1,e,s)}settledAfterEnd(e,t){const i=this.keyframes[e];if(e<1)return i.pose;const n=this.keyframes[e-1],s=[n.t,i.t],r=(h,d)=>h===void 0||d===void 0?0:Zn.settle(s,[h,d],1,t-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,o=i.pose.headingDeg===void 0||a===void 0?i.pose.headingDeg:((i.pose.headingDeg+r(0,a))%360+360)%360,c=i.pose.pitchDeg+r(n.pose.pitchDeg,i.pose.pitchDeg);return o===i.pose.headingDeg&&c===i.pose.pitchDeg?i.pose:{...i.pose,headingDeg:o,pitchDeg:c}}humanly(e,t,i){const n=Math.max(0,e-1),s=Math.min(this.keyframes.length-1,e+2),r=this.keyframes.slice(n,s+1),a=e-n,o=r.map(b=>b.t),c=(b,M)=>{const S=r.map(E=>b(E.pose));if(!S.some(E=>E===void 0))return Zn.at(o,S,a,t,M)},h=b=>{const M=r.map(S=>b(S.pose));if(!M.some(S=>S===void 0))return Zn.gaze(o,M,a,t)},d=r.map(b=>b.pose.headingDeg);let u;if(d.every(b=>b!==void 0)){const b=[d[0]];for(let M=1;M<d.length;M++)b.push(b[M-1]+((d[M]-d[M-1])%360+540)%360-180);u=(Zn.gaze(o,b,a,t)%360+360)%360}const p=this.keyframes[e],f=this.keyframes[e+1],m=(b,M)=>b.lat===M.lat&&b.lng===M.lng&&b.elevationM===M.elevationM,v=!m(p.pose,f.pose),g=v&&e>0&&m(this.keyframes[e-1].pose,p.pose),y=v&&e+2<this.keyframes.length&&m(f.pose,this.keyframes[e+2].pose);let w;if(g||y){const b=Zn.paced((t-p.t)/(f.t-p.t),(f.t-p.t)/1e3,g,y),M=(S,E)=>S===void 0||E===void 0?void 0:S+(E-S)*b;w={lat:M(p.pose.lat,f.pose.lat),lng:M(p.pose.lng,f.pose.lng),elevationM:M(p.pose.elevationM,f.pose.elevationM)}}return{...i,lat:w?w.lat:c(b=>b.lat,!1)??i.lat,lng:w?w.lng:c(b=>b.lng,!1)??i.lng,elevationM:w?w.elevationM:c(b=>b.elevationM,!1)??i.elevationM,headingDeg:u??i.headingDeg,pitchDeg:h(b=>b.pitchDeg)??i.pitchDeg,rollDeg:c(b=>b.rollDeg??0,!0)??i.rollDeg,fovDeg:c(b=>b.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(e){const t=new _d;for(const i of e.keyframes)t.addKeyframe(i.t,i.pose);return t}}class so{static MAX_CHANGE_PER_S=.05;points;followed;constructor(e){let t="none",i=0;this.points=e.map(({t:n,weather:s})=>(s.precipitationType!=="none"&&(t=s.precipitationType,i=s.precipitationIntensity),{t:n,lastFalling:t,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(so.follow(this.followed[n-1],s.intensity,r.intensity,(r.t-s.t)/1e3,(r.t-s.t)/1e3))}}at(e){if(this.points.length===0||e<this.points[0].t)return;let t=this.points.length-1;for(;t>0&&this.points[t].t>e;)t--;const i=this.points[t],n=this.points[t+1],s=n?so.follow(this.followed[t],i.intensity,n.intensity,(n.t-i.t)/1e3,(e-i.t)/1e3):so.follow(this.followed[t],i.intensity,i.intensity,1,(e-i.t)/1e3);return{type:so.typeBetween(i,n,e,s),intensity:s,character:so.characterBetween(i,n,e)}}static characterBetween(e,t,i){return e.type==="none"?t&&t.type!=="none"?t.intensity:e.lastFallingIntensity:!t||t.type==="none"?e.intensity:e.intensity+(t.intensity-e.intensity)*(i-e.t)/(t.t-e.t||1)}static typeBetween(e,t,i,n){return e.type==="none"?t&&t.type!=="none"&&i>e.t?t.type:n>0?e.lastFalling:"none":t&&t.type==="none"&&n<=0?"none":e.type}static follow(e,t,i,n,s){const r=so.MAX_CHANGE_PER_S,a=n>0?(i-t)/n:0,o=d=>t+a*Math.min(Math.max(d,0),n);let c=e,h=0;for(let d=0;d<8&&h<s;d++){const u=o(h)-c;if(Math.abs(u)<1e-9){const w=h<n?a:0;if(Math.abs(w)<=r){const M=h<n?Math.min(s,n):s;c=o(M),h=M;continue}const b=Math.min(s,n);c+=Math.sign(w)*r*(b-h),h=b;continue}const p=Math.sign(u),f=h<n?a:0,m=r-p*f,v=m>0?h+Math.abs(u)/m:1/0,g=h<n?n:1/0,y=Math.min(s,v,g);c+=p*r*(y-h),h=y,y===v&&(c=o(h))}return Math.min(1,Math.max(0,c))}}const zv=1e3,kp=.65,fx=.05,qf={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function xo(l){if(l.cloudLayers!==void 0)return l.cloudLayers;const e=[],t=l.lowerCloudCover??l.cloudCover;return t>0&&e.push({id:"lower",type:"cumulus",baseM:l.cloudBaseM??zv,thicknessM:650,coverage:t,sizeM:1400,density:1,darkness:l.cloudDarkness}),(l.highCloudCover??0)>0&&e.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:l.highCloudCover,sizeM:2200,density:.35,darkness:l.cloudDarkness,iceCrystalAlignment:l.iceCrystalAlignment}),e}function Ii(l,e,t){return l+(e-l)*t}function Bv(l,e,t){const i=((e-l)%360+540)%360-180;return((l+i*t)%360+360)%360}function FE(l,e,t){return Math.max(e,Math.min(t,l))}function UE(l=[],e=[],t){if(!(!l.length&&!e.length))return[...new Set([...l.map(i=>i.id),...e.map(i=>i.id)])].map(i=>{const n=l.find(o=>o.id===i),s=e.find(o=>o.id===i),r=n??{...s,density:0},a=s??{...n,density:0};return{...r,eastM:Ii(r.eastM,a.eastM,t),northM:Ii(r.northM,a.northM,t),baseM:Ii(r.baseM,a.baseM,t),thicknessM:Ii(r.thicknessM,a.thicknessM,t),widthM:Ii(r.widthM,a.widthM,t),depthM:Ii(r.depthM,a.depthM,t),rotationDeg:Bv(r.rotationDeg,a.rotationDeg,t),density:Ii(r.density,a.density,t),darkness:Ii(r.darkness??0,a.darkness??0,t)}})}function zE(l,e,t){if(l.cloudLayers===void 0&&e.cloudLayers===void 0)return;const i=xo(l),n=xo(e);return t>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const a=i.find(d=>d.id===r),o=n.find(d=>d.id===r),c=a??{...o,coverage:0},h=o??{...a,coverage:0};return{...c,instances:UE(a?.instances,o?.instances,t),baseM:Ii(c.baseM,h.baseM,t),thicknessM:Ii(c.thicknessM,h.thicknessM,t),coverage:Ii(c.coverage,h.coverage,t),sizeM:Ii(c.sizeM,h.sizeM,t),density:Ii(c.density,h.density,t),darkness:Ii(c.darkness??l.cloudDarkness,h.darkness??e.cloudDarkness,t),iceCrystalAlignment:c.iceCrystalAlignment===void 0||h.iceCrystalAlignment===void 0?void 0:Ii(c.iceCrystalAlignment,h.iceCrystalAlignment,t),windSpeed:c.windSpeed===void 0&&h.windSpeed===void 0?void 0:Ii(c.windSpeed??l.windSpeed,h.windSpeed??e.windSpeed,t),windDirectionDeg:c.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:Bv(c.windDirectionDeg??l.windDirectionDeg,h.windDirectionDeg??e.windDirectionDeg,t)}})}function BE(l,e,t){return{cloudLayers:zE(l,e,t),cloudCover:Ii(l.cloudCover,e.cloudCover,t),cloudDarkness:Ii(l.cloudDarkness,e.cloudDarkness,t),highCloudCover:l.highCloudCover===void 0||e.highCloudCover===void 0?void 0:Ii(l.highCloudCover,e.highCloudCover,t),iceCrystalAlignment:l.iceCrystalAlignment===void 0||e.iceCrystalAlignment===void 0?void 0:Ii(l.iceCrystalAlignment,e.iceCrystalAlignment,t),rareIceCrystals:l.rareIceCrystals===void 0||e.rareIceCrystals===void 0?void 0:Ii(l.rareIceCrystals,e.rareIceCrystals,t),lowerCloudCover:l.lowerCloudCover===void 0||e.lowerCloudCover===void 0?void 0:Ii(l.lowerCloudCover,e.lowerCloudCover,t),cloudBaseM:l.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:Ii(l.cloudBaseM,e.cloudBaseM,t),relativeHumidity:l.relativeHumidity===void 0||e.relativeHumidity===void 0?void 0:Ii(l.relativeHumidity,e.relativeHumidity,t),precipitationType:t<1?l.precipitationType:e.precipitationType,precipitationIntensity:Ii(l.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:Bv(l.windDirectionDeg,e.windDirectionDeg,t),windSpeed:Ii(l.windSpeed,e.windSpeed,t),storm:t<1?l.storm:e.storm}}class Rd{keyframes=[];ramp;addKeyframe(e,t){this.ramp=void 0;const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,weather:t}:this.keyframes.splice(i,0,{t:e,weather:t})}clear(){this.ramp=void 0,this.keyframes.length=0}removeKeyframeAt(e){this.ramp=void 0;const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getLatestWeatherAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].weather:void 0}getInterpolatedWeatherAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.weather;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];return i?n?BE(i.weather,n.weather,FE((e-i.t)/(n.t-i.t),0,1)):i.weather:n?.weather}getActualWeatherAt(e){const t=this.getInterpolatedWeatherAt(e);if(!t)return;const i=(this.ramp??=new so(this.keyframes)).at(e);if(!i)return t;const{type:n,intensity:s,character:r}=i,a=r>0?Math.min(1,s/r):n==="none"?0:1;return{...t,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(e){const t=new Rd;for(const i of e.keyframes)t.addKeyframe(i.t,{...qf,...i.weather});return t}}class Dd{keyframes=[];addKeyframe(e,t){const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,sound:t}:this.keyframes.splice(i,0,{t:e,sound:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}getLatestSoundAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].sound:void 0}getInterpolatedSoundAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.sound;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return n?.sound;if(!n)return i.sound;const s=(e-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(e){const t=new Dd;for(const i of e.keyframes)t.addKeyframe(i.t,i.sound);return t}lerp(e,t,i){return{kind:i<1?e.kind:t.kind,volume:e.volume+(t.volume-e.volume)*i,pitchHz:e.pitchHz+(t.pitchHz-e.pitchHz)*i,src:i<1?e.src:t.src}}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}}const HE=["none","hum","whistle","rumble","crackle"],GE=100,VE={kind:"none",volume:0,pitchHz:GE};class _c{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 _c.BODIES.map(e=>({id:e.id,category:"dslr",name:e.name,projection:"rectilinear",frame:{widthMm:e.widthMm,heightMm:e.heightMm,focalLengthMm:_c.DEFAULT_FOCAL_MM,focalRangeMm:_c.FOCAL_RANGE_MM},fNumber:8,fNumberRange:{min:1.4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/8e3,max:3600},years:{from:e.year},apertureBlades:7,detailUm:e.pixelUm,medium:{kind:"sensor",iso:100}}))}static names(){return Object.fromEntries(_c.BODIES.map(e=>[e.id,e.name]))}}class br{static DEFAULT_EYEPIECE_MM=26;static DEFAULT_APPARENT_FIELD_DEG=52;static FIELD_STOP_MM=2*br.DEFAULT_EYEPIECE_MM*Math.tan(br.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 e=br.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}}:{}})),t=br.FIELD_STOP_MM,i=br.TELESCOPES.map(n=>({id:n.id,category:"telescope",name:n.name,projection:"rectilinear",frame:{widthMm:t*16/9,heightMm:t,focalLengthMm:n.focalLengthMm,focalRangeMm:{minMm:n.focalLengthMm*br.RANGE.min,maxMm:n.focalLengthMm*br.RANGE.max}},visualAid:{apertureMm:n.apertureMm,eyepieceFocalMm:br.DEFAULT_EYEPIECE_MM},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}}));return[...e,...i]}static names(){return Object.fromEntries(br.instruments().map(e=>[e.id,e.name]))}}const Qh=[{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",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",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",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:"slr-35mm-zoom",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"}},{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"}},..._c.instruments(),...br.instruments()];class hi{static get default(){return Qh[0]}static byId(e){return Qh.find(t=>t.id===e)??this.default}static UNAIDED_FIELD_DEG=60;static UNAIDED_ASPECT=16/9;static fieldOfViewDeg(e){const t=e.frame;return t?2*Math.atan(t.heightMm/(2*t.focalLengthMm))*180/Math.PI:e.visualAid?.trueFieldDeg??hi.UNAIDED_FIELD_DEG}static aspectOf(e){const t=e.frame;return t?t.widthMm/t.heightMm:hi.UNAIDED_ASPECT}static frameWidthPx(e,t){return Math.round(t*hi.aspectOf(e))}static CATEGORIES=["eye","camera","dslr","phone","binoculars","telescope"];static unavailability(e,t){const i=e.years;if(!(t===void 0||!i)){if(t<i.from)return{kind:"before",from:i.from};if(i.to!==void 0&&t>i.to)return{kind:"after",to:i.to}}}static availableAt(e){return e===void 0?Qh:Qh.filter(t=>!t.years||e>=t.years.from&&(t.years.to===void 0||e<=t.years.to))}static fieldOfViewDegAt(e,t){const i=e.frame;if(!(!i||t<=0))return 2*Math.atan(i.heightMm/(2*t))*180/Math.PI}static focalLengthMmFor(e,t){const i=e.frame;if(!(!i||t<=0||t>=180))return i.heightMm/(2*Math.tan(t*Math.PI/360))}static bladesShowing(e,t){const i=t??e.fNumber;if(i===void 0||e.apertureBlades===void 0)return 0;const n=e.fNumberRange;return!n||n.max<=n.min?1:Math.max(0,Math.min(1,(i-n.min)/(n.max-n.min)))}static starPointsOf(e){const t=e.apertureBlades;return t===void 0||t<3?0:t%2===0?t:t*2}}class Nl extends Error{}class jf{constructor(e){this.name=e}validate(e){return!0}}class mx extends jf{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new Nl(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new Nl(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class gn{name;min;max;duration;subUnit;validator;constructor(e,t,i,n,s=new mx(e,t,i)){this.name=e,this.min=t,this.max=i,this.subUnit=n,this.duration=n?(n.max-n.min+1)*n.duration:1,this.validator=s}validate(e){return this.validator.validate(e)}[Symbol.iterator](){let e=this.min;return{next:()=>{const t={done:e>this.max,value:e};return e++,t}}}}class gx{millisecond;second;minute;hour;day;month;year}class WE extends gx{}class vx extends WE{millisecond=new gn("millisecond",0,999,void 0);second=new gn("second",0,59,this.millisecond);minute=new gn("minute",0,59,this.second);hour=new gn("hour",0,23,this.minute);day=new gn("day",1,31,this.hour);month=new gn("month",1,12,this.day);year=new gn("year",0,9999,this.month)}const ot=new vx;class $E extends mx{constructor(e=1,t=12){super("month",e,t)}}class aa{static instance=new aa;render(e){return e.value.toString()}}class es{unit;#e;constructor(e,t){this.unit=t,this.value=typeof e=="number"?e:e.value}get value(){return this.#e}set value(e){this.unit.validate(e),this.#e=e}get duration(){return this.value*this.unit.duration}#t(e){if(this.constructor.name!==e.constructor.name)throw new jf(`${this.unit.name} "${this.toString()}" cannot be compared with ${e.unit?.name} "${e.toString()}"`)}compare(e){return this.#t(e),this.value-e.value}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}previous(e=this.unit){const t=this.value-1;return new this.constructor(t,e)}next(e=this.unit){const t=this.value+1;return new this.constructor(t,e)}toString(e=aa.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class wi{static#e=new Map;static register(e,t){wi.#e.set(e,t)}static get(e){const t=wi.#e.get(e);if(!t)throw new Nl(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class Cp extends es{constructor(e=new Date().getFullYear(),t=ot.year){super(e,t)}static fromString(e,t=wi.get(Cp)){return new Cp(t.parse(e))}}class fa extends aa{static default=new fa("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class Lp extends es{constructor(e=new Date().getMonth()+1,t=ot.month){super(e,t)}static fromString(e,t=wi.get(Lp)){return new Lp(t.parse(e))}toString(e=fa.default){return super.toString(e)}}class Op extends es{constructor(e=new Date().getDate(),t=ot.day){super(e,t)}static fromString(e,t=wi.get(Op)){const i=t.parse(e);return new Op(i)}toString(e=fa.default){return super.toString(e)}}class Pp extends es{constructor(e=new Date().getHours(),t=ot.hour){super(e,t)}static fromString(e,t=wi.get(Pp)){return new Pp(t.parse(e))}toString(e=fa.default){return super.toString(e)}}class Np extends es{constructor(e=new Date().getMinutes(),t=ot.minute){super(e,t)}static fromString(e,t=wi.get(Np)){return new Np(t.parse(e))}toString(e=fa.default){return super.toString(e)}}class Fp extends es{constructor(e=new Date().getSeconds(),t=ot.second){super(e,t)}static fromString(e,t=wi.get(Fp)){return new Fp(t.parse(e),ot.second)}toString(e=fa.default){return super.toString(e)}}class $l extends es{static renderer=new fa("0",3);constructor(e,t=ot.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=$l.renderer){return super.toString(e)}}class KE{render(e){return e.toString()}}class XE extends KE{render(e){const t=e.value,i=Math.abs(t),n=Math.floor(i/60),s=i%60;if(n===0&&s===0)return"Z";{const r=t<0?"-":"+",a=n.toString().padStart(2,"0"),o=s>0?":"+s.toString().padEnd(2,"0"):"";return r+a+o}}}class ah{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=wi.get(ah),i=void 0){const n=t.parse(e,i);return new ah(n)}toString(e=new XE){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class qn{static timeshift(e,t){return e+(qn.isDaylight(t)?60:0)}static isDaylight(e){const{year:t,month:i,day:n}=e,s=e.hour??12;if(![t,i,n].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=qn.rule(t);if(!r)return!1;const a=qn.rank(i,n,s);return a>=qn.rank(r.start.month,r.start.day,2)&&a<qn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:qn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:qn.sunday(e,3,2)},end:{month:11,day:qn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:qn.sunday(e,4,1)},end:t}:e===1975?{start:{month:2,day:23},end:t}:e===1974?{start:{month:1,day:6},end:t}:{start:{month:4,day:qn.sunday(e,4,-1)},end:t}}static sunday(e,t,i){const n=new Date(Date.UTC(2e3,t-1,1));n.setUTCFullYear(e);const s=1+(7-n.getUTCDay())%7;if(i>0)return s+7*(i-1);const r=[31,qn.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let a=s;for(;a+7<=r;)a+=7;return a}static isLeap(e){return e%4===0&&(e%100!==0||e%400===0)}static rank(e,t,i){return(e*100+t)*100+i}}const YE={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},qE={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},jE={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},ZE={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},JE={name:"PT",timeshift:l=>qn.timeshift(-480,l),title:"Pacific Time (US)"},QE={name:"MT",timeshift:l=>qn.timeshift(-420,l),title:"Mountain Time (US)"},eA={name:"CT",timeshift:l=>qn.timeshift(-360,l),title:"Central Time (US)"},tA={name:"ET",timeshift:l=>qn.timeshift(-300,l),title:"Eastern Time (US)"},iA={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},nA={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},sA={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},rA={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},aA={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},oA={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},lA={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},cA={name:"Z",timeshift:"Z",title:"UTC"},hA={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},dA={name:"BST",timeshift:"+01",title:"British Summer Time"},uA={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},pA={name:"CET",timeshift:"+01",title:"Central European Time"},fA={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},mA={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},gA={name:"BJT",timeshift:"+08",title:"Beijing Time"},vA={name:"CST",timeshift:"-06",title:"Central Standard Time"},bA={name:"JST",timeshift:"+09",title:"Japan Standard Time"},yA={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},wA={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},MA={name:"LST",timeshift:"?",title:"Local Sideral Time"},s1=[oA,yA,aA,gA,dA,vA,nA,pA,uA,eA,iA,rA,sA,tA,hA,mA,bA,MA,jE,fA,ZE,QE,wA,qE,YE,JE,lA,cA];class Zf{static instance=new Zf;renderComponent(e,t){return e[t].toString()}renderSecond(e){return this.renderComponent(e,"second")+(e.millisecond?"."+e.millisecond.toString():"")}render(e){const t=[];e.year&&t.push(this.renderComponent(e,"year")),e.month&&t.push(this.renderComponent(e,"month")),e.day&&t.push(this.renderComponent(e,"day"));const i=[];e.hour&&i.push(this.renderComponent(e,"hour")),e.minute&&i.push(this.renderComponent(e,"minute")),e.second&&i.push(this.renderSecond(e));const n=t.join("-"),s=e.timeshift?e.timeshift.toString():"",r=i.join(":")+s;return n+(r.length>0?"T"+r:"")}}class Wo extends Nl{constructor(e="method is abstract"){super(e)}}class Hv{units;constructor(e){this.units=e}newYear(e){throw new Wo}newMonth(e){throw new Wo}newDay(e){throw new Wo}newHour(e){throw new Wo}newMinute(e){throw new Wo}newSecond(e){throw new Wo}}class xA extends gx{millisecond=new gn("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new gn("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new gn("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new gn("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new gn("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new gn("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new gn("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Gv=new xA;class Vv{static instance=new Vv;render(e){const t=tl.toSpec(e);let i="P";const n=t.years;n&&(i+=n.toString()+"Y");const s=t.months;s&&(i+=s.toString(aa.instance)+"MM");const r=t.days;r&&(i+=r.toString(aa.instance)+"D");const a=t.hours;a&&(i+=a.toString(aa.instance)+"H");const o=t.minutes;o&&(i+=o.toString(aa.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(aa.instance)+"S"),i}}class tl extends es{constructor(e={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 e=="number"?e:+(e.years?e.years*ot.year.duration:0)+(e.months?e.months*ot.month.duration:0)+(e.days?e.days*ot.day.duration:0)+(e.hours?e.hours*ot.hour.duration:0)+(e.minutes?e.minutes*ot.minute.duration:0)+(e.seconds?e.seconds*ot.second.duration:0)},new gn("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=EA){let i=typeof e=="number"?e:e.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/ot.year.duration,a=Math.floor(r);a>0&&(s.years=t.newYear(n*a),i-=a*ot.year.duration);const o=i/ot.month.duration,c=Math.floor(o);c>0&&(s.months=t.newMonth(n*c),i-=c*ot.month.duration);const h=i/ot.day.duration,d=Math.floor(h);d>0&&(s.days=t.newDay(n*d),i-=d*ot.day.duration);const u=i/ot.hour.duration,p=Math.floor(u);p>0&&(s.hours=t.newHour(n*p),i-=p*ot.hour.duration);const f=i/ot.minute.duration,m=Math.floor(f);m>0&&(s.minutes=t.newMinute(n*m),i-=m*ot.minute.duration);const v=i/ot.second.duration,g=Math.floor(n*v);return g>0&&(s.seconds=t.newSecond(g)),s}static fromString(e,t=wi.get(tl)){return new tl(t.parse(e))}static between(e,t){const i=t.getTime(),n=e.getTime();return new tl(i-n)}toSpec(){return tl.toSpec(this)}toString(e=Vv.instance){return e.render(this)}}class bx extends Hv{constructor(e){super(e)}newYear(e){return new Cp(e,this.units.year)}newMonth(e){return new Lp(e,this.units.month)}newDay(e){return new Op(e,this.units.day)}newHour(e){return new Pp(e,this.units.hour)}newMinute(e){return new Np(e,this.units.minute)}newSecond(e){return new Fp(e,this.units.second)}newMillisecond(e){return new $l(e,this.units.millisecond)}newTimeshift(e){return new ah(typeof e=="number"?e:e.value)}}const SA=new bx(ot),EA=new bx(Gv);class Sr{#e;#t;#i;#n;#s;#r;#a;#o;constructor(e={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:Sr.timeshiftOf(new Date)}){this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.millisecond=e.millisecond,this.timeshift=e.timeshift}get year(){return this.#e}set year(e){const t=typeof e=="number";this.#e&&t?this.#e.value=e:this.#e=t?this.factory.newYear(e):!e||e.start||e instanceof es?e:this.factory.newYear(e)}get month(){return this.#t}set month(e){const t=typeof e=="number";this.#t&&t?this.#t.value=e:this.#t=t?this.factory.newMonth(e):!e||e.start||e instanceof es?e:this.factory.newMonth(e)}get day(){return this.#i}set day(e){const t=typeof e=="number";this.#i&&t?this.#i.value=e:this.#i=t?this.factory.newDay(e):!e||e.start||e instanceof es?e:this.factory.newDay(e)}get hour(){return this.#n}set hour(e){const t=typeof e=="number";this.#n&&t?this.#n.value=e:this.#n=t?this.factory.newHour(e):!e||e.start||e instanceof es?e:this.factory.newHour(e)}get minute(){return this.#s}set minute(e){const t=typeof e=="number";this.#s&&t?this.#s.value=e:this.#s=t?this.factory.newMinute(e):!e||e.start||e instanceof es?e:this.factory.newMinute(e)}get second(){return this.#r}set second(e){const t=typeof e=="number";this.#r&&t?this.#r.value=e:this.#r=t?this.factory.newSecond(e):!e||e.start||e instanceof es?e:this.factory.newSecond(e)}get millisecond(){return this.#a}set millisecond(e){const t=typeof e=="number";this.#a&&t?this.#a.value=e:this.#a=t||e&&!(e instanceof es)?this.factory.newMillisecond(e):e}get timeshift(){return this.#o}set timeshift(e){const t=typeof e=="number";this.#o&&t?this.#o.value=e:this.#o=t||e&&!(e instanceof ah)?this.factory.newTimeshift(e):e}get factory(){return SA}static fromString(e,t=wi.get(Sr)){const{year:i,month:n,day:s,hour:r,minute:a,second:o,millisecond:c,timeshift:h}=t.parse(e);return new Sr({year:i,month:n,day:s,hour:r,minute:a,second:o,millisecond:c,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new Sr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sr.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Sr.fromString(i)}#l(e){if(this.constructor.name!==e.constructor.name)throw new jf(`Date "${this.toString()}" cannot be compared with "${e.toString()}"`)}compare(e){return this.#l(e),this.getTime()-e.getTime()}delta(e){const t=this.compare(e);return new tl(t)}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(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}clone(){return new Sr(this.toSpec())}previous(){let e=this.clone();try{e.second=this.second.previous()}catch{try{e.minute=this.minute.previous()}catch{try{e.hour=this.hour.previous()}catch{try{e.day=this.day.previous()}catch{try{e.month=this.month.previous()}catch{e.year=this.year.previous()}}}}}return e}next(){let e=this.clone();try{e.second=this.second.next()}catch{try{e.minute=this.minute.next()}catch{try{e.hour=this.hour.next()}catch{try{e.day=this.day.next()}catch{try{e.month=this.month.next()}catch{e.year=this.year.next()}}}}}return e}toString(e=Zf.instance){return e.render(this)}toSpec(){const e={},t=this.year?.toSpec();t&&(e.year=t);const i=this.month?.toSpec();i&&(e.month=i);const n=this.day?.toSpec();n&&(e.day=n);const s=this.hour?.toSpec();s&&(e.hour=s);const r=this.minute?.toSpec();r&&(e.minute=r);const a=this.second?.toSpec();a&&(e.second=a);const o=this.millisecond?.toSpec();o&&(e.millisecond=o);const c=this.timeshift?.toSpec();return c&&(e.timeshift=c),e}toJSON(){return this.toSpec()}}class jd extends aa{static instance=new jd(fa.default);constructor(e){super(),this.valueRenderer=e}render(e){return(this.valueRenderer?this.valueRenderer.render(e):super.render(e))+this.qualifier(e)}qualifier(e){return e.uncertain?e.approximate?"%":"?":e.approximate?"~":""}}class Kl extends es{#e;#t;constructor(e,t){super(e,t),this.#e=e.uncertain||!1,this.#t=e.approximate||!1}get uncertain(){return this.#e}set uncertain(e){return this.#e=e}get approximate(){return this.#t}set approximate(e){return this.#t=e}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(e){return this.isCertainAndPrecise()&&super.isEqual(e)}isBefore(e){return this.isCertainAndPrecise()&&super.isBefore(e)}isAfter(e){return this.isCertainAndPrecise()&&super.isAfter(e)}toString(e=jd.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class yx extends vx{year=new gn("year",-9999,9999,this.month);yearExtended=new gn("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const pp=new yx;class il extends Kl{constructor(e,t=pp.year){super(e,t)}static fromString(e,t=pp.year,i=wi.get(il)){const n=i.parse(e),s=n.value.start;if(e.startsWith("Y")&&(t=pp.yearExtended),s!==void 0){const r=new il(Object.assign({...n},{value:Math.max(s,t.min)})),a=new il(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:a}}else return new il(n,t)}}class wx extends jf{monthValidator=new $E;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class nl extends Kl{constructor(e,t=new gn(ot.month.name,1,24,ot.day,new wx)){super(e,t)}static fromString(e,t=wi.get(nl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=ot.month;const r=new nl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new nl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new nl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class sl extends Kl{constructor(e,t=ot.day){super(e,t)}static fromString(e,t=wi.get(sl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=ot.day;const r=new sl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new sl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new sl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class rl extends Kl{constructor(e,t=ot.hour){super(e,t)}static fromString(e,t=wi.get(rl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=ot.hour;const r=new rl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new rl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new rl(i)}}class al extends Kl{constructor(e,t=ot.minute){super(e,t)}static fromString(e,t=wi.get(al)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.minute,r=new al(Object.assign({...i},{value:Math.max(n,s.min)})),a=new al(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new al(i)}toString(e=jd.instance){return super.toString(e)}}class ol extends Kl{constructor(e,t=ot.second){super(e,t)}static fromString(e,t=wi.get(ol)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.second,r=new ol(Object.assign({...i},{value:Math.max(n,s.min)})),a=new ol(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new ol(i)}}class oh extends ah{static fromString(e,t=wi.get(oh),i=void 0){return new oh(t.parse(e,i))}}class Mx extends Hv{constructor(e){super(e)}newYear(e){return new il(e,this.units.year)}newMonth(e){return new nl(e,this.units.month)}newDay(e){return new sl(e,this.units.day)}newHour(e){return new rl(e,this.units.hour)}newMinute(e){return new al(e,this.units.minute)}newSecond(e){return new ol(e,this.units.second)}newMillisecond(e){return new $l(e,this.units.millisecond)}newTimeshift(e){return new oh(typeof e=="number"?e:e.value)}}const AA=new Mx(pp);new Mx(Gv);class $o extends Sr{constructor(e){super(e)}get factory(){return AA}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(e){return new $o({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sr.timeshiftOf(e)})}static fromString(e,t=wi.get($o)){const i=t.parse(e);return new $o(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return $o.fromString(i)}clone(){return new $o(this.toSpec())}}class Mh extends Kl{uncertainComponent;approximateComponent;constructor(e,t){super(e,t),this.uncertainComponent=e.uncertainComponent||!1,this.approximateComponent=e.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(e){return super.uncertain=e}get approximate(){return super.approximate||this.approximateComponent}set approximate(e){return super.approximate=e}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 TA extends yx{year=new gn("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const sg=new TA;class ll extends Mh{constructor(e,t=sg.year){super(e,t)}static fromString(e,t=sg.year,i=wi.get(ll)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new ll(Object.assign({...n},{value:Math.max(s,t.min)})),a=new ll(Object.assign({...n},{value:Math.min(n.value.end,t.max)})),o={start:r,end:a},c=n.value.estimate;return c&&(o.estimate=c),o}else return new ll(n)}}class IA extends wx{validate(e){switch(e){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(e)}}}class cl extends Mh{constructor(e,t=new gn(ot.month.name,1,41,ot.day,new IA)){super(e,t)}static fromString(e,t=wi.get(cl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.month,r=new cl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new cl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new cl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class hl extends Mh{constructor(e,t=ot.day){super(e,t)}static fromString(e,t=wi.get(hl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.day,r=new hl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new hl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new hl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class dl extends Mh{constructor(e,t=ot.hour){super(e,t)}static fromString(e,t=wi.get(dl)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.hour,r=new dl(Object.assign({...i},{value:Math.max(n,s.min)})),a=new dl(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new dl(i)}}class ul extends Mh{constructor(e,t=ot.minute){super(e,t)}static fromString(e,t=wi.get(ul)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=ot.minute,r=new ul(Object.assign({...i},{value:Math.max(n,s.min)})),a=new ul(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new ul(i)}}class pl extends Mh{constructor(e,t=ot.second){super(e,t)}static fromString(e,t=ot.second,i=wi.get(pl)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new pl(Object.assign({...n},{value:Math.max(s,t.min)})),a=new pl(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:a}}else return new pl(n,t)}}class xx extends oh{}class _A extends jd{qualifier(){return""}}class ro extends Zf{static instance=new ro;static valueRenderer=new _A(fa.default);static names=["year","month","day","hour","minute","second"];static qualifier(e,t){return e?t?"%":"?":t?"~":""}renderComponent(e,t){const i=e[t],n=ro.names.slice(ro.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),s=ro.qualifier(i.uncertainComponent,i.approximateComponent),r=ro.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(a=>a.approximate));return s+i.toString(ro.valueRenderer)+r}}class Sx extends Hv{constructor(e){super(e)}newYear(e){return new ll(e,this.units.year)}newMonth(e){return new cl(e,this.units.month)}newDay(e){return new hl(e,this.units.day)}newHour(e){return new dl(e,this.units.hour)}newMinute(e){return new ul(e,this.units.minute)}newSecond(e){return new pl(e,this.units.second)}newMillisecond(e){return new $l(e,this.units.millisecond)}newTimeshift(e){return new xx(typeof e=="number"?e:e.value)}}const RA=new Sx(sg);new Sx(Gv);class Ko extends $o{constructor(e){super(e)}toString(e=ro.instance){return super.toString(e)}get year(){return super.year}set year(e){super.year=e}get month(){return super.month}set month(e){super.month=e}get factory(){return RA}static fromDate(e){return new Ko({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sr.timeshiftOf(e)})}static fromString(e,t=wi.get(Ko)){const i=t.parse(e);return new Ko(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Ko.fromString(i)}clone(){return new Ko(this.toSpec())}}class Jf{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new Nl(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Wo(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class Wv extends Jf{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return Wv.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new Nl(`${this.name} cannot be negative`);return super.parse(e)}}class ce{static groupName(...e){return e.reduce((t,i)=>t?t+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(e,...t){return`(?<${e}>${t.join("")})`}static optional(e){return e+"?"}static nonCapturingGroup(...e){return`(?:${e.join("")})`}static optionalGroup(e,...t){return ce.optional(ce.group(e,...t))}static optionalNonCapturingGroup(...e){return ce.optional(ce.nonCapturingGroup(...e))}static numberGroup(e,t,i,n="\\d"){return ce.group(e,`${i||""}[${n}]${t}`)}}const r1="timeshiftValue",a1="shiftHour",o1="shiftMinute";class $v extends Jf{static format(e=""){return s1.map(t=>t.name).join("|")+"|"+ce.nonCapturingGroup(ce.group(e+a1,ce.numberGroup(ce.groupName(e,r1),"{2}","[+-]")),ce.optionalNonCapturingGroup(":?",ce.numberGroup(ce.groupName(e,o1),"{2}",void 0)))}constructor(){super(r1,$v.format())}parse(e,t){let i=0;const n=s1.find(s=>s.name===e);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(t??{})}catch(s){throw new Nl(`The time zone ${e} depends on the date: ${s.message}`)}e=n.timeshift}if(e!=="Z"){const s=this.regexGroups(e),r=s[a1];r&&(i+=parseInt(r,10)*60);const a=s[o1];a&&(i+=parseInt(a,10))}return i}}class Wi extends Wv{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Wi.uncertainGroup+Wi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return ce.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(ce.groupName(Wi.uncertainGroup,e),"?")+this.qualifierFormat(ce.groupName(Wi.approximateGroup,e),"~")+this.qualifierFormat(ce.groupName(Wi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return ce.numberGroup(e,t,i,"\\dX")+this.formatSuffix(e)}getValueAndSign(e){let t=e[this.name],i;return t.charAt(0)==="-"?(i=-1,t=t.substring(1)):i=1,{valueStr:t,sign:i}}parseGroups(e){const{valueStr:t,sign:i}=this.getValueAndSign(e);let n=0,s;for(s=0;s<t.length;s++){const c=t[s];if(c==="X")break;n=n*10+parseInt(c,10)}if(s<t.length){let c=1;for(let u=0;u<t.length-s;u++)c*=10;const h=i*n*c,d=h+c-1;n={start:h,end:d}}else n*=i;const r=e[ce.groupName(Wi.uncertainAndApproximateGroup,this.name)],a=e[ce.groupName(Wi.approximateGroup,this.name)]||r,o=e[ce.groupName(Wi.uncertainGroup,this.name)]||r;return{value:n,approximate:a?!!a:!1,uncertain:o?!!o:!1}}}const l1="yearValue";class Up extends Wi{constructor(){super(l1,Up.format())}static format(e=""){return"Y?"+Wi.numberFormat(ce.groupName(e,l1),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const c1="monthValue";class zp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,c1),"{1,2}",void 0)}constructor(){super(c1,zp.format())}}const h1="dayValue";class Bp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,h1),"{1,2}",void 0)}constructor(){super(h1,Bp.format())}}const d1="hourValue";class Hp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,d1),"{1,2}",void 0)}constructor(){super(d1,Hp.format())}}const u1="minuteValue";class Gp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,u1),"{1,2}",void 0)}constructor(){super(u1,Gp.format())}}const p1="secondValue";class Vp extends Wi{static format(e=""){return Wi.numberFormat(ce.groupName(e,p1),"{1,2}",void 0)}constructor(){super(p1,Vp.format())}}class Wp extends $v{}class wn extends Jf{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(e=wn.format()){super("date",e)}static format(e=""){return ce.group(ce.groupName(e,wn.yearGroup),Up.format(e))+ce.optionalNonCapturingGroup("-",ce.group(ce.groupName(e,wn.monthGroup),zp.format(e)),ce.optionalNonCapturingGroup("-",ce.group(ce.groupName(e,wn.dayGroup),Bp.format(e)),ce.optionalNonCapturingGroup("[T ]",ce.group(ce.groupName(e,wn.hourGroup),Hp.format(e)),":",ce.group(ce.groupName(e,wn.minuteGroup),Gp.format(e)),ce.optionalNonCapturingGroup(":",ce.group(ce.groupName(e,wn.secondGroup),Vp.format(e)),ce.optionalNonCapturingGroup("[.,]",ce.group(ce.groupName(e,wn.millisecondGroup),"\\d+"))),ce.optionalGroup(ce.groupName(e,wn.timeshiftGroup),Wp.format(e)))))}parseGroups(e){const t=e[wn.millisecondGroup],i=t?$l.parseFraction(t):void 0,n=e[wn.secondGroup],s=n?ol.fromString(n,new Vp):void 0,r=e[wn.minuteGroup];let a;r&&(a=al.fromString(r,new Gp),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const o=e[wn.hourGroup];let c;o&&(c=rl.fromString(o,new Hp),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[wn.dayGroup];let d;h&&(d=sl.fromString(h,new Bp),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[wn.monthGroup];let p;u&&(p=nl.fromString(u,new zp),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[wn.yearGroup];let m;f&&(m=il.fromString(f,void 0,new Up),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const v=e[wn.timeshiftGroup],g=v?oh.fromString(v,new Wp,{year:m?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:m,month:p,day:d,hour:c,minute:a,second:s,millisecond:i,timeshift:g}}}class ln extends Wi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=ln.uncertainGroup+ln.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(ce.groupName(ln.uncertainGroup,e),"?")+this.qualifierFormat(ce.groupName(ln.approximateGroup,e),"~")+this.qualifierFormat(ce.groupName(ln.uncertainAndApproximateGroup,e),"%")+Wi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[ce.groupName(ln.uncertainAndApproximateGroup,this.name)];return(e[ce.groupName(ln.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[ce.groupName(ln.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const Ih="yearValue",f1="exp",m1="signif";class $p extends ln{constructor(){super(Ih,$p.format())}static format(e=""){return"Y?"+ce.nonCapturingGroup(ce.group(ce.groupName(e,f1),"[-]?\\d+E\\d+")+"|"+ln.numberFormat(ce.groupName(e,Ih),"+","[-]?")+ce.optionalGroup(ce.groupName(e,m1),"S\\d+"))}parseGroups(e){const t=e[f1];if(t){const r=t.indexOf("E"),a=parseInt(t.substring(r+1),10),c=parseInt(t.substring(0,r),10)*Math.pow(10,a);e[Ih]=c.toString()}const i=e[m1],n=e[Ih];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:o}=this.getValueAndSign(e);let c="";for(let h=0;h<a.length;h++)c+=h<r?a.charAt(h):"X";e[Ih]=(o<0?"-":"")+c}const s=super.parseGroups(e);return i&&(s.value.estimate=parseInt(n,10)),s}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const g1="monthValue";class Kp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,g1),"{1,2}",void 0)}constructor(){super(g1,Kp.format())}}const v1="dayValue";class Xp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,v1),"{1,2}",void 0)}constructor(){super(v1,Xp.format())}}const b1="hourValue";class Yp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,b1),"{1,2}",void 0)}constructor(){super(b1,Yp.format())}}const y1="secondValue";class qp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,y1),"{1,2}",void 0)}constructor(){super(y1,qp.format())}}const w1="minuteValue";class jp extends ln{static format(e=""){return ln.numberFormat(ce.groupName(e,w1),"{1,2}",void 0)}constructor(){super(w1,jp.format())}}class DA extends Wp{}class Mn extends Jf{static yearGroup=wn.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",Mn.format())}static format(e=""){return ce.group(ce.groupName(e,Mn.yearGroup),$p.format(e))+ce.optionalNonCapturingGroup("-",ce.group(ce.groupName(e,Mn.monthGroup),Kp.format(e)),ce.optionalNonCapturingGroup("-",ce.group(ce.groupName(e,Mn.dayGroup),Xp.format(e)),ce.optionalNonCapturingGroup("[T ]",ce.group(ce.groupName(e,Mn.hourGroup),Yp.format(e)),":",ce.group(ce.groupName(e,Mn.minuteGroup),jp.format(e)),ce.optionalNonCapturingGroup(":",ce.group(ce.groupName(e,Mn.secondGroup),qp.format(e)),ce.optionalNonCapturingGroup("[.,]",ce.group(ce.groupName(e,Mn.millisecondGroup),"\\d+"))),ce.optionalGroup(ce.groupName(e,Mn.timeshiftGroup),DA.format(e)))))}parseGroups(e){const t=e[Mn.millisecondGroup],i=t?$l.parseFraction(t):void 0,n=e[Mn.secondGroup];let s;n&&(s=pl.fromString(n,void 0,new qp),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=e[Mn.minuteGroup];let a;r&&(a=ul.fromString(r,new jp),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const o=e[Mn.hourGroup];let c;o&&(c=dl.fromString(o,new Yp),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[Mn.dayGroup];let d;h&&(d=hl.fromString(h,new Xp),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[Mn.monthGroup];let p;u&&(p=cl.fromString(u,new Kp),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[Mn.yearGroup];let m;f&&(m=ll.fromString(f,void 0,new $p),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const v=e[Mn.timeshiftGroup],g=v?xx.fromString(v,new Wp,{year:m?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:m,month:p,day:d,hour:c,minute:a,second:s,millisecond:i,timeshift:g}}}const Ex=["spring","summer","autumn","winter"],rg=21,kA=32,CA=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let LA;function OA(){return LA??=new Mn}function jl(l){return typeof l?.value=="number"?l.value:void 0}function fp(l){const e=l.trim();if(/^\d{1,2}:/.test(e)){const r=CA.exec(e)?.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:e}:void 0}let t;try{t=Ko.fromString(e,OA())}catch{return}const i=jl(t.year),n=jl(t.month),s=n!==void 0&&n>=rg&&n<=kA;if(!(t.timeshift||i!==void 0&&Math.abs(i)>9999)&&!(n!==void 0&&n>12&&!s)&&!(s&&(t.day||t.hour)))return{year:i,month:s?void 0:n,...s?{season:Ex[(n-rg)%4]}:{},day:jl(t.day),hour:jl(t.hour),minute:jl(t.minute),second:jl(t.second),raw:e}}function fl(l){if(l.raw!==void 0)return l.raw;if(l.year===void 0){if(l.hour===void 0)return"";let t=`${String(l.hour).padStart(2,"0")}:${String(l.minute??0).padStart(2,"0")}`;return l.second!==void 0&&(t+=`:${String(l.second).padStart(2,"0")}`),t}let e=String(l.year).padStart(4,"0");return l.season!==void 0?`${e}-${rg+Ex.indexOf(l.season)}`:(l.month===void 0||(e+=`-${String(l.month).padStart(2,"0")}`,l.day===void 0)||(e+=`-${String(l.day).padStart(2,"0")}`,l.hour===void 0)||(e+=`T${String(l.hour).padStart(2,"0")}:${String(l.minute??0).padStart(2,"0")}`,l.second!==void 0&&(e+=`:${String(l.second).padStart(2,"0")}`)),e)}function ag(l){if(l.year!==void 0)return Date.UTC(l.year,(l.month??1)-1,l.day??1,l.hour??0,l.minute??0,l.second??0)}function M1(l){return(((l.day??0)*24+(l.hour??0))*60+(l.minute??0))*6e4+(l.second??0)*1e3}const PA=["year","month","day","hour","minute"],NA=["day","hour","minute"];function x1(l,e){return e.filter(t=>l[t]!==void 0).join(",")}function lh(l){if(l.durationSeconds!==void 0)return l.durationSeconds*1e3;const e=l.durationText===void 0?void 0:hs.parse(l.durationText);if(e)return e.chosenSeconds*1e3;if(!l.time||!l.endTime)return;const t=l.time.year!==void 0&&l.endTime.year!==void 0,i=t?PA:NA,n=x1(l.time,i);if(!(n===""||n!==x1(l.endTime,i)))return t?ag(l.endTime)-ag(l.time):M1(l.endTime)-M1(l.time)}function FA(l){if(l.durationSeconds===void 0&&!(!l.time||!l.endTime))return lh(l)===void 0?"imprecise":void 0}class Qf{constructor(e,t,i,n,s,r,a,o,c=[],h,d,u,p=[],f=[],m=[],v=[]){this.event=e,this.timeline=t,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=a,this.weather=o,this.decor=c,this.weatherSource=h,this.instrumentId=d,this.exposureSeconds=u,this.milestones=p,this.references=f,this.roads=m,this.traces=v}provenance=us.empty();loadIssues=[];account;sources;interpretation;variants=[];skyEvents;frozen;sway;lightPollution;observerMap;iso;metering;lens;vehicle;get observerCount(){return 1+this.decor.filter(e=>e.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return hi.byId(this.instrumentId)}static create(e,t,i){return new Qf({eventType:"sighting",time:e,place:t},new Yf,new _d,new Rd,new Dd,i)}}const UA=0,zA=0;function pt(l,e){const t=l.observerTrack.getInterpolatedPoseAt(e);if(t)return t;const i=l.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:UA,headingDeg:void 0,pitchDeg:zA,fovDeg:hi.fieldOfViewDeg(l.instrument)}}function en(l,e){return l.weatherTrack.getInterpolatedWeatherAt(e)??l.weather??qf}function _h(l,e){return l.weatherTrack.getActualWeatherAt(e)??l.weather??qf}function Kv(l,e){return l.soundTrack.getInterpolatedSoundAt(e)??VE}class kd{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===_i.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,n,s){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",a={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:_i.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new kd(a,new URL("case.json",s).href),c=o.tracks[0];return c.recording=e,c.base={url:n},c.event.id=o.proposedId(c),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(n=>n.kind==="observer");return i.find(n=>n.event.id!==void 0&&t.includes(n.event.id))??i.find(n=>n.recording?.id!==void 0&&t.includes(n.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===_i.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const n=t.find(s=>s.event.id===i)??t.find(s=>s.recording?.id===i);return n?[n]:[]})}addInterview(e,t,i,n,s){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const c={type:"event",eventType:_i.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...s!==void 0?{medium:s}:{},...n!==void 0&&n.length>0?{by:n}:{},...i!==void 0?{title:i}:{}};return this.json.events=[...this.json.events??[],c],this.caseChanged=!0,c}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}keep(e,t,i=!1){e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title)}replaceJson(e){const i=(e.events??[]).filter(s=>s.eventType===_i.SIGHTING_EVENT&&typeof s.url=="string"&&s.url!=="").map(s=>{const r=new URL(s.url,this.url).href,a=s.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(c=>c.url===r);return o?(o.event=s,o.kind=a,o):{event:s,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const n=new Map;for(const[s,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===_i.INTERVIEW_EVENT&&(s.id!==void 0&&o.id===s.id||s.url!==void 0&&o.url===s.url));a&&n.set(a,r)}this.transcripts.clear();for(const[s,r]of n)this.transcripts.set(s,r);this.json=e,this.caseChanged=!0}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))||[...this.transcripts.values()].some(e=>this.transcriptChanged(e))}markExported(e){if(this.caseChanged=!1,!!e){for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording));for(const t of this.transcripts.values())t.loaded=t.text}}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}static ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;eventIds(e){return new Set((this.json.events??[]).filter(t=>t!==e?.event).map(t=>t.id).filter(t=>t!==void 0))}proposedId(e){const t=a=>(a??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,n=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),s=this.eventIds(e);if(n!==""){let a=n;for(let o=2;s.has(a);o++)a=`${n}-${o}`;return a}let r=1;for(;s.has(`sighting-${r}`);)r++;return`sighting-${r}`}ensureId(e){return e.event.id===void 0&&(e.event.id=this.proposedId(e),this.caseChanged=!0),e.event.id}setId(e,t){const i=e.event.id,n=a=>a===i||a===e.recording?.id,s=(this.json.events??[]).filter(a=>a.eventType===_i.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&n(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&n(o)));if(t==="")return i===void 0?"ok":s.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!kd.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of s){const o=[a.interpretationOf].flat().map(c=>n(c)?t:c);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(c=>c!==void 0&&n(c)?t:c);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return _i.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,n){const s=e.recording;if(!s)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),a=new Set(this.tracks.map(D=>D.event.url)),o=new Set(this.tracks.map(D=>D.recording?.id));let c=this.tracks.filter(D=>D.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${c}.json`)||o.has(`${s.id??r}-interpretation-${c}`);)c++;const h=`interpretation-${r}-${c}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:m,description:v,sources:g,tags:y,timeline:w,milestones:b,interpretation:M,...S}=structuredClone(s),E={version:1,id:`${s.id??r}-interpretation-${c}`,...S,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},x={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...n!==void 0&&n.length>0?{by:n}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],x],this.caseChanged=!0;const T={event:x,url:new URL(x.url,this.url).href,kind:"reading",recording:E};return this.tracks.push(T),T}idsOf(e){return[e.event.id,e.recording?.id].filter(t=>t!==void 0)}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(n=>n!==void 0&&t.includes(n)))}addObservation(e,t,i,n){const s=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=n?"interpretation":"observer";let c=`${o}-${a}.json`,h=e.id??a;for(let m=2;s.has(c)||r.has(h);m++)c=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...n?{interpretationOf:this.ensureId(n.account)}:{},...t!==void 0?{time:t}:{},...n?.by&&n.by.length>0?{by:n.by}:{},...i!==void 0?{title:i}:{},url:u+c};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:n?"reading":"observer",recording:d};return this.tracks.push(f),n||(p.id=this.proposedId(f)),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(n=>n!==e.event),this.caseChanged=!0,{deleted:!0})}deleteReading(e){if(e.kind!=="reading")return!1;const t=this.tracks.indexOf(e);return t<0?!1:(this.tracks.splice(t,1),this.json.events=(this.json.events??[]).filter(i=>i!==e.event),this.caseChanged=!0,!0)}files(e=!0,t=!1){const i=this.url.replace(/[^/]*$/,""),n=o=>o.startsWith(i)?o.slice(i.length):o,s=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:n(o.url),content:JSON.stringify(o.recording,null,2)+`
336
336
  `})),r=decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",a=[...this.transcripts].filter(([o,c])=>e&&o.url!==void 0&&(t||this.transcriptChanged(c))).map(([o,c])=>({path:n(new URL(o.url,this.url).href),content:c.text}));return[{path:r,content:JSON.stringify(this.json,null,2)+`
337
337
  `},...s,...a]}}class Zp{constructor(e,t,i,n){this.button=e,this.onPick=i,this.idOf=n;const s=this.panel=e.ownerDocument.createElement("div");s.id=t,s.className="add-menu",s.setAttribute("popover",""),s.setAttribute("role","menu");const r=`--add-menu-${t}`;e.style.setProperty("anchor-name",r),s.style.setProperty("position-anchor",r),e.setAttribute("popovertarget",t),e.setAttribute("aria-haspopup","menu"),e.after(s)}static CSS=`
338
338
  .add-menu { padding: .3em 0; border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); border-radius: 4px; background: Canvas; color: CanvasText;
@@ -750,7 +750,7 @@ ${JSON.stringify(i)}`),t.push(`The account:
750
750
 
751
751
  ${e.ask}`,"Answer by calling draft_recording."),t.join(`
752
752
 
753
- `)}static imageBlock(e){return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}}}async clientFor(e,t){if(!e)throw new Gs("credential");const i=`${e}\0${t??""}`;if(this.client&&this.clientFor_===i)return this.client;const{default:n}=await ae(async()=>{const{default:s}=await import("./index-DQDuRMiM.js").then(r=>r.i);return{default:s}},[],import.meta.url);return this.client=new n({apiKey:e,...t?{defaultHeaders:{"anthropic-workspace-id":t}}:{},dangerouslyAllowBrowser:!0,maxRetries:1}),this.clientFor_=i,this.client}static read(e){if(e.stop_reason==="refusal")throw new Gs("refused");const t=e.content.find(n=>n.type==="tool_use"&&n.name===Z1.name);if(!t||t.type!=="tool_use")throw new Gs("malformed");const i=t.input;if(typeof i?.recording!="object"||i.recording===null||Array.isArray(i.recording))throw new Gs("malformed");return{recording:i.recording,claims:Array.isArray(i.claims)?i.claims.flatMap(n=>{const{path:s,basis:r,rationale:a}=n??{};return typeof s!="string"||typeof a!="string"?[]:[{path:s,basis:r==="derived"||r==="assumed"?r:"stated",rationale:a}]}):[],gaps:Array.isArray(i.gaps)?i.gaps.filter(n=>typeof n=="string"):[]}}static async diagnose(e,t){if(e instanceof Gs)return e;if(t?.aborted)return new Gs("cancelled",e);const{default:i}=await ae(async()=>{const{default:n}=await import("./index-DQDuRMiM.js").then(s=>s.i);return{default:n}},[],import.meta.url);return e instanceof i.AuthenticationError||e instanceof i.PermissionDeniedError?new Gs("credential",e):e instanceof i.RateLimitError?new Gs("rate-limited",e):e instanceof i.BadRequestError||e instanceof i.NotFoundError?new Gs("rejected",e.message,e):e instanceof i.APIConnectionError?new Gs("unreachable",e):new Gs("malformed",e)}}const hu=[{id:"claude",name:"Claude",credit:"Anthropic",creditUrl:"https://www.anthropic.com/legal/consumer-terms",create:()=>new Wr}],DT=[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async l=>{const{CoverageAssessor:e}=await ae(async()=>{const{CoverageAssessor:t}=await import("./CoverageAssessor-B8gBscye.js");return{CoverageAssessor:t}},[],import.meta.url);return new e().assess(l)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async l=>{const{HynekAssessor:e}=await ae(async()=>{const{HynekAssessor:t}=await import("./HynekAssessor-BopK5jfz.js");return{HynekAssessor:t}},[],import.meta.url);return new e().assess(l)}})}];class kT{constructor(e){this.labels=e}async read(e){const t=[],i=new Set;for(const n of DT){let s;try{s=await n.create().assess(e)}catch{continue}for(const a of s.criteria)a.basis===void 0&&!a.unsupported&&i.add(a.id);const r=s.score===void 0?s.verdict===void 0?"":this.verdictName(n.id,s.verdict):`${Math.round(s.score*100)}%`;r!==""&&t.push({group:"assessment",field:n.id,label:this.labels.assessmentNames[n.id]??n.name,value:r,unit:"",fromSource:!1,about:n.create().about})}return{entries:t,unanswered:i}}verdictName(e,t){return this.labels.assessmentVerdicts[`${e}.${t}`]??t.toUpperCase()}}class qr{static stated(e){return qr.statedIn(e,[])}static apply(e,t,i){const n=structuredClone(e);for(const s of i){const r=s.split("."),a=qr.read(t,r);a!==void 0&&qr.write(n,r,structuredClone(a))}return n}static statedIn(e,t){const i=[];for(const[n,s]of Object.entries(e)){if(s===void 0)continue;const r=[...t,n];qr.isPlainObject(s)?i.push(...qr.statedIn(s,r)):i.push(r.join("."))}return i}static isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static read(e,t){let i=e;for(const n of t){if(!qr.isPlainObject(i))return;i=i[n]}return i}static write(e,t,i){let n=e;for(const s of t.slice(0,-1)){const r=n[s];qr.isPlainObject(r)||(n[s]={}),n=n[s]}n[t[t.length-1]]=i}}const CT={x:At.CANVAS_WIDTH_PX/2,y:At.CANVAS_HEIGHT_PX/2,width:1,height:1};class df{static loadable(e){const t=e.decor?{decor:e.decor.map((n,s)=>df.decor(n,s))}:{},i=e.timeline?.keyframes;return i?{...e,...t,timeline:{...e.timeline,keyframes:i.map(n=>({t:n.t??0,shapes:(n.shapes??[]).map(s=>({sourceId:s.sourceId,shape:df.shape(s.shape)}))}))}}:{...e,...t}}static decor(e,t){const i=e.kind??"vehicle";return{...am(i)?{windows:c2(i)}:{},...i==="building"?{floors:dh}:{},...e,id:e.id??`decor-${t+1}`,kind:i,eastM:e.eastM??0,northM:e.northM??0}}static shape(e){const t=e?.kind==="polygon"?"polygon":"oval";return{...t==="polygon"?{points:[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}]}:{},...e,kind:t,bounds:{...CT},color:typeof e?.color=="string"?e.color:"#e8e6df",angle:0,transparency:0,haloScale:0,selected:!1}}}class m2{static sync(e,t,i,n,s){if(e.querySelector(".param-description")?.remove(),t===void 0){e.removeAttribute("data-describing");return}const r=document.createElement("div");r.className="param-description";const a=document.createElement("div");a.className="param-description-head";const o=document.createElement("span");o.className="param-nest-label",o.textContent=i;const c=document.createElement("button");c.type="button",c.className="param-description-close",c.textContent="×",c.title=n,c.setAttribute("aria-label",n),c.addEventListener("click",s),a.append(o,c);const h=document.createElement("p");h.className="param-description-text",h.textContent=t,r.append(a,h),r.addEventListener("keydown",d=>{d.key==="Escape"&&s()}),e.setAttribute("data-describing",""),e.append(r),c.focus({preventScroll:!0})}static CSS=`
753
+ `)}static imageBlock(e){return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}}}async clientFor(e,t){if(!e)throw new Gs("credential");const i=`${e}\0${t??""}`;if(this.client&&this.clientFor_===i)return this.client;const{default:n}=await ae(async()=>{const{default:s}=await import("./index-DQDuRMiM.js").then(r=>r.i);return{default:s}},[],import.meta.url);return this.client=new n({apiKey:e,...t?{defaultHeaders:{"anthropic-workspace-id":t}}:{},dangerouslyAllowBrowser:!0,maxRetries:1}),this.clientFor_=i,this.client}static read(e){if(e.stop_reason==="refusal")throw new Gs("refused");const t=e.content.find(n=>n.type==="tool_use"&&n.name===Z1.name);if(!t||t.type!=="tool_use")throw new Gs("malformed");const i=t.input;if(typeof i?.recording!="object"||i.recording===null||Array.isArray(i.recording))throw new Gs("malformed");return{recording:i.recording,claims:Array.isArray(i.claims)?i.claims.flatMap(n=>{const{path:s,basis:r,rationale:a}=n??{};return typeof s!="string"||typeof a!="string"?[]:[{path:s,basis:r==="derived"||r==="assumed"?r:"stated",rationale:a}]}):[],gaps:Array.isArray(i.gaps)?i.gaps.filter(n=>typeof n=="string"):[]}}static async diagnose(e,t){if(e instanceof Gs)return e;if(t?.aborted)return new Gs("cancelled",e);const{default:i}=await ae(async()=>{const{default:n}=await import("./index-DQDuRMiM.js").then(s=>s.i);return{default:n}},[],import.meta.url);return e instanceof i.AuthenticationError||e instanceof i.PermissionDeniedError?new Gs("credential",e):e instanceof i.RateLimitError?new Gs("rate-limited",e):e instanceof i.BadRequestError||e instanceof i.NotFoundError?new Gs("rejected",e.message,e):e instanceof i.APIConnectionError?new Gs("unreachable",e):new Gs("malformed",e)}}const hu=[{id:"claude",name:"Claude",credit:"Anthropic",creditUrl:"https://www.anthropic.com/legal/consumer-terms",create:()=>new Wr}],DT=[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async l=>{const{CoverageAssessor:e}=await ae(async()=>{const{CoverageAssessor:t}=await import("./CoverageAssessor-B8gBscye.js");return{CoverageAssessor:t}},[],import.meta.url);return new e().assess(l)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async l=>{const{HynekAssessor:e}=await ae(async()=>{const{HynekAssessor:t}=await import("./HynekAssessor-BopK5jfz.js");return{HynekAssessor:t}},[],import.meta.url);return new e().assess(l)}})}];class kT{constructor(e){this.labels=e}async read(e){const t=[],i=new Set;for(const n of DT){let s;try{s=await n.create().assess(e)}catch{continue}for(const a of s.criteria)a.basis===void 0&&!a.unsupported&&i.add(a.id);const r=s.score===void 0?s.verdict===void 0?"":this.verdictName(n.id,s.verdict):`${Math.round(s.score*100)}%`;r!==""&&t.push({group:"assessment",field:n.id,label:this.labels.assessmentNames[n.id]??n.name,value:r,unit:"",fromSource:!1,about:n.create().about})}return{entries:t,unanswered:i}}verdictName(e,t){return this.labels.assessmentVerdicts[`${e}.${t}`]??t.toUpperCase()}}class qr{static stated(e){return qr.statedIn(e,[])}static apply(e,t,i){const n=structuredClone(e);for(const s of i){const r=s.split("."),a=qr.read(t,r);a!==void 0&&qr.write(n,r,structuredClone(a))}return n}static statedIn(e,t){const i=[];for(const[n,s]of Object.entries(e)){if(s===void 0)continue;const r=[...t,n];qr.isPlainObject(s)?i.push(...qr.statedIn(s,r)):i.push(r.join("."))}return i}static isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static read(e,t){let i=e;for(const n of t){if(!qr.isPlainObject(i))return;i=i[n]}return i}static write(e,t,i){let n=e;for(const s of t.slice(0,-1)){const r=n[s];qr.isPlainObject(r)||(n[s]={}),n=n[s]}n[t[t.length-1]]=i}}const CT={x:Tt.CANVAS_WIDTH_PX/2,y:Tt.CANVAS_HEIGHT_PX/2,width:1,height:1};class df{static loadable(e){const t=e.decor?{decor:e.decor.map((n,s)=>df.decor(n,s))}:{},i=e.timeline?.keyframes;return i?{...e,...t,timeline:{...e.timeline,keyframes:i.map(n=>({t:n.t??0,shapes:(n.shapes??[]).map(s=>({sourceId:s.sourceId,shape:df.shape(s.shape)}))}))}}:{...e,...t}}static decor(e,t){const i=e.kind??"vehicle";return{...am(i)?{windows:c2(i)}:{},...i==="building"?{floors:dh}:{},...e,id:e.id??`decor-${t+1}`,kind:i,eastM:e.eastM??0,northM:e.northM??0}}static shape(e){const t=e?.kind==="polygon"?"polygon":"oval";return{...t==="polygon"?{points:[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}]}:{},...e,kind:t,bounds:{...CT},color:typeof e?.color=="string"?e.color:"#e8e6df",angle:0,transparency:0,haloScale:0,selected:!1}}}class m2{static sync(e,t,i,n,s){if(e.querySelector(".param-description")?.remove(),t===void 0){e.removeAttribute("data-describing");return}const r=document.createElement("div");r.className="param-description";const a=document.createElement("div");a.className="param-description-head";const o=document.createElement("span");o.className="param-nest-label",o.textContent=i;const c=document.createElement("button");c.type="button",c.className="param-description-close",c.textContent="×",c.title=n,c.setAttribute("aria-label",n),c.addEventListener("click",s),a.append(o,c);const h=document.createElement("p");h.className="param-description-text",h.textContent=t,r.append(a,h),r.addEventListener("keydown",d=>{d.key==="Escape"&&s()}),e.setAttribute("data-describing",""),e.append(r),c.focus({preventScroll:!0})}static CSS=`
754
754
  .param-summary[data-describing] > :not(.param-description) {
755
755
  display: none;
756
756
  }
@@ -4243,12 +4243,12 @@ canvas[data-cursor="rotate"] {
4243
4243
  pointer-events: none;
4244
4244
  white-space: nowrap;
4245
4245
  }
4246
- `;class Tl{constructor(e){this.points=e}static STATIONARY_M=5;static of(e){const t=[];for(const i of e.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||t.push({t:i.t,lat:n,lng:s,headingDeg:r})}if(t.length===0){const i=e.event.place?.[0];if(!i)return;t.push({t:0,lat:i.lat,lng:i.lng})}return new Tl(t)}static TRAVEL_M=50;get travels(){return this.spanM>Tl.TRAVEL_M}get moved(){return this.spanM>Tl.STATIONARY_M}get spanM(){const e=this.box,t=(e.south+e.north)/2,i=(e.west+e.east)/2;return Math.max(Math.abs(st(t,e.east,t,e.west).x),Math.abs(st(e.north,i,e.south,i).z))}get center(){const e=this.box;return{lat:(e.south+e.north)/2,lng:(e.west+e.east)/2}}boundsAround(e,t){const{lat:i,lng:n}=this.center,s=Math.max(this.spanM*(1+t),e)/2;return{north:ws(0,-s,i,n).lat,south:ws(0,s,i,n).lat,east:ws(s,0,i,n).lng,west:ws(-s,0,i,n).lng}}get box(){const e=this.points.map(i=>i.lat),t=this.points.map(i=>i.lng);return{south:Math.min(...e),north:Math.max(...e),west:Math.min(...t),east:Math.max(...t)}}}class nr{constructor(e,t){this.rotationPassed=e,this.scale=t}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(e){const t=e.event.tags?.includes("paralysis")||(e.exposure??0)>nr.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new nr(Math.max(1-(e.instrument.stabilization??0),nr.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,n=(d,u)=>Math.sin(2*Math.PI*d*t+u),[s,r,a,o,c,h]=nr.HZ;return{eastM:i*nr.SWAY_M*(.7*n(s,.3)+.3*n(o,1.9)),northM:i*nr.SWAY_M*(.6*n(a,2.2)+.4*n(c,.8)),upM:i*nr.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*nr.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(o,2.7)),pitchDeg:i*this.rotationPassed*nr.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*nr.DRIFT_ROLL_DEG*n(s,2.9)}}}class ri{constructor(e,t){this.stretches=e,this.rotationPassed=t}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(e){const t=Tl.of(e);if(!t||t.points.length<2)return;const i=[];let n=0;for(let s=1;s<t.points.length;s++){const r=t.points[s-1],a=t.points[s],o=(a.t-r.t)/1e3;if(o<=0)continue;const c=st(a.lat,a.lng,r.lat,r.lng),h=c.x,d=-c.z,u=Math.hypot(h,d),p=u/o,f=ri.stepHzFor(p);i.push({startMs:r.t,endMs:a.t,speedMPerS:p,eastUnit:u>0?h/u:0,northUnit:u>0?d/u:0,stepHz:f,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=f*o}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-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const n=ri.of(e)?.offsetAt(t)??ri.STILL;return i?n:ri.add(n,nr.of(e)?.offsetAt(t))}static stepHzFor(e){return e<ri.SLOWEST_WALK_M_PER_S||e>ri.FASTEST_WALK_M_PER_S?0:ri.REFERENCE_STEP_HZ*Math.pow(e/ri.REFERENCE_SPEED_M_PER_S,ri.CADENCE_EXPONENT)}offsetAt(e){return ri.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/ri.REFERENCE_SPEED_M_PER_S,n=(a,o,c,h)=>{if(a<0||a>ri.JOLT_LASTS_MS)return;const d=a/1e3,u=Math.exp(-d/ri.JOLT_DECAY_S)*Math.sin(2*Math.PI*ri.JOLT_HZ*d),p=h*o*i*u;return{eastM:p*t.eastUnit,northM:p*t.northUnit,upM:-Math.abs(p)*.3,rollDeg:0,pitchDeg:-h*c*i*u*this.rotationPassed,yawDeg:0}},s=t.rampsOut?n(e-t.endMs,ri.STOP_LURCH_M,ri.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=t.rampsIn?n(e-t.startMs,ri.START_LURCH_M,ri.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(e,t){return t?{eastM:e.eastM+t.eastM,northM:e.northM+t.northM,upM:e.upM+t.upM,rollDeg:e.rollDeg+t.rollDeg,pitchDeg:e.pitchDeg+t.pitchDeg,yawDeg:e.yawDeg+t.yawDeg}:e}cycleAt(e){const t=this.stretches.find(o=>e>=o.startMs&&e<=o.endMs);if(!t||t.stepHz===0)return ri.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(t,e),r=ri.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*t.speedMPerS/ri.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:ri.RISE_M_PER_M_PER_S*t.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(e,t){const i=1e3/e.stepHz,n=Math.min(i,(e.endMs-e.startMs)/2);if(n<=0)return 1;const s=t-e.startMs,r=e.endMs-t,a=Math.min(e.rampsIn?s/n:1,e.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class FT{constructor(e,t){this.timeline=e,this.onFrame=t}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 e=()=>{if(this.state!=="playing")return;const t=performance.now();if(this.currentT+=(t-this.lastWallTime)*this.playbackRate,this.lastWallTime=t,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}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(e){this.currentT=Math.max(0,Math.min(e,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(e){const t=new Map;for(const i of this.timeline.sourceIds){const n=this.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}this.onFrame(e,t)}}class Il{static sessionDeclared=!1;static unlock(e){if(Il.declarePlayback(),e.state!=="running")try{Promise.resolve(e.resume()).catch(()=>{});const t=e.createBufferSource();t.buffer=e.createBuffer(1,1,22050),t.connect(e.destination),t.start(0)}catch{}}static declarePlayback(){if(!(Il.sessionDeclared||typeof navigator>"u")){Il.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const J1=.05,Q1=.08,ey=2,ty=3,UT=14,zT=.02;class BT{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",e);return}}Il.unlock(this.context)}setSound(e){if(this.requested=e,!this.context)return;const t=this.keyFor(e);if(!t){this.silence();return}if(this.voice?.key!==t){this.stopVoice();const i=++this.voiceToken;t.startsWith("src:")?this.buildRecordedVoice(e.src,t,i):this.voice=this.buildSynthesizedVoice(e,t)}this.applyTo(this.voice,e)}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(e){if(!(e.volume<=0))return e.src?`src:${e.src}`:e.kind==="none"?void 0:e.kind}applyTo(e,t){const i=this.context;if(!e||!i)return;const n=i.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,n,J1);for(const{param:s,ratio:r}of e.pitch)s.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),n,J1)}buildSynthesizedVoice(e,t){const i=this.context;if(i)switch(e.kind){case"hum":return this.buildHum(i,t);case"whistle":return this.buildWhistle(i,t);case"rumble":return this.buildRumble(i,t);case"crackle":return this.buildCrackle(i,t);default:return}}buildHum(e,t){const i=e.createOscillator();i.type="sawtooth";const n=e.createOscillator();n.type="sawtooth";const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=e.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(this.output(e)),i.start(),n.start(),{key:t,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(e,t){const i=e.createOscillator();i.type="sine";const n=e.createOscillator();n.type="sine",n.frequency.value=5;const s=e.createGain(),r=e.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(this.output(e)),i.start(),n.start(),{key:t,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(e,t){const i=e.createBufferSource();i.buffer=this.brownNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=e.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(this.output(e)),i.start(),{key:t,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(e,t){const i=e.createBufferSource();i.buffer=this.whiteNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=e.createGain();s.gain.value=0;const r=e.createBufferSource();r.buffer=this.crackleEnvelope(e),r.loop=!0;const a=e.createGain();return a.gain.value=0,r.connect(a).connect(s.gain),i.connect(n).connect(s).connect(this.output(e)),i.start(),r.start(),{key:t,nodes:[n,s,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(e,t,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(e)}catch(o){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",o);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:t,nodes:[a],sources:[r],volumeParam:a.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(e){const t=this.context;if(!t)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${e}`);return n.arrayBuffer()}).then(n=>t.decodeAudioData(n)),this.buffers.set(e,i)),i}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*ey),e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*ey),e.sampleRate),i=t.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 t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*ty),e.sampleRate),i=t.getChannelData(0),n=Math.max(1,Math.floor(zT*e.sampleRate)),s=Math.round(ty*UT);for(let r=0;r<s;r++){const a=Math.floor(Math.random()*i.length),o=.4+Math.random()*.6;for(let c=0;c<n&&a+c<i.length;c++)i[a+c]=Math.max(i[a+c],o*(1-c/n))}this.crackleBuffer=t}return this.crackleBuffer}stopVoice(){const e=this.voice,t=this.context;if(this.voice=void 0,!e||!t)return;const i=t.currentTime;e.volumeParam.cancelScheduledValues(i),e.volumeParam.setTargetAtTime(0,i,Q1/3);const n=i+Q1;for(const s of e.sources){s.onended=()=>{s.disconnect();for(const r of e.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of e.nodes)r.disconnect()}}}}class jr{static KINDS=["beams","launches","reentries"];static isEmpty(e){return!e||jr.KINDS.every(t=>!e[t]?.length)}static written(e){if(jr.isEmpty(e))return;const t={};for(const i of jr.KINDS)e[i]?.length&&(t[i]=e[i]);return t}static read(e,t){const i=t,n={};for(const r of jr.KINDS){const a=[...e?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=t;if(i&&jr.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:o,...c}=i;s=jr.isReading(c)?c:void 0}return{skyEvents:jr.written(n),interpretation:s}}static isReading(e){return(e.bodies?.length??0)>0||e.title!==void 0||(e.smoke?.length??0)>0}}function _l(l){return[...l].sort((e,t)=>e.t-t.t)}function Em(l,e){let t;for(const i of _l(l)){if(i.t>e)break;t=i}return t}const Am=Math.PI/180,du=180/Math.PI;class Os{constructor(e,t,i){this.kind=e,this.canvasHeightPx=t,this.fovDeg=i;const n=i*Am/2;this.focalPx=e==="equidistant"?t/2/n:t/2/Math.tan(n)}focalPx;static of(e,t,i){return new Os(e.projection,t,i)}degToPx(e){const t=e*Am;return this.kind==="equidistant"?this.focalPx*t:2*this.focalPx*Math.tan(t/2)}pxToDeg(e){return this.kind==="equidistant"?e/this.focalPx*du:2*Math.atan(e/(2*this.focalPx))*du}angleDegToRadiusPx(e){const t=e*Am;return this.kind==="equidistant"?this.focalPx*t:this.focalPx*Math.tan(t)}halfWidthAngleDeg(e){return this.radiusPxToAngleDeg(this.canvasHeightPx*e/2)}radiusPxToAngleDeg(e){return this.kind==="equidistant"?e/this.focalPx*du:Math.atan(e/this.focalPx)*du}ofBounds(e){return{widthDeg:this.pxToDeg(e.width),heightDeg:this.pxToDeg(e.height)}}toBoundsSize(e){return{width:this.degToPx(e.widthDeg),height:this.degToPx(e.heightDeg)}}widthPx(e){return this.degToPx(At.angularWidthDeg(e))}}class Oi{static fovOf(e,t){return pt(e,t)?.fovDeg??hi.fieldOfViewDeg(e.instrument)}static toAngular(e){this.eachKeyframe(e,(t,i)=>{const n=i.ofBounds(t.bounds);return t.angular?.widthDeg===n.widthDeg&&t.angular.heightDeg===n.heightDeg?t:{...t,angular:n}})}static toBounds(e){this.eachKeyframe(e,(t,i)=>this.sizedFromAngle(t,i))}static sizedFromAngle(e,t){if(!e.angular)return e;const{width:i,height:n}=t.toBoundsSize(e.angular),s={x:e.bounds.x+(e.bounds.width-i)/2,y:e.bounds.y+(e.bounds.height-n)/2,width:i,height:n};if(e.kind!=="polygon")return{...e,bounds:s};const r=e.bounds.width===0?1:i/e.bounds.width,a=e.bounds.height===0?1:n/e.bounds.height;return{...e,bounds:s,points:e.points.map(o=>({x:o.x*r,y:o.y*a}))}}static toAim(e){this.eachKeyframe(e,(t,i,n)=>{const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);if(s&&Math.abs(s.x-t.bounds.x)<Oi.UNMOVED_PX&&Math.abs(s.y-t.bounds.y)<Oi.UNMOVED_PX)return t;const r=this.aimFrom(e,i,n,t.bounds);return r?{...t,aim:r}:t})}static UNMOVED_PX=.01;static aimOf(e,t,i){const n=Os.of(e.instrument,At.CANVAS_HEIGHT_PX,this.fovOf(e,t));return this.aimFrom(e,n,pt(e,t),i)}static aimFrom(e,t,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(e),r=t.radiusPxToAngleDeg(n.x+n.width/2-s.x),a=t.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+a}}static toPosition(e){this.eachKeyframe(e,(t,i,n)=>this.placedByAim(e,t,i,n))}static placedByAim(e,t,i,n){const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);return s?{...t,bounds:{...t.bounds,...s}}:t}static derivable(e){const t=new Set,i=new Map,n=new Map;return e.timeline.allKeyframes.forEach((s,r)=>{const a=pt(e,s.t),o=Os.of(e.instrument,At.CANVAS_HEIGHT_PX,this.fovOf(e,s.t));for(const{sourceId:c,shape:h}of s.shapes){const d=n.get(c),u=i.get(c);if(n.set(c,h),!d||!u){i.set(c,h);continue}const p=Object.fromEntries(Object.entries(h).filter(([v,g])=>v!=="bounds"&&v!=="points"&&JSON.stringify(g)!==JSON.stringify(d[v]))),f={...u,...p},m=this.placedByAim(e,this.sizedFromAngle(f,o),o,a);Oi.near(m,h)?(t.add(`${r}:${c}`),i.set(c,f)):i.set(c,h)}}),(s,r)=>t.has(`${s}:${r}`)}static SAME_PX=1e-6;static near(e,t){const i=(r,a)=>Math.abs(r-a)<=Oi.SAME_PX*Math.max(1,Math.abs(a)),n=e.bounds,s=t.bounds;return!i(n.x,s.x)||!i(n.y,s.y)||!i(n.width,s.width)||!i(n.height,s.height)?!1:t.kind!=="polygon"||e.kind!=="polygon"?!0:e.points.length===t.points.length&&e.points.every((r,a)=>i(r.x,t.points[a].x)&&i(r.y,t.points[a].y))}static positionOf(e,t,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(e),a=this.shortestArc(t.azimuthDeg-s.headingDeg),o=t.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,a)-i.width/2,y:r.y-this.offAxisPx(n,o)-i.height/2}}static frameCentre(e){return{x:hi.frameWidthPx(e.instrument,At.CANVAS_HEIGHT_PX)/2,y:At.CANVAS_HEIGHT_PX/2}}static shortestArc(e){return(e%360+540)%360-180}static offAxisPx(e,t){return Math.abs(t)>=Oi.OFF_CANVAS_DEG?Math.sign(t)*Oi.OFF_CANVAS_PX:e.angleDegToRadiusPx(t)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(e,t,i){const n=hi.frameWidthPx(t,At.CANVAS_HEIGHT_PX)/2,s=hi.frameWidthPx(e.instrument,At.CANVAS_HEIGHT_PX)/2,r=At.CANVAS_HEIGHT_PX/2;for(const a of[...e.timeline.allKeyframes]){const o=this.fovOf(e,a.t),c=i?.get(a.t)??o,h=Os.of(t,At.CANVAS_HEIGHT_PX,c),d=Os.of(e.instrument,At.CANVAS_HEIGHT_PX,o);e.timeline.addKeyframe(a.t,a.shapes.map(u=>{const{bounds:p}=u.shape,f=p.x+p.width/2-n,m=p.y+p.height/2-r,v=Math.hypot(f,m),g=v===0?1:d.angleDegToRadiusPx(h.radiusPxToAngleDeg(v))/v,y={...p,x:s+f*g-p.width/2,y:r+m*g-p.height/2};return{...u,shape:{...u.shape,bounds:y}}}))}this.toBounds(e)}static eachKeyframe(e,t){const{timeline:i}=e;for(const n of[...i.allKeyframes]){const s=pt(e,n.t),r=this.fovOf(e,n.t),a=Os.of(e.instrument,At.CANVAS_HEIGHT_PX,r);let o=!1;const c=n.shapes.map(h=>{const d=t(h.shape,a,s);return d===h.shape?h:(o=!0,{...h,shape:d})});o&&i.addKeyframe(n.t,c)}}}class ls{static restatedDecor(e){const t=ls.originOf(e);return e.decor.map(i=>{let n=i;if(i.saidPosition){const s=ls.restated(i.saidPosition,i,ls.frameAt(e,0,t,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=ls.restated(r.saidPosition,r,ls.frameAt(e,r.t,t,i.id));if(JSON.stringify(a)===JSON.stringify(r.saidPosition))return r;const o={...r,saidPosition:a};return a||delete o.saidPosition,o});n={...n,track:s}}return n})}static restatedObserverTrack(e){const t=e.observerTrack.toJSON(),i=ls.originOf(e);return!i||!t.keyframes.some(n=>n.pose.saidPosition)?t:{...t,keyframes:t.keyframes.map(n=>{const{pose:s}=n;if(!s.saidPosition||s.lat===void 0||s.lng===void 0)return n;const r=Kt.toLocal({lat:s.lat,lng:s.lng},i),a=ls.restated(s.saidPosition,r,ls.frameAt(e,n.t,i));if(JSON.stringify(a)===JSON.stringify(s.saidPosition))return n;const o={...s,saidPosition:a};return a||delete o.saidPosition,{...n,pose:o}})}}static restatedInterpretation(e){const t=e.interpretation;if(!t?.bodies.some(n=>n.track.some(s=>s.saidPosition)))return t;const i=ls.originOf(e);return{...t,bodies:t.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?ls.restated(s.saidPosition,{eastM:s.eastM,northM:s.northM},ls.frameAt(e,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(e){const t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],n=t?.lat??i?.lat,s=t?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}static frameAt(e,t,i,n){const s=[{label:"",eastM:0,northM:0},...e.decor.filter(r=>r.id!==n).map(r=>{const{eastM:a,northM:o}=qs(r,t);return{id:r.id,label:r.id,eastM:a,northM:o}})];return{origin:i,references:s}}static restated(e,t,i){return Kt.restated(e,{eastM:t.eastM,northM:t.northM},i)}}function uf(l){return us.restore(Rg(l),l.provenance)}function Rg(l){return Oi.toAngular(l),Oi.toAim(l),{version:1,id:l.id,time:l.event.time,endTime:l.event.endTime,durationSeconds:l.event.durationSeconds,durationText:l.event.durationText,utcOffsetHours:l.event.utcOffsetHours,timeZone:l.event.timeZone,place:l.event.place,observer:l.observer,account:l.account,sources:l.sources?.length?l.sources:void 0,sway:l.sway,vehicle:l.vehicle,description:l.event.description,image:l.event.image,summary:l.event.summary,summaryTime:l.event.summaryTime,tags:l.event.tags,timeline:l.timeline.toJSON(),observerTrack:ls.restatedObserverTrack(l),weatherTrack:l.weatherTrack.toJSON(),soundTrack:l.soundTrack.toJSON(),weather:l.weather,decor:ls.restatedDecor(l),milestones:l.milestones.length>0?l.milestones:void 0,references:l.references.length>0?l.references:void 0,roads:l.roads.length>0?l.roads:void 0,traces:l.traces.length>0?l.traces:void 0,weatherSource:l.weatherSource,instrument:l.instrumentId,exposureSeconds:l.exposureSeconds,iso:l.iso,metering:l.metering,lens:l.lens,lightPollution:l.lightPollution,observerMap:l.observerMap,interpretation:ls.restatedInterpretation(l),variants:l.variants.length>0?l.variants:void 0,skyEvents:jr.written(l.skyEvents),frozen:l.frozen}}function rb(l){el.check(l,"sighting");const{recording:e,provenance:t}=us.strip(l),i=HT(e);return i.provenance=t,i}function HT(l){const e=[],t=new Qf({eventType:"sighting",time:l.time,endTime:l.endTime,durationSeconds:l.durationSeconds,durationText:l.durationText,utcOffsetHours:l.utcOffsetHours,timeZone:l.timeZone,place:l.place,description:l.description,image:l.image,summary:l.summary,summaryTime:l.summaryTime,tags:l.tags},Yf.fromJSON(l.timeline,e),l.observerTrack?_d.fromJSON(l.observerTrack):new _d,l.weatherTrack?Rd.fromJSON(l.weatherTrack):new Rd,l.soundTrack?Dd.fromJSON(l.soundTrack):new Dd,l.observer&&{id:l.observer.id,title:l.observer.title,lastName:l.observer.lastName,firstNames:l.observer.firstNames},l.id,l.weather,l.decor??[],l.weatherSource,l.instrument,l.exposureSeconds??l.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),_l(l.milestones??[]),l.references??[],l.roads??[],l.traces??[]);t.account=l.account,t.sources=l.sources,t.sway=l.sway,t.iso=l.iso,t.metering=l.metering,t.lens=l.lens,t.lightPollution=l.lightPollution,t.observerMap=l.observerMap,t.vehicle=l.vehicle;const i=jr.read(l.skyEvents,l.interpretation);return t.interpretation=i.interpretation,t.variants=Array.isArray(l.variants)?l.variants:[],t.skyEvents=i.skyEvents,t.frozen=l.frozen,t.loadIssues=e,Oi.toBounds(t),Oi.toPosition(t),t}class ph{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(e,t=ph.EN){return t[e.kind].replace("{path}",e.path).replace("{expected}",e.expected??"").replace("{found}",e.found??"")}static warn(e,t){if(e.length===0)return;const i=e.map(n=>` ${ph.text(n)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
4246
+ `;class Tl{constructor(e){this.points=e}static STATIONARY_M=5;static of(e){const t=[];for(const i of e.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||t.push({t:i.t,lat:n,lng:s,headingDeg:r})}if(t.length===0){const i=e.event.place?.[0];if(!i)return;t.push({t:0,lat:i.lat,lng:i.lng})}return new Tl(t)}static TRAVEL_M=50;get travels(){return this.spanM>Tl.TRAVEL_M}get moved(){return this.spanM>Tl.STATIONARY_M}get spanM(){const e=this.box,t=(e.south+e.north)/2,i=(e.west+e.east)/2;return Math.max(Math.abs(st(t,e.east,t,e.west).x),Math.abs(st(e.north,i,e.south,i).z))}get center(){const e=this.box;return{lat:(e.south+e.north)/2,lng:(e.west+e.east)/2}}boundsAround(e,t){const{lat:i,lng:n}=this.center,s=Math.max(this.spanM*(1+t),e)/2;return{north:ws(0,-s,i,n).lat,south:ws(0,s,i,n).lat,east:ws(s,0,i,n).lng,west:ws(-s,0,i,n).lng}}get box(){const e=this.points.map(i=>i.lat),t=this.points.map(i=>i.lng);return{south:Math.min(...e),north:Math.max(...e),west:Math.min(...t),east:Math.max(...t)}}}class nr{constructor(e,t){this.rotationPassed=e,this.scale=t}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(e){const t=e.event.tags?.includes("paralysis")||(e.exposure??0)>nr.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new nr(Math.max(1-(e.instrument.stabilization??0),nr.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,n=(d,u)=>Math.sin(2*Math.PI*d*t+u),[s,r,a,o,c,h]=nr.HZ;return{eastM:i*nr.SWAY_M*(.7*n(s,.3)+.3*n(o,1.9)),northM:i*nr.SWAY_M*(.6*n(a,2.2)+.4*n(c,.8)),upM:i*nr.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*nr.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(o,2.7)),pitchDeg:i*this.rotationPassed*nr.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*nr.DRIFT_ROLL_DEG*n(s,2.9)}}}class ri{constructor(e,t){this.stretches=e,this.rotationPassed=t}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(e){const t=Tl.of(e);if(!t||t.points.length<2)return;const i=[];let n=0;for(let s=1;s<t.points.length;s++){const r=t.points[s-1],a=t.points[s],o=(a.t-r.t)/1e3;if(o<=0)continue;const c=st(a.lat,a.lng,r.lat,r.lng),h=c.x,d=-c.z,u=Math.hypot(h,d),p=u/o,f=ri.stepHzFor(p);i.push({startMs:r.t,endMs:a.t,speedMPerS:p,eastUnit:u>0?h/u:0,northUnit:u>0?d/u:0,stepHz:f,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=f*o}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-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const n=ri.of(e)?.offsetAt(t)??ri.STILL;return i?n:ri.add(n,nr.of(e)?.offsetAt(t))}static stepHzFor(e){return e<ri.SLOWEST_WALK_M_PER_S||e>ri.FASTEST_WALK_M_PER_S?0:ri.REFERENCE_STEP_HZ*Math.pow(e/ri.REFERENCE_SPEED_M_PER_S,ri.CADENCE_EXPONENT)}offsetAt(e){return ri.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/ri.REFERENCE_SPEED_M_PER_S,n=(a,o,c,h)=>{if(a<0||a>ri.JOLT_LASTS_MS)return;const d=a/1e3,u=Math.exp(-d/ri.JOLT_DECAY_S)*Math.sin(2*Math.PI*ri.JOLT_HZ*d),p=h*o*i*u;return{eastM:p*t.eastUnit,northM:p*t.northUnit,upM:-Math.abs(p)*.3,rollDeg:0,pitchDeg:-h*c*i*u*this.rotationPassed,yawDeg:0}},s=t.rampsOut?n(e-t.endMs,ri.STOP_LURCH_M,ri.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=t.rampsIn?n(e-t.startMs,ri.START_LURCH_M,ri.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(e,t){return t?{eastM:e.eastM+t.eastM,northM:e.northM+t.northM,upM:e.upM+t.upM,rollDeg:e.rollDeg+t.rollDeg,pitchDeg:e.pitchDeg+t.pitchDeg,yawDeg:e.yawDeg+t.yawDeg}:e}cycleAt(e){const t=this.stretches.find(o=>e>=o.startMs&&e<=o.endMs);if(!t||t.stepHz===0)return ri.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(t,e),r=ri.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*t.speedMPerS/ri.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:ri.RISE_M_PER_M_PER_S*t.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(e,t){const i=1e3/e.stepHz,n=Math.min(i,(e.endMs-e.startMs)/2);if(n<=0)return 1;const s=t-e.startMs,r=e.endMs-t,a=Math.min(e.rampsIn?s/n:1,e.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class FT{constructor(e,t){this.timeline=e,this.onFrame=t}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 e=()=>{if(this.state!=="playing")return;const t=performance.now();if(this.currentT+=(t-this.lastWallTime)*this.playbackRate,this.lastWallTime=t,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}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(e){this.currentT=Math.max(0,Math.min(e,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(e){const t=new Map;for(const i of this.timeline.sourceIds){const n=this.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}this.onFrame(e,t)}}class Il{static sessionDeclared=!1;static unlock(e){if(Il.declarePlayback(),e.state!=="running")try{Promise.resolve(e.resume()).catch(()=>{});const t=e.createBufferSource();t.buffer=e.createBuffer(1,1,22050),t.connect(e.destination),t.start(0)}catch{}}static declarePlayback(){if(!(Il.sessionDeclared||typeof navigator>"u")){Il.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const J1=.05,Q1=.08,ey=2,ty=3,UT=14,zT=.02;class BT{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",e);return}}Il.unlock(this.context)}setSound(e){if(this.requested=e,!this.context)return;const t=this.keyFor(e);if(!t){this.silence();return}if(this.voice?.key!==t){this.stopVoice();const i=++this.voiceToken;t.startsWith("src:")?this.buildRecordedVoice(e.src,t,i):this.voice=this.buildSynthesizedVoice(e,t)}this.applyTo(this.voice,e)}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(e){if(!(e.volume<=0))return e.src?`src:${e.src}`:e.kind==="none"?void 0:e.kind}applyTo(e,t){const i=this.context;if(!e||!i)return;const n=i.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,n,J1);for(const{param:s,ratio:r}of e.pitch)s.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),n,J1)}buildSynthesizedVoice(e,t){const i=this.context;if(i)switch(e.kind){case"hum":return this.buildHum(i,t);case"whistle":return this.buildWhistle(i,t);case"rumble":return this.buildRumble(i,t);case"crackle":return this.buildCrackle(i,t);default:return}}buildHum(e,t){const i=e.createOscillator();i.type="sawtooth";const n=e.createOscillator();n.type="sawtooth";const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=e.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(this.output(e)),i.start(),n.start(),{key:t,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(e,t){const i=e.createOscillator();i.type="sine";const n=e.createOscillator();n.type="sine",n.frequency.value=5;const s=e.createGain(),r=e.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(this.output(e)),i.start(),n.start(),{key:t,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(e,t){const i=e.createBufferSource();i.buffer=this.brownNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=e.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(this.output(e)),i.start(),{key:t,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(e,t){const i=e.createBufferSource();i.buffer=this.whiteNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=e.createGain();s.gain.value=0;const r=e.createBufferSource();r.buffer=this.crackleEnvelope(e),r.loop=!0;const a=e.createGain();return a.gain.value=0,r.connect(a).connect(s.gain),i.connect(n).connect(s).connect(this.output(e)),i.start(),r.start(),{key:t,nodes:[n,s,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(e,t,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(e)}catch(o){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",o);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:t,nodes:[a],sources:[r],volumeParam:a.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(e){const t=this.context;if(!t)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${e}`);return n.arrayBuffer()}).then(n=>t.decodeAudioData(n)),this.buffers.set(e,i)),i}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*ey),e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*ey),e.sampleRate),i=t.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 t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*ty),e.sampleRate),i=t.getChannelData(0),n=Math.max(1,Math.floor(zT*e.sampleRate)),s=Math.round(ty*UT);for(let r=0;r<s;r++){const a=Math.floor(Math.random()*i.length),o=.4+Math.random()*.6;for(let c=0;c<n&&a+c<i.length;c++)i[a+c]=Math.max(i[a+c],o*(1-c/n))}this.crackleBuffer=t}return this.crackleBuffer}stopVoice(){const e=this.voice,t=this.context;if(this.voice=void 0,!e||!t)return;const i=t.currentTime;e.volumeParam.cancelScheduledValues(i),e.volumeParam.setTargetAtTime(0,i,Q1/3);const n=i+Q1;for(const s of e.sources){s.onended=()=>{s.disconnect();for(const r of e.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of e.nodes)r.disconnect()}}}}class jr{static KINDS=["beams","launches","reentries"];static isEmpty(e){return!e||jr.KINDS.every(t=>!e[t]?.length)}static written(e){if(jr.isEmpty(e))return;const t={};for(const i of jr.KINDS)e[i]?.length&&(t[i]=e[i]);return t}static read(e,t){const i=t,n={};for(const r of jr.KINDS){const a=[...e?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=t;if(i&&jr.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:o,...c}=i;s=jr.isReading(c)?c:void 0}return{skyEvents:jr.written(n),interpretation:s}}static isReading(e){return(e.bodies?.length??0)>0||e.title!==void 0||(e.smoke?.length??0)>0}}function _l(l){return[...l].sort((e,t)=>e.t-t.t)}function Em(l,e){let t;for(const i of _l(l)){if(i.t>e)break;t=i}return t}const Am=Math.PI/180,du=180/Math.PI;class Os{constructor(e,t,i){this.kind=e,this.canvasHeightPx=t,this.fovDeg=i;const n=i*Am/2;this.focalPx=e==="equidistant"?t/2/n:t/2/Math.tan(n)}focalPx;static of(e,t,i){return new Os(e.projection,t,i)}degToPx(e){const t=e*Am;return this.kind==="equidistant"?this.focalPx*t:2*this.focalPx*Math.tan(t/2)}pxToDeg(e){return this.kind==="equidistant"?e/this.focalPx*du:2*Math.atan(e/(2*this.focalPx))*du}angleDegToRadiusPx(e){const t=e*Am;return this.kind==="equidistant"?this.focalPx*t:this.focalPx*Math.tan(t)}halfWidthAngleDeg(e){return this.radiusPxToAngleDeg(this.canvasHeightPx*e/2)}radiusPxToAngleDeg(e){return this.kind==="equidistant"?e/this.focalPx*du:Math.atan(e/this.focalPx)*du}ofBounds(e){return{widthDeg:this.pxToDeg(e.width),heightDeg:this.pxToDeg(e.height)}}toBoundsSize(e){return{width:this.degToPx(e.widthDeg),height:this.degToPx(e.heightDeg)}}widthPx(e){return this.degToPx(Tt.angularWidthDeg(e))}}class Oi{static fovOf(e,t){return pt(e,t)?.fovDeg??hi.fieldOfViewDeg(e.instrument)}static toAngular(e){this.eachKeyframe(e,(t,i)=>{const n=i.ofBounds(t.bounds);return t.angular?.widthDeg===n.widthDeg&&t.angular.heightDeg===n.heightDeg?t:{...t,angular:n}})}static toBounds(e){this.eachKeyframe(e,(t,i)=>this.sizedFromAngle(t,i))}static sizedFromAngle(e,t){if(!e.angular)return e;const{width:i,height:n}=t.toBoundsSize(e.angular),s={x:e.bounds.x+(e.bounds.width-i)/2,y:e.bounds.y+(e.bounds.height-n)/2,width:i,height:n};if(e.kind!=="polygon")return{...e,bounds:s};const r=e.bounds.width===0?1:i/e.bounds.width,a=e.bounds.height===0?1:n/e.bounds.height;return{...e,bounds:s,points:e.points.map(o=>({x:o.x*r,y:o.y*a}))}}static toAim(e){this.eachKeyframe(e,(t,i,n)=>{const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);if(s&&Math.abs(s.x-t.bounds.x)<Oi.UNMOVED_PX&&Math.abs(s.y-t.bounds.y)<Oi.UNMOVED_PX)return t;const r=this.aimFrom(e,i,n,t.bounds);return r?{...t,aim:r}:t})}static UNMOVED_PX=.01;static aimOf(e,t,i){const n=Os.of(e.instrument,Tt.CANVAS_HEIGHT_PX,this.fovOf(e,t));return this.aimFrom(e,n,pt(e,t),i)}static aimFrom(e,t,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(e),r=t.radiusPxToAngleDeg(n.x+n.width/2-s.x),a=t.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+a}}static toPosition(e){this.eachKeyframe(e,(t,i,n)=>this.placedByAim(e,t,i,n))}static placedByAim(e,t,i,n){const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);return s?{...t,bounds:{...t.bounds,...s}}:t}static derivable(e){const t=new Set,i=new Map,n=new Map;return e.timeline.allKeyframes.forEach((s,r)=>{const a=pt(e,s.t),o=Os.of(e.instrument,Tt.CANVAS_HEIGHT_PX,this.fovOf(e,s.t));for(const{sourceId:c,shape:h}of s.shapes){const d=n.get(c),u=i.get(c);if(n.set(c,h),!d||!u){i.set(c,h);continue}const p=Object.fromEntries(Object.entries(h).filter(([v,g])=>v!=="bounds"&&v!=="points"&&JSON.stringify(g)!==JSON.stringify(d[v]))),f={...u,...p},m=this.placedByAim(e,this.sizedFromAngle(f,o),o,a);Oi.near(m,h)?(t.add(`${r}:${c}`),i.set(c,f)):i.set(c,h)}}),(s,r)=>t.has(`${s}:${r}`)}static SAME_PX=1e-6;static near(e,t){const i=(r,a)=>Math.abs(r-a)<=Oi.SAME_PX*Math.max(1,Math.abs(a)),n=e.bounds,s=t.bounds;return!i(n.x,s.x)||!i(n.y,s.y)||!i(n.width,s.width)||!i(n.height,s.height)?!1:t.kind!=="polygon"||e.kind!=="polygon"?!0:e.points.length===t.points.length&&e.points.every((r,a)=>i(r.x,t.points[a].x)&&i(r.y,t.points[a].y))}static positionOf(e,t,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(e),a=this.shortestArc(t.azimuthDeg-s.headingDeg),o=t.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,a)-i.width/2,y:r.y-this.offAxisPx(n,o)-i.height/2}}static frameCentre(e){return{x:hi.frameWidthPx(e.instrument,Tt.CANVAS_HEIGHT_PX)/2,y:Tt.CANVAS_HEIGHT_PX/2}}static shortestArc(e){return(e%360+540)%360-180}static offAxisPx(e,t){return Math.abs(t)>=Oi.OFF_CANVAS_DEG?Math.sign(t)*Oi.OFF_CANVAS_PX:e.angleDegToRadiusPx(t)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(e,t,i){const n=hi.frameWidthPx(t,Tt.CANVAS_HEIGHT_PX)/2,s=hi.frameWidthPx(e.instrument,Tt.CANVAS_HEIGHT_PX)/2,r=Tt.CANVAS_HEIGHT_PX/2;for(const a of[...e.timeline.allKeyframes]){const o=this.fovOf(e,a.t),c=i?.get(a.t)??o,h=Os.of(t,Tt.CANVAS_HEIGHT_PX,c),d=Os.of(e.instrument,Tt.CANVAS_HEIGHT_PX,o);e.timeline.addKeyframe(a.t,a.shapes.map(u=>{const{bounds:p}=u.shape,f=p.x+p.width/2-n,m=p.y+p.height/2-r,v=Math.hypot(f,m),g=v===0?1:d.angleDegToRadiusPx(h.radiusPxToAngleDeg(v))/v,y={...p,x:s+f*g-p.width/2,y:r+m*g-p.height/2};return{...u,shape:{...u.shape,bounds:y}}}))}this.toBounds(e)}static eachKeyframe(e,t){const{timeline:i}=e;for(const n of[...i.allKeyframes]){const s=pt(e,n.t),r=this.fovOf(e,n.t),a=Os.of(e.instrument,Tt.CANVAS_HEIGHT_PX,r);let o=!1;const c=n.shapes.map(h=>{const d=t(h.shape,a,s);return d===h.shape?h:(o=!0,{...h,shape:d})});o&&i.addKeyframe(n.t,c)}}}class ls{static restatedDecor(e){const t=ls.originOf(e);return e.decor.map(i=>{let n=i;if(i.saidPosition){const s=ls.restated(i.saidPosition,i,ls.frameAt(e,0,t,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=ls.restated(r.saidPosition,r,ls.frameAt(e,r.t,t,i.id));if(JSON.stringify(a)===JSON.stringify(r.saidPosition))return r;const o={...r,saidPosition:a};return a||delete o.saidPosition,o});n={...n,track:s}}return n})}static restatedObserverTrack(e){const t=e.observerTrack.toJSON(),i=ls.originOf(e);return!i||!t.keyframes.some(n=>n.pose.saidPosition)?t:{...t,keyframes:t.keyframes.map(n=>{const{pose:s}=n;if(!s.saidPosition||s.lat===void 0||s.lng===void 0)return n;const r=Kt.toLocal({lat:s.lat,lng:s.lng},i),a=ls.restated(s.saidPosition,r,ls.frameAt(e,n.t,i));if(JSON.stringify(a)===JSON.stringify(s.saidPosition))return n;const o={...s,saidPosition:a};return a||delete o.saidPosition,{...n,pose:o}})}}static restatedInterpretation(e){const t=e.interpretation;if(!t?.bodies.some(n=>n.track.some(s=>s.saidPosition)))return t;const i=ls.originOf(e);return{...t,bodies:t.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?ls.restated(s.saidPosition,{eastM:s.eastM,northM:s.northM},ls.frameAt(e,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(e){const t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],n=t?.lat??i?.lat,s=t?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}static frameAt(e,t,i,n){const s=[{label:"",eastM:0,northM:0},...e.decor.filter(r=>r.id!==n).map(r=>{const{eastM:a,northM:o}=qs(r,t);return{id:r.id,label:r.id,eastM:a,northM:o}})];return{origin:i,references:s}}static restated(e,t,i){return Kt.restated(e,{eastM:t.eastM,northM:t.northM},i)}}function uf(l){return us.restore(Rg(l),l.provenance)}function Rg(l){return Oi.toAngular(l),Oi.toAim(l),{version:1,id:l.id,time:l.event.time,endTime:l.event.endTime,durationSeconds:l.event.durationSeconds,durationText:l.event.durationText,utcOffsetHours:l.event.utcOffsetHours,timeZone:l.event.timeZone,place:l.event.place,observer:l.observer,account:l.account,sources:l.sources?.length?l.sources:void 0,sway:l.sway,vehicle:l.vehicle,description:l.event.description,image:l.event.image,summary:l.event.summary,summaryTime:l.event.summaryTime,tags:l.event.tags,timeline:l.timeline.toJSON(),observerTrack:ls.restatedObserverTrack(l),weatherTrack:l.weatherTrack.toJSON(),soundTrack:l.soundTrack.toJSON(),weather:l.weather,decor:ls.restatedDecor(l),milestones:l.milestones.length>0?l.milestones:void 0,references:l.references.length>0?l.references:void 0,roads:l.roads.length>0?l.roads:void 0,traces:l.traces.length>0?l.traces:void 0,weatherSource:l.weatherSource,instrument:l.instrumentId,exposureSeconds:l.exposureSeconds,iso:l.iso,metering:l.metering,lens:l.lens,lightPollution:l.lightPollution,observerMap:l.observerMap,interpretation:ls.restatedInterpretation(l),variants:l.variants.length>0?l.variants:void 0,skyEvents:jr.written(l.skyEvents),frozen:l.frozen}}function rb(l){el.check(l,"sighting");const{recording:e,provenance:t}=us.strip(l),i=HT(e);return i.provenance=t,i}function HT(l){const e=[],t=new Qf({eventType:"sighting",time:l.time,endTime:l.endTime,durationSeconds:l.durationSeconds,durationText:l.durationText,utcOffsetHours:l.utcOffsetHours,timeZone:l.timeZone,place:l.place,description:l.description,image:l.image,summary:l.summary,summaryTime:l.summaryTime,tags:l.tags},Yf.fromJSON(l.timeline,e),l.observerTrack?_d.fromJSON(l.observerTrack):new _d,l.weatherTrack?Rd.fromJSON(l.weatherTrack):new Rd,l.soundTrack?Dd.fromJSON(l.soundTrack):new Dd,l.observer&&{id:l.observer.id,title:l.observer.title,lastName:l.observer.lastName,firstNames:l.observer.firstNames},l.id,l.weather,l.decor??[],l.weatherSource,l.instrument,l.exposureSeconds??l.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),_l(l.milestones??[]),l.references??[],l.roads??[],l.traces??[]);t.account=l.account,t.sources=l.sources,t.sway=l.sway,t.iso=l.iso,t.metering=l.metering,t.lens=l.lens,t.lightPollution=l.lightPollution,t.observerMap=l.observerMap,t.vehicle=l.vehicle;const i=jr.read(l.skyEvents,l.interpretation);return t.interpretation=i.interpretation,t.variants=Array.isArray(l.variants)?l.variants:[],t.skyEvents=i.skyEvents,t.frozen=l.frozen,t.loadIssues=e,Oi.toBounds(t),Oi.toPosition(t),t}class ph{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(e,t=ph.EN){return t[e.kind].replace("{path}",e.path).replace("{expected}",e.expected??"").replace("{found}",e.found??"")}static warn(e,t){if(e.length===0)return;const i=e.map(n=>` ${ph.text(n)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
4247
4247
  ${i.join(`
4248
4248
  `)}`)}}class yr{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,n){if(!yr.isObject(e)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:yr.typeOf(e)});return}for(const[s,r]of Object.entries(e)){const a=i?`${i}.${s}`:s,o=t[s];o?this.field(r,o,a,n):n.push({kind:"unknown-key",path:a})}}field(e,t,i,n){if(yr.isStated(e)){this.field(e.value,t,i,n);return}if(!(t.loose||e===void 0||e===null))switch(t.type){case"enum":(typeof e!="string"||!t.values?.includes(e))&&n.push({kind:"not-in-list",path:i,expected:(t.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(e)});return;case"object":t.fields?this.object(e,t.fields,i,n):yr.isObject(e)||n.push({kind:"wrong-type",path:i,expected:"object",found:yr.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((s,r)=>{const a=yr.isStated(s)?s.value:s;this.object(a,t.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:yr.typeOf(e)});return;default:typeof e!==t.type&&n.push({kind:"wrong-type",path:i,expected:t.type,found:yr.typeOf(e)})}}static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return yr.isObject(e)&&"value"in e&&Object.keys(e).every(t=>t==="value"||t==="basis"||t==="rationale")}static typeOf(e){return Array.isArray(e)?"array":e===null?"null":typeof e}}class Er{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(e,t){const i=Number.isFinite(t)?Math.max(0,t):0,n=Math.max(0,e-i*1e3),s=Math.max(0,e-n);return{fromMs:n,toMs:e,ms:s,seconds:s/1e3}}static instants(e,t,i,n,s){if(!(n>0))return 1;const r=s>0?Er.travelDegOver(e,t,i,i+n*1e3)/s/Er.PIXELS_PER_INSTANT:0,a=Er.flashesOver(e,n)*Er.INSTANTS_PER_FLASH,o=Math.ceil(Math.max(r,a));return o<2?1:Math.min(Er.MAX_INSTANTS,o)}static travelDegOver(e,t,i,n){let s=0;for(const r of e){if(!r.track||r.track.length<2)continue;const a=Er.directionAt(r,t,i),o=Er.directionAt(r,t,n),c=Math.min(1,Math.max(-1,a.x*o.x+a.y*o.y+a.z*o.z));s=Math.max(s,Math.acos(c)*180/Math.PI)}return s}static flashesOver(e,t){let i=0;for(const n of e)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*t}static directionAt(e,t,i){const n=qs(e,i),s=n.eastM,r=n.altitudeM-t,a=n.northM,o=Math.hypot(s,r,a);return o===0?{x:0,y:1,z:0}:{x:s/o,y:r/o,z:a/o}}}const g2={play:"Play",clickToPlay:"Click to play",pause:"Pause",noDuration:"No observation duration",currentPosition:"Current position",duration:"Duration",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",mute:"Mute",unmute:"Unmute",noSound:"No sound recorded",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",referencesMenu:"Pictures of the place",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:ph.EN},GT=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:g2},Symbol.toStringTag,{value:"Module"})),v2=Math.PI/180,VT=180/Math.PI,WT=256,b2=19,$T=1.25;function y2(l,e){return 156543.03392*Math.cos(l*v2)/2**e}function w2(l,e){return y2(l,e)*WT}function KT(l,e){let t=0;for(;t<b2&&w2(l,t+1)>=e;)t++;return t}function M2(l,e){return w2(l,e)}function XT(l,e){const t=e*$T;let i=0;for(;i<b2&&y2(l,i)>t;)i++;return i}function bp(l){const e=l*v2;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function x2(l,e,t){const i=2**t;return{x:(l+180)/360*i,y:bp(e)*i}}function S2(l,e,t){const i=bp(l.north),n=bp(l.south);return{x:(e-l.west)/(l.east-l.west),y:(bp(t)-i)/(n-i)}}function YT(l,e,t){const{x:i,y:n}=x2(l,e,t);return{x:Math.floor(i),y:Math.floor(n),z:t}}function qT(l){const e=2**l.z,t=l.x/e*360-180,i=(l.x+1)/e*360-180,n=iy(l.y,e);return{south:iy(l.y+1,e),north:n,west:t,east:i}}function iy(l,e){const t=l/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*VT}function E2(l,e,t,i){const n=YT(l,e,t),s=Math.floor(i/2),r=[];for(let c=-s;c<=s;c++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+c,z:t});const a=r.map(qT),o={south:Math.min(...a.map(c=>c.south)),north:Math.max(...a.map(c=>c.north)),west:Math.min(...a.map(c=>c.west)),east:Math.max(...a.map(c=>c.east))};return{tiles:r,bounds:o}}const jT="#2ec4ff";class qo{constructor(e){this.ctx=e}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(e,t){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-e,s.y-t);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(e){const{ctx:t}=this;t.save(),this.targets=[],t.clearRect(0,0,this.width,this.height),this.paintGround(e),this.paintNight(e.nightFraction),this.paintPath(e),this.paintTraces(e),e.position?(this.paintCone(e,e.position),this.paintDecor(e),this.paintMarkers(e),this.paintObserver(e,e.position)):(this.paintDecor(e),this.paintMarkers(e)),this.paintNorth(),this.paintFooter(e.bounds,e.attribution),t.restore()}toCanvas(e,t,i){const n=S2(e,i,t);return{x:n.x*this.width,y:n.y*this.height}}paintGround(e){const{ctx:t}=this;t.fillStyle="#1d2321",t.fillRect(0,0,this.width,this.height);const i=e.imagery;if(!i)return;const n=this.toCanvas(e.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(e.bounds,i.bounds.south,i.bounds.east);t.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(e=0){if(e<=0)return;const{ctx:t}=this;t.save(),t.fillStyle=`rgba(6, 12, 30, ${Math.min(e,1)*.78})`,t.fillRect(0,0,this.width,this.height),t.restore()}paintDecor(e){const{ctx:t}=this;for(const i of e.decor){const n=this.toCanvas(e.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}),t.beginPath(),t.rect(n.x-3.5,n.y-3.5,7,7),t.fillStyle="rgba(120, 220, 255, 0.85)",t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.7)",t.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;t.beginPath(),t.moveTo(n.x,n.y),t.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),t.lineWidth=3,t.strokeStyle="rgba(0, 0, 0, 0.6)",t.stroke(),t.lineWidth=1.5,t.strokeStyle="rgba(120, 220, 255, 0.9)",t.stroke()}}paintPath(e){if(!e.path.moved)return;const{ctx:t}=this,i=e.path.points.map(n=>this.toCanvas(e.bounds,n.lat,n.lng));t.beginPath(),t.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))t.lineTo(n.x,n.y);t.lineJoin="round",t.lineCap="round",t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=5,t.stroke(),t.strokeStyle="rgba(255, 255, 255, 0.9)",t.lineWidth=2,t.stroke()}paintTraces(e){const{ctx:t}=this;for(const i of e.traces??[]){const n=i.points.map(r=>this.toCanvas(e.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??jT;if(i.kind==="point")t.beginPath(),t.moveTo(n[0].x,n[0].y-6),t.lineTo(n[0].x+6,n[0].y),t.lineTo(n[0].x,n[0].y+6),t.lineTo(n[0].x-6,n[0].y),t.closePath(),t.fillStyle=s,t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.8)",t.stroke();else{t.beginPath(),t.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))t.lineTo(r.x,r.y);i.kind==="polygon"&&t.closePath(),t.lineJoin="round",t.setLineDash([]),t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=4.5,t.stroke(),t.setLineDash([9,5]),t.strokeStyle=s,t.lineWidth=2.5,t.stroke(),t.setLineDash([])}if(i.label){t.font="11px sans-serif",t.textAlign="left",t.textBaseline="middle";let r=n[0];if(i.kind==="line"&&e.position){const a=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=n.reduce((o,c)=>Math.hypot(c.x-a.x,c.y-a.y)>Math.hypot(o.x-a.x,o.y-a.y)?c:o)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(e,t){const{headingDeg:i,coneHalfAngleDeg:n}=e;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(e.bounds,t.lat,t.lng),a=Math.hypot(this.width,this.height),o=(i-90)*Math.PI/180,c=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,a,o-c,o+c),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(e){const{ctx:t}=this;t.textAlign="center",t.textBaseline="middle",t.font="bold 10px sans-serif";for(const i of[...e.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(e.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:qo.MARKER_RADIUS_PX}),t.beginPath(),t.arc(n.x,n.y,qo.MARKER_RADIUS_PX,0,Math.PI*2),t.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",t.fill(),t.lineWidth=2,t.strokeStyle="rgba(255, 255, 255, 0.9)",t.stroke(),t.fillStyle=i.current?"#1d2321":"#fff",t.fillText(i.label,n.x,n.y)}}paintObserver(e,t){const{ctx:i}=this,n=this.toCanvas(e.bounds,t.lat,t.lng);e.observerLabel&&this.targets.push({kind:"observer",label:e.observerLabel,lat:t.lat,lng:t.lng,x:n.x,y:n.y,radius:8});const s=e.markers.some(r=>{if(!r.current)return!1;const a=st(r.lat,r.lng,t.lat,t.lng);return Math.hypot(a.x,a.z)<=qo.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?qo.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:e}=this,t=this.width-14,i=16;e.beginPath(),e.moveTo(t,i-9),e.lineTo(t-4.5,i+5),e.lineTo(t,i+2),e.lineTo(t+4.5,i+5),e.closePath(),e.fillStyle="rgba(255, 255, 255, 0.92)",e.strokeStyle="rgba(0, 0, 0, 0.6)",e.lineWidth=1,e.fill(),e.stroke(),e.font="bold 9px sans-serif",e.textAlign="center",e.textBaseline="top",e.strokeText("N",t,i+6),e.fillText("N",t,i+6)}paintFooter(e,t){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=t?this.wrap(t,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const p of n.slice().reverse())this.paintOutlinedText(p,this.width-6,s),s-=11;const r=(e.south+e.north)/2,o=Math.abs(st(r,e.east,r,e.west).x)/this.width,c=qo.SCALE_STEPS_M.find(p=>p/o<=this.width/3);if(c===void 0)return;const h=c/o,d=8,u=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(d,u),i.lineTo(d+h,u),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(c>=1e3?`${c/1e3} km`:`${c} m`,d,u-3)}paintOutlinedText(e,t,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(e,t,i),n.fillStyle="#fff",n.fillText(e,t,i)}wrap(e,t){const i=[];let n="";for(const s of e.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>t?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class Zt{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(e,t){return Zt.including(e.boundsAround(Zt.MIN_SPAN_M,Zt.MARGIN),t)}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(e,t,i){const n=Math.min(Zt.MAX_ZOOM,Math.max(Zt.MIN_ZOOM,this.zoom*i)),s=this.centerX+(e-.5)/this.zoom,r=this.centerY+(t-.5)/this.zoom;this.centerX=s-(e-.5)/n,this.centerY=r-(t-.5)/n,this.zoom=n}panBy(e,t){this.centerX-=e/this.zoom,this.centerY-=t/this.zoom}refit(e,t){if(!this.changed)return;const i=this.boundsWithin(e),n=Zt.mercatorY01(t.north),s=Zt.mercatorY01(t.south),r=Zt.mercatorY01(i.north),a=Zt.mercatorY01(i.south);this.zoom=(t.east-t.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-t.west)/(t.east-t.west),this.centerY=((r+a)/2-n)/(s-n)}keepInView(e,t,i){if(!this.changed)return!1;const n=this.boundsWithin(e),s=Zt.mercatorY01(n.north),r=Zt.mercatorY01(n.south),a=(t.lng-n.west)/(n.east-n.west),o=(Zt.mercatorY01(t.lat)-s)/(r-s);return a>=i&&a<=1-i&&o>=i&&o<=1-i?!1:(this.panBy(.5-a,.5-o),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=Zt.mercatorY01(e.north),n=Zt.mercatorY01(e.south),s=e.east-e.west;return{west:e.west+(this.centerX-t)*s,east:e.west+(this.centerX+t)*s,north:Zt.latitudeAt(i+(this.centerY-t)*(n-i)),south:Zt.latitudeAt(i+(this.centerY+t)*(n-i))}}static including(e,t,i=3){const n=(e.north+e.south)/2,s=(e.east+e.west)/2,r=st(n,e.east,n,s).x;let a=r;for(const o of t){const{x:c,z:h}=st(o.lat,o.lng,n,s),d=Math.max(Math.abs(c),Math.abs(h));d<=r*i&&(a=Math.max(a,d*1.15))}return a<=r?e:{north:ws(0,-a,n,s).lat,south:ws(0,a,n,s).lat,east:ws(a,0,n,s).lng,west:ws(-a,0,n,s).lng}}static expand(e,t){const i=e.east-e.west,n=e.north-e.south;return{west:e.west-i*t,east:e.east+i*t,south:e.south-n*t,north:e.north+n*t}}static pointAt(e,t,i){const n=Zt.mercatorY01(e.north),s=Zt.mercatorY01(e.south);return{lat:Zt.latitudeAt(n+i*(s-n)),lng:e.west+t*(e.east-e.west)}}static mercatorY01(e){const t=e*Math.PI/180;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}static latitudeAt(e){return Math.atan(Math.sinh(Math.PI*(1-2*e)))*180/Math.PI}}const tr=256,ny=3,ZT=32768;class A2{fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(e,t){const i=(e.south+e.north)/2,n=(e.west+e.east)/2,s=Math.abs(st(i,e.east,i,e.west).x),r=Math.abs(st(e.north,n,e.south,n).z),a=KT(i,Math.max(s,r)),{tiles:o}=E2(n,i,a,ny),c=ny*tr,h=new Float32Array(c*c),d=o[0];await Promise.all(o.map(p=>this.decodeTileInto(p,d,h,c)));const u=new Float32Array(t.width*t.height);for(let p=0;p<t.height;p++){const f=e.north+(e.south-e.north)*(p/(t.height-1));for(let m=0;m<t.width;m++){const v=e.west+(e.east-e.west)*(m/(t.width-1));u[p*t.width+m]=this.sampleAt(f,v,a,d,h,c)}}return{heights:u,width:t.width,height:t.height,bounds:e}}async decodeTileInto(e,t,i,n){const s=this.tileUrlTemplate.replace("{z}",String(e.z)).replace("{x}",String(e.x)).replace("{y}",String(e.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()),o=document.createElement("canvas");o.width=tr,o.height=tr;const c=o.getContext("2d");if(!c)throw new Error("2D canvas context unavailable");c.drawImage(a,0,0);const{data:h}=c.getImageData(0,0,tr,tr),d=(e.x-t.x)*tr,u=(e.y-t.y)*tr;for(let p=0;p<tr;p++)for(let f=0;f<tr;f++){const m=(p*tr+f)*4,v=h[m]*256+h[m+1]+h[m+2]/256-ZT,g=d+f,y=u+p;i[y*n+g]=v}}sampleAt(e,t,i,n,s,r){const{x:a,y:o}=x2(t,e,i),c=(a-n.x)*tr,h=(o-n.y)*tr,d=Math.max(0,Math.min(r-1,Math.floor(c))),u=Math.max(0,Math.min(r-1,Math.floor(h))),p=Math.min(r-1,d+1),f=Math.min(r-1,u+1),m=c-d,v=h-u,g=s[u*r+d],y=s[u*r+p],w=s[f*r+d],b=s[f*r+p],M=g+(y-g)*m,S=w+(b-w)*m;return M+(S-M)*v}}class lm{constructor(e,t,i,n){this.width=e,this.height=t,this.samples=i,this.values=n}at(e,t,i=0){return this.values[(t*this.width+e)*this.samples+i]}static parse(e){const t=new DataView(e);if(e.byteLength<8||t.getUint16(0)!==18761||t.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=t.getUint32(4,!0),n=t.getUint16(i,!0),s=new Map;for(let g=0;g<n;g++){const y=i+2+g*12;s.set(t.getUint16(y,!0),{type:t.getUint16(y+2,!0),count:t.getUint32(y+4,!0),value:t.getUint32(y+8,!0)})}const r=(g,y)=>{const w=s.get(g);if(w===void 0){if(y===void 0)throw new Error(`TIFF without tag ${g}`);return y}return w.type===3?w.value&65535:w.value},a=g=>{const y=s.get(g);if(y===void 0)throw new Error(`TIFF without tag ${g}`);const w=y.type===3?2:4,b=[];if(y.count*w<=4){const M=new DataView(new ArrayBuffer(4));M.setUint32(0,y.value,!0);for(let S=0;S<y.count;S++)b.push(w===2?M.getUint16(S*2,!0):M.getUint32(0,!0))}else for(let M=0;M<y.count;M++)b.push(w===2?t.getUint16(y.value+M*2,!0):t.getUint32(y.value+M*4,!0));return b};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const o=r(256),c=r(257),h=r(277,1),d=a(258)[0],u=r(339,1)===3;if(!(u&&d===32||!u&&d===8))throw new Error(`Unsupported TIFF samples: ${d} bits`);const p=a(273),f=a(279),m=new Uint8Array(o*c*h*(d/8));let v=0;for(let g=0;g<p.length&&v<m.length;g++){const y=Math.min(f[g],m.length-v);m.set(new Uint8Array(e,p[g],y),v),v+=y}if(v<m.length)throw new Error("Truncated TIFF");return new lm(o,c,h,u?new Float32Array(m.buffer):m)}}class JT{constructor(e,t,i,n,s){this.heights=e,this.plants=t,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(e,t){const i=Math.floor(e/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-t/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(e,t,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 o=this.structureAt(e+a*this.metresPerPixel,t+r*this.metresPerPixel);o!==void 0&&(n===void 0||o>n)&&(n=o)}return n}}class Re{static METRES_PER_DEGREE=111320;static MIN_BRIDGE_M=4;static DEFAULT_DECK_M=6;static FOOTBRIDGE_DECK_M=2.5;static DECK_MARGIN_M=2.4;static JOIN_M=1;static JOIN_DEG=25;static RAIL_MATCH_M=6;static ROAD_MATCH_M=12;static DECK_SEEN_M=1.5;static DECK_STEP_M=.5;static DECK_GAP_M=2;static DECK_REACH_M=20;static DECK_MEETS_M=.3;static DECK_BEARING_M=4;static DEFAULT_DECK_HEIGHT_M=4;static MIN_POLE_M=6;static MAX_POLE_M=70;static MAX_SPAN_M=800;static MAX_LINES=16;static BY_VOLTAGE=[{upToKv:25,poleM:11,dropM:1.2,spreadM:.8},{upToKv:70,poleM:20,dropM:3,spreadM:3},{upToKv:100,poleM:22,dropM:3.5,spreadM:3.5},{upToKv:170,poleM:27,dropM:4.5,spreadM:4.5},{upToKv:250,poleM:32,dropM:5.5,spreadM:5.5},{upToKv:1e3,poleM:42,dropM:7,spreadM:7.5}];static toMetres(e,t){const[i,n]=e;return{east:(i-t.lng)*Re.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180),north:(n-t.lat)*Re.METRES_PER_DEGREE}}static path(e,t){return e.geometry.type!=="LineString"?[]:e.geometry.coordinates.map(i=>Re.toMetres(i,t))}static bearing(e,t){return(Math.atan2(t.east-e.east,t.north-e.north)*180/Math.PI+360)%360}static distanceToSegment(e,t,i){const n=i.east-t.east,s=i.north-t.north,r=n*n+s*s,a=r===0?0:Math.max(0,Math.min(1,((e.east-t.east)*n+(e.north-t.north)*s)/r));return Math.hypot(e.east-(t.east+a*n),e.north-(t.north+a*s))}static bridges(e,t,i,n){const s=e.elevatedRoads.map(o=>({path:Re.path(o,t),properties:o.properties})),r=(e.elevatedRailways??[]).map(o=>Re.path(o,t)),a=[];for(const o of Re.joined(e.bridges.map(c=>Re.path(c,t)))){const c=o[0],h=o[o.length-1],d=Math.hypot(h.east-c.east,h.north-c.north);if(d<Re.MIN_BRIDGE_M)continue;const u={east:(c.east+h.east)/2,north:(c.north+h.north)/2};if(Math.hypot(u.east,u.north)>i+d/2||Re.carriesRailway(c,h,r))continue;const[p,f]=Re.deckReach(c,h,n);a.push({eastM:Re.tenth((p.east+f.east)/2),northM:Re.tenth((p.north+f.north)/2),lengthM:Re.tenth(Math.hypot(f.east-p.east,f.north-p.north)),widthM:Re.roadOf(u,s).width,heightM:Re.tenth(Re.deckHeight(c,h,n)),headingDeg:Re.tenth(Re.bearing(c,h)%180),...Re.roadOf(u,s).name?{name:Re.roadOf(u,s).name}:{}})}return a.sort((o,c)=>Math.hypot(o.eastM,o.northM)-Math.hypot(c.eastM,c.northM)),a}static carriesRailway(e,t,i){const n={east:(e.east+t.east)/2,north:(e.north+t.north)/2},s=Re.bearing(e,t)%180;for(const r of i)for(let a=0;a+1<r.length;a++){if(Re.distanceToSegment(n,r[a],r[a+1])>Re.RAIL_MATCH_M)continue;const o=Math.abs(Re.bearing(r[a],r[a+1])%180-s);if(Math.min(o,180-o)<=Re.JOIN_DEG)return!0}return!1}static joined(e){const t=e.filter(i=>i.length>=2);for(let i=0;i<t.length;i++)for(let n=i+1;n<t.length;n++){const s=Re.join(t[i],t[n]);s!==void 0&&(t[i]=s,t.splice(n,1),n=i)}return t}static join(e,t){for(const i of[e,[...e].reverse()])for(const n of[t,[...t].reverse()]){const s=i[i.length-1],r=n[0];if(Math.hypot(s.east-r.east,s.north-r.north)>Re.JOIN_M)continue;const a=Math.abs(Re.bearing(i[0],s)-Re.bearing(r,n[n.length-1]));if(Math.min(a,360-a)<=Re.JOIN_DEG)return[...i,...n.slice(1)]}}static roadOf(e,t){let i;for(const a of t)for(let o=0;o+1<a.path.length;o++){const c=Re.distanceToSegment(e,a.path[o],a.path[o+1]);(i===void 0||c<i.distance)&&(i={distance:c,properties:a.properties})}if(i===void 0||i.distance>Re.ROAD_MATCH_M)return{width:Re.DEFAULT_DECK_M};const n=[i.properties.nom_voie_ban_gauche,i.properties.nom_voie_ban_droite,i.properties.cpx_toponyme_route_nommee].find(a=>typeof a=="string"&&a.length>0),s=Number(i.properties.largeur_de_chaussee),r=Number.isFinite(s)&&s>0?Re.tenth(s+Re.DECK_MARGIN_M):i.properties.nature==="Sentier"?Re.FOOTBRIDGE_DECK_M:Re.DEFAULT_DECK_M;return n?{width:r,name:n}:{width:r}}static deckReach(e,t,i){const n=Math.hypot(t.east-e.east,t.north-e.north);if(i===void 0||n===0)return[e,t];const s={east:(e.east+t.east)/2,north:(e.north+t.north)/2},r={east:(t.east-e.east)/n,north:(t.north-e.north)/n},a=u=>(i.structureAt(s.east+r.east*u,s.north+r.north*u)??0)>=Re.DECK_SEEN_M,o=u=>i.structureAt(s.east+r.east*u,s.north+r.north*u)??0,c=u=>{let p;for(let m=0;m<=n/2+Re.DECK_REACH_M;m+=Re.DECK_STEP_M)if(a(u*m))p=m;else if(p!==void 0&&m-p>Re.DECK_GAP_M)break;if(p===void 0)return n/2;let f=p;for(;f-p<Re.DECK_REACH_M&&o(u*(f+Re.DECK_STEP_M))>=Re.DECK_MEETS_M;)f+=Re.DECK_STEP_M;return Math.max(n/2,f+Re.DECK_BEARING_M)},h=c(-1),d=c(1);return[{east:s.east-r.east*h,north:s.north-r.north*h},{east:s.east+r.east*d,north:s.north+r.north*d}]}static deckHeight(e,t,i){if(i===void 0)return Re.DEFAULT_DECK_HEIGHT_M;const n=[],s=20;for(let r=4;r<=s-4;r++){const a=i.structureAt(e.east+(t.east-e.east)*r/s,e.north+(t.north-e.north)*r/s);a!==void 0&&a>=1.5&&n.push(a)}return n.length===0?Re.DEFAULT_DECK_HEIGHT_M:(n.sort((r,a)=>r-a),n[Math.floor(n.length/2)])}static lines(e,t,i,n){const s=[];for(const r of e.lines){const a=String(r.properties.voltage??""),o=Re.kilovolts(a);if(o===void 0)continue;const c=Re.BY_VOLTAGE.find(d=>o<=d.upToKv)??Re.BY_VOLTAGE[Re.BY_VOLTAGE.length-1],h=Re.path(r,t);for(let d=0;d+1<h.length;d++){const u=h[d],p=h[d+1],f=Math.hypot(p.east-u.east,p.north-u.north);if(f<5||f>Re.MAX_SPAN_M||Re.distanceToSegment({east:0,north:0},u,p)>i)continue;const m=Re.poleHeight(u,p,n)??c.poleM;s.push({eastM:Re.tenth((u.east+p.east)/2),northM:Re.tenth((u.north+p.north)/2),lengthM:Re.tenth(f),headingDeg:Re.tenth(Re.bearing(u,p)),heightM:Re.tenth(Math.max(4,m-c.dropM)),poleHeightM:Re.tenth(m),acrossM:[-c.spreadM,0,c.spreadM],voltage:a})}}return s.sort((r,a)=>Math.hypot(r.eastM,r.northM)-Math.hypot(a.eastM,a.northM)),s.slice(0,Re.MAX_LINES)}static kilovolts(e){const t=/([\d.,]+)\s*kV/i.exec(e);if(t===null)return;const i=Number(t[1].replace(",","."));return Number.isFinite(i)&&i>0?i:void 0}static poleHeight(e,t,i){if(i===void 0)return;const n=[e,t].map(s=>i.tallestStructureNear(s.east,s.north,3)).filter(s=>s!==void 0&&s>=Re.MIN_POLE_M&&s<=Re.MAX_POLE_M);return n.length===0?void 0:n.reduce((s,r)=>s+r,0)/n.length}static tenth(e){return Math.round(e*10)/10}}class Pt{static covers(e,t){return e>=41.2&&e<=51.3&&t>=-5.4&&t<=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(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??Pt.WMS,this.wfs=e.wfsEndpoint??Pt.WFS}static radius(e){return Math.min(e,Pt.MAX_RADIUS_M)}static lidarRadius(e){return Math.min(e,Pt.MAX_LIDAR_RADIUS_M)}async lidar(e,t){const i=Pt.lidarRadius(t),n=Math.ceil(2*i/Pt.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(e,i,n,Pt.HEIGHT_LAYER),this.raster(e,i,n,Pt.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new wr("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(d=>d===Pt.NO_DATA))throw new wr("no-coverage","No LiDAR HD survey here yet");const o=new Uint8Array(n*n),c=new Uint8Array(n*n);for(let d=0;d<n*n;d++){const u=r.values[d*r.samples],p=r.values[d*r.samples+1],f=r.values[d*r.samples+2];o[d]=p>u&&p>f?1:0,c[d]=u>120&&p<90&&f<90?1:0}const h=2*i/n;return{size:n,metresPerPixel:h,heights:a,vegetation:o,building:c,structures:new JT(a,o,c,n,h)}}async laserDate(e){return Pt.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",e))}async photoDate(e){return Pt.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",e))}static latest(e){return e.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(e,t,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(e,`BBOX(${t},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(e,t){const i=Pt.radius(t),n=Math.min(Pt.MAX_PHOTO_PIXELS,Math.ceil(2*i/Pt.METRES_PER_PIXEL)),s=await this.raster(e,i,n,Pt.PHOTO_LAYER);if(s.samples<3)throw new wr("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(e,t,i){const n=Pt.radius(t),s=n/Pt.METRES_PER_DEGREE,r=n/(Pt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),o=`BBOX(geometrie,${[e.lng-r,e.lat-s,e.lng+r,e.lat+s].map(g=>g.toFixed(6)).join(",")},'EPSG:4326')`,[c,h,d,u,p,f]=await Promise.all([this.features("construction_lineaire",`${o} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${o} 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",`${o} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",o,"voltage,geometrie"),i?this.features("batiment",o,Pt.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",o,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(f,p,[e.lng-r,e.lat-s,e.lng+r,e.lat+s]):[],v=[...p,...m];return{bridges:c,elevatedRoads:h,elevatedRailways:d,lines:u,buildings:v,zones:f,mapDate:Pt.latest(v.map(g=>g.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(e,t,i){const[n,s,r,a]=i,o=Pt.MAX_WHOLE_M/Pt.METRES_PER_DEGREE;let c;for(const d of e){if(d.properties.categorie!=="Religieux")continue;const[u,p,f,m]=Pt.extent(d);if(u>=n&&p>=s&&f<=r&&m<=a)continue;const v=[Math.max(u,n-o),Math.max(p,s-o),Math.min(f,r+o),Math.min(m,a+o)];c=c?[Math.min(c[0],v[0]),Math.min(c[1],v[1]),Math.max(c[2],v[2]),Math.max(c[3],v[3])]:v}if(!c)return[];const h=new Set(t.map(d=>d.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${c.map(u=>u.toFixed(6)).join(",")},'EPSG:4326')`,Pt.BUILDING_PROPERTIES,1e3)).filter(u=>!h.has(u.properties.cleabs))}catch{return[]}}static extent(e){let t=1/0,i=1/0,n=-1/0,s=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(t=Math.min(t,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(e.geometry.coordinates),[t,i,n,s]}async elevatedRoadLines(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${t} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,o=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const c of o)n.push(c.map(h=>({lat:h[1],lng:h[0]})))}return n}async waterSurfaces(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${t} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${t} 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(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${t} 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(e,t,i,n){const s=t/Pt.METRES_PER_DEGREE,r=t/(Pt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[e.lat-s,e.lng-r,e.lat+s,e.lng+r].map(c=>c.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let o;try{o=await this.fetchImpl(`${this.wms}?${a}`)}catch(c){throw new wr("unreachable",c instanceof Error?c.message:String(c))}if(!o.ok)throw new wr("unreachable",`The survey answered ${o.status}`);try{return lm.parse(await o.arrayBuffer())}catch(c){throw new wr("unreachable",c instanceof Error?c.message:String(c))}}async features(e,t,i,n=200){const s=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:e.includes(":")?e:`BDTOPO_V3:${e}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(n),CQL_FILTER:t,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(o){throw new wr("unreachable",o instanceof Error?o.message:String(o))}if(!r.ok)throw new wr("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class oo{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(e,t){if(e.length<2||t.length<2)return!1;const i=t[0],n=t.map(a=>st(a.lat,a.lng,i.lat,i.lng)),s=e.map(a=>st(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const o=s[a],c=s[a+1],h=Math.hypot(c.x-o.x,c.z-o.z);if(h<1e-6)continue;const d=Math.max(1,Math.ceil(h/oo.SAMPLE_M)),u=Math.atan2(c.x-o.x,-(c.z-o.z));for(let p=0;p<=d;p++){const f=p/d,m=oo.nearest(n,o.x+(c.x-o.x)*f,o.z+(c.z-o.z)*f);m.distanceM>oo.NEAR_M||oo.angleBetween(u,m.heading)<=oo.ALIGNED_DEG&&(r+=h/d)}}return r>=oo.LONG_ENOUGH_M}static nearest(e,t,i){let n={distanceM:1/0,heading:0};for(let s=0;s<e.length-1;s++){const r=e[s],a=e[s+1],o=a.x-r.x,c=a.z-r.z,h=o*o+c*c,d=h<1e-9?0:Math.max(0,Math.min(1,((t-r.x)*o+(i-r.z)*c)/h)),u=Math.hypot(t-(r.x+o*d),i-(r.z+c*d));u<n.distanceM&&(n={distanceM:u,heading:Math.atan2(o,-c)})}return n}static angleBetween(e,t){const i=Math.abs((e-t)*180/Math.PI%180);return Math.min(i,180-i)}}class kt{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(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??kt.WMS,this.timeoutMs=e.timeoutMs??kt.DEFAULT_TIMEOUT_MS,this.maxWindowM=e.maxWindowM??kt.MAX_WINDOW_M,this.geoplatform=new Pt({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:e.wfsEndpoint})}async getElevationGrid(e,t,i){const n={lat:(e.south+e.north)/2,lng:(e.west+e.east)/2};if(!Pt.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(st(n.lat,e.east,n.lat,e.west).x),r=Math.abs(st(e.north,n.lng,e.south,n.lng).z);t=this.finer(t,s,r);const a={x:s/Math.max(1,t.width-1),y:r/Math.max(1,t.height-1)},o={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},c={south:e.south-o.y/kt.METRES_PER_DEGREE,north:e.north+o.y/kt.METRES_PER_DEGREE,west:e.west-o.x/(kt.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:e.east+o.x/(kt.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},h=m=>Math.min(kt.MAX_PIXELS,Math.max(kt.MIN_PIXELS,Math.ceil(m/kt.METRES_PER_PIXEL))),d={width:h(s+2*o.x),height:h(r+2*o.y)},u={x:(s+2*o.x)/d.width,y:(r+2*o.y)/d.height};let p=new Error("No layer of the IGN's relief answered");const f=Math.max(u.x,u.y)>kt.COARSE_METRES_PER_PIXEL;for(const m of f?[...kt.LAYERS].reverse():kt.LAYERS)try{const v=await this.heights(c,d,m);m===kt.LAYERS[0]&&await this.layBridgeDecks(v,c,d,i?.route);const g=this.sample(v,t,e,c,u,a);if(g)return{heights:g,width:t.width,height:t.height,bounds:e};p=new Error(`${m} does not cover this place`)}catch(v){p=v}throw p}finer(e,t,i){if(e.width<kt.MESH_FROM_VERTICES||e.height<kt.MESH_FROM_VERTICES)return e;const n=(s,r)=>{const a=Math.ceil(s/kt.FINE_SPACING_M),o=Math.max(r-1,Math.min(kt.MAX_SEGMENTS,a));return o%2===0?o:o+1};return{width:n(t,e.width)+1,height:n(i,e.height)+1}}async raster(e,t,i){const n=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[e.south,e.west,e.north,e.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(t.width),HEIGHT:String(t.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 lm.parse(await s.arrayBuffer())}async heights(e,t,i){const n=await this.raster(e,t,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(e,t,i,n){if(!(!n||n.length<2)&&!(!(e.values instanceof Float32Array)||!e.values.some(s=>s>kt.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:t.west,south:t.south,east:t.east,north:t.north})).filter(a=>oo.follows(n,a));if(s.length===0)return;const r=Float32Array.from(e.values);await this.layClassifiedDecks(e,t,i,s),this.layRouteDecks(e,r,t,s)}catch{}}async layClassifiedDecks(e,t,i,n){try{const s=await this.raster(t,i,kt.CLASS_LAYER);if(s.samples<3||s.width!==e.width||s.height!==e.height)return;const r=(v,[g,y,w])=>s.values[v*s.samples]===g&&s.values[v*s.samples+1]===y&&s.values[v*s.samples+2]===w,a=e.width,o=e.height,c=new Uint8Array(a*o);let h=!1;for(let v=0;v<c.length;v++)r(v,kt.DECK)&&(c[v]=1,h=!0);if(!h)return;const d=kt.DECK_END_PIXELS,u=[];for(let v=0;v<c.length;v++){if(c[v]!==1)continue;const g=v%a,y=(v-g)/a;for(let w=-d;w<=d;w++)for(let b=-d;b<=d;b++){const M=g+b,S=y+w;if(M<0||S<0||M>=a||S>=o)continue;const E=S*a+M;c[E]===0&&r(E,kt.NO_CLASS)&&u.push(E)}}for(const v of u)c[v]=1;const p=this.paint(n,t,a,o),f=this.touching(c,p,a,o);if(f.every(v=>v===0))return;const m=await this.heights(t,i,kt.SURFACE_LAYER);if(m.width!==a||m.height!==o)return;for(let v=0;v<f.length;v++){if(f[v]===0)continue;const g=m.values[v];Number.isFinite(g)&&g>kt.NO_DATA_BELOW&&g>e.values[v]&&(e.values[v]=g)}}catch{}}layRouteDecks(e,t,i,n){const{width:s,height:r}=e,a=(i.north+i.south)/2,o=(i.east-i.west)*kt.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),c=(i.north-i.south)*kt.METRES_PER_DEGREE,h=o/s,d=c/r,u=g=>({x:(g.lng-i.west)/(i.east-i.west)*o,y:(i.north-g.lat)/(i.north-i.south)*c}),p=(g,y)=>{const w=Math.floor(g/h),b=Math.floor(y/d);if(w<0||b<0||w>=s||b>=r)return;const M=t[b*s+w];return Number.isFinite(M)&&M>kt.NO_DATA_BELOW?M:void 0},f=kt.DECK_HALF_WIDTH_M,m=kt.DECK_APPROACH_M,v=(g,y)=>{const w=Math.hypot(g.x-y.x,g.y-y.y)||1,b={x:(g.x-y.x)/w,y:(g.y-y.y)/w},M=[0,m/2,m].map(S=>p(g.x+b.x*S,g.y+b.y*S)).filter(S=>S!==void 0);return M.length>0?Math.max(...M):void 0};for(const g of kt.chains(n.map(y=>y.map(u)))){const y=[0];for(let R=1;R<g.length;R++)y.push(y[R-1]+Math.hypot(g[R].x-g[R-1].x,g[R].y-g[R-1].y));const w=y[y.length-1];if(w<1||w>kt.DECK_STRAIGHT_MAX_M)continue;const b=v(g[0],g[1]),M=v(g[g.length-1],g[g.length-2]);if(b===void 0||M===void 0)continue;const S=f+m,E=Math.max(0,Math.floor((Math.min(...g.map(R=>R.x))-S)/h)),x=Math.min(s-1,Math.ceil((Math.max(...g.map(R=>R.x))+S)/h)),T=Math.max(0,Math.floor((Math.min(...g.map(R=>R.y))-S)/d)),D=Math.min(r-1,Math.ceil((Math.max(...g.map(R=>R.y))+S)/d));for(let R=T;R<=D;R++)for(let O=E;O<=x;O++){const N=kt.nearestAlong(g,y,{x:(O+.5)*h,y:(R+.5)*d});if(N.distance>f||N.s<-m||N.s>w+m)continue;const C=b+(M-b)*Math.min(1,Math.max(0,N.s/w)),k=R*s+O;t[k]>=C||(e.values[k]=C)}}}static chains(e){const t=e.filter(s=>s.length>=2).map(s=>[...s]),i=[],n=(s,r)=>Math.hypot(s.x-r.x,s.y-r.y)<=1;for(;t.length>0;){let s=t.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<t.length;a++){const o=t[a],c=s[0],h=s[s.length-1];if(n(h,o[0]))s=[...s,...o.slice(1)];else if(n(h,o[o.length-1]))s=[...s,...[...o].reverse().slice(1)];else if(n(c,o[o.length-1]))s=[...o.slice(0,-1),...s];else if(n(c,o[0]))s=[...[...o].reverse().slice(0,-1),...s];else continue;t.splice(a,1),r=!0;break}}i.push(s)}return i}static nearestAlong(e,t,i){let n={s:0,distance:1/0};for(let s=0;s<e.length-1;s++){const r=e[s],a=e[s+1],o=a.x-r.x,c=a.y-r.y,h=o*o+c*c;if(h<1e-9)continue;let d=((i.x-r.x)*o+(i.y-r.y)*c)/h;s>0&&(d=Math.max(0,d)),s<e.length-2&&(d=Math.min(1,d));const u=Math.hypot(i.x-(r.x+o*d),i.y-(r.y+c*d));u<n.distance&&(n={s:t[s]+d*Math.sqrt(h),distance:u})}return n}paint(e,t,i,n){const s=new Uint8Array(i*n),r=o=>(o-t.west)/(t.east-t.west)*i,a=o=>(t.north-o)/(t.north-t.south)*n;for(const o of e)for(let c=0;c<o.length-1;c++){const h=r(o[c].lng),d=a(o[c].lat),u=r(o[c+1].lng),p=a(o[c+1].lat),f=Math.max(1,Math.ceil(Math.hypot(u-h,p-d)*2));for(let m=0;m<=f;m++){const v=Math.floor(h+(u-h)*m/f),g=Math.floor(d+(p-d)*m/f);for(let y=-1;y<=1;y++)for(let w=-1;w<=1;w++){const b=v+w,M=g+y;b>=0&&M>=0&&b<i&&M<n&&(s[M*i+b]=1)}}}return s}touching(e,t,i,n){const s=new Uint8Array(e.length),r=new Uint8Array(e.length);for(let a=0;a<e.length;a++){if(e[a]===0||r[a]===1)continue;const o=[],c=[a];r[a]=1;let h=!1;for(;c.length>0;){const d=c.pop();o.push(d),t[d]===1&&(h=!0);const u=d%i,p=(d-u)/i;for(let f=-1;f<=1;f++)for(let m=-1;m<=1;m++){const v=u+m,g=p+f;if(v<0||g<0||v>=i||g>=n)continue;const y=g*i+v;e[y]===1&&r[y]===0&&(r[y]=1,c.push(y))}}if(h)for(const d of o)s[d]=1}return s}sample(e,t,i,n,s,r){const{width:a,height:o}=t,c=new Float32Array(a*o),h=new Uint8Array(a*o),d=Math.min(r.x,this.maxWindowM)/s.x,u=Math.min(r.y,this.maxWindowM)/s.y;let p=0;for(let f=0;f<o;f++){const m=i.north+(i.south-i.north)*(o===1?.5:f/(o-1)),v=(n.north-m)/(n.north-n.south)*e.height-.5;for(let g=0;g<a;g++){const w=(i.west+(i.east-i.west)*(a===1?.5:g/(a-1))-n.west)/(n.east-n.west)*e.width-.5,b=d>1||u>1?this.tent(e,w,v,Math.max(1,d),Math.max(1,u)):this.bilinear(e,w,v),M=f*a+g;b===void 0?p++:(c[M]=b,h[M]=1)}}if(!(p===a*o||p/(a*o)>kt.MAX_HOLE_SHARE))return this.fill(c,h,a,o),c}tent(e,t,i,n,s){let r=0,a=0,o=0;const c=Math.max(0,Math.ceil(i-s)),h=Math.min(e.height-1,Math.floor(i+s)),d=Math.max(0,Math.ceil(t-n)),u=Math.min(e.width-1,Math.floor(t+n));for(let p=c;p<=h;p++){const f=1-Math.abs(p-i)/s;if(!(f<=0))for(let m=d;m<=u;m++){const v=f*(1-Math.abs(m-t)/n);if(v<=0)continue;o+=v;const g=e.at(m,p);!Number.isFinite(g)||g<kt.NO_DATA_BELOW||(r+=v*g,a+=v)}}return o>0&&a>=o*.5?r/a:void 0}bilinear(e,t,i){const n=Math.max(0,Math.min(e.width-1,Math.floor(t))),s=Math.max(0,Math.min(e.height-1,Math.floor(i))),r=Math.min(e.width-1,n+1),a=Math.min(e.height-1,s+1),o=Math.max(0,Math.min(1,t-n)),c=Math.max(0,Math.min(1,i-s)),h=e.at(n,s),d=e.at(r,s),u=e.at(n,a),p=e.at(r,a);for(const v of[h,d,u,p])if(!Number.isFinite(v)||v<kt.NO_DATA_BELOW)return;const f=h+(d-h)*o,m=u+(p-u)*o;return f+(m-f)*c}fill(e,t,i,n){let s=t.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let o=0;o<i;o++){const c=a*i+o;if(t[c])continue;let h=0,d=0;for(let u=-1;u<=1;u++)for(let p=-1;p<=1;p++){const f=a+u,m=o+p;f<0||m<0||f>=n||m>=i||!t[f*i+m]||(h+=e[f*i+m],d++)}d>0&&r.push([c,h/d])}if(r.length===0)return;for(const[a,o]of r)e[a]=o,t[a]=1;s-=r.length}}}class QT{providers;constructor(...e){this.providers=e}async getElevationGrid(e,t,i){let n=new Error("No source of relief to ask");for(const s of this.providers)try{return await s.getElevationGrid(e,t,i)}catch(r){n=r}throw n}}const yp=256,eI=5;async function T2(l,e,t,i){const n=(l.south+l.north)/2,s=(l.west+l.east)/2,r=Math.abs(st(n,l.east,n,l.west).x),a=Math.abs(st(l.north,s,l.south,s).z),o=Math.max(r,a),{zoom:c,gridSize:h}=tI(n,o,Math.max(e.width,e.height)),{tiles:d,bounds:u}=E2(s,n,c,h),p=h*yp,f=document.createElement("canvas");f.width=p,f.height=p;const m=f.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const v=d[0];await Promise.all(d.map(async b=>{const M=t(b),S=await i(M);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${M}`);const E=await createImageBitmap(await S.blob());m.drawImage(E,(b.x-v.x)*yp,(b.y-v.y)*yp)}));const g=Math.min(Math.max(e.width,e.height),p);if(g===p)return{source:f,width:p,height:p,bounds:u};const y=document.createElement("canvas");y.width=g,y.height=g;const w=y.getContext("2d");if(!w)throw new Error("2D canvas context unavailable");return w.drawImage(f,0,0,p,p,0,0,g,g),{source:y,width:g,height:g,bounds:u}}function tI(l,e,t){let i=XT(l,e/Math.max(1,t)),n=sy(l,i,e);for(;n>eI&&i>0;)i--,n=sy(l,i,e);return{zoom:i,gridSize:n,mPerPixel:M2(l,i)/yp}}function sy(l,e,t){const i=Math.ceil(t/2/M2(l,e));return Math.max(3,2*i+1)}class I2{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(e,t){return T2(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class ks{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(e,t=ks.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(e);if(!i)return[...t];const[n,s,r,a]=i.slice(1).map(Number),o=(n+r)/2,c=(s+a)/2,h=ks.FRANCE;return o>=h.south&&o<=h.north&&c>=h.west&&c<=h.east?[ks.FRANCE_ENDPOINT,...t.filter(u=>u!==ks.FRANCE_ENDPOINT)]:[...t]}fetchImpl;endpoints;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.endpoints=e.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(e){return this.queued(()=>this.ask(e))}queued(e){const t=ks.queue.then(e,e);return ks.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints??ks.endpointsFor(e))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(ks.HANG_MS)});if(s.ok)return await s.json();if(t=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){t=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,ks.RETRY_MS))}throw t??new Error("No Overpass instance answered")}}class lo{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(e={}){this.client=new ks(e)}async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${lo.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(e){const t=[];for(const i of e.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||t.push({id:`osm-${i.id??t.length}`,name:s.name,surface:lo.surfaceOf(s),widthM:lo.widthOf(s),...lo.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return t}static paintOf(e){const t=e.highway??"",i=e.junction==="roundabout"||e.junction==="circular",n=e.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(t==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(e.lanes??"",10),o=Number.parseInt(e.maxspeed??"",10),c=i?"roundabout":t==="motorway"?"motorway":t.endsWith("_link")?"slip":(t==="trunk"||t==="primary")&&(s||r)?"dual":t?"road":void 0;return{...c?{kind:c}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||t==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{}}}static widthOf(e){const t=Number.parseFloat(e.width??e.est_width??"");if(Number.isFinite(t)&&t>0)return t;const i=Number.parseInt(e.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:lo.WIDTH_M[e.highway]??lo.DEFAULT_WIDTH_M}static surfaceOf(e){const t=e.surface;return t==="dirt"||t==="earth"||t==="mud"?"dirt":t==="gravel"||t==="fine_gravel"||t==="compacted"||t==="ground"||t==="sand"||t==="unpaved"?"gravel":t?"paved":e.highway==="track"?"gravel":"paved"}}const Tm="https://ufoathome.org/roads/index.json";class kc{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??kc.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRoads(e);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(e){let t;try{t=await this.load()}catch{return}const i=t.find(({entry:n})=>n.north>=e.north&&n.south<=e.south&&n.east>=e.east&&n.west<=e.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 e=this.indexUrls.join(`
4249
- `);let t=kc.shared.get(e);return t||(t=this.fetchFirstAvailable(),kc.shared.set(e,t),t.then(i=>{i.length===0&&kc.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.150.0")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==Tm?[t,Tm]:[Tm]).map(i=>i+e)}}class po{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(e={}){this.platform=new Pt(e)}static covers(e){return Pt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRoads(e){return(await this.platform.roads(e)).flatMap((i,n)=>po.wayOf(i,n))}static wayOf(e,t){if(e.geometry.type!=="LineString")return[];const i=e.geometry.coordinates.map(([u,p])=>({lat:p,lng:u}));if(i.length<2)return[];const n=String(e.properties.nature??""),s=po.BY_NATURE[n]??po.DEFAULT,r=Number(e.properties.largeur_de_chaussee),a=Number(e.properties.nombre_de_voies),o=Number(e.properties.vitesse_moyenne_vl),c=po.DIRECTIONS[String(e.properties.sens_de_circulation??"")],h=po.KINDS[n],d=[e.properties.cpx_toponyme_route_nommee,e.properties.nom_voie_ban_gauche,e.properties.nom_voie_ban_droite].find(u=>typeof u=="string"&&u.length>0);return[{id:String(e.properties.cleabs??`ign-${t}`),...d?{name:d}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...e.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...c?{direction:c}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{},points:i}]}}class iI{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(e){if(po.covers(e))try{const t=await this.regional.getRoads(e);if(t.length>0)return t}catch{}return this.worldwide.getRoads(e)}}class Pd{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(e={}){this.platform=new Pt(e)}static covers(e){return Pt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getWater(e){return(await this.platform.waterSurfaces(e)).flatMap((i,n)=>Pd.surfacesOf(i,n))}static surfacesOf(e,t){const{type:i,coordinates:n}=e.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(e.properties.cleabs??`ign-water-${t}`);return s.flatMap((a,o)=>{const c=a.map(h=>Pd.open(h.map(d=>({lat:d[1],lng:d[0]})))).filter(h=>h.length>=3);return c.length>0?[{id:s.length>1?`${r}-${o}`:r,rings:c}]:[]})}static open(e){const t=e[0],i=e[e.length-1];return e.length>1&&t.lat===i.lat&&t.lng===i.lng?e.slice(0,-1):e}}class jo{attribution="Water © OpenStreetMap contributors";client;constructor(e={}){this.client=new ks(e)}async getWater(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${t});way["waterway"="riverbank"](${t});)->.w;(relation["natural"="water"](${t});relation["waterway"="riverbank"](${t});)->.r;.w out geom;.r out body;way(r.r)(${t});out geom;`;return jo.surfacesFrom(await this.client.query(i))}static surfacesFrom(e){const t=e.elements??[],i=new Map;for(const r of t)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 t){if(r.type!=="relation")continue;const a=c=>(r.members??[]).filter(h=>h.type==="way"&&h.role===c&&h.ref!==void 0&&i.has(h.ref)).map(h=>(s.add(h.ref),i.get(h.ref))),o=jo.rings(a("inner"));for(const[c,h]of jo.rings(a("outer")).entries()){const d=o.filter(u=>jo.contains(h,u[0]));n.push({id:`osm-r${r.id}-${c}`,rings:[h,...d]})}}for(const r of t)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 jo.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(e){const t=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=e.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!t(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const o=i[a],c=s[s.length-1];if(t(c,o[0]))s=[...s,...o.slice(1)];else if(t(c,o[o.length-1]))s=[...s,...[...o].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&t(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(e,t){let i=!1;for(let n=0,s=e.length-1;n<e.length;s=n++){const r=e[n],a=e[s];r.lat>t.lat!=a.lat>t.lat&&t.lng<(a.lng-r.lng)*(t.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class nI{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(e){if(Pd.covers(e))try{const t=await this.regional.getWater(e);if(t.length>0)return t}catch{}return this.worldwide.getWater(e)}}const Im="https://ufoathome.org/water/index.json";class Cc{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Cc.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getWater(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=e.north&&n.south<=e.south&&n.east>=e.east&&n.west<=e.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 e=this.indexUrls.join(`
4250
- `);let t=Cc.shared.get(e);return t||(t=this.fetchFirstAvailable(),Cc.shared.set(e,t),t.then(i=>{i.length===0&&Cc.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.150.0")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==Im?[t,Im]:[Im]).map(i=>i+e)}}class As{constructor(e){this.water=e}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(e){const t=As.key(e);let i=As.asked.get(t);return i===void 0&&(i=this.recalled(t,e),As.asked.set(t,i),i.catch(()=>As.asked.delete(t))),structuredClone(await i)}static forget(){As.asked.clear()}static key(e){return`v${As.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await As.openCache(),n=As.request(e);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<As.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(n)}}catch{}const s=await this.water.getWater(t);return i&&As.store(i,n,s),s}static async store(e,t,i){try{const n={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const r of s.slice(0,Math.max(0,s.length-As.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(As.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class fo{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(e={}){this.platform=new Pt(e)}static covers(e){return Pt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,n)=>fo.linesOf(i,n))}static linesOf(e,t){const{type:i,coordinates:n}=e.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=fo.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),c=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=fo.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=fo.electrificationOf(r.kind,d,e.properties.electrifie);return s.flatMap((p,f)=>{const m=p.map(v=>({lat:v[1],lng:v[0],...v.length>2&&Number.isFinite(v[2])&&v[2]>fo.NO_ALTITUDE?{altitudeM:v[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(c)?c:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class Nn{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(e={}){this.client=new ks(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,n=`[out:json][timeout:120];way["railway"~"^(${Nn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Nn.ROUTES})$"];out body;`;return Nn.apply(e,await this.client.query(n),t)}static apply(e,t,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=Nn.ways(t,n);return s.length===0?[...e]:e.map(r=>{const a=r.points.map(g=>st(g.lat,g.lng,n.lat,n.lng)),o=new Map,c=new Map,h=new Map;let d=0;const u=s.filter(g=>g.service===!!r.service);for(const g of Nn.samples(a)){d++;const y=Nn.waysAt(u,g);if(y.length===0)continue;const[w]=y;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&c.set(w.voltageV,(c.get(w.voltageV)??0)+1);for(const b of new Set(y.flatMap(M=>M.services)))h.set(b,(h.get(b)??0)+1)}const p=g=>[...g.entries()].sort((y,w)=>w[1]-y[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(c)),v=[...h.entries()].filter(([,g])=>g*4>=d).sort((g,y)=>y[1]-g[1]||g[0].localeCompare(y[0])).map(([g])=>g);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...v.length>0?{services:v}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=Nn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=t.get(s.ref)??new Set;r.add(n),t.set(s.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=Nn.servicesByWay(e),n=[];for(const s of e.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=Nn.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(o=>st(o.lat,o.lon,t.lat,t.lng))})}return n}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const n=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(n<1e-6)continue;const s=(e[i+1].x-e[i].x)/n,r=(e[i+1].z-e[i].z)/n;for(let a=Nn.SAMPLE_M/2;a<n;a+=Nn.SAMPLE_M)t.push({x:e[i].x+s*a,z:e[i].z+r*a,dx:s,dz:r})}return t}static waysAt(e,t){const i=Math.cos(Nn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of e){let r;for(let a=0;a<s.path.length-1;a++){const o=s.path[a],c=s.path[a+1],h=c.x-o.x,d=c.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=Nn.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class Lc{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new ks(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Lc.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Nn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=Nn.servicesByWay(e);for(const n of e.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(),o=Nn.voltageOf(r),c=Lc.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=Lc.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${n.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:c,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:Lc.levelOf(r),points:s.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class sI{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!fo.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class pn{constructor(e,t=Date.now){this.railways=e,this.now=t}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(e){const t=pn.key(e);let i=pn.asked.get(t)??pn.containing(e);if(i===void 0){const n=this.recalled(t,e);i={bounds:e,answer:n},pn.asked.set(t,i),n.catch(()=>pn.asked.delete(t))}return structuredClone(await i.answer)}static forget(){pn.asked.clear(),pn.failedAt=-1/0}static key(e){return`v${pn.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of pn.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await pn.openCache(),n=pn.request(e);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:o,lines:c}=await a.json();if(Array.isArray(c)){if(this.now()-o<pn.MAX_AGE_MS)return c;s=c}}}catch{}if(this.now()-pn.failedAt<pn.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(t)}catch(a){if(pn.failedAt=this.now(),s)return s;throw a}return i&&pn.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const s of n.slice(0,Math.max(0,n.length-pn.MAX_STORED)))await e.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(pn.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const _m="https://ufoathome.org/railways/index.json";class Oc{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Oc.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=e.north&&n.south<=e.south&&n.east>=e.east&&n.west<=e.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 e=this.indexUrls.join(`
4251
- `);let t=Oc.shared.get(e);return t||(t=this.fetchFirstAvailable(),Oc.shared.set(e,t),t.then(i=>{i.length===0&&Oc.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.150.0")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==_m?[t,_m]:[_m]).map(i=>i+e)}}function _2(){return{elevation:R2(),imagery:D2(),roads:k2(),water:C2(),railways:L2()}}function R2(){return new QT(new kt,new A2)}function D2(){return new I2}function k2(){return new kc({fallback:new iI(new po,new lo)})}function C2(){return new Cc({fallback:new As(new nI(new Pd,new jo))})}function L2(){return new Oc({fallback:new pn(new sI(new fo,new Lc))})}const rI=new Set,jc="show-observer-map",Zc="hide-milestones",vl="minified";class Ht extends HTMLElement{static get observedAttributes(){return["src",jc,Zc,vl]}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 Zt;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=Qf.create();issues=[];issueCheck=0;sightingAudio=new BT;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>Ht.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=g2;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(s)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");Ht.setIcon(this.moreButton,e?Je.UNFOLDED:Je.FOLDED);const t=e?this.messages.fewerControls:this.messages.moreControls;this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,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=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.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=`${e.clientX-s.left+12}px`,this.tooltip.style.top=`${e.clientY-s.top+12}px`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<Ht.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=Zt.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Zt.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ht.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(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const n=Zt.pointAt(t,(e.clientX-i.left)/i.width,(e.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 e=document.createElement("template");e.innerHTML=`<style>${NT}</style>${PT}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new uh(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 qo(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 t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),n=a=>{const o=i.getBoundingClientRect(),c=this.player.seekableDuration;if(o.width<=0||c<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*c;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.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.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.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}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(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===jc&&this.applyObserverMapDefault(),e===Zc&&this.setMilestonesShown(!this.hasAttribute(Zc)),e===vl){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(vl)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(O2)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages.clickToPlay:this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await kr.recording(e)}get sightingData(){return uf(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=rb(e),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),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(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await ae(async()=>{const{default:r}=await import("./sightingSchema-BuVLd3h2.js");return{default:r}},[],import.meta.url);n=new yr(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],ph.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(aI,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=this.messages.recordingIssues.replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=ph.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}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(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==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.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("playrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){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(e){this.toolbar.classList.toggle("hidden",!e),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==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(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of t)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 e=this.currentSighting.references;!this.referenceOpacityTouched&&e.length>0&&(this.referenceOpacityInput.value=String(e[0].opacity));for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}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=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const n=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),n=this.said.read(t.title)??t.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 o=document.createElement("span");o.textContent=n,o.title=n,r.append(a,o);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(i.opacity),c.title=this.messages.referenceOpacity,c.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),c.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,c.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{i.opacity=Number(c.value),this.dispatchReferenceView()}),s.append(r,c),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ht.setIcon(this.referencesButton,i?Je.PICTURES_ON:Je.PICTURES_OFF);const n=t?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)),Ht.setIcon(this.tracesButton,this.tracesShownState?Je.TRACES_ON:Je.TRACES_OFF);const e=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?_l(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/e,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(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.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(e){const i=(e?this.said.read(e.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=e!==void 0&&Number(n.dataset.t)===e.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=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const n=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,a)=>r-a):[],Math.max(e,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 o=document.createElement("i");o.className="seek-hover";const c=document.createElement("i");c.className="seek-played",a.append(o,c),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:c,hover:o})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,n=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=Ht.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=Ht.fillOf(p,s),p.element.classList.toggle("hovered",s>=p.start&&(s<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?Em(a,s):void 0,c=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}paintChrome(e){const t=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(!t||typeof t.setTransform!="function"||n===0||s===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),o=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new uh(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const n=Ht.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>n||(!s||Math.abs(a-e)<Math.abs(s.t-e))&&(s={t:a,name:r.title})}return s}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=(e.clientX-t.left)/t.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?Em(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const n=this.said.read(t.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(e=this.currentTime){const t=Er.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<Ht.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(Ht.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/Ht.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/Ht.EXPOSURE_STEP_PX),s=Math.min(Ht.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(t.fromMs+t.ms*a/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,a]of i){const o=n.get(r);if(!o)continue;const c=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(c,h))}return s}shapeAt(e,t,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,e,t,i);if(s)return s}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=hi.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}onFrame(e,t){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:rI;this.canvasRenderer.setStarPoints(hi.starPointsOf(this.sighting.instrument));const n=(pt(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of s)for(const[,c]of o.shapes){const h=o.share,d=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,c]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));const a=this.selectionShown&&i.size>1?Vt.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(Kv(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new FT(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*Ht.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.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 e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Je.PLAY:Je.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){Ht.icons.get(e)!==t&&(Ht.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}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},Ht.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,this.updateStartState(),Ht.setIcon(this.playPauseButton,e?Je.PAUSE:Je.PLAY);const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?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 e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.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(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.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 e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(jc),t=e===null?this.sighting.observerMap??this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const e=!this.observerMapPanel.hidden;Ht.setIcon(this.observerMapButton,e?Je.MAP_ON:Je.MAP_OFF);const t=e?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);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 e=this.observerPath!==void 0;if(this.observerPath=Tl.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=Zt.fitted(this.observerPath,t);(!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(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapFrozenImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?Zt.expand(e,Ht.OBSERVER_MAP_IMAGERY_AHEAD):e,n=Zt.IMAGERY_PX*(t?1+2*Ht.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=this.observerMapFrozenImagery,r=s?void 0:D2();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(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,n=this.observerMapView.changed?Zt.expand(e,Ht.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapFrozen(e){e!==this.observerMapFrozenImagery&&(this.observerMapFrozenImagery=e,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 observerMapFrozen(){return this.observerMapFrozenImagery}observerMapFrozenImagery;observerMapFrozenSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(c,h,d)=>{for(const u of t)if(!(u.x+u.width<c-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},n=[this.canvas.width-e.width,this.canvas.width],s=[0,e.width],r=Ht.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),o=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!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 e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,n=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*n,bottom:(e.bottom-t.top)*n}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=pt(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},Ht.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Em(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?_l(this.currentSighting.milestones):[]){const a=pt(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:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?Os.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(hi.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(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,_l(this.sighting.milestones).map(t=>t.t)),this.milestonesButton.setAttribute("aria-pressed",String(e)),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,Ht.setIcon(this.milestonesButton,this.milestonesShown?Je.MILESTONES_ON:Je.MILESTONES_OFF);const e=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=pt(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=qs(i,e),{lat:s,lng:r}=ws(n.eastM,-n.northM,t.lat,t.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const n=pt(this.currentSighting,this.currentTime),s=Os.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return ri.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=Ht.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,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 e=!this.hasSound;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Ht.setIcon(this.miniMuteButton,this.mutedState?Je.MUTED:Je.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){Ht.setIcon(this.muteButton,Je.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}Ht.setIcon(this.muteButton,this.mutedState?Je.MUTED:Je.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 e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ht.setIcon(this.fullscreenButton,e?Je.EXIT_FULLSCREEN:Je.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new vs(Zs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Id(Zs.preferencesFor(this),Td);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await pE(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;updateTimeLabelTitles(){const e=this.showClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime,t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=this.messages.currentPosition+t,this.timeEndLabel.title=this.messages.duration+t,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(e){this.messages=e,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=lh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?ag(e.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(e){if(this.realDurationMs===void 0)return Xa(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?ay(ry(this.realStartMs+i)):Xa(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Xa(e):Xa(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Xa(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Xa(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Xa(this.currentSighting.timeline.duration):this.canShowClockTime?ay(ry(this.realStartMs+this.realDurationMs)):Xa(this.realDurationMs)}}function ry(l){const e=new Date(l);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function ay(l){if(l.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return l.second?`${e(l.hour)}:${e(l.minute??0)}:${e(l.second)}`:`${e(l.hour)}:${e(l.minute??0)}`}function Xa(l){const e=Math.round(l/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Dg="rr0-ufo";function cm(){customElements.get(Dg)||customElements.define(Dg,Ht)}const aI="recordingissues",O2="minifiedreset";class ad{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((s,r)=>s.t-r.t):[],n=`${t}|${i.map(s=>`${s.kind}:${s.t}:${s.label}`).join("|")}`;n!==this.drawn&&(this.drawn=n,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(s=>{const r=document.createElement("span");return r.className=`timeline-mark ${s.kind}`,r.style.left=`${Math.min(Math.max(s.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+ad.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-ad.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=ad.SNAP_PX/t*this.duration;let n;for(const s of this.marks)Math.abs(s.t-e)>i||(!n||Math.abs(s.t-e)<Math.abs(n.t-e)||s.t===n.t&&s.kind==="milestone")&&(n=s);return n}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}class Pc{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const n=e.event.place?.[0],s=e.observerTrack;if(!n)return 0;const r=m=>{const v=s.getInterpolatedPoseAt(Math.max(0,m));if(!v||v.lat===void 0||v.lng===void 0)return;const g=st(v.lat,v.lng,n.lat,n.lng);return{eastM:g.x,northM:-g.z,heading:v.headingDeg}},a=r(t-Pc.HALF_SPAN_MS),o=r(t+Pc.HALF_SPAN_MS),c=r(t);if(!a||!o||!c)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*Pc.HALF_SPAN_MS/1e3;if(h/d<Pc.MIN_SPEED_MS)return 0;const u=i.heightAt(o.eastM,o.northM)-i.heightAt(a.eastM,a.northM),p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const oI=.08,oy=.15,ly=2,lI=2e3;class cI{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(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}Il.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);this.context?.close(),this.context=void 0,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<lI),i=new Set(t.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of t){const s=this.voices.get(n.id)??this.build(e,n.id);this.retarget(e,s,n)}}build(e,t){const i=e.createGain();i.gain.value=0;const n=e.createBiquadFilter();n.type="lowpass",n.connect(i).connect(this.masterOf(e));const s=e.createOscillator();s.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,s.connect(o),r.connect(o),o.connect(a).connect(n);const c=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*ly*.5,M},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(n);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(n);const v=c(),g=e.createBiquadFilter();g.type="bandpass",g.frequency.value=1400,g.Q.value=.7;const y=e.createGain();v.connect(g).connect(y).connect(n);const w=[s,r,h,p,v];for(const M of w)M.start();const b={nodes:[i,n,a,o,d,u,f,m,g,y,...w],sources:w,firing:s,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:y,cabin:n,output:i};return this.voices.set(t,b),b}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:a,distanceM:o}){const c=e.currentTime,h=(y,w)=>y.setTargetAtTime(w,c,oI),d=n.rpm/60,u=d*i.cylinders/2,p=Math.min(1,n.rpm/i.shiftUpRpm),f=Math.min(1.5,n.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const v=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,v);const g=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,g*s)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,oy/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},oy*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*ly,e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Nd{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(e){return Nd.BY_KIND[e??"generic"]??Nd.BY_KIND.generic}}class bl{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,n){const s=bl.SAMPLE_MS,r=[];for(let c=i;c<=n+s/2;c+=s){const h=t(c-s/2),d=t(c+s/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(s/1e3))}const a=[];let o=1;for(let c=0;c<r.length;c++){const h=r[c],d=(r[Math.min(c+1,r.length-1)]-r[Math.max(c-1,0)])/(2*s/1e3);if(h<bl.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=g=>u/e.kmhPer1000Rpm[g-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),v=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:v,gear:o})}return new bl(a,i)}at(e){const t=(e-this.startMs)/bl.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),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(t-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 pf{drives=new Map;at(e,t){const i=[],n=e.event.place?.[0],s=c=>{const h=e.observerTrack.getInterpolatedPoseAt(c),d=h?.lat??n?.lat,u=h?.lng??n?.lng;if(d===void 0||u===void 0||!n)return;const p=st(d,u,n.lat,n.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle;if(a){const c=Nd.of(a.kind),h=this.drive(`observer:${a.kind}`,pf.trackKey(e),()=>bl.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const o=s(t);for(const c of e.decor){if(!c.engine||!o)continue;const h=Nd.of(c.engine.kind),d=m=>{const v=qs(c,m);return{eastM:v.eastM,northM:v.northM}},u=this.drive(`decor:${c.id}`,pf.decorKey(c,r),()=>bl.of(h,d,0,r));if(!u)continue;const p=qs(c,t),f=Math.hypot(p.eastM-o.eastM,p.northM-o.northM,p.altitudeM);i.push({id:`decor:${c.id}`,profile:h,state:u.at(t),noise:c.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:f})}return i}drive(e,t,i){const n=this.drives.get(e);if(n&&n.key===t)return n.drive;const s=i();return this.drives.set(e,{key:t,drive:s}),s}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const hI="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==",dI=`
4249
+ `);let t=kc.shared.get(e);return t||(t=this.fetchFirstAvailable(),kc.shared.set(e,t),t.then(i=>{i.length===0&&kc.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.150.2")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==Tm?[t,Tm]:[Tm]).map(i=>i+e)}}class po{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(e={}){this.platform=new Pt(e)}static covers(e){return Pt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRoads(e){return(await this.platform.roads(e)).flatMap((i,n)=>po.wayOf(i,n))}static wayOf(e,t){if(e.geometry.type!=="LineString")return[];const i=e.geometry.coordinates.map(([u,p])=>({lat:p,lng:u}));if(i.length<2)return[];const n=String(e.properties.nature??""),s=po.BY_NATURE[n]??po.DEFAULT,r=Number(e.properties.largeur_de_chaussee),a=Number(e.properties.nombre_de_voies),o=Number(e.properties.vitesse_moyenne_vl),c=po.DIRECTIONS[String(e.properties.sens_de_circulation??"")],h=po.KINDS[n],d=[e.properties.cpx_toponyme_route_nommee,e.properties.nom_voie_ban_gauche,e.properties.nom_voie_ban_droite].find(u=>typeof u=="string"&&u.length>0);return[{id:String(e.properties.cleabs??`ign-${t}`),...d?{name:d}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...e.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...c?{direction:c}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{},points:i}]}}class iI{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(e){if(po.covers(e))try{const t=await this.regional.getRoads(e);if(t.length>0)return t}catch{}return this.worldwide.getRoads(e)}}class Pd{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(e={}){this.platform=new Pt(e)}static covers(e){return Pt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getWater(e){return(await this.platform.waterSurfaces(e)).flatMap((i,n)=>Pd.surfacesOf(i,n))}static surfacesOf(e,t){const{type:i,coordinates:n}=e.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(e.properties.cleabs??`ign-water-${t}`);return s.flatMap((a,o)=>{const c=a.map(h=>Pd.open(h.map(d=>({lat:d[1],lng:d[0]})))).filter(h=>h.length>=3);return c.length>0?[{id:s.length>1?`${r}-${o}`:r,rings:c}]:[]})}static open(e){const t=e[0],i=e[e.length-1];return e.length>1&&t.lat===i.lat&&t.lng===i.lng?e.slice(0,-1):e}}class jo{attribution="Water © OpenStreetMap contributors";client;constructor(e={}){this.client=new ks(e)}async getWater(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${t});way["waterway"="riverbank"](${t});)->.w;(relation["natural"="water"](${t});relation["waterway"="riverbank"](${t});)->.r;.w out geom;.r out body;way(r.r)(${t});out geom;`;return jo.surfacesFrom(await this.client.query(i))}static surfacesFrom(e){const t=e.elements??[],i=new Map;for(const r of t)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 t){if(r.type!=="relation")continue;const a=c=>(r.members??[]).filter(h=>h.type==="way"&&h.role===c&&h.ref!==void 0&&i.has(h.ref)).map(h=>(s.add(h.ref),i.get(h.ref))),o=jo.rings(a("inner"));for(const[c,h]of jo.rings(a("outer")).entries()){const d=o.filter(u=>jo.contains(h,u[0]));n.push({id:`osm-r${r.id}-${c}`,rings:[h,...d]})}}for(const r of t)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 jo.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(e){const t=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=e.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!t(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const o=i[a],c=s[s.length-1];if(t(c,o[0]))s=[...s,...o.slice(1)];else if(t(c,o[o.length-1]))s=[...s,...[...o].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&t(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(e,t){let i=!1;for(let n=0,s=e.length-1;n<e.length;s=n++){const r=e[n],a=e[s];r.lat>t.lat!=a.lat>t.lat&&t.lng<(a.lng-r.lng)*(t.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class nI{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(e){if(Pd.covers(e))try{const t=await this.regional.getWater(e);if(t.length>0)return t}catch{}return this.worldwide.getWater(e)}}const Im="https://ufoathome.org/water/index.json";class Cc{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Cc.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getWater(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=e.north&&n.south<=e.south&&n.east>=e.east&&n.west<=e.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 e=this.indexUrls.join(`
4250
+ `);let t=Cc.shared.get(e);return t||(t=this.fetchFirstAvailable(),Cc.shared.set(e,t),t.then(i=>{i.length===0&&Cc.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.150.2")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==Im?[t,Im]:[Im]).map(i=>i+e)}}class As{constructor(e){this.water=e}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(e){const t=As.key(e);let i=As.asked.get(t);return i===void 0&&(i=this.recalled(t,e),As.asked.set(t,i),i.catch(()=>As.asked.delete(t))),structuredClone(await i)}static forget(){As.asked.clear()}static key(e){return`v${As.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await As.openCache(),n=As.request(e);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<As.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(n)}}catch{}const s=await this.water.getWater(t);return i&&As.store(i,n,s),s}static async store(e,t,i){try{const n={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const r of s.slice(0,Math.max(0,s.length-As.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(As.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class fo{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(e={}){this.platform=new Pt(e)}static covers(e){return Pt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,n)=>fo.linesOf(i,n))}static linesOf(e,t){const{type:i,coordinates:n}=e.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=fo.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),c=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=fo.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=fo.electrificationOf(r.kind,d,e.properties.electrifie);return s.flatMap((p,f)=>{const m=p.map(v=>({lat:v[1],lng:v[0],...v.length>2&&Number.isFinite(v[2])&&v[2]>fo.NO_ALTITUDE?{altitudeM:v[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(c)?c:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class Nn{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(e={}){this.client=new ks(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,n=`[out:json][timeout:120];way["railway"~"^(${Nn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Nn.ROUTES})$"];out body;`;return Nn.apply(e,await this.client.query(n),t)}static apply(e,t,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=Nn.ways(t,n);return s.length===0?[...e]:e.map(r=>{const a=r.points.map(g=>st(g.lat,g.lng,n.lat,n.lng)),o=new Map,c=new Map,h=new Map;let d=0;const u=s.filter(g=>g.service===!!r.service);for(const g of Nn.samples(a)){d++;const y=Nn.waysAt(u,g);if(y.length===0)continue;const[w]=y;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&c.set(w.voltageV,(c.get(w.voltageV)??0)+1);for(const b of new Set(y.flatMap(M=>M.services)))h.set(b,(h.get(b)??0)+1)}const p=g=>[...g.entries()].sort((y,w)=>w[1]-y[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(c)),v=[...h.entries()].filter(([,g])=>g*4>=d).sort((g,y)=>y[1]-g[1]||g[0].localeCompare(y[0])).map(([g])=>g);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...v.length>0?{services:v}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=Nn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=t.get(s.ref)??new Set;r.add(n),t.set(s.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=Nn.servicesByWay(e),n=[];for(const s of e.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=Nn.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(o=>st(o.lat,o.lon,t.lat,t.lng))})}return n}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const n=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(n<1e-6)continue;const s=(e[i+1].x-e[i].x)/n,r=(e[i+1].z-e[i].z)/n;for(let a=Nn.SAMPLE_M/2;a<n;a+=Nn.SAMPLE_M)t.push({x:e[i].x+s*a,z:e[i].z+r*a,dx:s,dz:r})}return t}static waysAt(e,t){const i=Math.cos(Nn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of e){let r;for(let a=0;a<s.path.length-1;a++){const o=s.path[a],c=s.path[a+1],h=c.x-o.x,d=c.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=Nn.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class Lc{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new ks(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Lc.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Nn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=Nn.servicesByWay(e);for(const n of e.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(),o=Nn.voltageOf(r),c=Lc.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=Lc.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${n.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:c,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:Lc.levelOf(r),points:s.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class sI{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!fo.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class pn{constructor(e,t=Date.now){this.railways=e,this.now=t}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(e){const t=pn.key(e);let i=pn.asked.get(t)??pn.containing(e);if(i===void 0){const n=this.recalled(t,e);i={bounds:e,answer:n},pn.asked.set(t,i),n.catch(()=>pn.asked.delete(t))}return structuredClone(await i.answer)}static forget(){pn.asked.clear(),pn.failedAt=-1/0}static key(e){return`v${pn.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of pn.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await pn.openCache(),n=pn.request(e);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:o,lines:c}=await a.json();if(Array.isArray(c)){if(this.now()-o<pn.MAX_AGE_MS)return c;s=c}}}catch{}if(this.now()-pn.failedAt<pn.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(t)}catch(a){if(pn.failedAt=this.now(),s)return s;throw a}return i&&pn.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const s of n.slice(0,Math.max(0,n.length-pn.MAX_STORED)))await e.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(pn.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const _m="https://ufoathome.org/railways/index.json";class Oc{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Oc.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=e.north&&n.south<=e.south&&n.east>=e.east&&n.west<=e.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 e=this.indexUrls.join(`
4251
+ `);let t=Oc.shared.get(e);return t||(t=this.fetchFirstAvailable(),Oc.shared.set(e,t),t.then(i=>{i.length===0&&Oc.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.150.2")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==_m?[t,_m]:[_m]).map(i=>i+e)}}function _2(){return{elevation:R2(),imagery:D2(),roads:k2(),water:C2(),railways:L2()}}function R2(){return new QT(new kt,new A2)}function D2(){return new I2}function k2(){return new kc({fallback:new iI(new po,new lo)})}function C2(){return new Cc({fallback:new As(new nI(new Pd,new jo))})}function L2(){return new Oc({fallback:new pn(new sI(new fo,new Lc))})}const rI=new Set,jc="show-observer-map",Zc="hide-milestones",vl="minified";class Ht extends HTMLElement{static get observedAttributes(){return["src",jc,Zc,vl]}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 Zt;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=Qf.create();issues=[];issueCheck=0;sightingAudio=new BT;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>Ht.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=g2;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(s)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");Ht.setIcon(this.moreButton,e?Je.UNFOLDED:Je.FOLDED);const t=e?this.messages.fewerControls:this.messages.moreControls;this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,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=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.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=`${e.clientX-s.left+12}px`,this.tooltip.style.top=`${e.clientY-s.top+12}px`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<Ht.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=Zt.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Zt.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ht.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(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const n=Zt.pointAt(t,(e.clientX-i.left)/i.width,(e.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 e=document.createElement("template");e.innerHTML=`<style>${NT}</style>${PT}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new uh(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 qo(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 t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),n=a=>{const o=i.getBoundingClientRect(),c=this.player.seekableDuration;if(o.width<=0||c<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*c;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.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.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.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}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(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===jc&&this.applyObserverMapDefault(),e===Zc&&this.setMilestonesShown(!this.hasAttribute(Zc)),e===vl){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(vl)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(O2)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages.clickToPlay:this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await kr.recording(e)}get sightingData(){return uf(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=rb(e),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),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(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await ae(async()=>{const{default:r}=await import("./sightingSchema-BuVLd3h2.js");return{default:r}},[],import.meta.url);n=new yr(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],ph.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(aI,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=this.messages.recordingIssues.replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=ph.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}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(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==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.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("playrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){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(e){this.toolbar.classList.toggle("hidden",!e),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==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(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of t)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 e=this.currentSighting.references;!this.referenceOpacityTouched&&e.length>0&&(this.referenceOpacityInput.value=String(e[0].opacity));for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}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=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const n=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),n=this.said.read(t.title)??t.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 o=document.createElement("span");o.textContent=n,o.title=n,r.append(a,o);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(i.opacity),c.title=this.messages.referenceOpacity,c.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),c.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,c.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{i.opacity=Number(c.value),this.dispatchReferenceView()}),s.append(r,c),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ht.setIcon(this.referencesButton,i?Je.PICTURES_ON:Je.PICTURES_OFF);const n=t?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)),Ht.setIcon(this.tracesButton,this.tracesShownState?Je.TRACES_ON:Je.TRACES_OFF);const e=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?_l(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/e,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(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.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(e){const i=(e?this.said.read(e.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=e!==void 0&&Number(n.dataset.t)===e.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=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const n=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,a)=>r-a):[],Math.max(e,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 o=document.createElement("i");o.className="seek-hover";const c=document.createElement("i");c.className="seek-played",a.append(o,c),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:c,hover:o})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,n=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=Ht.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=Ht.fillOf(p,s),p.element.classList.toggle("hovered",s>=p.start&&(s<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?Em(a,s):void 0,c=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}paintChrome(e){const t=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(!t||typeof t.setTransform!="function"||n===0||s===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),o=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new uh(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const n=Ht.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>n||(!s||Math.abs(a-e)<Math.abs(s.t-e))&&(s={t:a,name:r.title})}return s}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=(e.clientX-t.left)/t.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?Em(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const n=this.said.read(t.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(e=this.currentTime){const t=Er.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<Ht.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(Ht.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/Ht.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/Ht.EXPOSURE_STEP_PX),s=Math.min(Ht.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(t.fromMs+t.ms*a/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,a]of i){const o=n.get(r);if(!o)continue;const c=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(c,h))}return s}shapeAt(e,t,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,e,t,i);if(s)return s}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=hi.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}onFrame(e,t){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:rI;this.canvasRenderer.setStarPoints(hi.starPointsOf(this.sighting.instrument));const n=(pt(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of s)for(const[,c]of o.shapes){const h=o.share,d=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,c]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));const a=this.selectionShown&&i.size>1?Vt.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(Kv(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new FT(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*Ht.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.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 e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Je.PLAY:Je.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){Ht.icons.get(e)!==t&&(Ht.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}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},Ht.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,this.updateStartState(),Ht.setIcon(this.playPauseButton,e?Je.PAUSE:Je.PLAY);const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?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 e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.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(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.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 e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(jc),t=e===null?this.sighting.observerMap??this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const e=!this.observerMapPanel.hidden;Ht.setIcon(this.observerMapButton,e?Je.MAP_ON:Je.MAP_OFF);const t=e?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);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 e=this.observerPath!==void 0;if(this.observerPath=Tl.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=Zt.fitted(this.observerPath,t);(!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(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapFrozenImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?Zt.expand(e,Ht.OBSERVER_MAP_IMAGERY_AHEAD):e,n=Zt.IMAGERY_PX*(t?1+2*Ht.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=this.observerMapFrozenImagery,r=s?void 0:D2();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(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,n=this.observerMapView.changed?Zt.expand(e,Ht.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapFrozen(e){e!==this.observerMapFrozenImagery&&(this.observerMapFrozenImagery=e,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 observerMapFrozen(){return this.observerMapFrozenImagery}observerMapFrozenImagery;observerMapFrozenSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(c,h,d)=>{for(const u of t)if(!(u.x+u.width<c-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},n=[this.canvas.width-e.width,this.canvas.width],s=[0,e.width],r=Ht.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),o=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!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 e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,n=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*n,bottom:(e.bottom-t.top)*n}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=pt(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},Ht.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Em(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?_l(this.currentSighting.milestones):[]){const a=pt(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:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?Os.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(hi.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(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,_l(this.sighting.milestones).map(t=>t.t)),this.milestonesButton.setAttribute("aria-pressed",String(e)),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,Ht.setIcon(this.milestonesButton,this.milestonesShown?Je.MILESTONES_ON:Je.MILESTONES_OFF);const e=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=pt(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=qs(i,e),{lat:s,lng:r}=ws(n.eastM,-n.northM,t.lat,t.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const n=pt(this.currentSighting,this.currentTime),s=Os.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return ri.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=Ht.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,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 e=!this.hasSound;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Ht.setIcon(this.miniMuteButton,this.mutedState?Je.MUTED:Je.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){Ht.setIcon(this.muteButton,Je.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}Ht.setIcon(this.muteButton,this.mutedState?Je.MUTED:Je.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 e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ht.setIcon(this.fullscreenButton,e?Je.EXIT_FULLSCREEN:Je.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new vs(Zs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Id(Zs.preferencesFor(this),Td);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await pE(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;updateTimeLabelTitles(){const e=this.showClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime,t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=this.messages.currentPosition+t,this.timeEndLabel.title=this.messages.duration+t,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(e){this.messages=e,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=lh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?ag(e.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(e){if(this.realDurationMs===void 0)return Xa(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?ay(ry(this.realStartMs+i)):Xa(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Xa(e):Xa(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Xa(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Xa(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Xa(this.currentSighting.timeline.duration):this.canShowClockTime?ay(ry(this.realStartMs+this.realDurationMs)):Xa(this.realDurationMs)}}function ry(l){const e=new Date(l);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function ay(l){if(l.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return l.second?`${e(l.hour)}:${e(l.minute??0)}:${e(l.second)}`:`${e(l.hour)}:${e(l.minute??0)}`}function Xa(l){const e=Math.round(l/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Dg="rr0-ufo";function cm(){customElements.get(Dg)||customElements.define(Dg,Ht)}const aI="recordingissues",O2="minifiedreset";class ad{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((s,r)=>s.t-r.t):[],n=`${t}|${i.map(s=>`${s.kind}:${s.t}:${s.label}`).join("|")}`;n!==this.drawn&&(this.drawn=n,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(s=>{const r=document.createElement("span");return r.className=`timeline-mark ${s.kind}`,r.style.left=`${Math.min(Math.max(s.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+ad.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-ad.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=ad.SNAP_PX/t*this.duration;let n;for(const s of this.marks)Math.abs(s.t-e)>i||(!n||Math.abs(s.t-e)<Math.abs(n.t-e)||s.t===n.t&&s.kind==="milestone")&&(n=s);return n}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}class Pc{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const n=e.event.place?.[0],s=e.observerTrack;if(!n)return 0;const r=m=>{const v=s.getInterpolatedPoseAt(Math.max(0,m));if(!v||v.lat===void 0||v.lng===void 0)return;const g=st(v.lat,v.lng,n.lat,n.lng);return{eastM:g.x,northM:-g.z,heading:v.headingDeg}},a=r(t-Pc.HALF_SPAN_MS),o=r(t+Pc.HALF_SPAN_MS),c=r(t);if(!a||!o||!c)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*Pc.HALF_SPAN_MS/1e3;if(h/d<Pc.MIN_SPEED_MS)return 0;const u=i.heightAt(o.eastM,o.northM)-i.heightAt(a.eastM,a.northM),p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const oI=.08,oy=.15,ly=2,lI=2e3;class cI{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(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}Il.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);this.context?.close(),this.context=void 0,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<lI),i=new Set(t.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of t){const s=this.voices.get(n.id)??this.build(e,n.id);this.retarget(e,s,n)}}build(e,t){const i=e.createGain();i.gain.value=0;const n=e.createBiquadFilter();n.type="lowpass",n.connect(i).connect(this.masterOf(e));const s=e.createOscillator();s.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,s.connect(o),r.connect(o),o.connect(a).connect(n);const c=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*ly*.5,M},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(n);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(n);const v=c(),g=e.createBiquadFilter();g.type="bandpass",g.frequency.value=1400,g.Q.value=.7;const y=e.createGain();v.connect(g).connect(y).connect(n);const w=[s,r,h,p,v];for(const M of w)M.start();const b={nodes:[i,n,a,o,d,u,f,m,g,y,...w],sources:w,firing:s,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:y,cabin:n,output:i};return this.voices.set(t,b),b}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:a,distanceM:o}){const c=e.currentTime,h=(y,w)=>y.setTargetAtTime(w,c,oI),d=n.rpm/60,u=d*i.cylinders/2,p=Math.min(1,n.rpm/i.shiftUpRpm),f=Math.min(1.5,n.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const v=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,v);const g=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,g*s)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,oy/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},oy*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*ly,e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Nd{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(e){return Nd.BY_KIND[e??"generic"]??Nd.BY_KIND.generic}}class bl{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,n){const s=bl.SAMPLE_MS,r=[];for(let c=i;c<=n+s/2;c+=s){const h=t(c-s/2),d=t(c+s/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(s/1e3))}const a=[];let o=1;for(let c=0;c<r.length;c++){const h=r[c],d=(r[Math.min(c+1,r.length-1)]-r[Math.max(c-1,0)])/(2*s/1e3);if(h<bl.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=g=>u/e.kmhPer1000Rpm[g-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),v=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:v,gear:o})}return new bl(a,i)}at(e){const t=(e-this.startMs)/bl.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),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(t-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 pf{drives=new Map;at(e,t){const i=[],n=e.event.place?.[0],s=c=>{const h=e.observerTrack.getInterpolatedPoseAt(c),d=h?.lat??n?.lat,u=h?.lng??n?.lng;if(d===void 0||u===void 0||!n)return;const p=st(d,u,n.lat,n.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle;if(a){const c=Nd.of(a.kind),h=this.drive(`observer:${a.kind}`,pf.trackKey(e),()=>bl.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const o=s(t);for(const c of e.decor){if(!c.engine||!o)continue;const h=Nd.of(c.engine.kind),d=m=>{const v=qs(c,m);return{eastM:v.eastM,northM:v.northM}},u=this.drive(`decor:${c.id}`,pf.decorKey(c,r),()=>bl.of(h,d,0,r));if(!u)continue;const p=qs(c,t),f=Math.hypot(p.eastM-o.eastM,p.northM-o.northM,p.altitudeM);i.push({id:`decor:${c.id}`,profile:h,state:u.at(t),noise:c.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:f})}return i}drive(e,t,i){const n=this.drives.get(e);if(n&&n.key===t)return n.drive;const s=i();return this.drives.set(e,{key:t,drive:s}),s}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const hI="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==",dI=`
4252
4252
  <div class="stage" id="stage">
4253
4253
  <div class="frame" id="frame">
4254
4254
  <canvas id="scene-canvas"></canvas>
@@ -10204,7 +10204,7 @@ ${Ne.OUTPUT_PROJECTION_GLSL}`)}}class $n{constructor(e,t){this.width=e,this.heig
10204
10204
  vec4 overlay = texture2D(uOverlay, vUv);
10205
10205
  ${pd}
10206
10206
  }
10207
- `,depthTest:!1,depthWrite:!1}),this.quadScene.add(new xe(new xs(2,2),this.material))}render(e,t,i,n,s,r){const a=e.getRenderTarget(),o=r??{scene:this.scene,overlay:this.overlay};e.setRenderTarget(o.scene),e.render(t,i),s?.(),(n||r&&!r.single)&&(ki.clearTransparent(e,o.overlay),n?.()),e.setRenderTarget(a),!r&&(this.material.uniforms.uMode.value=Ys.Finished,e.render(this.quadScene,this.quadCamera))}resize(e,t){this.scene.setSize(Math.max(1,e),Math.max(1,t)),this.overlay.setSize(Math.max(1,e),Math.max(1,t))}dispose(){this.scene.dispose(),this.overlay.dispose(),this.material.dispose(),this.quadScene.children[0].geometry.dispose()}}class Ts{static MAX_GHOSTS=12;static TAPS=12;static VISIBLE_RESPONSE=.03;frame;mips;ghostLayer;quadScene=new Or;quadCamera=new fr(-1,1,1,-1,0,1);quad;copyMaterial;ghostMaterial;developMaterial;constructor(e,t){const i=(a,o)=>[Math.max(1,a),Math.max(1,o)];this.frame={scene:new yi(...i(e,t),{type:Jt,samples:4}),overlay:new yi(...i(e,t),{type:Jt,samples:4}),single:!0};const n=i(Math.ceil(e/2),Math.ceil(t/2));this.mips=new yi(...n,{type:Jt,generateMipmaps:!0,minFilter:Cr,magFilter:Dt}),this.ghostLayer=new yi(...n,{type:Jt});const s=`
10207
+ `,depthTest:!1,depthWrite:!1}),this.quadScene.add(new xe(new xs(2,2),this.material))}render(e,t,i,n,s,r){const a=e.getRenderTarget(),o=r??{scene:this.scene,overlay:this.overlay};e.setRenderTarget(o.scene),e.render(t,i),s?.(),(n||r&&!r.single)&&(ki.clearTransparent(e,o.overlay),n?.()),e.setRenderTarget(a),!r&&(this.material.uniforms.uMode.value=Ys.Finished,e.render(this.quadScene,this.quadCamera))}resize(e,t){this.scene.setSize(Math.max(1,e),Math.max(1,t)),this.overlay.setSize(Math.max(1,e),Math.max(1,t))}dispose(){this.scene.dispose(),this.overlay.dispose(),this.material.dispose(),this.quadScene.children[0].geometry.dispose()}}class Ts{static MAX_GHOSTS=12;static TAPS=12;static VISIBLE_RESPONSE=.03;readable=!1;frame;mips;ghostLayer;quadScene=new Or;quadCamera=new fr(-1,1,1,-1,0,1);quad;copyMaterial;ghostMaterial;developMaterial;constructor(e,t){const i=(a,o)=>[Math.max(1,a),Math.max(1,o)];this.frame={scene:new yi(...i(e,t),{type:Jt,samples:4}),overlay:new yi(...i(e,t),{type:Jt,samples:4}),single:!0};const n=i(Math.ceil(e/2),Math.ceil(t/2));this.mips=new yi(...n,{type:Jt,generateMipmaps:!0,minFilter:Cr,magFilter:Dt}),this.ghostLayer=new yi(...n,{type:Jt});const s=`
10208
10208
  varying vec2 vUv;
10209
10209
  void main() {
10210
10210
  vUv = position.xy * 0.5 + 0.5;
@@ -10472,7 +10472,7 @@ ${Ne.OUTPUT_PROJECTION_GLSL}`)}}class $n{constructor(e,t){this.width=e,this.heig
10472
10472
  // A picture with nothing laid over it may not even have cleared its overlay (see EYE_UNIFORMS).
10473
10473
  gl_FragColor = vec4(finish(scene, texture2D(uOverlay, vUv) * uGain * uHasOverlay, lampOf(texel.a)), 1.0);
10474
10474
  }
10475
- `,blending:Js,depthTest:!1,depthWrite:!1}),this.quad=new xe(new xs(2,2),this.copyMaterial),this.quadScene.add(this.quad)}develop(e,t,i,n=1,s){const r=e.getRenderTarget();this.copyMaterial.uniforms.uSource.value=t.scene.texture,this.copyMaterial.uniforms.uGain.value=n,this.draw(e,this.copyMaterial,this.mips);const a=this.ghostMaterial.uniforms;a.uSize.value.set(this.mips.width,this.mips.height);const o=Math.min(i.ghosts.length,Ts.MAX_GHOSTS);a.uCount.value=o;for(let u=0;u<o;u++){const p=i.ghosts[u];a.uScale.value[u]=p.scale||1,a.uShare.value[u]=p.share,a.uBlur.value[u]=p.blur,a.uKind.value[u]=p.cause==="drops"?2:bi.scatters(p)?1:0,a.uOffset.value[u].set(p.offset?.[0]??0,p.offset?.[1]??0),a.uTint.value[u].set(...p.tint??[1,1,1])}a.uBlades.value=i.blades,a.uBladeAngle.value=i.bladeAngleRad,a.uDrops.value=i.drops,a.uImpacts.value=i.impacts;const c=a.uHistory.value;for(let u=0;u<c.length;u++)c[u]=i.history[u]??0;a.uStill.value=i.still?1:0,a.uRunning.value=i.running,a.uBright.value.set(((s?.x??0)+1)/2,((s?.y??0)+1)/2),a.uBrightRadius.value=s?.radius??0;const h=s?.flux??[0,0,0];a.uBrightFlux.value.set(h[0]*n,h[1]*n,h[2]*n),this.draw(e,this.ghostMaterial,this.ghostLayer);const d=this.developMaterial.uniforms;d.uSource.value=t.scene.texture,d.uOverlay.value=t.overlay.texture,d.uGain.value=n,d.uKept.value=1-i.scattered,this.draw(e,this.developMaterial,r)}pickAt(e,t,i,n,s){const r=this.mips.width,a=this.mips.height,o=(u,p)=>({x:Math.round((u+1)/2*r),y:Math.round((p+1)/2*a)}),c=o(t,i),h=this.window(e,c.x,c.y,0);if(!h)return;let d;for(const u of n.ghosts){const p=bi.sourceOf(u,{x:t,y:i});if(Math.abs(p.x)>=1||Math.abs(p.y)>=1)continue;const f=Math.max(2,Math.round(u.blur*a/Math.abs(u.scale))),m=Math.min(1+p.x,1-p.x)/2*r/a,v=Math.min(1+p.y,1-p.y)/2,g=Math.max(2*u.blur*a/Math.abs(u.scale),2)/a,y=Ts.smoothstep(0,g,m)*Ts.smoothstep(0,g,v),w=o(p.x,p.y),b=this.window(e,w.x,w.y,f);if(!b)continue;const M=y*u.share*b.mean/(u.scale*u.scale),S=.18*M*s;S<Ts.VISIBLE_RESPONSE||M<.3*h.mean||(!d||S>d.score)&&(d={score:S,hit:{ghost:u,source:{x:b.brightest.x/r*2-1,y:b.brightest.y/a*2-1}}})}return d?.hit}dropAt(e,t,i){const n=Math.round((t+1)/2*this.ghostLayer.width),s=Math.round((i+1)/2*this.ghostLayer.height);if(n<0||s<0||n>=this.ghostLayer.width||s>=this.ghostLayer.height)return 0;const r=new Uint16Array(4);return e.readRenderTargetPixels(this.ghostLayer,n,s,1,1,r),Ts.half(r[3])}window(e,t,i,n){const s=Math.max(1,Math.ceil(n/24)),r={x:Math.max(0,t-n),y:Math.max(0,i-n)},a={x:Math.min(this.mips.width-1,t+n),y:Math.min(this.mips.height-1,i+n)};if(r.x>a.x||r.y>a.y)return;const o=a.x-r.x+1,c=a.y-r.y+1,h=new Uint16Array(o*c*4);e.readRenderTargetPixels(this.mips,r.x,r.y,o,c,h);let d=0,u=0,p=-1,f={x:t,y:i};for(let m=r.y;m<=a.y;m+=s){const v=(m-r.y)*o*4;for(let g=0;g<o;g+=s){const y=.2126*Ts.half(h[v+g*4])+.7152*Ts.half(h[v+g*4+1])+.0722*Ts.half(h[v+g*4+2]);d+=y,u++,y>p&&(p=y,f={x:r.x+g,y:m})}}return{mean:u>0?d/u:0,brightest:f}}draw(e,t,i){this.quad.material=t,e.setRenderTarget(i),e.render(this.quadScene,this.quadCamera)}static half(e){const t=e>>10&31,i=e&1023,n=e&32768?-1:1;return t===0?n*i*2**-24:t===31?0:n*(1+i/1024)*2**(t-15)}static smoothstep(e,t,i){const n=Math.max(0,Math.min(1,(i-e)/(t-e)));return n*n*(3-2*n)}resize(e,t){const i=Math.max(1,e),n=Math.max(1,t);this.frame.scene.setSize(i,n),this.frame.overlay.setSize(i,n),this.mips.setSize(Math.ceil(i/2),Math.ceil(n/2)),this.ghostLayer.setSize(Math.ceil(i/2),Math.ceil(n/2))}dispose(){this.frame.scene.dispose(),this.frame.overlay.dispose(),this.mips.dispose(),this.ghostLayer.dispose(),this.copyMaterial.dispose(),this.ghostMaterial.dispose(),this.developMaterial.dispose(),this.quad.geometry.dispose(),this.quadScene.clear()}}class Us{static IDENTITY=[1,0,0,0,1,0,0,0,1];static NONE={colorMatrix:Us.IDENTITY,contrastGain:1};static combine(e,t){const[i,n,s,r,a,o,c,h,d]=e.colorMatrix,[u,p,f,m,v,g,y,w,b]=t.colorMatrix;return{colorMatrix:[u*i+p*r+f*c,u*n+p*a+f*h,u*s+p*o+f*d,m*i+v*r+g*c,m*n+v*a+g*h,m*s+v*o+g*d,y*i+w*r+b*c,y*n+w*a+b*h,y*s+w*o+b*d],contrastGain:e.contrastGain*t.contrastGain}}static isNone(e){return e.contrastGain===1&&e.colorMatrix.every((t,i)=>t===Us.IDENTITY[i])}}class jt{static MIN_RATIO=1;static STEP=.25;static MIN_SHARE_OF_DISPLAY=.75;static GPU_LATE_MS=12;static GPU_ROOM_MS=6;static INTERVAL_LATE_MS=21;static LOWER_COOLDOWN_MS=750;static RAISE_COOLDOWN_MS=2e3;static PROBE_WATCH_MS=2e3;static PROBE_EVERY_MS=6e3;static PROBE_BACKOFF_MS=3e4;ratio;maxRatio;timer;intervalMs;lastChangeMs=-1/0;nextProbeMs=0;probe;constructor(e,t){this.maxRatio=jt.clamp(e),this.ratio=this.maxRatio,this.timer=t?Pf.create(t):void 0}get pixelRatio(){return this.ratio}static SETTLE_MS=400;static SUSTAINED_MS=100;lastEditMs=-1/0;editStreakStartMs=-1/0;wasChanging=!1;noteChange(e){e-this.lastEditMs>jt.SETTLE_MS&&(this.editStreakStartMs=e),this.lastEditMs=e}changing(e){return e-this.lastEditMs<=jt.SETTLE_MS&&this.lastEditMs-this.editStreakStartMs>=jt.SUSTAINED_MS}ratioFor(e,t){return this.changing(e)?this.wasChanging?(this.update(e,t),this.ratio):(this.wasChanging=!0,this.reset(),this.ratio):(this.wasChanging=!1,this.maxRatio)}get timesGpu(){return this.timer!==void 0}set maximum(e){this.maxRatio=jt.clamp(e),this.ratio>this.maxRatio&&(this.ratio=this.maxRatio),this.ratio<this.minimum&&(this.ratio=Math.min(this.maxRatio,this.minimum))}get minimum(){const e=Math.floor(this.maxRatio*jt.MIN_SHARE_OF_DISPLAY/jt.STEP)*jt.STEP;return Math.max(jt.MIN_RATIO,e)}get maximum(){return this.maxRatio}beginDrawing(){this.timer?.begin()}endDrawing(){this.timer?.end()}reset(){this.intervalMs=void 0,this.probe=void 0,this.timer?.reset()}update(e,t){const i=this.timer?.poll();if(!(this.timer&&i===void 0))return i!==void 0?this.followGpu(e,i):this.followIntervals(e,t)}followGpu(e,t){if(t>jt.GPU_LATE_MS)return this.lower(e,jt.LOWER_COOLDOWN_MS);if(t<jt.GPU_ROOM_MS)return this.raise(e,jt.RAISE_COOLDOWN_MS)}followIntervals(e,t){if(!(t>0)||t>1e3)return;this.intervalMs=this.intervalMs===void 0?t:this.intervalMs*.9+t*.1;const i=this.intervalMs>jt.INTERVAL_LATE_MS;if(this.probe){if(i)return this.ratio=this.probe.ratioBefore,this.probe=void 0,this.lastChangeMs=e,this.nextProbeMs=e+jt.PROBE_BACKOFF_MS,this.ratio;e-this.probe.sinceMs>=jt.PROBE_WATCH_MS&&(this.probe=void 0,this.nextProbeMs=e+jt.PROBE_EVERY_MS);return}if(i){const n=this.lower(e,jt.LOWER_COOLDOWN_MS);return n!==void 0&&(this.nextProbeMs=e+jt.PROBE_EVERY_MS),n}if(this.ratio<this.maxRatio&&e>=this.nextProbeMs&&e-this.lastChangeMs>=jt.RAISE_COOLDOWN_MS){const n=this.ratio,s=this.raise(e,0);return s!==void 0&&(this.probe={sinceMs:e,ratioBefore:n}),s}}lower(e,t){if(!(this.ratio<=this.minimum||e-this.lastChangeMs<t))return this.ratio=Math.max(this.minimum,jt.clamp(this.ratio-jt.STEP)),this.lastChangeMs=e,this.ratio}raise(e,t){if(!(this.ratio>=this.maxRatio||e-this.lastChangeMs<t))return this.ratio=Math.min(this.maxRatio,jt.clamp(this.ratio+jt.STEP)),this.lastChangeMs=e,this.ratio}static clamp(e){return Number.isFinite(e)?Math.max(jt.MIN_RATIO,Math.round(e/jt.STEP)*jt.STEP):jt.MIN_RATIO}}class Pf{constructor(e,t){this.gl=e,this.extension=t}static IN_FLIGHT_MAX=8;static create(e){if(!(e instanceof WebGL2RenderingContext))return;const t=e.getExtension("EXT_disjoint_timer_query_webgl2");return t?new Pf(e,t):void 0}pending=[];active;smoothedMs;begin(){if(!(this.active||this.pending.length>=Pf.IN_FLIGHT_MAX))try{const e=this.gl.createQuery();if(!e)return;this.gl.beginQuery(this.extension.TIME_ELAPSED_EXT,e),this.active=e}catch{this.active=void 0}}end(){if(this.active){try{this.gl.endQuery(this.extension.TIME_ELAPSED_EXT),this.pending.push(this.active)}catch{}this.active=void 0}}poll(){const e=this.gl;try{for(let t=0;t<this.pending.length;t++){const i=this.pending[t];if(!e.getQueryParameter(i,e.QUERY_RESULT_AVAILABLE))continue;if(!e.getParameter(this.extension.GPU_DISJOINT_EXT)){const s=e.getQueryParameter(i,e.QUERY_RESULT)/1e6;this.smoothedMs=this.smoothedMs===void 0?s:this.smoothedMs*.8+s*.2}e.deleteQuery(i),this.pending.splice(t,1),t--}}catch{this.pending.length=0}return this.smoothedMs}reset(){this.smoothedMs=void 0}}class ut{static ICE_INDEX_RED=1.3067;static ICE_INDEX_BLUE=1.317;static SIDE_PRISM_ANGLE_DEG=60;static END_PRISM_ANGLE_DEG=90;static get PARHELIA_MAX_SUN_ALTITUDE_DEG(){const e=ut.ICE_INDEX_RED,t=Math.sqrt((4-e*e)/3);return Math.asin(Math.min(1,t))*180/Math.PI}static minimumDeviationDeg(e,t){const i=e*Math.PI/180,n=t*Math.sin(i/2);return n>1?Number.NaN:(2*Math.asin(n)-i)*180/Math.PI}static effectiveIndex(e,t){const i=t*Math.PI/180,n=Math.cos(i);return n<=0?Number.POSITIVE_INFINITY:Math.sqrt(e*e-Math.sin(i)**2)/n}static parheliaAzimuthDeg(e,t=ut.ICE_INDEX_RED){const i=ut.minimumDeviationDeg(ut.SIDE_PRISM_ANGLE_DEG,ut.effectiveIndex(t,e));return Number.isFinite(i)?i:void 0}static parheliaDistanceDeg(e,t=ut.ICE_INDEX_RED){const i=ut.parheliaAzimuthDeg(e,t);if(i===void 0)return;const n=e*Math.PI/180,s=Math.sin(n)**2,r=Math.cos(n)**2*Math.cos(i*Math.PI/180);return Math.acos(Math.max(-1,Math.min(1,s+r)))*180/Math.PI}static get PLATE_END_FACE_LIMIT_DEG(){const e=ut.ICE_INDEX_RED;return Math.asin(Math.min(1,Math.sqrt(e*e-1)))*180/Math.PI}static circumzenithalAltitudeDeg(e,t=ut.ICE_INDEX_RED){if(e<0||e>90-ut.PLATE_END_FACE_LIMIT_DEG)return;const i=Math.cos(e*Math.PI/180),n=Math.sqrt(t*t-i*i);if(!(n>=1))return Math.asin(n)*180/Math.PI}static DECK_HEIGHT_M=8e3;static deckLitUntilDeg(e){return Math.acos(6371e3/(6371e3+Math.max(0,e)))*180/Math.PI}static halo22(){return ut.ringOf("halo22",ut.SIDE_PRISM_ANGLE_DEG)}static halo46(){return ut.ringOf("halo46",ut.END_PRISM_ANGLE_DEG)}static ringOf(e,t){const i=ut.minimumDeviationDeg(t,ut.ICE_INDEX_RED),n=ut.minimumDeviationDeg(t,ut.ICE_INDEX_BLUE);return{id:e,angleDeg:(i+n)/2,redAngleDeg:i,blueAngleDeg:n}}static strength(e,t,i=90,n=0){const s=Math.max(0,Math.min(1,e)),r=Math.max(0,1-Math.max(0,Math.min(1,t))),a=i>=0?1:n<=0?0:Math.max(0,1+i/n);return s*r*a}static formsAt(e,t=0){if(e<=-t)return[];const i=[ut.halo22(),ut.halo46()],n=e>0?ut.parheliaDistanceDeg(e):void 0;n!==void 0&&i.push({id:"parhelia",angleDeg:n,redAngleDeg:n,blueAngleDeg:ut.parheliaDistanceDeg(e,ut.ICE_INDEX_BLUE)}),i.push({id:"tangentArc",angleDeg:ut.halo22().angleDeg}),e>0&&i.push({id:"parhelicCircle",angleDeg:e});const s=ut.circumzenithalAltitudeDeg(e);return s!==void 0&&i.push({id:"circumzenithal",angleDeg:s}),e>ut.PLATE_END_FACE_LIMIT_DEG&&i.push({id:"circumhorizontal"}),e<ut.PILLAR_MAX_SOURCE_ALTITUDE_DEG&&i.push({id:"pillar"}),i}static PILLAR_MAX_SOURCE_ALTITUDE_DEG=20}class jn{static get WATER_INDEX_RED(){return kn.indexAt(kn.RED_NM)}static get WATER_INDEX_BLUE(){return kn.indexAt(kn.BLUE_NM)}static radiusDeg(e,t){const i=(t*t-1)/(e*e-1);if(i<0||i>1)return Number.NaN;const n=Math.acos(Math.sqrt(i)),s=Math.asin(Math.sin(n)/t),r=2*(n-s)+(e-1)*(Math.PI-2*s),a=2*Math.PI;let o=r%a;return o<0&&(o+=a),o>Math.PI&&(o=a-o),180-o*180/Math.PI}static primary(){return jn.bowOf("primary",2,0)}static secondary(){return jn.bowOf("secondary",3,0)}static bowOf(e,t,i){const n=jn.radiusDeg(t,jn.WATER_INDEX_RED),s=jn.radiusDeg(t,jn.WATER_INDEX_BLUE),r=(n+s)/2;return{id:e,radiusDeg:r,redRadiusDeg:n,violetRadiusDeg:s,topAltitudeDeg:r-i}}static alexandersBandDeg(){return{fromDeg:jn.primary().redRadiusDeg,toDeg:jn.secondary().redRadiusDeg}}static formsAt(e){return e<0?[]:[jn.bowOf("primary",2,e),jn.bowOf("secondary",3,e)].filter(t=>t.topAltitudeDeg>0)}static FULL_MOON_MAGNITUDE=-12.7;static moonlightShare(e){return Math.min(1,10**(-.4*(e-jn.FULL_MOON_MAGNITUDE)))}static strength(e,t,i){if(i<=0)return 0;const n=Math.max(0,Math.min(1,e)),s=Math.max(0,1-Math.max(0,Math.min(1,t)));return n*s}}class Vs{constructor(e){this.radius=e;const t=Vs.SEGMENTS*Vs.VERTICES_PER_SEGMENT;this.positions=new Float32Array(t*3),this.colors=new Float32Array(t*3);const i=new ct;i.setAttribute("position",new mt(this.positions,3)),i.setAttribute("color",new mt(this.colors,3)),i.setDrawRange(0,0),this.object=new xe(i,Ps.material()),this.object.frustumCulled=!1,Ps.track(this.object)}static POINTS=24;static SEGMENTS=Vs.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(Vs.ACROSS-1)*6;static HEAD_HALF_WIDTH_DEG=.15;static SPREAD_FRACTION=.05;static FADE_POWER=1.8;object;positions;colors;head;tip;brightness=0;set(e,t,i){this.head=e&&oi(e.altitudeDeg,e.azimuthDeg,1),this.tip=t&&oi(t.altitudeDeg,t.azimuthDeg,1),this.brightness=i,this.rebuild()}rebuild(){const e=this.object.geometry,t=this.head,i=this.tip;if(!t||!i||this.brightness<=0){e.setDrawRange(0,0);return}const n=this.angleBetween(t,i);if(n<=0){e.setDrawRange(0,0);return}const s=n*Vs.SPREAD_FRACTION*Math.PI/180,r=h=>this.scale(this.slerp(t,i,h),this.radius),a=h=>this.radius*(Vs.HEAD_HALF_WIDTH_DEG*Math.PI/180+s*h),o=h=>this.brightness*(1-h)**Vs.FADE_POWER;let c=0;for(let h=1;h<Vs.POINTS;h++){const d=(h-1)/Vs.SEGMENTS,u=h/Vs.SEGMENTS;c=this.pushBand(c,r(d),r(u),a(d),a(u),o(d),o(u))}e.setDrawRange(0,c),e.getAttribute("position").needsUpdate=!0,e.getAttribute("color").needsUpdate=!0}pushBand(e,t,i,n,s,r,a){const o=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let c=0;c<Vs.ACROSS-1;c++){const h=c-1,d=c,u=this.across(t,o,n,h),p=this.across(i,o,s,h),f=this.across(t,o,n,d),m=this.across(i,o,s,d),v=(g,y)=>g===0?y:0;e=this.push(e,u,v(h,r)),e=this.push(e,p,v(h,a)),e=this.push(e,f,v(d,r)),e=this.push(e,p,v(h,a)),e=this.push(e,m,v(d,a)),e=this.push(e,f,v(d,r))}return e}across(e,t,i,n){return{x:e.x+t.x*i*n,y:e.y+t.y*i*n,z:e.z+t.z*i*n}}push(e,t,i){const n=e*3;this.positions[n]=t.x,this.positions[n+1]=t.y,this.positions[n+2]=t.z;const s=Fe.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.55,this.colors[n+1]=s*.75,this.colors[n+2]=s,e+1}slerp(e,t,i){const n=this.angleBetweenRadians(e,t);if(n<1e-9)return e;const s=Math.sin(n),r=Math.sin((1-i)*n)/s,a=Math.sin(i*n)/s;return{x:e.x*r+t.x*a,y:e.y*r+t.y*a,z:e.z*r+t.z*a}}angleBetween(e,t){return this.angleBetweenRadians(e,t)*180/Math.PI}angleBetweenRadians(e,t){const i=e.x*t.x+e.y*t.y+e.z*t.z;return Math.acos(Math.min(1,Math.max(-1,i)))}scale(e,t){return{x:e.x*t,y:e.y*t,z:e.z*t}}subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class KL{object=new zt;radius;tiers;drawn=[];constructor(e){this.radius=e,this.object.name="satellites",this.tiers=Dl.map(t=>{const i=new Cs(new ct,Ne.material(t.size));return Ne.track(i),i.frustumCulled=!1,this.object.add(i),i})}set(e,t,i,n){const s=this.tiers.map(()=>[]);this.drawn=[];for(const r of e){if(r.magnitude>t)continue;const a=i(r.position);if(a<=0)continue;const o=r.magnitude-2.5*Math.log10(a);if(o>t)continue;const c=Ml(o,t),h=vm(c),{x:d,y:u,z:p}=oi(r.position.altitudeDeg,r.position.azimuthDeg,this.radius),[f,m,v]=n(r.position,o);s[h].push({x:d,y:u,z:p,r:f,g:m,b:v,seed:r.norad*.6180339887%1}),this.drawn.push({satellite:r,direction:new _(d,u,p).normalize()})}this.tiers.forEach((r,a)=>{const o=s[a],c=new Float32Array(o.length*3),h=new Float32Array(o.length*3),d=new Float32Array(o.length);o.forEach((p,f)=>{c.set([p.x,p.y,p.z],f*3),h.set([p.r,p.g,p.b],f*3),d[f]=p.seed}),r.geometry.dispose();const u=new ct;u.setAttribute("position",new mt(c,3)),u.setAttribute("color",new mt(h,3)),u.setAttribute("seed",new mt(d,1)),r.geometry=u})}get count(){return this.drawn.length}nearest(e,t){let i,n=t;for(const s of this.drawn){const r=s.direction.dot(e);r>n&&(n=r,i=s.satellite)}return i}dispose(){for(const e of this.tiers)e.geometry.dispose(),e.material.dispose();this.object.removeFromParent(),this.drawn=[]}}class $s{static MU=398600.4418;static OMEGA=72921159e-12;static EARTH_RADIUS_KM=6371;static STEP_S=1;static DENSITY=[[0,1.225],[20,.0889],[40,.004],[60,31e-5],[80,185e-7],[100,56e-8],[120,222e-10],[150,208e-11],[200,254e-12],[250,607e-13],[300,192e-13],[400,28e-13],[500,522e-15],[600,114e-15],[700,307e-16],[800,114e-16],[900,576e-17],[1e3,356e-17]];static FREE_PATH_TIMES_DENSITY=68e-9;static ICE_DENSITY=917;static airDensity(e){const t=$s.DENSITY;if(e<=t[0][0])return t[0][1];let i=0;for(;i<t.length-2&&t[i+1][0]<e;)i++;const[n,s]=t[i],[r,a]=t[i+1];return s*Math.exp(Math.log(a/s)*(e-n)/(r-n))}static dragPerKm(e,t,i,n=.5){const s=$s.airDensity(e),r=$s.FREE_PATH_TIMES_DENSITY/s/1e3,a=Math.exp(-r/t),o=s*1e9*Math.PI*t*t/Math.max(i,1e-9),c=3*s/(4*n*1e-6*$s.ICE_DENSITY)*1e3;return a*o+(1-a)*c}static step(e,t,i,n,s){const[r,a,o,c,h,d]=e,u=Math.hypot(r,a,o),p=$s.OMEGA,f=-398600.4418/(u*u*u),m=f*r+2*p*h+p*p*r,v=f*a-2*p*c+p*p*a,g=f*o,y=Math.hypot(c,h,d),b=1/(1+$s.dragPerKm(u-$s.EARTH_RADIUS_KM,i,n,s)*y*t);e[3]=(c+m*t)*b,e[4]=(h+v*t)*b,e[5]=(d+g*t)*b,e[0]=r+e[3]*t,e[1]=a+e[4]*t,e[2]=o+e[5]*t;const M=Math.hypot(e[0],e[1],e[2]);if(M<$s.EARTH_RADIUS_KM){const S=$s.EARTH_RADIUS_KM/M;e[0]*=S,e[1]*=S,e[2]*=S,e[3]=e[4]=e[5]=0}}}class XL{constructor(e,t,i,n,s=.5){this.massKg=i,this.radiusAt=n,this.particleRadiusUm=s,this.state=Float64Array.of(...e,...t),this.positions=new Float64Array(192),this.positions.set(e,0)}positions;steps=0;state;at(e){const t=$s.STEP_S,i=Math.max(0,e/t),n=Math.ceil(i);for(;this.steps<n;){if($s.step(this.state,t,this.radiusAt(this.steps*t),this.massKg,this.particleRadiusUm),this.steps++,3*(this.steps+1)>this.positions.length){const o=new Float64Array(this.positions.length*2);o.set(this.positions),this.positions=o}this.positions.set(this.state.subarray(0,3),3*this.steps)}const s=Math.floor(i),r=i-s,a=this.positions;return r===0||s>=this.steps?[a[3*s],a[3*s+1],a[3*s+2]]:[0,1,2].map(o=>a[3*s+o]+(a[3*s+3+o]-a[3*s+o])*r)}}class Le{static EARTH_RADIUS_KM=6371;static SHADOW_RADIUS_KM=Le.EARTH_RADIUS_KM+15;static PENUMBRA_KM=10;static SUN_ILLUMINANCE_LUX=127e3;static RAYLEIGH_PER_M=[58e-7,135e-7,331e-7];static SCALE_HEIGHT_M=8e3;static OZONE_GRAZING_DEPTH=[2.4,1.8,.24];static ANISOTROPY=.7;static ALBEDO=.99;static WAVELENGTHS_UM=[.61,.55,.465];static ICE_INDEX=1.31;static DEFAULTS={exhaustKgPerS:273,condensedShare:.065,particleRadiusUm:.5,expansionKmPerS:.15,initialRadiusKm:.5,lifetimeS:420,collarShare:.85,collarExpansionKmPerS:2.5,collarLifetimeS:20};static PROPELLANTS={"rp1-lox":{condensedShare:.065,particleRadiusUm:.5},"methane-lox":{condensedShare:.09,particleRadiusUm:.5},"hydrogen-lox":{condensedShare:.13,particleRadiusUm:.5},hypergolic:{condensedShare:.079,particleRadiusUm:.4},solid:{condensedShare:.27,particleRadiusUm:.8}};static G0=9.80665;static COLLAR_SPREAD_OF_EXHAUST_VELOCITY=.735;static plumeOf(e){const t={},i=e.vehicle?.engine;if(i){const n=i.specificImpulseS===void 0?void 0:i.specificImpulseS*Le.G0;i.thrustKN!==void 0&&n&&(t.exhaustKgPerS=i.thrustKN*1e3/n),n&&(t.collarExpansionKmPerS=n/1e3*Le.COLLAR_SPREAD_OF_EXHAUST_VELOCITY),i.propellant&&Object.assign(t,Le.PROPELLANTS[i.propellant])}return{...Le.DEFAULTS,...t,...e.plume}}static PUFF_EVERY_S=.5;static SIGMA_OF_RADIUS=.5;static MAX_PUFFS=320;static DEG=Math.PI/180;static EARTH_ROTATION=72921159e-12;static VENT_DEFAULTS={speedKmPerS:.7,massKgPerS:20,condensedShare:.5,particleRadiusUm:.5,expansionKmPerS:.1,initialRadiusKm:.2,lifetimeS:600};static paths=new WeakMap;static exhaustVelocityKmPerS(e){return(e.vehicle?.engine?.specificImpulseS??348)*Le.G0/1e3}static releasesOf(e){const t=[],i=e.jets??[];if(i.length===0||e.burnFromT!==void 0||e.burnUntilT!==void 0){const n=e.track[0]?.t??0,s=e.track[e.track.length-1]?.t??0;t.push(Le.engineRelease(e,"burn",{fromT:e.burnFromT??n,untilT:e.burnUntilT??s}))}return i.forEach((n,s)=>t.push(Le.releaseOf(e,n,s))),t}static releaseOf(e,t,i){const n=`jet:${t.id??i}`;if((t.kind??"burn")==="burn")return Le.engineRelease(e,n,t);const s=Le.VENT_DEFAULTS;return{key:n,fromT:t.fromT,untilT:t.untilT,angleDeg:t.angleDeg??0,azimuthDeg:t.azimuthDeg??0,spinPeriodS:t.spinPeriodS,speedKmPerS:t.speedKmPerS??s.speedKmPerS,massKgPerS:t.massKgPerS??s.massKgPerS,condensedShare:t.condensedShare??s.condensedShare,particleRadiusUm:t.particleRadiusUm??s.particleRadiusUm,initialRadiusKm:t.initialRadiusKm??s.initialRadiusKm,populations:[{share:1,expansionKmPerS:t.expansionKmPerS??s.expansionKmPerS,lifetimeS:t.lifetimeS??s.lifetimeS}]}}static engineRelease(e,t,i){const n=Le.plumeOf(e);return{key:t,fromT:i.fromT,untilT:i.untilT,angleDeg:i.angleDeg??0,azimuthDeg:i.azimuthDeg??0,spinPeriodS:i.spinPeriodS,speedKmPerS:i.speedKmPerS??Le.exhaustVelocityKmPerS(e),massKgPerS:i.massKgPerS??n.exhaustKgPerS,condensedShare:i.condensedShare??n.condensedShare,particleRadiusUm:i.particleRadiusUm??n.particleRadiusUm,initialRadiusKm:i.initialRadiusKm??n.initialRadiusKm,populations:[{share:1-n.collarShare,expansionKmPerS:i.expansionKmPerS??n.expansionKmPerS,lifetimeS:i.lifetimeS??n.lifetimeS},{share:n.collarShare,expansionKmPerS:n.collarExpansionKmPerS,lifetimeS:n.collarLifetimeS}]}}static extinctionEfficiency(e,t){const i=2*Math.PI*e/t,n=Le.ICE_INDEX**2,s=8/3*i**4*((n-1)/(n+2))**2,r=2*i*(Le.ICE_INDEX-1),a=r<.001?r*r/2:2-4/r*Math.sin(r)+4/(r*r)*(1-Math.cos(r));return Math.min(s,a)}static scatteringColour(e){const t=Le.extinctionEfficiency(e,Le.WAVELENGTHS_UM[1]);return Le.WAVELENGTHS_UM.map(i=>Le.extinctionEfficiency(e,i)/t)}static sunDirectionAt(e){const t=new Fa(0,0,-6378137),i=ch(pe.Sun,e,t,!0,!0),n=(i.ra-zx(e))*15*Le.DEG,s=i.dec*Le.DEG;return[Math.cos(s)*Math.cos(n),Math.cos(s)*Math.sin(n),Math.sin(s)]}static puffsAt(e,t){const i=[];for(const n of e){let s=Le.paths.get(n);s||Le.paths.set(n,s=new Map);for(const r of Le.releasesOf(n)){const a=Math.min(r.untilT,t);if(a<=r.fromT)continue;const o=Math.max(Le.PUFF_EVERY_S*1e3,(r.untilT-r.fromT)/Le.MAX_PUFFS),c=[];for(let f=r.fromT;f<a;f+=o)c.push(f);c.push(a);const h=r.massKgPerS*(o/1e3),u=3*Le.extinctionEfficiency(r.particleRadiusUm,Le.WAVELENGTHS_UM[1])/(4*917*r.particleRadiusUm*1e-6),p=Le.scatteringColour(r.particleRadiusUm);r.populations.forEach((f,m)=>{if(f.share<=0)return;const v=y=>r.initialRadiusKm+f.expansionKmPerS*y,g=[];for(const y of c){const w=(t-y)/1e3;if(w>f.lifetimeS)continue;const b=y!==a||a===r.untilT,M=`${r.key}|${m}|${y}`;let S=b?s.get(M):void 0;if(!S){if(S=Le.launchPuff(n,r,y,h*f.share,v),!S)continue;b&&s.set(M,S)}g.push({ageS:w,position:S.at(w)})}for(let y=g.length-1;y>=0;y--){const{ageS:w,position:b}=g[y],M=g[y-1]??g[y+1],S=M?Math.hypot(b[0]-M.position[0],b[1]-M.position[1],b[2]-M.position[2]):0,E=v(w)+S/2,x=Le.SIGMA_OF_RADIUS*E*1e3,T=h*r.condensedShare*f.share*u/(2*Math.PI*x*x),D=Math.max(0,1-(w/f.lifetimeS)**2);T*D<=0||i.push({launchId:n.id,release:r.key,at:Le.geoPoint(b),radiusKm:E,opticalDepth:T*D,colour:p,ageS:w})}})}}return i}static viewsAt(e,t,i,n){const s=[];for(const r of Le.puffsAt(e,t)){const a=_t.seenFrom(i,r.at);if(a.altitudeDeg<0)continue;const o=Le.sunlightAt(r.at,n);if(o.lit<=0)continue;const c=Le.scatteringPhase(i,r.at,n),h=Le.SUN_ILLUMINANCE_LUX*Le.ALBEDO*c*r.opticalDepth*o.lit;h<=0||s.push({launchId:r.launchId,release:r.release,heightKm:r.at.heightM/1e3,centre:a,radiusDeg:Math.atan2(r.radiusKm,a.distanceKm)/Le.DEG,luminanceCdM2:h,sunTransmittance:o.transmittance,colour:r.colour,lit:o.lit,ageS:r.ageS})}return s}static launchPuff(e,t,i,n,s){const r={id:e.id,track:e.track,fragments:[]},a=_t.leadAt(r,i);if(!a)return;const o=e.track[0].t,c=e.track[e.track.length-1].t,h=Math.max(o,i-500),d=Math.min(c,i+500),u=Le.earthCentred(a),p=Le.earthCentred(_t.leadAt(r,h)),f=Le.earthCentred(_t.leadAt(r,d)),m=Math.max(.001,(d-h)/1e3),v=[0,1,2].map(C=>(f[C]-p[C])/m),g=Le.EARTH_ROTATION,y=[v[0]-g*u[1],v[1]+g*u[0],v[2]],w=C=>{const k=Math.hypot(C[0],C[1],C[2])||1;return C.map(P=>P/k)},b=w(y),M=w(u),S=M[0]*b[0]+M[1]*b[1]+M[2]*b[2];let E=[M[0]-S*b[0],M[1]-S*b[1],M[2]-S*b[2]];Math.hypot(E[0],E[1],E[2])<1e-6&&(E=[-b[2]*b[0],-b[2]*b[1],1-b[2]*b[2]]),E=w(E);const x=[b[1]*E[2]-b[2]*E[1],b[2]*E[0]-b[0]*E[2],b[0]*E[1]-b[1]*E[0]],T=t.spinPeriodS?360*((i-t.fromT)/1e3)/t.spinPeriodS:0,D=(t.azimuthDeg+T)*Le.DEG,R=t.angleDeg*Le.DEG,O=[0,1,2].map(C=>-b[C]*Math.cos(R)+Math.sin(R)*(Math.cos(D)*E[C]+Math.sin(D)*x[C])),N=[0,1,2].map(C=>v[C]+t.speedKmPerS*O[C]);return new XL(u,N,n,s,t.particleRadiusUm)}static geoPoint(e){const t=Math.hypot(e[0],e[1],e[2]);return{lat:Math.asin(e[2]/t)/Le.DEG,lng:Math.atan2(e[1],e[0])/Le.DEG,heightM:(t-$s.EARTH_RADIUS_KM)*1e3}}static sunlightAt(e,t){const i=Le.earthCentred(e),n=i[0]*t[0]+i[1]*t[1]+i[2]*t[2];if(n>=0)return{lit:1,transmittance:[1,1,1]};const s=Math.hypot(i[0]-n*t[0],i[1]-n*t[1],i[2]-n*t[2]),r=Le.PENUMBRA_KM,a=Math.min(1,Math.max(0,(s-(Le.SHADOW_RADIUS_KM-r/2))/r));if(a<=0)return{lit:0,transmittance:[0,0,0]};const o=Math.max(0,(s-Le.EARTH_RADIUS_KM)*1e3),c=Math.exp(-o/Le.SCALE_HEIGHT_M),h=Math.sqrt(2*Math.PI*Le.EARTH_RADIUS_KM*1e3*Le.SCALE_HEIGHT_M),d=Math.exp(-(((o/1e3-25)/15)**2)),u=[0,1,2].map(p=>Math.exp(-Le.RAYLEIGH_PER_M[p]*c*h-Le.OZONE_GRAZING_DEPTH[p]*d));return{lit:a,transmittance:u}}static scatteringPhase(e,t,i){const n=Le.earthCentred(e),s=Le.earthCentred(t),r=[n[0]-s[0],n[1]-s[1],n[2]-s[2]],a=Math.hypot(r[0],r[1],r[2])||1,o=-(r[0]*i[0]+r[1]*i[1]+r[2]*i[2])/a,c=Le.ANISOTROPY;return(1-c*c)/(4*Math.PI*(1+c*c-2*c*o)**1.5)}static earthCentred(e){const t=e.lat*Le.DEG,i=e.lng*Le.DEG,n=Le.EARTH_RADIUS_KM+e.heightM/1e3;return[n*Math.cos(t)*Math.cos(i),n*Math.cos(t)*Math.sin(i),n*Math.sin(t)]}}class gi{static RADIUS=840;static MAX_PUFFS=1e3;static RINGS=[0,.25,.5,.75,1,1.25];static COLUMN=gi.RINGS.map(e=>{const t=n=>Math.exp(-((n/Le.SIGMA_OF_RADIUS)**2)/2),i=t(gi.RINGS[gi.RINGS.length-1]);return Math.max(0,(t(e)-i)/(1-i))});static SECTORS=12;static VERTICES_PER_PUFF=gi.SECTORS*(3+6*(gi.RINGS.length-2));static BRIGHTEST_RELATIVE=6e4;object=new zt;mesh;positions=new Float32Array(gi.MAX_PUFFS*gi.VERTICES_PER_PUFF*3);colors=new Float32Array(gi.MAX_PUFFS*gi.VERTICES_PER_PUFF*3);shown=0;drawn=[];static VISIBLE_CONTRAST=.1;constructor(){this.object.name="plumes";const e=new ct;e.setAttribute("position",new mt(this.positions,3)),e.setAttribute("color",new mt(this.colors,3)),e.setDrawRange(0,0),this.mesh=new xe(e,Ps.material()),this.mesh.frustumCulled=!1,Ps.track(this.mesh),this.object.add(this.mesh)}get count(){return this.shown}set(e,t,i,n){let s=0,r=0;this.drawn=[];for(const o of e){if(r>=gi.MAX_PUFFS)break;const c=n(o.centre);if(c<=0)continue;const h=i(o.centre),d=[0,1,2].map(u=>Math.min(gi.BRIGHTEST_RELATIVE,o.luminanceCdM2*(o.colour?.[u]??1)*t*o.sunTransmittance[u]*h[u]*c));Math.max(...d)<=0||(s=this.pushPuff(s,o,d),this.drawn.push({view:o,direction:this.normalise(oi(o.centre.altitudeDeg,o.centre.azimuthDeg,1)),radiusRad:o.radiusDeg*Math.PI/180,luminance:.2126*d[0]+.7152*d[1]+.0722*d[2]}),r++)}this.shown=r;const a=this.mesh.geometry;a.setDrawRange(0,s),a.getAttribute("position").needsUpdate=!0,a.getAttribute("color").needsUpdate=!0}pushPuff(e,t,i){const n=oi(t.centre.altitudeDeg,t.centre.azimuthDeg,gi.RADIUS),s=this.normalise(n),r=this.normalise(this.cross({x:0,y:1,z:0},s)),a=this.cross(s,r),o=gi.RADIUS*Math.tan(t.radiusDeg*Math.PI/180),c=(d,u)=>{const p=u/gi.SECTORS*2*Math.PI,f=gi.RINGS[d]*o,m=Math.cos(p)*f,v=Math.sin(p)*f;return{x:n.x+r.x*m+a.x*v,y:n.y+r.y*m+a.y*v,z:n.z+r.z*m+a.z*v}},h=d=>gi.COLUMN[d];for(let d=0;d<gi.SECTORS;d++){const u=(d+1)%gi.SECTORS;e=this.push(e,n,i,h(0)),e=this.push(e,c(1,d),i,h(1)),e=this.push(e,c(1,u),i,h(1));for(let p=1;p<gi.RINGS.length-1;p++){const f=c(p,d),m=c(p,u),v=c(p+1,d),g=c(p+1,u);e=this.push(e,f,i,h(p)),e=this.push(e,m,i,h(p)),e=this.push(e,v,i,h(p+1)),e=this.push(e,m,i,h(p)),e=this.push(e,g,i,h(p+1)),e=this.push(e,v,i,h(p+1))}}return e}pickAt(e,t,i=0){const n=this.normalise(e);let s=0,r;for(const a of this.drawn){const o=Math.max(-1,Math.min(1,n.x*a.direction.x+n.y*a.direction.y+n.z*a.direction.z)),c=Math.max(0,Math.acos(o)-t)/Math.max(a.radiusRad,1e-9),h=a.luminance*gi.profile(c);h<=0||(s+=h,(!r||h>r.light)&&(r={view:a.view,light:h}))}return r&&s>=gi.VISIBLE_CONTRAST*i?r.view:void 0}static profile(e){const t=gi.RINGS;if(e>=t[t.length-1])return 0;let i=0;for(;e>t[i+1];)i++;const n=(e-t[i])/(t[i+1]-t[i]);return gi.COLUMN[i]+(gi.COLUMN[i+1]-gi.COLUMN[i])*n}push(e,t,i,n){const s=e*3;return this.positions[s]=t.x,this.positions[s+1]=t.y,this.positions[s+2]=t.z,this.colors[s]=i[0]*n,this.colors[s+1]=i[1]*n,this.colors[s+2]=i[2]*n,e+1}cross(e,t){return this.normalise({x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x})}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose(),this.object.removeFromParent()}}class Is{static RADIUS=840;static MAX_SEGMENTS=256;static VERTICES_PER_SEGMENT=12;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;static TRAIN_SHARE=.6;object=new zt;tiers;trains;positions;colors;shown=0;constructor(){this.object.name="reentries",this.tiers=Dl.map(i=>{const n=new Cs(new ct,Ne.material(i.size,!1));return Ne.track(n),n.frustumCulled=!1,this.object.add(n),n});const e=Is.MAX_SEGMENTS*Is.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new ct;t.setAttribute("position",new mt(this.positions,3)),t.setAttribute("color",new mt(this.colors,3)),t.setDrawRange(0,0),this.trains=new xe(t,Ps.material()),this.trains.frustumCulled=!1,Ps.track(this.trains),this.object.add(this.trains)}get count(){return this.shown}set(e,t,i,n){const s=this.tiers.map(()=>[]);let r=0,a=0;const o=new re;for(const h of e){const d=i(h.head);if(d<=0)continue;const u=h.magnitude-2.5*Math.log10(d);if(u>t)continue;a++,o.set(h.color);const p=Ml(u,t),{x:f,y:m,z:v}=oi(h.head.altitudeDeg,h.head.azimuthDeg,Is.RADIUS),[g,y,w]=n(h.head,u),b=Math.max(o.r,o.g,o.b)||1;s[vm(p)].push({x:f,y:m,z:v,r:g*o.r/b,g:y*o.g/b,b:w*o.b/b}),r=this.pushTrain(r,h.train,p,o)}this.shown=a,this.tiers.forEach((h,d)=>{const u=s[d],p=new Float32Array(u.length*3),f=new Float32Array(u.length*3);u.forEach((v,g)=>{p.set([v.x,v.y,v.z],g*3),f.set([v.r,v.g,v.b],g*3)}),h.geometry.dispose();const m=new ct;m.setAttribute("position",new mt(p,3)),m.setAttribute("color",new mt(f,3)),h.geometry=m});const c=this.trains.geometry;c.setDrawRange(0,r),c.getAttribute("position").needsUpdate=!0,c.getAttribute("color").needsUpdate=!0}pushTrain(e,t,i,n){const s=t.length-1;for(let r=0;r<s;r++){if(e+Is.VERTICES_PER_SEGMENT>Is.MAX_SEGMENTS*Is.VERTICES_PER_SEGMENT)return e;const a=1-r/s,o=1-(r+1)/s,c=oi(t[r].altitudeDeg,t[r].azimuthDeg,Is.RADIUS),h=oi(t[r+1].altitudeDeg,t[r+1].azimuthDeg,Is.RADIUS),d=p=>Is.RADIUS*((Is.MIN_HALF_WIDTH_DEG+Is.BRIGHT_HALF_WIDTH_DEG*i*p)*Math.PI/180),u=p=>Is.TRAIN_SHARE*i*p**1.6;e=this.pushRibbon(e,c,h,d(a),d(o),u(a),u(o),n)}return e}pushRibbon(e,t,i,n,s,r,a,o){const c={x:i.x-t.x,y:i.y-t.y,z:i.z-t.z};if(Math.hypot(c.x,c.y,c.z)<1e-9)return e;const h=this.normalise(this.cross(this.normalise(t),this.normalise(c)));for(const[d,u]of[[-1,0],[0,1]]){const p=this.across(t,h,n,d),f=this.across(i,h,s,d),m=this.across(t,h,n,u),v=this.across(i,h,s,u),g=(y,w)=>y===0?w:0;e=this.push(e,p,g(d,r),o),e=this.push(e,f,g(d,a),o),e=this.push(e,m,g(u,r),o),e=this.push(e,f,g(d,a),o),e=this.push(e,v,g(u,a),o),e=this.push(e,m,g(u,r),o)}return e}across(e,t,i,n){return{x:e.x+t.x*i*n,y:e.y+t.y*i*n,z:e.z+t.z*i*n}}push(e,t,i,n){const s=e*3;this.positions[s]=t.x,this.positions[s+1]=t.y,this.positions[s+2]=t.z;const r=Fe.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[s]=r*n.r,this.colors[s+1]=r*n.g,this.colors[s+2]=r*n.b,e+1}cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){for(const e of this.tiers)e.geometry.dispose(),e.material.dispose();this.trains.geometry.dispose(),this.trains.material.dispose(),this.object.removeFromParent()}}class bm{constructor(e){this.state=e}next(){this.state=this.state+1831565813|0;let e=this.state;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}between(e,t){return e+this.next()*(t-e)}}class Ir{static MIN_DURATION_MS=250;static MAX_DURATION_MS=1400;static schedule(e){const{ratePerHour:t,durationMs:i,velocityKmS:n,seed:s}=e;if(t<=0||i<=0)return[];const r=t*i/36e5,a=new bm(s),o=Math.floor(r),c=o+(a.next()<r-o?1:0),h=[];for(let d=0;d<c;d++){const u=Math.min(1,Math.max(0,(n-20)/52)),p=Ir.MAX_DURATION_MS-u*(Ir.MAX_DURATION_MS-Ir.MIN_DURATION_MS),f=a.between(5,70);h.push({t:a.between(0,i),durationMs:p*a.between(.7,1.3),fromRadiantDeg:f,bearingDeg:a.between(0,360),lengthDeg:Math.sin(f*Math.PI/180)*a.between(8,40)*(.6+u),brightness:a.next()**3}),h.sort((m,v)=>m.t-v.t)}return h}static FAINTEST_MAGNITUDE=6.5;static BRIGHTEST_MAGNITUDE=-4;static magnitudeOf(e){return Ir.FAINTEST_MAGNITUDE-(Ir.FAINTEST_MAGNITUDE-Ir.BRIGHTEST_MAGNITUDE)*e.brightness}static aliveAt(e,t){return e.filter(i=>t>=i.t&&t<=i.t+i.durationMs).map(i=>({meteor:i,progress:(t-i.t)/i.durationMs}))}}class uo{object=new zt;radius;core;glow;flashKey;static CORE_WIDTH_DEG=.06;static GLOW_WIDTH_DEG=.5;static SEGMENTS=28;static CORE_RELATIVE=1e3;constructor(e){this.radius=e,this.object.name="lightning-bolt",this.core=new Fs({color:15659775,transparent:!0,opacity:0,blending:An,depthWrite:!1,fog:!1}),this.glow=new Fs({color:10466559,transparent:!0,opacity:0,blending:An,depthWrite:!1,fog:!1}),this.object.visible=!1,this.object.renderOrder=5.95}set(e,t,i){if(!e||!e.cloudToGround||t<=.01){this.object.visible=!1;return}const n=`${e.channelSeed}:${Math.round(i)}`;n!==this.flashKey&&this.build(e,i,n),this.core.color.setHex(15659775).multiplyScalar(uo.CORE_RELATIVE*Math.min(1,t*1.4)),this.glow.color.setHex(10466559).multiplyScalar(.1*uo.CORE_RELATIVE*t*.35),this.core.opacity=1,this.glow.opacity=1,this.object.visible=!0}build(e,t,i){this.flashKey=i;for(const c of[...this.object.children])c.geometry.dispose(),this.object.remove(c);const n=new bm(e.channelSeed),s=Math.atan2(t,e.distanceM)*180/Math.PI,r=this.channel(n,e.azimuthDeg,s,0,1),a=[r],o=1+Math.floor(n.next()*2);for(let c=0;c<o;c++){const h=r[Math.floor(n.between(.15,.5)*r.length)];a.push(this.channel(n,h.azimuthDeg,h.altitudeDeg,h.altitudeDeg*n.between(.3,.7),.5))}for(const c of a)this.object.add(new xe(this.ribbon(c,uo.GLOW_WIDTH_DEG),this.glow)),this.object.add(new xe(this.ribbon(c,uo.CORE_WIDTH_DEG),this.core))}channel(e,t,i,n,s){const r=[],a=i-n;let o=t;for(let c=0;c<=uo.SEGMENTS;c++){const h=i-a*c/uo.SEGMENTS;r.push({azimuthDeg:o,altitudeDeg:h}),o+=e.between(-1,1)*a*.06*s}return r}ribbon(e,t){const i=new Float32Array(e.length*2*3),n=[],s=this.radius*Math.tan(t*Math.PI/180)/2,r=e.map(o=>{const{x:c,y:h,z:d}=oi(o.altitudeDeg,o.azimuthDeg,this.radius);return new _(c,h,d)});r.forEach((o,c)=>{const h=r[Math.min(c+1,r.length-1)],d=r[Math.max(c-1,0)],p=h.clone().sub(d).normalize().cross(o.clone().normalize()).normalize().multiplyScalar(s);if(i.set([o.x+p.x,o.y+p.y,o.z+p.z],c*6),i.set([o.x-p.x,o.y-p.y,o.z-p.z],c*6+3),c<r.length-1){const f=c*2;n.push(f,f+1,f+2,f+1,f+3,f+2)}});const a=new ct;return a.setAttribute("position",new mt(i,3)),a.setIndex(n),a}dispose(){for(const e of this.object.children)e.geometry.dispose();this.core.dispose(),this.glow.dispose(),this.object.removeFromParent()}}class xn{static MIN_INTERVAL_S=8;static MAX_INTERVAL_S=25;static SEVERE_MIN_INTERVAL_S=2;static SEVERE_MAX_INTERVAL_S=8;static CLOUD_TO_GROUND_FRACTION=.25;static MIN_DISTANCE_M=1e3;static MAX_DISTANCE_M=15e3;static INTERSTROKE_MS=60;static STROKE_DECAY_MS=40;static SOUND_SPEED_M_S=343;static schedule(e){const t=new bm(e.seed),i=[],{minS:n,maxS:s}=xn.intervalFor(e.intensity??.5);let r=t.between(0,s)*1e3;for(;r<e.durationMs;){const a=t.next()<xn.CLOUD_TO_GROUND_FRACTION,o=xn.MIN_DISTANCE_M,c=xn.MAX_DISTANCE_M,h=Math.sqrt(t.between(o*o,c*c)),d=a?1+Math.floor(t.next()*4):1,u=[];let p=0;for(let f=0;f<d;f++)u.push({offsetMs:p,intensity:f===0?1:t.between(.4,.9)}),p+=xn.INTERSTROKE_MS*t.between(.5,1.6);i.push({t:r,azimuthDeg:t.between(0,360),distanceM:h,cloudToGround:a,strokes:u,channelSeed:Math.floor(t.next()*2**31)}),r+=t.between(n,s)*1e3}return i}static intervalFor(e){const t=Math.min(1,Math.max(0,(e-.5)/.5));return{minS:xn.MIN_INTERVAL_S-t*(xn.MIN_INTERVAL_S-xn.SEVERE_MIN_INTERVAL_S),maxS:xn.MAX_INTERVAL_S-t*(xn.MAX_INTERVAL_S-xn.SEVERE_MAX_INTERVAL_S)}}static brightnessAt(e,t){let i=0;for(const n of e.strokes){const s=t-e.t-n.offsetMs;s<0||s>xn.STROKE_DECAY_MS*6||(i+=n.intensity*Math.exp(-s/xn.STROKE_DECAY_MS))}return Math.min(1,i)}static endOf(e){const t=e.strokes[e.strokes.length-1];return e.t+t.offsetMs+xn.STROKE_DECAY_MS*6}static thunderDelayMs(e){return e.distanceM/xn.SOUND_SPEED_M_S*1e3}}class Uc{static ODD_RADIUS_WEDGES_DEG=[28,56,80];static STANDS_OUT=1.5;static NEIGHBOURHOOD_DEG=2.5;static oddRadiiDeg(){const e=(ut.ICE_INDEX_RED+ut.ICE_INDEX_BLUE)/2;return Uc.ODD_RADIUS_WEDGES_DEG.map(t=>ut.minimumDeviationDeg(t,e)).filter(t=>Number.isFinite(t))}static at(e,t,i,n){const s=Math.PI/180,r=e,a=Math.abs(i),o=Math.sin(r*s)*Math.sin(t*s)+Math.cos(r*s)*Math.cos(t*s)*Math.cos(a*s),c=Math.acos(Math.max(-1,Math.min(1,o)))/s,h=Math.atan2(Math.sin(a*s)*Math.cos(t*s),Math.cos(r*s)*Math.sin(t*s)-Math.sin(r*s)*Math.cos(t*s)*Math.cos(a*s))/s,d=Math.abs(t-r),u=()=>{const y=n(t,a);if(!(y>0))return!1;const w=Uc.NEIGHBOURHOOD_DEG,b=1/Math.max(.2,Math.cos(t*s)),M=[n(t+w,a),n(t-w,a),n(t,a+w*b),n(t,Math.max(0,a-w*b))].sort((S,E)=>S-E);return y>M[1]*Uc.STANDS_OUT},p=()=>{const y=w=>{const b=c*s,M=w*s,S=Math.cos(b)*Math.cos(r*s)-Math.sin(b)*Math.cos(M)*Math.sin(r*s),E=Math.sin(b)*Math.sin(M),x=Math.cos(b)*Math.sin(r*s)+Math.sin(b)*Math.cos(M)*Math.cos(r*s);return n(Math.asin(Math.max(-1,Math.min(1,x)))/s,Math.abs(Math.atan2(E,S)/s))};return(y(70)+y(110)+y(250)+y(290))/4},f=(y,w=0)=>{if(u())return w>0&&!(n(t,a)>p()*w)?void 0:y};if(r>0&&r<ut.PARHELIA_MAX_SUN_ALTITUDE_DEG&&d<2.5){const y=ut.parheliaAzimuthDeg(r);if(y!==void 0&&a>=y-1.2&&a<=y+7){const w=f({id:"parhelion",angleDeg:ut.parheliaDistanceDeg(r)},2.5);if(w)return w}}if(r>0&&d<2.5&&Math.abs(a-120)<4){const y=f({id:"parhelion120",angleDeg:120},0);if(y)return y}const m=ut.circumzenithalAltitudeDeg(r);if(m!==void 0&&t>m-2&&t<m+4){const y=f({id:"circumzenithal",angleDeg:m});if(y)return y}if(r>ut.PLATE_END_FACE_LIMIT_DEG){const y=ut.circumzenithalAltitudeDeg(90-r);if(y!==void 0){const w=90-y;if(t>w-4&&t<w+2){const b=f({id:"circumhorizontal",angleDeg:w});if(b)return b}}}if(a<3&&r>0){if(t>r+3&&t<r+25&&r<ut.PILLAR_MAX_SOURCE_ALTITUDE_DEG){const y=f({id:"pillar"});if(y)return y}if(Math.abs(t+r)<3){const y=f({id:"subsun"});if(y)return y}}const v=ut.halo22();if(c>v.redAngleDeg-.6&&c<v.blueAngleDeg+2.5){const y=Math.abs(h)<50,w=Math.abs(h)>130;if(y||w){const b=f({id:y?"upperTangentArc":"lowerTangentArc",angleDeg:v.angleDeg},1.5);if(b)return b}}for(const y of Uc.oddRadiiDeg())if(c>y-.6&&c<y+1.8){const w=f({id:"oddRadius",angleDeg:y});if(w)return w}if(c>v.redAngleDeg-.6&&c<v.blueAngleDeg+2.5){const y=f({id:"halo22",angleDeg:v.angleDeg});if(y)return y}const g=ut.halo46();if(c>g.redAngleDeg-.6&&c<g.blueAngleDeg+3){const y=f({id:"halo46",angleDeg:g.angleDeg});if(y)return y}if(r>0&&d<1.2){const y=n(t,a),w=Math.max(n(t+3,a),n(t-3,a));if(y>0&&y>w*2)return{id:"parhelicCircle",angleDeg:r}}}}class _s{static RED_NM=656.3;static BLUE_NM=435.8;static ANCHOR_RED=1.3067;static ANCHOR_BLUE=1.317;static B=(_s.ANCHOR_BLUE-_s.ANCHOR_RED)/(1/(_s.BLUE_NM*_s.BLUE_NM)-1/(_s.RED_NM*_s.RED_NM));static A=_s.ANCHOR_RED-_s.B/(_s.RED_NM*_s.RED_NM);static indexAt(e){return _s.A+_s.B/(e*e)}}class ta{static MAX_FACES=20;normals=new Float64Array(ta.MAX_FACES*3);offsets=new Float64Array(ta.MAX_FACES);faceCount=8;radius=1;set(e,t,i,n,s,r,a=0){let o=0,c=0,h=0;Math.abs(i)<.9?(o=-t,c=e,h=0):(o=0,c=-i,h=t);const d=Math.hypot(o,c,h)||1;o/=d,c/=d,h/=d;const u=t*h-i*c,p=i*o-e*h,f=e*c-t*o,m=s/2,v=r/2;for(let g=0;g<6;g++){const y=n+g*Math.PI/3,w=Math.cos(y),b=Math.sin(y);this.normals[g*3]=o*w+u*b,this.normals[g*3+1]=c*w+p*b,this.normals[g*3+2]=h*w+f*b,this.offsets[g]=m}if(this.normals[18]=e,this.normals[19]=t,this.normals[20]=i,this.offsets[6]=v,this.normals[21]=-e,this.normals[22]=-t,this.normals[23]=-i,this.offsets[7]=v,this.faceCount=8,a>0){const g=ta.PYRAMID_TILT,y=Math.cos(g),w=Math.sin(g),b=Math.min(v,a*m*Math.tan(g)),M=v-b,S=y*M+w*m;for(let E=0;E<6;E++){const x=E*3,T=(8+E)*3,D=(14+E)*3;this.normals[T]=y*e+w*this.normals[x],this.normals[T+1]=y*t+w*this.normals[x+1],this.normals[T+2]=y*i+w*this.normals[x+2],this.normals[D]=-y*e+w*this.normals[x],this.normals[D+1]=-y*t+w*this.normals[x+1],this.normals[D+2]=-y*i+w*this.normals[x+2],this.offsets[8+E]=S,this.offsets[14+E]=S}this.faceCount=ta.MAX_FACES}this.radius=Math.hypot(m*2/Math.sqrt(3),v)}static rollToward(e,t,i,n,s,r){let a,o,c;Math.abs(i)<.9?(a=-t,o=e,c=0):(a=0,o=-i,c=t);const h=Math.hypot(a,o,c)||1;a/=h,o/=h,c/=h;const d=t*c-i*o,u=i*a-e*c,p=e*o-t*a;return Math.atan2(n*d+s*u+r*p,n*a+s*o+r*c)}get aimRadius(){return this.radius}trace(e,t,i,n,s,r,a){let o=-t,c=e,h=0,d=Math.hypot(o,c,h);d<1e-6&&(o=1,c=0,h=0,d=1),o/=d,c/=d,h/=d;const u=t*h-i*c,p=i*o-e*h,f=e*c-t*o,m=o*n+u*s-e*this.radius*2,v=c*n+p*s-t*this.radius*2,g=h*n+f*s-i*this.radius*2;let y=-1,w=-1/0,b=1/0;for(let W=0;W<this.faceCount;W++){const ee=this.normals[W*3],se=this.normals[W*3+1],Be=this.normals[W*3+2],ht=ee*e+se*t+Be*i,Xe=this.offsets[W]-(ee*m+se*v+Be*g);if(ht>1e-9){const j=Xe/ht;j<b&&(b=j)}else if(ht<-1e-9){const j=Xe/ht;j>w&&(w=j,y=W)}else if(Xe<0)return 0}if(y<0||w>=b)return 0;let M=0;const S=this.normals[y*3],E=this.normals[y*3+1],x=this.normals[y*3+2],T=-(S*e+E*t+x*i),D=Rf.reflectance(T,1,r);a[M].x=e+2*T*S,a[M].y=t+2*T*E,a[M].z=i+2*T*x,a[M].weight=D,M++;const R=1/r,O=Math.sqrt(Math.max(0,1-R*R*(1-T*T)));let N=R*e+(R*T-O)*S,C=R*t+(R*T-O)*E,k=R*i+(R*T-O)*x,P=m+e*w,F=v+t*w,G=g+i*w,Y=1-D;for(let W=0;W<ta.MAX_BOUNCES&&Y>ta.MIN_WEIGHT;W++){let ee=-1,se=1/0;for(let V=0;V<this.faceCount;V++){const He=this.normals[V*3],Ye=this.normals[V*3+1],Ve=this.normals[V*3+2],De=He*N+Ye*C+Ve*k;if(De<=1e-9)continue;const Qe=(this.offsets[V]-(He*P+Ye*F+Ve*G))/De;Qe>1e-9&&Qe<se&&(se=Qe,ee=V)}if(ee<0)break;const Be=this.normals[ee*3],ht=this.normals[ee*3+1],Xe=this.normals[ee*3+2],j=Be*N+ht*C+Xe*k,le=r*Math.sqrt(Math.max(0,1-j*j));if(P+=N*se,F+=C*se,G+=k*se,le<1){const V=Math.sqrt(Math.max(0,1-le*le)),He=Rf.reflectance(j,r,1);if(a[M].x=r*N-(r*j-V)*Be,a[M].y=r*C-(r*j-V)*ht,a[M].z=r*k-(r*j-V)*Xe,a[M].weight=Y*(1-He),M++,M>=a.length)return M;Y*=He}const oe=2*j;N-=oe*Be,C-=oe*ht,k-=oe*Xe}return M}static MAX_BOUNCES=6;static PYRAMID_TILT=62*Math.PI/180;static MIN_WEIGHT=1e-4}class $t{static AZIMUTH_BINS=512;static ALTITUDE_BINS=512;static DEFAULT_POPULATIONS=[{orientation:"tumbling",widthMicrons:50,lengthMicrons:50,share:.48},{orientation:"plate",widthMicrons:100,lengthMicrons:15,share:.27},{orientation:"column",widthMicrons:40,lengthMicrons:120,share:.18},{orientation:"parry",widthMicrons:40,lengthMicrons:120,share:.02},{orientation:"pyramidal",widthMicrons:40,lengthMicrons:120,share:.03,capFraction:.5},{orientation:"lowitz",widthMicrons:100,lengthMicrons:15,share:.02}];static DEFAULT_RARE_SHARE=fx;static populationsFor(e){const t=Math.min(.9,Math.max(0,e));if(Math.abs(t-$t.DEFAULT_RARE_SHARE)<1e-9)return $t.DEFAULT_POPULATIONS;const i=(1-t)/(1-$t.DEFAULT_RARE_SHARE);return $t.DEFAULT_POPULATIONS.map(n=>n.orientation==="pyramidal"||n.orientation==="lowitz"?{...n,share:n.share/$t.DEFAULT_RARE_SHARE*t}:{...n,share:n.share*i})}populations=$t.DEFAULT_POPULATIONS;populationTotal=1;static WORST_TILT_DEG=180;static BEST_TILT_DEG=.5;static SOURCE_RADIUS_DEG=.265;static UNDEVIATED_DEG=.6;crystal=new ta;emergent=Array.from({length:ta.MAX_BOUNCES+2},()=>({x:0,y:0,z:0,weight:0}));tally=new Float32Array($t.AZIMUTH_BINS*$t.ALTITUDE_BINS*3);radiance=new Float32Array($t.AZIMUTH_BINS*$t.ALTITUDE_BINS*3);scratch=new Float32Array($t.AZIMUTH_BINS*$t.ALTITUDE_BINS*3);seed=1;spare=0;hasSpare=!1;altitude=0;tilt=0;alignment=0;traced=0;begin(e,t,i=2654435769,n=$t.DEFAULT_POPULATIONS){this.populations=n,this.populationTotal=n.reduce((r,a)=>r+a.share,0)||1,this.seed=i>>>0||1,this.hasSpare=!1,this.tally.fill(0),this.traced=0,this.altitude=e*Math.PI/180,this.alignment=Math.min(1,Math.max(0,t));const s=$t.WORST_TILT_DEG*($t.BEST_TILT_DEG/$t.WORST_TILT_DEG)**this.alignment;this.tilt=s*Math.PI/180}trace(e){const t=$t.AZIMUTH_BINS,i=$t.ALTITUDE_BINS,n=this.tally,s=$t.SOURCE_RADIUS_DEG*Math.PI/180,r=Math.cos($t.UNDEVIATED_DEG*Math.PI/180),a=this.altitude;for(let o=0;o<e;o++){const c=this.pickPopulation();this.orient(c,this.tilt);const h=this.random()*2*Math.PI,d=s*Math.sqrt(this.random()),u=a+d*Math.sin(h),p=d*Math.cos(h)/Math.max(.05,Math.cos(a)),f=-Math.cos(u)*Math.cos(p),m=-Math.cos(u)*Math.sin(p),v=-Math.sin(u),g=this.crystal.aimRadius,y=(this.random()*2-1)*g,w=(this.random()*2-1)*g,b=4*g*g,M=En.SAMPLES[this.random()*En.SAMPLES.length|0],S=this.crystal.trace(f,m,v,y,w,_s.indexAt(M.wavelengthNm),this.emergent);for(let E=0;E<S;E++){const x=this.emergent[E],T=Math.hypot(x.x,x.y,x.z);if(T<1e-9||x.weight<=0)continue;const D=x.x/T,R=x.y/T,O=x.z/T;if(D*f+R*m+O*v>r)continue;const N=Math.asin(Math.max(-1,Math.min(1,-O))),C=Math.abs(Math.atan2(-R,-D)),k=Math.min(t-1,C/Math.PI*t|0),F=(Math.min(i-1,(N+Math.PI/2)/Math.PI*i|0)*t+k)*3,G=x.weight*b*En.SAMPLES.length;n[F]+=G*M.r,n[F+1]+=G*M.g,n[F+2]+=G*M.b}}this.traced+=e}get tracedRays(){return this.traced}harvest(){const e=$t.AZIMUTH_BINS,t=$t.ALTITUDE_BINS;return this.toRadiance(e,t),this.smooth(e,t),{width:e,height:t,data:this.radiance,sourceAltitudeDeg:this.altitude*180/Math.PI,alignment:this.alignment,rays:this.traced}}compute(e,t,i,n,s){return this.begin(e,t,n,s),this.trace(i),this.harvest()}toRadiance(e,t){const i=2*Math.PI/e,n=Math.max(1,this.traced),s=4*$t.REFERENCE_MICRONS*$t.REFERENCE_MICRONS;for(let r=0;r<t;r++){const a=Math.sin(r/t*Math.PI-Math.PI/2),o=Math.sin((r+1)/t*Math.PI-Math.PI/2),c=1/(i*(o-a)*n*s);for(let h=0;h<e;h++){const d=(r*e+h)*3;this.radiance[d]=this.tally[d]*c,this.radiance[d+1]=this.tally[d+1]*c,this.radiance[d+2]=this.tally[d+2]*c}}}static REFERENCE_MICRONS=50;smooth(e,t){const i=this.scratch,n=this.radiance;i.set(n);for(let r=0;r<t;r++){const a=r*e*3;for(let o=0;o<3;o++){let c=i[a+o];for(let h=0;h<e;h++){const d=a+h*3+o,u=h+1<e?i[d+3]:i[d];n[d]=(c+2*i[d]+u)/4,c=i[d]}}}i.set(n);const s=e*3;for(let r=0;r<t;r++){const a=r>0?-s:0,o=r+1<t?s:0,c=r*s;for(let h=c;h<c+s;h++)n[h]=(i[h+a]+2*i[h]+i[h+o])/4}}pickPopulation(){const e=this.random()*this.populationTotal;let t=0;for(const i of this.populations)if(t+=i.share,e<=t)return i;return this.populations[this.populations.length-1]}orient(e,t){const i=this.random()*2*Math.PI;let n=this.random()*2*Math.PI,s=0,r=0,a=1;switch(e.orientation){case"pyramidal":case"tumbling":{a=this.random()*2-1;const o=Math.sqrt(Math.max(0,1-a*a));s=o*Math.cos(i),r=o*Math.sin(i);break}case"plate":{a=this.spreadAboutAnAxis(t);const o=Math.sqrt(Math.max(0,1-a*a));s=o*Math.cos(i),r=o*Math.sin(i);break}case"column":case"parry":{a=this.spreadAboutAPlane(t);const o=Math.sqrt(Math.max(0,1-a*a));s=o*Math.cos(i),r=o*Math.sin(i),e.orientation==="parry"&&(n=Math.PI/2+this.gaussian()*t);break}}if(e.orientation==="lowitz"){const o=this.spreadAboutAPlane(t),c=Math.sqrt(Math.max(0,1-o*o)),h=c*Math.cos(i),d=c*Math.sin(i),u=o;let p=-u*h,f=-u*d,m=1-u*u;const v=Math.hypot(p,f,m)||1;p/=v,f/=v,m/=v;const g=d*m-u*f,y=u*p-h*m,w=h*f-d*p,b=this.random()*2*Math.PI;s=p*Math.cos(b)+g*Math.sin(b),r=f*Math.cos(b)+y*Math.sin(b),a=m*Math.cos(b)+w*Math.sin(b),n=ta.rollToward(s,r,a,h,d,u)+Math.PI/6}this.crystal.set(s,r,a,n,e.widthMicrons,e.lengthMicrons,e.capFraction??0)}random(){this.seed=this.seed+1831565813>>>0;let e=this.seed;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}spreadAboutAnAxis(e){const t=1/Math.max(1e-6,e*e),i=Math.max(1e-12,this.random()),n=1+Math.log(i+(1-i)*Math.exp(-2*t))/t;return Math.max(-1,Math.min(1,n))}spreadAboutAPlane(e){for(let t=0;t<8;t++){const i=this.gaussian()*e;if(i>=-1&&i<=1)return i}return this.random()*2-1}gaussian(){if(this.hasSpare)return this.hasSpare=!1,this.spare;const e=Math.sqrt(-2*Math.log(Math.max(1e-12,this.random()))),t=2*Math.PI*this.random();return this.spare=e*Math.sin(t),this.hasSpare=!0,e*Math.cos(t)}}class YL{static fromRadiance(e,t){const i=js.toHalfFloat(1);for(let n=0,s=0;s<e.length;n+=4,s+=3)t[n]=js.toHalfFloat(e[s]),t[n+1]=js.toHalfFloat(e[s+1]),t[n+2]=js.toHalfFloat(e[s+2]),t[n+3]=i}}class ji{static RADIUS=880;static RAYS=9e5;static RAYS_PER_BATCH=2e3;static BUDGET_MS=6;static URGENT_BUDGET_MS=40;static ALTITUDE_STEP_DEG=1;static ALIGNMENT_STEP=.05;static LEAP_ALTITUDE_DEG=5;static LEAP_ALIGNMENT=.25;static GAIN=.55;setCloudOffset(e){this.material.uniforms.uFieldOffset.value.copy(e)}object;material;sky=new $t;texture;texels;mappedAltitudeDeg=Number.NaN;mappedAlignment=Number.NaN;mappedRare=Number.NaN;tracing=!1;everDisplayed=!1;urgent=!1;workHandle;onRepaint;constructor(){const e=$t.AZIMUTH_BINS,t=$t.ALTITUDE_BINS;this.texels=new Uint16Array(e*t*4),this.texture=new Qs(this.texels,e,t,bn,Jt),this.texture.minFilter=Dt,this.texture.magFilter=Dt,this.texture.wrapS=tn,this.texture.wrapT=tn,this.texture.needsUpdate=!0,this.material=new Ct({uniforms:{uSource:{value:new _(0,1,0)},uUp:{value:new _(0,1,0)},uStrength:{value:0},uTint:{value:new _(1,.97,.92)},uIceCover:{value:0},uIceHeight:{value:1},uFieldOffset:{value:new _},uMap:{value:this.texture},uGain:{value:ji.GAIN}},vertexShader:`
10475
+ `,blending:Js,depthTest:!1,depthWrite:!1}),this.quad=new xe(new xs(2,2),this.copyMaterial),this.quadScene.add(this.quad)}develop(e,t,i,n=1,s,r=!0){const a=e.getRenderTarget();this.readable=r,this.copyMaterial.uniforms.uSource.value=t.scene.texture,this.copyMaterial.uniforms.uGain.value=n,this.draw(e,this.copyMaterial,this.mips);const o=this.ghostMaterial.uniforms;o.uSize.value.set(this.mips.width,this.mips.height);const c=Math.min(i.ghosts.length,Ts.MAX_GHOSTS);o.uCount.value=c;for(let p=0;p<c;p++){const f=i.ghosts[p];o.uScale.value[p]=f.scale||1,o.uShare.value[p]=f.share,o.uBlur.value[p]=f.blur,o.uKind.value[p]=f.cause==="drops"?2:bi.scatters(f)?1:0,o.uOffset.value[p].set(f.offset?.[0]??0,f.offset?.[1]??0),o.uTint.value[p].set(...f.tint??[1,1,1])}o.uBlades.value=i.blades,o.uBladeAngle.value=i.bladeAngleRad,o.uDrops.value=i.drops,o.uImpacts.value=i.impacts;const h=o.uHistory.value;for(let p=0;p<h.length;p++)h[p]=i.history[p]??0;o.uStill.value=i.still?1:0,o.uRunning.value=i.running,o.uBright.value.set(((s?.x??0)+1)/2,((s?.y??0)+1)/2),o.uBrightRadius.value=s?.radius??0;const d=s?.flux??[0,0,0];o.uBrightFlux.value.set(d[0]*n,d[1]*n,d[2]*n),this.draw(e,this.ghostMaterial,this.ghostLayer);const u=this.developMaterial.uniforms;u.uSource.value=t.scene.texture,u.uOverlay.value=t.overlay.texture,u.uGain.value=n,u.uKept.value=1-i.scattered,this.draw(e,this.developMaterial,a)}pickAt(e,t,i,n,s){const r=this.mips.width,a=this.mips.height,o=(u,p)=>({x:Math.round((u+1)/2*r),y:Math.round((p+1)/2*a)}),c=o(t,i),h=this.window(e,c.x,c.y,0);if(!h)return;let d;for(const u of n.ghosts){const p=bi.sourceOf(u,{x:t,y:i});if(Math.abs(p.x)>=1||Math.abs(p.y)>=1)continue;const f=Math.max(2,Math.round(u.blur*a/Math.abs(u.scale))),m=Math.min(1+p.x,1-p.x)/2*r/a,v=Math.min(1+p.y,1-p.y)/2,g=Math.max(2*u.blur*a/Math.abs(u.scale),2)/a,y=Ts.smoothstep(0,g,m)*Ts.smoothstep(0,g,v),w=o(p.x,p.y),b=this.window(e,w.x,w.y,f);if(!b)continue;const M=y*u.share*b.mean/(u.scale*u.scale),S=.18*M*s;S<Ts.VISIBLE_RESPONSE||M<.3*h.mean||(!d||S>d.score)&&(d={score:S,hit:{ghost:u,source:{x:b.brightest.x/r*2-1,y:b.brightest.y/a*2-1}}})}return d?.hit}holdsPictureAt(e,t,i){if(!this.readable)return!1;const n=this.window(e,Math.round((t+1)/2*this.mips.width),Math.round((i+1)/2*this.mips.height),4);return n!==void 0&&n.mean>0}dropAt(e,t,i){const n=Math.round((t+1)/2*this.ghostLayer.width),s=Math.round((i+1)/2*this.ghostLayer.height);if(n<0||s<0||n>=this.ghostLayer.width||s>=this.ghostLayer.height)return 0;const r=new Uint16Array(4);return e.readRenderTargetPixels(this.ghostLayer,n,s,1,1,r),Ts.half(r[3])}window(e,t,i,n){const s=Math.max(1,Math.ceil(n/24)),r={x:Math.max(0,t-n),y:Math.max(0,i-n)},a={x:Math.min(this.mips.width-1,t+n),y:Math.min(this.mips.height-1,i+n)};if(r.x>a.x||r.y>a.y)return;const o=a.x-r.x+1,c=a.y-r.y+1,h=new Uint16Array(o*c*4);e.readRenderTargetPixels(this.mips,r.x,r.y,o,c,h);let d=0,u=0,p=-1,f={x:t,y:i};for(let m=r.y;m<=a.y;m+=s){const v=(m-r.y)*o*4;for(let g=0;g<o;g+=s){const y=.2126*Ts.half(h[v+g*4])+.7152*Ts.half(h[v+g*4+1])+.0722*Ts.half(h[v+g*4+2]);d+=y,u++,y>p&&(p=y,f={x:r.x+g,y:m})}}return{mean:u>0?d/u:0,brightest:f}}draw(e,t,i){this.quad.material=t,e.setRenderTarget(i),e.render(this.quadScene,this.quadCamera)}static half(e){const t=e>>10&31,i=e&1023,n=e&32768?-1:1;return t===0?n*i*2**-24:t===31?0:n*(1+i/1024)*2**(t-15)}static smoothstep(e,t,i){const n=Math.max(0,Math.min(1,(i-e)/(t-e)));return n*n*(3-2*n)}resize(e,t){const i=Math.max(1,e),n=Math.max(1,t);(this.mips.width!==Math.ceil(i/2)||this.mips.height!==Math.ceil(n/2))&&(this.readable=!1),this.frame.scene.setSize(i,n),this.frame.overlay.setSize(i,n),this.mips.setSize(Math.ceil(i/2),Math.ceil(n/2)),this.ghostLayer.setSize(Math.ceil(i/2),Math.ceil(n/2))}dispose(){this.frame.scene.dispose(),this.frame.overlay.dispose(),this.mips.dispose(),this.ghostLayer.dispose(),this.copyMaterial.dispose(),this.ghostMaterial.dispose(),this.developMaterial.dispose(),this.quad.geometry.dispose(),this.quadScene.clear()}}class Us{static IDENTITY=[1,0,0,0,1,0,0,0,1];static NONE={colorMatrix:Us.IDENTITY,contrastGain:1};static combine(e,t){const[i,n,s,r,a,o,c,h,d]=e.colorMatrix,[u,p,f,m,v,g,y,w,b]=t.colorMatrix;return{colorMatrix:[u*i+p*r+f*c,u*n+p*a+f*h,u*s+p*o+f*d,m*i+v*r+g*c,m*n+v*a+g*h,m*s+v*o+g*d,y*i+w*r+b*c,y*n+w*a+b*h,y*s+w*o+b*d],contrastGain:e.contrastGain*t.contrastGain}}static isNone(e){return e.contrastGain===1&&e.colorMatrix.every((t,i)=>t===Us.IDENTITY[i])}}class jt{static MIN_RATIO=1;static STEP=.25;static MIN_SHARE_OF_DISPLAY=.75;static GPU_LATE_MS=12;static GPU_ROOM_MS=6;static INTERVAL_LATE_MS=21;static LOWER_COOLDOWN_MS=750;static RAISE_COOLDOWN_MS=2e3;static PROBE_WATCH_MS=2e3;static PROBE_EVERY_MS=6e3;static PROBE_BACKOFF_MS=3e4;ratio;maxRatio;timer;intervalMs;lastChangeMs=-1/0;nextProbeMs=0;probe;constructor(e,t){this.maxRatio=jt.clamp(e),this.ratio=this.maxRatio,this.timer=t?Pf.create(t):void 0}get pixelRatio(){return this.ratio}static SETTLE_MS=400;static SUSTAINED_MS=100;lastEditMs=-1/0;editStreakStartMs=-1/0;wasChanging=!1;noteChange(e){e-this.lastEditMs>jt.SETTLE_MS&&(this.editStreakStartMs=e),this.lastEditMs=e}changing(e){return e-this.lastEditMs<=jt.SETTLE_MS&&this.lastEditMs-this.editStreakStartMs>=jt.SUSTAINED_MS}ratioFor(e,t){return this.changing(e)?this.wasChanging?(this.update(e,t),this.ratio):(this.wasChanging=!0,this.reset(),this.ratio):(this.wasChanging=!1,this.maxRatio)}get timesGpu(){return this.timer!==void 0}set maximum(e){this.maxRatio=jt.clamp(e),this.ratio>this.maxRatio&&(this.ratio=this.maxRatio),this.ratio<this.minimum&&(this.ratio=Math.min(this.maxRatio,this.minimum))}get minimum(){const e=Math.floor(this.maxRatio*jt.MIN_SHARE_OF_DISPLAY/jt.STEP)*jt.STEP;return Math.max(jt.MIN_RATIO,e)}get maximum(){return this.maxRatio}beginDrawing(){this.timer?.begin()}endDrawing(){this.timer?.end()}reset(){this.intervalMs=void 0,this.probe=void 0,this.timer?.reset()}update(e,t){const i=this.timer?.poll();if(!(this.timer&&i===void 0))return i!==void 0?this.followGpu(e,i):this.followIntervals(e,t)}followGpu(e,t){if(t>jt.GPU_LATE_MS)return this.lower(e,jt.LOWER_COOLDOWN_MS);if(t<jt.GPU_ROOM_MS)return this.raise(e,jt.RAISE_COOLDOWN_MS)}followIntervals(e,t){if(!(t>0)||t>1e3)return;this.intervalMs=this.intervalMs===void 0?t:this.intervalMs*.9+t*.1;const i=this.intervalMs>jt.INTERVAL_LATE_MS;if(this.probe){if(i)return this.ratio=this.probe.ratioBefore,this.probe=void 0,this.lastChangeMs=e,this.nextProbeMs=e+jt.PROBE_BACKOFF_MS,this.ratio;e-this.probe.sinceMs>=jt.PROBE_WATCH_MS&&(this.probe=void 0,this.nextProbeMs=e+jt.PROBE_EVERY_MS);return}if(i){const n=this.lower(e,jt.LOWER_COOLDOWN_MS);return n!==void 0&&(this.nextProbeMs=e+jt.PROBE_EVERY_MS),n}if(this.ratio<this.maxRatio&&e>=this.nextProbeMs&&e-this.lastChangeMs>=jt.RAISE_COOLDOWN_MS){const n=this.ratio,s=this.raise(e,0);return s!==void 0&&(this.probe={sinceMs:e,ratioBefore:n}),s}}lower(e,t){if(!(this.ratio<=this.minimum||e-this.lastChangeMs<t))return this.ratio=Math.max(this.minimum,jt.clamp(this.ratio-jt.STEP)),this.lastChangeMs=e,this.ratio}raise(e,t){if(!(this.ratio>=this.maxRatio||e-this.lastChangeMs<t))return this.ratio=Math.min(this.maxRatio,jt.clamp(this.ratio+jt.STEP)),this.lastChangeMs=e,this.ratio}static clamp(e){return Number.isFinite(e)?Math.max(jt.MIN_RATIO,Math.round(e/jt.STEP)*jt.STEP):jt.MIN_RATIO}}class Pf{constructor(e,t){this.gl=e,this.extension=t}static IN_FLIGHT_MAX=8;static create(e){if(!(e instanceof WebGL2RenderingContext))return;const t=e.getExtension("EXT_disjoint_timer_query_webgl2");return t?new Pf(e,t):void 0}pending=[];active;smoothedMs;begin(){if(!(this.active||this.pending.length>=Pf.IN_FLIGHT_MAX))try{const e=this.gl.createQuery();if(!e)return;this.gl.beginQuery(this.extension.TIME_ELAPSED_EXT,e),this.active=e}catch{this.active=void 0}}end(){if(this.active){try{this.gl.endQuery(this.extension.TIME_ELAPSED_EXT),this.pending.push(this.active)}catch{}this.active=void 0}}poll(){const e=this.gl;try{for(let t=0;t<this.pending.length;t++){const i=this.pending[t];if(!e.getQueryParameter(i,e.QUERY_RESULT_AVAILABLE))continue;if(!e.getParameter(this.extension.GPU_DISJOINT_EXT)){const s=e.getQueryParameter(i,e.QUERY_RESULT)/1e6;this.smoothedMs=this.smoothedMs===void 0?s:this.smoothedMs*.8+s*.2}e.deleteQuery(i),this.pending.splice(t,1),t--}}catch{this.pending.length=0}return this.smoothedMs}reset(){this.smoothedMs=void 0}}class ut{static ICE_INDEX_RED=1.3067;static ICE_INDEX_BLUE=1.317;static SIDE_PRISM_ANGLE_DEG=60;static END_PRISM_ANGLE_DEG=90;static get PARHELIA_MAX_SUN_ALTITUDE_DEG(){const e=ut.ICE_INDEX_RED,t=Math.sqrt((4-e*e)/3);return Math.asin(Math.min(1,t))*180/Math.PI}static minimumDeviationDeg(e,t){const i=e*Math.PI/180,n=t*Math.sin(i/2);return n>1?Number.NaN:(2*Math.asin(n)-i)*180/Math.PI}static effectiveIndex(e,t){const i=t*Math.PI/180,n=Math.cos(i);return n<=0?Number.POSITIVE_INFINITY:Math.sqrt(e*e-Math.sin(i)**2)/n}static parheliaAzimuthDeg(e,t=ut.ICE_INDEX_RED){const i=ut.minimumDeviationDeg(ut.SIDE_PRISM_ANGLE_DEG,ut.effectiveIndex(t,e));return Number.isFinite(i)?i:void 0}static parheliaDistanceDeg(e,t=ut.ICE_INDEX_RED){const i=ut.parheliaAzimuthDeg(e,t);if(i===void 0)return;const n=e*Math.PI/180,s=Math.sin(n)**2,r=Math.cos(n)**2*Math.cos(i*Math.PI/180);return Math.acos(Math.max(-1,Math.min(1,s+r)))*180/Math.PI}static get PLATE_END_FACE_LIMIT_DEG(){const e=ut.ICE_INDEX_RED;return Math.asin(Math.min(1,Math.sqrt(e*e-1)))*180/Math.PI}static circumzenithalAltitudeDeg(e,t=ut.ICE_INDEX_RED){if(e<0||e>90-ut.PLATE_END_FACE_LIMIT_DEG)return;const i=Math.cos(e*Math.PI/180),n=Math.sqrt(t*t-i*i);if(!(n>=1))return Math.asin(n)*180/Math.PI}static DECK_HEIGHT_M=8e3;static deckLitUntilDeg(e){return Math.acos(6371e3/(6371e3+Math.max(0,e)))*180/Math.PI}static halo22(){return ut.ringOf("halo22",ut.SIDE_PRISM_ANGLE_DEG)}static halo46(){return ut.ringOf("halo46",ut.END_PRISM_ANGLE_DEG)}static ringOf(e,t){const i=ut.minimumDeviationDeg(t,ut.ICE_INDEX_RED),n=ut.minimumDeviationDeg(t,ut.ICE_INDEX_BLUE);return{id:e,angleDeg:(i+n)/2,redAngleDeg:i,blueAngleDeg:n}}static strength(e,t,i=90,n=0){const s=Math.max(0,Math.min(1,e)),r=Math.max(0,1-Math.max(0,Math.min(1,t))),a=i>=0?1:n<=0?0:Math.max(0,1+i/n);return s*r*a}static formsAt(e,t=0){if(e<=-t)return[];const i=[ut.halo22(),ut.halo46()],n=e>0?ut.parheliaDistanceDeg(e):void 0;n!==void 0&&i.push({id:"parhelia",angleDeg:n,redAngleDeg:n,blueAngleDeg:ut.parheliaDistanceDeg(e,ut.ICE_INDEX_BLUE)}),i.push({id:"tangentArc",angleDeg:ut.halo22().angleDeg}),e>0&&i.push({id:"parhelicCircle",angleDeg:e});const s=ut.circumzenithalAltitudeDeg(e);return s!==void 0&&i.push({id:"circumzenithal",angleDeg:s}),e>ut.PLATE_END_FACE_LIMIT_DEG&&i.push({id:"circumhorizontal"}),e<ut.PILLAR_MAX_SOURCE_ALTITUDE_DEG&&i.push({id:"pillar"}),i}static PILLAR_MAX_SOURCE_ALTITUDE_DEG=20}class jn{static get WATER_INDEX_RED(){return kn.indexAt(kn.RED_NM)}static get WATER_INDEX_BLUE(){return kn.indexAt(kn.BLUE_NM)}static radiusDeg(e,t){const i=(t*t-1)/(e*e-1);if(i<0||i>1)return Number.NaN;const n=Math.acos(Math.sqrt(i)),s=Math.asin(Math.sin(n)/t),r=2*(n-s)+(e-1)*(Math.PI-2*s),a=2*Math.PI;let o=r%a;return o<0&&(o+=a),o>Math.PI&&(o=a-o),180-o*180/Math.PI}static primary(){return jn.bowOf("primary",2,0)}static secondary(){return jn.bowOf("secondary",3,0)}static bowOf(e,t,i){const n=jn.radiusDeg(t,jn.WATER_INDEX_RED),s=jn.radiusDeg(t,jn.WATER_INDEX_BLUE),r=(n+s)/2;return{id:e,radiusDeg:r,redRadiusDeg:n,violetRadiusDeg:s,topAltitudeDeg:r-i}}static alexandersBandDeg(){return{fromDeg:jn.primary().redRadiusDeg,toDeg:jn.secondary().redRadiusDeg}}static formsAt(e){return e<0?[]:[jn.bowOf("primary",2,e),jn.bowOf("secondary",3,e)].filter(t=>t.topAltitudeDeg>0)}static FULL_MOON_MAGNITUDE=-12.7;static moonlightShare(e){return Math.min(1,10**(-.4*(e-jn.FULL_MOON_MAGNITUDE)))}static strength(e,t,i){if(i<=0)return 0;const n=Math.max(0,Math.min(1,e)),s=Math.max(0,1-Math.max(0,Math.min(1,t)));return n*s}}class Vs{constructor(e){this.radius=e;const t=Vs.SEGMENTS*Vs.VERTICES_PER_SEGMENT;this.positions=new Float32Array(t*3),this.colors=new Float32Array(t*3);const i=new ct;i.setAttribute("position",new mt(this.positions,3)),i.setAttribute("color",new mt(this.colors,3)),i.setDrawRange(0,0),this.object=new xe(i,Ps.material()),this.object.frustumCulled=!1,Ps.track(this.object)}static POINTS=24;static SEGMENTS=Vs.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(Vs.ACROSS-1)*6;static HEAD_HALF_WIDTH_DEG=.15;static SPREAD_FRACTION=.05;static FADE_POWER=1.8;object;positions;colors;head;tip;brightness=0;set(e,t,i){this.head=e&&oi(e.altitudeDeg,e.azimuthDeg,1),this.tip=t&&oi(t.altitudeDeg,t.azimuthDeg,1),this.brightness=i,this.rebuild()}rebuild(){const e=this.object.geometry,t=this.head,i=this.tip;if(!t||!i||this.brightness<=0){e.setDrawRange(0,0);return}const n=this.angleBetween(t,i);if(n<=0){e.setDrawRange(0,0);return}const s=n*Vs.SPREAD_FRACTION*Math.PI/180,r=h=>this.scale(this.slerp(t,i,h),this.radius),a=h=>this.radius*(Vs.HEAD_HALF_WIDTH_DEG*Math.PI/180+s*h),o=h=>this.brightness*(1-h)**Vs.FADE_POWER;let c=0;for(let h=1;h<Vs.POINTS;h++){const d=(h-1)/Vs.SEGMENTS,u=h/Vs.SEGMENTS;c=this.pushBand(c,r(d),r(u),a(d),a(u),o(d),o(u))}e.setDrawRange(0,c),e.getAttribute("position").needsUpdate=!0,e.getAttribute("color").needsUpdate=!0}pushBand(e,t,i,n,s,r,a){const o=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let c=0;c<Vs.ACROSS-1;c++){const h=c-1,d=c,u=this.across(t,o,n,h),p=this.across(i,o,s,h),f=this.across(t,o,n,d),m=this.across(i,o,s,d),v=(g,y)=>g===0?y:0;e=this.push(e,u,v(h,r)),e=this.push(e,p,v(h,a)),e=this.push(e,f,v(d,r)),e=this.push(e,p,v(h,a)),e=this.push(e,m,v(d,a)),e=this.push(e,f,v(d,r))}return e}across(e,t,i,n){return{x:e.x+t.x*i*n,y:e.y+t.y*i*n,z:e.z+t.z*i*n}}push(e,t,i){const n=e*3;this.positions[n]=t.x,this.positions[n+1]=t.y,this.positions[n+2]=t.z;const s=Fe.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.55,this.colors[n+1]=s*.75,this.colors[n+2]=s,e+1}slerp(e,t,i){const n=this.angleBetweenRadians(e,t);if(n<1e-9)return e;const s=Math.sin(n),r=Math.sin((1-i)*n)/s,a=Math.sin(i*n)/s;return{x:e.x*r+t.x*a,y:e.y*r+t.y*a,z:e.z*r+t.z*a}}angleBetween(e,t){return this.angleBetweenRadians(e,t)*180/Math.PI}angleBetweenRadians(e,t){const i=e.x*t.x+e.y*t.y+e.z*t.z;return Math.acos(Math.min(1,Math.max(-1,i)))}scale(e,t){return{x:e.x*t,y:e.y*t,z:e.z*t}}subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class KL{object=new zt;radius;tiers;drawn=[];constructor(e){this.radius=e,this.object.name="satellites",this.tiers=Dl.map(t=>{const i=new Cs(new ct,Ne.material(t.size));return Ne.track(i),i.frustumCulled=!1,this.object.add(i),i})}set(e,t,i,n){const s=this.tiers.map(()=>[]);this.drawn=[];for(const r of e){if(r.magnitude>t)continue;const a=i(r.position);if(a<=0)continue;const o=r.magnitude-2.5*Math.log10(a);if(o>t)continue;const c=Ml(o,t),h=vm(c),{x:d,y:u,z:p}=oi(r.position.altitudeDeg,r.position.azimuthDeg,this.radius),[f,m,v]=n(r.position,o);s[h].push({x:d,y:u,z:p,r:f,g:m,b:v,seed:r.norad*.6180339887%1}),this.drawn.push({satellite:r,direction:new _(d,u,p).normalize()})}this.tiers.forEach((r,a)=>{const o=s[a],c=new Float32Array(o.length*3),h=new Float32Array(o.length*3),d=new Float32Array(o.length);o.forEach((p,f)=>{c.set([p.x,p.y,p.z],f*3),h.set([p.r,p.g,p.b],f*3),d[f]=p.seed}),r.geometry.dispose();const u=new ct;u.setAttribute("position",new mt(c,3)),u.setAttribute("color",new mt(h,3)),u.setAttribute("seed",new mt(d,1)),r.geometry=u})}get count(){return this.drawn.length}nearest(e,t){let i,n=t;for(const s of this.drawn){const r=s.direction.dot(e);r>n&&(n=r,i=s.satellite)}return i}dispose(){for(const e of this.tiers)e.geometry.dispose(),e.material.dispose();this.object.removeFromParent(),this.drawn=[]}}class $s{static MU=398600.4418;static OMEGA=72921159e-12;static EARTH_RADIUS_KM=6371;static STEP_S=1;static DENSITY=[[0,1.225],[20,.0889],[40,.004],[60,31e-5],[80,185e-7],[100,56e-8],[120,222e-10],[150,208e-11],[200,254e-12],[250,607e-13],[300,192e-13],[400,28e-13],[500,522e-15],[600,114e-15],[700,307e-16],[800,114e-16],[900,576e-17],[1e3,356e-17]];static FREE_PATH_TIMES_DENSITY=68e-9;static ICE_DENSITY=917;static airDensity(e){const t=$s.DENSITY;if(e<=t[0][0])return t[0][1];let i=0;for(;i<t.length-2&&t[i+1][0]<e;)i++;const[n,s]=t[i],[r,a]=t[i+1];return s*Math.exp(Math.log(a/s)*(e-n)/(r-n))}static dragPerKm(e,t,i,n=.5){const s=$s.airDensity(e),r=$s.FREE_PATH_TIMES_DENSITY/s/1e3,a=Math.exp(-r/t),o=s*1e9*Math.PI*t*t/Math.max(i,1e-9),c=3*s/(4*n*1e-6*$s.ICE_DENSITY)*1e3;return a*o+(1-a)*c}static step(e,t,i,n,s){const[r,a,o,c,h,d]=e,u=Math.hypot(r,a,o),p=$s.OMEGA,f=-398600.4418/(u*u*u),m=f*r+2*p*h+p*p*r,v=f*a-2*p*c+p*p*a,g=f*o,y=Math.hypot(c,h,d),b=1/(1+$s.dragPerKm(u-$s.EARTH_RADIUS_KM,i,n,s)*y*t);e[3]=(c+m*t)*b,e[4]=(h+v*t)*b,e[5]=(d+g*t)*b,e[0]=r+e[3]*t,e[1]=a+e[4]*t,e[2]=o+e[5]*t;const M=Math.hypot(e[0],e[1],e[2]);if(M<$s.EARTH_RADIUS_KM){const S=$s.EARTH_RADIUS_KM/M;e[0]*=S,e[1]*=S,e[2]*=S,e[3]=e[4]=e[5]=0}}}class XL{constructor(e,t,i,n,s=.5){this.massKg=i,this.radiusAt=n,this.particleRadiusUm=s,this.state=Float64Array.of(...e,...t),this.positions=new Float64Array(192),this.positions.set(e,0)}positions;steps=0;state;at(e){const t=$s.STEP_S,i=Math.max(0,e/t),n=Math.ceil(i);for(;this.steps<n;){if($s.step(this.state,t,this.radiusAt(this.steps*t),this.massKg,this.particleRadiusUm),this.steps++,3*(this.steps+1)>this.positions.length){const o=new Float64Array(this.positions.length*2);o.set(this.positions),this.positions=o}this.positions.set(this.state.subarray(0,3),3*this.steps)}const s=Math.floor(i),r=i-s,a=this.positions;return r===0||s>=this.steps?[a[3*s],a[3*s+1],a[3*s+2]]:[0,1,2].map(o=>a[3*s+o]+(a[3*s+3+o]-a[3*s+o])*r)}}class Le{static EARTH_RADIUS_KM=6371;static SHADOW_RADIUS_KM=Le.EARTH_RADIUS_KM+15;static PENUMBRA_KM=10;static SUN_ILLUMINANCE_LUX=127e3;static RAYLEIGH_PER_M=[58e-7,135e-7,331e-7];static SCALE_HEIGHT_M=8e3;static OZONE_GRAZING_DEPTH=[2.4,1.8,.24];static ANISOTROPY=.7;static ALBEDO=.99;static WAVELENGTHS_UM=[.61,.55,.465];static ICE_INDEX=1.31;static DEFAULTS={exhaustKgPerS:273,condensedShare:.065,particleRadiusUm:.5,expansionKmPerS:.15,initialRadiusKm:.5,lifetimeS:420,collarShare:.85,collarExpansionKmPerS:2.5,collarLifetimeS:20};static PROPELLANTS={"rp1-lox":{condensedShare:.065,particleRadiusUm:.5},"methane-lox":{condensedShare:.09,particleRadiusUm:.5},"hydrogen-lox":{condensedShare:.13,particleRadiusUm:.5},hypergolic:{condensedShare:.079,particleRadiusUm:.4},solid:{condensedShare:.27,particleRadiusUm:.8}};static G0=9.80665;static COLLAR_SPREAD_OF_EXHAUST_VELOCITY=.735;static plumeOf(e){const t={},i=e.vehicle?.engine;if(i){const n=i.specificImpulseS===void 0?void 0:i.specificImpulseS*Le.G0;i.thrustKN!==void 0&&n&&(t.exhaustKgPerS=i.thrustKN*1e3/n),n&&(t.collarExpansionKmPerS=n/1e3*Le.COLLAR_SPREAD_OF_EXHAUST_VELOCITY),i.propellant&&Object.assign(t,Le.PROPELLANTS[i.propellant])}return{...Le.DEFAULTS,...t,...e.plume}}static PUFF_EVERY_S=.5;static SIGMA_OF_RADIUS=.5;static MAX_PUFFS=320;static DEG=Math.PI/180;static EARTH_ROTATION=72921159e-12;static VENT_DEFAULTS={speedKmPerS:.7,massKgPerS:20,condensedShare:.5,particleRadiusUm:.5,expansionKmPerS:.1,initialRadiusKm:.2,lifetimeS:600};static paths=new WeakMap;static exhaustVelocityKmPerS(e){return(e.vehicle?.engine?.specificImpulseS??348)*Le.G0/1e3}static releasesOf(e){const t=[],i=e.jets??[];if(i.length===0||e.burnFromT!==void 0||e.burnUntilT!==void 0){const n=e.track[0]?.t??0,s=e.track[e.track.length-1]?.t??0;t.push(Le.engineRelease(e,"burn",{fromT:e.burnFromT??n,untilT:e.burnUntilT??s}))}return i.forEach((n,s)=>t.push(Le.releaseOf(e,n,s))),t}static releaseOf(e,t,i){const n=`jet:${t.id??i}`;if((t.kind??"burn")==="burn")return Le.engineRelease(e,n,t);const s=Le.VENT_DEFAULTS;return{key:n,fromT:t.fromT,untilT:t.untilT,angleDeg:t.angleDeg??0,azimuthDeg:t.azimuthDeg??0,spinPeriodS:t.spinPeriodS,speedKmPerS:t.speedKmPerS??s.speedKmPerS,massKgPerS:t.massKgPerS??s.massKgPerS,condensedShare:t.condensedShare??s.condensedShare,particleRadiusUm:t.particleRadiusUm??s.particleRadiusUm,initialRadiusKm:t.initialRadiusKm??s.initialRadiusKm,populations:[{share:1,expansionKmPerS:t.expansionKmPerS??s.expansionKmPerS,lifetimeS:t.lifetimeS??s.lifetimeS}]}}static engineRelease(e,t,i){const n=Le.plumeOf(e);return{key:t,fromT:i.fromT,untilT:i.untilT,angleDeg:i.angleDeg??0,azimuthDeg:i.azimuthDeg??0,spinPeriodS:i.spinPeriodS,speedKmPerS:i.speedKmPerS??Le.exhaustVelocityKmPerS(e),massKgPerS:i.massKgPerS??n.exhaustKgPerS,condensedShare:i.condensedShare??n.condensedShare,particleRadiusUm:i.particleRadiusUm??n.particleRadiusUm,initialRadiusKm:i.initialRadiusKm??n.initialRadiusKm,populations:[{share:1-n.collarShare,expansionKmPerS:i.expansionKmPerS??n.expansionKmPerS,lifetimeS:i.lifetimeS??n.lifetimeS},{share:n.collarShare,expansionKmPerS:n.collarExpansionKmPerS,lifetimeS:n.collarLifetimeS}]}}static extinctionEfficiency(e,t){const i=2*Math.PI*e/t,n=Le.ICE_INDEX**2,s=8/3*i**4*((n-1)/(n+2))**2,r=2*i*(Le.ICE_INDEX-1),a=r<.001?r*r/2:2-4/r*Math.sin(r)+4/(r*r)*(1-Math.cos(r));return Math.min(s,a)}static scatteringColour(e){const t=Le.extinctionEfficiency(e,Le.WAVELENGTHS_UM[1]);return Le.WAVELENGTHS_UM.map(i=>Le.extinctionEfficiency(e,i)/t)}static sunDirectionAt(e){const t=new Fa(0,0,-6378137),i=ch(pe.Sun,e,t,!0,!0),n=(i.ra-zx(e))*15*Le.DEG,s=i.dec*Le.DEG;return[Math.cos(s)*Math.cos(n),Math.cos(s)*Math.sin(n),Math.sin(s)]}static puffsAt(e,t){const i=[];for(const n of e){let s=Le.paths.get(n);s||Le.paths.set(n,s=new Map);for(const r of Le.releasesOf(n)){const a=Math.min(r.untilT,t);if(a<=r.fromT)continue;const o=Math.max(Le.PUFF_EVERY_S*1e3,(r.untilT-r.fromT)/Le.MAX_PUFFS),c=[];for(let f=r.fromT;f<a;f+=o)c.push(f);c.push(a);const h=r.massKgPerS*(o/1e3),u=3*Le.extinctionEfficiency(r.particleRadiusUm,Le.WAVELENGTHS_UM[1])/(4*917*r.particleRadiusUm*1e-6),p=Le.scatteringColour(r.particleRadiusUm);r.populations.forEach((f,m)=>{if(f.share<=0)return;const v=y=>r.initialRadiusKm+f.expansionKmPerS*y,g=[];for(const y of c){const w=(t-y)/1e3;if(w>f.lifetimeS)continue;const b=y!==a||a===r.untilT,M=`${r.key}|${m}|${y}`;let S=b?s.get(M):void 0;if(!S){if(S=Le.launchPuff(n,r,y,h*f.share,v),!S)continue;b&&s.set(M,S)}g.push({ageS:w,position:S.at(w)})}for(let y=g.length-1;y>=0;y--){const{ageS:w,position:b}=g[y],M=g[y-1]??g[y+1],S=M?Math.hypot(b[0]-M.position[0],b[1]-M.position[1],b[2]-M.position[2]):0,E=v(w)+S/2,x=Le.SIGMA_OF_RADIUS*E*1e3,T=h*r.condensedShare*f.share*u/(2*Math.PI*x*x),D=Math.max(0,1-(w/f.lifetimeS)**2);T*D<=0||i.push({launchId:n.id,release:r.key,at:Le.geoPoint(b),radiusKm:E,opticalDepth:T*D,colour:p,ageS:w})}})}}return i}static viewsAt(e,t,i,n){const s=[];for(const r of Le.puffsAt(e,t)){const a=_t.seenFrom(i,r.at);if(a.altitudeDeg<0)continue;const o=Le.sunlightAt(r.at,n);if(o.lit<=0)continue;const c=Le.scatteringPhase(i,r.at,n),h=Le.SUN_ILLUMINANCE_LUX*Le.ALBEDO*c*r.opticalDepth*o.lit;h<=0||s.push({launchId:r.launchId,release:r.release,heightKm:r.at.heightM/1e3,centre:a,radiusDeg:Math.atan2(r.radiusKm,a.distanceKm)/Le.DEG,luminanceCdM2:h,sunTransmittance:o.transmittance,colour:r.colour,lit:o.lit,ageS:r.ageS})}return s}static launchPuff(e,t,i,n,s){const r={id:e.id,track:e.track,fragments:[]},a=_t.leadAt(r,i);if(!a)return;const o=e.track[0].t,c=e.track[e.track.length-1].t,h=Math.max(o,i-500),d=Math.min(c,i+500),u=Le.earthCentred(a),p=Le.earthCentred(_t.leadAt(r,h)),f=Le.earthCentred(_t.leadAt(r,d)),m=Math.max(.001,(d-h)/1e3),v=[0,1,2].map(C=>(f[C]-p[C])/m),g=Le.EARTH_ROTATION,y=[v[0]-g*u[1],v[1]+g*u[0],v[2]],w=C=>{const k=Math.hypot(C[0],C[1],C[2])||1;return C.map(P=>P/k)},b=w(y),M=w(u),S=M[0]*b[0]+M[1]*b[1]+M[2]*b[2];let E=[M[0]-S*b[0],M[1]-S*b[1],M[2]-S*b[2]];Math.hypot(E[0],E[1],E[2])<1e-6&&(E=[-b[2]*b[0],-b[2]*b[1],1-b[2]*b[2]]),E=w(E);const x=[b[1]*E[2]-b[2]*E[1],b[2]*E[0]-b[0]*E[2],b[0]*E[1]-b[1]*E[0]],T=t.spinPeriodS?360*((i-t.fromT)/1e3)/t.spinPeriodS:0,D=(t.azimuthDeg+T)*Le.DEG,R=t.angleDeg*Le.DEG,O=[0,1,2].map(C=>-b[C]*Math.cos(R)+Math.sin(R)*(Math.cos(D)*E[C]+Math.sin(D)*x[C])),N=[0,1,2].map(C=>v[C]+t.speedKmPerS*O[C]);return new XL(u,N,n,s,t.particleRadiusUm)}static geoPoint(e){const t=Math.hypot(e[0],e[1],e[2]);return{lat:Math.asin(e[2]/t)/Le.DEG,lng:Math.atan2(e[1],e[0])/Le.DEG,heightM:(t-$s.EARTH_RADIUS_KM)*1e3}}static sunlightAt(e,t){const i=Le.earthCentred(e),n=i[0]*t[0]+i[1]*t[1]+i[2]*t[2];if(n>=0)return{lit:1,transmittance:[1,1,1]};const s=Math.hypot(i[0]-n*t[0],i[1]-n*t[1],i[2]-n*t[2]),r=Le.PENUMBRA_KM,a=Math.min(1,Math.max(0,(s-(Le.SHADOW_RADIUS_KM-r/2))/r));if(a<=0)return{lit:0,transmittance:[0,0,0]};const o=Math.max(0,(s-Le.EARTH_RADIUS_KM)*1e3),c=Math.exp(-o/Le.SCALE_HEIGHT_M),h=Math.sqrt(2*Math.PI*Le.EARTH_RADIUS_KM*1e3*Le.SCALE_HEIGHT_M),d=Math.exp(-(((o/1e3-25)/15)**2)),u=[0,1,2].map(p=>Math.exp(-Le.RAYLEIGH_PER_M[p]*c*h-Le.OZONE_GRAZING_DEPTH[p]*d));return{lit:a,transmittance:u}}static scatteringPhase(e,t,i){const n=Le.earthCentred(e),s=Le.earthCentred(t),r=[n[0]-s[0],n[1]-s[1],n[2]-s[2]],a=Math.hypot(r[0],r[1],r[2])||1,o=-(r[0]*i[0]+r[1]*i[1]+r[2]*i[2])/a,c=Le.ANISOTROPY;return(1-c*c)/(4*Math.PI*(1+c*c-2*c*o)**1.5)}static earthCentred(e){const t=e.lat*Le.DEG,i=e.lng*Le.DEG,n=Le.EARTH_RADIUS_KM+e.heightM/1e3;return[n*Math.cos(t)*Math.cos(i),n*Math.cos(t)*Math.sin(i),n*Math.sin(t)]}}class gi{static RADIUS=840;static MAX_PUFFS=1e3;static RINGS=[0,.25,.5,.75,1,1.25];static COLUMN=gi.RINGS.map(e=>{const t=n=>Math.exp(-((n/Le.SIGMA_OF_RADIUS)**2)/2),i=t(gi.RINGS[gi.RINGS.length-1]);return Math.max(0,(t(e)-i)/(1-i))});static SECTORS=12;static VERTICES_PER_PUFF=gi.SECTORS*(3+6*(gi.RINGS.length-2));static BRIGHTEST_RELATIVE=6e4;object=new zt;mesh;positions=new Float32Array(gi.MAX_PUFFS*gi.VERTICES_PER_PUFF*3);colors=new Float32Array(gi.MAX_PUFFS*gi.VERTICES_PER_PUFF*3);shown=0;drawn=[];static VISIBLE_CONTRAST=.1;constructor(){this.object.name="plumes";const e=new ct;e.setAttribute("position",new mt(this.positions,3)),e.setAttribute("color",new mt(this.colors,3)),e.setDrawRange(0,0),this.mesh=new xe(e,Ps.material()),this.mesh.frustumCulled=!1,Ps.track(this.mesh),this.object.add(this.mesh)}get count(){return this.shown}set(e,t,i,n){let s=0,r=0;this.drawn=[];for(const o of e){if(r>=gi.MAX_PUFFS)break;const c=n(o.centre);if(c<=0)continue;const h=i(o.centre),d=[0,1,2].map(u=>Math.min(gi.BRIGHTEST_RELATIVE,o.luminanceCdM2*(o.colour?.[u]??1)*t*o.sunTransmittance[u]*h[u]*c));Math.max(...d)<=0||(s=this.pushPuff(s,o,d),this.drawn.push({view:o,direction:this.normalise(oi(o.centre.altitudeDeg,o.centre.azimuthDeg,1)),radiusRad:o.radiusDeg*Math.PI/180,luminance:.2126*d[0]+.7152*d[1]+.0722*d[2]}),r++)}this.shown=r;const a=this.mesh.geometry;a.setDrawRange(0,s),a.getAttribute("position").needsUpdate=!0,a.getAttribute("color").needsUpdate=!0}pushPuff(e,t,i){const n=oi(t.centre.altitudeDeg,t.centre.azimuthDeg,gi.RADIUS),s=this.normalise(n),r=this.normalise(this.cross({x:0,y:1,z:0},s)),a=this.cross(s,r),o=gi.RADIUS*Math.tan(t.radiusDeg*Math.PI/180),c=(d,u)=>{const p=u/gi.SECTORS*2*Math.PI,f=gi.RINGS[d]*o,m=Math.cos(p)*f,v=Math.sin(p)*f;return{x:n.x+r.x*m+a.x*v,y:n.y+r.y*m+a.y*v,z:n.z+r.z*m+a.z*v}},h=d=>gi.COLUMN[d];for(let d=0;d<gi.SECTORS;d++){const u=(d+1)%gi.SECTORS;e=this.push(e,n,i,h(0)),e=this.push(e,c(1,d),i,h(1)),e=this.push(e,c(1,u),i,h(1));for(let p=1;p<gi.RINGS.length-1;p++){const f=c(p,d),m=c(p,u),v=c(p+1,d),g=c(p+1,u);e=this.push(e,f,i,h(p)),e=this.push(e,m,i,h(p)),e=this.push(e,v,i,h(p+1)),e=this.push(e,m,i,h(p)),e=this.push(e,g,i,h(p+1)),e=this.push(e,v,i,h(p+1))}}return e}pickAt(e,t,i=0){const n=this.normalise(e);let s=0,r;for(const a of this.drawn){const o=Math.max(-1,Math.min(1,n.x*a.direction.x+n.y*a.direction.y+n.z*a.direction.z)),c=Math.max(0,Math.acos(o)-t)/Math.max(a.radiusRad,1e-9),h=a.luminance*gi.profile(c);h<=0||(s+=h,(!r||h>r.light)&&(r={view:a.view,light:h}))}return r&&s>=gi.VISIBLE_CONTRAST*i?r.view:void 0}static profile(e){const t=gi.RINGS;if(e>=t[t.length-1])return 0;let i=0;for(;e>t[i+1];)i++;const n=(e-t[i])/(t[i+1]-t[i]);return gi.COLUMN[i]+(gi.COLUMN[i+1]-gi.COLUMN[i])*n}push(e,t,i,n){const s=e*3;return this.positions[s]=t.x,this.positions[s+1]=t.y,this.positions[s+2]=t.z,this.colors[s]=i[0]*n,this.colors[s+1]=i[1]*n,this.colors[s+2]=i[2]*n,e+1}cross(e,t){return this.normalise({x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x})}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose(),this.object.removeFromParent()}}class Is{static RADIUS=840;static MAX_SEGMENTS=256;static VERTICES_PER_SEGMENT=12;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;static TRAIN_SHARE=.6;object=new zt;tiers;trains;positions;colors;shown=0;constructor(){this.object.name="reentries",this.tiers=Dl.map(i=>{const n=new Cs(new ct,Ne.material(i.size,!1));return Ne.track(n),n.frustumCulled=!1,this.object.add(n),n});const e=Is.MAX_SEGMENTS*Is.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new ct;t.setAttribute("position",new mt(this.positions,3)),t.setAttribute("color",new mt(this.colors,3)),t.setDrawRange(0,0),this.trains=new xe(t,Ps.material()),this.trains.frustumCulled=!1,Ps.track(this.trains),this.object.add(this.trains)}get count(){return this.shown}set(e,t,i,n){const s=this.tiers.map(()=>[]);let r=0,a=0;const o=new re;for(const h of e){const d=i(h.head);if(d<=0)continue;const u=h.magnitude-2.5*Math.log10(d);if(u>t)continue;a++,o.set(h.color);const p=Ml(u,t),{x:f,y:m,z:v}=oi(h.head.altitudeDeg,h.head.azimuthDeg,Is.RADIUS),[g,y,w]=n(h.head,u),b=Math.max(o.r,o.g,o.b)||1;s[vm(p)].push({x:f,y:m,z:v,r:g*o.r/b,g:y*o.g/b,b:w*o.b/b}),r=this.pushTrain(r,h.train,p,o)}this.shown=a,this.tiers.forEach((h,d)=>{const u=s[d],p=new Float32Array(u.length*3),f=new Float32Array(u.length*3);u.forEach((v,g)=>{p.set([v.x,v.y,v.z],g*3),f.set([v.r,v.g,v.b],g*3)}),h.geometry.dispose();const m=new ct;m.setAttribute("position",new mt(p,3)),m.setAttribute("color",new mt(f,3)),h.geometry=m});const c=this.trains.geometry;c.setDrawRange(0,r),c.getAttribute("position").needsUpdate=!0,c.getAttribute("color").needsUpdate=!0}pushTrain(e,t,i,n){const s=t.length-1;for(let r=0;r<s;r++){if(e+Is.VERTICES_PER_SEGMENT>Is.MAX_SEGMENTS*Is.VERTICES_PER_SEGMENT)return e;const a=1-r/s,o=1-(r+1)/s,c=oi(t[r].altitudeDeg,t[r].azimuthDeg,Is.RADIUS),h=oi(t[r+1].altitudeDeg,t[r+1].azimuthDeg,Is.RADIUS),d=p=>Is.RADIUS*((Is.MIN_HALF_WIDTH_DEG+Is.BRIGHT_HALF_WIDTH_DEG*i*p)*Math.PI/180),u=p=>Is.TRAIN_SHARE*i*p**1.6;e=this.pushRibbon(e,c,h,d(a),d(o),u(a),u(o),n)}return e}pushRibbon(e,t,i,n,s,r,a,o){const c={x:i.x-t.x,y:i.y-t.y,z:i.z-t.z};if(Math.hypot(c.x,c.y,c.z)<1e-9)return e;const h=this.normalise(this.cross(this.normalise(t),this.normalise(c)));for(const[d,u]of[[-1,0],[0,1]]){const p=this.across(t,h,n,d),f=this.across(i,h,s,d),m=this.across(t,h,n,u),v=this.across(i,h,s,u),g=(y,w)=>y===0?w:0;e=this.push(e,p,g(d,r),o),e=this.push(e,f,g(d,a),o),e=this.push(e,m,g(u,r),o),e=this.push(e,f,g(d,a),o),e=this.push(e,v,g(u,a),o),e=this.push(e,m,g(u,r),o)}return e}across(e,t,i,n){return{x:e.x+t.x*i*n,y:e.y+t.y*i*n,z:e.z+t.z*i*n}}push(e,t,i,n){const s=e*3;this.positions[s]=t.x,this.positions[s+1]=t.y,this.positions[s+2]=t.z;const r=Fe.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[s]=r*n.r,this.colors[s+1]=r*n.g,this.colors[s+2]=r*n.b,e+1}cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){for(const e of this.tiers)e.geometry.dispose(),e.material.dispose();this.trains.geometry.dispose(),this.trains.material.dispose(),this.object.removeFromParent()}}class bm{constructor(e){this.state=e}next(){this.state=this.state+1831565813|0;let e=this.state;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}between(e,t){return e+this.next()*(t-e)}}class Ir{static MIN_DURATION_MS=250;static MAX_DURATION_MS=1400;static schedule(e){const{ratePerHour:t,durationMs:i,velocityKmS:n,seed:s}=e;if(t<=0||i<=0)return[];const r=t*i/36e5,a=new bm(s),o=Math.floor(r),c=o+(a.next()<r-o?1:0),h=[];for(let d=0;d<c;d++){const u=Math.min(1,Math.max(0,(n-20)/52)),p=Ir.MAX_DURATION_MS-u*(Ir.MAX_DURATION_MS-Ir.MIN_DURATION_MS),f=a.between(5,70);h.push({t:a.between(0,i),durationMs:p*a.between(.7,1.3),fromRadiantDeg:f,bearingDeg:a.between(0,360),lengthDeg:Math.sin(f*Math.PI/180)*a.between(8,40)*(.6+u),brightness:a.next()**3}),h.sort((m,v)=>m.t-v.t)}return h}static FAINTEST_MAGNITUDE=6.5;static BRIGHTEST_MAGNITUDE=-4;static magnitudeOf(e){return Ir.FAINTEST_MAGNITUDE-(Ir.FAINTEST_MAGNITUDE-Ir.BRIGHTEST_MAGNITUDE)*e.brightness}static aliveAt(e,t){return e.filter(i=>t>=i.t&&t<=i.t+i.durationMs).map(i=>({meteor:i,progress:(t-i.t)/i.durationMs}))}}class uo{object=new zt;radius;core;glow;flashKey;static CORE_WIDTH_DEG=.06;static GLOW_WIDTH_DEG=.5;static SEGMENTS=28;static CORE_RELATIVE=1e3;constructor(e){this.radius=e,this.object.name="lightning-bolt",this.core=new Fs({color:15659775,transparent:!0,opacity:0,blending:An,depthWrite:!1,fog:!1}),this.glow=new Fs({color:10466559,transparent:!0,opacity:0,blending:An,depthWrite:!1,fog:!1}),this.object.visible=!1,this.object.renderOrder=5.95}set(e,t,i){if(!e||!e.cloudToGround||t<=.01){this.object.visible=!1;return}const n=`${e.channelSeed}:${Math.round(i)}`;n!==this.flashKey&&this.build(e,i,n),this.core.color.setHex(15659775).multiplyScalar(uo.CORE_RELATIVE*Math.min(1,t*1.4)),this.glow.color.setHex(10466559).multiplyScalar(.1*uo.CORE_RELATIVE*t*.35),this.core.opacity=1,this.glow.opacity=1,this.object.visible=!0}build(e,t,i){this.flashKey=i;for(const c of[...this.object.children])c.geometry.dispose(),this.object.remove(c);const n=new bm(e.channelSeed),s=Math.atan2(t,e.distanceM)*180/Math.PI,r=this.channel(n,e.azimuthDeg,s,0,1),a=[r],o=1+Math.floor(n.next()*2);for(let c=0;c<o;c++){const h=r[Math.floor(n.between(.15,.5)*r.length)];a.push(this.channel(n,h.azimuthDeg,h.altitudeDeg,h.altitudeDeg*n.between(.3,.7),.5))}for(const c of a)this.object.add(new xe(this.ribbon(c,uo.GLOW_WIDTH_DEG),this.glow)),this.object.add(new xe(this.ribbon(c,uo.CORE_WIDTH_DEG),this.core))}channel(e,t,i,n,s){const r=[],a=i-n;let o=t;for(let c=0;c<=uo.SEGMENTS;c++){const h=i-a*c/uo.SEGMENTS;r.push({azimuthDeg:o,altitudeDeg:h}),o+=e.between(-1,1)*a*.06*s}return r}ribbon(e,t){const i=new Float32Array(e.length*2*3),n=[],s=this.radius*Math.tan(t*Math.PI/180)/2,r=e.map(o=>{const{x:c,y:h,z:d}=oi(o.altitudeDeg,o.azimuthDeg,this.radius);return new _(c,h,d)});r.forEach((o,c)=>{const h=r[Math.min(c+1,r.length-1)],d=r[Math.max(c-1,0)],p=h.clone().sub(d).normalize().cross(o.clone().normalize()).normalize().multiplyScalar(s);if(i.set([o.x+p.x,o.y+p.y,o.z+p.z],c*6),i.set([o.x-p.x,o.y-p.y,o.z-p.z],c*6+3),c<r.length-1){const f=c*2;n.push(f,f+1,f+2,f+1,f+3,f+2)}});const a=new ct;return a.setAttribute("position",new mt(i,3)),a.setIndex(n),a}dispose(){for(const e of this.object.children)e.geometry.dispose();this.core.dispose(),this.glow.dispose(),this.object.removeFromParent()}}class xn{static MIN_INTERVAL_S=8;static MAX_INTERVAL_S=25;static SEVERE_MIN_INTERVAL_S=2;static SEVERE_MAX_INTERVAL_S=8;static CLOUD_TO_GROUND_FRACTION=.25;static MIN_DISTANCE_M=1e3;static MAX_DISTANCE_M=15e3;static INTERSTROKE_MS=60;static STROKE_DECAY_MS=40;static SOUND_SPEED_M_S=343;static schedule(e){const t=new bm(e.seed),i=[],{minS:n,maxS:s}=xn.intervalFor(e.intensity??.5);let r=t.between(0,s)*1e3;for(;r<e.durationMs;){const a=t.next()<xn.CLOUD_TO_GROUND_FRACTION,o=xn.MIN_DISTANCE_M,c=xn.MAX_DISTANCE_M,h=Math.sqrt(t.between(o*o,c*c)),d=a?1+Math.floor(t.next()*4):1,u=[];let p=0;for(let f=0;f<d;f++)u.push({offsetMs:p,intensity:f===0?1:t.between(.4,.9)}),p+=xn.INTERSTROKE_MS*t.between(.5,1.6);i.push({t:r,azimuthDeg:t.between(0,360),distanceM:h,cloudToGround:a,strokes:u,channelSeed:Math.floor(t.next()*2**31)}),r+=t.between(n,s)*1e3}return i}static intervalFor(e){const t=Math.min(1,Math.max(0,(e-.5)/.5));return{minS:xn.MIN_INTERVAL_S-t*(xn.MIN_INTERVAL_S-xn.SEVERE_MIN_INTERVAL_S),maxS:xn.MAX_INTERVAL_S-t*(xn.MAX_INTERVAL_S-xn.SEVERE_MAX_INTERVAL_S)}}static brightnessAt(e,t){let i=0;for(const n of e.strokes){const s=t-e.t-n.offsetMs;s<0||s>xn.STROKE_DECAY_MS*6||(i+=n.intensity*Math.exp(-s/xn.STROKE_DECAY_MS))}return Math.min(1,i)}static endOf(e){const t=e.strokes[e.strokes.length-1];return e.t+t.offsetMs+xn.STROKE_DECAY_MS*6}static thunderDelayMs(e){return e.distanceM/xn.SOUND_SPEED_M_S*1e3}}class Uc{static ODD_RADIUS_WEDGES_DEG=[28,56,80];static STANDS_OUT=1.5;static NEIGHBOURHOOD_DEG=2.5;static oddRadiiDeg(){const e=(ut.ICE_INDEX_RED+ut.ICE_INDEX_BLUE)/2;return Uc.ODD_RADIUS_WEDGES_DEG.map(t=>ut.minimumDeviationDeg(t,e)).filter(t=>Number.isFinite(t))}static at(e,t,i,n){const s=Math.PI/180,r=e,a=Math.abs(i),o=Math.sin(r*s)*Math.sin(t*s)+Math.cos(r*s)*Math.cos(t*s)*Math.cos(a*s),c=Math.acos(Math.max(-1,Math.min(1,o)))/s,h=Math.atan2(Math.sin(a*s)*Math.cos(t*s),Math.cos(r*s)*Math.sin(t*s)-Math.sin(r*s)*Math.cos(t*s)*Math.cos(a*s))/s,d=Math.abs(t-r),u=()=>{const y=n(t,a);if(!(y>0))return!1;const w=Uc.NEIGHBOURHOOD_DEG,b=1/Math.max(.2,Math.cos(t*s)),M=[n(t+w,a),n(t-w,a),n(t,a+w*b),n(t,Math.max(0,a-w*b))].sort((S,E)=>S-E);return y>M[1]*Uc.STANDS_OUT},p=()=>{const y=w=>{const b=c*s,M=w*s,S=Math.cos(b)*Math.cos(r*s)-Math.sin(b)*Math.cos(M)*Math.sin(r*s),E=Math.sin(b)*Math.sin(M),x=Math.cos(b)*Math.sin(r*s)+Math.sin(b)*Math.cos(M)*Math.cos(r*s);return n(Math.asin(Math.max(-1,Math.min(1,x)))/s,Math.abs(Math.atan2(E,S)/s))};return(y(70)+y(110)+y(250)+y(290))/4},f=(y,w=0)=>{if(u())return w>0&&!(n(t,a)>p()*w)?void 0:y};if(r>0&&r<ut.PARHELIA_MAX_SUN_ALTITUDE_DEG&&d<2.5){const y=ut.parheliaAzimuthDeg(r);if(y!==void 0&&a>=y-1.2&&a<=y+7){const w=f({id:"parhelion",angleDeg:ut.parheliaDistanceDeg(r)},2.5);if(w)return w}}if(r>0&&d<2.5&&Math.abs(a-120)<4){const y=f({id:"parhelion120",angleDeg:120},0);if(y)return y}const m=ut.circumzenithalAltitudeDeg(r);if(m!==void 0&&t>m-2&&t<m+4){const y=f({id:"circumzenithal",angleDeg:m});if(y)return y}if(r>ut.PLATE_END_FACE_LIMIT_DEG){const y=ut.circumzenithalAltitudeDeg(90-r);if(y!==void 0){const w=90-y;if(t>w-4&&t<w+2){const b=f({id:"circumhorizontal",angleDeg:w});if(b)return b}}}if(a<3&&r>0){if(t>r+3&&t<r+25&&r<ut.PILLAR_MAX_SOURCE_ALTITUDE_DEG){const y=f({id:"pillar"});if(y)return y}if(Math.abs(t+r)<3){const y=f({id:"subsun"});if(y)return y}}const v=ut.halo22();if(c>v.redAngleDeg-.6&&c<v.blueAngleDeg+2.5){const y=Math.abs(h)<50,w=Math.abs(h)>130;if(y||w){const b=f({id:y?"upperTangentArc":"lowerTangentArc",angleDeg:v.angleDeg},1.5);if(b)return b}}for(const y of Uc.oddRadiiDeg())if(c>y-.6&&c<y+1.8){const w=f({id:"oddRadius",angleDeg:y});if(w)return w}if(c>v.redAngleDeg-.6&&c<v.blueAngleDeg+2.5){const y=f({id:"halo22",angleDeg:v.angleDeg});if(y)return y}const g=ut.halo46();if(c>g.redAngleDeg-.6&&c<g.blueAngleDeg+3){const y=f({id:"halo46",angleDeg:g.angleDeg});if(y)return y}if(r>0&&d<1.2){const y=n(t,a),w=Math.max(n(t+3,a),n(t-3,a));if(y>0&&y>w*2)return{id:"parhelicCircle",angleDeg:r}}}}class _s{static RED_NM=656.3;static BLUE_NM=435.8;static ANCHOR_RED=1.3067;static ANCHOR_BLUE=1.317;static B=(_s.ANCHOR_BLUE-_s.ANCHOR_RED)/(1/(_s.BLUE_NM*_s.BLUE_NM)-1/(_s.RED_NM*_s.RED_NM));static A=_s.ANCHOR_RED-_s.B/(_s.RED_NM*_s.RED_NM);static indexAt(e){return _s.A+_s.B/(e*e)}}class ta{static MAX_FACES=20;normals=new Float64Array(ta.MAX_FACES*3);offsets=new Float64Array(ta.MAX_FACES);faceCount=8;radius=1;set(e,t,i,n,s,r,a=0){let o=0,c=0,h=0;Math.abs(i)<.9?(o=-t,c=e,h=0):(o=0,c=-i,h=t);const d=Math.hypot(o,c,h)||1;o/=d,c/=d,h/=d;const u=t*h-i*c,p=i*o-e*h,f=e*c-t*o,m=s/2,v=r/2;for(let g=0;g<6;g++){const y=n+g*Math.PI/3,w=Math.cos(y),b=Math.sin(y);this.normals[g*3]=o*w+u*b,this.normals[g*3+1]=c*w+p*b,this.normals[g*3+2]=h*w+f*b,this.offsets[g]=m}if(this.normals[18]=e,this.normals[19]=t,this.normals[20]=i,this.offsets[6]=v,this.normals[21]=-e,this.normals[22]=-t,this.normals[23]=-i,this.offsets[7]=v,this.faceCount=8,a>0){const g=ta.PYRAMID_TILT,y=Math.cos(g),w=Math.sin(g),b=Math.min(v,a*m*Math.tan(g)),M=v-b,S=y*M+w*m;for(let E=0;E<6;E++){const x=E*3,T=(8+E)*3,D=(14+E)*3;this.normals[T]=y*e+w*this.normals[x],this.normals[T+1]=y*t+w*this.normals[x+1],this.normals[T+2]=y*i+w*this.normals[x+2],this.normals[D]=-y*e+w*this.normals[x],this.normals[D+1]=-y*t+w*this.normals[x+1],this.normals[D+2]=-y*i+w*this.normals[x+2],this.offsets[8+E]=S,this.offsets[14+E]=S}this.faceCount=ta.MAX_FACES}this.radius=Math.hypot(m*2/Math.sqrt(3),v)}static rollToward(e,t,i,n,s,r){let a,o,c;Math.abs(i)<.9?(a=-t,o=e,c=0):(a=0,o=-i,c=t);const h=Math.hypot(a,o,c)||1;a/=h,o/=h,c/=h;const d=t*c-i*o,u=i*a-e*c,p=e*o-t*a;return Math.atan2(n*d+s*u+r*p,n*a+s*o+r*c)}get aimRadius(){return this.radius}trace(e,t,i,n,s,r,a){let o=-t,c=e,h=0,d=Math.hypot(o,c,h);d<1e-6&&(o=1,c=0,h=0,d=1),o/=d,c/=d,h/=d;const u=t*h-i*c,p=i*o-e*h,f=e*c-t*o,m=o*n+u*s-e*this.radius*2,v=c*n+p*s-t*this.radius*2,g=h*n+f*s-i*this.radius*2;let y=-1,w=-1/0,b=1/0;for(let W=0;W<this.faceCount;W++){const ee=this.normals[W*3],se=this.normals[W*3+1],Be=this.normals[W*3+2],ht=ee*e+se*t+Be*i,Xe=this.offsets[W]-(ee*m+se*v+Be*g);if(ht>1e-9){const j=Xe/ht;j<b&&(b=j)}else if(ht<-1e-9){const j=Xe/ht;j>w&&(w=j,y=W)}else if(Xe<0)return 0}if(y<0||w>=b)return 0;let M=0;const S=this.normals[y*3],E=this.normals[y*3+1],x=this.normals[y*3+2],T=-(S*e+E*t+x*i),D=Rf.reflectance(T,1,r);a[M].x=e+2*T*S,a[M].y=t+2*T*E,a[M].z=i+2*T*x,a[M].weight=D,M++;const R=1/r,O=Math.sqrt(Math.max(0,1-R*R*(1-T*T)));let N=R*e+(R*T-O)*S,C=R*t+(R*T-O)*E,k=R*i+(R*T-O)*x,P=m+e*w,F=v+t*w,G=g+i*w,Y=1-D;for(let W=0;W<ta.MAX_BOUNCES&&Y>ta.MIN_WEIGHT;W++){let ee=-1,se=1/0;for(let V=0;V<this.faceCount;V++){const He=this.normals[V*3],Ye=this.normals[V*3+1],Ve=this.normals[V*3+2],De=He*N+Ye*C+Ve*k;if(De<=1e-9)continue;const Qe=(this.offsets[V]-(He*P+Ye*F+Ve*G))/De;Qe>1e-9&&Qe<se&&(se=Qe,ee=V)}if(ee<0)break;const Be=this.normals[ee*3],ht=this.normals[ee*3+1],Xe=this.normals[ee*3+2],j=Be*N+ht*C+Xe*k,le=r*Math.sqrt(Math.max(0,1-j*j));if(P+=N*se,F+=C*se,G+=k*se,le<1){const V=Math.sqrt(Math.max(0,1-le*le)),He=Rf.reflectance(j,r,1);if(a[M].x=r*N-(r*j-V)*Be,a[M].y=r*C-(r*j-V)*ht,a[M].z=r*k-(r*j-V)*Xe,a[M].weight=Y*(1-He),M++,M>=a.length)return M;Y*=He}const oe=2*j;N-=oe*Be,C-=oe*ht,k-=oe*Xe}return M}static MAX_BOUNCES=6;static PYRAMID_TILT=62*Math.PI/180;static MIN_WEIGHT=1e-4}class $t{static AZIMUTH_BINS=512;static ALTITUDE_BINS=512;static DEFAULT_POPULATIONS=[{orientation:"tumbling",widthMicrons:50,lengthMicrons:50,share:.48},{orientation:"plate",widthMicrons:100,lengthMicrons:15,share:.27},{orientation:"column",widthMicrons:40,lengthMicrons:120,share:.18},{orientation:"parry",widthMicrons:40,lengthMicrons:120,share:.02},{orientation:"pyramidal",widthMicrons:40,lengthMicrons:120,share:.03,capFraction:.5},{orientation:"lowitz",widthMicrons:100,lengthMicrons:15,share:.02}];static DEFAULT_RARE_SHARE=fx;static populationsFor(e){const t=Math.min(.9,Math.max(0,e));if(Math.abs(t-$t.DEFAULT_RARE_SHARE)<1e-9)return $t.DEFAULT_POPULATIONS;const i=(1-t)/(1-$t.DEFAULT_RARE_SHARE);return $t.DEFAULT_POPULATIONS.map(n=>n.orientation==="pyramidal"||n.orientation==="lowitz"?{...n,share:n.share/$t.DEFAULT_RARE_SHARE*t}:{...n,share:n.share*i})}populations=$t.DEFAULT_POPULATIONS;populationTotal=1;static WORST_TILT_DEG=180;static BEST_TILT_DEG=.5;static SOURCE_RADIUS_DEG=.265;static UNDEVIATED_DEG=.6;crystal=new ta;emergent=Array.from({length:ta.MAX_BOUNCES+2},()=>({x:0,y:0,z:0,weight:0}));tally=new Float32Array($t.AZIMUTH_BINS*$t.ALTITUDE_BINS*3);radiance=new Float32Array($t.AZIMUTH_BINS*$t.ALTITUDE_BINS*3);scratch=new Float32Array($t.AZIMUTH_BINS*$t.ALTITUDE_BINS*3);seed=1;spare=0;hasSpare=!1;altitude=0;tilt=0;alignment=0;traced=0;begin(e,t,i=2654435769,n=$t.DEFAULT_POPULATIONS){this.populations=n,this.populationTotal=n.reduce((r,a)=>r+a.share,0)||1,this.seed=i>>>0||1,this.hasSpare=!1,this.tally.fill(0),this.traced=0,this.altitude=e*Math.PI/180,this.alignment=Math.min(1,Math.max(0,t));const s=$t.WORST_TILT_DEG*($t.BEST_TILT_DEG/$t.WORST_TILT_DEG)**this.alignment;this.tilt=s*Math.PI/180}trace(e){const t=$t.AZIMUTH_BINS,i=$t.ALTITUDE_BINS,n=this.tally,s=$t.SOURCE_RADIUS_DEG*Math.PI/180,r=Math.cos($t.UNDEVIATED_DEG*Math.PI/180),a=this.altitude;for(let o=0;o<e;o++){const c=this.pickPopulation();this.orient(c,this.tilt);const h=this.random()*2*Math.PI,d=s*Math.sqrt(this.random()),u=a+d*Math.sin(h),p=d*Math.cos(h)/Math.max(.05,Math.cos(a)),f=-Math.cos(u)*Math.cos(p),m=-Math.cos(u)*Math.sin(p),v=-Math.sin(u),g=this.crystal.aimRadius,y=(this.random()*2-1)*g,w=(this.random()*2-1)*g,b=4*g*g,M=En.SAMPLES[this.random()*En.SAMPLES.length|0],S=this.crystal.trace(f,m,v,y,w,_s.indexAt(M.wavelengthNm),this.emergent);for(let E=0;E<S;E++){const x=this.emergent[E],T=Math.hypot(x.x,x.y,x.z);if(T<1e-9||x.weight<=0)continue;const D=x.x/T,R=x.y/T,O=x.z/T;if(D*f+R*m+O*v>r)continue;const N=Math.asin(Math.max(-1,Math.min(1,-O))),C=Math.abs(Math.atan2(-R,-D)),k=Math.min(t-1,C/Math.PI*t|0),F=(Math.min(i-1,(N+Math.PI/2)/Math.PI*i|0)*t+k)*3,G=x.weight*b*En.SAMPLES.length;n[F]+=G*M.r,n[F+1]+=G*M.g,n[F+2]+=G*M.b}}this.traced+=e}get tracedRays(){return this.traced}harvest(){const e=$t.AZIMUTH_BINS,t=$t.ALTITUDE_BINS;return this.toRadiance(e,t),this.smooth(e,t),{width:e,height:t,data:this.radiance,sourceAltitudeDeg:this.altitude*180/Math.PI,alignment:this.alignment,rays:this.traced}}compute(e,t,i,n,s){return this.begin(e,t,n,s),this.trace(i),this.harvest()}toRadiance(e,t){const i=2*Math.PI/e,n=Math.max(1,this.traced),s=4*$t.REFERENCE_MICRONS*$t.REFERENCE_MICRONS;for(let r=0;r<t;r++){const a=Math.sin(r/t*Math.PI-Math.PI/2),o=Math.sin((r+1)/t*Math.PI-Math.PI/2),c=1/(i*(o-a)*n*s);for(let h=0;h<e;h++){const d=(r*e+h)*3;this.radiance[d]=this.tally[d]*c,this.radiance[d+1]=this.tally[d+1]*c,this.radiance[d+2]=this.tally[d+2]*c}}}static REFERENCE_MICRONS=50;smooth(e,t){const i=this.scratch,n=this.radiance;i.set(n);for(let r=0;r<t;r++){const a=r*e*3;for(let o=0;o<3;o++){let c=i[a+o];for(let h=0;h<e;h++){const d=a+h*3+o,u=h+1<e?i[d+3]:i[d];n[d]=(c+2*i[d]+u)/4,c=i[d]}}}i.set(n);const s=e*3;for(let r=0;r<t;r++){const a=r>0?-s:0,o=r+1<t?s:0,c=r*s;for(let h=c;h<c+s;h++)n[h]=(i[h+a]+2*i[h]+i[h+o])/4}}pickPopulation(){const e=this.random()*this.populationTotal;let t=0;for(const i of this.populations)if(t+=i.share,e<=t)return i;return this.populations[this.populations.length-1]}orient(e,t){const i=this.random()*2*Math.PI;let n=this.random()*2*Math.PI,s=0,r=0,a=1;switch(e.orientation){case"pyramidal":case"tumbling":{a=this.random()*2-1;const o=Math.sqrt(Math.max(0,1-a*a));s=o*Math.cos(i),r=o*Math.sin(i);break}case"plate":{a=this.spreadAboutAnAxis(t);const o=Math.sqrt(Math.max(0,1-a*a));s=o*Math.cos(i),r=o*Math.sin(i);break}case"column":case"parry":{a=this.spreadAboutAPlane(t);const o=Math.sqrt(Math.max(0,1-a*a));s=o*Math.cos(i),r=o*Math.sin(i),e.orientation==="parry"&&(n=Math.PI/2+this.gaussian()*t);break}}if(e.orientation==="lowitz"){const o=this.spreadAboutAPlane(t),c=Math.sqrt(Math.max(0,1-o*o)),h=c*Math.cos(i),d=c*Math.sin(i),u=o;let p=-u*h,f=-u*d,m=1-u*u;const v=Math.hypot(p,f,m)||1;p/=v,f/=v,m/=v;const g=d*m-u*f,y=u*p-h*m,w=h*f-d*p,b=this.random()*2*Math.PI;s=p*Math.cos(b)+g*Math.sin(b),r=f*Math.cos(b)+y*Math.sin(b),a=m*Math.cos(b)+w*Math.sin(b),n=ta.rollToward(s,r,a,h,d,u)+Math.PI/6}this.crystal.set(s,r,a,n,e.widthMicrons,e.lengthMicrons,e.capFraction??0)}random(){this.seed=this.seed+1831565813>>>0;let e=this.seed;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}spreadAboutAnAxis(e){const t=1/Math.max(1e-6,e*e),i=Math.max(1e-12,this.random()),n=1+Math.log(i+(1-i)*Math.exp(-2*t))/t;return Math.max(-1,Math.min(1,n))}spreadAboutAPlane(e){for(let t=0;t<8;t++){const i=this.gaussian()*e;if(i>=-1&&i<=1)return i}return this.random()*2-1}gaussian(){if(this.hasSpare)return this.hasSpare=!1,this.spare;const e=Math.sqrt(-2*Math.log(Math.max(1e-12,this.random()))),t=2*Math.PI*this.random();return this.spare=e*Math.sin(t),this.hasSpare=!0,e*Math.cos(t)}}class YL{static fromRadiance(e,t){const i=js.toHalfFloat(1);for(let n=0,s=0;s<e.length;n+=4,s+=3)t[n]=js.toHalfFloat(e[s]),t[n+1]=js.toHalfFloat(e[s+1]),t[n+2]=js.toHalfFloat(e[s+2]),t[n+3]=i}}class ji{static RADIUS=880;static RAYS=9e5;static RAYS_PER_BATCH=2e3;static BUDGET_MS=6;static URGENT_BUDGET_MS=40;static ALTITUDE_STEP_DEG=1;static ALIGNMENT_STEP=.05;static LEAP_ALTITUDE_DEG=5;static LEAP_ALIGNMENT=.25;static GAIN=.55;setCloudOffset(e){this.material.uniforms.uFieldOffset.value.copy(e)}object;material;sky=new $t;texture;texels;mappedAltitudeDeg=Number.NaN;mappedAlignment=Number.NaN;mappedRare=Number.NaN;tracing=!1;everDisplayed=!1;urgent=!1;workHandle;onRepaint;constructor(){const e=$t.AZIMUTH_BINS,t=$t.ALTITUDE_BINS;this.texels=new Uint16Array(e*t*4),this.texture=new Qs(this.texels,e,t,bn,Jt),this.texture.minFilter=Dt,this.texture.magFilter=Dt,this.texture.wrapS=tn,this.texture.wrapT=tn,this.texture.needsUpdate=!0,this.material=new Ct({uniforms:{uSource:{value:new _(0,1,0)},uUp:{value:new _(0,1,0)},uStrength:{value:0},uTint:{value:new _(1,.97,.92)},uIceCover:{value:0},uIceHeight:{value:1},uFieldOffset:{value:new _},uMap:{value:this.texture},uGain:{value:ji.GAIN}},vertexShader:`
10476
10476
  varying vec3 vDirection;
10477
10477
  void main() {
10478
10478
  vDirection = normalize((modelMatrix * vec4(position, 1.0)).xyz - cameraPosition);
@@ -10509,7 +10509,7 @@ uniform float uWindowLuminance;
10509
10509
  varying float vLitRank;
10510
10510
  ${o.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissivemap_fragment>
10511
10511
  totalEmissiveRadiance *= step(vLitRank, uLitShare) * uWindowLuminance * ${me.WINDOW_VARIETY_GLSL};`)}`},r.customProgramCacheKey=()=>"facade-lit-windows";const a=new xe(s,r);return a.castShadow=!0,a.receiveShadow=!0,t.add(a),t}static CLOSED_AT_NIGHT_SHARE=.2;static litWindowShare={value:0};static WINDOW_LUMINANCE_CD_M2=15;static ROOM_LIGHT_K=2900;static COLD_ROOM_LIGHT_K=4e3;static windowLuminance={value:0};static get WINDOW_VARIETY_GLSL(){const e=n=>`vec3(${n.map(s=>s.toFixed(4)).join(", ")})`,t=nh.ofTemperature(me.ROOM_LIGHT_K),i=nh.ofTemperature(me.COLD_ROOM_LIGHT_K);return`(mix(0.35, 2.0, fract(vLitRank * 97.13) * fract(vLitRank * 97.13)) * mix(${e(t)}, ${e(i)}, step(0.86, fract(vLitRank * 53.71))))`}static setWindowLuminance(e){me.windowLuminance.value=me.WINDOW_LUMINANCE_CD_M2*e}static setLitWindowShare(e){me.litWindowShare.value=Math.max(0,Math.min(1,e))}static build(e,t){const i=me.hasFacade(e)?me.buildFacade(e):e.kind==="building"?Xw(e.floors??dh,e.windows,e.observerSide,e.occupiedFloor,e.observerFacing):e.kind==="tree"?qw():e.kind==="shrub"?Yw():e.kind==="bridge"?hO(e):e.kind==="wire"?dO(e):e.kind==="wall"?fn.build(e):e.kind==="crop"?Zw():e.kind==="terrace"?yO():e.kind==="mound"?Jw():e.kind==="streetlight"?Qw(t,e.lamp?.mount,e.lamp):e.kind==="trafficlight"?xt.trafficLight(at.isPedestrian(e.lights)):e.kind==="crossing"?xt.crossing(me.sizeOf(e).widthM,me.sizeOf(e).lengthM):e.kind==="roadsign"?xt.roadSign(e.sign):e.kind==="vehicle"?eM(t,e.windows,e.observerSide,e.observerFacing):e.kind==="aircraft"?aM():e.kind==="entity"?sM():Nv();e.color&&this.paint(i,e.color);const n=this.scaleFor(e),s=new zt;return e.kind==="building"&&e.roof&&this.addRoof(s,e),i.name=me.BODY_NAME,i.scale.copy(n),s.add(i),e.headingDeg!==void 0&&(s.rotation.y=-e.headingDeg*w0),this.addLights(s,e.lights),me.fitLights(s,e,e.sizeM??{}),s}static scaleFor(e){const t=e.sizeM;if(!t||me.hasFacade(e)||e.kind==="bridge"||e.kind==="wire"||e.kind==="terrace"||e.kind==="wall"||e.kind==="crossing")return new _(1,1,1);const i=this.naturalSize(e.kind,e.floors);return new _(t.widthM===void 0?1:E0(t.widthM,i.widthM),t.heightM===void 0?1:E0(e.kind==="building"?this.wallHeightOf(e,t.heightM):t.heightM,i.heightM),t.lengthM===void 0?1:E0(t.lengthM,i.lengthM))}static naturalSize(e,t){const i=e==="building"?Math.max(1,(t??dh)+1):0;if(e==="bridge")return Ei.NATURAL_SIZE;if(e==="wire")return xl.NATURAL_SIZE;if(e==="terrace"||e==="wall")return{widthM:1,lengthM:1,heightM:1};if(e==="crossing")return{widthM:6,lengthM:2.5,heightM:xt.CROSSING_LIFT_M};const n=`${e}:${i}`,s=tM.get(n);if(s)return s;const r=e==="building"?Xw(i-1,void 0,void 0,void 0):e==="tree"?qw():e==="shrub"?Yw():e==="crop"?Zw():e==="mound"?Jw():e==="streetlight"?Qw(!1):e==="trafficlight"?xt.trafficLight(!1):e==="roadsign"?xt.roadSign(void 0):e==="vehicle"?eM(!1,void 0,void 0):e==="aircraft"?aM():e==="entity"?sM():Nv(),a=new vn().setFromObject(r),o={widthM:a.max.x-a.min.x,heightM:a.max.y-a.min.y,lengthM:a.max.z-a.min.z};return this.dispose(r),tM.set(n,o),o}static usesModel(e){return Od(e)!==void 0&&!(e.observerSide!==void 0&&Ro(e.kind))}static applyModel(e,t,i,n={}){const s=this.bodyOf(e),r=new zt;r.name=me.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*w0,i.updateMatrixWorld(!0);const a=new vn().setFromObject(i),o={lengthM:a.max.z-a.min.z,heightM:a.max.y-a.min.y,widthM:a.max.x-a.min.x},c=t.kind==="tree"&&t.sizeM?.heightM!==void 0?{heightM:t.sizeM.heightM}:t.sizeM,h=iM(c,o)??iM(n.depictedSizeM,o)??1;i.scale.multiplyScalar(h);const d=a.getCenter(new _).multiplyScalar(h);i.position.x-=d.x,i.position.z-=d.z,i.position.y-=t.kind==="aircraft"?d.y:a.min.y*h,i.traverse(u=>{u instanceof xe&&(u.castShadow=!0,u.receiveShadow=!0)}),r.add(i),t.kind==="tree"&&r.add(me.trunkShadow(o.heightM*h)),s.parent?(s.parent.add(r),s.removeFromParent()):e.add(r),this.dispose(s),me.fitLights(e,t,{widthM:o.widthM*h,heightM:o.heightM*h,lengthM:o.lengthM*h})}static fitLights(e,t,i){const n=hh.byId(Rr.rigOf(t)||void 0)?.referenceSizeM;if(!n||!t.lights)return;const s=(h,d)=>h===void 0||d===0?1:h/d,r=s(i.widthM,n.widthM),a=s(i.heightM,n.heightM),o=s(i.lengthM,n.lengthM),c=new Map(t.lights.map(h=>[h.id,h.offsetM]));e.traverse(h=>{const d=h.userData.lightId,u=d===void 0?void 0:c.get(d);u&&h.position.set(u.x*r,u.y*a,u.z*o)})}static trunkShadow(e){me.trunkProxy??={geometry:new ns(1,1.15,1,8),material:new Fs({colorWrite:!1,depthWrite:!1})};const t=new xe(me.trunkProxy.geometry,me.trunkProxy.material),i=Math.min(.3,Math.max(.12,e*.035)),n=e*.45;return t.scale.set(i,n,i),t.position.y=n/2,t.castShadow=!0,t.receiveShadow=!1,t.userData.sharedModel=!0,t.name="trunk-shadow",t}static trunkProxy;static sizeOf(e){const t=this.naturalSize(e.kind,e.floors);return{widthM:e.sizeM?.widthM??t.widthM,lengthM:e.sizeM?.lengthM??t.lengthM,heightM:e.sizeM?.heightM??t.heightM}}static addLights(e,t){for(const i of t??[]){const n=tO(i.color),s=at.figureOf(i),r=s?xt.pedestrianFigure(s,1.8*(i.radiusM??M0)):new hn(i.radiusM??M0,8,6),a=qt(e,r,n,i.offsetM.y,!0);a.position.set(i.offsetM.x,i.offsetM.y,i.offsetM.z),a.userData={emissive:!0,lightId:i.id,lightColor:n},a.visible=!1;const o=a.material;PS.apply(o),o.transparent=!0,o.depthWrite=!1,o.fog=!1}}static setLights(e,t,i,n,s=0,r=1,a=qL,o=[1,1,1],c){if(!t||t.length===0)return;const h=new Map(t.map(u=>[u.id,u]));let d;c&&t.some(u=>u.beamDeg!==void 0)&&(e.updateWorldMatrix(!0,!1),d=e.worldToLocal(me.eyeScratch.copy(c)));for(const u of e.children){if(!(u instanceof xe))continue;const p=u.userData.lightId;if(!p)continue;const f=h.get(p);if(!f)continue;const m=s>0?u2(f,i,i+s):ET(f,i)?1:0,v=d&&f.beamDeg!==void 0?me.beamShare(f.beamDeg,u.position,d):1;u.visible=m>0&&v>0;const g=f.radiusM??M0,y=Math.max(1,n*a/g),w=g*y,b=r/(Math.PI*w*w),M=u.material,S=u.userData.lightColor;if(S){const E=m*v*jL*(f.intensity??1)*b,x=[S[0]*E*o[0],S[1]*E*o[1],S[2]*E*o[2]],T=Math.min(1,$w/Math.max(x[0],x[1],x[2],1e-30));M.color.setRGB(x[0]*T,x[1]*T,x[2]*T)}u.scale.setScalar(y)}}static eyeScratch=new _;static beamShare(e,t,i){const n=i.x-t.x,s=i.y-t.y,r=i.z-t.z,a=Math.hypot(n,s,r);if(a===0)return 1;const o=-r/a;if(o<=0)return 0;const c=Math.log(.5)/Math.log(Math.cos(e*Math.PI/180));return Math.pow(o,c)}static setLit(e,t,i,n=1,s){const[r,a,o]=t==="streetlight"?[ZL*me.lampShare(s),JL,me.lampHue(s)]:[QL,eO,NS],c=i?r*n/(Math.PI*a*a):0,h=Math.min(1,$w/Math.max(o[0]*c,o[1]*c,o[2]*c,1e-30)),d=[o[0]*c*h,o[1]*c*h,o[2]*c*h];e.traverse(u=>{const p=u.userData;!(u instanceof xe)||!p.emissive||p.lightId||(u.material instanceof pr?u.material.emissive.setRGB(...d):u.material.color.setRGB(...d))})}static REFERENCE_LUMENS=1e4;static lampShare(e){return e?.lumens?e.lumens/me.REFERENCE_LUMENS:1}static lampHue(e){return e?.colorTemperatureK?nh.ofTemperature(e.colorTemperatureK):nO}static dispose(e){e.traverse(t=>{if(!(t instanceof xe))return;if(t.userData.sharedModel){for(const n of t.userData.tintedMaterials??[])n.dispose();return}t.geometry.dispose();const i=t.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const T0="https://ufoathome.org/models/index.json";class yd{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??SO()}async entries(e){const t=await this.load();return e?t.filter(i=>[i.kind].flat().includes(e)):t}async entry(e){return(await this.load()).find(t=>t.id===e)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const e=this.indexUrls.join(`
10512
- `);let t=yd.shared.get(e);return t||(t=this.fetchFirstAvailable(),yd.shared.set(e,t),t.then(i=>{i.length===0&&yd.shared.delete(e)})),this.loading=t}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,e).href})):void 0}catch{return}}}function SO(){const l=`?v=${encodeURIComponent("0.150.0")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==T0?[e,T0]:[T0]).map(t=>t+l)}const _p=[{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 yd}];async function I0(l){const{GLTFLoader:e}=await ae(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-DHQ7X9p5.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,n)=>{t.load(l,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${l}: ${s instanceof Error?s.message:String(s)}`)))})}class Xs{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new xe(new xs(2,2),new Ct({uniforms:{uColor:{value:new re(0,0,0)},uRadius:{value:1}},vertexShader:Xs.VERTEX,fragmentShader:Xs.FRAGMENT,transparent:!0,depthWrite:!1,blending:An,toneMapped:!1})),this.mesh.name=e,this.mesh.frustumCulled=!1,this.mesh.renderOrder=t,this.mesh.visible=!1}shine(e,t,i){this.mesh.visible=!0,this.mesh.position.set(e.x,e.y,e.z),this.mesh.material.uniforms.uRadius.value=t,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(e,t,i,n){const s=Math.max(e,n*Xs.MIN_ANGLE_RAD),r=Xs.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Xs.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(Xs.MAX_SHARE*Xs.FILL*Math.PI))}static VERTEX=`
10512
+ `);let t=yd.shared.get(e);return t||(t=this.fetchFirstAvailable(),yd.shared.set(e,t),t.then(i=>{i.length===0&&yd.shared.delete(e)})),this.loading=t}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,e).href})):void 0}catch{return}}}function SO(){const l=`?v=${encodeURIComponent("0.150.2")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==T0?[e,T0]:[T0]).map(t=>t+l)}const _p=[{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 yd}];async function I0(l){const{GLTFLoader:e}=await ae(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-DHQ7X9p5.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,n)=>{t.load(l,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${l}: ${s instanceof Error?s.message:String(s)}`)))})}class Xs{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new xe(new xs(2,2),new Ct({uniforms:{uColor:{value:new re(0,0,0)},uRadius:{value:1}},vertexShader:Xs.VERTEX,fragmentShader:Xs.FRAGMENT,transparent:!0,depthWrite:!1,blending:An,toneMapped:!1})),this.mesh.name=e,this.mesh.frustumCulled=!1,this.mesh.renderOrder=t,this.mesh.visible=!1}shine(e,t,i){this.mesh.visible=!0,this.mesh.position.set(e.x,e.y,e.z),this.mesh.material.uniforms.uRadius.value=t,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(e,t,i,n){const s=Math.max(e,n*Xs.MIN_ANGLE_RAD),r=Xs.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Xs.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(Xs.MAX_SHARE*Xs.FILL*Math.PI))}static VERTEX=`
10513
10513
  uniform float uRadius;
10514
10514
  varying vec2 vOffset;
10515
10515
  void main() {
@@ -10665,7 +10665,7 @@ float litFromWithin() {
10665
10665
  `+n.vertexShader,n.vertexShader=n.vertexShader.replace("#include <project_vertex>",`#include <project_vertex>
10666
10666
  cloudPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let s=`varying vec3 cloudPoint;
10667
10667
  `,r="";t.forEach((a,o)=>{const c=`cloud${o}_`;for(const[h,d]of Object.entries(a.uniforms))n.uniforms[c+h]=d;s+=lL(c),r+=`diffuseColor.a *= ${c}transmissionAt(normalize(cloudPoint), length(cloudPoint));
10668
- `}),n.fragmentShader=s+n.fragmentShader,n.fragmentShader=n.fragmentShader.replace("#include <opaque_fragment>",r+"#include <opaque_fragment>")},e.needsUpdate=!0}meshes=new Map;signatures=new Map;extents=new Map;placed=[];frame;direction=new _;up=new _;lookAt=new vt;vertex=new _;centre=new _;right=new _;above=new _;set(e,t){this.placed=e,this.frame=t;const i=new Set(e.map(n=>n.sourceId));for(const[n,s]of this.meshes)i.has(n)||(this.dispose(s),this.meshes.delete(n),this.signatures.delete(n),this.extents.delete(n));for(const n of e){let s=this.meshes.get(n.sourceId);s||(s=new xe(new xs(1,1,Mr.SEGMENTS,Mr.SEGMENTS),new Fs({transparent:!0,depthWrite:!1,depthTest:!0,fog:!1,toneMapped:!1})),this.configureCloudMaterial(s.material),s.frustumCulled=!1,s.layers.set(WS),this.scene.add(s),this.meshes.set(n.sourceId,s)),s.renderOrder=EO+n.renderOrder,s.visible=!n.hidden&&n.shape.transparency<1,s.visible&&this.paint(s,n,t)}}place(e,t,i){const n=this.frame;if(n)for(const s of this.placed){const r=this.meshes.get(s.sourceId);if(!r||!r.visible)continue;const a=this.extents.get(s.sourceId);if(!a)continue;const{bounds:o}=s.shape;let c=o.x+o.width/2,h=o.y+o.height/2,d=!0;if(s.aim){const u=i(Mr.directionOf(s.aim,this.direction));u&&Math.abs(u.ndcX)<Mr.FURTHEST_NDC&&Math.abs(u.ndcY)<Mr.FURTHEST_NDC?(c=(u.ndcX+1)/2*n.canvasWidthPx,h=(1-u.ndcY)/2*n.canvasHeightPx):d=!1}d?this.curve(r,e,t,n,a,c,h,s.distanceM):this.flat(r,e,n,a,s.distanceM)}}static FURTHEST_NDC=4;curve(e,t,i,n,s,r,a,o){const c=r-s.width/2,h=a-s.height/2,d=e.geometry.attributes.position,u=Mr.SEGMENTS;let p=0;for(let f=0;f<=u;f++){const m=h+f/u*s.height;for(let v=0;v<=u;v++){const g=c+v/u*s.width;i(g/n.canvasWidthPx*2-1,-(m/n.canvasHeightPx*2-1),this.direction),this.vertex.copy(t.position).addScaledVector(this.direction,o),d.setXYZ(p++,this.vertex.x,this.vertex.y,this.vertex.z)}}d.needsUpdate=!0,e.matrixAutoUpdate=!1,e.matrix.identity(),e.matrixWorldNeedsUpdate=!0,e.scale.set(At.sizeMAt(o,n.projection.pxToDeg(s.width)),At.sizeMAt(o,n.projection.pxToDeg(s.height)),1)}flat(e,t,i,n,s){const r=e.geometry.attributes.position,a=Mr.SEGMENTS,o=At.sizeMAt(s,i.projection.pxToDeg(n.width)),c=At.sizeMAt(s,i.projection.pxToDeg(n.height));this.up.set(0,1,0).applyQuaternion(t.quaternion),this.centre.copy(t.position).addScaledVector(this.direction,s),this.lookAt.lookAt(t.position,this.centre,this.up),this.right.setFromMatrixColumn(this.lookAt,0),this.above.setFromMatrixColumn(this.lookAt,1);let h=0;for(let d=0;d<=a;d++){const u=.5-d/a;for(let p=0;p<=a;p++){const f=p/a-.5;this.vertex.copy(this.centre).addScaledVector(this.right,f*o).addScaledVector(this.above,u*c),r.setXYZ(h++,this.vertex.x,this.vertex.y,this.vertex.z)}}r.needsUpdate=!0,e.matrixAutoUpdate=!1,e.matrix.identity(),e.matrixWorldNeedsUpdate=!0,e.scale.set(o,c,1)}static SEGMENTS=16;static directionOf(e,t){const i=e.azimuthDeg*Math.PI/180,n=e.altitudeDeg*Math.PI/180;return t.set(Math.sin(i)*Math.cos(n),Math.sin(n),-Math.cos(i)*Math.cos(n))}get any(){for(const e of this.meshes.values())if(e.visible)return!0;return!1}get furthestM(){return this.placed.reduce((e,t)=>Math.max(e,t.distanceM),0)}paint(e,t,i){const{shape:n}=t,s=uh.paintExtent(n),r=t.ghost?3:0,a={x:s.x-r,y:s.y-r,width:s.width+2*r,height:s.height+2*r};this.extents.set(t.sourceId,a);const o=`${Mr.signatureOf(n,i)}|${t.ghost?"ghost":""}`;if(this.signatures.get(t.sourceId)===o&&e.material.map)return;this.signatures.set(t.sourceId,o);const c=Math.min(i.scale,AO/Math.max(a.width,a.height,1)),h=Math.max(1,Math.ceil(a.width*c)),d=Math.max(1,Math.ceil(a.height*c)),u=e.material.map,p=u?.image??document.createElement("canvas"),f=p.width!==h||p.height!==d;f&&(p.width=h,p.height=d);const m=p.getContext("2d");if(!m)return;m.clearRect(0,0,h,d);const v=new uh(m);if(v.setStarPoints(i.starPoints),v.setRoll(i.rollRad),v.paintInto(n,a,c,t.ghost),u&&!f){u.needsUpdate=!0;return}u?.dispose();const g=new Lo(p);g.colorSpace=Bn,g.minFilter=Dt,g.generateMipmaps=!1,e.material.map=g,e.material.needsUpdate=!0}static signatureOf(e,t){const{bounds:i}=e;return JSON.stringify([e.kind,Math.round(i.width*10),Math.round(i.height*10),e.color,e.angle,e.transparency,e.haloScale,e.blur??0,e.brightness??0,e.kind==="polygon"?e.points:void 0,t.scale,t.starPoints,t.rollRad])}dispose(e){e.removeFromParent(),e.geometry.dispose(),e.material.map?.dispose(),e.material.dispose()}clear(){for(const e of this.meshes.values())this.dispose(e);this.meshes.clear(),this.signatures.clear(),this.extents.clear(),this.placed=[]}}function TO(l){const e=new Map,t=new Map,i=l.clone();return $S(l,i,function(n,s){e.set(s,n),t.set(n,s)}),i.traverse(function(n){if(!n.isSkinnedMesh)return;const s=n,r=e.get(n),a=r.skeleton.bones;s.skeleton=r.skeleton.clone(),s.bindMatrix.copy(r.bindMatrix),s.skeleton.bones=a.map(function(o){return t.get(o)}),s.bind(s.skeleton,s.bindMatrix)}),i}function $S(l,e,t){t(l,e);for(let i=0;i<l.children.length;i++)$S(l.children[i],e.children[i],t)}class je{static GROUND_RADIUS_M=636e4;static TOP_RADIUS_M=646e4;static WAVELENGTHS_NM=Array.from({length:15},(e,t)=>410+20*t);static WAVELENGTH_STEP_NM=20;static SOLAR_IRRADIANCE=[1.707,1.676,1.982,2.02,1.941,1.87,1.879,1.856,1.839,1.799,1.728,1.668,1.57,1.532,1.452];static OZONE_CROSS_SECTION=[.021,.069,.19,.418,.827,1.531,2.439,3.291,4.468,4.55,4.663,3.477,2.447,1.658,1.071];static RAYLEIGH_SCALE_HEIGHT_M=8e3;static AEROSOL_SCALE_HEIGHT_M=1200;static OZONE_PEAK_ALTITUDE_M=25e3;static OZONE_HALF_WIDTH_M=15e3;static DEFAULT_AEROSOL_OPTICAL_DEPTH=.1;static DEFAULT_OZONE_DOBSON=300;static AEROSOL_SINGLE_SCATTERING_ALBEDO=.9;static AEROSOL_ANGSTROM_EXPONENT=1.3;static AEROSOL_ASYMMETRY=.8;rayleighScattering;aerosolScattering;aerosolExtinction;ozoneAbsorption;constructor(e={}){const t=je.WAVELENGTHS_NM.length,i=e.aerosolOpticalDepth??je.DEFAULT_AEROSOL_OPTICAL_DEPTH,n=e.ozoneDobson??je.DEFAULT_OZONE_DOBSON;this.rayleighScattering=new Float64Array(t),this.aerosolScattering=new Float64Array(t),this.aerosolExtinction=new Float64Array(t),this.ozoneAbsorption=new Float64Array(t);const s=n*2687e17/je.OZONE_HALF_WIDTH_M;for(let r=0;r<t;r++){const a=je.WAVELENGTHS_NM[r];this.rayleighScattering[r]=je.rayleighAt(a);const o=i/je.AEROSOL_SCALE_HEIGHT_M*(a/550)**-1.3;this.aerosolExtinction[r]=o,this.aerosolScattering[r]=o*je.AEROSOL_SINGLE_SCATTERING_ALBEDO,this.ozoneAbsorption[r]=je.OZONE_CROSS_SECTION[r]*1e-25*s}}static rayleighAt(e){const t=e/1e3,i=1/(t*t),n=t*t;return(1.0455996-341.29061*i-.9023085*n)/(1+.0027059889*i-85.968563*n)*1e-28*1e-4*2546899e19}static rayleighDensity(e){return Math.exp(-Math.max(e,0)/je.RAYLEIGH_SCALE_HEIGHT_M)}static aerosolDensity(e){return Math.exp(-Math.max(e,0)/je.AEROSOL_SCALE_HEIGHT_M)}static ozoneDensity(e){return Math.max(0,1-Math.abs(e-je.OZONE_PEAK_ALTITUDE_M)/je.OZONE_HALF_WIDTH_M)}static rayleighPhase(e){return 3/(16*Math.PI)*(1+e*e)}static aerosolPhase(e,t=je.AEROSOL_ASYMMETRY){const i=t*t;return 3/(8*Math.PI)*(1-i)*(1+e*e)/((2+i)*Math.pow(Math.max(1+i-2*t*e,1e-6),1.5))}}class it{static TRANSMITTANCE_WIDTH=256;static TRANSMITTANCE_HEIGHT=64;static MULTIPLE_SIZE=64;static MULTIPLE_ROWS=16;static MULTIPLE_HEIGHT_POWER=2;static MULTIPLE_DIRECTIONS=16;static SKY_VIEW_WIDTH=192;static SKY_VIEW_HEIGHT=108;static STEPS=40;static MULTIPLE_STEPS=12;static GROUND_ALBEDO=.3;supported;renderer;transmittance;multiple;sunView;moonView;scene=new Or;camera=new fr(-1,1,1,-1,0,1);quad;transmittanceMaterial;multipleMaterial;skyViewMaterial;transmittanceReady=!1;multipleRows=0;multipleColumn=0;mediumKey="";static MULTIPLE_BLOCK=16;static shared=new Map;building=!1;adopted;tableUniforms;constructor(e){this.renderer=e,this.supported=e.capabilities.isWebGL2&&e.extensions.has("EXT_color_buffer_float"),this.transmittance=new yi(it.TRANSMITTANCE_WIDTH,it.TRANSMITTANCE_HEIGHT,{count:4,type:Jt,minFilter:Dt,magFilter:Dt,depthBuffer:!1}),this.multiple=new yi(it.MULTIPLE_SIZE,it.MULTIPLE_ROWS,{count:4,type:is,minFilter:pi,magFilter:pi,depthBuffer:!1});const t=()=>new yi(it.SKY_VIEW_WIDTH,it.SKY_VIEW_HEIGHT,{type:is,minFilter:pi,magFilter:pi,depthBuffer:!1});this.sunView=t(),this.moonView=t();const i=it.mediumUniforms(),n=this.tableUniforms={uT0:{value:this.transmittance.textures[0]},uT1:{value:this.transmittance.textures[1]},uT2:{value:this.transmittance.textures[2]},uT3:{value:this.transmittance.textures[3]},uM0:{value:this.multiple.textures[0]},uM1:{value:this.multiple.textures[1]},uM2:{value:this.multiple.textures[2]},uM3:{value:this.multiple.textures[3]}},s=(r,a={})=>new gS({glslVersion:xf,uniforms:{...i,...n,...a},vertexShader:it.VERTEX,fragmentShader:r,depthTest:!1,depthWrite:!1});this.transmittanceMaterial=s(it.TRANSMITTANCE_FRAGMENT),this.multipleMaterial=s(it.MULTIPLE_FRAGMENT),this.skyViewMaterial=s(it.SKY_VIEW_FRAGMENT,{uObserverRadius:{value:je.GROUND_RADIUS_M+2},uSourceMu:{value:1}}),this.quad=new xe(new xs(2,2),this.transmittanceMaterial),this.quad.frustumCulled=!1,this.scene.add(this.quad)}get transmittanceTextures(){return this.transmittance.textures}get sunViewTexture(){return this.sunView.texture}get moonViewTexture(){return this.moonView.texture}get ready(){return this.supported&&(this.adopted!==void 0||this.transmittanceReady&&this.multipleRows>=it.MULTIPLE_ROWS)}setMedium(e){const t=[e.rayleighScattering,e.aerosolScattering,e.aerosolExtinction,e.ozoneAbsorption].map(n=>Array.from(n,s=>s.toPrecision(6)).join(",")).join("|");if(t===this.mediumKey)return;this.abandonBuilding(),this.releaseAdopted(),this.mediumKey=t;const i=(n,s)=>{const r=this.transmittanceMaterial.uniforms[n].value;for(let a=0;a<4;a++)r[a].set(s[a*4]??0,s[a*4+1]??0,s[a*4+2]??0,s[a*4+3]??0)};i("uRayleigh",e.rayleighScattering),i("uAerosolScattering",e.aerosolScattering),i("uAerosolExtinction",e.aerosolExtinction),i("uOzone",e.ozoneAbsorption),this.transmittanceReady=!1,this.multipleRows=0,this.multipleColumn=0}invalidate(){this.adopted||(this.abandonBuilding(),this.transmittanceReady=!1,this.multipleRows=0,this.multipleColumn=0)}advance(e){if(!this.supported||!this.mediumKey)return!1;if(this.ready)return!0;const t=it.shared.get(this.mediumKey);if(t&&t!=="building")return this.adopt(t),!0;if(t==="building"&&!this.building)return!1;t||(it.shared.set(this.mediumKey,"building"),this.building=!0);const i=this.renderer.getRenderTarget();let n=Math.max(1,e);this.transmittanceReady||(this.draw(this.transmittanceMaterial,this.transmittance),this.transmittanceReady=!0,n--);const s=it.MULTIPLE_SIZE,r=it.MULTIPLE_BLOCK;for(;n>0&&this.multipleRows<it.MULTIPLE_ROWS;n--)this.multiple.scissor.set(this.multipleColumn,this.multipleRows,r,1),this.multiple.scissorTest=!0,this.draw(this.multipleMaterial,this.multiple),this.multipleColumn+=r,this.multipleColumn>=s&&(this.multipleColumn=0,this.multipleRows++);return this.multiple.scissorTest=!1,this.renderer.setRenderTarget(i),this.ready&&this.building&&this.share(this.mediumKey),this.ready}async share(e){this.building=!1;try{const t=await Promise.all([0,1,2,3].map(n=>this.readRaw(this.transmittance,n,Uint16Array))),i=await Promise.all([0,1,2,3].map(n=>this.readRaw(this.multiple,n,Float32Array)));this.mediumKey===e?it.shared.set(e,{transmittance:t,multiple:i}):it.shared.delete(e)}catch{it.shared.delete(e)}}async readRaw(e,t,i){const n=new i(e.width*e.height*4);return await this.renderer.readRenderTargetPixelsAsync(e,0,0,e.width,e.height,n,void 0,t),n}adopt(e){const t=(s,r,a,o)=>{const c=new Qs(s,r,a,bn,o?Jt:is);return c.minFilter=c.magFilter=o?Dt:pi,c.needsUpdate=!0,c},i=e.transmittance.map(s=>t(s,it.TRANSMITTANCE_WIDTH,it.TRANSMITTANCE_HEIGHT,!0)),n=e.multiple.map(s=>t(s,it.MULTIPLE_SIZE,it.MULTIPLE_ROWS,!1));i.forEach((s,r)=>this.tableUniforms[`uT${r}`].value=s),n.forEach((s,r)=>this.tableUniforms[`uM${r}`].value=s),this.adopted=[...i,...n]}releaseAdopted(){if(this.adopted){for(const e of this.adopted)e.dispose();this.adopted=void 0;for(let e=0;e<4;e++)this.tableUniforms[`uT${e}`].value=this.transmittance.textures[e],this.tableUniforms[`uM${e}`].value=this.multiple.textures[e]}}abandonBuilding(){this.building&&(this.building=!1,it.shared.get(this.mediumKey)==="building"&&it.shared.delete(this.mediumKey))}renderSkyViews(e,t,i){if(!this.ready)return;const n=this.renderer.getRenderTarget(),s=this.skyViewMaterial.uniforms;s.uObserverRadius.value=je.GROUND_RADIUS_M+Math.max(e,2),s.uSourceMu.value=Math.sin(t*Math.PI/180),this.draw(this.skyViewMaterial,this.sunView),s.uSourceMu.value=Math.sin(i*Math.PI/180),this.draw(this.skyViewMaterial,this.moonView),this.renderer.setRenderTarget(n)}static skyViewUv(e,t,i){const n=je.GROUND_RADIUS_M+Math.max(e,2),s=je.GROUND_RADIUS_M,r=Math.acos(Math.min(Math.sqrt(Math.max(n*n-s*s,0))/n,1)),a=Math.PI-r,o=t<a?.5*(1-Math.sqrt(Math.max(1-t/a,0))):.5+.5*Math.sqrt(Math.min((t-a)/r,1));return{u:Math.min(Math.max(Math.abs(i)/Math.PI,0),1),v:o}}async readTable(e,t){if(e==="multiple"){const s=new Float32Array(this.multiple.width*this.multiple.height*4);return await this.renderer.readRenderTargetPixelsAsync(this.multiple,0,0,this.multiple.width,this.multiple.height,s,void 0,t),s}const i=this.transmittance,n=new Uint16Array(i.width*i.height*4);return await this.renderer.readRenderTargetPixelsAsync(i,0,0,i.width,i.height,n,void 0,t),Float32Array.from(n,s=>js.fromHalfFloat(s))}readSkyViewNow(e){const t=e==="sun"?this.sunView:this.moonView,i=new Float32Array(t.width*t.height*4),n=this.renderer.getContext();return n.bindBuffer(n.PIXEL_PACK_BUFFER,null),this.renderer.readRenderTargetPixels(t,0,0,t.width,t.height,i),i}async readSkyView(e){const t=e==="sun"?this.sunView:this.moonView,i=new Float32Array(t.width*t.height*4);return await this.renderer.readRenderTargetPixelsAsync(t,0,0,t.width,t.height,i),i}dispose(){this.abandonBuilding(),this.releaseAdopted(),this.transmittance.dispose(),this.multiple.dispose(),this.sunView.dispose(),this.moonView.dispose(),this.transmittanceMaterial.dispose(),this.multipleMaterial.dispose(),this.skyViewMaterial.dispose(),this.quad.geometry.dispose()}draw(e,t){this.quad.material=e,this.renderer.setRenderTarget(t),this.renderer.render(this.scene,this.camera)}static mediumUniforms(){const e=()=>[new Ot,new Ot,new Ot,new Ot],t=(i,n)=>{const s=e();return je.WAVELENGTHS_NM.forEach((r,a)=>{s[Math.floor(a/4)].setComponent(a%4,i(r)*n*je.WAVELENGTH_STEP_NM*je.SOLAR_IRRADIANCE[a])}),s};return{uRayleigh:{value:e()},uAerosolScattering:{value:e()},uAerosolExtinction:{value:e()},uOzone:{value:e()},uCieX:{value:t(i=>En.colourMatching(i)[0],683)},uCieY:{value:t(i=>En.colourMatching(i)[1],683)},uCieZ:{value:t(i=>En.colourMatching(i)[2],683)},uScotopic:{value:t(i=>En.scotopic(i),1700)}}}static VERTEX=`
10668
+ `}),n.fragmentShader=s+n.fragmentShader,n.fragmentShader=n.fragmentShader.replace("#include <opaque_fragment>",r+"#include <opaque_fragment>")},e.needsUpdate=!0}meshes=new Map;signatures=new Map;extents=new Map;placed=[];frame;direction=new _;up=new _;lookAt=new vt;vertex=new _;centre=new _;right=new _;above=new _;set(e,t){this.placed=e,this.frame=t;const i=new Set(e.map(n=>n.sourceId));for(const[n,s]of this.meshes)i.has(n)||(this.dispose(s),this.meshes.delete(n),this.signatures.delete(n),this.extents.delete(n));for(const n of e){let s=this.meshes.get(n.sourceId);s||(s=new xe(new xs(1,1,Mr.SEGMENTS,Mr.SEGMENTS),new Fs({transparent:!0,depthWrite:!1,depthTest:!0,fog:!1,toneMapped:!1})),this.configureCloudMaterial(s.material),s.frustumCulled=!1,s.layers.set(WS),this.scene.add(s),this.meshes.set(n.sourceId,s)),s.renderOrder=EO+n.renderOrder,s.visible=!n.hidden&&n.shape.transparency<1,s.visible&&this.paint(s,n,t)}}place(e,t,i){const n=this.frame;if(n)for(const s of this.placed){const r=this.meshes.get(s.sourceId);if(!r||!r.visible)continue;const a=this.extents.get(s.sourceId);if(!a)continue;const{bounds:o}=s.shape;let c=o.x+o.width/2,h=o.y+o.height/2,d=!0;if(s.aim){const u=i(Mr.directionOf(s.aim,this.direction));u&&Math.abs(u.ndcX)<Mr.FURTHEST_NDC&&Math.abs(u.ndcY)<Mr.FURTHEST_NDC?(c=(u.ndcX+1)/2*n.canvasWidthPx,h=(1-u.ndcY)/2*n.canvasHeightPx):d=!1}d?this.curve(r,e,t,n,a,c,h,s.distanceM):this.flat(r,e,n,a,s.distanceM)}}static FURTHEST_NDC=4;curve(e,t,i,n,s,r,a,o){const c=r-s.width/2,h=a-s.height/2,d=e.geometry.attributes.position,u=Mr.SEGMENTS;let p=0;for(let f=0;f<=u;f++){const m=h+f/u*s.height;for(let v=0;v<=u;v++){const g=c+v/u*s.width;i(g/n.canvasWidthPx*2-1,-(m/n.canvasHeightPx*2-1),this.direction),this.vertex.copy(t.position).addScaledVector(this.direction,o),d.setXYZ(p++,this.vertex.x,this.vertex.y,this.vertex.z)}}d.needsUpdate=!0,e.matrixAutoUpdate=!1,e.matrix.identity(),e.matrixWorldNeedsUpdate=!0,e.scale.set(Tt.sizeMAt(o,n.projection.pxToDeg(s.width)),Tt.sizeMAt(o,n.projection.pxToDeg(s.height)),1)}flat(e,t,i,n,s){const r=e.geometry.attributes.position,a=Mr.SEGMENTS,o=Tt.sizeMAt(s,i.projection.pxToDeg(n.width)),c=Tt.sizeMAt(s,i.projection.pxToDeg(n.height));this.up.set(0,1,0).applyQuaternion(t.quaternion),this.centre.copy(t.position).addScaledVector(this.direction,s),this.lookAt.lookAt(t.position,this.centre,this.up),this.right.setFromMatrixColumn(this.lookAt,0),this.above.setFromMatrixColumn(this.lookAt,1);let h=0;for(let d=0;d<=a;d++){const u=.5-d/a;for(let p=0;p<=a;p++){const f=p/a-.5;this.vertex.copy(this.centre).addScaledVector(this.right,f*o).addScaledVector(this.above,u*c),r.setXYZ(h++,this.vertex.x,this.vertex.y,this.vertex.z)}}r.needsUpdate=!0,e.matrixAutoUpdate=!1,e.matrix.identity(),e.matrixWorldNeedsUpdate=!0,e.scale.set(o,c,1)}static SEGMENTS=16;static directionOf(e,t){const i=e.azimuthDeg*Math.PI/180,n=e.altitudeDeg*Math.PI/180;return t.set(Math.sin(i)*Math.cos(n),Math.sin(n),-Math.cos(i)*Math.cos(n))}get any(){for(const e of this.meshes.values())if(e.visible)return!0;return!1}get furthestM(){return this.placed.reduce((e,t)=>Math.max(e,t.distanceM),0)}paint(e,t,i){const{shape:n}=t,s=uh.paintExtent(n),r=t.ghost?3:0,a={x:s.x-r,y:s.y-r,width:s.width+2*r,height:s.height+2*r};this.extents.set(t.sourceId,a);const o=`${Mr.signatureOf(n,i)}|${t.ghost?"ghost":""}`;if(this.signatures.get(t.sourceId)===o&&e.material.map)return;this.signatures.set(t.sourceId,o);const c=Math.min(i.scale,AO/Math.max(a.width,a.height,1)),h=Math.max(1,Math.ceil(a.width*c)),d=Math.max(1,Math.ceil(a.height*c)),u=e.material.map,p=u?.image??document.createElement("canvas"),f=p.width!==h||p.height!==d;f&&(p.width=h,p.height=d);const m=p.getContext("2d");if(!m)return;m.clearRect(0,0,h,d);const v=new uh(m);if(v.setStarPoints(i.starPoints),v.setRoll(i.rollRad),v.paintInto(n,a,c,t.ghost),u&&!f){u.needsUpdate=!0;return}u?.dispose();const g=new Lo(p);g.colorSpace=Bn,g.minFilter=Dt,g.generateMipmaps=!1,e.material.map=g,e.material.needsUpdate=!0}static signatureOf(e,t){const{bounds:i}=e;return JSON.stringify([e.kind,Math.round(i.width*10),Math.round(i.height*10),e.color,e.angle,e.transparency,e.haloScale,e.blur??0,e.brightness??0,e.kind==="polygon"?e.points:void 0,t.scale,t.starPoints,t.rollRad])}dispose(e){e.removeFromParent(),e.geometry.dispose(),e.material.map?.dispose(),e.material.dispose()}clear(){for(const e of this.meshes.values())this.dispose(e);this.meshes.clear(),this.signatures.clear(),this.extents.clear(),this.placed=[]}}function TO(l){const e=new Map,t=new Map,i=l.clone();return $S(l,i,function(n,s){e.set(s,n),t.set(n,s)}),i.traverse(function(n){if(!n.isSkinnedMesh)return;const s=n,r=e.get(n),a=r.skeleton.bones;s.skeleton=r.skeleton.clone(),s.bindMatrix.copy(r.bindMatrix),s.skeleton.bones=a.map(function(o){return t.get(o)}),s.bind(s.skeleton,s.bindMatrix)}),i}function $S(l,e,t){t(l,e);for(let i=0;i<l.children.length;i++)$S(l.children[i],e.children[i],t)}class je{static GROUND_RADIUS_M=636e4;static TOP_RADIUS_M=646e4;static WAVELENGTHS_NM=Array.from({length:15},(e,t)=>410+20*t);static WAVELENGTH_STEP_NM=20;static SOLAR_IRRADIANCE=[1.707,1.676,1.982,2.02,1.941,1.87,1.879,1.856,1.839,1.799,1.728,1.668,1.57,1.532,1.452];static OZONE_CROSS_SECTION=[.021,.069,.19,.418,.827,1.531,2.439,3.291,4.468,4.55,4.663,3.477,2.447,1.658,1.071];static RAYLEIGH_SCALE_HEIGHT_M=8e3;static AEROSOL_SCALE_HEIGHT_M=1200;static OZONE_PEAK_ALTITUDE_M=25e3;static OZONE_HALF_WIDTH_M=15e3;static DEFAULT_AEROSOL_OPTICAL_DEPTH=.1;static DEFAULT_OZONE_DOBSON=300;static AEROSOL_SINGLE_SCATTERING_ALBEDO=.9;static AEROSOL_ANGSTROM_EXPONENT=1.3;static AEROSOL_ASYMMETRY=.8;rayleighScattering;aerosolScattering;aerosolExtinction;ozoneAbsorption;constructor(e={}){const t=je.WAVELENGTHS_NM.length,i=e.aerosolOpticalDepth??je.DEFAULT_AEROSOL_OPTICAL_DEPTH,n=e.ozoneDobson??je.DEFAULT_OZONE_DOBSON;this.rayleighScattering=new Float64Array(t),this.aerosolScattering=new Float64Array(t),this.aerosolExtinction=new Float64Array(t),this.ozoneAbsorption=new Float64Array(t);const s=n*2687e17/je.OZONE_HALF_WIDTH_M;for(let r=0;r<t;r++){const a=je.WAVELENGTHS_NM[r];this.rayleighScattering[r]=je.rayleighAt(a);const o=i/je.AEROSOL_SCALE_HEIGHT_M*(a/550)**-1.3;this.aerosolExtinction[r]=o,this.aerosolScattering[r]=o*je.AEROSOL_SINGLE_SCATTERING_ALBEDO,this.ozoneAbsorption[r]=je.OZONE_CROSS_SECTION[r]*1e-25*s}}static rayleighAt(e){const t=e/1e3,i=1/(t*t),n=t*t;return(1.0455996-341.29061*i-.9023085*n)/(1+.0027059889*i-85.968563*n)*1e-28*1e-4*2546899e19}static rayleighDensity(e){return Math.exp(-Math.max(e,0)/je.RAYLEIGH_SCALE_HEIGHT_M)}static aerosolDensity(e){return Math.exp(-Math.max(e,0)/je.AEROSOL_SCALE_HEIGHT_M)}static ozoneDensity(e){return Math.max(0,1-Math.abs(e-je.OZONE_PEAK_ALTITUDE_M)/je.OZONE_HALF_WIDTH_M)}static rayleighPhase(e){return 3/(16*Math.PI)*(1+e*e)}static aerosolPhase(e,t=je.AEROSOL_ASYMMETRY){const i=t*t;return 3/(8*Math.PI)*(1-i)*(1+e*e)/((2+i)*Math.pow(Math.max(1+i-2*t*e,1e-6),1.5))}}class it{static TRANSMITTANCE_WIDTH=256;static TRANSMITTANCE_HEIGHT=64;static MULTIPLE_SIZE=64;static MULTIPLE_ROWS=16;static MULTIPLE_HEIGHT_POWER=2;static MULTIPLE_DIRECTIONS=16;static SKY_VIEW_WIDTH=192;static SKY_VIEW_HEIGHT=108;static STEPS=40;static MULTIPLE_STEPS=12;static GROUND_ALBEDO=.3;supported;renderer;transmittance;multiple;sunView;moonView;scene=new Or;camera=new fr(-1,1,1,-1,0,1);quad;transmittanceMaterial;multipleMaterial;skyViewMaterial;transmittanceReady=!1;multipleRows=0;multipleColumn=0;mediumKey="";static MULTIPLE_BLOCK=16;static shared=new Map;building=!1;adopted;tableUniforms;constructor(e){this.renderer=e,this.supported=e.capabilities.isWebGL2&&e.extensions.has("EXT_color_buffer_float"),this.transmittance=new yi(it.TRANSMITTANCE_WIDTH,it.TRANSMITTANCE_HEIGHT,{count:4,type:Jt,minFilter:Dt,magFilter:Dt,depthBuffer:!1}),this.multiple=new yi(it.MULTIPLE_SIZE,it.MULTIPLE_ROWS,{count:4,type:is,minFilter:pi,magFilter:pi,depthBuffer:!1});const t=()=>new yi(it.SKY_VIEW_WIDTH,it.SKY_VIEW_HEIGHT,{type:is,minFilter:pi,magFilter:pi,depthBuffer:!1});this.sunView=t(),this.moonView=t();const i=it.mediumUniforms(),n=this.tableUniforms={uT0:{value:this.transmittance.textures[0]},uT1:{value:this.transmittance.textures[1]},uT2:{value:this.transmittance.textures[2]},uT3:{value:this.transmittance.textures[3]},uM0:{value:this.multiple.textures[0]},uM1:{value:this.multiple.textures[1]},uM2:{value:this.multiple.textures[2]},uM3:{value:this.multiple.textures[3]}},s=(r,a={})=>new gS({glslVersion:xf,uniforms:{...i,...n,...a},vertexShader:it.VERTEX,fragmentShader:r,depthTest:!1,depthWrite:!1});this.transmittanceMaterial=s(it.TRANSMITTANCE_FRAGMENT),this.multipleMaterial=s(it.MULTIPLE_FRAGMENT),this.skyViewMaterial=s(it.SKY_VIEW_FRAGMENT,{uObserverRadius:{value:je.GROUND_RADIUS_M+2},uSourceMu:{value:1}}),this.quad=new xe(new xs(2,2),this.transmittanceMaterial),this.quad.frustumCulled=!1,this.scene.add(this.quad)}get transmittanceTextures(){return this.transmittance.textures}get sunViewTexture(){return this.sunView.texture}get moonViewTexture(){return this.moonView.texture}get ready(){return this.supported&&(this.adopted!==void 0||this.transmittanceReady&&this.multipleRows>=it.MULTIPLE_ROWS)}setMedium(e){const t=[e.rayleighScattering,e.aerosolScattering,e.aerosolExtinction,e.ozoneAbsorption].map(n=>Array.from(n,s=>s.toPrecision(6)).join(",")).join("|");if(t===this.mediumKey)return;this.abandonBuilding(),this.releaseAdopted(),this.mediumKey=t;const i=(n,s)=>{const r=this.transmittanceMaterial.uniforms[n].value;for(let a=0;a<4;a++)r[a].set(s[a*4]??0,s[a*4+1]??0,s[a*4+2]??0,s[a*4+3]??0)};i("uRayleigh",e.rayleighScattering),i("uAerosolScattering",e.aerosolScattering),i("uAerosolExtinction",e.aerosolExtinction),i("uOzone",e.ozoneAbsorption),this.transmittanceReady=!1,this.multipleRows=0,this.multipleColumn=0}invalidate(){this.adopted||(this.abandonBuilding(),this.transmittanceReady=!1,this.multipleRows=0,this.multipleColumn=0)}advance(e){if(!this.supported||!this.mediumKey)return!1;if(this.ready)return!0;const t=it.shared.get(this.mediumKey);if(t&&t!=="building")return this.adopt(t),!0;if(t==="building"&&!this.building)return!1;t||(it.shared.set(this.mediumKey,"building"),this.building=!0);const i=this.renderer.getRenderTarget();let n=Math.max(1,e);this.transmittanceReady||(this.draw(this.transmittanceMaterial,this.transmittance),this.transmittanceReady=!0,n--);const s=it.MULTIPLE_SIZE,r=it.MULTIPLE_BLOCK;for(;n>0&&this.multipleRows<it.MULTIPLE_ROWS;n--)this.multiple.scissor.set(this.multipleColumn,this.multipleRows,r,1),this.multiple.scissorTest=!0,this.draw(this.multipleMaterial,this.multiple),this.multipleColumn+=r,this.multipleColumn>=s&&(this.multipleColumn=0,this.multipleRows++);return this.multiple.scissorTest=!1,this.renderer.setRenderTarget(i),this.ready&&this.building&&this.share(this.mediumKey),this.ready}async share(e){this.building=!1;try{const t=await Promise.all([0,1,2,3].map(n=>this.readRaw(this.transmittance,n,Uint16Array))),i=await Promise.all([0,1,2,3].map(n=>this.readRaw(this.multiple,n,Float32Array)));this.mediumKey===e?it.shared.set(e,{transmittance:t,multiple:i}):it.shared.delete(e)}catch{it.shared.delete(e)}}async readRaw(e,t,i){const n=new i(e.width*e.height*4);return await this.renderer.readRenderTargetPixelsAsync(e,0,0,e.width,e.height,n,void 0,t),n}adopt(e){const t=(s,r,a,o)=>{const c=new Qs(s,r,a,bn,o?Jt:is);return c.minFilter=c.magFilter=o?Dt:pi,c.needsUpdate=!0,c},i=e.transmittance.map(s=>t(s,it.TRANSMITTANCE_WIDTH,it.TRANSMITTANCE_HEIGHT,!0)),n=e.multiple.map(s=>t(s,it.MULTIPLE_SIZE,it.MULTIPLE_ROWS,!1));i.forEach((s,r)=>this.tableUniforms[`uT${r}`].value=s),n.forEach((s,r)=>this.tableUniforms[`uM${r}`].value=s),this.adopted=[...i,...n]}releaseAdopted(){if(this.adopted){for(const e of this.adopted)e.dispose();this.adopted=void 0;for(let e=0;e<4;e++)this.tableUniforms[`uT${e}`].value=this.transmittance.textures[e],this.tableUniforms[`uM${e}`].value=this.multiple.textures[e]}}abandonBuilding(){this.building&&(this.building=!1,it.shared.get(this.mediumKey)==="building"&&it.shared.delete(this.mediumKey))}renderSkyViews(e,t,i){if(!this.ready)return;const n=this.renderer.getRenderTarget(),s=this.skyViewMaterial.uniforms;s.uObserverRadius.value=je.GROUND_RADIUS_M+Math.max(e,2),s.uSourceMu.value=Math.sin(t*Math.PI/180),this.draw(this.skyViewMaterial,this.sunView),s.uSourceMu.value=Math.sin(i*Math.PI/180),this.draw(this.skyViewMaterial,this.moonView),this.renderer.setRenderTarget(n)}static skyViewUv(e,t,i){const n=je.GROUND_RADIUS_M+Math.max(e,2),s=je.GROUND_RADIUS_M,r=Math.acos(Math.min(Math.sqrt(Math.max(n*n-s*s,0))/n,1)),a=Math.PI-r,o=t<a?.5*(1-Math.sqrt(Math.max(1-t/a,0))):.5+.5*Math.sqrt(Math.min((t-a)/r,1));return{u:Math.min(Math.max(Math.abs(i)/Math.PI,0),1),v:o}}async readTable(e,t){if(e==="multiple"){const s=new Float32Array(this.multiple.width*this.multiple.height*4);return await this.renderer.readRenderTargetPixelsAsync(this.multiple,0,0,this.multiple.width,this.multiple.height,s,void 0,t),s}const i=this.transmittance,n=new Uint16Array(i.width*i.height*4);return await this.renderer.readRenderTargetPixelsAsync(i,0,0,i.width,i.height,n,void 0,t),Float32Array.from(n,s=>js.fromHalfFloat(s))}readSkyViewNow(e){const t=e==="sun"?this.sunView:this.moonView,i=new Float32Array(t.width*t.height*4),n=this.renderer.getContext();return n.bindBuffer(n.PIXEL_PACK_BUFFER,null),this.renderer.readRenderTargetPixels(t,0,0,t.width,t.height,i),i}async readSkyView(e){const t=e==="sun"?this.sunView:this.moonView,i=new Float32Array(t.width*t.height*4);return await this.renderer.readRenderTargetPixelsAsync(t,0,0,t.width,t.height,i),i}dispose(){this.abandonBuilding(),this.releaseAdopted(),this.transmittance.dispose(),this.multiple.dispose(),this.sunView.dispose(),this.moonView.dispose(),this.transmittanceMaterial.dispose(),this.multipleMaterial.dispose(),this.skyViewMaterial.dispose(),this.quad.geometry.dispose()}draw(e,t){this.quad.material=e,this.renderer.setRenderTarget(t),this.renderer.render(this.scene,this.camera)}static mediumUniforms(){const e=()=>[new Ot,new Ot,new Ot,new Ot],t=(i,n)=>{const s=e();return je.WAVELENGTHS_NM.forEach((r,a)=>{s[Math.floor(a/4)].setComponent(a%4,i(r)*n*je.WAVELENGTH_STEP_NM*je.SOLAR_IRRADIANCE[a])}),s};return{uRayleigh:{value:e()},uAerosolScattering:{value:e()},uAerosolExtinction:{value:e()},uOzone:{value:e()},uCieX:{value:t(i=>En.colourMatching(i)[0],683)},uCieY:{value:t(i=>En.colourMatching(i)[1],683)},uCieZ:{value:t(i=>En.colourMatching(i)[2],683)},uScotopic:{value:t(i=>En.scotopic(i),1700)}}}static VERTEX=`
10669
10669
  in vec3 position;
10670
10670
  void main() {
10671
10671
  gl_Position = vec4(position.xy, 0.0, 1.0);
@@ -10941,7 +10941,7 @@ cloudPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let
10941
10941
  }
10942
10942
  outColor = xyzs;
10943
10943
  }
10944
- `}class Et{static AIRGLOW_LAYER_ALTITUDE_M=9e4;static SUN_MAGNITUDE=-26.74;tables;material;onChange;state;drawnKey="";hasViews=!1;adaptingLuminance=1;get adaptation(){return this.adaptingLuminance*this.exposureScale}get sceneAdaptation(){return this.adaptingLuminance}ambientColours;reading=!1;exposureScale=1;filterScale=1;seenByEye=!0;readAgain=!1;constructor(e,t){this.onChange=t,this.tables=new it(e),this.tables.setMedium(new je),this.material=new Ct({glslVersion:xf,side:Hi,depthWrite:!1,uniforms:{uSunView:{value:this.tables.sunViewTexture},uMoonView:{value:this.tables.moonViewTexture},uSunAzimuth:{value:new ne(0,-1)},uMoonAzimuth:{value:new ne(0,-1)},uMoonScale:{value:0},uSunScale:{value:1},uUmbraGlow:{value:0},uUmbraExcess:{value:new Array(Et.UMBRA_AZIMUTHS).fill(0)},uUmbraTint:{value:new _(0,1,0)},uUmbraRefUv:{value:new ne(.5,.5)},uObserverRadius:{value:je.GROUND_RADIUS_M+2},uAirglow:{value:new Ot(...Et.airglowXyzs())},uArtificial:{value:new Ot(0,0,0,0)},uRodShare:{value:0},uInverseSemiSaturation:{value:1},uExposureScale:{value:1}},vertexShader:`
10944
+ `}class At{static AIRGLOW_LAYER_ALTITUDE_M=9e4;static SUN_MAGNITUDE=-26.74;tables;material;onChange;state;drawnKey="";hasViews=!1;adaptingLuminance=1;get adaptation(){return this.adaptingLuminance*this.exposureScale}get sceneAdaptation(){return this.adaptingLuminance}ambientColours;reading=!1;exposureScale=1;filterScale=1;seenByEye=!0;readAgain=!1;constructor(e,t){this.onChange=t,this.tables=new it(e),this.tables.setMedium(new je),this.material=new Ct({glslVersion:xf,side:Hi,depthWrite:!1,uniforms:{uSunView:{value:this.tables.sunViewTexture},uMoonView:{value:this.tables.moonViewTexture},uSunAzimuth:{value:new ne(0,-1)},uMoonAzimuth:{value:new ne(0,-1)},uMoonScale:{value:0},uSunScale:{value:1},uUmbraGlow:{value:0},uUmbraExcess:{value:new Array(At.UMBRA_AZIMUTHS).fill(0)},uUmbraTint:{value:new _(0,1,0)},uUmbraRefUv:{value:new ne(.5,.5)},uObserverRadius:{value:je.GROUND_RADIUS_M+2},uAirglow:{value:new Ot(...At.airglowXyzs())},uArtificial:{value:new Ot(0,0,0,0)},uRodShare:{value:0},uInverseSemiSaturation:{value:1},uExposureScale:{value:1}},vertexShader:`
10945
10945
  varying vec3 vDirection;
10946
10946
  void main() {
10947
10947
  vDirection = (modelMatrix * vec4(position, 1.0)).xyz - cameraPosition;
@@ -10960,7 +10960,7 @@ cloudPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let
10960
10960
  uniform float uMoonScale;
10961
10961
  uniform float uSunScale;
10962
10962
  uniform float uUmbraGlow;
10963
- uniform float uUmbraExcess[${Et.UMBRA_AZIMUTHS}];
10963
+ uniform float uUmbraExcess[${At.UMBRA_AZIMUTHS}];
10964
10964
  uniform vec3 uUmbraTint;
10965
10965
  uniform vec2 uUmbraRefUv;
10966
10966
  uniform float uObserverRadius;
@@ -10970,9 +10970,9 @@ cloudPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let
10970
10970
  uniform float uInverseSemiSaturation;
10971
10971
  uniform float uExposureScale;
10972
10972
  const float PI = 3.141592653589793;
10973
- const float UMBRA_GLOW_SCALE_DEG = ${Et.UMBRA_GLOW_SCALE_DEG.toFixed(2)};
10973
+ const float UMBRA_GLOW_SCALE_DEG = ${At.UMBRA_GLOW_SCALE_DEG.toFixed(2)};
10974
10974
  const float GROUND = ${je.GROUND_RADIUS_M.toFixed(1)};
10975
- const float AIRGLOW_RATIO = ${(je.GROUND_RADIUS_M/(je.GROUND_RADIUS_M+Et.AIRGLOW_LAYER_ALTITUDE_M)).toFixed(6)};
10975
+ const float AIRGLOW_RATIO = ${(je.GROUND_RADIUS_M/(je.GROUND_RADIUS_M+At.AIRGLOW_LAYER_ALTITUDE_M)).toFixed(6)};
10976
10976
  const float EXTINCTION = ${de.EXTINCTION_PER_AIR_MASS.toFixed(4)};
10977
10977
  const float ARTIFICIAL_ZENITH_FRACTION = ${de.scatteredFraction(90).toFixed(6)};
10978
10978
  const vec2 VIEW_SIZE = vec2(${it.SKY_VIEW_WIDTH}.0, ${it.SKY_VIEW_HEIGHT}.0);
@@ -11026,9 +11026,9 @@ cloudPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let
11026
11026
  float glowProfile = exp(-degrees(asin(clamp(dir.y, 0.0, 1.0))) / UMBRA_GLOW_SCALE_DEG);
11027
11027
  // Round the horizon by azimuth: north is -z and east +x (see azimuthVector).
11028
11028
  float turns = fract(atan(dir.x, -dir.z) / (2.0 * PI));
11029
- float at = turns * float(${Et.UMBRA_AZIMUTHS});
11029
+ float at = turns * float(${At.UMBRA_AZIMUTHS});
11030
11030
  int below = int(floor(at));
11031
- int above = below + 1 == ${Et.UMBRA_AZIMUTHS} ? 0 : below + 1;
11031
+ int above = below + 1 == ${At.UMBRA_AZIMUTHS} ? 0 : below + 1;
11032
11032
  float excess = mix(uUmbraExcess[below], uUmbraExcess[above], fract(at));
11033
11033
  light += excess * glowProfile * vec4(reference.y * uUmbraTint, reference.w);
11034
11034
  }
@@ -11044,7 +11044,7 @@ cloudPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let
11044
11044
  gl_FragColor = vec4(relativeOf(light.xyz, light.w), 1.0);
11045
11045
  #include <colorspace_fragment>
11046
11046
  }
11047
- `})}get supported(){return this.tables.supported}get ready(){return this.hasViews}get ambient(){return this.ready?this.ambientColours:void 0}setInstrument(e,t,i=0){const n=e?10**(.4*t):1,s=10**-i;n===this.exposureScale&&s===this.filterScale&&this.seenByEye===!e||(this.exposureScale=n,this.filterScale=s,this.seenByEye=!e,this.material.uniforms.uExposureScale.value=n*s,this.applyAdaptation(this.adaptingLuminance),this.onChange())}setConditions(e){this.tables.setMedium(new je(e)),this.tables.ready||(this.drawnKey="")}advance(e){!this.supported||this.tables.ready||this.tables.advance(e)&&this.state&&this.draw(this.state)}invalidate(){this.tables.invalidate(),this.drawnKey="",this.hasViews=!1}update(e){this.state=e,this.tables.ready?this.draw(e):this.hasViews||this.applyAdaptation(Et.predictedZenithLuminance(e))}dispose(){this.tables.dispose(),this.material.dispose()}draw(e){const t=[e.altitudeM.toFixed(0),e.sun.altitudeDeg.toFixed(3),e.moon.altitudeDeg.toFixed(3),e.lightPollution??""].join(":"),i=this.material.uniforms;i.uArtificial.value.set(...Et.artificialXyzs(e.lightPollution)),i.uSunAzimuth.value.copy(Et.azimuthVector(e.sun.azimuthDeg)),i.uMoonAzimuth.value.copy(Et.azimuthVector(e.moon.azimuthDeg)),i.uMoonScale.value=10**(-.4*(e.moon.magnitude-Et.SUN_MAGNITUDE));const n=this.effectiveSunScale(e);i.uSunScale.value=n;const s=Et.excessOf(e,n),r=s.reduce((o,c)=>o+c,0);if(i.uUmbraGlow.value=r,e.umbra){i.uUmbraExcess.value=s,i.uUmbraTint.value.set(...e.umbra.tint);const o=Et.umbraReferenceUv(e);i.uUmbraRefUv.value.set(o.u,o.v)}i.uObserverRadius.value=je.GROUND_RADIUS_M+Math.max(e.altitudeM,2);const a=t!==this.drawnKey;if(a){this.tables.renderSkyViews(e.altitudeM,e.sun.altitudeDeg,e.moon.altitudeDeg);const o=!this.hasViews;this.hasViews=!0,this.drawnKey=t,o&&!this.ambientColours&&this.adaptFromViews(this.tables.readSkyViewNow("sun"),this.tables.readSkyViewNow("moon"),e),this.readBack()}(n!==this.drawnSunScale||r!==this.drawnGlow)&&(this.drawnSunScale=n,this.drawnGlow=r,this.views&&!a&&this.adaptFromViews(this.views.sun,this.views.moon,e)),this.onChange()}drawnSunScale=1;drawnGlow=0;dayZenithY;effectiveSunScale(e){const t=e.sunLight??1;return e.zenithFloorCdM2?Math.max(t,e.zenithFloorCdM2/(this.dayZenithY??Et.ASSUMED_DAY_ZENITH_CD_M2)):t}static ASSUMED_DAY_ZENITH_CD_M2=3e3;static excessOf(e,t){return e.umbra?e.umbra.share.map(i=>Math.max(0,i-t)):[]}static UMBRA_AZIMUTHS=24;static excessAt(e,t){const i=e.length,n=(t/360*i%i+i)%i,s=Math.floor(n),r=n-s;return e[s]*(1-r)+e[(s+1)%i]*r}static UMBRA_GLOW_SCALE_DEG=5;static umbraReferenceUv(e){return it.skyViewUv(e.altitudeM,89*Math.PI/180,Et.azimuthBetween(e.sun.azimuthDeg+100,e.sun.azimuthDeg))}async readBack(){if(this.reading){this.readAgain=!0;return}this.reading=!0;let e=!1;try{const[t,i]=await Promise.all([this.tables.readSkyView("sun"),this.tables.readSkyView("moon")]),n=this.state;n&&this.adaptFromViews(t,i,n)}catch{e=!0,this.drawnKey=""}finally{this.reading=!1}if(e){this.readAgain=!1;return}this.readAgain&&(this.readAgain=!1,this.readBack())}adaptToSurroundings(e){if(!(e>0)||!(this.clearAdaptation>0))return!1;const t=e/this.clearAdaptation;return Math.abs(Math.log(t/this.surroundingsFactor))<.05?!1:(this.surroundingsFactor=t,this.views&&this.state?this.adaptFromViews(this.views.sun,this.views.moon,this.state):this.applyAdaptation(this.clearAdaptation*t),!0)}resetSurroundings(){this.surroundingsFactor=1}surroundingsFactor=1;clearAdaptation=0;views;adaptFromViews(e,t,i){this.views={sun:e,moon:t};const n=10**(-.4*(i.moon.magnitude-Et.SUN_MAGNITUDE)),s=it.skyViewUv(i.altitudeM,0,0);this.dayZenithY=Et.bilinear(e,s.u,s.v)[1];const r=this.effectiveSunScale(i),a=i.umbra?{excess:Et.excessOf(i,r),tint:i.umbra.tint}:void 0;let o;if(a&&a.excess.some(E=>E>0)){const E=Et.umbraReferenceUv(i);o=Et.bilinear(e,E.u,E.v)}const c=Et.airglowXyzs(),h=Et.artificialXyzs(i.lightPollution),d=(E,x,T=!0)=>{const D=(90-E)*Math.PI/180,R=it.skyViewUv(i.altitudeM,D,Et.azimuthBetween(x,i.sun.azimuthDeg)),O=it.skyViewUv(i.altitudeM,D,Et.azimuthBetween(x,i.moon.azimuthDeg)),N=Et.bilinear(e,R.u,R.v),C=Et.bilinear(t,O.u,O.v),k=T&&E>0?Et.airglowFactor(E):0,P=E>0?de.artificialShape(E):0,F=o&&a&&E>0?Et.excessAt(a.excess,x)*Math.exp(-E/Et.UMBRA_GLOW_SCALE_DEG):0,G=Y=>!o||!a?0:F*(Y<3?o[1]*a.tint[Y]:o[3]);return[0,1,2,3].map(Y=>r*N[Y]+n*C[Y]+c[Y]*k+h[Y]*P+G(Y))};let u=0,p=0;for(let E=5;E<90;E+=10){const x=Math.cos(E*Math.PI/180);for(let T=0;T<360;T+=30)u+=x*Math.log(Math.max(d(E,T)[1],1e-9)),p+=x}this.clearAdaptation=Math.exp(u/p),this.applyAdaptation(this.clearAdaptation*this.surroundingsFactor);const f=([E,x,T,D])=>{const R=this.exposureScale*this.filterScale,O=this.adaptingLuminance*this.exposureScale;return Fe.relativeOf([E*R,x*R,T*R],D*R,O,0)},m=(E,x,T=!0)=>f(d(E,x,T)),v=[0,0,0,0],g=5*Math.PI/180,y=20*Math.PI/180;for(let E=2.5;E<90;E+=5){const x=E*Math.PI/180,T=Math.sin(x)*Math.cos(x)*g*y;for(let D=10;D<360;D+=20){const R=d(E,D);for(let O=0;O<4;O++)v[O]+=R[O]*T}}const w=[0,0,0],b=[0,0,0];for(let E=0;E<360;E+=20){const x=m(2,E),T=m(2,E,!1);for(let D=0;D<3;D++)w[D]+=x[D]/18,b[D]+=T[D]/18}const M=this.ambientColours,S=this.announcedAdaptation;this.ambientColours={zenith:m(90,0),horizon:w,airlight:b,skyIrradiance:f(v),scale:this.relativeScale},this.announcedAdaptation=this.adaptingLuminance,!(M&&Et.alike(S,this.adaptingLuminance)&&M.zenith.every((E,x)=>Et.alike(E,this.ambientColours.zenith[x]))&&M.horizon.every((E,x)=>Et.alike(E,w[x])))&&this.onChange()}announcedAdaptation=0;static alike(e,t){return e===t||Math.abs(e-t)<=.01*Math.max(Math.abs(e),Math.abs(t))}relativeOfLuminance(e,t){const[i,n,s]=e,r=.2126*i+.7152*n+.0722*s,a=r>0?t/r:0,o=[a*(.4124*i+.3576*n+.1805*s),t,a*(.0193*i+.1192*n+.9505*s)],c=this.exposureScale*this.filterScale,h=this.adaptingLuminance*this.exposureScale;return Fe.relativeOf([o[0]*c,o[1]*c,o[2]*c],o[1]*c,h,0)}get recorded(){return!this.seenByEye}get rodShare(){const e=this.adaptingLuminance*this.exposureScale;return this.seenByEye?Fe.rodShare(e):0}get relativeScale(){const e=this.adaptingLuminance*this.exposureScale;return this.exposureScale*this.filterScale/Fe.semiSaturation(e)}applyAdaptation(e){this.adaptingLuminance=e;const t=e*this.exposureScale;this.material.uniforms.uRodShare.value=0,this.material.uniforms.uInverseSemiSaturation.value=1/Fe.semiSaturation(t)}static predictedZenithLuminance(e){const t=n=>90-n.altitudeDeg,i=de.magPerArcsec2({altitudeDeg:e.sun.altitudeDeg,separationDeg:t(e.sun)},{phaseAngleDeg:e.moon.phaseAngleDeg,altitudeDeg:e.moon.altitudeDeg,separationDeg:t(e.moon)},90,e.lightPollution);return de.toNanolamberts(i)*Et.CANDELAS_PER_NANOLAMBERT}static CANDELAS_PER_NANOLAMBERT=1e-5/Math.PI;static airglowXyzs(){const e=de.toNanolamberts(de.AIRGLOW_MAG_PER_ARCSEC2)*Et.CANDELAS_PER_NANOLAMBERT;return[e*.3127/.329,e,e*(1-.3127-.329)/.329,e]}static artificialXyzs(e){const t=de.artificialZenithNanolamberts(e)*Et.CANDELAS_PER_NANOLAMBERT;return[t*.4369/.4041,t,t*(1-.4369-.4041)/.4041,t]}static airglowFactor(e){const t=Math.cos(e*Math.PI/180)**2,i=je.GROUND_RADIUS_M/(je.GROUND_RADIUS_M+Et.AIRGLOW_LAYER_ALTITUDE_M),n=1/Math.sqrt(Math.max(1-i*i*t,1e-4)),s=1/Math.sqrt(Math.max(1-.96*t,.001));return n*10**(-.4*de.EXTINCTION_PER_AIR_MASS*(s-1))}static azimuthVector(e){const t=e*Math.PI/180;return new ne(Math.sin(t),-Math.cos(t))}static azimuthBetween(e,t){const i=Math.abs(e-t)%360;return(i>180?360-i:i)*Math.PI/180}static bilinear(e,t,i){const n=it.SKY_VIEW_WIDTH,s=it.SKY_VIEW_HEIGHT,r=Math.min(Math.max(t*n-.5,0),n-1),a=Math.min(Math.max(i*s-.5,0),s-1),o=Math.floor(r),c=Math.floor(a),h=Math.min(o+1,n-1),d=Math.min(c+1,s-1),u=r-o,p=a-c,f=(m,v,g)=>e[(m*n+v)*4+g];return[0,1,2,3].map(m=>(f(c,o,m)*(1-u)+f(c,h,m)*u)*(1-p)+(f(d,o,m)*(1-u)+f(d,h,m)*u)*p)}}class Oa{static DRY_OPTICAL_DEPTH=.08;static GROWTH_EXPONENT=.3;static MAX_RELATIVE_HUMIDITY=.95;static OPTICAL_DEPTH_STEP=.02;static relativeHumidity(e,t){const i=n=>Math.exp(17.625*n/(243.04+n));return Math.min(Math.max(i(t)/i(e),0),1)}static opticalDepth(e){const t=Math.min(Math.max(e,0),Oa.MAX_RELATIVE_HUMIDITY);return Oa.DRY_OPTICAL_DEPTH*(1-t)**-.3}static steppedOpticalDepth(e){const t=Oa.OPTICAL_DEPTH_STEP;return Math.round(Oa.opticalDepth(e)/t)*t}}class ar{static CHANNEL_WAVELENGTHS_NM=[680,550,440];static KOSCHMIEDER=-Math.log(.02);static PRECIPITATION_EXTINCTION_PER_KM={rain:{a:.365,b:.63},snow:{a:1.023,b:.72},hail:{a:.365,b:.63}};static FULL_INTENSITY_MM_PER_H=8;rayleigh;aerosol;constructor(e=je.DEFAULT_AEROSOL_OPTICAL_DEPTH,t=0){const[i,n,s]=ar.CHANNEL_WAVELENGTHS_NM;this.rayleigh=[je.rayleighAt(i),je.rayleighAt(n),je.rayleighAt(s)];const r=a=>e/je.AEROSOL_SCALE_HEIGHT_M*(a/550)**-1.3;this.aerosol=[r(i)+t,r(n)+t,r(s)+t],this.precipitationPerM=t}precipitationPerM;static of(e){const t=e.relativeHumidity===void 0?void 0:Oa.opticalDepth(e.relativeHumidity);return new ar(t,ar.precipitationExtinction(e))}static precipitationExtinction(e){const t=e.precipitationIntensity*(e.precipitationAmount??1);if(e.precipitationType==="none"||!(t>0))return 0;const i=ar.PRECIPITATION_EXTINCTION_PER_KM[e.precipitationType],n=t*ar.FULL_INTENSITY_MM_PER_H;return i.a*n**i.b/1e3}transmittance(e,t,i){const n=ar.meanDensity(e,t,je.RAYLEIGH_SCALE_HEIGHT_M),s=ar.meanDensity(e,t,je.AEROSOL_SCALE_HEIGHT_M);return[0,1,2].map(r=>Math.exp(-(this.rayleigh[r]*n+this.aerosol[r]*s)*i))}transmittanceFromSpace(e,t){const i=Math.max(t,0),n=1/(Math.sin(i*Math.PI/180)+.50572*(i+6.07995)**-1.6364),s=je.RAYLEIGH_SCALE_HEIGHT_M*je.rayleighDensity(e),r=je.AEROSOL_SCALE_HEIGHT_M*je.aerosolDensity(e);return[0,1,2].map(a=>Math.exp(-(this.rayleigh[a]*s+(this.aerosol[a]-this.precipitationPerM)*r)*n))}extinctionAt(e){return{rayleigh:this.rayleigh[1]*je.rayleighDensity(e),aerosol:this.aerosol[1]*je.aerosolDensity(e)}}visibilityM(e){const{rayleigh:t,aerosol:i}=this.extinctionAt(e);return ar.KOSCHMIEDER/(t+i)}get rayleighRatios(){return[this.rayleigh[0]/this.rayleigh[1],1,this.rayleigh[2]/this.rayleigh[1]]}static meanDensity(e,t,i){const n=Math.max(e,0),s=Math.max(t,0),r=s-n;return Math.abs(r)<.01?Math.exp(-n/i):i*(Math.exp(-n/i)-Math.exp(-s/i))/r}}class Cl extends wb{constructor(){super(new re(0,0,0),0,0),Cl.install()}setAir(e,t,i){const{rayleigh:n,aerosol:s}=e.extinctionAt(t);this.near=n,this.far=s,this.color.setRGB(i[0],i[1],i[2])}static fadeRim(e,t,i){e.transparent=!0,e.onBeforeCompile=n=>{n.fragmentShader=n.fragmentShader.replace("#include <fog_fragment>",`#include <fog_fragment>
11047
+ `})}get supported(){return this.tables.supported}get ready(){return this.hasViews}get ambient(){return this.ready?this.ambientColours:void 0}setInstrument(e,t,i=0){const n=e?10**(.4*t):1,s=10**-i;n===this.exposureScale&&s===this.filterScale&&this.seenByEye===!e||(this.exposureScale=n,this.filterScale=s,this.seenByEye=!e,this.material.uniforms.uExposureScale.value=n*s,this.applyAdaptation(this.adaptingLuminance),this.onChange())}setConditions(e){this.tables.setMedium(new je(e)),this.tables.ready||(this.drawnKey="")}advance(e){!this.supported||this.tables.ready||this.tables.advance(e)&&this.state&&this.draw(this.state)}invalidate(){this.tables.invalidate(),this.drawnKey="",this.hasViews=!1}update(e){this.state=e,this.tables.ready?this.draw(e):this.hasViews||this.applyAdaptation(At.predictedZenithLuminance(e))}dispose(){this.tables.dispose(),this.material.dispose()}draw(e){const t=[e.altitudeM.toFixed(0),e.sun.altitudeDeg.toFixed(3),e.moon.altitudeDeg.toFixed(3),e.lightPollution??""].join(":"),i=this.material.uniforms;i.uArtificial.value.set(...At.artificialXyzs(e.lightPollution)),i.uSunAzimuth.value.copy(At.azimuthVector(e.sun.azimuthDeg)),i.uMoonAzimuth.value.copy(At.azimuthVector(e.moon.azimuthDeg)),i.uMoonScale.value=10**(-.4*(e.moon.magnitude-At.SUN_MAGNITUDE));const n=this.effectiveSunScale(e);i.uSunScale.value=n;const s=At.excessOf(e,n),r=s.reduce((o,c)=>o+c,0);if(i.uUmbraGlow.value=r,e.umbra){i.uUmbraExcess.value=s,i.uUmbraTint.value.set(...e.umbra.tint);const o=At.umbraReferenceUv(e);i.uUmbraRefUv.value.set(o.u,o.v)}i.uObserverRadius.value=je.GROUND_RADIUS_M+Math.max(e.altitudeM,2);const a=t!==this.drawnKey;if(a){this.tables.renderSkyViews(e.altitudeM,e.sun.altitudeDeg,e.moon.altitudeDeg);const o=!this.hasViews;this.hasViews=!0,this.drawnKey=t,o&&!this.ambientColours&&this.adaptFromViews(this.tables.readSkyViewNow("sun"),this.tables.readSkyViewNow("moon"),e),this.readBack()}(n!==this.drawnSunScale||r!==this.drawnGlow)&&(this.drawnSunScale=n,this.drawnGlow=r,this.views&&!a&&this.adaptFromViews(this.views.sun,this.views.moon,e)),this.onChange()}drawnSunScale=1;drawnGlow=0;dayZenithY;effectiveSunScale(e){const t=e.sunLight??1;return e.zenithFloorCdM2?Math.max(t,e.zenithFloorCdM2/(this.dayZenithY??At.ASSUMED_DAY_ZENITH_CD_M2)):t}static ASSUMED_DAY_ZENITH_CD_M2=3e3;static excessOf(e,t){return e.umbra?e.umbra.share.map(i=>Math.max(0,i-t)):[]}static UMBRA_AZIMUTHS=24;static excessAt(e,t){const i=e.length,n=(t/360*i%i+i)%i,s=Math.floor(n),r=n-s;return e[s]*(1-r)+e[(s+1)%i]*r}static UMBRA_GLOW_SCALE_DEG=5;static umbraReferenceUv(e){return it.skyViewUv(e.altitudeM,89*Math.PI/180,At.azimuthBetween(e.sun.azimuthDeg+100,e.sun.azimuthDeg))}async readBack(){if(this.reading){this.readAgain=!0;return}this.reading=!0;let e=!1;try{const[t,i]=await Promise.all([this.tables.readSkyView("sun"),this.tables.readSkyView("moon")]),n=this.state;n&&this.adaptFromViews(t,i,n)}catch{e=!0,this.drawnKey=""}finally{this.reading=!1}if(e){this.readAgain=!1;return}this.readAgain&&(this.readAgain=!1,this.readBack())}adaptToSurroundings(e){if(!(e>0)||!(this.clearAdaptation>0))return!1;const t=e/this.clearAdaptation;return Math.abs(Math.log(t/this.surroundingsFactor))<.05?!1:(this.surroundingsFactor=t,this.views&&this.state?this.adaptFromViews(this.views.sun,this.views.moon,this.state):this.applyAdaptation(this.clearAdaptation*t),!0)}resetSurroundings(){this.surroundingsFactor=1}surroundingsFactor=1;clearAdaptation=0;views;adaptFromViews(e,t,i){this.views={sun:e,moon:t};const n=10**(-.4*(i.moon.magnitude-At.SUN_MAGNITUDE)),s=it.skyViewUv(i.altitudeM,0,0);this.dayZenithY=At.bilinear(e,s.u,s.v)[1];const r=this.effectiveSunScale(i),a=i.umbra?{excess:At.excessOf(i,r),tint:i.umbra.tint}:void 0;let o;if(a&&a.excess.some(E=>E>0)){const E=At.umbraReferenceUv(i);o=At.bilinear(e,E.u,E.v)}const c=At.airglowXyzs(),h=At.artificialXyzs(i.lightPollution),d=(E,x,T=!0)=>{const D=(90-E)*Math.PI/180,R=it.skyViewUv(i.altitudeM,D,At.azimuthBetween(x,i.sun.azimuthDeg)),O=it.skyViewUv(i.altitudeM,D,At.azimuthBetween(x,i.moon.azimuthDeg)),N=At.bilinear(e,R.u,R.v),C=At.bilinear(t,O.u,O.v),k=T&&E>0?At.airglowFactor(E):0,P=E>0?de.artificialShape(E):0,F=o&&a&&E>0?At.excessAt(a.excess,x)*Math.exp(-E/At.UMBRA_GLOW_SCALE_DEG):0,G=Y=>!o||!a?0:F*(Y<3?o[1]*a.tint[Y]:o[3]);return[0,1,2,3].map(Y=>r*N[Y]+n*C[Y]+c[Y]*k+h[Y]*P+G(Y))};let u=0,p=0;for(let E=5;E<90;E+=10){const x=Math.cos(E*Math.PI/180);for(let T=0;T<360;T+=30)u+=x*Math.log(Math.max(d(E,T)[1],1e-9)),p+=x}this.clearAdaptation=Math.exp(u/p),this.applyAdaptation(this.clearAdaptation*this.surroundingsFactor);const f=([E,x,T,D])=>{const R=this.exposureScale*this.filterScale,O=this.adaptingLuminance*this.exposureScale;return Fe.relativeOf([E*R,x*R,T*R],D*R,O,0)},m=(E,x,T=!0)=>f(d(E,x,T)),v=[0,0,0,0],g=5*Math.PI/180,y=20*Math.PI/180;for(let E=2.5;E<90;E+=5){const x=E*Math.PI/180,T=Math.sin(x)*Math.cos(x)*g*y;for(let D=10;D<360;D+=20){const R=d(E,D);for(let O=0;O<4;O++)v[O]+=R[O]*T}}const w=[0,0,0],b=[0,0,0];for(let E=0;E<360;E+=20){const x=m(2,E),T=m(2,E,!1);for(let D=0;D<3;D++)w[D]+=x[D]/18,b[D]+=T[D]/18}const M=this.ambientColours,S=this.announcedAdaptation;this.ambientColours={zenith:m(90,0),horizon:w,airlight:b,skyIrradiance:f(v),scale:this.relativeScale},this.announcedAdaptation=this.adaptingLuminance,!(M&&At.alike(S,this.adaptingLuminance)&&M.zenith.every((E,x)=>At.alike(E,this.ambientColours.zenith[x]))&&M.horizon.every((E,x)=>At.alike(E,w[x])))&&this.onChange()}announcedAdaptation=0;static alike(e,t){return e===t||Math.abs(e-t)<=.01*Math.max(Math.abs(e),Math.abs(t))}relativeOfLuminance(e,t){const[i,n,s]=e,r=.2126*i+.7152*n+.0722*s,a=r>0?t/r:0,o=[a*(.4124*i+.3576*n+.1805*s),t,a*(.0193*i+.1192*n+.9505*s)],c=this.exposureScale*this.filterScale,h=this.adaptingLuminance*this.exposureScale;return Fe.relativeOf([o[0]*c,o[1]*c,o[2]*c],o[1]*c,h,0)}get recorded(){return!this.seenByEye}get rodShare(){const e=this.adaptingLuminance*this.exposureScale;return this.seenByEye?Fe.rodShare(e):0}get relativeScale(){const e=this.adaptingLuminance*this.exposureScale;return this.exposureScale*this.filterScale/Fe.semiSaturation(e)}applyAdaptation(e){this.adaptingLuminance=e;const t=e*this.exposureScale;this.material.uniforms.uRodShare.value=0,this.material.uniforms.uInverseSemiSaturation.value=1/Fe.semiSaturation(t)}static predictedZenithLuminance(e){const t=n=>90-n.altitudeDeg,i=de.magPerArcsec2({altitudeDeg:e.sun.altitudeDeg,separationDeg:t(e.sun)},{phaseAngleDeg:e.moon.phaseAngleDeg,altitudeDeg:e.moon.altitudeDeg,separationDeg:t(e.moon)},90,e.lightPollution);return de.toNanolamberts(i)*At.CANDELAS_PER_NANOLAMBERT}static CANDELAS_PER_NANOLAMBERT=1e-5/Math.PI;static airglowXyzs(){const e=de.toNanolamberts(de.AIRGLOW_MAG_PER_ARCSEC2)*At.CANDELAS_PER_NANOLAMBERT;return[e*.3127/.329,e,e*(1-.3127-.329)/.329,e]}static artificialXyzs(e){const t=de.artificialZenithNanolamberts(e)*At.CANDELAS_PER_NANOLAMBERT;return[t*.4369/.4041,t,t*(1-.4369-.4041)/.4041,t]}static airglowFactor(e){const t=Math.cos(e*Math.PI/180)**2,i=je.GROUND_RADIUS_M/(je.GROUND_RADIUS_M+At.AIRGLOW_LAYER_ALTITUDE_M),n=1/Math.sqrt(Math.max(1-i*i*t,1e-4)),s=1/Math.sqrt(Math.max(1-.96*t,.001));return n*10**(-.4*de.EXTINCTION_PER_AIR_MASS*(s-1))}static azimuthVector(e){const t=e*Math.PI/180;return new ne(Math.sin(t),-Math.cos(t))}static azimuthBetween(e,t){const i=Math.abs(e-t)%360;return(i>180?360-i:i)*Math.PI/180}static bilinear(e,t,i){const n=it.SKY_VIEW_WIDTH,s=it.SKY_VIEW_HEIGHT,r=Math.min(Math.max(t*n-.5,0),n-1),a=Math.min(Math.max(i*s-.5,0),s-1),o=Math.floor(r),c=Math.floor(a),h=Math.min(o+1,n-1),d=Math.min(c+1,s-1),u=r-o,p=a-c,f=(m,v,g)=>e[(m*n+v)*4+g];return[0,1,2,3].map(m=>(f(c,o,m)*(1-u)+f(c,h,m)*u)*(1-p)+(f(d,o,m)*(1-u)+f(d,h,m)*u)*p)}}class Oa{static DRY_OPTICAL_DEPTH=.08;static GROWTH_EXPONENT=.3;static MAX_RELATIVE_HUMIDITY=.95;static OPTICAL_DEPTH_STEP=.02;static relativeHumidity(e,t){const i=n=>Math.exp(17.625*n/(243.04+n));return Math.min(Math.max(i(t)/i(e),0),1)}static opticalDepth(e){const t=Math.min(Math.max(e,0),Oa.MAX_RELATIVE_HUMIDITY);return Oa.DRY_OPTICAL_DEPTH*(1-t)**-.3}static steppedOpticalDepth(e){const t=Oa.OPTICAL_DEPTH_STEP;return Math.round(Oa.opticalDepth(e)/t)*t}}class ar{static CHANNEL_WAVELENGTHS_NM=[680,550,440];static KOSCHMIEDER=-Math.log(.02);static PRECIPITATION_EXTINCTION_PER_KM={rain:{a:.365,b:.63},snow:{a:1.023,b:.72},hail:{a:.365,b:.63}};static FULL_INTENSITY_MM_PER_H=8;rayleigh;aerosol;constructor(e=je.DEFAULT_AEROSOL_OPTICAL_DEPTH,t=0){const[i,n,s]=ar.CHANNEL_WAVELENGTHS_NM;this.rayleigh=[je.rayleighAt(i),je.rayleighAt(n),je.rayleighAt(s)];const r=a=>e/je.AEROSOL_SCALE_HEIGHT_M*(a/550)**-1.3;this.aerosol=[r(i)+t,r(n)+t,r(s)+t],this.precipitationPerM=t}precipitationPerM;static of(e){const t=e.relativeHumidity===void 0?void 0:Oa.opticalDepth(e.relativeHumidity);return new ar(t,ar.precipitationExtinction(e))}static precipitationExtinction(e){const t=e.precipitationIntensity*(e.precipitationAmount??1);if(e.precipitationType==="none"||!(t>0))return 0;const i=ar.PRECIPITATION_EXTINCTION_PER_KM[e.precipitationType],n=t*ar.FULL_INTENSITY_MM_PER_H;return i.a*n**i.b/1e3}transmittance(e,t,i){const n=ar.meanDensity(e,t,je.RAYLEIGH_SCALE_HEIGHT_M),s=ar.meanDensity(e,t,je.AEROSOL_SCALE_HEIGHT_M);return[0,1,2].map(r=>Math.exp(-(this.rayleigh[r]*n+this.aerosol[r]*s)*i))}transmittanceFromSpace(e,t){const i=Math.max(t,0),n=1/(Math.sin(i*Math.PI/180)+.50572*(i+6.07995)**-1.6364),s=je.RAYLEIGH_SCALE_HEIGHT_M*je.rayleighDensity(e),r=je.AEROSOL_SCALE_HEIGHT_M*je.aerosolDensity(e);return[0,1,2].map(a=>Math.exp(-(this.rayleigh[a]*s+(this.aerosol[a]-this.precipitationPerM)*r)*n))}extinctionAt(e){return{rayleigh:this.rayleigh[1]*je.rayleighDensity(e),aerosol:this.aerosol[1]*je.aerosolDensity(e)}}visibilityM(e){const{rayleigh:t,aerosol:i}=this.extinctionAt(e);return ar.KOSCHMIEDER/(t+i)}get rayleighRatios(){return[this.rayleigh[0]/this.rayleigh[1],1,this.rayleigh[2]/this.rayleigh[1]]}static meanDensity(e,t,i){const n=Math.max(e,0),s=Math.max(t,0),r=s-n;return Math.abs(r)<.01?Math.exp(-n/i):i*(Math.exp(-n/i)-Math.exp(-s/i))/r}}class Cl extends wb{constructor(){super(new re(0,0,0),0,0),Cl.install()}setAir(e,t,i){const{rayleigh:n,aerosol:s}=e.extinctionAt(t);this.near=n,this.far=s,this.color.setRGB(i[0],i[1],i[2])}static fadeRim(e,t,i){e.transparent=!0,e.onBeforeCompile=n=>{n.fragmentShader=n.fragmentShader.replace("#include <fog_fragment>",`#include <fog_fragment>
11048
11048
  #ifdef USE_FOG
11049
11049
  gl_FragColor.a *= 1.0 - smoothstep(${t.toFixed(1)}, ${i.toFixed(1)}, length(vAerialWorld.xz - cameraPosition.xz));
11050
11050
  #endif`)},e.customProgramCacheKey=()=>`aerial-rim-${t.toFixed(1)}-${i.toFixed(1)}`,e.needsUpdate=!0}static installed=!1;static install(){if(Cl.installed)return;Cl.installed=!0;const e=new ar(1),t=e.rayleighRatios,i=[e.aerosol[0]/e.aerosol[1],1,e.aerosol[2]/e.aerosol[1]],n=a=>`vec3(${a.map(o=>o.toFixed(4)).join(", ")})`,s=je.RAYLEIGH_SCALE_HEIGHT_M.toFixed(1),r=je.AEROSOL_SCALE_HEIGHT_M.toFixed(1);dt.fog_pars_vertex=`
@@ -11152,7 +11152,7 @@ void main() {`).replace("#include <opaque_fragment>",`
11152
11152
  vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
11153
11153
  gl_FragColor = vec4(light, 1.0);
11154
11154
  }
11155
- `,transparent:!0,blending:An,depthWrite:!1,side:Hi,fog:!1});this.object=new xe(new hn(Fb.RADIUS,128,32,0,Math.PI*2,0,Nt.MAX_ANGLE_RAD),t),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(e,t){if(!e||!t){this.object.visible=!1;return}this.towards.set(e.x,e.y,e.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<Nt.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=js.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=js.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class Nf{constructor(e){this.generator=e}static SIZE=128;target=new $d(Nf.SIZE,{type:Jt,generateMipmaps:!1,minFilter:Dt,magFilter:Dt});camera=new kb(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(e,t,i,n=[]){const s=e.shadowMap.autoUpdate;let r=!1;t.traverse(o=>{const c=o;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?s:!1;const a=n.map(o=>o.visible);for(const o of n)o.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),n.forEach((o,c)=>{o.visible=a[c]}),e.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 Jn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){Jn.install(),this.generator=new Sv(e),this.eye=new Nf(this.generator)}static decor;refresh(e,t,i,n,s,r,a,o=[],c,h=Jn.REFRESH_MS){for(const v of[...this.probes.keys()])n.some(g=>g.id===v&&g.shiny)||(this.probes.get(v).dispose(),this.probes.delete(v));const d=[{probe:this.eye}];for(const v of n){if(!v.shiny)continue;let g=this.probes.get(v.id);g||(g=new Nf(this.generator),this.probes.set(v.id,g)),d.push({probe:g,reflector:v})}const u=performance.now(),p=()=>d.filter(({probe:v})=>v.capturedVersion!==a),f=p().filter(({probe:v})=>u-v.capturedAtMs>=h);if(f.length>0){const v=f.reduce((g,y)=>y.probe.capturedAtMs<g.probe.capturedAtMs?y:g);if(v.reflector){const g=v.reflector.holder.getWorldPosition(this.scratch);v.probe.capture(e,t,g,[v.reflector.holder,...s]),Jn.reflectOn(v.reflector.holder,v.probe)}else{v.probe.capture(e,t,i,[...s,...o]),c?.(v.probe.sharp),Jn.decor=v.probe.filtered;for(const g of r)Jn.reflectOn(g,v.probe);for(const g of n)g.shiny||Jn.reflectOn(g.holder,v.probe)}v.probe.capturedVersion=a}const m=p();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:v})=>h-(u-v.capturedAtMs))))}scratch=new _;static reflectOn(e,t={filtered:Jn.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Kd?t.sharp&&s.setSurroundings(t.sharp):s instanceof go&&t.filtered&&s.envMap!==t.filtered&&(s.envMap=t.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const e of this.probes.values())e.dispose();this.generator.dispose()}static installed=!1;static install(){if(Jn.installed)return;Jn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!dt.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}dt.lights_fragment_maps=dt.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function IO(l,e){return JSON.stringify(l.cloudLayers)===JSON.stringify(e.cloudLayers)&&l.cloudCover===e.cloudCover&&l.cloudDarkness===e.cloudDarkness&&l.cloudBaseM===e.cloudBaseM&&l.highCloudCover===e.highCloudCover&&l.iceCrystalAlignment===e.iceCrystalAlignment&&l.rareIceCrystals===e.rareIceCrystals&&l.lowerCloudCover===e.lowerCloudCover&&l.relativeHumidity===e.relativeHumidity&&l.precipitationType===e.precipitationType&&l.precipitationIntensity===e.precipitationIntensity&&l.precipitationAmount===e.precipitationAmount&&l.windDirectionDeg===e.windDirectionDeg&&l.windSpeed===e.windSpeed&&l.storm===e.storm}const ju=900,_0=1,lM=4,R0=5,Zu=.5,Ju=Yt.GROUND_RADIUS_M;function cM(l){return Yt.groundRadiusFor(l)}const D0=.5,k0=850,C0=.03,_O=.015,Es=850,Yh=300,to=120,RO=700,DO=3.5,Qu=20,hM=.04,kO=.26,dM=4,L0=1.5,uM=-1,CO=.01,Rp=-4,LO=2,OO=20,ep=2600,PO=.97,NO=.38,qh=Rp,FO=8,UO=2,pM=1500,zO=.7,BO=.3,HO=.32,GO=.65,fM=2.4,VO=.9,WO=400,$O=[0,45,90,135,180,225,270,315],KO=2,XO=16,mM=4e3,gM=880,tp=40,vM=60,YO=10,qO=1,jO=Yt.REBUILD_DISTANCE_M,bM=.265,yM=[[0,0],...Array.from({length:8},(l,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*bM,Math.sin(t)*bM]})],O0=700,P0=250/zv,ZO=12,wM=5,N0=6,Ho=[.92,.92,.95],F0=[.15,.15,.19],U0={snow:{fallSpeedMPerS:2,size:.3,color:new re(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new re(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Tc=0,z0=0,JO=150,B0=3e3,jh=20,QO=15,MM=Tc,eP=40,xM=1,tP=9;function H0(l){return xM+(tP-xM)*l}const SM=new re(.75,.82,.92),iP=10,nP=.5;function EM(l){return Xr(l/iP,nP,1)}const Go=200,AM=.18,TM=.32,sP=.35,IM=new re(.85,.9,.98),_M=5,RM=.85,DM=.01;function rP(l,e,t=1){return Math.round(l*(DM+(1-DM)*e)*t)}function aP(l,e){return JSON.stringify(l.cloudLayers)===JSON.stringify(e.cloudLayers)&&l.cloudCover===e.cloudCover&&l.cloudDarkness===e.cloudDarkness&&l.cloudBaseM===e.cloudBaseM&&l.highCloudCover===e.highCloudCover&&l.iceCrystalAlignment===e.iceCrystalAlignment&&l.lowerCloudCover===e.lowerCloudCover}const kM=230,CM=.7,LM=.05,oP=.6,lP=.7,cP=.15,OM=.35,hP=3,dP=1/12,uP=.5,Gr=new re(.82,.86,1),pP=2500,fP=1.6,G0=15,mP={Venus:new re(1,.96,.85),Mars:new re(1,.55,.4),Jupiter:new re(.95,.87,.72),Saturn:new re(.92,.86,.68)};class Ee{renderer;scene=new Or;phenomena=new Mr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;onReferencesSettled;camera;celestialGroup=new zt;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(e,t){if(this.skyHoldUntilMs===null)return e;this.arrivalsPending++;let i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=t===void 0?void 0:setTimeout(n,t);return t!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+t),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),t+20))),e.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(e){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),e&&this.awaitArrival(e).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+mM,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),mM+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new Mt;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new ne;decorModelProvider=_p[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new bt(e=>this.awaitArrival(this.loadBodyModel(e)),()=>this.render(),()=>this.relativeScale);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(e){return(e.sizeM?.lengthM??Ee.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*Ee.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;beams=[];beamSystem;beamSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new hw(16777215,0);celestialLightTarget=new Gi;skyLight=new z_(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 Ap;weather=qf;observerElevationM=0;siteElevationM=0;air=new ar;groundRadius=Ju;terrainRadius=Ju;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new _;cloudFieldOffset=new _;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new _;rainLastVerticalFacing=-1;rainViewportSize=new ne;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new hw(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new _;sunVisible=!1;lensFlareScratch=new _;sunOcclusionRaycaster=new Ap;sunOcclusionDirectionScratch=new _;sunOcclusionRightScratch=new _;sunOcclusionUpScratch=new _;ufoOcclusionRaycaster=new Ap;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=bi.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(e){return Math.max(3,Math.round(6e6/Math.max(1,e)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;reentrySystem;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new Xd;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=_2()){this.renderer=new eL({canvas:e,antialias:!0}),this.resolution=new jt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=od,this.camera=new Ls(60,e.width/Math.max(e.height,1),.1,ju*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=t,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-to,this.celestialLight.shadow.camera.right=to,this.celestialLight.shadow.camera.top=to,this.celestialLight.shadow.camera.bottom=-to,this.celestialLight.shadow.camera.near=Es-Yh,this.celestialLight.shadow.camera.far=Es+Yh,this.celestialLight.shadow.bias=-.03/(2*Yh),this.celestialLight.shadow.normalBias=hM,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Gr),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 Et(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(e,t){this.cssSize.width=e,this.cssSize.height=t,this.renderer.setSize(e,t,!1),this.camera.aspect=e/Math.max(t,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(e){e!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=e,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(e,t={}){this.cloudOffsetM.set(e.x,0,e.z),this.cloudLayerOffsetsM=t,this.layeredClouds?.setOffsets(e,t),this.cloudFieldOffset.set(e.x*P0,0,e.z*P0);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(e){const t=((e.rollDeg??0)+this.gaitOffset.rollDeg)*Ri,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Ri;e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Ri,t,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,t,"YXZ"),e.elevationM!==this.observerElevationM&&(this.observerElevationM=e.elevationM,this.syncCloudLayer(),Math.abs(cM(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Ju),this.camera.far=Math.max(ju*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),e.lat!==void 0&&e.lng!==void 0&&this.placeTerrain(e.lat,e.lng,0,0),this.poseElevationM=e.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+e.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==e.fovDeg&&(this.camera.fov=e.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(e){this.stopTerrainFade(),this.terrainProviders=e,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),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;observerRoute;setObserverRoute(e){this.observerRoute=e,this.decorTerrainRadiusM=Ee.terrainReachFor(this.decorObjects,e)}decorTerrainRadiusM=0;static terrainReachFor(e,t){return Yt.decorReachFor(e,t)}placeTerrain(e,t,i,n){const s=(r,a)=>{const o=st(a.lat,a.lng,e,t);r.position.x=o.x-i,r.position.z=o.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}}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaited!==n){this.patchesAwaited=n;const u=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{this.terrainProviders===u&&this.setTerrainOrigin(e,t,i)}),Ee.TERRAIN_PATIENCE_MS)}return}const d=n.nearest(e,t);d&&(e=d.lat,t=d.lng,s=d.radiusM)}const r=s??Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:d,z:u}=st(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(d*d+u*u)<jO*(r/Ju))return}const a=this.terrainRadius,o=this.terrainMeshOrigin;o!==void 0&&Math.hypot(st(e,t,o.lat,o.lng).x,st(e,t,o.lat,o.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(Vw(e,t,this.terrainProviders,r,{route:this.observerRoute}),Ee.TERRAIN_PATIENCE_MS).then(({mesh:d,attribution:u,originElevationM:p,water:f,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(p??0),this.anchorGrassTo(d,e,t);const v=this.terrainMesh,g=this.terrainMeshOrigin,y=g?st(e,t,g.lat,g.lng):void 0;v&&y&&Math.hypot(y.x,y.z)<=a&&(d.position.y=v.position.y+this.groundYOfPatch(v,y.x,y.z)),v&&g&&y&&Math.hypot(y.x,y.z)<=a?this.crossfadeTerrain(d,v,g):this.disposeMesh(this.terrainMesh),d.renderOrder=qO,this.terrainMesh=d,this.terrainMeshOrigin={lat:e,lng:t},this.compileNextFrameOffThread(),this.terrainAttribution=u,this.scene.add(d),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,r),this.buildWater(e,t,r,f,m),this.buildRailways(e,t,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(e,t,r,d,p),this.render(),i?.()}).catch(d=>{console.warn("Terrain build failed, keeping the flat ground fallback:",d),i?.()})}buildFarRing(e,t,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,o=Yt.beamReachFor(this.beams,{lat:e,lng:t});if(!Yt.needsFarRing(i,a,o)){this.dropFarRing();return}if(this.farRing){const{x:f,z:m}=st(e,t,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(f,m)<i*Ee.FAR_RING_KEPT_SHARE)return}const c=this.terrainProviders.patches,h=c?.farRingOf?.(e,t);if(c&&!h){this.dropFarRing();return}const d=h?.radiusM??Yt.FAR_RING_RADIUS_M,u=++this.farRingToken,p=this.terrainProviders;this.awaitArrival(Vw(e,t,{elevation:p.elevation,imagery:p.imagery},d,void 0,{innerM:i*Ee.FAR_RING_OPEN_SHARE,referenceElevationM:s}),Ee.TERRAIN_PATIENCE_MS).then(({mesh:f})=>{if(u!==this.farRingToken||this.terrainProviders!==p){this.disposeMesh(f);return}this.dropFarRing(),this.farRingToken=u,f.renderOrder=Ee.FAR_RING_RENDER_ORDER,f.position.y=n.position.y-Ee.FAR_RING_DROP_M;const m=f.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:f,origin:{lat:e,lng:t}},this.farRingRadiusM=d,this.scene.add(f),f.position.x=n.position.x,f.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},f=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",f))}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(e,t,i){if(this.grassReference){const r=st(this.grassReference.lat,this.grassReference.lng,t,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:t,lng:i};const n=st(this.grassReference.lat,this.grassReference.lng,t,i);e.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t,i){this.stopTerrainFade();const n=e.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)/Ee.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:t,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const e=this.terrainMesh?.material;e&&(e.opacity=1,e.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=Yt.ROADS_MAX_RADIUS_M;buildRoads(e,t,i){const n=this.terrainProviders.roads;if(!n||i>Ee.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===e&&s.lng===t&&s.radiusM===i){this.drapeRoads(s.ways,e,t,n.contemporary);return}s&&Math.hypot(st(e,t,s.lat,s.lng).x,st(e,t,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,e,t,n.contemporary),this.awaitArrival(n.getRoads(md(e,t,i)),Ee.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t||(this.roadWays={lat:e,lng:t,radiusM:i,ways:r},this.drapeRoads(r,e,t,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(e,t,i,n,s){const r=this.terrainProviders.water;if(!r||i>Ee.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,e,t,i),Ee.ROADS_PATIENCE_MS).catch(o=>console.warn("Water not drawn:",o));return}const a=this.waterSurfaces;if(a&&a.lat===e&&a.lng===t&&a.radiusM===i){this.drapeWater(a.surfaces,e,t,i);return}a&&Math.hypot(st(e,t,a.lat,a.lng).x,st(e,t,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,e,t,i),this.awaitArrival((s??r.getWater(md(e,t,i))).then(o=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:o},this.drapeWater(o,e,t,i)}),Ee.ROADS_PATIENCE_MS).catch(o=>{console.warn("Water unavailable, drawing none:",o)})}async drapeWater(e,t,i,n){if(e.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),n,this.patchSpacingM(r)),Jn.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=ae(async()=>{const{WaterSystem:e}=await import("./WaterSystem-KGutPogf.js");return{WaterSystem:e}},[],import.meta.url).then(({WaterSystem:e})=>{const t=new e;return this.scene.add(t.group),this.waterSystem=t,t})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(e,t,i){const n=this.terrainProviders.railways;if(!n||i>Ee.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===e&&s.lng===t&&s.radiusM===i){this.drapeRailways(s.lines,e,t,i);return}s&&Math.hypot(st(e,t,s.lat,s.lng).x,st(e,t,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,e,t,i),this.awaitArrival(n.getRailways(md(e,t,i)).then(r=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.railwayLines={lat:e,lng:t,radiusM:i,lines:r},this.drapeRailways(r,e,t,i)}),Ee.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(e,t,i,n){if(!this.railwaySystem&&!e.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(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),n),Jn.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=ae(async()=>{const{RailwaySystem:e}=await import("./RailwaySystem-7MMun4zU.js");return{RailwaySystem:e}},[],import.meta.url).then(({RailwaySystem:e})=>{const t=new e;return this.scene.add(t.group),this.railwaySystem=t,t})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(e){e!==this.statedRoads&&(this.statedRoads=e,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const e=this.terrainMesh;e&&(this.roadSystem.group.position.copy(e.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(e)),this.roadSystem.setStated(this.statedRoads,(t,i)=>this.groundYOfPatch(e,t,i)))}setTraces(e,t=new Map){e===this.traces&&t===this.traceLabels||(this.traces=e,this.traceLabels=t,!(e.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(e){e!==this.tracesShown&&(this.tracesShown=e,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=ae(async()=>{const{TraceSystem:e}=await import("./TraceSystem-lNFPtyqy.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(R0);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainMeshOrigin;!e||!t||!i||(e.group.position.copy(t.position),e.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(t,n,s)))}buildingFootprints(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=me.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(e,t){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?st(i.lat,i.lng,e,t):{x:0,z:0}}surveyedLamps(e,t){const i=this.decorOriginInRoads(e,t);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(e,t){this.lampNudges.clear();const i=this.decorOriginInRoads(e,t);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(e,t){return e.length!==t.length||e.length===0?!1:e.every((i,n)=>{const s=t[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(e){const t=this.roadWays,i=this.terrainProviders.roads;if(!t||!i)return;const n=this.wallsOf(e,t.lat,t.lng),s=this.roadWalls;s?.lat===t.lat&&s.lng===t.lng&&s.walls.length===n.length&&s.walls.every((a,o)=>a.what===n[o].what&&Math.hypot(a.x-n[o].x,a.z-n[o].z)<.1)||this.drapeRoads(t.ways,t.lat,t.lng,i.contemporary)}wallsOf(e,t,i){const n=this.decorOriginInRoads(t,i);return e.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(e,t,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(e,t,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius,new Si(this.buildingFootprints(t,i),this.surveyedLamps(t,i))),this.roadWalls={lat:t,lng:i,walls:this.wallsOf(this.decorObjects,t,i)},this.lampsToKerb(t,i),this.roadAttribution=e.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(e){this.showCompass!==e&&(this.showCompass=e,this.disposeCompassLabels(),e&&this.buildCompassLabels(),this.render())}setCompassPoints(e){this.compassPoints!==e&&(this.compassPoints=e,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[e,t,i]=this.sunArriving,n=Math.max(t,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(e/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=Ln.K*t*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(e){this.compassHovered!==e&&(this.compassHovered=e,this.updateCompassVisibility())}setCompassForced(e){this.compassForced!==e&&(this.compassForced=e,this.updateCompassVisibility())}updateCompassVisibility(){const e=this.compassHovered||this.compassForced;if(this.compassSprites.some(t=>t.visible!==e)){for(const t of this.compassSprites)t.visible=e;this.developingExposure?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(e){if(IO(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!aP(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=ar.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Oa.steppedOpticalDepth(e.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=e.storm&&e.cloudDarkness>=uP,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects===e)return;if(Ee.onlyMoved(this.decorObjects,e)){this.decorObjects=e,this.decorTerrainRadiusM=Ee.terrainReachFor(e,this.observerRoute),this.layStreetsIfWallsMoved(e);return}this.decorObjects=e,this.decorTerrainRadiusM=Ee.terrainReachFor(e,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),me.dispose(i);this.decorGroups.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const t=e.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,FO);for(const i of e){const n=me.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&t.includes(i)&&this.addStreetlightLight(i.id,n,t.indexOf(i)<UO,i.lamp),i.model&&i.id.startsWith(Un.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.layStreetsIfWallsMoved(e),e.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(e){this.decorSunlight=e}setContrails(e){e!==this.contrails&&(this.contrails=e,!(e.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(e){this.contrailSunlight=e}loadContrailSystem(){return this.contrailSystemLoading??=ae(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-CXR_fe3m.js");return{ContrailSystem:e}},__vite__mapDeps([2,3]),import.meta.url).then(({ContrailSystem:e})=>{const t=new e;this.scene.add(t.group),this.contrailSystem=t})}contrailTint(e){const t=this.contrailSunlight.get(e),i=this.lastAstronomy?.sun,n=Ee.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(t&&i){const a=fs.litFraction(t.sunElevationDeg,t.heightM);if(a>0){const o=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=Nt.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*c*o[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setBeams(e){e!==this.beams&&(this.beams=e,this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),!(e.length===0&&!this.beamSystem)&&this.loadBeamSystem().then(()=>{this.updateBeams(),this.render()}))}get beamSegmentCount(){return this.beamSystem?.segmentCount??0}loadBeamSystem(){return this.beamSystemLoading??=ae(async()=>{const{BeamSystem:e}=await import("./BeamSystem-CrrOjNqD.js");return{BeamSystem:e}},__vite__mapDeps([4,5]),import.meta.url).then(({BeamSystem:e})=>{const t=new e;this.scene.add(t.group),this.beamSystem=t})}updateBeams(){const e=this.decorReferencePose;!this.beamSystem||e?.lat===void 0||e.lng===void 0||this.beamSystem.update(this.beams,this.decorTime,{reference:{lat:e.lat,lng:e.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(t,i,n)=>this.transmittanceTo(t,i,n),groundYAt:(t,i)=>this.groundYUnder(t,i)})}updateContrails(){const e=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:e?oi(e.altitudeDeg,e.azimuthDeg,1):void 0},t=>this.contrailTint(t))}contrailPixelRad(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/e)}setDecorPresence(e){this.decorPresence=e}entryOfDecorModel(e){return this.decorModelProvider.entry(e).catch(()=>{})}setDecorModelProvider(e){this.decorModelProvider=e;const t=this.decorObjects;this.decorObjects=[],this.setDecor(t)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:e,z:t}=this.bodyOrigin,i=this.groundYUnder(e,t),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(e+s*n,t-r)-i}}get bodyEastScale(){const e=this.decorReferencePose,t=this.decorCurrentPose;return e?.lat===void 0||t?.lat===void 0?1:Math.cos(t.lat*Ri)/Math.cos(e.lat*Ri)}bodyMaskedByDecor(e,t){const i=this.decorGroups.get(t);return i?this.bodySystem.maskedShare(e,i):void 0}setBodies(e,t=0,i=e.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,o=this.scatteredSky,c=this.bodyEastScale;Math.abs(c-1)>1e-9&&(e=e.map(d=>({...d,eastM:d.eastM*c}))),this.bodySystem.set(e,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(d,u)=>this.groundYUnder(d,u),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(d,u,p)=>this.transmittanceTo(d,u,p),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},t,o?Object.assign((d,u)=>o.relativeOfLuminance(d,u),{recorded:o.recorded}):void 0,i),this.bodySystem.setSmoke(n,t),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 e=this.celestialLight.color,t=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,o,c)=>(a*t+(o+c)/2*s)/Math.PI;return[r(e.r,i.r,n.r),r(e.g,i.g,n.g),r(e.b,i.b,n.b)]}bodyOutline(e,t){return this.bodySystem.outlineOf(e,t)}documentUrl;modelUrl(e){return e.url?this.documentRelative(e.url):void 0}documentRelative(e){if(e.startsWith("data:"))return e;const t=this.documentUrl??(typeof location>"u"?void 0:location.href);return t?new URL(e,t).href:e}async loadBodyModel(e){const t=e.url?void 0:e.id?await this.decorModelProvider.entry(e.id):void 0,i=this.modelUrl(e)??t?.url,n=e.credit??t?.credit;if(!(!i||!n))return{scene:await I0(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg,bindings:t?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(Od(e))||!me.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const n=TO(i.scene);n.traverse(s=>{s instanceof xe&&(s.userData.sharedModel=!0)}),me.applyModelParameters(n,e.modelParameters,i.bindings),me.applyModel(t,e,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.decorModelCredits.set(e.id,i.credit)}standInScenes=new Map;async loadDecorModel(e,t,i=!1){const n=i?lf[e.kind]:Od(e);if(!(!n||!me.usesModel(e)))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 o=i||e.kind==="tree"?await this.standInScene(r):await I0(r);if(t!==this.decorModelToken||i&&!this.pendingTrafficModels.has(e.id))return;const c=this.decorGroups.get(e.id);if(!c)return;!i&&e.kind!=="tree"&&Jn.reflectOn(o);const h={ref:JSON.stringify(n),scene:o,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(e.id,h),this.applyLoadedDecorModel(e,c,h),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${e.id}":`,s)}}standInScene(e){let t=this.standInScenes.get(e);return t||(t=I0(e).then(i=>(/jungle-jim-realistic-trees/.test(e)||Jn.reflectOn(i),i)),this.standInScenes.set(e,t)),t}updateDecorAnchoring(e,t,i=0){this.decorReferencePose=e,this.decorCurrentPose=t,this.decorTime=i;const n=e?.lat!==void 0&&e.lng!==void 0&&t?.lat!==void 0&&t?.lng!==void 0?st(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(f=>f.observerSide!==void 0&&Ro(f.kind));this.terrainMesh&&t?.lat!==void 0&&t.lng!==void 0&&(this.placeTerrain(t.lat,t.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,o;if(s){const f=qs(s,i),m=me.occupantView(s,f.headingDeg),v=-(f.headingDeg??0)*Ri,g=m.x*Math.cos(v)+m.z*Math.sin(v),y=-m.x*Math.sin(v)+m.z*Math.cos(v),w=f.eastM+n.x,b=-f.northM+n.z;r.x=-(w+g),r.z=-(b+y),this.camera.position.y=this.groundYUnder(w,b)+m.eyeY,o=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Ri,-(m.headingDeg+this.indoorLookYawDeg)*Ri,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const c=this.findCabin(i,n,r);this.fitShadowToCabin(c.length>0),this.dimCabinSky(c),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(f=>[f.x,f.z,f.cos,f.sin,f.halfWidthM,f.halfLengthM,f.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 f of this.decorObjects){if(f.kind==="terrace")continue;const m=this.decorGroups.get(f.id);if(!m)continue;const v=qs(f,i),g=this.lampNudges.get(f.id),y=v.eastM+(g?.eastM??0)+n.x+r.x,w=-(v.northM+(g?.northM??0))+n.z+r.z,b=this.terrainMesh,M=`${b?.geometry.uuid}:${(y-(b?.position.x??0)).toFixed(3)}:${(w-(b?.position.z??0)).toFixed(3)}:${(b?.position.y??0).toFixed(3)}:${v.headingDeg}:${v.altitudeM}:${h}`;if(m.userData.footprintKey!==M){if(f.kind==="wire"){const O=me.wireGround(f,y,w,v.headingDeg,(N,C)=>this.groundYUnder(N,C));m.userData.footprintGroundY=O.startY,me.shearWire(m,me.sizeOf(f).lengthM,O.dropM)}else if(f.kind==="crossing"){const O=this.groundYUnder(y,w),N=-(v.headingDeg??0)*Ri,C=Math.cos(N),k=Math.sin(N);m.userData.footprintGroundY=O,xt.drape(me.bodyOf(m),(P,F)=>this.groundYUnder(y+P*C+F*k,w-P*k+F*C)-O)}else m.userData.footprintGroundY=this.groundUnderFootprint(f,y,w,v.headingDeg,v.altitudeM);m.userData.footprintKey=M}const E=v.altitudeM>Ee.AIRBORNE_M&&Math.hypot(y,w)<Ee.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY;if(m.position.set(y,E+v.altitudeM,w),f.kind==="crop"){const O=Math.hypot(y,w);m.visible=O<=JO}const x=this.decorPresence.get(f.id),T=x!==void 0&&(i<x.fromMs||i>x.untilMs);x&&(m.visible=!T);const D=this.decorSunlight.get(f.id);D&&!T&&this.lightFromAbove(m,D),v.headingDeg!==void 0&&(m.rotation.y=-v.headingDeg*Ri);const R=AT(f,i);if(R!==void 0&&Ee.turnHead(m,v.headingDeg??0,R),f.kind==="crop"&&m.visible){const O=this.terrainMesh,N=[O?.geometry.uuid,y-(O?.position.x??0),w-(O?.position.z??0),m.position.y-(O?.position.y??0),v.headingDeg,v.altitudeM].map(C=>typeof C=="number"?C.toFixed(4):C).join(":");m.userData.cropGroundKey!==N&&(me.fitCropToGround(m,(C,k)=>this.groundYUnder(C,k)+v.altitudeM),m.userData.cropGroundKey=N)}if(!T){const O=m.position.distanceTo(this.camera.position);a=Math.max(a,O),O<Ee.trafficModelRangeM(f)&&this.pendingTrafficModels.delete(f.id)&&this.loadDecorModel(f,this.decorModelToken)}}if(s&&o!==void 0){const f=this.decorGroups.get(s.id);f&&(this.camera.position.y=f.position.y+o)}this.updateContrails(),this.updateBeams();const d=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,u=this.beams?.length&&this.terrainMeshOrigin?Yt.beamReachFor(this.beams,this.terrainMeshOrigin):0,p=Math.max(ju*1.2,this.groundRadius*2.5,a*1.2,d*1.05,u*1.2);Math.abs(this.camera.far-p)>1&&(this.camera.far=p,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainYUnder(e,t);let n=i;for(const s of this.terraces){const r=e-s.x,a=t-s.z,o=r*s.cos-a*s.sin,c=r*s.sin+a*s.cos;if(Math.abs(o)<=s.halfWidthM&&Math.abs(c)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(o))/s.bankM)),d=h*h*(3-2*h);n=Math.max(n,d*s.levelY+(1-d)*Math.min(s.levelY,i))}}return n}placeTerraces(e,t,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=qs(s,e),o=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=me.sizeOf(s),d=-(a.headingDeg??0)*Ri,u=Math.cos(d),p=Math.sin(d),f=`${n?.geometry.uuid}:${(o-(n?.position.x??0)).toFixed(3)}:${(c-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(o,0,c),a.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=me.fitTerrace(r,s,(m,v)=>this.terrainYUnder(o+m*u+v*p,c-m*p+v*u)),r.userData.terraceKey=f),this.terraces.push({x:o,z:c,cos:u,sin:p,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(e,t){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,e-i.position.x,t-i.position.z):z0}horizonAltitudeDeg(e){const t=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(t.x)}|${Math.round(t.y*10)}|${Math.round(t.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((e%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(e,t){return e<Math.max(0,this.horizonAltitudeDeg(t))+Ee.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(e){const t=this.terrainMesh;if(!t)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=e*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,o=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),c=Math.min(Math.max(this.patchSpacingM(t),1),50);let h=Number.NEGATIVE_INFINITY;for(let d=c;d<=o;d=Math.max(d+c,d*1.02)){const u=i.x+s*d,p=i.z+r*d,f=d<=this.terrainRadius?this.terrainYUnder(u,p):a.position.y+this.groundYOfPatch(a,u-a.position.x,p-a.position.z),m=d*d/(2*Ee.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(f-m-i.y,d))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(e){const t=e.geometry.getAttribute("position");return t&&t.count>=2?Math.abs(t.getX(1)-t.getX(0)):1/0}groundYOfPatch(e,t,i){const n=e.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return z0;const r=n.getX(0),a=n.getX(s-1),o=n.getZ(0),c=n.getZ((s-1)*s),h=Xr((t-r)/(a-r)*(s-1),0,s-1),d=Xr((i-o)/(c-o)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(d))return z0;const u=Math.min(Math.floor(h),s-2),p=Math.min(Math.floor(d),s-2),f=h-u,m=d-p,v=(M,S)=>n.getY(M*s+S),g=v(p,u),y=v(p,u+1),w=v(p+1,u),b=v(p+1,u+1);return f+m<=1?g+(y-g)*f+(w-g)*m:b+(w-b)*(1-f)+(y-b)*(1-m)}groundUnderFootprint(e,t,i,n,s=0){return me.groundUnderFootprint(e,t,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(e){this.gaitOffset=e}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(e,t){this.lookYawDeg=e,this.lookPitchDeg=t}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(e,t){this.indoorLookYawDeg=e,this.indoorLookPitchDeg=t}skyUnknown=!1;setSkyUnknown(e){e!==this.skyUnknown&&(this.skyUnknown=e,this.render())}perception=Us.NONE;setPerception(e){JSON.stringify(e)!==JSON.stringify(this.perception)&&(this.perception=e,this.render())}medium;setMedium(e,t,i,n,s){const r=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:n??e.iso,autoExposure:e.autoExposure===!0&&n===void 0,maxIso:e.maxIso,metering:s??e.metering??"average",exposureSeconds:t,fNumber:i}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30),i=e?Us.NONE:this.perception??Us.NONE;if(mn.uColorVision.value.set(...i.colorMatrix),mn.uContrast.value=i.contrastGain,!e){mn.uMedium.value=0;return}mn.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const n=e.autoExposure||this.skyUnknown?this.scatteredSky?.sceneAdaptation:void 0,s=n===void 0?void 0:this.meteredBodies(),r=n===void 0?void 0:n+s.mean,a=c=>.065*e.exposureSeconds*c*this.filterTransmittance/(e.fNumber*e.fNumber*t);let o=r!==void 0&&r>0?1/(t*r):void 0;o!==void 0&&e.metering==="highlights"&&s.brightest>0&&(o=Math.min(o,Ee.HIGHLIGHT_KEPT_AT/(.18*t*s.brightest))),mn.uMediumExposure.value=o!==void 0?Math.min(o,e.maxIso!==void 0?a(e.maxIso):1/0):a(e.iso)}static HIGHLIGHT_KEPT_AT=.3;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const e=this.camera;e.updateMatrixWorld();const t=e.fov*Math.PI/180,i=2*Math.atan(Math.tan(t/2)*e.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(t/2)),s=new _;let r=0,a=0;for(const{position:o,luminanceCdM2:c,solidAngleSr:h}of this.bodySystem.metered.values())s.copy(o).project(e),s.z<1&&Math.abs(s.x)<=1&&Math.abs(s.y)<=1&&(r+=c*h,a=Math.max(a,c*Math.min(1,h/(Ee.HIGHLIGHT_SHARE*n))**2));return{mean:r/n,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const e=this.camera.fov*Math.PI/180,t=this.grain.frameHeightMm/(2*Math.tan(e/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/t,e/i)}bloomSize=new ne;lampTransmittance(e){const t=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+e.position.y;return this.air.transmittance(t,i,e.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(e,t=0){this.decorLitAt={t:e,stepMs:t};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&me.setLights(s,n.lights,e,s.position.distanceTo(this.camera.position),t,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"?d2(n,e):void 0,o=a!==void 0?_o.lamps(a):om(n,e,this.lastAstronomy?.sun.altitudeDeg);me.setLit(r,n.kind,o,this.relativeScale,n.lamp);const c=this.streetlightLights.get(n.id);c&&(c.visible=o),a!==void 0&&(this.headlightSettings.set(n.id,a),this.aimDecorBeam(n,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=ae(async()=>{const{HeadlightSystem:e}=await import("./HeadlightSystem-CPbn_3dw.js");return{HeadlightSystem:e}},[],import.meta.url).then(({HeadlightSystem:e})=>{this.headlightSystem??=new e(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const e=this.headlightSystem;if(e){for(const t of this.decorObjects)t.kind==="vehicle"&&e.add(t.id);this.observerHeadlights&&e.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const e of this.decorObjects){const t=this.headlightSettings.get(e.id),i=this.decorGroups.get(e.id);t!==void 0&&i&&this.aimDecorBeam(e,i,t)}this.aimObserverBeam()}}headlightScatterPerM(){const e=this.siteElevationM+this.camera.position.y,t=200,i=this.air.transmittance(e,e,t)[1];return i>0?-Math.log(Math.min(1,i))/t:.05}aimDecorBeam(e,t,i){if(!this.headlightSystem?.has(e.id))return;t.updateMatrixWorld(!0);const n=new _(0,0,-1).transformDirection(t.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=me.sizeOf(e).lengthM,r=t.getWorldPosition(new _).addScaledVector(n,s/2-BO);r.y+=zO;const a=me.sizeOf(e).widthM;this.headlightSystem.aim(e.id,i,r,n,a*HO,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(e){this.observerHeadlights=e,e&&this.loadHeadlights(),this.headlightSystem&&(e?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const e=this.observerHeadlights;if(!e||!this.headlightSystem?.has("observer"))return;const t=e.setting==="auto"?this.lastAstronomy?_o.auto(this.lastAstronomy.sun.altitudeDeg):"off":e.setting,i=e.headingDeg*Math.PI/180,n=new _(Math.sin(i),0,-Math.cos(i)),s=new _(n.x*fM,this.camera.position.y-VO,n.z*fM);this.headlightSystem.aim("observer",t,s,n,GO,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(e,t,i,n){const s=me.bodyOf(t),r=s.children.find(c=>c.userData.emissive);if(!r)return;const a=pM*me.lampShare(n),o=new MS(16764006,a*this.relativeScale,WO);n?.colorTemperatureK&&o.color.setRGB(...me.lampHue(n)),o.userData.candela=a,o.position.copy(r.position).multiply(s.scale),o.castShadow=i,o.shadow.mapSize.set(512,512),o.shadow.bias=-.002,t.add(o),this.streetlightLights.set(e,o)}applyWindowGlow(){const e=this.lastAstronomy;me.setLitWindowShare(e?Pn.share(e.sun.altitudeDeg,e.localHour):0)}setAstronomy(e){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-e.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=e,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(e)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=e.sun,this.buildSky(e.sun),this.buildGround();const t=this.magnitudeLimitOf(e);this.buildStars(e.stars,t),this.placeBodies(e,t),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.applySkyColours(e),this.syncAnimationLoop(),this.render()}static relativeSkyOf(e,t){const i=r=>{const a=cr.luminanceOf(r);if(!(a>0))return[0,0,0];const o=Fe.relativeOfResponse(a)/a;return[r[0]*o,r[1]*o,r[2]*o]},n=i(e.zenith),s=i(e.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:t}}placeBodies(e,t){this.bodiesScale=this.relativeScale,this.sunBeamFraction=Qi.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,dM,new re(1,.96,.88),e.sun.magnitude),this.placeEclipse(e),this.setMoonMesh(e.moon,t),this.buildPlanets(e.planets,t),this.buildComet(e.comet,t),this.buildNovae(e.novae??[],t)}placeEclipse(e){const t=e.eclipse;if(!t||e.sun.altitudeDeg<Rp){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=dM/Es*(180/Math.PI),n=i/t.sunRadiusDeg,s=oi(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=oi(e.moon.altitudeDeg,e.moon.azimuthDeg,1),a=Math.acos(Xr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),o=a>1e-9?Xr(t.separationDeg*n*Ri/a,0,2):0,c=Math.sin(a),[h,d]=a>1e-9?[Math.sin((1-o)*a)/c,Math.sin(o*a)/c]:[1,0],u={x:s.x*h+r.x*d,y:s.y*h+r.y*d,z:s.z*h+r.z*d},p=t.moonRadiusDeg*n;this.eclipseDiscs={sun:new _(s.x,s.y,s.z).normalize(),moon:new _(u.x,u.y,u.z).normalize(),sunRadiusRad:i*Ri,moonRadiusRad:p*Ri};const f=.01,m=(y,w)=>oi(e.sun.altitudeDeg+y,e.sun.azimuthDeg+w,1),v={x:m(f,0).x-m(-f,0).x,y:m(f,0).y-m(-f,0).y,z:m(f,0).z-m(-f,0).z},g={x:m(0,f).x-m(0,-f).x,y:m(0,f).y-m(0,-f).y,z:m(0,f).z-m(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:n,up:v,right:g}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Bc(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(e){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(e,this.magnitudeLimitOf(e)),this.applyDazzleStrength(),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.updateBeams());const t=this.scatteredSky?.ambient??Ee.relativeSkyOf(Cv(e.sun.altitudeDeg),this.relativeScale),i=t,n=this.lightUnderClouds(e),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(e,t),this.updateCloudLighting(e.sun,this.baseFogColor),Ne.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??pM)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(e,i.zenith),this.applyAir(),this.buildLunarDiffraction(e.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(e){const t=this.scatteredSky?.ready?this.scatteredSky:void 0;if(e.altitudeDeg<-.5||!t){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,n=(i===void 0?je.DEFAULT_AEROSOL_OPTICAL_DEPTH:Oa.opticalDepth(i))*je.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),a=Nt.aureoleScale(n,Nt.airMass(e.altitudeDeg))*s,o=Nt.coronaScale(r),c=Nt.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),a.toExponential(2),o.toExponential(2),Math.log10(Math.max(t.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new Fb,this.celestialGroup.add(this.lunarDiffraction.object));const d=Nt.profile(Nt.HAZE_COARSE_MODE),u=Nt.profile(Nt.CLOUD_DROPLETS),p=EL(e.altitudeDeg),f=new Float32Array(Nt.STEPS*3);let m=0;for(let w=0;w<Nt.STEPS;w++){const b=w*3,M=[0,1,2].map(E=>c*p[E]*(a*d[b+E]+o*u[b+E])),S=cr.shown(M,cr.luminanceOf(M),(E,x)=>t.relativeOfLuminance(E,x));f.set(S,b),m=Math.max(m,cr.response(S))}const{x:v,y:g,z:y}=oi(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:v,y:g,z:y}:void 0,f)}applyAir(){this.scene.fog instanceof Cl||(this.scene.fog=new Cl),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(e,t,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+t,Math.hypot(e-n.x,t-n.y,i-n.z))}setSiteElevation(e){Math.abs(e-this.siteElevationM)<1||(this.siteElevationM=e,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const e=this.siteElevationM+this.observerElevationM+1.6,[t,i,n]=this.air.transmittance(e,e,Ee.UMBRA_PATH_M),s=.2126*t+.7152*i+.0722*n;return s>0?[(.4124*t+.3576*i+.1805*n)/s,1,(.0193*t+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(e){const t=e.eclipse?.horizonShare;return t&&Math.max(...t)<.1?{share:t,tint:this.umbraTint()}:void 0}scatteredSkyState(e){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:e.sun.altitudeDeg,azimuthDeg:e.sun.azimuthDeg,magnitude:e.sun.magnitude},sunLight:Qi.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?Qi.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:de.phaseAngleOf(e.moon.phase.illuminatedFraction)}}}pumpScatteredSky(){const e=this.scatteredSky;!e||e.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(e.advance(this.skyHoldUntilMs?XO:KO),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(e){if(e.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new KL(k0),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):ea(-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setReentries(e){if(e.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new Is,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):ea(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setLaunchPlumes(e){e.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new gi,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(e,this.relativeScale,t=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),t=>this.cloudTransmission(t)),this.render())}pickPlumeAt(e,t){if(!this.plumeSystem?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=this.plumeSystem.pickAt(i,Ee.BEAM_PICK_PIXELS*this.contrailPixelRad(),this.skyLightTowards(i));return n&&this.groundHides(e,t)?void 0:n}get plumePuffCount(){return this.plumeSystem?.count??0}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(C0*this.camera.fov*Math.PI/180);let s,r=n;const a=new _;for(const[o,c]of this.decorGroups){if(!c.visible||!o.startsWith(Un.ID_PREFIX))continue;a.copy(c.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,s=o)}return s&&!this.groundHides(e,t)?s:void 0}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(C0*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(e,t)?void 0:n}updateCelestialLight(e,t){const i=this.relativeScale,n=e.sun.altitudeDeg>=qh,s=!n&&e.moon.altitudeDeg>=qh,r=n?e.sun:e.moon,a=[0,0,0],o=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Ri)),c=this.siteElevationM+this.observerElevationM;let h=r,d=n||s?oM.directFraction(r.altitudeDeg,c):0;n&&d<=0&&e.moon.altitudeDeg>=qh&&(h=e.moon,d=oM.directFraction(h.altitudeDeg,c));const u=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Ri)),p=n||s?this.cloudTransmission(r):1,f=-Math.log(Math.max(p,1e-6)),m=Math.max(0,1/(1+.1125*f)-p),v=[0,0,0];if(n||s){const S=Nt.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(c,r.altitudeDeg);for(let R=0;R<3;R++)v[R]=S*E[R]*m*o,this.cloudBeam[R]=S*E[R];const{x,y:T,z:D}=oi(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(x,T,D),d>0){const R=Nt.illuminanceOf(h.magnitude)*i,O=h===r?E:this.air.transmittanceFromSpace(c,h.altitudeDeg),N=h===r?p:this.cloudTransmission(h);for(let C=0;C<3;C++)a[C]=R*O[C]*N*d}}else this.cloudBeam.fill(0);const g=this.surroundings;if(g)this.skyLight.color.setRGB(g.up[0]*i,g.up[1]*i,g.up[2]*i),this.skyLight.groundColor.setRGB(g.down[0]*i,g.down[1]*i,g.down[2]*i);else{const S=this.skyCloudTransmission(),E=t.skyIrradiance,x=[0,1,2].map(D=>E[D]*S+v[D]);this.skyLight.color.setRGB(x[0],x[1],x[2]);const T=it.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(T*(x[0]+a[0]*u),T*(x[1]+a[1]*u),T*(x[2]+a[2]*u))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===e.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||d<=0){this.celestialLight.intensity=0;return}const{x:y,y:w,z:b}=oi(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(y,w,b),this.celestialLight.shadow.normalBias=hM*Xr(w/kO,.1,1),this.placeShadowFrustum();const M=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/M,a[1]/M,a[2]/M),this.celestialLight.intensity=M,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(e,t){const i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=fs.litFraction(t.sunElevationDeg,t.heightM);if(s>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),a=Nt.illuminanceOf(i.magnitude)*this.relativeScale,o=t.heightM>=Ee.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)n[c]=Math.max(0,a*r[c]*s*o-this.sceneSunBeam[c])}}e.traverse(s=>{const r=s.material;if(!(r instanceof pr||r instanceof go)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=Ee.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 _(0,1,0);placeShadowFrustum(){const e=this.lightDirection,t=this.celestialLight.shadow.camera,i=(t.right-t.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,e);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(e,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=c=>{const h=r.dot(c)/i;return(h-Math.round(h))*i},o=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(o).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToCabin(e){if(e===this.cabinShadow)return;this.cabinShadow=e;const t=this.celestialLight.shadow;if(!e){this.shadowHalfExtentM=-1;return}const i=t.camera,n=DO;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=Qu+5,i.near=this.shadowLightDistanceM-Qu,i.far=this.shadowLightDistanceM+Qu,i.updateProjectionMatrix(),t.bias=-.004/(2*Qu),t.mapSize.x!==2048&&(t.mapSize.set(2048,2048),t.map?.dispose(),t.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(e){for(const t of e)t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==Ee.CABIN_SKY_SHARE&&(r.envMapIntensity=Ee.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(RO,Math.max(to,Math.ceil(e*1.25/20)*20));if(t===this.shadowHalfExtentM)return;this.shadowHalfExtentM=t;const i=this.celestialLight.shadow,n=i.camera;n.left=-t,n.right=t,n.top=t,n.bottom=-t;const s=Math.max(Yh,t*(Yh/to));this.shadowLightDistanceM=Math.max(Es,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*to?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=to;shadowLightDistanceM=Es;shadowUp=new _(0,1,0);shadowAxisX=new _;shadowAxisY=new _;shadowWorld=new _;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const n=i*Ri,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)e+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),t+=s}return e/t}cloudBeam=[0,0,0];cloudBeamDirection=new _(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Fe.semiSaturation(Fe.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new Rn,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(e,t,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(e){return this.meteorSystem?.midpointOf(e)}updateMeteors(e){this.meteorSystem?.update(e)}setInstrument(e){this.projectionKind=e.projection,this.grain=e.detailUm!==void 0&&e.frame?{detailUm:e.detailUm,frameHeightMm:e.frame.heightMm}:void 0;const t=hi.starPointsOf(e);t!==this.starPoints&&(this.starPoints=t,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=t),this.render())}magnitudeLimitOf(e){const t=de.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:de.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return ea(e.sun.altitudeDeg,this.instrumentMagnitudeGain,t)}setLightPollution(e){e!==this.lightPollution&&(this.lightPollution=e,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(e,t=!1,i=0){const n=Number.isFinite(e)?e:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(t,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 e=this.compileOffThread().then(()=>{this.compiling===e&&(this.compiling=void 0,this.render())});this.compiling=e;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 e=this.usableGhostPass();e?(this.exposureSubjectBounds=[],this.renderOnce(e.frame),e.develop(this.renderer,e.frame,this.ghostOptics,1,this.sunBeyondPicture()),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.developingExposure&&this.startExposure()}}}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const e=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const t=this.renderer.properties,i=performance.now()+Ee.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of e){const a=t.get(r)?.currentProgram;(!a||a.isReady())&&e.delete(r)}e.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(e){if(this.animationsRunning){const t=this.lastFrameTimeMs===void 0?0:e-this.lastFrameTimeMs;this.lastFrameTimeMs=e,this.hasAnimations()&&this.animate(e,t);const i=this.resolution.ratioFor(e,t);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(e,t,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"||s.observerSide!==void 0&&Ro(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=qs(s,e),o=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=me.sizeOf(s),d=Math.max(h.widthM,h.lengthM)/2;Math.hypot(o,c)<d&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<d&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(e=!1){this.reflections??=new Jn(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(a=>a.mesh)],i=[...this.starTiers.map(a=>a.points),...[...this.bodyMeshes.values()].filter(a=>a instanceof Cs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(a=>a!==void 0),...this.cabinDecor()],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,a=>this.measureSurroundings(a,n,s),e?0:Jn.REFRESH_MS);r===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()}))},r))}static adaptingLuminance(e,t){const i=(.2126*t[0]+.7152*t[1]+.0722*t[2])/Math.PI;return Math.max(e,Ee.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(e,t,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new fd;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>oi(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,s,r=>{const a=p=>p.map(f=>f/t),o=this.surroundings,c={up:a(r.up),down:a(r.down)},h=(p,f)=>p.some((m,v)=>Math.abs(m-f[v])>.03*Math.max(Math.abs(m),Math.abs(f[v]),1e-12)),d=!o||h(o.up,c.up)||h(o.down,c.down);d&&(this.surroundings=c),this.eyeSettledVersion=-1;const u=this.scatteredSky?.adaptToSurroundings(Ee.adaptingLuminance(Math.exp(r.logAverage)/t,c.down))??!1;if(!d&&!u){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(e){const t=this.surroundings;if(!t)return;const i=e.sun.altitudeDeg>=qh?e.sun:e.moon.altitudeDeg>=qh?e.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[t.up[0]*n,t.up[1]*n,t.up[2]*n]}}probeIrradiance;surroundings;animate(e,t){const i=Math.min(t/1e3,dP);this.twinkleSeconds=e/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(e/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=e/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(e){this.resolution.maximum=e,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(e){this.renderer.setPixelRatio(e),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(e,t){const i=t?Math.max(1,Math.round(e)):1;if(i===this.exposureInstants&&(i===1||t===this.exposureInstantAt)){this.exposureInstantAt=t;return}this.exposureInstants=i,this.exposureInstantAt=t,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(e){if(this.aimBeams(),me.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();e?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const t=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.phenomena.place(this.camera,(r,a,o)=>this.directionAtScreenPoint(r,a,o),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()),mn.uRodShare.value=this.scatteredSky?.rodShare??0,mn.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);mn.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!t){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,e):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,e);return}t.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(),e,this.pointLayerHost)}pointLayerHost={points:()=>{const e=[];return this.celestialGroup.traverse(t=>{(t instanceof Cs&&t.userData.pointSource||t instanceof xe&&t.userData.skyRibbon)&&e.push(t)}),[...e,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(e=this.camera){this.renderReferencesPass(e),this.renderBodiesOverReferences(e),this.renderPhenomenaPass(e),this.renderHudPass(e)}renderHudPass(e){const t=this.traceSystem?.any&&this.tracesShown;if(!t&&!this.compassSprites.some(s=>s.visible))return;t&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),e.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(R0),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(e){if(!this.references?.any||!this.bodySystem.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(VS),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new Fs({blending:zl,blendSrc:la,blendDst:la,blendSrcAlpha:la,blendDstAlpha:la,toneMapped:!1});renderReferencesPass(e){if(!this.references?.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(this.references.layer),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){const i=e.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,t);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:t},this.referencesLoading??=ae(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-BeFpOHFl.js");return{ReferenceSystem:n}},__vite__mapDeps([6,7]),import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=s;for(const[a,o]of this.referenceViews)s.setView(a,o);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})}referenceAspect(e){return this.references?.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new _)}referenceFailure(e){return this.references?.failureOf(this.documentRelative(e))}setReferencesShown(e){this.referencesShown=e,this.references?.setShown(e),this.render()}setReferenceView(e,t){this.referenceViews.set(e,t),this.references?.setView(e,t),this.render()}renderPhenomenaPass(e){if(!this.phenomena.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);s&&Ee.markDecorDepth(s,n.kind!=="crop")}e.layers.set(_0),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(WS),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new Fs({colorWrite:!1});static HEAD_TURN_LIMIT_DEG=85;static turnHead(e,t,i){const n=e.getObjectByName("head");if(!n)return;const s=((i-t)%360+540)%360-180,r=Math.max(-85,Math.min(Ee.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*Ri}static isSolidSurface(e){if(!(e instanceof xe))return!0;const t=Array.isArray(e.material)?e.material[0]:e.material;return t.depthWrite!==!1&&t.blending!==An}static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof xe))return;t&&Ee.isSolidSurface(i)?i.layers.enable(_0):i.layers.disable(_0)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new ne),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new hL(t,i)),this.exposureAccumulation.resize(t,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const e=this.exposureInstantAt,t=this.exposureAccumulation;if(!e||!t)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+Ee.EXPOSURE_BUDGET_MS,s=Ee.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const a=this.compassSprites.map(o=>o.visible);for(const o of this.compassSprites)o.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((o,c)=>{o.visible=a[c]})}t.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(e,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){mn.uRodShare.value=this.scatteredSky?.rodShare??0,mn.uHasOverlay.value=1,mn.uRelativeScale.value=this.relativeScale,this.applyMedium();const e=this.exposureInstants/this.exposureInstantsDone,t=this.usableGhostPass();if(t&&this.exposureAccumulation?t.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,e,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,e),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Or,n=new fr(-1,1,1,-1,0,2),s=tp/(gM*Math.tan(vM*Ri/2));for(const a of this.compassSprites){if(!a.visible)continue;const o=a.getWorldPosition(new _).sub(this.camera.position).normalize(),c=this.screenPointOf(o);if(!c)continue;const h=new Uh(a.material);h.position.set(c.ndcX,c.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 e=[],t=new vn,i=new _,n=this.camera.getWorldDirection(new _),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||(t.setFromObject(a),t.isEmpty())||t.distanceToPoint(this.camera.position)<Ee.MAP_SUBJECT_NEAREST_M)continue;let o=1/0,c=-1/0,h=1/0,d=-1/0;for(const u of[t.min.x,t.max.x])for(const p of[t.min.y,t.max.y])for(const f of[t.min.z,t.max.z]){if(i.set(u,p,f).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const v=(m.ndcX+1)/2,g=(1-m.ndcY)/2;o=Math.min(o,v),c=Math.max(c,v),h=Math.min(h,g),d=Math.max(d,g)}o=Math.max(o,0),c=Math.min(c,1),h=Math.max(h,0),d=Math.min(d,1),c>=o&&d>=h&&e.push({x:o,y:h,width:c-o,height:d-h})}return e}restateAt(e,t){this.restatingExposure=!0;try{e(t)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(e){const t=this.lensOptics;this.lensOptics=e,(t===void 0!=(e===void 0)||t&&e&&(t.focalLengthMm!==e.focalLengthMm||t.fNumber!==e.fNumber||t.focusDistance!==e.focusDistance||t.frameHeightMm!==e.frameHeightMm))&&(e&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.render())}usableDepthOfFieldPass(){const e=this.lensOptics;if(!e)return;const t=this.renderer.getDrawingBufferSize(new ne),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new vd(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}setLensGhosts(e){JSON.stringify(e)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=e,e.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}pickGhostAt(e,t){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,e,t,this.ghostOptics,mn.uMediumExposure.value)}pickDropAt(e,t){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,e,t)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const e=this.renderer.getDrawingBufferSize(new ne);return this.ghostPass?this.ghostPass.resize(e.x,e.y):this.ghostPass=new Ts(e.x,e.y),this.ghostPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new ne);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new Nb(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new ne);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new ki(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new ne(t,i),this.camera);return}const s=n.directionFor(t,i,this.camera.fov);this.camera.updateMatrixWorld(),e.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),e.ray.direction.set(s.x,s.y,s.z).applyQuaternion(this.camera.quaternion).normalize(),e.camera=this.camera}pickCloudAt(e,t){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(e,t))}cloudDirectionAt(e,t){return this.directionAtScreenPoint(e,t,new _)}directionAtScreenPoint(e,t,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(e){this.camera.updateMatrixWorld();const t=this.screenPointScratch.copy(e).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);if(this.projectionKind==="equidistant"&&this.equidistantPass)return ki.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*Ri);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new _;screenPointQuaternion=new Ns;screenPointSize=new ne;updateLensFlarePosition(){const e=this.lensFlare;if(!e)return;if(!this.sunVisible){e.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){e.mesh.visible=!1;return}const t=this.sunVisibleFraction();if(t<=0){e.mesh.visible=!1;return}e.mesh.visible=!0,this.sunUnhiddenFraction=t,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);e.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;e.uniforms.uResolution.value.set(n,s),e.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const e=this.lensFlare;if(!e||!e.mesh.visible)return;const t=this.sunDiscRadiance.map(r=>Math.max(0,r-Ee.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(t[1]<=0)return;const i=Math.tan(e.uniforms.uSourceRadiusDeg.value*Math.PI/180)/e.uniforms.uTanHalfFov.value/2,n=Math.PI*i*i,s=e.uniforms.uLensPosition.value;return{x:s.x,y:s.y,radius:i,flux:[t[0]*n,t[1]*n,t[2]*n]}}renderDazzleOnResample(){const e=this.lensFlare;if(!e||!this.sunVisible)return;const t=this.sunVisibleFraction();if(t<=0)return;this.sunUnhiddenFraction=t,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);e.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),e.uniforms.uResolution.value.set(n.x,n.y),e.uniforms.uEquidistant.value=1,e.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,e.mesh.visible=!0,e.mesh.layers.enable(lM),this.camera.layers.set(lM),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),e.mesh.visible=!1,e.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let e=0;for(const t of yM)this.isSunOccluded(t[0],t[1])||e++;return e/yM.length}raycastableDecor(){const e=[];for(const t of this.decorObjects){if(t.kind==="crop")continue;const i=this.decorGroups.get(t.id);i&&e.push(i)}return e}isSunOccluded(e=0,t=0){const i=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&i.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(this.sunWorldPosition).sub(this.camera.position),s=n.length();if(n.normalize(),e!==0||t!==0){const a=Math.PI/180,o=this.sunOcclusionRightScratch.set(n.z,0,-n.x);o.lengthSq()<1e-9&&o.set(1,0,0),o.normalize();const c=this.sunOcclusionUpScratch.crossVectors(o,n).normalize();n.addScaledVector(o,e*a).addScaledVector(c,t*a).normalize()}if(this.groundBlocks(this.camera.position,n,s))return!0;if(i.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(i,!0)[0];return r!==void 0&&r.distance<s}groundBlocks(e,t,i,n=0){const s=this.groundMesh;if(s&&t.y<0){const v=(s.position.y-e.y)/t.y;if(v>n&&v<i){const g=e.x+t.x*v-s.position.x,y=e.z+t.z*v-s.position.z;if(Math.hypot(g,y)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),o=Math.round(Math.sqrt(a.count));if(o<2||o*o!==a.count)return!1;const c=[r.position.x+a.getX(0),r.position.x+a.getX(o-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((o-1)*o)],d=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(o-1);if(!(d>0))return!1;let u=n,p=i;for(const[v,g,y]of[[e.x,t.x,c],[e.z,t.z,h]]){const w=Math.min(y[0],y[1]),b=Math.max(y[0],y[1]);if(Math.abs(g)<1e-12){if(v<w||v>b)return!1;continue}const M=(w-v)/g,S=(b-v)/g;u=Math.max(u,Math.min(M,S)),p=Math.min(p,Math.max(M,S))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),m=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let v=0;v<=m;v++){const g=u+(p-u)*v/m,y=e.x+t.x*g,w=e.y+t.y*g,b=e.z+t.z*g;if(w<=this.groundYUnder(y,b))return!0}return!1}setPhenomena(e,t){this.phenomena.set(e,t)}decorDistancesAt(e,t,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t),this.ufoOcclusionRaycaster.near=Zu;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 o=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(c=>Ee.isSolidSurface(c.object));o&&(r.occludesSourceIds?.includes(i)?n=n===void 0?o.distance:Math.max(n,o.distance):s=s===void 0?o.distance:Math.min(s,o.distance))}return{behindM:n,inFrontM:s}}pickBodyAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.origin,n=this.raycaster.ray.direction,s=CO*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,d])=>{const u=d.getWorldPosition(new _).sub(i);return{key:h,direction:u.clone().normalize(),radiusRad:Math.atan2(d.scale.x/2,u.length())}}),a=this.eclipseDiscs,o=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],c=Ee.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...o],s);if(c)return this.groundHides(e,t)?void 0:c}pickOpticsAt(e,t){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(e,t)?i:void 0}static nearestBody(e,t,i){let n,s=1/0,r=1/0,a=!1;for(const o of t){const c=Math.acos(Xr(o.direction.dot(e),-1,1))-o.radiusRad;if(c>i)continue;const h=c<=0,d=s<=0,u=o.inFront===!0;(h!==d?h:h?u!==a?u:o.radiusRad<r:c<s)&&(n=o.key,s=c,r=o.radiusRad,a=u)}return n}pickInterpretationBodyAt(e,t){const i=this.bodySystem.group.children.filter(p=>p.visible&&p.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=_O*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],o=a.length>0?Ee.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let c,h=1/0;const d=new vn,u=new _;for(const p of i){if(d.setFromObject(p),d.isEmpty())continue;d.getCenter(u);const f=d.getSize(new _).length()/2,m=u.clone().sub(s),v=m.length();if(v===0||m.dot(n)<=0||o!==void 0&&o<v-f)continue;const g=Math.acos(Math.min(1,m.normalize().dot(n))),y=Math.atan(f/v);if(y>r){const w=this.raycaster.intersectObject(p,!0)[0];if(!w||o!==void 0&&o<w.distance)continue}else if(g>r)continue;y<h&&(h=y,c=p.name.slice(5))}return c}pickStarAt(e,t){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(C0*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const o=a.direction.dot(i);o>r&&(r=o,s={star:a.star,altitudeDeg:a.altitudeDeg})}return s&&this.groundHides(e,t)?void 0:s}groundHides(e,t){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,1/0,Zu)}bodyScreenBox(e){const t=this.bodySystem.boxOf(e,this.bodyBoxScratch);if(!t)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let a=0;a<8;a++){const o=this.bodyCornerScratch.set(a&1?t.max.x:t.min.x,a&2?t.max.y:t.min.y,a&4?t.max.z:t.min.z),c=this.screenPointOf(o.sub(this.camera.position).normalize());if(!c)return;i=Math.min(i,c.ndcX),s=Math.max(s,c.ndcX),n=Math.min(n,c.ndcY),r=Math.max(r,c.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new vn;bodyCornerScratch=new _;pickPlacedBodyAt(e,t){return this.aimAtScreenPoint(this.raycaster,e,t),this.bodySystem.pick(this.raycaster)}decorScreenBox(e){const t=this.decorGroups.get(e);if(!t||!t.visible)return;const i=this.bodyBoxScratch.setFromObject(t);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-1/0;for(let o=0;o<8;o++){const c=this.bodyCornerScratch.set(o&1?i.max.x:i.min.x,o&2?i.max.y:i.min.y,o&4?i.max.z:i.min.z),h=this.screenPointOf(c.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(e){return this.lampNudges.get(e)}decorGroundPointAt(e,t,i,n=0){const s=this.decorGroups.get(e);if(!s)return;this.aimAtScreenPoint(this.raycaster,t,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(e){const t=this.decorGroups.get(e);return t?Math.hypot(t.position.x-this.camera.position.x,t.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(e){const t=this.decorGroups.get(e);return t?t.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Ri/2):0}decorGrabHeightAt(e,t,i){const n=this.decorGroups.get(e);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,t,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),o=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return o?Math.min(Math.max(o.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new co;decorHitScratch=new _;static firstSolid(e){return e.find(t=>{const i=t.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&s.transparent&&s.opacity<Ee.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],n=Ee.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(e,t){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray;i.group.updateMatrixWorld();const s=new xh().copy(n).applyMatrix4(new vt().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(u,p)=>{const f=new _(u,0,p).applyMatrix4(r);return this.groundYUnder(f.x,f.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,Ee.RAILWAY_PICK_ABOVE_M))return;const o=Ee.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!o||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,o.distance-Ee.RAILWAY_GROUND_MARGIN_M,Zu))return;const c=i.group.worldToLocal(o.point.clone()),h=i.lineAt(c.x,c.z);if(!h)return;const d=i.contactHeightM(h);return{line:h,distanceM:o.distance,...d!==void 0?{contactM:d}:{}}}pickBeamAt(e,t){const i=this.beamSystem;if(!i||i.segmentCount===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray,s=i.pickAt(n.origin,n.direction,Ee.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!s||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,s.distanceM-1,Zu))return;const r=Ee.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<s.distanceM))return s}skyLightTowards(e){const t=this.scatteredSky?.ambient;if(!t)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(e.x,e.y,e.z)||1,s=Math.max(0,Math.min(1,e.y/n));return i(t.horizon)+(i(t.zenith)-i(t.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),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.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,this.beamSystem?.dispose(),this.beamSystem=void 0,this.beamSystemLoading=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.reentrySystem?.dispose(),this.reentrySystem=void 0,this.plumeSystem?.dispose(),this.plumeSystem=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const e of this.bodyMeshes.values())this.disposeMesh(e);this.bodyMeshes.clear(),this.novaKeys.clear();for(const e of[...this.hitAreas.keys()])this.disposeHitArea(e);for(const e of[...this.glareSprites.keys()])this.disposeGlare(e);this.disposeCompassLabels();for(const e of this.decorGroups.values())me.dispose(e);this.decorGroups.clear(),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 e=t=>{this.animationFrameId=null,this.frame(t),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(e))};this.animationFrameId=requestAnimationFrame(e)}setAnimationsRunning(e,t=!1){const i=e&&t;if(e===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=e,this.framesDriven=i,e&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!e&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),this.syncAnimationLoop(),(!e||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(e=>e.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new _;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const e=this.lastAstronomy?.sun;return e!==void 0&&e.altitudeDeg<Ee.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(e){const t=this.skyMesh?.geometry??new hn(ju,32,16),i=t.attributes.position,n=t.getAttribute("color")??new gt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:o}=pL(i.getX(r),i.getY(r),i.getZ(r)),c=ML(a,o,e.azimuthDeg,e.altitudeDeg);n.setXYZ(r,c[0],c[1],c[2])}if(n.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",n);const s=new Fs({vertexColors:!0,side:Hi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new xe(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=cM(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Sb(this.groundRadius,48),i=new pr({color:new re(D0,D0,D0),fog:!0});Cl.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new xe(t,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 e=this.groundMesh?.material;if(!e)return;const t=this.terrainMesh===void 0;e.depthWrite!==t&&(e.depthWrite=t,e.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,e.depthTest=!0,e.needsUpdate=!0}cloudTransmission(e,t=!1){const i=`${e.altitudeDeg.toFixed(1)}:${e.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(";")+(t?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(e,t);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(e,t=!1){const i=oi(e.altitudeDeg,e.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,t);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-Xt.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*PO);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Xt.iceAlphaAt(i,ep,r,this.cloudFieldOffset)*NO),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<Rp){this.disposeMesh(this.bodyMeshes.get(e)),this.bodyMeshes.delete(e),this.disposeHitArea(e),this.disposeGlare(e),e==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:o}=oi(t.altitudeDeg,t.azimuthDeg,Es),c=this.cloudTransmission(t),h=this.arrivingIlluminance(t,s,c),d=Ee.unitLuminance(n);let u=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/Es)**2,f=[0,1,2].map(v=>d[v]*h[v]/(this.sunBeamFraction*p));this.sunDiscRadiance=f;const m=f.map(v=>Math.min(Ee.BRIGHTEST_RELATIVE,v));u instanceof xe||(this.disposeMesh(u),u=new xe(new hn(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)),u.material.color.setRGB(m[0],m[1],m[2]),u.scale.setScalar(i)}else{if(!(u instanceof Cs)){this.disposeMesh(u);const m=new ct;m.setAttribute("position",new mt(new Float32Array(3),3)),m.setAttribute("color",new mt(new Float32Array(3),3)),u=new Cs(m,Ne.material(Dl[Dl.length-1].size,!1)),Ne.track(u),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)}const p=u.geometry.getAttribute("color"),f=e.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*h[0]*f,d[1]*h[1]*f,d[2]*h[2]*f),p.needsUpdate=!0}if(u.position.set(r,a,o),this.setHitArea(e,r,a,o,i),e==="sun"&&(this.sunArriving=h),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,a,o,h,i/Es*(180/Math.PI),Ee.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,a*p+this.celestialGroup.position.y,o*p),this.lensFlare||(this.lensFlare=$L(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<Rp){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=oi(e.altitudeDeg,e.azimuthDeg,Es),a=this.cloudTransmission(e),o=this.arrivingIlluminance(e,e.magnitude,a),c=e.radiusDeg??ts.MEAN_RADIUS_DEG,h=Es*Math.tan(c*Ri),d=Math.max(Xr(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Es)**2,u=new re(...o.map(m=>Math.min(Ee.BRIGHTEST_RELATIVE,m/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(Xr(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof Uh?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=NM(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new Uh(new Ep({map:NM(e.phase),color:u,fog:!1,blending:An,depthWrite:!1})),f.userData.phaseKey=p,this.celestialGroup.add(f),this.bodyMeshes.set(i,f)),f.scale.set(h*2,h*2,1),f.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,o,c)}bentLight(e,t,i=LO){const[n,s,r]=this.arrivingIlluminance(e,t,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(e,t){return Ee.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new re;pointToPixel(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),t=(this.camera.fov*Math.PI/180/e)**2;return Math.min(1,Ne.CONE_SOLID_ANGLE/t)}pointScratch=new ne;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(e,t,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),s=Nt.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=cr.luminanceOf([e.r,e.g,e.b]);return t>0?[e.r/t,e.g/t,e.b/t]:[1,1,1]}setHitArea(e,t,i,n,s){let r=this.hitAreas.get(e);if(!r){const o=new Ep({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Uh(o),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const a=s*2;r.scale.set(a,a,1)}disposeHitArea(e){const t=this.hitAreas.get(e);t&&(t.removeFromParent(),t.material.dispose(),this.hitAreas.delete(e))}setGlare(e,t,i,n,s,r,a=0){if(Ln.radiusDeg(Ln.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(e);return}let o=this.glareSprites.get(e);o||(o=new Ln(`veil:${e}`),this.celestialGroup.add(o.mesh),this.glareSprites.set(e,o)),o.shine({x:t,y:i,z:n},s,r,a)}disposeGlare(e){const t=this.glareSprites.get(e);t&&(t.mesh.removeFromParent(),t.dispose(),this.glareSprites.delete(e))}buildComet(e,t){const i=e&&`comet:${e.id}`;if(!e||!i||e.magnitude>t){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=Ml(e.magnitude,t),s=y0(n);this.cometKey=i,this.setBodyMesh(i,e.position,L0*(.5+.5*n),new re(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new Vs(Es),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new ji,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:ep},0);return}const s=this.lowerCloudCover(),r=ut.deckLitUntilDeg(ut.DECK_HEIGHT_M),a=e.altitudeDeg>-r?e:t,o=this.bentLight(a,a===e?Et.SUN_MAGNITUDE:t.magnitude),c=ut.strength(i,s,a.altitudeDeg,r)*o.scale,{x:h,y:d,z:u}=oi(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},a.altitudeDeg,c,o.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??ep},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??kp,this.weather.rareIceCrystals)}buildRainbow(e,t){this.rainbow||(this.rainbow=new wl,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=e.altitudeDeg>0,s=n?e:t,r=this.lowerCloudCover(),a=this.bentLight(s,n?Et.SUN_MAGNITUDE:t.magnitude,OO),o=jn.strength(i,r,s.altitudeDeg)*a.scale;if(o<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:d}=oi(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},o,a.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new ho,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=Ks.galactic(i,n),r=Ee.directionOf(s.centre),a=Ee.directionOf(s.rotation),o=Ee.directionOf(s.pole),c=new lt().set(r.x,r.y,r.z,a.x,a.y,a.z,o.x,o.y,o.z),h=Ee.directionOf(Ks.eclipticPole(i,n)),d=Ee.directionOf(e.sun),u=d.clone().addScaledVector(h,-d.dot(h)).normalize();this.skyGlow.update({galactic:c,eclipticPole:h,sunLongitude:u,sunDirection:d,sunAltitudeDeg:e.sun.altitudeDeg,moon:{direction:Ee.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:de.phaseAngleOf(e.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new _(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:n}=oi(e.altitudeDeg,e.azimuthDeg,1);return new _(t,i,n).normalize()}buildNovae(e,t){const i=new Set;for(const n of e){if(n.magnitude>t)continue;const s=`nova:${n.id}`;i.add(s);const r=Ml(n.magnitude,t),a=y0(r);this.setBodyMesh(s,n.position,L0*(.5+.5*r),new re(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(e,t){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of e){if(n.magnitude>t)continue;i.add(n.body);const s=Ml(n.magnitude,t),r=y0(s),a=mP[n.body]??new re(1,1,1),o=new re(a.r*r,a.g*r,a.b*r),c=L0*(.5+.5*s);this.setBodyMesh(n.body,n.position,c,o,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(e,t){if(this.namedStars=[],!e||e.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=e,r=new Tr(n,s),a=V0(1337),o=[],c=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const d=i.mag[h];if(d>t)break;const{altitudeDeg:u,azimuthDeg:p}=r.position(i.ra[h],i.dec[h]);if(u<uM)continue;const{x:f,y:m,z:v}=oi(u,p,k0);o.push({x:f,y:m,z:v,brightness:Ml(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(g=>g*Nt.illuminanceOf(d)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of s2){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<uM)continue;const{x:p,y:f,z:m}=oi(d,u,k0);this.namedStars.push({star:h,direction:new _(p,f,m).normalize(),altitudeDeg:d})}this.starTiers=Dl.map((h,d)=>{const u=o.filter(M=>vm(M.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),m=new Float32Array(u.length*3),v=new Float32Array(u.length),g=new Float32Array(u.length);u.forEach((M,S)=>{p[S*3]=M.x,p[S*3+1]=M.y,p[S*3+2]=M.z,f[S]=M.brightness,m.set(M.illuminance,S*3),v[S]=M.phase,g[S]=M.speedFactor});const y=new ct;y.setAttribute("position",new mt(p,3)),y.setAttribute("seed",new mt(v.map(M=>M/(2*Math.PI)),1));const w=new mt(new Float32Array(u.length*3),3);y.setAttribute("color",w);let b=this.starTiers[d]?.points;return b?(b.geometry.dispose(),b.geometry=y):(b=new Cs(y,Ne.material(h.size)),Ne.track(b),this.celestialGroup.add(b)),{points:b,colorAttribute:w,brightness:f,illuminance:m,phase:v,speedFactor:g}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){Ne.setTime(e);const t=this.relativeScale;if(t!==this.starColoursRelative){this.starColoursRelative=t;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]*t,n[s*3+1]=i.illuminance[s*3+1]*t,n[s*3+2]=i.illuminance[s*3+2]*t;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new th(this.celestialGroup,O0,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 e=this.lowerCloudCover();if(e<=0){this.disposeCloudSystem();return}const t=this.weather.cloudDarkness,i=new re(Ho[0]+(F0[0]-Ho[0])*t,Ho[1]+(F0[1]-Ho[1])*t,Ho[2]+(F0[2]-Ho[2])*t);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=e,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=Iv(i,e,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=_v(O0);this.cloudMesh=new xe(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(e=>e.type!=="cirrus").reduce((e,t)=>e*(1-t.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(e=>e.type==="cirrus").reduce((e,t)=>e*(1-t.coverage),1):this.weather.highCloudCover}buildCirrus(){const e=this.weather.highCloudCover??0;if(this.layeredClouds||e<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=e,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:t,uniforms:i}=Iv(new re(...Ho),e,ep,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new xe(_v(O0*1.04),t),this.cirrusMesh.renderOrder=wM-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 e=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(e)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,e)}faceCloudDeck(e,t){const i=t<0;e.scale.y=i?-1:1,e.renderOrder=i?th.deckOrder(!0,0,1):wM}cloudLayerOffset(){const t=((this.weather.cloudBaseM??zv)-this.observerElevationM)*P0;return Math.sign(t||1)*Math.max(Math.abs(t),ZO)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(d=>d!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,a]=this.cloudBeam.map(d=>d/Math.PI),o=this.lightningLevel*G0*this.relativeScale/Math.PI,c=new re(t[0]+Gr.r*o,t[1]+Gr.g*o,t[2]+Gr.b*o);this.layeredClouds?.setLighting(n.clone(),new re(s,r,a),c,c);const h=Math.max(0,n.y);for(const d of i)d.sunDir.value.copy(n),d.sunColor.value.setRGB(s*h,r*h,a*h),d.ambientColor.value.copy(c)}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(e){return rP(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,B0],[this.rainSplashSystem?.points,Go],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:U0[this.weather.precipitationType].poolSize]];for(const[t,i]of e)t&&i!==void 0&&t.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=EM(H0(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const e=this.weather.precipitationType;if(e==="none")return;if(e==="rain"){this.buildRain();return}const t=U0[e],i=t.poolSize,n=V0(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),o=new Float32Array(i),c=new Float32Array(i),h=new Float32Array(i),d=new Float32Array(i),u=new Float32Array(i),p=new Float32Array(i),f=new Float32Array(i);for(let w=0;w<i;w++){const b=n()*Math.PI*2,M=n()*t.radiusM;s[w*3]=Math.cos(b)*M,s[w*3+1]=Tc+n()*(t.topYM-Tc),s[w*3+2]=Math.sin(b)*M,r[w]=n()*Math.PI*2,a[w]=.7+n()*.6,o[w]=.6+n()*.8,c[w]=.4+n()*1.2}const m=new ct;m.setAttribute("position",new mt(s,3)),m.setDrawRange(0,this.precipitationCount(i));const v={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new re(...this.baseFogColor)},uTexture:{value:gP(e)},uNearFocusDistance:{value:_M},uHazeDistance:{value:t.radiusM*RM}},g=new Ct({uniforms:v,vertexShader:xP,fragmentShader:SP,transparent:!0,depthWrite:!1});this.precipitationUniforms=v;const y=new Cs(m,g);y.renderOrder=N0,this.scene.add(y),this.precipitationPoints=y,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=o,this.precipitationWobbleAmpJitter=c,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=d,this.precipitationBounceDuration=u,this.precipitationBounceVelX=p,this.precipitationBounceVelZ=f}updatePrecipitation(e,t){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=U0[i];if(this.precipitationUniforms?.uColor.value.copy(Ee.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*Ri,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,o=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,m=this.precipitationBounceDuration,v=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,y=i==="snow"&&d&&u,w=i==="hail"&&p&&f&&m&&v&&g;for(let b=0,M=0;b<o.length;b+=3,M++){if(w&&p[M]>0){if(p[M]-=t,p[M]<=0){const x=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;o[b]=Math.cos(x)*T,o[b+1]=n.topYM,o[b+2]=Math.sin(x)*T,p[M]=0}else{const x=1-p[M]/m[M];o[b+1]=Tc+Math.sin(Math.PI*x)*f[M],o[b]=ip(o[b]+(r+v[M])*t,n.radiusM),o[b+2]=ip(o[b+2]+(a+g[M])*t,n.radiusM)}continue}let S=0,E=0;if(y){const x=oP*d[M],T=lP*u[M];S=Math.sin(e*x*Math.PI*2+c[M])*T,E=Math.sin(e*x*Math.PI*2+c[M]+Math.PI/2)*T}if(o[b]+=(r+S)*t,o[b+1]-=n.fallSpeedMPerS*h[M]*t,o[b+2]+=(a+E)*t,o[b]=ip(o[b],n.radiusM),o[b+2]=ip(o[b+2],n.radiusM),o[b+1]<Tc){if(w){f[M]=OM*(.2+Math.random()*1.6),m[M]=cP*(.5+Math.random()),p[M]=m[M];const D=Math.random()*Math.PI*2,R=hP*(f[M]/OM);v[M]=Math.cos(D)*R,g[M]=Math.sin(D)*R,o[b+1]=Tc;continue}const x=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;o[b]=Math.cos(x)*T,o[b+1]=n.topYM,o[b+2]=Math.sin(x)*T}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=H0(this.weather.precipitationIntensity);this.rainSystem=GL({count:B0,radiusM:jh,heightM:QO,bottomYM:MM,overallSpeed:eP,color:SM.clone(),opacity:.85,visibleCount:this.precipitationCount(B0),speedStreak:EM(e),pixelSize:kM,seed:9001,nearFocusDistanceM:_M,hazeDistanceM:jh*RM,hazeColor:new re(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=N0,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=V0(4242),t=new Float32Array(Go*3),i=new Float32Array(Go),n=new Float32Array(Go),s=new Float32Array(Go);for(let h=0;h<Go;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*jh;t[h*3]=Math.cos(d)*u,t[h*3+1]=MM,t[h*3+2]=Math.sin(d)*u,n[h]=PM(AM,TM),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new ct;r.setAttribute("position",new mt(t,3));const a=new mt(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Go));const o=new Ct({uniforms:{uMaxSize:{value:sP},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:IM.clone()},uTexture:{value:yP()}},vertexShader:wP,fragmentShader:MP,transparent:!0,depthWrite:!1}),c=new Cs(r,o);c.renderOrder=N0,this.scene.add(c),this.rainSplashSystem={points:c,positions:t,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 e=this.rainSystem;if(!e)return;const t=this.weather.windDirectionDeg*Ri;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-H0(this.weather.precipitationIntensity),-Math.cos(t)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);e.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(e){const t=this.rainSystem;if(!t)return;t.uniforms.uTime.value+=e,t.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),t.uniforms.uColor.value.copy(Ee.litBySky(SM,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(Ee.litBySky(IM,this.baseFogColor));const n=this.weather.windDirectionDeg*Ri,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=jh,o=h=>(h%(a*2)+a*3)%(a*2)-a;t.uniforms.uWindOffset.value.set(o(t.uniforms.uWindOffset.value.x+s*e),o(t.uniforms.uWindOffset.value.y+r*e)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const c=Math.abs(this.rainCameraDirection.y);if(Math.abs(c-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=c;const h=CM+(1-CM)*(1-c),d=LM+(1-LM)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=kM*h*(.5+.5*d)}this.updateRainSplashes(e)}updateRainSplashes(e){const t=this.rainSplashSystem;if(!t||e<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=t,a=r.array;for(let o=0,c=0;o<i.length;o+=3,c++){if(n[c]+=e,n[c]>=s[c]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*jh;i[o]=Math.cos(h)*d,i[o+2]=Math.sin(h)*d,s[c]=PM(AM,TM),n[c]=0}a[c]=n[c]/s[c]}t.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(e){this.lightningFlashes=e}updateLightning(e){let t,i=0;if(this.lightningArmed)for(const o of this.lightningFlashes){if(o.t>e)break;const c=xn.brightnessAt(o,e);c>i&&(t=o,i=c)}const n=t?Math.min(1,Math.max(.1,(pP/t.distanceM)**2)):0,s=i*n*(t?.cloudToGround?1:.6);if(s===this.lightningLevel&&!t?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const o=this.scene.fog,c=s*G0*this.relativeScale/Math.PI;o.color.setRGB(this.airlight[0]+Gr.r*c,this.airlight[1]+Gr.g*c,this.airlight[2]+Gr.b*c)}const r=this.skyMesh?.material?.color;if(r){const o=s*fP;r.setRGB(1+o*Gr.r,1+o*Gr.g,1+o*Gr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*G0*this.relativeScale,t){const{x:o,y:c,z:h}=oi(25,t.azimuthDeg,Es);this.lightningLight.position.set(o,c,h)}this.lightningBolt||(this.lightningBolt=new uo(Es*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,a),this.render()}buildCompassLabels(){this.compassSprites=$O.map(e=>{const t=kl.point(e,this.compassPoints),i=new Ep({map:EP(t),depthTest:!1,fog:!1}),n=new Uh(i),{x:s,y:r,z:a}=oi(0,e,gM);return n.position.set(s,r,a),n.scale.set(tp,tp,1),n.renderOrder=YO,n.layers.set(R0),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=vM*Math.PI/360,i=tp*Math.tan(e)/Math.tan(t);for(const n of this.compassSprites)n.scale.set(i,i,1)}disposeCompassLabels(){for(const e of this.compassSprites)e.removeFromParent(),e.material.map?.dispose(),e.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const e of this.starTiers)this.disposeMesh(e.points);this.starTiers=[]}disposeMesh(e){if(!e)return;e.removeFromParent(),"geometry"in e&&e.geometry.dispose();const t=e.material;for(const i of Array.isArray(t)?t:[t]){const n=i.map;n&&n.dispose(),i.dispose()}}}const Ri=Math.PI/180;function Xr(l,e,t){return Math.max(e,Math.min(t,l))}function PM(l,e){return l+Math.random()*(e-l)}function ip(l,e){return(l%(e*2)+e*3)%(e*2)-e}let np,sp;function gP(l){switch(l){case"snow":return vP();case"hail":return bP()}}function vP(){if(np)return np;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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)"),t.fillStyle=i,t.fillRect(0,0,l,l),np=new Lo(e),np}function bP(){if(sp)return sp;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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)"),t.fillStyle=i,t.fillRect(0,0,l,l),sp=new Lo(e),sp}let rp;function yP(){if(rp)return rp;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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)"),t.fillStyle=i,t.fillRect(0,0,l,l),rp=new Lo(e),rp}const wP=`
11155
+ `,transparent:!0,blending:An,depthWrite:!1,side:Hi,fog:!1});this.object=new xe(new hn(Fb.RADIUS,128,32,0,Math.PI*2,0,Nt.MAX_ANGLE_RAD),t),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(e,t){if(!e||!t){this.object.visible=!1;return}this.towards.set(e.x,e.y,e.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<Nt.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=js.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=js.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class Nf{constructor(e){this.generator=e}static SIZE=128;target=new $d(Nf.SIZE,{type:Jt,generateMipmaps:!1,minFilter:Dt,magFilter:Dt});camera=new kb(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(e,t,i,n=[]){const s=e.shadowMap.autoUpdate;let r=!1;t.traverse(o=>{const c=o;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?s:!1;const a=n.map(o=>o.visible);for(const o of n)o.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),n.forEach((o,c)=>{o.visible=a[c]}),e.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 Jn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){Jn.install(),this.generator=new Sv(e),this.eye=new Nf(this.generator)}static decor;refresh(e,t,i,n,s,r,a,o=[],c,h=Jn.REFRESH_MS){for(const v of[...this.probes.keys()])n.some(g=>g.id===v&&g.shiny)||(this.probes.get(v).dispose(),this.probes.delete(v));const d=[{probe:this.eye}];for(const v of n){if(!v.shiny)continue;let g=this.probes.get(v.id);g||(g=new Nf(this.generator),this.probes.set(v.id,g)),d.push({probe:g,reflector:v})}const u=performance.now(),p=()=>d.filter(({probe:v})=>v.capturedVersion!==a),f=p().filter(({probe:v})=>u-v.capturedAtMs>=h);if(f.length>0){const v=f.reduce((g,y)=>y.probe.capturedAtMs<g.probe.capturedAtMs?y:g);if(v.reflector){const g=v.reflector.holder.getWorldPosition(this.scratch);v.probe.capture(e,t,g,[v.reflector.holder,...s]),Jn.reflectOn(v.reflector.holder,v.probe)}else{v.probe.capture(e,t,i,[...s,...o]),c?.(v.probe.sharp),Jn.decor=v.probe.filtered;for(const g of r)Jn.reflectOn(g,v.probe);for(const g of n)g.shiny||Jn.reflectOn(g.holder,v.probe)}v.probe.capturedVersion=a}const m=p();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:v})=>h-(u-v.capturedAtMs))))}scratch=new _;static reflectOn(e,t={filtered:Jn.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Kd?t.sharp&&s.setSurroundings(t.sharp):s instanceof go&&t.filtered&&s.envMap!==t.filtered&&(s.envMap=t.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const e of this.probes.values())e.dispose();this.generator.dispose()}static installed=!1;static install(){if(Jn.installed)return;Jn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!dt.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}dt.lights_fragment_maps=dt.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function IO(l,e){return JSON.stringify(l.cloudLayers)===JSON.stringify(e.cloudLayers)&&l.cloudCover===e.cloudCover&&l.cloudDarkness===e.cloudDarkness&&l.cloudBaseM===e.cloudBaseM&&l.highCloudCover===e.highCloudCover&&l.iceCrystalAlignment===e.iceCrystalAlignment&&l.rareIceCrystals===e.rareIceCrystals&&l.lowerCloudCover===e.lowerCloudCover&&l.relativeHumidity===e.relativeHumidity&&l.precipitationType===e.precipitationType&&l.precipitationIntensity===e.precipitationIntensity&&l.precipitationAmount===e.precipitationAmount&&l.windDirectionDeg===e.windDirectionDeg&&l.windSpeed===e.windSpeed&&l.storm===e.storm}const ju=900,_0=1,lM=4,R0=5,Zu=.5,Ju=Yt.GROUND_RADIUS_M;function cM(l){return Yt.groundRadiusFor(l)}const D0=.5,k0=850,C0=.03,_O=.015,Es=850,Yh=300,to=120,RO=700,DO=3.5,Qu=20,hM=.04,kO=.26,dM=4,L0=1.5,uM=-1,CO=.01,Rp=-4,LO=2,OO=20,ep=2600,PO=.97,NO=.38,qh=Rp,FO=8,UO=2,pM=1500,zO=.7,BO=.3,HO=.32,GO=.65,fM=2.4,VO=.9,WO=400,$O=[0,45,90,135,180,225,270,315],KO=2,XO=16,mM=4e3,gM=880,tp=40,vM=60,YO=10,qO=1,jO=Yt.REBUILD_DISTANCE_M,bM=.265,yM=[[0,0],...Array.from({length:8},(l,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*bM,Math.sin(t)*bM]})],O0=700,P0=250/zv,ZO=12,wM=5,N0=6,Ho=[.92,.92,.95],F0=[.15,.15,.19],U0={snow:{fallSpeedMPerS:2,size:.3,color:new re(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new re(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Tc=0,z0=0,JO=150,B0=3e3,jh=20,QO=15,MM=Tc,eP=40,xM=1,tP=9;function H0(l){return xM+(tP-xM)*l}const SM=new re(.75,.82,.92),iP=10,nP=.5;function EM(l){return Xr(l/iP,nP,1)}const Go=200,AM=.18,TM=.32,sP=.35,IM=new re(.85,.9,.98),_M=5,RM=.85,DM=.01;function rP(l,e,t=1){return Math.round(l*(DM+(1-DM)*e)*t)}function aP(l,e){return JSON.stringify(l.cloudLayers)===JSON.stringify(e.cloudLayers)&&l.cloudCover===e.cloudCover&&l.cloudDarkness===e.cloudDarkness&&l.cloudBaseM===e.cloudBaseM&&l.highCloudCover===e.highCloudCover&&l.iceCrystalAlignment===e.iceCrystalAlignment&&l.lowerCloudCover===e.lowerCloudCover}const kM=230,CM=.7,LM=.05,oP=.6,lP=.7,cP=.15,OM=.35,hP=3,dP=1/12,uP=.5,Gr=new re(.82,.86,1),pP=2500,fP=1.6,G0=15,mP={Venus:new re(1,.96,.85),Mars:new re(1,.55,.4),Jupiter:new re(.95,.87,.72),Saturn:new re(.92,.86,.68)};class Ee{renderer;scene=new Or;phenomena=new Mr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;onReferencesSettled;camera;celestialGroup=new zt;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(e,t){if(this.skyHoldUntilMs===null)return e;this.arrivalsPending++;let i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=t===void 0?void 0:setTimeout(n,t);return t!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+t),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),t+20))),e.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(e){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),e&&this.awaitArrival(e).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+mM,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),mM+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new Mt;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new ne;decorModelProvider=_p[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new bt(e=>this.awaitArrival(this.loadBodyModel(e)),()=>this.render(),()=>this.relativeScale);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(e){return(e.sizeM?.lengthM??Ee.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*Ee.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;beams=[];beamSystem;beamSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new hw(16777215,0);celestialLightTarget=new Gi;skyLight=new z_(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 Ap;weather=qf;observerElevationM=0;siteElevationM=0;air=new ar;groundRadius=Ju;terrainRadius=Ju;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new _;cloudFieldOffset=new _;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new _;rainLastVerticalFacing=-1;rainViewportSize=new ne;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new hw(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new _;sunVisible=!1;lensFlareScratch=new _;sunOcclusionRaycaster=new Ap;sunOcclusionDirectionScratch=new _;sunOcclusionRightScratch=new _;sunOcclusionUpScratch=new _;ufoOcclusionRaycaster=new Ap;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=bi.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(e){return Math.max(3,Math.round(6e6/Math.max(1,e)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;reentrySystem;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new Xd;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=_2()){this.renderer=new eL({canvas:e,antialias:!0}),this.resolution=new jt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=od,this.camera=new Ls(60,e.width/Math.max(e.height,1),.1,ju*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=t,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-to,this.celestialLight.shadow.camera.right=to,this.celestialLight.shadow.camera.top=to,this.celestialLight.shadow.camera.bottom=-to,this.celestialLight.shadow.camera.near=Es-Yh,this.celestialLight.shadow.camera.far=Es+Yh,this.celestialLight.shadow.bias=-.03/(2*Yh),this.celestialLight.shadow.normalBias=hM,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Gr),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 At(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(e,t){this.cssSize.width=e,this.cssSize.height=t,this.renderer.setSize(e,t,!1),this.camera.aspect=e/Math.max(t,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(e){e!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=e,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(e,t={}){this.cloudOffsetM.set(e.x,0,e.z),this.cloudLayerOffsetsM=t,this.layeredClouds?.setOffsets(e,t),this.cloudFieldOffset.set(e.x*P0,0,e.z*P0);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(e){const t=((e.rollDeg??0)+this.gaitOffset.rollDeg)*Ri,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Ri;e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Ri,t,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,t,"YXZ"),e.elevationM!==this.observerElevationM&&(this.observerElevationM=e.elevationM,this.syncCloudLayer(),Math.abs(cM(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Ju),this.camera.far=Math.max(ju*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),e.lat!==void 0&&e.lng!==void 0&&this.placeTerrain(e.lat,e.lng,0,0),this.poseElevationM=e.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+e.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==e.fovDeg&&(this.camera.fov=e.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(e){this.stopTerrainFade(),this.terrainProviders=e,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),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;observerRoute;setObserverRoute(e){this.observerRoute=e,this.decorTerrainRadiusM=Ee.terrainReachFor(this.decorObjects,e)}decorTerrainRadiusM=0;static terrainReachFor(e,t){return Yt.decorReachFor(e,t)}placeTerrain(e,t,i,n){const s=(r,a)=>{const o=st(a.lat,a.lng,e,t);r.position.x=o.x-i,r.position.z=o.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}}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaited!==n){this.patchesAwaited=n;const u=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{this.terrainProviders===u&&this.setTerrainOrigin(e,t,i)}),Ee.TERRAIN_PATIENCE_MS)}return}const d=n.nearest(e,t);d&&(e=d.lat,t=d.lng,s=d.radiusM)}const r=s??Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:d,z:u}=st(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(d*d+u*u)<jO*(r/Ju))return}const a=this.terrainRadius,o=this.terrainMeshOrigin;o!==void 0&&Math.hypot(st(e,t,o.lat,o.lng).x,st(e,t,o.lat,o.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(Vw(e,t,this.terrainProviders,r,{route:this.observerRoute}),Ee.TERRAIN_PATIENCE_MS).then(({mesh:d,attribution:u,originElevationM:p,water:f,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(p??0),this.anchorGrassTo(d,e,t);const v=this.terrainMesh,g=this.terrainMeshOrigin,y=g?st(e,t,g.lat,g.lng):void 0;v&&y&&Math.hypot(y.x,y.z)<=a&&(d.position.y=v.position.y+this.groundYOfPatch(v,y.x,y.z)),v&&g&&y&&Math.hypot(y.x,y.z)<=a?this.crossfadeTerrain(d,v,g):this.disposeMesh(this.terrainMesh),d.renderOrder=qO,this.terrainMesh=d,this.terrainMeshOrigin={lat:e,lng:t},this.compileNextFrameOffThread(),this.terrainAttribution=u,this.scene.add(d),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,r),this.buildWater(e,t,r,f,m),this.buildRailways(e,t,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(e,t,r,d,p),this.render(),i?.()}).catch(d=>{console.warn("Terrain build failed, keeping the flat ground fallback:",d),i?.()})}buildFarRing(e,t,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,o=Yt.beamReachFor(this.beams,{lat:e,lng:t});if(!Yt.needsFarRing(i,a,o)){this.dropFarRing();return}if(this.farRing){const{x:f,z:m}=st(e,t,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(f,m)<i*Ee.FAR_RING_KEPT_SHARE)return}const c=this.terrainProviders.patches,h=c?.farRingOf?.(e,t);if(c&&!h){this.dropFarRing();return}const d=h?.radiusM??Yt.FAR_RING_RADIUS_M,u=++this.farRingToken,p=this.terrainProviders;this.awaitArrival(Vw(e,t,{elevation:p.elevation,imagery:p.imagery},d,void 0,{innerM:i*Ee.FAR_RING_OPEN_SHARE,referenceElevationM:s}),Ee.TERRAIN_PATIENCE_MS).then(({mesh:f})=>{if(u!==this.farRingToken||this.terrainProviders!==p){this.disposeMesh(f);return}this.dropFarRing(),this.farRingToken=u,f.renderOrder=Ee.FAR_RING_RENDER_ORDER,f.position.y=n.position.y-Ee.FAR_RING_DROP_M;const m=f.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:f,origin:{lat:e,lng:t}},this.farRingRadiusM=d,this.scene.add(f),f.position.x=n.position.x,f.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},f=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",f))}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(e,t,i){if(this.grassReference){const r=st(this.grassReference.lat,this.grassReference.lng,t,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:t,lng:i};const n=st(this.grassReference.lat,this.grassReference.lng,t,i);e.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t,i){this.stopTerrainFade();const n=e.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)/Ee.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:t,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const e=this.terrainMesh?.material;e&&(e.opacity=1,e.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=Yt.ROADS_MAX_RADIUS_M;buildRoads(e,t,i){const n=this.terrainProviders.roads;if(!n||i>Ee.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===e&&s.lng===t&&s.radiusM===i){this.drapeRoads(s.ways,e,t,n.contemporary);return}s&&Math.hypot(st(e,t,s.lat,s.lng).x,st(e,t,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,e,t,n.contemporary),this.awaitArrival(n.getRoads(md(e,t,i)),Ee.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t||(this.roadWays={lat:e,lng:t,radiusM:i,ways:r},this.drapeRoads(r,e,t,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(e,t,i,n,s){const r=this.terrainProviders.water;if(!r||i>Ee.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,e,t,i),Ee.ROADS_PATIENCE_MS).catch(o=>console.warn("Water not drawn:",o));return}const a=this.waterSurfaces;if(a&&a.lat===e&&a.lng===t&&a.radiusM===i){this.drapeWater(a.surfaces,e,t,i);return}a&&Math.hypot(st(e,t,a.lat,a.lng).x,st(e,t,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,e,t,i),this.awaitArrival((s??r.getWater(md(e,t,i))).then(o=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:o},this.drapeWater(o,e,t,i)}),Ee.ROADS_PATIENCE_MS).catch(o=>{console.warn("Water unavailable, drawing none:",o)})}async drapeWater(e,t,i,n){if(e.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),n,this.patchSpacingM(r)),Jn.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=ae(async()=>{const{WaterSystem:e}=await import("./WaterSystem-KGutPogf.js");return{WaterSystem:e}},[],import.meta.url).then(({WaterSystem:e})=>{const t=new e;return this.scene.add(t.group),this.waterSystem=t,t})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(e,t,i){const n=this.terrainProviders.railways;if(!n||i>Ee.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===e&&s.lng===t&&s.radiusM===i){this.drapeRailways(s.lines,e,t,i);return}s&&Math.hypot(st(e,t,s.lat,s.lng).x,st(e,t,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,e,t,i),this.awaitArrival(n.getRailways(md(e,t,i)).then(r=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.railwayLines={lat:e,lng:t,radiusM:i,lines:r},this.drapeRailways(r,e,t,i)}),Ee.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(e,t,i,n){if(!this.railwaySystem&&!e.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(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),n),Jn.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=ae(async()=>{const{RailwaySystem:e}=await import("./RailwaySystem-7MMun4zU.js");return{RailwaySystem:e}},[],import.meta.url).then(({RailwaySystem:e})=>{const t=new e;return this.scene.add(t.group),this.railwaySystem=t,t})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(e){e!==this.statedRoads&&(this.statedRoads=e,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const e=this.terrainMesh;e&&(this.roadSystem.group.position.copy(e.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(e)),this.roadSystem.setStated(this.statedRoads,(t,i)=>this.groundYOfPatch(e,t,i)))}setTraces(e,t=new Map){e===this.traces&&t===this.traceLabels||(this.traces=e,this.traceLabels=t,!(e.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(e){e!==this.tracesShown&&(this.tracesShown=e,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=ae(async()=>{const{TraceSystem:e}=await import("./TraceSystem-lNFPtyqy.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(R0);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainMeshOrigin;!e||!t||!i||(e.group.position.copy(t.position),e.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(t,n,s)))}buildingFootprints(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=me.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(e,t){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?st(i.lat,i.lng,e,t):{x:0,z:0}}surveyedLamps(e,t){const i=this.decorOriginInRoads(e,t);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(e,t){this.lampNudges.clear();const i=this.decorOriginInRoads(e,t);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(e,t){return e.length!==t.length||e.length===0?!1:e.every((i,n)=>{const s=t[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(e){const t=this.roadWays,i=this.terrainProviders.roads;if(!t||!i)return;const n=this.wallsOf(e,t.lat,t.lng),s=this.roadWalls;s?.lat===t.lat&&s.lng===t.lng&&s.walls.length===n.length&&s.walls.every((a,o)=>a.what===n[o].what&&Math.hypot(a.x-n[o].x,a.z-n[o].z)<.1)||this.drapeRoads(t.ways,t.lat,t.lng,i.contemporary)}wallsOf(e,t,i){const n=this.decorOriginInRoads(t,i);return e.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(e,t,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(e,t,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius,new Si(this.buildingFootprints(t,i),this.surveyedLamps(t,i))),this.roadWalls={lat:t,lng:i,walls:this.wallsOf(this.decorObjects,t,i)},this.lampsToKerb(t,i),this.roadAttribution=e.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(e){this.showCompass!==e&&(this.showCompass=e,this.disposeCompassLabels(),e&&this.buildCompassLabels(),this.render())}setCompassPoints(e){this.compassPoints!==e&&(this.compassPoints=e,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[e,t,i]=this.sunArriving,n=Math.max(t,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(e/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=Ln.K*t*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(e){this.compassHovered!==e&&(this.compassHovered=e,this.updateCompassVisibility())}setCompassForced(e){this.compassForced!==e&&(this.compassForced=e,this.updateCompassVisibility())}updateCompassVisibility(){const e=this.compassHovered||this.compassForced;if(this.compassSprites.some(t=>t.visible!==e)){for(const t of this.compassSprites)t.visible=e;this.developingExposure&&!this.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(e){if(IO(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!aP(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=ar.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Oa.steppedOpticalDepth(e.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=e.storm&&e.cloudDarkness>=uP,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects===e)return;if(Ee.onlyMoved(this.decorObjects,e)){this.decorObjects=e,this.decorTerrainRadiusM=Ee.terrainReachFor(e,this.observerRoute),this.layStreetsIfWallsMoved(e);return}this.decorObjects=e,this.decorTerrainRadiusM=Ee.terrainReachFor(e,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),me.dispose(i);this.decorGroups.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const t=e.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,FO);for(const i of e){const n=me.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&t.includes(i)&&this.addStreetlightLight(i.id,n,t.indexOf(i)<UO,i.lamp),i.model&&i.id.startsWith(Un.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.layStreetsIfWallsMoved(e),e.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(e){this.decorSunlight=e}setContrails(e){e!==this.contrails&&(this.contrails=e,!(e.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(e){this.contrailSunlight=e}loadContrailSystem(){return this.contrailSystemLoading??=ae(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-CXR_fe3m.js");return{ContrailSystem:e}},__vite__mapDeps([2,3]),import.meta.url).then(({ContrailSystem:e})=>{const t=new e;this.scene.add(t.group),this.contrailSystem=t})}contrailTint(e){const t=this.contrailSunlight.get(e),i=this.lastAstronomy?.sun,n=Ee.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(t&&i){const a=fs.litFraction(t.sunElevationDeg,t.heightM);if(a>0){const o=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=Nt.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*c*o[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setBeams(e){e!==this.beams&&(this.beams=e,this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),!(e.length===0&&!this.beamSystem)&&this.loadBeamSystem().then(()=>{this.updateBeams(),this.render()}))}get beamSegmentCount(){return this.beamSystem?.segmentCount??0}loadBeamSystem(){return this.beamSystemLoading??=ae(async()=>{const{BeamSystem:e}=await import("./BeamSystem-CrrOjNqD.js");return{BeamSystem:e}},__vite__mapDeps([4,5]),import.meta.url).then(({BeamSystem:e})=>{const t=new e;this.scene.add(t.group),this.beamSystem=t})}updateBeams(){const e=this.decorReferencePose;!this.beamSystem||e?.lat===void 0||e.lng===void 0||this.beamSystem.update(this.beams,this.decorTime,{reference:{lat:e.lat,lng:e.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(t,i,n)=>this.transmittanceTo(t,i,n),groundYAt:(t,i)=>this.groundYUnder(t,i)})}updateContrails(){const e=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:e?oi(e.altitudeDeg,e.azimuthDeg,1):void 0},t=>this.contrailTint(t))}contrailPixelRad(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/e)}setDecorPresence(e){this.decorPresence=e}entryOfDecorModel(e){return this.decorModelProvider.entry(e).catch(()=>{})}setDecorModelProvider(e){this.decorModelProvider=e;const t=this.decorObjects;this.decorObjects=[],this.setDecor(t)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:e,z:t}=this.bodyOrigin,i=this.groundYUnder(e,t),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(e+s*n,t-r)-i}}get bodyEastScale(){const e=this.decorReferencePose,t=this.decorCurrentPose;return e?.lat===void 0||t?.lat===void 0?1:Math.cos(t.lat*Ri)/Math.cos(e.lat*Ri)}bodyMaskedByDecor(e,t){const i=this.decorGroups.get(t);return i?this.bodySystem.maskedShare(e,i):void 0}setBodies(e,t=0,i=e.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,o=this.scatteredSky,c=this.bodyEastScale;Math.abs(c-1)>1e-9&&(e=e.map(d=>({...d,eastM:d.eastM*c}))),this.bodySystem.set(e,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(d,u)=>this.groundYUnder(d,u),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(d,u,p)=>this.transmittanceTo(d,u,p),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},t,o?Object.assign((d,u)=>o.relativeOfLuminance(d,u),{recorded:o.recorded}):void 0,i),this.bodySystem.setSmoke(n,t),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 e=this.celestialLight.color,t=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,o,c)=>(a*t+(o+c)/2*s)/Math.PI;return[r(e.r,i.r,n.r),r(e.g,i.g,n.g),r(e.b,i.b,n.b)]}bodyOutline(e,t){return this.bodySystem.outlineOf(e,t)}documentUrl;modelUrl(e){return e.url?this.documentRelative(e.url):void 0}documentRelative(e){if(e.startsWith("data:"))return e;const t=this.documentUrl??(typeof location>"u"?void 0:location.href);return t?new URL(e,t).href:e}async loadBodyModel(e){const t=e.url?void 0:e.id?await this.decorModelProvider.entry(e.id):void 0,i=this.modelUrl(e)??t?.url,n=e.credit??t?.credit;if(!(!i||!n))return{scene:await I0(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg,bindings:t?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(Od(e))||!me.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const n=TO(i.scene);n.traverse(s=>{s instanceof xe&&(s.userData.sharedModel=!0)}),me.applyModelParameters(n,e.modelParameters,i.bindings),me.applyModel(t,e,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.decorModelCredits.set(e.id,i.credit)}standInScenes=new Map;async loadDecorModel(e,t,i=!1){const n=i?lf[e.kind]:Od(e);if(!(!n||!me.usesModel(e)))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 o=i||e.kind==="tree"?await this.standInScene(r):await I0(r);if(t!==this.decorModelToken||i&&!this.pendingTrafficModels.has(e.id))return;const c=this.decorGroups.get(e.id);if(!c)return;!i&&e.kind!=="tree"&&Jn.reflectOn(o);const h={ref:JSON.stringify(n),scene:o,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(e.id,h),this.applyLoadedDecorModel(e,c,h),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${e.id}":`,s)}}standInScene(e){let t=this.standInScenes.get(e);return t||(t=I0(e).then(i=>(/jungle-jim-realistic-trees/.test(e)||Jn.reflectOn(i),i)),this.standInScenes.set(e,t)),t}updateDecorAnchoring(e,t,i=0){this.decorReferencePose=e,this.decorCurrentPose=t,this.decorTime=i;const n=e?.lat!==void 0&&e.lng!==void 0&&t?.lat!==void 0&&t?.lng!==void 0?st(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(f=>f.observerSide!==void 0&&Ro(f.kind));this.terrainMesh&&t?.lat!==void 0&&t.lng!==void 0&&(this.placeTerrain(t.lat,t.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,o;if(s){const f=qs(s,i),m=me.occupantView(s,f.headingDeg),v=-(f.headingDeg??0)*Ri,g=m.x*Math.cos(v)+m.z*Math.sin(v),y=-m.x*Math.sin(v)+m.z*Math.cos(v),w=f.eastM+n.x,b=-f.northM+n.z;r.x=-(w+g),r.z=-(b+y),this.camera.position.y=this.groundYUnder(w,b)+m.eyeY,o=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Ri,-(m.headingDeg+this.indoorLookYawDeg)*Ri,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const c=this.findCabin(i,n,r);this.fitShadowToCabin(c.length>0),this.dimCabinSky(c),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(f=>[f.x,f.z,f.cos,f.sin,f.halfWidthM,f.halfLengthM,f.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 f of this.decorObjects){if(f.kind==="terrace")continue;const m=this.decorGroups.get(f.id);if(!m)continue;const v=qs(f,i),g=this.lampNudges.get(f.id),y=v.eastM+(g?.eastM??0)+n.x+r.x,w=-(v.northM+(g?.northM??0))+n.z+r.z,b=this.terrainMesh,M=`${b?.geometry.uuid}:${(y-(b?.position.x??0)).toFixed(3)}:${(w-(b?.position.z??0)).toFixed(3)}:${(b?.position.y??0).toFixed(3)}:${v.headingDeg}:${v.altitudeM}:${h}`;if(m.userData.footprintKey!==M){if(f.kind==="wire"){const O=me.wireGround(f,y,w,v.headingDeg,(N,C)=>this.groundYUnder(N,C));m.userData.footprintGroundY=O.startY,me.shearWire(m,me.sizeOf(f).lengthM,O.dropM)}else if(f.kind==="crossing"){const O=this.groundYUnder(y,w),N=-(v.headingDeg??0)*Ri,C=Math.cos(N),k=Math.sin(N);m.userData.footprintGroundY=O,xt.drape(me.bodyOf(m),(P,F)=>this.groundYUnder(y+P*C+F*k,w-P*k+F*C)-O)}else m.userData.footprintGroundY=this.groundUnderFootprint(f,y,w,v.headingDeg,v.altitudeM);m.userData.footprintKey=M}const E=v.altitudeM>Ee.AIRBORNE_M&&Math.hypot(y,w)<Ee.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY;if(m.position.set(y,E+v.altitudeM,w),f.kind==="crop"){const O=Math.hypot(y,w);m.visible=O<=JO}const x=this.decorPresence.get(f.id),T=x!==void 0&&(i<x.fromMs||i>x.untilMs);x&&(m.visible=!T);const D=this.decorSunlight.get(f.id);D&&!T&&this.lightFromAbove(m,D),v.headingDeg!==void 0&&(m.rotation.y=-v.headingDeg*Ri);const R=AT(f,i);if(R!==void 0&&Ee.turnHead(m,v.headingDeg??0,R),f.kind==="crop"&&m.visible){const O=this.terrainMesh,N=[O?.geometry.uuid,y-(O?.position.x??0),w-(O?.position.z??0),m.position.y-(O?.position.y??0),v.headingDeg,v.altitudeM].map(C=>typeof C=="number"?C.toFixed(4):C).join(":");m.userData.cropGroundKey!==N&&(me.fitCropToGround(m,(C,k)=>this.groundYUnder(C,k)+v.altitudeM),m.userData.cropGroundKey=N)}if(!T){const O=m.position.distanceTo(this.camera.position);a=Math.max(a,O),O<Ee.trafficModelRangeM(f)&&this.pendingTrafficModels.delete(f.id)&&this.loadDecorModel(f,this.decorModelToken)}}if(s&&o!==void 0){const f=this.decorGroups.get(s.id);f&&(this.camera.position.y=f.position.y+o)}this.updateContrails(),this.updateBeams();const d=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,u=this.beams?.length&&this.terrainMeshOrigin?Yt.beamReachFor(this.beams,this.terrainMeshOrigin):0,p=Math.max(ju*1.2,this.groundRadius*2.5,a*1.2,d*1.05,u*1.2);Math.abs(this.camera.far-p)>1&&(this.camera.far=p,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainYUnder(e,t);let n=i;for(const s of this.terraces){const r=e-s.x,a=t-s.z,o=r*s.cos-a*s.sin,c=r*s.sin+a*s.cos;if(Math.abs(o)<=s.halfWidthM&&Math.abs(c)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(o))/s.bankM)),d=h*h*(3-2*h);n=Math.max(n,d*s.levelY+(1-d)*Math.min(s.levelY,i))}}return n}placeTerraces(e,t,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=qs(s,e),o=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=me.sizeOf(s),d=-(a.headingDeg??0)*Ri,u=Math.cos(d),p=Math.sin(d),f=`${n?.geometry.uuid}:${(o-(n?.position.x??0)).toFixed(3)}:${(c-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(o,0,c),a.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=me.fitTerrace(r,s,(m,v)=>this.terrainYUnder(o+m*u+v*p,c-m*p+v*u)),r.userData.terraceKey=f),this.terraces.push({x:o,z:c,cos:u,sin:p,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(e,t){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,e-i.position.x,t-i.position.z):z0}horizonAltitudeDeg(e){const t=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(t.x)}|${Math.round(t.y*10)}|${Math.round(t.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((e%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(e,t){return e<Math.max(0,this.horizonAltitudeDeg(t))+Ee.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(e){const t=this.terrainMesh;if(!t)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=e*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,o=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),c=Math.min(Math.max(this.patchSpacingM(t),1),50);let h=Number.NEGATIVE_INFINITY;for(let d=c;d<=o;d=Math.max(d+c,d*1.02)){const u=i.x+s*d,p=i.z+r*d,f=d<=this.terrainRadius?this.terrainYUnder(u,p):a.position.y+this.groundYOfPatch(a,u-a.position.x,p-a.position.z),m=d*d/(2*Ee.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(f-m-i.y,d))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(e){const t=e.geometry.getAttribute("position");return t&&t.count>=2?Math.abs(t.getX(1)-t.getX(0)):1/0}groundYOfPatch(e,t,i){const n=e.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return z0;const r=n.getX(0),a=n.getX(s-1),o=n.getZ(0),c=n.getZ((s-1)*s),h=Xr((t-r)/(a-r)*(s-1),0,s-1),d=Xr((i-o)/(c-o)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(d))return z0;const u=Math.min(Math.floor(h),s-2),p=Math.min(Math.floor(d),s-2),f=h-u,m=d-p,v=(M,S)=>n.getY(M*s+S),g=v(p,u),y=v(p,u+1),w=v(p+1,u),b=v(p+1,u+1);return f+m<=1?g+(y-g)*f+(w-g)*m:b+(w-b)*(1-f)+(y-b)*(1-m)}groundUnderFootprint(e,t,i,n,s=0){return me.groundUnderFootprint(e,t,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(e){this.gaitOffset=e}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(e,t){this.lookYawDeg=e,this.lookPitchDeg=t}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(e,t){this.indoorLookYawDeg=e,this.indoorLookPitchDeg=t}skyUnknown=!1;setSkyUnknown(e){e!==this.skyUnknown&&(this.skyUnknown=e,this.render())}perception=Us.NONE;setPerception(e){JSON.stringify(e)!==JSON.stringify(this.perception)&&(this.perception=e,this.render())}medium;setMedium(e,t,i,n,s){const r=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:n??e.iso,autoExposure:e.autoExposure===!0&&n===void 0,maxIso:e.maxIso,metering:s??e.metering??"average",exposureSeconds:t,fNumber:i}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30),i=e?Us.NONE:this.perception??Us.NONE;if(mn.uColorVision.value.set(...i.colorMatrix),mn.uContrast.value=i.contrastGain,!e){mn.uMedium.value=0;return}mn.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const n=e.autoExposure||this.skyUnknown?this.scatteredSky?.sceneAdaptation:void 0,s=n===void 0?void 0:this.meteredBodies(),r=n===void 0?void 0:n+s.mean,a=c=>.065*e.exposureSeconds*c*this.filterTransmittance/(e.fNumber*e.fNumber*t);let o=r!==void 0&&r>0?1/(t*r):void 0;o!==void 0&&e.metering==="highlights"&&s.brightest>0&&(o=Math.min(o,Ee.HIGHLIGHT_KEPT_AT/(.18*t*s.brightest))),mn.uMediumExposure.value=o!==void 0?Math.min(o,e.maxIso!==void 0?a(e.maxIso):1/0):a(e.iso)}static HIGHLIGHT_KEPT_AT=.3;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const e=this.camera;e.updateMatrixWorld();const t=e.fov*Math.PI/180,i=2*Math.atan(Math.tan(t/2)*e.aspect),n=4*Math.asin(Math.sin(i/2)*Math.sin(t/2)),s=new _;let r=0,a=0;for(const{position:o,luminanceCdM2:c,solidAngleSr:h}of this.bodySystem.metered.values())s.copy(o).project(e),s.z<1&&Math.abs(s.x)<=1&&Math.abs(s.y)<=1&&(r+=c*h,a=Math.max(a,c*Math.min(1,h/(Ee.HIGHLIGHT_SHARE*n))**2));return{mean:r/n,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const e=this.camera.fov*Math.PI/180,t=this.grain.frameHeightMm/(2*Math.tan(e/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/t,e/i)}bloomSize=new ne;lampTransmittance(e){const t=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+e.position.y;return this.air.transmittance(t,i,e.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(e,t=0){this.decorLitAt={t:e,stepMs:t};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&me.setLights(s,n.lights,e,s.position.distanceTo(this.camera.position),t,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"?d2(n,e):void 0,o=a!==void 0?_o.lamps(a):om(n,e,this.lastAstronomy?.sun.altitudeDeg);me.setLit(r,n.kind,o,this.relativeScale,n.lamp);const c=this.streetlightLights.get(n.id);c&&(c.visible=o),a!==void 0&&(this.headlightSettings.set(n.id,a),this.aimDecorBeam(n,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=ae(async()=>{const{HeadlightSystem:e}=await import("./HeadlightSystem-CPbn_3dw.js");return{HeadlightSystem:e}},[],import.meta.url).then(({HeadlightSystem:e})=>{this.headlightSystem??=new e(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const e=this.headlightSystem;if(e){for(const t of this.decorObjects)t.kind==="vehicle"&&e.add(t.id);this.observerHeadlights&&e.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const e of this.decorObjects){const t=this.headlightSettings.get(e.id),i=this.decorGroups.get(e.id);t!==void 0&&i&&this.aimDecorBeam(e,i,t)}this.aimObserverBeam()}}headlightScatterPerM(){const e=this.siteElevationM+this.camera.position.y,t=200,i=this.air.transmittance(e,e,t)[1];return i>0?-Math.log(Math.min(1,i))/t:.05}aimDecorBeam(e,t,i){if(!this.headlightSystem?.has(e.id))return;t.updateMatrixWorld(!0);const n=new _(0,0,-1).transformDirection(t.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=me.sizeOf(e).lengthM,r=t.getWorldPosition(new _).addScaledVector(n,s/2-BO);r.y+=zO;const a=me.sizeOf(e).widthM;this.headlightSystem.aim(e.id,i,r,n,a*HO,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(e){this.observerHeadlights=e,e&&this.loadHeadlights(),this.headlightSystem&&(e?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const e=this.observerHeadlights;if(!e||!this.headlightSystem?.has("observer"))return;const t=e.setting==="auto"?this.lastAstronomy?_o.auto(this.lastAstronomy.sun.altitudeDeg):"off":e.setting,i=e.headingDeg*Math.PI/180,n=new _(Math.sin(i),0,-Math.cos(i)),s=new _(n.x*fM,this.camera.position.y-VO,n.z*fM);this.headlightSystem.aim("observer",t,s,n,GO,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(e,t,i,n){const s=me.bodyOf(t),r=s.children.find(c=>c.userData.emissive);if(!r)return;const a=pM*me.lampShare(n),o=new MS(16764006,a*this.relativeScale,WO);n?.colorTemperatureK&&o.color.setRGB(...me.lampHue(n)),o.userData.candela=a,o.position.copy(r.position).multiply(s.scale),o.castShadow=i,o.shadow.mapSize.set(512,512),o.shadow.bias=-.002,t.add(o),this.streetlightLights.set(e,o)}applyWindowGlow(){const e=this.lastAstronomy;me.setLitWindowShare(e?Pn.share(e.sun.altitudeDeg,e.localHour):0)}setAstronomy(e){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-e.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=e,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(e)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=e.sun,this.buildSky(e.sun),this.buildGround();const t=this.magnitudeLimitOf(e);this.buildStars(e.stars,t),this.placeBodies(e,t),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.applySkyColours(e),this.syncAnimationLoop(),this.render()}static relativeSkyOf(e,t){const i=r=>{const a=cr.luminanceOf(r);if(!(a>0))return[0,0,0];const o=Fe.relativeOfResponse(a)/a;return[r[0]*o,r[1]*o,r[2]*o]},n=i(e.zenith),s=i(e.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:t}}placeBodies(e,t){this.bodiesScale=this.relativeScale,this.sunBeamFraction=Qi.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,dM,new re(1,.96,.88),e.sun.magnitude),this.placeEclipse(e),this.setMoonMesh(e.moon,t),this.buildPlanets(e.planets,t),this.buildComet(e.comet,t),this.buildNovae(e.novae??[],t)}placeEclipse(e){const t=e.eclipse;if(!t||e.sun.altitudeDeg<Rp){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=dM/Es*(180/Math.PI),n=i/t.sunRadiusDeg,s=oi(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=oi(e.moon.altitudeDeg,e.moon.azimuthDeg,1),a=Math.acos(Xr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),o=a>1e-9?Xr(t.separationDeg*n*Ri/a,0,2):0,c=Math.sin(a),[h,d]=a>1e-9?[Math.sin((1-o)*a)/c,Math.sin(o*a)/c]:[1,0],u={x:s.x*h+r.x*d,y:s.y*h+r.y*d,z:s.z*h+r.z*d},p=t.moonRadiusDeg*n;this.eclipseDiscs={sun:new _(s.x,s.y,s.z).normalize(),moon:new _(u.x,u.y,u.z).normalize(),sunRadiusRad:i*Ri,moonRadiusRad:p*Ri};const f=.01,m=(y,w)=>oi(e.sun.altitudeDeg+y,e.sun.azimuthDeg+w,1),v={x:m(f,0).x-m(-f,0).x,y:m(f,0).y-m(-f,0).y,z:m(f,0).z-m(-f,0).z},g={x:m(0,f).x-m(0,-f).x,y:m(0,f).y-m(0,-f).y,z:m(0,f).z-m(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:n,up:v,right:g}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Bc(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(e){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(e,this.magnitudeLimitOf(e)),this.applyDazzleStrength(),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.updateBeams());const t=this.scatteredSky?.ambient??Ee.relativeSkyOf(Cv(e.sun.altitudeDeg),this.relativeScale),i=t,n=this.lightUnderClouds(e),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(e,t),this.updateCloudLighting(e.sun,this.baseFogColor),Ne.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??pM)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(e,i.zenith),this.applyAir(),this.buildLunarDiffraction(e.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(e){const t=this.scatteredSky?.ready?this.scatteredSky:void 0;if(e.altitudeDeg<-.5||!t){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,n=(i===void 0?je.DEFAULT_AEROSOL_OPTICAL_DEPTH:Oa.opticalDepth(i))*je.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),a=Nt.aureoleScale(n,Nt.airMass(e.altitudeDeg))*s,o=Nt.coronaScale(r),c=Nt.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),a.toExponential(2),o.toExponential(2),Math.log10(Math.max(t.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new Fb,this.celestialGroup.add(this.lunarDiffraction.object));const d=Nt.profile(Nt.HAZE_COARSE_MODE),u=Nt.profile(Nt.CLOUD_DROPLETS),p=EL(e.altitudeDeg),f=new Float32Array(Nt.STEPS*3);let m=0;for(let w=0;w<Nt.STEPS;w++){const b=w*3,M=[0,1,2].map(E=>c*p[E]*(a*d[b+E]+o*u[b+E])),S=cr.shown(M,cr.luminanceOf(M),(E,x)=>t.relativeOfLuminance(E,x));f.set(S,b),m=Math.max(m,cr.response(S))}const{x:v,y:g,z:y}=oi(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:v,y:g,z:y}:void 0,f)}applyAir(){this.scene.fog instanceof Cl||(this.scene.fog=new Cl),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(e,t,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+t,Math.hypot(e-n.x,t-n.y,i-n.z))}setSiteElevation(e){Math.abs(e-this.siteElevationM)<1||(this.siteElevationM=e,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const e=this.siteElevationM+this.observerElevationM+1.6,[t,i,n]=this.air.transmittance(e,e,Ee.UMBRA_PATH_M),s=.2126*t+.7152*i+.0722*n;return s>0?[(.4124*t+.3576*i+.1805*n)/s,1,(.0193*t+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(e){const t=e.eclipse?.horizonShare;return t&&Math.max(...t)<.1?{share:t,tint:this.umbraTint()}:void 0}scatteredSkyState(e){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:e.sun.altitudeDeg,azimuthDeg:e.sun.azimuthDeg,magnitude:e.sun.magnitude},sunLight:Qi.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?Qi.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:de.phaseAngleOf(e.moon.phase.illuminatedFraction)}}}pumpScatteredSky(){const e=this.scatteredSky;!e||e.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(e.advance(this.skyHoldUntilMs?XO:KO),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(e){if(e.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new KL(k0),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):ea(-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setReentries(e){if(e.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new Is,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):ea(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setLaunchPlumes(e){e.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new gi,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(e,this.relativeScale,t=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),t=>this.cloudTransmission(t)),this.render())}pickPlumeAt(e,t){if(!this.plumeSystem?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=this.plumeSystem.pickAt(i,Ee.BEAM_PICK_PIXELS*this.contrailPixelRad(),this.skyLightTowards(i));return n&&this.groundHides(e,t)?void 0:n}get plumePuffCount(){return this.plumeSystem?.count??0}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(C0*this.camera.fov*Math.PI/180);let s,r=n;const a=new _;for(const[o,c]of this.decorGroups){if(!c.visible||!o.startsWith(Un.ID_PREFIX))continue;a.copy(c.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,s=o)}return s&&!this.groundHides(e,t)?s:void 0}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(C0*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(e,t)?void 0:n}updateCelestialLight(e,t){const i=this.relativeScale,n=e.sun.altitudeDeg>=qh,s=!n&&e.moon.altitudeDeg>=qh,r=n?e.sun:e.moon,a=[0,0,0],o=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Ri)),c=this.siteElevationM+this.observerElevationM;let h=r,d=n||s?oM.directFraction(r.altitudeDeg,c):0;n&&d<=0&&e.moon.altitudeDeg>=qh&&(h=e.moon,d=oM.directFraction(h.altitudeDeg,c));const u=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Ri)),p=n||s?this.cloudTransmission(r):1,f=-Math.log(Math.max(p,1e-6)),m=Math.max(0,1/(1+.1125*f)-p),v=[0,0,0];if(n||s){const S=Nt.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(c,r.altitudeDeg);for(let R=0;R<3;R++)v[R]=S*E[R]*m*o,this.cloudBeam[R]=S*E[R];const{x,y:T,z:D}=oi(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(x,T,D),d>0){const R=Nt.illuminanceOf(h.magnitude)*i,O=h===r?E:this.air.transmittanceFromSpace(c,h.altitudeDeg),N=h===r?p:this.cloudTransmission(h);for(let C=0;C<3;C++)a[C]=R*O[C]*N*d}}else this.cloudBeam.fill(0);const g=this.surroundings;if(g)this.skyLight.color.setRGB(g.up[0]*i,g.up[1]*i,g.up[2]*i),this.skyLight.groundColor.setRGB(g.down[0]*i,g.down[1]*i,g.down[2]*i);else{const S=this.skyCloudTransmission(),E=t.skyIrradiance,x=[0,1,2].map(D=>E[D]*S+v[D]);this.skyLight.color.setRGB(x[0],x[1],x[2]);const T=it.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(T*(x[0]+a[0]*u),T*(x[1]+a[1]*u),T*(x[2]+a[2]*u))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===e.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||d<=0){this.celestialLight.intensity=0;return}const{x:y,y:w,z:b}=oi(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(y,w,b),this.celestialLight.shadow.normalBias=hM*Xr(w/kO,.1,1),this.placeShadowFrustum();const M=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/M,a[1]/M,a[2]/M),this.celestialLight.intensity=M,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(e,t){const i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=fs.litFraction(t.sunElevationDeg,t.heightM);if(s>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),a=Nt.illuminanceOf(i.magnitude)*this.relativeScale,o=t.heightM>=Ee.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)n[c]=Math.max(0,a*r[c]*s*o-this.sceneSunBeam[c])}}e.traverse(s=>{const r=s.material;if(!(r instanceof pr||r instanceof go)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=Ee.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 _(0,1,0);placeShadowFrustum(){const e=this.lightDirection,t=this.celestialLight.shadow.camera,i=(t.right-t.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,e);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(e,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=c=>{const h=r.dot(c)/i;return(h-Math.round(h))*i},o=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(o).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToCabin(e){if(e===this.cabinShadow)return;this.cabinShadow=e;const t=this.celestialLight.shadow;if(!e){this.shadowHalfExtentM=-1;return}const i=t.camera,n=DO;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=Qu+5,i.near=this.shadowLightDistanceM-Qu,i.far=this.shadowLightDistanceM+Qu,i.updateProjectionMatrix(),t.bias=-.004/(2*Qu),t.mapSize.x!==2048&&(t.mapSize.set(2048,2048),t.map?.dispose(),t.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(e){for(const t of e)t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==Ee.CABIN_SKY_SHARE&&(r.envMapIntensity=Ee.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(RO,Math.max(to,Math.ceil(e*1.25/20)*20));if(t===this.shadowHalfExtentM)return;this.shadowHalfExtentM=t;const i=this.celestialLight.shadow,n=i.camera;n.left=-t,n.right=t,n.top=t,n.bottom=-t;const s=Math.max(Yh,t*(Yh/to));this.shadowLightDistanceM=Math.max(Es,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*to?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=to;shadowLightDistanceM=Es;shadowUp=new _(0,1,0);shadowAxisX=new _;shadowAxisY=new _;shadowWorld=new _;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const n=i*Ri,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)e+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),t+=s}return e/t}cloudBeam=[0,0,0];cloudBeamDirection=new _(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Fe.semiSaturation(Fe.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new Rn,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(e,t,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(e){return this.meteorSystem?.midpointOf(e)}updateMeteors(e){this.meteorSystem?.update(e)}setInstrument(e){this.projectionKind=e.projection,this.grain=e.detailUm!==void 0&&e.frame?{detailUm:e.detailUm,frameHeightMm:e.frame.heightMm}:void 0;const t=hi.starPointsOf(e);t!==this.starPoints&&(this.starPoints=t,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=t),this.render())}magnitudeLimitOf(e){const t=de.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:de.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return ea(e.sun.altitudeDeg,this.instrumentMagnitudeGain,t)}setLightPollution(e){e!==this.lightPollution&&(this.lightPollution=e,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(e,t=!1,i=0){const n=Number.isFinite(e)?e:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(t,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 e=this.compileOffThread().then(()=>{this.compiling===e&&(this.compiling=void 0,this.render())});this.compiling=e;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 e=this.usableGhostPass();e?(this.exposureSubjectBounds=[],this.renderOnce(e.frame),e.develop(this.renderer,e.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 e=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const t=this.renderer.properties,i=performance.now()+Ee.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of e){const a=t.get(r)?.currentProgram;(!a||a.isReady())&&e.delete(r)}e.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(e){if(this.animationsRunning){const t=this.lastFrameTimeMs===void 0?0:e-this.lastFrameTimeMs;this.lastFrameTimeMs=e,this.hasAnimations()&&this.animate(e,t);const i=this.resolution.ratioFor(e,t);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(e,t,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"||s.observerSide!==void 0&&Ro(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=qs(s,e),o=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=me.sizeOf(s),d=Math.max(h.widthM,h.lengthM)/2;Math.hypot(o,c)<d&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<d&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(e=!1){this.reflections??=new Jn(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(a=>a.mesh)],i=[...this.starTiers.map(a=>a.points),...[...this.bodyMeshes.values()].filter(a=>a instanceof Cs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(a=>a!==void 0),...this.cabinDecor()],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,a=>this.measureSurroundings(a,n,s),e?0:Jn.REFRESH_MS);r===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()}))},r))}static adaptingLuminance(e,t){const i=(.2126*t[0]+.7152*t[1]+.0722*t[2])/Math.PI;return Math.max(e,Ee.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(e,t,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new fd;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>oi(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,s,r=>{const a=p=>p.map(f=>f/t),o=this.surroundings,c={up:a(r.up),down:a(r.down)},h=(p,f)=>p.some((m,v)=>Math.abs(m-f[v])>.03*Math.max(Math.abs(m),Math.abs(f[v]),1e-12)),d=!o||h(o.up,c.up)||h(o.down,c.down);d&&(this.surroundings=c),this.eyeSettledVersion=-1;const u=this.scatteredSky?.adaptToSurroundings(Ee.adaptingLuminance(Math.exp(r.logAverage)/t,c.down))??!1;if(!d&&!u){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(e){const t=this.surroundings;if(!t)return;const i=e.sun.altitudeDeg>=qh?e.sun:e.moon.altitudeDeg>=qh?e.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[t.up[0]*n,t.up[1]*n,t.up[2]*n]}}probeIrradiance;surroundings;animate(e,t){const i=Math.min(t/1e3,dP);this.twinkleSeconds=e/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(e/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=e/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(e){this.resolution.maximum=e,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(e){this.renderer.setPixelRatio(e),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(e,t){const i=t?Math.max(1,Math.round(e)):1;if(i===this.exposureInstants&&(i===1||t===this.exposureInstantAt)){this.exposureInstantAt=t;return}this.exposureInstants=i,this.exposureInstantAt=t,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(e){if(this.aimBeams(),me.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();e?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const t=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.phenomena.place(this.camera,(r,a,o)=>this.directionAtScreenPoint(r,a,o),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()),mn.uRodShare.value=this.scatteredSky?.rodShare??0,mn.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);mn.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!t){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,e):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,e);return}t.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(),e,this.pointLayerHost)}pointLayerHost={points:()=>{const e=[];return this.celestialGroup.traverse(t=>{(t instanceof Cs&&t.userData.pointSource||t instanceof xe&&t.userData.skyRibbon)&&e.push(t)}),[...e,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(e=this.camera){this.renderReferencesPass(e),this.renderBodiesOverReferences(e),this.renderPhenomenaPass(e),this.renderHudPass(e)}renderHudPass(e){const t=this.traceSystem?.any&&this.tracesShown;if(!t&&!this.compassSprites.some(s=>s.visible))return;t&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),e.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(R0),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(e){if(!this.references?.any||!this.bodySystem.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(VS),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new Fs({blending:zl,blendSrc:la,blendDst:la,blendSrcAlpha:la,blendDstAlpha:la,toneMapped:!1});renderReferencesPass(e){if(!this.references?.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(this.references.layer),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){const i=e.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,t);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:t},this.referencesLoading??=ae(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-BeFpOHFl.js");return{ReferenceSystem:n}},__vite__mapDeps([6,7]),import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=s;for(const[a,o]of this.referenceViews)s.setView(a,o);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})}referenceAspect(e){return this.references?.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new _)}referenceFailure(e){return this.references?.failureOf(this.documentRelative(e))}setReferencesShown(e){this.referencesShown=e,this.references?.setShown(e),this.render()}setReferenceView(e,t){this.referenceViews.set(e,t),this.references?.setView(e,t),this.render()}renderPhenomenaPass(e){if(!this.phenomena.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);s&&Ee.markDecorDepth(s,n.kind!=="crop")}e.layers.set(_0),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(WS),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new Fs({colorWrite:!1});static HEAD_TURN_LIMIT_DEG=85;static turnHead(e,t,i){const n=e.getObjectByName("head");if(!n)return;const s=((i-t)%360+540)%360-180,r=Math.max(-85,Math.min(Ee.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*Ri}static isSolidSurface(e){if(!(e instanceof xe))return!0;const t=Array.isArray(e.material)?e.material[0]:e.material;return t.depthWrite!==!1&&t.blending!==An}static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof xe))return;t&&Ee.isSolidSurface(i)?i.layers.enable(_0):i.layers.disable(_0)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new ne),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new hL(t,i)),this.exposureAccumulation.resize(t,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const e=this.exposureInstantAt,t=this.exposureAccumulation;if(!e||!t)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+Ee.EXPOSURE_BUDGET_MS,s=Ee.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const a=this.compassSprites.map(o=>o.visible);for(const o of this.compassSprites)o.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((o,c)=>{o.visible=a[c]})}t.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(e,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){mn.uRodShare.value=this.scatteredSky?.rodShare??0,mn.uHasOverlay.value=1,mn.uRelativeScale.value=this.relativeScale,this.applyMedium();const e=this.exposureInstants/this.exposureInstantsDone,t=this.usableGhostPass();if(t&&this.exposureAccumulation?t.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,e,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,e),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Or,n=new fr(-1,1,1,-1,0,2),s=tp/(gM*Math.tan(vM*Ri/2));for(const a of this.compassSprites){if(!a.visible)continue;const o=a.getWorldPosition(new _).sub(this.camera.position).normalize(),c=this.screenPointOf(o);if(!c)continue;const h=new Uh(a.material);h.position.set(c.ndcX,c.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 e=[],t=new vn,i=new _,n=this.camera.getWorldDirection(new _),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||(t.setFromObject(a),t.isEmpty())||t.distanceToPoint(this.camera.position)<Ee.MAP_SUBJECT_NEAREST_M)continue;let o=1/0,c=-1/0,h=1/0,d=-1/0;for(const u of[t.min.x,t.max.x])for(const p of[t.min.y,t.max.y])for(const f of[t.min.z,t.max.z]){if(i.set(u,p,f).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const v=(m.ndcX+1)/2,g=(1-m.ndcY)/2;o=Math.min(o,v),c=Math.max(c,v),h=Math.min(h,g),d=Math.max(d,g)}o=Math.max(o,0),c=Math.min(c,1),h=Math.max(h,0),d=Math.min(d,1),c>=o&&d>=h&&e.push({x:o,y:h,width:c-o,height:d-h})}return e}restateAt(e,t){this.restatingExposure=!0;try{e(t)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(e){const t=this.lensOptics;this.lensOptics=e,(t===void 0!=(e===void 0)||t&&e&&(t.focalLengthMm!==e.focalLengthMm||t.fNumber!==e.fNumber||t.focusDistance!==e.focusDistance||t.frameHeightMm!==e.frameHeightMm))&&(e&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.render())}usableDepthOfFieldPass(){const e=this.lensOptics;if(!e)return;const t=this.renderer.getDrawingBufferSize(new ne),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new vd(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}setLensGhosts(e){JSON.stringify(e)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=e,e.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(e,t){return this.ghostPass?.holdsPictureAt(this.renderer,e,t)??!1}pickGhostAt(e,t){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,e,t,this.ghostOptics,mn.uMediumExposure.value)}pickDropAt(e,t){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,e,t)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const e=this.renderer.getDrawingBufferSize(new ne);return this.ghostPass?this.ghostPass.resize(e.x,e.y):this.ghostPass=new Ts(e.x,e.y),this.ghostPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new ne);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new Nb(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new ne);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new ki(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new ne(t,i),this.camera);return}const s=n.directionFor(t,i,this.camera.fov);this.camera.updateMatrixWorld(),e.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),e.ray.direction.set(s.x,s.y,s.z).applyQuaternion(this.camera.quaternion).normalize(),e.camera=this.camera}pickCloudAt(e,t){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(e,t))}cloudDirectionAt(e,t){return this.directionAtScreenPoint(e,t,new _)}directionAtScreenPoint(e,t,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(e){this.camera.updateMatrixWorld();const t=this.screenPointScratch.copy(e).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);if(this.projectionKind==="equidistant"&&this.equidistantPass)return ki.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*Ri);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new _;screenPointQuaternion=new Ns;screenPointSize=new ne;updateLensFlarePosition(){const e=this.lensFlare;if(!e)return;if(!this.sunVisible){e.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){e.mesh.visible=!1;return}const t=this.sunVisibleFraction();if(t<=0){e.mesh.visible=!1;return}e.mesh.visible=!0,this.sunUnhiddenFraction=t,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);e.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;e.uniforms.uResolution.value.set(n,s),e.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const e=this.lensFlare;if(!e||!e.mesh.visible)return;const t=this.sunDiscRadiance.map(r=>Math.max(0,r-Ee.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(t[1]<=0)return;const i=Math.tan(e.uniforms.uSourceRadiusDeg.value*Math.PI/180)/e.uniforms.uTanHalfFov.value/2,n=Math.PI*i*i,s=e.uniforms.uLensPosition.value;return{x:s.x,y:s.y,radius:i,flux:[t[0]*n,t[1]*n,t[2]*n]}}renderDazzleOnResample(){const e=this.lensFlare;if(!e||!this.sunVisible)return;const t=this.sunVisibleFraction();if(t<=0)return;this.sunUnhiddenFraction=t,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);e.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),e.uniforms.uResolution.value.set(n.x,n.y),e.uniforms.uEquidistant.value=1,e.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,e.mesh.visible=!0,e.mesh.layers.enable(lM),this.camera.layers.set(lM),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),e.mesh.visible=!1,e.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let e=0;for(const t of yM)this.isSunOccluded(t[0],t[1])||e++;return e/yM.length}raycastableDecor(){const e=[];for(const t of this.decorObjects){if(t.kind==="crop")continue;const i=this.decorGroups.get(t.id);i&&e.push(i)}return e}isSunOccluded(e=0,t=0){const i=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&i.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(this.sunWorldPosition).sub(this.camera.position),s=n.length();if(n.normalize(),e!==0||t!==0){const a=Math.PI/180,o=this.sunOcclusionRightScratch.set(n.z,0,-n.x);o.lengthSq()<1e-9&&o.set(1,0,0),o.normalize();const c=this.sunOcclusionUpScratch.crossVectors(o,n).normalize();n.addScaledVector(o,e*a).addScaledVector(c,t*a).normalize()}if(this.groundBlocks(this.camera.position,n,s))return!0;if(i.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(i,!0)[0];return r!==void 0&&r.distance<s}groundBlocks(e,t,i,n=0){const s=this.groundMesh;if(s&&t.y<0){const v=(s.position.y-e.y)/t.y;if(v>n&&v<i){const g=e.x+t.x*v-s.position.x,y=e.z+t.z*v-s.position.z;if(Math.hypot(g,y)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),o=Math.round(Math.sqrt(a.count));if(o<2||o*o!==a.count)return!1;const c=[r.position.x+a.getX(0),r.position.x+a.getX(o-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((o-1)*o)],d=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(o-1);if(!(d>0))return!1;let u=n,p=i;for(const[v,g,y]of[[e.x,t.x,c],[e.z,t.z,h]]){const w=Math.min(y[0],y[1]),b=Math.max(y[0],y[1]);if(Math.abs(g)<1e-12){if(v<w||v>b)return!1;continue}const M=(w-v)/g,S=(b-v)/g;u=Math.max(u,Math.min(M,S)),p=Math.min(p,Math.max(M,S))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),m=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let v=0;v<=m;v++){const g=u+(p-u)*v/m,y=e.x+t.x*g,w=e.y+t.y*g,b=e.z+t.z*g;if(w<=this.groundYUnder(y,b))return!0}return!1}setPhenomena(e,t){this.phenomena.set(e,t)}decorDistancesAt(e,t,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t),this.ufoOcclusionRaycaster.near=Zu;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 o=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(c=>Ee.isSolidSurface(c.object));o&&(r.occludesSourceIds?.includes(i)?n=n===void 0?o.distance:Math.max(n,o.distance):s=s===void 0?o.distance:Math.min(s,o.distance))}return{behindM:n,inFrontM:s}}pickBodyAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.origin,n=this.raycaster.ray.direction,s=CO*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,d])=>{const u=d.getWorldPosition(new _).sub(i);return{key:h,direction:u.clone().normalize(),radiusRad:Math.atan2(d.scale.x/2,u.length())}}),a=this.eclipseDiscs,o=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],c=Ee.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...o],s);if(c)return this.groundHides(e,t)?void 0:c}pickOpticsAt(e,t){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(e,t)?i:void 0}static nearestBody(e,t,i){let n,s=1/0,r=1/0,a=!1;for(const o of t){const c=Math.acos(Xr(o.direction.dot(e),-1,1))-o.radiusRad;if(c>i)continue;const h=c<=0,d=s<=0,u=o.inFront===!0;(h!==d?h:h?u!==a?u:o.radiusRad<r:c<s)&&(n=o.key,s=c,r=o.radiusRad,a=u)}return n}pickInterpretationBodyAt(e,t){const i=this.bodySystem.group.children.filter(p=>p.visible&&p.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=_O*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],o=a.length>0?Ee.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let c,h=1/0;const d=new vn,u=new _;for(const p of i){if(d.setFromObject(p),d.isEmpty())continue;d.getCenter(u);const f=d.getSize(new _).length()/2,m=u.clone().sub(s),v=m.length();if(v===0||m.dot(n)<=0||o!==void 0&&o<v-f)continue;const g=Math.acos(Math.min(1,m.normalize().dot(n))),y=Math.atan(f/v);if(y>r){const w=this.raycaster.intersectObject(p,!0)[0];if(!w||o!==void 0&&o<w.distance)continue}else if(g>r)continue;y<h&&(h=y,c=p.name.slice(5))}return c}pickStarAt(e,t){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(C0*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const o=a.direction.dot(i);o>r&&(r=o,s={star:a.star,altitudeDeg:a.altitudeDeg})}return s&&this.groundHides(e,t)?void 0:s}groundHides(e,t){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,1/0,Zu)}bodyScreenBox(e){const t=this.bodySystem.boxOf(e,this.bodyBoxScratch);if(!t)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let a=0;a<8;a++){const o=this.bodyCornerScratch.set(a&1?t.max.x:t.min.x,a&2?t.max.y:t.min.y,a&4?t.max.z:t.min.z),c=this.screenPointOf(o.sub(this.camera.position).normalize());if(!c)return;i=Math.min(i,c.ndcX),s=Math.max(s,c.ndcX),n=Math.min(n,c.ndcY),r=Math.max(r,c.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new vn;bodyCornerScratch=new _;pickPlacedBodyAt(e,t){return this.aimAtScreenPoint(this.raycaster,e,t),this.bodySystem.pick(this.raycaster)}decorScreenBox(e){const t=this.decorGroups.get(e);if(!t||!t.visible)return;const i=this.bodyBoxScratch.setFromObject(t);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-1/0;for(let o=0;o<8;o++){const c=this.bodyCornerScratch.set(o&1?i.max.x:i.min.x,o&2?i.max.y:i.min.y,o&4?i.max.z:i.min.z),h=this.screenPointOf(c.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(e){return this.lampNudges.get(e)}decorGroundPointAt(e,t,i,n=0){const s=this.decorGroups.get(e);if(!s)return;this.aimAtScreenPoint(this.raycaster,t,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(e){const t=this.decorGroups.get(e);return t?Math.hypot(t.position.x-this.camera.position.x,t.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(e){const t=this.decorGroups.get(e);return t?t.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Ri/2):0}decorGrabHeightAt(e,t,i){const n=this.decorGroups.get(e);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,t,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),o=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return o?Math.min(Math.max(o.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new co;decorHitScratch=new _;static firstSolid(e){return e.find(t=>{const i=t.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&s.transparent&&s.opacity<Ee.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],n=Ee.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(e,t){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray;i.group.updateMatrixWorld();const s=new xh().copy(n).applyMatrix4(new vt().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(u,p)=>{const f=new _(u,0,p).applyMatrix4(r);return this.groundYUnder(f.x,f.z)-r.elements[13]};if(!i.mayMeet(s.origin,s.direction,a,Ee.RAILWAY_PICK_ABOVE_M))return;const o=Ee.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!o||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,o.distance-Ee.RAILWAY_GROUND_MARGIN_M,Zu))return;const c=i.group.worldToLocal(o.point.clone()),h=i.lineAt(c.x,c.z);if(!h)return;const d=i.contactHeightM(h);return{line:h,distanceM:o.distance,...d!==void 0?{contactM:d}:{}}}pickBeamAt(e,t){const i=this.beamSystem;if(!i||i.segmentCount===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray,s=i.pickAt(n.origin,n.direction,Ee.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!s||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,s.distanceM-1,Zu))return;const r=Ee.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<s.distanceM))return s}skyLightTowards(e){const t=this.scatteredSky?.ambient;if(!t)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(e.x,e.y,e.z)||1,s=Math.max(0,Math.min(1,e.y/n));return i(t.horizon)+(i(t.zenith)-i(t.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),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.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,this.beamSystem?.dispose(),this.beamSystem=void 0,this.beamSystemLoading=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.reentrySystem?.dispose(),this.reentrySystem=void 0,this.plumeSystem?.dispose(),this.plumeSystem=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const e of this.bodyMeshes.values())this.disposeMesh(e);this.bodyMeshes.clear(),this.novaKeys.clear();for(const e of[...this.hitAreas.keys()])this.disposeHitArea(e);for(const e of[...this.glareSprites.keys()])this.disposeGlare(e);this.disposeCompassLabels();for(const e of this.decorGroups.values())me.dispose(e);this.decorGroups.clear(),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 e=t=>{this.animationFrameId=null,this.frame(t),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(e))};this.animationFrameId=requestAnimationFrame(e)}setAnimationsRunning(e,t=!1){const i=e&&t;if(e===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=e,this.framesDriven=i,e&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!e&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),!e&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!e||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(e=>e.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new _;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const e=this.lastAstronomy?.sun;return e!==void 0&&e.altitudeDeg<Ee.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(e){const t=this.skyMesh?.geometry??new hn(ju,32,16),i=t.attributes.position,n=t.getAttribute("color")??new gt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:o}=pL(i.getX(r),i.getY(r),i.getZ(r)),c=ML(a,o,e.azimuthDeg,e.altitudeDeg);n.setXYZ(r,c[0],c[1],c[2])}if(n.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",n);const s=new Fs({vertexColors:!0,side:Hi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new xe(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=cM(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Sb(this.groundRadius,48),i=new pr({color:new re(D0,D0,D0),fog:!0});Cl.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new xe(t,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 e=this.groundMesh?.material;if(!e)return;const t=this.terrainMesh===void 0;e.depthWrite!==t&&(e.depthWrite=t,e.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,e.depthTest=!0,e.needsUpdate=!0}cloudTransmission(e,t=!1){const i=`${e.altitudeDeg.toFixed(1)}:${e.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(";")+(t?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(e,t);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(e,t=!1){const i=oi(e.altitudeDeg,e.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,t);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-Xt.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*PO);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Xt.iceAlphaAt(i,ep,r,this.cloudFieldOffset)*NO),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<Rp){this.disposeMesh(this.bodyMeshes.get(e)),this.bodyMeshes.delete(e),this.disposeHitArea(e),this.disposeGlare(e),e==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:o}=oi(t.altitudeDeg,t.azimuthDeg,Es),c=this.cloudTransmission(t),h=this.arrivingIlluminance(t,s,c),d=Ee.unitLuminance(n);let u=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/Es)**2,f=[0,1,2].map(v=>d[v]*h[v]/(this.sunBeamFraction*p));this.sunDiscRadiance=f;const m=f.map(v=>Math.min(Ee.BRIGHTEST_RELATIVE,v));u instanceof xe||(this.disposeMesh(u),u=new xe(new hn(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)),u.material.color.setRGB(m[0],m[1],m[2]),u.scale.setScalar(i)}else{if(!(u instanceof Cs)){this.disposeMesh(u);const m=new ct;m.setAttribute("position",new mt(new Float32Array(3),3)),m.setAttribute("color",new mt(new Float32Array(3),3)),u=new Cs(m,Ne.material(Dl[Dl.length-1].size,!1)),Ne.track(u),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)}const p=u.geometry.getAttribute("color"),f=e.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*h[0]*f,d[1]*h[1]*f,d[2]*h[2]*f),p.needsUpdate=!0}if(u.position.set(r,a,o),this.setHitArea(e,r,a,o,i),e==="sun"&&(this.sunArriving=h),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,a,o,h,i/Es*(180/Math.PI),Ee.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,a*p+this.celestialGroup.position.y,o*p),this.lensFlare||(this.lensFlare=$L(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<Rp){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=oi(e.altitudeDeg,e.azimuthDeg,Es),a=this.cloudTransmission(e),o=this.arrivingIlluminance(e,e.magnitude,a),c=e.radiusDeg??ts.MEAN_RADIUS_DEG,h=Es*Math.tan(c*Ri),d=Math.max(Xr(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Es)**2,u=new re(...o.map(m=>Math.min(Ee.BRIGHTEST_RELATIVE,m/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(Xr(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof Uh?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=NM(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new Uh(new Ep({map:NM(e.phase),color:u,fog:!1,blending:An,depthWrite:!1})),f.userData.phaseKey=p,this.celestialGroup.add(f),this.bodyMeshes.set(i,f)),f.scale.set(h*2,h*2,1),f.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,o,c)}bentLight(e,t,i=LO){const[n,s,r]=this.arrivingIlluminance(e,t,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(e,t){return Ee.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new re;pointToPixel(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),t=(this.camera.fov*Math.PI/180/e)**2;return Math.min(1,Ne.CONE_SOLID_ANGLE/t)}pointScratch=new ne;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(e,t,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),s=Nt.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=cr.luminanceOf([e.r,e.g,e.b]);return t>0?[e.r/t,e.g/t,e.b/t]:[1,1,1]}setHitArea(e,t,i,n,s){let r=this.hitAreas.get(e);if(!r){const o=new Ep({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Uh(o),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const a=s*2;r.scale.set(a,a,1)}disposeHitArea(e){const t=this.hitAreas.get(e);t&&(t.removeFromParent(),t.material.dispose(),this.hitAreas.delete(e))}setGlare(e,t,i,n,s,r,a=0){if(Ln.radiusDeg(Ln.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(e);return}let o=this.glareSprites.get(e);o||(o=new Ln(`veil:${e}`),this.celestialGroup.add(o.mesh),this.glareSprites.set(e,o)),o.shine({x:t,y:i,z:n},s,r,a)}disposeGlare(e){const t=this.glareSprites.get(e);t&&(t.mesh.removeFromParent(),t.dispose(),this.glareSprites.delete(e))}buildComet(e,t){const i=e&&`comet:${e.id}`;if(!e||!i||e.magnitude>t){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=Ml(e.magnitude,t),s=y0(n);this.cometKey=i,this.setBodyMesh(i,e.position,L0*(.5+.5*n),new re(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new Vs(Es),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new ji,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:ep},0);return}const s=this.lowerCloudCover(),r=ut.deckLitUntilDeg(ut.DECK_HEIGHT_M),a=e.altitudeDeg>-r?e:t,o=this.bentLight(a,a===e?At.SUN_MAGNITUDE:t.magnitude),c=ut.strength(i,s,a.altitudeDeg,r)*o.scale,{x:h,y:d,z:u}=oi(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},a.altitudeDeg,c,o.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??ep},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??kp,this.weather.rareIceCrystals)}buildRainbow(e,t){this.rainbow||(this.rainbow=new wl,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=e.altitudeDeg>0,s=n?e:t,r=this.lowerCloudCover(),a=this.bentLight(s,n?At.SUN_MAGNITUDE:t.magnitude,OO),o=jn.strength(i,r,s.altitudeDeg)*a.scale;if(o<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:d}=oi(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},o,a.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new ho,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=Ks.galactic(i,n),r=Ee.directionOf(s.centre),a=Ee.directionOf(s.rotation),o=Ee.directionOf(s.pole),c=new lt().set(r.x,r.y,r.z,a.x,a.y,a.z,o.x,o.y,o.z),h=Ee.directionOf(Ks.eclipticPole(i,n)),d=Ee.directionOf(e.sun),u=d.clone().addScaledVector(h,-d.dot(h)).normalize();this.skyGlow.update({galactic:c,eclipticPole:h,sunLongitude:u,sunDirection:d,sunAltitudeDeg:e.sun.altitudeDeg,moon:{direction:Ee.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:de.phaseAngleOf(e.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new _(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:n}=oi(e.altitudeDeg,e.azimuthDeg,1);return new _(t,i,n).normalize()}buildNovae(e,t){const i=new Set;for(const n of e){if(n.magnitude>t)continue;const s=`nova:${n.id}`;i.add(s);const r=Ml(n.magnitude,t),a=y0(r);this.setBodyMesh(s,n.position,L0*(.5+.5*r),new re(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(e,t){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of e){if(n.magnitude>t)continue;i.add(n.body);const s=Ml(n.magnitude,t),r=y0(s),a=mP[n.body]??new re(1,1,1),o=new re(a.r*r,a.g*r,a.b*r),c=L0*(.5+.5*s);this.setBodyMesh(n.body,n.position,c,o,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(e,t){if(this.namedStars=[],!e||e.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=e,r=new Tr(n,s),a=V0(1337),o=[],c=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const d=i.mag[h];if(d>t)break;const{altitudeDeg:u,azimuthDeg:p}=r.position(i.ra[h],i.dec[h]);if(u<uM)continue;const{x:f,y:m,z:v}=oi(u,p,k0);o.push({x:f,y:m,z:v,brightness:Ml(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(g=>g*Nt.illuminanceOf(d)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of s2){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<uM)continue;const{x:p,y:f,z:m}=oi(d,u,k0);this.namedStars.push({star:h,direction:new _(p,f,m).normalize(),altitudeDeg:d})}this.starTiers=Dl.map((h,d)=>{const u=o.filter(M=>vm(M.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),m=new Float32Array(u.length*3),v=new Float32Array(u.length),g=new Float32Array(u.length);u.forEach((M,S)=>{p[S*3]=M.x,p[S*3+1]=M.y,p[S*3+2]=M.z,f[S]=M.brightness,m.set(M.illuminance,S*3),v[S]=M.phase,g[S]=M.speedFactor});const y=new ct;y.setAttribute("position",new mt(p,3)),y.setAttribute("seed",new mt(v.map(M=>M/(2*Math.PI)),1));const w=new mt(new Float32Array(u.length*3),3);y.setAttribute("color",w);let b=this.starTiers[d]?.points;return b?(b.geometry.dispose(),b.geometry=y):(b=new Cs(y,Ne.material(h.size)),Ne.track(b),this.celestialGroup.add(b)),{points:b,colorAttribute:w,brightness:f,illuminance:m,phase:v,speedFactor:g}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){Ne.setTime(e);const t=this.relativeScale;if(t!==this.starColoursRelative){this.starColoursRelative=t;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]*t,n[s*3+1]=i.illuminance[s*3+1]*t,n[s*3+2]=i.illuminance[s*3+2]*t;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new th(this.celestialGroup,O0,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 e=this.lowerCloudCover();if(e<=0){this.disposeCloudSystem();return}const t=this.weather.cloudDarkness,i=new re(Ho[0]+(F0[0]-Ho[0])*t,Ho[1]+(F0[1]-Ho[1])*t,Ho[2]+(F0[2]-Ho[2])*t);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=e,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=Iv(i,e,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=_v(O0);this.cloudMesh=new xe(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(e=>e.type!=="cirrus").reduce((e,t)=>e*(1-t.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(e=>e.type==="cirrus").reduce((e,t)=>e*(1-t.coverage),1):this.weather.highCloudCover}buildCirrus(){const e=this.weather.highCloudCover??0;if(this.layeredClouds||e<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=e,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:t,uniforms:i}=Iv(new re(...Ho),e,ep,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new xe(_v(O0*1.04),t),this.cirrusMesh.renderOrder=wM-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 e=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(e)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,e)}faceCloudDeck(e,t){const i=t<0;e.scale.y=i?-1:1,e.renderOrder=i?th.deckOrder(!0,0,1):wM}cloudLayerOffset(){const t=((this.weather.cloudBaseM??zv)-this.observerElevationM)*P0;return Math.sign(t||1)*Math.max(Math.abs(t),ZO)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(d=>d!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,a]=this.cloudBeam.map(d=>d/Math.PI),o=this.lightningLevel*G0*this.relativeScale/Math.PI,c=new re(t[0]+Gr.r*o,t[1]+Gr.g*o,t[2]+Gr.b*o);this.layeredClouds?.setLighting(n.clone(),new re(s,r,a),c,c);const h=Math.max(0,n.y);for(const d of i)d.sunDir.value.copy(n),d.sunColor.value.setRGB(s*h,r*h,a*h),d.ambientColor.value.copy(c)}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(e){return rP(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,B0],[this.rainSplashSystem?.points,Go],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:U0[this.weather.precipitationType].poolSize]];for(const[t,i]of e)t&&i!==void 0&&t.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=EM(H0(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const e=this.weather.precipitationType;if(e==="none")return;if(e==="rain"){this.buildRain();return}const t=U0[e],i=t.poolSize,n=V0(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),o=new Float32Array(i),c=new Float32Array(i),h=new Float32Array(i),d=new Float32Array(i),u=new Float32Array(i),p=new Float32Array(i),f=new Float32Array(i);for(let w=0;w<i;w++){const b=n()*Math.PI*2,M=n()*t.radiusM;s[w*3]=Math.cos(b)*M,s[w*3+1]=Tc+n()*(t.topYM-Tc),s[w*3+2]=Math.sin(b)*M,r[w]=n()*Math.PI*2,a[w]=.7+n()*.6,o[w]=.6+n()*.8,c[w]=.4+n()*1.2}const m=new ct;m.setAttribute("position",new mt(s,3)),m.setDrawRange(0,this.precipitationCount(i));const v={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new re(...this.baseFogColor)},uTexture:{value:gP(e)},uNearFocusDistance:{value:_M},uHazeDistance:{value:t.radiusM*RM}},g=new Ct({uniforms:v,vertexShader:xP,fragmentShader:SP,transparent:!0,depthWrite:!1});this.precipitationUniforms=v;const y=new Cs(m,g);y.renderOrder=N0,this.scene.add(y),this.precipitationPoints=y,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=o,this.precipitationWobbleAmpJitter=c,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=d,this.precipitationBounceDuration=u,this.precipitationBounceVelX=p,this.precipitationBounceVelZ=f}updatePrecipitation(e,t){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=U0[i];if(this.precipitationUniforms?.uColor.value.copy(Ee.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*Ri,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,o=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,m=this.precipitationBounceDuration,v=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,y=i==="snow"&&d&&u,w=i==="hail"&&p&&f&&m&&v&&g;for(let b=0,M=0;b<o.length;b+=3,M++){if(w&&p[M]>0){if(p[M]-=t,p[M]<=0){const x=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;o[b]=Math.cos(x)*T,o[b+1]=n.topYM,o[b+2]=Math.sin(x)*T,p[M]=0}else{const x=1-p[M]/m[M];o[b+1]=Tc+Math.sin(Math.PI*x)*f[M],o[b]=ip(o[b]+(r+v[M])*t,n.radiusM),o[b+2]=ip(o[b+2]+(a+g[M])*t,n.radiusM)}continue}let S=0,E=0;if(y){const x=oP*d[M],T=lP*u[M];S=Math.sin(e*x*Math.PI*2+c[M])*T,E=Math.sin(e*x*Math.PI*2+c[M]+Math.PI/2)*T}if(o[b]+=(r+S)*t,o[b+1]-=n.fallSpeedMPerS*h[M]*t,o[b+2]+=(a+E)*t,o[b]=ip(o[b],n.radiusM),o[b+2]=ip(o[b+2],n.radiusM),o[b+1]<Tc){if(w){f[M]=OM*(.2+Math.random()*1.6),m[M]=cP*(.5+Math.random()),p[M]=m[M];const D=Math.random()*Math.PI*2,R=hP*(f[M]/OM);v[M]=Math.cos(D)*R,g[M]=Math.sin(D)*R,o[b+1]=Tc;continue}const x=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;o[b]=Math.cos(x)*T,o[b+1]=n.topYM,o[b+2]=Math.sin(x)*T}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=H0(this.weather.precipitationIntensity);this.rainSystem=GL({count:B0,radiusM:jh,heightM:QO,bottomYM:MM,overallSpeed:eP,color:SM.clone(),opacity:.85,visibleCount:this.precipitationCount(B0),speedStreak:EM(e),pixelSize:kM,seed:9001,nearFocusDistanceM:_M,hazeDistanceM:jh*RM,hazeColor:new re(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=N0,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=V0(4242),t=new Float32Array(Go*3),i=new Float32Array(Go),n=new Float32Array(Go),s=new Float32Array(Go);for(let h=0;h<Go;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*jh;t[h*3]=Math.cos(d)*u,t[h*3+1]=MM,t[h*3+2]=Math.sin(d)*u,n[h]=PM(AM,TM),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new ct;r.setAttribute("position",new mt(t,3));const a=new mt(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Go));const o=new Ct({uniforms:{uMaxSize:{value:sP},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:IM.clone()},uTexture:{value:yP()}},vertexShader:wP,fragmentShader:MP,transparent:!0,depthWrite:!1}),c=new Cs(r,o);c.renderOrder=N0,this.scene.add(c),this.rainSplashSystem={points:c,positions:t,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 e=this.rainSystem;if(!e)return;const t=this.weather.windDirectionDeg*Ri;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-H0(this.weather.precipitationIntensity),-Math.cos(t)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);e.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(e){const t=this.rainSystem;if(!t)return;t.uniforms.uTime.value+=e,t.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),t.uniforms.uColor.value.copy(Ee.litBySky(SM,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(Ee.litBySky(IM,this.baseFogColor));const n=this.weather.windDirectionDeg*Ri,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=jh,o=h=>(h%(a*2)+a*3)%(a*2)-a;t.uniforms.uWindOffset.value.set(o(t.uniforms.uWindOffset.value.x+s*e),o(t.uniforms.uWindOffset.value.y+r*e)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const c=Math.abs(this.rainCameraDirection.y);if(Math.abs(c-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=c;const h=CM+(1-CM)*(1-c),d=LM+(1-LM)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=kM*h*(.5+.5*d)}this.updateRainSplashes(e)}updateRainSplashes(e){const t=this.rainSplashSystem;if(!t||e<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=t,a=r.array;for(let o=0,c=0;o<i.length;o+=3,c++){if(n[c]+=e,n[c]>=s[c]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*jh;i[o]=Math.cos(h)*d,i[o+2]=Math.sin(h)*d,s[c]=PM(AM,TM),n[c]=0}a[c]=n[c]/s[c]}t.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(e){this.lightningFlashes=e}updateLightning(e){let t,i=0;if(this.lightningArmed)for(const o of this.lightningFlashes){if(o.t>e)break;const c=xn.brightnessAt(o,e);c>i&&(t=o,i=c)}const n=t?Math.min(1,Math.max(.1,(pP/t.distanceM)**2)):0,s=i*n*(t?.cloudToGround?1:.6);if(s===this.lightningLevel&&!t?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const o=this.scene.fog,c=s*G0*this.relativeScale/Math.PI;o.color.setRGB(this.airlight[0]+Gr.r*c,this.airlight[1]+Gr.g*c,this.airlight[2]+Gr.b*c)}const r=this.skyMesh?.material?.color;if(r){const o=s*fP;r.setRGB(1+o*Gr.r,1+o*Gr.g,1+o*Gr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*G0*this.relativeScale,t){const{x:o,y:c,z:h}=oi(25,t.azimuthDeg,Es);this.lightningLight.position.set(o,c,h)}this.lightningBolt||(this.lightningBolt=new uo(Es*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,a),this.render()}buildCompassLabels(){this.compassSprites=$O.map(e=>{const t=kl.point(e,this.compassPoints),i=new Ep({map:EP(t),depthTest:!1,fog:!1}),n=new Uh(i),{x:s,y:r,z:a}=oi(0,e,gM);return n.position.set(s,r,a),n.scale.set(tp,tp,1),n.renderOrder=YO,n.layers.set(R0),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=vM*Math.PI/360,i=tp*Math.tan(e)/Math.tan(t);for(const n of this.compassSprites)n.scale.set(i,i,1)}disposeCompassLabels(){for(const e of this.compassSprites)e.removeFromParent(),e.material.map?.dispose(),e.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const e of this.starTiers)this.disposeMesh(e.points);this.starTiers=[]}disposeMesh(e){if(!e)return;e.removeFromParent(),"geometry"in e&&e.geometry.dispose();const t=e.material;for(const i of Array.isArray(t)?t:[t]){const n=i.map;n&&n.dispose(),i.dispose()}}}const Ri=Math.PI/180;function Xr(l,e,t){return Math.max(e,Math.min(t,l))}function PM(l,e){return l+Math.random()*(e-l)}function ip(l,e){return(l%(e*2)+e*3)%(e*2)-e}let np,sp;function gP(l){switch(l){case"snow":return vP();case"hail":return bP()}}function vP(){if(np)return np;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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)"),t.fillStyle=i,t.fillRect(0,0,l,l),np=new Lo(e),np}function bP(){if(sp)return sp;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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)"),t.fillStyle=i,t.fillRect(0,0,l,l),sp=new Lo(e),sp}let rp;function yP(){if(rp)return rp;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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)"),t.fillStyle=i,t.fillRect(0,0,l,l),rp=new Lo(e),rp}const wP=`
11156
11156
  uniform float uMaxSize;
11157
11157
  uniform float uScale;
11158
11158
  attribute float aLife;
@@ -11218,10 +11218,10 @@ void main() {
11218
11218
  gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
11219
11219
  }
11220
11220
  `;function NM(l){const t=document.createElement("canvas");t.width=128,t.height=128;const i=t.getContext("2d"),n=128/2-2,s=128/2,r=128/2,a="#010101",o="#f4f1e2";i.fillStyle=a,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const c=Xr(l.illuminatedFraction,0,1),h=l.phaseFraction<.5,d=n*Math.abs(1-2*c),u=c<.5;return i.save(),i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.clip(),i.fillStyle=o,i.beginPath(),h?(i.arc(s,r,n,-Math.PI/2,Math.PI/2,!1),i.ellipse(s,r,d,n,0,Math.PI/2,-Math.PI/2,u)):(i.arc(s,r,n,Math.PI/2,-Math.PI/2,!1),i.ellipse(s,r,d,n,0,-Math.PI/2,Math.PI/2,u)),i.fill(),i.restore(),new Lo(t)}function EP(l){const e=document.createElement("canvas");e.width=128,e.height=128;const t=e.getContext("2d");return t.fillStyle="rgba(0, 0, 0, 0.55)",t.beginPath(),t.arc(64,64,60,0,Math.PI*2),t.fill(),t.fillStyle="#ffffff",t.font="bold 52px sans-serif",t.textAlign="center",t.textBaseline="middle",t.fillText(l,64,68),new Lo(e)}function V0(l){let e=l;return function(){e|=0,e=e+1831565813|0;let i=Math.imul(e^e>>>15,1|e);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}class Ff{constructor(e,t){this.source=e,this.create=t}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=480;paint(e,t){this.disposed||(this.wanted={t:e,canvas:t},this.pumping||this.pump())}recordingChanged(e){this.scene&&(this.scene.sightingData=e)}dispose(){this.disposed=!0,this.scene?.remove(),this.scene=void 0}ensureScene(){if(this.scene)return this.scene;const e=this.create();return e.setAttribute("max-pixel-ratio","1"),e.setAttribute("always-live",""),Object.assign(e.style,{position:"fixed",left:"-10000px",top:"0",width:`${Ff.SCENE_WIDTH_PX}px`,visibility:"hidden",pointerEvents:"none"}),document.body.appendChild(e),e.documentUrl=this.source.documentUrl,e.accountInTheRound=this.source.accountInTheRound,e.sightingData=this.source.sightingData,this.scene=e,e}async pump(){this.pumping=!0;try{for(;this.wanted&&!this.disposed;){const{t:e,canvas:t}=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(e);for(let n=0;n<Ff.PATIENCE_FRAMES&&!this.wanted&&!this.disposed&&(await new Promise(s=>requestAnimationFrame(()=>s())),!this.wanted);n++)if(i.snapshotTo(t)){t.dataset.ready="true";break}}}finally{this.pumping=!1}}}class St{static held=new Map;static loaded=new Map;static generation=0;static address(e,t){const i=t??(typeof location>"u"?"http://localhost/":location.href);return new URL(e,i).href}static hold(e,t){St.held.set(e,t),St.loaded.delete(e),St.generation++}static release(){if(St.held.size!==0){for(const e of St.held.keys())St.loaded.delete(e);St.held.clear(),St.generation++}}static bytes(e,t=fetch.bind(globalThis)){const i=St.held.get(e);if(i)return Promise.resolve(i);let n=St.loaded.get(e);return n||(n=t(e).then(async s=>{if(!s.ok)throw new Error(`Frozen data not found (${s.status}): ${e}`);return new Uint8Array(await s.arrayBuffer())}),St.loaded.set(e,n),n.catch(()=>St.loaded.delete(e))),n}static async json(e){return JSON.parse(new TextDecoder().decode(await St.bytes(e)))}static async zip(e){const t=await St.bytes(e),{unzipSync:i}=await ae(async()=>{const{unzipSync:n}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:n}},[],import.meta.url);return i(t)}}class Ms{static SAME_BOUNDS_DEG=1e-9;loaded=!1;ready;list=[];constructor(e){this.ready=e.then(t=>{this.list=t},()=>{}).finally(()=>{this.loaded=!0})}nearest(e,t){let i,n=1/0;for(const s of this.list){if(s.far)continue;const{x:r,z:a}=st(s.lat,s.lng,e,t),o=Math.hypot(r,a);o<n&&(n=o,i=s)}return i}farRingOf(e,t){return this.list.find(i=>i.far&&Math.abs(i.lat-e)<=Ms.SAME_BOUNDS_DEG&&Math.abs(i.lng-t)<=Ms.SAME_BOUNDS_DEG)}static boundsOf(e){return md(e.lat,e.lng,e.radiusM)}static sameBounds(e,t){const i=(n,s)=>Math.abs(n-s)<=Ms.SAME_BOUNDS_DEG;return i(e.north,t.north)&&i(e.south,t.south)&&i(e.east,t.east)&&i(e.west,t.west)}static contains(e,t){return e.north>=t.north&&e.south<=t.south&&e.east>=t.east&&e.west<=t.west}static samePatches(e,t){return e.length===t.length&&e.every((i,n)=>i.lat===t[n].lat&&i.lng===t[n].lng&&i.radiusM===t[n].radiusM&&i.far===t[n].far)}}class Yd{static async encode(e){const{zipSync:t,strToU8:i}=await ae(async()=>{const{zipSync:r,strToU8:a}=await import("./browser-_Ncw3Jhn.js");return{zipSync:r,strToU8:a}},[],import.meta.url),n={},s={version:1,takenOn:e.takenOn,attribution:e.attribution,patches:e.patches.map((r,a)=>{const o=`${a}.f32`;return n[o]=Yd.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:o}})};return n["index.json"]=i(JSON.stringify(s,null,1)),t(n,{level:9})}static decode(e){const t=e["index.json"];if(!t)throw new Error("A relief annex without its index");const i=JSON.parse(new TextDecoder().decode(t));return{takenOn:i.takenOn,attribution:i.attribution,patches:i.patches.flatMap(n=>{const s=e[n.file];if(!s||s.length!==n.width*n.height*4)return[];const r={heights:Yd.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(e){const t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=e.length,n=new Uint8Array(t.length);for(let s=0;s<i;s++)for(let r=0;r<4;r++)n[r*i+s]=t[s*4+r];return n}static fromPlanes(e){const t=e.length/4,i=new Uint8Array(e.length);for(let n=0;n<t;n++)for(let s=0;s<4;s++)i[n*4+s]=e[s*t+n];return new Float32Array(i.buffer)}}class Ub{constructor(e){this.annex=e}async getElevationGrid(e,t,i){const{patches:n}=await this.annex,s=n.find(a=>Ms.sameBounds(Ms.boundsOf(a),e));if(s)return{...s.grid,heights:new Float32Array(s.grid.heights)};const r=n.find(a=>Ms.contains(a.grid.bounds,e));if(r)return Ub.resample(r.grid,e,t);throw new Error("The frozen relief does not hold this ground")}static resample(e,t,i){const{width:n,height:s}=i,r=new Float32Array(n*s),a=e.bounds.east-e.bounds.west,o=e.bounds.north-e.bounds.south;for(let c=0;c<s;c++){const h=t.north-(t.north-t.south)*(s>1?c/(s-1):0),d=Math.min(e.height-1,Math.max(0,(e.bounds.north-h)/o*(e.height-1))),u=Math.floor(d),p=Math.min(e.height-1,u+1),f=d-u;for(let m=0;m<n;m++){const v=t.west+(t.east-t.west)*(n>1?m/(n-1):0),g=Math.min(e.width-1,Math.max(0,(v-e.bounds.west)/a*(e.width-1))),y=Math.floor(g),w=Math.min(e.width-1,y+1),b=g-y,M=(x,T)=>e.heights[x*e.width+T],S=M(u,y)*(1-b)+M(u,w)*b,E=M(p,y)*(1-b)+M(p,w)*b;r[c*n+m]=S*(1-f)+E*f}}return{heights:r,width:n,height:s,bounds:t}}}function Zi(l,e){return l.find(t=>t.id===e)??l[0]}class AP{attribution;fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis);const t=e.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${t}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${t})`}async getImageryTexture(e,t){return T2(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const ap=[{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:()=>R2()},{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new A2}],Ll=[{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:l=>new I2({fetchImpl:l})},{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:l=>new AP({fetchImpl:l})}];class FM{constructor(e=fetch.bind(globalThis)){this.fetchImpl=e}tiles=new Map;fetch=async(e,t)=>{const i=await this.fetchImpl(e,t);if(i.ok){const n=typeof e=="string"?e:e instanceof URL?e.href:e.url,s=new Uint8Array(await i.clone().arrayBuffer());this.tiles.set(n,{bytes:s,type:i.headers.get("content-type")??"image/jpeg"})}return i}}class Uf{static async encode(e){const{zipSync:t,strToU8:i}=await ae(async()=>{const{zipSync:o,strToU8:c}=await import("./browser-_Ncw3Jhn.js");return{zipSync:o,strToU8:c}},[],import.meta.url),n={},s={};let r=0;for(const[o,c]of e.tiles){const h=`tiles/${r++}`;n[h]=c.bytes,s[o]={file:h,type:c.type}}const a={version:1,takenOn:e.takenOn,source:e.source,attribution:e.attribution,patches:e.patches,map:e.map,tiles:s};return n["index.json"]=i(JSON.stringify(a,null,1)),t(n,{level:0})}static decode(e){const t=e["index.json"];if(!t)throw new Error("An imagery annex without its index");const i=JSON.parse(new TextDecoder().decode(t)),n=new Map;for(const[s,{file:r,type:a}]of Object.entries(i.tiles)){const o=e[r];o&&n.set(s,{bytes:o,type:a})}return{takenOn:i.takenOn,source:i.source,attribution:i.attribution,patches:i.patches,map:i.map,tiles:n}}}class ym{constructor(e,t=""){this.annex=e,this.attributionStated=t}provider;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}async getImageryTexture(e,t){return(await(this.provider??=this.annex.then(n=>(this.attributionRead=n.attribution,Zi(Ll,n.source).create(ym.fetchFrom(n.tiles)))))).getImageryTexture(e,t)}static fetchFrom(e){return async t=>{const i=typeof t=="string"?t:t instanceof URL?t.href:t.url,n=e.get(i);return n?new Response(n.bytes,{status:200,headers:{"content-type":n.type}}):new Response(null,{status:404})}}}class TP{constructor(e,t=""){this.annex=e,this.attributionStated=t}picture;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}getImagery(){return this.picture??=this.annex.then(e=>{if(!e.map)throw new Error("An imagery annex that holds no map");return this.attributionRead=e.attribution,Zi(Ll,e.source).create(ym.fetchFrom(e.tiles)).getImageryTexture(e.map.bounds,{width:e.map.pixels,height:e.map.pixels})})}}class zb{constructor(e){this.annex=e}attributionRead;contemporaryRead;async itemsFor(e){const t=await this.annex;return this.attributionRead=t.attribution,this.contemporaryRead=t.contemporary,t.patches.find(i=>Ms.sameBounds(Ms.boundsOf(i),e))?.items??[]}}class IP{constructor(e,t=""){this.attributionStated=t,this.reader=new zb(e)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRoads(e){return this.reader.itemsFor(e)}}class _P{constructor(e,t=""){this.attributionStated=t,this.reader=new zb(e)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}getWater(e){return this.reader.itemsFor(e)}}class RP{constructor(e,t=""){this.attributionStated=t,this.reader=new zb(e)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRailways(e){return this.reader.itemsFor(e)}}class zf{static providers(e,t,i){const n=p=>Bi.held(e,p),s=n("relief"),r=n("imagery"),a=n("roads"),o=n("water"),c=n("railways");if(!s&&!r&&!a&&!o&&!c)return i;const h=p=>St.address(p.src,t),d=[],u={...i};if(s){const p=St.zip(h(s)).then(f=>Yd.decode(f));u.elevation=new Ub(p),d.push(p.then(f=>f.patches))}if(r){const p=St.zip(h(r)).then(f=>Uf.decode(f));u.imagery=new ym(p,r.attribution),d.push(p.then(f=>f.patches))}if(a){const p=St.json(h(a));u.roads=new IP(p,a.attribution),d.push(p.then(f=>f.patches))}if(o){const p=St.json(h(o));u.water=new _P(p,o.attribution),d.push(p.then(f=>f.patches))}if(c){const p=St.json(h(c));u.railways=new RP(p,c.attribution),d.push(p.then(f=>f.patches))}return u.patches=new Ms(zf.firstRead(d)),u}static map(e,t){const i=St.zip(St.address(e.src,t)).then(n=>Uf.decode(n));return new TP(i,e.attribution)}static async firstRead(e){for(const t of e)try{const i=await t;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[]}}class Hc{constructor(e){this.annex=e}static SAME_PLACE_DEG=1e-6;static SAME_TIME_MS=1e3;async between(e,t,i){let n;try{n=await this.annex}catch{return{status:"failed"}}const s=o=>Math.abs(o.lat-e.lat)<=Hc.SAME_PLACE_DEG&&Math.abs(o.lng-e.lng)<=Hc.SAME_PLACE_DEG,a=n.answers.find(o=>s(o)&&Math.abs(o.startMs-t)<=Hc.SAME_TIME_MS&&Math.abs(o.endMs-i)<=Hc.SAME_TIME_MS)??n.answers.find(o=>o.startMs<=t&&o.endMs>=i);return a?a.answer:{status:"failed"}}}const W0=7.5,Md=9;class Yr{static cache=new Map;static load(e){let t=Yr.cache.get(e);return t||(t=fetch(e).then(i=>i.arrayBuffer()).then(i=>Yr.parse(i)),Yr.cache.set(e,t)),t}static upTo(e,t){const i=e.filter((r,a)=>a===0||e[a-1].magnitudeLimit<t);if(i.length<=1)return Yr.load(e[0].url);const n=i.map(r=>r.url).join(`
11221
- `);let s=Yr.cache.get(n);return s||(s=Promise.all(i.map(r=>Yr.load(r.url))).then(r=>r.reduce((a,o)=>Yr.concat(a,o))),Yr.cache.set(n,s)),s}static parse(e){const t=e.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=t*Float32Array.BYTES_PER_ELEMENT;return{count:t,ra:new Float32Array(e,0*i,t),dec:new Float32Array(e,1*i,t),mag:new Float32Array(e,2*i,t),ci:new Float32Array(e,3*i,t)}}static concat(e,t){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:e.count+t.count,ra:i(e.ra,t.ra),dec:i(e.dec,t.dec),mag:i(e.mag,t.mag),ci:i(e.ci,t.ci)}}}class ii{constructor(e){if(this.heights=e,e.length!==ii.WIDTH*ii.HEIGHT)throw new Error(`a lunar relief has ${ii.WIDTH*ii.HEIGHT} samples, not ${e.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*ii.SAMPLES_PER_DEGREE;static HEIGHT=180*ii.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(e,t){const i=ii.SAMPLES_PER_DEGREE,n=(t%360+360)%360*i-.5,s=(90-e)*i-.5,r=Math.floor(n),a=Math.floor(s),o=n-r,c=s-a,h=(p,f)=>{const m=(p%ii.WIDTH+ii.WIDTH)%ii.WIDTH,v=Math.min(ii.HEIGHT-1,Math.max(0,f));return this.heights[v*ii.WIDTH+m]},d=h(r,a)*(1-o)+h(r+1,a)*o,u=h(r,a+1)*(1-o)+h(r+1,a+1)*o;return(d*(1-c)+u*c)*ii.UNIT_KM}static inBand(e,t){const i=Math.PI/180,n=Math.acos(Math.cos(e*i)*Math.cos(t*i))*180/Math.PI;return n>=ii.BAND_FROM_DEG&&n<=ii.BAND_TO_DEG}static withBump(e,t,i,n=.4){const s=new Int8Array(ii.WIDTH*ii.HEIGHT),r=ii.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),o=Math.floor(t*r),c=Math.floor((90-e)*r);for(let h=-a;h<=a;h++)for(let d=-a;d<=a;d++)Math.hypot(d,h)<=a&&(s[(c+h)*ii.WIDTH+(o+d+ii.WIDTH)%ii.WIDTH]=Math.round(i/ii.UNIT_KM));return new ii(s)}static smooth(){return new ii(new Int8Array(ii.WIDTH*ii.HEIGHT))}}class rr{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(e,t,i,n=rr.SAMPLES){const{s,u:r,w:a,distanceKm:o}=rr.frame(e,t),c=Math.PI/180,h=new Float32Array(n),d=ii.REFERENCE_RADIUS_KM;for(let u=0;u<n;u++){const p=u/n*2*Math.PI,f=Math.cos(p),m=Math.sin(p),v=f*r[0]+m*a[0],g=f*r[1]+m*a[1],y=f*r[2]+m*a[2];let w=0;for(let b=rr.SEARCH_FROM_DEG;b<=rr.SEARCH_TO_DEG;b+=rr.SEARCH_STEP_DEG){const M=Math.cos(b*c),S=Math.sin(b*c),E=M*s[0]+S*v,x=M*s[1]+S*g,T=M*s[2]+S*y,D=Math.asin(Math.max(-1,Math.min(1,T)))/c,R=Math.atan2(x,E)/c,O=d+i.heightKm(D,R),N=Math.atan2(O*S,o-O*M);N>w&&(w=N)}h[u]=w/c}return{radiusDeg:h,meanRadiusDeg:Math.asin(d/o)/c}}static frame(e,t){const i=new Fa(t.lat,t.lng,t.elevationM),n=Ua(e),s=fg(e,i,!1),r=new Ut(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*rr.AU_KM,o=rr.bodyFixed(e),c=o(r),h=Math.hypot(c[0],c[1],c[2]),d=[c[0]/h,c[1]/h,c[2]/h],u=j3(e,i),p=eb(u),f=Pa(u,new Ut(-r.x,-r.y,-r.z,n.t)),m=Math.asin(f.z/Math.hypot(f.x,f.y,f.z)),v=Math.atan2(-f.y,f.x),g=new Ut(-Math.sin(m)*Math.cos(v),Math.sin(m)*Math.sin(v),Math.cos(m),n.t),y=new Ut(-Math.sin(v),-Math.cos(v),0,n.t);return{s:d,u:o(Pa(p,g)),w:o(Pa(p,y)),distanceKm:a}}static surfacePoint(e,t,i,n){const{s,u:r,w:a}=rr.frame(e,t),o=Math.PI/180,c=[0,1,2].map(d=>Math.cos(i*o)*r[d]+Math.sin(i*o)*a[d]),h=[0,1,2].map(d=>Math.cos(n*o)*s[d]+Math.sin(n*o)*c[d]);return{latDeg:Math.asin(h[2])/o,lonDeg:Math.atan2(h[1],h[0])/o}}static radiusAt(e,t){const i=e.radiusDeg.length,n=(t/360*i%i+i)%i,s=Math.floor(n),r=n-s;return e.radiusDeg[s]*(1-r)+e.radiusDeg[(s+1)%i]*r}static uncoveredFraction(e,t,i){const n=e.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const o=a/n*2*Math.PI,c=Math.cos(o),h=Math.sin(o),d=c*i.upDeg+h*i.rightDeg,u=d*d-s+t*t;if(u<=0)continue;const p=Math.sqrt(u),f=d+p;if(f<=0)continue;const m=Math.max(0,d-p),v=Math.max(m,e.radiusDeg[a]);f>v&&(r+=.5*(f*f-v*v))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*t*t)))}static AU_KM=1495978707e-1;static bodyFixed(e){const t=uT(pe.Moon,e),i=Math.PI/180,n=t.ra*15*i,s=t.dec*i,r=t.spin*i,a=(c,[h,d,u])=>[Math.cos(c)*h+Math.sin(c)*d,-Math.sin(c)*h+Math.cos(c)*d,u],o=(c,[h,d,u])=>[h,Math.cos(c)*d+Math.sin(c)*u,-Math.sin(c)*d+Math.cos(c)*u];return c=>a(r,o(Math.PI/2-s,a(Math.PI/2+n,[c.x,c.y,c.z])))}static subObserverPoint(e,t){const i=new Fa(t.lat,t.lng,t.elevationM),n=Ua(e),s=fg(e,i,!1),r=rr.bodyFixed(e)(new Ut(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 xd{static cache=new Map;static load(e){let t=xd.cache.get(e);return t||(t=xd.fetchRelief(e).catch(()=>{}),xd.cache.set(e,t)),t}static async fetchRelief(e){const t=await fetch(e);if(!t.ok)return;let i=new Uint8Array(await t.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 ii(new Int8Array(i.buffer,i.byteOffset,i.length))}}class Bf{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=Bf.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(e){const t=Bf.MATRICES[String(e.type)];if(!t)return Us.NONE;const i=Number(e.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:t.map((r,a)=>Us.IDENTITY[a]+(r-Us.IDENTITY[a])*n),contrastGain:1}}}class Bb{static ID="fatigue";id=Bb.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(e){return Us.NONE}}class Jo{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=Jo.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary), drawn up to 0.1 % at most: a higher level is recorded but shown as 0.1 %, since nothing was measured past it. Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:Jo.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(e){const t=Number(e.bloodAlcohol??0),i=Math.max(0,Math.min(Jo.MAX_EFFECT_LEVEL,Number.isFinite(t)?t:0));if(i===0)return Us.NONE;const n=i/Jo.MEASURED_LEVEL*Jo.MEASURED_LOSS_DB;return{colorMatrix:Us.IDENTITY,contrastGain:10**(-n/20)}}}class Ol{static ALL=[new Bf,new Jo,new Bb];static byId(e){return Ol.ALL.find(t=>t.id===e)}static perceptionOf(e){return Ol.ALL.reduce((t,i)=>Us.combine(t,i.perceive(e?.[i.id]??{})),Us.NONE)}static compact(e){const t={};for(const i of Ol.ALL){const n=e[i.id]??{},s=Object.fromEntries(i.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(s).length>0&&(t[i.id]=s)}return Object.keys(t).length>0?t:void 0}}class Hf{constructor(e){this.names=e}body(e,t){return this.names?.bodies[e]??t}star(e){return this.names?.stars[e.name]??e.name}comet(e){return this.names?.comets[e.id]??e.name}nova(e){return this.names?.novae[e.id]??e.name}satelliteClass(e){return this.names?.satelliteClasses[e.id]??e.name}shower(e){return this.names?.showers[e.id]??e.name}lightRig(e){return this.names?.lightRigs[e.id]??e.name}instrument(e){return this.names?.instruments[e.id]??e.name}decorKind(e,t){return this.names?.decorKinds[e]??t}point(e){return kl.point(e,this.names?.compassPoints)}towards(e){return kl.towards(e,this.names)}}class Ar{static ENGLISH={kinds:{rail:"Railway",light_rail:"Light rail",tram:"Tramway",subway:"Metro",funicular:"Funicular"},highSpeed:"High-speed line",service:"Siding",singleTrack:"single track",tracks:"{count} tracks",overhead:"overhead wire {height} m above the rail",overheadVoltage:"overhead wire at {voltage}, {height} m above the rail",thirdRail:"third rail",thirdRailVoltage:"third rail at {voltage}",notElectrified:"not electrified",gauge:"{mm} mm gauge",metreGauge:"metre gauge",distance:"{distance} away"};static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(e,t){return e.highSpeed?t.highSpeed:e.service?t.service:t.kinds[e.kind]}static name(e,t){const i=e.name??Ar.kind(e,t);return e.services?.length?`${i} — ${e.services.join(", ")}`:i}static voltage(e,t){return e>=1e3?`${(e/1e3).toLocaleString(t,{maximumFractionDigits:1})} kV`:`${e.toLocaleString(t)} V`}static detail(e,t,i,n){const{line:s}=e,r=[];s.name&&r.push(Ar.kind(s,t).toLocaleLowerCase(n)),r.push(s.tracks>1?t.tracks.replace("{count}",String(s.tracks)):t.singleTrack);const a=s.voltageV?Ar.voltage(s.voltageV,n):void 0;if(e.contactM!==void 0){const o=e.contactM.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?t.overheadVoltage.replace("{voltage}",a):t.overhead).replace("{height}",o))}else s.electrification==="third_rail"?r.push(a?t.thirdRailVoltage.replace("{voltage}",a):t.thirdRail):s.electrification==="none"&&r.push(t.notElectrified);return s.gaugeMm===Ar.METRE_GAUGE_MM?r.push(t.metreGauge):s.gaugeMm!==Ar.STANDARD_GAUGE_MM&&r.push(t.gauge.replace("{mm}",s.gaugeMm.toLocaleString(n))),r.push(t.distance.replace("{distance}",i(e.distanceM))),s.services?.length?`${Ar.name(s,t)}; ${r.join(", ")}`:`${Ar.name(s,t)} — ${r.join(", ")}`}}class Hb{constructor(e,t){this.element=e,this.onChange=t,e.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(e,t,i=!0){const n=Hb.resolve(e,t);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(e,t){if(!(typeof e!="string"||e.trim()===""))try{const i=new URL(e.trim(),t??location.href);return i.protocol==="https:"||i.protocol==="http:"?i.href:void 0}catch{return}}}const DP={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},kP="Global Meteor Network",CP="https://globalmeteornetwork.org/data/",LP="“Thunder” by Jerimee",OP="https://creativecommons.org/licenses/by/3.0/",PP="CC BY 3.0";class Kn{static fill(e,t){e.innerHTML="";const i=u=>e.appendChild(u),n=t.currentTerrainAttribution;n&&i(Kn.text(n));const s=t.currentRoadAttribution;s&&i(Kn.text(s));const r=t.currentWaterAttribution;r&&i(Kn.text(r));const a=t.currentRailwayAttribution;a&&i(Kn.text(a));const o=t.ufoElement.observerMapCredit;o&&!n?.includes(o)&&i(Kn.text(o));for(const u of t.decorModelCredits){const p=u.author?` — ${u.author}`:"",f=document.createElement("li");u.sourceUrl?f.append(Kn.link(u.sourceUrl,u.title),document.createTextNode(`${p} (${u.license})`)):f.textContent=`${u.title}${p} (${u.license})`,i(f)}for(const u of t.ufoElement.sighting.references){if(!u.credit)continue;const p=document.createElement("li");u.creditUrl?p.appendChild(Kn.link(u.creditUrl,u.credit)):p.textContent=u.credit,i(p)}if(t.ufoElement.sighting.traces.length>0){const u=new vs(Zs.preferencesFor(t)),p=new Set(t.ufoElement.sighting.traces.map(f=>u.read(f.source)).filter(f=>!!f));for(const f of p)i(Kn.text(f))}const c=t.satelliteState;if(c.status==="ready"&&c.credit){const u=document.createElement("li");u.appendChild(Kn.link(c.creditUrl??"",c.credit)),i(u)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const u=document.createElement("li");u.append(Kn.link(CP,kP),document.createTextNode(" (CC BY 4.0)")),i(u)}const h=t.aircraftState;if(h.status==="ready"&&h.shown>0){const u=document.createElement("li");if(u.appendChild(Kn.link(h.creditUrl,h.credit)),i(u),h.trailCredit){const p=document.createElement("li");p.appendChild(Kn.link(h.trailCredit.creditUrl,h.trailCredit.credit)),i(p)}}const d=Kn.text(`${LP} (`);d.append(Kn.link(OP,PP),document.createTextNode(")")),i(d)}static text(e){const t=document.createElement("li");return t.textContent=e,t}static link(e,t){const i=document.createElement("a");return i.href=e,i.target="_blank",i.rel="noopener",i.textContent=t,i}}const NP=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,FP=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,UP=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,zP=20,BP=1;class HP{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(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",e);return}}Il.unlock(this.context)}setAmbient(e,t,i){if(this.requested={type:e,intensity:t,windSpeed:i},!this.context)return;this.paused&&(e="none",t=0,i=0);const n=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=n==="hail"?Math.min(1,t*1.3+.2):n==="rain"?t: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(NP,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,o=>{this.ambientSource=o?.source,this.ambientGain=o?.gain,o&&(o.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/zP,1);const s=i>BP;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(FP,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,o=>{this.windSource=o?.source,this.windGain=o?.gain,o&&(o.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:i,windSpeed:n}=this.requested;this.setAmbient(t,i,n)}playThunder(){!this.context||this.paused||this.playOneShot(UP,.9)}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(e,t,i,n){if(t!==i()){e?.source.stop();return}n(e)}async startLoop(e,t){const i=this.context;if(i)try{const n=await this.getBuffer(e),s=i.createBufferSource();s.buffer=n,s.loop=!0;const r=i.createGain();return r.gain.value=t,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(e,t){const i=this.context;if(i)try{const n=await this.getBuffer(e),s=i.createBufferSource();s.buffer=n;const r=i.createGain();r.gain.value=t,s.connect(r).connect(this.output(i)),s.start()}catch(n){console.warn("Thunder sound failed to load:",n)}}async getBuffer(e){const t=this.context;if(!t)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${e}`);return n.arrayBuffer()}).then(n=>t.decodeAudioData(n)),this.buffers.set(e,i)),i}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}class Ta{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[n,s]=this.perifocalAxes(),r=Math.sqrt(Ta.SUN_GM_AU3_PER_DAY2*(1+t)/i);this.perihelionPosition=this.scale(n,i),this.perihelionVelocity=this.scale(s,r),this.inverseSemiMajorAxis=(1-t)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(e){const t=e-this.elements.perihelionJd,i=this.universalAnomaly(t),n=this.inverseSemiMajorAxis*i*i,s=this.elements.perihelionAu,r=1-i*i/s*Ta.stumpffC(n),a=t-i*i*i/Math.sqrt(Ta.SUN_GM_AU3_PER_DAY2)*Ta.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(e){const t=this.positionAt(e);return Math.hypot(t.x,t.y,t.z)}universalAnomaly(e){if(e===0)return 0;const t=Math.sign(e),i=Math.sqrt(Ta.SUN_GM_AU3_PER_DAY2)*Math.abs(e),n=a=>{const o=this.inverseSemiMajorAxis*a*a,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*a*a*a*Ta.stumpffS(o)+c*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<Ta.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){const o=(r+s)/2;n(o)<i?r=o:s=o}return t*(r+s)/2}perifocalAxes(){const e=this.elements.ascendingNodeDeg*Math.PI/180,t=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,n=Math.cos(e),s=Math.sin(e),r=Math.cos(t),a=Math.sin(t),o=Math.cos(i),c=Math.sin(i);return[{x:n*r-s*a*o,y:s*r+n*a*o,z:a*c},{x:-n*a-s*r*o,y:-s*a+n*r*o,z:r*c}]}scale(e,t){return{x:e.x*t,y:e.y*t,z:e.z*t}}static stumpffC(e){if(Math.abs(e)<1e-6)return 1/2-e/24+e*e/720;if(e>0)return(1-Math.cos(Math.sqrt(e)))/e;const t=Math.sqrt(-e);return(Math.cosh(t)-1)/-e}static stumpffS(e){if(Math.abs(e)<1e-6)return 1/6-e/120+e*e/5040;if(e>0){const i=Math.sqrt(e);return(i-Math.sin(i))/(i*i*i)}const t=Math.sqrt(-e);return(Math.sinh(t)-t)/(t*t*t)}}const KS=[{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 Dp{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(e){const t=this.julianDayOf(e);return KS.filter(i=>Math.abs(t-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(e,t){return this.aroundDate(e).map(i=>this.appearanceOf(i,e,t)).sort((i,n)=>i.magnitude-n.magnitude)[0]}static appearanceOf(e,t,i){const n=di(t),s=this.earthPositionAt(n),r=this.apparentPositionOf(e,2451545+n.tt,s),a=this.subtract(r,s),o=this.length(r),c=this.length(a),h=this.tailEndAt(e,r,s,o,n,t,i),d=this.horizontalOf(a,n,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:o,earthDistanceAu:c,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(e,o,c)}}static magnitudeAt(e,t,i){const n=e.absoluteMagnitude+5*Math.log10(i)+2.5*e.activityExponent*Math.log10(t);return Math.max(n,e.peakMagnitude)}static tailEndAt(e,t,i,n,s,r,a){if(e.tailLengthAu===void 0)return{};const o=1+e.tailLengthAu/n,c=this.subtract({x:t.x*o,y:t.y*o,z:t.z*o},i),h=this.subtract(t,i);return{tailEnd:this.horizontalOf(c,s,r,a),tailLengthDeg:this.angleBetween(h,c)}}static apparentPositionOf(e,t,i){const n=this.orbitOf(e);let s=n.positionAt(t);for(let r=0;r<2;r++){const a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(t-a)}return s}static horizontalOf(e,t,i,n){const s=Pa(K3(),new Ut(e.x,e.y,e.z,t)),r=Pa(Jx(t),s),a=fg(t,new Fa(n.lat,n.lng,n.elevationM),!0),o=new Ut(r.x-a.x,r.y-a.y,r.z-a.z,t),c=rm(o);return Ld(c.ra,c.dec,i,n)}static earthPositionAt(e){return Pa($3(),Eo(pe.Earth,e))}static julianDayOf(e){return 2451545+di(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new Ta(e.orbit);return this.orbits.set(e.id,i),i}static subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}static length(e){return Math.hypot(e.x,e.y,e.z)}static angleBetween(e,t){const i=(e.x*t.x+e.y*t.y+e.z*t.z)/(this.length(e)*this.length(t)||1);return Math.acos(Math.min(1,Math.max(-1,i)))*180/Math.PI}}const $0=[{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 Gf{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return $0.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),n=[];for(const s of $0){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Tr.ofJ2000(s.raHours,s.decDeg,e,t),magnitude:r})}return n.sort((s,r)=>s.magnitude-r.magnitude)}static brightestAt(e,t){return this.appearancesAt(e,t)[0]}static byId(e){return $0.find(t=>t.id===e)}static magnitudeAt(e,t){const i=e.lightCurve,n=t-e.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],[o,c]=i[s]??i[0];if(o===r)return a;const h=Math.min(1,Math.max(0,(n-r)/(o-r)));return a+h*(c-a)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const GP=[{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}],wh=6.5;class sh{static activeAt(e){return GP.flatMap(t=>{const i=this.nearness(t,e);return i<=0?[]:[{shower:t,zhr:t.peakZhr*i,nearness:i}]})}static nearness(e,t){const i=this.dayOfYear(t),n=this.dayOfYear(this.asDate(e.start)),s=this.dayOfYear(this.asDate(e.peak)),r=this.dayOfYear(this.asDate(e.end)),a=this.wrappedDelta(i,s),o=this.wrappedDelta(s,n),c=this.wrappedDelta(r,s);return a<0?a<-o?0:1+a/o:a>0?a>c?0:1-a/c:1}static observedRatePerHour(e,t,i,n=wh){if(t<=0)return 0;const s=wh-n;return e*Math.sin(t*Math.PI/180)/Math.pow(i,s)}static radiantPosition(e,t,i){return Tr.ofJ2000(e.radiantRaHours,e.radiantDecDeg,t,i)}static dayOfYear(e){const t=Date.UTC(e.getUTCFullYear(),0,1);return Math.floor((Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())-t)/864e5)+1}static asDate(e){return new Date(Date.UTC(2001,e.month-1,e.day))}static wrappedDelta(e,t){const i=e-t;return i>182?i-365:i<-182?i+365:i}}class Ui{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=di(e),n=new tm(0,E3(e).elon-90,1),s=Pa(Z3(i),ib(n,i)),r=rm(s);return Ld(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=wh){const i=Ui.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),n=wh-t;return(Ui.QUIET_RATE_PER_HOUR+i)/Math.pow(Ui.POPULATION_INDEX,n)}static schedule(e){const t=new bm(e.seed^1542469173);return Ir.schedule(e).map(i=>{const n=Ui.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=Ui.turnAround(n,t.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:Ui.toHorizontal(a),bearingDeg:Ui.bearingFrom(a,n)}})}static turnAround(e,t){const[i,n]=Ui.basisAround(e),s=t*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(e,t){const[i,n]=Ui.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,r=Ui.normalise({x:t.x-e.x*s,y:t.y-e.y*s,z:t.z-e.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(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=Ui.normalise(Ui.cross(e,t));return[i,Ui.normalise(Ui.cross(e,i))]}static toHorizontal(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,e.y/t)))*180/Math.PI,azimuthDeg:(Math.atan2(e.x,-e.z)*180/Math.PI%360+360)%360}}static appearanceOf(e){const t=Ui.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Ui.turnAround(t,e.bearingDeg),n=e.fromRadiantDeg*Math.PI/180;return Ui.toHorizontal({x:t.x*Math.cos(n)+i.x*Math.sin(n),y:t.y*Math.cos(n)+i.y*Math.sin(n),z:t.z*Math.cos(n)+i.z*Math.sin(n)})}static toCartesian(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180,n=Math.cos(t);return{x:n*Math.sin(i),y:Math.sin(t),z:-n*Math.cos(i)}}static cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}static normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}static TYPICAL_VELOCITY_KM_S=40}const UM="https://ufoathome.org/tle/index.json";class Xn{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Xn.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/tle/index.json",location.href).href),e.includes(UM)||e.push(UM),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${Xn.FIRST_SNAPSHOT}T00:00:00Z`)-Xn.MAX_ELEMENT_AGE_DAYS*Xn.DAY_MS;if(e.getTime()<t)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(n=>e.getTime()>=Date.parse(n.from)-Xn.MAX_ELEMENT_AGE_DAYS*Xn.DAY_MS&&e.getTime()<=Date.parse(n.to)+Xn.MAX_ELEMENT_AGE_DAYS*Xn.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:i,base:n}=t,s=[],r=[];for(const a of Object.keys(i.kinds)){const o=await this.kindAt(a,e,i,n);s.push(...o),r.push(this.coverageOf(a,e,i,o.length>0))}return{objects:s,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(e,t,i,n){const s=t.getTime(),r=i.binDays*Xn.DAY_MS,a=Math.floor(s/r),o=s-a*r<r/2?a-1:a+1,c=new Set(i.kinds[e].bins),h=[a,o].map(m=>new Date(m*r).toISOString().slice(0,10)).filter(m=>c.has(m));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,n).href),...h.map(m=>this.binary(new URL(`${e}/${m}.bin`,n).href))]),p=new Map;for(const m of u)for(const v of Xn.decode(m,i.recordBytes)){const g=p.get(v.norad);(!g||Math.abs(v.epochMs-s)<Math.abs(g.epochMs-s))&&p.set(v.norad,v)}const f=[];for(const m of p.values()){const v=Math.abs(m.epochMs-s)/Xn.DAY_MS;if(v>Xn.MAX_ELEMENT_AGE_DAYS)continue;const g=d[m.norad]??{name:String(m.norad)};g.launch&&Date.parse(`${g.launch}T00:00:00Z`)>s||f.push({norad:m.norad,name:g.name,kind:e,launch:g.launch,stdMag:g.stdMag,elements:m,ageDays:v})}return f}coverageOf(e,t,i,n){const{from:s,to:r}=i.kinds[e],a=t.getTime(),o=Xn.MAX_ELEMENT_AGE_DAYS*Xn.DAY_MS,c=n?"covered":a<Date.parse(s)-o?"before":a>Date.parse(r)+o?"after":"gap";return{kind:e,status:c,from:s,to:r}}static decode(e,t){const i=new DataView(e),n=[];for(let s=0;s+t<=e.byteLength;s+=t)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 e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;return{index:await t.json(),base:e}}catch{}})(),this.index}json(e){return this.cached(e,async t=>t.json())}binary(e){return this.cached(e,async t=>t.arrayBuffer())}cached(e,t){let i=this.files.get(e);return i||(i=this.fetchImpl(e).then(n=>{if(!n.ok)throw new Error(`${e}: ${n.status}`);return t(n)}),i.catch(()=>this.files.delete(e)),this.files.set(e,i)),i}}class VP{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const i=At.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(t.inFrontM!==void 0){const i=At.sizeMAt(t.inFrontM,e);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(e){return e<=0?{}:{minM:this.lowerM===void 0?void 0:At.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:At.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class Pl{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*Pl.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=Pl.degOver(e)/t;return i<1?1:Math.min(Pl.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Dn{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 Pl.DEG_PER_SECOND*3600}static graspOf(e,t={}){if(e.visualAid)return Dn.visualAidGrasp(e,t.focalLengthMm);const i=t.exposureSeconds??e.exposureSeconds,n=t.fNumber??e.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return Dn.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??Dn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=Dn.resolutionArcsec(e,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,Dn.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(e,t){const i=e.visualAid,n=Dn.EYE,s=t??e.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(e,t,i){const s=(e.detailUm??Dn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*Dn.ARCSEC_PER_RADIAN,r=1.22*Dn.WAVELENGTH_M/(i/1e3)*Dn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(e){return e/Dn.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=Dn.graspOf(e,t),n=Dn.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(e,t){const i=t.fieldOfViewDeg===void 0?void 0:hi.focalLengthMmFor(e,t.fieldOfViewDeg);return Dn.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const zM=111320,Zh=Math.PI/180,WP=1.02,$P=1;class Sd{static of(e,t){const i=Sd.sightings(e,t);if(i.length<2)return;const n=Sd.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,o=Math.tan(r.widthDeg/2*Zh)===0?0:Math.tan(s.widthDeg/2*Zh)/Math.tan(r.widthDeg/2*Zh);if(o<WP)return;const c=a/(o-1),h=At.sizeMAt(c,s.widthDeg),d=i.map(u=>({t:u.t,m:At.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===t)?.shape,s=n?.angular?.widthDeg,r=pt(e,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(e){let t;for(const i of e)for(const n of e){if(i.t>=n.t)continue;const s=Sd.closedAlongSight(i,n),[r,a,o]=s>=0?[n,i,s]:[i,n,-s];o<$P||r.widthDeg<=a.widthDeg||(!t||o>t.closedM)&&(t={near:r,far:a,closedM:o})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*zM,n=(t.lng-e.lng)*zM*Math.cos(e.lat*Zh),s=(e.sightAzimuthDeg??0)*Zh;return i*Math.cos(s)+n*Math.sin(s)}}class as{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(e){if(e.statedM!==void 0&&e.statedM>0)return{distanceM:as.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:as.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:as.atLeastNearest(e.derivedM),basis:"derived"};const t=as.largest(e.range?.minM,e.crossing?.behindM),i=as.smallest(e.range?.maxM,e.crossing?.inFrontM),n=t===void 0?void 0:t*as.MARGIN,s=i===void 0?void 0:i/as.MARGIN;return n!==void 0&&s!==void 0?{distanceM:as.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:as.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<as.CONVENTIONAL_M?{distanceM:as.atLeastNearest(s),basis:"bounded"}:{distanceM:as.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(as.NEAREST_M,e)}static largest(...e){const t=e.filter(i=>i!==void 0&&i>0);return t.length===0?void 0:Math.max(...t)}static smallest(...e){const t=e.filter(i=>i!==void 0&&i>0);return t.length===0?void 0:Math.min(...t)}}const K0=Math.PI/180;class qe{constructor(e,t,i){this.body=e,this.ground=t,this.eyeAt=i;const n=[...e.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)qe.collect(this.motionKeys,s.t,s.motions),qe.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;lightKeys=new Map;static collect(e,t,i){for(const[n,s]of Object.entries(i??{})){const r=e.get(n)??[];r.push({t,value:s}),e.set(n,r)}}motionsAt(e){return qe.channelsAt(this.motionKeys,e,0)}lightsAt(e){return this.lightKeys.size>0?qe.channelsAt(this.lightKeys,e,void 0):void 0}static channelsAt(e,t,i){const n={};for(const[s,r]of e){let a=r.length-1;for(;a>=0&&r[a].t>t;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const o=r[a],c=r[Math.min(a+1,r.length-1)],h=c===o||c.t===o.t?0:Math.min(1,(t-o.t)/(c.t-o.t));n[s]=qe.lerp(o.value,c.value,h)}return n}static eyeOf(e,t,i){const n=pt(e,0),s=pt(e,t),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?st(s.lat,s.lng,n.lat,n.lng):void 0,o=a?a.x:0,c=a?-a.z:0;return{eastM:o,northM:c,upM:i.heightAt(o,c)+qe.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(e,t,i,n){const s=qe.directionOf(t,i),r=c=>e.upM+s.upM*c-n.heightAt(e.eastM+s.eastM*c,e.northM+s.northM*c);let a=0,o=0;for(;o<qe.MAX_RANGE_M;){if(o=a+Math.max(.5,a*.01),r(o)<=0){for(let c=0;c<30;c++){const h=(a+o)/2;r(h)<=0?o=h:a=h}return o}a=o}}static directionOf(e,t){const i=e*K0,n=t*K0;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(e){const t=this.keys;if(t.length===0||e<t[0].t)return;let i=0,n=t.length-1;for(;i<n;){const m=i+n+1>>1;t[m].t>e?n=m-1:i=m}const s=i,r=t[s];if(!r.present)return;const a=t[Math.min(s+1,t.length-1)],o=a===r||a.t===r.t?0:Math.min(1,(e-r.t)/(a.t-r.t)),c=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(e):void 0,h=c?c.eastM+qe.lerp(r.carried.eastM,a.carried.eastM,o):qe.lerp(r.eastM,a.eastM,o),d=c?c.northM+qe.lerp(r.carried.northM,a.carried.northM,o):qe.lerp(r.northM,a.northM,o),u={widthM:qe.lerp(r.sizeM.widthM,a.sizeM.widthM,o),lengthM:qe.lerp(r.sizeM.lengthM,a.sizeM.lengthM,o),heightM:qe.lerp(r.sizeM.heightM,a.sizeM.heightM,o)},p={headingDeg:qe.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,o),pitchDeg:qe.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,o),rollDeg:qe.lerp(r.attitude.rollDeg,a.attitude.rollDeg,o)};let f;if(c)f=c.upM+qe.lerp(r.carried.upM,a.carried.upM,o);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const m=qe.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,o);f=this.groundUnderFootprint(h,d,u,p.headingDeg)+m+u.heightM/2}else f=qe.lerp(this.centreUpOf(r),this.centreUpOf(a),o);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:d,upM:f,sizeM:u,attitude:p,appearance:{color:qe.lerpColor(r.appearance.color,a.appearance.color,o),albedo:qe.lerp(r.appearance.albedo,a.appearance.albedo,o),luminanceCdM2:qe.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,o),transparency:qe.lerp(r.appearance.transparency,a.appearance.transparency,o),haloScale:qe.lerp(r.appearance.haloScale,a.appearance.haloScale,o)},flame:qe.flameBetween(r.flame,a.flame,o),motions:this.motionsAt(e),lights:this.lightsAt(e),throwsFlame:this.body.track.some(m=>m.flame!==void 0&&m.flame.luminanceCdM2>0)}}static flameBetween(e,t,i){if(!e||e.luminanceCdM2<=0)return i>=1&&t&&t.luminanceCdM2>0?t:void 0;const n=e,s=t??e,r={...i<1?n:s,lengthM:qe.lerp(n.lengthM,s.lengthM,i),widthM:qe.lerp(n.widthM,s.widthM,i),luminanceCdM2:qe.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(e){if(!("upM"in e.vertical))return this.groundUnderFootprint(e.eastM,e.northM,e.sizeM,e.attitude.headingDeg)+e.vertical.aboveGroundM+e.sizeM.heightM/2;const t=e.vertical.fromGround;if(!t)return e.vertical.upM;const i=e.vertical.upM+this.ground.heightAt(t.eastM,t.northM);return Math.max(i,this.groundUnderFootprint(e.eastM,e.northM,e.sizeM,e.attitude.headingDeg)+e.sizeM.heightM/2)}groundUnderFootprint(e,t,i,n){const s=n*K0,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let o=this.ground.heightAt(e,t);for(const[c,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const d=c*i.widthM/2,u=h*i.lengthM/2;o=Math.max(o,this.ground.heightAt(e+r.eastM*d+a.eastM*u,t+r.northM*d+a.northM*u))}return o}place(e,t){const i=[];let n;for(const s of e){const r=s.sizeM??n?.sizeM??qe.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},o={color:s.appearance?.color??n?.appearance.color??qe.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??qe.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??qe.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??qe.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??qe.DEFAULT_APPEARANCE.haloScale},c=this.positionOf(s,r,t)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!c)continue;const h=s.flame??n?.flame,d=s.present??n?.present??!0;if(n={t:s.t,...c,sizeM:r,attitude:a,appearance:o,flame:h,present:d},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const u=qe.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:u.eastM*s.distanceM,northM:u.northM*s.distanceM,upM:u.upM*s.distanceM}}i.push(n)}return i}verticalOf(e,t){if(e.onGround)return{aboveGroundM:0};if(e.altitudeAboveGroundM!==void 0)return{aboveGroundM:e.altitudeAboveGroundM};if(e.altitudeM!==void 0)return{upM:e.altitudeM+t.heightM/2,fromGround:this.body.altitudeFrom}}positionOf(e,t,i){if(e.eastM!==void 0&&e.northM!==void 0)return{eastM:e.eastM,northM:e.northM,vertical:this.verticalOf(e,t)??{aboveGroundM:0}};if(e.azimuthDeg===void 0||e.altitudeDeg===void 0)return;const n=i(e.t);if(!n)return;const s=e.distanceM??(e.onGround?qe.lineOfSightMeetsGround(n,e.azimuthDeg,e.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=qe.directionOf(e.azimuthDeg,e.altitudeDeg),a=n.eastM+r.eastM*s,o=n.northM+r.northM*s;return{eastM:a,northM:o,vertical:this.verticalOf(e,t)??{upM:n.upM+r.upM*s}}}static lerp(e,t,i){return e+(t-e)*i}static lerpColor(e,t,i){const n=qe.rgbOf(e),s=qe.rgbOf(t);return!n||!s?i<1?e:t:"#"+n.map((r,a)=>Math.round(qe.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(e){const t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e);if(!t)return;const i=t[1].length===3?t[1].replace(/./g,"$&$&"):t[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(e,t,i){const n=((t-e)%360+540)%360-180;return((e+n*i)%360+360)%360}}class os{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(e){const t=e?.flares;return!e||!t||t.length===0?e:{...e,bodies:[...e.bodies,...t.flatMap(i=>os.bodiesOf(i))]}}static bodiesOf(e){const t={...os.MJU_7,...e.flare},i=[],n=e.aircraft;if(n.model||n.sound){const s=e.releases.map(h=>h.t),r=Math.min(n.t,...s)-12e4,a=Math.max(n.t,...s)+12e4,o=n.model?{color:"#30333a",albedo:.15}:{transparency:1},c=h=>{const d=os.aircraftAt(n,h);return{t:h,eastM:d.x,northM:d.y,altitudeM:d.z,attitude:{headingDeg:n.headingDeg},sizeM:n.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:o}};i.push({id:`${e.id}-aircraft`,title:e.title,model:n.model??{id:"sphere"},track:[c(r),c(a)],sound:n.sound})}return n.glow&&i.push(os.glowBody(e,n.glow)),e.releases.forEach((s,r)=>i.push(os.flareBody(e,t,s,r))),i}static aircraftAt(e,t){const i=e.headingDeg*Math.PI/180,n=(t-e.t)/1e3*e.speedMS;return{x:e.eastM+Math.sin(i)*n,y:e.northM+Math.cos(i)*n,z:e.altitudeM}}static burnShare(e,t){if(t<0||t>=e.burnS)return 0;if(t<.2)return t/.2;const i=e.burnS*.75;return t<=i?1:(e.burnS-t)/(e.burnS-i)}static trajectory(e,t,i,n=os.SAMPLE_MS){const s=e.aircraft,r=s.headingDeg*Math.PI/180,o={...os.aircraftAt(s,i),vx:Math.sin(r)*s.speedMS,vy:Math.cos(r)*s.speedMS,vz:-t.ejectionMS},c=(e.wind?.towardDeg??0)*Math.PI/180,h=e.wind?.speedMS??0,d=Math.sin(c)*h,u=Math.cos(c)*h,p=s.originElevationM??1e3,f=[{t:i,x:o.x,y:o.y,z:o.z}],m=os.STEP_S,v=Math.round(n/1e3/m),g=Math.ceil(t.burnS/m);for(let y=1;y<=g;y++){const w=y*m,b=t.massKg-t.burnedKg*Math.min(1,w/t.burnS),M=1.225*Math.exp(-(o.z+p)/8500),S=o.vx-d,E=o.vy-u,x=o.vz,T=Math.hypot(S,E,x),D=.5*M*t.dragAreaM2*T/b;o.vx=(o.vx+D*m*d)/(1+D*m),o.vy=(o.vy+D*m*u)/(1+D*m),o.vz=(o.vz-os.G*m)/(1+D*m),o.x+=o.vx*m,o.y+=o.vy*m,o.z+=o.vz*m,(y%v===0||y===g)&&f.push({t:i+Math.round(w*1e3),x:o.x,y:o.y,z:o.z})}return f}static glowBody(e,t){const i=t.sizeM/2,n=t.luminousIntensityCd/(Math.PI*i*i),s=[{t:t.fromT,lit:!0}];if(t.onS&&t.offS)for(let c=t.fromT,h=!0;c<t.untilT;h=!h)c+=(h?t.onS:t.offS)*1e3,c<t.untilT&&s.push({t:c,lit:!h});const r=(c,h)=>{const d=os.aircraftAt(e.aircraft,c);return{t:c,eastM:d.x,northM:d.y,altitudeM:d.z,appearance:{color:t.color,luminanceCdM2:h?n:0}}},a=[];s.forEach(({t:c,lit:h},d)=>{d>0&&a.push(r(c-1,!h)),a.push(r(c,h))}),a[0]={...a[0],sizeM:{widthM:t.sizeM,lengthM:t.sizeM,heightM:t.sizeM},present:!0};const o=s[s.length-1];return a.push(r(t.untilT,o.lit),{t:t.untilT+1,present:!1}),{id:`${e.id}-glow`,title:e.title,explains:t.explains,model:{id:"sphere"},track:a}}static flareBody(e,t,i,n){const s=t.flameSizeM,r=s/2,a=t.luminousIntensityCd/(Math.PI*r*r),o=os.trajectory(e,t,i.t),c=o.map((h,d)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...d===0?{sizeM:{widthM:s,lengthM:s,heightM:s},present:!0}:{},appearance:{color:t.color,luminanceCdM2:a*os.burnShare(t,(h.t-i.t)/1e3),...d===0?{haloScale:1}:{}}}));return c.push({t:o[o.length-1].t+1,present:!1}),{id:`${e.id}-flare-${n+1}`,title:e.title,explains:i.explains,model:{id:"sphere"},track:c}}}class It{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=It.COMMON.luminousIntensityCd/(Math.PI*It.COMMON.widthM/2*It.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(e){const t=e?.lanterns;return!e||!t||t.length===0?e:{...e,bodies:[...e.bodies,...t.flatMap(i=>It.bodiesOf(i))]}}static bodiesOf(e){return It.releasesOf(e).map((t,i)=>It.lanternBody(e,t,i))}static releasesOf(e){const t=[...e.releases??[]],i=e.group;if(!i||!(i.count>0))return t;const n=It.randomFrom(i.seed??1),s=o=>o.min+(o.max-o.min)*n(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let o=0;o<i.count;o++){const c=i.fromT+r*o+(n()-.5)*r,h=a*Math.sqrt(n()),d=2*Math.PI*n();t.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,c))),explains:i.explains,eastM:Math.round(h*Math.sin(d)*10)/10,northM:Math.round(h*Math.cos(d)*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 t}static randomFrom(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let i=t;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(e,t){return{...It.COMMON,...e.lantern,...t.lantern}}static heatShare(e,t){if(t<0||t>=e.burnS)return 0;const i=e.burnS*.75;return t<=i?1:(e.burnS-t)/(e.burnS-i)}static windAt(e,t){const i=It.componentsOf(e.wind),n=e.windAloft;if(!n)return i;const s=It.componentsOf(n),r=Math.max(0,Math.min(1,t/n.atM));return{x:i.x+(s.x-i.x)*r,y:i.y+(s.y-i.y)*r}}static trajectory(e,t,i=It.SAMPLE_MS){const n=It.typeOf(e,t),s=e.site,r=s.altitudeM??0,a=Math.max(0,t.burnedS??0),o=s.originElevationM??0,c=(e.airTemperatureC??10)+273.15,h={x:s.eastM+(t.eastM??0),y:s.northM+(t.northM??0),z:t.altitudeM??r,vx:0,vy:0,vz:0,excessK:n.insideExcessK*It.heatShare(n,a)},d=It.STEP_S,u=Math.max(1,Math.round(i/1e3/d)),p=Math.ceil(Math.max(0,n.burnS-a)/d),f=[{t:t.t,x:h.x,y:h.y,z:h.z,light:It.heatShare(n,a),tiltDeg:0,tiltTowardDeg:0}],m=It.gusts(e.turbulence??It.TURBULENCE,It.seedOf(t),d);for(let v=1;v<=p;v++){const g=v*d,y=a+g,w=It.heatShare(n,y);h.excessK+=(n.insideExcessK*w-h.excessK)*Math.min(1,d/It.COOLING_S);const b=h.z-r,M=c-It.LAPSE*Math.max(0,b),S=101325*Math.exp(-(h.z+o)/8400),E=S/(It.R_AIR*M),x=S/(It.R_AIR*(M+h.excessK)),T=n.massKg-n.fuelKg*Math.min(1,y/n.burnS),D=(E-x)*n.envelopeVolumeM3*It.G,R=T+x*n.envelopeVolumeM3+.5*E*n.envelopeVolumeM3,O=It.windAt(e,b),N=m(),C={x:O.x+N.x,y:O.y+N.y,z:N.z},k=h.vx-C.x,P=h.vy-C.y,F=h.vz-C.z,G=.5*E*n.dragAreaM2*Math.hypot(k,P,F)/R;h.vx=(h.vx+G*d*C.x)/(1+G*d),h.vy=(h.vy+G*d*C.y)/(1+G*d),h.vz=(h.vz+G*d*C.z+(D-T*It.G)/R*d)/(1+G*d);const Y=h.z<=r&&h.vz<=0;if(Y&&(h.vx=0,h.vy=0,h.vz=0),h.x+=h.vx*d,h.y+=h.vy*d,h.z=Math.max(r,h.z+h.vz*d),v%u===0||v===p){const W=C.x-h.vx,ee=C.y-h.vy,se=.5*E*n.dragAreaM2*Math.hypot(W,ee,C.z-h.vz)*Math.hypot(W,ee);f.push({t:t.t+Math.round(g*1e3),x:h.x,y:h.y,z:h.z,light:w,tiltDeg:Y?0:Math.atan2(se,T*It.G)*180/Math.PI,tiltTowardDeg:(Math.atan2(W,ee)*180/Math.PI+360)%360})}}return f}static seedOf(e){return e.seed!==void 0?e.seed:Math.round(e.t)*2654435761+Math.round((e.eastM??0)*100)*40503+Math.round((e.northM??0)*100)>>>0}static gusts(e,t,i){const n=It.randomFrom(t),s=()=>Math.sqrt(-2*Math.log(Math.max(1e-12,n())))*Math.cos(2*Math.PI*n()),r=e.timescaleS>0?Math.exp(-i/e.timescaleS):0,a=Math.sqrt(1-r*r),o={x:e.horizontalMS*s(),y:e.horizontalMS*s(),z:e.verticalMS*s()};return()=>(o.x=r*o.x+a*e.horizontalMS*s(),o.y=r*o.y+a*e.horizontalMS*s(),o.z=r*o.z+a*e.verticalMS*s(),o)}static componentsOf(e){if(!e)return{x:0,y:0};const t=e.towardDeg*Math.PI/180;return{x:Math.sin(t)*e.speedMS,y:Math.cos(t)*e.speedMS}}static lanternBody(e,t,i){const n=It.typeOf(e,t),s=n.luminousIntensityCd/(Math.PI*n.widthM/2*n.heightM/2),r=It.trajectory(e,t),a={widthM:n.widthM,lengthM:n.widthM,heightM:n.heightM},o=It.through(n.color,n.paperColor),c=r.map((h,d)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...d===0?{sizeM:a,present:!0}:{},attitude:{headingDeg:Math.round(h.tiltTowardDeg),pitchDeg:-Math.round(h.tiltDeg*10)/10},appearance:{color:o,luminanceCdM2:s*h.light,...d===0?{albedo:.6,haloScale:1}:{}},lights:It.lightsOf(s*h.light)}));return c.push({t:r[r.length-1].t+1,present:!1}),{id:`${e.id}-lantern-${i+1}`,title:It.TITLE,explains:t.explains,model:{id:`ufoathome-sky-lantern-${n.shape}`},modelParameters:{paperColor:n.paperColor},flicker:It.FLICKER,altitudeFrom:{eastM:r[0].x,northM:r[0].y},track:c}}static lightsOf(e){return{paper:e,"paper-inside":e*It.INSIDE_SHARE,flame:e>0?It.FLAME_CDM2*e/It.PAPER_FULL_CDM2:0}}static through(e,t){const i=o=>[1,3,5].map(c=>parseInt(o.slice(c,c+2),16)/255),n=i(e),s=i(t),r=n.map((o,c)=>o*s[c]),a=Math.max(...n)/(Math.max(...r)||1);return"#"+r.map(o=>Math.round(Math.min(1,o*a)*255).toString(16).padStart(2,"0")).join("")}}class Gb{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=Gb.FIRST_DAY}}class KP{constructor(e,t,i){this.citation=e,this.covers=t,this.load=i}loading;mayCover(e){return this.covers(e)}async between(e,t,i,n){try{return await(await this.provider()).between(e,t,i,n)}catch{return{status:"failed"}}}async describe(e,t){try{return await(await this.provider()).describe?.(e,t)}catch{return}}provider(){if(!this.loading){const e=this.load();this.loading=e,e.catch(()=>{this.loading===e&&(this.loading=void 0)})}return this.loading}}const XP="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",Fv=[{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 KP(XP,l=>Gb.mayCover(l),async()=>new(await ae(async()=>{const{AdsbLolArchiveProvider:l}=await import("./AdsbLolArchiveProvider-RNAaE2P_.js");return{AdsbLolArchiveProvider:l}},[],import.meta.url)).AdsbLolArchiveProvider)}];class cs{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const n=cs.positionAt(e,i);if(!n)return;const s=_t.seenFrom(t,n.geo);if(!(s.altitudeDeg<0))return{track:e,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:cs.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(n=>cs.seenFrom(n,t,i)??[])}static groundDistanceKm(e,t){const i=Math.PI/180,n=Math.sin((t.lat-e.lat)*i/2)**2+Math.cos(e.lat*i)*Math.cos(t.lat*i)*Math.sin((t.lng-e.lng)*i/2)**2;return 2*cs.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(e){return((e+180)%360+360)%360-180}static positionAt(e,t){const i=e.points;if(i.length===0||t<i[0].t||t>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=t;)n++;const s=i[n],r=i[n+1]??s,a=r.t-s.t;if(a>cs.MAX_GAP_S*1e3)return;const o=a>0?(t-s.t)/a:0,c=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*o,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*o,lng:cs.wrapLongitude(s.lng+h*o),heightM:c*cs.FT_TO_M},altitudeFt:c,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(e,t,i){const n=cs.positionAt(e,i-500),s=cs.positionAt(e,i+500);if(!n||!s)return;const r=cs.unit(_t.seenFrom(t,n.geo)),a=cs.unit(_t.seenFrom(t,s.geo)),o=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(o)*180/Math.PI}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180;return[Math.cos(t)*Math.sin(i),Math.cos(t)*Math.cos(i),Math.sin(t)]}}const BM="https://ufoathome.org/fireballs/index.json";class or{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??or.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/fireballs/index.json",location.href).href),e.includes(BM)||e.push(BM),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=or.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!or.mayCover(t))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(e).toISOString().slice(0,7),new Date(t).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>=e&&r.t<=t):void 0}static seenFrom(e,t){const i=or.peakFraction(e),n={lat:e.from[0]+(e.to[0]-e.from[0])*i,lng:e.from[1]+(e.to[1]-e.from[1])*i,heightM:e.peakHeightKm*1e3},s=_t.seenFrom(t,n);if(!(s.altitudeDeg<0))return{record:e,peak:s,magnitude:e.peakMagnitude+5*Math.log10(s.distanceKm/_t.STANDARD_DISTANCE_KM)}}static asReentry(e,t){const i=e.t-t,n=i+Math.max(e.durationS,.1)*1e3;return{id:`gmn-${e.id}`,track:[{t:i,lat:e.from[0],lng:e.from[1],altitudeKm:e.from[2]},{t:n,lat:e.to[0],lng:e.to[1],altitudeKm:e.to[2]}],fragments:[{absoluteMagnitude:e.peakMagnitude,color:or.COLOR,trainS:or.TRAIN_S}]}}static peakFraction(e){const t=e.from[2]-e.to[2];return Math.abs(t)<1e-6?.5:Math.min(1,Math.max(0,(e.from[2]-e.peakHeightKm)/t))}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(t.ok)return{index:await t.json(),base:e}}catch{}})(),this.index}monthOf(e,t){let i=this.months.get(e);return i||(i=this.fetchImpl(new URL(`${e}.json`,t).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(e,i)),i}}cm();const YP={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},qP="{name} — mag {mag}, {alt}° above the horizon",jP="{name} — {size}, {distance} away",ZP="{name} — satellite, mag {mag}, {height} km up",HM={ghost:"Ghost: {name}",halo:"Halo: {name}",double:"Double: {name}",unnamed:"a light",detail:"{name}. {cause}, {where}.",causes:{lens:"A reflection between two surfaces of the lens",sensor:"The sensor's reflection, sent back by its cover glass",filter:"The sensor's reflection, sent back by the filter",glass:"A reflection between the two faces of the glass in front of the lens",drops:"Light scattered by drops on the glass",condensation:"Light scattered by condensation on the glass",dirt:"Light scattered by dirt on the glass"},opposite:"across the centre of the picture from the light",sameSide:"on the same side of the centre as the light",around:"round the light",drop:{lens:"Drop on the lens",filter:"Drop on the filter",window:"Drop on the window",windscreen:"Drop on the windscreen"},dropDetail:"{name}. Like a small lens, it shows upside down and blurred what is on the other side of it, rather than what is behind it."},JP={name:"Rocket plume",detail:"{name} — {part}, {distance} away, {height} km up",ascent:"exhaust of the ascent",burn:"exhaust of an engine burn",vent:"vented propellant"},XS="satellites-change",YS="fireballs-change",qS="references-change",QP="aircraft-change",e6="rr0-confrontation",t6="{name} — mag {mag}, {alt}° below the horizontal",X0="Credits",GM="comet:",VM="nova:",Y0={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",trafficlight:"Traffic light",crossing:"Pedestrian crossing",roadsign:"Road sign",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},i6=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,n6=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,s6=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,r6=-18,a6={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},op={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Tt extends HTMLElement{creditsButton;set ownCredits(e){this.creditsButton.hidden=!e}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",jc,Zc,vl]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new _;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new Xn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new or;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static NO_BEAMS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=Fv[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return Tt.trafficRuntimeLoading??=ae(()=>import("./trafficRuntime-ZmzuyzhR.js"),__vite__mapDeps([8,3]),import.meta.url).then(e=>Tt.trafficRuntime=e),Tt.trafficRuntimeLoading.catch(()=>{Tt.trafficRuntimeLoading=void 0}),Tt.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new HP;vehicleAudio=new cI;aircraftAudio;vehicleHearing=new pf;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{if(this.lastHover={clientX:e.clientX,clientY:e.clientY,altKey:e.altKey},this.hoverFrame!==void 0&&e.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=e.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}))};hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;hoverAt(e){if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(e.clientX-i.left)/i.width*t.width,s=(e.clientY-i.top)/i.height*t.height;if(this.ufoElement.hasVisibleShapeAt(n,s)){this.hoverTooltip.hidden=!0;return}const r=(e.clientX-i.left)/i.width*2-1,a=-((e.clientY-i.top)/i.height*2-1),o=this.pickAt(r,a,!0,e.altKey);o?this.showHoverTooltip(e,e.altKey&&o.detail?o.detail():o.name):this.hoverTooltip.hidden=!0,this.showGhostPath(o?.path,i)}showGhostPath(e,t){if(!e){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),n=u=>({x:t.left-i.left+(u.x+1)/2*t.width,y:t.top-i.top+(1-u.y)/2*t.height}),s=n(e.from),r=n(e.to),a=n({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[o,c,h,d]=Array.from(this.ghostPath.children);for(const u of[o,c])u.setAttribute("x1",String(s.x)),u.setAttribute("y1",String(s.y)),u.setAttribute("x2",String(r.x)),u.setAttribute("y2",String(r.y));h.setAttribute("cx",String(a.x)),h.setAttribute("cy",String(a.y)),d.setAttribute("cx",String(r.x)),d.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(e,t,i=!0,n=!1){const s=this.naming,r=s.names;if(n&&this.sceneRenderer.pickDropAt(e,t)){const E=r?.ghostTooltip??HM,x=E.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:x,detail:()=>E.dropDetail.replace("{name}",x)}}const a=this.sceneRenderer.pickBodyAt(e,t);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const o=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(e,t):void 0,c=o?this.interpretationShown?.bodies.find(E=>E.id===o):void 0,h=c?this.said.read(c.title)||(c.model.id==="figure"?s.decorKind("entity",Y0.entity):void 0):void 0;if(o!==void 0&&h)return{kind:"body",id:o,name:h};const d=this.ufoElement.sighting.skyEvents?.beams,u=d?.length?this.sceneRenderer.pickBeamAt(e,t):void 0,p=u?d?.find(E=>E.id===u.id):void 0;if(u&&p){const E=this.said.read(p.title)||"Laser";return{kind:"beam",id:p.id,name:E,detail:()=>`${E} (${p.wavelengthNm} nm, ${p.powerW.toLocaleString()} W), ${this.distanceText(u.distanceM)}`}}const f=i?this.ghostPick(e,t):void 0;if(f)return f;const m=this.pickDecorAt(e,t),v=m?this.ufoElement.sighting.decor.find(E=>E.id===m):void 0;if(v){const E=this.said.read(v.title)||s.decorKind(v.kind,Y0[v.kind]);return{kind:"decor",id:v.id,name:E,detail:()=>this.decorTooltip(v,E)}}const g=this.sceneRenderer.pickRailwayAt(e,t);if(g){const E=r?.railwayTooltip??Ar.ENGLISH;return{kind:"railway",id:g.line.id,name:Ar.name(g.line,E),detail:()=>Ar.detail(g,E,x=>this.distanceText(x))}}const y=this.trafficTooltipAt(e,t);if(y)return{kind:"traffic",name:y};const w=this.plumePickAt(e,t);if(w)return w;const b=this.sceneRenderer.pickSatelliteAt(e,t);if(b)return{kind:"satellite",name:(r?.satelliteTooltip??ZP).replace("{name}",b.name).replace("{mag}",b.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(b.heightKm).toLocaleString())};const M=this.sceneRenderer.pickOpticsAt(e,t);if(M){const E=(r?.opticsTooltips??DP)[M.id].replace("{angle}",String(Math.round(M.angleDeg??0)));return{kind:"optics",id:M.id,name:E.split(" — ")[0],detail:()=>E}}const S=this.sceneRenderer.pickStarAt(e,t);if(S){const E=S.star.mag,x=S.altitudeDeg,T=x<0?r?.starTooltipBelow??t6:r?.starTooltip??qP,D=s.star(S.star);return{kind:"star",name:D,detail:()=>T.replace("{name}",D).replace("{mag}",E.toLocaleString(void 0,{maximumFractionDigits:Math.abs(E)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(x))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(e,t){const i=this.ufoElement.canvasElement,n={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},s=`${Math.round(e/n.x)}:${Math.round(t/n.y)}`,r=performance.now(),a=this.ghostLights.get(s);if(a&&r-a.atMs<Tt.GHOST_LIGHT_KEPT_MS)return a.light;let o=this.shiningDecorNear(e,t,2*Math.max(n.x,n.y)),c;if(!o)for(const[h,d]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const u=this.pickAt(e+h*n.x,t+d*n.y,!1);if(u?.kind==="star")c??=u;else if(u){o=u;break}}return o??=this.shiningDecorNear(e,t,6*Math.max(n.x,n.y)),o??=c,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(s,{light:o??null,atMs:r}),o??null}ghostPick(e,t){const i=this.sceneRenderer.pickGhostAt(e,t);if(!i)return;const n=this.naming.names?.ghostTooltip??HM,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,c=(bi.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:c,detail:()=>n.detail.replace("{name}",c).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(e,t,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 o=Math.hypot(Math.max(a.minX-e,0,e-a.maxX),Math.max(a.minY-t,0,t-a.maxY));if(o>i||n&&o>=n.distance)continue;const c=this.said.read(s.title)||this.naming.decorKind(s.kind,Y0[s.kind]);n={distance:o,pick:{kind:"decor",id:s.id,name:c}}}return n?.pick}glassWettingOf(e){const t=JSON.stringify([e.lens,e.instrumentId,e.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==e||this.glassWetting.key!==t){const i=new ml(n=>{if(!bi.records(e.instrument)||!bi.falling(e.lens))return 0;const s=_h(e,n*1e3),r=pt(e,n*1e3);return(s.precipitationAmount??1)*bi.impactRate(s,e.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:s.windDirectionDeg,windSpeedMS:s.windSpeed})});this.glassWetting={sighting:e,key:t,wetting:i}}return this.glassWetting.wetting}glassWetting;plumePickAt(e,t){const i=this.ufoElement.sighting.skyEvents?.launches,n=i?.length?this.sceneRenderer.pickPlumeAt(e,t):void 0,s=n?i?.find(c=>c.id===n.launchId):void 0;if(!n||!s)return;const r=this.naming.names?.plumeTooltip??JP,a=this.said.read(s.title)||s.vehicle?.mission||r.name,o=()=>n.release===void 0||n.release==="burn"?r.ascent:s.jets?.find((h,d)=>`jet:${h.id??d}`===n.release)?.kind==="vent"?r.vent:r.burn;return{kind:"plume",id:s.id,name:a,detail:()=>r.detail.replace("{name}",a).replace("{part}",o()).replace("{distance}",this.distanceText(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}distanceText(e){return e>=1e3?`${(e/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${e.toLocaleString(void 0,{maximumFractionDigits:e<10?1:0})} m`}decorTooltip(e,t){const i=c=>c.toLocaleString(void 0,{maximumFractionDigits:c<10?1:0}),n=me.sizeOf(e),s=this.sceneRenderer.decorDistanceM(e.id),r=s===void 0?"":this.distanceText(s);return(this.naming.names?.decorTooltip??jP).replace("{name}",t).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(e){const t=e.startsWith(GM)?e.slice(GM.length):void 0,i=t?KS.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const n=e.startsWith(VM)?Gf.byId(e.slice(VM.length)):void 0;if(n)return this.naming.nova(n);const s=YP[e];return s===void 0?e:this.naming.body(e,s)}get naming(){return this.sceneNaming}sceneNaming=new Hf;namesLanguage="en";async loadSceneNames(){const e=Id(Zs.preferencesFor(this),Td);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await hx(e);e===this.namesLanguage&&this.applySceneNaming(new Hf(t))}setBusy(e,t=""){this.busyElement.hidden=!e,this.busyNote.textContent=e?t:"",this.busyElement.setAttribute("aria-label",t),this.busyElement.setAttribute("aria-busy",String(e))}renderLoaderText(e,t){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,o)=>{o>0&&s.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of a){const d=document.createElement("span");d.className="scene-loader-letter",d.style.setProperty("--i",String(i++)),d.textContent=h,c.append(d)}s.append(c),i++})};n(this.loaderNotVideo,e),i+=6,n(this.loaderNote,t)}applySceneNaming(e){this.sceneNaming=e;const t=e.names?.credits??X0;this.creditsButton.title=t,this.creditsButton.setAttribute("aria-label",t),e.names&&this.renderLoaderText(e.names.notAVideo,e.names.isASimulation),this.sceneRenderer.setCompassPoints(e.names?.compassPoints)}showHoverTooltip(e,t){this.hoverTooltip.textContent=t,this.hoverTooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect(),n=e.clientX-i.left+12,s=n+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${s>0?Math.max(0,n-s-4):n}px`,this.hoverTooltip.style.top=`${e.clientY-i.top+12}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash(e){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),xn.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(_h(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const e=this.ufoElement.level;this.weatherAudio.setLevel(e),this.vehicleAudio.setLevel(e),this.aircraftAudio?.setLevel(e)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=e=>{if(this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const t=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&t-this.lastPlayingHoverMs>=Tt.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=t,this.hoverAt(this.lastHover))}this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(e,e),this.weatherAudio.setPaused(!e),this.vehicleAudio.setPaused(!e),this.aircraftAudio?.setPaused(!e),e&&this.unlockIfAlreadyActivated(),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${uI}</style>${dI}`,this.shadow.appendChild(e.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 Ee(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(qS));const t=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.renderLoaderText("This is not a video","It is a real-time simulation."),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=t,this.poster=new Hb(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.ufoElement=document.createElement(Dg),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapFrozenSource=s=>this.frozenMapOf(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"&&Kn.fill(n,this)}),this.creditsButton.title=X0,this.creditsButton.setAttribute("aria-label",X0),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("playrequest",()=>this.poster.release()),this.ufoElement.addEventListener(O2,()=>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.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 Tt.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new vs(Zs.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(e,t){const i=e.vehicle;return i?{setting:_o.at(i.headlights??"auto",i.headlightKeyframes,t)??"auto",headingDeg:this.travelHeadingAt(e,t)}:void 0}travelHeadingAt(e,t){const i=pt(e,t);if(!i)return 0;for(const n of[400,-400]){const s=pt(e,t+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=st(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(e){const t=e.allKeyframes;if(this.routeCache?.track===e&&this.routeCache.count===t.length)return this.routeCache.route;const i=t.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:e,count:t.length,route:n},n}traceLabels(e){const t=Zs.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==e||this.traceLabelsFor.language!==t){const i=new Map;for(const n of e){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:e,language:t,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){this.saidTexts=void 0,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 t of Tt.GESTURES)document.addEventListener(t,this.handlePageGesture,!0);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(e=>{if(e[e.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of Tt.GESTURES)document.removeEventListener(e,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(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),(e==="star-catalog-src"||e==="deep-star-catalog-src")&&i!==t&&this.isConnected&&this.loadStars(),e==="show-compass"&&i!==t&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),e==="max-pixel-ratio"&&i!==t){const n=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(n)&&n>0?n:Math.min(window.devicePixelRatio||1,2))}(e===jc||e===Zc||e===vl)&&i!==t&&this.forwardPlayerAttributes(),e===vl&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const e of[jc,Zc,vl]){const t=this.getAttribute(e);t===null?this.ufoElement.removeAttribute(e):this.ufoElement.setAttribute(e,t)}}setCompassForced(e){this.sceneRenderer.setCompassForced(e)}lookToward(e){const t=pt(this.ufoElement.sighting,this.lastTimeMs);if(e.kind==="observer"||t?.lat===void 0||t.lng===void 0||t.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:i,z:n}=st(e.lat,e.lng,t.lat,t.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-t.headingDeg)%360+540)%360-180,-t.pitchDeg)}setLookOffset(e,t){this.sceneRenderer.setLookOffset(e,t),this.ufoElement.setLookOffset(e,t),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setCloudRendering(e){this.sceneRenderer.setCloudRendering(e)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity*(e.precipitationAmount??1),e.windSpeed)}pickCloudAt(e,t){return this.sceneRenderer.pickCloudAt(e,t)}cloudDirectionAt(e,t){return this.sceneRenderer.cloudDirectionAt(e,t)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}decorScreenBox(e){return this.sceneRenderer.decorScreenBox(e)}decorDrawnOffset(e){return this.sceneRenderer.decorDrawnOffset(e)}decorGroundPointAt(e,t,i,n=0){return this.sceneRenderer.decorGroundPointAt(e,t,i,n)}decorMetresPerNdcY(e){return this.sceneRenderer.decorMetresPerNdcY(e)}decorGrabHeightAt(e,t,i){return this.sceneRenderer.decorGrabHeightAt(e,t,i)}bodyScreenBox(e){return this.sceneRenderer.bodyScreenBox(e)}pickPlacedBodyAt(e,t){return this.sceneRenderer.pickPlacedBodyAt(e,t)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(e){const t=kr.recording(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(e,t,i=!0){this.poster.show(e,t,i)}applyHold(){const e=this.holding,t=this.poster.up;this.loader.hidden=!e||t,e&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=e||t,this.ufoElement.controlsHeld=e||t,this.ufoElement.holdClock(e)}holdForNewScene(e){this.sceneRenderer.holdForNewScene(e)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(e){this.sceneRenderer.documentUrl=e}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.ufoElement.sightingData=e,this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?It.expand(os.expand(this.ufoElement.sighting.interpretation)):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(e){const t=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(e.width/t);return e.height!==i&&(e.height=i),this.seekPreview??=new Ff(this,()=>document.createElement(Vf))}showAt(e){this.ufoElement.currentTime=e,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(e){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const t=e.getContext("2d");return t?(t.imageSmoothingQuality="high",t.drawImage(this.sceneCanvas,0,0,e.width,e.height),!0):!1}referenceAspect(e){return this.sceneRenderer.referenceAspect(e)}screenPointOf(e){return this.sceneRenderer.screenPointOf(e)}directionAt(e,t){return this.sceneRenderer.directionAt(e,t)}referenceFailure(e){return this.sceneRenderer.referenceFailure(e)}applyReferenceView(e){this.sceneRenderer.setReferencesShown(e.shown);for(const t of this.ufoElement.sighting.references){const i=e.views?.[t.id];this.sceneRenderer.setReferenceView(t.id,{opacity:i?i.shown?i.opacity:0:e.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(e){this.liveTerrainProviders=e,this.frozenKey=void 0,this.applyFrozen(this.ufoElement.sighting.frozen)}liveTerrainProviders;frozenKey="none";applyFrozen(e){const t=Bi.isEmpty(e)?"none":`${JSON.stringify(e)}
11221
+ `);let s=Yr.cache.get(n);return s||(s=Promise.all(i.map(r=>Yr.load(r.url))).then(r=>r.reduce((a,o)=>Yr.concat(a,o))),Yr.cache.set(n,s)),s}static parse(e){const t=e.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=t*Float32Array.BYTES_PER_ELEMENT;return{count:t,ra:new Float32Array(e,0*i,t),dec:new Float32Array(e,1*i,t),mag:new Float32Array(e,2*i,t),ci:new Float32Array(e,3*i,t)}}static concat(e,t){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:e.count+t.count,ra:i(e.ra,t.ra),dec:i(e.dec,t.dec),mag:i(e.mag,t.mag),ci:i(e.ci,t.ci)}}}class ii{constructor(e){if(this.heights=e,e.length!==ii.WIDTH*ii.HEIGHT)throw new Error(`a lunar relief has ${ii.WIDTH*ii.HEIGHT} samples, not ${e.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*ii.SAMPLES_PER_DEGREE;static HEIGHT=180*ii.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(e,t){const i=ii.SAMPLES_PER_DEGREE,n=(t%360+360)%360*i-.5,s=(90-e)*i-.5,r=Math.floor(n),a=Math.floor(s),o=n-r,c=s-a,h=(p,f)=>{const m=(p%ii.WIDTH+ii.WIDTH)%ii.WIDTH,v=Math.min(ii.HEIGHT-1,Math.max(0,f));return this.heights[v*ii.WIDTH+m]},d=h(r,a)*(1-o)+h(r+1,a)*o,u=h(r,a+1)*(1-o)+h(r+1,a+1)*o;return(d*(1-c)+u*c)*ii.UNIT_KM}static inBand(e,t){const i=Math.PI/180,n=Math.acos(Math.cos(e*i)*Math.cos(t*i))*180/Math.PI;return n>=ii.BAND_FROM_DEG&&n<=ii.BAND_TO_DEG}static withBump(e,t,i,n=.4){const s=new Int8Array(ii.WIDTH*ii.HEIGHT),r=ii.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),o=Math.floor(t*r),c=Math.floor((90-e)*r);for(let h=-a;h<=a;h++)for(let d=-a;d<=a;d++)Math.hypot(d,h)<=a&&(s[(c+h)*ii.WIDTH+(o+d+ii.WIDTH)%ii.WIDTH]=Math.round(i/ii.UNIT_KM));return new ii(s)}static smooth(){return new ii(new Int8Array(ii.WIDTH*ii.HEIGHT))}}class rr{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(e,t,i,n=rr.SAMPLES){const{s,u:r,w:a,distanceKm:o}=rr.frame(e,t),c=Math.PI/180,h=new Float32Array(n),d=ii.REFERENCE_RADIUS_KM;for(let u=0;u<n;u++){const p=u/n*2*Math.PI,f=Math.cos(p),m=Math.sin(p),v=f*r[0]+m*a[0],g=f*r[1]+m*a[1],y=f*r[2]+m*a[2];let w=0;for(let b=rr.SEARCH_FROM_DEG;b<=rr.SEARCH_TO_DEG;b+=rr.SEARCH_STEP_DEG){const M=Math.cos(b*c),S=Math.sin(b*c),E=M*s[0]+S*v,x=M*s[1]+S*g,T=M*s[2]+S*y,D=Math.asin(Math.max(-1,Math.min(1,T)))/c,R=Math.atan2(x,E)/c,O=d+i.heightKm(D,R),N=Math.atan2(O*S,o-O*M);N>w&&(w=N)}h[u]=w/c}return{radiusDeg:h,meanRadiusDeg:Math.asin(d/o)/c}}static frame(e,t){const i=new Fa(t.lat,t.lng,t.elevationM),n=Ua(e),s=fg(e,i,!1),r=new Ut(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*rr.AU_KM,o=rr.bodyFixed(e),c=o(r),h=Math.hypot(c[0],c[1],c[2]),d=[c[0]/h,c[1]/h,c[2]/h],u=j3(e,i),p=eb(u),f=Pa(u,new Ut(-r.x,-r.y,-r.z,n.t)),m=Math.asin(f.z/Math.hypot(f.x,f.y,f.z)),v=Math.atan2(-f.y,f.x),g=new Ut(-Math.sin(m)*Math.cos(v),Math.sin(m)*Math.sin(v),Math.cos(m),n.t),y=new Ut(-Math.sin(v),-Math.cos(v),0,n.t);return{s:d,u:o(Pa(p,g)),w:o(Pa(p,y)),distanceKm:a}}static surfacePoint(e,t,i,n){const{s,u:r,w:a}=rr.frame(e,t),o=Math.PI/180,c=[0,1,2].map(d=>Math.cos(i*o)*r[d]+Math.sin(i*o)*a[d]),h=[0,1,2].map(d=>Math.cos(n*o)*s[d]+Math.sin(n*o)*c[d]);return{latDeg:Math.asin(h[2])/o,lonDeg:Math.atan2(h[1],h[0])/o}}static radiusAt(e,t){const i=e.radiusDeg.length,n=(t/360*i%i+i)%i,s=Math.floor(n),r=n-s;return e.radiusDeg[s]*(1-r)+e.radiusDeg[(s+1)%i]*r}static uncoveredFraction(e,t,i){const n=e.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const o=a/n*2*Math.PI,c=Math.cos(o),h=Math.sin(o),d=c*i.upDeg+h*i.rightDeg,u=d*d-s+t*t;if(u<=0)continue;const p=Math.sqrt(u),f=d+p;if(f<=0)continue;const m=Math.max(0,d-p),v=Math.max(m,e.radiusDeg[a]);f>v&&(r+=.5*(f*f-v*v))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*t*t)))}static AU_KM=1495978707e-1;static bodyFixed(e){const t=uT(pe.Moon,e),i=Math.PI/180,n=t.ra*15*i,s=t.dec*i,r=t.spin*i,a=(c,[h,d,u])=>[Math.cos(c)*h+Math.sin(c)*d,-Math.sin(c)*h+Math.cos(c)*d,u],o=(c,[h,d,u])=>[h,Math.cos(c)*d+Math.sin(c)*u,-Math.sin(c)*d+Math.cos(c)*u];return c=>a(r,o(Math.PI/2-s,a(Math.PI/2+n,[c.x,c.y,c.z])))}static subObserverPoint(e,t){const i=new Fa(t.lat,t.lng,t.elevationM),n=Ua(e),s=fg(e,i,!1),r=rr.bodyFixed(e)(new Ut(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 xd{static cache=new Map;static load(e){let t=xd.cache.get(e);return t||(t=xd.fetchRelief(e).catch(()=>{}),xd.cache.set(e,t)),t}static async fetchRelief(e){const t=await fetch(e);if(!t.ok)return;let i=new Uint8Array(await t.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 ii(new Int8Array(i.buffer,i.byteOffset,i.length))}}class Bf{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=Bf.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(e){const t=Bf.MATRICES[String(e.type)];if(!t)return Us.NONE;const i=Number(e.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:t.map((r,a)=>Us.IDENTITY[a]+(r-Us.IDENTITY[a])*n),contrastGain:1}}}class Bb{static ID="fatigue";id=Bb.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(e){return Us.NONE}}class Jo{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=Jo.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary), drawn up to 0.1 % at most: a higher level is recorded but shown as 0.1 %, since nothing was measured past it. Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:Jo.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(e){const t=Number(e.bloodAlcohol??0),i=Math.max(0,Math.min(Jo.MAX_EFFECT_LEVEL,Number.isFinite(t)?t:0));if(i===0)return Us.NONE;const n=i/Jo.MEASURED_LEVEL*Jo.MEASURED_LOSS_DB;return{colorMatrix:Us.IDENTITY,contrastGain:10**(-n/20)}}}class Ol{static ALL=[new Bf,new Jo,new Bb];static byId(e){return Ol.ALL.find(t=>t.id===e)}static perceptionOf(e){return Ol.ALL.reduce((t,i)=>Us.combine(t,i.perceive(e?.[i.id]??{})),Us.NONE)}static compact(e){const t={};for(const i of Ol.ALL){const n=e[i.id]??{},s=Object.fromEntries(i.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(s).length>0&&(t[i.id]=s)}return Object.keys(t).length>0?t:void 0}}class Hf{constructor(e){this.names=e}body(e,t){return this.names?.bodies[e]??t}star(e){return this.names?.stars[e.name]??e.name}comet(e){return this.names?.comets[e.id]??e.name}nova(e){return this.names?.novae[e.id]??e.name}satelliteClass(e){return this.names?.satelliteClasses[e.id]??e.name}shower(e){return this.names?.showers[e.id]??e.name}lightRig(e){return this.names?.lightRigs[e.id]??e.name}instrument(e){return this.names?.instruments[e.id]??e.name}decorKind(e,t){return this.names?.decorKinds[e]??t}point(e){return kl.point(e,this.names?.compassPoints)}towards(e){return kl.towards(e,this.names)}}class Ar{static ENGLISH={kinds:{rail:"Railway",light_rail:"Light rail",tram:"Tramway",subway:"Metro",funicular:"Funicular"},highSpeed:"High-speed line",service:"Siding",singleTrack:"single track",tracks:"{count} tracks",overhead:"overhead wire {height} m above the rail",overheadVoltage:"overhead wire at {voltage}, {height} m above the rail",thirdRail:"third rail",thirdRailVoltage:"third rail at {voltage}",notElectrified:"not electrified",gauge:"{mm} mm gauge",metreGauge:"metre gauge",distance:"{distance} away"};static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(e,t){return e.highSpeed?t.highSpeed:e.service?t.service:t.kinds[e.kind]}static name(e,t){const i=e.name??Ar.kind(e,t);return e.services?.length?`${i} — ${e.services.join(", ")}`:i}static voltage(e,t){return e>=1e3?`${(e/1e3).toLocaleString(t,{maximumFractionDigits:1})} kV`:`${e.toLocaleString(t)} V`}static detail(e,t,i,n){const{line:s}=e,r=[];s.name&&r.push(Ar.kind(s,t).toLocaleLowerCase(n)),r.push(s.tracks>1?t.tracks.replace("{count}",String(s.tracks)):t.singleTrack);const a=s.voltageV?Ar.voltage(s.voltageV,n):void 0;if(e.contactM!==void 0){const o=e.contactM.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?t.overheadVoltage.replace("{voltage}",a):t.overhead).replace("{height}",o))}else s.electrification==="third_rail"?r.push(a?t.thirdRailVoltage.replace("{voltage}",a):t.thirdRail):s.electrification==="none"&&r.push(t.notElectrified);return s.gaugeMm===Ar.METRE_GAUGE_MM?r.push(t.metreGauge):s.gaugeMm!==Ar.STANDARD_GAUGE_MM&&r.push(t.gauge.replace("{mm}",s.gaugeMm.toLocaleString(n))),r.push(t.distance.replace("{distance}",i(e.distanceM))),s.services?.length?`${Ar.name(s,t)}; ${r.join(", ")}`:`${Ar.name(s,t)} — ${r.join(", ")}`}}class Hb{constructor(e,t){this.element=e,this.onChange=t,e.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(e,t,i=!0){const n=Hb.resolve(e,t);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(e,t){if(!(typeof e!="string"||e.trim()===""))try{const i=new URL(e.trim(),t??location.href);return i.protocol==="https:"||i.protocol==="http:"?i.href:void 0}catch{return}}}const DP={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},kP="Global Meteor Network",CP="https://globalmeteornetwork.org/data/",LP="“Thunder” by Jerimee",OP="https://creativecommons.org/licenses/by/3.0/",PP="CC BY 3.0";class Kn{static fill(e,t){e.innerHTML="";const i=u=>e.appendChild(u),n=t.currentTerrainAttribution;n&&i(Kn.text(n));const s=t.currentRoadAttribution;s&&i(Kn.text(s));const r=t.currentWaterAttribution;r&&i(Kn.text(r));const a=t.currentRailwayAttribution;a&&i(Kn.text(a));const o=t.ufoElement.observerMapCredit;o&&!n?.includes(o)&&i(Kn.text(o));for(const u of t.decorModelCredits){const p=u.author?` — ${u.author}`:"",f=document.createElement("li");u.sourceUrl?f.append(Kn.link(u.sourceUrl,u.title),document.createTextNode(`${p} (${u.license})`)):f.textContent=`${u.title}${p} (${u.license})`,i(f)}for(const u of t.ufoElement.sighting.references){if(!u.credit)continue;const p=document.createElement("li");u.creditUrl?p.appendChild(Kn.link(u.creditUrl,u.credit)):p.textContent=u.credit,i(p)}if(t.ufoElement.sighting.traces.length>0){const u=new vs(Zs.preferencesFor(t)),p=new Set(t.ufoElement.sighting.traces.map(f=>u.read(f.source)).filter(f=>!!f));for(const f of p)i(Kn.text(f))}const c=t.satelliteState;if(c.status==="ready"&&c.credit){const u=document.createElement("li");u.appendChild(Kn.link(c.creditUrl??"",c.credit)),i(u)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const u=document.createElement("li");u.append(Kn.link(CP,kP),document.createTextNode(" (CC BY 4.0)")),i(u)}const h=t.aircraftState;if(h.status==="ready"&&h.shown>0){const u=document.createElement("li");if(u.appendChild(Kn.link(h.creditUrl,h.credit)),i(u),h.trailCredit){const p=document.createElement("li");p.appendChild(Kn.link(h.trailCredit.creditUrl,h.trailCredit.credit)),i(p)}}const d=Kn.text(`${LP} (`);d.append(Kn.link(OP,PP),document.createTextNode(")")),i(d)}static text(e){const t=document.createElement("li");return t.textContent=e,t}static link(e,t){const i=document.createElement("a");return i.href=e,i.target="_blank",i.rel="noopener",i.textContent=t,i}}const NP=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,FP=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,UP=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,zP=20,BP=1;class HP{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(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",e);return}}Il.unlock(this.context)}setAmbient(e,t,i){if(this.requested={type:e,intensity:t,windSpeed:i},!this.context)return;this.paused&&(e="none",t=0,i=0);const n=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=n==="hail"?Math.min(1,t*1.3+.2):n==="rain"?t: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(NP,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,o=>{this.ambientSource=o?.source,this.ambientGain=o?.gain,o&&(o.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/zP,1);const s=i>BP;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(FP,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,o=>{this.windSource=o?.source,this.windGain=o?.gain,o&&(o.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:i,windSpeed:n}=this.requested;this.setAmbient(t,i,n)}playThunder(){!this.context||this.paused||this.playOneShot(UP,.9)}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(e,t,i,n){if(t!==i()){e?.source.stop();return}n(e)}async startLoop(e,t){const i=this.context;if(i)try{const n=await this.getBuffer(e),s=i.createBufferSource();s.buffer=n,s.loop=!0;const r=i.createGain();return r.gain.value=t,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(e,t){const i=this.context;if(i)try{const n=await this.getBuffer(e),s=i.createBufferSource();s.buffer=n;const r=i.createGain();r.gain.value=t,s.connect(r).connect(this.output(i)),s.start()}catch(n){console.warn("Thunder sound failed to load:",n)}}async getBuffer(e){const t=this.context;if(!t)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${e}`);return n.arrayBuffer()}).then(n=>t.decodeAudioData(n)),this.buffers.set(e,i)),i}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}class Ta{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[n,s]=this.perifocalAxes(),r=Math.sqrt(Ta.SUN_GM_AU3_PER_DAY2*(1+t)/i);this.perihelionPosition=this.scale(n,i),this.perihelionVelocity=this.scale(s,r),this.inverseSemiMajorAxis=(1-t)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(e){const t=e-this.elements.perihelionJd,i=this.universalAnomaly(t),n=this.inverseSemiMajorAxis*i*i,s=this.elements.perihelionAu,r=1-i*i/s*Ta.stumpffC(n),a=t-i*i*i/Math.sqrt(Ta.SUN_GM_AU3_PER_DAY2)*Ta.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(e){const t=this.positionAt(e);return Math.hypot(t.x,t.y,t.z)}universalAnomaly(e){if(e===0)return 0;const t=Math.sign(e),i=Math.sqrt(Ta.SUN_GM_AU3_PER_DAY2)*Math.abs(e),n=a=>{const o=this.inverseSemiMajorAxis*a*a,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*a*a*a*Ta.stumpffS(o)+c*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<Ta.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){const o=(r+s)/2;n(o)<i?r=o:s=o}return t*(r+s)/2}perifocalAxes(){const e=this.elements.ascendingNodeDeg*Math.PI/180,t=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,n=Math.cos(e),s=Math.sin(e),r=Math.cos(t),a=Math.sin(t),o=Math.cos(i),c=Math.sin(i);return[{x:n*r-s*a*o,y:s*r+n*a*o,z:a*c},{x:-n*a-s*r*o,y:-s*a+n*r*o,z:r*c}]}scale(e,t){return{x:e.x*t,y:e.y*t,z:e.z*t}}static stumpffC(e){if(Math.abs(e)<1e-6)return 1/2-e/24+e*e/720;if(e>0)return(1-Math.cos(Math.sqrt(e)))/e;const t=Math.sqrt(-e);return(Math.cosh(t)-1)/-e}static stumpffS(e){if(Math.abs(e)<1e-6)return 1/6-e/120+e*e/5040;if(e>0){const i=Math.sqrt(e);return(i-Math.sin(i))/(i*i*i)}const t=Math.sqrt(-e);return(Math.sinh(t)-t)/(t*t*t)}}const KS=[{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 Dp{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(e){const t=this.julianDayOf(e);return KS.filter(i=>Math.abs(t-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(e,t){return this.aroundDate(e).map(i=>this.appearanceOf(i,e,t)).sort((i,n)=>i.magnitude-n.magnitude)[0]}static appearanceOf(e,t,i){const n=di(t),s=this.earthPositionAt(n),r=this.apparentPositionOf(e,2451545+n.tt,s),a=this.subtract(r,s),o=this.length(r),c=this.length(a),h=this.tailEndAt(e,r,s,o,n,t,i),d=this.horizontalOf(a,n,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:o,earthDistanceAu:c,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(e,o,c)}}static magnitudeAt(e,t,i){const n=e.absoluteMagnitude+5*Math.log10(i)+2.5*e.activityExponent*Math.log10(t);return Math.max(n,e.peakMagnitude)}static tailEndAt(e,t,i,n,s,r,a){if(e.tailLengthAu===void 0)return{};const o=1+e.tailLengthAu/n,c=this.subtract({x:t.x*o,y:t.y*o,z:t.z*o},i),h=this.subtract(t,i);return{tailEnd:this.horizontalOf(c,s,r,a),tailLengthDeg:this.angleBetween(h,c)}}static apparentPositionOf(e,t,i){const n=this.orbitOf(e);let s=n.positionAt(t);for(let r=0;r<2;r++){const a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(t-a)}return s}static horizontalOf(e,t,i,n){const s=Pa(K3(),new Ut(e.x,e.y,e.z,t)),r=Pa(Jx(t),s),a=fg(t,new Fa(n.lat,n.lng,n.elevationM),!0),o=new Ut(r.x-a.x,r.y-a.y,r.z-a.z,t),c=rm(o);return Ld(c.ra,c.dec,i,n)}static earthPositionAt(e){return Pa($3(),Eo(pe.Earth,e))}static julianDayOf(e){return 2451545+di(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new Ta(e.orbit);return this.orbits.set(e.id,i),i}static subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}static length(e){return Math.hypot(e.x,e.y,e.z)}static angleBetween(e,t){const i=(e.x*t.x+e.y*t.y+e.z*t.z)/(this.length(e)*this.length(t)||1);return Math.acos(Math.min(1,Math.max(-1,i)))*180/Math.PI}}const $0=[{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 Gf{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return $0.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),n=[];for(const s of $0){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Tr.ofJ2000(s.raHours,s.decDeg,e,t),magnitude:r})}return n.sort((s,r)=>s.magnitude-r.magnitude)}static brightestAt(e,t){return this.appearancesAt(e,t)[0]}static byId(e){return $0.find(t=>t.id===e)}static magnitudeAt(e,t){const i=e.lightCurve,n=t-e.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],[o,c]=i[s]??i[0];if(o===r)return a;const h=Math.min(1,Math.max(0,(n-r)/(o-r)));return a+h*(c-a)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const GP=[{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}],wh=6.5;class sh{static activeAt(e){return GP.flatMap(t=>{const i=this.nearness(t,e);return i<=0?[]:[{shower:t,zhr:t.peakZhr*i,nearness:i}]})}static nearness(e,t){const i=this.dayOfYear(t),n=this.dayOfYear(this.asDate(e.start)),s=this.dayOfYear(this.asDate(e.peak)),r=this.dayOfYear(this.asDate(e.end)),a=this.wrappedDelta(i,s),o=this.wrappedDelta(s,n),c=this.wrappedDelta(r,s);return a<0?a<-o?0:1+a/o:a>0?a>c?0:1-a/c:1}static observedRatePerHour(e,t,i,n=wh){if(t<=0)return 0;const s=wh-n;return e*Math.sin(t*Math.PI/180)/Math.pow(i,s)}static radiantPosition(e,t,i){return Tr.ofJ2000(e.radiantRaHours,e.radiantDecDeg,t,i)}static dayOfYear(e){const t=Date.UTC(e.getUTCFullYear(),0,1);return Math.floor((Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())-t)/864e5)+1}static asDate(e){return new Date(Date.UTC(2001,e.month-1,e.day))}static wrappedDelta(e,t){const i=e-t;return i>182?i-365:i<-182?i+365:i}}class Ui{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=di(e),n=new tm(0,E3(e).elon-90,1),s=Pa(Z3(i),ib(n,i)),r=rm(s);return Ld(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=wh){const i=Ui.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),n=wh-t;return(Ui.QUIET_RATE_PER_HOUR+i)/Math.pow(Ui.POPULATION_INDEX,n)}static schedule(e){const t=new bm(e.seed^1542469173);return Ir.schedule(e).map(i=>{const n=Ui.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=Ui.turnAround(n,t.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:Ui.toHorizontal(a),bearingDeg:Ui.bearingFrom(a,n)}})}static turnAround(e,t){const[i,n]=Ui.basisAround(e),s=t*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(e,t){const[i,n]=Ui.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,r=Ui.normalise({x:t.x-e.x*s,y:t.y-e.y*s,z:t.z-e.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(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=Ui.normalise(Ui.cross(e,t));return[i,Ui.normalise(Ui.cross(e,i))]}static toHorizontal(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,e.y/t)))*180/Math.PI,azimuthDeg:(Math.atan2(e.x,-e.z)*180/Math.PI%360+360)%360}}static appearanceOf(e){const t=Ui.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Ui.turnAround(t,e.bearingDeg),n=e.fromRadiantDeg*Math.PI/180;return Ui.toHorizontal({x:t.x*Math.cos(n)+i.x*Math.sin(n),y:t.y*Math.cos(n)+i.y*Math.sin(n),z:t.z*Math.cos(n)+i.z*Math.sin(n)})}static toCartesian(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180,n=Math.cos(t);return{x:n*Math.sin(i),y:Math.sin(t),z:-n*Math.cos(i)}}static cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}static normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}static TYPICAL_VELOCITY_KM_S=40}const UM="https://ufoathome.org/tle/index.json";class Xn{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Xn.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/tle/index.json",location.href).href),e.includes(UM)||e.push(UM),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${Xn.FIRST_SNAPSHOT}T00:00:00Z`)-Xn.MAX_ELEMENT_AGE_DAYS*Xn.DAY_MS;if(e.getTime()<t)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(n=>e.getTime()>=Date.parse(n.from)-Xn.MAX_ELEMENT_AGE_DAYS*Xn.DAY_MS&&e.getTime()<=Date.parse(n.to)+Xn.MAX_ELEMENT_AGE_DAYS*Xn.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:i,base:n}=t,s=[],r=[];for(const a of Object.keys(i.kinds)){const o=await this.kindAt(a,e,i,n);s.push(...o),r.push(this.coverageOf(a,e,i,o.length>0))}return{objects:s,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(e,t,i,n){const s=t.getTime(),r=i.binDays*Xn.DAY_MS,a=Math.floor(s/r),o=s-a*r<r/2?a-1:a+1,c=new Set(i.kinds[e].bins),h=[a,o].map(m=>new Date(m*r).toISOString().slice(0,10)).filter(m=>c.has(m));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,n).href),...h.map(m=>this.binary(new URL(`${e}/${m}.bin`,n).href))]),p=new Map;for(const m of u)for(const v of Xn.decode(m,i.recordBytes)){const g=p.get(v.norad);(!g||Math.abs(v.epochMs-s)<Math.abs(g.epochMs-s))&&p.set(v.norad,v)}const f=[];for(const m of p.values()){const v=Math.abs(m.epochMs-s)/Xn.DAY_MS;if(v>Xn.MAX_ELEMENT_AGE_DAYS)continue;const g=d[m.norad]??{name:String(m.norad)};g.launch&&Date.parse(`${g.launch}T00:00:00Z`)>s||f.push({norad:m.norad,name:g.name,kind:e,launch:g.launch,stdMag:g.stdMag,elements:m,ageDays:v})}return f}coverageOf(e,t,i,n){const{from:s,to:r}=i.kinds[e],a=t.getTime(),o=Xn.MAX_ELEMENT_AGE_DAYS*Xn.DAY_MS,c=n?"covered":a<Date.parse(s)-o?"before":a>Date.parse(r)+o?"after":"gap";return{kind:e,status:c,from:s,to:r}}static decode(e,t){const i=new DataView(e),n=[];for(let s=0;s+t<=e.byteLength;s+=t)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 e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;return{index:await t.json(),base:e}}catch{}})(),this.index}json(e){return this.cached(e,async t=>t.json())}binary(e){return this.cached(e,async t=>t.arrayBuffer())}cached(e,t){let i=this.files.get(e);return i||(i=this.fetchImpl(e).then(n=>{if(!n.ok)throw new Error(`${e}: ${n.status}`);return t(n)}),i.catch(()=>this.files.delete(e)),this.files.set(e,i)),i}}class VP{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const i=Tt.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(t.inFrontM!==void 0){const i=Tt.sizeMAt(t.inFrontM,e);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(e){return e<=0?{}:{minM:this.lowerM===void 0?void 0:Tt.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:Tt.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class Pl{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*Pl.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=Pl.degOver(e)/t;return i<1?1:Math.min(Pl.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Dn{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 Pl.DEG_PER_SECOND*3600}static graspOf(e,t={}){if(e.visualAid)return Dn.visualAidGrasp(e,t.focalLengthMm);const i=t.exposureSeconds??e.exposureSeconds,n=t.fNumber??e.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return Dn.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??Dn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=Dn.resolutionArcsec(e,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,Dn.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(e,t){const i=e.visualAid,n=Dn.EYE,s=t??e.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(e,t,i){const s=(e.detailUm??Dn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*Dn.ARCSEC_PER_RADIAN,r=1.22*Dn.WAVELENGTH_M/(i/1e3)*Dn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(e){return e/Dn.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=Dn.graspOf(e,t),n=Dn.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(e,t){const i=t.fieldOfViewDeg===void 0?void 0:hi.focalLengthMmFor(e,t.fieldOfViewDeg);return Dn.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const zM=111320,Zh=Math.PI/180,WP=1.02,$P=1;class Sd{static of(e,t){const i=Sd.sightings(e,t);if(i.length<2)return;const n=Sd.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,o=Math.tan(r.widthDeg/2*Zh)===0?0:Math.tan(s.widthDeg/2*Zh)/Math.tan(r.widthDeg/2*Zh);if(o<WP)return;const c=a/(o-1),h=Tt.sizeMAt(c,s.widthDeg),d=i.map(u=>({t:u.t,m:Tt.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===t)?.shape,s=n?.angular?.widthDeg,r=pt(e,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(e){let t;for(const i of e)for(const n of e){if(i.t>=n.t)continue;const s=Sd.closedAlongSight(i,n),[r,a,o]=s>=0?[n,i,s]:[i,n,-s];o<$P||r.widthDeg<=a.widthDeg||(!t||o>t.closedM)&&(t={near:r,far:a,closedM:o})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*zM,n=(t.lng-e.lng)*zM*Math.cos(e.lat*Zh),s=(e.sightAzimuthDeg??0)*Zh;return i*Math.cos(s)+n*Math.sin(s)}}class as{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(e){if(e.statedM!==void 0&&e.statedM>0)return{distanceM:as.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:as.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:as.atLeastNearest(e.derivedM),basis:"derived"};const t=as.largest(e.range?.minM,e.crossing?.behindM),i=as.smallest(e.range?.maxM,e.crossing?.inFrontM),n=t===void 0?void 0:t*as.MARGIN,s=i===void 0?void 0:i/as.MARGIN;return n!==void 0&&s!==void 0?{distanceM:as.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:as.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<as.CONVENTIONAL_M?{distanceM:as.atLeastNearest(s),basis:"bounded"}:{distanceM:as.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(as.NEAREST_M,e)}static largest(...e){const t=e.filter(i=>i!==void 0&&i>0);return t.length===0?void 0:Math.max(...t)}static smallest(...e){const t=e.filter(i=>i!==void 0&&i>0);return t.length===0?void 0:Math.min(...t)}}const K0=Math.PI/180;class qe{constructor(e,t,i){this.body=e,this.ground=t,this.eyeAt=i;const n=[...e.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)qe.collect(this.motionKeys,s.t,s.motions),qe.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;lightKeys=new Map;static collect(e,t,i){for(const[n,s]of Object.entries(i??{})){const r=e.get(n)??[];r.push({t,value:s}),e.set(n,r)}}motionsAt(e){return qe.channelsAt(this.motionKeys,e,0)}lightsAt(e){return this.lightKeys.size>0?qe.channelsAt(this.lightKeys,e,void 0):void 0}static channelsAt(e,t,i){const n={};for(const[s,r]of e){let a=r.length-1;for(;a>=0&&r[a].t>t;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const o=r[a],c=r[Math.min(a+1,r.length-1)],h=c===o||c.t===o.t?0:Math.min(1,(t-o.t)/(c.t-o.t));n[s]=qe.lerp(o.value,c.value,h)}return n}static eyeOf(e,t,i){const n=pt(e,0),s=pt(e,t),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?st(s.lat,s.lng,n.lat,n.lng):void 0,o=a?a.x:0,c=a?-a.z:0;return{eastM:o,northM:c,upM:i.heightAt(o,c)+qe.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(e,t,i,n){const s=qe.directionOf(t,i),r=c=>e.upM+s.upM*c-n.heightAt(e.eastM+s.eastM*c,e.northM+s.northM*c);let a=0,o=0;for(;o<qe.MAX_RANGE_M;){if(o=a+Math.max(.5,a*.01),r(o)<=0){for(let c=0;c<30;c++){const h=(a+o)/2;r(h)<=0?o=h:a=h}return o}a=o}}static directionOf(e,t){const i=e*K0,n=t*K0;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(e){const t=this.keys;if(t.length===0||e<t[0].t)return;let i=0,n=t.length-1;for(;i<n;){const m=i+n+1>>1;t[m].t>e?n=m-1:i=m}const s=i,r=t[s];if(!r.present)return;const a=t[Math.min(s+1,t.length-1)],o=a===r||a.t===r.t?0:Math.min(1,(e-r.t)/(a.t-r.t)),c=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(e):void 0,h=c?c.eastM+qe.lerp(r.carried.eastM,a.carried.eastM,o):qe.lerp(r.eastM,a.eastM,o),d=c?c.northM+qe.lerp(r.carried.northM,a.carried.northM,o):qe.lerp(r.northM,a.northM,o),u={widthM:qe.lerp(r.sizeM.widthM,a.sizeM.widthM,o),lengthM:qe.lerp(r.sizeM.lengthM,a.sizeM.lengthM,o),heightM:qe.lerp(r.sizeM.heightM,a.sizeM.heightM,o)},p={headingDeg:qe.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,o),pitchDeg:qe.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,o),rollDeg:qe.lerp(r.attitude.rollDeg,a.attitude.rollDeg,o)};let f;if(c)f=c.upM+qe.lerp(r.carried.upM,a.carried.upM,o);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const m=qe.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,o);f=this.groundUnderFootprint(h,d,u,p.headingDeg)+m+u.heightM/2}else f=qe.lerp(this.centreUpOf(r),this.centreUpOf(a),o);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:d,upM:f,sizeM:u,attitude:p,appearance:{color:qe.lerpColor(r.appearance.color,a.appearance.color,o),albedo:qe.lerp(r.appearance.albedo,a.appearance.albedo,o),luminanceCdM2:qe.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,o),transparency:qe.lerp(r.appearance.transparency,a.appearance.transparency,o),haloScale:qe.lerp(r.appearance.haloScale,a.appearance.haloScale,o)},flame:qe.flameBetween(r.flame,a.flame,o),motions:this.motionsAt(e),lights:this.lightsAt(e),throwsFlame:this.body.track.some(m=>m.flame!==void 0&&m.flame.luminanceCdM2>0)}}static flameBetween(e,t,i){if(!e||e.luminanceCdM2<=0)return i>=1&&t&&t.luminanceCdM2>0?t:void 0;const n=e,s=t??e,r={...i<1?n:s,lengthM:qe.lerp(n.lengthM,s.lengthM,i),widthM:qe.lerp(n.widthM,s.widthM,i),luminanceCdM2:qe.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(e){if(!("upM"in e.vertical))return this.groundUnderFootprint(e.eastM,e.northM,e.sizeM,e.attitude.headingDeg)+e.vertical.aboveGroundM+e.sizeM.heightM/2;const t=e.vertical.fromGround;if(!t)return e.vertical.upM;const i=e.vertical.upM+this.ground.heightAt(t.eastM,t.northM);return Math.max(i,this.groundUnderFootprint(e.eastM,e.northM,e.sizeM,e.attitude.headingDeg)+e.sizeM.heightM/2)}groundUnderFootprint(e,t,i,n){const s=n*K0,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let o=this.ground.heightAt(e,t);for(const[c,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const d=c*i.widthM/2,u=h*i.lengthM/2;o=Math.max(o,this.ground.heightAt(e+r.eastM*d+a.eastM*u,t+r.northM*d+a.northM*u))}return o}place(e,t){const i=[];let n;for(const s of e){const r=s.sizeM??n?.sizeM??qe.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},o={color:s.appearance?.color??n?.appearance.color??qe.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??qe.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??qe.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??qe.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??qe.DEFAULT_APPEARANCE.haloScale},c=this.positionOf(s,r,t)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!c)continue;const h=s.flame??n?.flame,d=s.present??n?.present??!0;if(n={t:s.t,...c,sizeM:r,attitude:a,appearance:o,flame:h,present:d},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const u=qe.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:u.eastM*s.distanceM,northM:u.northM*s.distanceM,upM:u.upM*s.distanceM}}i.push(n)}return i}verticalOf(e,t){if(e.onGround)return{aboveGroundM:0};if(e.altitudeAboveGroundM!==void 0)return{aboveGroundM:e.altitudeAboveGroundM};if(e.altitudeM!==void 0)return{upM:e.altitudeM+t.heightM/2,fromGround:this.body.altitudeFrom}}positionOf(e,t,i){if(e.eastM!==void 0&&e.northM!==void 0)return{eastM:e.eastM,northM:e.northM,vertical:this.verticalOf(e,t)??{aboveGroundM:0}};if(e.azimuthDeg===void 0||e.altitudeDeg===void 0)return;const n=i(e.t);if(!n)return;const s=e.distanceM??(e.onGround?qe.lineOfSightMeetsGround(n,e.azimuthDeg,e.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=qe.directionOf(e.azimuthDeg,e.altitudeDeg),a=n.eastM+r.eastM*s,o=n.northM+r.northM*s;return{eastM:a,northM:o,vertical:this.verticalOf(e,t)??{upM:n.upM+r.upM*s}}}static lerp(e,t,i){return e+(t-e)*i}static lerpColor(e,t,i){const n=qe.rgbOf(e),s=qe.rgbOf(t);return!n||!s?i<1?e:t:"#"+n.map((r,a)=>Math.round(qe.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(e){const t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e);if(!t)return;const i=t[1].length===3?t[1].replace(/./g,"$&$&"):t[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(e,t,i){const n=((t-e)%360+540)%360-180;return((e+n*i)%360+360)%360}}class os{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(e){const t=e?.flares;return!e||!t||t.length===0?e:{...e,bodies:[...e.bodies,...t.flatMap(i=>os.bodiesOf(i))]}}static bodiesOf(e){const t={...os.MJU_7,...e.flare},i=[],n=e.aircraft;if(n.model||n.sound){const s=e.releases.map(h=>h.t),r=Math.min(n.t,...s)-12e4,a=Math.max(n.t,...s)+12e4,o=n.model?{color:"#30333a",albedo:.15}:{transparency:1},c=h=>{const d=os.aircraftAt(n,h);return{t:h,eastM:d.x,northM:d.y,altitudeM:d.z,attitude:{headingDeg:n.headingDeg},sizeM:n.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:o}};i.push({id:`${e.id}-aircraft`,title:e.title,model:n.model??{id:"sphere"},track:[c(r),c(a)],sound:n.sound})}return n.glow&&i.push(os.glowBody(e,n.glow)),e.releases.forEach((s,r)=>i.push(os.flareBody(e,t,s,r))),i}static aircraftAt(e,t){const i=e.headingDeg*Math.PI/180,n=(t-e.t)/1e3*e.speedMS;return{x:e.eastM+Math.sin(i)*n,y:e.northM+Math.cos(i)*n,z:e.altitudeM}}static burnShare(e,t){if(t<0||t>=e.burnS)return 0;if(t<.2)return t/.2;const i=e.burnS*.75;return t<=i?1:(e.burnS-t)/(e.burnS-i)}static trajectory(e,t,i,n=os.SAMPLE_MS){const s=e.aircraft,r=s.headingDeg*Math.PI/180,o={...os.aircraftAt(s,i),vx:Math.sin(r)*s.speedMS,vy:Math.cos(r)*s.speedMS,vz:-t.ejectionMS},c=(e.wind?.towardDeg??0)*Math.PI/180,h=e.wind?.speedMS??0,d=Math.sin(c)*h,u=Math.cos(c)*h,p=s.originElevationM??1e3,f=[{t:i,x:o.x,y:o.y,z:o.z}],m=os.STEP_S,v=Math.round(n/1e3/m),g=Math.ceil(t.burnS/m);for(let y=1;y<=g;y++){const w=y*m,b=t.massKg-t.burnedKg*Math.min(1,w/t.burnS),M=1.225*Math.exp(-(o.z+p)/8500),S=o.vx-d,E=o.vy-u,x=o.vz,T=Math.hypot(S,E,x),D=.5*M*t.dragAreaM2*T/b;o.vx=(o.vx+D*m*d)/(1+D*m),o.vy=(o.vy+D*m*u)/(1+D*m),o.vz=(o.vz-os.G*m)/(1+D*m),o.x+=o.vx*m,o.y+=o.vy*m,o.z+=o.vz*m,(y%v===0||y===g)&&f.push({t:i+Math.round(w*1e3),x:o.x,y:o.y,z:o.z})}return f}static glowBody(e,t){const i=t.sizeM/2,n=t.luminousIntensityCd/(Math.PI*i*i),s=[{t:t.fromT,lit:!0}];if(t.onS&&t.offS)for(let c=t.fromT,h=!0;c<t.untilT;h=!h)c+=(h?t.onS:t.offS)*1e3,c<t.untilT&&s.push({t:c,lit:!h});const r=(c,h)=>{const d=os.aircraftAt(e.aircraft,c);return{t:c,eastM:d.x,northM:d.y,altitudeM:d.z,appearance:{color:t.color,luminanceCdM2:h?n:0}}},a=[];s.forEach(({t:c,lit:h},d)=>{d>0&&a.push(r(c-1,!h)),a.push(r(c,h))}),a[0]={...a[0],sizeM:{widthM:t.sizeM,lengthM:t.sizeM,heightM:t.sizeM},present:!0};const o=s[s.length-1];return a.push(r(t.untilT,o.lit),{t:t.untilT+1,present:!1}),{id:`${e.id}-glow`,title:e.title,explains:t.explains,model:{id:"sphere"},track:a}}static flareBody(e,t,i,n){const s=t.flameSizeM,r=s/2,a=t.luminousIntensityCd/(Math.PI*r*r),o=os.trajectory(e,t,i.t),c=o.map((h,d)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...d===0?{sizeM:{widthM:s,lengthM:s,heightM:s},present:!0}:{},appearance:{color:t.color,luminanceCdM2:a*os.burnShare(t,(h.t-i.t)/1e3),...d===0?{haloScale:1}:{}}}));return c.push({t:o[o.length-1].t+1,present:!1}),{id:`${e.id}-flare-${n+1}`,title:e.title,explains:i.explains,model:{id:"sphere"},track:c}}}class It{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=It.COMMON.luminousIntensityCd/(Math.PI*It.COMMON.widthM/2*It.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(e){const t=e?.lanterns;return!e||!t||t.length===0?e:{...e,bodies:[...e.bodies,...t.flatMap(i=>It.bodiesOf(i))]}}static bodiesOf(e){return It.releasesOf(e).map((t,i)=>It.lanternBody(e,t,i))}static releasesOf(e){const t=[...e.releases??[]],i=e.group;if(!i||!(i.count>0))return t;const n=It.randomFrom(i.seed??1),s=o=>o.min+(o.max-o.min)*n(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let o=0;o<i.count;o++){const c=i.fromT+r*o+(n()-.5)*r,h=a*Math.sqrt(n()),d=2*Math.PI*n();t.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,c))),explains:i.explains,eastM:Math.round(h*Math.sin(d)*10)/10,northM:Math.round(h*Math.cos(d)*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 t}static randomFrom(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let i=t;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(e,t){return{...It.COMMON,...e.lantern,...t.lantern}}static heatShare(e,t){if(t<0||t>=e.burnS)return 0;const i=e.burnS*.75;return t<=i?1:(e.burnS-t)/(e.burnS-i)}static windAt(e,t){const i=It.componentsOf(e.wind),n=e.windAloft;if(!n)return i;const s=It.componentsOf(n),r=Math.max(0,Math.min(1,t/n.atM));return{x:i.x+(s.x-i.x)*r,y:i.y+(s.y-i.y)*r}}static trajectory(e,t,i=It.SAMPLE_MS){const n=It.typeOf(e,t),s=e.site,r=s.altitudeM??0,a=Math.max(0,t.burnedS??0),o=s.originElevationM??0,c=(e.airTemperatureC??10)+273.15,h={x:s.eastM+(t.eastM??0),y:s.northM+(t.northM??0),z:t.altitudeM??r,vx:0,vy:0,vz:0,excessK:n.insideExcessK*It.heatShare(n,a)},d=It.STEP_S,u=Math.max(1,Math.round(i/1e3/d)),p=Math.ceil(Math.max(0,n.burnS-a)/d),f=[{t:t.t,x:h.x,y:h.y,z:h.z,light:It.heatShare(n,a),tiltDeg:0,tiltTowardDeg:0}],m=It.gusts(e.turbulence??It.TURBULENCE,It.seedOf(t),d);for(let v=1;v<=p;v++){const g=v*d,y=a+g,w=It.heatShare(n,y);h.excessK+=(n.insideExcessK*w-h.excessK)*Math.min(1,d/It.COOLING_S);const b=h.z-r,M=c-It.LAPSE*Math.max(0,b),S=101325*Math.exp(-(h.z+o)/8400),E=S/(It.R_AIR*M),x=S/(It.R_AIR*(M+h.excessK)),T=n.massKg-n.fuelKg*Math.min(1,y/n.burnS),D=(E-x)*n.envelopeVolumeM3*It.G,R=T+x*n.envelopeVolumeM3+.5*E*n.envelopeVolumeM3,O=It.windAt(e,b),N=m(),C={x:O.x+N.x,y:O.y+N.y,z:N.z},k=h.vx-C.x,P=h.vy-C.y,F=h.vz-C.z,G=.5*E*n.dragAreaM2*Math.hypot(k,P,F)/R;h.vx=(h.vx+G*d*C.x)/(1+G*d),h.vy=(h.vy+G*d*C.y)/(1+G*d),h.vz=(h.vz+G*d*C.z+(D-T*It.G)/R*d)/(1+G*d);const Y=h.z<=r&&h.vz<=0;if(Y&&(h.vx=0,h.vy=0,h.vz=0),h.x+=h.vx*d,h.y+=h.vy*d,h.z=Math.max(r,h.z+h.vz*d),v%u===0||v===p){const W=C.x-h.vx,ee=C.y-h.vy,se=.5*E*n.dragAreaM2*Math.hypot(W,ee,C.z-h.vz)*Math.hypot(W,ee);f.push({t:t.t+Math.round(g*1e3),x:h.x,y:h.y,z:h.z,light:w,tiltDeg:Y?0:Math.atan2(se,T*It.G)*180/Math.PI,tiltTowardDeg:(Math.atan2(W,ee)*180/Math.PI+360)%360})}}return f}static seedOf(e){return e.seed!==void 0?e.seed:Math.round(e.t)*2654435761+Math.round((e.eastM??0)*100)*40503+Math.round((e.northM??0)*100)>>>0}static gusts(e,t,i){const n=It.randomFrom(t),s=()=>Math.sqrt(-2*Math.log(Math.max(1e-12,n())))*Math.cos(2*Math.PI*n()),r=e.timescaleS>0?Math.exp(-i/e.timescaleS):0,a=Math.sqrt(1-r*r),o={x:e.horizontalMS*s(),y:e.horizontalMS*s(),z:e.verticalMS*s()};return()=>(o.x=r*o.x+a*e.horizontalMS*s(),o.y=r*o.y+a*e.horizontalMS*s(),o.z=r*o.z+a*e.verticalMS*s(),o)}static componentsOf(e){if(!e)return{x:0,y:0};const t=e.towardDeg*Math.PI/180;return{x:Math.sin(t)*e.speedMS,y:Math.cos(t)*e.speedMS}}static lanternBody(e,t,i){const n=It.typeOf(e,t),s=n.luminousIntensityCd/(Math.PI*n.widthM/2*n.heightM/2),r=It.trajectory(e,t),a={widthM:n.widthM,lengthM:n.widthM,heightM:n.heightM},o=It.through(n.color,n.paperColor),c=r.map((h,d)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...d===0?{sizeM:a,present:!0}:{},attitude:{headingDeg:Math.round(h.tiltTowardDeg),pitchDeg:-Math.round(h.tiltDeg*10)/10},appearance:{color:o,luminanceCdM2:s*h.light,...d===0?{albedo:.6,haloScale:1}:{}},lights:It.lightsOf(s*h.light)}));return c.push({t:r[r.length-1].t+1,present:!1}),{id:`${e.id}-lantern-${i+1}`,title:It.TITLE,explains:t.explains,model:{id:`ufoathome-sky-lantern-${n.shape}`},modelParameters:{paperColor:n.paperColor},flicker:It.FLICKER,altitudeFrom:{eastM:r[0].x,northM:r[0].y},track:c}}static lightsOf(e){return{paper:e,"paper-inside":e*It.INSIDE_SHARE,flame:e>0?It.FLAME_CDM2*e/It.PAPER_FULL_CDM2:0}}static through(e,t){const i=o=>[1,3,5].map(c=>parseInt(o.slice(c,c+2),16)/255),n=i(e),s=i(t),r=n.map((o,c)=>o*s[c]),a=Math.max(...n)/(Math.max(...r)||1);return"#"+r.map(o=>Math.round(Math.min(1,o*a)*255).toString(16).padStart(2,"0")).join("")}}class Gb{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=Gb.FIRST_DAY}}class KP{constructor(e,t,i){this.citation=e,this.covers=t,this.load=i}loading;mayCover(e){return this.covers(e)}async between(e,t,i,n){try{return await(await this.provider()).between(e,t,i,n)}catch{return{status:"failed"}}}async describe(e,t){try{return await(await this.provider()).describe?.(e,t)}catch{return}}provider(){if(!this.loading){const e=this.load();this.loading=e,e.catch(()=>{this.loading===e&&(this.loading=void 0)})}return this.loading}}const XP="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",Fv=[{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 KP(XP,l=>Gb.mayCover(l),async()=>new(await ae(async()=>{const{AdsbLolArchiveProvider:l}=await import("./AdsbLolArchiveProvider-RNAaE2P_.js");return{AdsbLolArchiveProvider:l}},[],import.meta.url)).AdsbLolArchiveProvider)}];class cs{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const n=cs.positionAt(e,i);if(!n)return;const s=_t.seenFrom(t,n.geo);if(!(s.altitudeDeg<0))return{track:e,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:cs.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(n=>cs.seenFrom(n,t,i)??[])}static groundDistanceKm(e,t){const i=Math.PI/180,n=Math.sin((t.lat-e.lat)*i/2)**2+Math.cos(e.lat*i)*Math.cos(t.lat*i)*Math.sin((t.lng-e.lng)*i/2)**2;return 2*cs.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(e){return((e+180)%360+360)%360-180}static positionAt(e,t){const i=e.points;if(i.length===0||t<i[0].t||t>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=t;)n++;const s=i[n],r=i[n+1]??s,a=r.t-s.t;if(a>cs.MAX_GAP_S*1e3)return;const o=a>0?(t-s.t)/a:0,c=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*o,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*o,lng:cs.wrapLongitude(s.lng+h*o),heightM:c*cs.FT_TO_M},altitudeFt:c,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(e,t,i){const n=cs.positionAt(e,i-500),s=cs.positionAt(e,i+500);if(!n||!s)return;const r=cs.unit(_t.seenFrom(t,n.geo)),a=cs.unit(_t.seenFrom(t,s.geo)),o=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(o)*180/Math.PI}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180;return[Math.cos(t)*Math.sin(i),Math.cos(t)*Math.cos(i),Math.sin(t)]}}const BM="https://ufoathome.org/fireballs/index.json";class or{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??or.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/fireballs/index.json",location.href).href),e.includes(BM)||e.push(BM),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=or.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!or.mayCover(t))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(e).toISOString().slice(0,7),new Date(t).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>=e&&r.t<=t):void 0}static seenFrom(e,t){const i=or.peakFraction(e),n={lat:e.from[0]+(e.to[0]-e.from[0])*i,lng:e.from[1]+(e.to[1]-e.from[1])*i,heightM:e.peakHeightKm*1e3},s=_t.seenFrom(t,n);if(!(s.altitudeDeg<0))return{record:e,peak:s,magnitude:e.peakMagnitude+5*Math.log10(s.distanceKm/_t.STANDARD_DISTANCE_KM)}}static asReentry(e,t){const i=e.t-t,n=i+Math.max(e.durationS,.1)*1e3;return{id:`gmn-${e.id}`,track:[{t:i,lat:e.from[0],lng:e.from[1],altitudeKm:e.from[2]},{t:n,lat:e.to[0],lng:e.to[1],altitudeKm:e.to[2]}],fragments:[{absoluteMagnitude:e.peakMagnitude,color:or.COLOR,trainS:or.TRAIN_S}]}}static peakFraction(e){const t=e.from[2]-e.to[2];return Math.abs(t)<1e-6?.5:Math.min(1,Math.max(0,(e.from[2]-e.peakHeightKm)/t))}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(t.ok)return{index:await t.json(),base:e}}catch{}})(),this.index}monthOf(e,t){let i=this.months.get(e);return i||(i=this.fetchImpl(new URL(`${e}.json`,t).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(e,i)),i}}cm();const YP={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},qP="{name} — mag {mag}, {alt}° above the horizon",jP="{name} — {size}, {distance} away",ZP="{name} — satellite, mag {mag}, {height} km up",HM={ghost:"Ghost: {name}",halo:"Halo: {name}",double:"Double: {name}",unnamed:"a light",detail:"{name}. {cause}, {where}.",causes:{lens:"A reflection between two surfaces of the lens",sensor:"The sensor's reflection, sent back by its cover glass",filter:"The sensor's reflection, sent back by the filter",glass:"A reflection between the two faces of the glass in front of the lens",drops:"Light scattered by drops on the glass",condensation:"Light scattered by condensation on the glass",dirt:"Light scattered by dirt on the glass"},opposite:"across the centre of the picture from the light",sameSide:"on the same side of the centre as the light",around:"round the light",drop:{lens:"Drop on the lens",filter:"Drop on the filter",window:"Drop on the window",windscreen:"Drop on the windscreen"},dropDetail:"{name}. Like a small lens, it shows upside down and blurred what is on the other side of it, rather than what is behind it."},JP={name:"Rocket plume",detail:"{name} — {part}, {distance} away, {height} km up",ascent:"exhaust of the ascent",burn:"exhaust of an engine burn",vent:"vented propellant"},XS="satellites-change",YS="fireballs-change",qS="references-change",QP="aircraft-change",e6="rr0-confrontation",t6="{name} — mag {mag}, {alt}° below the horizontal",X0="Credits",GM="comet:",VM="nova:",Y0={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",trafficlight:"Traffic light",crossing:"Pedestrian crossing",roadsign:"Road sign",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},i6=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,n6=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,s6=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,r6=-18,a6={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},op={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Et extends HTMLElement{creditsButton;set ownCredits(e){this.creditsButton.hidden=!e}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",jc,Zc,vl]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new _;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new Xn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new or;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static NO_BEAMS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=Fv[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return Et.trafficRuntimeLoading??=ae(()=>import("./trafficRuntime-ZmzuyzhR.js"),__vite__mapDeps([8,3]),import.meta.url).then(e=>Et.trafficRuntime=e),Et.trafficRuntimeLoading.catch(()=>{Et.trafficRuntimeLoading=void 0}),Et.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new HP;vehicleAudio=new cI;aircraftAudio;vehicleHearing=new pf;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{if(this.lastHover={clientX:e.clientX,clientY:e.clientY,altKey:e.altKey},this.ghostMissedSinceMs=void 0,this.hoverFrame!==void 0&&e.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=e.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(e,t){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return!0;const n=(e.clientX-i.left)/i.width*2-1,s=1-(e.clientY-i.top)/i.height*2;return this.sceneRenderer.ghostsReadableAt(n,s)?this.sceneRenderer.pickGhostAt(n,s)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=t,t-this.ghostMissedSinceMs>Et.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;hoverAt(e){if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(e.clientX-i.left)/i.width*t.width,s=(e.clientY-i.top)/i.height*t.height;if(this.ufoElement.hasVisibleShapeAt(n,s)){this.hoverTooltip.hidden=!0;return}const r=(e.clientX-i.left)/i.width*2-1,a=-((e.clientY-i.top)/i.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(r,a))return;const o=this.pickAt(r,a,!0,e.altKey);o?this.showHoverTooltip(e,e.altKey&&o.detail?o.detail():o.name):this.hoverTooltip.hidden=!0,this.showGhostPath(o?.path,i)}showGhostPath(e,t){if(!e){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),n=u=>({x:t.left-i.left+(u.x+1)/2*t.width,y:t.top-i.top+(1-u.y)/2*t.height}),s=n(e.from),r=n(e.to),a=n({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[o,c,h,d]=Array.from(this.ghostPath.children);for(const u of[o,c])u.setAttribute("x1",String(s.x)),u.setAttribute("y1",String(s.y)),u.setAttribute("x2",String(r.x)),u.setAttribute("y2",String(r.y));h.setAttribute("cx",String(a.x)),h.setAttribute("cy",String(a.y)),d.setAttribute("cx",String(r.x)),d.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(e,t,i=!0,n=!1){const s=this.naming,r=s.names;if(n&&this.sceneRenderer.pickDropAt(e,t)){const E=r?.ghostTooltip??HM,x=E.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:x,detail:()=>E.dropDetail.replace("{name}",x)}}const a=this.sceneRenderer.pickBodyAt(e,t);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const o=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(e,t):void 0,c=o?this.interpretationShown?.bodies.find(E=>E.id===o):void 0,h=c?this.said.read(c.title)||(c.model.id==="figure"?s.decorKind("entity",Y0.entity):void 0):void 0;if(o!==void 0&&h)return{kind:"body",id:o,name:h};const d=this.ufoElement.sighting.skyEvents?.beams,u=d?.length?this.sceneRenderer.pickBeamAt(e,t):void 0,p=u?d?.find(E=>E.id===u.id):void 0;if(u&&p){const E=this.said.read(p.title)||"Laser";return{kind:"beam",id:p.id,name:E,detail:()=>`${E} (${p.wavelengthNm} nm, ${p.powerW.toLocaleString()} W), ${this.distanceText(u.distanceM)}`}}const f=i?this.ghostPick(e,t):void 0;if(f)return f;const m=this.pickDecorAt(e,t),v=m?this.ufoElement.sighting.decor.find(E=>E.id===m):void 0;if(v){const E=this.said.read(v.title)||s.decorKind(v.kind,Y0[v.kind]);return{kind:"decor",id:v.id,name:E,detail:()=>this.decorTooltip(v,E)}}const g=this.sceneRenderer.pickRailwayAt(e,t);if(g){const E=r?.railwayTooltip??Ar.ENGLISH;return{kind:"railway",id:g.line.id,name:Ar.name(g.line,E),detail:()=>Ar.detail(g,E,x=>this.distanceText(x))}}const y=this.trafficTooltipAt(e,t);if(y)return{kind:"traffic",name:y};const w=this.plumePickAt(e,t);if(w)return w;const b=this.sceneRenderer.pickSatelliteAt(e,t);if(b)return{kind:"satellite",name:(r?.satelliteTooltip??ZP).replace("{name}",b.name).replace("{mag}",b.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(b.heightKm).toLocaleString())};const M=this.sceneRenderer.pickOpticsAt(e,t);if(M){const E=(r?.opticsTooltips??DP)[M.id].replace("{angle}",String(Math.round(M.angleDeg??0)));return{kind:"optics",id:M.id,name:E.split(" — ")[0],detail:()=>E}}const S=this.sceneRenderer.pickStarAt(e,t);if(S){const E=S.star.mag,x=S.altitudeDeg,T=x<0?r?.starTooltipBelow??t6:r?.starTooltip??qP,D=s.star(S.star);return{kind:"star",name:D,detail:()=>T.replace("{name}",D).replace("{mag}",E.toLocaleString(void 0,{maximumFractionDigits:Math.abs(E)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(x))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(e,t){const i=this.ufoElement.canvasElement,n={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},s=`${Math.round(e/n.x)}:${Math.round(t/n.y)}`,r=performance.now(),a=this.ghostLights.get(s);if(a&&r-a.atMs<Et.GHOST_LIGHT_KEPT_MS)return a.light;let o=this.shiningDecorNear(e,t,2*Math.max(n.x,n.y)),c;if(!o)for(const[h,d]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const u=this.pickAt(e+h*n.x,t+d*n.y,!1);if(u?.kind==="star")c??=u;else if(u){o=u;break}}return o??=this.shiningDecorNear(e,t,6*Math.max(n.x,n.y)),o??=c,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(s,{light:o??null,atMs:r}),o??null}ghostPick(e,t){const i=this.sceneRenderer.pickGhostAt(e,t);if(!i)return;const n=this.naming.names?.ghostTooltip??HM,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,c=(bi.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:c,detail:()=>n.detail.replace("{name}",c).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(e,t,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 o=Math.hypot(Math.max(a.minX-e,0,e-a.maxX),Math.max(a.minY-t,0,t-a.maxY));if(o>i||n&&o>=n.distance)continue;const c=this.said.read(s.title)||this.naming.decorKind(s.kind,Y0[s.kind]);n={distance:o,pick:{kind:"decor",id:s.id,name:c}}}return n?.pick}glassWettingOf(e){const t=JSON.stringify([e.lens,e.instrumentId,e.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==e||this.glassWetting.key!==t){const i=new ml(n=>{if(!bi.records(e.instrument)||!bi.falling(e.lens))return 0;const s=_h(e,n*1e3),r=pt(e,n*1e3);return(s.precipitationAmount??1)*bi.impactRate(s,e.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:s.windDirectionDeg,windSpeedMS:s.windSpeed})});this.glassWetting={sighting:e,key:t,wetting:i}}return this.glassWetting.wetting}glassWetting;plumePickAt(e,t){const i=this.ufoElement.sighting.skyEvents?.launches,n=i?.length?this.sceneRenderer.pickPlumeAt(e,t):void 0,s=n?i?.find(c=>c.id===n.launchId):void 0;if(!n||!s)return;const r=this.naming.names?.plumeTooltip??JP,a=this.said.read(s.title)||s.vehicle?.mission||r.name,o=()=>n.release===void 0||n.release==="burn"?r.ascent:s.jets?.find((h,d)=>`jet:${h.id??d}`===n.release)?.kind==="vent"?r.vent:r.burn;return{kind:"plume",id:s.id,name:a,detail:()=>r.detail.replace("{name}",a).replace("{part}",o()).replace("{distance}",this.distanceText(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}distanceText(e){return e>=1e3?`${(e/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${e.toLocaleString(void 0,{maximumFractionDigits:e<10?1:0})} m`}decorTooltip(e,t){const i=c=>c.toLocaleString(void 0,{maximumFractionDigits:c<10?1:0}),n=me.sizeOf(e),s=this.sceneRenderer.decorDistanceM(e.id),r=s===void 0?"":this.distanceText(s);return(this.naming.names?.decorTooltip??jP).replace("{name}",t).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(e){const t=e.startsWith(GM)?e.slice(GM.length):void 0,i=t?KS.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const n=e.startsWith(VM)?Gf.byId(e.slice(VM.length)):void 0;if(n)return this.naming.nova(n);const s=YP[e];return s===void 0?e:this.naming.body(e,s)}get naming(){return this.sceneNaming}sceneNaming=new Hf;namesLanguage="en";async loadSceneNames(){const e=Id(Zs.preferencesFor(this),Td);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await hx(e);e===this.namesLanguage&&this.applySceneNaming(new Hf(t))}setBusy(e,t=""){this.busyElement.hidden=!e,this.busyNote.textContent=e?t:"",this.busyElement.setAttribute("aria-label",t),this.busyElement.setAttribute("aria-busy",String(e))}renderLoaderText(e,t){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,o)=>{o>0&&s.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of a){const d=document.createElement("span");d.className="scene-loader-letter",d.style.setProperty("--i",String(i++)),d.textContent=h,c.append(d)}s.append(c),i++})};n(this.loaderNotVideo,e),i+=6,n(this.loaderNote,t)}applySceneNaming(e){this.sceneNaming=e;const t=e.names?.credits??X0;this.creditsButton.title=t,this.creditsButton.setAttribute("aria-label",t),e.names&&this.renderLoaderText(e.names.notAVideo,e.names.isASimulation),this.sceneRenderer.setCompassPoints(e.names?.compassPoints)}showHoverTooltip(e,t){this.hoverTooltip.textContent=t,this.hoverTooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect(),n=e.clientX-i.left+12,s=n+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${s>0?Math.max(0,n-s-4):n}px`,this.hoverTooltip.style.top=`${e.clientY-i.top+12}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash(e){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),xn.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(_h(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const e=this.ufoElement.level;this.weatherAudio.setLevel(e),this.vehicleAudio.setLevel(e),this.aircraftAudio?.setLevel(e)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=e=>{if(this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const t=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&t-this.lastPlayingHoverMs>=Et.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=t,this.ghostStillUnder(this.lastHover,t)&&this.hoverAt(this.lastHover))}this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(e,e),this.weatherAudio.setPaused(!e),this.vehicleAudio.setPaused(!e),this.aircraftAudio?.setPaused(!e),e&&this.unlockIfAlreadyActivated(),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${uI}</style>${dI}`,this.shadow.appendChild(e.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 Ee(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(qS));const t=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.renderLoaderText("This is not a video","It is a real-time simulation."),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=t,this.poster=new Hb(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.ufoElement=document.createElement(Dg),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapFrozenSource=s=>this.frozenMapOf(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"&&Kn.fill(n,this)}),this.creditsButton.title=X0,this.creditsButton.setAttribute("aria-label",X0),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("playrequest",()=>this.poster.release()),this.ufoElement.addEventListener(O2,()=>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.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 Et.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new vs(Zs.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(e,t){const i=e.vehicle;return i?{setting:_o.at(i.headlights??"auto",i.headlightKeyframes,t)??"auto",headingDeg:this.travelHeadingAt(e,t)}:void 0}travelHeadingAt(e,t){const i=pt(e,t);if(!i)return 0;for(const n of[400,-400]){const s=pt(e,t+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=st(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(e){const t=e.allKeyframes;if(this.routeCache?.track===e&&this.routeCache.count===t.length)return this.routeCache.route;const i=t.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:e,count:t.length,route:n},n}traceLabels(e){const t=Zs.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==e||this.traceLabelsFor.language!==t){const i=new Map;for(const n of e){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:e,language:t,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){this.saidTexts=void 0,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 t of Et.GESTURES)document.addEventListener(t,this.handlePageGesture,!0);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(e=>{if(e[e.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of Et.GESTURES)document.removeEventListener(e,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(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),(e==="star-catalog-src"||e==="deep-star-catalog-src")&&i!==t&&this.isConnected&&this.loadStars(),e==="show-compass"&&i!==t&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),e==="max-pixel-ratio"&&i!==t){const n=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(n)&&n>0?n:Math.min(window.devicePixelRatio||1,2))}(e===jc||e===Zc||e===vl)&&i!==t&&this.forwardPlayerAttributes(),e===vl&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const e of[jc,Zc,vl]){const t=this.getAttribute(e);t===null?this.ufoElement.removeAttribute(e):this.ufoElement.setAttribute(e,t)}}setCompassForced(e){this.sceneRenderer.setCompassForced(e)}lookToward(e){const t=pt(this.ufoElement.sighting,this.lastTimeMs);if(e.kind==="observer"||t?.lat===void 0||t.lng===void 0||t.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:i,z:n}=st(e.lat,e.lng,t.lat,t.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-t.headingDeg)%360+540)%360-180,-t.pitchDeg)}setLookOffset(e,t){this.sceneRenderer.setLookOffset(e,t),this.ufoElement.setLookOffset(e,t),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setCloudRendering(e){this.sceneRenderer.setCloudRendering(e)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity*(e.precipitationAmount??1),e.windSpeed)}pickCloudAt(e,t){return this.sceneRenderer.pickCloudAt(e,t)}cloudDirectionAt(e,t){return this.sceneRenderer.cloudDirectionAt(e,t)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}decorScreenBox(e){return this.sceneRenderer.decorScreenBox(e)}decorDrawnOffset(e){return this.sceneRenderer.decorDrawnOffset(e)}decorGroundPointAt(e,t,i,n=0){return this.sceneRenderer.decorGroundPointAt(e,t,i,n)}decorMetresPerNdcY(e){return this.sceneRenderer.decorMetresPerNdcY(e)}decorGrabHeightAt(e,t,i){return this.sceneRenderer.decorGrabHeightAt(e,t,i)}bodyScreenBox(e){return this.sceneRenderer.bodyScreenBox(e)}pickPlacedBodyAt(e,t){return this.sceneRenderer.pickPlacedBodyAt(e,t)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(e){const t=kr.recording(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(e,t,i=!0){this.poster.show(e,t,i)}applyHold(){const e=this.holding,t=this.poster.up;this.loader.hidden=!e||t,e&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=e||t,this.ufoElement.controlsHeld=e||t,this.ufoElement.holdClock(e)}holdForNewScene(e){this.sceneRenderer.holdForNewScene(e)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(e){this.sceneRenderer.documentUrl=e}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.ufoElement.sightingData=e,this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?It.expand(os.expand(this.ufoElement.sighting.interpretation)):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(e){const t=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(e.width/t);return e.height!==i&&(e.height=i),this.seekPreview??=new Ff(this,()=>document.createElement(Vf))}showAt(e){this.ufoElement.currentTime=e,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(e){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const t=e.getContext("2d");return t?(t.imageSmoothingQuality="high",t.drawImage(this.sceneCanvas,0,0,e.width,e.height),!0):!1}referenceAspect(e){return this.sceneRenderer.referenceAspect(e)}screenPointOf(e){return this.sceneRenderer.screenPointOf(e)}directionAt(e,t){return this.sceneRenderer.directionAt(e,t)}referenceFailure(e){return this.sceneRenderer.referenceFailure(e)}applyReferenceView(e){this.sceneRenderer.setReferencesShown(e.shown);for(const t of this.ufoElement.sighting.references){const i=e.views?.[t.id];this.sceneRenderer.setReferenceView(t.id,{opacity:i?i.shown?i.opacity:0:e.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(e){this.liveTerrainProviders=e,this.frozenKey=void 0,this.applyFrozen(this.ufoElement.sighting.frozen)}liveTerrainProviders;frozenKey="none";applyFrozen(e){const t=Bi.isEmpty(e)?"none":`${JSON.stringify(e)}
11222
11222
  ${this.documentUrl??""}
11223
11223
  ${St.generation}`;if(t===this.frozenKey)return;const i=this.frozenKey!==void 0&&this.traffic?.set!==void 0;this.frozenKey=t,this.sceneRenderer.setTerrainProviders(zf.providers(e,this.documentUrl,this.liveTerrainProviders??_2())),this.ufoElement.observerMapFrozen=this.frozenMapOf(e),i&&(this.traffic=void 0,this.decorMemo=void 0)}frozenMapOf(e){const t=Bi.held(e,"map");if(!t)return;const i=`${St.address(t.src,this.documentUrl)}
11224
- ${St.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery:zf.map(t,this.documentUrl)}),this.frozenMap.imagery}frozenMap;setDecorModelProvider(e){this.sceneRenderer.setDecorModelProvider(e)}get decorModelCredits(){return[...new Map(this.sceneRenderer.currentDecorModelCredits.map(t=>[`${t.title}|${t.author??""}|${t.license}|${t.sourceUrl??""}`,t])).values()]}applyFrameFormat(){const e=this.ufoElement.sighting.instrument,t=At.CANVAS_HEIGHT_PX,i=hi.frameWidthPx(e,t);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${t}`)}resizeToStage(){const e=this.frameElement.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),i=Math.max(1,Math.round(e.height));this.sceneCanvas.width=t,this.sceneCanvas.height=i,this.sceneRenderer.resize(t,i)}async loadStars(){const e=[{magnitudeLimit:W0,url:this.getAttribute("star-catalog-src")??n6},{magnitudeLimit:Md,url:this.getAttribute("deep-star-catalog-src")??s6}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>W0?Md:W0;const n=await Yr.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=Md||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=Dn.gainFor(e.instrument,{fNumber:pt(e,0)?.fNumber,fieldOfViewDeg:Oi.fovOf(e,0),exposureSeconds:e.exposure});return ea(r6,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=Er.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,n=this.degreesPerPixelAt(e),s=Pl.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(e).length,Er.instants(this.decorWithTraffic(this.ufoElement.sighting),pt(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(t.fromMs+t.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-1)*s/r),stepMs:t.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(e){const t=this.sceneCanvas.height;return t<=0?0:Oi.fovOf(this.ufoElement.sighting,e)/t}roadGradeAt(e,t){return e.observerTrack.allKeyframes.length<2?0:Pc.at(e,t,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(e,t){const i=this.ufoElement.sighting;this.setWeather(_h(i,e)),this.sceneRenderer.setInstrument(i.instrument),this.sceneRenderer.setLightPollution(i.lightPollution),t||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,e)),t||this.pushAircraftSound(i,e),this.updateMeteorShower(i,e),this.updateLightning(i,e,t!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(i),e)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??Tt.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(e)),this.sceneRenderer.setContrails(this.traffic?.contrails??Tt.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(e));const n=pt(i,e);this.sceneRenderer.setReferences(i.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0);const s=pt(i,0),r=en(i,0),a=zn(i.event.time??{},n?.lng??op.lng,i.event.utcOffsetHours),o=i.weatherSource!==void 0&&a?YA(a):void 0,c=Object.fromEntries(xo(en(i,e)).map(R=>[R.id,ef(e,i.weatherTrack,r,s,n,R.id,R.instances?.length?void 0:o)]));this.sceneRenderer.setCloudOffset(ef(e,i.weatherTrack,r,s,n,void 0,o),c),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,e)}:op),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(Dn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:Oi.fovOf(i,e),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,Ci.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso,i.metering),this.sceneRenderer.setLensGhosts(bi.optics(i.instrument,n?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(e/1e3))),this.sceneRenderer.setPerception(Ol.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(ri.bodyAt(i,e,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(pt(i,0),n,e),this.placeBodiesAt(e,t===void 0),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),this.applyFrozen(i.frozen),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,e)),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(e);const h=n?.lat??op.lat,d=n?.lng??op.lng,u=zn(i.event.time??{},d,i.event.utcOffsetHours),p={lat:h,lng:d,elevationM:n?.elevationM??0};this.pushSatellitesAt(u,e,p),this.ensureFireballs(u);const f=i.skyEvents,m=[...f?.reentries??[],...this.fireballs?.reentries??[]];this.sceneRenderer.setReentries(m.length===0?[]:_t.viewsAt(m,e,{lat:h,lng:d,heightM:p.elevationM})),this.sceneRenderer.setBeams(f?.beams??Tt.NO_BEAMS);const v=f?.launches??[];if(this.sceneRenderer.setLaunchPlumes(v.length===0||!u?[]:Le.viewsAt(v,e,{lat:h,lng:d,heightM:p.elevationM},Le.sunDirectionAt(new Date(u.getTime()+e)))),t&&!t.sky)return;if(this.sceneRenderer.setSkyUnknown(!u),!u){this.sceneRenderer.setAstronomy(a6);return}const g=new Date(u.getTime()+e),y=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/Pl.DEG_PER_SECOND*1e3)),w=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),b=`${Math.floor(g.getTime()/y)}|${Math.round(h/w)}|${Math.round(d/w)}|${Math.round(p.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(b===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=b;const M=Ti("Sun",g,p),S=Ti("Moon",g,p);let E=Qi.separationOf(M,S)<1?Qi.viewAt(g,p):void 0;if(E){const R=Qi.offsetOf(M,S,E.separationDeg);if(E.obscuration>Tt.LIMB_FROM_OBSCURATION){const O=this.limbFor(g,p);O&&(E={...E,obscuration:1-rr.uncoveredFraction(O,E.sunRadiusDeg,R),limb:O})}E={...E,horizonShare:Qi.horizonShare(E,R,M.altitudeDeg,M.azimuthDeg,ts.distanceKm(g,p))}}const x={...M,magnitude:vp("Sun",g)-2.5*Math.log10(Qi.beamFraction(E))};this.lastSun={altitudeDeg:x.altitudeDeg,azimuthDeg:x.azimuthDeg};const T={...S,phase:Xo(g),magnitude:vp("Moon",g),radiusDeg:ts.apparentRadiusDeg(g,p)},D=pT.map(R=>({body:R,position:Ti(R,g,p),magnitude:vp(R,g)}));this.sceneRenderer.setAstronomy({sun:x,moon:T,planets:D,comet:this.cometAt(g,p),novae:Gf.appearancesAt(g,p).map(({outburst:R,position:O,magnitude:N})=>({id:R.id,position:O,magnitude:N})),stars:this.starCatalog?{catalog:this.starCatalog,date:g,observer:p}:void 0,frame:{date:g,observer:p},localHour:((g.getUTCHours()+g.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(d/15)))%24+24)%24,eclipse:E}),this.ufoElement.setSunAltitude(x.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(e,t){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,xd.load(i6).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(e.getTime()-i.atMs)<5e3&&i.lat===t.lat&&i.lng===t.lng&&i.elevationM===t.elevationM)return i.profile;const n=rr.profile(e,t,this.limbRelief);return this.limbCache={profile:n,atMs:e.getTime(),lat:t.lat,lng:t.lng,elevationM:t.elevationM},n}pushSatellitesAt(e,t,i){if(this.ensureSatellites(e),!e||!this.satellites){this.sceneRenderer.setSatellites([]);return}const n=new Date(e.getTime()+t),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(e){const t=this.ufoElement.sighting,i=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=e?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!or.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,Tt.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(o=>or.asReentry(o,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(YS)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(e){const t=this.ensureTraffic(e);if(!t||t.objects.length===0)return e.decor;const i=this.decorMemo;if(i&&i.base===e.decor&&i.traffic===t.objects)return i.merged;const n=[...e.decor,...t.objects];return this.decorMemo={base:e.decor,traffic:t.objects,merged:n},n}seatedDecor(e,t){if(!e.some(r=>r.observerKeyframes?.length))return e;const i=e.map(r=>{if(!r.observerKeyframes?.length)return"";const a=W1(r,t);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===e&&n.seats===i)return n.seated;const s=e.map(r=>{if(!r.observerKeyframes?.length)return r;const a=W1(r,t);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:e,seats:i,seated:s},s}ensureTraffic(e){const t=pt(e,0),i=t?.lng===void 0?void 0:zn(e.event.time??{},t.lng,e.event.utcOffsetHours),n=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||t?.lat===void 0||t.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${t.lat.toFixed(3)},${t.lng.toFixed(3)}|${Math.round(t.elevationM??0)}`;if(this.traffic?.key===r)return this.traffic.set;if(this.upperAirHeardLive=void 0,r===""||s===void 0||t?.lat===void 0||t.lng===void 0){this.traffic={key:r,status:"outside"};return}let a=Tt.aircraftProviders.get(this.aircraftSource.id);if(a||Tt.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const o={key:r,status:"loading",startMs:s,observer:{lat:t.lat,lng:t.lng}};this.traffic=o;const c={lat:t.lat,lng:t.lng,heightM:t.elevationM??0},h=cs.MAX_GAP_S*1e3,d=Tt.SOUND_LOOKBACK_MS,u={lat:t.lat,lng:t.lng,elevationM:t.elevationM??0},p=(f,m)=>f.TrafficDecor.from(o.tracks??[],c,s,f.TrafficDecor.MAX_OBJECTS,{models:m,sunElevationAt:v=>this.sunElevationAt(v,u)});a.between(c,s-d,s+n+h).then(async f=>{if(this.traffic!==o)return;if(f.status!=="found"){o.status=f.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let m;try{m=await Tt.loadTrafficRuntime()}catch{this.traffic===o&&(o.status="unavailable",this.announceTraffic());return}this.traffic===o&&(o.status="ready",o.tracks=f.tracks,o.set=p(m),this.startAircraftSound(o,m),this.announceTraffic(),this.describeTraffic(a,o,m,p),o.set.shown>0&&(this.readUpperAir(o,m,s-d,s+n+h),this.readTrailTraffic(a,o,m,c,s-Tt.TRAIL_LOOKBACK_MS,s+n+h)))})}trafficSunlight(e){const t=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return t;for(const[r,a]of n.presence){if(e<a.fromMs||e>a.untilMs)continue;const o=n.flights.get(r),c=o?cs.positionAt(o,i.startMs+e):void 0;c&&t.set(r,{heightM:c.geo.heightM,sunElevationDeg:fs.sunElevationDeg(s,i.observer,c.geo)})}return t}trafficTooltipAt(e,t){const i=this.sceneRenderer.pickTrafficAt(e,t),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming,r=Tt.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,a=>s.towards(a))}trafficInfoAt(e){const t=this.traffic,i=t?.set?.flights.get(e);if(!t||!i||t.startMs===void 0||!t.observer)return;const n=Tt.trafficRuntime;if(!n)return;const s=t.descriptions?.get(Un.keyOf(i)),r=pt(this.ufoElement.sighting,this.lastTimeMs),a={lat:t.observer.lat,lng:t.observer.lng,heightM:r?.elevationM??0},o=n.AmbientNoise.dbA(_h(this.ufoElement.sighting,this.lastTimeMs)),c=n.TrafficInfos.at(i,s,a,t.startMs+this.lastTimeMs,{ambientDbA:o}),h=c&&this.contrailAt(e,this.lastTimeMs);return c&&h?{...c,contrail:h}:c}contrailAt(e,t){const i=this.traffic?.contrails?.find(s=>s.id===e);if(!i)return;let n;for(const s of i.points){if(s.tMs>t)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(e,t){this.aircraftAudio??=this.newAircraftAudio(t),this.sortOutAudible(e,t)}sortOutAudible(e,t){!e.set||!e.observer||(e.audible=t.TrafficSound.candidates(e.set.flights,e.descriptions??new Map,Un.keyOf,{...e.observer,heightM:0},{ambientDbA:t.AmbientNoise.BASE_DB_A}))}pushAircraftSound(e,t){this.startDecorAircraftSound(e),this.startBodySound();const i=this.aircraftAudio;if(!i)return;const n=Tt.trafficRuntime;if(!n){i.setVoices([]);return}const s=pt(e,t),r=_h(e,t),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},o=this.trafficVoices(t,s,a,n),c=e.event.place?.[0],h={lat:s?.lat??c?.lat,lng:s?.lng??c?.lng};h.lat!==void 0&&h.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,o.push(...this.decorAircraftHearing.voices(e,t,{lat:h.lat,lng:h.lng,heightM:s?.elevationM??0},a,d=>this.decorModelSounds.get(d.model?.id??""))),o.push(...this.bodyVoices(e,t,a,n)),o.sort((d,u)=>u.levelDbA-d.levelDbA),o.length=Math.min(o.length,4)),i.setVoices(o,s?.headingDeg??0)}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(e=>e.sound)||(Tt.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(Tt.trafficRuntime):Tt.loadTrafficRuntime().catch(()=>{}))}bodyVoices(e,t,i,n){const s=this.interpretationShown,r=e.event.place?.[0];if(!s||!r||!s.bodies.some(p=>p.sound))return[];const a=this.sceneRenderer.bodyGround,o=p=>qe.eyeOf(e,p,a),c=o(t);if(!c)return[];const h=new Map,d=(p,f)=>{let m=h.get(p.id);return m||h.set(p.id,m=new qe(p,a,o)),m.at(f)};this.bodyHearing??=new n.BodyHearing;const u=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(s.bodies,d,c,r,t,u,i)}trafficVoices(e,t,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:t?.elevationM??0};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,Un.keyOf,a,s.startMs+e,i)}startDecorAircraftSound(e){const t=e.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(t.length!==0){for(const i of t){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||Tt.trafficRuntime){!this.aircraftAudio&&Tt.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(Tt.trafficRuntime));return}Tt.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(e){const t=new e.AircraftAudio;return t.setLevel(this.ufoElement.level),this.interacted&&t.resume(),t.setPaused(this.ufoElement.playbackState!=="playing"),t}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(QP)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(e,t,i,n){if(!e.describe||!t.set||!t.tracks)return;const s=new Set([...t.set.flights.values()].map(c=>Un.keyOf(c))),r=t.tracks.filter(c=>s.has(Un.keyOf(c))&&c.points.length>0),a=new Map,o=new Map;await Promise.all(r.map(async c=>{const h=new Date(c.points[0].t).toISOString().slice(0,10),d=await e.describe(c,h).catch(()=>{});d&&(o.set(Un.keyOf(c),d),a.set(Un.keyOf(c),i.AircraftModels.of(d)))})),!(this.traffic!==t||a.size===0)&&(t.descriptions=o,t.models=a,t.set=n(i,a),this.planContrails(t,i),this.sortOutAudible(t,i),this.announceTraffic())}async readTrailTraffic(e,t,i,n,s,r){if(t.startMs===void 0)return;const a=await e.between(n,s,r).catch(()=>{});if(this.traffic!==t||a?.status!=="found")return;const o=a.tracks.filter(d=>d.points.some(u=>u.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),c=new Map(t.models??[]);if(e.describe&&await Promise.all(o.filter(d=>d.points.length>0&&!c.has(Un.keyOf(d))).map(async d=>{const u=await e.describe(d,new Date(d.points[0].t).toISOString().slice(0,10)).catch(()=>{});u&&c.set(Un.keyOf(d),i.AircraftModels.of(u))})),this.traffic!==t||t.startMs===void 0)return;const h=i.TrafficDecor.from(o,n,t.startMs,Tt.TRAIL_MAX_AIRCRAFT,{models:c});t.trailSet=Tt.alignTrailIds(h,t.set),t.models=new Map([...c,...t.models??[]]),this.planContrails(t,i),this.announceTraffic()}static alignTrailIds(e,t){if(!t)return e;const i=new Map;for(const[a,o]of t.flights){const c=t.presence.get(a);if(c)for(const[h,d]of e.flights){const u=e.presence.get(h);!u||Un.keyOf(d)!==Un.keyOf(o)||u.fromMs<=c.untilMs&&c.fromMs<=u.untilMs&&i.set(h,a)}}const n=a=>i.get(a)??`${a}-trail`,s=new Set(i.values()),r=t.objects.filter(a=>!s.has(a.id));return{...e,objects:[...e.objects.map(a=>({...a,id:n(a.id)})),...r],presence:new Map([...[...e.presence].map(([a,o])=>[n(a),o]),...r.map(a=>[a.id,t.presence.get(a.id)])]),flights:new Map([...[...e.flights].map(([a,o])=>[n(a),o]),...r.map(a=>[a.id,t.flights.get(a.id)])])}}async readUpperAir(e,t,i,n){if(!e.observer)return;const s=Bi.held(this.ufoElement.sighting.frozen,"upperAir");let r;if(s){const c=St.address(s.src,this.documentUrl);r=Tt.upperAirProviders.get(c),r||Tt.upperAirProviders.set(c,r=new Hc(St.json(c)))}else{const c=this.upperAirSource??t.UPPER_AIR_SOURCES[0];r=Tt.upperAirProviders.get(c.id),r||Tt.upperAirProviders.set(c.id,r=c.create())}const a={lat:e.observer.lat,lng:e.observer.lng},o=await r.between(a,i,n);this.traffic!==e||o.status!=="found"||(s||(this.upperAirHeardLive={...a,startMs:i,endMs:n,answer:o}),e.air=o.samples,e.airSource=o.source,this.planContrails(e,t),this.announceTraffic())}planContrails(e,t){const i=e.trailSet??e.set;!i||!e.air||e.startMs===void 0||(e.contrails=t.AircraftContrails.plan(i,e.models,e.air,e.startMs))}contrailSunlight(e){const t=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 t;for(const r of i.contrails){const a=n.presence.get(r.id),o=n.flights.get(r.id);if(!a||!o)continue;const c=cs.positionAt(o,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,e)));c&&t.set(r.id,{heightM:c.geo.heightM,sunElevationDeg:fs.sunElevationDeg(s,i.observer,c.geo)})}return t}sunElevationAt(e,t){const i=Ti("Sun",new Date(e.t),t);return fs.sunElevationDeg(i,t,e)}upperAirSource;upperAirHeardLive;get upperAirHeard(){return this.upperAirHeardLive}setUpperAirSource(e){e.id!==this.upperAirSource?.id&&(this.upperAirSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(e){e.id!==this.aircraftSource.id&&(this.aircraftSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const e=this.traffic?.contrails?.length?this.upperAirSource??Tt.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:e&&{credit:e.credit,creditUrl:e.creditUrl},status:this.traffic?.status??"none",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(e){const t=e?String(e.getTime()):"";if(t===this.satellitesFor)return;this.satellitesFor=t,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!e){this.satelliteStatus="none";return}this.satelliteStatus="loading";const n=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(XS)))},s=Tt.tleArchive;(async()=>{if(!await s.covers(e))return n("outside");const[r,a]=await Promise.all([s.at(e),ae(()=>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 e=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:e?.coverage,credit:e?.credit,creditUrl:e?.creditUrl}}burningCandidates(){return{reentries:this.ufoElement.sighting.skyEvents?.reentries??[],fireballs:this.fireballs?.reentries??[]}}trafficCandidates(){const e=this.traffic;if(!(e?.status!=="ready"||!e.tracks||e.startMs===void 0))return{tracks:e.tracks,startMs:e.startMs,describe:t=>e.descriptions?.get(Un.keyOf(t))}}satellitePositionsAt(e){const t=this.satellites,i=this.ufoElement.sighting,n=pt(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!(!t||r===void 0||a===void 0))return t.passes.positionsAt(e,{lat:r,lng:a,elevationM:n?.elevationM??0})}satellitePassesDuring(e){const t=this.satellites,i=this.ufoElement.sighting,n=pt(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!t||r===void 0||a===void 0)return[];const o=zn(i.event.time??{},a,i.event.utcOffsetHours);if(!o)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:a,elevationM:n?.elevationM??0},d=JSON.stringify([this.satellitesFor,o.getTime(),r,a,h.elevationM,c]);if(this.satellitePassesMemo?.key===d)return this.satellitePassesMemo.passes;const u=Math.max(10,Math.ceil(c/1e3/600)),p=t.passes.passesDuring(o,new Date(o.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:p},p}cometAt(e,t){const i=Dp.brightestAt(e,t);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}pushPhenomenaAt(e){const t=this.ufoElement.sighting;t!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=t);const i=t.timeline,n=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,r=this.projectionAt(e),a=new Map,o=new Map,c=new Set;for(const f of i.sourceIds){const m=i.getInterpolatedShapeAt(e,f);if(!m)continue;const v={...m,bounds:{...m.bounds,x:m.bounds.x+s.x,y:m.bounds.y+s.y}};a.set(f,v);const g=m.aim?this.sceneRenderer.screenPointOf(Mr.directionOf(m.aim,this.directionScratch)):{ndcX:(v.bounds.x+v.bounds.width/2)/n.width*2-1,ndcY:-((v.bounds.y+v.bounds.height/2)/n.height*2-1)},y=g!==void 0&&Math.abs(g.ndcX)<=1&&Math.abs(g.ndcY)<=1,w=y?this.sceneRenderer.decorDistancesAt(g.ndcX,g.ndcY,f):{};c.add(f),(y||m.aim)&&c.delete(f);const b=m.angular?.widthDeg??r.pxToDeg(m.bounds.width),M=this.sizeEstimateOf(f);M.add(b,w);const S=Sd.of(t,f);o.set(f,as.resolve({hypothesisM:this.distanceHypotheses.get(f),derivedM:S&&b>0?At.distanceMAt(S.widthM,b):void 0,range:M.distanceRangeAt(b),crossing:w}))}for(const[f,m]of a)for(const[v,g]of a){if(v===f||g.transparency>=1||g.bounds.width*g.bounds.height<=m.bounds.width*m.bounds.height||!(m.bounds.x>=g.bounds.x&&m.bounds.y>=g.bounds.y&&m.bounds.x+m.bounds.width<=g.bounds.x+g.bounds.width&&m.bounds.y+m.bounds.height<=g.bounds.y+g.bounds.height))continue;const w=o.get(v);w&&o.set(f,{distanceM:w.distanceM*.999,basis:w.basis});break}this.depths=o;const h=i.sourceIds,d=[];for(const[f,m]of a)d.push({sourceId:f,shape:m,distanceM:o.get(f).distanceM,renderOrder:h.indexOf(f),aim:m.aim,hidden:c.has(f)||this.interpretationShown!==void 0&&(!this.comparing||m.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const p=(pt(t,e)?.rollDeg??0)+ri.bodyAt(t,e,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(d,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:hi.starPointsOf(t.instrument),rollRad:p*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(e){this.interpretationShown=It.expand(os.expand(e)),this.ufoElement.playerTitle=e?.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(e){this.inTheRound=e}get compareAccount(){return this.comparing}set compareAccount(e){e!==this.comparing&&(this.comparing=e,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())}get confrontation(){return this.confrontationReadings}groundAlong(e,t,i){const n=this.sceneRenderer.bodyGround,s=qe.eyeOf(this.ufoElement.sighting,i,n);return s?qe.lineOfSightMeetsGround(s,e,t,n):void 0}bodyMaskedBy(e,t){return this.sceneRenderer.bodyMaskedByDecor(e,t)}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=u=>qe.eyeOf(n,u,i),r=new qe(e,i,s).at(t),a=s(t);if(!r||!a)return;const o=r.eastM-a.eastM,c=r.northM-a.northM,h=r.upM-a.upM,d=Math.hypot(o,c);return{azimuthDeg:(Math.atan2(o,c)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,d)*180/Math.PI,distanceM:Math.hypot(d,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(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=o=>qe.eyeOf(n,o,i),r=new qe(e,i,s).at(t),a=s(t);return r&&a?Ai.projectionOf(r,a):void 0}directionToBody(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=f=>qe.eyeOf(n,f,i),r=new qe(e,i,s),a=r.at(t)?t:e.track[0]?.t,o=a===void 0?void 0:r.at(a),c=a===void 0?void 0:s(a);if(!o||!c)return;const h=o.eastM-c.eastM,d=o.northM-c.northM,u=o.upM-c.upM,p=Math.hypot(h,d);if(!(p===0&&u===0))return{azimuthDeg:(Math.atan2(h,d)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(u,p)*180/Math.PI}}placeBodiesAt(e,t){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,o=f=>qe.eyeOf(n,f,a);i&&(s=i.bodies.map(f=>new qe(f,a,o).at(e)).filter(f=>f!==void 0));const c=en(n,e),h=c.windDirectionDeg*Math.PI/180,d={x:c.windSpeed*Math.sin(h),z:-c.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(s,e/1e3,i?.bodies.map(f=>f.id)??[],i?.smoke??[],d);const u=i&&this.comparing?o(e):void 0;if(u&&(r=new Ai(n.timeline,this.confrontationTolerance).at(e,s,u,f=>f.outlineNode?this.sceneRenderer.bodyOutline?.(f.id,f.outlineNode):void 0)),this.confrontationReadings=r,!t)return;const p=JSON.stringify(r);p!==this.confrontationSignature&&(this.confrontationSignature=p,this.dispatchEvent(new CustomEvent(e6,{detail:r})))}setDistanceHypothesis(e,t){t===void 0||!(t>0)?this.distanceHypotheses.delete(e):this.distanceHypotheses.set(e,t),this.updateAstronomy(this.lastTimeMs)}depthOf(e){return this.depths.get(e)}sizeRangeOf(e){return this.sizeEstimateOf(e).sizeRange}distanceRangeAt(e,t){const i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e);if(!i)return{};const n=i.angular?.widthDeg??this.projectionAt(t).pxToDeg(i.bounds.width);return this.sizeEstimateOf(e).distanceRangeAt(n)}sizeContradictory(e){return this.sizeEstimateOf(e).contradictory}updateMeteorShower(e,t){this.ensureMeteorSchedule(e),this.sceneRenderer.updateMeteors(t)}updateLightning(e,t,i){if(this.ensureLightningSchedule(e),this.sceneRenderer.updateLightning(t),i)return;const n=this.lastLightningT;if(this.lastLightningT=t,n===void 0||t<n||this.ufoElement.playbackState!=="playing")return;const s=this.lightningFlashes.filter(r=>r.t>n&&r.t<=t).pop();s&&en(e,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(e){const t=en(e,0).precipitationIntensity,i=`${this.meteorInputsOf(e)}|${t}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const n=e.event.time,s=e.event.place?.[0],r=n?.year!==void 0?zn(n,s?.lng??0,e.event.utcOffsetHours):void 0,a=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,o=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=xn.schedule({durationMs:a,seed:o,intensity:t}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(e){const t=this.meteorInputsOf(e);t!==this.meteorScheduleFor&&(this.meteorScheduleFor=t,this.scheduleMeteors(e))}meteorInputsOf(e){const t=e.event.place?.[0],i=e.event.time;return JSON.stringify([t?.lat,t?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,e.event.utcOffsetHours,e.event.durationSeconds,e.timeline.duration])}scheduleMeteors(e){const t=e.event.place?.[0],i=e.event.time,n=t?.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?zn(i,t.lng,e.event.utcOffsetHours):void 0;if(!n||t?.lat===void 0||t.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:t.lat,lng:t.lng,elevationM:0},r=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,a=Math.round(n.getTime()/1e3)+Math.round(t.lat*1e3),o=Ui.schedule({ratePerHour:Ui.observedRatePerHour(Ui.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:Ui.TYPICAL_VELOCITY_KM_S,seed:a}),c=sh.activeAt(n).map(d=>{const u=sh.radiantPosition(d.shower,n,s);return{entry:d,position:u,rate:sh.observedRatePerHour(d.zhr,u.altitudeDeg,d.shower.populationIndex)}}).sort((d,u)=>u.rate-d.rate)[0];if(!c||c.rate<=0){this.sceneRenderer.setMeteorShower(o,0,0);return}const h=Ir.schedule({ratePerHour:c.rate,durationMs:r,velocityKmS:c.entry.shower.velocityKmS,seed:a+1});this.sceneRenderer.setMeteorShower([...h,...o],c.position.altitudeDeg,c.position.azimuthDeg)}groundHides(e,t){return this.sceneRenderer.groundHidesDirection(e,t)}get groundKey(){return this.sceneRenderer.groundKey}meteorByRank(e,t=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)<=t).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[e%i.length],s=this.sceneRenderer.meteorMidpoint(n);if(s)return{t:Math.round(n.t+n.durationMs*.45),...s}}lensOpticsAt(e){const t=this.ufoElement.sighting,i=t.instrument,n=i.frame,s=pt(t,e),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=hi.focalLengthMmFor(i,Oi.fovOf(t,e));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return Os.of(t.instrument,At.CANVAS_HEIGHT_PX,Oi.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new VP,this.sizeEstimates.set(e,t)),t}}const Vf="rr0-scene";function o6(){cm(),customElements.get(Vf)||customElements.define(Vf,Tt)}class Vb{constructor(e,t,i=Vb.TOLERANCE_PX){this.timeline=e,this.clock=t,this.tolerancePx=i}static TOLERANCE_PX=1;currentPointer=null;shapePrototype=null;sourceId="";samples=[];start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.samples=[],this.clock.start(i=>this.recordSample(i))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop(),this.thin()}thin(){const e=this.samples;if(e.length<=2)return;const t=new Set([0,e.length-1]),i=[[0,e.length-1]];for(;i.length>0;){const[n,s]=i.pop(),r=e[n],a=e[s];let o=0,c=-1;for(let h=n+1;h<s;h++){const d=e[h],u=(d.t-r.t)/(a.t-r.t),p=Math.hypot(r.x+(a.x-r.x)*u-d.x,r.y+(a.y-r.y)*u-d.y);p>o&&(o=p,c=h)}c!==-1&&o>this.tolerancePx&&(t.add(c),i.push([n,c],[c,s]))}e.forEach((n,s)=>{t.has(s)||this.timeline.removeShapeAt(n.t,this.sourceId)}),this.samples=[]}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=px(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}]),this.samples[this.samples.length-1]?.t===e&&this.samples.pop(),this.samples.push({t:e,x:this.currentPointer.x,y:this.currentPointer.y})}}class l6{constructor(e){this.intervalMs=e}rafId=null;startTime=0;lastTick=0;start(e){this.startTime=performance.now(),this.lastTick=0;const t=()=>{const i=performance.now()-this.startTime;i-this.lastTick>=this.intervalMs&&(this.lastTick=i,e(i)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}class Ra{constructor(e,t,i,n={}){this.id=e,this.aspect=t,this.parts=i,this.minimum=n}static ALL=[new Ra("triangle",.9,[{points:[[.5,0],[1,1],[0,1]],fx:0,fy:0,fw:1,fh:1}]),new Ra("saucer",.6,[{part:"dome",fx:.28,fy:0,fw:.44,fh:.62},{part:"disc",fx:0,fy:.42,fw:1,fh:.42}]),new Ra("cigar",.25,[{fx:0,fy:0,fw:1,fh:1}]),new Ra("chevron",.55,[{points:[[.5,0],[1,1],[.5,.6],[0,1]],fx:0,fy:0,fw:1,fh:1}]),new Ra("light",1,[{fx:.3,fy:.3,fw:.4,fh:.4}],{haloScale:2.5,brightness:.5})];static byId(e){return Ra.ALL.find(t=>t.id===e)}get partNames(){return this.parts.map(e=>e.part)}boundsAt(e){const t=e.width*this.aspect;return{x:e.x,y:e.y+e.height/2-t/2,width:e.width,height:t}}shapesIn(e,t){return this.parts.map(i=>{const n={x:e.x+i.fx*e.width,y:e.y+i.fy*e.height,width:i.fw*e.width,height:i.fh*e.height};return{...i.points?ux(n,i.points.map(([r,a])=>({x:r*n.width,y:a*n.height})),t.color):dx(n,t.color),transparency:t.transparency,haloScale:Math.max(t.haloScale,this.minimum.haloScale??0),blur:t.blur,brightness:Math.max(t.brightness,this.minimum.brightness??0)}})}}const WM="rr0-provider-settings",c6=`
11224
+ ${St.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery:zf.map(t,this.documentUrl)}),this.frozenMap.imagery}frozenMap;setDecorModelProvider(e){this.sceneRenderer.setDecorModelProvider(e)}get decorModelCredits(){return[...new Map(this.sceneRenderer.currentDecorModelCredits.map(t=>[`${t.title}|${t.author??""}|${t.license}|${t.sourceUrl??""}`,t])).values()]}applyFrameFormat(){const e=this.ufoElement.sighting.instrument,t=Tt.CANVAS_HEIGHT_PX,i=hi.frameWidthPx(e,t);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${t}`)}resizeToStage(){const e=this.frameElement.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),i=Math.max(1,Math.round(e.height));this.sceneCanvas.width=t,this.sceneCanvas.height=i,this.sceneRenderer.resize(t,i)}async loadStars(){const e=[{magnitudeLimit:W0,url:this.getAttribute("star-catalog-src")??n6},{magnitudeLimit:Md,url:this.getAttribute("deep-star-catalog-src")??s6}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>W0?Md:W0;const n=await Yr.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=Md||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=Dn.gainFor(e.instrument,{fNumber:pt(e,0)?.fNumber,fieldOfViewDeg:Oi.fovOf(e,0),exposureSeconds:e.exposure});return ea(r6,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=Er.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,n=this.degreesPerPixelAt(e),s=Pl.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(e).length,Er.instants(this.decorWithTraffic(this.ufoElement.sighting),pt(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(t.fromMs+t.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-1)*s/r),stepMs:t.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(e){const t=this.sceneCanvas.height;return t<=0?0:Oi.fovOf(this.ufoElement.sighting,e)/t}roadGradeAt(e,t){return e.observerTrack.allKeyframes.length<2?0:Pc.at(e,t,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(e,t){const i=this.ufoElement.sighting;this.setWeather(_h(i,e)),this.sceneRenderer.setInstrument(i.instrument),this.sceneRenderer.setLightPollution(i.lightPollution),t||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,e)),t||this.pushAircraftSound(i,e),this.updateMeteorShower(i,e),this.updateLightning(i,e,t!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(i),e)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??Et.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(e)),this.sceneRenderer.setContrails(this.traffic?.contrails??Et.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(e));const n=pt(i,e);this.sceneRenderer.setReferences(i.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0);const s=pt(i,0),r=en(i,0),a=zn(i.event.time??{},n?.lng??op.lng,i.event.utcOffsetHours),o=i.weatherSource!==void 0&&a?YA(a):void 0,c=Object.fromEntries(xo(en(i,e)).map(R=>[R.id,ef(e,i.weatherTrack,r,s,n,R.id,R.instances?.length?void 0:o)]));this.sceneRenderer.setCloudOffset(ef(e,i.weatherTrack,r,s,n,void 0,o),c),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,e)}:op),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(Dn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:Oi.fovOf(i,e),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,Ci.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso,i.metering),this.sceneRenderer.setLensGhosts(bi.optics(i.instrument,n?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(e/1e3))),this.sceneRenderer.setPerception(Ol.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(ri.bodyAt(i,e,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(pt(i,0),n,e),this.placeBodiesAt(e,t===void 0),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),this.applyFrozen(i.frozen),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,e)),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(e);const h=n?.lat??op.lat,d=n?.lng??op.lng,u=zn(i.event.time??{},d,i.event.utcOffsetHours),p={lat:h,lng:d,elevationM:n?.elevationM??0};this.pushSatellitesAt(u,e,p),this.ensureFireballs(u);const f=i.skyEvents,m=[...f?.reentries??[],...this.fireballs?.reentries??[]];this.sceneRenderer.setReentries(m.length===0?[]:_t.viewsAt(m,e,{lat:h,lng:d,heightM:p.elevationM})),this.sceneRenderer.setBeams(f?.beams??Et.NO_BEAMS);const v=f?.launches??[];if(this.sceneRenderer.setLaunchPlumes(v.length===0||!u?[]:Le.viewsAt(v,e,{lat:h,lng:d,heightM:p.elevationM},Le.sunDirectionAt(new Date(u.getTime()+e)))),t&&!t.sky)return;if(this.sceneRenderer.setSkyUnknown(!u),!u){this.sceneRenderer.setAstronomy(a6);return}const g=new Date(u.getTime()+e),y=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/Pl.DEG_PER_SECOND*1e3)),w=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),b=`${Math.floor(g.getTime()/y)}|${Math.round(h/w)}|${Math.round(d/w)}|${Math.round(p.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(b===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=b;const M=Ti("Sun",g,p),S=Ti("Moon",g,p);let E=Qi.separationOf(M,S)<1?Qi.viewAt(g,p):void 0;if(E){const R=Qi.offsetOf(M,S,E.separationDeg);if(E.obscuration>Et.LIMB_FROM_OBSCURATION){const O=this.limbFor(g,p);O&&(E={...E,obscuration:1-rr.uncoveredFraction(O,E.sunRadiusDeg,R),limb:O})}E={...E,horizonShare:Qi.horizonShare(E,R,M.altitudeDeg,M.azimuthDeg,ts.distanceKm(g,p))}}const x={...M,magnitude:vp("Sun",g)-2.5*Math.log10(Qi.beamFraction(E))};this.lastSun={altitudeDeg:x.altitudeDeg,azimuthDeg:x.azimuthDeg};const T={...S,phase:Xo(g),magnitude:vp("Moon",g),radiusDeg:ts.apparentRadiusDeg(g,p)},D=pT.map(R=>({body:R,position:Ti(R,g,p),magnitude:vp(R,g)}));this.sceneRenderer.setAstronomy({sun:x,moon:T,planets:D,comet:this.cometAt(g,p),novae:Gf.appearancesAt(g,p).map(({outburst:R,position:O,magnitude:N})=>({id:R.id,position:O,magnitude:N})),stars:this.starCatalog?{catalog:this.starCatalog,date:g,observer:p}:void 0,frame:{date:g,observer:p},localHour:((g.getUTCHours()+g.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(d/15)))%24+24)%24,eclipse:E}),this.ufoElement.setSunAltitude(x.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(e,t){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,xd.load(i6).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(e.getTime()-i.atMs)<5e3&&i.lat===t.lat&&i.lng===t.lng&&i.elevationM===t.elevationM)return i.profile;const n=rr.profile(e,t,this.limbRelief);return this.limbCache={profile:n,atMs:e.getTime(),lat:t.lat,lng:t.lng,elevationM:t.elevationM},n}pushSatellitesAt(e,t,i){if(this.ensureSatellites(e),!e||!this.satellites){this.sceneRenderer.setSatellites([]);return}const n=new Date(e.getTime()+t),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(e){const t=this.ufoElement.sighting,i=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=e?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!or.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,Et.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(o=>or.asReentry(o,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(YS)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(e){const t=this.ensureTraffic(e);if(!t||t.objects.length===0)return e.decor;const i=this.decorMemo;if(i&&i.base===e.decor&&i.traffic===t.objects)return i.merged;const n=[...e.decor,...t.objects];return this.decorMemo={base:e.decor,traffic:t.objects,merged:n},n}seatedDecor(e,t){if(!e.some(r=>r.observerKeyframes?.length))return e;const i=e.map(r=>{if(!r.observerKeyframes?.length)return"";const a=W1(r,t);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===e&&n.seats===i)return n.seated;const s=e.map(r=>{if(!r.observerKeyframes?.length)return r;const a=W1(r,t);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:e,seats:i,seated:s},s}ensureTraffic(e){const t=pt(e,0),i=t?.lng===void 0?void 0:zn(e.event.time??{},t.lng,e.event.utcOffsetHours),n=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||t?.lat===void 0||t.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${t.lat.toFixed(3)},${t.lng.toFixed(3)}|${Math.round(t.elevationM??0)}`;if(this.traffic?.key===r)return this.traffic.set;if(this.upperAirHeardLive=void 0,r===""||s===void 0||t?.lat===void 0||t.lng===void 0){this.traffic={key:r,status:"outside"};return}let a=Et.aircraftProviders.get(this.aircraftSource.id);if(a||Et.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const o={key:r,status:"loading",startMs:s,observer:{lat:t.lat,lng:t.lng}};this.traffic=o;const c={lat:t.lat,lng:t.lng,heightM:t.elevationM??0},h=cs.MAX_GAP_S*1e3,d=Et.SOUND_LOOKBACK_MS,u={lat:t.lat,lng:t.lng,elevationM:t.elevationM??0},p=(f,m)=>f.TrafficDecor.from(o.tracks??[],c,s,f.TrafficDecor.MAX_OBJECTS,{models:m,sunElevationAt:v=>this.sunElevationAt(v,u)});a.between(c,s-d,s+n+h).then(async f=>{if(this.traffic!==o)return;if(f.status!=="found"){o.status=f.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let m;try{m=await Et.loadTrafficRuntime()}catch{this.traffic===o&&(o.status="unavailable",this.announceTraffic());return}this.traffic===o&&(o.status="ready",o.tracks=f.tracks,o.set=p(m),this.startAircraftSound(o,m),this.announceTraffic(),this.describeTraffic(a,o,m,p),o.set.shown>0&&(this.readUpperAir(o,m,s-d,s+n+h),this.readTrailTraffic(a,o,m,c,s-Et.TRAIL_LOOKBACK_MS,s+n+h)))})}trafficSunlight(e){const t=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return t;for(const[r,a]of n.presence){if(e<a.fromMs||e>a.untilMs)continue;const o=n.flights.get(r),c=o?cs.positionAt(o,i.startMs+e):void 0;c&&t.set(r,{heightM:c.geo.heightM,sunElevationDeg:fs.sunElevationDeg(s,i.observer,c.geo)})}return t}trafficTooltipAt(e,t){const i=this.sceneRenderer.pickTrafficAt(e,t),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming,r=Et.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,a=>s.towards(a))}trafficInfoAt(e){const t=this.traffic,i=t?.set?.flights.get(e);if(!t||!i||t.startMs===void 0||!t.observer)return;const n=Et.trafficRuntime;if(!n)return;const s=t.descriptions?.get(Un.keyOf(i)),r=pt(this.ufoElement.sighting,this.lastTimeMs),a={lat:t.observer.lat,lng:t.observer.lng,heightM:r?.elevationM??0},o=n.AmbientNoise.dbA(_h(this.ufoElement.sighting,this.lastTimeMs)),c=n.TrafficInfos.at(i,s,a,t.startMs+this.lastTimeMs,{ambientDbA:o}),h=c&&this.contrailAt(e,this.lastTimeMs);return c&&h?{...c,contrail:h}:c}contrailAt(e,t){const i=this.traffic?.contrails?.find(s=>s.id===e);if(!i)return;let n;for(const s of i.points){if(s.tMs>t)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(e,t){this.aircraftAudio??=this.newAircraftAudio(t),this.sortOutAudible(e,t)}sortOutAudible(e,t){!e.set||!e.observer||(e.audible=t.TrafficSound.candidates(e.set.flights,e.descriptions??new Map,Un.keyOf,{...e.observer,heightM:0},{ambientDbA:t.AmbientNoise.BASE_DB_A}))}pushAircraftSound(e,t){this.startDecorAircraftSound(e),this.startBodySound();const i=this.aircraftAudio;if(!i)return;const n=Et.trafficRuntime;if(!n){i.setVoices([]);return}const s=pt(e,t),r=_h(e,t),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},o=this.trafficVoices(t,s,a,n),c=e.event.place?.[0],h={lat:s?.lat??c?.lat,lng:s?.lng??c?.lng};h.lat!==void 0&&h.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,o.push(...this.decorAircraftHearing.voices(e,t,{lat:h.lat,lng:h.lng,heightM:s?.elevationM??0},a,d=>this.decorModelSounds.get(d.model?.id??""))),o.push(...this.bodyVoices(e,t,a,n)),o.sort((d,u)=>u.levelDbA-d.levelDbA),o.length=Math.min(o.length,4)),i.setVoices(o,s?.headingDeg??0)}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(e=>e.sound)||(Et.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(Et.trafficRuntime):Et.loadTrafficRuntime().catch(()=>{}))}bodyVoices(e,t,i,n){const s=this.interpretationShown,r=e.event.place?.[0];if(!s||!r||!s.bodies.some(p=>p.sound))return[];const a=this.sceneRenderer.bodyGround,o=p=>qe.eyeOf(e,p,a),c=o(t);if(!c)return[];const h=new Map,d=(p,f)=>{let m=h.get(p.id);return m||h.set(p.id,m=new qe(p,a,o)),m.at(f)};this.bodyHearing??=new n.BodyHearing;const u=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(s.bodies,d,c,r,t,u,i)}trafficVoices(e,t,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:t?.elevationM??0};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,Un.keyOf,a,s.startMs+e,i)}startDecorAircraftSound(e){const t=e.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(t.length!==0){for(const i of t){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||Et.trafficRuntime){!this.aircraftAudio&&Et.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(Et.trafficRuntime));return}Et.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(e){const t=new e.AircraftAudio;return t.setLevel(this.ufoElement.level),this.interacted&&t.resume(),t.setPaused(this.ufoElement.playbackState!=="playing"),t}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(QP)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(e,t,i,n){if(!e.describe||!t.set||!t.tracks)return;const s=new Set([...t.set.flights.values()].map(c=>Un.keyOf(c))),r=t.tracks.filter(c=>s.has(Un.keyOf(c))&&c.points.length>0),a=new Map,o=new Map;await Promise.all(r.map(async c=>{const h=new Date(c.points[0].t).toISOString().slice(0,10),d=await e.describe(c,h).catch(()=>{});d&&(o.set(Un.keyOf(c),d),a.set(Un.keyOf(c),i.AircraftModels.of(d)))})),!(this.traffic!==t||a.size===0)&&(t.descriptions=o,t.models=a,t.set=n(i,a),this.planContrails(t,i),this.sortOutAudible(t,i),this.announceTraffic())}async readTrailTraffic(e,t,i,n,s,r){if(t.startMs===void 0)return;const a=await e.between(n,s,r).catch(()=>{});if(this.traffic!==t||a?.status!=="found")return;const o=a.tracks.filter(d=>d.points.some(u=>u.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),c=new Map(t.models??[]);if(e.describe&&await Promise.all(o.filter(d=>d.points.length>0&&!c.has(Un.keyOf(d))).map(async d=>{const u=await e.describe(d,new Date(d.points[0].t).toISOString().slice(0,10)).catch(()=>{});u&&c.set(Un.keyOf(d),i.AircraftModels.of(u))})),this.traffic!==t||t.startMs===void 0)return;const h=i.TrafficDecor.from(o,n,t.startMs,Et.TRAIL_MAX_AIRCRAFT,{models:c});t.trailSet=Et.alignTrailIds(h,t.set),t.models=new Map([...c,...t.models??[]]),this.planContrails(t,i),this.announceTraffic()}static alignTrailIds(e,t){if(!t)return e;const i=new Map;for(const[a,o]of t.flights){const c=t.presence.get(a);if(c)for(const[h,d]of e.flights){const u=e.presence.get(h);!u||Un.keyOf(d)!==Un.keyOf(o)||u.fromMs<=c.untilMs&&c.fromMs<=u.untilMs&&i.set(h,a)}}const n=a=>i.get(a)??`${a}-trail`,s=new Set(i.values()),r=t.objects.filter(a=>!s.has(a.id));return{...e,objects:[...e.objects.map(a=>({...a,id:n(a.id)})),...r],presence:new Map([...[...e.presence].map(([a,o])=>[n(a),o]),...r.map(a=>[a.id,t.presence.get(a.id)])]),flights:new Map([...[...e.flights].map(([a,o])=>[n(a),o]),...r.map(a=>[a.id,t.flights.get(a.id)])])}}async readUpperAir(e,t,i,n){if(!e.observer)return;const s=Bi.held(this.ufoElement.sighting.frozen,"upperAir");let r;if(s){const c=St.address(s.src,this.documentUrl);r=Et.upperAirProviders.get(c),r||Et.upperAirProviders.set(c,r=new Hc(St.json(c)))}else{const c=this.upperAirSource??t.UPPER_AIR_SOURCES[0];r=Et.upperAirProviders.get(c.id),r||Et.upperAirProviders.set(c.id,r=c.create())}const a={lat:e.observer.lat,lng:e.observer.lng},o=await r.between(a,i,n);this.traffic!==e||o.status!=="found"||(s||(this.upperAirHeardLive={...a,startMs:i,endMs:n,answer:o}),e.air=o.samples,e.airSource=o.source,this.planContrails(e,t),this.announceTraffic())}planContrails(e,t){const i=e.trailSet??e.set;!i||!e.air||e.startMs===void 0||(e.contrails=t.AircraftContrails.plan(i,e.models,e.air,e.startMs))}contrailSunlight(e){const t=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 t;for(const r of i.contrails){const a=n.presence.get(r.id),o=n.flights.get(r.id);if(!a||!o)continue;const c=cs.positionAt(o,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,e)));c&&t.set(r.id,{heightM:c.geo.heightM,sunElevationDeg:fs.sunElevationDeg(s,i.observer,c.geo)})}return t}sunElevationAt(e,t){const i=Ti("Sun",new Date(e.t),t);return fs.sunElevationDeg(i,t,e)}upperAirSource;upperAirHeardLive;get upperAirHeard(){return this.upperAirHeardLive}setUpperAirSource(e){e.id!==this.upperAirSource?.id&&(this.upperAirSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(e){e.id!==this.aircraftSource.id&&(this.aircraftSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const e=this.traffic?.contrails?.length?this.upperAirSource??Et.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:e&&{credit:e.credit,creditUrl:e.creditUrl},status:this.traffic?.status??"none",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(e){const t=e?String(e.getTime()):"";if(t===this.satellitesFor)return;this.satellitesFor=t,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!e){this.satelliteStatus="none";return}this.satelliteStatus="loading";const n=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(XS)))},s=Et.tleArchive;(async()=>{if(!await s.covers(e))return n("outside");const[r,a]=await Promise.all([s.at(e),ae(()=>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 e=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:e?.coverage,credit:e?.credit,creditUrl:e?.creditUrl}}burningCandidates(){return{reentries:this.ufoElement.sighting.skyEvents?.reentries??[],fireballs:this.fireballs?.reentries??[]}}trafficCandidates(){const e=this.traffic;if(!(e?.status!=="ready"||!e.tracks||e.startMs===void 0))return{tracks:e.tracks,startMs:e.startMs,describe:t=>e.descriptions?.get(Un.keyOf(t))}}satellitePositionsAt(e){const t=this.satellites,i=this.ufoElement.sighting,n=pt(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!(!t||r===void 0||a===void 0))return t.passes.positionsAt(e,{lat:r,lng:a,elevationM:n?.elevationM??0})}satellitePassesDuring(e){const t=this.satellites,i=this.ufoElement.sighting,n=pt(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!t||r===void 0||a===void 0)return[];const o=zn(i.event.time??{},a,i.event.utcOffsetHours);if(!o)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:a,elevationM:n?.elevationM??0},d=JSON.stringify([this.satellitesFor,o.getTime(),r,a,h.elevationM,c]);if(this.satellitePassesMemo?.key===d)return this.satellitePassesMemo.passes;const u=Math.max(10,Math.ceil(c/1e3/600)),p=t.passes.passesDuring(o,new Date(o.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:p},p}cometAt(e,t){const i=Dp.brightestAt(e,t);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}pushPhenomenaAt(e){const t=this.ufoElement.sighting;t!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=t);const i=t.timeline,n=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,r=this.projectionAt(e),a=new Map,o=new Map,c=new Set;for(const f of i.sourceIds){const m=i.getInterpolatedShapeAt(e,f);if(!m)continue;const v={...m,bounds:{...m.bounds,x:m.bounds.x+s.x,y:m.bounds.y+s.y}};a.set(f,v);const g=m.aim?this.sceneRenderer.screenPointOf(Mr.directionOf(m.aim,this.directionScratch)):{ndcX:(v.bounds.x+v.bounds.width/2)/n.width*2-1,ndcY:-((v.bounds.y+v.bounds.height/2)/n.height*2-1)},y=g!==void 0&&Math.abs(g.ndcX)<=1&&Math.abs(g.ndcY)<=1,w=y?this.sceneRenderer.decorDistancesAt(g.ndcX,g.ndcY,f):{};c.add(f),(y||m.aim)&&c.delete(f);const b=m.angular?.widthDeg??r.pxToDeg(m.bounds.width),M=this.sizeEstimateOf(f);M.add(b,w);const S=Sd.of(t,f);o.set(f,as.resolve({hypothesisM:this.distanceHypotheses.get(f),derivedM:S&&b>0?Tt.distanceMAt(S.widthM,b):void 0,range:M.distanceRangeAt(b),crossing:w}))}for(const[f,m]of a)for(const[v,g]of a){if(v===f||g.transparency>=1||g.bounds.width*g.bounds.height<=m.bounds.width*m.bounds.height||!(m.bounds.x>=g.bounds.x&&m.bounds.y>=g.bounds.y&&m.bounds.x+m.bounds.width<=g.bounds.x+g.bounds.width&&m.bounds.y+m.bounds.height<=g.bounds.y+g.bounds.height))continue;const w=o.get(v);w&&o.set(f,{distanceM:w.distanceM*.999,basis:w.basis});break}this.depths=o;const h=i.sourceIds,d=[];for(const[f,m]of a)d.push({sourceId:f,shape:m,distanceM:o.get(f).distanceM,renderOrder:h.indexOf(f),aim:m.aim,hidden:c.has(f)||this.interpretationShown!==void 0&&(!this.comparing||m.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const p=(pt(t,e)?.rollDeg??0)+ri.bodyAt(t,e,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(d,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:hi.starPointsOf(t.instrument),rollRad:p*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(e){this.interpretationShown=It.expand(os.expand(e)),this.ufoElement.playerTitle=e?.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(e){this.inTheRound=e}get compareAccount(){return this.comparing}set compareAccount(e){e!==this.comparing&&(this.comparing=e,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())}get confrontation(){return this.confrontationReadings}groundAlong(e,t,i){const n=this.sceneRenderer.bodyGround,s=qe.eyeOf(this.ufoElement.sighting,i,n);return s?qe.lineOfSightMeetsGround(s,e,t,n):void 0}bodyMaskedBy(e,t){return this.sceneRenderer.bodyMaskedByDecor(e,t)}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=u=>qe.eyeOf(n,u,i),r=new qe(e,i,s).at(t),a=s(t);if(!r||!a)return;const o=r.eastM-a.eastM,c=r.northM-a.northM,h=r.upM-a.upM,d=Math.hypot(o,c);return{azimuthDeg:(Math.atan2(o,c)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,d)*180/Math.PI,distanceM:Math.hypot(d,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(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=o=>qe.eyeOf(n,o,i),r=new qe(e,i,s).at(t),a=s(t);return r&&a?Ai.projectionOf(r,a):void 0}directionToBody(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=f=>qe.eyeOf(n,f,i),r=new qe(e,i,s),a=r.at(t)?t:e.track[0]?.t,o=a===void 0?void 0:r.at(a),c=a===void 0?void 0:s(a);if(!o||!c)return;const h=o.eastM-c.eastM,d=o.northM-c.northM,u=o.upM-c.upM,p=Math.hypot(h,d);if(!(p===0&&u===0))return{azimuthDeg:(Math.atan2(h,d)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(u,p)*180/Math.PI}}placeBodiesAt(e,t){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,o=f=>qe.eyeOf(n,f,a);i&&(s=i.bodies.map(f=>new qe(f,a,o).at(e)).filter(f=>f!==void 0));const c=en(n,e),h=c.windDirectionDeg*Math.PI/180,d={x:c.windSpeed*Math.sin(h),z:-c.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(s,e/1e3,i?.bodies.map(f=>f.id)??[],i?.smoke??[],d);const u=i&&this.comparing?o(e):void 0;if(u&&(r=new Ai(n.timeline,this.confrontationTolerance).at(e,s,u,f=>f.outlineNode?this.sceneRenderer.bodyOutline?.(f.id,f.outlineNode):void 0)),this.confrontationReadings=r,!t)return;const p=JSON.stringify(r);p!==this.confrontationSignature&&(this.confrontationSignature=p,this.dispatchEvent(new CustomEvent(e6,{detail:r})))}setDistanceHypothesis(e,t){t===void 0||!(t>0)?this.distanceHypotheses.delete(e):this.distanceHypotheses.set(e,t),this.updateAstronomy(this.lastTimeMs)}depthOf(e){return this.depths.get(e)}sizeRangeOf(e){return this.sizeEstimateOf(e).sizeRange}distanceRangeAt(e,t){const i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e);if(!i)return{};const n=i.angular?.widthDeg??this.projectionAt(t).pxToDeg(i.bounds.width);return this.sizeEstimateOf(e).distanceRangeAt(n)}sizeContradictory(e){return this.sizeEstimateOf(e).contradictory}updateMeteorShower(e,t){this.ensureMeteorSchedule(e),this.sceneRenderer.updateMeteors(t)}updateLightning(e,t,i){if(this.ensureLightningSchedule(e),this.sceneRenderer.updateLightning(t),i)return;const n=this.lastLightningT;if(this.lastLightningT=t,n===void 0||t<n||this.ufoElement.playbackState!=="playing")return;const s=this.lightningFlashes.filter(r=>r.t>n&&r.t<=t).pop();s&&en(e,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(e){const t=en(e,0).precipitationIntensity,i=`${this.meteorInputsOf(e)}|${t}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const n=e.event.time,s=e.event.place?.[0],r=n?.year!==void 0?zn(n,s?.lng??0,e.event.utcOffsetHours):void 0,a=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,o=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=xn.schedule({durationMs:a,seed:o,intensity:t}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(e){const t=this.meteorInputsOf(e);t!==this.meteorScheduleFor&&(this.meteorScheduleFor=t,this.scheduleMeteors(e))}meteorInputsOf(e){const t=e.event.place?.[0],i=e.event.time;return JSON.stringify([t?.lat,t?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,e.event.utcOffsetHours,e.event.durationSeconds,e.timeline.duration])}scheduleMeteors(e){const t=e.event.place?.[0],i=e.event.time,n=t?.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?zn(i,t.lng,e.event.utcOffsetHours):void 0;if(!n||t?.lat===void 0||t.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:t.lat,lng:t.lng,elevationM:0},r=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,a=Math.round(n.getTime()/1e3)+Math.round(t.lat*1e3),o=Ui.schedule({ratePerHour:Ui.observedRatePerHour(Ui.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:Ui.TYPICAL_VELOCITY_KM_S,seed:a}),c=sh.activeAt(n).map(d=>{const u=sh.radiantPosition(d.shower,n,s);return{entry:d,position:u,rate:sh.observedRatePerHour(d.zhr,u.altitudeDeg,d.shower.populationIndex)}}).sort((d,u)=>u.rate-d.rate)[0];if(!c||c.rate<=0){this.sceneRenderer.setMeteorShower(o,0,0);return}const h=Ir.schedule({ratePerHour:c.rate,durationMs:r,velocityKmS:c.entry.shower.velocityKmS,seed:a+1});this.sceneRenderer.setMeteorShower([...h,...o],c.position.altitudeDeg,c.position.azimuthDeg)}groundHides(e,t){return this.sceneRenderer.groundHidesDirection(e,t)}get groundKey(){return this.sceneRenderer.groundKey}meteorByRank(e,t=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)<=t).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[e%i.length],s=this.sceneRenderer.meteorMidpoint(n);if(s)return{t:Math.round(n.t+n.durationMs*.45),...s}}lensOpticsAt(e){const t=this.ufoElement.sighting,i=t.instrument,n=i.frame,s=pt(t,e),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=hi.focalLengthMmFor(i,Oi.fovOf(t,e));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return Os.of(t.instrument,Tt.CANVAS_HEIGHT_PX,Oi.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new VP,this.sizeEstimates.set(e,t)),t}}const Vf="rr0-scene";function o6(){cm(),customElements.get(Vf)||customElements.define(Vf,Et)}class Vb{constructor(e,t,i=Vb.TOLERANCE_PX){this.timeline=e,this.clock=t,this.tolerancePx=i}static TOLERANCE_PX=1;currentPointer=null;shapePrototype=null;sourceId="";samples=[];start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.samples=[],this.clock.start(i=>this.recordSample(i))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop(),this.thin()}thin(){const e=this.samples;if(e.length<=2)return;const t=new Set([0,e.length-1]),i=[[0,e.length-1]];for(;i.length>0;){const[n,s]=i.pop(),r=e[n],a=e[s];let o=0,c=-1;for(let h=n+1;h<s;h++){const d=e[h],u=(d.t-r.t)/(a.t-r.t),p=Math.hypot(r.x+(a.x-r.x)*u-d.x,r.y+(a.y-r.y)*u-d.y);p>o&&(o=p,c=h)}c!==-1&&o>this.tolerancePx&&(t.add(c),i.push([n,c],[c,s]))}e.forEach((n,s)=>{t.has(s)||this.timeline.removeShapeAt(n.t,this.sourceId)}),this.samples=[]}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=px(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}]),this.samples[this.samples.length-1]?.t===e&&this.samples.pop(),this.samples.push({t:e,x:this.currentPointer.x,y:this.currentPointer.y})}}class l6{constructor(e){this.intervalMs=e}rafId=null;startTime=0;lastTick=0;start(e){this.startTime=performance.now(),this.lastTick=0;const t=()=>{const i=performance.now()-this.startTime;i-this.lastTick>=this.intervalMs&&(this.lastTick=i,e(i)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}class Ra{constructor(e,t,i,n={}){this.id=e,this.aspect=t,this.parts=i,this.minimum=n}static ALL=[new Ra("triangle",.9,[{points:[[.5,0],[1,1],[0,1]],fx:0,fy:0,fw:1,fh:1}]),new Ra("saucer",.6,[{part:"dome",fx:.28,fy:0,fw:.44,fh:.62},{part:"disc",fx:0,fy:.42,fw:1,fh:.42}]),new Ra("cigar",.25,[{fx:0,fy:0,fw:1,fh:1}]),new Ra("chevron",.55,[{points:[[.5,0],[1,1],[.5,.6],[0,1]],fx:0,fy:0,fw:1,fh:1}]),new Ra("light",1,[{fx:.3,fy:.3,fw:.4,fh:.4}],{haloScale:2.5,brightness:.5})];static byId(e){return Ra.ALL.find(t=>t.id===e)}get partNames(){return this.parts.map(e=>e.part)}boundsAt(e){const t=e.width*this.aspect;return{x:e.x,y:e.y+e.height/2-t/2,width:e.width,height:t}}shapesIn(e,t){return this.parts.map(i=>{const n={x:e.x+i.fx*e.width,y:e.y+i.fy*e.height,width:i.fw*e.width,height:i.fh*e.height};return{...i.points?ux(n,i.points.map(([r,a])=>({x:r*n.width,y:a*n.height})),t.color):dx(n,t.color),transparency:t.transparency,haloScale:Math.max(t.haloScale,this.minimum.haloScale??0),blur:t.blur,brightness:Math.max(t.brightness,this.minimum.brightness??0)}})}}const WM="rr0-provider-settings",c6=`
11225
11225
  rr0-provider-settings { display: block; }
11226
11226
  rr0-provider-settings .ps-provider { margin: .3em 0; }
11227
11227
  rr0-provider-settings .ps-heading { font-weight: 600; margin-right: .6em; }
@@ -11297,7 +11297,7 @@ ${Wt.rules([],[".model-picker .model-picker-address p"])}
11297
11297
  .model-picker .model-name { font-weight: 600; }
11298
11298
  .model-picker .model-credit { font-size: .8em; color: #666; }
11299
11299
  `;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await ae(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-Bj4DwXU0.js");return{ModelThumbnails:i}},__vite__mapDeps([9,10]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const n=document.createElement("button");n.type="button",n.className="model-picker-button",e.after(n),e.hidden=!0;let s=0,r;const a=()=>{const c=++s,h=e.selectedOptions[0],d=e.value===""?i?.current():void 0,u=JSON.stringify([e.value,h?.textContent,d?.url,d?.title,this.messages().choose,[...e.options].map(m=>m.value).join()]);if(u===r){--s;return}r=u,n.replaceChildren();const p=document.createElement("span");p.textContent=`${d?d.title||d.url:h?.textContent??""} …`,n.title=this.messages().choose,n.append(p);const f=e.value;(d?Promise.resolve({url:d.url}):t(f)).then(m=>Ed.pictureOf(m)).then(m=>{if(!m||c!==s)return;const v=new Image;v.src=m,v.alt="",n.prepend(v)})};e.addEventListener("change",a),new MutationObserver(a).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:c=>{i.apply(c),a()}};n.addEventListener("click",()=>void this.open(e,t,o)),a()}chooseFrom(e,t,i,n){this.ensureStyle(),this.open(e,t,n,i)}ensureStyle(){const e=this.root instanceof ShadowRoot?this.root:this.root.getRootNode(),t=e instanceof ShadowRoot?e:document.head;if(t.querySelector("style[data-model-picker]"))return;const i=document.createElement("style");i.dataset.modelPicker="",i.textContent=Ed.STYLE,t.append(i)}open(e,t,i,n){const s=this.messages(),r=document.createElement("div");r.className="model-picker-backdrop";const a=document.createElement("div");a.className="model-picker",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=s.title;const c=document.createElement("button");c.type="button",c.className="model-picker-close",c.setAttribute("aria-label",s.close),c.title=s.close,c.innerHTML=Te.CLOSE;const h=document.createElement("header");h.append(o,c);const d=document.createElement("div");d.className="model-picker-body",a.append(h,d),r.append(a);const u=()=>{r.remove(),document.removeEventListener("keydown",p,!0),ae(async()=>{const{ModelViewer:E}=await import("./ModelViewer-YecYa7OI.js");return{ModelViewer:E}},__vite__mapDeps([11,10]),import.meta.url).then(({ModelViewer:E})=>E.end())},p=E=>{E.key==="Escape"&&(E.stopPropagation(),u())},f=i?.current(),m="\0address",v=E=>E===m&&f?Promise.resolve({url:f.url}):t(E),g=E=>{if(u(),n){E!==m&&n(E);return}E===m||E===e.value||(e.value=E,e.dispatchEvent(new Event("change",{bubbles:!0})))};let y;const w=new Map,b=E=>{const x=document.createElement("button");x.type="button",x.className="model-card",x.dataset.value=E.value,x.setAttribute("aria-pressed",String(!n&&(E.value===m||E.value===e.value&&!f)));const T=document.createElement("div");T.className="model-thumb";const D=document.createElement("span");if(D.className="model-name",D.textContent=E.textContent,x.append(T,D),E.title){const k=document.createElement("span");k.className="model-credit",k.textContent=E.title,x.append(k)}v(E.value).then(k=>Ed.pictureOf(k)).then(k=>{if(!k)return;const P=new Image;P.src=k,P.alt="",T.append(P)});let R,O=!1;const N=()=>{O&&!(R&&!R.active)||(O=!0,Promise.all([v(E.value),ae(()=>import("./ModelViewer-YecYa7OI.js"),__vite__mapDeps([11,10]),import.meta.url)]).then(([k,{ModelViewer:P}])=>{!k||!O||(R=P.show(T,k))}).catch(()=>{}))},C=()=>{O=!1,R?.stop(),R=void 0};return w.set(x,N),x.addEventListener("pointerenter",N),x.addEventListener("focus",N),x.addEventListener("pointerleave",()=>{document.activeElement!==x&&C()}),x.addEventListener("blur",C),x.addEventListener("click",k=>{if(R?.consumeDrag()){k.preventDefault();return}g(E.value)}),x},M=()=>(y=document.createElement("div"),y.className="model-picker-grid",d.append(y),y);if(f){const E=new Option(f.title||f.url,m);E.title=[f.author,f.license].filter(Boolean).join(" — "),M().append(b(E))}for(const E of Array.from(e.children))if(E instanceof HTMLOptGroupElement){const x=document.createElement("h3");x.textContent=E.label,d.append(x);const T=M();for(const D of Array.from(E.children))T.append(b(D));y=void 0}else E instanceof HTMLOptionElement&&(y??M()).append(b(E));i&&this.addAddressForm(h,c,a,d,i,s,u),c.addEventListener("click",u),r.addEventListener("click",E=>{E.target===r&&u()}),document.addEventListener("keydown",p,!0),this.root.append(r);const S=a.querySelector('.model-card[aria-pressed="true"]');(S??c).focus(),S&&w.get(S)?.()}addAddressForm(e,t,i,n,s,r,a){const o=document.createElement("button");o.type="button",o.className="model-picker-add",o.textContent="+",o.title=r.address,o.setAttribute("aria-label",r.address),o.setAttribute("aria-expanded","false"),e.insertBefore(o,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(w,b,M="")=>{const S=document.createElement("label"),E=document.createElement("span");E.textContent=w;const x=document.createElement("input");return x.type=b,x.placeholder=M,S.append(E,x),c.append(S),x},d=h(r.addressUrl,"url","https://…/model.glb"),u=h(r.addressName,"text"),p=h(r.addressAuthor,"text"),f=h(r.addressLicense,"text","CC0 1.0"),m=h(r.addressSource,"url","https://…"),v=document.createElement("p");v.textContent=r.addressIncomplete;const g=document.createElement("button");g.type="submit",g.className="model-picker-use",g.textContent=r.addressUse,c.append(v,g),i.insertBefore(c,n);const y=()=>{g.disabled=d.value.trim()==="",v.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const w of[d,u,p,f,m])w.addEventListener("input",y);o.addEventListener("click",()=>{const w=c.hidden;if(c.hidden=!w,o.setAttribute("aria-expanded",String(w)),!w)return;const b=s.current();d.value=b?.url??"",u.value=b?.title??"",p.value=b?.author??"",f.value=b?.license??"",m.value=b?.source??"",y(),d.focus()}),c.addEventListener("submit",w=>{w.preventDefault(),d.value.trim()!==""&&(s.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:m.value.trim()}),a())}),y()}}class $b{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=$b.SPAN_DEG;try{const s=(await this.provider.getElevationGrid({south:e-i,north:e+i,west:t-i,east:t+i},{width:2,height:2})).heights[0];return Number.isFinite(s)?s:void 0}catch{return}}}class W6{formatters=new Map;available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const i=Date.UTC(t.year,(t.month??1)-1,t.day??1,t.hour??12,t.minute??0,t.second??0),n=this.zoneOffsetHours(e,new Date(i));if(n!==void 0)return this.zoneOffsetHours(e,new Date(i-n*36e5))??n}zoneOffsetHours(e,t){let i=this.formatters.get(e);if(i===void 0){try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"})}catch{i=null}this.formatters.set(e,i)}if(i===null)return;const n=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",s=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(n);if(s)return s[1]?(s[1]==="-"?-1:1)*(Number(s[2])+Number(s[3])/60):0}zonesAt(e,t){const i=t?.year!==void 0?t:{year:new Date().getFullYear(),month:1,day:1,hour:12};return this.available().filter(n=>this.offsetHoursAt(n,i)===e)}}class ms{static STEP_MS=100;static plan(e){const t=ms.routeOf(e),i=Yt.decorReachFor(e.decor,t),n=Math.max(e.observerTrack.duration,e.timeline.duration,0),s=[];let r;const a=(c,h,d,u)=>{if(Math.abs(c.radiusM-u)>=u*.1)return!1;const{x:p,z:f}=st(h,d,c.lat,c.lng);return Math.hypot(p,f)<Yt.rebuildDistanceFor(u)};for(let c=0;;c=Math.min(n,c+ms.STEP_MS)){const h=pt(e,c);if(h?.lat!==void 0&&h.lng!==void 0){const d=Math.max(Yt.groundRadiusFor(h.elevationM??0),i);(!r||!a(r,h.lat,h.lng,d))&&(r=s.find(u=>a(u,h.lat,h.lng,d)),r||s.push(r={lat:h.lat,lng:h.lng,radiusM:d}))}if(c>=n)break}const o=e.skyEvents?.beams??[];if(o.length>0)for(const c of[...s])Yt.needsFarRing(c.radiusM,0,Yt.beamReachFor(o,c))&&s.push({lat:c.lat,lng:c.lng,radiusM:Yt.FAR_RING_RADIUS_M,far:!0});return s}static routeOf(e){const t=e.observerTrack.allKeyframes.flatMap(i=>i.pose.lat!==void 0&&i.pose.lng!==void 0?[{lat:i.pose.lat,lng:i.pose.lng}]:[]);return t.length>=2?t:void 0}static async freeze(e,t,i,n,s){const r=new Date().toISOString().slice(0,10),a=o=>s?.(o,i.length);switch(e){case"relief":{const o=ms.routeOf(t),c=[];for(const[u,p]of i.entries()){try{const f=await n.elevation.getElevationGrid(Ms.boundsOf(p),{width:kf,height:kf},{route:o});c.push({...p,grid:f})}catch(f){console.warn("Relief not frozen for a patch:",f)}a(u+1)}if(c.length===0)return;const h=n.elevationCredit;return{bytes:await Yd.encode({takenOn:r,attribution:h,patches:c}),attribution:h,takenOn:r,answered:c.length,patches:i.length}}case"imagery":{const o=new FM,c=Zi(Ll,n.imagery),h=c.create(o.fetch);let d=0;for(const[f,m]of i.entries()){try{await h.getImageryTexture(Ms.boundsOf(m),{width:Cf,height:Cf}),d++}catch(v){console.warn("Imagery not frozen for a patch:",v)}a(f+1)}if(o.tiles.size===0)return;const u=h.attribution;return{bytes:await Uf.encode({takenOn:r,source:c.id,attribution:u,patches:[...i],tiles:o.tiles}),attribution:u,takenOn:r,answered:d,patches:i.length}}case"roads":return ms.vector(n.roads,i,r,a,(o,c)=>o.getRoads(c),o=>o.contemporary);case"water":return ms.vector(n.water,i,r,a,(o,c)=>o.getWater(c));case"railways":return ms.vector(n.railways,i,r,a,(o,c)=>o.getRailways(c),o=>o.contemporary)}}static mapGround(e){const t=Tl.of(e);return t&&Zt.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=ms.mapGround(e);if(!i)return;const n=new Date().toISOString().slice(0,10),s=new FM,r=Zi(Ll,t),a=r.create(s.fetch),o=Zt.IMAGERY_PX;try{await a.getImageryTexture(i,{width:o,height:o})}catch(d){console.warn("Map imagery not frozen:",d);return}const c=a.attribution;return{bytes:await Uf.encode({takenOn:n,source:r.id,attribution:c,patches:[],map:{bounds:i,pixels:o},tiles:s.tiles}),attribution:c,takenOn:n,answered:1,patches:1}}static async vector(e,t,i,n,s,r){if(!e)return;const a=[];for(const[h,d]of t.entries()){if(d.radiusM<=Yt.ROADS_MAX_RADIUS_M)try{a.push({...d,items:await s(e,Ms.boundsOf(d))})}catch(u){console.warn("Not frozen for a patch:",u)}n(h+1)}if(a.length===0)return;const o={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:a};return{bytes:new TextEncoder().encode(JSON.stringify(o)),attribution:e.attribution,takenOn:i,answered:a.length,patches:t.length}}}class Vi{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.replace(this.shown,i.detail)),this.root.querySelector("#frozen-refresh").addEventListener("click",()=>void this.refresh(this.shown)),this.root.querySelector("#annex-export").addEventListener("click",()=>void this.exportAnnex(this.shown))}messages;busy=!1;shown="relief";editor;editorFor;editTimer;get sourceInput(){return this.root.querySelector("#annex-source")}get editorHost(){return this.root.querySelector("#annex-editor")}get note(){return this.root.querySelector("#frozen-note")}localize(e){this.messages=e,this.root.title=e.frozenHint;const t=(i,n)=>{this.root.querySelector(`#${i}`).textContent=n};t("label-annex-source",e.annexSource),t("frozen-refresh",e.frozenRefresh),t("annex-export",e.export),this.sourceInput.messages=e,this.render()}itemLabel(e){return this.groupName(e)}where(e){const t=this.annex(e);return this.isLive(e)?this.messages.frozenLiveState:!t||t.refresh?this.messages.frozenPending:Vi.isInline(t.src)?this.messages.annexStorageInline:t.src}isInlineGroup(e){const t=this.annex(e);return t!==void 0&&!this.isLive(e)&&Vi.isInline(t.src)}annex(e){const t=this.host.sighting().frozen?.[e];return t?.src!==void 0?t:void 0}isLive(e){return Bi.isLive(this.host.sighting().frozen,e)}setLive(e,t){if(this.isLive(e)===t)return;const i={...this.host.sighting().frozen??{}};if(i.live){delete i.live;for(const s of Bi.NAMES)i[s]={...i[s]??{},live:!0}}const n={...i[e]??{}};t?n.live=!0:delete n.live,i[e]=Object.keys(n).length>0?n:void 0,this.setFrozen(i)}show(e){this.shown=e,this.render()}render(){if(!this.messages)return;const e=this.shown,t=this.isLive(e),i=this.annex(e),n=this.root.querySelector("#frozen-state");n.textContent=t?this.messages.frozenLiveState:i&&!i.refresh?[this.messages.frozenTakenOn.replaceAll("{date}",i.takenOn??"?"),i.attribution].filter(Boolean).join(" · "):this.messages.frozenPending;const s=this.root.querySelector("#frozen-refresh");s.disabled=this.busy||t;const r=i!==void 0&&!i.refresh&&!t,a=r&&Vi.isInline(i.src);this.sourceInput.url=r?a?this.host.masterUrl():this.address(i.src):"",r||(this.sourceInput.mode="file"),this.sourceInput.disabled=this.busy||t,this.root.querySelector("#annex-export").disabled=i===void 0||this.busy,this.renderEditor(r&&!a?i:void 0)}async renderEditor(e){const t=this.shown,i=e&&!Vi.isZip(t)?await this.textOf(e).catch(()=>{}):void 0;if(t!==this.shown||(this.editorHost.hidden=i===void 0,i===void 0))return;const n=`${t}|${e.src}`;if(this.editor&&this.editorFor===n)return;if(this.editorFor=n,this.editor){this.editor.replaceText(i,!1);return}const{SightingFileEditor:s}=await ae(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-BtY-RLip.js");return{SightingFileEditor:r}},__vite__mapDeps([12,1,13]),import.meta.url);this.editor??=new s(this.editorHost,i,r=>this.edited(r),this.messages.annexEditorLabel,{schema:{},phrases:this.messages.fileSearchPhrases})}async textOf(e){return JSON.stringify(JSON.parse(new TextDecoder().decode(await this.bytesOf(e))),null,1)}edited(e){const t=this.shown;clearTimeout(this.editTimer),this.editTimer=setTimeout(()=>{let i;try{i=JSON.parse(e)}catch{return}this.write(t,new TextEncoder().encode(JSON.stringify(i)),{keepEditor:!0})},600)}async replace(e,t){if(t.url){if(this.address(t.url)===new URL(this.host.masterUrl(),location.href).href){await this.setStorage(e,!0);return}const n={...this.host.sighting().frozen??{}};let s;try{s=await this.bytesAt(t.url)}catch{s=void 0}if(s!==void 0)try{n[e]={src:t.url,...await Vi.describe(e,s)}}catch{Wt.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){Wt.show(this.note,this.messages.frozenMissing.replaceAll("{file}",t.url),"warning");return}St.hold(this.address(t.url),await this.bytesOf(r)),n[e]={...r,src:t.url}}Wt.show(this.note,void 0),this.setFrozen(n);return}const{InputFileElement:i}=await ae(async()=>{const{InputFileElement:n}=await Promise.resolve().then(()=>JS);return{InputFileElement:n}},void 0,import.meta.url);await this.write(e,await i.bytesOf(t))}async write(e,t,i={}){const n={...this.host.sighting().frozen??{}},s=this.annex(e);let r;try{r=await Vi.describe(e,t)}catch{Wt.show(this.note,this.messages.annexUnreadable,"warning");return}const a=s!==void 0&&Vi.isInline(s.src),o=a?Vi.dataUrl(e,t):s?.src??Bi.annexName(this.host.base(),e);a||St.hold(this.address(o),t),n[e]={...n[e]?.live?{live:!0}:{},src:o,...r},Wt.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${o}`),this.setFrozen(n)}async setStorage(e,t){const i={...this.host.sighting().frozen??{}},n=this.annex(e);if(!n||Vi.isInline(n.src)===t)return;const s=await this.bytesOf(n);let r;t?r=Vi.dataUrl(e,s):(r=Bi.annexName(this.host.base(),e),St.hold(this.address(r),s)),i[e]={...n,src:r},this.editorFor=`${e}|${r}`,this.setFrozen(i)}async exportAnnex(e){const t=this.annex(e);if(!t)return;const i=await this.bytesOf(t),n=Vi.isInline(t.src)?Bi.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:Vi.isZip(e)?"application/zip":"application/json"}),n)}static async describe(e,t){let i;if(Vi.isZip(e)){const{unzipSync:n}=await ae(async()=>{const{unzipSync:s}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:s}},[],import.meta.url);i=JSON.parse(new TextDecoder().decode(n(t)["index.json"]))}else i=JSON.parse(new TextDecoder().decode(t));if(typeof i!="object"||i===null)throw new Error("Not an annex");return{takenOn:typeof i.takenOn=="string"?i.takenOn:void 0,attribution:typeof i.attribution=="string"?i.attribution:void 0}}async bytesAt(e){return St.bytes(this.address(e))}static isInline(e){return e.startsWith("data:")}static isZip(e){return e==="relief"||e==="imagery"||e==="map"}static dataUrl(e,t){let i="";for(let n=0;n<t.length;n+=32768)i+=String.fromCharCode(...t.subarray(n,n+32768));return`data:${Vi.isZip(e)?"application/zip":"application/json"};base64,${btoa(i)}`}async refresh(e){if(this.busy)return;const t={...this.host.sighting().frozen??{}};if(e==="upperAir"){const i=t.upperAir;i&&(t.upperAir={...i,refresh:!0}),this.setFrozen(t);return}this.busy=!0,this.render();try{const i=t[e]?.src,n=(i&&!Vi.isInline(i)?Vi.baseOf(i):void 0)??this.host.base();(e==="map"?await this.takeMap(t,this.host.sources(),n):await this.take(e,t,ms.plan(this.host.sighting()),this.host.sources(),n))?Wt.show(this.note,void 0):Wt.show(this.note,this.messages.frozenFailed.replaceAll("{group}",this.groupName(e)),"warning")}finally{this.busy=!1}this.setFrozen(t)}hasWork(){const e=this.host.sighting();return Bi.isEmpty(e.frozen)?this.host.upperAirHeard()!==void 0||ms.plan(e).length>0:!0}async prepare(e){const t=this.host.sighting(),i={...t.frozen??{}},n=new Map;this.busy=!0,this.render();try{const s=d=>Bi.isLive(i,d),r=d=>i[d]?.src!==void 0?i[d]:void 0;for(const d of Bi.NAMES)!i.live&&i[d]?.live&&(i[d]={live:!0});const a=ms.plan(t);let o;for(const d of Bi.TERRAIN){if(s(d))continue;const u=r(d);if(a.length>0&&(!u||u.refresh||!await this.fits(d,u,a))&&await this.take(d,i,a,o??=this.host.sources(),e)){await this.keep(r(d),n);continue}u?.refresh&&(i[d]={...u,refresh:void 0}),r(d)&&await this.keep(r(d),n)}if(!s("map")){const d=r("map");ms.mapGround(t)!==void 0&&(!d||d.refresh||!await this.fitsMap(d))&&await this.takeMap(i,o??=this.host.sources(),e)?await this.keep(r("map"),n):d&&(d.refresh&&(i.map={...d,refresh:void 0}),await this.keep(r("map"),n))}const c=this.host.upperAirHeard(),h=r("upperAir");if(!s("upperAir")&&c&&(!h||h.refresh)){const d=new Date().toISOString().slice(0,10),u={version:1,takenOn:d,attribution:c.answer.source.name,answers:[c]},p=new TextEncoder().encode(JSON.stringify(u)),f=this.place("upperAir",h?.src,e,p);i.upperAir={src:f,takenOn:d,attribution:c.answer.source.name},Vi.isInline(f)||n.set(f,p)}else h&&!s("upperAir")&&(h.refresh&&(i.upperAir={...h,refresh:void 0}),await this.keep(r("upperAir"),n))}finally{this.busy=!1}return this.setFrozen(i),n}async take(e,t,i,n,s){const r=this.groupName(e),a=await ms.freeze(e,this.host.sighting(),i,n,(o,c)=>Wt.show(this.note,this.messages.frozenTaking.replaceAll("{group}",r).replaceAll("{done}",String(o)).replaceAll("{of}",String(c))));return Wt.show(this.note,void 0),a?(t[e]={src:this.place(e,t[e]?.src,s,a.bytes),takenOn:a.takenOn,attribution:a.attribution},!0):!1}async takeMap(e,t,i){Wt.show(this.note,this.messages.frozenTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const n=await ms.freezeMap(this.host.sighting(),t.imagery);return Wt.show(this.note,void 0),n?(e.map={src:this.place("map",e.map?.src,i,n.bytes),takenOn:n.takenOn,attribution:n.attribution},!0):!1}async fitsMap(e){const t=ms.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await St.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&Ms.sameBounds(i.map.bounds,t)}catch{return!1}}async fits(e,t,i){try{const n=this.address(t.src),s=t.src.endsWith(".zip")?JSON.parse(new TextDecoder().decode((await St.zip(n))["index.json"])).patches:(await St.json(n)).patches,r=e==="relief"||e==="imagery"?i:i.filter(a=>a.radiusM<=Yt.ROADS_MAX_RADIUS_M);return Ms.samePatches(s.map(({lat:a,lng:o,radiusM:c})=>({lat:a,lng:o,radiusM:c})),r)}catch{return!1}}place(e,t,i,n){if(t!==void 0&&Vi.isInline(t))return Vi.dataUrl(e,n);const s=t??Bi.annexName(i,e);return St.hold(this.address(s),n),s}async keep(e,t){if(!Vi.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{Wt.show(this.note,this.messages.frozenMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return St.bytes(this.address(e.src))}address(e){return St.address(e,this.host.documentUrl())}setFrozen(e){for(const t of Bi.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().frozen=Bi.isEmpty(e)?void 0:e,this.render(),this.host.changed()}destroy(){clearTimeout(this.editTimer),this.editor?.destroy(),this.editor=void 0,this.editorFor=void 0}static baseOf(e){return e?.match(/^(.*)\.[a-z-]+\.(zip|json)$/)?.[1]}static size(e){return e<1e6?`${Math.max(1,Math.round(e/1e3))} kB`:`${(e/1e6).toFixed(1)} MB`}groupName(e){return{relief:this.messages.frozenRelief,imagery:this.messages.frozenImagery,roads:this.messages.frozenRoads,water:this.messages.frozenWater,railways:this.messages.frozenRailways,upperAir:this.messages.frozenUpperAir,map:this.messages.frozenMap}[e]}}class Xf{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.take(this.shown,i.detail)),this.root.querySelector("#section-annex-export").addEventListener("click",()=>this.exportAnnex(this.shown))}messages;shown="weather";get sourceInput(){return this.root.querySelector("#section-annex-source")}get note(){return this.root.querySelector("#section-annex-note")}localize(e){this.messages=e;const t=(i,n)=>{this.root.querySelector(`#${i}`).textContent=n};t("label-section-annex-source",e.annexSource),t("section-annex-export",e.export),this.sourceInput.messages=e,this.render()}show(e){this.shown=e,Wt.show(this.note,void 0),this.render()}srcOf(e){return this.host.sighting().frozen?.[e]?.src}itemLabel(e){return{weather:this.messages.fileItemWeather,place:this.messages.fileItemPlace,lightPollution:this.messages.fileItemLightPollution,decor:this.messages.fileItemDecor}[e]}where(e){return this.srcOf(e)??this.messages.annexStorageInline}isInline(e){return this.srcOf(e)===void 0}static pathOf(e){return[Sn.KEYS[e][0]]}render(){if(!this.messages)return;const e=this.srcOf(this.shown);this.sourceInput.url=e?this.resolve(e):this.host.masterUrl(),this.root.querySelector("#section-annex-state").textContent=this.state(this.shown)}state(e){const t=this.host.sighting();switch(e){case"weather":return t.weatherSource?.name??this.messages.weatherStatedByObserver;case"place":return t.event.place?.[0]?.name??"";case"lightPollution":return t.provenance.at("lightPollution")?.rationale??(t.lightPollution===void 0?"":String(t.lightPollution));case"decor":return""}}setStorage(e,t){const i={...this.host.sighting().frozen??{}};if(t===(i[e]?.src===void 0))return;const{src:n,...s}=i[e]??{};i[e]=t?s:{...s,src:Sn.annexName(this.host.base(),e)},this.write(e,i)}annex(e){const t=this.srcOf(e);return t===void 0?void 0:{src:t,bytes:this.bytesOf(e)}}bytesOf(e){const t=uf(this.host.sighting()),i={version:1};for(const n of Sn.KEYS[e])t[n]!==void 0&&(i[n]=t[n]);return new TextEncoder().encode(JSON.stringify(i))}resolve(e){return new URL(e,this.host.documentUrl()??location.href).href}exportAnnex(e){const t=this.srcOf(e)??Sn.annexName(this.host.base(),e);this.host.download(new Blob([this.bytesOf(e)],{type:"application/json"}),decodeURIComponent(t.split("/").pop()??t))}async take(e,t){if(t.url&&this.resolve(t.url)===this.resolve(this.host.masterUrl())){this.setStorage(e,!0);return}if(t.url)try{await fetch(this.resolve(t.url),{method:"HEAD"}).then(o=>{if(!o.ok)throw new Error(String(o.status))})}catch{const o={...this.host.sighting().frozen??{}};o[e]={...o[e]??{},src:t.url},Wt.show(this.note,void 0),this.write(e,o);return}let i;try{const{InputFileElement:o}=await ae(async()=>{const{InputFileElement:h}=await Promise.resolve().then(()=>JS);return{InputFileElement:h}},void 0,import.meta.url),c=await o.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=JSON.parse(new TextDecoder().decode(c)),typeof i!="object"||i===null||Sn.KEYS[e].every(h=>i[h]===void 0))throw new Error("Not this section")}catch{Wt.show(this.note,this.messages.annexUnreadable,"warning");return}const n=this.host.sighting(),s={...uf(n)};for(const o of Sn.KEYS[e])s[o]=i[o];const r=rb(s);Xf.copy(e,r,n);const a={...n.frozen??{}};t.url?a[e]={...a[e]??{},src:t.url}:a[e]=a[e]??{},Wt.show(this.note,void 0),this.write(e,a)}write(e,t){this.host.sighting().frozen=Bi.isEmpty(t)?void 0:t,this.render(),this.host.changed(e)}static copy(e,t,i){switch(e){case"weather":i.weatherTrack.clear();for(const n of t.weatherTrack.allKeyframes)i.weatherTrack.addKeyframe(n.t,n.weather);i.weatherSource=t.weatherSource;break;case"place":i.event.place=t.event.place;break;case"lightPollution":i.lightPollution=t.lightPollution;break;case"decor":i.decor=t.decor;break}for(const n of Sn.KEYS[e]){i.provenance.clear(n);for(const s of t.provenance.paths())(s===n||s.startsWith(`${n}.`))&&i.provenance.set(s,t.provenance.at(s))}}}class $6{constructor(e="https://api.open-meteo.com/v1/forecast"){this.endpoint=e}async zoneAt(e,t){const i=new URL(this.endpoint);i.searchParams.set("latitude",String(e)),i.searchParams.set("longitude",String(t)),i.searchParams.set("timezone","auto"),i.searchParams.set("forecast_days","1");try{const n=await fetch(i.toString());if(!n.ok)return;const s=await n.json();return s.timezone&&s.timezone!=="GMT"?s.timezone:void 0}catch{return}}}const K6=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new $6}],up=new Set;cm();o6();Wc.register();const Sc={width:48,height:28},X6=2500,ix=40,Y6=10,nx=600,sx=900,Ec=2e-4,q6=900,j6=-1.46,Z6=3,tg=.2,J6=.5,Q6=3,eN=.01,tN=1.6,ig=2e3,iN=250,rx=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),nN=1,sN=5,rN=10,io=4,Jh="ufo-1",aN={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function oN(l){return l.kind==="oval"?"oval":"polygon"}const lN=-6,cN=21;class Ce extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=K6[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new W6;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;durationElement;exportButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;candidatesView;sectionFolds;frozenPanel;sectionFilePanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=z6();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lensGlassSelect;isoInput;meteringSelect;lensDropsInput;lensCondensationInput;lensDirtInput;lensShelteredInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;launchEditor;launchEditorLoading;beamEditor;beamEditorLoading;lanternEditor;lanternEditorLoading;fileEditor;fileEditorLoading;fileEditorHost;fileNote;fileAsk;identityAsk;fileSyncTimer;fileApplyTimer;historySnapshot;historyTimer;historyAnswering=!1;undoButton;redoButton;labelFileGroup;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new q0(F6());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelPosition;observerSaid;observerSaidShown;observerPosition;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;wholeKeyframesInput;labelImportFile;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;accountShapeIds;labelNarrativeSource;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;labelRareIce;highCloudCoverInput;iceCrystalAlignmentInput;rareIceCrystalsInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelLaunchesSubgroup;labelBeamsSubgroup;labelLanternsSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;weatherProviderSelect;weatherFileLink;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorList;observerList;observerShown="principal";static CLICK_SLOP_PX=5;static OBSERVER_PRINCIPAL="principal";surroundings;surroundingsProvider;sceneryStatus;scenerySource;labelScenerySource;sceneryWarning;sceneryRadius;labelSceneryRadius;sceneryChoice;decorModelProvider=_p[0].create();milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=So;currentAppearance={...aN};currentSourceId=Jh;selectedSourceIds=new Set([Jh]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSourceInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;referenceFailure;addReferenceButton;referenceAddMenu;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;findGhostsButton;searchingGhosts=!1;ghostsStatus;ghostFinding;ghostsShown=!0;ghostsShownButton;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;traceImportInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;addTraceButton;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$;pictureRegistration;pictureRegistrationLoading;referenceFields;labelReferenceGroup;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),(e.ctrlKey||e.metaKey)&&!e.altKey&&["z","y"].includes(e.key.toLowerCase())){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;e.preventDefault(),e.key.toLowerCase()==="y"||e.shiftKey?this.redo():this.undo();return}if(rx.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;rx.has(e.key)?this.selectedMembers().length===0&&t===this?this.walkOrTurn(e):this.moveOrResizeSelectedShapes(e):this.canvasMode()==="decor"?this.deleteDecor():this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0,t=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedBodyId:void 0;this.endDrag(),t!==void 0&&this.showBody(t),e!==void 0&&(this.selectDecor(e),this.revealDecorPanel(),this.flash(this.shadow.querySelector("#decor-item label, #decor-item .field")))};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${OT}</style>${LT}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const r of this.shadow.querySelectorAll(Jp))r.build();for(const r of this.shadow.querySelectorAll($f))r.build();for(const r of this.shadow.querySelectorAll(qd))r.build();for(const r of this.shadow.querySelectorAll(tf))r.build();this.sceneElement=document.createElement(Vf),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",r=>{this.ufoElement.sighting.observerMap=r.detail.open,this.dispatchEvent(new CustomEvent("sightingchange"))}),this.sceneElement.accountInTheRound=!1,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.steadyObserver=!0,this.ufoElement.observerPlacing=!0,this.ufoElement.addEventListener("observerplace",r=>{const{lat:a,lng:o}=r.detail;this.latInput.value=String(Number(a.toFixed(6))),this.lngInput.value=String(Number(o.toFixed(6))),this.updateObserver()}),this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.shapeRotationInput=this.shadow.getElementById("shapeRotation"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextDuplicateButton=this.shadow.getElementById("context-duplicate"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewAccountButton=this.shadow.getElementById("context-view-account"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.previousMarkButton=this.shadow.getElementById("previous-mark"),this.nextMarkButton=this.shadow.getElementById("next-mark"),this.timelineMarks=new ad(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const r of[this.timeStartLabel,this.timeEndLabel])r.addEventListener("click",()=>this.switchTimeDisplay()),r.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.durationElement=this.shadow.querySelector($f),this.durationInput=this.durationElement.input,this.exportButton=this.shadow.getElementById("export"),this.saveButton=this.shadow.getElementById("save"),this.shareButton=this.shadow.getElementById("share"),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.sectionFolds=new Dx(this.shadow);const t=this;this.witnessErrorView=new n2({get sighting(){return t.ufoElement.sighting},messages:()=>this.messages.witnessError,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:r=>{const a=this.ufoElement.sighting,{conditions:o,...c}=a.account??{},h={...c,...r?{conditions:r}:{}};a.account=Object.values(h).some(d=>d!==void 0)?h:void 0},recordingJson:()=>this.sightingData,lawsChanged:()=>{this.sceneElement.confrontationTolerance=Ai.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}},this.shadow.querySelector(".app")),this.timelineTracks=new a2(this.shadow.getElementById("timeline-tracks"),r=>this.goToMark(r),this.messages),this.tracksToggle=this.shadow.getElementById("toggle-tracks"),this.tracksToggle.addEventListener("click",()=>this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")!=="true")),this.shadow.querySelector(".scene-card").addEventListener("pointerdown",r=>{r.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new o2(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",r=>{const a=r.target.id;Ce.SCENE_LINKED.includes(a)&&this.setActiveSceneField(a)}),this.shadow.addEventListener("focusout",r=>{const a=r.relatedTarget;(!a||!Ce.SCENE_LINKED.includes(a.id))&&this.setActiveSceneField(void 0)}),this.shadow.addEventListener("input",()=>this.refreshSceneField()),this.importInput=this.shadow.getElementById("import"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeRememberInput=this.shadow.getElementById("narrativeRemember"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lensGlassSelect=this.shadow.getElementById("lens-glass"),this.isoInput=this.shadow.getElementById("iso"),this.meteringSelect=this.shadow.getElementById("metering"),this.lensDropsInput=this.shadow.getElementById("lens-drops"),this.lensCondensationInput=this.shadow.getElementById("lens-condensation"),this.lensDirtInput=this.shadow.getElementById("lens-dirt"),this.lensShelteredInput=this.shadow.getElementById("lens-sheltered"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.rareIceCrystalsInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${tf}[name="observer"]`),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),this.labelRoll=this.shadow.getElementById("label-roll"),this.labelSway=this.shadow.getElementById("label-sway"),this.labelLightPollution=this.shadow.getElementById("label-light-pollution"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelObserverId=this.shadow.getElementById("label-observer-id"),this.labelObserverTitle=this.shadow.getElementById("label-observer-title"),this.labelObserverLastName=this.shadow.getElementById("label-observer-last-name"),this.labelObserverFirstNames=this.shadow.getElementById("label-observer-first-names"),this.labelObserverAge=this.shadow.getElementById("label-observer-age"),this.labelObserverBirth=this.shadow.getElementById("label-observer-birth"),this.labelObserverOccupation=this.shadow.getElementById("label-observer-occupation"),this.labelAccountSource=this.shadow.getElementById("label-account-source"),this.labelAccountFollowedUp=this.shadow.getElementById("label-account-followed-up"),this.labelSightingId=this.shadow.getElementById("label-sighting-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.wholeKeyframesInput=this.shadow.getElementById("whole-keyframes");try{this.wholeKeyframesInput.checked=localStorage.getItem(Ce.WHOLE_KEYFRAMES_STORAGE)==="true"}catch{}this.wholeKeyframesInput.addEventListener("change",()=>this.setKeyframesWritten()),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),this.labelNarrativeRemember=this.shadow.getElementById("label-narrative-remember"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelFileGroup=this.shadow.getElementById("label-file-group"),this.fileEditorHost=this.shadow.getElementById("file-editor"),this.fileNote=this.shadow.getElementById("file-note"),this.frozenPanel=new Vi(this.shadow.getElementById("frozen-data"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,sources:()=>this.freezerSources(),upperAirHeard:()=>this.sceneElement.upperAirHeard,changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleFileSync(),this.refreshFileItems()},base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(r,a)=>this.download(r,a)}),this.sectionFilePanel=new Xf(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(r,a)=>this.download(r,a),changed:r=>{if(this.touch(),this.ufoElement.refresh(),r==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),r==="place"&&this.syncPlaceNameField(),r==="lightPollution"){const a=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=a===void 0?"":String(a),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}}),this.sectionFilePanel.localize(this.messages),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.frozenPanel.localize(this.messages),this.refreshFileItems(),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",r=>{r.preventDefault(),this.keepReadingWeather()}),this.shadow.getElementById("file-ask-stop").addEventListener("click",()=>this.stopReadingWeather()),this.shadow.getElementById("file-ask-keep").addEventListener("click",()=>this.keepReadingWeather()),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelObserverGroup=this.shadow.getElementById("label-observer-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelRareIce=this.shadow.getElementById("label-rare-ice"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelShapesSubgroup=this.shadow.getElementById("label-shapes-subgroup"),this.labelBodiesSubgroup=this.shadow.getElementById("label-bodies-subgroup"),this.labelLaunchesSubgroup=this.shadow.getElementById("label-launches-subgroup"),this.labelBeamsSubgroup=this.shadow.getElementById("label-beams-subgroup"),this.labelLanternsSubgroup=this.shadow.getElementById("label-lanterns-subgroup"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.weatherProviderSelect=this.shadow.getElementById("weatherSource"),this.weatherFileLink=this.shadow.getElementById("weather-file-link"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorList=new ps({header:this.shadow.getElementById("decor-list-header"),body:this.shadow.getElementById("decor-item"),ids:{list:"decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind:r=>`option-decor-${r}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:r=>this.selectDecor(r),onAdd:r=>this.addDecor(r),onRemove:()=>this.deleteDecor()}),this.decorList.setKinds([{value:"building",label:"Building"},{value:"tree",label:"Tree"},{value:"shrub",label:"Shrub"},{value:"bridge",label:"Bridge"},{value:"wire",label:"Overhead line"},{value:"crop",label:"Crop row"},{value:"terrace",label:"Terrace (restanque)"},{value:"mound",label:"Stone heap"},{value:"wall",label:"Dry-stone wall"},{value:"streetlight",label:"Streetlight"},{value:"trafficlight",label:"Traffic light"},{value:"crossing",label:"Pedestrian crossing"},{value:"roadsign",label:"Road sign"},{value:"vehicle",label:"Vehicle"},{value:"aircraft",label:"Aircraft"},{value:"entity",label:"Being"},{value:"observer",label:"Other observer",hidden:!0}]),this.decorList.setLabels({list:"Environment",remove:"Delete decor",add:"Add",empty:"No decor",actions:{"look-at-decor":"Look at it"}}),this.observerList=new ps({header:this.shadow.getElementById("observer-list-header"),body:this.shadow.getElementById("observer-item"),ids:{list:"observer-pick",remove:"delete-observer",add:"add-decor-observer"},actions:[{id:"look-at-observer",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:r=>this.selectObserver(r),onAdd:()=>this.addDecor("observer"),onRemove:()=>this.deleteDecor()}),this.observerList.setLabels({list:"Observer",remove:"Delete observer",add:"Add observer",actions:{"look-at-observer":"Look at it"}}),this.sceneryStatus=this.shadow.getElementById("scenery-status"),this.sceneryWarning=this.shadow.getElementById("scenery-warning"),this.scenerySource=this.shadow.getElementById("scenery-source"),this.labelScenerySource=this.shadow.getElementById("label-scenery-source"),this.sceneryRadius=this.shadow.getElementById("scenery-radius"),this.labelSceneryRadius=this.shadow.getElementById("label-scenery-radius"),this.sceneryRadius.value=this.readSceneryRadius(),this.surroundings=new On(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:r=>this.setPlantedDecor(r),kindName:r=>this.decorList.kindLabel(r),cite:r=>this.citeSource(r),busy:(r,a)=>this.sceneElement.setBusy(r,a),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(r=>({lat:r.pose.lat,lng:r.pose.lng})).filter(r=>typeof r.lat=="number"&&typeof r.lng=="number")},So,async(r,a)=>this.surroundingsProvider?this.surroundingsProvider.covers(r,a)?this.surroundingsProvider:void 0:(await ae(async()=>{const{SurroundingsSources:o}=await import("./surroundingsSources-BK1okKkz.js");return{SurroundingsSources:o}},[],import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,r,a),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-file-link").addEventListener("click",()=>this.openFileItem("decor")),this.scenerySource.addEventListener("change",()=>{const r=this.scenerySource.value===Ce.FILE_SOURCE;if(this.setDecorFromFile(r),r){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===Ce.NO_SCENERY){this.surroundings.withdraw();return}const a=this.plantingCentre();a&&this.surroundings.survey(a.lat,a.lng)}),this.sceneryRadius.addEventListener("input",()=>{const r=Number(this.sceneryRadius.value);if(!Number.isFinite(r)||r<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const a=this.plantingCentre();this.surroundings.radiusChanged(r,a?.lat,a?.lng)}),this.fillScenerySources(),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSourceInput=this.shadow.getElementById("reference-source"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.referenceFailure=this.shadow.getElementById("reference-failure"),this.addReferenceButton=this.shadow.getElementById("add-reference"),this.referenceAddMenu=new Zp(this.addReferenceButton,"reference-add-kind",r=>this.addReferenceOfKind(r),r=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[r]??`reference-add-${r}`),this.setReferenceAddKinds("From an address","From a file","Street-level pictures nearby"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.findGhostsButton=this.shadow.getElementById("reference-find-ghosts"),this.ghostsStatus=this.shadow.getElementById("reference-ghosts-status"),this.findGhostsButton.addEventListener("click",()=>void this.findGhosts()),this.ghostsShownButton=this.shadow.getElementById("reference-ghosts-shown"),this.ghostsShownButton.addEventListener("click",()=>{this.ghostsShown=!this.ghostsShown,this.syncGhostsShown(),this.ufoElement.refresh()}),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.traceImportInput=this.shadow.getElementById("trace-import"),this.traceSelect=this.shadow.getElementById("trace"),this.deleteTraceButton=this.shadow.getElementById("delete-trace"),this.traceTitleInput=this.shadow.getElementById("traceTitle"),this.traceSourceInput=this.shadow.getElementById("traceSource"),this.traceStatus=this.shadow.getElementById("trace-status"),this.labelTraceImport=this.shadow.getElementById("label-trace-import"),this.addTraceButton=this.shadow.getElementById("add-trace"),this.labelTraceTitle=this.shadow.getElementById("label-trace-title"),this.labelTraceSource=this.shadow.getElementById("label-trace-source"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.goToMilestoneButton=this.shadow.getElementById("go-to-milestone"),this.modelPicker=new Ed(this.shadow,()=>({title:this.messages.modelPickerTitle,close:this.messages.modelPickerClose,choose:this.messages.modelPickerChoose,address:this.messages.decorModelAdvanced,addressUrl:this.messages.decorModelUrl,addressName:this.messages.decorModelTitle,addressAuthor:this.messages.decorModelAuthor,addressLicense:this.messages.decorModelLicense,addressSource:this.messages.decorModelSource,addressUse:this.messages.modelPickerUse,addressIncomplete:this.messages.modelPickerIncomplete})),this.decorParametersHost=this.shadow.getElementById("decor-parameters"),this.decorParameterForm=new _r(this.decorParametersHost,"en","decorParam.");const i={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new _r(this.decorBaseHost,"en","decorBase.",i,(r,a)=>this.enhanceDecorModelChoice(r,a)),this.decorStateForm=new _r(this.decorStateHost,"en","decorState.",i),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",r=>{this.focus({preventScroll:!0}),this.onPointerDown(r)}),this.ufoElement.canvasElement.addEventListener("pointermove",r=>this.onPointerMove(r));let n;this.ufoElement.canvasElement.addEventListener("pointerdown",r=>{n={x:r.clientX,y:r.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",r=>{const a=n;n=void 0,!(!a?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(r.clientX-a.x,r.clientY-a.y)>Ce.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",r=>this.onContextMenu(r)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextDuplicateButton.addEventListener("click",()=>this.duplicateSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.saveButton.addEventListener("click",()=>this.exportJson()),this.shareButton.addEventListener("click",()=>this.openShare()),this.importInput.addEventListener("filepick",r=>{const a=r.detail;a.file?this.importFromFile(a.file):this.importFromUrl(a.url)}),this.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()});for(const r of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])r.addEventListener(r instanceof HTMLSelectElement||r.type==="checkbox"?"change":"input",()=>this.updateLens());this.lightPollutionInput.addEventListener("input",()=>{const r=this.ufoElement.sighting;r.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),r.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),r.lightPollution===void 0?this.scheduleLightPollutionLookup():this.syncLightPollutionStatus()}),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.narrativeRememberInput.addEventListener("change",()=>this.rememberNarrativeSettings()),this.renderNarrativeSettings(),this.durationElement.addEventListener("durationchange",r=>{const{seconds:a,text:o}=r.detail;this.ufoElement.sighting.event.durationText=o,this.ufoElement.durationSeconds=a,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((a??0)*1e3),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.shapeRotationInput.addEventListener("input",()=>this.updateShapeRotation()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const r of this.referenceFields)r.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceSourceInput.addEventListener("filepick",r=>void this.setReferenceSource(r.detail)),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.addTraceButton.addEventListener("click",()=>{const r=this.shadow.getElementById("trace-import-row");r.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",r=>void this.addTraces(r.detail)),this.traceSelect.addEventListener("change",()=>this.selectTrace(this.traceSelect.value)),this.deleteTraceButton.addEventListener("click",()=>this.deleteTrace()),this.traceTitleInput.addEventListener("input",()=>this.writeTraceFields()),this.traceSourceInput.addEventListener("input",()=>this.writeTraceFields()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",r=>this.onReferenceWheel(r),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",r=>this.onBodyWheel(r),{passive:!1}),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.goToMilestoneButton.addEventListener("click",()=>{this.currentMilestoneT!==void 0&&this.goToMark(this.currentMilestoneT)}),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const r of[this.milestoneLabelInput,this.milestoneNoteInput])r.addEventListener("input",()=>this.updateMilestone());this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showNovaButton.addEventListener("click",()=>this.lookAtNova()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.showFireballButton.addEventListener("click",()=>this.showNextFireball()),this.sceneElement.addEventListener(qS,()=>{const r=this.currentReference();r&&this.syncReferenceStatus(r)}),this.sceneElement.addEventListener(YS,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(XS,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown),this.shapeAddMenu=new Zp(this.addShapeButton,"add-shape-kind",r=>{const a=Ra.byId(r);if(a){this.addModel(a);return}this.currentAppearance={...this.currentAppearance,presetId:r},this.addShape()},r=>`add-shape-${r}`),this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const r of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])r.addEventListener("input",()=>this.updateObserver());for(const r of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])r.addEventListener("input",()=>this.updateObserver());this.isoInput.addEventListener("input",()=>this.updateExposureSettings()),this.meteringSelect.addEventListener("change",()=>this.updateExposureSettings()),this.observerPosition.addEventListener("positionchange",r=>{if(this.observerSaid=r.detail.said,!this.observerPosition.relative)return;const a=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(a,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",r=>this.writeObserverBasis(r.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("focus",()=>this.sceneElement.setCompassForced(!0)),this.headingInput.addEventListener("input",()=>this.refreshHeadingPoint()),this.headingInput.addEventListener("blur",()=>this.sceneElement.setCompassForced(!1)),this.filterSelect.addEventListener("change",()=>this.updateObserver()),this.instrumentSelect.addEventListener("change",()=>{const r=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const a=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(o=>[o.t,Oi.fovOf(this.ufoElement.sighting,o.t)]));this.retuneFieldOfView(r),this.retuneExposure(r),Oi.reproject(this.ufoElement.sighting,r,a),this.sceneElement.applyFrameFormat(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const s=r=>this.shadow.querySelector(`${Jp}[name="${r}"]`);this.startDate=s("obs-time"),this.endDate=s("obs-end-time"),this.birthDate=s("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=Ol.ALL,this.perceptionSettings.labels=this.messages.observerPerception,this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata()),this.startDate.messages=this.messages,this.endDate.messages=this.messages,this.birthDate.messages=this.messages;for(const r of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(r,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",r=>{const{time:a}=r.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=a}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",r=>{this.birth=r.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",r=>{const{time:a}=r.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=a})});for(const r of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])r.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(Ce.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const r of this.weatherFields){if(r===this.iceCrystalAlignmentInput||r===this.rareIceCrystalsInput){r.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}r.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const r of this.soundFields)r.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.weatherProviderSelect.addEventListener("change",()=>this.onWeatherProviderChosen()),this.weatherFileLink.addEventListener("click",()=>this.openFileItem("weather")),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(r=>this.shadow.getElementById(r.getAttribute("aria-controls")));for(const r of this.groupTabs)r.addEventListener("click",()=>this.toggleGroup(r,!this.isGroupOpen(r)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const r of this.subgroupTabs)r.addEventListener("click",()=>this.openSubgroup(r));Fn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new qc(this.messages,this.naming,this.said,this.tagNames,{messages:this.messages,locale:this.language}),this.paramSummary.addEventListener("click",r=>this.onParamSummaryClick(r)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(r=>r.id==="group-shape")],!0),this.sectionChosen=!1,this.opensMostLacking=!0,this.attachWitnessErrors(),this.labelPanels(this.messages),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),this.setRecordButtonLabel(!1),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=JA(this.shadow.getElementById("cloud-editor"),this.sceneElement,(r=!0)=>{r&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(r,a)=>{this.headingInput.value=String(this.rounded(r)),this.pitchInput.value=String(this.rounded(a)),this.updateObserver()},Id(Zs.preferencesFor(this),Td),this.framePlace()),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),Zs.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages(),this.shadow.addEventListener("pointerdown",this.armHistory,!0),this.shadow.addEventListener("keydown",this.armHistory,!0);for(const t of["input","change","click","keyup","pointerup"])this.shadow.addEventListener(t,this.scheduleHistoryRecord,!0);this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),this.shadow.removeEventListener("pointerdown",this.armHistory,!0),this.shadow.removeEventListener("keydown",this.armHistory,!0);for(const e of["input","change","click","keyup","pointerup"])this.shadow.removeEventListener(e,this.scheduleHistoryRecord,!0);clearTimeout(this.historyTimer),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag(),queueMicrotask(()=>{this.isConnected||this.releaseFileEditor()})}releaseFileEditor(){this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileEditorLoading=void 0}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.sourceUrl=void 0,this.endDrag(),this.ufoElement.sightingData=e,this.sceneElement.applyFrameFormat(),this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??Jh,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncObserverMetadataFields(),this.offsetIsAuthors=!1,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField();const t=this.plantingCentre();this.surroundings.placeLoaded(t?.lat,t?.lng),this.syncSceneryPicker(),this.syncWeatherOwnership(),this.frozenPanel.render(),this.refreshFileItems(),this.markClean(),this.sectionChosen||(this.opensMostLacking=!0)}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&this.fileText()!==this.baseline}get edited(){return this.touched}markClean(){this.applyingFileText||(this.baseline=this.fileText(),this.touched=!1,this.savedFileText=this.baseline,this.fileEditor?.markSaved(),this.refreshEditorHead())}set embedded(e){this.shadow.getElementById("editor-head").hidden=e,this.shadow.querySelector(".app").classList.toggle("embedded",e),e||this.shadow.querySelector("#editor-head .head-actions").prepend(this.historyControls)}get historyControls(){return this.undoButton.parentElement}refreshEditorHead(){this.saveButton&&(this.refreshEditorTitle(),this.saveButton.disabled=!this.dirty,this.shareButton.disabled=this.sourceUrl===void 0,this.shareButton.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"")}sourceUrl;shareButton;shareDialog;shareMessages;shareSubject={module:"rr0-sighting-editor",link:()=>`${rh.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}`,element:()=>`<rr0-sighting-editor src="${this.sourceUrl??""}"></rr0-sighting-editor>`};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}refreshEditorTitle(){const e=this.ufoElement.sighting.event,t=e.place?.[0]?.name?.split(",")[0].trim(),i=e.time;let n="";i?.year!==void 0&&(n=i.month!==void 0&&i.day!==void 0?new Date(Date.UTC(i.year,i.month-1,i.day)).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"}):String(i.year));const s=[t,n].filter(Boolean).join(", ")||this.sightingIdInput.value||this.messages.stateNew,r=this.shadow.getElementById("editor-title");r.textContent!==s&&(r.textContent=s)}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.historySnapshot!==void 0&&(clearTimeout(this.historyTimer),this.historyTimer=setTimeout(()=>this.recordHistory(),350))};recordHistory(){this.historyTimer=void 0;const e=this.fileEditor;if(e===void 0||this.historySnapshot===void 0)return;const t=this.fileText();t!==this.historySnapshot&&(this.historySnapshot=t,this.historyAnswering=!1,e.replaceText(t,this.fileSyncActive()),this.fileTextApplied=e.text,this.syncHistoryButtons(),this.refreshEditorHead())}undo(){this.stepHistory(e=>e.undo(this.fileSyncActive()))}redo(){this.stepHistory(e=>e.redo(this.fileSyncActive()))}stepHistory(e){this.historyTimer!==void 0&&(clearTimeout(this.historyTimer),this.recordHistory());const t=this.fileEditor;t===void 0||this.isRecording||this.ufoElement.playbackState==="playing"||e(t)&&(clearTimeout(this.fileApplyTimer),this.applyFileText(t.text,!0),this.historyAnswering=!0,this.syncHistoryButtons(),this.refreshEditorHead())}syncHistoryButtons(){this.undoButton.disabled=!(this.fileEditor?.canUndo??!1),this.redoButton.disabled=!(this.fileEditor?.canRedo??!1)}resetHistory(){clearTimeout(this.historyTimer),this.historyTimer=void 0,this.historySnapshot=void 0,this.historyAnswering=!1,this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileTextApplied=void 0,this.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>{})}touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=zi.inspect(this.sightingData,this.loadedJson());if(e.length===0){this.downloadJson();return}this.askAboutIdentity(e)}loadedJson(){try{return this.baseline?JSON.parse(this.baseline):void 0}catch{return}}askAboutIdentity(e){const t={lastName:this.messages.identityLastName,firstNames:this.messages.identityFirstNames,nameInId:this.messages.identityNameInId,nameInText:this.messages.identityNameInText,address:this.messages.identityAddress,email:this.messages.identityEmail,phone:this.messages.identityPhone};this.shadow.getElementById("identity-ask-text").textContent=this.messages.identityAsk,this.shadow.getElementById("identity-ask-found").replaceChildren(...e.map(s=>{const r=document.createElement("li");return r.textContent=t[s.kind].replaceAll("{value}",s.found),r}));const n=e.some(s=>["lastName","firstNames","nameInId","nameInText"].includes(s.kind));this.shadow.getElementById("identity-ask-initials").hidden=!n,typeof this.identityAsk.showModal=="function"?this.identityAsk.showModal():this.identityAsk.setAttribute("open","")}closeIdentityAsk(){typeof this.identityAsk.close=="function"?this.identityAsk.close():this.identityAsk.removeAttribute("open")}writeNamesAsInitials(){const e=zi.namesOf(this.sightingData);this.observerLastNameInput.value=zi.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>zi.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=zi.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=zi.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=zi.withInitials(this.descriptionInput.value,e),this.touch(),this.updateObserverMetadata(),this.descriptionInput.dispatchEvent(new Event("input"))}async downloadJson(){const e=this.fileBase();let t=new Map;if(this.frozenPanel.hasWork()){this.exportButton.disabled=!0;try{t=await this.frozenPanel.prepare(e)}finally{this.exportButton.disabled=!1}}const i=this.sightingData;for(const r of Sn.NAMES){const a=this.sectionFilePanel.annex(r);if(a){/^[a-z][a-z0-9+.-]*:/i.test(a.src)||t.set(a.src,a.bytes);for(const o of Sn.KEYS[r])delete i[o]}}const n=`${e}.json`,s=this.writtenText(i);if(t.size===0)this.download(new Blob([s],{type:"application/json"}),n);else{const{zipSync:r,strToU8:a}=await ae(async()=>{const{zipSync:h,strToU8:d}=await import("./browser-_Ncw3Jhn.js");return{zipSync:h,strToU8:d}},[],import.meta.url),o={[n]:a(s)};for(const[h,d]of t)o[h]=d;const c=r(o,{level:0});this.download(new Blob([c],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.frozenExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",Vi.size(c.length)))}this.markClean()}fileBase(){const e=this.sceneElement.documentUrl?.split(/[?#]/)[0].split("/").pop();return e?.endsWith(".json")&&e.length>5?decodeURIComponent(e.slice(0,-5)):`${this.sightingData.observer?.id??"sighting"}-sighting`}refreshFileItems(){const e=this.fileItemSelect;if(!e)return;this.syncFilePickers();const t=e.value||"recording";e.replaceChildren(new Option(this.messages.fileItemRecording,"recording"),...Sn.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...Bi.NAMES.map(i=>new Option(this.frozenPanel.itemLabel(i),i))),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=Bi.NAMES.includes(e),i=Sn.NAMES.includes(e)?e:void 0;this.shadow.getElementById("file-recording").hidden=t||i!==void 0,this.shadow.getElementById("frozen-data").hidden=!t,this.shadow.getElementById("file-section").hidden=i===void 0;for(const s of["file-recording","frozen-data","file-section"]){const r=this.shadow.getElementById(s);r.hidden||ps.glue(r)}t&&this.frozenPanel.show(e),i&&this.sectionFilePanel.show(i);const n=t&&this.frozenPanel.isInlineGroup(e)?["frozen",e,"src"]:i&&this.sectionFilePanel.isInline(i)?Xf.pathOf(i):void 0;this.fileEditorHost.hidden=(t||i!==void 0)&&n===void 0,n&&this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(s=>{this.syncFileEditor(!1),s.reveal(n)},()=>{})}sectionFromFile(e){return Sn.fromFile(this.ufoElement.sighting.frozen,e)}masterUrl(){return this.sceneElement.documentUrl??new URL(`${this.fileBase()}.json`,location.href).href}weatherFileItemLabel(){return this.sectionFilePanel?.itemLabel("weather")??""}download(e,t){const i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=t,n.click(),URL.revokeObjectURL(i)}freezerSources(){const e=Zi(ap,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:Zi(Ll,this.chosenSourceId.get("imagery")).id,roads:k2(),water:C2(),railways:L2()}}async importFromFile(e){this.holdLoad(()=>void this.loadFile(e))||await this.loadFile(e)}async loadFile(e){try{const t=new Uint8Array(await new Promise((s,r)=>{const a=new FileReader;a.onload=()=>s(a.result),a.onerror=()=>r(a.error),a.readAsArrayBuffer(e)}));St.release();const i=await this.recordingText(t),n=JSON.parse(i);if(_i.isCase(n)){if(_i.check(n),this.offerCase(n,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=n,this.resetHistory(),this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importInput.url=""}catch(t){window.alert(this.importErrorFor(t))}}async recordingText(e){if(e[0]!==80||e[1]!==75)return new TextDecoder().decode(e);const{unzipSync:t,strFromU8:i}=await ae(async()=>{const{unzipSync:d,strFromU8:u}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:d,strFromU8:u}},[],import.meta.url),n=t(e),s=/\.(relief|imagery|map)\.zip$|\.(roads|water|railways|upper-air|weather)\.json$/,r=Object.keys(n).find(d=>d.endsWith(".json")&&!s.test(d));if(!r)throw new Error("No recording in this archive");const a=r.includes("/")?r.slice(0,r.lastIndexOf("/")+1):"";for(const[d,u]of Object.entries(n))d!==r&&d.startsWith(a)&&St.hold(St.address(d.slice(a.length),void 0),u);const o=i(n[r]),c=JSON.parse(o);let h=!1;for(const d of Sn.NAMES){const u=c.frozen?.[d]?.src,p=u!==void 0?n[a+u]:void 0;if(!p)continue;const f=JSON.parse(i(p));for(const m of Sn.KEYS[d])f[m]!==void 0&&(c[m]=f[m]);h=!0}return h?JSON.stringify(c):o}offerCase(e,t){return!this.dispatchEvent(new CustomEvent("caseloaded",{detail:{json:e,url:t},bubbles:!0,composed:!0,cancelable:!0}))}bodyShapeIds(){return this.accountShapeIds?[...this.accountShapeIds]:this.ufoElement.sighting.timeline.sourceIds}set documentUrl(e){this.sceneElement.documentUrl=e}async importFromUrl(e=this.importInput.url){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){try{const t=await kr.recording(e);if(_i.isCase(t)){_i.check(t);const n=new URL(e,location.href).href;if(this.offerCase(t,n)){this.importInput.url=n;return}throw new Error("A case has no recording to edit here")}const i=t;St.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=new URL(e,location.href).href,this.resetHistory(),this.importInput.url=new URL(e,location.href).href,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(e instanceof Ad)return e.said(this.messages.formatVersionError);if(!(e instanceof Vo))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";static SCENERY_STORAGE="rr0-sighting-editor.surroundings";static SCENERY_RADIUS_STORAGE="rr0-sighting-editor.surroundings-radius";static NO_SCENERY="none";narrativeProvider=hu[0].create();get narrativeSourceId(){return Zi(hu,this.chosenSourceId.get("narrative")).id}narrativeAbort;async draftFromDescription(){const e=this.descriptionInput.value.trim();if(e===""||this.narrativeAbort)return;const t=this.narrativeAbort=new AbortController;this.setNarrativeBusy(!0);try{const i=await this.narrativeProvider.draft({ask:e,current:this.sightingData,language:Ce.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const n=i instanceof Gs&&i.kind==="cancelled";this.narrativeStatus.textContent=n?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!n)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:n,...s}=i,r=i.timeZone?s:i,a=qr.stated(r);if(a.length>0){const o=this.ufoElement.sighting.provenance,c=Rg(this.ufoElement.sighting);this.sightingData=qr.apply(c,df.loadable(r),a),this.ufoElement.sighting.provenance=o,this.recordNarrativeProvenance(e,a),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=a.length>0?this.messages.narrativeApplied.replace("{count}",String(a.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const i=this.ufoElement.sighting,n=new Set(t);for(const s of e.claims)!n.has(s.path)&&!t.some(r=>s.path.startsWith(`${r}.`))||i.provenance.set(s.path,{basis:s.basis,rationale:s.rationale,of:Ce.valueAt(Rg(this.ufoElement.sighting),s.path)})}static valueAt(e,t){let i=e;for(const n of t.split(".")){if(typeof i!="object"||i===null)return;i=i[n]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(n=>n.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[hN[t]]));for(const n of i){const s=document.createElement("div");s.className=`claim ${t}`;const r=document.createElement("code");r.textContent=n.path;const a=document.createElement(t==="stated"?"q":"span");a.textContent=n.rationale,s.append(r,a),this.narrativeReport.append(s)}}}if(e.gaps.length>0){this.narrativeReport.append(this.narrativeHeading(this.messages.narrativeGaps));const t=document.createElement("ul");t.className="gaps";for(const i of e.gaps){const n=document.createElement("li");n.textContent=i,t.append(n)}this.narrativeReport.append(t)}this.narrativeReport.hidden=this.narrativeReport.childElementCount===0}narrativeHeading(e){const t=document.createElement("h4");return t.textContent=e,t}setNarrativeBusy(e){this.descriptionInput.disabled=e,this.narrativeStopButton.hidden=!e,e&&(this.narrativeStatus.textContent=this.messages.narrativeWorking,this.narrativeStatus.classList.remove("error")),this.syncNarrativeEnabled()}syncNarrativeEnabled(){const e=Zi(hu,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(n=>n.required&&(this.narrativeSettingInputs.get(n.id)?.value.trim()??"")===""),i=this.descriptionInput.value.trim()==="";this.narrativeDraftButton.disabled=!!this.narrativeAbort||t!==void 0||i,this.narrativeDraftButton.title=t?this.messages.narrativeNeedsSetting.replace("{setting}",this.said.read(t.label)??t.id).replace("{source}",e):i?this.messages.narrativeNeedsAsk:"",this.narrativeRememberInput.parentElement.hidden=!this.narrativeProvider.settings.some(n=>n.remembered==="credential");for(const n of this.narrativeProvider.settings){const s=this.narrativeSettingInputs.get(n.id);if(!s||!n.suspect)continue;const r=s.value.trim(),a=r===""?void 0:n.suspect(r);s.classList.toggle("invalid",a!==void 0),s.title=a?this.said.read(a)??"":this.said.read(n.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const n=document.createElement("label"),s=document.createElement("span");s.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const o of i.choices??[]){const c=document.createElement("option");c.value=o.value,c.textContent=this.said.read(o.label)??o.value,r.appendChild(c)}}else r=document.createElement("input"),r.type=i.kind==="secret"?"password":"text",r.autocomplete="off",r.spellcheck=!1,r.placeholder=this.said.read(i.placeholder)??"";r.id=`narrative-${i.id}`,r.title=this.said.read(i.hint)??"";const a=e[i.id]??this.storedNarrativeSetting(i.id);return a!==void 0&&(r.value=a),r.addEventListener(i.kind==="choice"?"change":"input",()=>{this.rememberNarrativeSettings(),this.syncNarrativeEnabled()}),this.narrativeSettingInputs.set(i.id,r),n.append(s,document.createTextNode(" "),r),n});this.narrativeSettingsBox.replaceChildren(...t),this.narrativeRememberInput.checked=this.narrativeProvider.settings.some(i=>i.remembered==="credential"&&this.storedNarrativeSetting(i.id)!==void 0),this.syncNarrativeEnabled()}narrativeSettingValues(){const e={};for(const[t,i]of this.narrativeSettingInputs){const n=i.value.trim();n!==""&&(e[t]=n)}return e}narrativeErrorFor(e){if(!(e instanceof Gs))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}rememberNarrativeSettings(){try{for(const e of this.narrativeProvider.settings){const t=this.narrativeStorageKey(e.id),i=this.narrativeSettingInputs.get(e.id)?.value??"";(e.remembered==="preference"||e.remembered==="credential"&&this.narrativeRememberInput.checked)&&i!==""?localStorage.setItem(t,i):localStorage.removeItem(t)}localStorage.removeItem(Ce.NARRATIVE_KEY_STORAGE),localStorage.removeItem(Ce.NARRATIVE_SCOPE_STORAGE)}catch{}}narrativeStorageKey(e){return`rr0-sighting-editor.narrative.${this.narrativeSourceId}.${e}`}storedNarrativeSetting(e){try{const t=localStorage.getItem(this.narrativeStorageKey(e));if(t!==null)return t;if(this.narrativeSourceId!=="claude")return;const i=e==="key"?Ce.NARRATIVE_KEY_STORAGE:e==="workspace"?Ce.NARRATIVE_SCOPE_STORAGE:void 0;return i&&localStorage.getItem(i)||void 0}catch{return}}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const i=(e%360+360)%360;return String(i)!==t.value&&(t.value=String(i)),i}refreshSourceRows(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),Ce.creditLink(Zi(Q0,this.chosenSourceId.get("place")))),this.weatherSourceRow.replaceChildren(),this.fillWeatherProvider(),this.sourcePickers(this.shadow.getElementById("weather-source-rows"),"weather-source-kind","weather",[["weather",this.messages.fileItemWeather,this.shadow.getElementById("weather-picker")],["upper-air",this.messages.frozenUpperAir,this.sourcePicker("upper-air",V6,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),Ce.creditLink(Zi(cp,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",hu,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.sourcePickers(this.terrainSourceRows,"source-kind","location",[["place",this.messages.fileItemPlace,this.sourcePicker("place",Q0,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",cp,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",ap,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",Ll,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.frozenRoads,this.sourcePicker("roads",[Ce.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.frozenWater,this.sourcePicker("water",[Ce.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.frozenRailways,this.sourcePicker("railways",[Ce.LIVE_RAILWAYS],()=>{},this.groupChoice(["railways"]))]]),this.sourcePickers(this.shadow.getElementById("decor-source-rows"),"decor-source-kind","decor",[["scenery",this.messages.fileItemDecor,this.shadow.getElementById("scenery-picker")],["aircraft",this.messages.sourceAircraft,this.sourcePicker("aircraft",Fv,()=>this.applyAircraftSource())],["decor-model",this.messages.decorModel,this.sourcePicker("decor-model",_p,()=>this.applyDecorModelSource())]])}sourcePicker(e,t,i,n){const s=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;for(const d of t){const u=document.createElement("option");u.value=d.id,u.textContent=d.name,u.title=d.credit,r.appendChild(u)}n&&r.appendChild(new Option(this.messages.sourceFile,Ce.FILE_SOURCE));const a=()=>this.chosenSourceId.get(e)??t[0].id;r.value=n?.fromFile()?Ce.FILE_SOURCE:a();const o=document.createElement("a");o.className="source-credit",o.target="_blank",o.rel="noopener noreferrer";const c=document.createElement("button");c.type="button",c.className="link source-file-link",c.addEventListener("click",()=>this.openFileItem(n.item));const h=()=>{const d=r.value===Ce.FILE_SOURCE,u=Zi(t,d?a():r.value);r.title=d?n.where():u.credit,o.hidden=d,o.href=u.creditUrl,o.textContent=u.credit,c.hidden=!d,d&&(c.textContent=n.label(),c.title=n.where())};return h(),r.addEventListener("change",()=>{const d=r.value===Ce.FILE_SOURCE;d||this.chosenSourceId.set(e,r.value),n?.setFromFile(d),h(),d||i(Zi(t,r.value))}),n&&this.filePickers.set(e,()=>{r.value=n.fromFile()?Ce.FILE_SOURCE:a(),h()}),s.append(r,document.createTextNode(" "),o,c),s}groupChoice(e){return{item:e[0],fromFile:()=>!this.frozenPanel.isLive(e[0]),setFromFile:t=>{for(const i of e)this.frozenPanel.setLive(i,!t)},label:()=>this.frozenPanel.itemLabel(e[0]),where:()=>this.frozenPanel.where(e[0])}}sectionChoice(e,t){return{item:e,fromFile:()=>this.sectionFromFile(e),setFromFile:i=>{const n={...this.ufoElement.sighting.frozen??{}};i?n[e]=n[e]??{}:delete n[e],this.ufoElement.sighting.frozen=Bi.isEmpty(n)?void 0:n,this.touch(),this.scheduleFileSync(),this.refreshFileItems(),i||t()},label:()=>this.sectionFilePanel.itemLabel(e),where:()=>this.sectionFilePanel.where(e)}}static FILE_SOURCE="file";filePickers=new Map;syncFilePickers(){for(const e of this.filePickers.values())e()}openFileItem(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-file");t&&this.toggleGroup(t,!0),this.fileItemSelect.value=e,this.showFileItem(e)}static LIVE_ROADS={id:"ign-osm",name:"IGN BD TOPO / OpenStreetMap",credit:"© IGN, BD TOPO (Licence Ouverte 2.0) in France; © OpenStreetMap contributors (ODbL) elsewhere",creditUrl:"https://www.openstreetmap.org/copyright",create:()=>{}};static LIVE_WATER=Ce.LIVE_ROADS;static LIVE_RAILWAYS=Ce.LIVE_ROADS;sourcePickers(e,t,i,n){const s=document.createElement("label"),r=document.createElement("span");r.id=`label-${t}`,r.textContent=this.messages.sourceKind;const a=document.createElement("select");a.id=t;const o=n.map(([h,d,u])=>{a.append(new Option(d,h));const p=document.createElement("span");return p.className="source-picker",p.dataset.kind=h,p.append(u),p});a.value=this.sourceKindShown.get(i)??n[0][0];const c=()=>{this.sourceKindShown.set(i,a.value);for(const h of o)h.hidden=h.dataset.kind!==a.value};a.addEventListener("change",c),c(),s.append(r,document.createTextNode(" "),a),e.replaceChildren(s,...o)}sourceKindShown=new Map;static creditLink(e){const t=document.createElement("a");return t.className="source-credit",t.target="_blank",t.rel="noopener noreferrer",t.href=e.creditUrl,t.textContent=e.credit,t}refreshSourceCredits(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),Ce.creditLink(Zi(Q0,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),Ce.creditLink(Zi(cp,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:Zi(ap,this.chosenSourceId.get("elevation")).create(),imagery:Zi(Ll,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(Zi(Fv,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=Zi(_p,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.decorModelEntries=void 0,this.refreshDecorModelOptions(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId)),this.ufoElement.refresh()}get placeSearchLanguage(){return navigator.languages?.[0]}set placeSearchProvider(e){this.placeProvider=e}async searchPlace(){const e=this.placeNameInput.value.trim();if(e===""||this.sectionFromFile("place"))return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let i;try{i=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=i,this.refreshPlaceMatches(),i.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const i=document.createElement("option");return i.textContent=t.name,i.title=t.name,i})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates||this.sectionFromFile("place"))return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||Math.abs(e-this.namedCoordinates.lat)<Ec&&Math.abs(t-this.namedCoordinates.lng)<Ec||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),sx))}timeZoneIsStated(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone!==this.autoFilledTimeZone:e.utcOffsetHours!==void 0}scheduleTimeZoneLookup(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);if(e===void 0||t===void 0||this.timeZoneIsStated())return;const i=this.timeZoneLookedUpAt;i&&Math.abs(e-i.lat)<Ec&&Math.abs(t-i.lng)<Ec||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),sx))}async lookUpTimeZone(e,t){this.timeZoneLookedUpAt={lat:e,lng:t};const i=await this.timeZoneProvider.zoneAt(e,t);this.placeZone=i??void 0,!(!i||this.timeZoneIsStated())&&this.timeZones.available().includes(i)&&(this.autoFilledTimeZone=i,this.timeZoneSelect.value=i,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange")))}async reversePlace(e,t){const i=++this.placeSearchToken;let n;try{n=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}if(i!==this.placeSearchToken)return;this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=n?.name??"",this.placeNameInput.title=n?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=n?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!n;const s=this.ufoElement.sighting.event.place?.[0]??{lat:e,lng:t};this.ufoElement.sighting.event.place=[{lat:s.lat,lng:s.lng,name:this.stringOrUndefined(this.placeNameInput.value.trim())}]}updateObserver(){if(this.refreshHeadingPoint(),this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),i=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),n=this.numberOrUndefined(this.pitchInput.value)??0,s=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,a=Math.max(0,r-(this.groundElevationM??0)),o=this.ufoElement.sighting.event,c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());o.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),f=(u.frame&&p!==void 0?hi.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),m=this.numberOrUndefined(this.fNumberInput.value),v=this.filterSelect.value,g=Ci.byId(c.getLatestPoseAt(h-1)?.filter),y=v===Ci.NONE.id||v===""?g===Ci.NONE?void 0:Ci.NONE.id:v,w=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=w===u.exposureSeconds?void 0:w;const b=this.numberOrUndefined(this.focusDistanceInput.value),M=Math.abs(f-hi.fieldOfViewDeg(u))>.01||m!==u.fNumber||b!==void 0||y!==void 0;e===void 0&&t===void 0&&i===void 0&&n===0&&s===0&&a===0&&!M?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:a,headingDeg:i,pitchDeg:n,rollDeg:s===0?void 0:s,...this.observerSaid&&e!==void 0?{saidPosition:this.observerSaid}:{},fovDeg:f,fNumber:m,focusDistanceM:b,filter:y});const E=this.plantingCentre();this.surroundings.placeChanged(E?.lat,E?.lng),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}syncAgeFromBirth(e){const t=this.birth,i=this.ufoElement.sighting.event.time;if(!t||!i||e&&!lp.isFirm(t))return;const n=lp.at(t,i);n!==void 0&&(this.observerAgeInput.value=String(n),this.updateObserverMetadata())}syncBirthFromAge(){const e=this.ufoElement.sighting.event.time,t=this.numberOrUndefined(this.observerAgeInput.value);if(!e||t===void 0)return;const i=this.birth;if(i&&lp.at(i,e)===t)return;const n=lp.birthFor(t,e);n&&(this.birthDate.setPrecise(!1),this.birth=n,this.birthDate.time=n,this.updateObserverMetadata())}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.refreshSceneryWarning(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&lh({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.sighting.event.durationText=void 0,this.ufoElement.durationSeconds=void 0)}refreshTimeZoneOptions(){let e=this.timeZoneSelect.options[0];if(!e){e=document.createElement("option"),e.value="";const t=this.timeZoneSelect.parentNode,i=this.timeZoneSelect.nextSibling;this.timeZoneSelect.remove(),this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(n=>{const s=document.createElement("option");return s.value=n,s.textContent=n,s})),t?.insertBefore(this.timeZoneSelect,i)}e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.value=this.zoneShown()}zoneShown(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone:e.utcOffsetHours===void 0?"":this.preferredZoneFor(e.utcOffsetHours)??""}updateTimeZone(){const e=this.ufoElement.sighting.event,t=this.stringOrUndefined(this.timeZoneSelect.value);if(e.timeZone=t,this.offsetIsAuthors=!1,t===void 0){e.utcOffsetHours=void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup();return}this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event;if(this.offsetIsAuthors&&e.utcOffsetHours!==void 0){const t=this.preferredZoneFor(e.utcOffsetHours);e.timeZone=t,this.timeZoneSelect.value=t??""}else{const t=e.timeZone?this.timeZones.offsetHoursAt(e.timeZone,this.timeZoneReference()):void 0;t!==void 0&&(e.utcOffsetHours=t)}this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}timeZoneReference(){const e=this.ufoElement.sighting.event.time;return e?.year!==void 0?e:{year:new Date().getFullYear(),month:1,day:1,hour:12}}preferredZoneFor(e){const t=this.timeZones.zonesAt(e,this.timeZoneReference());if(t.length===0)return;const i=this.ufoElement.sighting.event.timeZone;if(i&&t.includes(i))return i;if(this.placeZone&&t.includes(this.placeZone))return this.placeZone;const n=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return n&&t.includes(n)?n:t[0]}updateUtcOffset(){const e=this.ufoElement.sighting.event,t=this.numberOrUndefined(this.utcOffsetInput.value);if(t===void 0)e.utcOffsetHours=void 0,e.timeZone=void 0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value="";else{const i=this.preferredZoneFor(t);if(i===void 0){this.utcOffsetInput.classList.add("invalid"),this.utcOffsetInput.title=this.messages.utcOffsetNoZone;return}e.utcOffsetHours=t,e.timeZone=i,this.offsetIsAuthors=!0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value=i}this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObserverMetadata(){const e=this.ufoElement.sighting,t=this.observerFirstNamesInput.value.split(",").map(n=>n.trim()).filter(n=>n.length>0),i={id:this.stringOrUndefined(this.observerIdInput.value),title:this.observerTitleInput.value.trim()===""?void 0:this.said.write(e.observer?.title,this.observerTitleInput.value.trim(),this.writingLanguage),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0};e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,e.id=this.stringOrUndefined(this.sightingIdInput.value),this.updateAccount(),this.ufoElement.refresh()}updateAccount(){const e=this.ufoElement.sighting,t=this.accountFollowedUpSelect.value,i={observerAgeYears:this.numberOrUndefined(this.observerAgeInput.value),observerBirth:this.birth,observerPerception:Ol.compact(this.perceptionSettings.values),observerOccupation:this.observerOccupationInput.value.trim()===""?void 0:this.said.write(e.account?.observerOccupation,this.observerOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.accountSourceSelect.value),followedUp:t===""?void 0:t==="yes",conditions:e.account?.conditions};e.account=Object.values(i).some(n=>n!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...n]=e.sources??[],{url:s,...r}=i??{},a=t===""?r:{...r,url:t},o=Object.keys(a).length>0?[a,...n]:n;e.sources=o.length>0?o:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState()):this.ufoElement.sighting.weatherSource!==void 0&&(this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...en(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={...en(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value),rareIceCrystals:Number(this.rareIceCrystalsInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(n=>n.id===this.currentReferenceId),t=e!==void 0;ps.showPresence(this.shadow.getElementById("reference-row"),this.shadow.getElementById("reference-item"),t),this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const n of[this.referenceSelect,...this.referenceFields])n.disabled=!t;if(this.referenceSourceInput.disabled=!t,this.refreshLandmarkList(),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSourceInput.url=i?"":e.src,this.referenceSourceInput.mode=i?"file":"url",this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.ghostFinding&&(this.ghostFinding.referenceId!==e.id||this.ghostFinding.src!==e.src)&&(this.ghostFinding=void 0,this.ghostsStatus.textContent="",this.syncGhostsShown(),this.ufoElement.refresh()),this.referenceOpacityInput.value=String(e.opacity),this.referenceHeadingInput.value=String(e.registration.headingDeg),this.referencePitchInput.value=String(e.registration.pitchDeg),this.referenceRollInput.value=String(e.registration.rollDeg??0),this.referenceFovInput.value=String(e.registration.fovDeg),this.syncReferenceStatus(e)}syncReferenceStatus(e){const t=this.sceneElement.referenceFailure(e.src);if(Wt.show(this.referenceFailure,t?this.pictureFailureText(t):void 0,"error"),this.syncFindGhosts(e),this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const i=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>x6?this.messages.referenceEmbedded.replace("{kb}",String(i)):"";return}this.referenceStatus.textContent=""}pictureFailureText(e){switch(e.kind){case"notShared":return this.messages.referenceNotShared;case"status":return this.messages.referenceNotFound.replace("{status}",String(e.status));case"notPicture":return this.messages.referenceNotPicture;default:return this.messages.referenceUnreachable}}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,i=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(s=>{if(s.id!==this.currentReferenceId)return s;const r=s.src,a={headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||hp))},o=s.registration,c=a.headingDeg!==o.headingDeg||a.pitchDeg!==o.pitchDeg||a.rollDeg!==o.rollDeg||a.fovDeg!==o.fovDeg;return{...s,kind:this.referenceKindSelect.value,src:r,title:this.said.write(s.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:i===void 0||Number.isNaN(i)?void 0:Math.round(i*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:a,from:c?this.observerPositionNow()??s.from:s.from}});const n=e.references.find(s=>s.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(n),this.syncReferenceStatus(n),this.ufoElement.refresh()}useObserverPoseForReference(){const e=pt(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(e.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=pt(this.ufoElement.sighting,this.ufoElement.currentTime);return e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0}addReference(e,t,i={}){const n=this.ufoElement.sighting,s=pt(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${n.references.length+1}`,a={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:M6,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:hp},from:this.observerPositionNow(),...i};n.references=[...n.references,a],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSourceInput.mode="url",this.referenceSourceInput.focus()}addReferenceFromFile(){this.addReference(""),this.referenceSourceInput.mode="file",this.referenceSourceInput.openPicker()}async setReferenceSource(e){const t=this.currentReferenceId;if(t===void 0)return;let i;if(e.file){const s=e.file;i=await new Promise((r,a)=>{const o=new FileReader;o.onload=()=>r(o.result),o.onerror=()=>a(o.error),o.readAsDataURL(s)})}else i=e.url;const n=this.ufoElement.sighting;n.references=n.references.map(s=>s.id!==t?s:{...s,src:i,title:s.title??(e.file?this.said.write(void 0,e.file.name.replace(/\.[^.]+$/,""),this.writingLanguage):void 0)}),this.touch(),this.refreshReferenceList(),this.ufoElement.refresh()}pictureAspect(e){if(!this.pictureRegistration){this.loadPictureRegistration();return}return this.sceneElement.referenceAspect(e)}loadPictureRegistration(){return this.pictureRegistrationLoading??=ae(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-ZngZKmqH.js");return{PictureRegistration:e}},[],import.meta.url).then(({PictureRegistration:e})=>{this.pictureRegistration=e,this.ufoElement.refresh()})}currentReference(){return this.ufoElement.sighting.references.find(e=>e.id===this.currentReferenceId)}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const n=this.pictureAspect(t.id);if(!(n!==void 0&&this.pictureRegistration.picturePointOf(this.directionAtCanvasPoint(e),t.registration,n)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.pictureAspect(t.id):void 0;if(!t||i===void 0)return;const n=8;for(const s of this.currentLandmarks()){const r=this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(s.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=n)return{landmarkId:s.id,end:"picture"};const a=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(s.scene));if(a&&Math.hypot(a.x-e.x,a.y-e.y)<=n)return{landmarkId:s.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,i=this.canvasPointFromEvent(e);if(!t||!i)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,i);return}const n=i.x-t.startPointer.x,s=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(n,s)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+n*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-s*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const n=this.currentReference(),s=n?this.pictureAspect(n.id):void 0;if(!n||s===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(a=>{if(a.id!==e)return a;if(t==="scene")return{...a,scene:this.pictureRegistration.aimOf(r)};const o=this.pictureRegistration.picturePointOf(r,n.registration,s);return o?{...a,picture:o}:a})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||hp,i=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(i)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const i=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const r=this.pictureAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const a=this.pictureRegistration.picturePointOf(i,t.registration,r);if(!a){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=a,this.syncRegisterStatus(),this.ufoElement.refresh();return}const n=this.currentLandmarks(),s=this.nextLandmarkId(n);this.writeLandmarks([...n,{id:s,picture:this.pendingLandmark,scene:this.pictureRegistration.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=s,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(i=>i.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.pictureAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),n=this.pictureRegistration.solve(i,t,e.registration.fovDeg);n?(this.referenceFit={n:i.length,residualDeg:n.residualDeg},this.referenceHeadingInput.value=String(this.rounded(n.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(n.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(n.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(n.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return this.pictureRegistration.worldDirectionOf(e.picture,t.registration,i).angleTo(this.pictureRegistration.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const i=this.said.read(e.label);return i?`${t+1} · ${i}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),i=e?this.pictureAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[s,r]of t.entries()){const a=document.createElement("option");a.value=r.id;const o=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";a.textContent=this.landmarkLabel(r,s)+o,this.referenceLandmarksSelect.appendChild(a)}this.currentLandmarkId!==void 0&&!t.some(s=>s.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const n=t.find(s=>s.id===this.currentLandmarkId);ps.showPresence(this.shadow.getElementById("reference-landmark-row"),this.shadow.getElementById("reference-landmark-item"),t.length>0),this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=n===void 0,this.referenceLandmarkLabelInput.disabled=n===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(n?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(a=>a.id===e?{...a,label:this.said.write(a.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:a));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),n=i.findIndex(a=>a.id===e),s=this.currentReference(),r=s?this.pictureAspect(s.id):void 0;if(t&&n>=0){const a=s&&r!==void 0?` · ${this.landmarkResidualDeg(i[n],s,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[n],n)+a}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.pictureAspect(t.id);if(i===void 0)return;const{registration:n}=t,s=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(a=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a,n,i))),r=this.currentLandmarks().map((a,o)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a.picture,n,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(a.scene)),label:this.landmarkLabel(a,o),selected:a.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(a,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(this.pendingLandmark,n,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(a=>a!==void 0)?s:void 0,r.filter(a=>a.picture!==void 0),this.landmarkHint()),this.paintGhostFinding(e,t,i)};paintGhostFinding(e,t,i){const n=this.ghostFinding;if(!n||!this.ghostsShown||n.referenceId!==t.id||n.src!==t.src)return;const{search:s}=n,r=t.registration,a=d=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf({u:d.x/s.width,v:d.y/s.height},r,i)),o=[];for(const d of s.pairs){const u=a(d.ghost),p=a(d.light),f=a({x:d.ghost.x+d.ghost.radius,y:d.ghost.y});!u||!p||o.push({ghost:u,light:p,ghostRadius:f?Math.hypot(f.x-u.x,f.y-u.y):0})}const c=s.centre?a(s.centre):void 0,h=s.cropped?a({x:s.width/2,y:s.height/2}):void 0;e.paintGhosts(o,c,h)}adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:n}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(n??0)),this.updateObserver();const s=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(c=>c.t===s);if(r<0)return;const a=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),o=[["headingDeg",t],["pitchDeg",i],["rollDeg",n??0]];for(const[c,h]of o)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${c}`,{basis:"derived",rationale:a,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceAddMenu.setDisabled("street",e?void 0:this.messages.referenceStreetNoPlace)}setReferenceAddKinds(e,t,i){const n=this.numberOrUndefined(this.latInput?.value??"")!==void 0&&this.numberOrUndefined(this.lngInput?.value??"")!==void 0;this.referenceAddMenu.setKinds([{value:"address",label:e},{value:"file",label:t},{value:"street",label:i,...n?{}:{disabledReason:this.messages?.referenceStreetNoPlace??""}}])}addReferenceOfKind(e){switch(e){case"file":this.addReferenceFromFile();break;case"street":this.searchStreetPictures();break;default:this.addReferenceFromAddress()}}async searchStreetPictures(){const e=pt(this.ufoElement.sighting,0),t=e?.lat??this.numberOrUndefined(this.latInput.value),i=e?.lng??this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const n=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.addReferenceButton.disabled=!0;try{this.streetPictures$??=new(await ae(async()=>{const{PanoramaxPictures:r}=await import("./PanoramaxPictures-CELY3Ecc.js");return{PanoramaxPictures:r}},[],import.meta.url)).PanoramaxPictures,this.streetPictures=await this.streetPictures$.nearby(t,i,n)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.addReferenceButton.disabled=!1;return}this.addReferenceButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,a]of this.streetPictures.entries()){const o=document.createElement("option");o.value=String(r),o.textContent=this.streetPictureLabel(a,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(o)}const s=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!s,this.referenceStreetAddButton.hidden=!s,this.referenceStatus.textContent=s?"":this.messages.referenceStreetNone.replace("{m}",String(n))}streetPictureLabel(e,t){return t.replace("{distance}",String(Math.round(e.distanceM))).replace("{bearing}",String(Math.round(e.bearingDeg))).replace("{date}",e.takenAt.slice(0,10)).replace("{panorama}",e.panorama?this.messages.referenceStreetPanorama:"")}addStreetPicture(){const e=this.streetPictures[Number(this.referenceStreetSelect.value)];e&&this.addReference(e.src,this.streetPictureLabel(e,this.messages.referenceStreetTitle),{kind:e.panorama?"panorama":"photo",credit:e.credit,creditUrl:e.creditUrl,registration:{headingDeg:e.azimuthDeg??0,pitchDeg:0,fovDeg:hp}})}traceLabel(e){const t=e.kind==="point"?this.messages.traceKindPoint:e.kind==="line"?this.messages.traceKindLine:this.messages.traceKindPolygon,i=this.said.read(e.title);return i?`${i} (${t})`:`${e.id} (${t})`}refreshTraceList(){const e=this.ufoElement.sighting.traces;this.traceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.traceLabel(t),this.traceSelect.appendChild(i)}e.some(t=>t.id===this.currentTraceId)||(this.currentTraceId=e[0]?.id),this.currentTraceId!==void 0&&(this.traceSelect.value=this.currentTraceId),this.syncTraceFields()}selectTrace(e){this.currentTraceId=e,this.syncTraceFields()}syncTraceFields(){const e=this.ufoElement.sighting.traces.find(i=>i.id===this.currentTraceId),t=e!==void 0;ps.showPresence(this.shadow.getElementById("trace-row"),this.shadow.getElementById("trace-item"),t);for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t;this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(n=>n.id!==this.currentTraceId?n:{...n,title:this.said.write(n.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(n.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(n=>n.value===this.currentTraceId),i=e.traces.find(n=>n.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTraces(e){const t=e.file?.name??decodeURIComponent(e.url.split("/").pop()??e.url);let i;try{const{KmlImport:h}=await ae(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url);i=await h.fromBytes(await Wb.bytesOf(e))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(i.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const n=this.ufoElement.sighting,s=new Set(n.traces.map(h=>h.id));let r=1;const a=this.said.write(void 0,i.documentName??t,this.writingLanguage),o=i.traces.map(h=>{for(;s.has(`trace-${r}`);)r++;const d=`trace-${r}`;return s.add(d),{...h,id:d,title:h.title===void 0?void 0:this.said.write(void 0,h.title,this.writingLanguage),source:a}});n.traces=[...n.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const c=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",t)+c,this.ufoElement.refresh()}deleteTrace(){if(this.currentTraceId===void 0)return;const e=this.ufoElement.sighting;e.traces=e.traces.filter(t=>t.id!==this.currentTraceId),this.currentTraceId=e.traces[0]?.id,this.refreshTraceList(),this.ufoElement.refresh()}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of HE){const t=document.createElement("option");t.value=e,t.textContent=this.soundKindLabel(e,this.messages),this.soundKindOptions.set(e,t),this.soundKindSelect.appendChild(t)}}soundKindLabel(e,t){switch(e){case"hum":return t.soundHum;case"whistle":return t.soundWhistle;case"rumble":return t.soundRumble;case"crackle":return t.soundCrackle;default:return t.soundNone}}applySoundAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;const e=this.readSound();this.ufoElement.sighting.soundTrack.addKeyframe(this.ufoElement.currentTime,e),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e),this.ufoElement.refresh(),this.previewSound(e)}previewSound(e){clearTimeout(this.soundPreviewTimer),this.ufoElement.previewSound(e),this.soundPreviewTimer=setTimeout(()=>this.ufoElement.stopSoundPreview(),X6)}readSound(){return{kind:this.soundKindSelect.value,volume:Number(this.soundVolumeInput.value),pitchHz:Number(this.soundPitchInput.value),src:this.soundSrcInput.value.trim()||void 0}}syncSoundFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=Kv(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.soundKindSelect&&(this.soundKindSelect.value=e.kind),t!==this.soundVolumeInput&&(this.soundVolumeInput.value=String(e.volume)),t!==this.soundPitchInput&&(this.soundPitchInput.value=String(e.pitchHz)),t!==this.soundSrcInput&&(this.soundSrcInput.value=e.src??""),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e)}updateSoundPitchReadout(e){this.soundPitchValue.textContent=`${Math.round(e)} Hz`}updateSoundFieldsDisabledState(e){const t=e.kind==="none"&&!e.src;this.soundVolumeInput.disabled=t,this.soundSrcInput.disabled=t,this.soundPitchInput.disabled=t||e.src!==void 0}set weatherProvider(e){this.weatherInference=new q0(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===Ce.FILE_SOURCE;if(!e){const t=Zi(Ic,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new q0(t.create()))}if(this.setWeatherFromFile(e),this.weatherInferredInput.checked!==!e){this.weatherInferredInput.checked=!e,this.keepWeatherSource=e;try{this.weatherInferredInput.dispatchEvent(new Event("change"))}finally{this.keepWeatherSource=!1}}}keepWeatherSource=!1;setWeatherFromFile(e){const t=this.ufoElement.sighting;if(Sn.fromFile(t.frozen,"weather")===e)return;const i={...t.frozen??{}};e?i.weather={...i.weather??{},live:void 0}:delete i.weather,i.weather&&i.weather.live===void 0&&delete i.weather.live,t.frozen=Bi.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...Ic.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,Ce.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked;this.weatherProviderSelect.value=e?Ce.FILE_SOURCE:Zi(Ic,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const t=Zi(Ic,this.chosenSourceId.get("weather")),i=this.shadow.getElementById("weather-credit");i.hidden=e,i.href=t.creditUrl,i.textContent=t.credit,this.weatherFileLink.hidden=!e,e&&(this.weatherFileLink.textContent=this.weatherFileItemLabel(),this.weatherFileLink.title=this.sectionFilePanel?.where("weather")??"")}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.setWeatherFromFile(!this.weatherFromRecords),this.weatherFromRecords?this.scheduleWeatherLookup(!0):(this.cancelWeatherLookup(),this.keepWeatherSource||(this.ufoElement.sighting.weatherSource=void 0),this.syncWeatherSourceState())}scheduleWeatherLookup(e=!1){if(!this.weatherFromRecords||this.pendingWeatherEdit!==void 0)return;const t=this.ufoElement.sighting.weatherSource;!e&&t!==void 0&&!eg(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),nx))}cancelWeatherLookup(){clearTimeout(this.weatherLookupTimer),this.weatherLookupToken++,this.weatherLookupPending=!1}async inferWeather(){if(!this.weatherFromRecords)return;const e=++this.weatherLookupToken;this.weatherLookupPending=!0,this.syncWeatherSourceState();const t=await this.weatherInference.infer(this.ufoElement.sighting);e!==this.weatherLookupToken||!this.weatherFromRecords||(this.weatherLookupPending=!1,this.weatherLookupResult=t,t.status==="inferred"?(this.weatherInference.applyTo(this.ufoElement.sighting,t),this.weatherTrackSpan=this.ufoElement.seekableDuration,this.ufoElement.refresh(),this.syncWeatherFromTimeline()):this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}ensureWeatherTrackSpan(){const e=this.ufoElement.sighting.weatherSource;if(!this.weatherFromRecords||e===void 0||!eg(e))return;const t=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||t===this.weatherTrackSpan||(this.weatherTrackSpan=t,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const a of this.weatherFields)a.disabled=t&&e!==void 0&&a!==this.iceCrystalAlignmentInput&&a!==this.rareIceCrystalsInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?a.title=this.messages.weatherWhilePlaying:a.title===this.messages.weatherWhilePlaying&&(a.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&eg(e)){this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState();return}this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const n=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=n,this.labelWeatherInferred.title=n,this.syncWeatherProvider();const s=t&&e!==void 0;if(this.weatherSourceLink.hidden=!s,s){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const r=i?t?this.weatherStatusMessage():"":this.weatherUnavailableMessage();this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""||!i}startDateHalfEntered(){return this.shadow.getElementById("obs-time-native")?.validity.badInput===!0}weatherUnavailableMessage(){const e=this.weatherInference.missingOf(this.ufoElement.sighting);return this.startDateHalfEntered()&&(e.date=!0),e.date&&e.place?this.messages.weatherNeedsDateAndPlace:e.date?this.messages.weatherNeedsDate:this.messages.weatherNeedsPlace}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&zn(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`, ${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherLookupResult=void 0,this.weatherFromRecords=!Sn.fromFile(e.frozen,"weather")&&(e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0),this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=cp[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(this.sectionFromFile("lightPollution"))return!1;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),nx)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,n=this.lightPollutionProvider,s=e.event.time?.year,r=()=>{e.lightPollution!==void 0&&(e.lightPollution=void 0,e.provenance.clear("lightPollution"),this.lightPollutionInput.value="",this.ufoElement.refresh())};if(!t||t.lat===void 0||t.lng===void 0||s===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(s<n.year){r(),this.lightPollutionLookup={status:"too-early",year:s},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const a=await n.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=a,a.status==="found"?(e.lightPollution=a.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${n.citation}, at ${a.lat.toFixed(4)}, ${a.lng.toFixed(4)}: ${Math.round(a.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:a.lightPollution}),this.lightPollutionInput.value=String(a.lightPollution),this.ufoElement.refresh()):a.status==="natural"&&r(),this.syncLightPollutionStatus())}syncLightPollutionStatus(){const e=this.lightPollutionLookup,t=this.messages;let i="";switch(e?.status){case"pending":i=t.lightPollutionLookingUp;break;case"found":i=t.lightPollutionFound.replace("{artificial}",Math.round(e.artificialMcdPerM2*1e3).toLocaleString(this.language));break;case"natural":i=t.lightPollutionNatural;break;case"outside":i=t.lightPollutionOutside;break;case"failed":i=t.lightPollutionFailed;break;case"too-early":i=t.lightPollutionTooEarly.replace("{atlasYear}",String(this.lightPollutionProvider.year)).replace("{year}",String(e.year));break}this.lightPollutionStatusText.textContent=i===""?"":`${i} `,this.lightPollutionSourceRow.hidden=!(e?.status==="found"||e?.status==="natural"||e?.status==="outside")}syncDurationField(){const e=this.shadow.activeElement;if(e!==this.durationInput&&e!==this.durationElement.textField){const t=this.ufoElement.sighting.event,i=lh(t);this.durationElement.set(i!==void 0?i/1e3:void 0,t.durationText)}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("missing-required",e),this.markUnansweredQuestions(),this.durationInput.setAttribute("aria-invalid",String(e));const t=FA(this.ufoElement.sighting.event);this.durationElement.title=t==="imprecise"?this.messages.durationImprecise:""}syncPlaybackControls(){this.ensureWeatherTrackSpan();const e=this.ufoElement.playbackState==="playing",t=this.ufoElement.seekableDuration>0;Te.show(this.playPauseButton,e?"⏸":"▶"),this.playPauseButton.disabled=!t;const i=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch();for(const[n,s]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])n.title=s,n.setAttribute("aria-label",s);this.refreshTimelineMarks()}switchTimeDisplay(){this.ufoElement.toggleTimeDisplay(),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}syncTimeDisplaySwitch(){const e=this.ufoElement.canSwitchTimeDisplay,t=this.ufoElement.showingClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime;for(const[i,n]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${n} — ${t}`:n,i.classList.toggle("switchable",e),e?(i.setAttribute("role","button"),i.setAttribute("tabindex","0")):(i.removeAttribute("role"),i.removeAttribute("tabindex"))}chooseTimeInputMode(){const e=this.ufoElement.sighting.event;this.startDate.setPrecise(Cn.opensPrecise(e.time)),this.endDate.setPrecise(Cn.opensPrecise(e.endTime))}syncObservationTimeFields(){this.startDate.time=this.ufoElement.sighting.event.time}syncObservationEndTimeFields(){this.endDate.time=this.ufoElement.sighting.event.endTime}syncUtcOffsetField(){const e=this.ufoElement.sighting.event.utcOffsetHours;this.utcOffsetInput.value=e===void 0?"":String(e),this.updateUtcOffsetValidity()}updateUtcOffsetValidity(){const e=this.ufoElement.sighting.event.utcOffsetHours,t=this.ufoElement.sighting.event.place?.[0]?.lng,i=t===void 0?void 0:Math.round(t/15),n=e!==void 0&&i!==void 0&&Math.abs(e-i)>Z6;this.utcOffsetInput.classList.toggle("invalid",n),this.utcOffsetInput.title=n?this.messages.utcOffsetImplausible.replace("{solar}",i>=0?`+${i}`:String(i)):""}scheduleGroundElevation(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||this.groundElevationFor&&this.isSamePlace(this.groundElevationFor,e,t)||(clearTimeout(this.groundElevationTimer),this.groundElevationTimer=setTimeout(()=>void this.applyGroundElevation(e,t),q6))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Ec&&Math.abs(e.lng-i)<Ec}async applyGroundElevation(e,t){const i=++this.groundElevationToken,n=Zi(ap,this.chosenSourceId.get("elevation")),s=await new $b(n.create()).at(e,t);if(i!==this.groundElevationToken||s===void 0)return;this.groundElevationFor={lat:e,lng:t};const r=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(s),this.syncElevationField(r)}syncElevationField(e){const t=this.groundElevationM;this.elevationInput.value=String(Math.round((t??0)+e)),this.elevationInput.min=t===void 0?"":String(t),this.elevationInput.title=t===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=t===void 0||Math.round(e)===0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(pt(this.ufoElement.sighting,0)?.elevationM??0),this.scheduleGroundElevation()}syncPlaceNameField(){const e=this.ufoElement.sighting.event.place?.[0],t=e?.name??"";this.placeNameInput.value=t,this.placeNameInput.title=t,this.namedCoordinates=e&&t?{lat:e.lat,lng:e.lng}:void 0,this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=""}syncObserverMetadataFields(){this.witnessErrorView?.refresh();const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=this.said.read(e.observer?.title)??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.observerList.rename(Ce.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(Cn.opensPreciseDate(e.account?.observerBirth)),this.perceptionSettings.values=e.account?.observerPerception??{},this.birth=e.account?.observerBirth,this.birthDate.time=this.birth,this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"";const t=e.lens;this.lensGlassSelect.value=t?.glass??"",this.lensDropsInput.value=t?.drops?.toString()??"",this.lensCondensationInput.value=t?.condensation?.toString()??"",this.lensDirtInput.value=t?.dirt?.toString()??"",this.lensShelteredInput.checked=t?.sheltered===!0,this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=en(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??kp)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??fx)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),i=e.event.place?.[0],n=this.shadow.activeElement;n!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),n!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),this.syncObserverPosition(),n!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),n!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),n!==this.elevationInput&&this.syncElevationField(t?.elevationM??0)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=i.getInterpolatedShapeAt(n,this.currentSourceId),r=this.buildAppearanceShape(e??s?.bounds??this.defaultBounds(),s,t);this.commitShapes(n,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,i=!0){if(t&&!i)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const n=i1(e,this.currentAppearance);return t?{...n,angle:t.angle,title:t.title,selected:t.selected}:n}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();for(const[i,n]of this.groupTabs.entries()){const s=n===e&&t;n.setAttribute("aria-expanded",String(s)),this.groupPanels[i].hidden=!s}if(t){const i=e.parentElement.getBoundingClientRect(),n=e.getBoundingClientRect();(n.left<i.left||n.right>i.right)&&(e.parentElement.scrollLeft+=n.left-i.left-(i.width-n.width)/2)}if(t&&e.getAttribute("aria-controls")==="group-decor"){const i=this.decorList.value;i!==""&&i!==this.currentDecorId&&this.selectDecor(i)}t&&e.getAttribute("aria-controls")==="group-observer"&&this.observerShown!==Ce.OBSERVER_PRINCIPAL&&this.selectDecor(this.observerShown),t&&e.getAttribute("aria-controls")==="group-weather"&&this.syncSkyParts(),t&&e.getAttribute("aria-controls")==="group-observation"&&this.candidatesView?.refresh(),this.placeDecorItem(),this.syncCanvasMode(),this.refreshTimelineMarks(),t&&this.sectionFolds.refresh(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>{this.syncFileEditor(!1),this.showFileItem(this.fileItemSelect.value)},()=>this.showFileNote(this.messages.importError,"error"))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await ae(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-BtY-RLip.js");return{SightingFileEditor:t}},__vite__mapDeps([12,1,13]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileTextApplied=this.historySnapshot,this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel,{baseline:this.touched?this.savedFileText:this.fileText(),phrases:this.messages.fileSearchPhrases,caretMoved:t=>this.onFileCaret(t)}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}fileSyncActive(){return this.fileEditor!==void 0&&this.isGroupIdOpen("group-file")}fileFocus;caretTimer;followingCaret=!1;onFileCaret(e){clearTimeout(this.caretTimer),this.caretTimer=setTimeout(()=>this.focusFromFile(e),120)}focusFromFile(e){if(!this.fileSyncActive())return;const t=this.ufoElement.sighting;this.followingCaret=!0;try{const i=e[0]==="decor"&&typeof e[1]=="number"?t.decor[e[1]]:void 0;if(i!==void 0){this.fileFocus="decor",this.selectDecor(i.id);return}const n=e[0]==="timeline"&&e[1]==="keyframes"&&typeof e[2]=="number"&&e[3]==="shapes"&&typeof e[4]=="number"?t.timeline.allKeyframes[e[2]]?.shapes[e[4]]:void 0;if(n!==void 0){this.fileFocus="shape",this.selectUnit(n.sourceId),this.syncCanvasMode(),this.ufoElement.refresh();return}this.fileFocus=void 0,this.syncCanvasMode(),this.ufoElement.refresh()}finally{this.followingCaret=!1}}showInFile(e){this.followingCaret||e===void 0||!this.fileSyncActive()||this.fileEditor.reveal(e)}bodyPath(e){try{const i=(JSON.parse(this.fileEditor.text).interpretation?.bodies??[]).findIndex(n=>n.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,n]of t.entries()){const s=n.shapes.findIndex(r=>r.sourceId===e);if(s>=0)return["timeline","keyframes",i,"shapes",s]}}showFileNote(e,t="info"){Wt.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.sightingData)}writtenText(e){const t=this.keyframesWritten();return S1.of(e,t,t==="thin"?Oi.derivable(this.ufoElement.sighting):void 0)}keyframesWritten(){return this.wholeKeyframesInput.checked?"whole":"thin"}static WHOLE_KEYFRAMES_STORAGE="rr0-sighting-editor.whole-keyframes";setKeyframesWritten(){try{this.wholeKeyframesInput.checked?localStorage.setItem(Ce.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(Ce.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=rb(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=S1.of(uf(e),t,t==="thin"?Oi.derivable(e):void 0),this.savedFileText=this.baseline}this.resetHistory()}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(e=!0){const t=this.fileEditor;if(!(t===void 0||!this.isGroupIdOpen("group-file")||t.focused)&&!this.historyAnswering){if(t.edited)try{JSON.parse(t.text)}catch{return}t.replaceText(this.fileText(),e),this.fileTextApplied=t.text}}onFileTextEdited(e){this.syncHistoryButtons(),clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e,t=!1){this.fileApplyTimer=void 0;let i;try{i=JSON.parse(e)}catch{return}if(typeof i!="object"||i===null||Array.isArray(i)||!t&&JSON.stringify(i)===JSON.stringify(this.sightingData))return;const n=this.ufoElement.currentTime,s=!t&&this.fileTextApplied!==void 0&&JSON.stringify(i.weatherTrack)!==JSON.stringify(Ce.weatherOf(this.fileTextApplied)),r={track:this.sightingData.weatherTrack,source:this.sightingData.weatherSource};this.applyingFileText=!0;try{if(this.sightingData=i,this.touched=!0,this.ufoElement.currentTime=n,s&&!this.restoringWeather&&this.weatherFromRecords){const a=this.ufoElement.sighting.weatherSource;a===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):Ic.some(o=>o.id===a.id)&&this.askAboutWeather(r,a.name??a.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(a){this.showFileNote(a instanceof Ad?a.said(this.messages.formatVersionError):this.messages.importErrorMalformed,"error"),this.fileTextApplied=e}finally{this.applyingFileText=!1}}fileTextApplied;static weatherOf(e){try{return JSON.parse(e).weatherTrack}catch{return}}pendingWeatherEdit;restoringWeather=!1;askAboutWeather(e,t){this.cancelWeatherLookup(),this.pendingWeatherEdit=e,this.shadow.getElementById("file-ask-text").textContent=this.messages.weatherEditedAsk.replaceAll("{source}",t),this.shadow.getElementById("file-ask-stop").textContent=this.messages.weatherEditedStop,this.shadow.getElementById("file-ask-keep").textContent=this.messages.weatherEditedKeep,typeof this.fileAsk.showModal=="function"?this.fileAsk.showModal():this.fileAsk.setAttribute("open","")}closeFileAsk(){typeof this.fileAsk.close=="function"?this.fileAsk.close():this.fileAsk.removeAttribute("open")}stopReadingWeather(){this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState(),this.ufoElement.refresh(),this.syncFileEditor(!1)}keepReadingWeather(){const e=this.pendingWeatherEdit;if(this.pendingWeatherEdit=void 0,this.closeFileAsk(),e!==void 0){this.restoringWeather=!0;try{this.applyFileText(JSON.stringify({...this.sightingData,weatherTrack:e.track,weatherSource:e.source}))}finally{this.restoringWeather=!1}this.syncFileEditor(!1)}}applyingFileText=!1;leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(!1),0))}static SCENE_LINKED=["heading","pitch","focalLength","apparentWidth","realWidth","objectDistance","color","haloScale","cloudCover","windDirection","windSpeed","referenceOpacity"];setActiveSceneField(e){e!==this.activeSceneField&&(this.activeSceneField=e,e==="referenceOpacity"&&!this.ufoElement.referencesShown?(this.ufoElement.toggleReferences(),this.referencesShownForField=!0):e!=="referenceOpacity"&&this.referencesShownForField&&(this.ufoElement.referencesShown&&this.ufoElement.toggleReferences(),this.referencesShownForField=!1),this.refreshSceneField())}refreshSceneField(){const e=this.sceneFieldOverlay;if(!e)return;const t=this.activeSceneField,i=this.ufoElement.sighting,n=this.ufoElement.currentTime,s=this.ufoElement.canvasElement,r=this.messages,a=c=>this.numberOrUndefined(c.value),o=(c,h=1)=>c===void 0?"?":c.toLocaleString(this.language,{maximumFractionDigits:h});if(t==="pitch"){const c=a(this.pitchInput)??0,h=Os.of(i.instrument,s.height,Oi.fovOf(i,n)),d=Math.sign(c)*h.angleDegToRadiusPx(Math.min(89,Math.abs(c))),u=Math.min(1,Math.max(0,(s.height/2+d)/s.height));e.horizon(u,r.overlayHorizon.replaceAll("{deg}",o(c)))}else if(t==="focalLength"){const c=Oi.fovOf(i,n),d=2*Os.of(i.instrument,s.height,c).halfWidthAngleDeg(s.width/s.height);e.frame(r.overlayFov.replaceAll("{v}",o(c)).replaceAll("{h}",o(d)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const c=i.timeline.getInterpolatedShapeAt(n,this.currentSourceId);if(!c){e.hide();return}const h=c.bounds,u=[[a(this.apparentWidthInput),"°",1],[a(this.realWidthInput)," m",1],[a(this.objectDistanceInput)," m",0]].filter(([p])=>p!==void 0).map(([p,f,m])=>`${o(p,m)}${f}`).join(" · ");e.measure((h.x+h.width/2)/s.width,(h.y+h.height/2)/s.height,Math.max(h.width,h.height)*1.3/s.width,u)}else if(t==="windDirection"||t==="windSpeed"){const c=a(this.windDirectionInput)??0,h=c-(a(this.headingInput)??0);e.wind(h,r.overlayWind.replaceAll("{point}",this.naming.point(c)).replaceAll("{speed}",o(a(this.windSpeedInput))))}else e.hide()}attachWitnessErrors(){const e=this,t=()=>this.ufoElement.sighting,i=()=>this.ufoElement.currentTime,n=this.shadow.querySelector('rr0-date-input[name="obs-time"]');this.witnessErrorView.attach({kind:"time",label:n.closest("label"),input:n,path:()=>t().event.time?"time":void 0,value:()=>t().event.time?.hour!==void 0?0:void 0}),this.witnessErrorView.attach({kind:"duration",label:this.durationElement.closest("label"),input:this.durationElement,path:()=>t().event.durationSeconds!==void 0?"durationSeconds":void 0,value:()=>t().event.durationSeconds});const s=c=>{let h=-1;return c.forEach((d,u)=>{d<=i()&&(h=u)}),h===-1&&c.length>0?0:h};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const c=s(t().observerTrack.allKeyframes.map(h=>h.t));return c===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${c}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const c=t().timeline.allKeyframes,h=s(c.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId)).map(f=>f.t));if(h===-1||this.apparentWidthInput.value==="")return;const d=c.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId))[h],u=c.indexOf(d),p=d.shapes.findIndex(f=>f.sourceId===this.currentSourceId);return`timeline.keyframes.${u}.shapes.${p}.shape.angular`},value:()=>this.numberOrUndefined(this.apparentWidthInput.value)});const r=this.shadow.getElementById("observerPerception").closest(".form-section");this.witnessErrorView.placeObserverSections(r);const a=document.createElement("div");a.className="form-section candidates-section",this.shadow.getElementById("group-observation").append(a);const o=c=>c?.closest("label")??void 0;this.candidatesView=new Yn({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const c=this.ufoElement.sighting.event,h=c.place?.[0];if(!h||c.time?.year===void 0||c.time.hour===void 0)return;const d=zn(c.time,h.lng,c.utcOffsetHours);return d?{date:d,observer:{lat:h.lat,lng:h.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:c=>ea(c,this.instrumentGain()),fieldLabels:()=>({time:o(n),heading:o(this.headingInput),size:o(this.apparentWidthInput),duration:o(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:c=>{const h=`${c}/${this.language}`;return this.poherMatrix?.key!==h&&(this.poherMatrix={key:h,loaded:Ao.load(c,this.language,d=>kr.json(d))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const c=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,h=this.sceneElement.satellitePassesDuring(c);return h.length>0?{passes:h,positionsAt:d=>this.sceneElement.satellitePositionsAt(d)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const c=this.ufoElement.sighting.interpretation;return[...c&&c.bodies.length>0?[{id:"own",label:this.said.read(c.title)??this.principalObserverLabel(),interpretation:c}]:[],...this.readings]},starName:c=>this.naming.star({name:c}),projectionAt:(c,h)=>this.sceneElement.bodyProjectionAt(c,h),variants:()=>this.ufoElement.sighting.variants,keep:c=>this.editVariants(h=>[...h,c]),remove:c=>this.editVariants(h=>h.filter((d,u)=>u!==c))},a)}readings=[];editVariants(e){this.touch(),this.armHistory(),this.ufoElement.sighting.variants=e(this.ufoElement.sighting.variants),this.scheduleHistoryRecord()}poherMatrix;poherFacts(){const e=this.ufoElement.sighting,t={},i=e.event,n=i.place?.[0];if(n&&i.time?.year!==void 0&&i.time.hour!==void 0){const h=zn(i.time,n.lng,i.utcOffsetHours);h&&(t.sunAltitudeDeg=Ti("Sun",h,{lat:n.lat,lng:n.lng,elevationM:this.groundElevationM??0}).altitudeDeg)}if(i.durationSeconds!==void 0&&(t.durationSeconds=i.durationSeconds),e.weatherTrack.allKeyframes.length>0){const h=en(e,0);t.cloudCover=h.cloudCover,t.lightning=h.storm,t.lowVisibility=h.precipitationType!=="none"&&h.precipitationIntensity>.3}const s=e.timeline,r=s.sourceIds[0];if(r){const h=s.allKeyframes.filter(p=>p.shapes.some(f=>f.sourceId===r)),d=h.map(p=>({t:p.t,shape:s.getShapeAt(p.t,r)})).filter(p=>p.shape?.aim),u=s.getInterpolatedShapeAt(h[0]?.t??0,r);if(u?.aim&&(t.elevationDeg=u.aim.altitudeDeg),u?.angular){t.widthDeg=u.angular.widthDeg;const p=u.angular.heightDeg>0?u.angular.widthDeg/u.angular.heightDeg:1;t.round=u.kind==="oval"&&p>.8&&p<1.25}if(u?.brightness!==void 0&&(t.brightness=u.brightness),d.length>1){const p=(g,y)=>{const w=Math.PI/180,b=Math.sin(g.altitudeDeg*w)*Math.sin(y.altitudeDeg*w)+Math.cos(g.altitudeDeg*w)*Math.cos(y.altitudeDeg*w)*Math.cos((g.azimuthDeg-y.azimuthDeg)*w);return Math.acos(Math.max(-1,Math.min(1,b)))/w},f=d.slice(1).map((g,y)=>({deg:p(d[y].shape.aim,g.shape.aim),s:(g.t-d[y].t)/1e3}));t.sweepDeg=p(d[0].shape.aim,d[d.length-1].shape.aim);const m=f.reduce((g,y)=>g+y.deg,0);t.straysDeg=Math.max(0,m-t.sweepDeg)/2;const v=(d[d.length-1].t-d[0].t)/1e3;if(v>0){t.speedDegPerS=m/v;const g=Math.max(...f.filter(y=>y.s>0).map(y=>y.deg/y.s));t.speedVariation=t.speedDegPerS>0?g/t.speedDegPerS:0}}}const a=new Set(s.sourceIds.map(h=>s.groupMembers(h)?.[0]??h));a.size>0&&(t.count=a.size);const o=[...a].map(h=>s.getInterpolatedShapeAt(0,h)?.aim).filter(h=>h!==void 0);if(o.length>=3){const h=Math.PI/180,d=o.map(m=>({x:(((m.azimuthDeg-o[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*h),y:m.altitudeDeg}));let[u,p]=[d[0],d[1]];for(const m of d)for(const v of d)Math.hypot(m.x-v.x,m.y-v.y)>Math.hypot(u.x-p.x,u.y-p.y)&&([u,p]=[m,v]);const f=Math.hypot(u.x-p.x,u.y-p.y);t.aligned=f>0&&d.every(m=>Math.abs((p.x-u.x)*(u.y-m.y)-(u.x-m.x)*(p.y-u.y))/f<=Math.max(.5,f*.1))}const c=new Set([...a].map(h=>s.getInterpolatedShapeAt(0,h)?.color).filter(h=>h!==void 0));return c.size>0&&(t.colors=[...c]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(h=>h.sound.kind!=="none")&&(t.sound=!0),t}candidatesTimer;refreshCandidatesSoon(){clearTimeout(this.candidatesTimer),this.isGroupIdOpen("group-observation")&&(this.candidatesTimer=setTimeout(()=>this.candidatesView?.refresh(),150))}showOverlays(){const e=this.shadow.querySelector(".scene-card");e.dataset.shown="",clearTimeout(this.overlayTimer),this.overlayTimer=setTimeout(()=>delete e.dataset.shown,3500)}setTracksShown(e){this.shadow.querySelector(".scene-card").toggleAttribute("data-tracks",e),this.shadow.getElementById("timeline-tracks").hidden=!e,this.tracksToggle.setAttribute("aria-expanded",String(e));const i=e?this.messages.collapseTracks:this.messages.expandTracks;this.tracksToggle.title=i,this.tracksToggle.setAttribute("aria-label",i),this.refreshTracks()}flash(e){e&&(e.classList.add("flash"),setTimeout(()=>e.classList.remove("flash"),1800))}refreshTracks(){if(!this.timelineTracks||this.tracksToggle.getAttribute("aria-expanded")!=="true")return;const e=this.ufoElement.sighting,t=this.messages,i=r=>{const a=this.groupTabs.find(o=>o.getAttribute("aria-controls")===r);a&&this.toggleGroup(a,!0)},n=r=>()=>{this.touch(),this.armHistory(),r(),this.scheduleHistoryRecord(),this.refreshTimelineMarks()},s=[{id:"shapes",label:t.shapesTrack,color:"#f5c451",times:e.timeline.allKeyframes.map(r=>r.t),open:()=>this.revealShapePanel(),add:n(()=>{e.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,!1)})},{id:"observer",label:t.observerTrack,color:"#7fd4ff",times:e.observerTrack.allKeyframes.map(r=>r.t),open:()=>i("group-location"),add:n(()=>this.updateObserver())},{id:"weather",label:t.weatherTrack,color:"#b9c8d8",times:e.weatherTrack.allKeyframes.map(r=>r.t),open:()=>i("group-weather"),add:n(()=>this.applyWeatherAtPlayhead())},{id:"sound",label:t.soundTrack,color:"#9fd9a8",times:e.soundTrack.allKeyframes.map(r=>r.t),open:()=>i("group-sound"),add:n(()=>this.applySoundAtPlayhead())}];this.timelineTracks.show(s,this.ufoElement.seekableDuration,this.ufoElement.currentTime)}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(o,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${o})`})),i=o=>t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(c=>!o||c.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(c=>c.t)),n=()=>t(this.messages.observerTrack,e.observerTrack.allKeyframes.map(o=>o.t)),s=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(o=>o.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(o=>o.t)),a=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?n():this.isGroupIdOpen("group-weather")?s():this.isGroupIdOpen("group-sound")?r():[...i(!1),...n(),...s(),...r()];for(const o of e.milestones)a.push({t:o.t,kind:"milestone",label:this.said.read(o.label)??""});this.timelineMarks.show(a,this.ufoElement.seekableDuration),this.refreshTracks(),this.witnessErrorView?.refreshFields(),this.activeSceneField&&this.refreshSceneField()}seekTo(e){this.goToMark(e*1e3)}set passages(e){const t=this.shadow.getElementById("moment-passages");t.replaceChildren(...(e??[]).map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.className="at",s.innerHTML=Je.PLAY,s.append(i.clock),s.addEventListener("click",()=>this.seekTo(i.at));const r=document.createElement("button");return r.type="button",r.className="excerpt",r.textContent=i.said,r.title=i.where,r.addEventListener("click",()=>i.open()),n.append(s,r),n})),t.hidden=t.childElementCount===0}openSection(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);t&&this.toggleGroup(t,!0)}showRender(){this.sceneElement.scrollIntoView?.({block:"center",behavior:"smooth"})}goToMark(e){e!==void 0&&(this.ufoElement.currentTime=e,this.syncPlaybackControls())}isGroupIdOpen(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-file")?this.fileFocus==="decor"&&this.editableDecor()!==void 0?"decor":this.fileFocus==="shape"&&this.selectedSourceIds.size>0?"shape":"scene":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-weather")&&(this.shadow.getElementById("sky-launches")?.hidden===!1||this.shadow.getElementById("sky-beams")?.hidden===!1)?"scene":this.isGroupIdOpen("group-shape")?"shape":this.isGroupIdOpen("group-decor")&&this.editableDecor()!==void 0?"decor":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",i=this.lastCanvasMode==="picture",n=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",t&&this.currentReference()&&this.loadPictureRegistration(),this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,n&&this.ufoElement.repaintOverlay(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const s=this.currentReference();s&&this.syncReferenceStatus(s),this.syncStreetSearchAvailability(),this.syncBodiesShown()}skyOf(e){if(!(!e||!e.lanterns?.length&&!e.flares?.length))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],lanterns:e.lanterns,flares:e.flares}}),this.skyPart.sky}skyPart;syncBodiesShown(){const t=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading,i=this.ufoElement.sighting.interpretation,n=t?i:this.skyOf(i);this.sceneElement.compareAccount=t&&n!==void 0,this.sceneElement.interpretation!==n&&(this.sceneElement.interpretation=n),this.accountViewSelect.value=t&&n!==void 0?"bodies":"shapes",this.syncSkyParts(),this.shadow.getElementById("account-view-row").hidden=this.isReading}syncSkyParts(){this.isGroupIdOpen("group-weather")&&(this.shadow.getElementById("sky-beams")?.hidden===!1&&this.loadBeamEditor().then(e=>e.refresh()),this.shadow.getElementById("sky-lanterns")?.hidden===!1&&this.loadLanternEditor().then(e=>e.refresh()),this.shadow.getElementById("sky-launches")?.hidden===!1&&this.loadLaunchEditor().then(e=>e.refresh()))}chooseAccountView(e){const t=this.groupTabs.find(n=>n.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}openSubgroup(e){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const i of this.subgroupTabs){if(i.parentElement!==t)continue;const n=i===e;i.setAttribute("aria-expanded",String(n)),this.shadow.getElementById(i.getAttribute("aria-controls")).hidden=!n}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(i=>i.sync()),e.getAttribute("aria-controls")==="sky-launches"&&this.loadLaunchEditor().then(i=>i.sync()),e.getAttribute("aria-controls")==="sky-beams"&&this.loadBeamEditor().then(i=>i.sync()),e.getAttribute("aria-controls")==="sky-lanterns"&&this.loadLanternEditor().then(i=>i.sync()),this.syncCanvasMode()}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|");i!==this.paramSummarySignature&&(this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.runAssessments())}paramChips=[];renderParamSummary(){this.saveButton&&this.refreshEditorTitle();const e=Ce.NESTED_GROUPS,t=[];let i;for(const n of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==n.group&&(i=void 0),e.includes(n.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=n.group;const a=document.createElement("span");a.className="param-nest-label",a.textContent=n.group==="assessment"?this.messages.assessmentGroup:n.group==="summary"?this.messages.summaryGroup:Ce.tabLabel(this.groupTabs[this.summaryPanelIndex(n.group)]),r.append(a),i={group:n.group,element:r},t.push(r)}const s=this.paramChip(n);i?i.element.append(s):t.push(s)}this.paramSummary.replaceChildren(...t),this.shadow.getElementById("label-param-summary").textContent=this.messages.paramSummaryTitle.replace("{n}",String(t.length)),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),m2.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return this.panelIndex(e==="phenomenon"?"shape":e)}static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]}};assessmentChips=[];assessmentToken=0;async runAssessments(){const e=++this.assessmentToken,t=await new kT(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.openMostLackingGroup(),this.renderParamSummary())}opensMostLacking=!1;sectionChosen=!1;openMostLackingGroup(){if(!this.opensMostLacking)return;this.opensMostLacking=!1;const e=n=>{const s=n.querySelector(".tab-badge");return s&&!s.hidden?Number(s.textContent):0},t=this.groupTabs.find(n=>this.isGroupOpen(n));let i=t&&e(t)>0?t:void 0;for(const n of this.groupTabs)e(n)>(i?e(i):0)&&(i=n);i&&i!==t&&(this.toggleGroup(i,!0),this.sectionChosen=!1)}fitGroupTabs(){const e=this.groupTabs[0]?.parentElement;e&&(e.classList.add("measuring"),e.classList.remove("compact"),e.classList.toggle("compact",e.scrollWidth>e.clientWidth),e.offsetWidth,e.classList.remove("measuring"))}static titleGroupTab(e){e.title=[e.dataset.intro,e.dataset.unanswered].filter(Boolean).join(`
11300
- `)}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const i=document.createElement("span");return i.className="tab-badge",i.hidden=!0,e.append(i),i}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const s of e){const r=Ce.QUESTION_FIELDS[s];if(r&&!r.fields.some(a=>this.shadow.getElementById(a)?.classList.contains("missing-required")))for(const a of r.fields){const o=this.shadow.getElementById(a);o&&!o.hidden&&o.value===""&&t.add(a)}}for(const[s,r]of Object.entries(Ce.QUESTION_FIELDS))for(const a of Ce.QUESTION_FIELDS[s].fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=t.has(a)&&!o.classList.contains("missing-required");o.classList.toggle("wanted",c),(c||o.title===this.messages.questionUnanswered)&&(o.title=c?this.messages.questionUnanswered:"")}const i=new Map;let n;for(const[s,r]of Object.entries(Ce.QUESTION_FIELDS))for(const a of r.fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=o.classList.contains("missing-required");!c&&!o.classList.contains("wanted")||(c&&(n=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const s of this.groupTabs){const r=this.panelOf(s),a=i.get(r)??0,o=r===n,c=Ce.badgeOn(s);c.hidden=a===0,c.textContent=String(a),c.classList.toggle("optional",!o);const h=a===0?void 0:o?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(a));h?s.dataset.unanswered=h:delete s.dataset.unanswered,Ce.titleGroupTab(s)}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field;const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const s=document.createElement("span");s.className="param-chip-swatch",s.style.background=e.color,t.append(s)}const n=document.createElement("span");return n.className="param-chip-value",n.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(n),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(a=>a.field==="description")?.full,this.syncDescription();return}const i=Number(t.dataset.panel);if(i<0)return;const n=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const s=t.dataset.field;if(s.startsWith("shape:")){this.selectedSourceIds=new Set([s.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(s.startsWith("body:")){const a=this.subgroupTabs.find(o=>o.getAttribute("aria-controls")==="shape-bodies");a&&this.openSubgroup(a),this.loadBodyEditor().then(o=>o.show(s.slice(5)));return}if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorList.focus();return}const r=this.shadow.getElementById(s);r===null||!n.contains(r)||(this.revealSubgroupOf(r),this.sectionFolds.reveal(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe(),this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorBaseFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateShapeToolbarVisibility(){const e=this.ufoElement.sighting.timeline.sourceIds.length===0,t=this.shadow.getElementById("shape-row");t&&ps.showPresence(t,this.shadow.getElementById("shape-item")??void 0,!e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.shapeRotationInput])i.disabled=e,i.title=t}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:oN(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.shadow.activeElement!==this.shapeRotationInput&&(this.shapeRotationInput.value=String(Ce.rotationDeg(e.angle))),this.refreshApparentSize())}static rotationDeg(e){const t=(e*180/Math.PI%360+540)%360-180;return Math.round((t===-180?180:t)*10)/10}updateShapeRotation(){const e=this.numberOrUndefined(this.shapeRotationInput.value);if(e===void 0)return;const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,n=t.getInterpolatedShapeAt(i,this.currentSourceId);n&&(this.commitShapes(i,[{sourceId:this.currentSourceId,shape:{...n,angle:e*Math.PI/180}}]),this.ufoElement.refresh())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,At.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,At.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(At.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(At.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,n=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!n)return;const s=this.currentProjection(),r=s.degToPx(e),a=n.bounds.height*(n.bounds.width===0?1:r/n.bounds.width),o={x:n.bounds.x+(n.bounds.width-r)/2,y:n.bounds.y+(n.bounds.height-a)/2,width:r,height:a},c=s.ofBounds(o),h=n.kind==="oval"?{...n,bounds:o,angular:c}:{...n,bounds:o,angular:c,points:this.scalePoints(n,o)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,n=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(s=>({x:s.x*i,y:s.y*n}))}refreshFilterOptions(){const e={[Ci.NONE.id]:this.messages.filterNone,[Ci.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[Ci.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=s=>e[s.id]??s.name,i=[...this.filterSelect.options].map(s=>s.textContent);if(i.length!==Ci.ALL.length||Ci.ALL.some((s,r)=>i[r]!==t(s))){const s=this.filterSelect.value||Ci.NONE.id;this.filterSelect.replaceChildren();for(const r of Ci.ALL){const a=document.createElement("option");a.value=r.id,a.textContent=t(r),this.filterSelect.appendChild(a)}this.filterSelect.value=s}const n=this.ufoElement?.sighting?.instrument;for(const s of this.filterSelect.options){const r=!n||Ci.usableWith(Ci.byId(s.value),n);s.disabled=!r,s.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,n={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},s=r=>{const a=this.naming.instrument(r),o=hi.unavailability(r,t);if(!o)return{id:r.id,label:a};const c=(o.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(o.from)).replace("{to}",String(o.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",a),hint:c}:{id:r.id,label:a,disabledReason:c}};this.instrumentSelect.choices=hi.CATEGORIES.map(r=>({label:n[r],children:Qh.filter(a=>a.category===r).map(s)})).filter(r=>r.children.length>0),this.instrumentSelect.value=this.instrumentSelect.value||i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Ce.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const s=Number(i[1]),r=Number(i[2]);return r>0?s/r:void 0}const n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=pt(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??hi.fieldOfViewDeg(t),r=n?hi.focalLengthMmFor(t,s):s;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=n?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=n?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=n!==void 0&&n.focalRangeMm===void 0,this.focalLengthInput.min=String(n?n.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(n?n.focalRangeMm?.maxMm??2e3:179),Fn.fit(this.focalLengthInput.parentElement??this.shadow),this.sectionFolds?.refresh(),this.focalFovOutput.textContent=n&&s!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(s,s<10?1:0)):"";const a=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=a===void 0?"":String(a)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const o=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=o===void 0?"":Ce.exposureText(o)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const h of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(h,bi.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const c=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.isoInput.placeholder=c?c.autoExposure?"auto":String(c.iso):"",this.setRowVisible(this.isoInput,c!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,c?.autoExposure===!0),this.meteringSelect.disabled=e.iso!==void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,n!==void 0&&t.fNumber!==void 0),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=Ci.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=hi.fieldOfViewDeg(e),n=hi.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>eN||t.observerTrack.addKeyframe(s.t,{...s.pose,fovDeg:n})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,n=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!n){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(n.max,Math.max(n.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return pt(e,this.ufoElement.currentTime)?.fovDeg??hi.fieldOfViewDeg(e.instrument)}currentProjection(){return Os.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=At.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const n=pt(this.ufoElement.sighting,this.ufoElement.currentTime),s=n?.focusDistanceM;if(s!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(s));return}const r=(n?hi.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,a=n?.fNumber??t.fNumber;if(a===void 0||r<=0){this.blurBoundOutput.textContent="";return}const o=this.ufoElement.canvasElement.height;if(o<=0)return;const c=2*Ig*e/o*i.heightMm,h=r*r/(a*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:i}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&i===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const n=this.numberOrUndefined(this.realWidthInput.value),s=n!==void 0&&(t!==void 0&&n<t||i!==void 0&&n>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),a=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+a+s;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+s}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}newBodyStart(){const e=this.currentSourceId,t=this.ufoElement.currentTime,i=e===void 0?void 0:this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e),n=(m,v)=>Number(m.toFixed(v)),s=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??Y6,a=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),o=a!==void 0&&a<r,c=n(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:n(At.sizeMAt(c,h),2),lengthM:n(At.sizeMAt(c,h),2),heightM:n(At.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},f={t,...p,distanceM:c,...o?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=ae(async()=>{const{BodyEditor:e}=await import("./BodyEditor-rPUSfhG-.js");return{BodyEditor:e}},__vite__mapDeps([14,15]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,seekTo:t=>{this.ufoElement.currentTime=t},readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}loadLanternEditor(){return this.lanternEditorLoading??=ae(async()=>{const{LanternEditor:e}=await import("./LanternEditor-Bq27r-0W.js");return{LanternEditor:e}},__vite__mapDeps([16,17]),import.meta.url).then(({LanternEditor:e})=>(this.lanternEditor=new e(this.shadow.getElementById("lantern-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()}},this.language),this.lanternEditor)),this.lanternEditorLoading}loadBeamEditor(){return this.beamEditorLoading??=ae(async()=>{const{BeamEditor:e}=await import("./BeamEditor-BHpoDP6v.js");return{BeamEditor:e}},__vite__mapDeps([18,5,19]),import.meta.url).then(({BeamEditor:e})=>(this.beamEditor=new e(this.shadow.getElementById("beam-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language),this.beamEditor)),this.beamEditorLoading}loadLaunchEditor(){return this.launchEditorLoading??=ae(async()=>{const{LaunchEditor:e}=await import("./LaunchEditor-D-1-8brV.js");return{LaunchEditor:e}},__vite__mapDeps([20,21]),import.meta.url).then(({LaunchEditor:e})=>(this.launchEditor=new e(this.shadow.getElementById("launch-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language),this.launchEditor)),this.launchEditorLoading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const s=i===void 0||i<=0?void 0:At.sizeMAt(e.distanceM,i);this.realWidthInput.value=s===void 0?"":this.plain(s,s<1?2:s<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const n={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=n.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,n=Os.of(i.instrument,At.CANVAS_HEIGHT_PX,Oi.fovOf(i,e)),s=this.ufoElement.seekableDuration;s>i.timeline.duration&&i.timeline.setSpan(s),i.timeline.addKeyframe(e,t.map(r=>{const a=Oi.aimOf(i,e,r.shape.bounds),o=n.ofBounds(r.shape.bounds),{aim:c,...h}=r.shape;return{...r,shape:a?{...h,aim:a,angular:o}:{...h,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.ufoElement.sighting.timeline.sourceIds.length>0&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const n=/^ufo-(\d+)$/.exec(e);return n?`${this.messages.shape} ${n[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;this.currentSourceId=this.newSourceIds(1)[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}newSourceIds(e){const t=this.ufoElement.sighting.timeline,i=[];t.sourceIds.length===0&&this.currentSourceId!==void 0&&i.push(this.currentSourceId);const n=new Set([...t.sourceIds,this.currentSourceId]);let s=n.size+1;for(;i.length<e;){for(;n.has(`ufo-${s}`);)s++;i.push(`ufo-${s}`),n.add(`ufo-${s}`)}return i}shapeAddKinds(){const e=this.messages,t={triangle:e.modelTriangle,saucer:e.modelSaucer,cigar:e.modelCigar,chevron:e.modelChevron,light:e.modelLight};return[{value:"oval",label:e.oval},{value:"polygon",label:e.polygon},...Ra.ALL.map(i=>({value:i.id,label:t[i.id]}))]}addModel(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,i=e.boundsAt(this.offsetDefaultBounds(t.sourceIds.length)),n=e.shapesIn(i,this.currentAppearance),s=this.newSourceIds(n.length),r=this.shapeAddKinds().find(h=>h.value===e.id).label,a=/^ufo-(\d+)$/.exec(s[0])?.[1]??"",o={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},c=n.map((h,d)=>{const u=e.partNames[d],p=u?`${r} ${a}, ${o[u]}`:`${r} ${a}`;return{sourceId:s[d],shape:{...h,title:this.said.write(void 0,p,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,c),s.length>1&&t.group(s),this.currentSourceId=s[s.length-1],this.selectedSourceIds=new Set(s),this.refreshSourceList(),this.ufoElement.refresh()}duplicateSelected(){if(this.hideContextMenu(),this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(r=>this.selectedSourceIds.has(r));if(t.length===0)return;const i=this.newSourceIds(t.length),n=24;for(const r of e.allKeyframes){const a=r.shapes.filter(o=>t.includes(o.sourceId)).map(o=>{const{bounds:c}=o.shape;return{sourceId:i[t.indexOf(o.sourceId)],shape:{...o.shape,bounds:{...c,x:c.x+n,y:c.y+n}}}});a.length>0&&this.commitShapes(r.t,a)}const s=e.groupMembers(t[0]);t.length>1&&s?.length===t.length&&t.every(r=>s.includes(r))&&e.group(i),this.currentSourceId=i[i.length-1],this.selectedSourceIds=new Set(i),this.refreshSourceList(),this.ufoElement.refresh()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i));t.length!==0&&this.removeShapes(t)}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??Jh,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}offsetDefaultBounds(e){const t=this.defaultBounds(),i=24;return{...t,x:t.x+e*i,y:t.y+e*i}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=e.sourceIds.length>0?[...new Set([...e.sourceIds,this.currentSourceId])]:[];this.sourceSelect.innerHTML="";for(const i of t){const n=document.createElement("option");n.value=i,n.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(n)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const n=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorList.kindLabel(e.kind)} ${n}`}addDecor(e=this.decorList.pickedKind??"building"){this.observerAdded=e==="observer";const t=this.ufoElement.sighting,n={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="trafficlight"?{lights:hh.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:dh}:{},windows:c2(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(n.id,e)}readSceneryChoice(){try{return localStorage.getItem(Ce.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(Ce.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(Ce.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(Ce.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await ae(()=>import("./surroundingsSources-BK1okKkz.js"),[],import.meta.url).catch(()=>{});if(!e)return;const{SURROUNDINGS_SOURCES:t,SurroundingsSources:i}=e;if(!this.isConnected)return;const n=document.createElement("option");n.value=Ce.NO_SCENERY,n.id="option-scenery-none",n.textContent=this.messages.surveySourceNone;const s=t.map(a=>{const o=document.createElement("option");return o.value=a.id,o.textContent=a.name,o.title=a.credit,o}),r=new Option(this.messages.sourceFile,Ce.FILE_SOURCE);r.id="option-scenery-file",this.scenerySource.replaceChildren(n,...s,r),this.surveyIds=t.map(a=>a.id),this.defaultSurveyId=i.DEFAULT_ID,this.syncSceneryPicker()}surveyIds;defaultSurveyId;sceneryAsked(){return this.sceneryChoice!==Ce.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?Ce.FILE_SOURCE:this.sceneryChoice===Ce.NO_SCENERY?Ce.NO_SCENERY:this.surveyIds.includes(this.sceneryChoice??"")?this.sceneryChoice:this.defaultSurveyId??this.surveyIds[0]),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-radius-row").hidden=e||this.sceneryChoice===Ce.NO_SCENERY;const t=this.shadow.getElementById("scenery-file-link");t.hidden=!e,e&&(t.textContent=this.sectionFilePanel.itemLabel("decor"),t.title=this.sectionFilePanel.where("decor"))}setDecorFromFile(e){const t=this.ufoElement.sighting;if(this.sectionFromFile("decor")===e)return;const i={...t.frozen??{}};e?i.decor=i.decor??{}:delete i.decor,t.frozen=Bi.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],n=t?.lat??i?.lat,s=t?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}setPlantedDecor(e){this.ufoElement.sighting.decor=e,e.some(t=>t.id===this.currentDecorId)||(this.currentDecorId=e[0]?.id),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleHistoryRecord()}refreshSceneryWarning(){const e=this.ufoElement?.sighting,t=e?of.anachronism(e.decor,e.event.time):void 0;this.sceneryWarning.hidden=t===void 0,this.sceneryWarning.textContent=t?this.messages.surveyWarning.replace("{survey}",t.survey).replace("{observation}",t.observation):""}citeSource(e){const t=this.ufoElement.sighting;(t.sources??[]).some(i=>i.url===e.url)||(t.sources=[...t.sources??[],e])}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const n=this.ufoElement.sighting.decor.find(s=>s.id===e);!n||n.model||n.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(s=>s.id===e?{...s,model:{id:i.id},sizeM:i.sizeM}:s),this.currentDecorId===e&&this.syncDecorVisibility(),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*ig,t=Math.round(e/iN*1e3);return{lights:hh.byId("airliner")?.create(),track:[{t:0,eastM:-ig,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:ig,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.kind===e).length;return`${this.decorList.kindLabel(e)} ${t+1}`}deleteDecor(){const t=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);t!==void 0&&this.removeDecor(t.id)}removeDecor(e){const t=this.ufoElement.sighting;t.decor=t.decor.filter(i=>i.id!==e),this.currentDecorId===e&&(this.currentDecorId=t.decor[0]?.id),this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="decor"),this.decorList.show(e),this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh();const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===e);t>=0&&this.showInFile(["decor",t])}updateDecor(e={}){if(this.currentDecorId===void 0)return;const t=this.ufoElement.sighting;t.decor=t.decor.map(i=>i.id!==this.currentDecorId?i:{...i,...e}),this.syncDecorVisibility(),this.ufoElement.refresh()}decorModelEntries;refreshDecorModelOptions(e){if(!e||this.decorModelEntries?.kind===e.kind)return;const t=e.kind;this.decorModelProvider.entries(t).catch(()=>[]).then(i=>{this.decorModelEntries={kind:t,entries:i},this.isConnected&&this.decorBaseForm.sync()})}drawnEntry;drawnEntryAsked;publishedParametersOf(e){const t=Od(e);if(!(!t?.id||t.url!==void 0)){if(this.drawnEntry?.id===t.id)return this.drawnEntry.parameters;if(this.drawnEntryAsked!==t.id){this.drawnEntryAsked=t.id;const i=t.id;this.decorModelProvider.entry(i).catch(()=>{}).then(n=>{this.drawnEntryAsked!==i||!n||(this.drawnEntry=n,this.isConnected&&this.syncDecorVisibility())})}}}modelPicker;enhanceDecorModelChoice(e,t){e.key==="model.id"&&(t.addEventListener("change",()=>t.dispatchEvent(new Event("input",{bubbles:!0}))),this.modelPicker.enhance(t,async i=>{const n=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),s=i!==""?i:n?lf[n.kind]?.id:void 0;return s!==void 0?this.decorModelProvider.entry(s).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):n===void 0?void 0:{decorKind:n.kind}},{current:()=>{const i=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId)?.model;return i?.url===void 0?void 0:{url:i.url,title:i.credit?.title??"",author:i.credit?.author??"",license:i.credit?.license??"",source:i.credit?.sourceUrl??""}},apply:i=>this.commitDecorBase(n=>{const s=this.stringOrUndefined(i.title),r=this.stringOrUndefined(i.license);n.model={url:i.url,credit:s!==void 0&&r!==void 0?{title:s,license:r,author:this.stringOrUndefined(i.author),sourceUrl:this.stringOrUndefined(i.source)}:void 0}},"model")}))}async adoptCatalogueSize(e,t){const[i,n]=await Promise.all([e.model?.id?this.decorModelProvider.entry(e.model.id).catch(()=>{}):void 0,t?this.decorModelProvider.entry(t).catch(()=>{}):void 0]),s=this.ufoElement.sighting.decor.find(o=>o.id===e.id);if(!s||s.model?.id!==t||!n?.sizeM)return;const r=s.sizeM!==void 0&&i?.sizeM!==void 0&&s.sizeM.widthM===i.sizeM.widthM&&s.sizeM.lengthM===i.sizeM.lengthM&&s.sizeM.heightM===i.sizeM.heightM;if(s.sizeM&&!r)return;const a={...s.sizeM,...Object.fromEntries(Object.entries(n.sizeM).filter(([,o])=>o!==void 0).map(([o,c])=>[o,this.roundedMeters(c)]))};this.updateDecor({sizeM:a})}roundedMeters(e){return Math.round(e*100)/100}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=_l([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const i=String.fromCharCode(65+t);if(!e.has(i))return i}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,i=t.milestones.find(n=>n.t===e);i&&(t.milestones=t.milestones.filter(n=>n.t!==i.t),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh())}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.goToMark(e)}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(i=>i.t===e?{...i,label:this.said.write(i.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(i.note,this.milestoneNoteInput.value,this.writingLanguage)}:i),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=_l(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;ps.showPresence(this.shadow.getElementById("milestone-row"),this.shadow.getElementById("milestone-item"),t);for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.deleteMilestoneButton])i.disabled=!t;this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.filter(e=>e.kind!=="observer").map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning(),this.refreshObserverList()}refreshObserverList(){const e=Ce.OBSERVER_PRINCIPAL,t=this.ufoElement.sighting.decor.filter(n=>n.kind==="observer");this.currentDecorId!==void 0&&t.some(n=>n.id===this.currentDecorId)&&this.observerAdded&&(this.observerShown=this.currentDecorId),this.observerAdded=!1,t.some(n=>n.id===this.observerShown)||(this.observerShown=e),this.observerList.setItems([{id:e,label:this.principalObserverLabel()},...t.map(n=>({id:n.id,label:this.decorLabel(n)}))],this.observerShown);const i=this.observerShown!==e;this.observerList.setRemoveEnabled(i),this.observerList.setActionEnabled("look-at-observer",i),this.placeDecorItem()}principalObserverLabel(){const e=[this.observerTitleInput.value,this.observerFirstNamesInput.value,this.observerLastNameInput.value].map(t=>t.trim()).filter(Boolean).join(" ");return e===""?this.messages.principalObserver:`${e} (${this.messages.principalObserver.toLowerCase()})`}observerAdded=!1;selectObserver(e){this.observerShown=e,e!==Ce.OBSERVER_PRINCIPAL&&this.selectDecor(e),this.refreshObserverList()}placeDecorItem(){const e=this.shadow.getElementById("decor-item"),t=this.shadow.getElementById("observer-decor-host"),i=this.shadow.getElementById("observer-principal");if(!e||!t||!i)return;const n=this.observerShown!==Ce.OBSERVER_PRINCIPAL;if(i.hidden=n,n&&this.isGroupIdOpen("group-observer")){e.parentElement!==t&&t.append(e),e.hidden=!1;return}e.parentElement===t&&this.shadow.getElementById("decor-list-header").after(e),e.hidden=this.decorList.value===""}syncDecorFields(){this.syncDecorVisibility()}async findGhosts(){const e=this.currentReference();if(e?.src){this.searchingGhosts=!0,this.syncFindGhosts(e);try{const{GhostSearchView:t}=await ae(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-UG9G-yF8.js");return{GhostSearchView:r}},__vite__mapDeps([22,7]),import.meta.url),i=this.messages,n={searching:i.referenceGhostsSearching,found:i.referenceGhostsFound,foundScaled:i.referenceGhostsFoundScaled,low:i.referenceGhostsLow,none:i.referenceGhostsNone,cropped:i.referenceGhostsCropped},s=await new t(this.ghostsStatus,n).search(e.src);this.ghostFinding=s&&s.pairs.length>0?{referenceId:e.id,src:e.src,search:s}:void 0,this.ghostsShown=!0,this.syncGhostsShown(),this.ufoElement.refresh()}finally{this.searchingGhosts=!1,this.syncFindGhosts(this.currentReference())}}}syncGhostsShown(){this.ghostsShownButton.hidden=!this.ghostFinding,this.ghostsShownButton.setAttribute("aria-pressed",String(this.ghostsShown)),this.ghostsShownButton.textContent=this.ghostsShown?this.messages.referenceGhostsHide:this.messages.referenceGhostsShow}syncFindGhosts(e){const t=!e?.src||this.sceneElement.referenceFailure(e.src)!==void 0;this.findGhostsButton.disabled=this.searchingGhosts||t,this.addReferenceLandmarkButton.disabled=t,t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark()}updateExposureSettings(){const e=this.ufoElement.sighting;e.iso=this.numberOrUndefined(this.isoInput.value);const t=this.meteringSelect.value;e.metering=t==="average"||t==="highlights"?t:void 0,this.meteringSelect.disabled=e.iso!==void 0,this.ufoElement.refresh()}updateLens(){const e=this.lensGlassSelect.value,t={...e?{glass:e}:{},drops:this.numberOrUndefined(this.lensDropsInput.value),condensation:this.numberOrUndefined(this.lensCondensationInput.value),dirt:this.numberOrUndefined(this.lensDirtInput.value),...this.lensShelteredInput.checked?{sheltered:!0}:{}};for(const i of["drops","condensation","dirt"])t[i]===void 0&&delete t[i];this.ufoElement.sighting.lens=Object.keys(t).length>0?t:void 0,this.ufoElement.refresh()}label(e,t){const i=this.shadow.getElementById(e);i&&(i.textContent=t)}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}decorBaseShownFor;showDecorBase(e){if(this.decorBaseHost.hidden=e===void 0,this.decorStateHost.hidden=e===void 0,!e){this.decorBaseForm.clear(),this.decorStateForm.clear(),this.decorBaseShown=!1,this.decorBaseShownFor=void 0;return}const t=this.decorBaseShownFor!==e.id;if(this.decorBaseShownFor=e.id,this.decorBaseShown){this.decorBaseForm.sync(t),this.decorStateForm.sync(t);return}this.decorBaseShown=!0;const i=()=>new Io(()=>{const n=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId);return n?Rr.viewOf(n,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(n,s)=>this.commitDecorBase(n,s.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(Ws.BASE,i(),()=>{}),this.decorStateForm.show(Ws.STATE,i(),()=>{})}decorPositionPlace(){const e=()=>{const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===this.currentDecorId);return t<0?[]:[`decor.${t}.eastM`,`decor.${t}.northM`]};return{frame:()=>this.positionFrame(this.currentDecorId),messages:()=>this.messages,basis:{read:()=>this.ufoElement.sighting.provenance.at(e()[0]??"")?.basis,write:(t,i)=>this.writePositionBasis(e(),i)}}}framePlace(){return{frame:()=>this.positionFrame(),messages:()=>this.messages}}positionFrame(e){const t=this.ufoElement.currentTime,i=[{label:this.messages.positionObserver,eastM:0,northM:0}];for(const n of this.ufoElement.sighting.decor){if(n.id===e)continue;const{eastM:s,northM:r}=qs(n,t);i.push({id:n.id,label:this.decorLabel(n),eastM:s,northM:r})}return{origin:this.plantingCentre(),references:i}}syncObserverPosition(){const e=this.ufoElement.sighting,t=this.ufoElement.currentTime;this.observerSaid=e.observerTrack.getLatestPoseAt(t)?.saidPosition;const i=this.positionFrame();this.observerPosition.frame={...i,references:i.references.filter(s=>s.id!==void 0)};const n=JSON.stringify(this.observerSaid??null);n!==this.observerSaidShown&&(this.observerSaidShown=n,this.observerPosition.said=this.observerSaid),this.observerPosition.basis=e.provenance.at(this.observerPositionPaths()[0]??"")?.basis}observerPositionPaths(){const e=this.ufoElement.currentTime,t=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(i=>i.t===e);return t<0?[]:[`observerTrack.keyframes.${t}.pose.lat`,`observerTrack.keyframes.${t}.pose.lng`]}writeObserverBasis(e){this.observerPositionPaths().length===0&&this.updateObserver(),this.writePositionBasis(this.observerPositionPaths(),e)}writePositionBasis(e,t){const i=this.ufoElement.sighting.provenance;for(const n of e)t===void 0||t==="stated"?i.clear(n):i.set(n,{basis:t});this.dispatchEvent(new CustomEvent("sightingchange"))}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=Al.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:me.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:Al.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:Ws.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:lf[e.kind]?.id}}placedByAuthor(e){if(!e.lamp?.supposed)return e;const t=this.sceneElement.decorDrawnOffset(e.id),{supposed:i,...n}=e.lamp,s={...e,eastM:e.eastM+(t?.eastM??0),northM:e.northM+(t?.northM??0),...Object.keys(n).length>0?{lamp:n}:{}};Object.keys(n).length===0&&delete s.lamp;const r=this.ufoElement.sighting;return r.decor=r.decor.map(a=>a.id===e.id?s:a),s}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId);if(!i)return;const n=t==="eastM"||t==="northM"?this.placedByAuthor(i):i;if((t==="lit"||t==="headlights")&&this.ufoElement.playbackState==="playing")return;const s=this.ufoElement.currentTime,r=Rr.viewOf(n,s,this.sceneElement.sunAltitudeDeg);e(r);const a=this.ufoElement.sighting;a.decor=a.decor.map(c=>c.id===n.id?Rr.apply(c,r,t,s):c),t==="model.id"&&this.adoptCatalogueSize(n,r.model?.id);const o=a.decor.find(c=>c.id===n.id);t==="title"&&this.decorList.rename(o.id,this.decorLabel(o)),this.syncDecorVisibility(),this.ufoElement.refresh(),t==="lightRig"&&this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorBaseFromTimeline(){this.ufoElement.playbackState==="playing"||!this.decorBaseShown||(this.decorBaseForm.sync(),this.decorStateForm.sync())}showDecorParameters(e){const t=e?si.of(e,this.publishedParametersOf(e)):void 0;if(!e||!t){this.decorParametersShownFor=void 0,this.decorParameterForm.clear(),this.decorParametersHost.hidden=!0;return}this.decorParametersHost.hidden=!1;const i=`${e.id}|${t.kind}|${t.parameters.map(r=>r.key).join(",")}`;if(i===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=i;const n=e.id,s=new Io(()=>this.ufoElement.sighting.decor.find(r=>r.id===n),r=>{const a=this.ufoElement.sighting;a.decor=a.decor.map(o=>{if(o.id!==n)return o;const c=structuredClone(o);return r(c),c})});this.decorParameterForm.show(t,s,()=>{this.syncDecorVisibility(),this.ufoElement.refresh()})}syncDecorParameterVisibility(){this.showDecorParameters(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);this.refreshDecorModelOptions(e),this.showDecorBase(e),this.syncDecorParameterVisibility()}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++,this.meteorMagnitudeLimit());e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;meteorMagnitudeLimit(){const e=this.ufoElement.sighting,t=this.observerAtStart(),i=e.event.time?.year!==void 0?zn(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const n=Ti("Sun",i,t).altitudeDeg;return ea(n,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Rs;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Hf;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new vs(["en"]);tagNames=new _g({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,n=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?zn(i,t.lng,e.event.utcOffsetHours):void 0,s=JSON.stringify([n?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,en(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status,this.sceneElement.groundKey]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!n||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.disabled=!0,this.showCometButton.disabled=!0,this.showNovaButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown),this.labelSkyButtons();return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},a=[this.starsClause(n,r),this.showerClause(n,r),this.cometClause(n,r),this.novaClause(n,r),this.eclipseClause(n,r),this.moonClause(n,r),this.satelliteClause(n,r),this.reentryClause(n,r),this.fireballClause(n,r),this.opticsClause(n,r),this.rainbowClause(n,r),this.glowClause(n,r)].filter(o=>o!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",a.join(" · ")),this.labelSkyButtons()}labelSkyButtons(){const e=this.messages,t=[[this.showMeteorButton,e.showMeteor,e.noMeteor],[this.showCometButton,e.showComet,e.noComet],[this.showNovaButton,e.showNova,e.noNova],[this.showSatelliteButton,e.showSatellite,e.noSatellite],[this.showFireballButton,e.showFireball,e.noFireball]];for(const[i,n,s]of t){const r=i.disabled?s:n;i.title=r,i.setAttribute("aria-label",r)}}instrumentGain(){const e=this.ufoElement.sighting;return Dn.gainFor(e.instrument,{fNumber:pt(e,0)?.fNumber,fieldOfViewDeg:Oi.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Ti("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=ea(i,n,s),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<j6)return this.messages.skyStarsNone;const o=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",a(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(r)).replace("{device}",this.naming.instrument(o)).replace("{gain}",a(Math.abs(n))).replace("{eye}",a(ea(i,0,s)));return r<=Md?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",a(Md))}showerClause(e,t){const i=Ui.observedRatePerHour(Ui.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=sh.activeAt(e);if(n.length===0)return this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyNothingActive.replace("{sporadic}",i);const s=n.map(r=>{const a=sh.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:sh.observedRatePerHour(r.zhr,a.altitudeDeg,r.shower.populationIndex)}}).sort((r,a)=>a.rate-r.rate)[0];return s.rate<=0?(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(s.entry.shower))):(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerActive.replace("{name}",this.naming.shower(s.entry.shower)).replace("{altitude}",String(Math.round(s.position.altitudeDeg))).replace("{bearing}",this.naming.towards(s.position.azimuthDeg)).replace("{rate}",s.rate.toLocaleString(void 0,{maximumFractionDigits:s.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=Dp.brightestAt(e,t);if(!i||i.magnitude>wh){this.showCometButton.disabled=!0;return}return this.showCometButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.cometText(i)}novaClause(e,t){const i=Gf.brightestAt(e,t);if(!i||i.magnitude>wh){this.showNovaButton.disabled=!0;return}return this.showNovaButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.novaText(i)}eclipseClause(e,t){const i=Qi.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const n=Ti("Sun",i.peak,t),s=r=>r.replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),a=Math.round(i.totality.seconds%60);return s(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${a} s`)}return s(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=Ti("Moon",e,t);if(i.altitudeDeg<=0||Xo(e).illuminatedFraction<.97)return;const n=[],s=ts.distanceKm(e,t),r=ts.relativeToMean(ts.radiusAtKm(s)),a=s<=ts.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:s>=ts.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return a&&n.push(a.replace("{distance}",(Math.round(s/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(ts.radiusAtKm(s)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Kf.isIn(e)&&n.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),n.length>0?n.join(" · "):void 0}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=xr.visibilityAt(e,t),n=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(n!==void 0)return n;if(this.showSatelliteButton.disabled=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=ea(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),a=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",a);const o=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",o).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",a):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),n=i+this.satelliteSpanMs(),s=[i,n,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==s){const c={key:s,status:"loading"};this.reentries=c,Ce.reentryArchive.candidates(i,n,t).then(h=>{c.status=h?"ready":"unavailable",c.candidates=h,this.reentries===c&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=xr.visibilityAt(e,t).sunAltitudeDeg<-6,a=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(a.length===0)return;const o=a.slice(0,3).map(c=>this.reentryText(c));return a.length>3&&o.push(this.messages.skyReentriesMore.replace("{count}",String(a.length-3))),this.messages.skyReentries.replace("{list}",o.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,n=new Date(e.timeMs);if(t.precision==="day"){const a=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",a)}const s=this.observerClock(n).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",s).replace("{hours}",(t.uncertaintyHours??0).toLocaleString(this.showerLanguage()));const r=e.offsetMinutes?this.messages.skyReentryOffset.replace("{minutes}",String(e.offsetMinutes)):"";return t.seenFrom&&e.seenKm!==void 0?this.messages.skyReentrySeen.replace("{name}",i).replace("{time}",s).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",s)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(c=>c.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(c=>c.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses();if(this.showSatelliteButton.disabled=this.aimableSatellitePasses(i).length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const s=i[0].peak,a=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",s.object.name).replace("{magnitude}",s.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(s.altitudeDeg))).replace("{bearing}",this.naming.towards(s.azimuthDeg)).replace("{time}",this.observerClock(s.date)),o=this.starlinkTrain(i);return o?`${a}, ${o}`:a}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const n=i.peak.magnitude;if(n===void 0)return!1;const s=Ti("Sun",i.peak.date,t);return n<=ea(s.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,n)=>i.peak.magnitude-n.peak.magnitude)}aimableSatellitePasses(e){return e.filter(t=>this.passTimelineMs(t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(t.peak.altitudeDeg,t.peak.azimuthDeg))}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:a,launch:o}=r.peak.object;a!=="starlink"||!o||(r.peak.date.getTime()-Date.parse(`${o}T00:00:00Z`))/864e5>60||t.set(o,(t.get(o)??0)+1)}const[i,n]=[...t.entries()].sort((r,a)=>a[1]-r[1])[0]??[];if(!i||!n||n<3)return;const s=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(n)).replace("{date}",s)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=pt(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=zn(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.aimableSatellitePasses(this.visibleSatellitePasses());if(e.length===0)return;const t=e.map(n=>`${n.object.norad}@${n.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>or.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=or.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,n)=>i.magnitude-n.magnitude)}aimableFireballs(e,t){return e.filter(i=>this.fireballTimelineMs(i,t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(i.peak.altitudeDeg,i.peak.azimuthDeg))}fireballTimelineMs(e,t){const{record:i}=e,n=i.from[2]-i.to[2],s=Math.abs(n)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/n));return i.t-t.getTime()+s*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.disabled=this.aimableFireballs(i,e).length===0,i.length===0)return;const n=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",n.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(n.record.t))).replace("{altitude}",String(Math.round(n.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(n.peak.azimuthDeg)).replace("{distance}",String(Math.round(n.peak.distanceKm/10)*10)).replace("{stations}",String(n.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const n=zn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.aimableFireballs(this.strikingFireballs(n,this.observerAtStart()),n);if(s.length===0)return;const r=s[this.fireballRank++%s.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,n),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=en(this.ufoElement.sighting,0),n=Ti("Sun",e,t),s=Ti("Moon",e,t),r=ut.deckLitUntilDeg(ut.DECK_HEIGHT_M),a=n.altitudeDeg>-r,o=a?n:s;if(o.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(ut.strength(c,i.lowerCloudCover??i.cloudCover,o.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=a?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(ut.formsAt(o.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??kp;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const i=en(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Ti("Sun",e,t),s=Ti("Moon",e,t),r=n.altitudeDeg>0,a=r?n:s;if(a.altitudeDeg<=0)return this.messages.skyBowNoSource;const o=i.lowerCloudCover??i.cloudCover;if(jn.strength(i.precipitationIntensity,o,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=jn.formsAt(a.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(jn.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(Xo(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Ti("Sun",e,t);if(i.altitudeDeg>lN)return;const n=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),s=[];if(n.milkyWay&&s.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(n.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(n.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(n.milkyWay.azimuthDeg))),n.zodiacal){const p=n.zodiacal.sunSeparationDeg<=Gt.CONE_SEPARATION_DEG;s.push((p?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(n.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(n.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(n.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(n.zodiacal.sunSeparationDeg))))}if(s.length>0)return this.listed(s);const r=this.decimal(n.darkestSkyMagPerArcsec2,1),a=Ti("Moon",e,t),o=n.darkestSkyMagPerArcsec2<cN,c=this.ufoElement.sighting.lightPollution,h=de.scatteringAt(90-a.altitudeDeg)*de.moonOutput(de.phaseAngleOf(Xo(e).illuminatedFraction),a.altitudeDeg)*de.scatteredFraction(90),d=de.artificialZenithNanolamberts(c)>h;if(o&&a.altitudeDeg>0&&!d){const p=Math.round(Xo(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=de.artificialZenithNanolamberts(c)>de.twilightExcessNanolamberts(i.altitudeDeg);return o&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):o?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Ti("Sun",e,t),n=Ti("Moon",e,t);return de.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:de.phaseAngleOf(Xo(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new Gt;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=i=>String(Math.round(i??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=this.naming.comet(e.apparition),i=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",i):(e.elongationDeg<Dp.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=zn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Dp.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!s||this.sceneElement.groundHides(s.position.altitudeDeg,s.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=zn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Gf.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!s||this.sceneElement.groundHides(s.position.altitudeDeg,s.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(o=>o.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:n}=qs(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,a=Math.atan2(n-tN,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(a*10)/10),this.updateObserver()}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return i1(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Sc.width/2,y:e.height/2-Sc.height/2,width:Sc.width,height:Sc.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new Vb(this.ufoElement.sighting.timeline,new l6(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t),this.recordButton.querySelector(".record-label")||this.recordButton.replaceChildren(Object.assign(document.createElement("span"),{className:"record-icon"}),Object.assign(document.createElement("span"),{className:"record-label"})),Te.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=Zs.preferencesFor(this);this.preferences=t;const i=Id(t,Td),n=this.narrativeProvider.localize?.(i),[s,r,a]=i==="en"?[So,{},void 0]:await Promise.all([cx(i),vE(i),hx(i)]);if(await n,e!==this.localeToken)return;const o=i!==this.language;this.language=i,this.naming=new Hf(a),this.said=new vs(t),this.tagNames=new _g(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new qc(s,this.naming,this.said,this.tagNames,{messages:s,locale:this.language}),this.refreshParamSummary()),o?this.showSaidTexts():this.showTags()}preferences=[];language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===Jh&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.sourceSelect.setAttribute("aria-label",e.shape),this.shadow.getElementById("shape-empty").textContent=e.emptyShapes,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.shadow.getElementById("label-shape-rotation").textContent=e.shapeRotation,this.shapeRotationInput.title=e.shapeRotationTitle,this.labelSizeLock.textContent=e.sizeLock;for(const[i,n]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(i).textContent=n;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.shadow.getElementById("label-account-view").textContent=e.accountView,this.accountViewSelect.options[0].textContent=e.accountView2d,this.accountViewSelect.options[1].textContent=e.accountView3d,this.accountViewSelect.title=e.accountViewHint,this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextDuplicateButton.textContent=e.duplicate,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.frozenPanel.localize(e),this.sectionFilePanel.localize(e),this.shadow.getElementById("observer-identity-hint").textContent=e.identityHint,this.shadow.getElementById("identity-ask-initials").textContent=e.identityInitials,this.shadow.getElementById("identity-ask-keep").textContent=e.identityKeep,this.shadow.getElementById("identity-ask-back").textContent=e.identityBack,this.labelImportFile.textContent=e.importFile,this.shadow.getElementById("label-whole-keyframes").textContent=e.wholeKeyframes,this.wholeKeyframesInput.closest("label").title=e.wholeKeyframesHint,this.importInput.placeholder=e.importUrlPlaceholder;for(const i of this.shadow.querySelectorAll(qd))i.messages=e;this.labelObserverAge.textContent=e.observerAge,this.labelObserverBirth.textContent=e.observerBirth,this.perceptionSettings.labels=e.observerPerception,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,this.labelAccountUrl.textContent=e.accountUrl,this.labelAccountFollowedUp.textContent=e.accountFollowedUp;for(const[i,n]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const s=this.shadow.getElementById(i);s&&(s.textContent=n)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelPosition.textContent=e.positionLabel,this.observerPosition.messages=e,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.label("label-iso",e.iso),this.isoInput.title=e.isoTitle,this.label("label-metering",e.metering),this.meteringSelect.title=e.meteringTitle,this.label("metering-device",e.meteringDevice),this.label("metering-average",e.meteringAverage),this.label("metering-highlights",e.meteringHighlights),this.label("label-lens-glass",e.lensGlass),this.label("label-reference-ghosts",e.referenceGhosts),this.findGhostsButton.textContent=e.referenceFindGhosts,this.syncGhostsShown(),this.label("lens-glass-none",e.lensGlassNone),this.label("lens-glass-filter",e.lensGlassFilter),this.label("lens-glass-window",e.lensGlassWindow),this.label("lens-glass-windscreen",e.lensGlassWindscreen),this.label("label-lens-drops",e.lensDrops),this.lensDropsInput.title=e.lensDropsTitle,this.label("label-lens-condensation",e.lensCondensation),this.lensCondensationInput.title=e.lensCondensationTitle,this.label("label-lens-dirt",e.lensDirt),this.lensDirtInput.title=e.lensDirtTitle,this.label("label-lens-sheltered",e.lensSheltered),this.lensShelteredInput.title=e.lensShelteredTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.shapeAddMenu.panel.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"trafficlight",label:e.decorTrafficLight},{value:"crossing",label:e.decorCrossing},{value:"roadsign",label:e.decorRoadSign},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,empty:e.emptyDecor,actions:{"look-at-decor":e.lookAtDecor}}),this.labelSkyButtons(),this.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.observerList.setLabels({list:e.observerGroup,remove:e.deleteObserver,add:e.addObserver,actions:{"look-at-observer":e.lookAtDecor}}),this.refreshObserverList(),this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const t=this.shadow.getElementById("option-scenery-none");t&&(t.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote,this.shadow.getElementById("milestone-empty").textContent=e.emptyMilestones;for(const[i,n]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])i.title=n,i.setAttribute("aria-label",n);this.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup,this.labelLaunchesSubgroup.textContent=e.launchesSubgroup,this.labelBeamsSubgroup.textContent=e.beamsSubgroup,this.labelLanternsSubgroup.textContent=e.lanternsSubgroup;for(const i of["location","decor","weather"]){const n=this.shadow.getElementById(`${i}-settings-button`);n?.setAttribute("title",e.dataSources),n?.setAttribute("aria-label",e.dataSources);const s=this.shadow.getElementById(`label-${i}-settings`);s&&(s.textContent=e.dataSources)}this.bodyEditor?.setLanguage(this.language),this.launchEditor?.setLanguage(this.language),this.beamEditor?.setLanguage(this.language),this.lanternEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerTab,this.labelWeatherGroup.textContent=e.sky,this.fitGroupTabs(),this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new qc(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),this.refreshParamSummary(),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelRareIce.textContent=e.rareIceCrystals,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.referenceSelect.setAttribute("aria-label",e.reference),this.shadow.getElementById("reference-empty").textContent=e.emptyReferences,this.shadow.getElementById("reference-landmark-empty").textContent=e.emptyReferenceLandmarks,this.shadow.getElementById("trace-empty").textContent=e.emptyTraces,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSourceInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.setReferenceAddKinds(e.addReferenceUrl,e.addReferenceFile,e.referenceStreetSearch),this.addReferenceButton.title=e.addReference,this.addReferenceButton.setAttribute("aria-label",e.addReference),this.referenceAddMenu.panel.setAttribute("aria-label",e.addReference),this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.title=e.addReferenceLandmark,this.addReferenceLandmarkButton.setAttribute("aria-label",e.addReferenceLandmark),this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,this.labelTraceImport.textContent=e.traceImport,this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=e.traceImport,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[i,n]of this.soundKindOptions)n.textContent=this.soundKindLabel(i,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e)}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[n,s]of Object.entries(t))this.shadow.getElementById(`label-section-${n}`).textContent=s;this.sectionFolds.setMessages(e),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const n of["location-settings","decor-settings","weather-settings"])gs.popover(this.shadow.getElementById(n),e.close);gs.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),gs.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),gs.button(this.contextMenu,e.close,()=>this.hideContextMenu()),gs.button(this.decorContextMenu,e.close,()=>this.hideDecorContextMenu()),this.shadow.getElementById("label-editor-kicker").textContent=e.editorKicker,this.shadow.getElementById("label-save").textContent=e.save,this.shareDialog.useLanguage(this.language).then(n=>{n&&(this.shareMessages=n,this.shadow.getElementById("label-share").textContent=n.share,this.refreshEditorHead())});const i={observation:e.panelIntroObservation,observer:e.panelIntroObserver,location:e.panelIntroLocation,temporal:e.panelIntroTemporal,decor:e.panelIntroDecor,weather:e.panelIntroWeather,shape:e.panelIntroShape,sound:e.panelIntroSound,reference:e.panelIntroReference,file:e.panelIntroFile};for(const[n,s]of Object.entries(i)){const r=this.shadow.querySelector(`[aria-controls="group-${n}"]`);r.dataset.intro=s,Ce.titleGroupTab(r)}this.refreshEditorHead()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;if(!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)){const d=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;this.beginCameraDrag(t,u?.kind==="decor"?u.id:void 0,u?.kind==="body"?u.id:void 0)}return}const n=this.decorMoveAxis(e);if(i==="decor"&&n&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t,n))return;const s=this.ufoElement.sighting.timeline,r=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const d=new Sm(this.selectedMembers()),u=Vt.hitTestHandle({bounds:d.bounds(),angle:0},t);if(u==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:d,startPointer:t},this.startDragListening();return}if(u){if(a)return;this.dragState={kind:"group-resize",group:d,handle:u},this.startDragListening();return}}else{const d=s.getInterpolatedShapeAt(r,this.currentSourceId),u=d?.kind==="polygon"?Vt.hitTestVertex(d,t):void 0;if(d?.kind==="polygon"&&u!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:d,vertexIndex:u},this.startDragListening();return}const p=d&&Vt.hitTestHandle(d,t);if(d&&p){if(a)return;this.beginDrag(p==="rotate"?"rotate":"resize",this.currentSourceId,d,t,p);return}}const c=this.ufoElement.shapeAt(t.x,t.y,up);if(!c){const d=n==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;if(u?.kind==="body"&&u.id!==void 0){a?this.showBody(u.id):this.beginCameraDrag(t,void 0,u.id);return}const p=u?.kind==="decor"?u.id:void 0;if(p!==void 0){a?(this.selectDecor(p),this.revealDecorPanel()):this.beginCameraDrag(t,p);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),this.flash(this.shapeTitleInput.closest("label")),e.shiftKey?this.toggleUnitSelection(c.sourceId):this.selectedSourceIds.has(c.sourceId)||this.selectUnit(c.sourceId),a||!o)return;const h=[...this.selectedSourceIds].map(d=>({sourceId:d,original:d===c.sourceId?c.shape:s.getInterpolatedShapeAt(r,d)??c.shape}));this.dragState={kind:"move",sources:h,startPointer:t},this.startDragListening()}showBody(e){if(this.fileSyncActive()){this.showInFile(this.bodyPath(e));return}this.revealShapePanel();const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-bodies");t&&this.openSubgroup(t),this.loadBodyEditor().then(i=>i.show(e))}revealDecorPanel(){if(this.fileSyncActive()){this.fileFocus="decor",this.syncCanvasMode();return}const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-decor");e&&this.toggleGroup(e,!0)}revealShapePanel(){if(this.fileSyncActive()){this.fileFocus="shape",this.syncCanvasMode();return}const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="shape"),this.refreshSourceList(),this.onSelectionOrTimeChanged(),this.showInFile(this.shapePath(e)))}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(s=>this.selectedSourceIds.has(s))){if(i.length>=this.selectedSourceIds.size)return;for(const s of i)this.selectedSourceIds.delete(s);if(!this.selectedSourceIds.has(this.currentSourceId)){const s=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,a)=>s.indexOf(r)-s.indexOf(a)).pop()}}else{for(const s of i)this.selectedSourceIds.add(s);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(n,this.currentSourceId):void 0,a=s?.kind==="polygon"&&Vt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,up);if(a){this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),this.currentSourceId=a.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const o=this.pickDecorAt(e),c=o?this.ufoElement.sighting.decor.find(h=>h.id===o):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(e.clientX-i.left)/i.width*2-1,s=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(n,s)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const i=this.ufoElement.sighting.timeline.sourceIds,n=i.filter(p=>this.selectedSourceIds.has(p)),s=i.length<=n.length,r=n.length>0&&i.slice(i.length-n.length).every(p=>this.selectedSourceIds.has(p)),a=n.length>0&&i.slice(0,n.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||a,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:a?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const o=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!o,this.contextUngroupButton.title=o?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?Vt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=f2;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";const t=[...this.ufoElement.sighting.timeline.sourceIds],i=this.ufoElement.sighting.interpretation?.bodies??[];if(t.length===0&&i.length===0){const n=document.createElement("span");n.className="submenu-empty",n.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(n)}for(const n of t){const s=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=e.occludesSourceIds?.includes(n)??!1,r.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,n,r.checked)),s.appendChild(r),s.appendChild(document.createTextNode(this.shapeLabel(n))),this.contextMasksSubmenu.appendChild(s)}for(const n of i){const s=this.sceneElement.bodyMaskedBy(n.id,e.id);if(s===void 0)continue;const r=document.createElement("span");r.className="submenu-empty submenu-fact";const a=this.said.read(n.title)??n.id,o=this.messages;r.textContent=`${a} — ${s>=.995?o.masksBodyFully:s>.005?o.masksBodyPartly.replace("{share}",String(Math.round(s*100))):o.masksBodyNot}`,this.contextMasksSubmenu.appendChild(r)}}updateDecorOccludesShape(e,t,i){const n=this.ufoElement.sighting;n.decor=n.decor.map(s=>{if(s.id!==e)return s;const r=i?[...new Set([...s.occludesSourceIds??[],t])]:(s.occludesSourceIds??[]).filter(a=>a!==t);return{...s,occludesSourceIds:r.length>0?r:void 0}}),this.ufoElement.refresh()}viewObserverAccount(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=Vt.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=Vt.hitTestVertex(i,e);if(n===void 0)return;const s=Vt.deleteVertex(i,n);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,i,n,s){this.dragState={kind:e,sourceId:t,original:i,handle:s,startPointer:n},this.startDragListening()}ndcOf(e){const t=this.ufoElement.canvasElement.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height*2-1)}}skyDirectionOf(e){const t=this.ndcOf(e);if(!t)return;const i=this.sceneElement.directionAt(t.x,t.y);return{azimuthDeg:(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,i.y)))*180/Math.PI}}beginBodyDrag(e){const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!n||!i)return!1;i.show(n);const s=i.readingNow(),r=this.skyDirectionOf(e);return!s||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:s.azimuthDeg,bodyAltitudeDeg:s.altitudeDeg},this.setCanvasCursor("move"),this.startDragListening(),!0)}onBodyDragPointerMove(e){const t=this.dragState;if(t?.kind!=="body")return;const i=this.skyDirectionOf(e);if(!i)return;const n=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+n,t.bodyAltitudeDeg+i.altitudeDeg-t.pointerAltitudeDeg)}bodyCanvasBounds(){const e=this.bodyEditor?.currentBodyId;return this.canvasBoundsOf(e===void 0?void 0:this.sceneElement.bodyScreenBox(e))}canvasBoundsOf(e){if(!e)return;const t=this.ufoElement.canvasElement,i=Math.max(ix,(e.maxX-e.minX)/2*t.width),n=Math.max(ix,(e.maxY-e.minY)/2*t.height),s=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return{x:s-i/2,y:r-n/2,width:i,height:n}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),n=e.reading();if(!i||!n)return!1;const s=Vt.hitTestHandle({bounds:i,angle:0},t);if(!s)return!1;if(s==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...n.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:s,centre:r,startPointer:t,startSizeM:{...n.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(s,0)),this.startDragListening(),!0}beginBodyHandleDrag(e){return this.beginFrameDrag(this.bodyFrame,e)}onFrameDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="frame-rotate"){const u=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,p=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,f=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:f.headingDeg,pitchDeg:f.pitchDeg+p,rollDeg:f.rollDeg+u}:{headingDeg:f.headingDeg+u,pitchDeg:f.pitchDeg,rollDeg:f.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:n,startPointer:s,startSizeM:r,handle:a}=t,o=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=a==="e"||a==="w",h=a==="n"||a==="s",d=c?o(i.x-n.x,s.x-n.x):h?o(i.y-n.y,s.y-n.y):o(Math.hypot(i.x-n.x,i.y-n.y),Math.hypot(s.x-n.x,s.y-n.y));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:tg};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.decorReading(),resize:e=>this.commitDecorBase(t=>{Object.assign(t,{sizeM:{widthM:this.roundedMeters(e.widthM),lengthM:this.roundedMeters(e.lengthM),heightM:this.roundedMeters(e.heightM)}})},"sizeM.widthM"),turnTo:e=>this.commitDecorBase(t=>{t.headingDeg=this.rounded((e.headingDeg%360+360)%360)},"headingDeg"),rotateDegPerPx:J6};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=me.naturalSize(e.kind,e.floors);return{sizeM:{widthM:e.sizeM?.widthM??t.widthM??1,lengthM:e.sizeM?.lengthM??t.lengthM??1,heightM:e.sizeM?.heightM??t.heightM??1},attitude:{headingDeg:Rr.viewOf(e,this.ufoElement.currentTime).headingDeg,pitchDeg:0,rollDeg:0}}}onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!n||!i||(e.preventDefault(),i.show(n),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorMoveAxis(e){if(!(e.metaKey||[e.shiftKey,e.altKey,e.ctrlKey].filter(Boolean).length>1))return e.shiftKey?"east":e.altKey?"north":e.ctrlKey?"up":"ground"}grabsDecor(e,t,i){const n=this.pickDecorAt(e);if(n===i.id)return!0;const s=this.decorCanvasBounds();return s!==void 0&&t.x>=s.x&&t.x<=s.x+s.width&&t.y>=s.y&&t.y<=s.y+s.height?n===void 0||this.ufoElement.sighting.decor.find(a=>a.id===n)?.kind==="terrace":!1}beginDecorDrag(e,t,i){const n=this.editableDecor();if(!n)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.ufoElement.shapeAt(t.x,t.y,up)||!this.grabsDecor(e,t,n))return!1;const s=this.ndcOf(e),r=Rr.viewOf(this.placedByAuthor(n),this.ufoElement.currentTime),a=s?this.sceneElement.decorGrabHeightAt?.(n.id,s.x,s.y)??0:0,o=s&&this.sceneElement.decorGroundPointAt(n.id,s.x,s.y,a);return!s||!o?!1:(this.dragState={kind:"decor-move",id:n.id,startGround:o,grabHeightM:a,axis:i,startAltitudeM:r.altitudeM,startNdcY:s.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(n.id)??0,startEastM:r.eastM,startNorthM:r.northM},this.setCanvasCursor("move"),this.startDragListening(),!0)}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e);if(!i)return;const n=this.sceneElement.decorGroundPointAt(t.id,i.x,i.y,t.grabHeightM);!n&&t.axis!=="up"||this.commitDecorBase(s=>{n&&(t.axis==="ground"||t.axis==="east")&&(s.eastM=this.roundedMeters(t.startEastM+n.x-t.startGround.x)),n&&(t.axis==="ground"||t.axis==="north")&&(s.northM=this.roundedMeters(t.startNorthM-(n.z-t.startGround.z))),t.axis==="up"&&(s.altitudeM=this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))},"eastM")}beginCameraDrag(e,t,i){const n=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,pressedBodyId:i,moved:!1,startPointer:e,startHeadingDeg:n?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:n?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:n},n||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&Ro(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Ro(i.kind)),t=e?`${e.id}:${e.observerSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.dragState?.kind==="body"){this.onBodyDragPointerMove(e);return}if(this.dragState?.kind==="frame-resize"||this.dragState?.kind==="frame-rotate"){this.onFrameDragPointerMove(e);return}if(this.dragState?.kind==="decor-move"){this.onDecorMovePointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:n,startPointer:s}=this.dragState,r=t.x-s.x,a=t.y-s.y,o=n.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+a}}}));this.commitShapes(i,o)}else if(this.dragState.kind==="group-resize"){const{group:n,handle:s}=this.dragState;this.commitShapes(i,n.resize(s,t))}else if(this.dragState.kind==="group-rotate"){const{group:n,startPointer:s}=this.dragState;this.commitShapes(i,n.rotate(t,s))}else if(this.dragState.kind==="vertex"){const{sourceId:n,original:s,vertexIndex:r}=this.dragState,a=Vt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:a}])}else{const{kind:n,sourceId:s,original:r,handle:a}=this.dragState,o=n==="resize"?Vt.resizeShape(r,a,t):Vt.rotateShape(r,t);this.commitShapes(i,[{sourceId:s,shape:o}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:n,startPitchDeg:s,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<Q6)return;this.cameraDragState.moved=!0}const a=n+(t.x-i.x)*tg,o=Math.max(-90,Math.min(90,s-(t.y-i.y)*tg));if(r){this.indoorLookYawDeg=a,this.indoorLookPitchDeg=o,this.sceneElement.setIndoorLook(a,o),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}walkOrTurn(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing"||this.isObserverInsideDecor())return;const t=e.shiftKey?rN:1,i=this.numberOrUndefined(this.headingInput.value)??0;if(e.key==="ArrowLeft"||e.key==="ArrowRight"){this.headingInput.value=String(this.rounded(i+(e.key==="ArrowRight"?1:-1)*sN*t)),this.updateObserver();return}const n=this.numberOrUndefined(this.latInput.value),s=this.numberOrUndefined(this.lngInput.value);if(n===void 0||s===void 0)return;const r=(e.key==="ArrowUp"?1:-1)*nN*t,a=i*Math.PI/180,o=ws(Math.sin(a)*r,-Math.cos(a)*r,n,s);this.latInput.value=o.lat.toFixed(7),this.lngInput.value=o.lng.toFixed(7);const c=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(c,this.plantingCentre()),this.surroundings.walked(o.lat,o.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=st(t.lat,t.lng,e.lat,e.lng),n=i.x,s=-i.z;if(Math.hypot(n,s)<1e-6)return;const r=(o,c)=>Math.round((o-c)*1e3)/1e3,a=this.ufoElement.sighting;a.decor=a.decor.map(o=>({...o,eastM:r(o.eastM,n),northM:r(o.northM,s),...o.track?{track:o.track.map(c=>({...c,eastM:r(c.eastM,n),northM:r(c.northM,s)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(yo,i.width-io);break;case"ArrowRight":i.width+=io;break;case"ArrowUp":i.height=Math.max(yo,i.height-io);break;case"ArrowDown":i.height+=io;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=io;break;case"ArrowRight":i.x+=io;break;case"ArrowUp":i.y-=io;break;case"ArrowDown":i.y+=io;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:n,shape:s}=i[0];this.commitShapes(t,[{sourceId:n,shape:{...s,bounds:this.nudgeBounds(s.bounds,e)}}])}else{const n=new Sm(i),s=this.nudgeBounds(n.bounds(),e);this.commitShapes(t,n.scaleTo(s))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode(),n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const o=r?this.bodyCanvasBounds():void 0,c=o&&Vt.hitTestHandle({bounds:o,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const o=this.decorCanvasBounds(),c=o&&Vt.hitTestHandle({bounds:o,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.editableDecor();if(h&&!this.ufoElement.shapeAt(t.x,t.y,up)&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const o=Vt.hitTestHandle({bounds:new Sm(this.selectedMembers()).bounds(),angle:0},t);if(o)return this.cursorForHandle(o,0)}else{const o=n.getInterpolatedShapeAt(s,this.currentSourceId);if(o?.kind==="polygon"&&Vt.hitTestVertex(o,t)!==void 0)return"vertex";const c=o&&Vt.hitTestHandle(o,t);if(o&&c)return this.cursorForHandle(c,o.angle)}return n.hitTest(s,t.x,t.y)?r&&a?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${Vt.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),n=e.clientX-i.left,s=e.clientY-i.top;this.recorder?.onPointerMove(n,s),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(px(this.buildPrototype({x:0,y:0,width:Sc.width,height:Sc.height}),n,s))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(!(i.width===0||i.height===0))return{x:(e.clientX-i.left)/i.width*t.width,y:(e.clientY-i.top)/i.height*t.height}}}const hN={measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},ax="rr0-sighting-editor",ox="rr0-ufo-recorder";class dN extends Ce{}function tE(){Ax(),Rx(),ZS(),p6(),d6(),v6(),cm(),customElements.get(ax)||customElements.define(ax,Ce),customElements.get(ox)||customElements.define(ox,dN)}const Uv={event:"Event",accountOf:"Observation of",passagesHeading:"Reported in",interviewOf:"Interview of",untitledInterview:"Interview {n}",deleteInterviewQuestion:"Delete this interview from the case? Nothing is written until the case is saved.",untitledReading:"Reading {n}",eventsInTime:"Events · in the order of time",citedMoment:"Moment {k}, quoted in {title}: “{quote}”",backToInterview:"Back to the interview",openEvent:"Open",previousEvent:"Previous event",nextEvent:"Next event",kindReading:"Reading",readingsCount:"{n} reading(s)",untitledObservation:"Observation {n}",deleteRecording:"Delete this recording from the case",deleteReadingQuestion:"Delete this reading? Nothing is written until the case is saved.",deleteObservationQuestion:"Delete this observation from the case? Nothing is written until the case is saved.",deleteRefused:"This observation is interpreted by {n} reading(s): delete them first.",titleField:"Title of the interpretation",authorField:"Author",addTitle:"Add an event",kindField:"Type",kindObservation:"Observation",kindInterview:"Interview",witnessField:"Witness",mediumField:"Medium",interviewerField:"Interviewer",plainTitleField:"Title",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"An existing recording",observerField:"Observer",fileField:"File",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",recordingId:"ID",idTaken:"Another recording of the case has this ID.",idInvalid:"An ID is made of letters, digits, hyphens and underscores, and starts with a letter or a digit.",idNeeded:"A reading names this recording by its ID: it cannot be left empty.",idDuplicated:"Two events of the case have the ID “{id}”: a reading that names it is ambiguous.",readingUnresolved:"A reading names “{id}”, which no event of the case has as its ID, nor any recording it lists.",caseTitle:"Title",caseTime:"When",eventsTab:"Events",fileTab:"File",importFile:"Load case file",inputFileFromFile:"from your disk",inputFileFromUrl:"from an address",inputFileModeHint:"Click to give it the other way: a file of yours, or an address",inputFileLoad:"Load",fileNotACase:"That file is not a case (it has no events).",formatVersionError:"This file states version {found} of its format; this UFO@home reads up to version {supported}. Open it with a newer UFO@home.",fileInvalid:"This text is not valid JSON yet, or not a case: the case keeps what it last understood.",fileLoading:"Loading the editor…",add:"Add",addHint:"Add an event",interpretationOf:"Interpretation of",interpretationOfNone:"—",exportButton:"Save",exportTitle:"Save the case",exportAlso:"Also save the observations",addToCase:"Add to a case",unsavedChanges:"Changes not saved",discardQuestion:"Some changes are not saved yet. Load anyway and lose them?",discardTitle:"Unsaved changes",discardOk:"Load anyway",leaveQuestion:"Some changes are not saved yet. Leave anyway and lose them?",leaveOk:"Leave anyway"},uN=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:Uv},Symbol.toStringTag,{value:"Module"})),lx="rr0-case-editor",pN=`
11300
+ `)}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const i=document.createElement("span");return i.className="tab-badge",i.hidden=!0,e.append(i),i}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const s of e){const r=Ce.QUESTION_FIELDS[s];if(r&&!r.fields.some(a=>this.shadow.getElementById(a)?.classList.contains("missing-required")))for(const a of r.fields){const o=this.shadow.getElementById(a);o&&!o.hidden&&o.value===""&&t.add(a)}}for(const[s,r]of Object.entries(Ce.QUESTION_FIELDS))for(const a of Ce.QUESTION_FIELDS[s].fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=t.has(a)&&!o.classList.contains("missing-required");o.classList.toggle("wanted",c),(c||o.title===this.messages.questionUnanswered)&&(o.title=c?this.messages.questionUnanswered:"")}const i=new Map;let n;for(const[s,r]of Object.entries(Ce.QUESTION_FIELDS))for(const a of r.fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=o.classList.contains("missing-required");!c&&!o.classList.contains("wanted")||(c&&(n=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const s of this.groupTabs){const r=this.panelOf(s),a=i.get(r)??0,o=r===n,c=Ce.badgeOn(s);c.hidden=a===0,c.textContent=String(a),c.classList.toggle("optional",!o);const h=a===0?void 0:o?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(a));h?s.dataset.unanswered=h:delete s.dataset.unanswered,Ce.titleGroupTab(s)}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field;const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const s=document.createElement("span");s.className="param-chip-swatch",s.style.background=e.color,t.append(s)}const n=document.createElement("span");return n.className="param-chip-value",n.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(n),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(a=>a.field==="description")?.full,this.syncDescription();return}const i=Number(t.dataset.panel);if(i<0)return;const n=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const s=t.dataset.field;if(s.startsWith("shape:")){this.selectedSourceIds=new Set([s.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(s.startsWith("body:")){const a=this.subgroupTabs.find(o=>o.getAttribute("aria-controls")==="shape-bodies");a&&this.openSubgroup(a),this.loadBodyEditor().then(o=>o.show(s.slice(5)));return}if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorList.focus();return}const r=this.shadow.getElementById(s);r===null||!n.contains(r)||(this.revealSubgroupOf(r),this.sectionFolds.reveal(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe(),this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorBaseFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateShapeToolbarVisibility(){const e=this.ufoElement.sighting.timeline.sourceIds.length===0,t=this.shadow.getElementById("shape-row");t&&ps.showPresence(t,this.shadow.getElementById("shape-item")??void 0,!e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.shapeRotationInput])i.disabled=e,i.title=t}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:oN(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.shadow.activeElement!==this.shapeRotationInput&&(this.shapeRotationInput.value=String(Ce.rotationDeg(e.angle))),this.refreshApparentSize())}static rotationDeg(e){const t=(e*180/Math.PI%360+540)%360-180;return Math.round((t===-180?180:t)*10)/10}updateShapeRotation(){const e=this.numberOrUndefined(this.shapeRotationInput.value);if(e===void 0)return;const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,n=t.getInterpolatedShapeAt(i,this.currentSourceId);n&&(this.commitShapes(i,[{sourceId:this.currentSourceId,shape:{...n,angle:e*Math.PI/180}}]),this.ufoElement.refresh())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,Tt.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,Tt.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(Tt.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(Tt.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,n=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!n)return;const s=this.currentProjection(),r=s.degToPx(e),a=n.bounds.height*(n.bounds.width===0?1:r/n.bounds.width),o={x:n.bounds.x+(n.bounds.width-r)/2,y:n.bounds.y+(n.bounds.height-a)/2,width:r,height:a},c=s.ofBounds(o),h=n.kind==="oval"?{...n,bounds:o,angular:c}:{...n,bounds:o,angular:c,points:this.scalePoints(n,o)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,n=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(s=>({x:s.x*i,y:s.y*n}))}refreshFilterOptions(){const e={[Ci.NONE.id]:this.messages.filterNone,[Ci.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[Ci.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=s=>e[s.id]??s.name,i=[...this.filterSelect.options].map(s=>s.textContent);if(i.length!==Ci.ALL.length||Ci.ALL.some((s,r)=>i[r]!==t(s))){const s=this.filterSelect.value||Ci.NONE.id;this.filterSelect.replaceChildren();for(const r of Ci.ALL){const a=document.createElement("option");a.value=r.id,a.textContent=t(r),this.filterSelect.appendChild(a)}this.filterSelect.value=s}const n=this.ufoElement?.sighting?.instrument;for(const s of this.filterSelect.options){const r=!n||Ci.usableWith(Ci.byId(s.value),n);s.disabled=!r,s.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,n={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},s=r=>{const a=this.naming.instrument(r),o=hi.unavailability(r,t);if(!o)return{id:r.id,label:a};const c=(o.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(o.from)).replace("{to}",String(o.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",a),hint:c}:{id:r.id,label:a,disabledReason:c}};this.instrumentSelect.choices=hi.CATEGORIES.map(r=>({label:n[r],children:Qh.filter(a=>a.category===r).map(s)})).filter(r=>r.children.length>0),this.instrumentSelect.value=this.instrumentSelect.value||i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Ce.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const s=Number(i[1]),r=Number(i[2]);return r>0?s/r:void 0}const n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=pt(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??hi.fieldOfViewDeg(t),r=n?hi.focalLengthMmFor(t,s):s;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=n?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=n?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=n!==void 0&&n.focalRangeMm===void 0,this.focalLengthInput.min=String(n?n.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(n?n.focalRangeMm?.maxMm??2e3:179),Fn.fit(this.focalLengthInput.parentElement??this.shadow),this.sectionFolds?.refresh(),this.focalFovOutput.textContent=n&&s!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(s,s<10?1:0)):"";const a=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=a===void 0?"":String(a)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const o=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=o===void 0?"":Ce.exposureText(o)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const h of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(h,bi.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const c=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.isoInput.placeholder=c?c.autoExposure?"auto":String(c.iso):"",this.setRowVisible(this.isoInput,c!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,c?.autoExposure===!0),this.meteringSelect.disabled=e.iso!==void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,n!==void 0&&t.fNumber!==void 0),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=Ci.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=hi.fieldOfViewDeg(e),n=hi.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>eN||t.observerTrack.addKeyframe(s.t,{...s.pose,fovDeg:n})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,n=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!n){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(n.max,Math.max(n.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return pt(e,this.ufoElement.currentTime)?.fovDeg??hi.fieldOfViewDeg(e.instrument)}currentProjection(){return Os.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=Tt.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const n=pt(this.ufoElement.sighting,this.ufoElement.currentTime),s=n?.focusDistanceM;if(s!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(s));return}const r=(n?hi.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,a=n?.fNumber??t.fNumber;if(a===void 0||r<=0){this.blurBoundOutput.textContent="";return}const o=this.ufoElement.canvasElement.height;if(o<=0)return;const c=2*Ig*e/o*i.heightMm,h=r*r/(a*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:i}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&i===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const n=this.numberOrUndefined(this.realWidthInput.value),s=n!==void 0&&(t!==void 0&&n<t||i!==void 0&&n>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),a=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+a+s;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+s}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}newBodyStart(){const e=this.currentSourceId,t=this.ufoElement.currentTime,i=e===void 0?void 0:this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e),n=(m,v)=>Number(m.toFixed(v)),s=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??Y6,a=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),o=a!==void 0&&a<r,c=n(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:n(Tt.sizeMAt(c,h),2),lengthM:n(Tt.sizeMAt(c,h),2),heightM:n(Tt.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},f={t,...p,distanceM:c,...o?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=ae(async()=>{const{BodyEditor:e}=await import("./BodyEditor-rPUSfhG-.js");return{BodyEditor:e}},__vite__mapDeps([14,15]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,seekTo:t=>{this.ufoElement.currentTime=t},readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}loadLanternEditor(){return this.lanternEditorLoading??=ae(async()=>{const{LanternEditor:e}=await import("./LanternEditor-Bq27r-0W.js");return{LanternEditor:e}},__vite__mapDeps([16,17]),import.meta.url).then(({LanternEditor:e})=>(this.lanternEditor=new e(this.shadow.getElementById("lantern-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()}},this.language),this.lanternEditor)),this.lanternEditorLoading}loadBeamEditor(){return this.beamEditorLoading??=ae(async()=>{const{BeamEditor:e}=await import("./BeamEditor-BHpoDP6v.js");return{BeamEditor:e}},__vite__mapDeps([18,5,19]),import.meta.url).then(({BeamEditor:e})=>(this.beamEditor=new e(this.shadow.getElementById("beam-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language),this.beamEditor)),this.beamEditorLoading}loadLaunchEditor(){return this.launchEditorLoading??=ae(async()=>{const{LaunchEditor:e}=await import("./LaunchEditor-D-1-8brV.js");return{LaunchEditor:e}},__vite__mapDeps([20,21]),import.meta.url).then(({LaunchEditor:e})=>(this.launchEditor=new e(this.shadow.getElementById("launch-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language),this.launchEditor)),this.launchEditorLoading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const s=i===void 0||i<=0?void 0:Tt.sizeMAt(e.distanceM,i);this.realWidthInput.value=s===void 0?"":this.plain(s,s<1?2:s<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const n={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=n.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,n=Os.of(i.instrument,Tt.CANVAS_HEIGHT_PX,Oi.fovOf(i,e)),s=this.ufoElement.seekableDuration;s>i.timeline.duration&&i.timeline.setSpan(s),i.timeline.addKeyframe(e,t.map(r=>{const a=Oi.aimOf(i,e,r.shape.bounds),o=n.ofBounds(r.shape.bounds),{aim:c,...h}=r.shape;return{...r,shape:a?{...h,aim:a,angular:o}:{...h,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.ufoElement.sighting.timeline.sourceIds.length>0&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const n=/^ufo-(\d+)$/.exec(e);return n?`${this.messages.shape} ${n[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;this.currentSourceId=this.newSourceIds(1)[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}newSourceIds(e){const t=this.ufoElement.sighting.timeline,i=[];t.sourceIds.length===0&&this.currentSourceId!==void 0&&i.push(this.currentSourceId);const n=new Set([...t.sourceIds,this.currentSourceId]);let s=n.size+1;for(;i.length<e;){for(;n.has(`ufo-${s}`);)s++;i.push(`ufo-${s}`),n.add(`ufo-${s}`)}return i}shapeAddKinds(){const e=this.messages,t={triangle:e.modelTriangle,saucer:e.modelSaucer,cigar:e.modelCigar,chevron:e.modelChevron,light:e.modelLight};return[{value:"oval",label:e.oval},{value:"polygon",label:e.polygon},...Ra.ALL.map(i=>({value:i.id,label:t[i.id]}))]}addModel(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,i=e.boundsAt(this.offsetDefaultBounds(t.sourceIds.length)),n=e.shapesIn(i,this.currentAppearance),s=this.newSourceIds(n.length),r=this.shapeAddKinds().find(h=>h.value===e.id).label,a=/^ufo-(\d+)$/.exec(s[0])?.[1]??"",o={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},c=n.map((h,d)=>{const u=e.partNames[d],p=u?`${r} ${a}, ${o[u]}`:`${r} ${a}`;return{sourceId:s[d],shape:{...h,title:this.said.write(void 0,p,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,c),s.length>1&&t.group(s),this.currentSourceId=s[s.length-1],this.selectedSourceIds=new Set(s),this.refreshSourceList(),this.ufoElement.refresh()}duplicateSelected(){if(this.hideContextMenu(),this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(r=>this.selectedSourceIds.has(r));if(t.length===0)return;const i=this.newSourceIds(t.length),n=24;for(const r of e.allKeyframes){const a=r.shapes.filter(o=>t.includes(o.sourceId)).map(o=>{const{bounds:c}=o.shape;return{sourceId:i[t.indexOf(o.sourceId)],shape:{...o.shape,bounds:{...c,x:c.x+n,y:c.y+n}}}});a.length>0&&this.commitShapes(r.t,a)}const s=e.groupMembers(t[0]);t.length>1&&s?.length===t.length&&t.every(r=>s.includes(r))&&e.group(i),this.currentSourceId=i[i.length-1],this.selectedSourceIds=new Set(i),this.refreshSourceList(),this.ufoElement.refresh()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i));t.length!==0&&this.removeShapes(t)}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??Jh,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}offsetDefaultBounds(e){const t=this.defaultBounds(),i=24;return{...t,x:t.x+e*i,y:t.y+e*i}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=e.sourceIds.length>0?[...new Set([...e.sourceIds,this.currentSourceId])]:[];this.sourceSelect.innerHTML="";for(const i of t){const n=document.createElement("option");n.value=i,n.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(n)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const n=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorList.kindLabel(e.kind)} ${n}`}addDecor(e=this.decorList.pickedKind??"building"){this.observerAdded=e==="observer";const t=this.ufoElement.sighting,n={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="trafficlight"?{lights:hh.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:dh}:{},windows:c2(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(n.id,e)}readSceneryChoice(){try{return localStorage.getItem(Ce.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(Ce.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(Ce.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(Ce.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await ae(()=>import("./surroundingsSources-BK1okKkz.js"),[],import.meta.url).catch(()=>{});if(!e)return;const{SURROUNDINGS_SOURCES:t,SurroundingsSources:i}=e;if(!this.isConnected)return;const n=document.createElement("option");n.value=Ce.NO_SCENERY,n.id="option-scenery-none",n.textContent=this.messages.surveySourceNone;const s=t.map(a=>{const o=document.createElement("option");return o.value=a.id,o.textContent=a.name,o.title=a.credit,o}),r=new Option(this.messages.sourceFile,Ce.FILE_SOURCE);r.id="option-scenery-file",this.scenerySource.replaceChildren(n,...s,r),this.surveyIds=t.map(a=>a.id),this.defaultSurveyId=i.DEFAULT_ID,this.syncSceneryPicker()}surveyIds;defaultSurveyId;sceneryAsked(){return this.sceneryChoice!==Ce.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?Ce.FILE_SOURCE:this.sceneryChoice===Ce.NO_SCENERY?Ce.NO_SCENERY:this.surveyIds.includes(this.sceneryChoice??"")?this.sceneryChoice:this.defaultSurveyId??this.surveyIds[0]),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-radius-row").hidden=e||this.sceneryChoice===Ce.NO_SCENERY;const t=this.shadow.getElementById("scenery-file-link");t.hidden=!e,e&&(t.textContent=this.sectionFilePanel.itemLabel("decor"),t.title=this.sectionFilePanel.where("decor"))}setDecorFromFile(e){const t=this.ufoElement.sighting;if(this.sectionFromFile("decor")===e)return;const i={...t.frozen??{}};e?i.decor=i.decor??{}:delete i.decor,t.frozen=Bi.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],n=t?.lat??i?.lat,s=t?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}setPlantedDecor(e){this.ufoElement.sighting.decor=e,e.some(t=>t.id===this.currentDecorId)||(this.currentDecorId=e[0]?.id),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleHistoryRecord()}refreshSceneryWarning(){const e=this.ufoElement?.sighting,t=e?of.anachronism(e.decor,e.event.time):void 0;this.sceneryWarning.hidden=t===void 0,this.sceneryWarning.textContent=t?this.messages.surveyWarning.replace("{survey}",t.survey).replace("{observation}",t.observation):""}citeSource(e){const t=this.ufoElement.sighting;(t.sources??[]).some(i=>i.url===e.url)||(t.sources=[...t.sources??[],e])}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const n=this.ufoElement.sighting.decor.find(s=>s.id===e);!n||n.model||n.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(s=>s.id===e?{...s,model:{id:i.id},sizeM:i.sizeM}:s),this.currentDecorId===e&&this.syncDecorVisibility(),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*ig,t=Math.round(e/iN*1e3);return{lights:hh.byId("airliner")?.create(),track:[{t:0,eastM:-ig,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:ig,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.kind===e).length;return`${this.decorList.kindLabel(e)} ${t+1}`}deleteDecor(){const t=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);t!==void 0&&this.removeDecor(t.id)}removeDecor(e){const t=this.ufoElement.sighting;t.decor=t.decor.filter(i=>i.id!==e),this.currentDecorId===e&&(this.currentDecorId=t.decor[0]?.id),this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="decor"),this.decorList.show(e),this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh();const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===e);t>=0&&this.showInFile(["decor",t])}updateDecor(e={}){if(this.currentDecorId===void 0)return;const t=this.ufoElement.sighting;t.decor=t.decor.map(i=>i.id!==this.currentDecorId?i:{...i,...e}),this.syncDecorVisibility(),this.ufoElement.refresh()}decorModelEntries;refreshDecorModelOptions(e){if(!e||this.decorModelEntries?.kind===e.kind)return;const t=e.kind;this.decorModelProvider.entries(t).catch(()=>[]).then(i=>{this.decorModelEntries={kind:t,entries:i},this.isConnected&&this.decorBaseForm.sync()})}drawnEntry;drawnEntryAsked;publishedParametersOf(e){const t=Od(e);if(!(!t?.id||t.url!==void 0)){if(this.drawnEntry?.id===t.id)return this.drawnEntry.parameters;if(this.drawnEntryAsked!==t.id){this.drawnEntryAsked=t.id;const i=t.id;this.decorModelProvider.entry(i).catch(()=>{}).then(n=>{this.drawnEntryAsked!==i||!n||(this.drawnEntry=n,this.isConnected&&this.syncDecorVisibility())})}}}modelPicker;enhanceDecorModelChoice(e,t){e.key==="model.id"&&(t.addEventListener("change",()=>t.dispatchEvent(new Event("input",{bubbles:!0}))),this.modelPicker.enhance(t,async i=>{const n=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),s=i!==""?i:n?lf[n.kind]?.id:void 0;return s!==void 0?this.decorModelProvider.entry(s).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):n===void 0?void 0:{decorKind:n.kind}},{current:()=>{const i=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId)?.model;return i?.url===void 0?void 0:{url:i.url,title:i.credit?.title??"",author:i.credit?.author??"",license:i.credit?.license??"",source:i.credit?.sourceUrl??""}},apply:i=>this.commitDecorBase(n=>{const s=this.stringOrUndefined(i.title),r=this.stringOrUndefined(i.license);n.model={url:i.url,credit:s!==void 0&&r!==void 0?{title:s,license:r,author:this.stringOrUndefined(i.author),sourceUrl:this.stringOrUndefined(i.source)}:void 0}},"model")}))}async adoptCatalogueSize(e,t){const[i,n]=await Promise.all([e.model?.id?this.decorModelProvider.entry(e.model.id).catch(()=>{}):void 0,t?this.decorModelProvider.entry(t).catch(()=>{}):void 0]),s=this.ufoElement.sighting.decor.find(o=>o.id===e.id);if(!s||s.model?.id!==t||!n?.sizeM)return;const r=s.sizeM!==void 0&&i?.sizeM!==void 0&&s.sizeM.widthM===i.sizeM.widthM&&s.sizeM.lengthM===i.sizeM.lengthM&&s.sizeM.heightM===i.sizeM.heightM;if(s.sizeM&&!r)return;const a={...s.sizeM,...Object.fromEntries(Object.entries(n.sizeM).filter(([,o])=>o!==void 0).map(([o,c])=>[o,this.roundedMeters(c)]))};this.updateDecor({sizeM:a})}roundedMeters(e){return Math.round(e*100)/100}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=_l([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const i=String.fromCharCode(65+t);if(!e.has(i))return i}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,i=t.milestones.find(n=>n.t===e);i&&(t.milestones=t.milestones.filter(n=>n.t!==i.t),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh())}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.goToMark(e)}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(i=>i.t===e?{...i,label:this.said.write(i.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(i.note,this.milestoneNoteInput.value,this.writingLanguage)}:i),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=_l(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;ps.showPresence(this.shadow.getElementById("milestone-row"),this.shadow.getElementById("milestone-item"),t);for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.deleteMilestoneButton])i.disabled=!t;this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.filter(e=>e.kind!=="observer").map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning(),this.refreshObserverList()}refreshObserverList(){const e=Ce.OBSERVER_PRINCIPAL,t=this.ufoElement.sighting.decor.filter(n=>n.kind==="observer");this.currentDecorId!==void 0&&t.some(n=>n.id===this.currentDecorId)&&this.observerAdded&&(this.observerShown=this.currentDecorId),this.observerAdded=!1,t.some(n=>n.id===this.observerShown)||(this.observerShown=e),this.observerList.setItems([{id:e,label:this.principalObserverLabel()},...t.map(n=>({id:n.id,label:this.decorLabel(n)}))],this.observerShown);const i=this.observerShown!==e;this.observerList.setRemoveEnabled(i),this.observerList.setActionEnabled("look-at-observer",i),this.placeDecorItem()}principalObserverLabel(){const e=[this.observerTitleInput.value,this.observerFirstNamesInput.value,this.observerLastNameInput.value].map(t=>t.trim()).filter(Boolean).join(" ");return e===""?this.messages.principalObserver:`${e} (${this.messages.principalObserver.toLowerCase()})`}observerAdded=!1;selectObserver(e){this.observerShown=e,e!==Ce.OBSERVER_PRINCIPAL&&this.selectDecor(e),this.refreshObserverList()}placeDecorItem(){const e=this.shadow.getElementById("decor-item"),t=this.shadow.getElementById("observer-decor-host"),i=this.shadow.getElementById("observer-principal");if(!e||!t||!i)return;const n=this.observerShown!==Ce.OBSERVER_PRINCIPAL;if(i.hidden=n,n&&this.isGroupIdOpen("group-observer")){e.parentElement!==t&&t.append(e),e.hidden=!1;return}e.parentElement===t&&this.shadow.getElementById("decor-list-header").after(e),e.hidden=this.decorList.value===""}syncDecorFields(){this.syncDecorVisibility()}async findGhosts(){const e=this.currentReference();if(e?.src){this.searchingGhosts=!0,this.syncFindGhosts(e);try{const{GhostSearchView:t}=await ae(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-UG9G-yF8.js");return{GhostSearchView:r}},__vite__mapDeps([22,7]),import.meta.url),i=this.messages,n={searching:i.referenceGhostsSearching,found:i.referenceGhostsFound,foundScaled:i.referenceGhostsFoundScaled,low:i.referenceGhostsLow,none:i.referenceGhostsNone,cropped:i.referenceGhostsCropped},s=await new t(this.ghostsStatus,n).search(e.src);this.ghostFinding=s&&s.pairs.length>0?{referenceId:e.id,src:e.src,search:s}:void 0,this.ghostsShown=!0,this.syncGhostsShown(),this.ufoElement.refresh()}finally{this.searchingGhosts=!1,this.syncFindGhosts(this.currentReference())}}}syncGhostsShown(){this.ghostsShownButton.hidden=!this.ghostFinding,this.ghostsShownButton.setAttribute("aria-pressed",String(this.ghostsShown)),this.ghostsShownButton.textContent=this.ghostsShown?this.messages.referenceGhostsHide:this.messages.referenceGhostsShow}syncFindGhosts(e){const t=!e?.src||this.sceneElement.referenceFailure(e.src)!==void 0;this.findGhostsButton.disabled=this.searchingGhosts||t,this.addReferenceLandmarkButton.disabled=t,t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark()}updateExposureSettings(){const e=this.ufoElement.sighting;e.iso=this.numberOrUndefined(this.isoInput.value);const t=this.meteringSelect.value;e.metering=t==="average"||t==="highlights"?t:void 0,this.meteringSelect.disabled=e.iso!==void 0,this.ufoElement.refresh()}updateLens(){const e=this.lensGlassSelect.value,t={...e?{glass:e}:{},drops:this.numberOrUndefined(this.lensDropsInput.value),condensation:this.numberOrUndefined(this.lensCondensationInput.value),dirt:this.numberOrUndefined(this.lensDirtInput.value),...this.lensShelteredInput.checked?{sheltered:!0}:{}};for(const i of["drops","condensation","dirt"])t[i]===void 0&&delete t[i];this.ufoElement.sighting.lens=Object.keys(t).length>0?t:void 0,this.ufoElement.refresh()}label(e,t){const i=this.shadow.getElementById(e);i&&(i.textContent=t)}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}decorBaseShownFor;showDecorBase(e){if(this.decorBaseHost.hidden=e===void 0,this.decorStateHost.hidden=e===void 0,!e){this.decorBaseForm.clear(),this.decorStateForm.clear(),this.decorBaseShown=!1,this.decorBaseShownFor=void 0;return}const t=this.decorBaseShownFor!==e.id;if(this.decorBaseShownFor=e.id,this.decorBaseShown){this.decorBaseForm.sync(t),this.decorStateForm.sync(t);return}this.decorBaseShown=!0;const i=()=>new Io(()=>{const n=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId);return n?Rr.viewOf(n,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(n,s)=>this.commitDecorBase(n,s.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(Ws.BASE,i(),()=>{}),this.decorStateForm.show(Ws.STATE,i(),()=>{})}decorPositionPlace(){const e=()=>{const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===this.currentDecorId);return t<0?[]:[`decor.${t}.eastM`,`decor.${t}.northM`]};return{frame:()=>this.positionFrame(this.currentDecorId),messages:()=>this.messages,basis:{read:()=>this.ufoElement.sighting.provenance.at(e()[0]??"")?.basis,write:(t,i)=>this.writePositionBasis(e(),i)}}}framePlace(){return{frame:()=>this.positionFrame(),messages:()=>this.messages}}positionFrame(e){const t=this.ufoElement.currentTime,i=[{label:this.messages.positionObserver,eastM:0,northM:0}];for(const n of this.ufoElement.sighting.decor){if(n.id===e)continue;const{eastM:s,northM:r}=qs(n,t);i.push({id:n.id,label:this.decorLabel(n),eastM:s,northM:r})}return{origin:this.plantingCentre(),references:i}}syncObserverPosition(){const e=this.ufoElement.sighting,t=this.ufoElement.currentTime;this.observerSaid=e.observerTrack.getLatestPoseAt(t)?.saidPosition;const i=this.positionFrame();this.observerPosition.frame={...i,references:i.references.filter(s=>s.id!==void 0)};const n=JSON.stringify(this.observerSaid??null);n!==this.observerSaidShown&&(this.observerSaidShown=n,this.observerPosition.said=this.observerSaid),this.observerPosition.basis=e.provenance.at(this.observerPositionPaths()[0]??"")?.basis}observerPositionPaths(){const e=this.ufoElement.currentTime,t=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(i=>i.t===e);return t<0?[]:[`observerTrack.keyframes.${t}.pose.lat`,`observerTrack.keyframes.${t}.pose.lng`]}writeObserverBasis(e){this.observerPositionPaths().length===0&&this.updateObserver(),this.writePositionBasis(this.observerPositionPaths(),e)}writePositionBasis(e,t){const i=this.ufoElement.sighting.provenance;for(const n of e)t===void 0||t==="stated"?i.clear(n):i.set(n,{basis:t});this.dispatchEvent(new CustomEvent("sightingchange"))}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=Al.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:me.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:Al.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:Ws.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:lf[e.kind]?.id}}placedByAuthor(e){if(!e.lamp?.supposed)return e;const t=this.sceneElement.decorDrawnOffset(e.id),{supposed:i,...n}=e.lamp,s={...e,eastM:e.eastM+(t?.eastM??0),northM:e.northM+(t?.northM??0),...Object.keys(n).length>0?{lamp:n}:{}};Object.keys(n).length===0&&delete s.lamp;const r=this.ufoElement.sighting;return r.decor=r.decor.map(a=>a.id===e.id?s:a),s}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId);if(!i)return;const n=t==="eastM"||t==="northM"?this.placedByAuthor(i):i;if((t==="lit"||t==="headlights")&&this.ufoElement.playbackState==="playing")return;const s=this.ufoElement.currentTime,r=Rr.viewOf(n,s,this.sceneElement.sunAltitudeDeg);e(r);const a=this.ufoElement.sighting;a.decor=a.decor.map(c=>c.id===n.id?Rr.apply(c,r,t,s):c),t==="model.id"&&this.adoptCatalogueSize(n,r.model?.id);const o=a.decor.find(c=>c.id===n.id);t==="title"&&this.decorList.rename(o.id,this.decorLabel(o)),this.syncDecorVisibility(),this.ufoElement.refresh(),t==="lightRig"&&this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorBaseFromTimeline(){this.ufoElement.playbackState==="playing"||!this.decorBaseShown||(this.decorBaseForm.sync(),this.decorStateForm.sync())}showDecorParameters(e){const t=e?si.of(e,this.publishedParametersOf(e)):void 0;if(!e||!t){this.decorParametersShownFor=void 0,this.decorParameterForm.clear(),this.decorParametersHost.hidden=!0;return}this.decorParametersHost.hidden=!1;const i=`${e.id}|${t.kind}|${t.parameters.map(r=>r.key).join(",")}`;if(i===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=i;const n=e.id,s=new Io(()=>this.ufoElement.sighting.decor.find(r=>r.id===n),r=>{const a=this.ufoElement.sighting;a.decor=a.decor.map(o=>{if(o.id!==n)return o;const c=structuredClone(o);return r(c),c})});this.decorParameterForm.show(t,s,()=>{this.syncDecorVisibility(),this.ufoElement.refresh()})}syncDecorParameterVisibility(){this.showDecorParameters(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);this.refreshDecorModelOptions(e),this.showDecorBase(e),this.syncDecorParameterVisibility()}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++,this.meteorMagnitudeLimit());e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;meteorMagnitudeLimit(){const e=this.ufoElement.sighting,t=this.observerAtStart(),i=e.event.time?.year!==void 0?zn(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const n=Ti("Sun",i,t).altitudeDeg;return ea(n,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Rs;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Hf;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new vs(["en"]);tagNames=new _g({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,n=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?zn(i,t.lng,e.event.utcOffsetHours):void 0,s=JSON.stringify([n?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,en(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status,this.sceneElement.groundKey]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!n||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.disabled=!0,this.showCometButton.disabled=!0,this.showNovaButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown),this.labelSkyButtons();return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},a=[this.starsClause(n,r),this.showerClause(n,r),this.cometClause(n,r),this.novaClause(n,r),this.eclipseClause(n,r),this.moonClause(n,r),this.satelliteClause(n,r),this.reentryClause(n,r),this.fireballClause(n,r),this.opticsClause(n,r),this.rainbowClause(n,r),this.glowClause(n,r)].filter(o=>o!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",a.join(" · ")),this.labelSkyButtons()}labelSkyButtons(){const e=this.messages,t=[[this.showMeteorButton,e.showMeteor,e.noMeteor],[this.showCometButton,e.showComet,e.noComet],[this.showNovaButton,e.showNova,e.noNova],[this.showSatelliteButton,e.showSatellite,e.noSatellite],[this.showFireballButton,e.showFireball,e.noFireball]];for(const[i,n,s]of t){const r=i.disabled?s:n;i.title=r,i.setAttribute("aria-label",r)}}instrumentGain(){const e=this.ufoElement.sighting;return Dn.gainFor(e.instrument,{fNumber:pt(e,0)?.fNumber,fieldOfViewDeg:Oi.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Ti("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=ea(i,n,s),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<j6)return this.messages.skyStarsNone;const o=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",a(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(r)).replace("{device}",this.naming.instrument(o)).replace("{gain}",a(Math.abs(n))).replace("{eye}",a(ea(i,0,s)));return r<=Md?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",a(Md))}showerClause(e,t){const i=Ui.observedRatePerHour(Ui.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=sh.activeAt(e);if(n.length===0)return this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyNothingActive.replace("{sporadic}",i);const s=n.map(r=>{const a=sh.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:sh.observedRatePerHour(r.zhr,a.altitudeDeg,r.shower.populationIndex)}}).sort((r,a)=>a.rate-r.rate)[0];return s.rate<=0?(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(s.entry.shower))):(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerActive.replace("{name}",this.naming.shower(s.entry.shower)).replace("{altitude}",String(Math.round(s.position.altitudeDeg))).replace("{bearing}",this.naming.towards(s.position.azimuthDeg)).replace("{rate}",s.rate.toLocaleString(void 0,{maximumFractionDigits:s.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=Dp.brightestAt(e,t);if(!i||i.magnitude>wh){this.showCometButton.disabled=!0;return}return this.showCometButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.cometText(i)}novaClause(e,t){const i=Gf.brightestAt(e,t);if(!i||i.magnitude>wh){this.showNovaButton.disabled=!0;return}return this.showNovaButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.novaText(i)}eclipseClause(e,t){const i=Qi.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const n=Ti("Sun",i.peak,t),s=r=>r.replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),a=Math.round(i.totality.seconds%60);return s(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${a} s`)}return s(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=Ti("Moon",e,t);if(i.altitudeDeg<=0||Xo(e).illuminatedFraction<.97)return;const n=[],s=ts.distanceKm(e,t),r=ts.relativeToMean(ts.radiusAtKm(s)),a=s<=ts.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:s>=ts.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return a&&n.push(a.replace("{distance}",(Math.round(s/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(ts.radiusAtKm(s)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Kf.isIn(e)&&n.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),n.length>0?n.join(" · "):void 0}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=xr.visibilityAt(e,t),n=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(n!==void 0)return n;if(this.showSatelliteButton.disabled=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=ea(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),a=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",a);const o=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",o).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",a):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),n=i+this.satelliteSpanMs(),s=[i,n,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==s){const c={key:s,status:"loading"};this.reentries=c,Ce.reentryArchive.candidates(i,n,t).then(h=>{c.status=h?"ready":"unavailable",c.candidates=h,this.reentries===c&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=xr.visibilityAt(e,t).sunAltitudeDeg<-6,a=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(a.length===0)return;const o=a.slice(0,3).map(c=>this.reentryText(c));return a.length>3&&o.push(this.messages.skyReentriesMore.replace("{count}",String(a.length-3))),this.messages.skyReentries.replace("{list}",o.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,n=new Date(e.timeMs);if(t.precision==="day"){const a=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",a)}const s=this.observerClock(n).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",s).replace("{hours}",(t.uncertaintyHours??0).toLocaleString(this.showerLanguage()));const r=e.offsetMinutes?this.messages.skyReentryOffset.replace("{minutes}",String(e.offsetMinutes)):"";return t.seenFrom&&e.seenKm!==void 0?this.messages.skyReentrySeen.replace("{name}",i).replace("{time}",s).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",s)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(c=>c.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(c=>c.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses();if(this.showSatelliteButton.disabled=this.aimableSatellitePasses(i).length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const s=i[0].peak,a=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",s.object.name).replace("{magnitude}",s.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(s.altitudeDeg))).replace("{bearing}",this.naming.towards(s.azimuthDeg)).replace("{time}",this.observerClock(s.date)),o=this.starlinkTrain(i);return o?`${a}, ${o}`:a}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const n=i.peak.magnitude;if(n===void 0)return!1;const s=Ti("Sun",i.peak.date,t);return n<=ea(s.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,n)=>i.peak.magnitude-n.peak.magnitude)}aimableSatellitePasses(e){return e.filter(t=>this.passTimelineMs(t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(t.peak.altitudeDeg,t.peak.azimuthDeg))}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:a,launch:o}=r.peak.object;a!=="starlink"||!o||(r.peak.date.getTime()-Date.parse(`${o}T00:00:00Z`))/864e5>60||t.set(o,(t.get(o)??0)+1)}const[i,n]=[...t.entries()].sort((r,a)=>a[1]-r[1])[0]??[];if(!i||!n||n<3)return;const s=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(n)).replace("{date}",s)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=pt(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=zn(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.aimableSatellitePasses(this.visibleSatellitePasses());if(e.length===0)return;const t=e.map(n=>`${n.object.norad}@${n.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>or.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=or.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,n)=>i.magnitude-n.magnitude)}aimableFireballs(e,t){return e.filter(i=>this.fireballTimelineMs(i,t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(i.peak.altitudeDeg,i.peak.azimuthDeg))}fireballTimelineMs(e,t){const{record:i}=e,n=i.from[2]-i.to[2],s=Math.abs(n)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/n));return i.t-t.getTime()+s*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.disabled=this.aimableFireballs(i,e).length===0,i.length===0)return;const n=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",n.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(n.record.t))).replace("{altitude}",String(Math.round(n.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(n.peak.azimuthDeg)).replace("{distance}",String(Math.round(n.peak.distanceKm/10)*10)).replace("{stations}",String(n.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const n=zn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.aimableFireballs(this.strikingFireballs(n,this.observerAtStart()),n);if(s.length===0)return;const r=s[this.fireballRank++%s.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,n),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=en(this.ufoElement.sighting,0),n=Ti("Sun",e,t),s=Ti("Moon",e,t),r=ut.deckLitUntilDeg(ut.DECK_HEIGHT_M),a=n.altitudeDeg>-r,o=a?n:s;if(o.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(ut.strength(c,i.lowerCloudCover??i.cloudCover,o.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=a?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(ut.formsAt(o.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??kp;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const i=en(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Ti("Sun",e,t),s=Ti("Moon",e,t),r=n.altitudeDeg>0,a=r?n:s;if(a.altitudeDeg<=0)return this.messages.skyBowNoSource;const o=i.lowerCloudCover??i.cloudCover;if(jn.strength(i.precipitationIntensity,o,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=jn.formsAt(a.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(jn.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(Xo(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Ti("Sun",e,t);if(i.altitudeDeg>lN)return;const n=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),s=[];if(n.milkyWay&&s.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(n.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(n.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(n.milkyWay.azimuthDeg))),n.zodiacal){const p=n.zodiacal.sunSeparationDeg<=Gt.CONE_SEPARATION_DEG;s.push((p?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(n.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(n.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(n.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(n.zodiacal.sunSeparationDeg))))}if(s.length>0)return this.listed(s);const r=this.decimal(n.darkestSkyMagPerArcsec2,1),a=Ti("Moon",e,t),o=n.darkestSkyMagPerArcsec2<cN,c=this.ufoElement.sighting.lightPollution,h=de.scatteringAt(90-a.altitudeDeg)*de.moonOutput(de.phaseAngleOf(Xo(e).illuminatedFraction),a.altitudeDeg)*de.scatteredFraction(90),d=de.artificialZenithNanolamberts(c)>h;if(o&&a.altitudeDeg>0&&!d){const p=Math.round(Xo(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=de.artificialZenithNanolamberts(c)>de.twilightExcessNanolamberts(i.altitudeDeg);return o&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):o?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Ti("Sun",e,t),n=Ti("Moon",e,t);return de.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:de.phaseAngleOf(Xo(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new Gt;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=i=>String(Math.round(i??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=this.naming.comet(e.apparition),i=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",i):(e.elongationDeg<Dp.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=zn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Dp.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!s||this.sceneElement.groundHides(s.position.altitudeDeg,s.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=zn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Gf.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!s||this.sceneElement.groundHides(s.position.altitudeDeg,s.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(o=>o.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:n}=qs(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,a=Math.atan2(n-tN,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(a*10)/10),this.updateObserver()}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return i1(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Sc.width/2,y:e.height/2-Sc.height/2,width:Sc.width,height:Sc.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new Vb(this.ufoElement.sighting.timeline,new l6(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t),this.recordButton.querySelector(".record-label")||this.recordButton.replaceChildren(Object.assign(document.createElement("span"),{className:"record-icon"}),Object.assign(document.createElement("span"),{className:"record-label"})),Te.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=Zs.preferencesFor(this);this.preferences=t;const i=Id(t,Td),n=this.narrativeProvider.localize?.(i),[s,r,a]=i==="en"?[So,{},void 0]:await Promise.all([cx(i),vE(i),hx(i)]);if(await n,e!==this.localeToken)return;const o=i!==this.language;this.language=i,this.naming=new Hf(a),this.said=new vs(t),this.tagNames=new _g(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new qc(s,this.naming,this.said,this.tagNames,{messages:s,locale:this.language}),this.refreshParamSummary()),o?this.showSaidTexts():this.showTags()}preferences=[];language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===Jh&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.sourceSelect.setAttribute("aria-label",e.shape),this.shadow.getElementById("shape-empty").textContent=e.emptyShapes,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.shadow.getElementById("label-shape-rotation").textContent=e.shapeRotation,this.shapeRotationInput.title=e.shapeRotationTitle,this.labelSizeLock.textContent=e.sizeLock;for(const[i,n]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(i).textContent=n;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.shadow.getElementById("label-account-view").textContent=e.accountView,this.accountViewSelect.options[0].textContent=e.accountView2d,this.accountViewSelect.options[1].textContent=e.accountView3d,this.accountViewSelect.title=e.accountViewHint,this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextDuplicateButton.textContent=e.duplicate,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.frozenPanel.localize(e),this.sectionFilePanel.localize(e),this.shadow.getElementById("observer-identity-hint").textContent=e.identityHint,this.shadow.getElementById("identity-ask-initials").textContent=e.identityInitials,this.shadow.getElementById("identity-ask-keep").textContent=e.identityKeep,this.shadow.getElementById("identity-ask-back").textContent=e.identityBack,this.labelImportFile.textContent=e.importFile,this.shadow.getElementById("label-whole-keyframes").textContent=e.wholeKeyframes,this.wholeKeyframesInput.closest("label").title=e.wholeKeyframesHint,this.importInput.placeholder=e.importUrlPlaceholder;for(const i of this.shadow.querySelectorAll(qd))i.messages=e;this.labelObserverAge.textContent=e.observerAge,this.labelObserverBirth.textContent=e.observerBirth,this.perceptionSettings.labels=e.observerPerception,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,this.labelAccountUrl.textContent=e.accountUrl,this.labelAccountFollowedUp.textContent=e.accountFollowedUp;for(const[i,n]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const s=this.shadow.getElementById(i);s&&(s.textContent=n)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelPosition.textContent=e.positionLabel,this.observerPosition.messages=e,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.label("label-iso",e.iso),this.isoInput.title=e.isoTitle,this.label("label-metering",e.metering),this.meteringSelect.title=e.meteringTitle,this.label("metering-device",e.meteringDevice),this.label("metering-average",e.meteringAverage),this.label("metering-highlights",e.meteringHighlights),this.label("label-lens-glass",e.lensGlass),this.label("label-reference-ghosts",e.referenceGhosts),this.findGhostsButton.textContent=e.referenceFindGhosts,this.syncGhostsShown(),this.label("lens-glass-none",e.lensGlassNone),this.label("lens-glass-filter",e.lensGlassFilter),this.label("lens-glass-window",e.lensGlassWindow),this.label("lens-glass-windscreen",e.lensGlassWindscreen),this.label("label-lens-drops",e.lensDrops),this.lensDropsInput.title=e.lensDropsTitle,this.label("label-lens-condensation",e.lensCondensation),this.lensCondensationInput.title=e.lensCondensationTitle,this.label("label-lens-dirt",e.lensDirt),this.lensDirtInput.title=e.lensDirtTitle,this.label("label-lens-sheltered",e.lensSheltered),this.lensShelteredInput.title=e.lensShelteredTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.shapeAddMenu.panel.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"trafficlight",label:e.decorTrafficLight},{value:"crossing",label:e.decorCrossing},{value:"roadsign",label:e.decorRoadSign},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,empty:e.emptyDecor,actions:{"look-at-decor":e.lookAtDecor}}),this.labelSkyButtons(),this.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.observerList.setLabels({list:e.observerGroup,remove:e.deleteObserver,add:e.addObserver,actions:{"look-at-observer":e.lookAtDecor}}),this.refreshObserverList(),this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const t=this.shadow.getElementById("option-scenery-none");t&&(t.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote,this.shadow.getElementById("milestone-empty").textContent=e.emptyMilestones;for(const[i,n]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])i.title=n,i.setAttribute("aria-label",n);this.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup,this.labelLaunchesSubgroup.textContent=e.launchesSubgroup,this.labelBeamsSubgroup.textContent=e.beamsSubgroup,this.labelLanternsSubgroup.textContent=e.lanternsSubgroup;for(const i of["location","decor","weather"]){const n=this.shadow.getElementById(`${i}-settings-button`);n?.setAttribute("title",e.dataSources),n?.setAttribute("aria-label",e.dataSources);const s=this.shadow.getElementById(`label-${i}-settings`);s&&(s.textContent=e.dataSources)}this.bodyEditor?.setLanguage(this.language),this.launchEditor?.setLanguage(this.language),this.beamEditor?.setLanguage(this.language),this.lanternEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerTab,this.labelWeatherGroup.textContent=e.sky,this.fitGroupTabs(),this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new qc(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),this.refreshParamSummary(),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelRareIce.textContent=e.rareIceCrystals,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.referenceSelect.setAttribute("aria-label",e.reference),this.shadow.getElementById("reference-empty").textContent=e.emptyReferences,this.shadow.getElementById("reference-landmark-empty").textContent=e.emptyReferenceLandmarks,this.shadow.getElementById("trace-empty").textContent=e.emptyTraces,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSourceInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.setReferenceAddKinds(e.addReferenceUrl,e.addReferenceFile,e.referenceStreetSearch),this.addReferenceButton.title=e.addReference,this.addReferenceButton.setAttribute("aria-label",e.addReference),this.referenceAddMenu.panel.setAttribute("aria-label",e.addReference),this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.title=e.addReferenceLandmark,this.addReferenceLandmarkButton.setAttribute("aria-label",e.addReferenceLandmark),this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,this.labelTraceImport.textContent=e.traceImport,this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=e.traceImport,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[i,n]of this.soundKindOptions)n.textContent=this.soundKindLabel(i,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e)}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[n,s]of Object.entries(t))this.shadow.getElementById(`label-section-${n}`).textContent=s;this.sectionFolds.setMessages(e),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const n of["location-settings","decor-settings","weather-settings"])gs.popover(this.shadow.getElementById(n),e.close);gs.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),gs.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),gs.button(this.contextMenu,e.close,()=>this.hideContextMenu()),gs.button(this.decorContextMenu,e.close,()=>this.hideDecorContextMenu()),this.shadow.getElementById("label-editor-kicker").textContent=e.editorKicker,this.shadow.getElementById("label-save").textContent=e.save,this.shareDialog.useLanguage(this.language).then(n=>{n&&(this.shareMessages=n,this.shadow.getElementById("label-share").textContent=n.share,this.refreshEditorHead())});const i={observation:e.panelIntroObservation,observer:e.panelIntroObserver,location:e.panelIntroLocation,temporal:e.panelIntroTemporal,decor:e.panelIntroDecor,weather:e.panelIntroWeather,shape:e.panelIntroShape,sound:e.panelIntroSound,reference:e.panelIntroReference,file:e.panelIntroFile};for(const[n,s]of Object.entries(i)){const r=this.shadow.querySelector(`[aria-controls="group-${n}"]`);r.dataset.intro=s,Ce.titleGroupTab(r)}this.refreshEditorHead()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;if(!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)){const d=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;this.beginCameraDrag(t,u?.kind==="decor"?u.id:void 0,u?.kind==="body"?u.id:void 0)}return}const n=this.decorMoveAxis(e);if(i==="decor"&&n&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t,n))return;const s=this.ufoElement.sighting.timeline,r=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const d=new Sm(this.selectedMembers()),u=Vt.hitTestHandle({bounds:d.bounds(),angle:0},t);if(u==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:d,startPointer:t},this.startDragListening();return}if(u){if(a)return;this.dragState={kind:"group-resize",group:d,handle:u},this.startDragListening();return}}else{const d=s.getInterpolatedShapeAt(r,this.currentSourceId),u=d?.kind==="polygon"?Vt.hitTestVertex(d,t):void 0;if(d?.kind==="polygon"&&u!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:d,vertexIndex:u},this.startDragListening();return}const p=d&&Vt.hitTestHandle(d,t);if(d&&p){if(a)return;this.beginDrag(p==="rotate"?"rotate":"resize",this.currentSourceId,d,t,p);return}}const c=this.ufoElement.shapeAt(t.x,t.y,up);if(!c){const d=n==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;if(u?.kind==="body"&&u.id!==void 0){a?this.showBody(u.id):this.beginCameraDrag(t,void 0,u.id);return}const p=u?.kind==="decor"?u.id:void 0;if(p!==void 0){a?(this.selectDecor(p),this.revealDecorPanel()):this.beginCameraDrag(t,p);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),this.flash(this.shapeTitleInput.closest("label")),e.shiftKey?this.toggleUnitSelection(c.sourceId):this.selectedSourceIds.has(c.sourceId)||this.selectUnit(c.sourceId),a||!o)return;const h=[...this.selectedSourceIds].map(d=>({sourceId:d,original:d===c.sourceId?c.shape:s.getInterpolatedShapeAt(r,d)??c.shape}));this.dragState={kind:"move",sources:h,startPointer:t},this.startDragListening()}showBody(e){if(this.fileSyncActive()){this.showInFile(this.bodyPath(e));return}this.revealShapePanel();const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-bodies");t&&this.openSubgroup(t),this.loadBodyEditor().then(i=>i.show(e))}revealDecorPanel(){if(this.fileSyncActive()){this.fileFocus="decor",this.syncCanvasMode();return}const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-decor");e&&this.toggleGroup(e,!0)}revealShapePanel(){if(this.fileSyncActive()){this.fileFocus="shape",this.syncCanvasMode();return}const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="shape"),this.refreshSourceList(),this.onSelectionOrTimeChanged(),this.showInFile(this.shapePath(e)))}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(s=>this.selectedSourceIds.has(s))){if(i.length>=this.selectedSourceIds.size)return;for(const s of i)this.selectedSourceIds.delete(s);if(!this.selectedSourceIds.has(this.currentSourceId)){const s=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,a)=>s.indexOf(r)-s.indexOf(a)).pop()}}else{for(const s of i)this.selectedSourceIds.add(s);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(n,this.currentSourceId):void 0,a=s?.kind==="polygon"&&Vt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,up);if(a){this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),this.currentSourceId=a.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const o=this.pickDecorAt(e),c=o?this.ufoElement.sighting.decor.find(h=>h.id===o):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(e.clientX-i.left)/i.width*2-1,s=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(n,s)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const i=this.ufoElement.sighting.timeline.sourceIds,n=i.filter(p=>this.selectedSourceIds.has(p)),s=i.length<=n.length,r=n.length>0&&i.slice(i.length-n.length).every(p=>this.selectedSourceIds.has(p)),a=n.length>0&&i.slice(0,n.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||a,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:a?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const o=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!o,this.contextUngroupButton.title=o?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?Vt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=f2;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";const t=[...this.ufoElement.sighting.timeline.sourceIds],i=this.ufoElement.sighting.interpretation?.bodies??[];if(t.length===0&&i.length===0){const n=document.createElement("span");n.className="submenu-empty",n.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(n)}for(const n of t){const s=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=e.occludesSourceIds?.includes(n)??!1,r.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,n,r.checked)),s.appendChild(r),s.appendChild(document.createTextNode(this.shapeLabel(n))),this.contextMasksSubmenu.appendChild(s)}for(const n of i){const s=this.sceneElement.bodyMaskedBy(n.id,e.id);if(s===void 0)continue;const r=document.createElement("span");r.className="submenu-empty submenu-fact";const a=this.said.read(n.title)??n.id,o=this.messages;r.textContent=`${a} — ${s>=.995?o.masksBodyFully:s>.005?o.masksBodyPartly.replace("{share}",String(Math.round(s*100))):o.masksBodyNot}`,this.contextMasksSubmenu.appendChild(r)}}updateDecorOccludesShape(e,t,i){const n=this.ufoElement.sighting;n.decor=n.decor.map(s=>{if(s.id!==e)return s;const r=i?[...new Set([...s.occludesSourceIds??[],t])]:(s.occludesSourceIds??[]).filter(a=>a!==t);return{...s,occludesSourceIds:r.length>0?r:void 0}}),this.ufoElement.refresh()}viewObserverAccount(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=Vt.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=Vt.hitTestVertex(i,e);if(n===void 0)return;const s=Vt.deleteVertex(i,n);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,i,n,s){this.dragState={kind:e,sourceId:t,original:i,handle:s,startPointer:n},this.startDragListening()}ndcOf(e){const t=this.ufoElement.canvasElement.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height*2-1)}}skyDirectionOf(e){const t=this.ndcOf(e);if(!t)return;const i=this.sceneElement.directionAt(t.x,t.y);return{azimuthDeg:(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,i.y)))*180/Math.PI}}beginBodyDrag(e){const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!n||!i)return!1;i.show(n);const s=i.readingNow(),r=this.skyDirectionOf(e);return!s||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:s.azimuthDeg,bodyAltitudeDeg:s.altitudeDeg},this.setCanvasCursor("move"),this.startDragListening(),!0)}onBodyDragPointerMove(e){const t=this.dragState;if(t?.kind!=="body")return;const i=this.skyDirectionOf(e);if(!i)return;const n=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+n,t.bodyAltitudeDeg+i.altitudeDeg-t.pointerAltitudeDeg)}bodyCanvasBounds(){const e=this.bodyEditor?.currentBodyId;return this.canvasBoundsOf(e===void 0?void 0:this.sceneElement.bodyScreenBox(e))}canvasBoundsOf(e){if(!e)return;const t=this.ufoElement.canvasElement,i=Math.max(ix,(e.maxX-e.minX)/2*t.width),n=Math.max(ix,(e.maxY-e.minY)/2*t.height),s=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return{x:s-i/2,y:r-n/2,width:i,height:n}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),n=e.reading();if(!i||!n)return!1;const s=Vt.hitTestHandle({bounds:i,angle:0},t);if(!s)return!1;if(s==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...n.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:s,centre:r,startPointer:t,startSizeM:{...n.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(s,0)),this.startDragListening(),!0}beginBodyHandleDrag(e){return this.beginFrameDrag(this.bodyFrame,e)}onFrameDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="frame-rotate"){const u=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,p=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,f=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:f.headingDeg,pitchDeg:f.pitchDeg+p,rollDeg:f.rollDeg+u}:{headingDeg:f.headingDeg+u,pitchDeg:f.pitchDeg,rollDeg:f.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:n,startPointer:s,startSizeM:r,handle:a}=t,o=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=a==="e"||a==="w",h=a==="n"||a==="s",d=c?o(i.x-n.x,s.x-n.x):h?o(i.y-n.y,s.y-n.y):o(Math.hypot(i.x-n.x,i.y-n.y),Math.hypot(s.x-n.x,s.y-n.y));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:tg};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.decorReading(),resize:e=>this.commitDecorBase(t=>{Object.assign(t,{sizeM:{widthM:this.roundedMeters(e.widthM),lengthM:this.roundedMeters(e.lengthM),heightM:this.roundedMeters(e.heightM)}})},"sizeM.widthM"),turnTo:e=>this.commitDecorBase(t=>{t.headingDeg=this.rounded((e.headingDeg%360+360)%360)},"headingDeg"),rotateDegPerPx:J6};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=me.naturalSize(e.kind,e.floors);return{sizeM:{widthM:e.sizeM?.widthM??t.widthM??1,lengthM:e.sizeM?.lengthM??t.lengthM??1,heightM:e.sizeM?.heightM??t.heightM??1},attitude:{headingDeg:Rr.viewOf(e,this.ufoElement.currentTime).headingDeg,pitchDeg:0,rollDeg:0}}}onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!n||!i||(e.preventDefault(),i.show(n),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorMoveAxis(e){if(!(e.metaKey||[e.shiftKey,e.altKey,e.ctrlKey].filter(Boolean).length>1))return e.shiftKey?"east":e.altKey?"north":e.ctrlKey?"up":"ground"}grabsDecor(e,t,i){const n=this.pickDecorAt(e);if(n===i.id)return!0;const s=this.decorCanvasBounds();return s!==void 0&&t.x>=s.x&&t.x<=s.x+s.width&&t.y>=s.y&&t.y<=s.y+s.height?n===void 0||this.ufoElement.sighting.decor.find(a=>a.id===n)?.kind==="terrace":!1}beginDecorDrag(e,t,i){const n=this.editableDecor();if(!n)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.ufoElement.shapeAt(t.x,t.y,up)||!this.grabsDecor(e,t,n))return!1;const s=this.ndcOf(e),r=Rr.viewOf(this.placedByAuthor(n),this.ufoElement.currentTime),a=s?this.sceneElement.decorGrabHeightAt?.(n.id,s.x,s.y)??0:0,o=s&&this.sceneElement.decorGroundPointAt(n.id,s.x,s.y,a);return!s||!o?!1:(this.dragState={kind:"decor-move",id:n.id,startGround:o,grabHeightM:a,axis:i,startAltitudeM:r.altitudeM,startNdcY:s.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(n.id)??0,startEastM:r.eastM,startNorthM:r.northM},this.setCanvasCursor("move"),this.startDragListening(),!0)}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e);if(!i)return;const n=this.sceneElement.decorGroundPointAt(t.id,i.x,i.y,t.grabHeightM);!n&&t.axis!=="up"||this.commitDecorBase(s=>{n&&(t.axis==="ground"||t.axis==="east")&&(s.eastM=this.roundedMeters(t.startEastM+n.x-t.startGround.x)),n&&(t.axis==="ground"||t.axis==="north")&&(s.northM=this.roundedMeters(t.startNorthM-(n.z-t.startGround.z))),t.axis==="up"&&(s.altitudeM=this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))},"eastM")}beginCameraDrag(e,t,i){const n=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,pressedBodyId:i,moved:!1,startPointer:e,startHeadingDeg:n?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:n?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:n},n||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&Ro(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Ro(i.kind)),t=e?`${e.id}:${e.observerSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.dragState?.kind==="body"){this.onBodyDragPointerMove(e);return}if(this.dragState?.kind==="frame-resize"||this.dragState?.kind==="frame-rotate"){this.onFrameDragPointerMove(e);return}if(this.dragState?.kind==="decor-move"){this.onDecorMovePointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:n,startPointer:s}=this.dragState,r=t.x-s.x,a=t.y-s.y,o=n.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+a}}}));this.commitShapes(i,o)}else if(this.dragState.kind==="group-resize"){const{group:n,handle:s}=this.dragState;this.commitShapes(i,n.resize(s,t))}else if(this.dragState.kind==="group-rotate"){const{group:n,startPointer:s}=this.dragState;this.commitShapes(i,n.rotate(t,s))}else if(this.dragState.kind==="vertex"){const{sourceId:n,original:s,vertexIndex:r}=this.dragState,a=Vt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:a}])}else{const{kind:n,sourceId:s,original:r,handle:a}=this.dragState,o=n==="resize"?Vt.resizeShape(r,a,t):Vt.rotateShape(r,t);this.commitShapes(i,[{sourceId:s,shape:o}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:n,startPitchDeg:s,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<Q6)return;this.cameraDragState.moved=!0}const a=n+(t.x-i.x)*tg,o=Math.max(-90,Math.min(90,s-(t.y-i.y)*tg));if(r){this.indoorLookYawDeg=a,this.indoorLookPitchDeg=o,this.sceneElement.setIndoorLook(a,o),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}walkOrTurn(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing"||this.isObserverInsideDecor())return;const t=e.shiftKey?rN:1,i=this.numberOrUndefined(this.headingInput.value)??0;if(e.key==="ArrowLeft"||e.key==="ArrowRight"){this.headingInput.value=String(this.rounded(i+(e.key==="ArrowRight"?1:-1)*sN*t)),this.updateObserver();return}const n=this.numberOrUndefined(this.latInput.value),s=this.numberOrUndefined(this.lngInput.value);if(n===void 0||s===void 0)return;const r=(e.key==="ArrowUp"?1:-1)*nN*t,a=i*Math.PI/180,o=ws(Math.sin(a)*r,-Math.cos(a)*r,n,s);this.latInput.value=o.lat.toFixed(7),this.lngInput.value=o.lng.toFixed(7);const c=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(c,this.plantingCentre()),this.surroundings.walked(o.lat,o.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=st(t.lat,t.lng,e.lat,e.lng),n=i.x,s=-i.z;if(Math.hypot(n,s)<1e-6)return;const r=(o,c)=>Math.round((o-c)*1e3)/1e3,a=this.ufoElement.sighting;a.decor=a.decor.map(o=>({...o,eastM:r(o.eastM,n),northM:r(o.northM,s),...o.track?{track:o.track.map(c=>({...c,eastM:r(c.eastM,n),northM:r(c.northM,s)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(yo,i.width-io);break;case"ArrowRight":i.width+=io;break;case"ArrowUp":i.height=Math.max(yo,i.height-io);break;case"ArrowDown":i.height+=io;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=io;break;case"ArrowRight":i.x+=io;break;case"ArrowUp":i.y-=io;break;case"ArrowDown":i.y+=io;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:n,shape:s}=i[0];this.commitShapes(t,[{sourceId:n,shape:{...s,bounds:this.nudgeBounds(s.bounds,e)}}])}else{const n=new Sm(i),s=this.nudgeBounds(n.bounds(),e);this.commitShapes(t,n.scaleTo(s))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode(),n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const o=r?this.bodyCanvasBounds():void 0,c=o&&Vt.hitTestHandle({bounds:o,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const o=this.decorCanvasBounds(),c=o&&Vt.hitTestHandle({bounds:o,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.editableDecor();if(h&&!this.ufoElement.shapeAt(t.x,t.y,up)&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const o=Vt.hitTestHandle({bounds:new Sm(this.selectedMembers()).bounds(),angle:0},t);if(o)return this.cursorForHandle(o,0)}else{const o=n.getInterpolatedShapeAt(s,this.currentSourceId);if(o?.kind==="polygon"&&Vt.hitTestVertex(o,t)!==void 0)return"vertex";const c=o&&Vt.hitTestHandle(o,t);if(o&&c)return this.cursorForHandle(c,o.angle)}return n.hitTest(s,t.x,t.y)?r&&a?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${Vt.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),n=e.clientX-i.left,s=e.clientY-i.top;this.recorder?.onPointerMove(n,s),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(px(this.buildPrototype({x:0,y:0,width:Sc.width,height:Sc.height}),n,s))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(!(i.width===0||i.height===0))return{x:(e.clientX-i.left)/i.width*t.width,y:(e.clientY-i.top)/i.height*t.height}}}const hN={measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},ax="rr0-sighting-editor",ox="rr0-ufo-recorder";class dN extends Ce{}function tE(){Ax(),Rx(),ZS(),p6(),d6(),v6(),cm(),customElements.get(ax)||customElements.define(ax,Ce),customElements.get(ox)||customElements.define(ox,dN)}const Uv={event:"Event",accountOf:"Observation of",passagesHeading:"Reported in",interviewOf:"Interview of",untitledInterview:"Interview {n}",deleteInterviewQuestion:"Delete this interview from the case? Nothing is written until the case is saved.",untitledReading:"Reading {n}",eventsInTime:"Events · in the order of time",citedMoment:"Moment {k}, quoted in {title}: “{quote}”",backToInterview:"Back to the interview",openEvent:"Open",previousEvent:"Previous event",nextEvent:"Next event",kindReading:"Reading",readingsCount:"{n} reading(s)",untitledObservation:"Observation {n}",deleteRecording:"Delete this recording from the case",deleteReadingQuestion:"Delete this reading? Nothing is written until the case is saved.",deleteObservationQuestion:"Delete this observation from the case? Nothing is written until the case is saved.",deleteRefused:"This observation is interpreted by {n} reading(s): delete them first.",titleField:"Title of the interpretation",authorField:"Author",addTitle:"Add an event",kindField:"Type",kindObservation:"Observation",kindInterview:"Interview",witnessField:"Witness",mediumField:"Medium",interviewerField:"Interviewer",plainTitleField:"Title",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"An existing recording",observerField:"Observer",fileField:"File",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",recordingId:"ID",idTaken:"Another recording of the case has this ID.",idInvalid:"An ID is made of letters, digits, hyphens and underscores, and starts with a letter or a digit.",idNeeded:"A reading names this recording by its ID: it cannot be left empty.",idDuplicated:"Two events of the case have the ID “{id}”: a reading that names it is ambiguous.",readingUnresolved:"A reading names “{id}”, which no event of the case has as its ID, nor any recording it lists.",caseTitle:"Title",caseTime:"When",eventsTab:"Events",fileTab:"File",importFile:"Load case file",inputFileFromFile:"from your disk",inputFileFromUrl:"from an address",inputFileModeHint:"Click to give it the other way: a file of yours, or an address",inputFileLoad:"Load",fileNotACase:"That file is not a case (it has no events).",formatVersionError:"This file states version {found} of its format; this UFO@home reads up to version {supported}. Open it with a newer UFO@home.",fileInvalid:"This text is not valid JSON yet, or not a case: the case keeps what it last understood.",fileLoading:"Loading the editor…",add:"Add",addHint:"Add an event",interpretationOf:"Interpretation of",interpretationOfNone:"—",exportButton:"Save",exportTitle:"Save the case",exportAlso:"Also save the observations",addToCase:"Add to a case",unsavedChanges:"Changes not saved",discardQuestion:"Some changes are not saved yet. Load anyway and lose them?",discardTitle:"Unsaved changes",discardOk:"Load anyway",leaveQuestion:"Some changes are not saved yet. Leave anyway and lose them?",leaveOk:"Leave anyway"},uN=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:Uv},Symbol.toStringTag,{value:"Module"})),lx="rr0-case-editor",pN=`
11301
11301
  <style>
11302
11302
  :host { display: block; }
11303
11303
  ${gs.CSS}