@rr0/ufoathome 0.105.0 → 0.105.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.
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ContrailSystem-oqsCCklf.js","./ContrailGrowth-CuAzwIoc.js","./trafficRuntime-Ce_f9RDO.js","./ModelThumbnails-BMvmda-2.js","./ModelSource-BJHgjQd9.js","./ModelViewer-O9_A3wzF.js","./SightingFileEditor-BUpjvTYf.js","./sightingSchema-5AlscPkV.js","./BodyEditor-CiPDf3PA.js","./BodyEditorMessages_en-D6h_2jc7.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
const Kw="modulepreload",Zw=function(a,e){return new URL(a,e).href},Rg={},je=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){let r=function(h){return Promise.all(h.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");n=r(t.map(h=>{if(h=Zw(h,i),h in Rg)return;Rg[h]=!0;const d=h.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(!!i)for(let g=o.length-1;g>=0;g--){const m=o[g];if(m.href===h&&(!d||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":Kw,d||(f.as="script"),f.crossOrigin="",f.href=h,c&&f.setAttribute("nonce",c),document.head.appendChild(f),d)return new Promise((g,m)=>{f.addEventListener("load",g),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function s(r){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=r,window.dispatchEvent(o),!o.defaultPrevented)throw r}return n.then(r=>{for(const o of r||[])o.status==="rejected"&&s(o.reason);return e().catch(s)})};class wn{constructor(e){this.entries=e}static empty(){return new wn(new Map)}get size(){return this.entries.size}at(e){return this.entries.get(e)}paths(){return[...this.entries.keys()]}set(e,t){t.basis==="stated"&&t.rationale===void 0?this.entries.delete(e):this.entries.set(e,t)}clear(e){for(const t of this.entries.keys())(t===e||t.startsWith(`${e}.`))&&this.entries.delete(t)}static strip(e){const t=new wn(new Map);return{recording:wn.stripValue(e,[],t),provenance:t}}static restore(e,t){if(t.size===0)return e;const i=structuredClone(e);for(const n of t.paths()){const s=t.at(n),r=n.split("."),o=wn.holderOf(i,r);if(!o)continue;const l=r[r.length-1],c=o[l];c!==void 0&&(s.of!==void 0&&JSON.stringify(s.of)!==JSON.stringify(c)||(o[l]={value:c,...s.basis==="stated"?{}:{basis:s.basis},...s.rationale===void 0?{}:{rationale:s.rationale}}))}return i}static isWrapper(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&"value"in e}static stripValue(e,t,i){return wn.isWrapper(e)?(i.set(t.join("."),{basis:e.basis??"stated",...e.rationale===void 0?{}:{rationale:e.rationale},of:e.value}),wn.stripValue(e.value,t,i)):Array.isArray(e)?e.map((n,s)=>wn.stripValue(n,[...t,String(s)],i)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,s])=>[n,wn.stripValue(s,[...t,n],i)])):e}static holderOf(e,t){let i=e;for(const n of t.slice(0,-1)){if(typeof i!="object"||i===null)return;i=i[n]}return typeof i=="object"&&i!==null?i:void 0}}class Es{static SIGHTING_EVENT="sighting";static INTERPRETATION_EVENT="interpretation";static isCase(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Array.isArray(e.events)&&!("timeline"in e)}static sightingUrls(e,t){return(e.events??[]).filter(i=>i.eventType===Es.SIGHTING_EVENT&&!i.interpretationOf&&typeof i.url=="string"&&i.url!=="").map(i=>new URL(i.url,t).href)}static interpretationEvents(e,t){return t?(e.events??[]).filter(i=>i.eventType===Es.INTERPRETATION_EVENT?i.sighting===t:i.eventType!==Es.SIGHTING_EVENT||i.interpretationOf===void 0?!1:[i.interpretationOf].flat().includes(t)).map(i=>i):[]}static async interpretationOf(e,t,i){if(e.bodies||e.reentries)return Es.withModelsFrom(wn.strip({title:e.title,bodies:e.bodies??[],smoke:e.smoke,reentries:e.reentries}).recording,t);if(!e.url)return{title:e.title,bodies:[]};const n=new URL(e.url,t).href,s=await i(n),r="timeline"in s&&s.interpretation?s.interpretation:s;return Es.withModelsFrom(wn.strip({title:e.title??r.title,bodies:r.bodies??[],smoke:r.smoke,reentries:r.reentries}).recording,n)}static withModelsFrom(e,t){return{...e,bodies:e.bodies.map(i=>i.model?.url?{...i,model:{...i.model,url:new URL(i.model.url,t).href}}:i)}}}class xa extends Error{constructor(e,t,i){super(`${e}: ${t}${i===void 0?"":` (HTTP ${i})`}`),this.kind=e,this.url=t,this.status=i,this.name="SightingFetchError"}}class Nc{static async json(e){const t=new URL(e,location.href);if(location.protocol==="https:"&&t.protocol==="http:")throw new xa("mixed-content",e);let i;try{i=await fetch(e)}catch{throw await this.diagnose(e,t)}if(!i.ok)throw new xa("status",e,i.status);try{return await i.json()}catch{throw new xa("malformed",e)}}static async diagnose(e,t){if(t.origin===location.origin)return new xa("unreachable",e);try{return await fetch(e,{mode:"no-cors"}),new xa("cors",e)}catch{return new xa("unreachable",e)}}}class qn{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[qn.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>qn.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(qn.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(o=>o===i)??Object.keys(s).find(o=>qn.base(o)===qn.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 Fc(a,e){for(const t of a){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class hs{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 bn{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=bn.ISO.exec(t);if(!i||t==="P"||t.endsWith("T"))return;const[,n,s,r,o,l]=i,c=d=>d===void 0?0:Number(d.replace(",",".")),h=c(n)*604800+c(s)*86400+c(r)*3600+c(o)*60+c(l);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=>bn.seconds(d));if(r.some(d=>d===void 0))return;const[o,l]=r,c=Math.min(o,l??o),h=Math.max(o,l??o);return{doubt:n,minSeconds:c,maxSeconds:h,chosenSeconds:(c+h)/2}}static isExact(e){const t=bn.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 lt{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/lt.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 jw(a,e,t){if(!a||!e)return t<1?a:e;const i=((e.azimuthDeg-a.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((a.azimuthDeg+i*t)%360+360)%360,altitudeDeg:a.altitudeDeg+(e.altitudeDeg-a.altitudeDeg)*t}}function Jw(a,e="#39ff14"){return{kind:"oval",bounds:a,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function Qw(a,e,t="#39ff14"){return{kind:"polygon",bounds:a,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function e2(a,e="#39ff14"){const{width:t,height:i}=a;return Qw(a,[{x:0,y:0},{x:t,y:0},{x:t,y:i},{x:0,y:i}],e)}const t2={oval:Jw,polygon:e2};function Cg(a,e){return{...t2[e.presetId](a,e.color),transparency:e.transparency,haloScale:e.haloScale,blur:e.blur,brightness:e.brightness}}function i2(a,e,t){const{bounds:i}=a;return e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height}function Ay(a,e,t){const i=a.bounds.width,n=a.bounds.height;return{...a,bounds:{x:e-i/2,y:t-n/2,width:i,height:n}}}function Cn(a,e,t){return a+(e-a)*t}function Pg(a){const e=/^#([0-9a-f]{6})$/i.exec(a);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function n2(a){return`#${a.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function s2(a,e,t){const i=Pg(a),n=Pg(e);return!i||!n?t<1?a:e:n2([Cn(i[0],n[0],t),Cn(i[1],n[1],t),Cn(i[2],n[2],t)])}function r2(a,e,t){const i={x:Cn(a.bounds.x,e.bounds.x,t),y:Cn(a.bounds.y,e.bounds.y,t),width:Cn(a.bounds.width,e.bounds.width,t),height:Cn(a.bounds.height,e.bounds.height,t)},n=Cn(a.angle,e.angle,t),s=Cn(a.transparency,e.transparency,t),r=Cn(a.haloScale,e.haloScale,t),o=Cn(a.blur??0,e.blur??0,t),l=Cn(a.brightness??0,e.brightness??0,t),c=s2(a.color,e.color,t),h=lt.lerpAngular(a.angular,e.angular,t),d=jw(a.aim,e.aim,t);return a.kind==="polygon"&&e.kind==="polygon"&&a.points.length===e.points.length?{...a,bounds:i,angle:n,transparency:s,haloScale:r,blur:o,brightness:l,color:c,angular:h,aim:d,points:a.points.map((u,p)=>({x:Cn(u.x,e.points[p].x,t),y:Cn(u.y,e.points[p].y,t)}))}:{...t<1?a:e,bounds:i,angle:n,transparency:s,haloScale:r,blur:o,brightness:l,color:c,angular:h,aim:d}}class Ea{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,o)=>{const l=`timeline.keyframes.${s}.shapes.${o}.shape`,c=Ea.completed(r,i.get(r.sourceId),l,t);return i.set(r.sourceId,c),{sourceId:r.sourceId,shape:c}})}))}static completed(e,t,i,n){const s=e.shape??{},r=t??Ea.firstAppearance(s,i,n),o={...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 o.aim,s.angular||delete o.angular);const l=s.kind??r.kind??"oval",c={...o,...s,kind:l};if(l==="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:`"${Ea.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:{...Ea.NEUTRAL_BOUNDS},color:Ea.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:lt.CANVAS_WIDTH_PX/2,y:lt.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Gu{keyframes=[];order=[];groups=[];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?r2(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 o=this.getInterpolatedShapeAt(e,s[r]);if(o&&i2(o,t,i))return{sourceId:s[r],shape:o}}}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)}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(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes,order:this.order,groups:this.groups}}static fromJSON(e,t){const i=new Gu;for(const n of Ea.complete(e.keyframes??[],t))i.addKeyframe(n.t,n.shapes);if(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 a2(a,e,t){return Math.max(e,Math.min(t,a))}function o2(a,e,t){const i=((e-a)%360+540)%360-180;return((a+i*t)%360+360)%360}function bo(a,e,t){return a+(e-a)*t}function l2(a,e,t){return{lat:a.lat===void 0||e.lat===void 0?void 0:bo(a.lat,e.lat,t),lng:a.lng===void 0||e.lng===void 0?void 0:bo(a.lng,e.lng,t),elevationM:bo(a.elevationM,e.elevationM,t),headingDeg:a.headingDeg===void 0||e.headingDeg===void 0?void 0:o2(a.headingDeg,e.headingDeg,t),pitchDeg:bo(a.pitchDeg,e.pitchDeg,t),rollDeg:bo(a.rollDeg??0,e.rollDeg??0,t),fovDeg:bo(a.fovDeg,e.fovDeg,t),fNumber:a.fNumber,focusDistanceM:a.focusDistanceM,filter:a.filter}}class Qa{static at(e,t,i,n,s){const r=e[i],l=e[i+1]-r;if(l<=0)return t[i];const c=Qa.tangent(e,t,i,s),h=Qa.tangent(e,t,i+1,s),d=(n-r)/l,u=d*d,p=u*d;return(2*p-3*u+1)*t[i]+(p-2*u+d)*l*c+(-2*p+3*u)*t[i+1]+(p-u)*l*h}static BRAKE_S=.8;static paced(e,t,i,n){if(!i&&!n)return e;const s=t>0?Math.min(.5,Qa.BRAKE_S/t):.5;if(i&&n){const o=1/(1-s);return e<=s?o*e*e/(2*s):e>=1-s?1-o*(1-e)*(1-e)/(2*s):o*(e-s/2)}const r=o=>{const l=1/(1-s/2);if(o<=1-s)return l*o;const c=o-(1-s);return l*(1-s)+l*(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 o=r(i-1),l=r(i);if(o*l<=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/o+u/l)}}class Uc{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 i.pose;const s=l2(i.pose,n.pose,a2((e-i.t)/(n.t-i.t),0,1));return this.humanly(t-1,e,s)}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),o=e-n,l=r.map(y=>y.t),c=(y,b)=>{const w=r.map(S=>y(S.pose));if(!w.some(S=>S===void 0))return Qa.at(l,w,o,t,b)},h=r.map(y=>y.pose.headingDeg);let d;if(h.every(y=>y!==void 0)){const y=[h[0]];for(let b=1;b<h.length;b++)y.push(y[b-1]+((h[b]-h[b-1])%360+540)%360-180);d=(Qa.at(l,y,o,t,!0)%360+360)%360}const u=this.keyframes[e],p=this.keyframes[e+1],f=(y,b)=>y.lat===b.lat&&y.lng===b.lng&&y.elevationM===b.elevationM,g=!f(u.pose,p.pose),m=g&&e>0&&f(this.keyframes[e-1].pose,u.pose),v=g&&e+2<this.keyframes.length&&f(p.pose,this.keyframes[e+2].pose);let x;if(m||v){const y=Qa.paced((t-u.t)/(p.t-u.t),(p.t-u.t)/1e3,m,v),b=(w,S)=>w===void 0||S===void 0?void 0:w+(S-w)*y;x={lat:b(u.pose.lat,p.pose.lat),lng:b(u.pose.lng,p.pose.lng),elevationM:b(u.pose.elevationM,p.pose.elevationM)}}return{...i,lat:x?x.lat:c(y=>y.lat,!1)??i.lat,lng:x?x.lng:c(y=>y.lng,!1)??i.lng,elevationM:x?x.elevationM:c(y=>y.elevationM,!1)??i.elevationM,headingDeg:d??i.headingDeg,pitchDeg:c(y=>y.pitchDeg,!0)??i.pitchDeg,rollDeg:c(y=>y.rollDeg??0,!0)??i.rollDeg,fovDeg:c(y=>y.fovDeg,!0)??i.fovDeg}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new Uc;for(const i of e.keyframes)t.addKeyframe(i.t,i.pose);return t}}class $r{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($r.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?$r.follow(this.followed[t],i.intensity,n.intensity,(n.t-i.t)/1e3,(e-i.t)/1e3):$r.follow(this.followed[t],i.intensity,i.intensity,1,(e-i.t)/1e3);return{type:$r.typeBetween(i,n,e,s),intensity:s,character:$r.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=$r.MAX_CHANGE_PER_S,o=n>0?(i-t)/n:0,l=d=>t+o*Math.min(Math.max(d,0),n);let c=e,h=0;for(let d=0;d<8&&h<s;d++){const u=l(h)-c;if(Math.abs(u)<1e-9){const y=h<n?o:0;if(Math.abs(y)<=r){const w=h<n?Math.min(s,n):s;c=l(w),h=w;continue}const b=Math.min(s,n);c+=Math.sign(y)*r*(b-h),h=b;continue}const p=Math.sign(u),f=h<n?o:0,g=r-p*f,m=g>0?h+Math.abs(u)/g:1/0,v=h<n?n:1/0,x=Math.min(s,m,v);c+=p*r*(x-h),h=x,x===m&&(c=l(h))}return Math.min(1,Math.max(0,c))}}const xm=1e3,Od=.65,Vu={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function Ks(a){if(a.cloudLayers!==void 0)return a.cloudLayers;const e=[],t=a.lowerCloudCover??a.cloudCover;return t>0&&e.push({id:"lower",type:"cumulus",baseM:a.cloudBaseM??xm,thicknessM:650,coverage:t,sizeM:1400,density:1,darkness:a.cloudDarkness}),(a.highCloudCover??0)>0&&e.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:a.highCloudCover,sizeM:2200,density:.35,darkness:a.cloudDarkness,iceCrystalAlignment:a.iceCrystalAlignment}),e}function ii(a,e,t){return a+(e-a)*t}function Sm(a,e,t){const i=((e-a)%360+540)%360-180;return((a+i*t)%360+360)%360}function c2(a,e,t){return Math.max(e,Math.min(t,a))}function h2(a=[],e=[],t){if(!(!a.length&&!e.length))return[...new Set([...a.map(i=>i.id),...e.map(i=>i.id)])].map(i=>{const n=a.find(l=>l.id===i),s=e.find(l=>l.id===i),r=n??{...s,density:0},o=s??{...n,density:0};return{...r,eastM:ii(r.eastM,o.eastM,t),northM:ii(r.northM,o.northM,t),baseM:ii(r.baseM,o.baseM,t),thicknessM:ii(r.thicknessM,o.thicknessM,t),widthM:ii(r.widthM,o.widthM,t),depthM:ii(r.depthM,o.depthM,t),rotationDeg:Sm(r.rotationDeg,o.rotationDeg,t),density:ii(r.density,o.density,t),darkness:ii(r.darkness??0,o.darkness??0,t)}})}function d2(a,e,t){if(a.cloudLayers===void 0&&e.cloudLayers===void 0)return;const i=Ks(a),n=Ks(e);return t>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const o=i.find(d=>d.id===r),l=n.find(d=>d.id===r),c=o??{...l,coverage:0},h=l??{...o,coverage:0};return{...c,instances:h2(o?.instances,l?.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??a.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??a.windSpeed,h.windSpeed??e.windSpeed,t),windDirectionDeg:c.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:Sm(c.windDirectionDeg??a.windDirectionDeg,h.windDirectionDeg??e.windDirectionDeg,t)}})}function u2(a,e,t){return{cloudLayers:d2(a,e,t),cloudCover:ii(a.cloudCover,e.cloudCover,t),cloudDarkness:ii(a.cloudDarkness,e.cloudDarkness,t),highCloudCover:a.highCloudCover===void 0||e.highCloudCover===void 0?void 0:ii(a.highCloudCover,e.highCloudCover,t),iceCrystalAlignment:a.iceCrystalAlignment===void 0||e.iceCrystalAlignment===void 0?void 0:ii(a.iceCrystalAlignment,e.iceCrystalAlignment,t),lowerCloudCover:a.lowerCloudCover===void 0||e.lowerCloudCover===void 0?void 0:ii(a.lowerCloudCover,e.lowerCloudCover,t),cloudBaseM:a.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:ii(a.cloudBaseM,e.cloudBaseM,t),relativeHumidity:a.relativeHumidity===void 0||e.relativeHumidity===void 0?void 0:ii(a.relativeHumidity,e.relativeHumidity,t),precipitationType:t<1?a.precipitationType:e.precipitationType,precipitationIntensity:ii(a.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:Sm(a.windDirectionDeg,e.windDirectionDeg,t),windSpeed:ii(a.windSpeed,e.windSpeed,t),storm:t<1?a.storm:e.storm}}class Bc{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?u2(i.weather,n.weather,c2((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 $r(this.keyframes)).at(e);if(!i)return t;const{type:n,intensity:s,character:r}=i,o=r>0?Math.min(1,s/r):n==="none"?0:1;return{...t,precipitationType:n,precipitationIntensity:r,precipitationAmount:o}}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 Bc;for(const i of e.keyframes)t.addKeyframe(i.t,{...Vu,...i.weather});return t}}class zc{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 zc;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 p2=["none","hum","whistle","rumble","crackle"],f2=100,m2={kind:"none",volume:0,pitchHz:f2},dh=[{id:"eye",name:"Naked eye",flare:0,projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",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",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",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",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",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",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}},{id:"phone-portrait",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}}];class Rt{static get default(){return dh[0]}static byId(e){return dh.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:Rt.UNAIDED_FIELD_DEG}static aspectOf(e){const t=e.frame;return t?t.widthMm/t.heightMm:Rt.UNAIDED_ASPECT}static frameWidthPx(e,t){return Math.round(t*Rt.aspectOf(e))}static availableAt(e){return e===void 0?dh:dh.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 LENS_FLARE_ARTIFACTS=1;static flareArtifactsOf(e){return e.flare??Rt.LENS_FLARE_ARTIFACTS}static starPointsOf(e){const t=e.apertureBlades;return t===void 0||t<3?0:t%2===0?t:t*2}}class lo extends Error{}class Wu{constructor(e){this.name=e}validate(e){return!0}}class Ty extends Wu{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new lo(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new lo(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class Ri{name;min;max;duration;subUnit;validator;constructor(e,t,i,n,s=new Ty(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 Iy{millisecond;second;minute;hour;day;month;year}class g2 extends Iy{}class Dy extends g2{millisecond=new Ri("millisecond",0,999,void 0);second=new Ri("second",0,59,this.millisecond);minute=new Ri("minute",0,59,this.second);hour=new Ri("hour",0,23,this.minute);day=new Ri("day",1,31,this.hour);month=new Ri("month",1,12,this.day);year=new Ri("year",0,9999,this.month)}const Ze=new Dy;class v2 extends Ty{constructor(e=1,t=12){super("month",e,t)}}class Zs{static instance=new Zs;render(e){return e.value.toString()}}class ln{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 Wu(`${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=Zs.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Yt{static#e=new Map;static register(e,t){Yt.#e.set(e,t)}static get(e){const t=Yt.#e.get(e);if(!t)throw new lo(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class Nd extends ln{constructor(e=new Date().getFullYear(),t=Ze.year){super(e,t)}static fromString(e,t=Yt.get(Nd)){return new Nd(t.parse(e))}}class lr extends Zs{static default=new lr("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class Fd extends ln{constructor(e=new Date().getMonth()+1,t=Ze.month){super(e,t)}static fromString(e,t=Yt.get(Fd)){return new Fd(t.parse(e))}toString(e=lr.default){return super.toString(e)}}class Ud extends ln{constructor(e=new Date().getDate(),t=Ze.day){super(e,t)}static fromString(e,t=Yt.get(Ud)){const i=t.parse(e);return new Ud(i)}toString(e=lr.default){return super.toString(e)}}class Bd extends ln{constructor(e=new Date().getHours(),t=Ze.hour){super(e,t)}static fromString(e,t=Yt.get(Bd)){return new Bd(t.parse(e))}toString(e=lr.default){return super.toString(e)}}class zd extends ln{constructor(e=new Date().getMinutes(),t=Ze.minute){super(e,t)}static fromString(e,t=Yt.get(zd)){return new zd(t.parse(e))}toString(e=lr.default){return super.toString(e)}}class Hd extends ln{constructor(e=new Date().getSeconds(),t=Ze.second){super(e,t)}static fromString(e,t=Yt.get(Hd)){return new Hd(t.parse(e),Ze.second)}toString(e=lr.default){return super.toString(e)}}class fo extends ln{static renderer=new lr("0",3);constructor(e,t=Ze.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=fo.renderer){return super.toString(e)}}class b2{render(e){return e.toString()}}class y2 extends b2{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?"-":"+",o=n.toString().padStart(2,"0"),l=s>0?":"+s.toString().padEnd(2,"0"):"";return r+o+l}}}class _l{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=Yt.get(_l),i=void 0){const n=t.parse(e,i);return new _l(n)}toString(e=new y2){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class sn{static timeshift(e,t){return e+(sn.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=sn.rule(t);if(!r)return!1;const o=sn.rank(i,n,s);return o>=sn.rank(r.start.month,r.start.day,2)&&o<sn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:sn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:sn.sunday(e,3,2)},end:{month:11,day:sn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:sn.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:sn.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,sn.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let o=s;for(;o+7<=r;)o+=7;return o}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 M2={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},w2={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},x2={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},S2={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},E2={name:"PT",timeshift:a=>sn.timeshift(-480,a),title:"Pacific Time (US)"},_2={name:"MT",timeshift:a=>sn.timeshift(-420,a),title:"Mountain Time (US)"},A2={name:"CT",timeshift:a=>sn.timeshift(-360,a),title:"Central Time (US)"},T2={name:"ET",timeshift:a=>sn.timeshift(-300,a),title:"Eastern Time (US)"},I2={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},D2={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},R2={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},C2={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},P2={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},L2={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},k2={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},O2={name:"Z",timeshift:"Z",title:"UTC"},N2={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},F2={name:"BST",timeshift:"+01",title:"British Summer Time"},U2={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},B2={name:"CET",timeshift:"+01",title:"Central European Time"},z2={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},H2={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},G2={name:"BJT",timeshift:"+08",title:"Beijing Time"},V2={name:"CST",timeshift:"-06",title:"Central Standard Time"},W2={name:"JST",timeshift:"+09",title:"Japan Standard Time"},X2={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},$2={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},Y2={name:"LST",timeshift:"?",title:"Local Sideral Time"},Lg=[L2,X2,P2,G2,F2,V2,D2,B2,U2,A2,I2,C2,R2,T2,N2,H2,W2,Y2,x2,z2,S2,_2,$2,w2,M2,E2,k2,O2];class Xu{static instance=new Xu;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 Sa extends lo{constructor(e="method is abstract"){super(e)}}class Em{units;constructor(e){this.units=e}newYear(e){throw new Sa}newMonth(e){throw new Sa}newDay(e){throw new Sa}newHour(e){throw new Sa}newMinute(e){throw new Sa}newSecond(e){throw new Sa}}class q2 extends Iy{millisecond=new Ri("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new Ri("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Ri("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new Ri("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new Ri("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new Ri("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new Ri("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const _m=new q2;class Am{static instance=new Am;render(e){const t=La.toSpec(e);let i="P";const n=t.years;n&&(i+=n.toString()+"Y");const s=t.months;s&&(i+=s.toString(Zs.instance)+"MM");const r=t.days;r&&(i+=r.toString(Zs.instance)+"D");const o=t.hours;o&&(i+=o.toString(Zs.instance)+"H");const l=t.minutes;l&&(i+=l.toString(Zs.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(Zs.instance)+"S"),i}}class La extends ln{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*Ze.year.duration:0)+(e.months?e.months*Ze.month.duration:0)+(e.days?e.days*Ze.day.duration:0)+(e.hours?e.hours*Ze.hour.duration:0)+(e.minutes?e.minutes*Ze.minute.duration:0)+(e.seconds?e.seconds*Ze.second.duration:0)},new Ri("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=Z2){let i=typeof e=="number"?e:e.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/Ze.year.duration,o=Math.floor(r);o>0&&(s.years=t.newYear(n*o),i-=o*Ze.year.duration);const l=i/Ze.month.duration,c=Math.floor(l);c>0&&(s.months=t.newMonth(n*c),i-=c*Ze.month.duration);const h=i/Ze.day.duration,d=Math.floor(h);d>0&&(s.days=t.newDay(n*d),i-=d*Ze.day.duration);const u=i/Ze.hour.duration,p=Math.floor(u);p>0&&(s.hours=t.newHour(n*p),i-=p*Ze.hour.duration);const f=i/Ze.minute.duration,g=Math.floor(f);g>0&&(s.minutes=t.newMinute(n*g),i-=g*Ze.minute.duration);const m=i/Ze.second.duration,v=Math.floor(n*m);return v>0&&(s.seconds=t.newSecond(v)),s}static fromString(e,t=Yt.get(La)){return new La(t.parse(e))}static between(e,t){const i=t.getTime(),n=e.getTime();return new La(i-n)}toSpec(){return La.toSpec(this)}toString(e=Am.instance){return e.render(this)}}class Ry extends Em{constructor(e){super(e)}newYear(e){return new Nd(e,this.units.year)}newMonth(e){return new Fd(e,this.units.month)}newDay(e){return new Ud(e,this.units.day)}newHour(e){return new Bd(e,this.units.hour)}newMinute(e){return new zd(e,this.units.minute)}newSecond(e){return new Hd(e,this.units.second)}newMillisecond(e){return new fo(e,this.units.millisecond)}newTimeshift(e){return new _l(typeof e=="number"?e:e.value)}}const K2=new Ry(Ze),Z2=new Ry(_m);class ws{#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:ws.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 ln?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 ln?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 ln?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 ln?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 ln?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 ln?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 ln)?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 _l)?this.factory.newTimeshift(e):e}get factory(){return K2}static fromString(e,t=Yt.get(ws)){const{year:i,month:n,day:s,hour:r,minute:o,second:l,millisecond:c,timeshift:h}=t.parse(e);return new ws({year:i,month:n,day:s,hour:r,minute:o,second:l,millisecond:c,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new ws({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:ws.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return ws.fromString(i)}#l(e){if(this.constructor.name!==e.constructor.name)throw new Wu(`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 La(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 ws(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=Xu.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 o=this.second?.toSpec();o&&(e.second=o);const l=this.millisecond?.toSpec();l&&(e.millisecond=l);const c=this.timeshift?.toSpec();return c&&(e.timeshift=c),e}toJSON(){return this.toSpec()}}class ih extends Zs{static instance=new ih(lr.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 mo extends ln{#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=ih.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class Cy extends Dy{year=new Ri("year",-9999,9999,this.month);yearExtended=new Ri("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const bd=new Cy;class ka extends mo{constructor(e,t=bd.year){super(e,t)}static fromString(e,t=bd.year,i=Yt.get(ka)){const n=i.parse(e),s=n.value.start;if(e.startsWith("Y")&&(t=bd.yearExtended),s!==void 0){const r=new ka(Object.assign({...n},{value:Math.max(s,t.min)})),o=new ka(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:o}}else return new ka(n,t)}}class Py extends Wu{monthValidator=new v2;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class Oa extends mo{constructor(e,t=new Ri(Ze.month.name,1,24,Ze.day,new Py)){super(e,t)}static fromString(e,t=Yt.get(Oa)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=Ze.month;const r=new Oa(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Oa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Oa(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Na extends mo{constructor(e,t=Ze.day){super(e,t)}static fromString(e,t=Yt.get(Na)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=Ze.day;const r=new Na(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Na(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Na(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Fa extends mo{constructor(e,t=Ze.hour){super(e,t)}static fromString(e,t=Yt.get(Fa)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=Ze.hour;const r=new Fa(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Fa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Fa(i)}}class Ua extends mo{constructor(e,t=Ze.minute){super(e,t)}static fromString(e,t=Yt.get(Ua)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.minute,r=new Ua(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ua(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ua(i)}toString(e=ih.instance){return super.toString(e)}}class Ba extends mo{constructor(e,t=Ze.second){super(e,t)}static fromString(e,t=Yt.get(Ba)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.second,r=new Ba(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ba(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ba(i)}}class Al extends _l{static fromString(e,t=Yt.get(Al),i=void 0){return new Al(t.parse(e,i))}}class Ly extends Em{constructor(e){super(e)}newYear(e){return new ka(e,this.units.year)}newMonth(e){return new Oa(e,this.units.month)}newDay(e){return new Na(e,this.units.day)}newHour(e){return new Fa(e,this.units.hour)}newMinute(e){return new Ua(e,this.units.minute)}newSecond(e){return new Ba(e,this.units.second)}newMillisecond(e){return new fo(e,this.units.millisecond)}newTimeshift(e){return new Al(typeof e=="number"?e:e.value)}}const j2=new Ly(bd);new Ly(_m);class _a extends ws{constructor(e){super(e)}get factory(){return j2}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 _a({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:ws.timeshiftOf(e)})}static fromString(e,t=Yt.get(_a)){const i=t.parse(e);return new _a(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return _a.fromString(i)}clone(){return new _a(this.toSpec())}}class Ul extends mo{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 J2 extends Cy{year=new Ri("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Hf=new J2;class za extends Ul{constructor(e,t=Hf.year){super(e,t)}static fromString(e,t=Hf.year,i=Yt.get(za)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new za(Object.assign({...n},{value:Math.max(s,t.min)})),o=new za(Object.assign({...n},{value:Math.min(n.value.end,t.max)})),l={start:r,end:o},c=n.value.estimate;return c&&(l.estimate=c),l}else return new za(n)}}class Q2 extends Py{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 Ha extends Ul{constructor(e,t=new Ri(Ze.month.name,1,41,Ze.day,new Q2)){super(e,t)}static fromString(e,t=Yt.get(Ha)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.month,r=new Ha(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ha(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ha(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Ga extends Ul{constructor(e,t=Ze.day){super(e,t)}static fromString(e,t=Yt.get(Ga)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.day,r=new Ga(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ga(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ga(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Va extends Ul{constructor(e,t=Ze.hour){super(e,t)}static fromString(e,t=Yt.get(Va)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.hour,r=new Va(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Va(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Va(i)}}class Wa extends Ul{constructor(e,t=Ze.minute){super(e,t)}static fromString(e,t=Yt.get(Wa)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.minute,r=new Wa(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Wa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Wa(i)}}class Xa extends Ul{constructor(e,t=Ze.second){super(e,t)}static fromString(e,t=Ze.second,i=Yt.get(Xa)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new Xa(Object.assign({...n},{value:Math.max(s,t.min)})),o=new Xa(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:o}}else return new Xa(n,t)}}class ky extends Al{}class ex extends ih{qualifier(){return""}}class Yr extends Xu{static instance=new Yr;static valueRenderer=new ex(lr.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=Yr.names.slice(Yr.names.indexOf(t)+1).map(o=>e[o]).filter(Boolean),s=Yr.qualifier(i.uncertainComponent,i.approximateComponent),r=Yr.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(o=>o.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(o=>o.approximate));return s+i.toString(Yr.valueRenderer)+r}}class Oy extends Em{constructor(e){super(e)}newYear(e){return new za(e,this.units.year)}newMonth(e){return new Ha(e,this.units.month)}newDay(e){return new Ga(e,this.units.day)}newHour(e){return new Va(e,this.units.hour)}newMinute(e){return new Wa(e,this.units.minute)}newSecond(e){return new Xa(e,this.units.second)}newMillisecond(e){return new fo(e,this.units.millisecond)}newTimeshift(e){return new ky(typeof e=="number"?e:e.value)}}const tx=new Oy(Hf);new Oy(_m);class Aa extends _a{constructor(e){super(e)}toString(e=Yr.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 tx}static fromDate(e){return new Aa({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:ws.timeshiftOf(e)})}static fromString(e,t=Yt.get(Aa)){const i=t.parse(e);return new Aa(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Aa.fromString(i)}clone(){return new Aa(this.toSpec())}}class $u{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new lo(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Sa(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class Tm extends $u{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return Tm.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new lo(`${this.name} cannot be negative`);return super.parse(e)}}class ae{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 ae.optional(ae.group(e,...t))}static optionalNonCapturingGroup(...e){return ae.optional(ae.nonCapturingGroup(...e))}static numberGroup(e,t,i,n="\\d"){return ae.group(e,`${i||""}[${n}]${t}`)}}const kg="timeshiftValue",Og="shiftHour",Ng="shiftMinute";class Im extends $u{static format(e=""){return Lg.map(t=>t.name).join("|")+"|"+ae.nonCapturingGroup(ae.group(e+Og,ae.numberGroup(ae.groupName(e,kg),"{2}","[+-]")),ae.optionalNonCapturingGroup(":?",ae.numberGroup(ae.groupName(e,Ng),"{2}",void 0)))}constructor(){super(kg,Im.format())}parse(e,t){let i=0;const n=Lg.find(s=>s.name===e);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(t??{})}catch(s){throw new lo(`The time zone ${e} depends on the date: ${s.message}`)}e=n.timeshift}if(e!=="Z"){const s=this.regexGroups(e),r=s[Og];r&&(i+=parseInt(r,10)*60);const o=s[Ng];o&&(i+=parseInt(o,10))}return i}}class di extends Tm{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=di.uncertainGroup+di.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return ae.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(ae.groupName(di.uncertainGroup,e),"?")+this.qualifierFormat(ae.groupName(di.approximateGroup,e),"~")+this.qualifierFormat(ae.groupName(di.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return ae.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[ae.groupName(di.uncertainAndApproximateGroup,this.name)],o=e[ae.groupName(di.approximateGroup,this.name)]||r,l=e[ae.groupName(di.uncertainGroup,this.name)]||r;return{value:n,approximate:o?!!o:!1,uncertain:l?!!l:!1}}}const Fg="yearValue";class Gd extends di{constructor(){super(Fg,Gd.format())}static format(e=""){return"Y?"+di.numberFormat(ae.groupName(e,Fg),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const Ug="monthValue";class Vd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Ug),"{1,2}",void 0)}constructor(){super(Ug,Vd.format())}}const Bg="dayValue";class Wd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Bg),"{1,2}",void 0)}constructor(){super(Bg,Wd.format())}}const zg="hourValue";class Xd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,zg),"{1,2}",void 0)}constructor(){super(zg,Xd.format())}}const Hg="minuteValue";class $d extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Hg),"{1,2}",void 0)}constructor(){super(Hg,$d.format())}}const Gg="secondValue";class Yd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Gg),"{1,2}",void 0)}constructor(){super(Gg,Yd.format())}}class qd extends Im{}class Li extends $u{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=Li.format()){super("date",e)}static format(e=""){return ae.group(ae.groupName(e,Li.yearGroup),Gd.format(e))+ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,Li.monthGroup),Vd.format(e)),ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,Li.dayGroup),Wd.format(e)),ae.optionalNonCapturingGroup("[T ]",ae.group(ae.groupName(e,Li.hourGroup),Xd.format(e)),":",ae.group(ae.groupName(e,Li.minuteGroup),$d.format(e)),ae.optionalNonCapturingGroup(":",ae.group(ae.groupName(e,Li.secondGroup),Yd.format(e)),ae.optionalNonCapturingGroup("[.,]",ae.group(ae.groupName(e,Li.millisecondGroup),"\\d+"))),ae.optionalGroup(ae.groupName(e,Li.timeshiftGroup),qd.format(e)))))}parseGroups(e){const t=e[Li.millisecondGroup],i=t?fo.parseFraction(t):void 0,n=e[Li.secondGroup],s=n?Ba.fromString(n,new Yd):void 0,r=e[Li.minuteGroup];let o;r&&(o=Ua.fromString(r,new $d),o.uncertain=o.uncertain||s?.uncertain||!1,o.approximate=o.approximate||s?.approximate||!1);const l=e[Li.hourGroup];let c;l&&(c=Fa.fromString(l,new Xd),c.uncertain=c.uncertain||o?.uncertain||!1,c.approximate=c.approximate||o?.approximate||!1);const h=e[Li.dayGroup];let d;h&&(d=Na.fromString(h,new Wd),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[Li.monthGroup];let p;u&&(p=Oa.fromString(u,new Vd),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[Li.yearGroup];let g;f&&(g=ka.fromString(f,void 0,new Gd),g.uncertain=g.uncertain||p?.uncertain||!1,g.approximate=g.approximate||p?.approximate||!1);const m=e[Li.timeshiftGroup],v=m?Al.fromString(m,new qd,{year:g?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:g,month:p,day:d,hour:c,minute:o,second:s,millisecond:i,timeshift:v}}}class _i extends di{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=_i.uncertainGroup+_i.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(ae.groupName(_i.uncertainGroup,e),"?")+this.qualifierFormat(ae.groupName(_i.approximateGroup,e),"~")+this.qualifierFormat(ae.groupName(_i.uncertainAndApproximateGroup,e),"%")+di.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[ae.groupName(_i.uncertainAndApproximateGroup,this.name)];return(e[ae.groupName(_i.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[ae.groupName(_i.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const Vl="yearValue",Vg="exp",Wg="signif";class Kd extends _i{constructor(){super(Vl,Kd.format())}static format(e=""){return"Y?"+ae.nonCapturingGroup(ae.group(ae.groupName(e,Vg),"[-]?\\d+E\\d+")+"|"+_i.numberFormat(ae.groupName(e,Vl),"+","[-]?")+ae.optionalGroup(ae.groupName(e,Wg),"S\\d+"))}parseGroups(e){const t=e[Vg];if(t){const r=t.indexOf("E"),o=parseInt(t.substring(r+1),10),c=parseInt(t.substring(0,r),10)*Math.pow(10,o);e[Vl]=c.toString()}const i=e[Wg],n=e[Vl];if(i){const r=parseInt(i.substring(1),10),{valueStr:o,sign:l}=this.getValueAndSign(e);let c="";for(let h=0;h<o.length;h++)c+=h<r?o.charAt(h):"X";e[Vl]=(l<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 Xg="monthValue";class Zd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,Xg),"{1,2}",void 0)}constructor(){super(Xg,Zd.format())}}const $g="dayValue";class jd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,$g),"{1,2}",void 0)}constructor(){super($g,jd.format())}}const Yg="hourValue";class Jd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,Yg),"{1,2}",void 0)}constructor(){super(Yg,Jd.format())}}const qg="secondValue";class Qd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,qg),"{1,2}",void 0)}constructor(){super(qg,Qd.format())}}const Kg="minuteValue";class eu extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,Kg),"{1,2}",void 0)}constructor(){super(Kg,eu.format())}}class ix extends qd{}class ki extends $u{static yearGroup=Li.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",ki.format())}static format(e=""){return ae.group(ae.groupName(e,ki.yearGroup),Kd.format(e))+ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,ki.monthGroup),Zd.format(e)),ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,ki.dayGroup),jd.format(e)),ae.optionalNonCapturingGroup("[T ]",ae.group(ae.groupName(e,ki.hourGroup),Jd.format(e)),":",ae.group(ae.groupName(e,ki.minuteGroup),eu.format(e)),ae.optionalNonCapturingGroup(":",ae.group(ae.groupName(e,ki.secondGroup),Qd.format(e)),ae.optionalNonCapturingGroup("[.,]",ae.group(ae.groupName(e,ki.millisecondGroup),"\\d+"))),ae.optionalGroup(ae.groupName(e,ki.timeshiftGroup),ix.format(e)))))}parseGroups(e){const t=e[ki.millisecondGroup],i=t?fo.parseFraction(t):void 0,n=e[ki.secondGroup];let s;n&&(s=Xa.fromString(n,void 0,new Qd),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=e[ki.minuteGroup];let o;r&&(o=Wa.fromString(r,new eu),o.uncertain=o.uncertain||s?.uncertain||!1,o.approximate=o.approximate||s?.approximate||!1);const l=e[ki.hourGroup];let c;l&&(c=Va.fromString(l,new Jd),c.uncertain=c.uncertain||o?.uncertain||!1,c.approximate=c.approximate||o?.approximate||!1);const h=e[ki.dayGroup];let d;h&&(d=Ga.fromString(h,new jd),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[ki.monthGroup];let p;u&&(p=Ha.fromString(u,new Zd),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ki.yearGroup];let g;f&&(g=za.fromString(f,void 0,new Kd),g.uncertain=g.uncertain||p?.uncertain||!1,g.approximate=g.approximate||p?.approximate||!1);const m=e[ki.timeshiftGroup],v=m?ky.fromString(m,new qd,{year:g?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:g,month:p,day:d,hour:c,minute:o,second:s,millisecond:i,timeshift:v}}}const Ny=["spring","summer","autumn","winter"],Gf=21,nx=32,sx=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let rx;function ax(){return rx??=new ki}function yo(a){return typeof a?.value=="number"?a.value:void 0}function yd(a){const e=a.trim();if(/^\d{1,2}:/.test(e)){const r=sx.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=Aa.fromString(e,ax())}catch{return}const i=yo(t.year),n=yo(t.month),s=n!==void 0&&n>=Gf&&n<=nx;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:Ny[(n-Gf)%4]}:{},day:yo(t.day),hour:yo(t.hour),minute:yo(t.minute),second:yo(t.second),raw:e}}function cl(a){if(a.raw!==void 0)return a.raw;if(a.year===void 0){if(a.hour===void 0)return"";let t=`${String(a.hour).padStart(2,"0")}:${String(a.minute??0).padStart(2,"0")}`;return a.second!==void 0&&(t+=`:${String(a.second).padStart(2,"0")}`),t}let e=String(a.year).padStart(4,"0");return a.season!==void 0?`${e}-${Gf+Ny.indexOf(a.season)}`:(a.month===void 0||(e+=`-${String(a.month).padStart(2,"0")}`,a.day===void 0)||(e+=`-${String(a.day).padStart(2,"0")}`,a.hour===void 0)||(e+=`T${String(a.hour).padStart(2,"0")}:${String(a.minute??0).padStart(2,"0")}`,a.second!==void 0&&(e+=`:${String(a.second).padStart(2,"0")}`)),e)}function Vf(a){if(a.year!==void 0)return Date.UTC(a.year,(a.month??1)-1,a.day??1,a.hour??0,a.minute??0,a.second??0)}function Zg(a){return(((a.day??0)*24+(a.hour??0))*60+(a.minute??0))*6e4+(a.second??0)*1e3}const ox=["year","month","day","hour","minute"],lx=["day","hour","minute"];function jg(a,e){return e.filter(t=>a[t]!==void 0).join(",")}function Tl(a){if(a.durationSeconds!==void 0)return a.durationSeconds*1e3;const e=a.durationText===void 0?void 0:bn.parse(a.durationText);if(e)return e.chosenSeconds*1e3;if(!a.time||!a.endTime)return;const t=a.time.year!==void 0&&a.endTime.year!==void 0,i=t?ox:lx,n=jg(a.time,i);if(!(n===""||n!==jg(a.endTime,i)))return t?Vf(a.endTime)-Vf(a.time):Zg(a.endTime)-Zg(a.time)}function cx(a){if(a.durationSeconds===void 0&&!(!a.time||!a.endTime))return Tl(a)===void 0?"imprecise":void 0}class Yu{constructor(e,t,i,n,s,r,o,l,c=[],h,d,u,p=[],f=[],g=[],m=[]){this.event=e,this.timeline=t,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=o,this.weather=l,this.decor=c,this.weatherSource=h,this.instrumentId=d,this.exposureSeconds=u,this.milestones=p,this.references=f,this.roads=g,this.traces=m}provenance=wn.empty();loadIssues=[];account;sources;interpretation;sway;lightPollution;observerMap;iso;vehicle;get observerCount(){return 1+this.decor.filter(e=>e.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return Rt.byId(this.instrumentId)}static create(e,t,i){return new Yu({eventType:"sighting",time:e,place:t},new Gu,new Uc,new Bc,new zc,i)}}const hx=0,dx=0;function at(a,e){const t=a.observerTrack.getInterpolatedPoseAt(e);if(t)return t;const i=a.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:hx,headingDeg:void 0,pitchDeg:dx,fovDeg:Rt.fieldOfViewDeg(a.instrument)}}function hi(a,e){return a.weatherTrack.getInterpolatedWeatherAt(e)??a.weather??Vu}function uh(a,e){return a.weatherTrack.getActualWeatherAt(e)??a.weather??Vu}function Dm(a,e){return a.soundTrack.getInterpolatedSoundAt(e)??m2}class tu{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Es.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;static around(e,t,i,n,s){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Es.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},l=new tu(o,new URL("case.json",s).href),c=l.tracks[0];return c.recording=e,c.base={url:n},l.caseChanged=!0,l}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat();return this.tracks.find(i=>i.kind==="observer"&&i.recording?.id!==void 0&&t.includes(i.recording.id))??this.tracks.find(i=>i.kind==="observer")}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)}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))}markExported(e){if(this.caseChanged=!1,!!e)for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording))}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}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$/,""),o=new Set(this.tracks.map(A=>A.event.url)),l=new Set(this.tracks.map(A=>A.recording?.id));let c=this.tracks.filter(A=>A.kind==="reading").length+1;for(;o.has(`interpretation-${r}-${c}.json`)||l.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:g,description:m,sources:v,tags:x,timeline:y,milestones:b,interpretation:w,...S}=structuredClone(s),_={version:1,id:`${s.id??r}-interpretation-${c}`,...S,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},M={type:"event",eventType:"sighting",interpretationOf:s.id??r,time:t,...n!==void 0&&n.length>0?{by:n}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],M],this.caseChanged=!0;const T={event:M,url:new URL(M.url,this.url).href,kind:"reading",recording:_};return this.tracks.push(T),T}idsOf(e){return e.recording?.id!==void 0?[e.recording.id]:[]}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(g=>g.event.url)),r=new Set(this.tracks.map(g=>g.recording?.id)),o=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",l=n?"interpretation":"observer";let c=`${l}-${o}.json`,h=e.id??o;for(let g=2;s.has(c)||r.has(h);g++)c=`${l}-${o}-${g}.json`,h=`${e.id??o}-${g}`;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:n.account.recording?.id??h}:{},...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),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)+`
|
|
2
|
+
const Kw="modulepreload",Zw=function(a,e){return new URL(a,e).href},Rg={},je=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){let r=function(h){return Promise.all(h.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");n=r(t.map(h=>{if(h=Zw(h,i),h in Rg)return;Rg[h]=!0;const d=h.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(!!i)for(let g=o.length-1;g>=0;g--){const m=o[g];if(m.href===h&&(!d||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":Kw,d||(f.as="script"),f.crossOrigin="",f.href=h,c&&f.setAttribute("nonce",c),document.head.appendChild(f),d)return new Promise((g,m)=>{f.addEventListener("load",g),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function s(r){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=r,window.dispatchEvent(o),!o.defaultPrevented)throw r}return n.then(r=>{for(const o of r||[])o.status==="rejected"&&s(o.reason);return e().catch(s)})};class wn{constructor(e){this.entries=e}static empty(){return new wn(new Map)}get size(){return this.entries.size}at(e){return this.entries.get(e)}paths(){return[...this.entries.keys()]}set(e,t){t.basis==="stated"&&t.rationale===void 0?this.entries.delete(e):this.entries.set(e,t)}clear(e){for(const t of this.entries.keys())(t===e||t.startsWith(`${e}.`))&&this.entries.delete(t)}static strip(e){const t=new wn(new Map);return{recording:wn.stripValue(e,[],t),provenance:t}}static restore(e,t){if(t.size===0)return e;const i=structuredClone(e);for(const n of t.paths()){const s=t.at(n),r=n.split("."),o=wn.holderOf(i,r);if(!o)continue;const l=r[r.length-1],c=o[l];c!==void 0&&(s.of!==void 0&&JSON.stringify(s.of)!==JSON.stringify(c)||(o[l]={value:c,...s.basis==="stated"?{}:{basis:s.basis},...s.rationale===void 0?{}:{rationale:s.rationale}}))}return i}static isWrapper(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&"value"in e}static stripValue(e,t,i){return wn.isWrapper(e)?(i.set(t.join("."),{basis:e.basis??"stated",...e.rationale===void 0?{}:{rationale:e.rationale},of:e.value}),wn.stripValue(e.value,t,i)):Array.isArray(e)?e.map((n,s)=>wn.stripValue(n,[...t,String(s)],i)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,s])=>[n,wn.stripValue(s,[...t,n],i)])):e}static holderOf(e,t){let i=e;for(const n of t.slice(0,-1)){if(typeof i!="object"||i===null)return;i=i[n]}return typeof i=="object"&&i!==null?i:void 0}}class Es{static SIGHTING_EVENT="sighting";static INTERPRETATION_EVENT="interpretation";static isCase(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Array.isArray(e.events)&&!("timeline"in e)}static sightingUrls(e,t){return(e.events??[]).filter(i=>i.eventType===Es.SIGHTING_EVENT&&!i.interpretationOf&&typeof i.url=="string"&&i.url!=="").map(i=>new URL(i.url,t).href)}static interpretationEvents(e,t){return t?(e.events??[]).filter(i=>i.eventType===Es.INTERPRETATION_EVENT?i.sighting===t:i.eventType!==Es.SIGHTING_EVENT||i.interpretationOf===void 0?!1:[i.interpretationOf].flat().includes(t)).map(i=>i):[]}static async interpretationOf(e,t,i){if(e.bodies||e.reentries)return Es.withModelsFrom(wn.strip({title:e.title,bodies:e.bodies??[],smoke:e.smoke,reentries:e.reentries}).recording,t);if(!e.url)return{title:e.title,bodies:[]};const n=new URL(e.url,t).href,s=await i(n),r="timeline"in s&&s.interpretation?s.interpretation:s;return Es.withModelsFrom(wn.strip({title:e.title??r.title,bodies:r.bodies??[],smoke:r.smoke,reentries:r.reentries}).recording,n)}static withModelsFrom(e,t){return{...e,bodies:e.bodies.map(i=>i.model?.url?{...i,model:{...i.model,url:new URL(i.model.url,t).href}}:i)}}}class xa extends Error{constructor(e,t,i){super(`${e}: ${t}${i===void 0?"":` (HTTP ${i})`}`),this.kind=e,this.url=t,this.status=i,this.name="SightingFetchError"}}class Nc{static async json(e){const t=new URL(e,location.href);if(location.protocol==="https:"&&t.protocol==="http:")throw new xa("mixed-content",e);let i;try{i=await fetch(e)}catch{throw await this.diagnose(e,t)}if(!i.ok)throw new xa("status",e,i.status);try{return await i.json()}catch{throw new xa("malformed",e)}}static async diagnose(e,t){if(t.origin===location.origin)return new xa("unreachable",e);try{return await fetch(e,{mode:"no-cors"}),new xa("cors",e)}catch{return new xa("unreachable",e)}}}class qn{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[qn.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>qn.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(qn.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(o=>o===i)??Object.keys(s).find(o=>qn.base(o)===qn.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 Fc(a,e){for(const t of a){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class hs{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 bn{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=bn.ISO.exec(t);if(!i||t==="P"||t.endsWith("T"))return;const[,n,s,r,o,l]=i,c=d=>d===void 0?0:Number(d.replace(",",".")),h=c(n)*604800+c(s)*86400+c(r)*3600+c(o)*60+c(l);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=>bn.seconds(d));if(r.some(d=>d===void 0))return;const[o,l]=r,c=Math.min(o,l??o),h=Math.max(o,l??o);return{doubt:n,minSeconds:c,maxSeconds:h,chosenSeconds:(c+h)/2}}static isExact(e){const t=bn.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 lt{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/lt.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 jw(a,e,t){if(!a||!e)return t<1?a:e;const i=((e.azimuthDeg-a.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((a.azimuthDeg+i*t)%360+360)%360,altitudeDeg:a.altitudeDeg+(e.altitudeDeg-a.altitudeDeg)*t}}function Jw(a,e="#39ff14"){return{kind:"oval",bounds:a,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function Qw(a,e,t="#39ff14"){return{kind:"polygon",bounds:a,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function e2(a,e="#39ff14"){const{width:t,height:i}=a;return Qw(a,[{x:0,y:0},{x:t,y:0},{x:t,y:i},{x:0,y:i}],e)}const t2={oval:Jw,polygon:e2};function Cg(a,e){return{...t2[e.presetId](a,e.color),transparency:e.transparency,haloScale:e.haloScale,blur:e.blur,brightness:e.brightness}}function i2(a,e,t){const{bounds:i}=a;return e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height}function Ay(a,e,t){const i=a.bounds.width,n=a.bounds.height;return{...a,bounds:{x:e-i/2,y:t-n/2,width:i,height:n}}}function Cn(a,e,t){return a+(e-a)*t}function Pg(a){const e=/^#([0-9a-f]{6})$/i.exec(a);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function n2(a){return`#${a.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function s2(a,e,t){const i=Pg(a),n=Pg(e);return!i||!n?t<1?a:e:n2([Cn(i[0],n[0],t),Cn(i[1],n[1],t),Cn(i[2],n[2],t)])}function r2(a,e,t){const i={x:Cn(a.bounds.x,e.bounds.x,t),y:Cn(a.bounds.y,e.bounds.y,t),width:Cn(a.bounds.width,e.bounds.width,t),height:Cn(a.bounds.height,e.bounds.height,t)},n=Cn(a.angle,e.angle,t),s=Cn(a.transparency,e.transparency,t),r=Cn(a.haloScale,e.haloScale,t),o=Cn(a.blur??0,e.blur??0,t),l=Cn(a.brightness??0,e.brightness??0,t),c=s2(a.color,e.color,t),h=lt.lerpAngular(a.angular,e.angular,t),d=jw(a.aim,e.aim,t);return a.kind==="polygon"&&e.kind==="polygon"&&a.points.length===e.points.length?{...a,bounds:i,angle:n,transparency:s,haloScale:r,blur:o,brightness:l,color:c,angular:h,aim:d,points:a.points.map((u,p)=>({x:Cn(u.x,e.points[p].x,t),y:Cn(u.y,e.points[p].y,t)}))}:{...t<1?a:e,bounds:i,angle:n,transparency:s,haloScale:r,blur:o,brightness:l,color:c,angular:h,aim:d}}class Ea{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,o)=>{const l=`timeline.keyframes.${s}.shapes.${o}.shape`,c=Ea.completed(r,i.get(r.sourceId),l,t);return i.set(r.sourceId,c),{sourceId:r.sourceId,shape:c}})}))}static completed(e,t,i,n){const s=e.shape??{},r=t??Ea.firstAppearance(s,i,n),o={...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 o.aim,s.angular||delete o.angular);const l=s.kind??r.kind??"oval",c={...o,...s,kind:l};if(l==="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:`"${Ea.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:{...Ea.NEUTRAL_BOUNDS},color:Ea.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:lt.CANVAS_WIDTH_PX/2,y:lt.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Gu{keyframes=[];order=[];groups=[];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?r2(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 o=this.getInterpolatedShapeAt(e,s[r]);if(o&&i2(o,t,i))return{sourceId:s[r],shape:o}}}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)}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(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes,order:this.order,groups:this.groups}}static fromJSON(e,t){const i=new Gu;for(const n of Ea.complete(e.keyframes??[],t))i.addKeyframe(n.t,n.shapes);if(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 a2(a,e,t){return Math.max(e,Math.min(t,a))}function o2(a,e,t){const i=((e-a)%360+540)%360-180;return((a+i*t)%360+360)%360}function bo(a,e,t){return a+(e-a)*t}function l2(a,e,t){return{lat:a.lat===void 0||e.lat===void 0?void 0:bo(a.lat,e.lat,t),lng:a.lng===void 0||e.lng===void 0?void 0:bo(a.lng,e.lng,t),elevationM:bo(a.elevationM,e.elevationM,t),headingDeg:a.headingDeg===void 0||e.headingDeg===void 0?void 0:o2(a.headingDeg,e.headingDeg,t),pitchDeg:bo(a.pitchDeg,e.pitchDeg,t),rollDeg:bo(a.rollDeg??0,e.rollDeg??0,t),fovDeg:bo(a.fovDeg,e.fovDeg,t),fNumber:a.fNumber,focusDistanceM:a.focusDistanceM,filter:a.filter}}class Qa{static at(e,t,i,n,s){const r=e[i],l=e[i+1]-r;if(l<=0)return t[i];const c=Qa.tangent(e,t,i,s),h=Qa.tangent(e,t,i+1,s),d=(n-r)/l,u=d*d,p=u*d;return(2*p-3*u+1)*t[i]+(p-2*u+d)*l*c+(-2*p+3*u)*t[i+1]+(p-u)*l*h}static BRAKE_S=.8;static paced(e,t,i,n){if(!i&&!n)return e;const s=t>0?Math.min(.5,Qa.BRAKE_S/t):.5;if(i&&n){const o=1/(1-s);return e<=s?o*e*e/(2*s):e>=1-s?1-o*(1-e)*(1-e)/(2*s):o*(e-s/2)}const r=o=>{const l=1/(1-s/2);if(o<=1-s)return l*o;const c=o-(1-s);return l*(1-s)+l*(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 o=r(i-1),l=r(i);if(o*l<=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/o+u/l)}}class Uc{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 i.pose;const s=l2(i.pose,n.pose,a2((e-i.t)/(n.t-i.t),0,1));return this.humanly(t-1,e,s)}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),o=e-n,l=r.map(y=>y.t),c=(y,b)=>{const w=r.map(S=>y(S.pose));if(!w.some(S=>S===void 0))return Qa.at(l,w,o,t,b)},h=r.map(y=>y.pose.headingDeg);let d;if(h.every(y=>y!==void 0)){const y=[h[0]];for(let b=1;b<h.length;b++)y.push(y[b-1]+((h[b]-h[b-1])%360+540)%360-180);d=(Qa.at(l,y,o,t,!0)%360+360)%360}const u=this.keyframes[e],p=this.keyframes[e+1],f=(y,b)=>y.lat===b.lat&&y.lng===b.lng&&y.elevationM===b.elevationM,g=!f(u.pose,p.pose),m=g&&e>0&&f(this.keyframes[e-1].pose,u.pose),v=g&&e+2<this.keyframes.length&&f(p.pose,this.keyframes[e+2].pose);let x;if(m||v){const y=Qa.paced((t-u.t)/(p.t-u.t),(p.t-u.t)/1e3,m,v),b=(w,S)=>w===void 0||S===void 0?void 0:w+(S-w)*y;x={lat:b(u.pose.lat,p.pose.lat),lng:b(u.pose.lng,p.pose.lng),elevationM:b(u.pose.elevationM,p.pose.elevationM)}}return{...i,lat:x?x.lat:c(y=>y.lat,!1)??i.lat,lng:x?x.lng:c(y=>y.lng,!1)??i.lng,elevationM:x?x.elevationM:c(y=>y.elevationM,!1)??i.elevationM,headingDeg:d??i.headingDeg,pitchDeg:c(y=>y.pitchDeg,!0)??i.pitchDeg,rollDeg:c(y=>y.rollDeg??0,!0)??i.rollDeg,fovDeg:c(y=>y.fovDeg,!0)??i.fovDeg}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new Uc;for(const i of e.keyframes)t.addKeyframe(i.t,i.pose);return t}}class $r{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($r.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?$r.follow(this.followed[t],i.intensity,n.intensity,(n.t-i.t)/1e3,(e-i.t)/1e3):$r.follow(this.followed[t],i.intensity,i.intensity,1,(e-i.t)/1e3);return{type:$r.typeBetween(i,n,e,s),intensity:s,character:$r.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=$r.MAX_CHANGE_PER_S,o=n>0?(i-t)/n:0,l=d=>t+o*Math.min(Math.max(d,0),n);let c=e,h=0;for(let d=0;d<8&&h<s;d++){const u=l(h)-c;if(Math.abs(u)<1e-9){const y=h<n?o:0;if(Math.abs(y)<=r){const w=h<n?Math.min(s,n):s;c=l(w),h=w;continue}const b=Math.min(s,n);c+=Math.sign(y)*r*(b-h),h=b;continue}const p=Math.sign(u),f=h<n?o:0,g=r-p*f,m=g>0?h+Math.abs(u)/g:1/0,v=h<n?n:1/0,x=Math.min(s,m,v);c+=p*r*(x-h),h=x,x===m&&(c=l(h))}return Math.min(1,Math.max(0,c))}}const xm=1e3,Od=.65,Vu={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function Ks(a){if(a.cloudLayers!==void 0)return a.cloudLayers;const e=[],t=a.lowerCloudCover??a.cloudCover;return t>0&&e.push({id:"lower",type:"cumulus",baseM:a.cloudBaseM??xm,thicknessM:650,coverage:t,sizeM:1400,density:1,darkness:a.cloudDarkness}),(a.highCloudCover??0)>0&&e.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:a.highCloudCover,sizeM:2200,density:.35,darkness:a.cloudDarkness,iceCrystalAlignment:a.iceCrystalAlignment}),e}function ii(a,e,t){return a+(e-a)*t}function Sm(a,e,t){const i=((e-a)%360+540)%360-180;return((a+i*t)%360+360)%360}function c2(a,e,t){return Math.max(e,Math.min(t,a))}function h2(a=[],e=[],t){if(!(!a.length&&!e.length))return[...new Set([...a.map(i=>i.id),...e.map(i=>i.id)])].map(i=>{const n=a.find(l=>l.id===i),s=e.find(l=>l.id===i),r=n??{...s,density:0},o=s??{...n,density:0};return{...r,eastM:ii(r.eastM,o.eastM,t),northM:ii(r.northM,o.northM,t),baseM:ii(r.baseM,o.baseM,t),thicknessM:ii(r.thicknessM,o.thicknessM,t),widthM:ii(r.widthM,o.widthM,t),depthM:ii(r.depthM,o.depthM,t),rotationDeg:Sm(r.rotationDeg,o.rotationDeg,t),density:ii(r.density,o.density,t),darkness:ii(r.darkness??0,o.darkness??0,t)}})}function d2(a,e,t){if(a.cloudLayers===void 0&&e.cloudLayers===void 0)return;const i=Ks(a),n=Ks(e);return t>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const o=i.find(d=>d.id===r),l=n.find(d=>d.id===r),c=o??{...l,coverage:0},h=l??{...o,coverage:0};return{...c,instances:h2(o?.instances,l?.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??a.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??a.windSpeed,h.windSpeed??e.windSpeed,t),windDirectionDeg:c.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:Sm(c.windDirectionDeg??a.windDirectionDeg,h.windDirectionDeg??e.windDirectionDeg,t)}})}function u2(a,e,t){return{cloudLayers:d2(a,e,t),cloudCover:ii(a.cloudCover,e.cloudCover,t),cloudDarkness:ii(a.cloudDarkness,e.cloudDarkness,t),highCloudCover:a.highCloudCover===void 0||e.highCloudCover===void 0?void 0:ii(a.highCloudCover,e.highCloudCover,t),iceCrystalAlignment:a.iceCrystalAlignment===void 0||e.iceCrystalAlignment===void 0?void 0:ii(a.iceCrystalAlignment,e.iceCrystalAlignment,t),lowerCloudCover:a.lowerCloudCover===void 0||e.lowerCloudCover===void 0?void 0:ii(a.lowerCloudCover,e.lowerCloudCover,t),cloudBaseM:a.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:ii(a.cloudBaseM,e.cloudBaseM,t),relativeHumidity:a.relativeHumidity===void 0||e.relativeHumidity===void 0?void 0:ii(a.relativeHumidity,e.relativeHumidity,t),precipitationType:t<1?a.precipitationType:e.precipitationType,precipitationIntensity:ii(a.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:Sm(a.windDirectionDeg,e.windDirectionDeg,t),windSpeed:ii(a.windSpeed,e.windSpeed,t),storm:t<1?a.storm:e.storm}}class Bc{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?u2(i.weather,n.weather,c2((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 $r(this.keyframes)).at(e);if(!i)return t;const{type:n,intensity:s,character:r}=i,o=r>0?Math.min(1,s/r):n==="none"?0:1;return{...t,precipitationType:n,precipitationIntensity:r,precipitationAmount:o}}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 Bc;for(const i of e.keyframes)t.addKeyframe(i.t,{...Vu,...i.weather});return t}}class zc{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 zc;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 p2=["none","hum","whistle","rumble","crackle"],f2=100,m2={kind:"none",volume:0,pitchHz:f2},dh=[{id:"eye",name:"Naked eye",flare:0,projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",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",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",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",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",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",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}},{id:"phone-portrait",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}}];class Rt{static get default(){return dh[0]}static byId(e){return dh.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:Rt.UNAIDED_FIELD_DEG}static aspectOf(e){const t=e.frame;return t?t.widthMm/t.heightMm:Rt.UNAIDED_ASPECT}static frameWidthPx(e,t){return Math.round(t*Rt.aspectOf(e))}static availableAt(e){return e===void 0?dh:dh.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 LENS_FLARE_ARTIFACTS=1;static flareArtifactsOf(e){return e.flare??Rt.LENS_FLARE_ARTIFACTS}static starPointsOf(e){const t=e.apertureBlades;return t===void 0||t<3?0:t%2===0?t:t*2}}class lo extends Error{}class Wu{constructor(e){this.name=e}validate(e){return!0}}class Ty extends Wu{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new lo(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new lo(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class Ci{name;min;max;duration;subUnit;validator;constructor(e,t,i,n,s=new Ty(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 Iy{millisecond;second;minute;hour;day;month;year}class g2 extends Iy{}class Dy extends g2{millisecond=new Ci("millisecond",0,999,void 0);second=new Ci("second",0,59,this.millisecond);minute=new Ci("minute",0,59,this.second);hour=new Ci("hour",0,23,this.minute);day=new Ci("day",1,31,this.hour);month=new Ci("month",1,12,this.day);year=new Ci("year",0,9999,this.month)}const Ze=new Dy;class v2 extends Ty{constructor(e=1,t=12){super("month",e,t)}}class Zs{static instance=new Zs;render(e){return e.value.toString()}}class ln{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 Wu(`${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=Zs.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Yt{static#e=new Map;static register(e,t){Yt.#e.set(e,t)}static get(e){const t=Yt.#e.get(e);if(!t)throw new lo(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class Nd extends ln{constructor(e=new Date().getFullYear(),t=Ze.year){super(e,t)}static fromString(e,t=Yt.get(Nd)){return new Nd(t.parse(e))}}class lr extends Zs{static default=new lr("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class Fd extends ln{constructor(e=new Date().getMonth()+1,t=Ze.month){super(e,t)}static fromString(e,t=Yt.get(Fd)){return new Fd(t.parse(e))}toString(e=lr.default){return super.toString(e)}}class Ud extends ln{constructor(e=new Date().getDate(),t=Ze.day){super(e,t)}static fromString(e,t=Yt.get(Ud)){const i=t.parse(e);return new Ud(i)}toString(e=lr.default){return super.toString(e)}}class Bd extends ln{constructor(e=new Date().getHours(),t=Ze.hour){super(e,t)}static fromString(e,t=Yt.get(Bd)){return new Bd(t.parse(e))}toString(e=lr.default){return super.toString(e)}}class zd extends ln{constructor(e=new Date().getMinutes(),t=Ze.minute){super(e,t)}static fromString(e,t=Yt.get(zd)){return new zd(t.parse(e))}toString(e=lr.default){return super.toString(e)}}class Hd extends ln{constructor(e=new Date().getSeconds(),t=Ze.second){super(e,t)}static fromString(e,t=Yt.get(Hd)){return new Hd(t.parse(e),Ze.second)}toString(e=lr.default){return super.toString(e)}}class fo extends ln{static renderer=new lr("0",3);constructor(e,t=Ze.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=fo.renderer){return super.toString(e)}}class b2{render(e){return e.toString()}}class y2 extends b2{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?"-":"+",o=n.toString().padStart(2,"0"),l=s>0?":"+s.toString().padEnd(2,"0"):"";return r+o+l}}}class _l{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=Yt.get(_l),i=void 0){const n=t.parse(e,i);return new _l(n)}toString(e=new y2){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class sn{static timeshift(e,t){return e+(sn.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=sn.rule(t);if(!r)return!1;const o=sn.rank(i,n,s);return o>=sn.rank(r.start.month,r.start.day,2)&&o<sn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:sn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:sn.sunday(e,3,2)},end:{month:11,day:sn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:sn.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:sn.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,sn.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let o=s;for(;o+7<=r;)o+=7;return o}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 M2={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},w2={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},x2={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},S2={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},E2={name:"PT",timeshift:a=>sn.timeshift(-480,a),title:"Pacific Time (US)"},_2={name:"MT",timeshift:a=>sn.timeshift(-420,a),title:"Mountain Time (US)"},A2={name:"CT",timeshift:a=>sn.timeshift(-360,a),title:"Central Time (US)"},T2={name:"ET",timeshift:a=>sn.timeshift(-300,a),title:"Eastern Time (US)"},I2={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},D2={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},R2={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},C2={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},P2={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},L2={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},k2={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},O2={name:"Z",timeshift:"Z",title:"UTC"},N2={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},F2={name:"BST",timeshift:"+01",title:"British Summer Time"},U2={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},B2={name:"CET",timeshift:"+01",title:"Central European Time"},z2={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},H2={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},G2={name:"BJT",timeshift:"+08",title:"Beijing Time"},V2={name:"CST",timeshift:"-06",title:"Central Standard Time"},W2={name:"JST",timeshift:"+09",title:"Japan Standard Time"},X2={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},$2={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},Y2={name:"LST",timeshift:"?",title:"Local Sideral Time"},Lg=[L2,X2,P2,G2,F2,V2,D2,B2,U2,A2,I2,C2,R2,T2,N2,H2,W2,Y2,x2,z2,S2,_2,$2,w2,M2,E2,k2,O2];class Xu{static instance=new Xu;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 Sa extends lo{constructor(e="method is abstract"){super(e)}}class Em{units;constructor(e){this.units=e}newYear(e){throw new Sa}newMonth(e){throw new Sa}newDay(e){throw new Sa}newHour(e){throw new Sa}newMinute(e){throw new Sa}newSecond(e){throw new Sa}}class q2 extends Iy{millisecond=new Ci("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new Ci("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Ci("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new Ci("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new Ci("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new Ci("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new Ci("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const _m=new q2;class Am{static instance=new Am;render(e){const t=La.toSpec(e);let i="P";const n=t.years;n&&(i+=n.toString()+"Y");const s=t.months;s&&(i+=s.toString(Zs.instance)+"MM");const r=t.days;r&&(i+=r.toString(Zs.instance)+"D");const o=t.hours;o&&(i+=o.toString(Zs.instance)+"H");const l=t.minutes;l&&(i+=l.toString(Zs.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(Zs.instance)+"S"),i}}class La extends ln{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*Ze.year.duration:0)+(e.months?e.months*Ze.month.duration:0)+(e.days?e.days*Ze.day.duration:0)+(e.hours?e.hours*Ze.hour.duration:0)+(e.minutes?e.minutes*Ze.minute.duration:0)+(e.seconds?e.seconds*Ze.second.duration:0)},new Ci("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=Z2){let i=typeof e=="number"?e:e.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/Ze.year.duration,o=Math.floor(r);o>0&&(s.years=t.newYear(n*o),i-=o*Ze.year.duration);const l=i/Ze.month.duration,c=Math.floor(l);c>0&&(s.months=t.newMonth(n*c),i-=c*Ze.month.duration);const h=i/Ze.day.duration,d=Math.floor(h);d>0&&(s.days=t.newDay(n*d),i-=d*Ze.day.duration);const u=i/Ze.hour.duration,p=Math.floor(u);p>0&&(s.hours=t.newHour(n*p),i-=p*Ze.hour.duration);const f=i/Ze.minute.duration,g=Math.floor(f);g>0&&(s.minutes=t.newMinute(n*g),i-=g*Ze.minute.duration);const m=i/Ze.second.duration,v=Math.floor(n*m);return v>0&&(s.seconds=t.newSecond(v)),s}static fromString(e,t=Yt.get(La)){return new La(t.parse(e))}static between(e,t){const i=t.getTime(),n=e.getTime();return new La(i-n)}toSpec(){return La.toSpec(this)}toString(e=Am.instance){return e.render(this)}}class Ry extends Em{constructor(e){super(e)}newYear(e){return new Nd(e,this.units.year)}newMonth(e){return new Fd(e,this.units.month)}newDay(e){return new Ud(e,this.units.day)}newHour(e){return new Bd(e,this.units.hour)}newMinute(e){return new zd(e,this.units.minute)}newSecond(e){return new Hd(e,this.units.second)}newMillisecond(e){return new fo(e,this.units.millisecond)}newTimeshift(e){return new _l(typeof e=="number"?e:e.value)}}const K2=new Ry(Ze),Z2=new Ry(_m);class ws{#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:ws.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 ln?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 ln?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 ln?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 ln?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 ln?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 ln?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 ln)?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 _l)?this.factory.newTimeshift(e):e}get factory(){return K2}static fromString(e,t=Yt.get(ws)){const{year:i,month:n,day:s,hour:r,minute:o,second:l,millisecond:c,timeshift:h}=t.parse(e);return new ws({year:i,month:n,day:s,hour:r,minute:o,second:l,millisecond:c,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new ws({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:ws.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return ws.fromString(i)}#l(e){if(this.constructor.name!==e.constructor.name)throw new Wu(`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 La(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 ws(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=Xu.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 o=this.second?.toSpec();o&&(e.second=o);const l=this.millisecond?.toSpec();l&&(e.millisecond=l);const c=this.timeshift?.toSpec();return c&&(e.timeshift=c),e}toJSON(){return this.toSpec()}}class ih extends Zs{static instance=new ih(lr.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 mo extends ln{#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=ih.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class Cy extends Dy{year=new Ci("year",-9999,9999,this.month);yearExtended=new Ci("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const bd=new Cy;class ka extends mo{constructor(e,t=bd.year){super(e,t)}static fromString(e,t=bd.year,i=Yt.get(ka)){const n=i.parse(e),s=n.value.start;if(e.startsWith("Y")&&(t=bd.yearExtended),s!==void 0){const r=new ka(Object.assign({...n},{value:Math.max(s,t.min)})),o=new ka(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:o}}else return new ka(n,t)}}class Py extends Wu{monthValidator=new v2;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class Oa extends mo{constructor(e,t=new Ci(Ze.month.name,1,24,Ze.day,new Py)){super(e,t)}static fromString(e,t=Yt.get(Oa)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=Ze.month;const r=new Oa(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Oa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Oa(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Na extends mo{constructor(e,t=Ze.day){super(e,t)}static fromString(e,t=Yt.get(Na)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=Ze.day;const r=new Na(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Na(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Na(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Fa extends mo{constructor(e,t=Ze.hour){super(e,t)}static fromString(e,t=Yt.get(Fa)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=Ze.hour;const r=new Fa(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Fa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Fa(i)}}class Ua extends mo{constructor(e,t=Ze.minute){super(e,t)}static fromString(e,t=Yt.get(Ua)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.minute,r=new Ua(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ua(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ua(i)}toString(e=ih.instance){return super.toString(e)}}class Ba extends mo{constructor(e,t=Ze.second){super(e,t)}static fromString(e,t=Yt.get(Ba)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.second,r=new Ba(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ba(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ba(i)}}class Al extends _l{static fromString(e,t=Yt.get(Al),i=void 0){return new Al(t.parse(e,i))}}class Ly extends Em{constructor(e){super(e)}newYear(e){return new ka(e,this.units.year)}newMonth(e){return new Oa(e,this.units.month)}newDay(e){return new Na(e,this.units.day)}newHour(e){return new Fa(e,this.units.hour)}newMinute(e){return new Ua(e,this.units.minute)}newSecond(e){return new Ba(e,this.units.second)}newMillisecond(e){return new fo(e,this.units.millisecond)}newTimeshift(e){return new Al(typeof e=="number"?e:e.value)}}const j2=new Ly(bd);new Ly(_m);class _a extends ws{constructor(e){super(e)}get factory(){return j2}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 _a({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:ws.timeshiftOf(e)})}static fromString(e,t=Yt.get(_a)){const i=t.parse(e);return new _a(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return _a.fromString(i)}clone(){return new _a(this.toSpec())}}class Ul extends mo{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 J2 extends Cy{year=new Ci("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Hf=new J2;class za extends Ul{constructor(e,t=Hf.year){super(e,t)}static fromString(e,t=Hf.year,i=Yt.get(za)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new za(Object.assign({...n},{value:Math.max(s,t.min)})),o=new za(Object.assign({...n},{value:Math.min(n.value.end,t.max)})),l={start:r,end:o},c=n.value.estimate;return c&&(l.estimate=c),l}else return new za(n)}}class Q2 extends Py{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 Ha extends Ul{constructor(e,t=new Ci(Ze.month.name,1,41,Ze.day,new Q2)){super(e,t)}static fromString(e,t=Yt.get(Ha)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.month,r=new Ha(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ha(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ha(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Ga extends Ul{constructor(e,t=Ze.day){super(e,t)}static fromString(e,t=Yt.get(Ga)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.day,r=new Ga(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ga(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ga(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Va extends Ul{constructor(e,t=Ze.hour){super(e,t)}static fromString(e,t=Yt.get(Va)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.hour,r=new Va(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Va(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Va(i)}}class Wa extends Ul{constructor(e,t=Ze.minute){super(e,t)}static fromString(e,t=Yt.get(Wa)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.minute,r=new Wa(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Wa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Wa(i)}}class Xa extends Ul{constructor(e,t=Ze.second){super(e,t)}static fromString(e,t=Ze.second,i=Yt.get(Xa)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new Xa(Object.assign({...n},{value:Math.max(s,t.min)})),o=new Xa(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:o}}else return new Xa(n,t)}}class ky extends Al{}class ex extends ih{qualifier(){return""}}class Yr extends Xu{static instance=new Yr;static valueRenderer=new ex(lr.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=Yr.names.slice(Yr.names.indexOf(t)+1).map(o=>e[o]).filter(Boolean),s=Yr.qualifier(i.uncertainComponent,i.approximateComponent),r=Yr.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(o=>o.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(o=>o.approximate));return s+i.toString(Yr.valueRenderer)+r}}class Oy extends Em{constructor(e){super(e)}newYear(e){return new za(e,this.units.year)}newMonth(e){return new Ha(e,this.units.month)}newDay(e){return new Ga(e,this.units.day)}newHour(e){return new Va(e,this.units.hour)}newMinute(e){return new Wa(e,this.units.minute)}newSecond(e){return new Xa(e,this.units.second)}newMillisecond(e){return new fo(e,this.units.millisecond)}newTimeshift(e){return new ky(typeof e=="number"?e:e.value)}}const tx=new Oy(Hf);new Oy(_m);class Aa extends _a{constructor(e){super(e)}toString(e=Yr.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 tx}static fromDate(e){return new Aa({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:ws.timeshiftOf(e)})}static fromString(e,t=Yt.get(Aa)){const i=t.parse(e);return new Aa(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Aa.fromString(i)}clone(){return new Aa(this.toSpec())}}class $u{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new lo(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Sa(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class Tm extends $u{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return Tm.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new lo(`${this.name} cannot be negative`);return super.parse(e)}}class ae{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 ae.optional(ae.group(e,...t))}static optionalNonCapturingGroup(...e){return ae.optional(ae.nonCapturingGroup(...e))}static numberGroup(e,t,i,n="\\d"){return ae.group(e,`${i||""}[${n}]${t}`)}}const kg="timeshiftValue",Og="shiftHour",Ng="shiftMinute";class Im extends $u{static format(e=""){return Lg.map(t=>t.name).join("|")+"|"+ae.nonCapturingGroup(ae.group(e+Og,ae.numberGroup(ae.groupName(e,kg),"{2}","[+-]")),ae.optionalNonCapturingGroup(":?",ae.numberGroup(ae.groupName(e,Ng),"{2}",void 0)))}constructor(){super(kg,Im.format())}parse(e,t){let i=0;const n=Lg.find(s=>s.name===e);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(t??{})}catch(s){throw new lo(`The time zone ${e} depends on the date: ${s.message}`)}e=n.timeshift}if(e!=="Z"){const s=this.regexGroups(e),r=s[Og];r&&(i+=parseInt(r,10)*60);const o=s[Ng];o&&(i+=parseInt(o,10))}return i}}class di extends Tm{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=di.uncertainGroup+di.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return ae.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(ae.groupName(di.uncertainGroup,e),"?")+this.qualifierFormat(ae.groupName(di.approximateGroup,e),"~")+this.qualifierFormat(ae.groupName(di.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return ae.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[ae.groupName(di.uncertainAndApproximateGroup,this.name)],o=e[ae.groupName(di.approximateGroup,this.name)]||r,l=e[ae.groupName(di.uncertainGroup,this.name)]||r;return{value:n,approximate:o?!!o:!1,uncertain:l?!!l:!1}}}const Fg="yearValue";class Gd extends di{constructor(){super(Fg,Gd.format())}static format(e=""){return"Y?"+di.numberFormat(ae.groupName(e,Fg),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const Ug="monthValue";class Vd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Ug),"{1,2}",void 0)}constructor(){super(Ug,Vd.format())}}const Bg="dayValue";class Wd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Bg),"{1,2}",void 0)}constructor(){super(Bg,Wd.format())}}const zg="hourValue";class Xd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,zg),"{1,2}",void 0)}constructor(){super(zg,Xd.format())}}const Hg="minuteValue";class $d extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Hg),"{1,2}",void 0)}constructor(){super(Hg,$d.format())}}const Gg="secondValue";class Yd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Gg),"{1,2}",void 0)}constructor(){super(Gg,Yd.format())}}class qd extends Im{}class Li extends $u{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=Li.format()){super("date",e)}static format(e=""){return ae.group(ae.groupName(e,Li.yearGroup),Gd.format(e))+ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,Li.monthGroup),Vd.format(e)),ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,Li.dayGroup),Wd.format(e)),ae.optionalNonCapturingGroup("[T ]",ae.group(ae.groupName(e,Li.hourGroup),Xd.format(e)),":",ae.group(ae.groupName(e,Li.minuteGroup),$d.format(e)),ae.optionalNonCapturingGroup(":",ae.group(ae.groupName(e,Li.secondGroup),Yd.format(e)),ae.optionalNonCapturingGroup("[.,]",ae.group(ae.groupName(e,Li.millisecondGroup),"\\d+"))),ae.optionalGroup(ae.groupName(e,Li.timeshiftGroup),qd.format(e)))))}parseGroups(e){const t=e[Li.millisecondGroup],i=t?fo.parseFraction(t):void 0,n=e[Li.secondGroup],s=n?Ba.fromString(n,new Yd):void 0,r=e[Li.minuteGroup];let o;r&&(o=Ua.fromString(r,new $d),o.uncertain=o.uncertain||s?.uncertain||!1,o.approximate=o.approximate||s?.approximate||!1);const l=e[Li.hourGroup];let c;l&&(c=Fa.fromString(l,new Xd),c.uncertain=c.uncertain||o?.uncertain||!1,c.approximate=c.approximate||o?.approximate||!1);const h=e[Li.dayGroup];let d;h&&(d=Na.fromString(h,new Wd),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[Li.monthGroup];let p;u&&(p=Oa.fromString(u,new Vd),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[Li.yearGroup];let g;f&&(g=ka.fromString(f,void 0,new Gd),g.uncertain=g.uncertain||p?.uncertain||!1,g.approximate=g.approximate||p?.approximate||!1);const m=e[Li.timeshiftGroup],v=m?Al.fromString(m,new qd,{year:g?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:g,month:p,day:d,hour:c,minute:o,second:s,millisecond:i,timeshift:v}}}class _i extends di{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=_i.uncertainGroup+_i.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(ae.groupName(_i.uncertainGroup,e),"?")+this.qualifierFormat(ae.groupName(_i.approximateGroup,e),"~")+this.qualifierFormat(ae.groupName(_i.uncertainAndApproximateGroup,e),"%")+di.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[ae.groupName(_i.uncertainAndApproximateGroup,this.name)];return(e[ae.groupName(_i.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[ae.groupName(_i.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const Vl="yearValue",Vg="exp",Wg="signif";class Kd extends _i{constructor(){super(Vl,Kd.format())}static format(e=""){return"Y?"+ae.nonCapturingGroup(ae.group(ae.groupName(e,Vg),"[-]?\\d+E\\d+")+"|"+_i.numberFormat(ae.groupName(e,Vl),"+","[-]?")+ae.optionalGroup(ae.groupName(e,Wg),"S\\d+"))}parseGroups(e){const t=e[Vg];if(t){const r=t.indexOf("E"),o=parseInt(t.substring(r+1),10),c=parseInt(t.substring(0,r),10)*Math.pow(10,o);e[Vl]=c.toString()}const i=e[Wg],n=e[Vl];if(i){const r=parseInt(i.substring(1),10),{valueStr:o,sign:l}=this.getValueAndSign(e);let c="";for(let h=0;h<o.length;h++)c+=h<r?o.charAt(h):"X";e[Vl]=(l<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 Xg="monthValue";class Zd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,Xg),"{1,2}",void 0)}constructor(){super(Xg,Zd.format())}}const $g="dayValue";class jd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,$g),"{1,2}",void 0)}constructor(){super($g,jd.format())}}const Yg="hourValue";class Jd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,Yg),"{1,2}",void 0)}constructor(){super(Yg,Jd.format())}}const qg="secondValue";class Qd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,qg),"{1,2}",void 0)}constructor(){super(qg,Qd.format())}}const Kg="minuteValue";class eu extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,Kg),"{1,2}",void 0)}constructor(){super(Kg,eu.format())}}class ix extends qd{}class ki extends $u{static yearGroup=Li.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",ki.format())}static format(e=""){return ae.group(ae.groupName(e,ki.yearGroup),Kd.format(e))+ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,ki.monthGroup),Zd.format(e)),ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,ki.dayGroup),jd.format(e)),ae.optionalNonCapturingGroup("[T ]",ae.group(ae.groupName(e,ki.hourGroup),Jd.format(e)),":",ae.group(ae.groupName(e,ki.minuteGroup),eu.format(e)),ae.optionalNonCapturingGroup(":",ae.group(ae.groupName(e,ki.secondGroup),Qd.format(e)),ae.optionalNonCapturingGroup("[.,]",ae.group(ae.groupName(e,ki.millisecondGroup),"\\d+"))),ae.optionalGroup(ae.groupName(e,ki.timeshiftGroup),ix.format(e)))))}parseGroups(e){const t=e[ki.millisecondGroup],i=t?fo.parseFraction(t):void 0,n=e[ki.secondGroup];let s;n&&(s=Xa.fromString(n,void 0,new Qd),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=e[ki.minuteGroup];let o;r&&(o=Wa.fromString(r,new eu),o.uncertain=o.uncertain||s?.uncertain||!1,o.approximate=o.approximate||s?.approximate||!1);const l=e[ki.hourGroup];let c;l&&(c=Va.fromString(l,new Jd),c.uncertain=c.uncertain||o?.uncertain||!1,c.approximate=c.approximate||o?.approximate||!1);const h=e[ki.dayGroup];let d;h&&(d=Ga.fromString(h,new jd),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[ki.monthGroup];let p;u&&(p=Ha.fromString(u,new Zd),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ki.yearGroup];let g;f&&(g=za.fromString(f,void 0,new Kd),g.uncertain=g.uncertain||p?.uncertain||!1,g.approximate=g.approximate||p?.approximate||!1);const m=e[ki.timeshiftGroup],v=m?ky.fromString(m,new qd,{year:g?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:g,month:p,day:d,hour:c,minute:o,second:s,millisecond:i,timeshift:v}}}const Ny=["spring","summer","autumn","winter"],Gf=21,nx=32,sx=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let rx;function ax(){return rx??=new ki}function yo(a){return typeof a?.value=="number"?a.value:void 0}function yd(a){const e=a.trim();if(/^\d{1,2}:/.test(e)){const r=sx.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=Aa.fromString(e,ax())}catch{return}const i=yo(t.year),n=yo(t.month),s=n!==void 0&&n>=Gf&&n<=nx;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:Ny[(n-Gf)%4]}:{},day:yo(t.day),hour:yo(t.hour),minute:yo(t.minute),second:yo(t.second),raw:e}}function cl(a){if(a.raw!==void 0)return a.raw;if(a.year===void 0){if(a.hour===void 0)return"";let t=`${String(a.hour).padStart(2,"0")}:${String(a.minute??0).padStart(2,"0")}`;return a.second!==void 0&&(t+=`:${String(a.second).padStart(2,"0")}`),t}let e=String(a.year).padStart(4,"0");return a.season!==void 0?`${e}-${Gf+Ny.indexOf(a.season)}`:(a.month===void 0||(e+=`-${String(a.month).padStart(2,"0")}`,a.day===void 0)||(e+=`-${String(a.day).padStart(2,"0")}`,a.hour===void 0)||(e+=`T${String(a.hour).padStart(2,"0")}:${String(a.minute??0).padStart(2,"0")}`,a.second!==void 0&&(e+=`:${String(a.second).padStart(2,"0")}`)),e)}function Vf(a){if(a.year!==void 0)return Date.UTC(a.year,(a.month??1)-1,a.day??1,a.hour??0,a.minute??0,a.second??0)}function Zg(a){return(((a.day??0)*24+(a.hour??0))*60+(a.minute??0))*6e4+(a.second??0)*1e3}const ox=["year","month","day","hour","minute"],lx=["day","hour","minute"];function jg(a,e){return e.filter(t=>a[t]!==void 0).join(",")}function Tl(a){if(a.durationSeconds!==void 0)return a.durationSeconds*1e3;const e=a.durationText===void 0?void 0:bn.parse(a.durationText);if(e)return e.chosenSeconds*1e3;if(!a.time||!a.endTime)return;const t=a.time.year!==void 0&&a.endTime.year!==void 0,i=t?ox:lx,n=jg(a.time,i);if(!(n===""||n!==jg(a.endTime,i)))return t?Vf(a.endTime)-Vf(a.time):Zg(a.endTime)-Zg(a.time)}function cx(a){if(a.durationSeconds===void 0&&!(!a.time||!a.endTime))return Tl(a)===void 0?"imprecise":void 0}class Yu{constructor(e,t,i,n,s,r,o,l,c=[],h,d,u,p=[],f=[],g=[],m=[]){this.event=e,this.timeline=t,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=o,this.weather=l,this.decor=c,this.weatherSource=h,this.instrumentId=d,this.exposureSeconds=u,this.milestones=p,this.references=f,this.roads=g,this.traces=m}provenance=wn.empty();loadIssues=[];account;sources;interpretation;sway;lightPollution;observerMap;iso;vehicle;get observerCount(){return 1+this.decor.filter(e=>e.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return Rt.byId(this.instrumentId)}static create(e,t,i){return new Yu({eventType:"sighting",time:e,place:t},new Gu,new Uc,new Bc,new zc,i)}}const hx=0,dx=0;function at(a,e){const t=a.observerTrack.getInterpolatedPoseAt(e);if(t)return t;const i=a.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:hx,headingDeg:void 0,pitchDeg:dx,fovDeg:Rt.fieldOfViewDeg(a.instrument)}}function hi(a,e){return a.weatherTrack.getInterpolatedWeatherAt(e)??a.weather??Vu}function uh(a,e){return a.weatherTrack.getActualWeatherAt(e)??a.weather??Vu}function Dm(a,e){return a.soundTrack.getInterpolatedSoundAt(e)??m2}class tu{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Es.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;static around(e,t,i,n,s){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Es.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},l=new tu(o,new URL("case.json",s).href),c=l.tracks[0];return c.recording=e,c.base={url:n},l.caseChanged=!0,l}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat();return this.tracks.find(i=>i.kind==="observer"&&i.recording?.id!==void 0&&t.includes(i.recording.id))??this.tracks.find(i=>i.kind==="observer")}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)}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))}markExported(e){if(this.caseChanged=!1,!!e)for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording))}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}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$/,""),o=new Set(this.tracks.map(A=>A.event.url)),l=new Set(this.tracks.map(A=>A.recording?.id));let c=this.tracks.filter(A=>A.kind==="reading").length+1;for(;o.has(`interpretation-${r}-${c}.json`)||l.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:g,description:m,sources:v,tags:x,timeline:y,milestones:b,interpretation:w,...S}=structuredClone(s),_={version:1,id:`${s.id??r}-interpretation-${c}`,...S,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},M={type:"event",eventType:"sighting",interpretationOf:s.id??r,time:t,...n!==void 0&&n.length>0?{by:n}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],M],this.caseChanged=!0;const T={event:M,url:new URL(M.url,this.url).href,kind:"reading",recording:_};return this.tracks.push(T),T}idsOf(e){return e.recording?.id!==void 0?[e.recording.id]:[]}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(g=>g.event.url)),r=new Set(this.tracks.map(g=>g.recording?.id)),o=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",l=n?"interpretation":"observer";let c=`${l}-${o}.json`,h=e.id??o;for(let g=2;s.has(c)||r.has(h);g++)c=`${l}-${o}-${g}.json`,h=`${e.id??o}-${g}`;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:n.account.recording?.id??h}:{},...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),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)+`
|
|
3
3
|
`}));return[{path:decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",content:JSON.stringify(this.json,null,2)+`
|
|
4
4
|
`},...s]}}class Gn{constructor(e,t,i,n="en"){this.parts=e,this.messages=t,this.onChange=i,this.locale=n,this.setMessages(t),e.text.addEventListener("input",()=>{this.readText(),this.showDeduction()}),e.picker.addEventListener("change",()=>this.writeFromPicker()),e.mode.addEventListener("click",()=>this.setPrecise(!this.precise)),e.text.addEventListener("blur",()=>this.validate()),e.text.addEventListener("focus",()=>this.showDeduction())}precise=!0;hint="";get isPrecise(){return this.precise}setMessages(e,t=this.locale){this.messages=e,this.locale=t,e.edtfPlaceholder!==void 0&&(this.parts.text.placeholder=e.edtfPlaceholder),this.parts.mode.title=e.edtfModeTitle,this.parts.mode.setAttribute("aria-label",e.edtfModeTitle),this.setPrecise(this.precise)}setPrecise(e){this.precise=e,this.parts.picker.hidden=!e,this.parts.text.hidden=e,this.parts.mode.textContent=e?this.messages.datePrecise:this.messages.dateEdtf,this.parts.mode.setAttribute("aria-pressed",String(!e)),this.parts.help&&(this.parts.help.hidden=e),this.showDeduction()}set(e){const{text:t,picker:i}=this.parts;t.value=e?cl(e):"",i.step=Gn.stepFor(e),i.value=Gn.pickerValueOf(e),t.setCustomValidity(""),t.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...e){return e.every(t=>t===void 0||Gn.isPickable(t)&&Gn.qualifierOf(cl(t))==="")}static isPickable(e){return!!e&&e.year!==void 0&&e.month!==void 0&&e.day!==void 0&&e.hour!==void 0&&e.minute!==void 0}static pickerValueOf(e){if(!Gn.isPickable(e))return"";const t=(n,s=2)=>String(n).padStart(s,"0"),i=e.second?`:${t(e.second)}`:"";return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}T${t(e.hour)}:${t(e.minute)}${i}`}static stepFor(e){return e?.second?"1":"60"}static qualifierOf(e){const t=/[?%]/.test(e),i=/[~%]/.test(e);return t&&i?"%":t?"?":i?"~":""}describe(e){return Gn.describeTime(e,this.messages,this.locale)}static describeTime(e,t,i){const n=cl(e),s=Gn.qualifierOf(n),r=h=>String(h).padStart(2,"0"),o=[];if(e.season!==void 0){const h={spring:t.timeSeasonSpring,summer:t.timeSeasonSummer,autumn:t.timeSeasonAutumn,winter:t.timeSeasonWinter}[e.season];o.push(e.year!==void 0?`${h} ${e.year}`:h)}else if(e.year!==void 0){const h=e.day!==void 0?{...e.year>=1583?{weekday:"long"}:{},year:"numeric",month:"long",day:"numeric"}:e.month!==void 0?{year:"numeric",month:"long"}:{year:"numeric"},d=new Date(Date.UTC(e.year,(e.month??1)-1,e.day??1));o.push(new Intl.DateTimeFormat(i,{...h,timeZone:"UTC"}).format(d))}e.hour!==void 0&&o.push(`${r(e.hour)}:${r(e.minute??0)}${e.second!==void 0?`:${r(e.second)}`:""}`);const l=o.join(", "),c=s==="~"?t.timeQualifierApproximate:s==="?"?t.timeQualifierUncertain:s==="%"?t.timeQualifierBoth:"";return c?`${l} — ${c.toLowerCase()}`:l}setHint(e){this.hint=e,this.showDeduction()}showDeduction(){const{text:e}=this.parts,t=e.value.trim();if(this.precise||t===""){e.title=this.hint;return}const i=yd(t);e.title=i?`→ ${this.describe(i)}`:this.messages.edtfInvalid}readText(){const e=this.parts.text.value.trim();if(e===""){this.clean(),this.onChange(void 0);return}const t=yd(e);t&&(this.clean(),this.onChange(t))}clean(){this.parts.text.setCustomValidity(""),this.parts.text.classList.remove("invalid")}writeFromPicker(){const{picker:e,text:t}=this.parts;e.value===""&&e.validity.badInput||(t.value=e.value===""?"":e.value.replace(/\.\d+$/,""),this.readText())}validate(){const{text:e}=this.parts,t=e.value.trim();t===""||yd(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}}const ux={color:"Color",transparency:"Transparency",halo:"Halo",blur:"Blur",brightness:"Brilliance",shapeTitle:"Name",utcOffset:"Time zone",cloudBase:"Cloud base",elevation:"Altitude",heightAboveGround:"Height above ground",duration:"Duration",placeName:"Place",latitude:"Latitude",longitude:"Longitude",heading:"Heading",pitch:"Tilt",roll:"Roll",sway:"Sway at rest",swayTitle:"How much the body holding the instrument moves the view when not walking: 1 for a person standing, 0 for a tripod. Blank: 1 (0 if the account says the observer was paralysed)",lightPollution:"Night sky",lightPollutionTitle:'The zenith of a moonless night at this place, in magnitudes per square arcsecond, as a Sky Quality Meter reads it or as the World Atlas of artificial sky brightness (Falchi et al. 2016, lightpollutionmap.info, "SQM") gives it. 22 is a natural sky; a suburb is about 19, a city centre 17. Blank: a natural sky',observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Observer info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",timeSeasonSpring:"Spring",timeSeasonSummer:"Summer",timeSeasonAutumn:"Autumn",timeSeasonWinter:"Winter",summaryGroups:{observation:"Observation",location:"Position",temporal:"Time",weather:"Weather",sound:"Sound"},summaryGroup:"Summary",summaryDescription:"Description",closeDescription:"Close the description",observerGroup:"Observer",observerId:"ID",observerTitle:"Title",observerLastName:"Last name",observerFirstNames:"First names",sightingId:"ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",filter:"In front of it",filterNone:"nothing",filterSolarVisual:"a solar filter for the eye (eclipse glasses, density 5)",filterSolarPhoto:"a solar film for a camera (density 3.8)",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorShrub:"Shrub",decorBridge:"Bridge",decorWire:"Overhead line",decorCrop:"Crop row",decorTerrace:"Terrace (restanque)",decorMound:"Stone heap",decorStreetlight:"Streetlight",decorVehicle:"Vehicle",decorObserver:"Other observer",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",goToMilestone:"Go to this moment",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelNone:"Built-in shape",decorModelDefault:"Default model",decorModelAdvanced:"Model from an address",decorModelFromCatalogue:"From the catalogue, which the recording names it by. Change a field and it becomes this recording's own address.",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorFloors:"Floors",decorOccupiedFloor:"Occupied floor",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorWindows:"Windows",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},Il={...ux,oval:"Oval",polygon:"Polygon",addVertex:"Add vertex",deleteVertex:"Delete vertex",notAPolygon:"Select a single polygon shape",tooFewVertices:"A shape needs at least 3 points",shape:"Shape",apparentWidth:"Apparent width",realWidth:"Real width",distance:"Distance",sizeLock:"Hold",lockNone:"nothing",lockApparent:"the apparent width",lockReal:"the real width",lockDistance:"the distance",apparentSize:"{moons}× the Moon",utcOffsetPlaceholder:"from longitude",realSizeBetween:"The scene bounds that width: between {min} and {max} m, from what it crosses",realSizeAtLeast:"The scene bounds that width: at least {min} m, from what it passes behind",realSizeAtMost:"The scene bounds that width: at most {max} m, from what it passes in front of",realSizeUnknown:"Nothing in the scene bounds that width: it is only what the distance implies",realSizeOutside:" — the width above is outside that",blurBound:"Blurred through this lens: nearer than {max} m",blurBoundNoInstrument:"Blur through the naked eye bounds no distance — an eye has no aperture to be out of focus with",blurBoundNotAtInfinity:"Blur bounds a distance only for a lens focused at infinity: this one is focused at {focus} m, which blurs on both sides of it",realSizeContradiction:"Contradiction: the declared crossings cannot all be true",realDistanceHere:" — i.e. between {min} and {max} m here",clearDistanceHypothesis:"Withdraw the distance hypothesis",clearDistanceHypothesisTitle:"Back to what the recording establishes",depthStated:"Drawn at {m} m, as the recording states",depthHypothesis:"Drawn at {m} m: your hypothesis — what the decor hides of it is what a thing that far would lose",depthDerived:"Drawn at {m} m, from the observer's own walk",depthBounded:"Drawn at {m} m, from what it passes behind and in front of",depthConventional:"Drawn at {m} m by convention: nothing in the recording establishes a distance",addShape:"Add shape",deleteShape:"Delete shape",play:"Play",pause:"Pause",noDuration:"No observation duration",previousKeyframe:"Previous keyframe",nextKeyframe:"Next keyframe",keyframeMark:"Keyframe",shapesTrack:"shapes",observerTrack:"observer",weatherTrack:"weather",soundTrack:"sound",group:"Group",ungroup:"Ungroup",bringToFront:"Bring to front",sendToBack:"Send to back",contextMenuDelete:"Delete",onlyOneShape:"There is only one shape",alreadyAtFront:"This shape is already at the front",alreadyAtBack:"This shape is already at the back",needTwoShapesToGroup:"Select at least two shapes to group them",notGrouped:"This shape isn't part of a group",multipleShapesSelected:"Multiple shapes selected — select just one to edit this",samplingRate:"Sampling rate",currentPosition:"Current position",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",durationPlaceholder:"observation length",durationImprecise:"These dates don't precisely enough determine a duration — enter it manually.",export:"Save",importFile:"Load JSON file",importUrl:"Or load from URL",importUrlPlaceholder:"https://…/sighting.json",importButton:"Load",importError:"Couldn't load that recording — check the file or URL and try again.",importErrorCors:'That address answers, but the browser is not allowed to read it from this page. The file itself is fine — its server needs to send the header "Access-Control-Allow-Origin: *" with it. If it is not your server, that is what to ask its administrator for.',importErrorMixedContent:"A secure page cannot load an address starting with http://. Use https:// if that server offers it.",importErrorUnreachable:"Nothing answered at that address. Check the spelling, and that you are online.",importErrorStatus:"That server answered with an error ({status}). The address is probably wrong, or the file has moved.",importErrorMalformed:"That address answered, but what came back is not a recording.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",sourceAircraft:"Air traffic",placeNamePlaceholder:"Valensole, France",searchPlace:"Locate",placeMatch:"Matches",placeSearching:"Looking up the place…",placeMatchFound:"place found",placeMatchesFound:"places found",placeNotFound:"No place by that name",placeSearchFailed:"Place search temporarily unavailable",utcOffsetNoZone:"No time zone reads this offset on that day",utcOffsetImplausible:"This time zone doesn't match the longitude entered, whose own solar time is UTC{solar} — yet the scene and the weather record both obey what is declared here. Clear the field to derive it from the longitude.",timeZoneManual:"unknown",altitudeAboveSeaLevel:"The observer's altitude above sea level — the ground at the location entered sets its floor: an observer in the Alps is not at 0 m.",groundAt:"ground at {m} m",headingPlaceholder:"unknown",edtfInvalid:"Not a valid EDTF date/time (e.g. 1965-07-01T05:00, 2025-06?, 2025~).",edtfPlaceholder:"YYYY-MM-DDThh:mm[?~%] or hh:mm",observationTimeHint:"EDTF — e.g. 1965-07-01T05:00, 2025-06? (uncertain), 2025~ (approximate), or just 05:00 if the date isn't known",observationEndTimeHint:"EDTF — e.g. 1965-07-01T05:10, 2025-06? (uncertain), 2025~ (approximate), or just 05:10 if the date isn't known",presetsGroupLabel:"UFO shape",description:"Description",tagsPlaceholder:"comma-separated",weather:"Weather",shapeGroup:"Phenomenon",shapesSubgroup:"Shapes",bodiesSubgroup:"Bodies",soundGroup:"Sound",temporalGroup:"Time",fileGroup:"File",fileLoading:"Loading the editor…",fileEditorLabel:"The recording as JSON text",timeQualifierExact:"Exact",durationPrecise:"precise",durationIso:"EDTF",durationModeTitle:"Say the length exactly, or as stated: about, between two lengths",durationInvalid:"Not a duration: PT10M, PT1H30M, PT5M/PT10M…",durationHelpTitle:"What the text takes (EDTF)",durationHelpLines:`PT45S — 45 seconds
|
|
5
5
|
PT10M — 10 minutes
|
|
@@ -2800,7 +2800,7 @@ canvas[data-cursor="rotate"] {
|
|
|
2800
2800
|
`;class ul{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 ul(t)}static TRAVEL_M=50;get travels(){return this.spanM>ul.TRAVEL_M}get moved(){return this.spanM>ul.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(ci(t,e.east,t,e.west).x),Math.abs(ci(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:Zn(0,-s,i,n).lat,south:Zn(0,s,i,n).lat,east:Zn(s,0,i,n).lng,west:Zn(-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 ts{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)>ts.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new ts(Math.max(1-(e.instrument.stabilization??0),ts.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,o,l,c,h]=ts.HZ;return{eastM:i*ts.SWAY_M*(.7*n(s,.3)+.3*n(l,1.9)),northM:i*ts.SWAY_M*(.6*n(o,2.2)+.4*n(c,.8)),upM:i*ts.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*ts.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(l,2.7)),pitchDeg:i*this.rotationPassed*ts.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(o,.4)),rollDeg:i*this.rotationPassed*ts.DRIFT_ROLL_DEG*n(s,2.9)}}}class Ft{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=ul.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],o=t.points[s],l=(o.t-r.t)/1e3;if(l<=0)continue;const c=ci(o.lat,o.lng,r.lat,r.lng),h=c.x,d=-c.z,u=Math.hypot(h,d),p=u/l,f=Ft.stepHzFor(p);i.push({startMs:r.t,endMs:o.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*l}for(let s=0;s<i.length;s++){const r=i[s-1],o=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=o===void 0||o.stepHz===0}if(i.some(s=>s.stepHz>0))return new Ft(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const n=Ft.of(e)?.offsetAt(t)??Ft.STILL;return i?n:Ft.add(n,ts.of(e)?.offsetAt(t))}static stepHzFor(e){return e<Ft.SLOWEST_WALK_M_PER_S||e>Ft.FASTEST_WALK_M_PER_S?0:Ft.REFERENCE_STEP_HZ*Math.pow(e/Ft.REFERENCE_SPEED_M_PER_S,Ft.CADENCE_EXPONENT)}offsetAt(e){return Ft.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/Ft.REFERENCE_SPEED_M_PER_S,n=(o,l,c,h)=>{if(o<0||o>Ft.JOLT_LASTS_MS)return;const d=o/1e3,u=Math.exp(-d/Ft.JOLT_DECAY_S)*Math.sin(2*Math.PI*Ft.JOLT_HZ*d),p=h*l*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,Ft.STOP_LURCH_M,Ft.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=t.rampsIn?n(e-t.startMs,Ft.START_LURCH_M,Ft.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(l=>e>=l.startMs&&e<=l.endMs);if(!t||t.stepHz===0)return Ft.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(t,e),r=Ft.SWAY_M*s*Math.cos(n/2),o=s*this.rotationPassed*t.speedMPerS/Ft.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:Ft.RISE_M_PER_M_PER_S*t.speedMPerS*s*Math.cos(n),rollDeg:Ft.HEAD_ROLL_DEG*o*Math.cos(n/2),pitchDeg:-1.25*o*Math.cos(n),yawDeg:Ft.HEAD_YAW_DEG*o*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,o=Math.min(e.rampsIn?s/n:1,e.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(o,0)))/2}}class Vx{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 to{static sessionDeclared=!1;static unlock(e){if(to.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(!(to.sessionDeclared||typeof navigator>"u")){to.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const uv=.05,pv=.08,fv=2,mv=3,Wx=14,Xx=.02;class $x{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}}to.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,uv);for(const{param:s,ratio:r}of e.pitch)s.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),n,uv)}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 o=e.createGain();return o.gain.value=0,r.connect(o).connect(s.gain),i.connect(n).connect(s).connect(this.output(e)),i.start(),r.start(),{key:t,nodes:[n,s,o],sources:[i,r],volumeParam:o.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(l){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",l);return}if(i!==this.voiceToken||!this.context)return;const r=n.createBufferSource();r.buffer=s,r.loop=!0;const o=n.createGain();o.gain.value=0,r.connect(o).connect(this.output(n)),r.start(),this.voice={key:t,nodes:[o],sources:[r],volumeParam:o.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*fv),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*fv),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*mv),e.sampleRate),i=t.getChannelData(0),n=Math.max(1,Math.floor(Xx*e.sampleRate)),s=Math.round(mv*Wx);for(let r=0;r<s;r++){const o=Math.floor(Math.random()*i.length),l=.4+Math.random()*.6;for(let c=0;c<n&&o+c<i.length;c++)i[o+c]=Math.max(i[o+c],l*(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,pv/3);const n=i+pv;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 Xe{static svg(e){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${e}" fill="currentColor"/></svg>`}static outline(e){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${e}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}static solid(e){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${e}" fill="currentColor" fill-rule="evenodd"/></svg>`}static BOOKMARK="M6 3.5h12a.5.5 0 0 1 .5.5v16.5L12 16.8l-6.5 3.7V4a.5.5 0 0 1 .5-.5z";static PICTURE="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z";static PICTURE_HILLS="M4.5 17.5l4.5-6 3 4 2.5-3 5 5z";static PIN="M12 21.5s-6.5-5.7-6.5-10.8a6.5 6.5 0 0 1 13 0c0 5.1-6.5 10.8-6.5 10.8z";static PIN_HOLE="M12 8.4a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8z";static MILESTONES_OFF=Xe.outline(Xe.BOOKMARK);static MILESTONES_ON=Xe.solid(Xe.BOOKMARK);static PICTURES_OFF=Xe.outline(`${Xe.PICTURE}${Xe.PICTURE_HILLS}`);static PICTURES_ON=Xe.solid(`${Xe.PICTURE}${Xe.PICTURE_HILLS}`);static TRACE_LINE="M3 19.5l2.2-2.2 1.4 1.4L4.4 20.9zM8 14.5l2.2-2.2 1.4 1.4-2.2 2.2zM13 9.5l2.2-2.2 1.4 1.4-2.2 2.2z";static TRACE_MARK="M18.5 2.5l3.5 3.5-3.5 3.5-3.5-3.5z";static TRACES_OFF=Xe.outline(`${Xe.TRACE_LINE}${Xe.TRACE_MARK}`);static TRACES_ON=Xe.solid(`${Xe.TRACE_LINE}${Xe.TRACE_MARK}`);static MAP_OFF=Xe.outline(`${Xe.PIN}${Xe.PIN_HOLE}`);static MAP_ON=Xe.solid(`${Xe.PIN}${Xe.PIN_HOLE}`);static SHARE=Xe.outline("M14 4l7 7-7 7v-4.2C8.6 13.8 5.4 15.6 3.5 19c.6-5.6 3.4-9.6 10.5-10.8V4z");static FOLDED=Xe.svg("M15.4 7.4 14 6l-6 6 6 6 1.4-1.4L10.8 12z");static UNFOLDED=Xe.svg("M8.6 16.6 10 18l6-6-6-6-1.4 1.4 4.6 4.6z");static PLAY=Xe.svg("M7.4 5v14l11-7z");static PAUSE=Xe.svg("M6 5h4v14H6zM14 5h4v14h-4z");static VOLUME=Xe.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zm12.5 2.5A4 4 0 0 0 12.5 8.5v7A4 4 0 0 0 14.5 12zM12.5 4.2v2.1a6.5 6.5 0 0 1 0 11.4v2.1a8.6 8.6 0 0 0 0-15.6z");static MUTED=Xe.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zM15 9.8l1.4-1.4 2.6 2.6 2.6-2.6 1.4 1.4-2.6 2.6 2.6 2.6-1.4 1.4-2.6-2.6-2.6 2.6-1.4-1.4 2.6-2.6z");static ENTER_FULLSCREEN=Xe.svg("M5 5h5v2H7v3H5V5zm9 0h5v5h-2V7h-3V5zM5 14h2v3h3v2H5v-5zm12 0h2v5h-5v-2h3v-3z");static EXIT_FULLSCREEN=Xe.svg("M8 5h2v5H5V8h3V5zm6 0h2v3h3v2h-5V5zM5 14h5v5H8v-3H5v-2zm9 0h5v2h-3v3h-2v-5z")}function io(a){return[...a].sort((e,t)=>e.t-t.t)}function up(a,e){let t;for(const i of io(a)){if(i.t>e)break;t=i}return t}const pp=Math.PI/180,gh=180/Math.PI;class Ts{constructor(e,t,i){this.kind=e,this.canvasHeightPx=t,this.fovDeg=i;const n=i*pp/2;this.focalPx=e==="equidistant"?t/2/n:t/2/Math.tan(n)}focalPx;static of(e,t,i){return new Ts(e.projection,t,i)}degToPx(e){const t=e*pp;return this.kind==="equidistant"?this.focalPx*t:2*this.focalPx*Math.tan(t/2)}pxToDeg(e){return this.kind==="equidistant"?e/this.focalPx*gh:2*Math.atan(e/(2*this.focalPx))*gh}angleDegToRadiusPx(e){const t=e*pp;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*gh:Math.atan(e/this.focalPx)*gh}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(lt.angularWidthDeg(e))}}class Ui{static fovOf(e,t){return at(e,t)?.fovDeg??Rt.fieldOfViewDeg(e.instrument)}static toAngular(e){this.eachKeyframe(e,(t,i)=>({...t,angular:i.ofBounds(t.bounds)}))}static toBounds(e){this.eachKeyframe(e,(t,i)=>{if(!t.angular)return t;const{width:n,height:s}=i.toBoundsSize(t.angular),r={x:t.bounds.x+(t.bounds.width-n)/2,y:t.bounds.y+(t.bounds.height-s)/2,width:n,height:s};if(t.kind!=="polygon")return{...t,bounds:r};const o=t.bounds.width===0?1:n/t.bounds.width,l=t.bounds.height===0?1:s/t.bounds.height;return{...t,bounds:r,points:t.points.map(c=>({x:c.x*o,y:c.y*l}))}})}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)<Ui.UNMOVED_PX&&Math.abs(s.y-t.bounds.y)<Ui.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=Ts.of(e.instrument,lt.CANVAS_HEIGHT_PX,this.fovOf(e,t));return this.aimFrom(e,n,at(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),o=t.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+o}}static toPosition(e){this.eachKeyframe(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 positionOf(e,t,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(e),o=this.shortestArc(t.azimuthDeg-s.headingDeg),l=t.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,o)-i.width/2,y:r.y-this.offAxisPx(n,l)-i.height/2}}static frameCentre(e){return{x:Rt.frameWidthPx(e.instrument,lt.CANVAS_HEIGHT_PX)/2,y:lt.CANVAS_HEIGHT_PX/2}}static shortestArc(e){return(e%360+540)%360-180}static offAxisPx(e,t){return Math.abs(t)>=Ui.OFF_CANVAS_DEG?Math.sign(t)*Ui.OFF_CANVAS_PX:e.angleDegToRadiusPx(t)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(e,t,i){const n=Rt.frameWidthPx(t,lt.CANVAS_HEIGHT_PX)/2,s=Rt.frameWidthPx(e.instrument,lt.CANVAS_HEIGHT_PX)/2,r=lt.CANVAS_HEIGHT_PX/2;for(const o of[...e.timeline.allKeyframes]){const l=this.fovOf(e,o.t),c=i?.get(o.t)??l,h=Ts.of(t,lt.CANVAS_HEIGHT_PX,c),d=Ts.of(e.instrument,lt.CANVAS_HEIGHT_PX,l);e.timeline.addKeyframe(o.t,o.shapes.map(u=>{const{bounds:p}=u.shape,f=p.x+p.width/2-n,g=p.y+p.height/2-r,m=Math.hypot(f,g),v=m===0?1:d.angleDegToRadiusPx(h.radiusPxToAngleDeg(m))/m,x={...p,x:s+f*v-p.width/2,y:r+g*v-p.height/2};return{...u,shape:{...u.shape,bounds:x}}}))}this.toBounds(e)}static eachKeyframe(e,t){const{timeline:i}=e;for(const n of[...i.allKeyframes]){const s=at(e,n.t),r=this.fovOf(e,n.t),o=Ts.of(e.instrument,lt.CANVAS_HEIGHT_PX,r);i.addKeyframe(n.t,n.shapes.map(l=>({...l,shape:t(l.shape,o,s)})))}}}function Yx(a){return wn.restore(Zf(a),a.provenance)}function Zf(a){return Ui.toAngular(a),Ui.toAim(a),{version:1,id:a.id,time:a.event.time,endTime:a.event.endTime,durationSeconds:a.event.durationSeconds,durationText:a.event.durationText,utcOffsetHours:a.event.utcOffsetHours,timeZone:a.event.timeZone,place:a.event.place,observer:a.observer,account:a.account,sources:a.sources?.length?a.sources:void 0,sway:a.sway,vehicle:a.vehicle,description:a.event.description,tags:a.event.tags,timeline:a.timeline.toJSON(),observerTrack:a.observerTrack.toJSON(),weatherTrack:a.weatherTrack.toJSON(),soundTrack:a.soundTrack.toJSON(),weather:a.weather,decor:a.decor,milestones:a.milestones.length>0?a.milestones:void 0,references:a.references.length>0?a.references:void 0,roads:a.roads.length>0?a.roads:void 0,traces:a.traces.length>0?a.traces:void 0,weatherSource:a.weatherSource,instrument:a.instrumentId,exposureSeconds:a.exposureSeconds,iso:a.iso,lightPollution:a.lightPollution,observerMap:a.observerMap,interpretation:a.interpretation}}function qx(a){const{recording:e,provenance:t}=wn.strip(a),i=Kx(e);return i.provenance=t,i}function Kx(a){const e=[],t=new Yu({eventType:"sighting",time:a.time,endTime:a.endTime,durationSeconds:a.durationSeconds,durationText:a.durationText,utcOffsetHours:a.utcOffsetHours,timeZone:a.timeZone,place:a.place,description:a.description,tags:a.tags},Gu.fromJSON(a.timeline,e),a.observerTrack?Uc.fromJSON(a.observerTrack):new Uc,a.weatherTrack?Bc.fromJSON(a.weatherTrack):new Bc,a.soundTrack?zc.fromJSON(a.soundTrack):new zc,a.observer&&{id:a.observer.id,title:a.observer.title,lastName:a.observer.lastName,firstNames:a.observer.firstNames},a.id,a.weather,a.decor??[],a.weatherSource,a.instrument,a.exposureSeconds??a.observerTrack?.keyframes.map(i=>i.pose.exposureSeconds).find(i=>i!==void 0),io(a.milestones??[]),a.references??[],a.roads??[],a.traces??[]);return t.account=a.account,t.sources=a.sources,t.sway=a.sway,t.iso=a.iso,t.lightPollution=a.lightPollution,t.observerMap=a.observerMap,t.vehicle=a.vehicle,t.interpretation=a.interpretation,t.loadIssues=e,Ui.toBounds(t),Ui.toPosition(t),t}class Dl{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=Dl.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=>` ${Dl.text(n)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
|
|
2801
2801
|
${i.join(`
|
|
2802
2802
|
`)}`)}}class gs{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,n){if(!gs.isObject(e)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:gs.typeOf(e)});return}for(const[s,r]of Object.entries(e)){const o=i?`${i}.${s}`:s,l=t[s];l?this.field(r,l,o,n):n.push({kind:"unknown-key",path:o})}}field(e,t,i,n){if(gs.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):gs.isObject(e)||n.push({kind:"wrong-type",path:i,expected:"object",found:gs.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((s,r)=>{const o=gs.isStated(s)?s.value:s;this.object(o,t.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:gs.typeOf(e)});return;default:typeof e!==t.type&&n.push({kind:"wrong-type",path:i,expected:t.type,found:gs.typeOf(e)})}}static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return gs.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 xs{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?xs.travelDegOver(e,t,i,i+n*1e3)/s/xs.PIXELS_PER_INSTANT:0,o=xs.flashesOver(e,n)*xs.INSTANTS_PER_FLASH,l=Math.ceil(Math.max(r,o));return l<2?1:Math.min(xs.MAX_INSTANTS,l)}static travelDegOver(e,t,i,n){let s=0;for(const r of e){if(!r.track||r.track.length<2)continue;const o=xs.directionAt(r,t,i),l=xs.directionAt(r,t,n),c=Math.min(1,Math.max(-1,o.x*l.x+o.y*l.y+o.z*l.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=tr(e,i),s=n.eastM,r=n.altitudeM-t,o=n.northM,l=Math.hypot(s,r,o);return l===0?{x:0,y:1,z:0}:{x:s/l,y:r/l,z:o/l}}}const qy={play:"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:Dl.EN},Zx=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:qy},Symbol.toStringTag,{value:"Module"})),Ky=Math.PI/180,jx=180/Math.PI,Jx=256,Zy=19,Qx=1.25;function jy(a,e){return 156543.03392*Math.cos(a*Ky)/2**e}function Jy(a,e){return jy(a,e)*Jx}function eS(a,e){let t=0;for(;t<Zy&&Jy(a,t+1)>=e;)t++;return t}function Qy(a,e){return Jy(a,e)}function tS(a,e){const t=e*Qx;let i=0;for(;i<Zy&&jy(a,i)>t;)i++;return i}function wd(a){const e=a*Ky;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function eM(a,e,t){const i=2**t;return{x:(a+180)/360*i,y:wd(e)*i}}function tM(a,e,t){const i=wd(a.north),n=wd(a.south);return{x:(e-a.west)/(a.east-a.west),y:(wd(t)-i)/(n-i)}}function iS(a,e,t){const{x:i,y:n}=eM(a,e,t);return{x:Math.floor(i),y:Math.floor(n),z:t}}function nS(a){const e=2**a.z,t=a.x/e*360-180,i=(a.x+1)/e*360-180,n=gv(a.y,e);return{south:gv(a.y+1,e),north:n,west:t,east:i}}function gv(a,e){const t=a/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*jx}function iM(a,e,t,i){const n=iS(a,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 o=r.map(nS),l={south:Math.min(...o.map(c=>c.south)),north:Math.max(...o.map(c=>c.north)),west:Math.min(...o.map(c=>c.west)),east:Math.max(...o.map(c=>c.east))};return{tiles:r,bounds:l}}const sS="#2ec4ff";class Ia{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=tM(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??sS;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 o=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=n.reduce((l,c)=>Math.hypot(c.x-o.x,c.y-o.y)>Math.hypot(l.x-o.x,l.y-o.y)?c:l)}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),o=Math.hypot(this.width,this.height),l=(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,o,l-c,l+c),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,o);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:Ia.MARKER_RADIUS_PX}),t.beginPath(),t.arc(n.x,n.y,Ia.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 o=ci(r.lat,r.lng,t.lat,t.lng);return Math.hypot(o.x,o.z)<=Ia.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?Ia.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,l=Math.abs(ci(r,e.east,r,e.west).x)/this.width,c=Ia.SCALE_STEPS_M.find(p=>p/l<=this.width/3);if(c===void 0)return;const h=c/l,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 li{static MIN_ZOOM=.25;static MAX_ZOOM=64;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(li.MAX_ZOOM,Math.max(li.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=li.mercatorY01(t.north),s=li.mercatorY01(t.south),r=li.mercatorY01(i.north),o=li.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+o)/2-n)/(s-n)}keepInView(e,t,i){if(!this.changed)return!1;const n=this.boundsWithin(e),s=li.mercatorY01(n.north),r=li.mercatorY01(n.south),o=(t.lng-n.west)/(n.east-n.west),l=(li.mercatorY01(t.lat)-s)/(r-s);return o>=i&&o<=1-i&&l>=i&&l<=1-i?!1:(this.panBy(.5-o,.5-l),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=li.mercatorY01(e.north),n=li.mercatorY01(e.south),s=e.east-e.west;return{west:e.west+(this.centerX-t)*s,east:e.west+(this.centerX+t)*s,north:li.latitudeAt(i+(this.centerY-t)*(n-i)),south:li.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=ci(n,e.east,n,s).x;let o=r;for(const l of t){const{x:c,z:h}=ci(l.lat,l.lng,n,s),d=Math.max(Math.abs(c),Math.abs(h));d<=r*i&&(o=Math.max(o,d*1.15))}return o<=r?e:{north:Zn(0,-o,n,s).lat,south:Zn(0,o,n,s).lat,east:Zn(o,0,n,s).lng,west:Zn(-o,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=li.mercatorY01(e.north),s=li.mercatorY01(e.south);return{lat:li.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 Qn=256,vv=3,rS=32768;class nM{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(ci(i,e.east,i,e.west).x),r=Math.abs(ci(e.north,n,e.south,n).z),o=eS(i,Math.max(s,r)),{tiles:l}=iM(n,i,o,vv),c=vv*Qn,h=new Float32Array(c*c),d=l[0];await Promise.all(l.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 g=0;g<t.width;g++){const m=e.west+(e.east-e.west)*(g/(t.width-1));u[p*t.width+g]=this.sampleAt(f,m,o,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 o=await createImageBitmap(await r.blob()),l=document.createElement("canvas");l.width=Qn,l.height=Qn;const c=l.getContext("2d");if(!c)throw new Error("2D canvas context unavailable");c.drawImage(o,0,0);const{data:h}=c.getImageData(0,0,Qn,Qn),d=(e.x-t.x)*Qn,u=(e.y-t.y)*Qn;for(let p=0;p<Qn;p++)for(let f=0;f<Qn;f++){const g=(p*Qn+f)*4,m=h[g]*256+h[g+1]+h[g+2]/256-rS,v=d+f,x=u+p;i[x*n+v]=m}}sampleAt(e,t,i,n,s,r){const{x:o,y:l}=eM(t,e,i),c=(o-n.x)*Qn,h=(l-n.y)*Qn,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),g=c-d,m=h-u,v=s[u*r+d],x=s[u*r+p],y=s[f*r+d],b=s[f*r+p],w=v+(x-v)*g,S=y+(b-y)*g;return w+(S-w)*m}}const xd=256,aS=5;async function sM(a,e,t,i){const n=(a.south+a.north)/2,s=(a.west+a.east)/2,r=Math.abs(ci(n,a.east,n,a.west).x),o=Math.abs(ci(a.north,s,a.south,s).z),l=Math.max(r,o),{zoom:c,gridSize:h}=oS(n,l,Math.max(e.width,e.height)),{tiles:d,bounds:u}=iM(s,n,c,h),p=h*xd,f=document.createElement("canvas");f.width=p,f.height=p;const g=f.getContext("2d");if(!g)throw new Error("2D canvas context unavailable");const m=d[0];await Promise.all(d.map(async b=>{const w=t(b),S=await i(w);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${w}`);const _=await createImageBitmap(await S.blob());g.drawImage(_,(b.x-m.x)*xd,(b.y-m.y)*xd)}));const v=Math.min(Math.max(e.width,e.height),p);if(v===p)return{source:f,width:p,height:p,bounds:u};const x=document.createElement("canvas");x.width=v,x.height=v;const y=x.getContext("2d");if(!y)throw new Error("2D canvas context unavailable");return y.drawImage(f,0,0,p,p,0,0,v,v),{source:x,width:v,height:v,bounds:u}}function oS(a,e,t){let i=tS(a,e/Math.max(1,t)),n=bv(a,i,e);for(;n>aS&&i>0;)i--,n=bv(a,i,e);return{zoom:i,gridSize:n,mPerPixel:Qy(a,i)/xd}}function bv(a,e,t){const i=Math.ceil(t/2/Qy(a,e));return Math.max(3,2*i+1)}class rM{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 sM(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class vs{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;static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];fetchImpl;endpoints;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.endpoints=e.endpoints??vs.ENDPOINTS}static queue=Promise.resolve();static RETRY_MS=4e3;async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${vs.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.queued(()=>this.ask(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:vs.surfaceOf(s),widthM:vs.widthOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return t}queued(e){const t=vs.queue.then(e,e);return vs.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints)for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`);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,vs.RETRY_MS))}throw t??new Error("No Overpass instance answered")}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:vs.WIDTH_M[e.highway]??vs.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 fp="https://ufoathome.org/roads/index.json";class Jo{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??Jo.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(`
|
|
2803
|
-
`);let t=Jo.shared.get(e);return t||(t=this.fetchFirstAvailable(),Jo.shared.set(e,t),t.then(i=>{i.length===0&&Jo.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.105.0")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==fp?[t,fp]:[fp]).map(i=>i+e)}}function lS(){return{elevation:new nM,imagery:aM(),roads:cS()}}function aM(){return new rM}function cS(){return new Jo({fallback:new vs})}const hS=new Set,pl="show-observer-map",fl="hide-milestones";class vt extends HTMLElement{static get observedAttributes(){return["src",pl,fl]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;static OBSERVER_MAP_MIN_SPAN_M=400;static OBSERVER_MAP_MARGIN=.6;static OBSERVER_MAP_IMAGERY_PX=768;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 li;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Yu.create();issues=[];issueCheck=0;sightingAudio=new $x;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>vt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=qy;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");vt.setIcon(this.moreButton,e?Xe.UNFOLDED:Xe.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)<vt.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>=li.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=li.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},vt.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=li.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>${Gx}</style>${Hx}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Gc(this.canvas.getContext("2d")),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",t=>{t.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 Ia(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.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",t=>{t.key!=="Enter"&&t.key!==" "||(t.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.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",t=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(t),this.beginTouchScrub(t)}),this.seekInput.addEventListener("pointerup",t=>{this.seekSnapArmed=!1,this.endTouchScrub(t)}),this.seekInput.addEventListener("pointercancel",t=>this.endTouchScrub(t)),this.seekInput.addEventListener("pointermove",t=>{this.nameMarkUnder(t),this.hoverSeek(t),this.touchScrub(t)}),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 t of["touchend","click"])this.stageElement.addEventListener(t,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",t=>{if(this.enableClickToPlay){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}t.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",t=>{this.enableClickToPlay&&(t.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.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.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===pl&&this.applyObserverMapDefault(),e===fl&&this.setMilestonesShown(!this.hasAttribute(fl))}async loadFromSrc(e){this.sightingData=await Nc.json(e)}get sightingData(){return Yx(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=qx(e),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.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await je(async()=>{const{default:r}=await import("./sightingSchema-5AlscPkV.js");return{default:r}},[],import.meta.url);n=new gs(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],Dl.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(dS,{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=Dl.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;return}this.togglePlayPause()}}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)}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"),o=document.createElement("input");o.type="checkbox",o.checked=i.shown;const l=document.createElement("span");l.textContent=n,l.title=n,r.append(o,l);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,o.addEventListener("change",()=>{i.shown=o.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"),vt.setIcon(this.referencesButton,i?Xe.PICTURES_ON:Xe.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)),vt.setIcon(this.tracesButton,this.tracesShownState?Xe.TRACES_ON:Xe.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?io(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),o=r?`${s} — ${r}`:s;return n.title=o,n.setAttribute("aria-label",o),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)??"",o=this.said.read(i.note);return s.textContent=o?`${r} — ${o}`: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,o)=>r-o):[],Math.max(e,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const o=document.createElement("div");o.className="seek-segment",o.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const l=document.createElement("i");l.className="seek-hover";const c=document.createElement("i");c.className="seek-played",o.append(l,c),s.push(o),this.seekSegmentList.push({start:n[r],end:n[r+1],element:o,played:c,hover:l})}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}%`}paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=vt.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=vt.fillOf(p,s),p.element.classList.toggle("hovered",s>=p.start&&(s<p.end||f===r))});const o=this.milestonesShown?this.sighting.milestones:[],l=o.length>0?up(o,s):void 0,c=l?this.said.read(l.label)??"":"",h=l?this.said.read(l.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)}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=vt.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const o=Number(r.dataset.t);Math.abs(o-e)>n||(!s||Math.abs(o-e)<Math.abs(s.t-e))&&(s={t:o,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?up(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=xs.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<vt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(vt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/vt.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/vt.EXPOSURE_STEP_PX),s=Math.min(vt.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let o=0;o<s;o++)r.push(t.fromMs+t.ms*o/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,o]of i){const l=n.get(r);if(!l)continue;const c=l.bounds.x+l.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=l.bounds.y+l.bounds.height/2-(o.bounds.y+o.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=Rt.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:hS;this.canvasRenderer.setStarPoints(Rt.starPointsOf(this.sighting.instrument));const n=(at(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[,l]of o.shapes){const c=o.share,h=c===1?l:{...l,transparency:1-(1-l.transparency)*c};this.canvasRenderer.paintShape(this.shifted(h,r))}for(const[o,l]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));if(this.selectionShown&&i.size>1){const o=Tt.groupBoundsFor([...t].filter(([l])=>i.has(l)).map(([,l])=>l.bounds));this.canvasRenderer.paintGroupHandles(o)}this.overlayPainter?.(this.canvasRenderer),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(Dm(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),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 Vx(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*vt.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;return}else this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Xe.PLAY:Xe.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){vt.icons.get(e)!==t&&(vt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-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},vt.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,vt.setIcon(this.playPauseButton,e?Xe.PAUSE:Xe.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(pl),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;vt.setIcon(this.observerMapButton,e?Xe.MAP_ON:Xe.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=ul.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=li.including(this.observerPath.boundsAround(vt.OBSERVER_MAP_MIN_SPAN_M,vt.OBSERVER_MAP_MARGIN),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.observerMapImageryNeededFor(e))return;const t=this.observerMapView.changed,i=t?li.expand(e,vt.OBSERVER_MAP_IMAGERY_AHEAD):e,n=vt.OBSERVER_MAP_IMAGERY_PX*(t?1+2*vt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=aM();try{const r=await s.getImageryTexture(i,{width:n,height:n});if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=r,this.observerMapImageryCredit=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?li.expand(e,vt.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}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=vt.OBSERVER_MAP_CLEARANCE_PX,o=i(...n,0),l=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&l&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!o&&(l||!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=at(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},vt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?up(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?io(this.currentSighting.milestones):[]){const o=at(this.currentSighting,r.t);o?.lat===void 0||o.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:o.lat,lng:o.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?Ts.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Rt.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,io(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,vt.setIcon(this.milestonesButton,this.milestonesShown?Xe.MILESTONES_ON:Xe.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=at(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=tr(i,e),{lat:s,lng:r}=Zn(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=at(this.currentSighting,this.currentTime),s=Ts.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return Ft.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=vt.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;if(this.muteButton.disabled=e,this.volumeInput.hidden=e,e){vt.setIcon(this.muteButton,Xe.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}vt.setIcon(this.muteButton,this.mutedState?Xe.MUTED:Xe.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=t,this.muteButton.setAttribute("aria-label",t),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;vt.setIcon(this.fullscreenButton,e?Xe.EXIT_FULLSCREEN:Xe.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 qn(hs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Fc(hs.preferencesFor(this),Hc);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await Mx(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=Tl(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Vf(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.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return vh(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?Mv(yv(this.realStartMs+i)):vh(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?vh(this.currentSighting.timeline.duration):this.canShowClockTime?Mv(yv(this.realStartMs+this.realDurationMs)):vh(this.realDurationMs)}}function yv(a){const e=new Date(a);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function Mv(a){if(a.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return a.second?`${e(a.hour)}:${e(a.minute??0)}:${e(a.second)}`:`${e(a.hour)}:${e(a.minute??0)}`}function vh(a){const e=Math.round(a/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const jf="rr0-ufo";function qu(){customElements.get(jf)||customElements.define(jf,vt)}const dS="recordingissues";class Sc{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+Sc.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Sc.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Sc.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 Qo{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=g=>{const m=s.getInterpolatedPoseAt(Math.max(0,g));if(!m||m.lat===void 0||m.lng===void 0)return;const v=ci(m.lat,m.lng,n.lat,n.lng);return{eastM:v.x,northM:-v.z,heading:m.headingDeg}},o=r(t-Qo.HALF_SPAN_MS),l=r(t+Qo.HALF_SPAN_MS),c=r(t);if(!o||!l||!c)return 0;const h=Math.hypot(l.eastM-o.eastM,l.northM-o.northM),d=2*Qo.HALF_SPAN_MS/1e3;if(h/d<Qo.MIN_SPEED_MS)return 0;const u=i.heightAt(l.eastM,l.northM)-i.heightAt(o.eastM,o.northM),p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(l.eastM-o.eastM,l.northM-o.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const uS=.08,wv=.15,xv=2,pS=2e3;class fS{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}}to.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<pS),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 o=e.createGain(),l=e.createBiquadFilter();l.type="lowpass",l.frequency.value=900,s.connect(l),r.connect(l),l.connect(o).connect(n);const c=()=>{const w=e.createBufferSource();return w.buffer=this.noise(e),w.loop=!0,w.loopStart=Math.random()*xv*.5,w},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 g=e.createGain();p.connect(f).connect(g).connect(n);const m=c(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const x=e.createGain();m.connect(v).connect(x).connect(n);const y=[s,r,h,p,m];for(const w of y)w.start();const b={nodes:[i,n,o,l,d,u,f,g,v,x,...y],sources:y,firing:s,crank:r,knock:d,engineGain:o,knockGain:u,roadGain:g,windGain:x,cabin:n,output:i};return this.voices.set(t,b),b}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:o,distanceM:l}){const c=e.currentTime,h=(x,y)=>x.setTargetAtTime(y,c,uS),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 g=!r||o;h(t.windGain.gain,f**2*(g?.5:.06));const m=r?o?3500:700:8e3/(1+l/60);h(t.cabin.frequency,m);const v=r?.5:Math.min(1,8/Math.max(l,1));h(t.output.gain,v*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,wv/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},wv*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*xv,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 Vc{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 Vc.BY_KIND[e??"generic"]??Vc.BY_KIND.generic}}class $a{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=$a.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 o=[];let l=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<$a.STANDING_MPS){l=1,o.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;l<e.kmhPer1000Rpm.length&&p(l)>e.shiftUpRpm;)l++;for(;l>1&&p(l)<e.shiftDownRpm;)l--;const f=Math.max(p(l),e.idleRpm*(1+.3*Math.min(1,h/3))),g=.15+.5*Math.min(1,(h/35)**2),m=d>.15?Math.min(1,g+d/2.5):d<-.3?.05:g;o.push({speedMps:h,rpm:f,load:m,gear:l})}return new $a(o,i)}at(e){const t=(e-this.startMs)/$a.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 du{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=ci(d,u,n.lat,n.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),o=e.vehicle;if(o){const c=Vc.of(o.kind),h=this.drive(`observer:${o.kind}`,du.trackKey(e),()=>$a.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:o.noise??1,inside:!0,windowsOpen:o.windowsOpen===!0,distanceM:0})}const l=s(t);for(const c of e.decor){if(!c.engine||!l)continue;const h=Vc.of(c.engine.kind),d=g=>{const m=tr(c,g);return{eastM:m.eastM,northM:m.northM}},u=this.drive(`decor:${c.id}`,du.decorKey(c,r),()=>$a.of(h,d,0,r));if(!u)continue;const p=tr(c,t),f=Math.hypot(p.eastM-l.eastM,p.northM-l.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 mS=`
|
|
2803
|
+
`);let t=Jo.shared.get(e);return t||(t=this.fetchFirstAvailable(),Jo.shared.set(e,t),t.then(i=>{i.length===0&&Jo.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.105.2")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==fp?[t,fp]:[fp]).map(i=>i+e)}}function lS(){return{elevation:new nM,imagery:aM(),roads:cS()}}function aM(){return new rM}function cS(){return new Jo({fallback:new vs})}const hS=new Set,pl="show-observer-map",fl="hide-milestones";class vt extends HTMLElement{static get observedAttributes(){return["src",pl,fl]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;static OBSERVER_MAP_MIN_SPAN_M=400;static OBSERVER_MAP_MARGIN=.6;static OBSERVER_MAP_IMAGERY_PX=768;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 li;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Yu.create();issues=[];issueCheck=0;sightingAudio=new $x;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>vt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=qy;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");vt.setIcon(this.moreButton,e?Xe.UNFOLDED:Xe.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)<vt.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>=li.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=li.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},vt.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=li.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>${Gx}</style>${Hx}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Gc(this.canvas.getContext("2d")),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",t=>{t.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 Ia(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.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",t=>{t.key!=="Enter"&&t.key!==" "||(t.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.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",t=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(t),this.beginTouchScrub(t)}),this.seekInput.addEventListener("pointerup",t=>{this.seekSnapArmed=!1,this.endTouchScrub(t)}),this.seekInput.addEventListener("pointercancel",t=>this.endTouchScrub(t)),this.seekInput.addEventListener("pointermove",t=>{this.nameMarkUnder(t),this.hoverSeek(t),this.touchScrub(t)}),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 t of["touchend","click"])this.stageElement.addEventListener(t,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",t=>{if(this.enableClickToPlay){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}t.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",t=>{this.enableClickToPlay&&(t.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.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.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===pl&&this.applyObserverMapDefault(),e===fl&&this.setMilestonesShown(!this.hasAttribute(fl))}async loadFromSrc(e){this.sightingData=await Nc.json(e)}get sightingData(){return Yx(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=qx(e),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.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await je(async()=>{const{default:r}=await import("./sightingSchema-5AlscPkV.js");return{default:r}},[],import.meta.url);n=new gs(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],Dl.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(dS,{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=Dl.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;return}this.togglePlayPause()}}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)}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"),o=document.createElement("input");o.type="checkbox",o.checked=i.shown;const l=document.createElement("span");l.textContent=n,l.title=n,r.append(o,l);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,o.addEventListener("change",()=>{i.shown=o.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"),vt.setIcon(this.referencesButton,i?Xe.PICTURES_ON:Xe.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)),vt.setIcon(this.tracesButton,this.tracesShownState?Xe.TRACES_ON:Xe.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?io(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),o=r?`${s} — ${r}`:s;return n.title=o,n.setAttribute("aria-label",o),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)??"",o=this.said.read(i.note);return s.textContent=o?`${r} — ${o}`: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,o)=>r-o):[],Math.max(e,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const o=document.createElement("div");o.className="seek-segment",o.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const l=document.createElement("i");l.className="seek-hover";const c=document.createElement("i");c.className="seek-played",o.append(l,c),s.push(o),this.seekSegmentList.push({start:n[r],end:n[r+1],element:o,played:c,hover:l})}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}%`}paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=vt.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=vt.fillOf(p,s),p.element.classList.toggle("hovered",s>=p.start&&(s<p.end||f===r))});const o=this.milestonesShown?this.sighting.milestones:[],l=o.length>0?up(o,s):void 0,c=l?this.said.read(l.label)??"":"",h=l?this.said.read(l.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)}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=vt.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const o=Number(r.dataset.t);Math.abs(o-e)>n||(!s||Math.abs(o-e)<Math.abs(s.t-e))&&(s={t:o,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?up(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=xs.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<vt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(vt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/vt.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/vt.EXPOSURE_STEP_PX),s=Math.min(vt.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let o=0;o<s;o++)r.push(t.fromMs+t.ms*o/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,o]of i){const l=n.get(r);if(!l)continue;const c=l.bounds.x+l.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=l.bounds.y+l.bounds.height/2-(o.bounds.y+o.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=Rt.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:hS;this.canvasRenderer.setStarPoints(Rt.starPointsOf(this.sighting.instrument));const n=(at(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[,l]of o.shapes){const c=o.share,h=c===1?l:{...l,transparency:1-(1-l.transparency)*c};this.canvasRenderer.paintShape(this.shifted(h,r))}for(const[o,l]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));if(this.selectionShown&&i.size>1){const o=Tt.groupBoundsFor([...t].filter(([l])=>i.has(l)).map(([,l])=>l.bounds));this.canvasRenderer.paintGroupHandles(o)}this.overlayPainter?.(this.canvasRenderer),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(Dm(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),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 Vx(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*vt.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;return}else this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Xe.PLAY:Xe.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){vt.icons.get(e)!==t&&(vt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-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},vt.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,vt.setIcon(this.playPauseButton,e?Xe.PAUSE:Xe.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(pl),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;vt.setIcon(this.observerMapButton,e?Xe.MAP_ON:Xe.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=ul.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=li.including(this.observerPath.boundsAround(vt.OBSERVER_MAP_MIN_SPAN_M,vt.OBSERVER_MAP_MARGIN),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.observerMapImageryNeededFor(e))return;const t=this.observerMapView.changed,i=t?li.expand(e,vt.OBSERVER_MAP_IMAGERY_AHEAD):e,n=vt.OBSERVER_MAP_IMAGERY_PX*(t?1+2*vt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=aM();try{const r=await s.getImageryTexture(i,{width:n,height:n});if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=r,this.observerMapImageryCredit=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?li.expand(e,vt.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}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=vt.OBSERVER_MAP_CLEARANCE_PX,o=i(...n,0),l=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&l&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!o&&(l||!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=at(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},vt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?up(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?io(this.currentSighting.milestones):[]){const o=at(this.currentSighting,r.t);o?.lat===void 0||o.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:o.lat,lng:o.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?Ts.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Rt.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,io(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,vt.setIcon(this.milestonesButton,this.milestonesShown?Xe.MILESTONES_ON:Xe.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=at(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=tr(i,e),{lat:s,lng:r}=Zn(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=at(this.currentSighting,this.currentTime),s=Ts.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return Ft.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=vt.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;if(this.muteButton.disabled=e,this.volumeInput.hidden=e,e){vt.setIcon(this.muteButton,Xe.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}vt.setIcon(this.muteButton,this.mutedState?Xe.MUTED:Xe.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=t,this.muteButton.setAttribute("aria-label",t),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;vt.setIcon(this.fullscreenButton,e?Xe.EXIT_FULLSCREEN:Xe.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 qn(hs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Fc(hs.preferencesFor(this),Hc);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await Mx(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=Tl(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Vf(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.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return vh(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?Mv(yv(this.realStartMs+i)):vh(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?vh(this.currentSighting.timeline.duration):this.canShowClockTime?Mv(yv(this.realStartMs+this.realDurationMs)):vh(this.realDurationMs)}}function yv(a){const e=new Date(a);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function Mv(a){if(a.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return a.second?`${e(a.hour)}:${e(a.minute??0)}:${e(a.second)}`:`${e(a.hour)}:${e(a.minute??0)}`}function vh(a){const e=Math.round(a/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const jf="rr0-ufo";function qu(){customElements.get(jf)||customElements.define(jf,vt)}const dS="recordingissues";class Sc{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+Sc.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Sc.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Sc.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 Qo{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=g=>{const m=s.getInterpolatedPoseAt(Math.max(0,g));if(!m||m.lat===void 0||m.lng===void 0)return;const v=ci(m.lat,m.lng,n.lat,n.lng);return{eastM:v.x,northM:-v.z,heading:m.headingDeg}},o=r(t-Qo.HALF_SPAN_MS),l=r(t+Qo.HALF_SPAN_MS),c=r(t);if(!o||!l||!c)return 0;const h=Math.hypot(l.eastM-o.eastM,l.northM-o.northM),d=2*Qo.HALF_SPAN_MS/1e3;if(h/d<Qo.MIN_SPEED_MS)return 0;const u=i.heightAt(l.eastM,l.northM)-i.heightAt(o.eastM,o.northM),p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(l.eastM-o.eastM,l.northM-o.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const uS=.08,wv=.15,xv=2,pS=2e3;class fS{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}}to.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<pS),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 o=e.createGain(),l=e.createBiquadFilter();l.type="lowpass",l.frequency.value=900,s.connect(l),r.connect(l),l.connect(o).connect(n);const c=()=>{const w=e.createBufferSource();return w.buffer=this.noise(e),w.loop=!0,w.loopStart=Math.random()*xv*.5,w},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 g=e.createGain();p.connect(f).connect(g).connect(n);const m=c(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const x=e.createGain();m.connect(v).connect(x).connect(n);const y=[s,r,h,p,m];for(const w of y)w.start();const b={nodes:[i,n,o,l,d,u,f,g,v,x,...y],sources:y,firing:s,crank:r,knock:d,engineGain:o,knockGain:u,roadGain:g,windGain:x,cabin:n,output:i};return this.voices.set(t,b),b}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:o,distanceM:l}){const c=e.currentTime,h=(x,y)=>x.setTargetAtTime(y,c,uS),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 g=!r||o;h(t.windGain.gain,f**2*(g?.5:.06));const m=r?o?3500:700:8e3/(1+l/60);h(t.cabin.frequency,m);const v=r?.5:Math.min(1,8/Math.max(l,1));h(t.output.gain,v*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,wv/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},wv*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*xv,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 Vc{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 Vc.BY_KIND[e??"generic"]??Vc.BY_KIND.generic}}class $a{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=$a.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 o=[];let l=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<$a.STANDING_MPS){l=1,o.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;l<e.kmhPer1000Rpm.length&&p(l)>e.shiftUpRpm;)l++;for(;l>1&&p(l)<e.shiftDownRpm;)l--;const f=Math.max(p(l),e.idleRpm*(1+.3*Math.min(1,h/3))),g=.15+.5*Math.min(1,(h/35)**2),m=d>.15?Math.min(1,g+d/2.5):d<-.3?.05:g;o.push({speedMps:h,rpm:f,load:m,gear:l})}return new $a(o,i)}at(e){const t=(e-this.startMs)/$a.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 du{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=ci(d,u,n.lat,n.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),o=e.vehicle;if(o){const c=Vc.of(o.kind),h=this.drive(`observer:${o.kind}`,du.trackKey(e),()=>$a.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:o.noise??1,inside:!0,windowsOpen:o.windowsOpen===!0,distanceM:0})}const l=s(t);for(const c of e.decor){if(!c.engine||!l)continue;const h=Vc.of(c.engine.kind),d=g=>{const m=tr(c,g);return{eastM:m.eastM,northM:m.northM}},u=this.drive(`decor:${c.id}`,du.decorKey(c,r),()=>$a.of(h,d,0,r));if(!u)continue;const p=tr(c,t),f=Math.hypot(p.eastM-l.eastM,p.northM-l.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 mS=`
|
|
2804
2804
|
<div class="stage" id="stage">
|
|
2805
2805
|
<div class="frame" id="frame">
|
|
2806
2806
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -7906,7 +7906,7 @@ vec3 finish(vec3 relative, vec4 overlay) {
|
|
|
7906
7906
|
* @fileoverview Astronomy calculation library for browser scripting and Node.js.
|
|
7907
7907
|
* @author Don Cross <cosinekitty@gmail.com>
|
|
7908
7908
|
* @license MIT
|
|
7909
|
-
*/const ag=173.1446326846693,js=14959787069098932e-8,ge=.017453292519943295,K1=.26179938779914946,Ds=57.29577951308232,QM=3.819718634205488,ZI=365.24217,Z1=new Date("2000-01-01T12:00:00Z"),gr=2*Math.PI,Gr=3600*(180/Math.PI),nl=484813681109536e-20,ew=10800*60,jI=2*ew,j1=7292115e-11,JI=ew/Math.PI,QI=-.17-5*Math.log10(JI),J1=29.530588,eD=24*3600,yc=695700,tD=yc/js,J0=.996647180302104,iD=J0*J0,Q0=6378.1366,nD=Q0/js,sD=1737.4,rD=1736,aD=rD/js,tw=81.30056,og=.0002959122082855911,em=2825345909524226e-22,tm=8459715185680659e-23,im=1292024916781969e-23,nm=1524358900784276e-23;function Iu(a){if(a!==!0&&a!==!1)throw console.trace(),`Value is not boolean: ${a}`;return a}function Ai(a){if(!Number.isFinite(a))throw console.trace(),`Value is not a finite number: ${a}`;return a}function Wo(a){return a-Math.floor(a)}function iw(a,e){const t=a.x*a.x+a.y*a.y+a.z*a.z;if(Math.abs(t)<1e-8)throw"AngleBetween: first vector is too short.";const i=e.x*e.x+e.y*e.y+e.z*e.z;if(Math.abs(i)<1e-8)throw"AngleBetween: second vector is too short.";const n=(a.x*e.x+a.y*e.y+a.z*e.z)/Math.sqrt(t*i);return n<=-1?180:n>=1?0:Ds*Math.acos(n)}var ue;(function(a){a.Sun="Sun",a.Moon="Moon",a.Mercury="Mercury",a.Venus="Venus",a.Earth="Earth",a.Mars="Mars",a.Jupiter="Jupiter",a.Saturn="Saturn",a.Uranus="Uranus",a.Neptune="Neptune",a.Pluto="Pluto",a.SSB="SSB",a.EMB="EMB",a.Star1="Star1",a.Star2="Star2",a.Star3="Star3",a.Star4="Star4",a.Star5="Star5",a.Star6="Star6",a.Star7="Star7",a.Star8="Star8"})(ue||(ue={}));const oD=[ue.Star1,ue.Star2,ue.Star3,ue.Star4,ue.Star5,ue.Star6,ue.Star7,ue.Star8],lD=[{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0}];function cD(a){const e=oD.indexOf(a);return e>=0?lD[e]:null}function lg(a){const e=cD(a);return e&&e.dist>0?e:null}var Ci;(function(a){a[a.From2000=0]="From2000",a[a.Into2000=1]="Into2000"})(Ci||(Ci={}));const er={Mercury:[[[[4.40250710144,0,0],[.40989414977,1.48302034195,26087.9031415742],[.050462942,4.47785489551,52175.8062831484],[.00855346844,1.16520322459,78263.70942472259],[.00165590362,4.11969163423,104351.61256629678],[.00034561897,.77930768443,130439.51570787099],[7583476e-11,3.71348404924,156527.41884944518]],[[26087.90313685529,0,0],[.01131199811,6.21874197797,26087.9031415742],[.00292242298,3.04449355541,52175.8062831484],[.00075775081,6.08568821653,78263.70942472259],[.00019676525,2.80965111777,104351.61256629678]]],[[[.11737528961,1.98357498767,26087.9031415742],[.02388076996,5.03738959686,52175.8062831484],[.01222839532,3.14159265359,0],[.0054325181,1.79644363964,78263.70942472259],[.0012977877,4.83232503958,104351.61256629678],[.00031866927,1.58088495658,130439.51570787099],[7963301e-11,4.60972126127,156527.41884944518]],[[.00274646065,3.95008450011,26087.9031415742],[.00099737713,3.14159265359,0]]],[[[.39528271651,0,0],[.07834131818,6.19233722598,26087.9031415742],[.00795525558,2.95989690104,52175.8062831484],[.00121281764,6.01064153797,78263.70942472259],[.00021921969,2.77820093972,104351.61256629678],[4354065e-11,5.82894543774,130439.51570787099]],[[.0021734774,4.65617158665,26087.9031415742],[.00044141826,1.42385544001,52175.8062831484]]]],Venus:[[[[3.17614666774,0,0],[.01353968419,5.59313319619,10213.285546211],[.00089891645,5.30650047764,20426.571092422],[5477194e-11,4.41630661466,7860.4193924392],[3455741e-11,2.6996444782,11790.6290886588],[2372061e-11,2.99377542079,3930.2096962196],[1317168e-11,5.18668228402,26.2983197998],[1664146e-11,4.25018630147,1577.3435424478],[1438387e-11,4.15745084182,9683.5945811164],[1200521e-11,6.15357116043,30639.856638633]],[[10213.28554621638,0,0],[.00095617813,2.4640651111,10213.285546211],[7787201e-11,.6247848222,20426.571092422]]],[[[.05923638472,.26702775812,10213.285546211],[.00040107978,1.14737178112,20426.571092422],[.00032814918,3.14159265359,0]],[[.00287821243,1.88964962838,10213.285546211]]],[[[.72334820891,0,0],[.00489824182,4.02151831717,10213.285546211],[1658058e-11,4.90206728031,20426.571092422],[1378043e-11,1.12846591367,11790.6290886588],[1632096e-11,2.84548795207,7860.4193924392],[498395e-11,2.58682193892,9683.5945811164],[221985e-11,2.01346696541,19367.1891622328],[237454e-11,2.55136053886,15720.8387848784]],[[.00034551041,.89198706276,10213.285546211]]]],Earth:[[[[1.75347045673,0,0],[.03341656453,4.66925680415,6283.0758499914],[.00034894275,4.62610242189,12566.1516999828],[3417572e-11,2.82886579754,3.523118349],[3497056e-11,2.74411783405,5753.3848848968],[3135899e-11,3.62767041756,77713.7714681205],[2676218e-11,4.41808345438,7860.4193924392],[2342691e-11,6.13516214446,3930.2096962196],[1273165e-11,2.03709657878,529.6909650946],[1324294e-11,.74246341673,11506.7697697936],[901854e-11,2.04505446477,26.2983197998],[1199167e-11,1.10962946234,1577.3435424478],[857223e-11,3.50849152283,398.1490034082],[779786e-11,1.17882681962,5223.6939198022],[99025e-10,5.23268072088,5884.9268465832],[753141e-11,2.53339052847,5507.5532386674],[505267e-11,4.58292599973,18849.2275499742],[492392e-11,4.20505711826,775.522611324],[356672e-11,2.91954114478,.0673103028],[284125e-11,1.89869240932,796.2980068164],[242879e-11,.34481445893,5486.777843175],[317087e-11,5.84901948512,11790.6290886588],[271112e-11,.31486255375,10977.078804699],[206217e-11,4.80646631478,2544.3144198834],[205478e-11,1.86953770281,5573.1428014331],[202318e-11,2.45767790232,6069.7767545534],[126225e-11,1.08295459501,20.7753954924],[155516e-11,.83306084617,213.299095438]],[[6283.0758499914,0,0],[.00206058863,2.67823455808,6283.0758499914],[4303419e-11,2.63512233481,12566.1516999828]],[[8721859e-11,1.07253635559,6283.0758499914]]],[[],[[.00227777722,3.4137662053,6283.0758499914],[3805678e-11,3.37063423795,12566.1516999828]]],[[[1.00013988784,0,0],[.01670699632,3.09846350258,6283.0758499914],[.00013956024,3.05524609456,12566.1516999828],[308372e-10,5.19846674381,77713.7714681205],[1628463e-11,1.17387558054,5753.3848848968],[1575572e-11,2.84685214877,7860.4193924392],[924799e-11,5.45292236722,11506.7697697936],[542439e-11,4.56409151453,3930.2096962196],[47211e-10,3.66100022149,5884.9268465832],[85831e-11,1.27079125277,161000.6857376741],[57056e-11,2.01374292245,83996.84731811189],[55736e-11,5.2415979917,71430.69561812909],[174844e-11,3.01193636733,18849.2275499742],[243181e-11,4.2734953079,11790.6290886588]],[[.00103018607,1.10748968172,6283.0758499914],[1721238e-11,1.06442300386,12566.1516999828]],[[4359385e-11,5.78455133808,6283.0758499914]]]],Mars:[[[[6.20347711581,0,0],[.18656368093,5.0503710027,3340.6124266998],[.01108216816,5.40099836344,6681.2248533996],[.00091798406,5.75478744667,10021.8372800994],[.00027744987,5.97049513147,3.523118349],[.00010610235,2.93958560338,2281.2304965106],[.00012315897,.84956094002,2810.9214616052],[8926784e-11,4.15697846427,.0172536522],[8715691e-11,6.11005153139,13362.4497067992],[6797556e-11,.36462229657,398.1490034082],[7774872e-11,3.33968761376,5621.8429232104],[3575078e-11,1.6618650571,2544.3144198834],[4161108e-11,.22814971327,2942.4634232916],[3075252e-11,.85696614132,191.4482661116],[2628117e-11,.64806124465,3337.0893083508],[2937546e-11,6.07893711402,.0673103028],[2389414e-11,5.03896442664,796.2980068164],[2579844e-11,.02996736156,3344.1355450488],[1528141e-11,1.14979301996,6151.533888305],[1798806e-11,.65634057445,529.6909650946],[1264357e-11,3.62275122593,5092.1519581158],[1286228e-11,3.06796065034,2146.1654164752],[1546404e-11,2.91579701718,1751.539531416],[1024902e-11,3.69334099279,8962.4553499102],[891566e-11,.18293837498,16703.062133499],[858759e-11,2.4009381194,2914.0142358238],[832715e-11,2.46418619474,3340.5951730476],[83272e-10,4.49495782139,3340.629680352],[712902e-11,3.66335473479,1059.3819301892],[748723e-11,3.82248614017,155.4203994342],[723861e-11,.67497311481,3738.761430108],[635548e-11,2.92182225127,8432.7643848156],[655162e-11,.48864064125,3127.3133312618],[550474e-11,3.81001042328,.9803210682],[55275e-10,4.47479317037,1748.016413067],[425966e-11,.55364317304,6283.0758499914],[415131e-11,.49662285038,213.299095438],[472167e-11,3.62547124025,1194.4470102246],[306551e-11,.38052848348,6684.7479717486],[312141e-11,.99853944405,6677.7017350506],[293198e-11,4.22131299634,20.7753954924],[302375e-11,4.48618007156,3532.0606928114],[274027e-11,.54222167059,3340.545116397],[281079e-11,5.88163521788,1349.8674096588],[231183e-11,1.28242156993,3870.3033917944],[283602e-11,5.7688543494,3149.1641605882],[236117e-11,5.75503217933,3333.498879699],[274033e-11,.13372524985,3340.6797370026],[299395e-11,2.78323740866,6254.6266625236]],[[3340.61242700512,0,0],[.01457554523,3.60433733236,3340.6124266998],[.00168414711,3.92318567804,6681.2248533996],[.00020622975,4.26108844583,10021.8372800994],[3452392e-11,4.7321039319,3.523118349],[2586332e-11,4.60670058555,13362.4497067992],[841535e-11,4.45864030426,2281.2304965106]],[[.00058152577,2.04961712429,3340.6124266998],[.00013459579,2.45738706163,6681.2248533996]]],[[[.03197134986,3.76832042431,3340.6124266998],[.00298033234,4.10616996305,6681.2248533996],[.00289104742,0,0],[.00031365539,4.4465105309,10021.8372800994],[34841e-9,4.7881254926,13362.4497067992]],[[.00217310991,6.04472194776,3340.6124266998],[.00020976948,3.14159265359,0],[.00012834709,1.60810667915,6681.2248533996]]],[[[1.53033488271,0,0],[.1418495316,3.47971283528,3340.6124266998],[.00660776362,3.81783443019,6681.2248533996],[.00046179117,4.15595316782,10021.8372800994],[8109733e-11,5.55958416318,2810.9214616052],[7485318e-11,1.77239078402,5621.8429232104],[5523191e-11,1.3643630377,2281.2304965106],[382516e-10,4.49407183687,13362.4497067992],[2306537e-11,.09081579001,2544.3144198834],[1999396e-11,5.36059617709,3337.0893083508],[2484394e-11,4.9254563992,2942.4634232916],[1960195e-11,4.74249437639,3344.1355450488],[1167119e-11,2.11260868341,5092.1519581158],[1102816e-11,5.00908403998,398.1490034082],[899066e-11,4.40791133207,529.6909650946],[992252e-11,5.83861961952,6151.533888305],[807354e-11,2.10217065501,1059.3819301892],[797915e-11,3.44839203899,796.2980068164],[740975e-11,1.49906336885,2146.1654164752]],[[.01107433345,2.03250524857,3340.6124266998],[.00103175887,2.37071847807,6681.2248533996],[128772e-9,0,0],[.0001081588,2.70888095665,10021.8372800994]],[[.00044242249,.47930604954,3340.6124266998],[8138042e-11,.86998389204,6681.2248533996]]]],Jupiter:[[[[.59954691494,0,0],[.09695898719,5.06191793158,529.6909650946],[.00573610142,1.44406205629,7.1135470008],[.00306389205,5.41734730184,1059.3819301892],[.00097178296,4.14264726552,632.7837393132],[.00072903078,3.64042916389,522.5774180938],[.00064263975,3.41145165351,103.0927742186],[.00039806064,2.29376740788,419.4846438752],[.00038857767,1.27231755835,316.3918696566],[.00027964629,1.7845459182,536.8045120954],[.0001358973,5.7748104079,1589.0728952838],[8246349e-11,3.5822792584,206.1855484372],[8768704e-11,3.63000308199,949.1756089698],[7368042e-11,5.0810119427,735.8765135318],[626315e-10,.02497628807,213.299095438],[6114062e-11,4.51319998626,1162.4747044078],[4905396e-11,1.32084470588,110.2063212194],[5305285e-11,1.30671216791,14.2270940016],[5305441e-11,4.18625634012,1052.2683831884],[4647248e-11,4.69958103684,3.9321532631],[3045023e-11,4.31676431084,426.598190876],[2609999e-11,1.56667394063,846.0828347512],[2028191e-11,1.06376530715,3.1813937377],[1764763e-11,2.14148655117,1066.49547719],[1722972e-11,3.88036268267,1265.5674786264],[1920945e-11,.97168196472,639.897286314],[1633223e-11,3.58201833555,515.463871093],[1431999e-11,4.29685556046,625.6701923124],[973272e-11,4.09764549134,95.9792272178]],[[529.69096508814,0,0],[.00489503243,4.2208293947,529.6909650946],[.00228917222,6.02646855621,7.1135470008],[.00030099479,4.54540782858,1059.3819301892],[.0002072092,5.45943156902,522.5774180938],[.00012103653,.16994816098,536.8045120954],[6067987e-11,4.42422292017,103.0927742186],[5433968e-11,3.98480737746,419.4846438752],[4237744e-11,5.89008707199,14.2270940016]],[[.00047233601,4.32148536482,7.1135470008],[.00030649436,2.929777887,529.6909650946],[.00014837605,3.14159265359,0]]],[[[.02268615702,3.55852606721,529.6909650946],[.00109971634,3.90809347197,1059.3819301892],[.00110090358,0,0],[8101428e-11,3.60509572885,522.5774180938],[6043996e-11,4.25883108339,1589.0728952838],[6437782e-11,.30627119215,536.8045120954]],[[.00078203446,1.52377859742,529.6909650946]]],[[[5.20887429326,0,0],[.25209327119,3.49108639871,529.6909650946],[.00610599976,3.84115365948,1059.3819301892],[.00282029458,2.57419881293,632.7837393132],[.00187647346,2.07590383214,522.5774180938],[.00086792905,.71001145545,419.4846438752],[.00072062974,.21465724607,536.8045120954],[.00065517248,5.9799588479,316.3918696566],[.00029134542,1.67759379655,103.0927742186],[.00030135335,2.16132003734,949.1756089698],[.00023453271,3.54023522184,735.8765135318],[.00022283743,4.19362594399,1589.0728952838],[.00023947298,.2745803748,7.1135470008],[.00013032614,2.96042965363,1162.4747044078],[970336e-10,1.90669633585,206.1855484372],[.00012749023,2.71550286592,1052.2683831884],[7057931e-11,2.18184839926,1265.5674786264],[6137703e-11,6.26418240033,846.0828347512],[2616976e-11,2.00994012876,1581.959348283]],[[.0127180152,2.64937512894,529.6909650946],[.00061661816,3.00076460387,1059.3819301892],[.00053443713,3.89717383175,522.5774180938],[.00031185171,4.88276958012,536.8045120954],[.00041390269,0,0]]]],Saturn:[[[[.87401354025,0,0],[.11107659762,3.96205090159,213.299095438],[.01414150957,4.58581516874,7.1135470008],[.00398379389,.52112032699,206.1855484372],[.00350769243,3.30329907896,426.598190876],[.00206816305,.24658372002,103.0927742186],[792713e-9,3.84007056878,220.4126424388],[.00023990355,4.66976924553,110.2063212194],[.00016573588,.43719228296,419.4846438752],[.00014906995,5.76903183869,316.3918696566],[.0001582029,.93809155235,632.7837393132],[.00014609559,1.56518472,3.9321532631],[.00013160301,4.44891291899,14.2270940016],[.00015053543,2.71669915667,639.897286314],[.00013005299,5.98119023644,11.0457002639],[.00010725067,3.12939523827,202.2533951741],[5863206e-11,.23656938524,529.6909650946],[5227757e-11,4.20783365759,3.1813937377],[6126317e-11,1.76328667907,277.0349937414],[5019687e-11,3.17787728405,433.7117378768],[459255e-10,.61977744975,199.0720014364],[4005867e-11,2.24479718502,63.7358983034],[2953796e-11,.98280366998,95.9792272178],[387367e-10,3.22283226966,138.5174968707],[2461186e-11,2.03163875071,735.8765135318],[3269484e-11,.77492638211,949.1756089698],[1758145e-11,3.2658010994,522.5774180938],[1640172e-11,5.5050445305,846.0828347512],[1391327e-11,4.02333150505,323.5054166574],[1580648e-11,4.37265307169,309.2783226558],[1123498e-11,2.83726798446,415.5524906121],[1017275e-11,3.71700135395,227.5261894396],[848642e-11,3.1915017083,209.3669421749]],[[213.2990952169,0,0],[.01297370862,1.82834923978,213.299095438],[.00564345393,2.88499717272,7.1135470008],[.00093734369,1.06311793502,426.598190876],[.00107674962,2.27769131009,206.1855484372],[.00040244455,2.04108104671,220.4126424388],[.00019941774,1.2795439047,103.0927742186],[.00010511678,2.7488034213,14.2270940016],[6416106e-11,.38238295041,639.897286314],[4848994e-11,2.43037610229,419.4846438752],[4056892e-11,2.92133209468,110.2063212194],[3768635e-11,3.6496533078,3.9321532631]],[[.0011644133,1.17988132879,7.1135470008],[.00091841837,.0732519584,213.299095438],[.00036661728,0,0],[.00015274496,4.06493179167,206.1855484372]]],[[[.04330678039,3.60284428399,213.299095438],[.00240348302,2.85238489373,426.598190876],[.00084745939,0,0],[.00030863357,3.48441504555,220.4126424388],[.00034116062,.57297307557,206.1855484372],[.0001473407,2.11846596715,639.897286314],[9916667e-11,5.79003188904,419.4846438752],[6993564e-11,4.7360468972,7.1135470008],[4807588e-11,5.43305312061,316.3918696566]],[[.00198927992,4.93901017903,213.299095438],[.00036947916,3.14159265359,0],[.00017966989,.5197943111,426.598190876]]],[[[9.55758135486,0,0],[.52921382865,2.39226219573,213.299095438],[.01873679867,5.2354960466,206.1855484372],[.01464663929,1.64763042902,426.598190876],[.00821891141,5.93520042303,316.3918696566],[.00547506923,5.0153261898,103.0927742186],[.0037168465,2.27114821115,220.4126424388],[.00361778765,3.13904301847,7.1135470008],[.00140617506,5.70406606781,632.7837393132],[.00108974848,3.29313390175,110.2063212194],[.00069006962,5.94099540992,419.4846438752],[.00061053367,.94037691801,639.897286314],[.00048913294,1.55733638681,202.2533951741],[.00034143772,.19519102597,277.0349937414],[.00032401773,5.47084567016,949.1756089698],[.00020936596,.46349251129,735.8765135318],[9796004e-11,5.20477537945,1265.5674786264],[.00011993338,5.98050967385,846.0828347512],[208393e-9,1.52102476129,433.7117378768],[.00015298404,3.0594381494,529.6909650946],[6465823e-11,.17732249942,1052.2683831884],[.00011380257,1.7310542704,522.5774180938],[3419618e-11,4.94550542171,1581.959348283]],[[.0618298134,.2584351148,213.299095438],[.00506577242,.71114625261,206.1855484372],[.00341394029,5.79635741658,426.598190876],[.00188491195,.47215589652,220.4126424388],[.00186261486,3.14159265359,0],[.00143891146,1.40744822888,7.1135470008]],[[.00436902572,4.78671677509,213.299095438]]]],Uranus:[[[[5.48129294297,0,0],[.09260408234,.89106421507,74.7815985673],[.01504247898,3.6271926092,1.4844727083],[.00365981674,1.89962179044,73.297125859],[.00272328168,3.35823706307,149.5631971346],[.00070328461,5.39254450063,63.7358983034],[.00068892678,6.09292483287,76.2660712756],[.00061998615,2.26952066061,2.9689454166],[.00061950719,2.85098872691,11.0457002639],[.0002646877,3.14152083966,71.8126531507],[.00025710476,6.11379840493,454.9093665273],[.0002107885,4.36059339067,148.0787244263],[.00017818647,1.74436930289,36.6485629295],[.00014613507,4.73732166022,3.9321532631],[.00011162509,5.8268179635,224.3447957019],[.0001099791,.48865004018,138.5174968707],[9527478e-11,2.95516862826,35.1640902212],[7545601e-11,5.236265824,109.9456887885],[4220241e-11,3.23328220918,70.8494453042],[40519e-9,2.277550173,151.0476698429],[3354596e-11,1.0654900738,4.4534181249],[2926718e-11,4.62903718891,9.5612275556],[349034e-10,5.48306144511,146.594251718],[3144069e-11,4.75199570434,77.7505439839],[2922333e-11,5.35235361027,85.8272988312],[2272788e-11,4.36600400036,70.3281804424],[2051219e-11,1.51773566586,.1118745846],[2148602e-11,.60745949945,38.1330356378],[1991643e-11,4.92437588682,277.0349937414],[1376226e-11,2.04283539351,65.2203710117],[1666902e-11,3.62744066769,380.12776796],[1284107e-11,3.11347961505,202.2533951741],[1150429e-11,.93343589092,3.1813937377],[1533221e-11,2.58594681212,52.6901980395],[1281604e-11,.54271272721,222.8603229936],[1372139e-11,4.19641530878,111.4301614968],[1221029e-11,.1990065003,108.4612160802],[946181e-11,1.19253165736,127.4717966068],[1150989e-11,4.17898916639,33.6796175129]],[[74.7815986091,0,0],[.00154332863,5.24158770553,74.7815985673],[.00024456474,1.71260334156,1.4844727083],[9258442e-11,.4282973235,11.0457002639],[8265977e-11,1.50218091379,63.7358983034],[915016e-10,1.41213765216,149.5631971346]]],[[[.01346277648,2.61877810547,74.7815985673],[623414e-9,5.08111189648,149.5631971346],[.00061601196,3.14159265359,0],[9963722e-11,1.61603805646,76.2660712756],[992616e-10,.57630380333,73.297125859]],[[.00034101978,.01321929936,74.7815985673]]],[[[19.21264847206,0,0],[.88784984413,5.60377527014,74.7815985673],[.03440836062,.32836099706,73.297125859],[.0205565386,1.7829515933,149.5631971346],[.0064932241,4.52247285911,76.2660712756],[.00602247865,3.86003823674,63.7358983034],[.00496404167,1.40139935333,454.9093665273],[.00338525369,1.58002770318,138.5174968707],[.00243509114,1.57086606044,71.8126531507],[.00190522303,1.99809394714,1.4844727083],[.00161858838,2.79137786799,148.0787244263],[.00143706183,1.38368544947,11.0457002639],[.00093192405,.17437220467,36.6485629295],[.00071424548,4.24509236074,224.3447957019],[.00089806014,3.66105364565,109.9456887885],[.00039009723,1.66971401684,70.8494453042],[.00046677296,1.39976401694,35.1640902212],[.00039025624,3.36234773834,277.0349937414],[.00036755274,3.88649278513,146.594251718],[.00030348723,.70100838798,151.0476698429],[.00029156413,3.180563367,77.7505439839],[.00022637073,.72518687029,529.6909650946],[.00011959076,1.7504339214,984.6003316219],[.00025620756,5.25656086672,380.12776796]],[[.01479896629,3.67205697578,74.7815985673]]]],Neptune:[[[[5.31188633046,0,0],[.0179847553,2.9010127389,38.1330356378],[.01019727652,.48580922867,1.4844727083],[.00124531845,4.83008090676,36.6485629295],[.00042064466,5.41054993053,2.9689454166],[.00037714584,6.09221808686,35.1640902212],[.00033784738,1.24488874087,76.2660712756],[.00016482741,7727998e-11,491.5579294568],[9198584e-11,4.93747051954,39.6175083461],[899425e-10,.27462171806,175.1660598002]],[[38.13303563957,0,0],[.00016604172,4.86323329249,1.4844727083],[.00015744045,2.27887427527,38.1330356378]]],[[[.03088622933,1.44104372644,38.1330356378],[.00027780087,5.91271884599,76.2660712756],[.00027623609,0,0],[.00015355489,2.52123799551,36.6485629295],[.00015448133,3.50877079215,39.6175083461]]],[[[30.07013205828,0,0],[.27062259632,1.32999459377,38.1330356378],[.01691764014,3.25186135653,36.6485629295],[.00807830553,5.18592878704,1.4844727083],[.0053776051,4.52113935896,35.1640902212],[.00495725141,1.5710564165,491.5579294568],[.00274571975,1.84552258866,175.1660598002],[.0001201232,1.92059384991,1021.2488945514],[.00121801746,5.79754470298,76.2660712756],[.00100896068,.3770272493,73.297125859],[.00135134092,3.37220609835,39.6175083461],[7571796e-11,1.07149207335,388.4651552382]]]]};function hD(a){var e,t,i,n,s,r,o;const l=2e3+(a-14)/ZI;return l<-500?(e=(l-1820)/100,-20+32*e*e):l<500?(e=l/100,t=e*e,i=e*t,n=t*t,s=t*i,r=i*i,10583.6-1014.41*e+33.78311*t-5.952053*i-.1798452*n+.022174192*s+.0090316521*r):l<1600?(e=(l-1e3)/100,t=e*e,i=e*t,n=t*t,s=t*i,r=i*i,1574.2-556.01*e+71.23472*t+.319781*i-.8503463*n-.005050998*s+.0083572073*r):l<1700?(e=l-1600,t=e*e,i=e*t,120-.9808*e-.01532*t+i/7129):l<1800?(e=l-1700,t=e*e,i=e*t,n=t*t,8.83+.1603*e-.0059285*t+13336e-8*i-n/1174e3):l<1860?(e=l-1800,t=e*e,i=e*t,n=t*t,s=t*i,r=i*i,o=i*n,13.72-.332447*e+.0068612*t+.0041116*i-37436e-8*n+121272e-10*s-1699e-10*r+875e-12*o):l<1900?(e=l-1860,t=e*e,i=e*t,n=t*t,s=t*i,7.62+.5737*e-.251754*t+.01680668*i-.0004473624*n+s/233174):l<1920?(e=l-1900,t=e*e,i=e*t,n=t*t,-2.79+1.494119*e-.0598939*t+.0061966*i-197e-6*n):l<1941?(e=l-1920,t=e*e,i=e*t,21.2+.84493*e-.0761*t+.0020936*i):l<1961?(e=l-1950,t=e*e,i=e*t,29.07+.407*e-t/233+i/2547):l<1986?(e=l-1975,t=e*e,i=e*t,45.45+1.067*e-t/260-i/718):l<2005?(e=l-2e3,t=e*e,i=e*t,n=t*t,s=t*i,63.86+.3345*e-.060374*t+.0017275*i+651814e-9*n+2373599e-11*s):l<2050?(e=l-2e3,62.92+.32217*e+.005589*e*e):l<2150?(e=(l-1820)/100,-20+32*e*e-.5628*(2150-l)):(e=(l-1820)/100,-20+32*e*e)}let dD=hD;function Q1(a){return a+dD(a)/86400}class no{constructor(e){if(e instanceof no){this.date=e.date,this.ut=e.ut,this.tt=e.tt;return}const t=1e3*3600*24;if(e instanceof Date&&Number.isFinite(e.getTime())){this.date=e,this.ut=(e.getTime()-Z1.getTime())/t,this.tt=Q1(this.ut);return}if(Number.isFinite(e)){this.date=new Date(Z1.getTime()+e*t),this.ut=e,this.tt=Q1(this.ut);return}throw"Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date."}static FromTerrestrialTime(e){let t=new no(e);for(;;){const i=e-t.tt;if(Math.abs(i)<1e-12)return t;t=t.AddDays(i)}}toString(){return this.date.toISOString()}AddDays(e){return new no(this.ut+e)}}function uD(a,e,t){return new no(a.ut+t*(e.ut-a.ut))}function Ht(a){return a instanceof no?a:new no(a)}function pD(a){function e(u){return u%jI*nl}const t=a.tt/36525,i=e(128710479305e-5+t*1295965810481e-4),n=e(335779.526232+t*17395272628478e-4),s=e(107226070369e-5+t*1602961601209e-3),r=e(450160.398036-t*69628905431e-4);let o=Math.sin(r),l=Math.cos(r),c=(-172064161-174666*t)*o+33386*l,h=(92052331+9086*t)*l+15377*o,d=2*(n-s+r);return o=Math.sin(d),l=Math.cos(d),c+=(-13170906-1675*t)*o-13696*l,h+=(5730336-3015*t)*l-4587*o,d=2*(n+r),o=Math.sin(d),l=Math.cos(d),c+=(-2276413-234*t)*o+2796*l,h+=(978459-485*t)*l+1374*o,d=2*r,o=Math.sin(d),l=Math.cos(d),c+=(2074554+207*t)*o-698*l,h+=(-897492+470*t)*l-291*o,o=Math.sin(i),l=Math.cos(i),c+=(1475877-3633*t)*o+11817*l,h+=(73871-184*t)*l-1924*o,{dpsi:-135e-6+c*1e-7,deps:388e-6+h*1e-7}}function nw(a){var e=a.tt/36525,t=((((-434e-10*e-576e-9)*e+.0020034)*e-1831e-7)*e-46.836769)*e+84381.406;return t/3600}var jh;function oh(a){if(!jh||Math.abs(jh.tt-a.tt)>1e-6){const e=pD(a),t=nw(a),i=t+e.deps/3600;jh={tt:a.tt,dpsi:e.dpsi,deps:e.deps,ee:e.dpsi*Math.cos(t*ge)/15,mobl:t,tobl:i}}return jh}function fD(a,e){const t=a*ge,i=Math.cos(t),n=Math.sin(t);return[e[0],e[1]*i-e[2]*n,e[1]*n+e[2]*i]}function mD(a,e){return fD(nw(a),e)}function sw(a){const e=a.tt/36525;function t(ke,Ee){const He=[];let Ge;for(Ge=0;Ge<=Ee-ke;++Ge)He.push(0);return{min:ke,array:He}}function i(ke,Ee,He,Ge){const Ve=[];for(let Lt=0;Lt<=Ee-ke;++Lt)Ve.push(t(He,Ge));return{min:ke,array:Ve}}function n(ke,Ee,He){const Ge=ke.array[Ee-ke.min];return Ge.array[He-Ge.min]}function s(ke,Ee,He,Ge){const Ve=ke.array[Ee-ke.min];Ve.array[He-Ve.min]=Ge}let r,o,l,c,h,d,u,p,f,g,m,v,x,y,b,w,S,_,M,T,A,R,C,k=i(-6,6,1,4),z=i(-6,6,1,4);function L(ke,Ee){return n(k,ke,Ee)}function N(ke,Ee){return n(z,ke,Ee)}function F(ke,Ee,He){return s(k,ke,Ee,He)}function V(ke,Ee,He){return s(z,ke,Ee,He)}function Z(ke,Ee,He,Ge,Ve){Ve(ke*He-Ee*Ge,Ee*He+ke*Ge)}function K(ke){return Math.sin(gr*ke)}u=e*e,f=0,C=0,m=0,v=3422.7;var ie=K(.19833+.05611*e),oe=K(.27869+.04508*e),qe=K(.16827-.36903*e),ot=K(.34734-5.37261*e),Qe=K(.10498-5.37899*e),q=K(.42681-.41855*e),re=K(.14943-5.37511*e);for(_=.84*ie+.31*oe+14.27*qe+7.26*ot+.28*Qe+.24*q,M=2.94*ie+.31*oe+14.27*qe+9.34*ot+1.12*Qe+.83*q,T=-6.4*ie-1.89*q,A=.21*ie+.31*oe+14.27*qe-88.7*ot-15.3*Qe+.24*q-1.86*re,R=_-T,p=-3332e-9*K(.59734-5.37261*e)-539e-9*K(.35498-5.37899*e)-64e-9*K(.39943-5.37511*e),x=gr*Wo(.60643382+1336.85522467*e-313e-8*u)+_/Gr,y=gr*Wo(.37489701+1325.55240982*e+2565e-8*u)+M/Gr,b=gr*Wo(.99312619+99.99735956*e-44e-8*u)+T/Gr,w=gr*Wo(.25909118+1342.2278298*e-892e-8*u)+A/Gr,S=gr*Wo(.82736186+1236.85308708*e-397e-8*u)+R/Gr,h=1;h<=4;++h){switch(h){case 1:l=y,o=4,c=1.000002208;break;case 2:l=b,o=3,c=.997504612-.002495388*e;break;case 3:l=w,o=4,c=1.000002708+139.978*p;break;case 4:l=S,o=6,c=1;break;default:throw`Internal error: I = ${h}`}for(F(0,h,1),F(1,h,Math.cos(l)*c),V(0,h,0),V(1,h,Math.sin(l)*c),d=2;d<=o;++d)Z(L(d-1,h),N(d-1,h),L(1,h),N(1,h),(ke,Ee)=>(F(d,h,ke),V(d,h,Ee)));for(d=1;d<=o;++d)F(-d,h,L(d,h)),V(-d,h,-N(d,h))}function ne(ke,Ee,He,Ge){for(var Ve={x:1,y:0},Lt=[0,ke,Ee,He,Ge],kt=1;kt<=4;++kt)Lt[kt]!==0&&Z(Ve.x,Ve.y,L(Lt[kt],kt),N(Lt[kt],kt),(pi,si)=>(Ve.x=pi,Ve.y=si));return Ve}function G(ke,Ee,He,Ge,Ve,Lt,kt,pi){var si=ne(Ve,Lt,kt,pi);f+=ke*si.y,C+=Ee*si.y,m+=He*si.x,v+=Ge*si.x}G(13.902,14.06,-.001,.2607,0,0,0,4),G(.403,-4.01,.394,.0023,0,0,0,3),G(2369.912,2373.36,.601,28.2333,0,0,0,2),G(-125.154,-112.79,-.725,-.9781,0,0,0,1),G(1.979,6.98,-.445,.0433,1,0,0,4),G(191.953,192.72,.029,3.0861,1,0,0,2),G(-8.466,-13.51,.455,-.1093,1,0,0,1),G(22639.5,22609.07,.079,186.5398,1,0,0,0),G(18.609,3.59,-.094,.0118,1,0,0,-1),G(-4586.465,-4578.13,-.077,34.3117,1,0,0,-2),G(3.215,5.44,.192,-.0386,1,0,0,-3),G(-38.428,-38.64,.001,.6008,1,0,0,-4),G(-.393,-1.43,-.092,.0086,1,0,0,-6),G(-.289,-1.59,.123,-.0053,0,1,0,4),G(-24.42,-25.1,.04,-.3,0,1,0,2),G(18.023,17.93,.007,.1494,0,1,0,1),G(-668.146,-126.98,-1.302,-.3997,0,1,0,0),G(.56,.32,-.001,-.0037,0,1,0,-1),G(-165.145,-165.06,.054,1.9178,0,1,0,-2),G(-1.877,-6.46,-.416,.0339,0,1,0,-4),G(.213,1.02,-.074,.0054,2,0,0,4),G(14.387,14.78,-.017,.2833,2,0,0,2),G(-.586,-1.2,.054,-.01,2,0,0,1),G(769.016,767.96,.107,10.1657,2,0,0,0),G(1.75,2.01,-.018,.0155,2,0,0,-1),G(-211.656,-152.53,5.679,-.3039,2,0,0,-2),G(1.225,.91,-.03,-.0088,2,0,0,-3),G(-30.773,-34.07,-.308,.3722,2,0,0,-4),G(-.57,-1.4,-.074,.0109,2,0,0,-6),G(-2.921,-11.75,.787,-.0484,1,1,0,2),G(1.267,1.52,-.022,.0164,1,1,0,1),G(-109.673,-115.18,.461,-.949,1,1,0,0),G(-205.962,-182.36,2.056,1.4437,1,1,0,-2),G(.233,.36,.012,-.0025,1,1,0,-3),G(-4.391,-9.66,-.471,.0673,1,1,0,-4),G(.283,1.53,-.111,.006,1,-1,0,4),G(14.577,31.7,-1.54,.2302,1,-1,0,2),G(147.687,138.76,.679,1.1528,1,-1,0,0),G(-1.089,.55,.021,0,1,-1,0,-1),G(28.475,23.59,-.443,-.2257,1,-1,0,-2),G(-.276,-.38,-.006,-.0036,1,-1,0,-3),G(.636,2.27,.146,-.0102,1,-1,0,-4),G(-.189,-1.68,.131,-.0028,0,2,0,2),G(-7.486,-.66,-.037,-.0086,0,2,0,0),G(-8.096,-16.35,-.74,.0918,0,2,0,-2),G(-5.741,-.04,0,-9e-4,0,0,2,2),G(.255,0,0,0,0,0,2,1),G(-411.608,-.2,0,-.0124,0,0,2,0),G(.584,.84,0,.0071,0,0,2,-1),G(-55.173,-52.14,0,-.1052,0,0,2,-2),G(.254,.25,0,-.0017,0,0,2,-3),G(.025,-1.67,0,.0031,0,0,2,-4),G(1.06,2.96,-.166,.0243,3,0,0,2),G(36.124,50.64,-1.3,.6215,3,0,0,0),G(-13.193,-16.4,.258,-.1187,3,0,0,-2),G(-1.187,-.74,.042,.0074,3,0,0,-4),G(-.293,-.31,-.002,.0046,3,0,0,-6),G(-.29,-1.45,.116,-.0051,2,1,0,2),G(-7.649,-10.56,.259,-.1038,2,1,0,0),G(-8.627,-7.59,.078,-.0192,2,1,0,-2),G(-2.74,-2.54,.022,.0324,2,1,0,-4),G(1.181,3.32,-.212,.0213,2,-1,0,2),G(9.703,11.67,-.151,.1268,2,-1,0,0),G(-.352,-.37,.001,-.0028,2,-1,0,-1),G(-2.494,-1.17,-.003,-.0017,2,-1,0,-2),G(.36,.2,-.012,-.0043,2,-1,0,-4),G(-1.167,-1.25,.008,-.0106,1,2,0,0),G(-7.412,-6.12,.117,.0484,1,2,0,-2),G(-.311,-.65,-.032,.0044,1,2,0,-4),G(.757,1.82,-.105,.0112,1,-2,0,2),G(2.58,2.32,.027,.0196,1,-2,0,0),G(2.533,2.4,-.014,-.0212,1,-2,0,-2),G(-.344,-.57,-.025,.0036,0,3,0,-2),G(-.992,-.02,0,0,1,0,2,2),G(-45.099,-.02,0,-.001,1,0,2,0),G(-.179,-9.52,0,-.0833,1,0,2,-2),G(-.301,-.33,0,.0014,1,0,2,-4),G(-6.382,-3.37,0,-.0481,1,0,-2,2),G(39.528,85.13,0,-.7136,1,0,-2,0),G(9.366,.71,0,-.0112,1,0,-2,-2),G(.202,.02,0,0,1,0,-2,-4),G(.415,.1,0,.0013,0,1,2,0),G(-2.152,-2.26,0,-.0066,0,1,2,-2),G(-1.44,-1.3,0,.0014,0,1,-2,2),G(.384,-.04,0,0,0,1,-2,-2),G(1.938,3.6,-.145,.0401,4,0,0,0),G(-.952,-1.58,.052,-.013,4,0,0,-2),G(-.551,-.94,.032,-.0097,3,1,0,0),G(-.482,-.57,.005,-.0045,3,1,0,-2),G(.681,.96,-.026,.0115,3,-1,0,0),G(-.297,-.27,.002,-9e-4,2,2,0,-2),G(.254,.21,-.003,0,2,-2,0,-2),G(-.25,-.22,.004,.0014,1,3,0,-2),G(-3.996,0,0,4e-4,2,0,2,0),G(.557,-.75,0,-.009,2,0,2,-2),G(-.459,-.38,0,-.0053,2,0,-2,2),G(-1.298,.74,0,4e-4,2,0,-2,0),G(.538,1.14,0,-.0141,2,0,-2,-2),G(.263,.02,0,0,1,1,2,0),G(.426,.07,0,-6e-4,1,1,-2,-2),G(-.304,.03,0,3e-4,1,-1,2,0),G(-.372,-.19,0,-.0027,1,-1,-2,2),G(.418,0,0,0,0,0,4,0),G(-.33,-.04,0,0,3,0,2,0);function Re(ke,Ee,He,Ge,Ve){return ke*ne(Ee,He,Ge,Ve).y}g=0,g+=Re(-526.069,0,0,1,-2),g+=Re(-3.352,0,0,1,-4),g+=Re(44.297,1,0,1,-2),g+=Re(-6,1,0,1,-4),g+=Re(20.599,-1,0,1,0),g+=Re(-30.598,-1,0,1,-2),g+=Re(-24.649,-2,0,1,0),g+=Re(-2,-2,0,1,-2),g+=Re(-22.571,0,1,1,-2),g+=Re(10.985,0,-1,1,-2),f+=.82*K(.7736-62.5512*e)+.31*K(.0466-125.1025*e)+.35*K(.5785-25.1042*e)+.66*K(.4591+1335.8075*e)+.64*K(.313-91.568*e)+1.14*K(.148+1331.2898*e)+.21*K(.5918+1056.5859*e)+.44*K(.5784+1322.8595*e)+.24*K(.2275-5.7374*e)+.28*K(.2965+2.6929*e)+.33*K(.3132+6.3368*e),r=w+C/Gr;let Ue=(1.000002708+139.978*p)*(18518.511+1.189+m)*Math.sin(r)-6.24*Math.sin(3*r)+g;return{geo_eclip_lon:gr*Wo((x+f/Gr)/gr),geo_eclip_lat:Math.PI/(180*3600)*Ue,distance_au:Gr*nD/(.999953253*v)}}function rw(a,e){return[a.rot[0][0]*e[0]+a.rot[1][0]*e[1]+a.rot[2][0]*e[2],a.rot[0][1]*e[0]+a.rot[1][1]*e[1]+a.rot[2][1]*e[2],a.rot[0][2]*e[0]+a.rot[1][2]*e[1]+a.rot[2][2]*e[2]]}function jc(a,e,t){const i=cg(e,t);return rw(i,a)}function cg(a,e){const t=a.tt/36525;let i=84381.406,n=((((-951e-10*t+132851e-9)*t-.00114045)*t-1.0790069)*t+5038.481507)*t,s=((((3337e-10*t-467e-9)*t-.00772503)*t+.0512623)*t-.025754)*t+i,r=((((-56e-9*t+170663e-9)*t-.00121197)*t-2.3814292)*t+10.556403)*t;i*=nl,n*=nl,s*=nl,r*=nl;const o=Math.sin(i),l=Math.cos(i),c=Math.sin(-n),h=Math.cos(-n),d=Math.sin(-s),u=Math.cos(-s),p=Math.sin(r),f=Math.cos(r),g=f*h-c*p*u,m=f*c*l+p*u*h*l-o*p*d,v=f*c*o+p*u*h*o+l*p*d,x=-p*h-c*f*u,y=-p*c*l+f*u*h*l-o*f*d,b=-p*c*o+f*u*h*o+l*f*d,w=c*d,S=-d*h*l-o*u,_=-d*h*o+u*l;if(e===Ci.Into2000)return new or([[g,m,v],[x,y,b],[w,S,_]]);if(e===Ci.From2000)return new or([[g,x,w],[m,y,S],[v,b,_]]);throw"Invalid precess direction"}function gD(a){const e=.779057273264+.00273781191135448*a.ut,t=a.ut%1;let i=360*((e+t)%1);return i<0&&(i+=360),i}let Jh;function lh(a){if(!Jh||Jh.tt!==a.tt){const e=a.tt/36525;let t=15*oh(a).ee;const i=gD(a);let s=((t+.014506+((((-368e-10*e-29956e-9)*e-44e-8)*e+1.3915817)*e+4612.156534)*e)/3600+i)%360/15;s<0&&(s+=24),Jh={tt:a.tt,st:s}}return Jh.st}function vD(a){const e=Ht(a);return lh(e)}function aw(a,e){const t=a.latitude*ge,i=Math.sin(t),n=Math.cos(t),s=1/Math.hypot(n,J0*i),r=iD*s,o=a.height/1e3,l=Q0*s+o,c=Q0*r+o,h=(15*e+a.longitude)*ge,d=Math.sin(h),u=Math.cos(h);return{pos:[l*n*u/js,l*n*d/js,c*i/js],vel:[-j1*l*n*d*86400/js,j1*l*n*u*86400/js,0]}}function Du(a,e,t){const i=hg(e,t);return rw(i,a)}function hg(a,e){const t=oh(a),i=t.mobl*ge,n=t.tobl*ge,s=t.dpsi*nl,r=Math.cos(i),o=Math.sin(i),l=Math.cos(n),c=Math.sin(n),h=Math.cos(s),d=Math.sin(s),u=h,p=-d*r,f=-d*o,g=d*l,m=h*r*l+o*c,v=h*o*l-r*c,x=d*c,y=h*r*c-o*l,b=h*o*c+r*l;if(e===Ci.From2000)return new or([[u,g,x],[p,m,y],[f,v,b]]);if(e===Ci.Into2000)return new or([[u,p,f],[g,m,v],[x,y,b]]);throw"Invalid precess direction"}function ip(a,e,t){return t===Ci.Into2000?jc(Du(a,e,t),e,t):Du(jc(a,e,t),e,t)}function ow(a,e){const t=lh(a),i=aw(e,t).pos;return ip(i,a,Ci.Into2000)}class Mt{constructor(e,t,i,n){this.x=e,this.y=t,this.z=i,this.t=n}Length(){return Math.hypot(this.x,this.y,this.z)}}class ra{constructor(e,t,i,n,s,r,o){this.x=e,this.y=t,this.z=i,this.vx=n,this.vy=s,this.vz=r,this.t=o}}class np{constructor(e,t,i){this.lat=Ai(e),this.lon=Ai(t),this.dist=Ai(i)}}class sm{constructor(e,t,i,n){this.ra=Ai(e),this.dec=Ai(t),this.dist=Ai(i),this.vec=n}}class or{constructor(e){this.rot=e}}class bD{constructor(e,t,i,n){this.azimuth=Ai(e),this.altitude=Ai(t),this.ra=Ai(i),this.dec=Ai(n)}}class yD{constructor(e,t,i){this.vec=e,this.elat=Ai(t),this.elon=Ai(i)}}function lw(a,e){return new Mt(a[0],a[1],a[2],e)}function MD(a,e){const t=lw(a,e),i=t.x*t.x+t.y*t.y,n=Math.sqrt(i+t.z*t.z);if(i===0){if(t.z===0)throw"Indeterminate sky coordinates";return new sm(0,t.z<0?-90:90,n,t)}let s=QM*Math.atan2(t.y,t.x);s<0&&(s+=24);const r=Ds*Math.atan2(a[2],Math.sqrt(i));return new sm(s,r,n,t)}function wl(a,e){const t=a*ge,i=Math.cos(t),n=Math.sin(t);return[i*e[0]+n*e[1],i*e[1]-n*e[0],e[2]]}function dg(a,e,t,i,n){let s=Ht(a);sp(e),Ai(t),Ai(i);const r=Math.sin(e.latitude*ge),o=Math.cos(e.latitude*ge),l=Math.sin(e.longitude*ge),c=Math.cos(e.longitude*ge),h=Math.sin(i*ge),d=Math.cos(i*ge),u=Math.sin(t*K1),p=Math.cos(t*K1);let f=[o*c,o*l,r],g=[-r*c,-r*l,o],m=[l,-c,0];const v=-15*lh(s);let x=wl(v,f),y=wl(v,g),b=wl(v,m),w=[d*p,d*u,h];const S=w[0]*x[0]+w[1]*x[1]+w[2]*x[2],_=w[0]*y[0]+w[1]*y[1]+w[2]*y[2],M=w[0]*b[0]+w[1]*b[1]+w[2]*b[2];let T=Math.hypot(_,M),A;T>0?(A=-Ds*Math.atan2(M,_),A<0&&(A+=360)):A=0;let R=Ds*Math.atan2(T,S),C=t,k=i;if(n){let z=R,L=vw(n,90-R);if(R-=L,L>0&&R>3e-4){const N=Math.sin(R*ge),F=Math.cos(R*ge),V=Math.sin(z*ge),Z=Math.cos(z*ge),K=[];for(let ie=0;ie<3;++ie)K.push((w[ie]-Z*x[ie])/V*N+x[ie]*F);T=Math.hypot(K[0],K[1]),T>0?(C=QM*Math.atan2(K[1],K[0]),C<0&&(C+=24)):C=0,k=Ds*Math.atan2(K[2],T)}}return new bD(A,90-R,C,k)}function sp(a){if(!(a instanceof ha))throw`Not an instance of the Observer class: ${a}`;if(Ai(a.latitude),Ai(a.longitude),Ai(a.height),a.latitude<-90||a.latitude>90)throw`Latitude ${a.latitude} is out of range. Must be -90..+90.`;return a}class ha{constructor(e,t,i){this.latitude=e,this.longitude=t,this.height=i,sp(this)}}function wD(a){const e=Ht(a).AddDays(-1/ag),t=Sl(er.Earth,e),i=[-t.x,-t.y,-t.z],[n,s,r]=ip(i,e,Ci.From2000),o=ge*oh(e).tobl,l=Math.cos(o),c=Math.sin(o),h=new Mt(n,s,r,e);return cw(h,l,c)}function Jc(a,e,t,i,n){sp(t),Iu(i),Iu(n);const s=Ht(e),r=ow(s,t),o=Cu(a,s,n),l=[o.x-r[0],o.y-r[1],o.z-r[2]],c=ip(l,s,Ci.From2000);return MD(c,s)}function rm(a,e,t){const i=Ht(a),n=lh(i);let s=aw(e,n).pos;return t||(s=ip(s,i,Ci.Into2000)),lw(s,i)}function cw(a,e,t){const i=a.x,n=a.y*e+a.z*t,s=-a.y*t+a.z*e,r=Math.hypot(i,n);let o=0;r>0&&(o=Ds*Math.atan2(n,i),o<0&&(o+=360));let l=Ds*Math.atan2(s,r),c=new Mt(i,n,s,a.t);return new yD(c,l,o)}function am(a){const e=oh(a.t),t=[a.x,a.y,a.z],i=jc(t,a.t,Ci.From2000),[n,s,r]=Du(i,a.t,Ci.From2000),o=new Mt(n,s,r,a.t),l=e.tobl*ge;return cw(o,Math.cos(l),Math.sin(l))}function Tr(a){const e=Ht(a),t=sw(e),i=t.distance_au*Math.cos(t.geo_eclip_lat),n=[i*Math.cos(t.geo_eclip_lon),i*Math.sin(t.geo_eclip_lon),t.distance_au*Math.sin(t.geo_eclip_lat)],s=mD(e,n),r=jc(s,e,Ci.Into2000);return new Mt(r[0],r[1],r[2],e)}function hw(a){const e=Ht(a),t=1e-5,i=e.AddDays(-t),n=e.AddDays(+t),s=Tr(i),r=Tr(n);return new ra((s.x+r.x)/2,(s.y+r.y)/2,(s.z+r.z)/2,(r.x-s.x)/(2*t),(r.y-s.y)/(2*t),(r.z-s.z)/(2*t),e)}function xD(a){const e=Ht(a),t=hw(e),i=1+tw;return new ra(t.x/i,t.y/i,t.z/i,t.vx/i,t.vy/i,t.vz/i,e)}function xl(a,e,t){let i=1,n=0;for(let s of a){let r=0;for(let[l,c,h]of s)r+=l*Math.cos(c+e*h);let o=i*r;t&&(o%=gr),n+=o,i*=e}return n}function sf(a,e){let t=1,i=0,n=0,s=0;for(let r of a){let o=0,l=0;for(let[c,h,d]of r){let u=h+e*d;o+=c*d*Math.sin(u),s>0&&(l+=c*Math.cos(u))}n+=s*i*l-t*o,i=t,t*=e,++s}return n}const Mc=365250,om=0,lm=1,cm=2;function hm(a){return new on(a[0]+44036e-11*a[1]-190919e-12*a[2],-479966e-12*a[0]+.917482137087*a[1]-.397776982902*a[2],.397776982902*a[1]+.917482137087*a[2])}function dw(a,e,t){const i=t*Math.cos(e),n=Math.cos(a),s=Math.sin(a);return[i*n,i*s,t*Math.sin(e)]}function Sl(a,e){const t=e.tt/Mc,i=xl(a[om],t,!0),n=xl(a[lm],t,!1),s=xl(a[cm],t,!1),r=dw(i,n,s);return hm(r).ToAstroVector(e)}function dm(a,e){const t=e/Mc,i=xl(a[om],t,!0),n=xl(a[lm],t,!1),s=xl(a[cm],t,!1),r=sf(a[om],t),o=sf(a[lm],t),l=sf(a[cm],t),c=Math.cos(i),h=Math.sin(i),d=Math.cos(n),u=Math.sin(n),p=+(l*d*c)-s*u*c*o-s*d*h*r,f=+(l*d*h)-s*u*h*o+s*d*c*r,g=+(l*u)+s*d*o,m=dw(i,n,s),v=[p/Mc,f/Mc,g/Mc],x=hm(m),y=hm(v);return new uo(e,x,y)}function Qh(a,e,t,i){const n=i/(i+og),s=Sl(er[t],e);a.x+=n*s.x,a.y+=n*s.y,a.z+=n*s.z}function SD(a){const e=new Mt(0,0,0,a);return Qh(e,a,ue.Jupiter,em),Qh(e,a,ue.Saturn,tm),Qh(e,a,ue.Uranus,im),Qh(e,a,ue.Neptune,nm),e}const um=51,ED=29200,sl=146,vr=201,Za=[[-73e4,[-26.118207232108,-14.376168177825,3.384402515299],[.0016339372163656,-.0027861699588508,-.0013585880229445]],[-700800,[41.974905202127,-.448502952929,-12.770351505989],[.00073458569351457,.0022785014891658,.00048619778602049]],[-671600,[14.706930780744,44.269110540027,9.353698474772],[-.00210001479998,.00022295915939915,.00070143443551414]],[-642400,[-29.441003929957,-6.43016153057,6.858481011305],[.00084495803960544,-.0030783914758711,-.0012106305981192]],[-613200,[39.444396946234,-6.557989760571,-13.913760296463],[.0011480029005873,.0022400006880665,.00035168075922288]],[-584e3,[20.2303809507,43.266966657189,7.382966091923],[-.0019754081700585,.00053457141292226,.00075929169129793]],[-554800,[-30.65832536462,2.093818874552,9.880531138071],[61010603013347e-18,-.0031326500935382,-.00099346125151067]],[-525600,[35.737703251673,-12.587706024764,-14.677847247563],[.0015802939375649,.0021347678412429,.00019074436384343]],[-496400,[25.466295188546,41.367478338417,5.216476873382],[-.0018054401046468,.0008328308359951,.00080260156912107]],[-467200,[-29.847174904071,10.636426313081,12.297904180106],[-.00063257063052907,-.0029969577578221,-.00074476074151596]],[-438e3,[30.774692107687,-18.236637015304,-14.945535879896],[.0020113162005465,.0019353827024189,-20937793168297e-19]],[-408800,[30.243153324028,38.656267888503,2.938501750218],[-.0016052508674468,.0011183495337525,.00083333973416824]],[-379600,[-27.288984772533,18.643162147874,14.023633623329],[-.0011856388898191,-.0027170609282181,-.00049015526126399]],[-350400,[24.519605196774,-23.245756064727,-14.626862367368],[.0024322321483154,.0016062008146048,-.00023369181613312]],[-321200,[34.505274805875,35.125338586954,.557361475637],[-.0013824391637782,.0013833397561817,.00084823598806262]],[-292e3,[-23.275363915119,25.818514298769,15.055381588598],[-.0016062295460975,-.0023395961498533,-.00024377362639479]],[-262800,[17.050384798092,-27.180376290126,-13.608963321694],[.0028175521080578,.0011358749093955,-.00049548725258825]],[-233600,[38.093671910285,30.880588383337,-1.843688067413],[-.0011317697153459,.0016128814698472,.00084177586176055]],[-204400,[-18.197852930878,31.932869934309,15.438294826279],[-.0019117272501813,-.0019146495909842,-19657304369835e-18]],[-175200,[8.528924039997,-29.618422200048,-11.805400994258],[.0031034370787005,.0005139363329243,-.00077293066202546]],[-146e3,[40.94685725864,25.904973592021,-4.256336240499],[-.00083652705194051,.0018129497136404,.0008156422827306]],[-116800,[-12.326958895325,36.881883446292,15.217158258711],[-.0021166103705038,-.001481442003599,.00017401209844705]],[-87600,[-.633258375909,-30.018759794709,-9.17193287495],[.0032016994581737,-.00025279858672148,-.0010411088271861]],[-58400,[42.936048423883,20.344685584452,-6.588027007912],[-.00050525450073192,.0019910074335507,.00077440196540269]],[-29200,[-5.975910552974,40.61180995846,14.470131723673],[-.0022184202156107,-.0010562361130164,.00033652250216211]],[0,[-9.875369580774,-27.978926224737,-5.753711824704],[.0030287533248818,-.0011276087003636,-.0012651326732361]],[29200,[43.958831986165,14.214147973292,-8.808306227163],[-.00014717608981871,.0021404187242141,.00071486567806614]],[58400,[.67813676352,43.094461639362,13.243238780721],[-.0022358226110718,-.00063233636090933,.00047664798895648]],[87600,[-18.282602096834,-23.30503958666,-1.766620508028],[.0025567245263557,-.0019902940754171,-.0013943491701082]],[116800,[43.873338744526,7.700705617215,-10.814273666425],[.00023174803055677,.0022402163127924,.00062988756452032]],[146e3,[7.392949027906,44.382678951534,11.629500214854],[-.002193281545383,-.00021751799585364,.00059556516201114]],[175200,[-24.981690229261,-16.204012851426,2.466457544298],[.001819398914958,-.0026765419531201,-.0013848283502247]],[204400,[42.530187039511,.845935508021,-12.554907527683],[.00065059779150669,.0022725657282262,.00051133743202822]],[233600,[13.999526486822,44.462363044894,9.669418486465],[-.0021079296569252,.00017533423831993,.00069128485798076]],[262800,[-29.184024803031,-7.371243995762,6.493275957928],[.00093581363109681,-.0030610357109184,-.0012364201089345]],[292e3,[39.831980671753,-6.078405766765,-13.909815358656],[.0011117769689167,.0022362097830152,.00036230548231153]],[321200,[20.294955108476,43.417190420251,7.450091985932],[-.0019742157451535,.00053102050468554,.00075938408813008]],[350400,[-30.66999230216,2.318743558955,9.973480913858],[45605107450676e-18,-.0031308219926928,-.00099066533301924]],[379600,[35.626122155983,-12.897647509224,-14.777586508444],[.0016015684949743,.0021171931182284,.00018002516202204]],[408800,[26.133186148561,41.232139187599,5.00640132622],[-.0017857704419579,.00086046232702817,.00080614690298954]],[438e3,[-29.57674022923,11.863535943587,12.631323039872],[-.00072292830060955,-.0029587820140709,-.000708242964503]],[467200,[29.910805787391,-19.159019294,-15.013363865194],[.0020871080437997,.0018848372554514,-38528655083926e-18]],[496400,[31.375957451819,38.050372720763,2.433138343754],[-.0015546055556611,.0011699815465629,.00083565439266001]],[525600,[-26.360071336928,20.662505904952,14.414696258958],[-.0013142373118349,-.0026236647854842,-.00042542017598193]],[554800,[22.599441488648,-24.508879898306,-14.484045731468],[.0025454108304806,.0014917058755191,-.00030243665086079]],[584e3,[35.877864013014,33.894226366071,-.224524636277],[-.0012941245730845,.0014560427668319,.00084762160640137]],[613200,[-21.538149762417,28.204068269761,15.321973799534],[-.001731211740901,-.0021939631314577,-.0001631691327518]],[642400,[13.971521374415,-28.339941764789,-13.083792871886],[.0029334630526035,.00091860931752944,-.00059939422488627]],[671600,[39.526942044143,28.93989736011,-2.872799527539],[-.0010068481658095,.001702113288809,.00083578230511981]],[700800,[-15.576200701394,34.399412961275,15.466033737854],[-.0020098814612884,-.0017191109825989,70414782780416e-18]],[73e4,[4.24325283709,-30.118201690825,-10.707441231349],[.0031725847067411,.0001609846120227,-.00090672150593868]]];class on{constructor(e,t,i){this.x=e,this.y=t,this.z=i}clone(){return new on(this.x,this.y,this.z)}ToAstroVector(e){return new Mt(this.x,this.y,this.z,e)}static zero(){return new on(0,0,0)}quadrature(){return this.x*this.x+this.y*this.y+this.z*this.z}add(e){return new on(this.x+e.x,this.y+e.y,this.z+e.z)}sub(e){return new on(this.x-e.x,this.y-e.y,this.z-e.z)}incr(e){this.x+=e.x,this.y+=e.y,this.z+=e.z}decr(e){this.x-=e.x,this.y-=e.y,this.z-=e.z}mul(e){return new on(e*this.x,e*this.y,e*this.z)}div(e){return new on(this.x/e,this.y/e,this.z/e)}mean(e){return new on((this.x+e.x)/2,(this.y+e.y)/2,(this.z+e.z)/2)}neg(){return new on(-this.x,-this.y,-this.z)}}class uo{constructor(e,t,i){this.tt=e,this.r=t,this.v=i}clone(){return new uo(this.tt,this.r,this.v)}sub(e){return new uo(this.tt,this.r.sub(e.r),this.v.sub(e.v))}}function _D(a){let[e,[t,i,n],[s,r,o]]=a;return new uo(e,new on(t,i,n),new on(s,r,o))}function ed(a,e,t,i){const n=i/(i+og),s=dm(er[t],e);return a.r.incr(s.r.mul(n)),a.v.incr(s.v.mul(n)),s}function rc(a,e,t){const i=t.sub(a),n=i.quadrature();return i.mul(e/(n*Math.sqrt(n)))}class rp{constructor(e){let t=new uo(e,new on(0,0,0),new on(0,0,0));this.Jupiter=ed(t,e,ue.Jupiter,em),this.Saturn=ed(t,e,ue.Saturn,tm),this.Uranus=ed(t,e,ue.Uranus,im),this.Neptune=ed(t,e,ue.Neptune,nm),this.Jupiter.r.decr(t.r),this.Jupiter.v.decr(t.v),this.Saturn.r.decr(t.r),this.Saturn.v.decr(t.v),this.Uranus.r.decr(t.r),this.Uranus.v.decr(t.v),this.Neptune.r.decr(t.r),this.Neptune.v.decr(t.v),this.Sun=new uo(e,t.r.mul(-1),t.v.mul(-1))}Acceleration(e){let t=rc(e,og,this.Sun.r);return t.incr(rc(e,em,this.Jupiter.r)),t.incr(rc(e,tm,this.Saturn.r)),t.incr(rc(e,im,this.Uranus.r)),t.incr(rc(e,nm,this.Neptune.r)),t}}class ap{constructor(e,t,i,n){this.tt=e,this.r=t,this.v=i,this.a=n}clone(){return new ap(this.tt,this.r.clone(),this.v.clone(),this.a.clone())}}class uw{constructor(e,t){this.bary=e,this.grav=t}}function Ru(a,e,t,i){return new on(e.x+a*(t.x+a*i.x/2),e.y+a*(t.y+a*i.y/2),e.z+a*(t.z+a*i.z/2))}function eb(a,e,t){return new on(e.x+a*t.x,e.y+a*t.y,e.z+a*t.z)}function pm(a,e){const t=a-e.tt,i=new rp(a),n=Ru(t,e.r,e.v,e.a),s=i.Acceleration(n).mean(e.a),r=Ru(t,e.r,e.v,s),o=e.v.add(s.mul(t)),l=i.Acceleration(r),c=new ap(a,r,o,l);return new uw(i,c)}const AD=[];function pw(a,e){const t=Math.floor(a);return t<0?0:t>=e?e-1:t}function fm(a){const e=_D(a),t=new rp(e.tt),i=e.r.add(t.Sun.r),n=e.v.add(t.Sun.v),s=t.Acceleration(i),r=new ap(e.tt,i,n,s);return new uw(t,r)}function TD(a,e){const t=Za[0][0];if(e<t||e>Za[um-1][0])return null;const i=pw((e-t)/ED,um-1);if(!a[i]){const s=a[i]=[];s[0]=fm(Za[i]).grav,s[vr-1]=fm(Za[i+1]).grav;let r,o=s[0].tt;for(r=1;r<vr-1;++r)s[r]=pm(o+=sl,s[r-1]).grav;o=s[vr-1].tt;var n=[];for(n[vr-1]=s[vr-1],r=vr-2;r>0;--r)n[r]=pm(o-=sl,n[r+1]).grav;for(r=vr-2;r>0;--r){const l=r/(vr-1);s[r].r=s[r].r.mul(1-l).add(n[r].r.mul(l)),s[r].v=s[r].v.mul(1-l).add(n[r].v.mul(l)),s[r].a=s[r].a.mul(1-l).add(n[r].a.mul(l))}}return a[i]}function tb(a,e,t){let i=fm(a);const n=Math.ceil((e-i.grav.tt)/t);for(let s=0;s<n;++s)i=pm(s+1===n?e:i.grav.tt+t,i.grav);return i}function fw(a,e){let t,i,n;const s=TD(AD,a.tt);if(s){const r=pw((a.tt-s[0].tt)/sl,vr-1),o=s[r],l=s[r+1],c=o.a.mean(l.a),h=Ru(a.tt-o.tt,o.r,o.v,c),d=eb(a.tt-o.tt,o.v,c),u=Ru(a.tt-l.tt,l.r,l.v,c),p=eb(a.tt-l.tt,l.v,c),f=(a.tt-o.tt)/sl;t=h.mul(1-f).add(u.mul(f)),i=d.mul(1-f).add(p.mul(f))}else{let r;a.tt<Za[0][0]?r=tb(Za[0],a.tt,-sl):r=tb(Za[um-1],a.tt,+sl),t=r.grav.r,i=r.grav.v,n=r.bary}return n||(n=new rp(a.tt)),t=t.sub(n.Sun.r),i=i.sub(n.Sun.v),new ra(t.x,t.y,t.z,i.x,i.y,i.z,a)}function oa(a,e){var t=Ht(e);if(a in er)return Sl(er[a],t);if(a===ue.Pluto){const r=fw(t);return new Mt(r.x,r.y,r.z,t)}if(a===ue.Sun)return new Mt(0,0,0,t);if(a===ue.Moon){var i=Sl(er.Earth,t),n=Tr(t);return new Mt(i.x+n.x,i.y+n.y,i.z+n.z,t)}if(a===ue.EMB){const r=Sl(er.Earth,t),o=Tr(t),l=1+tw;return new Mt(r.x+o.x/l,r.y+o.y/l,r.z+o.z/l,t)}if(a===ue.SSB)return SD(t);const s=lg(a);if(s){const r=new np(s.dec,15*s.ra,s.dist);return mg(r,t)}throw`HelioVector: Unknown body "${a}"`}function ID(a,e){let t=e,i=0;for(let n=0;n<10;++n){const s=a(t),r=s.Length()/ag;if(r>1)throw"Object is too distant for light-travel solver.";const o=e.AddDays(-r);if(i=Math.abs(o.tt-t.tt),i<1e-9)return s;t=o}throw`Light-travel time solver did not converge: dt = ${i}`}class DD{constructor(e,t,i,n){this.observerBody=e,this.targetBody=t,this.aberration=i,this.observerPos=n}Position(e){this.aberration&&(this.observerPos=oa(this.observerBody,e));const t=oa(this.targetBody,e);return new Mt(t.x-this.observerPos.x,t.y-this.observerPos.y,t.z-this.observerPos.z,e)}}function RD(a,e,t,i){Iu(i);const n=Ht(a);if(lg(t)){const o=oa(t,n);if(i){const c=PD(e,n),h=new Mt(o.x-c.x,o.y-c.y,o.z-c.z,n),d=ag/h.Length();return new Mt(h.x+c.vx/d,h.y+c.vy/d,h.z+c.vz/d,n)}const l=oa(e,n);return new Mt(o.x-l.x,o.y-l.y,o.z-l.z,n)}let s;i?s=new Mt(0,0,0,n):s=oa(e,n);const r=new DD(e,t,i,s);return ID(o=>r.Position(o),n)}function Cu(a,e,t){Iu(t);const i=Ht(e);switch(a){case ue.Earth:return new Mt(0,0,0,i);case ue.Moon:return Tr(i);default:const n=RD(i,ue.Earth,a,t);return n.t=i,n}}function CD(a,e){return new ra(a.r.x,a.r.y,a.r.z,a.v.x,a.v.y,a.v.z,e)}function PD(a,e){const t=Ht(e);switch(a){case ue.Sun:return new ra(0,0,0,0,0,0,t);case ue.SSB:const i=new rp(t.tt);return new ra(-i.Sun.r.x,-i.Sun.r.y,-i.Sun.r.z,-i.Sun.v.x,-i.Sun.v.y,-i.Sun.v.z,t);case ue.Mercury:case ue.Venus:case ue.Earth:case ue.Mars:case ue.Jupiter:case ue.Saturn:case ue.Uranus:case ue.Neptune:const n=dm(er[a],t.tt);return CD(n,t);case ue.Pluto:return fw(t);case ue.Moon:case ue.EMB:const s=dm(er.Earth,t.tt),r=a==ue.Moon?hw(t):xD(t);return new ra(r.x+s.r.x,r.y+s.r.y,r.z+s.r.z,r.vx+s.v.x,r.vy+s.v.y,r.vz+s.v.z,t);default:if(lg(a)){const o=oa(a,t);return new ra(o.x,o.y,o.z,0,0,0,t)}throw`HelioState: Unsupported body "${a}"`}}function LD(a,e,t,i,n){let s=(n+t)/2-i,r=(n-t)/2,o=i,l;if(s==0){if(r==0||(l=-o/r,l<-1||l>1))return null}else{let d=r*r-4*s*o;if(d<=0)return null;let u=Math.sqrt(d),p=(-r+u)/(2*s),f=(-r-u)/(2*s);if(-1<=p&&p<=1){if(-1<=f&&f<=1)return null;l=p}else if(-1<=f&&f<=1)l=f;else return null}let c=a+l*e,h=(2*s*l+r)/e;return{t:c,df_dt:h}}function ug(a,e,t,i){const n=Ai(i&&i.dt_tolerance_seconds||1),s=Math.abs(n/eD);let r=i&&i.init_f1||a(e),o=i&&i.init_f2||a(t),l=NaN,c=0,h=i&&i.iter_limit||20,d=!0;for(;;){if(++c>h)throw"Excessive iteration in Search()";let u=uD(e,t,.5),p=u.ut-e.ut;if(Math.abs(p)<s)return u;d?l=a(u):d=!0;let f=LD(u.ut,t.ut-u.ut,r,l,o);if(f){let g=Ht(f.t),m=a(g);if(f.df_dt!==0){if(Math.abs(m/f.df_dt)<s)return g;let v=1.2*Math.abs(m/f.df_dt);if(v<p/10){let x=g.AddDays(-v),y=g.AddDays(+v);if((x.ut-e.ut)*(x.ut-t.ut)<0&&(y.ut-e.ut)*(y.ut-t.ut)<0){let b=a(x),w=a(y);if(b<0&&w>=0){r=b,o=w,e=x,t=y,l=m,d=!1;continue}}}}}if(r<0&&l>=0){t=u,o=l;continue}if(l<0&&o>=0){e=u,r=l;continue}return null}}function kD(a){let e=a;for(;e<=-180;)e+=360;for(;e>180;)e-=360;return e}function OD(a){for(;a<0;)a+=360;for(;a>=360;)a-=360;return a}function ND(a,e,t){if(a===ue.Earth||e===ue.Earth)throw"The Earth does not have a longitude as seen from itself.";const i=Ht(t),n=Cu(a,i,!1),s=am(n),r=Cu(e,i,!1),o=am(r);return OD(s.elon-o.elon)}function FD(a,e,t,i){let n,s=0,r=0,o=0;switch(a){case ue.Mercury:n=-.6,s=4.98,r=-4.88,o=3.02;break;case ue.Venus:e<163.6?(n=-4.47,s=1.03,r=.57,o=.13):(n=.98,s=-1.02);break;case ue.Mars:n=-1.52,s=1.6;break;case ue.Jupiter:n=-9.4,s=.5;break;case ue.Uranus:n=-7.19,s=.25;break;case ue.Neptune:n=-6.87;break;case ue.Pluto:n=-1,s=4;break;default:throw`VisualMagnitude: unsupported body ${a}`}const l=e/100;let c=n+l*(s+l*(r+l*o));return c+=5*Math.log10(t*i),c}function UD(a,e,t,i,n){const s=am(i),r=ge*28.06,o=ge*(169.51+382e-7*n.tt),l=ge*s.elat,c=ge*s.elon,h=Math.asin(Math.sin(l)*Math.cos(r)-Math.cos(l)*Math.sin(r)*Math.sin(c-o)),d=Math.sin(Math.abs(h));let u=-9+.044*a;return u+=d*(-2.6+1.2*d),u+=5*Math.log10(e*t),{mag:u,ring_tilt:Ds*h}}function BD(a,e,t){let i=a*ge,n=i*i,s=n*n,r=-12.717+1.49*Math.abs(i)+.0431*s;const o=385000.6/js;let l=t/o;return r+=5*Math.log10(e*l),r}class zD{constructor(e,t,i,n,s,r,o,l){this.time=e,this.mag=t,this.phase_angle=i,this.helio_dist=n,this.geo_dist=s,this.gc=r,this.hc=o,this.ring_tilt=l,this.phase_fraction=(1+Math.cos(ge*i))/2}}function mw(a,e){if(a===ue.Earth)throw"The illumination of the Earth is not defined.";const t=Ht(e),i=Sl(er.Earth,t);let n,s,r,o;a===ue.Sun?(r=new Mt(-i.x,-i.y,-i.z,t),s=new Mt(0,0,0,t),n=0):(a===ue.Moon?(r=Tr(t),s=new Mt(i.x+r.x,i.y+r.y,i.z+r.z,t)):(s=oa(a,e),r=new Mt(s.x-i.x,s.y-i.y,s.z-i.z,t)),n=iw(r,s));let l=r.Length(),c=s.Length(),h;if(a===ue.Sun)o=QI+5*Math.log10(l);else if(a===ue.Moon)o=BD(n,c,l);else if(a===ue.Saturn){const d=UD(n,c,l,r,t);o=d.mag,h=d.ring_tilt}else o=FD(a,n,c,l);return new zD(t,o,n,c,l,r,s,h)}function gw(a){return ND(ue.Moon,ue.Sun,a)}function Cd(a,e,t){function i(u){let p=gw(u);return kD(p-a)}Ai(a),Ai(t);const n=1.5,s=Ht(e);let r=i(s),o,l,c;if(t<0){if(r<0&&(r+=360),o=-(J1*r)/360,c=o+n,c<t)return null;l=Math.max(t,o-n)}else{if(r>0&&(r-=360),o=-(J1*r)/360,l=o-n,l>t)return null;c=Math.min(t,o+n)}const h=s.AddDays(l),d=s.AddDays(c);return ug(i,h,d,{dt_tolerance_seconds:.1})}var ib;(function(a){a[a.Pericenter=0]="Pericenter",a[a.Apocenter=1]="Apocenter"})(ib||(ib={}));function pg(a){return new or([[a.rot[0][0],a.rot[1][0],a.rot[2][0]],[a.rot[0][1],a.rot[1][1],a.rot[2][1]],[a.rot[0][2],a.rot[1][2],a.rot[2][2]]])}function fg(a,e){return new or([[e.rot[0][0]*a.rot[0][0]+e.rot[1][0]*a.rot[0][1]+e.rot[2][0]*a.rot[0][2],e.rot[0][1]*a.rot[0][0]+e.rot[1][1]*a.rot[0][1]+e.rot[2][1]*a.rot[0][2],e.rot[0][2]*a.rot[0][0]+e.rot[1][2]*a.rot[0][1]+e.rot[2][2]*a.rot[0][2]],[e.rot[0][0]*a.rot[1][0]+e.rot[1][0]*a.rot[1][1]+e.rot[2][0]*a.rot[1][2],e.rot[0][1]*a.rot[1][0]+e.rot[1][1]*a.rot[1][1]+e.rot[2][1]*a.rot[1][2],e.rot[0][2]*a.rot[1][0]+e.rot[1][2]*a.rot[1][1]+e.rot[2][2]*a.rot[1][2]],[e.rot[0][0]*a.rot[2][0]+e.rot[1][0]*a.rot[2][1]+e.rot[2][0]*a.rot[2][2],e.rot[0][1]*a.rot[2][0]+e.rot[1][1]*a.rot[2][1]+e.rot[2][1]*a.rot[2][2],e.rot[0][2]*a.rot[2][0]+e.rot[1][2]*a.rot[2][1]+e.rot[2][2]*a.rot[2][2]]])}function mg(a,e){e=Ht(e);const t=a.lat*ge,i=a.lon*ge,n=a.dist*Math.cos(t);return new Mt(n*Math.cos(i),n*Math.sin(i),a.dist*Math.sin(t),e)}function op(a){const e=HD(a);return new sm(e.lon/15,e.lat,e.dist,a)}function HD(a){const e=a.x*a.x+a.y*a.y,t=Math.sqrt(e+a.z*a.z);let i,n;if(e===0){if(a.z===0)throw"Zero-length vector not allowed.";n=0,i=a.z<0?-90:90}else n=Ds*Math.atan2(a.y,a.x),n<0&&(n+=360),i=Ds*Math.atan2(a.z,Math.sqrt(e));return new np(i,n,t)}function vw(a,e){let t;if(Ai(e),e<-90||e>90)return 0;if(a==="normal"||a==="jplhor"){let i=e;i<-1&&(i=-1),t=1.02/Math.tan((i+10.3/(i+5.11))*ge)/60,a==="normal"&&e<-1&&(t*=(e+90)/89)}else if(!a)t=0;else throw`Invalid refraction option: ${a}`;return t}function _r(a,e){return new Mt(a.rot[0][0]*e.x+a.rot[1][0]*e.y+a.rot[2][0]*e.z,a.rot[0][1]*e.x+a.rot[1][1]*e.y+a.rot[2][1]*e.z,a.rot[0][2]*e.x+a.rot[1][2]*e.y+a.rot[2][2]*e.z,e.t)}function GD(){return new or([[1,0,0],[0,.9174821430670688,-.3977769691083922],[0,.3977769691083922,.9174821430670688]])}function VD(){return new or([[1,0,0],[0,.9174821430670688,.3977769691083922],[0,-.3977769691083922,.9174821430670688]])}function bw(a){a=Ht(a);const e=cg(a,Ci.From2000),t=hg(a,Ci.From2000);return fg(e,t)}function yw(a){a=Ht(a);const e=hg(a,Ci.Into2000),t=cg(a,Ci.Into2000);return fg(e,t)}function WD(a,e){a=Ht(a);const t=Math.sin(e.latitude*ge),i=Math.cos(e.latitude*ge),n=Math.sin(e.longitude*ge),s=Math.cos(e.longitude*ge),r=[i*s,i*n,t],o=[-t*s,-t*n,i],l=[n,-s,0],c=-15*lh(a),h=wl(c,r),d=wl(c,o),u=wl(c,l);return new or([[d[0],u[0],h[0]],[d[1],u[1],h[1]],[d[2],u[2],h[2]]])}function XD(a,e){const t=WD(a,e);return pg(t)}function $D(a,e){a=Ht(a);const t=XD(a,e),i=yw(a);return fg(t,i)}function YD(a,e){const t=$D(a,e);return pg(t)}function qD(a){const t=oh(Ht(a)).tobl*ge,i=Math.cos(t),n=Math.sin(t);return new or([[1,0,0],[0,+i,+n],[0,-n,+i]])}var po;(function(a){a.Penumbral="penumbral",a.Partial="partial",a.Annular="annular",a.Total="total"})(po||(po={}));class KD{constructor(e,t,i,n,s,r,o){this.time=e,this.u=t,this.r=i,this.k=n,this.p=s,this.target=r,this.dir=o}}function ZD(a,e,t,i){const n=(i.x*t.x+i.y*t.y+i.z*t.z)/(i.x*i.x+i.y*i.y+i.z*i.z),s=n*i.x-t.x,r=n*i.y-t.y,o=n*i.z-t.z,l=js*Math.hypot(s,r,o),c=+yc-(1+n)*(yc-a),h=-yc+(1+n)*(yc+a);return new KD(e,n,l,c,h,t,i)}function mm(a,e){const t=ow(a,e),i=Cu(ue.Sun,a,!0),n=Tr(a),s=new Mt(t[0]-n.x,t[1]-n.y,t[2]-n.z,a);return n.x-=i.x,n.y-=i.y,n.z-=i.z,ZD(sD,a,s,n)}function jD(a,e){const t=11574074074074073e-21,i=e.AddDays(-t),n=e.AddDays(+t),s=a(i);return(a(n).r-s.r)/t}function JD(a,e){const t=a.AddDays(-.2),i=a.AddDays(.2);function n(r){return mm(r,e)}const s=ug(r=>jD(n,r),t,i);if(!s)throw`PeakLocalMoonShadow: search failure for search_center_time = ${a}`;return mm(s,e)}function QD(a){const e=sw(a);return Ds*e.geo_eclip_lat}function e4(a,e,t){if(a<=0)throw"Radius of first disc must be positive.";if(e<=0)throw"Radius of second disc must be positive.";if(t<0)throw"Distance between discs is not allowed to be negative.";if(t>=a+e)return 0;if(t==0)return a<=e?1:e*e/(a*a);const i=(a*a-e*e+t*t)/(2*t),n=a*a-i*i;if(n<=0)return a<=e?1:e*e/(a*a);const s=Math.sqrt(n),r=a*a*Math.acos(i/a)-i*s,o=e*e*Math.acos((t-i)/e)-(t-i)*s;return(r+o)/(Math.PI*a*a)}function t4(a,e){const t=new Mt(a.x+e.x,a.y+e.y,a.z+e.z,a.t),i=Math.asin(tD/t.Length()),n=Math.asin(aD/e.Length()),s=iw(e,t),r=e4(i,n,s*ge);return Math.min(.9999,r)}function i4(a){return a>.014?po.Total:po.Annular}class n4{constructor(e,t){this.time=e,this.altitude=t}}class s4{constructor(e,t,i,n,s,r,o){this.kind=e,this.obscuration=t,this.partial_begin=i,this.total_begin=n,this.peak=s,this.total_end=r,this.partial_end=o}}function nb(a){return a.p-a.r}function sb(a){return Math.abs(a.k)-a.r}function r4(a,e){const t=Mw(e,a.time);let i=a.time.AddDays(-.2),n=a.time.AddDays(.2);const s=td(e,1,nb,i,a.time),r=td(e,-1,nb,a.time,n);let o,l,c;a.r<Math.abs(a.k)?(i=a.time.AddDays(-.01),n=a.time.AddDays(.01),o=td(e,1,sb,i,a.time),l=td(e,-1,sb,a.time,n),c=i4(a.k)):c=po.Partial;const h=c===po.Total?1:t4(a.dir,a.target);return new s4(c,h,s,o,t,l,r)}function td(a,e,t,i,n){function s(o){const l=mm(o,a);return e*t(l)}const r=ug(s,i,n);if(!r)throw"Local eclipse transition search failed.";return Mw(a,r)}function Mw(a,e){const t=a4(e,a);return new n4(e,t)}function a4(a,e){const t=Jc(ue.Sun,a,e,!0,!0);return dg(a,e,t.ra,t.dec,"normal").altitude}function o4(a,e){a=Ht(a),sp(e);const t=1.8;let i=a;for(;;){const n=Cd(0,i,40);if(!n)throw"Cannot find next new moon";const s=QD(n);if(Math.abs(s)<t){const r=JD(n,e);if(r.r<r.p){const o=r4(r,e);if(o.partial_begin.altitude>0||o.partial_end.altitude>0)return o}}i=n.AddDays(10)}}var rb;(function(a){a[a.Invalid=0]="Invalid",a[a.Ascending=1]="Ascending",a[a.Descending=-1]="Descending"})(rb||(rb={}));class ww{constructor(e,t,i,n){this.ra=e,this.dec=t,this.spin=i,this.north=n}}function l4(a){const e=Du([0,0,1],a,Ci.Into2000),t=jc(e,a,Ci.Into2000),i=new Mt(t[0],t[1],t[2],a),n=op(i),s=190.41375788700253+360.9856122880876*a.ut;return new ww(n.ra,n.dec,s,i)}function c4(a,e){const t=Ht(e),i=t.tt,n=i/36525;let s,r,o;switch(a){case ue.Sun:s=286.13,r=63.87,o=84.176+14.1844*i;break;case ue.Mercury:s=281.0103-.0328*n,r=61.4155-.0049*n,o=329.5988+6.1385108*i+.01067257*Math.sin(ge*(174.7910857+4.092335*i))-.00112309*Math.sin(ge*(349.5821714+8.18467*i))-1104e-7*Math.sin(ge*(164.3732571+12.277005*i))-2539e-8*Math.sin(ge*(339.1643429+16.36934*i))-571e-8*Math.sin(ge*(153.9554286+20.461675*i));break;case ue.Venus:s=272.76,r=67.16,o=160.2-1.4813688*i;break;case ue.Earth:return l4(t);case ue.Moon:const u=ge*(125.045-.0529921*i),p=ge*(250.089-.1059842*i),f=ge*(260.008+13.0120009*i),g=ge*(176.625+13.3407154*i),m=ge*(357.529+.9856003*i),v=ge*(311.589+26.4057084*i),x=ge*(134.963+13.064993*i),y=ge*(276.617+.3287146*i),b=ge*(34.226+1.7484877*i),w=ge*(15.134-.1589763*i),S=ge*(119.743+.0036096*i),_=ge*(239.961+.1643573*i),M=ge*(25.053+12.9590088*i);s=269.9949+.0031*n-3.8787*Math.sin(u)-.1204*Math.sin(p)+.07*Math.sin(f)-.0172*Math.sin(g)+.0072*Math.sin(v)-.0052*Math.sin(w)+.0043*Math.sin(M),r=66.5392+.013*n+1.5419*Math.cos(u)+.0239*Math.cos(p)-.0278*Math.cos(f)+.0068*Math.cos(g)-.0029*Math.cos(v)+9e-4*Math.cos(x)+8e-4*Math.cos(w)-9e-4*Math.cos(M),o=38.3213+(13.17635815-14e-13*i)*i+3.561*Math.sin(u)+.1208*Math.sin(p)-.0642*Math.sin(f)+.0158*Math.sin(g)+.0252*Math.sin(m)-.0066*Math.sin(v)-.0047*Math.sin(x)-.0046*Math.sin(y)+.0028*Math.sin(b)+.0052*Math.sin(w)+.004*Math.sin(S)+.0019*Math.sin(_)-.0044*Math.sin(M);break;case ue.Mars:s=317.269202-.10927547*n+68e-6*Math.sin(ge*(198.991226+19139.4819985*n))+238e-6*Math.sin(ge*(226.292679+38280.8511281*n))+52e-6*Math.sin(ge*(249.663391+57420.7251593*n))+9e-6*Math.sin(ge*(266.18351+76560.636795*n))+.419057*Math.sin(ge*(79.398797+.5042615*n)),r=54.432516-.05827105*n+51e-6*Math.cos(ge*(122.433576+19139.9407476*n))+141e-6*Math.cos(ge*(43.058401+38280.8753272*n))+31e-6*Math.cos(ge*(57.663379+57420.7517205*n))+5e-6*Math.cos(ge*(79.476401+76560.6495004*n))+1.591274*Math.cos(ge*(166.325722+.5042615*n)),o=176.049863+350.891982443297*i+145e-6*Math.sin(ge*(129.071773+19140.0328244*n))+157e-6*Math.sin(ge*(36.352167+38281.0473591*n))+4e-5*Math.sin(ge*(56.668646+57420.929536*n))+1e-6*Math.sin(ge*(67.364003+76560.2552215*n))+1e-6*Math.sin(ge*(104.79268+95700.4387578*n))+.584542*Math.sin(ge*(95.391654+.5042615*n));break;case ue.Jupiter:const T=ge*(99.360714+4850.4046*n),A=ge*(175.895369+1191.9605*n),R=ge*(300.323162+262.5475*n),C=ge*(114.012305+6070.2476*n),k=ge*(49.511251+64.3*n);s=268.056595-.006499*n+117e-6*Math.sin(T)+938e-6*Math.sin(A)+.001432*Math.sin(R)+3e-5*Math.sin(C)+.00215*Math.sin(k),r=64.495303+.002413*n+5e-5*Math.cos(T)+404e-6*Math.cos(A)+617e-6*Math.cos(R)-13e-6*Math.cos(C)+926e-6*Math.cos(k),o=284.95+870.536*i;break;case ue.Saturn:s=40.589-.036*n,r=83.537-.004*n,o=38.9+810.7939024*i;break;case ue.Uranus:s=257.311,r=-15.175,o=203.81-501.1600928*i;break;case ue.Neptune:const z=ge*(357.85+52.316*n);s=299.36+.7*Math.sin(z),r=43.46-.51*Math.cos(z),o=249.978+541.1397757*i-.48*Math.sin(z);break;case ue.Pluto:s=132.993,r=-6.163,o=302.695+56.3625225*i;break;default:throw`Invalid body: ${a}`}const l=r*ge,c=s*ge,h=Math.cos(l),d=new Mt(h*Math.cos(c),h*Math.sin(c),Math.sin(l),t);return new ww(s/15,r,o,d)}const h4=["Venus","Mars","Jupiter","Saturn"];function xw(a){return new ha(a.lat,a.lng,a.elevationM)}function gg(a,e,t,i,n=!0){const s=dg(t,xw(i),a,e,n?"normal":void 0);return{altitudeDeg:s.altitude,azimuthDeg:s.azimuth}}class Ss{up;north;west;constructor(e,t){const i=Ht(e),n=Math.sin(t.lat*br),s=Math.cos(t.lat*br),r=Math.sin(t.lng*br),o=Math.cos(t.lng*br),l=-15*vD(i),c=yw(i);this.up=Ss.rotate(c,Ss.spin(l,[s*o,s*r,n]),i),this.north=Ss.rotate(c,Ss.spin(l,[-n*o,-n*r,s]),i),this.west=Ss.rotate(c,Ss.spin(l,[r,-o,0]),i)}static ofJ2000(e,t,i,n,s=!0){const r=Ht(i),o=mg(new np(t,e*15,1),r),l=op(_r(bw(r),o));return gg(l.ra,l.dec,i,n,s)}position(e,t){const i=Math.sin(t*br),n=Math.cos(t*br),s=Math.sin(e*ob),r=Math.cos(e*ob),o=n*r,l=n*s,c=i,h=o*this.up[0]+l*this.up[1]+c*this.up[2],d=o*this.north[0]+l*this.north[1]+c*this.north[2],u=o*this.west[0]+l*this.west[1]+c*this.west[2],p=Math.hypot(d,u);let f=0;p>0&&(f=-ab*Math.atan2(u,d),f<0&&(f+=360));let g=ab*Math.atan2(p,h);return g-=vw("normal",90-g),{altitudeDeg:90-g,azimuthDeg:f}}static spin(e,[t,i,n]){const s=Math.cos(e*br),r=Math.sin(e*br);return[s*t+r*i,s*i-r*t,n]}static rotate(e,[t,i,n],s){const r=_r(e,new Mt(t,i,n,s));return[r.x,r.y,r.z]}}const br=Math.PI/180,ab=180/Math.PI,ob=15*br;function Ni(a,e,t){const i=xw(t),n=Jc(ue[a],e,i,!0,!0),s=dg(e,i,n.ra,n.dec,"normal");return{altitudeDeg:s.altitude,azimuthDeg:s.azimuth}}function rf(a,e){return mw(ue[a],e).mag}function Ca(a){const e=gw(a),t=mw(ue.Moon,a);return{phaseFraction:e/360,illuminatedFraction:t.phase_fraction}}const d4=2e3,u4=3,p4=20;function Yn(a,e,t){if(a.year===void 0&&a.month===void 0&&a.day===void 0&&a.hour===void 0)return;const i=a.year!==void 0,n=a.year??d4,s=a.month??(i?1:u4),r=a.day??(i?1:p4),o=t??Math.round(e/15);return new Date(Date.UTC(n,s-1,r,(a.hour??12)-o,a.minute??0,a.second??0))}const lb=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];class so{static POINT_DEG=360/16;static point(e,t=lb){const i=(e%360+360)%360,n=Math.round(i/so.POINT_DEG)%16;return t[n]}static POINTS=lb;static towards(e,t){return t?t.towards(so.point(e,t.compassPoints)):`to the ${so.point(e)}`}}class Vs{static ANCHOR="vec4 diffuseColor = vec4( diffuse, opacity );";static CORE=.18;static RIM=.5;static FALLOFF={core:Vs.CORE,rim:Vs.RIM};static apply(e){e.transparent=!0,e.depthWrite=!1,e.onBeforeCompile=t=>{t.fragmentShader=Vs.patch(t.fragmentShader)}}static patch(e){return e.replace(Vs.ANCHOR,`float distanceFromCentre = length( gl_PointCoord - vec2( 0.5 ) );
|
|
7909
|
+
*/const ag=173.1446326846693,js=14959787069098932e-8,ge=.017453292519943295,K1=.26179938779914946,Ds=57.29577951308232,QM=3.819718634205488,ZI=365.24217,Z1=new Date("2000-01-01T12:00:00Z"),gr=2*Math.PI,Gr=3600*(180/Math.PI),nl=484813681109536e-20,ew=10800*60,jI=2*ew,j1=7292115e-11,JI=ew/Math.PI,QI=-.17-5*Math.log10(JI),J1=29.530588,eD=24*3600,yc=695700,tD=yc/js,J0=.996647180302104,iD=J0*J0,Q0=6378.1366,nD=Q0/js,sD=1737.4,rD=1736,aD=rD/js,tw=81.30056,og=.0002959122082855911,em=2825345909524226e-22,tm=8459715185680659e-23,im=1292024916781969e-23,nm=1524358900784276e-23;function Iu(a){if(a!==!0&&a!==!1)throw console.trace(),`Value is not boolean: ${a}`;return a}function Ai(a){if(!Number.isFinite(a))throw console.trace(),`Value is not a finite number: ${a}`;return a}function Wo(a){return a-Math.floor(a)}function iw(a,e){const t=a.x*a.x+a.y*a.y+a.z*a.z;if(Math.abs(t)<1e-8)throw"AngleBetween: first vector is too short.";const i=e.x*e.x+e.y*e.y+e.z*e.z;if(Math.abs(i)<1e-8)throw"AngleBetween: second vector is too short.";const n=(a.x*e.x+a.y*e.y+a.z*e.z)/Math.sqrt(t*i);return n<=-1?180:n>=1?0:Ds*Math.acos(n)}var ue;(function(a){a.Sun="Sun",a.Moon="Moon",a.Mercury="Mercury",a.Venus="Venus",a.Earth="Earth",a.Mars="Mars",a.Jupiter="Jupiter",a.Saturn="Saturn",a.Uranus="Uranus",a.Neptune="Neptune",a.Pluto="Pluto",a.SSB="SSB",a.EMB="EMB",a.Star1="Star1",a.Star2="Star2",a.Star3="Star3",a.Star4="Star4",a.Star5="Star5",a.Star6="Star6",a.Star7="Star7",a.Star8="Star8"})(ue||(ue={}));const oD=[ue.Star1,ue.Star2,ue.Star3,ue.Star4,ue.Star5,ue.Star6,ue.Star7,ue.Star8],lD=[{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0}];function cD(a){const e=oD.indexOf(a);return e>=0?lD[e]:null}function lg(a){const e=cD(a);return e&&e.dist>0?e:null}var Pi;(function(a){a[a.From2000=0]="From2000",a[a.Into2000=1]="Into2000"})(Pi||(Pi={}));const er={Mercury:[[[[4.40250710144,0,0],[.40989414977,1.48302034195,26087.9031415742],[.050462942,4.47785489551,52175.8062831484],[.00855346844,1.16520322459,78263.70942472259],[.00165590362,4.11969163423,104351.61256629678],[.00034561897,.77930768443,130439.51570787099],[7583476e-11,3.71348404924,156527.41884944518]],[[26087.90313685529,0,0],[.01131199811,6.21874197797,26087.9031415742],[.00292242298,3.04449355541,52175.8062831484],[.00075775081,6.08568821653,78263.70942472259],[.00019676525,2.80965111777,104351.61256629678]]],[[[.11737528961,1.98357498767,26087.9031415742],[.02388076996,5.03738959686,52175.8062831484],[.01222839532,3.14159265359,0],[.0054325181,1.79644363964,78263.70942472259],[.0012977877,4.83232503958,104351.61256629678],[.00031866927,1.58088495658,130439.51570787099],[7963301e-11,4.60972126127,156527.41884944518]],[[.00274646065,3.95008450011,26087.9031415742],[.00099737713,3.14159265359,0]]],[[[.39528271651,0,0],[.07834131818,6.19233722598,26087.9031415742],[.00795525558,2.95989690104,52175.8062831484],[.00121281764,6.01064153797,78263.70942472259],[.00021921969,2.77820093972,104351.61256629678],[4354065e-11,5.82894543774,130439.51570787099]],[[.0021734774,4.65617158665,26087.9031415742],[.00044141826,1.42385544001,52175.8062831484]]]],Venus:[[[[3.17614666774,0,0],[.01353968419,5.59313319619,10213.285546211],[.00089891645,5.30650047764,20426.571092422],[5477194e-11,4.41630661466,7860.4193924392],[3455741e-11,2.6996444782,11790.6290886588],[2372061e-11,2.99377542079,3930.2096962196],[1317168e-11,5.18668228402,26.2983197998],[1664146e-11,4.25018630147,1577.3435424478],[1438387e-11,4.15745084182,9683.5945811164],[1200521e-11,6.15357116043,30639.856638633]],[[10213.28554621638,0,0],[.00095617813,2.4640651111,10213.285546211],[7787201e-11,.6247848222,20426.571092422]]],[[[.05923638472,.26702775812,10213.285546211],[.00040107978,1.14737178112,20426.571092422],[.00032814918,3.14159265359,0]],[[.00287821243,1.88964962838,10213.285546211]]],[[[.72334820891,0,0],[.00489824182,4.02151831717,10213.285546211],[1658058e-11,4.90206728031,20426.571092422],[1378043e-11,1.12846591367,11790.6290886588],[1632096e-11,2.84548795207,7860.4193924392],[498395e-11,2.58682193892,9683.5945811164],[221985e-11,2.01346696541,19367.1891622328],[237454e-11,2.55136053886,15720.8387848784]],[[.00034551041,.89198706276,10213.285546211]]]],Earth:[[[[1.75347045673,0,0],[.03341656453,4.66925680415,6283.0758499914],[.00034894275,4.62610242189,12566.1516999828],[3417572e-11,2.82886579754,3.523118349],[3497056e-11,2.74411783405,5753.3848848968],[3135899e-11,3.62767041756,77713.7714681205],[2676218e-11,4.41808345438,7860.4193924392],[2342691e-11,6.13516214446,3930.2096962196],[1273165e-11,2.03709657878,529.6909650946],[1324294e-11,.74246341673,11506.7697697936],[901854e-11,2.04505446477,26.2983197998],[1199167e-11,1.10962946234,1577.3435424478],[857223e-11,3.50849152283,398.1490034082],[779786e-11,1.17882681962,5223.6939198022],[99025e-10,5.23268072088,5884.9268465832],[753141e-11,2.53339052847,5507.5532386674],[505267e-11,4.58292599973,18849.2275499742],[492392e-11,4.20505711826,775.522611324],[356672e-11,2.91954114478,.0673103028],[284125e-11,1.89869240932,796.2980068164],[242879e-11,.34481445893,5486.777843175],[317087e-11,5.84901948512,11790.6290886588],[271112e-11,.31486255375,10977.078804699],[206217e-11,4.80646631478,2544.3144198834],[205478e-11,1.86953770281,5573.1428014331],[202318e-11,2.45767790232,6069.7767545534],[126225e-11,1.08295459501,20.7753954924],[155516e-11,.83306084617,213.299095438]],[[6283.0758499914,0,0],[.00206058863,2.67823455808,6283.0758499914],[4303419e-11,2.63512233481,12566.1516999828]],[[8721859e-11,1.07253635559,6283.0758499914]]],[[],[[.00227777722,3.4137662053,6283.0758499914],[3805678e-11,3.37063423795,12566.1516999828]]],[[[1.00013988784,0,0],[.01670699632,3.09846350258,6283.0758499914],[.00013956024,3.05524609456,12566.1516999828],[308372e-10,5.19846674381,77713.7714681205],[1628463e-11,1.17387558054,5753.3848848968],[1575572e-11,2.84685214877,7860.4193924392],[924799e-11,5.45292236722,11506.7697697936],[542439e-11,4.56409151453,3930.2096962196],[47211e-10,3.66100022149,5884.9268465832],[85831e-11,1.27079125277,161000.6857376741],[57056e-11,2.01374292245,83996.84731811189],[55736e-11,5.2415979917,71430.69561812909],[174844e-11,3.01193636733,18849.2275499742],[243181e-11,4.2734953079,11790.6290886588]],[[.00103018607,1.10748968172,6283.0758499914],[1721238e-11,1.06442300386,12566.1516999828]],[[4359385e-11,5.78455133808,6283.0758499914]]]],Mars:[[[[6.20347711581,0,0],[.18656368093,5.0503710027,3340.6124266998],[.01108216816,5.40099836344,6681.2248533996],[.00091798406,5.75478744667,10021.8372800994],[.00027744987,5.97049513147,3.523118349],[.00010610235,2.93958560338,2281.2304965106],[.00012315897,.84956094002,2810.9214616052],[8926784e-11,4.15697846427,.0172536522],[8715691e-11,6.11005153139,13362.4497067992],[6797556e-11,.36462229657,398.1490034082],[7774872e-11,3.33968761376,5621.8429232104],[3575078e-11,1.6618650571,2544.3144198834],[4161108e-11,.22814971327,2942.4634232916],[3075252e-11,.85696614132,191.4482661116],[2628117e-11,.64806124465,3337.0893083508],[2937546e-11,6.07893711402,.0673103028],[2389414e-11,5.03896442664,796.2980068164],[2579844e-11,.02996736156,3344.1355450488],[1528141e-11,1.14979301996,6151.533888305],[1798806e-11,.65634057445,529.6909650946],[1264357e-11,3.62275122593,5092.1519581158],[1286228e-11,3.06796065034,2146.1654164752],[1546404e-11,2.91579701718,1751.539531416],[1024902e-11,3.69334099279,8962.4553499102],[891566e-11,.18293837498,16703.062133499],[858759e-11,2.4009381194,2914.0142358238],[832715e-11,2.46418619474,3340.5951730476],[83272e-10,4.49495782139,3340.629680352],[712902e-11,3.66335473479,1059.3819301892],[748723e-11,3.82248614017,155.4203994342],[723861e-11,.67497311481,3738.761430108],[635548e-11,2.92182225127,8432.7643848156],[655162e-11,.48864064125,3127.3133312618],[550474e-11,3.81001042328,.9803210682],[55275e-10,4.47479317037,1748.016413067],[425966e-11,.55364317304,6283.0758499914],[415131e-11,.49662285038,213.299095438],[472167e-11,3.62547124025,1194.4470102246],[306551e-11,.38052848348,6684.7479717486],[312141e-11,.99853944405,6677.7017350506],[293198e-11,4.22131299634,20.7753954924],[302375e-11,4.48618007156,3532.0606928114],[274027e-11,.54222167059,3340.545116397],[281079e-11,5.88163521788,1349.8674096588],[231183e-11,1.28242156993,3870.3033917944],[283602e-11,5.7688543494,3149.1641605882],[236117e-11,5.75503217933,3333.498879699],[274033e-11,.13372524985,3340.6797370026],[299395e-11,2.78323740866,6254.6266625236]],[[3340.61242700512,0,0],[.01457554523,3.60433733236,3340.6124266998],[.00168414711,3.92318567804,6681.2248533996],[.00020622975,4.26108844583,10021.8372800994],[3452392e-11,4.7321039319,3.523118349],[2586332e-11,4.60670058555,13362.4497067992],[841535e-11,4.45864030426,2281.2304965106]],[[.00058152577,2.04961712429,3340.6124266998],[.00013459579,2.45738706163,6681.2248533996]]],[[[.03197134986,3.76832042431,3340.6124266998],[.00298033234,4.10616996305,6681.2248533996],[.00289104742,0,0],[.00031365539,4.4465105309,10021.8372800994],[34841e-9,4.7881254926,13362.4497067992]],[[.00217310991,6.04472194776,3340.6124266998],[.00020976948,3.14159265359,0],[.00012834709,1.60810667915,6681.2248533996]]],[[[1.53033488271,0,0],[.1418495316,3.47971283528,3340.6124266998],[.00660776362,3.81783443019,6681.2248533996],[.00046179117,4.15595316782,10021.8372800994],[8109733e-11,5.55958416318,2810.9214616052],[7485318e-11,1.77239078402,5621.8429232104],[5523191e-11,1.3643630377,2281.2304965106],[382516e-10,4.49407183687,13362.4497067992],[2306537e-11,.09081579001,2544.3144198834],[1999396e-11,5.36059617709,3337.0893083508],[2484394e-11,4.9254563992,2942.4634232916],[1960195e-11,4.74249437639,3344.1355450488],[1167119e-11,2.11260868341,5092.1519581158],[1102816e-11,5.00908403998,398.1490034082],[899066e-11,4.40791133207,529.6909650946],[992252e-11,5.83861961952,6151.533888305],[807354e-11,2.10217065501,1059.3819301892],[797915e-11,3.44839203899,796.2980068164],[740975e-11,1.49906336885,2146.1654164752]],[[.01107433345,2.03250524857,3340.6124266998],[.00103175887,2.37071847807,6681.2248533996],[128772e-9,0,0],[.0001081588,2.70888095665,10021.8372800994]],[[.00044242249,.47930604954,3340.6124266998],[8138042e-11,.86998389204,6681.2248533996]]]],Jupiter:[[[[.59954691494,0,0],[.09695898719,5.06191793158,529.6909650946],[.00573610142,1.44406205629,7.1135470008],[.00306389205,5.41734730184,1059.3819301892],[.00097178296,4.14264726552,632.7837393132],[.00072903078,3.64042916389,522.5774180938],[.00064263975,3.41145165351,103.0927742186],[.00039806064,2.29376740788,419.4846438752],[.00038857767,1.27231755835,316.3918696566],[.00027964629,1.7845459182,536.8045120954],[.0001358973,5.7748104079,1589.0728952838],[8246349e-11,3.5822792584,206.1855484372],[8768704e-11,3.63000308199,949.1756089698],[7368042e-11,5.0810119427,735.8765135318],[626315e-10,.02497628807,213.299095438],[6114062e-11,4.51319998626,1162.4747044078],[4905396e-11,1.32084470588,110.2063212194],[5305285e-11,1.30671216791,14.2270940016],[5305441e-11,4.18625634012,1052.2683831884],[4647248e-11,4.69958103684,3.9321532631],[3045023e-11,4.31676431084,426.598190876],[2609999e-11,1.56667394063,846.0828347512],[2028191e-11,1.06376530715,3.1813937377],[1764763e-11,2.14148655117,1066.49547719],[1722972e-11,3.88036268267,1265.5674786264],[1920945e-11,.97168196472,639.897286314],[1633223e-11,3.58201833555,515.463871093],[1431999e-11,4.29685556046,625.6701923124],[973272e-11,4.09764549134,95.9792272178]],[[529.69096508814,0,0],[.00489503243,4.2208293947,529.6909650946],[.00228917222,6.02646855621,7.1135470008],[.00030099479,4.54540782858,1059.3819301892],[.0002072092,5.45943156902,522.5774180938],[.00012103653,.16994816098,536.8045120954],[6067987e-11,4.42422292017,103.0927742186],[5433968e-11,3.98480737746,419.4846438752],[4237744e-11,5.89008707199,14.2270940016]],[[.00047233601,4.32148536482,7.1135470008],[.00030649436,2.929777887,529.6909650946],[.00014837605,3.14159265359,0]]],[[[.02268615702,3.55852606721,529.6909650946],[.00109971634,3.90809347197,1059.3819301892],[.00110090358,0,0],[8101428e-11,3.60509572885,522.5774180938],[6043996e-11,4.25883108339,1589.0728952838],[6437782e-11,.30627119215,536.8045120954]],[[.00078203446,1.52377859742,529.6909650946]]],[[[5.20887429326,0,0],[.25209327119,3.49108639871,529.6909650946],[.00610599976,3.84115365948,1059.3819301892],[.00282029458,2.57419881293,632.7837393132],[.00187647346,2.07590383214,522.5774180938],[.00086792905,.71001145545,419.4846438752],[.00072062974,.21465724607,536.8045120954],[.00065517248,5.9799588479,316.3918696566],[.00029134542,1.67759379655,103.0927742186],[.00030135335,2.16132003734,949.1756089698],[.00023453271,3.54023522184,735.8765135318],[.00022283743,4.19362594399,1589.0728952838],[.00023947298,.2745803748,7.1135470008],[.00013032614,2.96042965363,1162.4747044078],[970336e-10,1.90669633585,206.1855484372],[.00012749023,2.71550286592,1052.2683831884],[7057931e-11,2.18184839926,1265.5674786264],[6137703e-11,6.26418240033,846.0828347512],[2616976e-11,2.00994012876,1581.959348283]],[[.0127180152,2.64937512894,529.6909650946],[.00061661816,3.00076460387,1059.3819301892],[.00053443713,3.89717383175,522.5774180938],[.00031185171,4.88276958012,536.8045120954],[.00041390269,0,0]]]],Saturn:[[[[.87401354025,0,0],[.11107659762,3.96205090159,213.299095438],[.01414150957,4.58581516874,7.1135470008],[.00398379389,.52112032699,206.1855484372],[.00350769243,3.30329907896,426.598190876],[.00206816305,.24658372002,103.0927742186],[792713e-9,3.84007056878,220.4126424388],[.00023990355,4.66976924553,110.2063212194],[.00016573588,.43719228296,419.4846438752],[.00014906995,5.76903183869,316.3918696566],[.0001582029,.93809155235,632.7837393132],[.00014609559,1.56518472,3.9321532631],[.00013160301,4.44891291899,14.2270940016],[.00015053543,2.71669915667,639.897286314],[.00013005299,5.98119023644,11.0457002639],[.00010725067,3.12939523827,202.2533951741],[5863206e-11,.23656938524,529.6909650946],[5227757e-11,4.20783365759,3.1813937377],[6126317e-11,1.76328667907,277.0349937414],[5019687e-11,3.17787728405,433.7117378768],[459255e-10,.61977744975,199.0720014364],[4005867e-11,2.24479718502,63.7358983034],[2953796e-11,.98280366998,95.9792272178],[387367e-10,3.22283226966,138.5174968707],[2461186e-11,2.03163875071,735.8765135318],[3269484e-11,.77492638211,949.1756089698],[1758145e-11,3.2658010994,522.5774180938],[1640172e-11,5.5050445305,846.0828347512],[1391327e-11,4.02333150505,323.5054166574],[1580648e-11,4.37265307169,309.2783226558],[1123498e-11,2.83726798446,415.5524906121],[1017275e-11,3.71700135395,227.5261894396],[848642e-11,3.1915017083,209.3669421749]],[[213.2990952169,0,0],[.01297370862,1.82834923978,213.299095438],[.00564345393,2.88499717272,7.1135470008],[.00093734369,1.06311793502,426.598190876],[.00107674962,2.27769131009,206.1855484372],[.00040244455,2.04108104671,220.4126424388],[.00019941774,1.2795439047,103.0927742186],[.00010511678,2.7488034213,14.2270940016],[6416106e-11,.38238295041,639.897286314],[4848994e-11,2.43037610229,419.4846438752],[4056892e-11,2.92133209468,110.2063212194],[3768635e-11,3.6496533078,3.9321532631]],[[.0011644133,1.17988132879,7.1135470008],[.00091841837,.0732519584,213.299095438],[.00036661728,0,0],[.00015274496,4.06493179167,206.1855484372]]],[[[.04330678039,3.60284428399,213.299095438],[.00240348302,2.85238489373,426.598190876],[.00084745939,0,0],[.00030863357,3.48441504555,220.4126424388],[.00034116062,.57297307557,206.1855484372],[.0001473407,2.11846596715,639.897286314],[9916667e-11,5.79003188904,419.4846438752],[6993564e-11,4.7360468972,7.1135470008],[4807588e-11,5.43305312061,316.3918696566]],[[.00198927992,4.93901017903,213.299095438],[.00036947916,3.14159265359,0],[.00017966989,.5197943111,426.598190876]]],[[[9.55758135486,0,0],[.52921382865,2.39226219573,213.299095438],[.01873679867,5.2354960466,206.1855484372],[.01464663929,1.64763042902,426.598190876],[.00821891141,5.93520042303,316.3918696566],[.00547506923,5.0153261898,103.0927742186],[.0037168465,2.27114821115,220.4126424388],[.00361778765,3.13904301847,7.1135470008],[.00140617506,5.70406606781,632.7837393132],[.00108974848,3.29313390175,110.2063212194],[.00069006962,5.94099540992,419.4846438752],[.00061053367,.94037691801,639.897286314],[.00048913294,1.55733638681,202.2533951741],[.00034143772,.19519102597,277.0349937414],[.00032401773,5.47084567016,949.1756089698],[.00020936596,.46349251129,735.8765135318],[9796004e-11,5.20477537945,1265.5674786264],[.00011993338,5.98050967385,846.0828347512],[208393e-9,1.52102476129,433.7117378768],[.00015298404,3.0594381494,529.6909650946],[6465823e-11,.17732249942,1052.2683831884],[.00011380257,1.7310542704,522.5774180938],[3419618e-11,4.94550542171,1581.959348283]],[[.0618298134,.2584351148,213.299095438],[.00506577242,.71114625261,206.1855484372],[.00341394029,5.79635741658,426.598190876],[.00188491195,.47215589652,220.4126424388],[.00186261486,3.14159265359,0],[.00143891146,1.40744822888,7.1135470008]],[[.00436902572,4.78671677509,213.299095438]]]],Uranus:[[[[5.48129294297,0,0],[.09260408234,.89106421507,74.7815985673],[.01504247898,3.6271926092,1.4844727083],[.00365981674,1.89962179044,73.297125859],[.00272328168,3.35823706307,149.5631971346],[.00070328461,5.39254450063,63.7358983034],[.00068892678,6.09292483287,76.2660712756],[.00061998615,2.26952066061,2.9689454166],[.00061950719,2.85098872691,11.0457002639],[.0002646877,3.14152083966,71.8126531507],[.00025710476,6.11379840493,454.9093665273],[.0002107885,4.36059339067,148.0787244263],[.00017818647,1.74436930289,36.6485629295],[.00014613507,4.73732166022,3.9321532631],[.00011162509,5.8268179635,224.3447957019],[.0001099791,.48865004018,138.5174968707],[9527478e-11,2.95516862826,35.1640902212],[7545601e-11,5.236265824,109.9456887885],[4220241e-11,3.23328220918,70.8494453042],[40519e-9,2.277550173,151.0476698429],[3354596e-11,1.0654900738,4.4534181249],[2926718e-11,4.62903718891,9.5612275556],[349034e-10,5.48306144511,146.594251718],[3144069e-11,4.75199570434,77.7505439839],[2922333e-11,5.35235361027,85.8272988312],[2272788e-11,4.36600400036,70.3281804424],[2051219e-11,1.51773566586,.1118745846],[2148602e-11,.60745949945,38.1330356378],[1991643e-11,4.92437588682,277.0349937414],[1376226e-11,2.04283539351,65.2203710117],[1666902e-11,3.62744066769,380.12776796],[1284107e-11,3.11347961505,202.2533951741],[1150429e-11,.93343589092,3.1813937377],[1533221e-11,2.58594681212,52.6901980395],[1281604e-11,.54271272721,222.8603229936],[1372139e-11,4.19641530878,111.4301614968],[1221029e-11,.1990065003,108.4612160802],[946181e-11,1.19253165736,127.4717966068],[1150989e-11,4.17898916639,33.6796175129]],[[74.7815986091,0,0],[.00154332863,5.24158770553,74.7815985673],[.00024456474,1.71260334156,1.4844727083],[9258442e-11,.4282973235,11.0457002639],[8265977e-11,1.50218091379,63.7358983034],[915016e-10,1.41213765216,149.5631971346]]],[[[.01346277648,2.61877810547,74.7815985673],[623414e-9,5.08111189648,149.5631971346],[.00061601196,3.14159265359,0],[9963722e-11,1.61603805646,76.2660712756],[992616e-10,.57630380333,73.297125859]],[[.00034101978,.01321929936,74.7815985673]]],[[[19.21264847206,0,0],[.88784984413,5.60377527014,74.7815985673],[.03440836062,.32836099706,73.297125859],[.0205565386,1.7829515933,149.5631971346],[.0064932241,4.52247285911,76.2660712756],[.00602247865,3.86003823674,63.7358983034],[.00496404167,1.40139935333,454.9093665273],[.00338525369,1.58002770318,138.5174968707],[.00243509114,1.57086606044,71.8126531507],[.00190522303,1.99809394714,1.4844727083],[.00161858838,2.79137786799,148.0787244263],[.00143706183,1.38368544947,11.0457002639],[.00093192405,.17437220467,36.6485629295],[.00071424548,4.24509236074,224.3447957019],[.00089806014,3.66105364565,109.9456887885],[.00039009723,1.66971401684,70.8494453042],[.00046677296,1.39976401694,35.1640902212],[.00039025624,3.36234773834,277.0349937414],[.00036755274,3.88649278513,146.594251718],[.00030348723,.70100838798,151.0476698429],[.00029156413,3.180563367,77.7505439839],[.00022637073,.72518687029,529.6909650946],[.00011959076,1.7504339214,984.6003316219],[.00025620756,5.25656086672,380.12776796]],[[.01479896629,3.67205697578,74.7815985673]]]],Neptune:[[[[5.31188633046,0,0],[.0179847553,2.9010127389,38.1330356378],[.01019727652,.48580922867,1.4844727083],[.00124531845,4.83008090676,36.6485629295],[.00042064466,5.41054993053,2.9689454166],[.00037714584,6.09221808686,35.1640902212],[.00033784738,1.24488874087,76.2660712756],[.00016482741,7727998e-11,491.5579294568],[9198584e-11,4.93747051954,39.6175083461],[899425e-10,.27462171806,175.1660598002]],[[38.13303563957,0,0],[.00016604172,4.86323329249,1.4844727083],[.00015744045,2.27887427527,38.1330356378]]],[[[.03088622933,1.44104372644,38.1330356378],[.00027780087,5.91271884599,76.2660712756],[.00027623609,0,0],[.00015355489,2.52123799551,36.6485629295],[.00015448133,3.50877079215,39.6175083461]]],[[[30.07013205828,0,0],[.27062259632,1.32999459377,38.1330356378],[.01691764014,3.25186135653,36.6485629295],[.00807830553,5.18592878704,1.4844727083],[.0053776051,4.52113935896,35.1640902212],[.00495725141,1.5710564165,491.5579294568],[.00274571975,1.84552258866,175.1660598002],[.0001201232,1.92059384991,1021.2488945514],[.00121801746,5.79754470298,76.2660712756],[.00100896068,.3770272493,73.297125859],[.00135134092,3.37220609835,39.6175083461],[7571796e-11,1.07149207335,388.4651552382]]]]};function hD(a){var e,t,i,n,s,r,o;const l=2e3+(a-14)/ZI;return l<-500?(e=(l-1820)/100,-20+32*e*e):l<500?(e=l/100,t=e*e,i=e*t,n=t*t,s=t*i,r=i*i,10583.6-1014.41*e+33.78311*t-5.952053*i-.1798452*n+.022174192*s+.0090316521*r):l<1600?(e=(l-1e3)/100,t=e*e,i=e*t,n=t*t,s=t*i,r=i*i,1574.2-556.01*e+71.23472*t+.319781*i-.8503463*n-.005050998*s+.0083572073*r):l<1700?(e=l-1600,t=e*e,i=e*t,120-.9808*e-.01532*t+i/7129):l<1800?(e=l-1700,t=e*e,i=e*t,n=t*t,8.83+.1603*e-.0059285*t+13336e-8*i-n/1174e3):l<1860?(e=l-1800,t=e*e,i=e*t,n=t*t,s=t*i,r=i*i,o=i*n,13.72-.332447*e+.0068612*t+.0041116*i-37436e-8*n+121272e-10*s-1699e-10*r+875e-12*o):l<1900?(e=l-1860,t=e*e,i=e*t,n=t*t,s=t*i,7.62+.5737*e-.251754*t+.01680668*i-.0004473624*n+s/233174):l<1920?(e=l-1900,t=e*e,i=e*t,n=t*t,-2.79+1.494119*e-.0598939*t+.0061966*i-197e-6*n):l<1941?(e=l-1920,t=e*e,i=e*t,21.2+.84493*e-.0761*t+.0020936*i):l<1961?(e=l-1950,t=e*e,i=e*t,29.07+.407*e-t/233+i/2547):l<1986?(e=l-1975,t=e*e,i=e*t,45.45+1.067*e-t/260-i/718):l<2005?(e=l-2e3,t=e*e,i=e*t,n=t*t,s=t*i,63.86+.3345*e-.060374*t+.0017275*i+651814e-9*n+2373599e-11*s):l<2050?(e=l-2e3,62.92+.32217*e+.005589*e*e):l<2150?(e=(l-1820)/100,-20+32*e*e-.5628*(2150-l)):(e=(l-1820)/100,-20+32*e*e)}let dD=hD;function Q1(a){return a+dD(a)/86400}class no{constructor(e){if(e instanceof no){this.date=e.date,this.ut=e.ut,this.tt=e.tt;return}const t=1e3*3600*24;if(e instanceof Date&&Number.isFinite(e.getTime())){this.date=e,this.ut=(e.getTime()-Z1.getTime())/t,this.tt=Q1(this.ut);return}if(Number.isFinite(e)){this.date=new Date(Z1.getTime()+e*t),this.ut=e,this.tt=Q1(this.ut);return}throw"Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date."}static FromTerrestrialTime(e){let t=new no(e);for(;;){const i=e-t.tt;if(Math.abs(i)<1e-12)return t;t=t.AddDays(i)}}toString(){return this.date.toISOString()}AddDays(e){return new no(this.ut+e)}}function uD(a,e,t){return new no(a.ut+t*(e.ut-a.ut))}function Ht(a){return a instanceof no?a:new no(a)}function pD(a){function e(u){return u%jI*nl}const t=a.tt/36525,i=e(128710479305e-5+t*1295965810481e-4),n=e(335779.526232+t*17395272628478e-4),s=e(107226070369e-5+t*1602961601209e-3),r=e(450160.398036-t*69628905431e-4);let o=Math.sin(r),l=Math.cos(r),c=(-172064161-174666*t)*o+33386*l,h=(92052331+9086*t)*l+15377*o,d=2*(n-s+r);return o=Math.sin(d),l=Math.cos(d),c+=(-13170906-1675*t)*o-13696*l,h+=(5730336-3015*t)*l-4587*o,d=2*(n+r),o=Math.sin(d),l=Math.cos(d),c+=(-2276413-234*t)*o+2796*l,h+=(978459-485*t)*l+1374*o,d=2*r,o=Math.sin(d),l=Math.cos(d),c+=(2074554+207*t)*o-698*l,h+=(-897492+470*t)*l-291*o,o=Math.sin(i),l=Math.cos(i),c+=(1475877-3633*t)*o+11817*l,h+=(73871-184*t)*l-1924*o,{dpsi:-135e-6+c*1e-7,deps:388e-6+h*1e-7}}function nw(a){var e=a.tt/36525,t=((((-434e-10*e-576e-9)*e+.0020034)*e-1831e-7)*e-46.836769)*e+84381.406;return t/3600}var jh;function oh(a){if(!jh||Math.abs(jh.tt-a.tt)>1e-6){const e=pD(a),t=nw(a),i=t+e.deps/3600;jh={tt:a.tt,dpsi:e.dpsi,deps:e.deps,ee:e.dpsi*Math.cos(t*ge)/15,mobl:t,tobl:i}}return jh}function fD(a,e){const t=a*ge,i=Math.cos(t),n=Math.sin(t);return[e[0],e[1]*i-e[2]*n,e[1]*n+e[2]*i]}function mD(a,e){return fD(nw(a),e)}function sw(a){const e=a.tt/36525;function t(ke,Ee){const He=[];let Ge;for(Ge=0;Ge<=Ee-ke;++Ge)He.push(0);return{min:ke,array:He}}function i(ke,Ee,He,Ge){const Ve=[];for(let Lt=0;Lt<=Ee-ke;++Lt)Ve.push(t(He,Ge));return{min:ke,array:Ve}}function n(ke,Ee,He){const Ge=ke.array[Ee-ke.min];return Ge.array[He-Ge.min]}function s(ke,Ee,He,Ge){const Ve=ke.array[Ee-ke.min];Ve.array[He-Ve.min]=Ge}let r,o,l,c,h,d,u,p,f,g,m,v,x,y,b,w,S,_,M,T,A,R,C,k=i(-6,6,1,4),z=i(-6,6,1,4);function L(ke,Ee){return n(k,ke,Ee)}function N(ke,Ee){return n(z,ke,Ee)}function F(ke,Ee,He){return s(k,ke,Ee,He)}function V(ke,Ee,He){return s(z,ke,Ee,He)}function Z(ke,Ee,He,Ge,Ve){Ve(ke*He-Ee*Ge,Ee*He+ke*Ge)}function K(ke){return Math.sin(gr*ke)}u=e*e,f=0,C=0,m=0,v=3422.7;var ie=K(.19833+.05611*e),oe=K(.27869+.04508*e),qe=K(.16827-.36903*e),ot=K(.34734-5.37261*e),Qe=K(.10498-5.37899*e),q=K(.42681-.41855*e),re=K(.14943-5.37511*e);for(_=.84*ie+.31*oe+14.27*qe+7.26*ot+.28*Qe+.24*q,M=2.94*ie+.31*oe+14.27*qe+9.34*ot+1.12*Qe+.83*q,T=-6.4*ie-1.89*q,A=.21*ie+.31*oe+14.27*qe-88.7*ot-15.3*Qe+.24*q-1.86*re,R=_-T,p=-3332e-9*K(.59734-5.37261*e)-539e-9*K(.35498-5.37899*e)-64e-9*K(.39943-5.37511*e),x=gr*Wo(.60643382+1336.85522467*e-313e-8*u)+_/Gr,y=gr*Wo(.37489701+1325.55240982*e+2565e-8*u)+M/Gr,b=gr*Wo(.99312619+99.99735956*e-44e-8*u)+T/Gr,w=gr*Wo(.25909118+1342.2278298*e-892e-8*u)+A/Gr,S=gr*Wo(.82736186+1236.85308708*e-397e-8*u)+R/Gr,h=1;h<=4;++h){switch(h){case 1:l=y,o=4,c=1.000002208;break;case 2:l=b,o=3,c=.997504612-.002495388*e;break;case 3:l=w,o=4,c=1.000002708+139.978*p;break;case 4:l=S,o=6,c=1;break;default:throw`Internal error: I = ${h}`}for(F(0,h,1),F(1,h,Math.cos(l)*c),V(0,h,0),V(1,h,Math.sin(l)*c),d=2;d<=o;++d)Z(L(d-1,h),N(d-1,h),L(1,h),N(1,h),(ke,Ee)=>(F(d,h,ke),V(d,h,Ee)));for(d=1;d<=o;++d)F(-d,h,L(d,h)),V(-d,h,-N(d,h))}function ne(ke,Ee,He,Ge){for(var Ve={x:1,y:0},Lt=[0,ke,Ee,He,Ge],kt=1;kt<=4;++kt)Lt[kt]!==0&&Z(Ve.x,Ve.y,L(Lt[kt],kt),N(Lt[kt],kt),(pi,si)=>(Ve.x=pi,Ve.y=si));return Ve}function G(ke,Ee,He,Ge,Ve,Lt,kt,pi){var si=ne(Ve,Lt,kt,pi);f+=ke*si.y,C+=Ee*si.y,m+=He*si.x,v+=Ge*si.x}G(13.902,14.06,-.001,.2607,0,0,0,4),G(.403,-4.01,.394,.0023,0,0,0,3),G(2369.912,2373.36,.601,28.2333,0,0,0,2),G(-125.154,-112.79,-.725,-.9781,0,0,0,1),G(1.979,6.98,-.445,.0433,1,0,0,4),G(191.953,192.72,.029,3.0861,1,0,0,2),G(-8.466,-13.51,.455,-.1093,1,0,0,1),G(22639.5,22609.07,.079,186.5398,1,0,0,0),G(18.609,3.59,-.094,.0118,1,0,0,-1),G(-4586.465,-4578.13,-.077,34.3117,1,0,0,-2),G(3.215,5.44,.192,-.0386,1,0,0,-3),G(-38.428,-38.64,.001,.6008,1,0,0,-4),G(-.393,-1.43,-.092,.0086,1,0,0,-6),G(-.289,-1.59,.123,-.0053,0,1,0,4),G(-24.42,-25.1,.04,-.3,0,1,0,2),G(18.023,17.93,.007,.1494,0,1,0,1),G(-668.146,-126.98,-1.302,-.3997,0,1,0,0),G(.56,.32,-.001,-.0037,0,1,0,-1),G(-165.145,-165.06,.054,1.9178,0,1,0,-2),G(-1.877,-6.46,-.416,.0339,0,1,0,-4),G(.213,1.02,-.074,.0054,2,0,0,4),G(14.387,14.78,-.017,.2833,2,0,0,2),G(-.586,-1.2,.054,-.01,2,0,0,1),G(769.016,767.96,.107,10.1657,2,0,0,0),G(1.75,2.01,-.018,.0155,2,0,0,-1),G(-211.656,-152.53,5.679,-.3039,2,0,0,-2),G(1.225,.91,-.03,-.0088,2,0,0,-3),G(-30.773,-34.07,-.308,.3722,2,0,0,-4),G(-.57,-1.4,-.074,.0109,2,0,0,-6),G(-2.921,-11.75,.787,-.0484,1,1,0,2),G(1.267,1.52,-.022,.0164,1,1,0,1),G(-109.673,-115.18,.461,-.949,1,1,0,0),G(-205.962,-182.36,2.056,1.4437,1,1,0,-2),G(.233,.36,.012,-.0025,1,1,0,-3),G(-4.391,-9.66,-.471,.0673,1,1,0,-4),G(.283,1.53,-.111,.006,1,-1,0,4),G(14.577,31.7,-1.54,.2302,1,-1,0,2),G(147.687,138.76,.679,1.1528,1,-1,0,0),G(-1.089,.55,.021,0,1,-1,0,-1),G(28.475,23.59,-.443,-.2257,1,-1,0,-2),G(-.276,-.38,-.006,-.0036,1,-1,0,-3),G(.636,2.27,.146,-.0102,1,-1,0,-4),G(-.189,-1.68,.131,-.0028,0,2,0,2),G(-7.486,-.66,-.037,-.0086,0,2,0,0),G(-8.096,-16.35,-.74,.0918,0,2,0,-2),G(-5.741,-.04,0,-9e-4,0,0,2,2),G(.255,0,0,0,0,0,2,1),G(-411.608,-.2,0,-.0124,0,0,2,0),G(.584,.84,0,.0071,0,0,2,-1),G(-55.173,-52.14,0,-.1052,0,0,2,-2),G(.254,.25,0,-.0017,0,0,2,-3),G(.025,-1.67,0,.0031,0,0,2,-4),G(1.06,2.96,-.166,.0243,3,0,0,2),G(36.124,50.64,-1.3,.6215,3,0,0,0),G(-13.193,-16.4,.258,-.1187,3,0,0,-2),G(-1.187,-.74,.042,.0074,3,0,0,-4),G(-.293,-.31,-.002,.0046,3,0,0,-6),G(-.29,-1.45,.116,-.0051,2,1,0,2),G(-7.649,-10.56,.259,-.1038,2,1,0,0),G(-8.627,-7.59,.078,-.0192,2,1,0,-2),G(-2.74,-2.54,.022,.0324,2,1,0,-4),G(1.181,3.32,-.212,.0213,2,-1,0,2),G(9.703,11.67,-.151,.1268,2,-1,0,0),G(-.352,-.37,.001,-.0028,2,-1,0,-1),G(-2.494,-1.17,-.003,-.0017,2,-1,0,-2),G(.36,.2,-.012,-.0043,2,-1,0,-4),G(-1.167,-1.25,.008,-.0106,1,2,0,0),G(-7.412,-6.12,.117,.0484,1,2,0,-2),G(-.311,-.65,-.032,.0044,1,2,0,-4),G(.757,1.82,-.105,.0112,1,-2,0,2),G(2.58,2.32,.027,.0196,1,-2,0,0),G(2.533,2.4,-.014,-.0212,1,-2,0,-2),G(-.344,-.57,-.025,.0036,0,3,0,-2),G(-.992,-.02,0,0,1,0,2,2),G(-45.099,-.02,0,-.001,1,0,2,0),G(-.179,-9.52,0,-.0833,1,0,2,-2),G(-.301,-.33,0,.0014,1,0,2,-4),G(-6.382,-3.37,0,-.0481,1,0,-2,2),G(39.528,85.13,0,-.7136,1,0,-2,0),G(9.366,.71,0,-.0112,1,0,-2,-2),G(.202,.02,0,0,1,0,-2,-4),G(.415,.1,0,.0013,0,1,2,0),G(-2.152,-2.26,0,-.0066,0,1,2,-2),G(-1.44,-1.3,0,.0014,0,1,-2,2),G(.384,-.04,0,0,0,1,-2,-2),G(1.938,3.6,-.145,.0401,4,0,0,0),G(-.952,-1.58,.052,-.013,4,0,0,-2),G(-.551,-.94,.032,-.0097,3,1,0,0),G(-.482,-.57,.005,-.0045,3,1,0,-2),G(.681,.96,-.026,.0115,3,-1,0,0),G(-.297,-.27,.002,-9e-4,2,2,0,-2),G(.254,.21,-.003,0,2,-2,0,-2),G(-.25,-.22,.004,.0014,1,3,0,-2),G(-3.996,0,0,4e-4,2,0,2,0),G(.557,-.75,0,-.009,2,0,2,-2),G(-.459,-.38,0,-.0053,2,0,-2,2),G(-1.298,.74,0,4e-4,2,0,-2,0),G(.538,1.14,0,-.0141,2,0,-2,-2),G(.263,.02,0,0,1,1,2,0),G(.426,.07,0,-6e-4,1,1,-2,-2),G(-.304,.03,0,3e-4,1,-1,2,0),G(-.372,-.19,0,-.0027,1,-1,-2,2),G(.418,0,0,0,0,0,4,0),G(-.33,-.04,0,0,3,0,2,0);function Re(ke,Ee,He,Ge,Ve){return ke*ne(Ee,He,Ge,Ve).y}g=0,g+=Re(-526.069,0,0,1,-2),g+=Re(-3.352,0,0,1,-4),g+=Re(44.297,1,0,1,-2),g+=Re(-6,1,0,1,-4),g+=Re(20.599,-1,0,1,0),g+=Re(-30.598,-1,0,1,-2),g+=Re(-24.649,-2,0,1,0),g+=Re(-2,-2,0,1,-2),g+=Re(-22.571,0,1,1,-2),g+=Re(10.985,0,-1,1,-2),f+=.82*K(.7736-62.5512*e)+.31*K(.0466-125.1025*e)+.35*K(.5785-25.1042*e)+.66*K(.4591+1335.8075*e)+.64*K(.313-91.568*e)+1.14*K(.148+1331.2898*e)+.21*K(.5918+1056.5859*e)+.44*K(.5784+1322.8595*e)+.24*K(.2275-5.7374*e)+.28*K(.2965+2.6929*e)+.33*K(.3132+6.3368*e),r=w+C/Gr;let Ue=(1.000002708+139.978*p)*(18518.511+1.189+m)*Math.sin(r)-6.24*Math.sin(3*r)+g;return{geo_eclip_lon:gr*Wo((x+f/Gr)/gr),geo_eclip_lat:Math.PI/(180*3600)*Ue,distance_au:Gr*nD/(.999953253*v)}}function rw(a,e){return[a.rot[0][0]*e[0]+a.rot[1][0]*e[1]+a.rot[2][0]*e[2],a.rot[0][1]*e[0]+a.rot[1][1]*e[1]+a.rot[2][1]*e[2],a.rot[0][2]*e[0]+a.rot[1][2]*e[1]+a.rot[2][2]*e[2]]}function jc(a,e,t){const i=cg(e,t);return rw(i,a)}function cg(a,e){const t=a.tt/36525;let i=84381.406,n=((((-951e-10*t+132851e-9)*t-.00114045)*t-1.0790069)*t+5038.481507)*t,s=((((3337e-10*t-467e-9)*t-.00772503)*t+.0512623)*t-.025754)*t+i,r=((((-56e-9*t+170663e-9)*t-.00121197)*t-2.3814292)*t+10.556403)*t;i*=nl,n*=nl,s*=nl,r*=nl;const o=Math.sin(i),l=Math.cos(i),c=Math.sin(-n),h=Math.cos(-n),d=Math.sin(-s),u=Math.cos(-s),p=Math.sin(r),f=Math.cos(r),g=f*h-c*p*u,m=f*c*l+p*u*h*l-o*p*d,v=f*c*o+p*u*h*o+l*p*d,x=-p*h-c*f*u,y=-p*c*l+f*u*h*l-o*f*d,b=-p*c*o+f*u*h*o+l*f*d,w=c*d,S=-d*h*l-o*u,_=-d*h*o+u*l;if(e===Pi.Into2000)return new or([[g,m,v],[x,y,b],[w,S,_]]);if(e===Pi.From2000)return new or([[g,x,w],[m,y,S],[v,b,_]]);throw"Invalid precess direction"}function gD(a){const e=.779057273264+.00273781191135448*a.ut,t=a.ut%1;let i=360*((e+t)%1);return i<0&&(i+=360),i}let Jh;function lh(a){if(!Jh||Jh.tt!==a.tt){const e=a.tt/36525;let t=15*oh(a).ee;const i=gD(a);let s=((t+.014506+((((-368e-10*e-29956e-9)*e-44e-8)*e+1.3915817)*e+4612.156534)*e)/3600+i)%360/15;s<0&&(s+=24),Jh={tt:a.tt,st:s}}return Jh.st}function vD(a){const e=Ht(a);return lh(e)}function aw(a,e){const t=a.latitude*ge,i=Math.sin(t),n=Math.cos(t),s=1/Math.hypot(n,J0*i),r=iD*s,o=a.height/1e3,l=Q0*s+o,c=Q0*r+o,h=(15*e+a.longitude)*ge,d=Math.sin(h),u=Math.cos(h);return{pos:[l*n*u/js,l*n*d/js,c*i/js],vel:[-j1*l*n*d*86400/js,j1*l*n*u*86400/js,0]}}function Du(a,e,t){const i=hg(e,t);return rw(i,a)}function hg(a,e){const t=oh(a),i=t.mobl*ge,n=t.tobl*ge,s=t.dpsi*nl,r=Math.cos(i),o=Math.sin(i),l=Math.cos(n),c=Math.sin(n),h=Math.cos(s),d=Math.sin(s),u=h,p=-d*r,f=-d*o,g=d*l,m=h*r*l+o*c,v=h*o*l-r*c,x=d*c,y=h*r*c-o*l,b=h*o*c+r*l;if(e===Pi.From2000)return new or([[u,g,x],[p,m,y],[f,v,b]]);if(e===Pi.Into2000)return new or([[u,p,f],[g,m,v],[x,y,b]]);throw"Invalid precess direction"}function ip(a,e,t){return t===Pi.Into2000?jc(Du(a,e,t),e,t):Du(jc(a,e,t),e,t)}function ow(a,e){const t=lh(a),i=aw(e,t).pos;return ip(i,a,Pi.Into2000)}class Mt{constructor(e,t,i,n){this.x=e,this.y=t,this.z=i,this.t=n}Length(){return Math.hypot(this.x,this.y,this.z)}}class ra{constructor(e,t,i,n,s,r,o){this.x=e,this.y=t,this.z=i,this.vx=n,this.vy=s,this.vz=r,this.t=o}}class np{constructor(e,t,i){this.lat=Ai(e),this.lon=Ai(t),this.dist=Ai(i)}}class sm{constructor(e,t,i,n){this.ra=Ai(e),this.dec=Ai(t),this.dist=Ai(i),this.vec=n}}class or{constructor(e){this.rot=e}}class bD{constructor(e,t,i,n){this.azimuth=Ai(e),this.altitude=Ai(t),this.ra=Ai(i),this.dec=Ai(n)}}class yD{constructor(e,t,i){this.vec=e,this.elat=Ai(t),this.elon=Ai(i)}}function lw(a,e){return new Mt(a[0],a[1],a[2],e)}function MD(a,e){const t=lw(a,e),i=t.x*t.x+t.y*t.y,n=Math.sqrt(i+t.z*t.z);if(i===0){if(t.z===0)throw"Indeterminate sky coordinates";return new sm(0,t.z<0?-90:90,n,t)}let s=QM*Math.atan2(t.y,t.x);s<0&&(s+=24);const r=Ds*Math.atan2(a[2],Math.sqrt(i));return new sm(s,r,n,t)}function wl(a,e){const t=a*ge,i=Math.cos(t),n=Math.sin(t);return[i*e[0]+n*e[1],i*e[1]-n*e[0],e[2]]}function dg(a,e,t,i,n){let s=Ht(a);sp(e),Ai(t),Ai(i);const r=Math.sin(e.latitude*ge),o=Math.cos(e.latitude*ge),l=Math.sin(e.longitude*ge),c=Math.cos(e.longitude*ge),h=Math.sin(i*ge),d=Math.cos(i*ge),u=Math.sin(t*K1),p=Math.cos(t*K1);let f=[o*c,o*l,r],g=[-r*c,-r*l,o],m=[l,-c,0];const v=-15*lh(s);let x=wl(v,f),y=wl(v,g),b=wl(v,m),w=[d*p,d*u,h];const S=w[0]*x[0]+w[1]*x[1]+w[2]*x[2],_=w[0]*y[0]+w[1]*y[1]+w[2]*y[2],M=w[0]*b[0]+w[1]*b[1]+w[2]*b[2];let T=Math.hypot(_,M),A;T>0?(A=-Ds*Math.atan2(M,_),A<0&&(A+=360)):A=0;let R=Ds*Math.atan2(T,S),C=t,k=i;if(n){let z=R,L=vw(n,90-R);if(R-=L,L>0&&R>3e-4){const N=Math.sin(R*ge),F=Math.cos(R*ge),V=Math.sin(z*ge),Z=Math.cos(z*ge),K=[];for(let ie=0;ie<3;++ie)K.push((w[ie]-Z*x[ie])/V*N+x[ie]*F);T=Math.hypot(K[0],K[1]),T>0?(C=QM*Math.atan2(K[1],K[0]),C<0&&(C+=24)):C=0,k=Ds*Math.atan2(K[2],T)}}return new bD(A,90-R,C,k)}function sp(a){if(!(a instanceof ha))throw`Not an instance of the Observer class: ${a}`;if(Ai(a.latitude),Ai(a.longitude),Ai(a.height),a.latitude<-90||a.latitude>90)throw`Latitude ${a.latitude} is out of range. Must be -90..+90.`;return a}class ha{constructor(e,t,i){this.latitude=e,this.longitude=t,this.height=i,sp(this)}}function wD(a){const e=Ht(a).AddDays(-1/ag),t=Sl(er.Earth,e),i=[-t.x,-t.y,-t.z],[n,s,r]=ip(i,e,Pi.From2000),o=ge*oh(e).tobl,l=Math.cos(o),c=Math.sin(o),h=new Mt(n,s,r,e);return cw(h,l,c)}function Jc(a,e,t,i,n){sp(t),Iu(i),Iu(n);const s=Ht(e),r=ow(s,t),o=Cu(a,s,n),l=[o.x-r[0],o.y-r[1],o.z-r[2]],c=ip(l,s,Pi.From2000);return MD(c,s)}function rm(a,e,t){const i=Ht(a),n=lh(i);let s=aw(e,n).pos;return t||(s=ip(s,i,Pi.Into2000)),lw(s,i)}function cw(a,e,t){const i=a.x,n=a.y*e+a.z*t,s=-a.y*t+a.z*e,r=Math.hypot(i,n);let o=0;r>0&&(o=Ds*Math.atan2(n,i),o<0&&(o+=360));let l=Ds*Math.atan2(s,r),c=new Mt(i,n,s,a.t);return new yD(c,l,o)}function am(a){const e=oh(a.t),t=[a.x,a.y,a.z],i=jc(t,a.t,Pi.From2000),[n,s,r]=Du(i,a.t,Pi.From2000),o=new Mt(n,s,r,a.t),l=e.tobl*ge;return cw(o,Math.cos(l),Math.sin(l))}function Tr(a){const e=Ht(a),t=sw(e),i=t.distance_au*Math.cos(t.geo_eclip_lat),n=[i*Math.cos(t.geo_eclip_lon),i*Math.sin(t.geo_eclip_lon),t.distance_au*Math.sin(t.geo_eclip_lat)],s=mD(e,n),r=jc(s,e,Pi.Into2000);return new Mt(r[0],r[1],r[2],e)}function hw(a){const e=Ht(a),t=1e-5,i=e.AddDays(-t),n=e.AddDays(+t),s=Tr(i),r=Tr(n);return new ra((s.x+r.x)/2,(s.y+r.y)/2,(s.z+r.z)/2,(r.x-s.x)/(2*t),(r.y-s.y)/(2*t),(r.z-s.z)/(2*t),e)}function xD(a){const e=Ht(a),t=hw(e),i=1+tw;return new ra(t.x/i,t.y/i,t.z/i,t.vx/i,t.vy/i,t.vz/i,e)}function xl(a,e,t){let i=1,n=0;for(let s of a){let r=0;for(let[l,c,h]of s)r+=l*Math.cos(c+e*h);let o=i*r;t&&(o%=gr),n+=o,i*=e}return n}function sf(a,e){let t=1,i=0,n=0,s=0;for(let r of a){let o=0,l=0;for(let[c,h,d]of r){let u=h+e*d;o+=c*d*Math.sin(u),s>0&&(l+=c*Math.cos(u))}n+=s*i*l-t*o,i=t,t*=e,++s}return n}const Mc=365250,om=0,lm=1,cm=2;function hm(a){return new on(a[0]+44036e-11*a[1]-190919e-12*a[2],-479966e-12*a[0]+.917482137087*a[1]-.397776982902*a[2],.397776982902*a[1]+.917482137087*a[2])}function dw(a,e,t){const i=t*Math.cos(e),n=Math.cos(a),s=Math.sin(a);return[i*n,i*s,t*Math.sin(e)]}function Sl(a,e){const t=e.tt/Mc,i=xl(a[om],t,!0),n=xl(a[lm],t,!1),s=xl(a[cm],t,!1),r=dw(i,n,s);return hm(r).ToAstroVector(e)}function dm(a,e){const t=e/Mc,i=xl(a[om],t,!0),n=xl(a[lm],t,!1),s=xl(a[cm],t,!1),r=sf(a[om],t),o=sf(a[lm],t),l=sf(a[cm],t),c=Math.cos(i),h=Math.sin(i),d=Math.cos(n),u=Math.sin(n),p=+(l*d*c)-s*u*c*o-s*d*h*r,f=+(l*d*h)-s*u*h*o+s*d*c*r,g=+(l*u)+s*d*o,m=dw(i,n,s),v=[p/Mc,f/Mc,g/Mc],x=hm(m),y=hm(v);return new uo(e,x,y)}function Qh(a,e,t,i){const n=i/(i+og),s=Sl(er[t],e);a.x+=n*s.x,a.y+=n*s.y,a.z+=n*s.z}function SD(a){const e=new Mt(0,0,0,a);return Qh(e,a,ue.Jupiter,em),Qh(e,a,ue.Saturn,tm),Qh(e,a,ue.Uranus,im),Qh(e,a,ue.Neptune,nm),e}const um=51,ED=29200,sl=146,vr=201,Za=[[-73e4,[-26.118207232108,-14.376168177825,3.384402515299],[.0016339372163656,-.0027861699588508,-.0013585880229445]],[-700800,[41.974905202127,-.448502952929,-12.770351505989],[.00073458569351457,.0022785014891658,.00048619778602049]],[-671600,[14.706930780744,44.269110540027,9.353698474772],[-.00210001479998,.00022295915939915,.00070143443551414]],[-642400,[-29.441003929957,-6.43016153057,6.858481011305],[.00084495803960544,-.0030783914758711,-.0012106305981192]],[-613200,[39.444396946234,-6.557989760571,-13.913760296463],[.0011480029005873,.0022400006880665,.00035168075922288]],[-584e3,[20.2303809507,43.266966657189,7.382966091923],[-.0019754081700585,.00053457141292226,.00075929169129793]],[-554800,[-30.65832536462,2.093818874552,9.880531138071],[61010603013347e-18,-.0031326500935382,-.00099346125151067]],[-525600,[35.737703251673,-12.587706024764,-14.677847247563],[.0015802939375649,.0021347678412429,.00019074436384343]],[-496400,[25.466295188546,41.367478338417,5.216476873382],[-.0018054401046468,.0008328308359951,.00080260156912107]],[-467200,[-29.847174904071,10.636426313081,12.297904180106],[-.00063257063052907,-.0029969577578221,-.00074476074151596]],[-438e3,[30.774692107687,-18.236637015304,-14.945535879896],[.0020113162005465,.0019353827024189,-20937793168297e-19]],[-408800,[30.243153324028,38.656267888503,2.938501750218],[-.0016052508674468,.0011183495337525,.00083333973416824]],[-379600,[-27.288984772533,18.643162147874,14.023633623329],[-.0011856388898191,-.0027170609282181,-.00049015526126399]],[-350400,[24.519605196774,-23.245756064727,-14.626862367368],[.0024322321483154,.0016062008146048,-.00023369181613312]],[-321200,[34.505274805875,35.125338586954,.557361475637],[-.0013824391637782,.0013833397561817,.00084823598806262]],[-292e3,[-23.275363915119,25.818514298769,15.055381588598],[-.0016062295460975,-.0023395961498533,-.00024377362639479]],[-262800,[17.050384798092,-27.180376290126,-13.608963321694],[.0028175521080578,.0011358749093955,-.00049548725258825]],[-233600,[38.093671910285,30.880588383337,-1.843688067413],[-.0011317697153459,.0016128814698472,.00084177586176055]],[-204400,[-18.197852930878,31.932869934309,15.438294826279],[-.0019117272501813,-.0019146495909842,-19657304369835e-18]],[-175200,[8.528924039997,-29.618422200048,-11.805400994258],[.0031034370787005,.0005139363329243,-.00077293066202546]],[-146e3,[40.94685725864,25.904973592021,-4.256336240499],[-.00083652705194051,.0018129497136404,.0008156422827306]],[-116800,[-12.326958895325,36.881883446292,15.217158258711],[-.0021166103705038,-.001481442003599,.00017401209844705]],[-87600,[-.633258375909,-30.018759794709,-9.17193287495],[.0032016994581737,-.00025279858672148,-.0010411088271861]],[-58400,[42.936048423883,20.344685584452,-6.588027007912],[-.00050525450073192,.0019910074335507,.00077440196540269]],[-29200,[-5.975910552974,40.61180995846,14.470131723673],[-.0022184202156107,-.0010562361130164,.00033652250216211]],[0,[-9.875369580774,-27.978926224737,-5.753711824704],[.0030287533248818,-.0011276087003636,-.0012651326732361]],[29200,[43.958831986165,14.214147973292,-8.808306227163],[-.00014717608981871,.0021404187242141,.00071486567806614]],[58400,[.67813676352,43.094461639362,13.243238780721],[-.0022358226110718,-.00063233636090933,.00047664798895648]],[87600,[-18.282602096834,-23.30503958666,-1.766620508028],[.0025567245263557,-.0019902940754171,-.0013943491701082]],[116800,[43.873338744526,7.700705617215,-10.814273666425],[.00023174803055677,.0022402163127924,.00062988756452032]],[146e3,[7.392949027906,44.382678951534,11.629500214854],[-.002193281545383,-.00021751799585364,.00059556516201114]],[175200,[-24.981690229261,-16.204012851426,2.466457544298],[.001819398914958,-.0026765419531201,-.0013848283502247]],[204400,[42.530187039511,.845935508021,-12.554907527683],[.00065059779150669,.0022725657282262,.00051133743202822]],[233600,[13.999526486822,44.462363044894,9.669418486465],[-.0021079296569252,.00017533423831993,.00069128485798076]],[262800,[-29.184024803031,-7.371243995762,6.493275957928],[.00093581363109681,-.0030610357109184,-.0012364201089345]],[292e3,[39.831980671753,-6.078405766765,-13.909815358656],[.0011117769689167,.0022362097830152,.00036230548231153]],[321200,[20.294955108476,43.417190420251,7.450091985932],[-.0019742157451535,.00053102050468554,.00075938408813008]],[350400,[-30.66999230216,2.318743558955,9.973480913858],[45605107450676e-18,-.0031308219926928,-.00099066533301924]],[379600,[35.626122155983,-12.897647509224,-14.777586508444],[.0016015684949743,.0021171931182284,.00018002516202204]],[408800,[26.133186148561,41.232139187599,5.00640132622],[-.0017857704419579,.00086046232702817,.00080614690298954]],[438e3,[-29.57674022923,11.863535943587,12.631323039872],[-.00072292830060955,-.0029587820140709,-.000708242964503]],[467200,[29.910805787391,-19.159019294,-15.013363865194],[.0020871080437997,.0018848372554514,-38528655083926e-18]],[496400,[31.375957451819,38.050372720763,2.433138343754],[-.0015546055556611,.0011699815465629,.00083565439266001]],[525600,[-26.360071336928,20.662505904952,14.414696258958],[-.0013142373118349,-.0026236647854842,-.00042542017598193]],[554800,[22.599441488648,-24.508879898306,-14.484045731468],[.0025454108304806,.0014917058755191,-.00030243665086079]],[584e3,[35.877864013014,33.894226366071,-.224524636277],[-.0012941245730845,.0014560427668319,.00084762160640137]],[613200,[-21.538149762417,28.204068269761,15.321973799534],[-.001731211740901,-.0021939631314577,-.0001631691327518]],[642400,[13.971521374415,-28.339941764789,-13.083792871886],[.0029334630526035,.00091860931752944,-.00059939422488627]],[671600,[39.526942044143,28.93989736011,-2.872799527539],[-.0010068481658095,.001702113288809,.00083578230511981]],[700800,[-15.576200701394,34.399412961275,15.466033737854],[-.0020098814612884,-.0017191109825989,70414782780416e-18]],[73e4,[4.24325283709,-30.118201690825,-10.707441231349],[.0031725847067411,.0001609846120227,-.00090672150593868]]];class on{constructor(e,t,i){this.x=e,this.y=t,this.z=i}clone(){return new on(this.x,this.y,this.z)}ToAstroVector(e){return new Mt(this.x,this.y,this.z,e)}static zero(){return new on(0,0,0)}quadrature(){return this.x*this.x+this.y*this.y+this.z*this.z}add(e){return new on(this.x+e.x,this.y+e.y,this.z+e.z)}sub(e){return new on(this.x-e.x,this.y-e.y,this.z-e.z)}incr(e){this.x+=e.x,this.y+=e.y,this.z+=e.z}decr(e){this.x-=e.x,this.y-=e.y,this.z-=e.z}mul(e){return new on(e*this.x,e*this.y,e*this.z)}div(e){return new on(this.x/e,this.y/e,this.z/e)}mean(e){return new on((this.x+e.x)/2,(this.y+e.y)/2,(this.z+e.z)/2)}neg(){return new on(-this.x,-this.y,-this.z)}}class uo{constructor(e,t,i){this.tt=e,this.r=t,this.v=i}clone(){return new uo(this.tt,this.r,this.v)}sub(e){return new uo(this.tt,this.r.sub(e.r),this.v.sub(e.v))}}function _D(a){let[e,[t,i,n],[s,r,o]]=a;return new uo(e,new on(t,i,n),new on(s,r,o))}function ed(a,e,t,i){const n=i/(i+og),s=dm(er[t],e);return a.r.incr(s.r.mul(n)),a.v.incr(s.v.mul(n)),s}function rc(a,e,t){const i=t.sub(a),n=i.quadrature();return i.mul(e/(n*Math.sqrt(n)))}class rp{constructor(e){let t=new uo(e,new on(0,0,0),new on(0,0,0));this.Jupiter=ed(t,e,ue.Jupiter,em),this.Saturn=ed(t,e,ue.Saturn,tm),this.Uranus=ed(t,e,ue.Uranus,im),this.Neptune=ed(t,e,ue.Neptune,nm),this.Jupiter.r.decr(t.r),this.Jupiter.v.decr(t.v),this.Saturn.r.decr(t.r),this.Saturn.v.decr(t.v),this.Uranus.r.decr(t.r),this.Uranus.v.decr(t.v),this.Neptune.r.decr(t.r),this.Neptune.v.decr(t.v),this.Sun=new uo(e,t.r.mul(-1),t.v.mul(-1))}Acceleration(e){let t=rc(e,og,this.Sun.r);return t.incr(rc(e,em,this.Jupiter.r)),t.incr(rc(e,tm,this.Saturn.r)),t.incr(rc(e,im,this.Uranus.r)),t.incr(rc(e,nm,this.Neptune.r)),t}}class ap{constructor(e,t,i,n){this.tt=e,this.r=t,this.v=i,this.a=n}clone(){return new ap(this.tt,this.r.clone(),this.v.clone(),this.a.clone())}}class uw{constructor(e,t){this.bary=e,this.grav=t}}function Ru(a,e,t,i){return new on(e.x+a*(t.x+a*i.x/2),e.y+a*(t.y+a*i.y/2),e.z+a*(t.z+a*i.z/2))}function eb(a,e,t){return new on(e.x+a*t.x,e.y+a*t.y,e.z+a*t.z)}function pm(a,e){const t=a-e.tt,i=new rp(a),n=Ru(t,e.r,e.v,e.a),s=i.Acceleration(n).mean(e.a),r=Ru(t,e.r,e.v,s),o=e.v.add(s.mul(t)),l=i.Acceleration(r),c=new ap(a,r,o,l);return new uw(i,c)}const AD=[];function pw(a,e){const t=Math.floor(a);return t<0?0:t>=e?e-1:t}function fm(a){const e=_D(a),t=new rp(e.tt),i=e.r.add(t.Sun.r),n=e.v.add(t.Sun.v),s=t.Acceleration(i),r=new ap(e.tt,i,n,s);return new uw(t,r)}function TD(a,e){const t=Za[0][0];if(e<t||e>Za[um-1][0])return null;const i=pw((e-t)/ED,um-1);if(!a[i]){const s=a[i]=[];s[0]=fm(Za[i]).grav,s[vr-1]=fm(Za[i+1]).grav;let r,o=s[0].tt;for(r=1;r<vr-1;++r)s[r]=pm(o+=sl,s[r-1]).grav;o=s[vr-1].tt;var n=[];for(n[vr-1]=s[vr-1],r=vr-2;r>0;--r)n[r]=pm(o-=sl,n[r+1]).grav;for(r=vr-2;r>0;--r){const l=r/(vr-1);s[r].r=s[r].r.mul(1-l).add(n[r].r.mul(l)),s[r].v=s[r].v.mul(1-l).add(n[r].v.mul(l)),s[r].a=s[r].a.mul(1-l).add(n[r].a.mul(l))}}return a[i]}function tb(a,e,t){let i=fm(a);const n=Math.ceil((e-i.grav.tt)/t);for(let s=0;s<n;++s)i=pm(s+1===n?e:i.grav.tt+t,i.grav);return i}function fw(a,e){let t,i,n;const s=TD(AD,a.tt);if(s){const r=pw((a.tt-s[0].tt)/sl,vr-1),o=s[r],l=s[r+1],c=o.a.mean(l.a),h=Ru(a.tt-o.tt,o.r,o.v,c),d=eb(a.tt-o.tt,o.v,c),u=Ru(a.tt-l.tt,l.r,l.v,c),p=eb(a.tt-l.tt,l.v,c),f=(a.tt-o.tt)/sl;t=h.mul(1-f).add(u.mul(f)),i=d.mul(1-f).add(p.mul(f))}else{let r;a.tt<Za[0][0]?r=tb(Za[0],a.tt,-sl):r=tb(Za[um-1],a.tt,+sl),t=r.grav.r,i=r.grav.v,n=r.bary}return n||(n=new rp(a.tt)),t=t.sub(n.Sun.r),i=i.sub(n.Sun.v),new ra(t.x,t.y,t.z,i.x,i.y,i.z,a)}function oa(a,e){var t=Ht(e);if(a in er)return Sl(er[a],t);if(a===ue.Pluto){const r=fw(t);return new Mt(r.x,r.y,r.z,t)}if(a===ue.Sun)return new Mt(0,0,0,t);if(a===ue.Moon){var i=Sl(er.Earth,t),n=Tr(t);return new Mt(i.x+n.x,i.y+n.y,i.z+n.z,t)}if(a===ue.EMB){const r=Sl(er.Earth,t),o=Tr(t),l=1+tw;return new Mt(r.x+o.x/l,r.y+o.y/l,r.z+o.z/l,t)}if(a===ue.SSB)return SD(t);const s=lg(a);if(s){const r=new np(s.dec,15*s.ra,s.dist);return mg(r,t)}throw`HelioVector: Unknown body "${a}"`}function ID(a,e){let t=e,i=0;for(let n=0;n<10;++n){const s=a(t),r=s.Length()/ag;if(r>1)throw"Object is too distant for light-travel solver.";const o=e.AddDays(-r);if(i=Math.abs(o.tt-t.tt),i<1e-9)return s;t=o}throw`Light-travel time solver did not converge: dt = ${i}`}class DD{constructor(e,t,i,n){this.observerBody=e,this.targetBody=t,this.aberration=i,this.observerPos=n}Position(e){this.aberration&&(this.observerPos=oa(this.observerBody,e));const t=oa(this.targetBody,e);return new Mt(t.x-this.observerPos.x,t.y-this.observerPos.y,t.z-this.observerPos.z,e)}}function RD(a,e,t,i){Iu(i);const n=Ht(a);if(lg(t)){const o=oa(t,n);if(i){const c=PD(e,n),h=new Mt(o.x-c.x,o.y-c.y,o.z-c.z,n),d=ag/h.Length();return new Mt(h.x+c.vx/d,h.y+c.vy/d,h.z+c.vz/d,n)}const l=oa(e,n);return new Mt(o.x-l.x,o.y-l.y,o.z-l.z,n)}let s;i?s=new Mt(0,0,0,n):s=oa(e,n);const r=new DD(e,t,i,s);return ID(o=>r.Position(o),n)}function Cu(a,e,t){Iu(t);const i=Ht(e);switch(a){case ue.Earth:return new Mt(0,0,0,i);case ue.Moon:return Tr(i);default:const n=RD(i,ue.Earth,a,t);return n.t=i,n}}function CD(a,e){return new ra(a.r.x,a.r.y,a.r.z,a.v.x,a.v.y,a.v.z,e)}function PD(a,e){const t=Ht(e);switch(a){case ue.Sun:return new ra(0,0,0,0,0,0,t);case ue.SSB:const i=new rp(t.tt);return new ra(-i.Sun.r.x,-i.Sun.r.y,-i.Sun.r.z,-i.Sun.v.x,-i.Sun.v.y,-i.Sun.v.z,t);case ue.Mercury:case ue.Venus:case ue.Earth:case ue.Mars:case ue.Jupiter:case ue.Saturn:case ue.Uranus:case ue.Neptune:const n=dm(er[a],t.tt);return CD(n,t);case ue.Pluto:return fw(t);case ue.Moon:case ue.EMB:const s=dm(er.Earth,t.tt),r=a==ue.Moon?hw(t):xD(t);return new ra(r.x+s.r.x,r.y+s.r.y,r.z+s.r.z,r.vx+s.v.x,r.vy+s.v.y,r.vz+s.v.z,t);default:if(lg(a)){const o=oa(a,t);return new ra(o.x,o.y,o.z,0,0,0,t)}throw`HelioState: Unsupported body "${a}"`}}function LD(a,e,t,i,n){let s=(n+t)/2-i,r=(n-t)/2,o=i,l;if(s==0){if(r==0||(l=-o/r,l<-1||l>1))return null}else{let d=r*r-4*s*o;if(d<=0)return null;let u=Math.sqrt(d),p=(-r+u)/(2*s),f=(-r-u)/(2*s);if(-1<=p&&p<=1){if(-1<=f&&f<=1)return null;l=p}else if(-1<=f&&f<=1)l=f;else return null}let c=a+l*e,h=(2*s*l+r)/e;return{t:c,df_dt:h}}function ug(a,e,t,i){const n=Ai(i&&i.dt_tolerance_seconds||1),s=Math.abs(n/eD);let r=i&&i.init_f1||a(e),o=i&&i.init_f2||a(t),l=NaN,c=0,h=i&&i.iter_limit||20,d=!0;for(;;){if(++c>h)throw"Excessive iteration in Search()";let u=uD(e,t,.5),p=u.ut-e.ut;if(Math.abs(p)<s)return u;d?l=a(u):d=!0;let f=LD(u.ut,t.ut-u.ut,r,l,o);if(f){let g=Ht(f.t),m=a(g);if(f.df_dt!==0){if(Math.abs(m/f.df_dt)<s)return g;let v=1.2*Math.abs(m/f.df_dt);if(v<p/10){let x=g.AddDays(-v),y=g.AddDays(+v);if((x.ut-e.ut)*(x.ut-t.ut)<0&&(y.ut-e.ut)*(y.ut-t.ut)<0){let b=a(x),w=a(y);if(b<0&&w>=0){r=b,o=w,e=x,t=y,l=m,d=!1;continue}}}}}if(r<0&&l>=0){t=u,o=l;continue}if(l<0&&o>=0){e=u,r=l;continue}return null}}function kD(a){let e=a;for(;e<=-180;)e+=360;for(;e>180;)e-=360;return e}function OD(a){for(;a<0;)a+=360;for(;a>=360;)a-=360;return a}function ND(a,e,t){if(a===ue.Earth||e===ue.Earth)throw"The Earth does not have a longitude as seen from itself.";const i=Ht(t),n=Cu(a,i,!1),s=am(n),r=Cu(e,i,!1),o=am(r);return OD(s.elon-o.elon)}function FD(a,e,t,i){let n,s=0,r=0,o=0;switch(a){case ue.Mercury:n=-.6,s=4.98,r=-4.88,o=3.02;break;case ue.Venus:e<163.6?(n=-4.47,s=1.03,r=.57,o=.13):(n=.98,s=-1.02);break;case ue.Mars:n=-1.52,s=1.6;break;case ue.Jupiter:n=-9.4,s=.5;break;case ue.Uranus:n=-7.19,s=.25;break;case ue.Neptune:n=-6.87;break;case ue.Pluto:n=-1,s=4;break;default:throw`VisualMagnitude: unsupported body ${a}`}const l=e/100;let c=n+l*(s+l*(r+l*o));return c+=5*Math.log10(t*i),c}function UD(a,e,t,i,n){const s=am(i),r=ge*28.06,o=ge*(169.51+382e-7*n.tt),l=ge*s.elat,c=ge*s.elon,h=Math.asin(Math.sin(l)*Math.cos(r)-Math.cos(l)*Math.sin(r)*Math.sin(c-o)),d=Math.sin(Math.abs(h));let u=-9+.044*a;return u+=d*(-2.6+1.2*d),u+=5*Math.log10(e*t),{mag:u,ring_tilt:Ds*h}}function BD(a,e,t){let i=a*ge,n=i*i,s=n*n,r=-12.717+1.49*Math.abs(i)+.0431*s;const o=385000.6/js;let l=t/o;return r+=5*Math.log10(e*l),r}class zD{constructor(e,t,i,n,s,r,o,l){this.time=e,this.mag=t,this.phase_angle=i,this.helio_dist=n,this.geo_dist=s,this.gc=r,this.hc=o,this.ring_tilt=l,this.phase_fraction=(1+Math.cos(ge*i))/2}}function mw(a,e){if(a===ue.Earth)throw"The illumination of the Earth is not defined.";const t=Ht(e),i=Sl(er.Earth,t);let n,s,r,o;a===ue.Sun?(r=new Mt(-i.x,-i.y,-i.z,t),s=new Mt(0,0,0,t),n=0):(a===ue.Moon?(r=Tr(t),s=new Mt(i.x+r.x,i.y+r.y,i.z+r.z,t)):(s=oa(a,e),r=new Mt(s.x-i.x,s.y-i.y,s.z-i.z,t)),n=iw(r,s));let l=r.Length(),c=s.Length(),h;if(a===ue.Sun)o=QI+5*Math.log10(l);else if(a===ue.Moon)o=BD(n,c,l);else if(a===ue.Saturn){const d=UD(n,c,l,r,t);o=d.mag,h=d.ring_tilt}else o=FD(a,n,c,l);return new zD(t,o,n,c,l,r,s,h)}function gw(a){return ND(ue.Moon,ue.Sun,a)}function Cd(a,e,t){function i(u){let p=gw(u);return kD(p-a)}Ai(a),Ai(t);const n=1.5,s=Ht(e);let r=i(s),o,l,c;if(t<0){if(r<0&&(r+=360),o=-(J1*r)/360,c=o+n,c<t)return null;l=Math.max(t,o-n)}else{if(r>0&&(r-=360),o=-(J1*r)/360,l=o-n,l>t)return null;c=Math.min(t,o+n)}const h=s.AddDays(l),d=s.AddDays(c);return ug(i,h,d,{dt_tolerance_seconds:.1})}var ib;(function(a){a[a.Pericenter=0]="Pericenter",a[a.Apocenter=1]="Apocenter"})(ib||(ib={}));function pg(a){return new or([[a.rot[0][0],a.rot[1][0],a.rot[2][0]],[a.rot[0][1],a.rot[1][1],a.rot[2][1]],[a.rot[0][2],a.rot[1][2],a.rot[2][2]]])}function fg(a,e){return new or([[e.rot[0][0]*a.rot[0][0]+e.rot[1][0]*a.rot[0][1]+e.rot[2][0]*a.rot[0][2],e.rot[0][1]*a.rot[0][0]+e.rot[1][1]*a.rot[0][1]+e.rot[2][1]*a.rot[0][2],e.rot[0][2]*a.rot[0][0]+e.rot[1][2]*a.rot[0][1]+e.rot[2][2]*a.rot[0][2]],[e.rot[0][0]*a.rot[1][0]+e.rot[1][0]*a.rot[1][1]+e.rot[2][0]*a.rot[1][2],e.rot[0][1]*a.rot[1][0]+e.rot[1][1]*a.rot[1][1]+e.rot[2][1]*a.rot[1][2],e.rot[0][2]*a.rot[1][0]+e.rot[1][2]*a.rot[1][1]+e.rot[2][2]*a.rot[1][2]],[e.rot[0][0]*a.rot[2][0]+e.rot[1][0]*a.rot[2][1]+e.rot[2][0]*a.rot[2][2],e.rot[0][1]*a.rot[2][0]+e.rot[1][1]*a.rot[2][1]+e.rot[2][1]*a.rot[2][2],e.rot[0][2]*a.rot[2][0]+e.rot[1][2]*a.rot[2][1]+e.rot[2][2]*a.rot[2][2]]])}function mg(a,e){e=Ht(e);const t=a.lat*ge,i=a.lon*ge,n=a.dist*Math.cos(t);return new Mt(n*Math.cos(i),n*Math.sin(i),a.dist*Math.sin(t),e)}function op(a){const e=HD(a);return new sm(e.lon/15,e.lat,e.dist,a)}function HD(a){const e=a.x*a.x+a.y*a.y,t=Math.sqrt(e+a.z*a.z);let i,n;if(e===0){if(a.z===0)throw"Zero-length vector not allowed.";n=0,i=a.z<0?-90:90}else n=Ds*Math.atan2(a.y,a.x),n<0&&(n+=360),i=Ds*Math.atan2(a.z,Math.sqrt(e));return new np(i,n,t)}function vw(a,e){let t;if(Ai(e),e<-90||e>90)return 0;if(a==="normal"||a==="jplhor"){let i=e;i<-1&&(i=-1),t=1.02/Math.tan((i+10.3/(i+5.11))*ge)/60,a==="normal"&&e<-1&&(t*=(e+90)/89)}else if(!a)t=0;else throw`Invalid refraction option: ${a}`;return t}function _r(a,e){return new Mt(a.rot[0][0]*e.x+a.rot[1][0]*e.y+a.rot[2][0]*e.z,a.rot[0][1]*e.x+a.rot[1][1]*e.y+a.rot[2][1]*e.z,a.rot[0][2]*e.x+a.rot[1][2]*e.y+a.rot[2][2]*e.z,e.t)}function GD(){return new or([[1,0,0],[0,.9174821430670688,-.3977769691083922],[0,.3977769691083922,.9174821430670688]])}function VD(){return new or([[1,0,0],[0,.9174821430670688,.3977769691083922],[0,-.3977769691083922,.9174821430670688]])}function bw(a){a=Ht(a);const e=cg(a,Pi.From2000),t=hg(a,Pi.From2000);return fg(e,t)}function yw(a){a=Ht(a);const e=hg(a,Pi.Into2000),t=cg(a,Pi.Into2000);return fg(e,t)}function WD(a,e){a=Ht(a);const t=Math.sin(e.latitude*ge),i=Math.cos(e.latitude*ge),n=Math.sin(e.longitude*ge),s=Math.cos(e.longitude*ge),r=[i*s,i*n,t],o=[-t*s,-t*n,i],l=[n,-s,0],c=-15*lh(a),h=wl(c,r),d=wl(c,o),u=wl(c,l);return new or([[d[0],u[0],h[0]],[d[1],u[1],h[1]],[d[2],u[2],h[2]]])}function XD(a,e){const t=WD(a,e);return pg(t)}function $D(a,e){a=Ht(a);const t=XD(a,e),i=yw(a);return fg(t,i)}function YD(a,e){const t=$D(a,e);return pg(t)}function qD(a){const t=oh(Ht(a)).tobl*ge,i=Math.cos(t),n=Math.sin(t);return new or([[1,0,0],[0,+i,+n],[0,-n,+i]])}var po;(function(a){a.Penumbral="penumbral",a.Partial="partial",a.Annular="annular",a.Total="total"})(po||(po={}));class KD{constructor(e,t,i,n,s,r,o){this.time=e,this.u=t,this.r=i,this.k=n,this.p=s,this.target=r,this.dir=o}}function ZD(a,e,t,i){const n=(i.x*t.x+i.y*t.y+i.z*t.z)/(i.x*i.x+i.y*i.y+i.z*i.z),s=n*i.x-t.x,r=n*i.y-t.y,o=n*i.z-t.z,l=js*Math.hypot(s,r,o),c=+yc-(1+n)*(yc-a),h=-yc+(1+n)*(yc+a);return new KD(e,n,l,c,h,t,i)}function mm(a,e){const t=ow(a,e),i=Cu(ue.Sun,a,!0),n=Tr(a),s=new Mt(t[0]-n.x,t[1]-n.y,t[2]-n.z,a);return n.x-=i.x,n.y-=i.y,n.z-=i.z,ZD(sD,a,s,n)}function jD(a,e){const t=11574074074074073e-21,i=e.AddDays(-t),n=e.AddDays(+t),s=a(i);return(a(n).r-s.r)/t}function JD(a,e){const t=a.AddDays(-.2),i=a.AddDays(.2);function n(r){return mm(r,e)}const s=ug(r=>jD(n,r),t,i);if(!s)throw`PeakLocalMoonShadow: search failure for search_center_time = ${a}`;return mm(s,e)}function QD(a){const e=sw(a);return Ds*e.geo_eclip_lat}function e4(a,e,t){if(a<=0)throw"Radius of first disc must be positive.";if(e<=0)throw"Radius of second disc must be positive.";if(t<0)throw"Distance between discs is not allowed to be negative.";if(t>=a+e)return 0;if(t==0)return a<=e?1:e*e/(a*a);const i=(a*a-e*e+t*t)/(2*t),n=a*a-i*i;if(n<=0)return a<=e?1:e*e/(a*a);const s=Math.sqrt(n),r=a*a*Math.acos(i/a)-i*s,o=e*e*Math.acos((t-i)/e)-(t-i)*s;return(r+o)/(Math.PI*a*a)}function t4(a,e){const t=new Mt(a.x+e.x,a.y+e.y,a.z+e.z,a.t),i=Math.asin(tD/t.Length()),n=Math.asin(aD/e.Length()),s=iw(e,t),r=e4(i,n,s*ge);return Math.min(.9999,r)}function i4(a){return a>.014?po.Total:po.Annular}class n4{constructor(e,t){this.time=e,this.altitude=t}}class s4{constructor(e,t,i,n,s,r,o){this.kind=e,this.obscuration=t,this.partial_begin=i,this.total_begin=n,this.peak=s,this.total_end=r,this.partial_end=o}}function nb(a){return a.p-a.r}function sb(a){return Math.abs(a.k)-a.r}function r4(a,e){const t=Mw(e,a.time);let i=a.time.AddDays(-.2),n=a.time.AddDays(.2);const s=td(e,1,nb,i,a.time),r=td(e,-1,nb,a.time,n);let o,l,c;a.r<Math.abs(a.k)?(i=a.time.AddDays(-.01),n=a.time.AddDays(.01),o=td(e,1,sb,i,a.time),l=td(e,-1,sb,a.time,n),c=i4(a.k)):c=po.Partial;const h=c===po.Total?1:t4(a.dir,a.target);return new s4(c,h,s,o,t,l,r)}function td(a,e,t,i,n){function s(o){const l=mm(o,a);return e*t(l)}const r=ug(s,i,n);if(!r)throw"Local eclipse transition search failed.";return Mw(a,r)}function Mw(a,e){const t=a4(e,a);return new n4(e,t)}function a4(a,e){const t=Jc(ue.Sun,a,e,!0,!0);return dg(a,e,t.ra,t.dec,"normal").altitude}function o4(a,e){a=Ht(a),sp(e);const t=1.8;let i=a;for(;;){const n=Cd(0,i,40);if(!n)throw"Cannot find next new moon";const s=QD(n);if(Math.abs(s)<t){const r=JD(n,e);if(r.r<r.p){const o=r4(r,e);if(o.partial_begin.altitude>0||o.partial_end.altitude>0)return o}}i=n.AddDays(10)}}var rb;(function(a){a[a.Invalid=0]="Invalid",a[a.Ascending=1]="Ascending",a[a.Descending=-1]="Descending"})(rb||(rb={}));class ww{constructor(e,t,i,n){this.ra=e,this.dec=t,this.spin=i,this.north=n}}function l4(a){const e=Du([0,0,1],a,Pi.Into2000),t=jc(e,a,Pi.Into2000),i=new Mt(t[0],t[1],t[2],a),n=op(i),s=190.41375788700253+360.9856122880876*a.ut;return new ww(n.ra,n.dec,s,i)}function c4(a,e){const t=Ht(e),i=t.tt,n=i/36525;let s,r,o;switch(a){case ue.Sun:s=286.13,r=63.87,o=84.176+14.1844*i;break;case ue.Mercury:s=281.0103-.0328*n,r=61.4155-.0049*n,o=329.5988+6.1385108*i+.01067257*Math.sin(ge*(174.7910857+4.092335*i))-.00112309*Math.sin(ge*(349.5821714+8.18467*i))-1104e-7*Math.sin(ge*(164.3732571+12.277005*i))-2539e-8*Math.sin(ge*(339.1643429+16.36934*i))-571e-8*Math.sin(ge*(153.9554286+20.461675*i));break;case ue.Venus:s=272.76,r=67.16,o=160.2-1.4813688*i;break;case ue.Earth:return l4(t);case ue.Moon:const u=ge*(125.045-.0529921*i),p=ge*(250.089-.1059842*i),f=ge*(260.008+13.0120009*i),g=ge*(176.625+13.3407154*i),m=ge*(357.529+.9856003*i),v=ge*(311.589+26.4057084*i),x=ge*(134.963+13.064993*i),y=ge*(276.617+.3287146*i),b=ge*(34.226+1.7484877*i),w=ge*(15.134-.1589763*i),S=ge*(119.743+.0036096*i),_=ge*(239.961+.1643573*i),M=ge*(25.053+12.9590088*i);s=269.9949+.0031*n-3.8787*Math.sin(u)-.1204*Math.sin(p)+.07*Math.sin(f)-.0172*Math.sin(g)+.0072*Math.sin(v)-.0052*Math.sin(w)+.0043*Math.sin(M),r=66.5392+.013*n+1.5419*Math.cos(u)+.0239*Math.cos(p)-.0278*Math.cos(f)+.0068*Math.cos(g)-.0029*Math.cos(v)+9e-4*Math.cos(x)+8e-4*Math.cos(w)-9e-4*Math.cos(M),o=38.3213+(13.17635815-14e-13*i)*i+3.561*Math.sin(u)+.1208*Math.sin(p)-.0642*Math.sin(f)+.0158*Math.sin(g)+.0252*Math.sin(m)-.0066*Math.sin(v)-.0047*Math.sin(x)-.0046*Math.sin(y)+.0028*Math.sin(b)+.0052*Math.sin(w)+.004*Math.sin(S)+.0019*Math.sin(_)-.0044*Math.sin(M);break;case ue.Mars:s=317.269202-.10927547*n+68e-6*Math.sin(ge*(198.991226+19139.4819985*n))+238e-6*Math.sin(ge*(226.292679+38280.8511281*n))+52e-6*Math.sin(ge*(249.663391+57420.7251593*n))+9e-6*Math.sin(ge*(266.18351+76560.636795*n))+.419057*Math.sin(ge*(79.398797+.5042615*n)),r=54.432516-.05827105*n+51e-6*Math.cos(ge*(122.433576+19139.9407476*n))+141e-6*Math.cos(ge*(43.058401+38280.8753272*n))+31e-6*Math.cos(ge*(57.663379+57420.7517205*n))+5e-6*Math.cos(ge*(79.476401+76560.6495004*n))+1.591274*Math.cos(ge*(166.325722+.5042615*n)),o=176.049863+350.891982443297*i+145e-6*Math.sin(ge*(129.071773+19140.0328244*n))+157e-6*Math.sin(ge*(36.352167+38281.0473591*n))+4e-5*Math.sin(ge*(56.668646+57420.929536*n))+1e-6*Math.sin(ge*(67.364003+76560.2552215*n))+1e-6*Math.sin(ge*(104.79268+95700.4387578*n))+.584542*Math.sin(ge*(95.391654+.5042615*n));break;case ue.Jupiter:const T=ge*(99.360714+4850.4046*n),A=ge*(175.895369+1191.9605*n),R=ge*(300.323162+262.5475*n),C=ge*(114.012305+6070.2476*n),k=ge*(49.511251+64.3*n);s=268.056595-.006499*n+117e-6*Math.sin(T)+938e-6*Math.sin(A)+.001432*Math.sin(R)+3e-5*Math.sin(C)+.00215*Math.sin(k),r=64.495303+.002413*n+5e-5*Math.cos(T)+404e-6*Math.cos(A)+617e-6*Math.cos(R)-13e-6*Math.cos(C)+926e-6*Math.cos(k),o=284.95+870.536*i;break;case ue.Saturn:s=40.589-.036*n,r=83.537-.004*n,o=38.9+810.7939024*i;break;case ue.Uranus:s=257.311,r=-15.175,o=203.81-501.1600928*i;break;case ue.Neptune:const z=ge*(357.85+52.316*n);s=299.36+.7*Math.sin(z),r=43.46-.51*Math.cos(z),o=249.978+541.1397757*i-.48*Math.sin(z);break;case ue.Pluto:s=132.993,r=-6.163,o=302.695+56.3625225*i;break;default:throw`Invalid body: ${a}`}const l=r*ge,c=s*ge,h=Math.cos(l),d=new Mt(h*Math.cos(c),h*Math.sin(c),Math.sin(l),t);return new ww(s/15,r,o,d)}const h4=["Venus","Mars","Jupiter","Saturn"];function xw(a){return new ha(a.lat,a.lng,a.elevationM)}function gg(a,e,t,i,n=!0){const s=dg(t,xw(i),a,e,n?"normal":void 0);return{altitudeDeg:s.altitude,azimuthDeg:s.azimuth}}class Ss{up;north;west;constructor(e,t){const i=Ht(e),n=Math.sin(t.lat*br),s=Math.cos(t.lat*br),r=Math.sin(t.lng*br),o=Math.cos(t.lng*br),l=-15*vD(i),c=yw(i);this.up=Ss.rotate(c,Ss.spin(l,[s*o,s*r,n]),i),this.north=Ss.rotate(c,Ss.spin(l,[-n*o,-n*r,s]),i),this.west=Ss.rotate(c,Ss.spin(l,[r,-o,0]),i)}static ofJ2000(e,t,i,n,s=!0){const r=Ht(i),o=mg(new np(t,e*15,1),r),l=op(_r(bw(r),o));return gg(l.ra,l.dec,i,n,s)}position(e,t){const i=Math.sin(t*br),n=Math.cos(t*br),s=Math.sin(e*ob),r=Math.cos(e*ob),o=n*r,l=n*s,c=i,h=o*this.up[0]+l*this.up[1]+c*this.up[2],d=o*this.north[0]+l*this.north[1]+c*this.north[2],u=o*this.west[0]+l*this.west[1]+c*this.west[2],p=Math.hypot(d,u);let f=0;p>0&&(f=-ab*Math.atan2(u,d),f<0&&(f+=360));let g=ab*Math.atan2(p,h);return g-=vw("normal",90-g),{altitudeDeg:90-g,azimuthDeg:f}}static spin(e,[t,i,n]){const s=Math.cos(e*br),r=Math.sin(e*br);return[s*t+r*i,s*i-r*t,n]}static rotate(e,[t,i,n],s){const r=_r(e,new Mt(t,i,n,s));return[r.x,r.y,r.z]}}const br=Math.PI/180,ab=180/Math.PI,ob=15*br;function Ni(a,e,t){const i=xw(t),n=Jc(ue[a],e,i,!0,!0),s=dg(e,i,n.ra,n.dec,"normal");return{altitudeDeg:s.altitude,azimuthDeg:s.azimuth}}function rf(a,e){return mw(ue[a],e).mag}function Ca(a){const e=gw(a),t=mw(ue.Moon,a);return{phaseFraction:e/360,illuminatedFraction:t.phase_fraction}}const d4=2e3,u4=3,p4=20;function Yn(a,e,t){if(a.year===void 0&&a.month===void 0&&a.day===void 0&&a.hour===void 0)return;const i=a.year!==void 0,n=a.year??d4,s=a.month??(i?1:u4),r=a.day??(i?1:p4),o=t??Math.round(e/15);return new Date(Date.UTC(n,s-1,r,(a.hour??12)-o,a.minute??0,a.second??0))}const lb=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];class so{static POINT_DEG=360/16;static point(e,t=lb){const i=(e%360+360)%360,n=Math.round(i/so.POINT_DEG)%16;return t[n]}static POINTS=lb;static towards(e,t){return t?t.towards(so.point(e,t.compassPoints)):`to the ${so.point(e)}`}}class Vs{static ANCHOR="vec4 diffuseColor = vec4( diffuse, opacity );";static CORE=.18;static RIM=.5;static FALLOFF={core:Vs.CORE,rim:Vs.RIM};static apply(e){e.transparent=!0,e.depthWrite=!1,e.onBeforeCompile=t=>{t.fragmentShader=Vs.patch(t.fragmentShader)}}static patch(e){return e.replace(Vs.ANCHOR,`float distanceFromCentre = length( gl_PointCoord - vec2( 0.5 ) );
|
|
7910
7910
|
// Outside the inscribed circle there is no star at all — this is what kills the corners.
|
|
7911
7911
|
if ( distanceFromCentre > ${Vs.RIM.toFixed(2)} ) discard;
|
|
7912
7912
|
float glare = 1.0 - smoothstep( ${Vs.CORE.toFixed(2)}, ${Vs.RIM.toFixed(2)}, distanceFromCentre );
|
|
@@ -8952,7 +8952,7 @@ ${Ce.OUTPUT_PROJECTION_GLSL}`)}}class mn{constructor(e,t){this.width=e,this.heig
|
|
|
8952
8952
|
gl_FragColor = vec4(iceHaloLight(dir, ice), 1.0);
|
|
8953
8953
|
}
|
|
8954
8954
|
`,transparent:!0,blending:Bi,depthWrite:!1,side:ni,fog:!1}),this.object=new Ae(new yi(Xi.RADIUS,64,32),this.material),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1;const i=this.material.uniforms;this.deckUniforms={uSource:i.uSource,uUp:i.uUp,uStrength:i.uStrength,uTint:i.uTint,uMap:i.uMap,uGain:i.uGain,uHaloShown:{value:0}}}deckUniforms;shown=!1;hostedByDeck=!1;set hosted(e){this.hostedByDeck=e,this.show(this.shown)}show(e){this.shown=e,this.object.visible=e&&!this.hostedByDeck,this.deckUniforms.uHaloShown.value=e?1:0}get awaitingFirstDisplay(){return this.tracing&&!this.everDisplayed}setUrgent(e){this.urgent=e}set onReady(e){this.onRepaint=e}update(e,t,i,n,s,r){const o=this.material.uniforms;if(i<=0){o.uStrength.value=0,this.show(!1),this.stopWork();return}o.uSource.value.set(e.x,e.y,e.z).normalize(),o.uStrength.value=i,o.uTint.value.set(n[0],n[1],n[2]),o.uIceCover.value=s.cover,o.uIceHeight.value=s.layerHeight,this.show(this.everDisplayed),this.requestMap(t,r)}requestMap(e,t){if(!(!(Math.abs(e-this.mappedAltitudeDeg)<Xi.ALTITUDE_STEP_DEG)||!(Math.abs(t-this.mappedAlignment)<Xi.ALIGNMENT_STEP))){this.next=void 0;return}if(this.tracing){if(this.tracingFor(e,t)){this.next=void 0;return}if(!(!(Math.abs(e-this.pendingAltitudeDeg)<Xi.LEAP_ALTITUDE_DEG)||!(Math.abs(t-this.pendingAlignment)<Xi.LEAP_ALIGNMENT))){this.next={sourceAltitudeDeg:e,alignment:t};return}}this.next=void 0,this.pendingAltitudeDeg=e,this.pendingAlignment=t,this.stopWork(),this.tracing=!0,this.startTracing(e,t)}startTracing(e,t){const i=++this.ticket,n=()=>{i!==this.ticket||!this.tracing||(this.sky.begin(e,t),this.scheduleWork())};ea.with(s=>{i!==this.ticket||!this.tracing||(this.job=s.trace(e,t,Xi.RAYS,r=>{this.job=void 0,this.texels.set(r),this.display(),this.finishTracing()},n))},n)}ticket=0;job;pendingAltitudeDeg=Number.NaN;pendingAlignment=Number.NaN;next;tracingFor(e,t){return this.tracing&&Math.abs(e-this.pendingAltitudeDeg)<Xi.ALTITUDE_STEP_DEG&&Math.abs(t-this.pendingAlignment)<Xi.ALIGNMENT_STEP}scheduleWork(){if(this.workHandle!==void 0)return;const e=()=>{if(this.workHandle=void 0,!this.tracing)return;const t=performance.now(),i=this.urgent?Xi.URGENT_BUDGET_MS:Xi.BUDGET_MS;do this.sky.trace(Xi.RAYS_PER_BATCH);while(this.sky.tracedRays<Xi.RAYS&&performance.now()-t<i);if(this.sky.tracedRays>=Xi.RAYS){this.publish(),this.finishTracing();return}this.workHandle=requestAnimationFrame(e)};this.workHandle=requestAnimationFrame(e)}finishTracing(){this.tracing=!1,this.mappedAltitudeDeg=this.pendingAltitudeDeg,this.mappedAlignment=this.pendingAlignment;const e=this.next;e&&this.requestMap(e.sourceAltitudeDeg,e.alignment)}stopWork(){this.ticket++,this.job?.cancel(),this.job=void 0,this.workHandle!==void 0&&cancelAnimationFrame(this.workHandle),this.workHandle=void 0,this.tracing=!1,this.next=void 0}publish(){F4.fromRadiance(this.sky.harvest().data,this.texels),this.display()}display(){this.texture.needsUpdate=!0,this.everDisplayed=!0,this.show(this.material.uniforms.uStrength.value>0),this.onRepaint?.()}dispose(){this.stopWork(),this.texture.dispose(),this.object.geometry.dispose(),this.material.dispose()}}class Wi{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=Wi.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(Wi.ACROSS-1)*6;static RADIUS=840;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;object;positions;colors;meteors=[];radiantAltitudeDeg=0;radiantAzimuthDeg=0;constructor(){const e=Wi.MAX_CONCURRENT*Wi.SEGMENTS*Wi.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new ct;t.setAttribute("position",new tt(this.positions,3)),t.setAttribute("color",new tt(this.colors,3)),t.setDrawRange(0,0),this.object=new Ae(t,cs.material()),this.object.frustumCulled=!1,cs.track(this.object)}get schedule(){return this.meteors}setShower(e,t,i){this.meteors=e,this.radiantAltitudeDeg=t,this.radiantAzimuthDeg=i}update(e){const t=this.object.geometry;if(this.meteors.length===0){t.setDrawRange(0,0);return}const i=ro.aliveAt(this.meteors,e).slice(0,Wi.MAX_CONCURRENT);let n=0;for(const{meteor:s,progress:r}of i){const o=this.radiantOf(s);if(!o)continue;const l=jt(o.altitudeDeg,o.azimuthDeg,1),[c,h]=this.basisAround(l),d=s.fromRadiantDeg+r*s.lengthDeg,u=Math.max(s.fromRadiantDeg,d-s.lengthDeg*.6),p=Math.min(1,(1-r)*2.5),f=this.turn(c,h,s.bearingDeg),g=(.15+.85*s.brightness)*p,m=y=>g*y**1.6,v=y=>this.onSphere(l,f,u+(d-u)*y),x=y=>Wi.RADIUS*((Wi.MIN_HALF_WIDTH_DEG+Wi.BRIGHT_HALF_WIDTH_DEG*s.brightness*y)*Math.PI/180);for(let y=1;y<Wi.POINTS;y++){const b=(y-1)/Wi.SEGMENTS,w=y/Wi.SEGMENTS;n=this.pushRibbon(n,v(b),v(w),x(b),x(w),m(b),m(w))}}t.setDrawRange(0,n),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}midpointOf(e){const t=this.radiantOf(e);if(!t)return;const i=jt(t.altitudeDeg,t.azimuthDeg,1),[n,s]=this.basisAround(i),r=this.turn(n,s,e.bearingDeg),o=this.onSphere(i,r,e.fromRadiantDeg+e.lengthDeg/2),l=Math.hypot(o.x,o.y,o.z)||1;return{altitudeDeg:Math.asin(o.y/l)*180/Math.PI,azimuthDeg:(Math.atan2(o.x,-o.z)*180/Math.PI+360)%360}}radiantOf(e){return e.radiant?e.radiant:this.radiantAltitudeDeg>0?{altitudeDeg:this.radiantAltitudeDeg,azimuthDeg:this.radiantAzimuthDeg}:void 0}pushRibbon(e,t,i,n,s,r,o){const l=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let c=0;c<Wi.ACROSS-1;c++){const h=c-1,d=c,u=this.across(t,l,n,h),p=this.across(i,l,s,h),f=this.across(t,l,n,d),g=this.across(i,l,s,d),m=(v,x)=>v===0?x:0;e=this.push(e,u,m(h,r)),e=this.push(e,p,m(h,o)),e=this.push(e,f,m(d,r)),e=this.push(e,p,m(h,o)),e=this.push(e,g,m(d,o)),e=this.push(e,f,m(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=Ie.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.9,this.colors[n+1]=s*.95,this.colors[n+2]=s,e+1}turn(e,t,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:e.x*s+t.x*r,y:e.y*s+t.y*r,z:e.z*s+t.z*r}}onSphere(e,t,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:(e.x*s+t.x*r)*Wi.RADIUS,y:(e.y*s+t.y*r)*Wi.RADIUS,z:(e.z*s+t.z*r)*Wi.RADIUS}}basisAround(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=this.normalise(this.cross(e,t));return[i,this.normalise(this.cross(e,i))]}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 Zt{constructor(e,t={}){this.size=e,this.span=Math.min(e.lengthM,Math.max(0,t.spanM??e.lengthM)),this.bank=(e.lengthM-this.span)/2,this.deck=Math.min(e.heightM,t.deckThicknessM??Zt.DEFAULT_DECK_THICKNESS_M),this.railHeight=t.railing?.heightM??Zt.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,t.railing?.postSpacingM??Zt.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(t.railing?.rails??Zt.DEFAULT_RAILS))}static DEFAULT_DECK_THICKNESS_M=1.2;static DEFAULT_RAILING_HEIGHT_M=1.05;static DEFAULT_POST_SPACING_M=1.5;static DEFAULT_RAILS=2;static BANK_SLOPE=1.5;static ABUTMENT_THICKNESS_M=1;static POST_SIDE_M=.08;static RAIL_HEIGHT_M=.08;static RAIL_DEPTH_M=.06;static BANK_STATIONS=12;static NATURAL_SIZE=Object.freeze({widthM:9,lengthM:40,heightM:6.5});span;bank;deck;railHeight;postSpacing;rails;roadAt(e){const t=Math.abs(e)-this.span/2;return t<=0?this.size.heightM:this.bank<=0?0:Math.max(0,this.size.heightM*(1-t/this.bank))}build(){const{widthM:e,heightM:t}=this.size,i=this.span/2,n=[];if(this.span>0){n.push(Zt.box(e,this.deck,this.span,0,t-this.deck/2,0));for(const l of[-1,1]){const c=t-this.deck;c>0&&this.bank>0&&n.push(Zt.box(e+1,c,Zt.ABUTMENT_THICKNESS_M,0,c/2,l*(i-Zt.ABUTMENT_THICKNESS_M/2)))}}const s=[];this.span>0&&s.push(Zt.box(e,.04,this.span,0,t+.02,0));const r=[];for(const l of[-1,1])this.bank<=0||(r.push(this.embankment(l)),s.push(this.bankRoad(l)));const o=[];for(const l of[-1,1])o.push(...this.railing(l*(e/2-Zt.POST_SIDE_M)));return{concrete:Zt.merge(n),road:Zt.merge(s),earth:Zt.merge(r),railing:Zt.merge(o)}}embankment(e){const t=this.size.widthM/2,i=this.stations(e),n=[],s=(c,h,d,u)=>{n.push(c.x,c.y,c.z,h.x,h.y,h.z,d.x,d.y,d.z,c.x,c.y,c.z,d.x,d.y,d.z,u.x,u.y,u.z)},r=c=>{const h=this.roadAt(c),d=t+Zt.BANK_SLOPE*h;return{leftFoot:new D(-d,0,c),leftTop:new D(-t,h,c),rightTop:new D(t,h,c),rightFoot:new D(d,0,c)}};for(let c=1;c<i.length;c++){const h=r(i[c-1]),d=r(i[c]),u=e>0,p=(f,g,m,v)=>u?s(f,g,m,v):s(v,m,g,f);p(h.leftFoot,h.leftTop,d.leftTop,d.leftFoot),p(h.leftTop,h.rightTop,d.rightTop,d.leftTop),p(h.rightTop,h.rightFoot,d.rightFoot,d.rightTop)}const o=r(i[0]);e>0?s(o.leftFoot,o.rightFoot,o.rightTop,o.leftTop):s(o.leftTop,o.rightTop,o.rightFoot,o.leftFoot);const l=new ct;return l.setAttribute("position",new wt(n,3)),l.computeVertexNormals(),l}bankRoad(e){const t=this.size.widthM/2,i=this.stations(e),n=[];for(let r=1;r<i.length;r++){const o=i[r-1],l=i[r],c=this.roadAt(o)+.02,h=this.roadAt(l)+.02,d=e>0?[[-t,c,o],[t,c,o],[t,h,l],[-t,h,l]]:[[-t,h,l],[t,h,l],[t,c,o],[-t,c,o]];for(const u of[0,2,1,0,3,2])n.push(...d[u])}const s=new ct;return s.setAttribute("position",new wt(n,3)),s.computeVertexNormals(),s}stations(e){const t=[];for(let i=0;i<=Zt.BANK_STATIONS;i++)t.push(e*(this.span/2+this.bank*i/Zt.BANK_STATIONS));return t}railing(e){const t=this.size.lengthM/2,i=Math.max(1,Math.round(this.size.lengthM/this.postSpacing)),n=[];for(let o=0;o<=i;o++)n.push(-t+this.size.lengthM*o/i);const s=[],r=Zt.POST_SIDE_M;for(const o of n)s.push(Zt.box(r,this.railHeight,r,e,this.roadAt(o)+this.railHeight/2,o));for(let o=1;o<=this.rails;o++){const l=this.railHeight*o/this.rails-Zt.RAIL_HEIGHT_M/2;for(let c=1;c<n.length;c++){const h=new D(e,this.roadAt(n[c-1])+l,n[c-1]),d=new D(e,this.roadAt(n[c])+l,n[c]);s.push(Zt.beam(h,d))}}return s}static box(e,t,i,n,s,r){return new Zi(e,t,i).translate(n,s,r)}static beam(e,t){const i=new D().subVectors(t,e),n=new Zi(Zt.RAIL_DEPTH_M,Zt.RAIL_HEIGHT_M,i.length()),s=new dn().setFromUnitVectors(new D(0,0,1),i.clone().normalize()),r=new D().addVectors(e,t).multiplyScalar(.5);return n.applyMatrix4(new it().compose(r,s,new D(1,1,1)))}static merge(e){const t=e.map(l=>l.getIndex()?l.toNonIndexed():l),i=t.reduce((l,c)=>l+c.getAttribute("position").count,0),n=new Float32Array(i*3),s=new Float32Array(i*3);let r=0;for(const l of t){const c=l.getAttribute("position"),h=l.getAttribute("normal");n.set(c.array,r*3),h&&s.set(h.array,r*3),r+=c.count}const o=new ct;o.setAttribute("position",new wt(n,3)),o.setAttribute("normal",new wt(s,3));for(const l of e)l.dispose();for(const l of t)l.dispose();return o}}class ja{constructor(e,t={}){this.size=e,this.structure=t}static DEFAULT_DIAMETER_M=.008;static POLE_RADIUS_M=.13;static POLE_ABOVE_M=.5;static NATURAL_SIZE=Object.freeze({widthM:1,lengthM:30,heightM:5});get strands(){const e=this.structure.strands;return!e||e.length===0?[{heightM:this.size.heightM,acrossM:0}]:e.map(t=>({heightM:t.heightM,acrossM:t.acrossM??0}))}get poleStations(){const e=this.size.lengthM/2;switch(this.structure.poles??"both"){case"start":return[e];case"end":return[-e];case"none":return[];default:return[-e,e]}}get poleHeightM(){return this.structure.poleHeightM??Math.max(...this.strands.map(e=>e.heightM))+ja.POLE_ABOVE_M}build(){const e=this.structure.diameterM??ja.DEFAULT_DIAMETER_M,t=this.strands.map(n=>{const s=new us(e/2,e/2,this.size.lengthM,6);return s.rotateX(Math.PI/2),s.translate(n.acrossM,n.heightM,0),s}),i=this.poleStations.map(n=>{const s=new us(ja.POLE_RADIUS_M*.8,ja.POLE_RADIUS_M,this.poleHeightM,8);return s.translate(0,this.poleHeightM/2,n),s});return{strands:t,poles:i}}}const af=Math.PI/180;function Pt(a,e,t,i,n=!1){const s=n?new On({color:new se(...t)}):new Nl({color:new se(...t)}),r=new Ae(e,s);return r.position.y=i,r.userData={emissive:n},r.castShadow=!n,r.receiveShadow=!n,a.add(r),r}const of=.25,U4=.002,B4=100,z4=1500,H4=.25,G4=1e3,V4=.15;function W4(a){const e=/^#([0-9a-f]{6})$/i.exec(a);if(!e)return[1,1,1];const t=parseInt(e[1],16);return[(t>>16&255)/255,(t>>8&255)/255,(t&255)/255]}const X4=[.32,.32,.3],Ew=[1,.85,.5],$4=[.25,.25,.25],_w=[1,.97,.85],Y4=[.55,.68,.72],q4=.12,Xs=.03,$s=.05,Aw={front:0,behind:Math.PI,left:Math.PI/2,right:-Math.PI/2,"front-left":Math.PI/2,"behind-left":Math.PI/2,"front-right":-Math.PI/2,"behind-right":-Math.PI/2};function yn(a,e){return a?.[e]}function Ys(a,e,t,i,n,s,r,o){if(o===void 0)return;const l=new On({color:new se(...Y4).multiplyScalar(q4),transparent:!0,opacity:o/100,depthWrite:!1}),c=new Ae(new Zi(e,t,i),l);c.position.set(n,s,r),c.renderOrder=2,a.add(c)}const ns=.05,lf=[.6,.58,.53],db=[.5,.5,.48];function rl(a,e,t,i,n,s,r,o){const l=new Nl({color:new se(...o),side:ni}),c=new Ae(new Zi(e,t,i),l);c.position.set(n,s,r),a.add(c)}function K4(a,e,t,i,n,s,r,o,l){const c=(i-s)/2,h=(f,g,m,v)=>{f<=0||(e?rl(a,f,g,ns,m,o+v,r,l):rl(a,ns,g,f,r,o+v,m,l))};h(t,c,0,i/2-c/2),h(t,c,0,-(i/2-c/2));const d=[...n].sort((f,g)=>f.center-g.center);let u=-t/2;for(const f of d){const m=f.center-f.main/2-u;h(m,s,u+m/2,0),u=f.center+f.main/2}const p=t/2-u;h(p,s,u+p/2,0)}function Tw(a,e,t,i,n,s,r,o,l,c){const h=(i+n)/2,d=n-i,u=(p,f,g,m)=>{p.length===0?f?rl(a,g,d,ns,0,h,m,lf):rl(a,ns,d,g,m,h,0,lf):K4(a,f,g,d,p,s,m,h,lf)};u(r,!0,e*2,-t+ns),u(o,!0,e*2,t-ns),u(l,!1,t*2,-e+ns),u(c,!1,t*2,e-ns),rl(a,e*2,ns,t*2,0,i+ns,0,db),rl(a,e*2,ns,t*2,0,n-ns,0,db)}function gm(a,e,t,i){switch(a){case"front":return{x:0,z:-(t-i)};case"behind":return{x:0,z:t-i};case"left":return{x:-(e-i),z:0};case"right":return{x:e-i,z:0};case"front-left":return{x:-(e-i),z:-qs};case"front-right":return{x:e-i,z:-qs};case"behind-left":return{x:-(e-i),z:qs};case"behind-right":return{x:e-i,z:qs}}}function Iw(a,e,t,i,n,s,r,o){const l=ym();l.scale.setScalar(n),l.rotation.y=Aw[t];const{x:c,z:h}=gm(e,s,r,o);l.position.set(c,i,h),a.add(l)}const vm=6,bm=6,jr=3,ac=1.4,oc=jr*.5,Dw=1.2,Rw=.35,Z4=.75,j4=1.6;function ub(a,e,t,i,n){const s=new Ct,r=Math.max(1,a+1),o=r*jr;Pt(s,new Zi(vm,o,bm),[.55,.54,.5],o/2);const l=vm/2,c=bm/2;for(let h=0;h<r;h++){const d=h*jr+jr/2;Ys(s,ac,oc,$s,0,d,-c-Xs,yn(e,"front")),Ys(s,ac,oc,$s,0,d,c+Xs,yn(e,"behind")),Ys(s,$s,oc,ac,-l-Xs,d,0,yn(e,"left")),Ys(s,$s,oc,ac,l+Xs,d,0,yn(e,"right"))}if(t){const h=Math.min(Math.max(i??0,0),r-1);Iw(s,t,n??t,h*jr,.72,l,c,Dw);const d=u=>yn(e,u)!==void 0?[{main:ac,center:0}]:[];Tw(s,l,c,h*jr,(h+1)*jr,oc,d("front"),d("behind"),d("left"),d("right"))}return s}function pb(){const a=new Ct,e=[[0,0,.55,.5],[.4,.1,.35,.4],[-.35,-.2,.4,.38],[.1,-.4,.35,.36],[-.15,.4,.3,.34]];for(const[t,i,n,s]of e){const r=new yi(n,10,7);r.scale(1,.85,1),r.translate(t,0,i),Pt(a,r,[.26,.28,.17],s)}return a}function J4(a){const e=new Ct,t=new Zt($t.sizeOf(a),a.bridge).build();Pt(e,t.concrete,[.6,.6,.58],0);const i=Pt(e,t.road,[.2,.2,.21],0),n=Pt(e,t.earth,[.3,.36,.22],0);for(const s of[i,n])s.material.side=kn;return Pt(e,t.railing,[.5,.52,.55],0),e}function Q4(a){const e=new Ct,t=new ja($t.sizeOf(a),a.wire).build();for(const i of t.strands)Pt(e,i,[.1,.1,.11],0);for(const i of t.poles)Pt(e,i,[.3,.24,.18],0);return e}function fb(){const a=new Ct;return Pt(a,new us(.15,.22,2,8),[.32,.22,.14],1),Pt(a,new Bl(1.4,3,8),[.16,.32,.14],3.5),a}const mb=.275,eR=.35,tR=.9,iR=34,nR=8,sR=1.4;function gb(){const a=new Ct,e=new yi(mb,7,3,0,Math.PI*2,0,Math.PI/2);e.scale(1,eR/mb,1);const t=$t.repeatOnGrid(e,iR,tR,nR,sR),i=Pt(a,t,[.26,.28,.22],0);return i.castShadow=!0,i.userData.cropBasePositions=t.getAttribute("position").array.slice(),i.userData.cropVerticesPerClump=e.getAttribute("position").count,e.dispose(),a}function vb(){const a=new Ct,e=new yi(1,7,3,0,Math.PI*2,0,Math.PI/2);return Pt(a,e,[.38,.36,.32],0),a}const rR=[.24,.22,.18],aR=[.14,.17,.08];function oR(){const a=new Ct,e=Pt(a,new Zi(1,1,1),rR,.5),t=Pt(a,new Zi(1,.03,1),aR,1.015);for(const i of[e,t])i.material.side=kn;return a}function bb(a){const e=new Ct;return Pt(e,new us(.05,.08,5,8),[.28,.28,.3],2.5),Pt(e,new yi(.25,12,8),a?Ew:X4,5.1,!0),e}const lR=[.08,.08,.08],Xr=.8,Zo=1,Bs=1.7,cf=.6,ba=.46,sd=1.5,Xo=.8,qs=.5,cR=Bs;function yb(a,e,t,i){const n=new Ct;Pt(n,new Zi(1.8,1.4,4.2),[.45,.14,.14],.7),Pt(n,new Zi(Xr*2,cf,Zo*2),[.4,.12,.12],Bs);for(const r of[-1.4,1.4])for(const o of[-.95,.95]){const l=Pt(n,new us(.4,.4,.3,12),lR,.4);l.rotation.z=Math.PI/2,l.position.x=o,l.position.z=r}const s=a?_w:$4;for(const r of[-.7,.7])Pt(n,new yi(.15,8,6),s,.7,!0).position.set(r,.7,-2.1);if(Ys(n,sd,ba,$s,0,Bs,-Zo-Xs,yn(e,"front")),Ys(n,sd,ba,$s,0,Bs,Zo+Xs,yn(e,"behind")),Ys(n,$s,ba,Xo,-Xr-Xs,Bs,-qs,yn(e,"front-left")),Ys(n,$s,ba,Xo,-Xr-Xs,Bs,qs,yn(e,"behind-left")),Ys(n,$s,ba,Xo,Xr+Xs,Bs,-qs,yn(e,"front-right")),Ys(n,$s,ba,Xo,Xr+Xs,Bs,qs,yn(e,"behind-right")),t){Iw(n,t,i??t,Z4,.5,Xr,Zo,Rw);const r=(c,h)=>{const d=[];return yn(e,c)!==void 0&&d.push({main:Xo,center:-qs}),yn(e,h)!==void 0&&d.push({main:Xo,center:qs}),d},o=yn(e,"front")!==void 0?[{main:sd,center:0}]:[],l=yn(e,"behind")!==void 0?[{main:sd,center:0}]:[];Tw(n,Xr,Zo,Bs-cf/2,Bs+cf/2,ba,o,l,r("front-left","behind-left"),r("front-right","behind-right"))}return n}const Mb=new Map;function wb(a,e){if(!a)return;const t=[[a.lengthM,e.lengthM],[a.heightM,e.heightM],[a.widthM,e.widthM]];for(const[i,n]of t)if(i!==void 0&&n>1e-6)return i/n}function hf(a,e){return e>1e-6?a/e:1}const Cw=[.95,.9,.82],xb=[.72,.74,.78];function Sb(){const a=new Ct;Pt(a,new us(.25,.3,1.5,10),xb,.75),Pt(a,new yi(.26,10,8),xb,1.74);const e=Pt(a,new Bl(.07,.16,8),Cw,1.74);return e.rotation.x=-Math.PI/2,e.position.z=-.22,a}function ym(){const a=new Ct;Pt(a,new us(.25,.3,1.5,10),[.3,.3,.35],.75),Pt(a,new yi(.22,10,8),[.62,.52,.46],1.72);const e=Pt(a,new Bl(.07,.16,8),Cw,1.72);return e.rotation.x=-Math.PI/2,e.position.z=-.2,a}const hR=17,Eb=18.5,df=[.16,.16,.18];function _b(){const a=new Ct,e=Pt(a,new us(1.8,1.8,Eb*2,10),df,0);e.rotation.x=Math.PI/2,Pt(a,new Zi(hR*2,.5,4.5),df,0);const t=Pt(a,new Zi(.4,5.5,4),df,3);return t.position.z=-Eb+2,a}class $t{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound","terrace"]);static groundUnderFootprint(e,t,i,n,s,r=0){const o=$t.sizeOf(e);if(r>o.heightM)return s(t,i);const l=(n??0)*Math.PI/180,c=Math.min(21,Math.max(2,Math.ceil(o.lengthM/.75)+1)),h=Math.min(21,Math.max(2,Math.ceil(o.widthM/.75)+1)),d=$t.GROWS_FROM_GROUND.has(e.kind);let u=d?1/0:-1/0;for(let p=0;p<c;p++){const f=(p/(c-1)-.5)*o.lengthM;for(let g=0;g<h;g++){const m=(g/(h-1)-.5)*o.widthM,v=t+Math.sin(l)*f+Math.cos(l)*m,x=i-Math.cos(l)*f+Math.sin(l)*m;u=d?Math.min(u,s(v,x)):Math.max(u,s(v,x))}}return Number.isFinite(u)?u:s(t,i)}static occupantView(e,t=e.headingDeg){const i=e.observerSide;if(!i)throw new Error("occupantView requires object.observerSide to be set");const{x:n,z:s}=e.kind==="vehicle"?gm(i,Xr,Zo,Rw):gm(i,vm/2,bm/2,Dw),r=e.kind==="vehicle"?cR:(e.occupiedFloor??0)*jr+j4,o=(t??0)-Aw[e.observerFacing??i]/af,l=this.scaleFor(e);return{x:n*l.x,z:s*l.z,eyeY:r*l.y,headingDeg:o}}static BODY_NAME="decor-body";static bodyOf(e){return e.getObjectByName($t.BODY_NAME)??e}static repeatOnGrid(e,t,i,n,s){const r=e.getAttribute("position"),o=e.getAttribute("normal"),l=e.getIndex();if(!l)throw new Error("repeatOnGrid needs an indexed geometry");const c=r.count,h=t*n,d=new Float32Array(c*h*3),u=new Float32Array(c*h*3),p=new Uint32Array(l.count*h),f=-((t-1)*i)/2,g=-((n-1)*s)/2;let m=0;for(let x=0;x<n;x++)for(let y=0;y<t;y++,m++){const b=g+x*s,w=f+y*i;for(let S=0;S<c;S++){const _=(m*c+S)*3;d[_]=r.getX(S)+b,d[_+1]=r.getY(S),d[_+2]=r.getZ(S)+w,u[_]=o.getX(S),u[_+1]=o.getY(S),u[_+2]=o.getZ(S)}for(let S=0;S<l.count;S++)p[m*l.count+S]=l.getX(S)+m*c}const v=new ct;return v.setAttribute("position",new wt(d,3)),v.setAttribute("normal",new wt(u,3)),v.setIndex(new Ym(p,1)),v}static fitTerrace(e,t,i){const n=$t.sizeOf(t),s=n.widthM/2,r=n.lengthM/2,o=i(0,0)+n.heightM,l=Math.min(16,Math.max(1,Math.ceil(n.lengthM/3))),c=$t.bodyOf(e).children.filter(b=>b.isMesh);if(c.length<2)return o;const h=Math.min(10,n.widthM/4),d=[-s];for(const b of[.25,.5,.75,1])d.push(-s+h*b);const u=Math.max(1,Math.ceil((n.widthM-2*h)/3));for(let b=1;b<u;b++)d.push(-s+h+(n.widthM-2*h)*b/u);for(const b of[1,.75,.5,.25,0])d.push(s-h*b);const p=b=>-r+n.lengthM*b/l,f=.8,g=(b,w)=>{const S=Math.min(1,Math.max(0,(s-Math.abs(b))/h)),_=S*S*(3-2*S);return _*o+(1-_)*Math.min(o,i(b,w))},m=[],v=(b,w)=>{const S=i(b[0],b[1])-f,_=i(w[0],w[1])-f,M=Math.max(g(b[0],b[1]),S),T=Math.max(g(w[0],w[1]),_);m.push(b[0],S,b[1],w[0],_,w[1],b[0],M,b[1]),m.push(w[0],_,w[1],w[0],T,w[1],b[0],M,b[1])};for(let b=0;b<d.length-1;b++)v([d[b],-r],[d[b+1],-r]),v([d[b],r],[d[b+1],r]);const x=[];for(let b=0;b<d.length-1;b++)for(let w=0;w<l;w++){const S=[d[b],p(w)],_=[d[b+1],p(w)],M=[d[b],p(w+1)],T=[d[b+1],p(w+1)];for(const[A,R,C]of[[S,M,_],[_,M,T]])for(const k of[A,R,C])x.push(k[0],g(k[0],k[1]),k[1])}const y=(b,w)=>{const S=new ct;S.setAttribute("position",new wt(w,3)),S.computeVertexNormals(),b.geometry.dispose(),b.geometry=S,b.position.y=0};return y(c[0],m),y(c[1],x),o}static fitCropToGround(e,t){e.updateMatrixWorld(!0);const i=new D;e.traverse(n=>{const s=n,r=s.userData.cropBasePositions,o=s.userData.cropVerticesPerClump;if(!s.isMesh||!r||!o)return;const l=s.geometry.getAttribute("position"),c=new it().copy(s.matrixWorld).invert();for(let h=0;h<l.count;h+=o){i.set(r[h*3],0,r[h*3+2]).applyMatrix4(s.matrixWorld),i.y=t(i.x,i.z),i.applyMatrix4(c);for(let d=h;d<h+o;d++)l.setY(d,r[d*3+1]+i.y)}l.needsUpdate=!0,s.geometry.computeBoundingBox(),s.geometry.computeBoundingSphere()})}static paint(e,t){e.traverse(i=>{const n=i,s=n.userData;if(!n.isMesh||s?.emissive)return;const r=n.material;r?.color&&r.color.set(t)})}static build(e,t){const i=e.kind==="building"?ub(e.floors??hl,e.windows,e.observerSide,e.occupiedFloor,e.observerFacing):e.kind==="tree"?fb():e.kind==="shrub"?pb():e.kind==="bridge"?J4(e):e.kind==="wire"?Q4(e):e.kind==="crop"?gb():e.kind==="terrace"?oR():e.kind==="mound"?vb():e.kind==="streetlight"?bb(t):e.kind==="vehicle"?yb(t,e.windows,e.observerSide,e.observerFacing):e.kind==="aircraft"?_b():e.kind==="entity"?Sb():ym();e.color&&this.paint(i,e.color);const n=this.scaleFor(e),s=new Ct;return i.name=$t.BODY_NAME,i.scale.copy(n),s.add(i),e.headingDeg!==void 0&&(s.rotation.y=-e.headingDeg*af),this.addLights(s,e.lights),s}static scaleFor(e){const t=e.sizeM;if(!t||e.kind==="bridge"||e.kind==="wire"||e.kind==="terrace")return new D(1,1,1);const i=this.naturalSize(e.kind,e.floors);return new D(t.widthM===void 0?1:hf(t.widthM,i.widthM),t.heightM===void 0?1:hf(t.heightM,i.heightM),t.lengthM===void 0?1:hf(t.lengthM,i.lengthM))}static naturalSize(e,t){const i=e==="building"?Math.max(1,(t??hl)+1):0;if(e==="bridge")return Zt.NATURAL_SIZE;if(e==="wire")return ja.NATURAL_SIZE;if(e==="terrace")return{widthM:1,lengthM:1,heightM:1};const n=`${e}:${i}`,s=Mb.get(n);if(s)return s;const r=e==="building"?ub(i-1,void 0,void 0,void 0):e==="tree"?fb():e==="shrub"?pb():e==="crop"?gb():e==="mound"?vb():e==="streetlight"?bb(!1):e==="vehicle"?yb(!1,void 0,void 0):e==="aircraft"?_b():e==="entity"?Sb():ym(),o=new un().setFromObject(r),l={widthM:o.max.x-o.min.x,heightM:o.max.y-o.min.y,lengthM:o.max.z-o.min.z};return this.dispose(r),Mb.set(n,l),l}static usesModel(e){return lu(e)!==void 0&&!(e.observerSide!==void 0&&eo(e.kind))}static applyModel(e,t,i,n={}){const s=this.bodyOf(e),r=new Ct;r.name=$t.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*af,i.updateMatrixWorld(!0);const o=new un().setFromObject(i),l={lengthM:o.max.z-o.min.z,heightM:o.max.y-o.min.y,widthM:o.max.x-o.min.x},c=wb(t.sizeM,l)??wb(n.depictedSizeM,l)??1;i.scale.multiplyScalar(c);const h=o.getCenter(new D).multiplyScalar(c);i.position.x-=h.x,i.position.z-=h.z,i.position.y-=t.kind==="aircraft"?h.y:o.min.y*c,i.traverse(d=>{d instanceof Ae&&(d.castShadow=!0,d.receiveShadow=!0)}),r.add(i),s.parent?(s.parent.add(r),s.removeFromParent()):e.add(r),this.dispose(s)}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=W4(i.color),s=Pt(e,new yi(of,8,6),n,i.offsetM.y,!0);s.position.set(i.offsetM.x,i.offsetM.y,i.offsetM.z),s.userData={emissive:!0,lightId:i.id,lightColor:n},s.visible=!1;const r=s.material;r.blending=Bi,r.transparent=!0,r.depthWrite=!1,r.fog=!1}}static setLights(e,t,i,n,s=0,r=1,o=U4,l=[1,1,1]){if(!t||t.length===0)return;const c=new Map(t.map(p=>[p.id,p])),h=Math.max(1,n*o/of),d=of*h,u=r/(Math.PI*d*d);for(const p of e.children){if(!(p instanceof Ae))continue;const f=p.userData.lightId;if(!f)continue;const g=c.get(f);if(!g)continue;const m=s>0?$y(g,i,i+s):Nx(g,i)?1:0;p.visible=m>0;const v=p.material,x=p.userData.lightColor;if(x){const y=m*B4*(g.intensity??1)*u;v.color.setRGB(x[0]*y*l[0],x[1]*y*l[1],x[2]*y*l[2])}p.scale.setScalar(h)}}static setLit(e,t,i,n=1){const[s,r,o]=t==="streetlight"?[z4,H4,Ew]:[G4,V4,_w],l=i?s*n/(Math.PI*r*r):0,c=[o[0]*l,o[1]*l,o[2]*l];e.traverse(h=>{const d=h.userData;!(h instanceof Ae)||!d.emissive||d.lightId||h.material.color.setRGB(...c)})}static dispose(e){e.traverse(t=>{if(!(t instanceof Ae)||t.userData.sharedModel)return;t.geometry.dispose();const i=t.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const uf="https://ufoathome.org/models/index.json";class Cc{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??dR()}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(`
|
|
8955
|
-
`);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.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 dR(){const a=`?v=${encodeURIComponent("0.105.
|
|
8955
|
+
`);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.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 dR(){const a=`?v=${encodeURIComponent("0.105.2")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==uf?[e,uf]:[uf]).map(t=>t+a)}const Pd=[{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 Cc}];async function pf(a){const{GLTFLoader:e}=await je(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-BlqKtwJh.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,n)=>{t.load(a,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${a}: ${s instanceof Error?s.message:String(s)}`)))})}const Pw=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class Wn{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new Ae(new Sn(2,2),new xt({uniforms:{uColor:{value:new se(0,0,0)},uRadius:{value:1}},vertexShader:Wn.VERTEX,fragmentShader:Wn.FRAGMENT,transparent:!0,depthWrite:!1,blending:Bi,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*Wn.MIN_ANGLE_RAD),r=Wn.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Wn.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(Wn.MAX_SHARE*Wn.FILL*Math.PI))}static VERTEX=`
|
|
8956
8956
|
uniform float uRadius;
|
|
8957
8957
|
varying vec2 vOffset;
|
|
8958
8958
|
void main() {
|
|
@@ -9583,7 +9583,7 @@ void main() {`).replace("#include <opaque_fragment>",`
|
|
|
9583
9583
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
9584
9584
|
gl_FragColor = vec4(light, 1.0);
|
|
9585
9585
|
}
|
|
9586
|
-
`,transparent:!0,blending:Bi,depthWrite:!1,side:ni,fog:!1});this.object=new Ae(new yi(bg.RADIUS,128,32,0,Math.PI*2,0,St.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<St.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=jn.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=jn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class ku{constructor(e){this.generator=e}static SIZE=128;target=new Zc(ku.SIZE,{type:Jt,generateMipmaps:!1,minFilter:gt,magFilter:gt});camera=new eg(.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(l=>{const c=l;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?s:!1;const o=n.map(l=>l.visible);for(const l of n)l.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),n.forEach((l,c)=>{l.visible=o[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 Pn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){Pn.install(),this.generator=new G0(e),this.eye=new ku(this.generator)}static decor;refresh(e,t,i,n,s,r,o,l=[],c,h=Pn.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const d=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new ku(this.generator),this.probes.set(m.id,v)),d.push({probe:v,reflector:m})}const u=performance.now(),p=()=>d.filter(({probe:m})=>m.capturedVersion!==o),f=p().filter(({probe:m})=>u-m.capturedAtMs>=h);if(f.length>0){const m=f.reduce((v,x)=>x.probe.capturedAtMs<v.probe.capturedAtMs?x:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(e,t,v,[m.reflector.holder,...s]),Pn.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(e,t,i,[...s,...l]),c?.(m.probe.sharp),Pn.decor=m.probe.filtered;for(const v of r)Pn.reflectOn(v,m.probe);for(const v of n)v.shiny||Pn.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=o}const g=p();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>h-(u-m.capturedAtMs))))}scratch=new D;static reflectOn(e,t={filtered:Pn.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof eh?t.sharp&&s.setSurroundings(t.sharp):s instanceof Qr&&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(Pn.installed)return;Pn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!Je.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}Je.lights_fragment_maps=Je.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function fR(a,e){return JSON.stringify(a.cloudLayers)===JSON.stringify(e.cloudLayers)&&a.cloudCover===e.cloudCover&&a.cloudDarkness===e.cloudDarkness&&a.cloudBaseM===e.cloudBaseM&&a.highCloudCover===e.highCloudCover&&a.iceCrystalAlignment===e.iceCrystalAlignment&&a.lowerCloudCover===e.lowerCloudCover&&a.relativeHumidity===e.relativeHumidity&&a.precipitationType===e.precipitationType&&a.precipitationIntensity===e.precipitationIntensity&&a.precipitationAmount===e.precipitationAmount&&a.windDirectionDeg===e.windDirectionDeg&&a.windSpeed===e.windSpeed&&a.storm===e.storm}const od=900,ff=1,Ab=4,mf=5,Tb=.5,xc=900,mR=6371e3,gR=3e4;function Ib(a){const e=Math.sqrt(2*mR*Math.max(a,0));return Math.max(xc,Math.min(e,gR))}const gf=.5,vf=850,bf=.03,vR=.015,_n=850,cc=300,Vr=120,bR=700,yR=.04,Db=4,yf=1.5,Rb=-1,MR=.01,Ld=-4,wR=2,xR=20,ld=2600,SR=.97,ER=.38,cd=Ld,Cb=1500,_R=400,AR=[0,45,90,135,180,225,270,315],TR=2,IR=16,Pb=4e3,Lb=880,hd=40,kb=60,DR=10,RR=1,CR=150,PR=55,LR=.5,kR=17,Ob=.265,Nb=[[0,0],...Array.from({length:8},(a,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*Ob,Math.sin(t)*Ob]})],Mf=700,wf=250/xm,OR=12,Fb=5,xf=6,ya=[.92,.92,.95],Sf=[.15,.15,.19],Ef={snow:{fallSpeedMPerS:2,size:.3,color:new se(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new se(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},jo=0,_f=0,NR=150,Af=3e3,hc=20,FR=15,Ub=jo,UR=40,Bb=1,BR=9;function Tf(a){return Bb+(BR-Bb)*a}const zb=new se(.75,.82,.92),zR=10,HR=.5;function Hb(a){return yr(a/zR,HR,1)}const Ma=200,Gb=.18,Vb=.32,GR=.35,Wb=new se(.85,.9,.98),Xb=5,$b=.85,Yb=.01;function VR(a,e,t=1){return Math.round(a*(Yb+(1-Yb)*e)*t)}function WR(a,e){return JSON.stringify(a.cloudLayers)===JSON.stringify(e.cloudLayers)&&a.cloudCover===e.cloudCover&&a.cloudDarkness===e.cloudDarkness&&a.cloudBaseM===e.cloudBaseM&&a.highCloudCover===e.highCloudCover&&a.iceCrystalAlignment===e.iceCrystalAlignment&&a.lowerCloudCover===e.lowerCloudCover}const qb=230,Kb=.7,Zb=.05,XR=.6,$R=.7,YR=.15,jb=.35,qR=3,KR=1/12,ZR=.5,Us=new se(.82,.86,1),jR=2500,JR=1.6,If=15,QR={Venus:new se(1,.96,.85),Mars:new se(1,.55,.4),Jupiter:new se(.95,.87,.72),Saturn:new se(.92,.86,.68)};class ut{renderer;scene=new rr;phenomena=new ys(this.scene);references=new bs(this.scene,()=>this.render());camera;celestialGroup=new Ct;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;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()+Pb,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),Pb+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new is;roadAttribution;roadWays;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new xe;decorModelProvider=Pd[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new pt(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??ut.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*ut.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new g1(16777215,0);celestialLightTarget=new Qt;skyLight=new d3(16777215,0,0);streetlightLights=new Map;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new Id;weather=Vu;observerElevationM=0;siteElevationM=0;air=new rs;groundRadius=xc;terrainRadius=xc;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new D;cloudFieldOffset=new D;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new D;rainLastVerticalFacing=-1;rainViewportSize=new xe;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new g1(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new Id;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new Id;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;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;iceHalos;lunarDiffraction;eclipsedSun=new th;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=lS()){this.renderer=new AI({canvas:e,antialias:!0}),this.resolution=new Dt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Ec,this.camera=new Ln(60,e.width/Math.max(e.height,1),.1,od*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=-Vr,this.celestialLight.shadow.camera.right=Vr,this.celestialLight.shadow.camera.top=Vr,this.celestialLight.shadow.camera.bottom=-Vr,this.celestialLight.shadow.camera.near=_n-cc,this.celestialLight.shadow.camera.far=_n+cc,this.celestialLight.shadow.bias=-.03/(2*cc),this.celestialLight.shadow.normalBias=yR,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Us),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);const i=new rt(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}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*wf,0,e.z*wf);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)*Pi,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Pi;if(e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Pi,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(Ib(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/xc),this.camera.far=Math.max(od*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),this.terrainMesh&&this.terrainOrigin&&e.lat!==void 0&&e.lng!==void 0){const n=ci(this.terrainOrigin.lat,this.terrainOrigin.lng,e.lat,e.lng);this.terrainMesh.position.x=n.x,this.terrainMesh.position.z=n.z}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.terrainOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const n=this.groundRadius;if(this.terrainOrigin&&Math.abs(this.terrainRadius-n)<n*.1){const{x:l,z:c}=ci(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(l*l+c*c)<CR*(n/xc))return}const s=this.terrainOrigin,r=this.terrainRadius;(!s||s.lat!==e||s.lng!==t)&&(this.roadSystem.clear(),this.roadAttribution=void 0),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=n;const o=++this.terrainBuildToken;this.awaitArrival(y4(e,t,this.terrainProviders,n),ut.TERRAIN_PATIENCE_MS).then(({mesh:l,attribution:c,originElevationM:h})=>{if(o!==this.terrainBuildToken)return;this.setSiteElevation(h??0);const d=this.terrainMesh,u=s?ci(e,t,s.lat,s.lng):void 0;d&&u&&Math.hypot(u.x,u.z)<=r&&(l.position.y=d.position.y+this.groundYOfPatch(d,u.x,u.z)),d&&u&&Math.hypot(u.x,u.z)<=r?this.crossfadeTerrain(l,d):this.disposeMesh(this.terrainMesh),l.renderOrder=RR,this.terrainMesh=l,this.compileNextFrameOffThread(),this.terrainAttribution=c,this.scene.add(l),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,n),this.drapeStatedRoads(),this.drapeTraces(),this.render(),i?.()}).catch(l=>{console.warn("Terrain build failed, keeping the flat ground fallback:",l),i?.()})}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t){this.stopTerrainFade();const i=e.material;i.opacity=0,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-4;const n=performance.now(),s=()=>{const r=Math.min(1,(performance.now()-n)/ut.TERRAIN_CROSSFADE_MS);if(i.opacity=r*r*(3-2*r),this.render(),r<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(s);return}i.polygonOffset=!1,i.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:t,frameId:requestAnimationFrame(s)}}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=5e3;buildRoads(e,t,i){const n=this.terrainProviders.roads;if(!n||i>ut.ROADS_MAX_RADIUS_M){this.roadSystem.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}this.awaitArrival(n.getRoads(Sw(e,t,i)),ut.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)})}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.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??=je(async()=>{const{TraceSystem:e}=await import("./TraceSystem-DCqCjgtt.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(mf);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainOrigin;!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)))}drapeRoads(e,t,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.set(e,t,i,(r,o)=>this.groundYOfPatch(s,r,o),n),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;applyLensFlareTint(e){if(!this.lensFlare)return;const t=PR*(this.sunArriving[1]/kR);this.lensFlare.uniforms.uColorGain.value.setRGB(t*e[0],t*e[1],t*e[2]),this.applyDazzleStrength()}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=an.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(fR(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!WR(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=rs.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Sr.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>=ZR,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects!==e){this.decorObjects=e,this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const t of this.decorGroups.values())t.removeFromParent(),$t.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear();for(const t of e){const i=$t.build(t,t.lit??!1);this.scene.add(i),this.decorGroups.set(t.id,i),t.kind==="streetlight"&&this.addStreetlightLight(t.id,i),t.model&&t.id.startsWith(as.ID_PREFIX)?(this.pendingTrafficModels.set(t.id,t),this.awaitArrival(this.loadDecorModel(t,this.decorModelToken,!0))):this.reuseLoadedDecorModel(t,i)||this.awaitArrival(this.loadDecorModel(t,this.decorModelToken))}this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}}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??=je(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-oqsCCklf.js");return{ContrailSystem:e}},__vite__mapDeps([0,1]),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=ut.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(t&&i){const o=Xn.litFraction(t.sunElevationDeg,t.heightM);if(o>0){const l=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=St.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*c*l[h]*o}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);updateContrails(){this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad()},e=>this.contrailTint(e))}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}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);return{heightAt:(n,s)=>this.groundYUnder(e+n,t-s)-i}}setBodies(e,t=0,i=e.map(r=>r.id),n=[],s){const{x:r,z:o}=this.bodyOrigin,l=this.scatteredSky;this.bodySystem.set(e,{originX:r,originZ:o,originGroundY:this.groundYUnder(r,o),eye:this.camera.position,groundYAt:(h,d)=>this.groundYUnder(h,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(h,d,u)=>this.transmittanceTo(h,d,u)},t,l?(h,d)=>l.relativeOfLuminance(h,d):void 0,i),this.bodySystem.setSmoke(n,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const c=this.bodySystem.furthestFrom(this.camera.position)*1.2;c>this.camera.far&&(this.camera.far=c,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=(o,l,c)=>(o*t+(l+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 pf(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(lu(e))||!$t.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const n=i.scene.clone(!0);n.traverse(s=>{s instanceof Ae&&(s.userData.sharedModel=!0)}),$t.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?ou[e.kind]:lu(e);if(!(!n||!$t.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,o=n.credit??s?.credit;if(!r||!o)return;const l=i?await this.standInScene(r):await pf(r);if(t!==this.decorModelToken||i&&!this.pendingTrafficModels.has(e.id))return;const c=this.decorGroups.get(e.id);if(!c)return;i||Pn.reflectOn(l);const h={ref:JSON.stringify(n),scene:l,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:o};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=pf(e).then(i=>(Pn.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?ci(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(h=>h.observerSide!==void 0&&eo(h.kind));if(this.terrainMesh&&this.terrainOrigin&&t?.lat!==void 0&&t.lng!==void 0){const h=ci(this.terrainOrigin.lat,this.terrainOrigin.lng,t.lat,t.lng);this.terrainMesh.position.x=h.x-(s?0:this.gaitOffset.eastM),this.terrainMesh.position.z=h.z+(s?0:this.gaitOffset.northM),this.roadSystem.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 o=0,l;if(s){const h=tr(s,i),d=$t.occupantView(s,h.headingDeg),u=-(h.headingDeg??0)*Pi,p=d.x*Math.cos(u)+d.z*Math.sin(u),f=-d.x*Math.sin(u)+d.z*Math.cos(u),g=h.eastM+n.x,m=-h.northM+n.z;r.x=-(g+p),r.z=-(m+f),this.camera.position.y=this.groundYUnder(g,m)+d.eyeY,l=d.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Pi,-(d.headingDeg+this.indoorLookYawDeg)*Pi,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z},this.placeShadowFrustum(),this.placeTerraces(i,n,r),!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 h of this.decorObjects){if(h.kind==="terrace")continue;const d=this.decorGroups.get(h.id);if(!d)continue;const u=tr(h,i),p=u.eastM+n.x+r.x,f=-u.northM+n.z+r.z,g=this.terrainMesh,m=`${g?.geometry.uuid}:${(p-(g?.position.x??0)).toFixed(3)}:${(f-(g?.position.z??0)).toFixed(3)}:${(g?.position.y??0).toFixed(3)}:${u.headingDeg}:${u.altitudeM}`;if(d.userData.footprintKey!==m&&(d.userData.footprintGroundY=this.groundUnderFootprint(h,p,f,u.headingDeg,u.altitudeM),d.userData.footprintKey=m),d.position.set(p,d.userData.footprintGroundY+u.altitudeM,f),h.kind==="crop"){const b=Math.hypot(p,f);d.visible=b<=NR}const v=this.decorPresence.get(h.id),x=v!==void 0&&(i<v.fromMs||i>v.untilMs);v&&(d.visible=!x);const y=this.decorSunlight.get(h.id);if(y&&!x&&this.lightFromAbove(d,y),u.headingDeg!==void 0&&(d.rotation.y=-u.headingDeg*Pi),h.kind==="crop"&&d.visible){const b=this.terrainMesh,w=[b?.geometry.uuid,p-(b?.position.x??0),f-(b?.position.z??0),d.position.y-(b?.position.y??0),u.headingDeg,u.altitudeM].map(S=>typeof S=="number"?S.toFixed(4):S).join(":");d.userData.cropGroundKey!==w&&($t.fitCropToGround(d,(S,_)=>this.groundYUnder(S,_)+u.altitudeM),d.userData.cropGroundKey=w)}if(!x){const b=d.position.distanceTo(this.camera.position);o=Math.max(o,b),b<ut.trafficModelRangeM(h)&&this.pendingTrafficModels.delete(h.id)&&this.loadDecorModel(h,this.decorModelToken)}}if(s&&l!==void 0){const h=this.decorGroups.get(s.id);h&&(this.camera.position.y=h.position.y+l)}this.updateContrails();const c=Math.max(od*1.2,this.groundRadius*2.5,o*1.2);Math.abs(this.camera.far-c)>1&&(this.camera.far=c,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,o=t-s.z,l=r*s.cos-o*s.sin,c=r*s.sin+o*s.cos;if(Math.abs(l)<=s.halfWidthM&&Math.abs(c)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(l))/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 o=tr(s,e),l=o.eastM+t.x+i.x,c=-o.northM+t.z+i.z,h=$t.sizeOf(s),d=-(o.headingDeg??0)*Pi,u=Math.cos(d),p=Math.sin(d),f=`${n?.geometry.uuid}:${(l-(n?.position.x??0)).toFixed(3)}:${(c-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${o.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(l,0,c),o.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=$t.fitTerrace(r,s,(g,m)=>this.terrainYUnder(l+g*u+m*p,c-g*p+m*u)),r.userData.terraceKey=f),this.terraces.push({x:l,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):_f}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 _f;const r=n.getX(0),o=n.getX(s-1),l=n.getZ(0),c=n.getZ((s-1)*s),h=yr((t-r)/(o-r)*(s-1),0,s-1),d=yr((i-l)/(c-l)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(d))return _f;const u=Math.min(Math.floor(h),s-2),p=Math.min(Math.floor(d),s-2),f=h-u,g=d-p,m=(w,S)=>n.getY(w*s+S),v=m(p,u),x=m(p,u+1),y=m(p+1,u),b=m(p+1,u+1);return f+g<=1?v+(x-v)*f+(y-v)*g:b+(y-b)*(1-f)+(x-b)*(1-g)}groundUnderFootprint(e,t,i,n,s=0){return $t.groundUnderFootprint(e,t,i,n,(r,o)=>this.groundYUnder(r,o),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}medium;setMedium(e,t,i,n){const s=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:n??e.iso,autoExposure:e.autoExposure===!0,exposureSeconds:t,fNumber:i}:void 0;JSON.stringify(s)!==JSON.stringify(this.medium)&&(this.medium=s,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30);if(!e){Mn.uMedium.value=0;return}Mn.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const i=e.autoExposure?this.scatteredSky?.sceneAdaptation:void 0;Mn.uMediumExposure.value=i!==void 0&&i>0?1/(t*i):.065*e.exposureSeconds*e.iso*this.filterTransmittance/(e.fNumber*e.fNumber*t)}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 xe;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))}updateDecorLitState(e,t=0){const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&$t.setLights(s,n.lights,e,s.position.distanceTo(this.camera.position),t,this.relativeScale,i,this.lampTransmittance(s)),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const o=cu(n,e);$t.setLit(r,n.kind,o,this.relativeScale);const l=this.streetlightLights.get(n.id);l&&(l.visible=o)}}addStreetlightLight(e,t){const i=$t.bodyOf(t),n=i.children.find(r=>r.userData.emissive);if(!n)return;const s=new BM(16764006,Cb*this.relativeScale,_R);s.position.copy(n.position).multiply(i.scale),s.castShadow=!0,s.shadow.mapSize.set(512,512),s.shadow.bias=-.002,t.add(s),this.streetlightLights.set(e,s)}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.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 o=As.luminanceOf(r);if(!(o>0))return[0,0,0];const l=Ie.relativeOfResponse(o)/o;return[r[0]*l,r[1]*l,r[2]*l]},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=bi.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,Db,new se(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<Ld){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=Db/_n*(180/Math.PI),n=i/t.sunRadiusDeg,s=jt(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=jt(e.moon.altitudeDeg,e.moon.azimuthDeg,1),o=Math.acos(yr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),l=o>1e-9?yr(t.separationDeg*n*Pi/o,0,2):0,c=Math.sin(o),[h,d]=o>1e-9?[Math.sin((1-l)*o)/c,Math.sin(l*o)/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 D(s.x,s.y,s.z).normalize(),moon:new D(u.x,u.y,u.z).normalize(),sunRadiusRad:i*Pi,moonRadiusRad:p*Pi};const f=.01,g=(x,y)=>jt(e.sun.altitudeDeg+x,e.sun.azimuthDeg+y,1),m={x:g(f,0).x-g(-f,0).x,y:g(f,0).y-g(-f,0).y,z:g(f,0).z-g(-f,0).z},v={x:g(0,f).x-g(0,-f).x,y:g(0,f).y-g(0,-f).y,z:g(0,f).z-g(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:n,up:m,right:v}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new al(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));const t=this.scatteredSky?.ambient??ut.relativeSkyOf(j0(e.sun.altitudeDeg),this.relativeScale),i=t,n=this.lightUnderClouds(e),s=r=>n?[0,1,2].map(o=>r[o]*n.through+n.radiance[o]*(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),Ce.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=Cb*this.relativeScale;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?Be.DEFAULT_AEROSOL_OPTICAL_DEPTH:Sr.opticalDepth(i))*Be.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),o=St.aureoleScale(n,St.airMass(e.altitudeDeg))*s,l=St.coronaScale(r),c=St.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),o.toExponential(2),l.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 bg,this.celestialGroup.add(this.lunarDiffraction.object));const d=St.profile(St.HAZE_COARSE_MODE),u=St.profile(St.CLOUD_DROPLETS),p=q1(e.altitudeDeg),f=new Float32Array(St.STEPS*3);let g=0;for(let y=0;y<St.STEPS;y++){const b=y*3,w=[0,1,2].map(_=>c*p[_]*(o*d[b+_]+l*u[b+_])),S=As.shown(w,As.luminanceOf(w),(_,M)=>t.relativeOfLuminance(_,M));f.set(S,b),g=Math.max(g,As.response(S))}const{x:m,y:v,z:x}=jt(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(g>1/200?{x:m,y:v,z:x}:void 0,f)}applyAir(){this.scene.fog instanceof ao||(this.scene.fog=new ao),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,ut.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:bi.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?bi.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:ce.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?IR:TR),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 N4(vf),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):sa(-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 Tn,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):sa(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}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(bf*this.camera.fov*Math.PI/180);let s,r=n;const o=new D;for(const[l,c]of this.decorGroups){if(!c.visible||!l.startsWith(as.ID_PREFIX))continue;o.copy(c.position).sub(this.camera.position).normalize();const h=o.dot(i);h>r&&(r=h,s=l)}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(bf*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>=cd,s=!n&&e.moon.altitudeDeg>=cd,r=n?e.sun:e.moon,o=[0,0,0],l=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Pi)),c=n||s?this.cloudTransmission(r):1,h=-Math.log(Math.max(c,1e-6)),d=Math.max(0,1/(1+.1125*h)-c),u=[0,0,0];if(n||s){const x=St.illuminanceOf(r.magnitude)*i,y=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,r.altitudeDeg);for(let _=0;_<3;_++)o[_]=x*y[_]*c,u[_]=x*y[_]*d*l,this.cloudBeam[_]=x*y[_];const{x:b,y:w,z:S}=jt(r.altitudeDeg,r.azimuthDeg,1);this.cloudBeamDirection.set(b,w,S)}else this.cloudBeam.fill(0);const p=this.surroundings;if(p)this.skyLight.color.setRGB(p.up[0]*i,p.up[1]*i,p.up[2]*i),this.skyLight.groundColor.setRGB(p.down[0]*i,p.down[1]*i,p.down[2]*i);else{const x=this.skyCloudTransmission(),y=t.skyIrradiance,b=[0,1,2].map(S=>y[S]*x+u[S]);this.skyLight.color.setRGB(b[0],b[1],b[2]);const w=We.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(w*(b[0]+o[0]*l),w*(b[1]+o[1]*l),w*(b[2]+o[2]*l))}if(this.skyLight.intensity=1,this.sceneSunBeam=n?[o[0],o[1],o[2]]:[0,0,0],!n&&!s){this.celestialLight.intensity=0;return}const{x:f,y:g,z:m}=jt(r.altitudeDeg,r.azimuthDeg,1);this.lightDirection.set(f,g,m),this.placeShadowFrustum();const v=Math.max(o[0],o[1],o[2],1e-30);this.celestialLight.color.setRGB(o[0]/v,o[1]/v,o[2]/v),this.celestialLight.intensity=v,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=Xn.litFraction(t.sunElevationDeg,t.heightM);if(s>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),o=St.illuminanceOf(i.magnitude)*this.relativeScale,l=t.heightM>=ut.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)n[c]=Math.max(0,o*r[c]*s*l-this.sceneSunBeam[c])}}e.traverse(s=>{const r=s.material;if(!(r instanceof Nl||r instanceof Qr)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const o=ut.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*o,r.color.g*n[1]*o,r.color.b*n[2]*o)})}lightDirection=new D(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,0,this.bodyOrigin.z),o=c=>{const h=r.dot(c)/i;return(h-Math.round(h))*i},l=this.celestialLightTarget.position.set(0,0,0).addScaledVector(n,o(n)).addScaledVector(s,o(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(l).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToBodies(){const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(bR,Math.max(Vr,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(cc,t*(cc/Vr));this.shadowLightDistanceM=Math.max(_n,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*Vr?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=Vr;shadowLightDistanceM=_n;shadowUp=new D(0,1,0);shadowAxisX=new D;shadowAxisY=new D;shadowWorld=new D;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const n=i*Pi,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 D(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Ie.semiSaturation(Ie.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new Wi,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=Rt.starPointsOf(e),i=Rt.flareArtifactsOf(e);t===this.starPoints&&i===this.lensFlareArtifactIntensity||(this.starPoints=t,this.lensFlareArtifactIntensity=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=t,this.lensFlare.uniforms.uFlareIntensity.value=i),this.render())}magnitudeLimitOf(e){const t=ce.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return sa(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{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()+ut.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of e){const o=t.get(r)?.currentProgram;(!o||o.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()}refreshReflections(e=!1){this.reflections??=new Pn(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(o=>o.mesh)],i=[...this.starTiers.map(o=>o.points),...[...this.bodyMeshes.values()].filter(o=>o instanceof Vn),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(o=>o!==void 0)],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values()],s,i,o=>this.measureSurroundings(o,n,s),e?0:Pn.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))}measureSurroundings(e,t,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new Ic;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>jt(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,s,r=>{const o=p=>p.map(f=>f/t),l=this.surroundings,c={up:o(r.up),down:o(r.down)},h=(p,f)=>p.some((g,m)=>Math.abs(g-f[m])>.03*Math.max(Math.abs(g),Math.abs(f[m]),1e-12)),d=!l||h(l.up,c.up)||h(l.down,c.down);d&&(this.surroundings=c),this.eyeSettledVersion=-1;const u=this.scatteredSky?.adaptToSurroundings(Math.exp(r.logAverage)/t)??!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>=cd?e.sun:e.moon.altitudeDeg>=cd?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,KR);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.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,o,l)=>this.directionAtScreenPoint(r,o,l),r=>this.screenPointOf(r)),this.references.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references.furthestM)*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 Vn&&t.userData.pointSource||t instanceof Ae&&t.userData.skyRibbon)&&e.push(t)}),e},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(mf),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(Lw),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 On({blending:nh,blendSrc:vc,blendDst:vc,blendSrcAlpha:vc,blendDstAlpha:vc,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(Ow),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){this.references.set(e.map(i=>{const n=this.documentRelative(i.src);return n===i.src?i:{...i,src:n}}),void 0,t)}referenceAspect(e){return this.references.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new D)}referenceFailedToLoad(e){return this.references.failedToLoad(this.documentRelative(e))}setReferencesShown(e){this.references.setShown(e),this.render()}setReferenceView(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&&ut.markDecorDepth(s,n.kind!=="crop")}e.layers.set(ff),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(kw),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new On({colorWrite:!1});static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Ae))return;const n=Array.isArray(i.material)?i.material[0]:i.material;t&&n.depthWrite!==!1&&n.blending!==Bi?i.layers.enable(ff):i.layers.disable(ff)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new xe),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new NI(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()+ut.EXPOSURE_BUDGET_MS,s=ut.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const o=this.compassSprites.map(l=>l.visible);for(const l of this.compassSprites)l.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((l,c)=>{l.visible=o[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(){if(Mn.uRodShare.value=this.scatteredSky?.rodShare??0,Mn.uHasOverlay.value=1,Mn.uRelativeScale.value=this.relativeScale,this.applyMedium(),this.exposureAccumulation?.develop(this.renderer,this.exposureInstants/this.exposureInstantsDone),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(s=>s.visible))return;const e=new rr,t=new Rs(-1,1,1,-1,0,2),i=hd/(Lb*Math.tan(kb*Pi/2));for(const s of this.compassSprites){if(!s.visible)continue;const r=s.getWorldPosition(new D).sub(this.camera.position).normalize(),o=this.screenPointOf(r);if(!o)continue;const l=new jl(s.material);l.position.set(o.ndcX,o.ndcY,-1),l.scale.set(i/this.camera.aspect,i,1),e.add(l)}const n=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(e,t)}finally{this.renderer.autoClear=n}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const e=[],t=new un,i=new D,n=this.camera.getWorldDirection(new D),s=this.decorObjects.filter(o=>o.track?.length||o.kind==="aircraft"||o.kind==="vehicle").map(o=>this.decorGroups.get(o.id)),r=this.bodySystem.reflectors.map(o=>o.holder);for(const o of[...s,...r]){if(!o?.visible||(t.setFromObject(o),t.isEmpty())||t.distanceToPoint(this.camera.position)<ut.MAP_SUBJECT_NEAREST_M)continue;let l=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 g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;l=Math.min(l,m),c=Math.max(c,m),h=Math.min(h,v),d=Math.max(d,v)}l=Math.max(l,0),c=Math.min(c,1),h=Math.max(h,0),d=Math.min(d,1),c>=l&&d>=h&&e.push({x:l,y:h,width:c-l,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 xe),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new Rc(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new xe);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new vg(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new xe);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new ti(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new xe(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 D)}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 ti.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*Pi);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new D;screenPointQuaternion=new dn;screenPointSize=new xe;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)}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(Ab),this.camera.layers.set(Ab),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 Nb)this.isSunOccluded(t[0],t[1])||e++;return e/Nb.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 o=Math.PI/180,l=this.sunOcclusionRightScratch.set(n.z,0,-n.x);l.lengthSq()<1e-9&&l.set(1,0,0),l.normalize();const c=this.sunOcclusionUpScratch.crossVectors(l,n).normalize();n.addScaledVector(l,e*o).addScaledVector(c,t*o).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 m=(s.position.y-e.y)/t.y;if(m>n&&m<i){const v=e.x+t.x*m-s.position.x,x=e.z+t.z*m-s.position.z;if(Math.hypot(v,x)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const o=r.geometry.getAttribute("position"),l=Math.round(Math.sqrt(o.count));if(l<2||l*l!==o.count)return!1;const c=[r.position.x+o.getX(0),r.position.x+o.getX(l-1)],h=[r.position.z+o.getZ(0),r.position.z+o.getZ((l-1)*l)],d=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(l-1);if(!(d>0))return!1;let u=n,p=i;for(const[m,v,x]of[[e.x,t.x,c],[e.z,t.z,h]]){const y=Math.min(x[0],x[1]),b=Math.max(x[0],x[1]);if(Math.abs(v)<1e-12){if(m<y||m>b)return!1;continue}const w=(y-m)/v,S=(b-m)/v;u=Math.max(u,Math.min(w,S)),p=Math.min(p,Math.max(w,S))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),g=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let m=0;m<=g;m++){const v=u+(p-u)*m/g,x=e.x+t.x*v,y=e.y+t.y*v,b=e.z+t.z*v;if(y<=this.groundYUnder(x,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=Tb;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const o=this.decorGroups.get(r.id);if(!o)continue;const l=this.ufoOcclusionRaycaster.intersectObject(o,!0)[0];l&&(r.occludesSourceIds?.includes(i)?n=n===void 0?l.distance:Math.max(n,l.distance):s=s===void 0?l.distance:Math.min(s,l.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=MR*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,d])=>{const u=d.getWorldPosition(new D).sub(i);return{key:h,direction:u.clone().normalize(),radiusRad:Math.atan2(d.scale.x/2,u.length())}}),o=this.eclipseDiscs,l=o?[{key:"sun",direction:o.sun,radiusRad:o.sunRadiusRad},{key:"moon",direction:o.moon,radiusRad:o.moonRadiusRad,inFront:!0}]:[],c=ut.nearestBody(n,[...r.filter(h=>!o||h.key!=="sun"&&h.key!=="moon"),...l],s);if(c)return this.groundHides(e,t)?void 0:c}static nearestBody(e,t,i){let n,s=1/0,r=1/0,o=!1;for(const l of t){const c=Math.acos(yr(l.direction.dot(e),-1,1))-l.radiusRad;if(c>i)continue;const h=c<=0,d=s<=0,u=l.inFront===!0;(h!==d?h:h?u!==o?u:l.radiusRad<r:c<s)&&(n=l.key,s=c,r=l.radiusRad,o=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=vR*this.camera.fov*Math.PI/180,o=[...this.decorGroups.values()],l=o.length>0?ut.firstSolid(this.raycaster.intersectObjects(o,!0))?.distance:void 0;let c,h=1/0;const d=new un,u=new D;for(const p of i){if(d.setFromObject(p),d.isEmpty())continue;d.getCenter(u);const f=d.getSize(new D).length()/2,g=u.clone().sub(s),m=g.length();if(m===0||g.dot(n)<=0||l!==void 0&&l<m-f)continue;const v=Math.acos(Math.min(1,g.normalize().dot(n))),x=Math.max(r,Math.atan(f/m));v<=x&&x<h&&(h=x,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(bf*this.camera.fov*Math.PI/180);let s,r=n;for(const o of this.namedStars){const l=o.direction.dot(i);l>r&&(r=l,s={star:o.star,altitudeDeg:o.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,Tb)}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 o=0;o<8;o++){const l=this.bodyCornerScratch.set(o&1?t.max.x:t.min.x,o&2?t.max.y:t.min.y,o&4?t.max.z:t.min.z),c=this.screenPointOf(l.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 un;bodyCornerScratch=new D;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,o=-1/0;for(let l=0;l<8;l++){const c=this.bodyCornerScratch.set(l&1?i.max.x:i.min.x,l&2?i.max.y:i.min.y,l&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),o=Math.max(o,h.ndcY)}return{minX:n,minY:s,maxX:r,maxY:o}}decorGroundPointAt(e,t,i){const n=this.decorGroups.get(e);if(!n)return;this.aimAtScreenPoint(this.raycaster,t,i);const s=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-n.position.y),this.decorHitScratch);return s?{x:s.x,z:s.z}:void 0}decorPlaneScratch=new qr;decorHitScratch=new D;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<ut.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],n=ut.firstSolid(this.raycaster.intersectObjects(i.map(([,r])=>r),!0));if(!n)return;let s=n.object;for(;s&&!i.some(([,r])=>r===s);)s=s.parent;return i.find(([,r])=>r===s)?.[0]}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.roadSystem.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=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.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.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())$t.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 D;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const e=this.lastAstronomy?.sun;return e!==void 0&&e.altitudeDeg<ut.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 yi(od,32,16),i=t.attributes.position,n=t.getAttribute("color")??new wt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:o,azimuthDeg:l}=BI(i.getX(r),i.getY(r),i.getZ(r)),c=YI(o,l,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 On({vertexColors:!0,side:ni,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Ae(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=Ib(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Km(this.groundRadius,48),i=new Nl({color:new se(gf,gf,gf),fog:!0});ao.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Ae(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,o])=>`${r}=${Math.round(o.x/10)},${Math.round(o.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=jt(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-It.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*SR);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-It.iceAlphaAt(i,ld,r,this.cloudFieldOffset)*ER),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<Ld){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:o,z:l}=jt(t.altitudeDeg,t.azimuthDeg,_n),c=q1(t.altitudeDeg),h=this.cloudTransmission(t),d=this.arrivingIlluminance(t,s,h),u=ut.unitLuminance(n);let p=this.bodyMeshes.get(e);if(e==="sun"){const f=Math.PI*(i/_n)**2,g=[0,1,2].map(v=>u[v]*d[v]/(this.sunBeamFraction*f));this.sunDiscRadiance=g;const m=g.map(v=>Math.min(ut.BRIGHTEST_RELATIVE,v));p instanceof Ae||(this.disposeMesh(p),p=new Ae(new yi(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(p),this.bodyMeshes.set(e,p)),p.material.color.setRGB(m[0],m[1],m[2]),p.scale.setScalar(i)}else{if(!(p instanceof Vn)){this.disposeMesh(p);const m=new ct;m.setAttribute("position",new tt(new Float32Array(3),3)),m.setAttribute("color",new tt(new Float32Array(3),3)),p=new Vn(m,Ce.material(Ml[Ml.length-1].size,!1)),Ce.track(p),this.celestialGroup.add(p),this.bodyMeshes.set(e,p)}const f=p.geometry.getAttribute("color"),g=e.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*d[0]*g,u[1]*d[1]*g,u[2]*d[2]*g),f.needsUpdate=!0}if(p.position.set(r,o,l),this.setHitArea(e,r,o,l,i),e==="sun"&&(this.sunArriving=d),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,o,l,d,i/_n*(180/Math.PI),ut.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,o*f+this.celestialGroup.position.y,l*f),this.lensFlare||(this.lensFlare=O4(),this.lensFlare.uniforms.uOpacity.value=LR,this.lensFlare.uniforms.uFlareIntensity.value=this.lensFlareArtifactIntensity,this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyLensFlareTint(c)}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<Ld){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=jt(e.altitudeDeg,e.azimuthDeg,_n),o=this.cloudTransmission(e),l=this.arrivingIlluminance(e,e.magnitude,o),c=e.radiusDeg??cn.MEAN_RADIUS_DEG,h=_n*Math.tan(c*Pi),d=Math.max(yr(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/_n)**2,u=new se(...l.map(g=>Math.min(ut.BRIGHTEST_RELATIVE,g/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(yr(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof jl?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=Qb(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new jl(new Td({map:Qb(e.phase),color:u,fog:!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,l,c)}bentLight(e,t,i=wR){const[n,s,r]=this.arrivingIlluminance(e,t,1),o=Math.max(s,1e-30);return{scale:s/i,tint:[n/o,1,r/o]}}static litBySky(e,t){return ut.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new se;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,Ce.CONE_SOLID_ANGLE/t)}pointScratch=new xe;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=St.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=As.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 l=new Td({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new jl(l),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const o=s*2;r.scale.set(o,o,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,o=0){if(an.radiusDeg(an.K*Math.max(...s))<=Math.max(r,o)){this.disposeGlare(e);return}let l=this.glareSprites.get(e);l||(l=new an(`veil:${e}`),this.celestialGroup.add(l.mesh),this.glareSprites.set(e,l)),l.shine({x:t,y:i,z:n},s,r,o)}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=il(e.magnitude,t),s=nf(n);this.cometKey=i,this.setBodyMesh(i,e.position,yf*(.5+.5*n),new se(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new zn(_n),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new Xi,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:ld},0);return}const s=this.lowerCloudCover(),r=bt.deckLitUntilDeg(bt.DECK_HEIGHT_M),o=e.altitudeDeg>-r?e:t,l=this.bentLight(o,o===e?rt.SUN_MAGNITUDE:t.magnitude),c=bt.strength(i,s,o.altitudeDeg,r)*l.scale,{x:h,y:d,z:u}=jt(o.altitudeDeg,o.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},o.altitudeDeg,c,l.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??ld},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??Od)}buildRainbow(e,t){this.rainbow||(this.rainbow=new Ka,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(),o=this.bentLight(s,n?rt.SUN_MAGNITUDE:t.magnitude,xR),l=rn.strength(i,r,s.altitudeDeg)*o.scale;if(l<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:d}=jt(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},l,o.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Kr,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=Hn.galactic(i,n),r=ut.directionOf(s.centre),o=ut.directionOf(s.rotation),l=ut.directionOf(s.pole),c=new Ke().set(r.x,r.y,r.z,o.x,o.y,o.z,l.x,l.y,l.z),h=ut.directionOf(Hn.eclipticPole(i,n)),d=ut.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:ut.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:ce.phaseAngleOf(e.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new D(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:n}=jt(e.altitudeDeg,e.azimuthDeg,1);return new D(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=il(n.magnitude,t),o=nf(r);this.setBodyMesh(s,n.position,yf*(.5+.5*r),new se(o,o,o),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=il(n.magnitude,t),r=nf(s),o=QR[n.body]??new se(1,1,1),l=new se(o.r*r,o.g*r,o.b*r),c=yf*(.5+.5*s);this.setBodyMesh(n.body,n.position,c,l,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 Ss(n,s),o=Df(1337),l=[],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<Rb)continue;const{x:f,y:g,z:m}=jt(u,p,vf);l.push({x:f,y:g,z:m,brightness:il(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(v=>v*St.illuminanceOf(d)),phase:o()*Math.PI*2,speedFactor:.7+o()*.6})}for(const h of f4){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<Rb)continue;const{x:p,y:f,z:g}=jt(d,u,vf);this.namedStars.push({star:h,direction:new D(p,f,g).normalize(),altitudeDeg:d})}this.starTiers=Ml.map((h,d)=>{const u=l.filter(w=>rg(w.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),g=new Float32Array(u.length*3),m=new Float32Array(u.length),v=new Float32Array(u.length);u.forEach((w,S)=>{p[S*3]=w.x,p[S*3+1]=w.y,p[S*3+2]=w.z,f[S]=w.brightness,g.set(w.illuminance,S*3),m[S]=w.phase,v[S]=w.speedFactor});const x=new ct;x.setAttribute("position",new tt(p,3)),x.setAttribute("seed",new tt(m.map(w=>w/(2*Math.PI)),1));const y=new tt(new Float32Array(u.length*3),3);x.setAttribute("color",y);let b=this.starTiers[d]?.points;return b?(b.geometry.dispose(),b.geometry=x):(b=new Vn(x,Ce.material(h.size)),Ce.track(b),this.celestialGroup.add(b)),{points:b,colorAttribute:y,brightness:f,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){Ce.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 bl(this.celestialGroup,Mf,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 se(ya[0]+(Sf[0]-ya[0])*t,ya[1]+(Sf[1]-ya[1])*t,ya[2]+(Sf[2]-ya[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}=$0(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=Y0(Mf);this.cloudMesh=new Ae(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}=$0(new se(...ya),e,ld,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Ae(Y0(Mf*1.04),t),this.cirrusMesh.renderOrder=Fb-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?bl.deckOrder(!0,0,1):Fb}cloudLayerOffset(){const t=((this.weather.cloudBaseM??xm)-this.observerElevationM)*wf;return Math.sign(t||1)*Math.max(Math.abs(t),OR)}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,o]=this.cloudBeam.map(d=>d/Math.PI),l=this.lightningLevel*If*this.relativeScale/Math.PI,c=new se(t[0]+Us.r*l,t[1]+Us.g*l,t[2]+Us.b*l);this.layeredClouds?.setLighting(n.clone(),new se(s,r,o),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,o*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 VR(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,Af],[this.rainSplashSystem?.points,Ma],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:Ef[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=Hb(Tf(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=Ef[e],i=t.poolSize,n=Df(9001),s=new Float32Array(i*3),r=new Float32Array(i),o=new Float32Array(i),l=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 y=0;y<i;y++){const b=n()*Math.PI*2,w=n()*t.radiusM;s[y*3]=Math.cos(b)*w,s[y*3+1]=jo+n()*(t.topYM-jo),s[y*3+2]=Math.sin(b)*w,r[y]=n()*Math.PI*2,o[y]=.7+n()*.6,l[y]=.6+n()*.8,c[y]=.4+n()*1.2}const g=new ct;g.setAttribute("position",new tt(s,3)),g.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new se(...this.baseFogColor)},uTexture:{value:eC(e)},uNearFocusDistance:{value:Xb},uHazeDistance:{value:t.radiusM*$b}},v=new xt({uniforms:m,vertexShader:aC,fragmentShader:oC,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const x=new Vn(g,v);x.renderOrder=xf,this.scene.add(x),this.precipitationPoints=x,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=o,this.precipitationWobbleFreqJitter=l,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=Ef[i];if(this.precipitationUniforms?.uColor.value.copy(ut.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*Pi,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,o=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,l=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,x=i==="snow"&&d&&u,y=i==="hail"&&p&&f&&g&&m&&v;for(let b=0,w=0;b<l.length;b+=3,w++){if(y&&p[w]>0){if(p[w]-=t,p[w]<=0){const M=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;l[b]=Math.cos(M)*T,l[b+1]=n.topYM,l[b+2]=Math.sin(M)*T,p[w]=0}else{const M=1-p[w]/g[w];l[b+1]=jo+Math.sin(Math.PI*M)*f[w],l[b]=dd(l[b]+(r+m[w])*t,n.radiusM),l[b+2]=dd(l[b+2]+(o+v[w])*t,n.radiusM)}continue}let S=0,_=0;if(x){const M=XR*d[w],T=$R*u[w];S=Math.sin(e*M*Math.PI*2+c[w])*T,_=Math.sin(e*M*Math.PI*2+c[w]+Math.PI/2)*T}if(l[b]+=(r+S)*t,l[b+1]-=n.fallSpeedMPerS*h[w]*t,l[b+2]+=(o+_)*t,l[b]=dd(l[b],n.radiusM),l[b+2]=dd(l[b+2],n.radiusM),l[b+1]<jo){if(y){f[w]=jb*(.2+Math.random()*1.6),g[w]=YR*(.5+Math.random()),p[w]=g[w];const A=Math.random()*Math.PI*2,R=qR*(f[w]/jb);m[w]=Math.cos(A)*R,v[w]=Math.sin(A)*R,l[b+1]=jo;continue}const M=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;l[b]=Math.cos(M)*T,l[b+1]=n.topYM,l[b+2]=Math.sin(M)*T}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=Tf(this.weather.precipitationIntensity);this.rainSystem=C4({count:Af,radiusM:hc,heightM:FR,bottomYM:Ub,overallSpeed:UR,color:zb.clone(),opacity:.85,visibleCount:this.precipitationCount(Af),speedStreak:Hb(e),pixelSize:qb,seed:9001,nearFocusDistanceM:Xb,hazeDistanceM:hc*$b,hazeColor:new se(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=xf,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=Df(4242),t=new Float32Array(Ma*3),i=new Float32Array(Ma),n=new Float32Array(Ma),s=new Float32Array(Ma);for(let h=0;h<Ma;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*hc;t[h*3]=Math.cos(d)*u,t[h*3+1]=Ub,t[h*3+2]=Math.sin(d)*u,n[h]=Jb(Gb,Vb),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new ct;r.setAttribute("position",new tt(t,3));const o=new tt(s,1);r.setAttribute("aLife",o),r.setDrawRange(0,this.precipitationCount(Ma));const l=new xt({uniforms:{uMaxSize:{value:GR},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:Wb.clone()},uTexture:{value:nC()}},vertexShader:sC,fragmentShader:rC,transparent:!0,depthWrite:!1}),c=new Vn(r,l);c.renderOrder=xf,this.scene.add(c),this.rainSplashSystem={points:c,positions:t,life:i,duration:n,lifeAttribute:o}}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*Pi;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-Tf(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(ut.litBySky(zb,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(ut.litBySky(Wb,this.baseFogColor));const n=this.weather.windDirectionDeg*Pi,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,o=hc,l=h=>(h%(o*2)+o*3)%(o*2)-o;t.uniforms.uWindOffset.value.set(l(t.uniforms.uWindOffset.value.x+s*e),l(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=Kb+(1-Kb)*(1-c),d=Zb+(1-Zb)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=qb*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,o=r.array;for(let l=0,c=0;l<i.length;l+=3,c++){if(n[c]+=e,n[c]>=s[c]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*hc;i[l]=Math.cos(h)*d,i[l+2]=Math.sin(h)*d,s[c]=Jb(Gb,Vb),n[c]=0}o[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 l of this.lightningFlashes){if(l.t>e)break;const c=Oi.brightnessAt(l,e);c>i&&(t=l,i=c)}const n=t?Math.min(1,Math.max(.1,(jR/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 l=this.scene.fog,c=s*If*this.relativeScale/Math.PI;l.color.setRGB(this.airlight[0]+Us.r*c,this.airlight[1]+Us.g*c,this.airlight[2]+Us.b*c)}const r=this.skyMesh?.material?.color;if(r){const l=s*JR;r.setRGB(1+l*Us.r,1+l*Us.g,1+l*Us.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*If*this.relativeScale,t){const{x:l,y:c,z:h}=jt(25,t.azimuthDeg,_n);this.lightningLight.position.set(l,c,h)}this.lightningBolt||(this.lightningBolt=new Zr(_n*.95),this.celestialGroup.add(this.lightningBolt.object));const o=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,o),this.render()}buildCompassLabels(){this.compassSprites=AR.map(e=>{const t=so.point(e,this.compassPoints),i=new Td({map:lC(t),depthTest:!1,fog:!1}),n=new jl(i),{x:s,y:r,z:o}=jt(0,e,Lb);return n.position.set(s,r,o),n.scale.set(hd,hd,1),n.renderOrder=DR,n.layers.set(mf),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=kb*Math.PI/360,i=hd*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 Pi=Math.PI/180;function yr(a,e,t){return Math.max(e,Math.min(t,a))}function Jb(a,e){return a+Math.random()*(e-a)}function dd(a,e){return(a%(e*2)+e*3)%(e*2)-e}let ud,pd;function eC(a){switch(a){case"snow":return tC();case"hail":return iC()}}function tC(){if(ud)return ud;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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,a,a),ud=new Cr(e),ud}function iC(){if(pd)return pd;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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,a,a),pd=new Cr(e),pd}let fd;function nC(){if(fd)return fd;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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,a,a),fd=new Cr(e),fd}const sC=`
|
|
9586
|
+
`,transparent:!0,blending:Bi,depthWrite:!1,side:ni,fog:!1});this.object=new Ae(new yi(bg.RADIUS,128,32,0,Math.PI*2,0,St.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<St.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=jn.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=jn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class ku{constructor(e){this.generator=e}static SIZE=128;target=new Zc(ku.SIZE,{type:Jt,generateMipmaps:!1,minFilter:gt,magFilter:gt});camera=new eg(.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(l=>{const c=l;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?s:!1;const o=n.map(l=>l.visible);for(const l of n)l.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),n.forEach((l,c)=>{l.visible=o[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 Pn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){Pn.install(),this.generator=new G0(e),this.eye=new ku(this.generator)}static decor;refresh(e,t,i,n,s,r,o,l=[],c,h=Pn.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const d=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new ku(this.generator),this.probes.set(m.id,v)),d.push({probe:v,reflector:m})}const u=performance.now(),p=()=>d.filter(({probe:m})=>m.capturedVersion!==o),f=p().filter(({probe:m})=>u-m.capturedAtMs>=h);if(f.length>0){const m=f.reduce((v,x)=>x.probe.capturedAtMs<v.probe.capturedAtMs?x:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(e,t,v,[m.reflector.holder,...s]),Pn.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(e,t,i,[...s,...l]),c?.(m.probe.sharp),Pn.decor=m.probe.filtered;for(const v of r)Pn.reflectOn(v,m.probe);for(const v of n)v.shiny||Pn.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=o}const g=p();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>h-(u-m.capturedAtMs))))}scratch=new D;static reflectOn(e,t={filtered:Pn.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof eh?t.sharp&&s.setSurroundings(t.sharp):s instanceof Qr&&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(Pn.installed)return;Pn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!Je.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}Je.lights_fragment_maps=Je.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function fR(a,e){return JSON.stringify(a.cloudLayers)===JSON.stringify(e.cloudLayers)&&a.cloudCover===e.cloudCover&&a.cloudDarkness===e.cloudDarkness&&a.cloudBaseM===e.cloudBaseM&&a.highCloudCover===e.highCloudCover&&a.iceCrystalAlignment===e.iceCrystalAlignment&&a.lowerCloudCover===e.lowerCloudCover&&a.relativeHumidity===e.relativeHumidity&&a.precipitationType===e.precipitationType&&a.precipitationIntensity===e.precipitationIntensity&&a.precipitationAmount===e.precipitationAmount&&a.windDirectionDeg===e.windDirectionDeg&&a.windSpeed===e.windSpeed&&a.storm===e.storm}const od=900,ff=1,Ab=4,mf=5,Tb=.5,xc=900,mR=6371e3,gR=3e4;function Ib(a){const e=Math.sqrt(2*mR*Math.max(a,0));return Math.max(xc,Math.min(e,gR))}const gf=.5,vf=850,bf=.03,vR=.015,_n=850,cc=300,Vr=120,bR=700,yR=.04,Db=4,yf=1.5,Rb=-1,MR=.01,Ld=-4,wR=2,xR=20,ld=2600,SR=.97,ER=.38,cd=Ld,Cb=1500,_R=400,AR=[0,45,90,135,180,225,270,315],TR=2,IR=16,Pb=4e3,Lb=880,hd=40,kb=60,DR=10,RR=1,CR=150,PR=55,LR=.5,kR=17,Ob=.265,Nb=[[0,0],...Array.from({length:8},(a,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*Ob,Math.sin(t)*Ob]})],Mf=700,wf=250/xm,OR=12,Fb=5,xf=6,ya=[.92,.92,.95],Sf=[.15,.15,.19],Ef={snow:{fallSpeedMPerS:2,size:.3,color:new se(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new se(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},jo=0,_f=0,NR=150,Af=3e3,hc=20,FR=15,Ub=jo,UR=40,Bb=1,BR=9;function Tf(a){return Bb+(BR-Bb)*a}const zb=new se(.75,.82,.92),zR=10,HR=.5;function Hb(a){return yr(a/zR,HR,1)}const Ma=200,Gb=.18,Vb=.32,GR=.35,Wb=new se(.85,.9,.98),Xb=5,$b=.85,Yb=.01;function VR(a,e,t=1){return Math.round(a*(Yb+(1-Yb)*e)*t)}function WR(a,e){return JSON.stringify(a.cloudLayers)===JSON.stringify(e.cloudLayers)&&a.cloudCover===e.cloudCover&&a.cloudDarkness===e.cloudDarkness&&a.cloudBaseM===e.cloudBaseM&&a.highCloudCover===e.highCloudCover&&a.iceCrystalAlignment===e.iceCrystalAlignment&&a.lowerCloudCover===e.lowerCloudCover}const qb=230,Kb=.7,Zb=.05,XR=.6,$R=.7,YR=.15,jb=.35,qR=3,KR=1/12,ZR=.5,Us=new se(.82,.86,1),jR=2500,JR=1.6,If=15,QR={Venus:new se(1,.96,.85),Mars:new se(1,.55,.4),Jupiter:new se(.95,.87,.72),Saturn:new se(.92,.86,.68)};class ut{renderer;scene=new rr;phenomena=new ys(this.scene);references=new bs(this.scene,()=>this.render());camera;celestialGroup=new Ct;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;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()+Pb,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),Pb+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new is;roadAttribution;roadWays;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new xe;decorModelProvider=Pd[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new pt(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??ut.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*ut.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new g1(16777215,0);celestialLightTarget=new Qt;skyLight=new d3(16777215,0,0);streetlightLights=new Map;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new Id;weather=Vu;observerElevationM=0;siteElevationM=0;air=new rs;groundRadius=xc;terrainRadius=xc;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new D;cloudFieldOffset=new D;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new D;rainLastVerticalFacing=-1;rainViewportSize=new xe;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new g1(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new Id;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new Id;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;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;iceHalos;lunarDiffraction;eclipsedSun=new th;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=lS()){this.renderer=new AI({canvas:e,antialias:!0}),this.resolution=new Dt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Ec,this.camera=new Ln(60,e.width/Math.max(e.height,1),.1,od*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=-Vr,this.celestialLight.shadow.camera.right=Vr,this.celestialLight.shadow.camera.top=Vr,this.celestialLight.shadow.camera.bottom=-Vr,this.celestialLight.shadow.camera.near=_n-cc,this.celestialLight.shadow.camera.far=_n+cc,this.celestialLight.shadow.bias=-.03/(2*cc),this.celestialLight.shadow.normalBias=yR,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Us),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);const i=new rt(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}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*wf,0,e.z*wf);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)*Di,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Di;if(e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Di,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(Ib(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/xc),this.camera.far=Math.max(od*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),this.terrainMesh&&this.terrainOrigin&&e.lat!==void 0&&e.lng!==void 0){const n=ci(this.terrainOrigin.lat,this.terrainOrigin.lng,e.lat,e.lng);this.terrainMesh.position.x=n.x,this.terrainMesh.position.z=n.z}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.terrainOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const n=this.groundRadius;if(this.terrainOrigin&&Math.abs(this.terrainRadius-n)<n*.1){const{x:l,z:c}=ci(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(l*l+c*c)<CR*(n/xc))return}const s=this.terrainOrigin,r=this.terrainRadius;(!s||s.lat!==e||s.lng!==t)&&(this.roadSystem.clear(),this.roadAttribution=void 0),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=n;const o=++this.terrainBuildToken;this.awaitArrival(y4(e,t,this.terrainProviders,n),ut.TERRAIN_PATIENCE_MS).then(({mesh:l,attribution:c,originElevationM:h})=>{if(o!==this.terrainBuildToken)return;this.setSiteElevation(h??0);const d=this.terrainMesh,u=s?ci(e,t,s.lat,s.lng):void 0;d&&u&&Math.hypot(u.x,u.z)<=r&&(l.position.y=d.position.y+this.groundYOfPatch(d,u.x,u.z)),d&&u&&Math.hypot(u.x,u.z)<=r?this.crossfadeTerrain(l,d):this.disposeMesh(this.terrainMesh),l.renderOrder=RR,this.terrainMesh=l,this.compileNextFrameOffThread(),this.terrainAttribution=c,this.scene.add(l),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,n),this.drapeStatedRoads(),this.drapeTraces(),this.render(),i?.()}).catch(l=>{console.warn("Terrain build failed, keeping the flat ground fallback:",l),i?.()})}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t){this.stopTerrainFade();const i=e.material;i.opacity=0,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-4;const n=performance.now(),s=()=>{const r=Math.min(1,(performance.now()-n)/ut.TERRAIN_CROSSFADE_MS);if(i.opacity=r*r*(3-2*r),this.render(),r<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(s);return}i.polygonOffset=!1,i.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:t,frameId:requestAnimationFrame(s)}}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=5e3;buildRoads(e,t,i){const n=this.terrainProviders.roads;if(!n||i>ut.ROADS_MAX_RADIUS_M){this.roadSystem.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}this.awaitArrival(n.getRoads(Sw(e,t,i)),ut.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)})}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.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??=je(async()=>{const{TraceSystem:e}=await import("./TraceSystem-DCqCjgtt.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(mf);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainOrigin;!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)))}drapeRoads(e,t,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.set(e,t,i,(r,o)=>this.groundYOfPatch(s,r,o),n),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;applyLensFlareTint(e){if(!this.lensFlare)return;const t=PR*(this.sunArriving[1]/kR);this.lensFlare.uniforms.uColorGain.value.setRGB(t*e[0],t*e[1],t*e[2]),this.applyDazzleStrength()}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=an.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(fR(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!WR(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=rs.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Sr.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>=ZR,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects!==e){this.decorObjects=e,this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const t of this.decorGroups.values())t.removeFromParent(),$t.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear();for(const t of e){const i=$t.build(t,t.lit??!1);this.scene.add(i),this.decorGroups.set(t.id,i),t.kind==="streetlight"&&this.addStreetlightLight(t.id,i),t.model&&t.id.startsWith(as.ID_PREFIX)?(this.pendingTrafficModels.set(t.id,t),this.awaitArrival(this.loadDecorModel(t,this.decorModelToken,!0))):this.reuseLoadedDecorModel(t,i)||this.awaitArrival(this.loadDecorModel(t,this.decorModelToken))}this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}}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??=je(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-oqsCCklf.js");return{ContrailSystem:e}},__vite__mapDeps([0,1]),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=ut.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(t&&i){const o=Xn.litFraction(t.sunElevationDeg,t.heightM);if(o>0){const l=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=St.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*c*l[h]*o}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);updateContrails(){this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad()},e=>this.contrailTint(e))}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}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);return{heightAt:(n,s)=>this.groundYUnder(e+n,t-s)-i}}setBodies(e,t=0,i=e.map(r=>r.id),n=[],s){const{x:r,z:o}=this.bodyOrigin,l=this.scatteredSky;this.bodySystem.set(e,{originX:r,originZ:o,originGroundY:this.groundYUnder(r,o),eye:this.camera.position,groundYAt:(h,d)=>this.groundYUnder(h,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(h,d,u)=>this.transmittanceTo(h,d,u)},t,l?(h,d)=>l.relativeOfLuminance(h,d):void 0,i),this.bodySystem.setSmoke(n,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const c=this.bodySystem.furthestFrom(this.camera.position)*1.2;c>this.camera.far&&(this.camera.far=c,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=(o,l,c)=>(o*t+(l+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 pf(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(lu(e))||!$t.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const n=i.scene.clone(!0);n.traverse(s=>{s instanceof Ae&&(s.userData.sharedModel=!0)}),$t.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?ou[e.kind]:lu(e);if(!(!n||!$t.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,o=n.credit??s?.credit;if(!r||!o)return;const l=i?await this.standInScene(r):await pf(r);if(t!==this.decorModelToken||i&&!this.pendingTrafficModels.has(e.id))return;const c=this.decorGroups.get(e.id);if(!c)return;i||Pn.reflectOn(l);const h={ref:JSON.stringify(n),scene:l,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:o};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=pf(e).then(i=>(Pn.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?ci(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(d=>d.observerSide!==void 0&&eo(d.kind));if(this.terrainMesh&&this.terrainOrigin&&t?.lat!==void 0&&t.lng!==void 0){const d=ci(this.terrainOrigin.lat,this.terrainOrigin.lng,t.lat,t.lng);this.terrainMesh.position.x=d.x-(s?0:this.gaitOffset.eastM),this.terrainMesh.position.z=d.z+(s?0:this.gaitOffset.northM),this.roadSystem.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 o=0,l;if(s){const d=tr(s,i),u=$t.occupantView(s,d.headingDeg),p=-(d.headingDeg??0)*Di,f=u.x*Math.cos(p)+u.z*Math.sin(p),g=-u.x*Math.sin(p)+u.z*Math.cos(p),m=d.eastM+n.x,v=-d.northM+n.z;r.x=-(m+f),r.z=-(v+g),this.camera.position.y=this.groundYUnder(m,v)+u.eyeY,l=u.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Di,-(u.headingDeg+this.indoorLookYawDeg)*Di,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z},this.placeShadowFrustum(),this.placeTerraces(i,n,r);const c=this.terraces.map(d=>[d.x,d.z,d.cos,d.sin,d.halfWidthM,d.halfLengthM,d.levelY].map(u=>u.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 d of this.decorObjects){if(d.kind==="terrace")continue;const u=this.decorGroups.get(d.id);if(!u)continue;const p=tr(d,i),f=p.eastM+n.x+r.x,g=-p.northM+n.z+r.z,m=this.terrainMesh,v=`${m?.geometry.uuid}:${(f-(m?.position.x??0)).toFixed(3)}:${(g-(m?.position.z??0)).toFixed(3)}:${(m?.position.y??0).toFixed(3)}:${p.headingDeg}:${p.altitudeM}:${c}`;if(u.userData.footprintKey!==v&&(u.userData.footprintGroundY=this.groundUnderFootprint(d,f,g,p.headingDeg,p.altitudeM),u.userData.footprintKey=v),u.position.set(f,u.userData.footprintGroundY+p.altitudeM,g),d.kind==="crop"){const w=Math.hypot(f,g);u.visible=w<=NR}const x=this.decorPresence.get(d.id),y=x!==void 0&&(i<x.fromMs||i>x.untilMs);x&&(u.visible=!y);const b=this.decorSunlight.get(d.id);if(b&&!y&&this.lightFromAbove(u,b),p.headingDeg!==void 0&&(u.rotation.y=-p.headingDeg*Di),d.kind==="crop"&&u.visible){const w=this.terrainMesh,S=[w?.geometry.uuid,f-(w?.position.x??0),g-(w?.position.z??0),u.position.y-(w?.position.y??0),p.headingDeg,p.altitudeM].map(_=>typeof _=="number"?_.toFixed(4):_).join(":");u.userData.cropGroundKey!==S&&($t.fitCropToGround(u,(_,M)=>this.groundYUnder(_,M)+p.altitudeM),u.userData.cropGroundKey=S)}if(!y){const w=u.position.distanceTo(this.camera.position);o=Math.max(o,w),w<ut.trafficModelRangeM(d)&&this.pendingTrafficModels.delete(d.id)&&this.loadDecorModel(d,this.decorModelToken)}}if(s&&l!==void 0){const d=this.decorGroups.get(s.id);d&&(this.camera.position.y=d.position.y+l)}this.updateContrails();const h=Math.max(od*1.2,this.groundRadius*2.5,o*1.2);Math.abs(this.camera.far-h)>1&&(this.camera.far=h,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,o=t-s.z,l=r*s.cos-o*s.sin,c=r*s.sin+o*s.cos;if(Math.abs(l)<=s.halfWidthM&&Math.abs(c)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(l))/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 o=tr(s,e),l=o.eastM+t.x+i.x,c=-o.northM+t.z+i.z,h=$t.sizeOf(s),d=-(o.headingDeg??0)*Di,u=Math.cos(d),p=Math.sin(d),f=`${n?.geometry.uuid}:${(l-(n?.position.x??0)).toFixed(3)}:${(c-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${o.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(l,0,c),o.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=$t.fitTerrace(r,s,(g,m)=>this.terrainYUnder(l+g*u+m*p,c-g*p+m*u)),r.userData.terraceKey=f),this.terraces.push({x:l,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):_f}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 _f;const r=n.getX(0),o=n.getX(s-1),l=n.getZ(0),c=n.getZ((s-1)*s),h=yr((t-r)/(o-r)*(s-1),0,s-1),d=yr((i-l)/(c-l)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(d))return _f;const u=Math.min(Math.floor(h),s-2),p=Math.min(Math.floor(d),s-2),f=h-u,g=d-p,m=(w,S)=>n.getY(w*s+S),v=m(p,u),x=m(p,u+1),y=m(p+1,u),b=m(p+1,u+1);return f+g<=1?v+(x-v)*f+(y-v)*g:b+(y-b)*(1-f)+(x-b)*(1-g)}groundUnderFootprint(e,t,i,n,s=0){return $t.groundUnderFootprint(e,t,i,n,(r,o)=>this.groundYUnder(r,o),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}medium;setMedium(e,t,i,n){const s=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:n??e.iso,autoExposure:e.autoExposure===!0,exposureSeconds:t,fNumber:i}:void 0;JSON.stringify(s)!==JSON.stringify(this.medium)&&(this.medium=s,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30);if(!e){Mn.uMedium.value=0;return}Mn.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const i=e.autoExposure?this.scatteredSky?.sceneAdaptation:void 0;Mn.uMediumExposure.value=i!==void 0&&i>0?1/(t*i):.065*e.exposureSeconds*e.iso*this.filterTransmittance/(e.fNumber*e.fNumber*t)}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 xe;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))}updateDecorLitState(e,t=0){const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&$t.setLights(s,n.lights,e,s.position.distanceTo(this.camera.position),t,this.relativeScale,i,this.lampTransmittance(s)),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const o=cu(n,e);$t.setLit(r,n.kind,o,this.relativeScale);const l=this.streetlightLights.get(n.id);l&&(l.visible=o)}}addStreetlightLight(e,t){const i=$t.bodyOf(t),n=i.children.find(r=>r.userData.emissive);if(!n)return;const s=new BM(16764006,Cb*this.relativeScale,_R);s.position.copy(n.position).multiply(i.scale),s.castShadow=!0,s.shadow.mapSize.set(512,512),s.shadow.bias=-.002,t.add(s),this.streetlightLights.set(e,s)}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.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 o=As.luminanceOf(r);if(!(o>0))return[0,0,0];const l=Ie.relativeOfResponse(o)/o;return[r[0]*l,r[1]*l,r[2]*l]},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=bi.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,Db,new se(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<Ld){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=Db/_n*(180/Math.PI),n=i/t.sunRadiusDeg,s=jt(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=jt(e.moon.altitudeDeg,e.moon.azimuthDeg,1),o=Math.acos(yr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),l=o>1e-9?yr(t.separationDeg*n*Di/o,0,2):0,c=Math.sin(o),[h,d]=o>1e-9?[Math.sin((1-l)*o)/c,Math.sin(l*o)/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 D(s.x,s.y,s.z).normalize(),moon:new D(u.x,u.y,u.z).normalize(),sunRadiusRad:i*Di,moonRadiusRad:p*Di};const f=.01,g=(x,y)=>jt(e.sun.altitudeDeg+x,e.sun.azimuthDeg+y,1),m={x:g(f,0).x-g(-f,0).x,y:g(f,0).y-g(-f,0).y,z:g(f,0).z-g(-f,0).z},v={x:g(0,f).x-g(0,-f).x,y:g(0,f).y-g(0,-f).y,z:g(0,f).z-g(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:n,up:m,right:v}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new al(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));const t=this.scatteredSky?.ambient??ut.relativeSkyOf(j0(e.sun.altitudeDeg),this.relativeScale),i=t,n=this.lightUnderClouds(e),s=r=>n?[0,1,2].map(o=>r[o]*n.through+n.radiance[o]*(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),Ce.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=Cb*this.relativeScale;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?Be.DEFAULT_AEROSOL_OPTICAL_DEPTH:Sr.opticalDepth(i))*Be.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),o=St.aureoleScale(n,St.airMass(e.altitudeDeg))*s,l=St.coronaScale(r),c=St.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),o.toExponential(2),l.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 bg,this.celestialGroup.add(this.lunarDiffraction.object));const d=St.profile(St.HAZE_COARSE_MODE),u=St.profile(St.CLOUD_DROPLETS),p=q1(e.altitudeDeg),f=new Float32Array(St.STEPS*3);let g=0;for(let y=0;y<St.STEPS;y++){const b=y*3,w=[0,1,2].map(_=>c*p[_]*(o*d[b+_]+l*u[b+_])),S=As.shown(w,As.luminanceOf(w),(_,M)=>t.relativeOfLuminance(_,M));f.set(S,b),g=Math.max(g,As.response(S))}const{x:m,y:v,z:x}=jt(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(g>1/200?{x:m,y:v,z:x}:void 0,f)}applyAir(){this.scene.fog instanceof ao||(this.scene.fog=new ao),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,ut.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:bi.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?bi.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:ce.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?IR:TR),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 N4(vf),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):sa(-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 Tn,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):sa(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}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(bf*this.camera.fov*Math.PI/180);let s,r=n;const o=new D;for(const[l,c]of this.decorGroups){if(!c.visible||!l.startsWith(as.ID_PREFIX))continue;o.copy(c.position).sub(this.camera.position).normalize();const h=o.dot(i);h>r&&(r=h,s=l)}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(bf*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>=cd,s=!n&&e.moon.altitudeDeg>=cd,r=n?e.sun:e.moon,o=[0,0,0],l=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Di)),c=n||s?this.cloudTransmission(r):1,h=-Math.log(Math.max(c,1e-6)),d=Math.max(0,1/(1+.1125*h)-c),u=[0,0,0];if(n||s){const x=St.illuminanceOf(r.magnitude)*i,y=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,r.altitudeDeg);for(let _=0;_<3;_++)o[_]=x*y[_]*c,u[_]=x*y[_]*d*l,this.cloudBeam[_]=x*y[_];const{x:b,y:w,z:S}=jt(r.altitudeDeg,r.azimuthDeg,1);this.cloudBeamDirection.set(b,w,S)}else this.cloudBeam.fill(0);const p=this.surroundings;if(p)this.skyLight.color.setRGB(p.up[0]*i,p.up[1]*i,p.up[2]*i),this.skyLight.groundColor.setRGB(p.down[0]*i,p.down[1]*i,p.down[2]*i);else{const x=this.skyCloudTransmission(),y=t.skyIrradiance,b=[0,1,2].map(S=>y[S]*x+u[S]);this.skyLight.color.setRGB(b[0],b[1],b[2]);const w=We.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(w*(b[0]+o[0]*l),w*(b[1]+o[1]*l),w*(b[2]+o[2]*l))}if(this.skyLight.intensity=1,this.sceneSunBeam=n?[o[0],o[1],o[2]]:[0,0,0],!n&&!s){this.celestialLight.intensity=0;return}const{x:f,y:g,z:m}=jt(r.altitudeDeg,r.azimuthDeg,1);this.lightDirection.set(f,g,m),this.placeShadowFrustum();const v=Math.max(o[0],o[1],o[2],1e-30);this.celestialLight.color.setRGB(o[0]/v,o[1]/v,o[2]/v),this.celestialLight.intensity=v,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=Xn.litFraction(t.sunElevationDeg,t.heightM);if(s>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),o=St.illuminanceOf(i.magnitude)*this.relativeScale,l=t.heightM>=ut.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)n[c]=Math.max(0,o*r[c]*s*l-this.sceneSunBeam[c])}}e.traverse(s=>{const r=s.material;if(!(r instanceof Nl||r instanceof Qr)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const o=ut.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*o,r.color.g*n[1]*o,r.color.b*n[2]*o)})}lightDirection=new D(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,0,this.bodyOrigin.z),o=c=>{const h=r.dot(c)/i;return(h-Math.round(h))*i},l=this.celestialLightTarget.position.set(0,0,0).addScaledVector(n,o(n)).addScaledVector(s,o(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(l).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToBodies(){const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(bR,Math.max(Vr,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(cc,t*(cc/Vr));this.shadowLightDistanceM=Math.max(_n,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*Vr?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=Vr;shadowLightDistanceM=_n;shadowUp=new D(0,1,0);shadowAxisX=new D;shadowAxisY=new D;shadowWorld=new D;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const n=i*Di,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 D(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Ie.semiSaturation(Ie.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new Wi,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=Rt.starPointsOf(e),i=Rt.flareArtifactsOf(e);t===this.starPoints&&i===this.lensFlareArtifactIntensity||(this.starPoints=t,this.lensFlareArtifactIntensity=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=t,this.lensFlare.uniforms.uFlareIntensity.value=i),this.render())}magnitudeLimitOf(e){const t=ce.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return sa(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{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()+ut.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of e){const o=t.get(r)?.currentProgram;(!o||o.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()}refreshReflections(e=!1){this.reflections??=new Pn(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(o=>o.mesh)],i=[...this.starTiers.map(o=>o.points),...[...this.bodyMeshes.values()].filter(o=>o instanceof Vn),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(o=>o!==void 0)],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values()],s,i,o=>this.measureSurroundings(o,n,s),e?0:Pn.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))}measureSurroundings(e,t,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new Ic;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>jt(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,s,r=>{const o=p=>p.map(f=>f/t),l=this.surroundings,c={up:o(r.up),down:o(r.down)},h=(p,f)=>p.some((g,m)=>Math.abs(g-f[m])>.03*Math.max(Math.abs(g),Math.abs(f[m]),1e-12)),d=!l||h(l.up,c.up)||h(l.down,c.down);d&&(this.surroundings=c),this.eyeSettledVersion=-1;const u=this.scatteredSky?.adaptToSurroundings(Math.exp(r.logAverage)/t)??!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>=cd?e.sun:e.moon.altitudeDeg>=cd?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,KR);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.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,o,l)=>this.directionAtScreenPoint(r,o,l),r=>this.screenPointOf(r)),this.references.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references.furthestM)*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 Vn&&t.userData.pointSource||t instanceof Ae&&t.userData.skyRibbon)&&e.push(t)}),e},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(mf),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(Lw),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 On({blending:nh,blendSrc:vc,blendDst:vc,blendSrcAlpha:vc,blendDstAlpha:vc,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(Ow),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){this.references.set(e.map(i=>{const n=this.documentRelative(i.src);return n===i.src?i:{...i,src:n}}),void 0,t)}referenceAspect(e){return this.references.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new D)}referenceFailedToLoad(e){return this.references.failedToLoad(this.documentRelative(e))}setReferencesShown(e){this.references.setShown(e),this.render()}setReferenceView(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&&ut.markDecorDepth(s,n.kind!=="crop")}e.layers.set(ff),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(kw),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new On({colorWrite:!1});static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Ae))return;const n=Array.isArray(i.material)?i.material[0]:i.material;t&&n.depthWrite!==!1&&n.blending!==Bi?i.layers.enable(ff):i.layers.disable(ff)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new xe),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new NI(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()+ut.EXPOSURE_BUDGET_MS,s=ut.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const o=this.compassSprites.map(l=>l.visible);for(const l of this.compassSprites)l.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((l,c)=>{l.visible=o[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(){if(Mn.uRodShare.value=this.scatteredSky?.rodShare??0,Mn.uHasOverlay.value=1,Mn.uRelativeScale.value=this.relativeScale,this.applyMedium(),this.exposureAccumulation?.develop(this.renderer,this.exposureInstants/this.exposureInstantsDone),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(s=>s.visible))return;const e=new rr,t=new Rs(-1,1,1,-1,0,2),i=hd/(Lb*Math.tan(kb*Di/2));for(const s of this.compassSprites){if(!s.visible)continue;const r=s.getWorldPosition(new D).sub(this.camera.position).normalize(),o=this.screenPointOf(r);if(!o)continue;const l=new jl(s.material);l.position.set(o.ndcX,o.ndcY,-1),l.scale.set(i/this.camera.aspect,i,1),e.add(l)}const n=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(e,t)}finally{this.renderer.autoClear=n}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const e=[],t=new un,i=new D,n=this.camera.getWorldDirection(new D),s=this.decorObjects.filter(o=>o.track?.length||o.kind==="aircraft"||o.kind==="vehicle").map(o=>this.decorGroups.get(o.id)),r=this.bodySystem.reflectors.map(o=>o.holder);for(const o of[...s,...r]){if(!o?.visible||(t.setFromObject(o),t.isEmpty())||t.distanceToPoint(this.camera.position)<ut.MAP_SUBJECT_NEAREST_M)continue;let l=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 g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;l=Math.min(l,m),c=Math.max(c,m),h=Math.min(h,v),d=Math.max(d,v)}l=Math.max(l,0),c=Math.min(c,1),h=Math.max(h,0),d=Math.min(d,1),c>=l&&d>=h&&e.push({x:l,y:h,width:c-l,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 xe),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new Rc(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new xe);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new vg(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new xe);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new ti(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new xe(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 D)}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 ti.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*Di);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new D;screenPointQuaternion=new dn;screenPointSize=new xe;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)}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(Ab),this.camera.layers.set(Ab),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 Nb)this.isSunOccluded(t[0],t[1])||e++;return e/Nb.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 o=Math.PI/180,l=this.sunOcclusionRightScratch.set(n.z,0,-n.x);l.lengthSq()<1e-9&&l.set(1,0,0),l.normalize();const c=this.sunOcclusionUpScratch.crossVectors(l,n).normalize();n.addScaledVector(l,e*o).addScaledVector(c,t*o).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 m=(s.position.y-e.y)/t.y;if(m>n&&m<i){const v=e.x+t.x*m-s.position.x,x=e.z+t.z*m-s.position.z;if(Math.hypot(v,x)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const o=r.geometry.getAttribute("position"),l=Math.round(Math.sqrt(o.count));if(l<2||l*l!==o.count)return!1;const c=[r.position.x+o.getX(0),r.position.x+o.getX(l-1)],h=[r.position.z+o.getZ(0),r.position.z+o.getZ((l-1)*l)],d=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(l-1);if(!(d>0))return!1;let u=n,p=i;for(const[m,v,x]of[[e.x,t.x,c],[e.z,t.z,h]]){const y=Math.min(x[0],x[1]),b=Math.max(x[0],x[1]);if(Math.abs(v)<1e-12){if(m<y||m>b)return!1;continue}const w=(y-m)/v,S=(b-m)/v;u=Math.max(u,Math.min(w,S)),p=Math.min(p,Math.max(w,S))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),g=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let m=0;m<=g;m++){const v=u+(p-u)*m/g,x=e.x+t.x*v,y=e.y+t.y*v,b=e.z+t.z*v;if(y<=this.groundYUnder(x,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=Tb;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const o=this.decorGroups.get(r.id);if(!o)continue;const l=this.ufoOcclusionRaycaster.intersectObject(o,!0)[0];l&&(r.occludesSourceIds?.includes(i)?n=n===void 0?l.distance:Math.max(n,l.distance):s=s===void 0?l.distance:Math.min(s,l.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=MR*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,d])=>{const u=d.getWorldPosition(new D).sub(i);return{key:h,direction:u.clone().normalize(),radiusRad:Math.atan2(d.scale.x/2,u.length())}}),o=this.eclipseDiscs,l=o?[{key:"sun",direction:o.sun,radiusRad:o.sunRadiusRad},{key:"moon",direction:o.moon,radiusRad:o.moonRadiusRad,inFront:!0}]:[],c=ut.nearestBody(n,[...r.filter(h=>!o||h.key!=="sun"&&h.key!=="moon"),...l],s);if(c)return this.groundHides(e,t)?void 0:c}static nearestBody(e,t,i){let n,s=1/0,r=1/0,o=!1;for(const l of t){const c=Math.acos(yr(l.direction.dot(e),-1,1))-l.radiusRad;if(c>i)continue;const h=c<=0,d=s<=0,u=l.inFront===!0;(h!==d?h:h?u!==o?u:l.radiusRad<r:c<s)&&(n=l.key,s=c,r=l.radiusRad,o=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=vR*this.camera.fov*Math.PI/180,o=[...this.decorGroups.values()],l=o.length>0?ut.firstSolid(this.raycaster.intersectObjects(o,!0))?.distance:void 0;let c,h=1/0;const d=new un,u=new D;for(const p of i){if(d.setFromObject(p),d.isEmpty())continue;d.getCenter(u);const f=d.getSize(new D).length()/2,g=u.clone().sub(s),m=g.length();if(m===0||g.dot(n)<=0||l!==void 0&&l<m-f)continue;const v=Math.acos(Math.min(1,g.normalize().dot(n))),x=Math.max(r,Math.atan(f/m));v<=x&&x<h&&(h=x,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(bf*this.camera.fov*Math.PI/180);let s,r=n;for(const o of this.namedStars){const l=o.direction.dot(i);l>r&&(r=l,s={star:o.star,altitudeDeg:o.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,Tb)}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 o=0;o<8;o++){const l=this.bodyCornerScratch.set(o&1?t.max.x:t.min.x,o&2?t.max.y:t.min.y,o&4?t.max.z:t.min.z),c=this.screenPointOf(l.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 un;bodyCornerScratch=new D;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,o=-1/0;for(let l=0;l<8;l++){const c=this.bodyCornerScratch.set(l&1?i.max.x:i.min.x,l&2?i.max.y:i.min.y,l&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),o=Math.max(o,h.ndcY)}return{minX:n,minY:s,maxX:r,maxY:o}}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}decorMetresPerNdcY(e){const t=this.decorGroups.get(e);return t?t.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Di/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 o=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,n.position),l=this.raycaster.ray.intersectPlane(o,this.decorHitScratch);return l?Math.min(Math.max(l.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new qr;decorHitScratch=new D;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<ut.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],n=ut.firstSolid(this.raycaster.intersectObjects(i.map(([,r])=>r),!0));if(!n)return;let s=n.object;for(;s&&!i.some(([,r])=>r===s);)s=s.parent;return i.find(([,r])=>r===s)?.[0]}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.roadSystem.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=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.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.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())$t.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 D;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const e=this.lastAstronomy?.sun;return e!==void 0&&e.altitudeDeg<ut.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 yi(od,32,16),i=t.attributes.position,n=t.getAttribute("color")??new wt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:o,azimuthDeg:l}=BI(i.getX(r),i.getY(r),i.getZ(r)),c=YI(o,l,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 On({vertexColors:!0,side:ni,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Ae(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=Ib(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Km(this.groundRadius,48),i=new Nl({color:new se(gf,gf,gf),fog:!0});ao.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Ae(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,o])=>`${r}=${Math.round(o.x/10)},${Math.round(o.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=jt(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-It.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*SR);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-It.iceAlphaAt(i,ld,r,this.cloudFieldOffset)*ER),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<Ld){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:o,z:l}=jt(t.altitudeDeg,t.azimuthDeg,_n),c=q1(t.altitudeDeg),h=this.cloudTransmission(t),d=this.arrivingIlluminance(t,s,h),u=ut.unitLuminance(n);let p=this.bodyMeshes.get(e);if(e==="sun"){const f=Math.PI*(i/_n)**2,g=[0,1,2].map(v=>u[v]*d[v]/(this.sunBeamFraction*f));this.sunDiscRadiance=g;const m=g.map(v=>Math.min(ut.BRIGHTEST_RELATIVE,v));p instanceof Ae||(this.disposeMesh(p),p=new Ae(new yi(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(p),this.bodyMeshes.set(e,p)),p.material.color.setRGB(m[0],m[1],m[2]),p.scale.setScalar(i)}else{if(!(p instanceof Vn)){this.disposeMesh(p);const m=new ct;m.setAttribute("position",new tt(new Float32Array(3),3)),m.setAttribute("color",new tt(new Float32Array(3),3)),p=new Vn(m,Ce.material(Ml[Ml.length-1].size,!1)),Ce.track(p),this.celestialGroup.add(p),this.bodyMeshes.set(e,p)}const f=p.geometry.getAttribute("color"),g=e.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*d[0]*g,u[1]*d[1]*g,u[2]*d[2]*g),f.needsUpdate=!0}if(p.position.set(r,o,l),this.setHitArea(e,r,o,l,i),e==="sun"&&(this.sunArriving=d),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,o,l,d,i/_n*(180/Math.PI),ut.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,o*f+this.celestialGroup.position.y,l*f),this.lensFlare||(this.lensFlare=O4(),this.lensFlare.uniforms.uOpacity.value=LR,this.lensFlare.uniforms.uFlareIntensity.value=this.lensFlareArtifactIntensity,this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyLensFlareTint(c)}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<Ld){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=jt(e.altitudeDeg,e.azimuthDeg,_n),o=this.cloudTransmission(e),l=this.arrivingIlluminance(e,e.magnitude,o),c=e.radiusDeg??cn.MEAN_RADIUS_DEG,h=_n*Math.tan(c*Di),d=Math.max(yr(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/_n)**2,u=new se(...l.map(g=>Math.min(ut.BRIGHTEST_RELATIVE,g/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(yr(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof jl?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=Qb(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new jl(new Td({map:Qb(e.phase),color:u,fog:!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,l,c)}bentLight(e,t,i=wR){const[n,s,r]=this.arrivingIlluminance(e,t,1),o=Math.max(s,1e-30);return{scale:s/i,tint:[n/o,1,r/o]}}static litBySky(e,t){return ut.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new se;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,Ce.CONE_SOLID_ANGLE/t)}pointScratch=new xe;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=St.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=As.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 l=new Td({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new jl(l),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const o=s*2;r.scale.set(o,o,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,o=0){if(an.radiusDeg(an.K*Math.max(...s))<=Math.max(r,o)){this.disposeGlare(e);return}let l=this.glareSprites.get(e);l||(l=new an(`veil:${e}`),this.celestialGroup.add(l.mesh),this.glareSprites.set(e,l)),l.shine({x:t,y:i,z:n},s,r,o)}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=il(e.magnitude,t),s=nf(n);this.cometKey=i,this.setBodyMesh(i,e.position,yf*(.5+.5*n),new se(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new zn(_n),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new Xi,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:ld},0);return}const s=this.lowerCloudCover(),r=bt.deckLitUntilDeg(bt.DECK_HEIGHT_M),o=e.altitudeDeg>-r?e:t,l=this.bentLight(o,o===e?rt.SUN_MAGNITUDE:t.magnitude),c=bt.strength(i,s,o.altitudeDeg,r)*l.scale,{x:h,y:d,z:u}=jt(o.altitudeDeg,o.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},o.altitudeDeg,c,l.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??ld},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??Od)}buildRainbow(e,t){this.rainbow||(this.rainbow=new Ka,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(),o=this.bentLight(s,n?rt.SUN_MAGNITUDE:t.magnitude,xR),l=rn.strength(i,r,s.altitudeDeg)*o.scale;if(l<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:d}=jt(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},l,o.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Kr,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=Hn.galactic(i,n),r=ut.directionOf(s.centre),o=ut.directionOf(s.rotation),l=ut.directionOf(s.pole),c=new Ke().set(r.x,r.y,r.z,o.x,o.y,o.z,l.x,l.y,l.z),h=ut.directionOf(Hn.eclipticPole(i,n)),d=ut.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:ut.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:ce.phaseAngleOf(e.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new D(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:n}=jt(e.altitudeDeg,e.azimuthDeg,1);return new D(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=il(n.magnitude,t),o=nf(r);this.setBodyMesh(s,n.position,yf*(.5+.5*r),new se(o,o,o),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=il(n.magnitude,t),r=nf(s),o=QR[n.body]??new se(1,1,1),l=new se(o.r*r,o.g*r,o.b*r),c=yf*(.5+.5*s);this.setBodyMesh(n.body,n.position,c,l,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 Ss(n,s),o=Df(1337),l=[],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<Rb)continue;const{x:f,y:g,z:m}=jt(u,p,vf);l.push({x:f,y:g,z:m,brightness:il(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(v=>v*St.illuminanceOf(d)),phase:o()*Math.PI*2,speedFactor:.7+o()*.6})}for(const h of f4){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<Rb)continue;const{x:p,y:f,z:g}=jt(d,u,vf);this.namedStars.push({star:h,direction:new D(p,f,g).normalize(),altitudeDeg:d})}this.starTiers=Ml.map((h,d)=>{const u=l.filter(w=>rg(w.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),g=new Float32Array(u.length*3),m=new Float32Array(u.length),v=new Float32Array(u.length);u.forEach((w,S)=>{p[S*3]=w.x,p[S*3+1]=w.y,p[S*3+2]=w.z,f[S]=w.brightness,g.set(w.illuminance,S*3),m[S]=w.phase,v[S]=w.speedFactor});const x=new ct;x.setAttribute("position",new tt(p,3)),x.setAttribute("seed",new tt(m.map(w=>w/(2*Math.PI)),1));const y=new tt(new Float32Array(u.length*3),3);x.setAttribute("color",y);let b=this.starTiers[d]?.points;return b?(b.geometry.dispose(),b.geometry=x):(b=new Vn(x,Ce.material(h.size)),Ce.track(b),this.celestialGroup.add(b)),{points:b,colorAttribute:y,brightness:f,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){Ce.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 bl(this.celestialGroup,Mf,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 se(ya[0]+(Sf[0]-ya[0])*t,ya[1]+(Sf[1]-ya[1])*t,ya[2]+(Sf[2]-ya[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}=$0(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=Y0(Mf);this.cloudMesh=new Ae(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}=$0(new se(...ya),e,ld,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Ae(Y0(Mf*1.04),t),this.cirrusMesh.renderOrder=Fb-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?bl.deckOrder(!0,0,1):Fb}cloudLayerOffset(){const t=((this.weather.cloudBaseM??xm)-this.observerElevationM)*wf;return Math.sign(t||1)*Math.max(Math.abs(t),OR)}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,o]=this.cloudBeam.map(d=>d/Math.PI),l=this.lightningLevel*If*this.relativeScale/Math.PI,c=new se(t[0]+Us.r*l,t[1]+Us.g*l,t[2]+Us.b*l);this.layeredClouds?.setLighting(n.clone(),new se(s,r,o),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,o*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 VR(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,Af],[this.rainSplashSystem?.points,Ma],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:Ef[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=Hb(Tf(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=Ef[e],i=t.poolSize,n=Df(9001),s=new Float32Array(i*3),r=new Float32Array(i),o=new Float32Array(i),l=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 y=0;y<i;y++){const b=n()*Math.PI*2,w=n()*t.radiusM;s[y*3]=Math.cos(b)*w,s[y*3+1]=jo+n()*(t.topYM-jo),s[y*3+2]=Math.sin(b)*w,r[y]=n()*Math.PI*2,o[y]=.7+n()*.6,l[y]=.6+n()*.8,c[y]=.4+n()*1.2}const g=new ct;g.setAttribute("position",new tt(s,3)),g.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new se(...this.baseFogColor)},uTexture:{value:eC(e)},uNearFocusDistance:{value:Xb},uHazeDistance:{value:t.radiusM*$b}},v=new xt({uniforms:m,vertexShader:aC,fragmentShader:oC,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const x=new Vn(g,v);x.renderOrder=xf,this.scene.add(x),this.precipitationPoints=x,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=o,this.precipitationWobbleFreqJitter=l,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=Ef[i];if(this.precipitationUniforms?.uColor.value.copy(ut.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*Di,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,o=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,l=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,x=i==="snow"&&d&&u,y=i==="hail"&&p&&f&&g&&m&&v;for(let b=0,w=0;b<l.length;b+=3,w++){if(y&&p[w]>0){if(p[w]-=t,p[w]<=0){const M=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;l[b]=Math.cos(M)*T,l[b+1]=n.topYM,l[b+2]=Math.sin(M)*T,p[w]=0}else{const M=1-p[w]/g[w];l[b+1]=jo+Math.sin(Math.PI*M)*f[w],l[b]=dd(l[b]+(r+m[w])*t,n.radiusM),l[b+2]=dd(l[b+2]+(o+v[w])*t,n.radiusM)}continue}let S=0,_=0;if(x){const M=XR*d[w],T=$R*u[w];S=Math.sin(e*M*Math.PI*2+c[w])*T,_=Math.sin(e*M*Math.PI*2+c[w]+Math.PI/2)*T}if(l[b]+=(r+S)*t,l[b+1]-=n.fallSpeedMPerS*h[w]*t,l[b+2]+=(o+_)*t,l[b]=dd(l[b],n.radiusM),l[b+2]=dd(l[b+2],n.radiusM),l[b+1]<jo){if(y){f[w]=jb*(.2+Math.random()*1.6),g[w]=YR*(.5+Math.random()),p[w]=g[w];const A=Math.random()*Math.PI*2,R=qR*(f[w]/jb);m[w]=Math.cos(A)*R,v[w]=Math.sin(A)*R,l[b+1]=jo;continue}const M=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;l[b]=Math.cos(M)*T,l[b+1]=n.topYM,l[b+2]=Math.sin(M)*T}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=Tf(this.weather.precipitationIntensity);this.rainSystem=C4({count:Af,radiusM:hc,heightM:FR,bottomYM:Ub,overallSpeed:UR,color:zb.clone(),opacity:.85,visibleCount:this.precipitationCount(Af),speedStreak:Hb(e),pixelSize:qb,seed:9001,nearFocusDistanceM:Xb,hazeDistanceM:hc*$b,hazeColor:new se(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=xf,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=Df(4242),t=new Float32Array(Ma*3),i=new Float32Array(Ma),n=new Float32Array(Ma),s=new Float32Array(Ma);for(let h=0;h<Ma;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*hc;t[h*3]=Math.cos(d)*u,t[h*3+1]=Ub,t[h*3+2]=Math.sin(d)*u,n[h]=Jb(Gb,Vb),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new ct;r.setAttribute("position",new tt(t,3));const o=new tt(s,1);r.setAttribute("aLife",o),r.setDrawRange(0,this.precipitationCount(Ma));const l=new xt({uniforms:{uMaxSize:{value:GR},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:Wb.clone()},uTexture:{value:nC()}},vertexShader:sC,fragmentShader:rC,transparent:!0,depthWrite:!1}),c=new Vn(r,l);c.renderOrder=xf,this.scene.add(c),this.rainSplashSystem={points:c,positions:t,life:i,duration:n,lifeAttribute:o}}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*Di;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-Tf(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(ut.litBySky(zb,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(ut.litBySky(Wb,this.baseFogColor));const n=this.weather.windDirectionDeg*Di,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,o=hc,l=h=>(h%(o*2)+o*3)%(o*2)-o;t.uniforms.uWindOffset.value.set(l(t.uniforms.uWindOffset.value.x+s*e),l(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=Kb+(1-Kb)*(1-c),d=Zb+(1-Zb)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=qb*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,o=r.array;for(let l=0,c=0;l<i.length;l+=3,c++){if(n[c]+=e,n[c]>=s[c]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*hc;i[l]=Math.cos(h)*d,i[l+2]=Math.sin(h)*d,s[c]=Jb(Gb,Vb),n[c]=0}o[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 l of this.lightningFlashes){if(l.t>e)break;const c=Oi.brightnessAt(l,e);c>i&&(t=l,i=c)}const n=t?Math.min(1,Math.max(.1,(jR/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 l=this.scene.fog,c=s*If*this.relativeScale/Math.PI;l.color.setRGB(this.airlight[0]+Us.r*c,this.airlight[1]+Us.g*c,this.airlight[2]+Us.b*c)}const r=this.skyMesh?.material?.color;if(r){const l=s*JR;r.setRGB(1+l*Us.r,1+l*Us.g,1+l*Us.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*If*this.relativeScale,t){const{x:l,y:c,z:h}=jt(25,t.azimuthDeg,_n);this.lightningLight.position.set(l,c,h)}this.lightningBolt||(this.lightningBolt=new Zr(_n*.95),this.celestialGroup.add(this.lightningBolt.object));const o=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,o),this.render()}buildCompassLabels(){this.compassSprites=AR.map(e=>{const t=so.point(e,this.compassPoints),i=new Td({map:lC(t),depthTest:!1,fog:!1}),n=new jl(i),{x:s,y:r,z:o}=jt(0,e,Lb);return n.position.set(s,r,o),n.scale.set(hd,hd,1),n.renderOrder=DR,n.layers.set(mf),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=kb*Math.PI/360,i=hd*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 Di=Math.PI/180;function yr(a,e,t){return Math.max(e,Math.min(t,a))}function Jb(a,e){return a+Math.random()*(e-a)}function dd(a,e){return(a%(e*2)+e*3)%(e*2)-e}let ud,pd;function eC(a){switch(a){case"snow":return tC();case"hail":return iC()}}function tC(){if(ud)return ud;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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,a,a),ud=new Cr(e),ud}function iC(){if(pd)return pd;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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,a,a),pd=new Cr(e),pd}let fd;function nC(){if(fd)return fd;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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,a,a),fd=new Cr(e),fd}const sC=`
|
|
9587
9587
|
uniform float uMaxSize;
|
|
9588
9588
|
uniform float uScale;
|
|
9589
9589
|
attribute float aLife;
|
|
@@ -9649,7 +9649,7 @@ void main() {
|
|
|
9649
9649
|
gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
|
|
9650
9650
|
}
|
|
9651
9651
|
`;function Qb(a){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,o="#010101",l="#f4f1e2";i.fillStyle=o,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const c=yr(a.illuminatedFraction,0,1),h=a.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=l,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 Cr(t)}function lC(a){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(a,64,68),new Cr(e)}function Df(a){let e=a;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 Ou{constructor(e,t){this.source=e,this.create=t}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=320;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"),Object.assign(e.style,{position:"fixed",left:"-10000px",top:"0",width:`${Ou.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<Ou.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}}}const Rf=7.5,Pc=9;class Hs{static cache=new Map;static load(e){let t=Hs.cache.get(e);return t||(t=fetch(e).then(i=>i.arrayBuffer()).then(i=>Hs.parse(i)),Hs.cache.set(e,t)),t}static upTo(e,t){const i=e.filter((r,o)=>o===0||e[o-1].magnitudeLimit<t);if(i.length<=1)return Hs.load(e[0].url);const n=i.map(r=>r.url).join(`
|
|
9652
|
-
`);let s=Hs.cache.get(n);return s||(s=Promise.all(i.map(r=>Hs.load(r.url))).then(r=>r.reduce((o,l)=>Hs.concat(o,l))),Hs.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 Nt{constructor(e){if(this.heights=e,e.length!==Nt.WIDTH*Nt.HEIGHT)throw new Error(`a lunar relief has ${Nt.WIDTH*Nt.HEIGHT} samples, not ${e.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*Nt.SAMPLES_PER_DEGREE;static HEIGHT=180*Nt.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=Nt.SAMPLES_PER_DEGREE,n=(t%360+360)%360*i-.5,s=(90-e)*i-.5,r=Math.floor(n),o=Math.floor(s),l=n-r,c=s-o,h=(p,f)=>{const g=(p%Nt.WIDTH+Nt.WIDTH)%Nt.WIDTH,m=Math.min(Nt.HEIGHT-1,Math.max(0,f));return this.heights[m*Nt.WIDTH+g]},d=h(r,o)*(1-l)+h(r+1,o)*l,u=h(r,o+1)*(1-l)+h(r+1,o+1)*l;return(d*(1-c)+u*c)*Nt.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>=Nt.BAND_FROM_DEG&&n<=Nt.BAND_TO_DEG}static withBump(e,t,i,n=.4){const s=new Int8Array(Nt.WIDTH*Nt.HEIGHT),r=Nt.SAMPLES_PER_DEGREE,o=Math.ceil(n*r),l=Math.floor(t*r),c=Math.floor((90-e)*r);for(let h=-o;h<=o;h++)for(let d=-o;d<=o;d++)Math.hypot(d,h)<=o&&(s[(c+h)*Nt.WIDTH+(l+d+Nt.WIDTH)%Nt.WIDTH]=Math.round(i/Nt.UNIT_KM));return new Nt(s)}static smooth(){return new Nt(new Int8Array(Nt.WIDTH*Nt.HEIGHT))}}class ss{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=ss.SAMPLES){const{s,u:r,w:o,distanceKm:l}=ss.frame(e,t),c=Math.PI/180,h=new Float32Array(n),d=Nt.REFERENCE_RADIUS_KM;for(let u=0;u<n;u++){const p=u/n*2*Math.PI,f=Math.cos(p),g=Math.sin(p),m=f*r[0]+g*o[0],v=f*r[1]+g*o[1],x=f*r[2]+g*o[2];let y=0;for(let b=ss.SEARCH_FROM_DEG;b<=ss.SEARCH_TO_DEG;b+=ss.SEARCH_STEP_DEG){const w=Math.cos(b*c),S=Math.sin(b*c),_=w*s[0]+S*m,M=w*s[1]+S*v,T=w*s[2]+S*x,A=Math.asin(Math.max(-1,Math.min(1,T)))/c,R=Math.atan2(M,_)/c,C=d+i.heightKm(A,R),k=Math.atan2(C*S,l-C*w);k>y&&(y=k)}h[u]=y/c}return{radiusDeg:h,meanRadiusDeg:Math.asin(d/l)/c}}static frame(e,t){const i=new ha(t.lat,t.lng,t.elevationM),n=Tr(e),s=rm(e,i,!1),r=new Mt(s.x-n.x,s.y-n.y,s.z-n.z,n.t),o=Math.hypot(r.x,r.y,r.z)*ss.AU_KM,l=ss.bodyFixed(e),c=l(r),h=Math.hypot(c[0],c[1],c[2]),d=[c[0]/h,c[1]/h,c[2]/h],u=YD(e,i),p=pg(u),f=_r(u,new Mt(-r.x,-r.y,-r.z,n.t)),g=Math.asin(f.z/Math.hypot(f.x,f.y,f.z)),m=Math.atan2(-f.y,f.x),v=new Mt(-Math.sin(g)*Math.cos(m),Math.sin(g)*Math.sin(m),Math.cos(g),n.t),x=new Mt(-Math.sin(m),-Math.cos(m),0,n.t);return{s:d,u:l(_r(p,v)),w:l(_r(p,x)),distanceKm:o}}static surfacePoint(e,t,i,n){const{s,u:r,w:o}=ss.frame(e,t),l=Math.PI/180,c=[0,1,2].map(d=>Math.cos(i*l)*r[d]+Math.sin(i*l)*o[d]),h=[0,1,2].map(d=>Math.cos(n*l)*s[d]+Math.sin(n*l)*c[d]);return{latDeg:Math.asin(h[2])/l,lonDeg:Math.atan2(h[1],h[0])/l}}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 o=0;o<n;o++){const l=o/n*2*Math.PI,c=Math.cos(l),h=Math.sin(l),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 g=Math.max(0,d-p),m=Math.max(g,e.radiusDeg[o]);f>m&&(r+=.5*(f*f-m*m))}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=c4(ue.Moon,e),i=Math.PI/180,n=t.ra*15*i,s=t.dec*i,r=t.spin*i,o=(c,[h,d,u])=>[Math.cos(c)*h+Math.sin(c)*d,-Math.sin(c)*h+Math.cos(c)*d,u],l=(c,[h,d,u])=>[h,Math.cos(c)*d+Math.sin(c)*u,-Math.sin(c)*d+Math.cos(c)*u];return c=>o(r,l(Math.PI/2-s,o(Math.PI/2+n,[c.x,c.y,c.z])))}static subObserverPoint(e,t){const i=new ha(t.lat,t.lng,t.elevationM),n=Tr(e),s=rm(e,i,!1),r=ss.bodyFixed(e)(new Mt(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),o=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/o)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class Lc{static cache=new Map;static load(e){let t=Lc.cache.get(e);return t||(t=Lc.fetchRelief(e).catch(()=>{}),Lc.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 Nt(new Int8Array(i.buffer,i.byteOffset,i.length))}}class Nu{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 so.point(e,this.names?.compassPoints)}towards(e){return so.towards(e,this.names)}}const cC="Global Meteor Network",hC="https://globalmeteornetwork.org/data/",dC="“Thunder” by Jerimee",uC="https://creativecommons.org/licenses/by/3.0/",pC="CC BY 3.0";class Dn{static fill(e,t){e.innerHTML="";const i=h=>e.appendChild(h),n=t.currentTerrainAttribution;n&&i(Dn.text(n));const s=t.currentRoadAttribution;s&&i(Dn.text(s));const r=t.ufoElement.observerMapCredit;r&&!n?.includes(r)&&i(Dn.text(r));for(const h of t.decorModelCredits){const d=h.author?` — ${h.author}`:"",u=document.createElement("li");h.sourceUrl?u.append(Dn.link(h.sourceUrl,h.title),document.createTextNode(`${d} (${h.license})`)):u.textContent=`${h.title}${d} (${h.license})`,i(u)}for(const h of t.ufoElement.sighting.references){if(!h.credit)continue;const d=document.createElement("li");h.creditUrl?d.appendChild(Dn.link(h.creditUrl,h.credit)):d.textContent=h.credit,i(d)}if(t.ufoElement.sighting.traces.length>0){const h=new qn(hs.preferencesFor(t)),d=new Set(t.ufoElement.sighting.traces.map(u=>h.read(u.source)).filter(u=>!!u));for(const u of d)i(Dn.text(u))}const o=t.satelliteState;if(o.status==="ready"&&o.credit){const h=document.createElement("li");h.appendChild(Dn.link(o.creditUrl??"",o.credit)),i(h)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const h=document.createElement("li");h.append(Dn.link(hC,cC),document.createTextNode(" (CC BY 4.0)")),i(h)}const l=t.aircraftState;if(l.status==="ready"&&l.shown>0){const h=document.createElement("li");if(h.appendChild(Dn.link(l.creditUrl,l.credit)),i(h),l.trailCredit){const d=document.createElement("li");d.appendChild(Dn.link(l.trailCredit.creditUrl,l.trailCredit.credit)),i(d)}}const c=Dn.text(`${dC} (`);c.append(Dn.link(uC,pC),document.createTextNode(")")),i(c)}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 fC=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,mC=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,gC=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,vC=20,bC=1;class yC{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}}to.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(fC,this.ambientVolume).then(o=>this.applyIfCurrent(o,r,()=>this.ambientToken,l=>{this.ambientSource=l?.source,this.ambientGain=l?.gain,l&&(l.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/vC,1);const s=i>bC;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(mC,this.windVolume).then(o=>this.applyIfCurrent(o,r,()=>this.windToken,l=>{this.windSource=l?.source,this.windGain=l?.gain,l&&(l.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(gC,.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 Mr{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[n,s]=this.perifocalAxes(),r=Math.sqrt(Mr.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*Mr.stumpffC(n),o=t-i*i*i/Math.sqrt(Mr.SUN_GM_AU3_PER_DAY2)*Mr.stumpffS(n);return{x:r*this.perihelionPosition.x+o*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+o*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+o*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(Mr.SUN_GM_AU3_PER_DAY2)*Math.abs(e),n=o=>{const l=this.inverseSemiMajorAxis*o*o,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*o*o*o*Mr.stumpffS(l)+c*o};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let o=0;o<Mr.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);o++){const l=(r+s)/2;n(l)<i?r=l:s=l}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),o=Math.sin(t),l=Math.cos(i),c=Math.sin(i);return[{x:n*r-s*o*l,y:s*r+n*o*l,z:o*c},{x:-n*o-s*r*l,y:-s*o+n*r*l,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 Nw=[{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 kd{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 Nw.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=Ht(t),s=this.earthPositionAt(n),r=this.apparentPositionOf(e,2451545+n.tt,s),o=this.subtract(r,s),l=this.length(r),c=this.length(o),h=this.tailEndAt(e,r,s,l,n,t,i),d=this.horizontalOf(o,n,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:l,earthDistanceAu:c,elongationDeg:this.angleBetween(o,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(e,l,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,o){if(e.tailLengthAu===void 0)return{};const l=1+e.tailLengthAu/n,c=this.subtract({x:t.x*l,y:t.y*l,z:t.z*l},i),h=this.subtract(t,i);return{tailEnd:this.horizontalOf(c,s,r,o),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 o=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(t-o)}return s}static horizontalOf(e,t,i,n){const s=_r(VD(),new Mt(e.x,e.y,e.z,t)),r=_r(bw(t),s),o=rm(t,new ha(n.lat,n.lng,n.elevationM),!0),l=new Mt(r.x-o.x,r.y-o.y,r.z-o.z,t),c=op(l);return gg(c.ra,c.dec,i,n)}static earthPositionAt(e){return _r(GD(),oa(ue.Earth,e))}static julianDayOf(e){return 2451545+Ht(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new Mr(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 Cf=[{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 Fu{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return Cf.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),n=[];for(const s of Cf){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Ss.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 Cf.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,o]=i[s-1]??i[0],[l,c]=i[s]??i[0];if(l===r)return o;const h=Math.min(1,Math.max(0,(n-r)/(l-r)));return o+h*(c-o)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const MC=[{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}],Fl=6.5;class El{static activeAt(e){return MC.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)),o=this.wrappedDelta(i,s),l=this.wrappedDelta(s,n),c=this.wrappedDelta(r,s);return o<0?o<-l?0:1+o/l:o>0?o>c?0:1-o/c:1}static observedRatePerHour(e,t,i,n=Fl){if(t<=0)return 0;const s=Fl-n;return e*Math.sin(t*Math.PI/180)/Math.pow(i,s)}static radiantPosition(e,t,i){return Ss.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 oi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=Ht(e),n=new np(0,wD(e).elon-90,1),s=_r(qD(i),mg(n,i)),r=op(s);return gg(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=Fl){const i=oi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),n=Fl-t;return(oi.QUIET_RATE_PER_HOUR+i)/Math.pow(oi.POPULATION_INDEX,n)}static schedule(e){const t=new lp(e.seed^1542469173);return ro.schedule(e).map(i=>{const n=oi.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=oi.turnAround(n,t.between(0,360)),o={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:oi.toHorizontal(o),bearingDeg:oi.bearingFrom(o,n)}})}static turnAround(e,t){const[i,n]=oi.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]=oi.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,r=oi.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=oi.normalise(oi.cross(e,t));return[i,oi.normalise(oi.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=oi.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=oi.turnAround(t,e.bearingDeg),n=e.fromRadiantDeg*Math.PI/180;return oi.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 ey="https://ufoathome.org/tle/index.json";class en{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??en.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(ey)||e.push(ey),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${en.FIRST_SNAPSHOT}T00:00:00Z`)-en.MAX_ELEMENT_AGE_DAYS*en.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)-en.MAX_ELEMENT_AGE_DAYS*en.DAY_MS&&e.getTime()<=Date.parse(n.to)+en.MAX_ELEMENT_AGE_DAYS*en.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:i,base:n}=t,s=[],r=[];for(const o of Object.keys(i.kinds)){const l=await this.kindAt(o,e,i,n);s.push(...l),r.push(this.coverageOf(o,e,i,l.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*en.DAY_MS,o=Math.floor(s/r),l=s-o*r<r/2?o-1:o+1,c=new Set(i.kinds[e].bins),h=[o,l].map(g=>new Date(g*r).toISOString().slice(0,10)).filter(g=>c.has(g));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,n).href),...h.map(g=>this.binary(new URL(`${e}/${g}.bin`,n).href))]),p=new Map;for(const g of u)for(const m of en.decode(g,i.recordBytes)){const v=p.get(m.norad);(!v||Math.abs(m.epochMs-s)<Math.abs(v.epochMs-s))&&p.set(m.norad,m)}const f=[];for(const g of p.values()){const m=Math.abs(g.epochMs-s)/en.DAY_MS;if(m>en.MAX_ELEMENT_AGE_DAYS)continue;const v=d[g.norad]??{name:String(g.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>s||f.push({norad:g.norad,name:v.name,kind:e,launch:v.launch,stdMag:v.stdMag,elements:g,ageDays:m})}return f}coverageOf(e,t,i,n){const{from:s,to:r}=i.kinds[e],o=t.getTime(),l=en.MAX_ELEMENT_AGE_DAYS*en.DAY_MS,c=n?"covered":o<Date.parse(s)-l?"before":o>Date.parse(r)+l?"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 wC{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const i=lt.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(t.inFrontM!==void 0){const i=lt.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:lt.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:lt.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class oo{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*oo.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=oo.degOver(e)/t;return i<1?1:Math.min(oo.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class nn{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 oo.DEG_PER_SECOND*3600}static graspOf(e,t={}){const i=t.exposureSeconds??e.exposureSeconds,n=t.fNumber??e.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return nn.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??nn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,o=nn.resolutionArcsec(e,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,nn.trailLimitedSeconds(o)),resolutionArcsec:o}}static resolutionArcsec(e,t,i){const s=(e.detailUm??nn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*nn.ARCSEC_PER_RADIAN,r=1.22*nn.WAVELENGTH_M/(i/1e3)*nn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(e){return e/nn.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=nn.graspOf(e,t),n=nn.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,o=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*o)}static gainFor(e,t){const i=t.fieldOfViewDeg===void 0?void 0:Rt.focalLengthMmFor(e,t.fieldOfViewDeg);return nn.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const ty=111320,dc=Math.PI/180,xC=1.02,SC=1;class kc{static of(e,t){const i=kc.sightings(e,t);if(i.length<2)return;const n=kc.baseline(i);if(!n)return;const{near:s,far:r,closedM:o}=n,l=Math.tan(r.widthDeg/2*dc)===0?0:Math.tan(s.widthDeg/2*dc)/Math.tan(r.widthDeg/2*dc);if(l<xC)return;const c=o/(l-1),h=lt.sizeMAt(c,s.widthDeg),d=i.map(u=>({t:u.t,m:lt.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.m)),fromT:r.t,toT:s.t,closedM:o}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(o=>o.sourceId===t)?.shape,s=n?.angular?.widthDeg,r=at(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=kc.closedAlongSight(i,n),[r,o,l]=s>=0?[n,i,s]:[i,n,-s];l<SC||r.widthDeg<=o.widthDeg||(!t||l>t.closedM)&&(t={near:r,far:o,closedM:l})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*ty,n=(t.lng-e.lng)*ty*Math.cos(e.lat*dc),s=(e.sightAzimuthDeg??0)*dc;return i*Math.cos(s)+n*Math.sin(s)}}class gn{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:gn.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:gn.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:gn.atLeastNearest(e.derivedM),basis:"derived"};const t=gn.largest(e.range?.minM,e.crossing?.behindM),i=gn.smallest(e.range?.maxM,e.crossing?.inFrontM),n=t===void 0?void 0:t*gn.MARGIN,s=i===void 0?void 0:i/gn.MARGIN;return n!==void 0&&s!==void 0?{distanceM:gn.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:gn.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<gn.CONVENTIONAL_M?{distanceM:gn.atLeastNearest(s),basis:"bounded"}:{distanceM:gn.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(gn.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 Pf=Math.PI/180;class dt{constructor(e,t,i){this.body=e,this.ground=t;const n=[...e.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)dt.collect(this.motionKeys,s.t,s.motions),dt.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};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 dt.channelsAt(this.motionKeys,e,0)}lightsAt(e){return this.lightKeys.size>0?dt.channelsAt(this.lightKeys,e,void 0):void 0}static channelsAt(e,t,i){const n={};for(const[s,r]of e){let o=r.length-1;for(;o>=0&&r[o].t>t;)o--;if(o<0){i!==void 0&&(n[s]=i);continue}const l=r[o],c=r[Math.min(o+1,r.length-1)],h=c===l||c.t===l.t?0:Math.min(1,(t-l.t)/(c.t-l.t));n[s]=dt.lerp(l.value,c.value,h)}return n}static eyeOf(e,t,i){const n=at(e,0),s=at(e,t),o=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ci(s.lat,s.lng,n.lat,n.lng):void 0,l=o?o.x:0,c=o?-o.z:0;return{eastM:l,northM:c,upM:i.heightAt(l,c)+dt.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(e,t,i,n){const s=dt.directionOf(t,i),r=c=>e.upM+s.upM*c-n.heightAt(e.eastM+s.eastM*c,e.northM+s.northM*c);let o=0,l=0;for(;l<dt.MAX_RANGE_M;){if(l=o+Math.max(.5,o*.01),r(l)<=0){for(let c=0;c<30;c++){const h=(o+l)/2;r(h)<=0?l=h:o=h}return l}o=l}}static directionOf(e,t){const i=e*Pf,n=t*Pf;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=t.length-1;for(;i>0&&t[i].t>e;)i--;const n=t[i];if(!n.present)return;const s=t[Math.min(i+1,t.length-1)],r=s===n||s.t===n.t?0:Math.min(1,(e-n.t)/(s.t-n.t)),o=dt.lerp(n.eastM,s.eastM,r),l=dt.lerp(n.northM,s.northM,r),c={widthM:dt.lerp(n.sizeM.widthM,s.sizeM.widthM,r),lengthM:dt.lerp(n.sizeM.lengthM,s.sizeM.lengthM,r),heightM:dt.lerp(n.sizeM.heightM,s.sizeM.heightM,r)},h={headingDeg:dt.lerpAngle(n.attitude.headingDeg,s.attitude.headingDeg,r),pitchDeg:dt.lerp(n.attitude.pitchDeg,s.attitude.pitchDeg,r),rollDeg:dt.lerp(n.attitude.rollDeg,s.attitude.rollDeg,r)};let d;if("aboveGroundM"in n.vertical&&"aboveGroundM"in s.vertical){const u=dt.lerp(n.vertical.aboveGroundM,s.vertical.aboveGroundM,r);d=this.groundUnderFootprint(o,l,c,h.headingDeg)+u+c.heightM/2}else d=dt.lerp(this.centreUpOf(n),this.centreUpOf(s),r);return{id:this.body.id,model:this.body.model,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:o,northM:l,upM:d,sizeM:c,attitude:h,appearance:{color:(r<1?n:s).appearance.color,albedo:dt.lerp(n.appearance.albedo,s.appearance.albedo,r),luminanceCdM2:dt.lerp(n.appearance.luminanceCdM2,s.appearance.luminanceCdM2,r)},flame:dt.flameBetween(n.flame,s.flame,r),motions:this.motionsAt(e),lights:this.lightsAt(e),throwsFlame:this.body.track.some(u=>u.flame!==void 0&&u.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:dt.lerp(n.lengthM,s.lengthM,i),widthM:dt.lerp(n.widthM,s.widthM,i),luminanceCdM2:dt.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(e){return"upM"in e.vertical?e.vertical.upM:this.groundUnderFootprint(e.eastM,e.northM,e.sizeM,e.attitude.headingDeg)+e.vertical.aboveGroundM+e.sizeM.heightM/2}groundUnderFootprint(e,t,i,n){const s=n*Pf,r={eastM:Math.cos(s),northM:-Math.sin(s)},o={eastM:Math.sin(s),northM:Math.cos(s)};let l=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;l=Math.max(l,this.ground.heightAt(e+r.eastM*d+o.eastM*u,t+r.northM*d+o.northM*u))}return l}place(e,t){const i=[];let n;for(const s of e){const r=s.sizeM??n?.sizeM??dt.DEFAULT_SIZE,o={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},l={color:s.appearance?.color??n?.appearance.color??dt.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??dt.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??dt.DEFAULT_APPEARANCE.luminanceCdM2},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;n={t:s.t,...c,sizeM:r,attitude:o,appearance:l,flame:h,present:d},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}}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?dt.lineOfSightMeetsGround(n,e.azimuthDeg,e.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=dt.directionOf(e.azimuthDeg,e.altitudeDeg),o=n.eastM+r.eastM*s,l=n.northM+r.northM*s;return{eastM:o,northM:l,vertical:this.verticalOf(e,t)??{upM:n.upM+r.upM*s}}}static lerp(e,t,i){return e+(t-e)*i}static lerpAngle(e,t,i){const n=((t-e)%360+540)%360-180;return((e+n*i)%360+360)%360}}class At{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=1.5;static FADE_MS=600;static TRAIN_POINTS=8;static leadAt(e,t){const i=e.track;if(i.length<2||t<i[0].t||t>i[i.length-1].t)return;let n=0;for(;n<i.length-2&&i[n+1].t<t;)n++;const s=i[n],r=i[n+1],o=r.t-s.t,l=o>0?(t-s.t)/o:0,[c,h]=At.alongGreatCircle(s,r,l);return{lat:c,lng:h,heightM:(s.altitudeKm+(r.altitudeKm-s.altitudeKm)*l)*1e3}}static viewsAt(e,t,i){const n=[];for(const s of e){const r=s.track[0]?.t??0,o=s.track[s.track.length-1]?.t??0;s.fragments.forEach((l,c)=>{const h=l.fromT??r,d=l.untilT??o;if(t<h||t>d)return;const u=(l.lagS??0)*1e3,p=At.leadAt(s,t-u);if(!p)return;const f=At.seenFrom(i,p);if(f.altitudeDeg<0)return;const g=Math.min(At.FADE_MS,(d-h)/4),m=g>0?Math.min(1,(t-h)/g,(d-t)/g):1,v=-2.5*Math.log10(Math.max(m,.001)),x=l.absoluteMagnitude+5*Math.log10(f.distanceKm/At.STANDARD_DISTANCE_KM)+v,y=[f],b=(l.trainS??At.DEFAULT_TRAIN_S)*1e3;for(let w=1;w<=At.TRAIN_POINTS;w++){const S=Math.min(b*w/At.TRAIN_POINTS,t-h),_=At.leadAt(s,t-u-S);if(!_||(y.push(At.seenFrom(i,_)),S>=t-h))break}n.push({reentryId:s.id,fragmentId:l.id??String(c),head:f,magnitude:x,color:l.color??At.DEFAULT_COLOR,train:y})})}return n}static seenFrom(e,t){const i=At.ecef(e),n=At.ecef(t),s=n[0]-i[0],r=n[1]-i[1],o=n[2]-i[2],l=e.lat*At.DEG,c=e.lng*At.DEG,h=-Math.sin(c)*s+Math.cos(c)*r,d=-Math.sin(l)*Math.cos(c)*s-Math.sin(l)*Math.sin(c)*r+Math.cos(l)*o,u=Math.cos(l)*Math.cos(c)*s+Math.cos(l)*Math.sin(c)*r+Math.sin(l)*o,p=Math.hypot(h,d,u);return{altitudeDeg:Math.asin(u/p)/At.DEG,azimuthDeg:(Math.atan2(h,d)/At.DEG+360)%360,distanceKm:p/1e3}}static ecef(e){const t=e.lat*At.DEG,i=e.lng*At.DEG,n=Math.sin(t),s=At.A/Math.sqrt(1-At.E2*n*n);return[(s+e.heightM)*Math.cos(t)*Math.cos(i),(s+e.heightM)*Math.cos(t)*Math.sin(i),(s*(1-At.E2)+e.heightM)*n]}static alongGreatCircle(e,t,i){const n=h=>{const d=h.lat*At.DEG,u=h.lng*At.DEG;return[Math.cos(d)*Math.cos(u),Math.cos(d)*Math.sin(u),Math.sin(d)]},s=n(e),r=n(t),o=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),l=Math.acos(o);let c;if(l<1e-12)c=s;else{const h=Math.sin((1-i)*l)/Math.sin(l),d=Math.sin(i*l)/Math.sin(l);c=[s[0]*h+r[0]*d,s[1]*h+r[1]*d,s[2]*h+r[2]*d]}return[Math.atan2(c[2],Math.hypot(c[0],c[1]))/At.DEG,Math.atan2(c[1],c[0])/At.DEG]}}class yg{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=yg.FIRST_DAY}}class EC{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 _C="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",Mm=[{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 EC(_C,a=>yg.mayCover(a),async()=>new(await je(async()=>{const{AdsbLolArchiveProvider:a}=await import("./AdsbLolArchiveProvider-Ir8tinqO.js");return{AdsbLolArchiveProvider:a}},[],import.meta.url)).AdsbLolArchiveProvider)}];class vn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const n=vn.positionAt(e,i);if(!n)return;const s=At.seenFrom(t,n.geo);if(!(s.altitudeDeg<0))return{track:e,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:vn.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(n=>vn.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*vn.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,o=r.t-s.t;if(o>vn.MAX_GAP_S*1e3)return;const l=o>0?(t-s.t)/o:0,c=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*l,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*l,lng:vn.wrapLongitude(s.lng+h*l),heightM:c*vn.FT_TO_M},altitudeFt:c,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(e,t,i){const n=vn.positionAt(e,i-500),s=vn.positionAt(e,i+500);if(!n||!s)return;const r=vn.unit(At.seenFrom(t,n.geo)),o=vn.unit(At.seenFrom(t,s.geo)),l=Math.min(1,Math.max(-1,r[0]*o[0]+r[1]*o[1]+r[2]*o[2]));return Math.acos(l)*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 iy="https://ufoathome.org/fireballs/index.json";class os{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??os.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(iy)||e.push(iy),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=os.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!os.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=os.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=At.seenFrom(t,n);if(!(s.altitudeDeg<0))return{record:e,peak:s,magnitude:e.peakMagnitude+5*Math.log10(s.distanceKm/At.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:os.COLOR,trainS:os.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}}const $o=Math.PI/180,uc=180/Math.PI;class vi{constructor(e){this.timeline=e}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;at(e,t,i,n){const s=[];for(const r of t){const o=vi.projectionOf(r,i,n?.(r));if(o)for(const l of r.explains){const c=this.timeline.getInterpolatedShapeAt(e,l);!c||c.transparency>=1||s.push({...vi.compare(l,r.id,{aim:c.aim,angular:c.angular},o),title:c.title})}}return s}static compare(e,t,i,n){const s=[],r=i.aim?vi.separationDeg(i.aim,n.aim):void 0;if(r!==void 0){const c=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;r>Math.max(vi.DIRECTION_TOLERANCE_DEG,c)&&s.push("direction")}const o=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,l=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0;return o!==void 0&&!vi.withinSize(o)&&s.push("width"),l!==void 0&&!vi.withinSize(l)&&s.push("height"),{sourceId:e,bodyId:t,stated:i,predicted:n,separationDeg:r,widthRatio:o,heightRatio:l,disagreements:s}}static projectionOf(e,t,i){const n=i&&i.length>0?i:vi.outlineOf(e),s=i&&i.length>0?vi.centreOf(i):e,r=vi.normalized({eastM:s.eastM-t.eastM,northM:s.northM-t.northM,upM:s.upM-t.upM});if(!r)return;const o=vi.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},l=vi.cross(o,r);let c=1/0,h=-1/0,d=1/0,u=-1/0;for(const p of n){const f={eastM:p.eastM-t.eastM,northM:p.northM-t.northM,upM:p.upM-t.upM},g=vi.dot(f,r);if(g<=0)return;const m=Math.atan2(vi.dot(f,o),g),v=Math.atan2(vi.dot(f,l),g);c=Math.min(c,m),h=Math.max(h,m),d=Math.min(d,v),u=Math.max(u,v)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*uc+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*uc},angular:{widthDeg:(h-c)*uc,heightDeg:(u-d)*uc}}}static centreOf(e){const t=i=>(Math.min(...e.map(n=>n[i]))+Math.max(...e.map(n=>n[i])))/2;return{eastM:t("eastM"),northM:t("northM"),upM:t("upM")}}static separationDeg(e,t){const i=e.altitudeDeg*$o,n=t.altitudeDeg*$o,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((e.azimuthDeg-t.azimuthDeg)*$o);return Math.acos(Math.max(-1,Math.min(1,s)))*uc}static withinSize(e){return e<=vi.SIZE_TOLERANCE&&e>=1/vi.SIZE_TOLERANCE}static outlineOf(e){const t=e.sizeM.widthM/2,i=e.sizeM.lengthM/2,n=e.sizeM.heightM/2,s=[],r=e.model.url===void 0?e.model.id:void 0;if(r!==void 0&&r!=="box"&&Pw.includes(r))for(let d=0;d<=vi.RINGS;d++){const u=d/vi.RINGS*Math.PI;for(let p=0;p<vi.SEGMENTS;p++){const f=p/vi.SEGMENTS*2*Math.PI;s.push([t*Math.sin(u)*Math.cos(f),i*Math.sin(u)*Math.sin(f),n*Math.cos(u)])}}else for(const d of[-t,t])for(const u of[-i,i])for(const p of[-n,n])s.push([d,u,p]);const l=e.attitude.headingDeg*$o,c=e.attitude.pitchDeg*$o,h=e.attitude.rollDeg*$o;return s.map(([d,u,p])=>{const f=d*Math.cos(h)+p*Math.sin(h),g=-d*Math.sin(h)+p*Math.cos(h),m=u*Math.cos(c)-g*Math.sin(c),v=u*Math.sin(c)+g*Math.cos(c);return{eastM:e.eastM+f*Math.cos(l)+m*Math.sin(l),northM:e.northM-f*Math.sin(l)+m*Math.cos(l),upM:e.upM+v}})}static dot(e,t){return e.eastM*t.eastM+e.northM*t.northM+e.upM*t.upM}static cross(e,t){return{eastM:e.northM*t.upM-e.upM*t.northM,northM:e.upM*t.eastM-e.eastM*t.upM,upM:e.eastM*t.northM-e.northM*t.eastM}}static normalized(e){const t=Math.hypot(e.eastM,e.northM,e.upM);return t>1e-9?{eastM:e.eastM/t,northM:e.northM/t,upM:e.upM/t}:void 0}}qu();const AC={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},TC="{name} — mag {mag}, {alt}° above the horizon",IC="{name} — satellite, mag {mag}, {height} km up",Fw="satellites-change",Uw="fireballs-change",DC="aircraft-change",RC="rr0-confrontation",CC="{name} — mag {mag}, {alt}° below the horizontal",Lf="Credits",ny="comet:",sy="nova:",ry={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",streetlight:"Streetlight",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},PC=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,LC=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,kC=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,OC=-18,NC={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},md={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class ei 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",pl,fl]}shadow;stageElement;frameElement;sceneCanvas;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new D;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new en;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new os;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=Mm[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return ei.trafficRuntimeLoading??=je(()=>import("./trafficRuntime-Ce_f9RDO.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>ei.trafficRuntime=e),ei.trafficRuntimeLoading.catch(()=>{ei.trafficRuntimeLoading=void 0}),ei.trafficRuntimeLoading}traffic;lastSun;decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new yC;vehicleAudio=new fS;aircraftAudio;vehicleHearing=new du;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{this.sceneRenderer.setCompassHovered(!0);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,o=-((e.clientY-i.top)/i.height*2-1),l=this.naming,c=l.names,h=this.sceneRenderer.pickBodyAt(r,o);if(h){this.showHoverTooltip(e,this.bodyName(h));return}const d=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(r,o):void 0,u=d?this.interpretationShown?.bodies.find(y=>y.id===d):void 0,p=u?this.said.read(u.title)||(u.model.id==="figure"?l.decorKind("entity",ry.entity):void 0):void 0;if(p){this.showHoverTooltip(e,p);return}const f=this.sceneRenderer.pickDecorAt(r,o),g=f?this.ufoElement.sighting.decor.find(y=>y.id===f):void 0;if(g){this.showHoverTooltip(e,this.said.read(g.title)||l.decorKind(g.kind,ry[g.kind]));return}const m=this.trafficTooltipAt(r,o);if(m){this.showHoverTooltip(e,m);return}const v=this.sceneRenderer.pickSatelliteAt(r,o);if(v){this.showHoverTooltip(e,(c?.satelliteTooltip??IC).replace("{name}",v.name).replace("{mag}",v.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(v.heightKm).toLocaleString()));return}const x=this.sceneRenderer.pickStarAt(r,o);if(x){const y=x.star.mag,b=x.altitudeDeg,w=b<0?c?.starTooltipBelow??CC:c?.starTooltip??TC;this.showHoverTooltip(e,w.replace("{name}",l.star(x.star)).replace("{mag}",y.toLocaleString(void 0,{maximumFractionDigits:Math.abs(y)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(b)))));return}this.hoverTooltip.hidden=!0};bodyName(e){const t=e.startsWith(ny)?e.slice(ny.length):void 0,i=t?Nw.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const n=e.startsWith(sy)?Fu.byId(e.slice(sy.length)):void 0;if(n)return this.naming.nova(n);const s=AC[e];return s===void 0?e:this.naming.body(e,s)}get naming(){return this.sceneNaming}sceneNaming=new Nu;namesLanguage="en";async loadSceneNames(){const e=Fc(hs.preferencesFor(this),Hc);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await Gy(e);e===this.namesLanguage&&this.applySceneNaming(new Nu(t))}renderLoaderText(e,t){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((o,l)=>{l>0&&s.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of o){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??Lf;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();this.hoverTooltip.style.left=`${e.clientX-i.left+12}px`,this.hoverTooltip.style.top=`${e.clientY-i.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash(e){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),Oi.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(uh(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=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"&&this.sceneRenderer.frame(performance.now())};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>${gS}</style>${mS}`,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 ut(this.sceneCanvas);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.sceneRenderer.onFirstFrameHold=s=>{t.hidden=!s,this.ufoElement.captionHeld=s,this.ufoElement.holdClock(s)},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(jf),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,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"&&Dn.fill(n,this)}),this.creditsButton.title=Lf,this.creditsButton.setAttribute("aria-label",Lf),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),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 ei.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new qn(hs.preferencesFor(this))}saidTexts;traceLabelsFor;traceLabels(e){const t=hs.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 ei.GESTURES)document.addEventListener(t,this.handlePageGesture,!0);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u")&&(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 ei.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===pl||e===fl)&&i!==t&&this.forwardPlayerAttributes()}forwardPlayerAttributes(){for(const e of[pl,fl]){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=at(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}=ci(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)}decorGroundPointAt(e,t,i){return this.sceneRenderer.decorGroundPointAt(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=Nc.json(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.sightingData=i}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.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?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 Ou(this,()=>document.createElement(Uu))}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.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)}referenceFailedToLoad(e){return this.sceneRenderer.referenceFailedToLoad(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}setTerrainProviders(e){this.sceneRenderer.setTerrainProviders(e)}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=lt.CANVAS_HEIGHT_PX,i=Rt.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:Rf,url:this.getAttribute("star-catalog-src")??LC},{magnitudeLimit:Pc,url:this.getAttribute("deep-star-catalog-src")??kC}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>Rf?Pc:Rf;const n=await Hs.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=Pc||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=nn.gainFor(e.instrument,{fNumber:at(e,0)?.fNumber,fieldOfViewDeg:Ui.fovOf(e,0),exposureSeconds:e.exposure});return sa(OC,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=xs.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,n=this.degreesPerPixelAt(e),s=oo.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(e).length,xs.instants(this.decorWithTraffic(this.ufoElement.sighting),at(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,o=>this.applySceneAt(t.fromMs+t.ms*o/(r-1),{sky:Math.floor(o*s/r)!==Math.floor((o-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:Ui.fovOf(this.ufoElement.sighting,e)/t}roadGradeAt(e,t){return e.observerTrack.allKeyframes.length<2?0:Qo.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(uh(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??ei.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(e)),this.sceneRenderer.setContrails(this.traffic?.contrails??ei.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(e));const n=at(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=at(i,0),r=hi(i,0),o=Yn(i.event.time??{},n?.lng??md.lng,i.event.utcOffsetHours),l=i.weatherSource!==void 0&&o?vx(o):void 0,c=Object.fromEntries(Ks(hi(i,e)).map(T=>[T.id,su(e,i.weatherTrack,r,s,n,T.id,T.instances?.length?void 0:l)]));this.sceneRenderer.setCloudOffset(su(e,i.weatherTrack,r,s,n,void 0,l),c),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,e)}:md),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(nn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:Ui.fovOf(i,e),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,Si.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso),this.sceneRenderer.setGait(Ft.bodyAt(i,e,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(at(i,0),n,e),this.placeBodiesAt(e,t===void 0),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),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??md.lat,d=n?.lng??md.lng,u=Yn(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=[...this.interpretationShown?.reentries??[],...this.fireballs?.reentries??[]];if(this.sceneRenderer.setReentries(f.length===0?[]:At.viewsAt(f,e,{lat:h,lng:d,heightM:p.elevationM})),t&&!t.sky)return;if(!u){this.sceneRenderer.setAstronomy(NC);return}const g=new Date(u.getTime()+e),m=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/oo.DEG_PER_SECOND*1e3)),v=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),x=`${Math.floor(g.getTime()/m)}|${Math.round(h/v)}|${Math.round(d/v)}|${Math.round(p.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(x===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=x;const y=Ni("Sun",g,p),b=Ni("Moon",g,p);let w=bi.separationOf(y,b)<1?bi.viewAt(g,p):void 0;if(w){const T=bi.offsetOf(y,b,w.separationDeg);if(w.obscuration>ei.LIMB_FROM_OBSCURATION){const A=this.limbFor(g,p);A&&(w={...w,obscuration:1-ss.uncoveredFraction(A,w.sunRadiusDeg,T),limb:A})}w={...w,horizonShare:bi.horizonShare(w,T,y.altitudeDeg,y.azimuthDeg,cn.distanceKm(g,p))}}const S={...y,magnitude:rf("Sun",g)-2.5*Math.log10(bi.beamFraction(w))};this.lastSun={altitudeDeg:S.altitudeDeg,azimuthDeg:S.azimuthDeg};const _={...b,phase:Ca(g),magnitude:rf("Moon",g),radiusDeg:cn.apparentRadiusDeg(g,p)},M=h4.map(T=>({body:T,position:Ni(T,g,p),magnitude:rf(T,g)}));this.sceneRenderer.setAstronomy({sun:S,moon:_,planets:M,comet:this.cometAt(g,p),novae:Fu.appearancesAt(g,p).map(({outburst:T,position:A,magnitude:R})=>({id:T.id,position:A,magnitude:R})),stars:this.starCatalog?{catalog:this.starCatalog,date:g,observer:p}:void 0,frame:{date:g,observer:p},eclipse:w}),this.ufoElement.setSunAltitude(S.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(e,t){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,Lc.load(PC).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=ss.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||!os.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,ei.fireballArchive.between(n,n+i).then(o=>{r.status=o?"ready":"unavailable",r.records=o??[],r.reentries=r.records.map(l=>os.asReentry(l,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(Uw)),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 o=lv(r,t);return`${o.side??"-"}/${o.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 o=lv(r,t);return{...r,observerSide:o.side,observerFacing:o.facing}});return this.seatedMemo={base:e,seats:i,seated:s},s}ensureTraffic(e){const t=at(e,0),i=t?.lng===void 0?void 0:Yn(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(r===""||s===void 0||t?.lat===void 0||t.lng===void 0){this.traffic={key:r,status:"outside"};return}let o=ei.aircraftProviders.get(this.aircraftSource.id);if(o||ei.aircraftProviders.set(this.aircraftSource.id,o=this.aircraftSource.create()),o.mayCover&&!o.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const l={key:r,status:"loading",startMs:s,observer:{lat:t.lat,lng:t.lng}};this.traffic=l;const c={lat:t.lat,lng:t.lng,heightM:t.elevationM??0},h=vn.MAX_GAP_S*1e3,d=ei.SOUND_LOOKBACK_MS,u={lat:t.lat,lng:t.lng,elevationM:t.elevationM??0},p=(f,g)=>f.TrafficDecor.from(l.tracks??[],c,s,f.TrafficDecor.MAX_OBJECTS,{models:g,sunElevationAt:m=>this.sunElevationAt(m,u)});o.between(c,s-d,s+n+h).then(async f=>{if(this.traffic!==l)return;if(f.status!=="found"){l.status=f.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let g;try{g=await ei.loadTrafficRuntime()}catch{this.traffic===l&&(l.status="unavailable",this.announceTraffic());return}this.traffic===l&&(l.status="ready",l.tracks=f.tracks,l.set=p(g),this.startAircraftSound(l,g),this.announceTraffic(),this.describeTraffic(o,l,g,p),l.set.shown>0&&this.readUpperAir(l,g,s-d,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,o]of n.presence){if(e<o.fromMs||e>o.untilMs)continue;const l=n.flights.get(r),c=l?vn.positionAt(l,i.startMs+e):void 0;c&&t.set(r,{heightM:c.geo.heightM,sunElevationDeg:Xn.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=ei.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,o=>s.towards(o))}trafficInfoAt(e){const t=this.traffic,i=t?.set?.flights.get(e);if(!t||!i||t.startMs===void 0||!t.observer)return;const n=ei.trafficRuntime;if(!n)return;const s=t.descriptions?.get(as.keyOf(i)),r=at(this.ufoElement.sighting,this.lastTimeMs),o={lat:t.observer.lat,lng:t.observer.lng,heightM:r?.elevationM??0},l=n.AmbientNoise.dbA(uh(this.ufoElement.sighting,this.lastTimeMs)),c=n.TrafficInfos.at(i,s,o,t.startMs+this.lastTimeMs,{ambientDbA:l}),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.aircraftAudio=new t.AircraftAudio,this.aircraftAudio.setLevel(this.ufoElement.level),this.interacted&&this.aircraftAudio.resume(),this.aircraftAudio.setPaused(this.ufoElement.playbackState!=="playing")),this.sortOutAudible(e,t)}sortOutAudible(e,t){!e.set||!e.observer||(e.audible=t.TrafficSound.candidates(e.set.flights,e.descriptions??new Map,as.keyOf,{...e.observer,heightM:0},{ambientDbA:t.AmbientNoise.BASE_DB_A}))}pushAircraftSound(e,t){const i=this.aircraftAudio;if(!i)return;const n=ei.trafficRuntime,s=this.traffic,r=s?.set;if(!n||!s||!r||!s.audible||s.startMs===void 0||!s.observer){i.setVoices([]);return}const o=at(e,t),l={lat:s.observer.lat,lng:s.observer.lng,heightM:o?.elevationM??0},c=uh(e,t),h=n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,as.keyOf,l,s.startMs+t,{ambientDbA:n.AmbientNoise.dbA(c),referenceAmplitude:n.AmbientNoise.referenceAmplitude(c)});i.setVoices(h,o?.headingDeg??0)}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(DC)),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=>as.keyOf(c))),r=t.tracks.filter(c=>s.has(as.keyOf(c))&&c.points.length>0),o=new Map,l=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&&(l.set(as.keyOf(c),d),o.set(as.keyOf(c),i.AircraftModels.of(d)))})),!(this.traffic!==t||o.size===0)&&(t.descriptions=l,t.models=o,t.set=n(i,o),this.planContrails(t,i),this.sortOutAudible(t,i),this.announceTraffic())}async readUpperAir(e,t,i,n){if(!e.observer)return;const s=this.upperAirSource??t.UPPER_AIR_SOURCES[0];let r=ei.upperAirProviders.get(s.id);r||ei.upperAirProviders.set(s.id,r=s.create());const o=await r.between(e.observer,i,n);this.traffic!==e||o.status!=="found"||(e.air=o.samples,e.airSource=o.source,this.planContrails(e,t),this.announceTraffic())}planContrails(e,t){!e.set||!e.air||e.startMs===void 0||(e.contrails=t.AircraftContrails.plan(e.set,e.models,e.air,e.startMs))}contrailSunlight(e){const t=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return t;for(const r of i.contrails){const o=n.presence.get(r.id),l=n.flights.get(r.id);if(!o||!l)continue;const c=vn.positionAt(l,i.startMs+Math.min(o.untilMs,Math.max(o.fromMs,e)));c&&t.set(r.id,{heightM:c.geo.heightM,sunElevationDeg:Xn.sunElevationDeg(s,i.observer,c.geo)})}return t}sunElevationAt(e,t){const i=Ni("Sun",new Date(e.t),t);return Xn.sunElevationDeg(i,t,e)}upperAirSource;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??ei.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(Fw)))},s=ei.tleArchive;(async()=>{if(!await s.covers(e))return n("outside");const[r,o]=await Promise.all([s.at(e),je(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new o.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}}satellitePassesDuring(e){const t=this.satellites,i=this.ufoElement.sighting,n=at(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,o=n?.lng??s?.lng;if(!t||r===void 0||o===void 0)return[];const l=Yn(i.event.time??{},o,i.event.utcOffsetHours);if(!l)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:o,elevationM:n?.elevationM??0},d=JSON.stringify([this.satellitesFor,l.getTime(),r,o,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(l,new Date(l.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:p},p}cometAt(e,t){const i=kd.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),o=new Map,l=new Map,c=new Set;for(const f of i.sourceIds){const g=i.getInterpolatedShapeAt(e,f);if(!g)continue;const m={...g,bounds:{...g.bounds,x:g.bounds.x+s.x,y:g.bounds.y+s.y}};o.set(f,m);const v=g.aim?this.sceneRenderer.screenPointOf(ys.directionOf(g.aim,this.directionScratch)):{ndcX:(m.bounds.x+m.bounds.width/2)/n.width*2-1,ndcY:-((m.bounds.y+m.bounds.height/2)/n.height*2-1)},x=v!==void 0&&Math.abs(v.ndcX)<=1&&Math.abs(v.ndcY)<=1,y=x?this.sceneRenderer.decorDistancesAt(v.ndcX,v.ndcY,f):{};c.add(f),(x||g.aim)&&c.delete(f);const b=g.angular?.widthDeg??r.pxToDeg(g.bounds.width),w=this.sizeEstimateOf(f);w.add(b,y);const S=kc.of(t,f);l.set(f,gn.resolve({hypothesisM:this.distanceHypotheses.get(f),derivedM:S&&b>0?lt.distanceMAt(S.widthM,b):void 0,range:w.distanceRangeAt(b),crossing:y}))}for(const[f,g]of o)for(const[m,v]of o){if(m===f||v.transparency>=1||v.bounds.width*v.bounds.height<=g.bounds.width*g.bounds.height||!(g.bounds.x>=v.bounds.x&&g.bounds.y>=v.bounds.y&&g.bounds.x+g.bounds.width<=v.bounds.x+v.bounds.width&&g.bounds.y+g.bounds.height<=v.bounds.y+v.bounds.height))continue;const y=l.get(m);y&&l.set(f,{distanceM:y.distanceM*.999,basis:y.basis});break}this.depths=l;const h=i.sourceIds,d=[];for(const[f,g]of o)d.push({sourceId:f,shape:g,distanceM:l.get(f).distanceM,renderOrder:h.indexOf(f),aim:g.aim,hidden:c.has(f)||this.interpretationShown!==void 0&&(!this.comparing||g.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const p=(at(t,e)?.rollDeg??0)+Ft.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:Rt.starPointsOf(t.instrument),rollRad:p*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(e){this.interpretationShown=e,this.syncAccountHidden(),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){this.comparing=e,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs)}get confrontation(){return this.confrontationReadings}groundAlong(e,t,i){const n=this.sceneRenderer.bodyGround,s=dt.eyeOf(this.ufoElement.sighting,i,n);return s?dt.lineOfSightMeetsGround(s,e,t,n):void 0}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=u=>dt.eyeOf(n,u,i),r=new dt(e,i,s).at(t),o=s(t);if(!r||!o)return;const l=r.eastM-o.eastM,c=r.northM-o.northM,h=r.upM-o.upM,d=Math.hypot(l,c);return{azimuthDeg:(Math.atan2(l,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}}directionToBody(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=f=>dt.eyeOf(n,f,i),r=new dt(e,i,s),o=r.at(t)?t:e.track[0]?.t,l=o===void 0?void 0:r.at(o),c=o===void 0?void 0:s(o);if(!l||!c)return;const h=l.eastM-c.eastM,d=l.northM-c.northM,u=l.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 o=this.sceneRenderer.bodyGround,l=f=>dt.eyeOf(n,f,o);i&&(s=i.bodies.map(f=>new dt(f,o,l).at(e)).filter(f=>f!==void 0));const c=hi(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?l(e):void 0;if(u&&(r=new vi(n.timeline).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(RC,{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&&hi(e,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(e){const t=hi(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?Yn(n,s?.lng??0,e.event.utcOffsetHours):void 0,o=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,l=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=Oi.schedule({durationMs:o,seed:l,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?Yn(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,o=Math.round(n.getTime()/1e3)+Math.round(t.lat*1e3),l=oi.schedule({ratePerHour:oi.observedRatePerHour(oi.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:oi.TYPICAL_VELOCITY_KM_S,seed:o}),c=El.activeAt(n).map(d=>{const u=El.radiantPosition(d.shower,n,s);return{entry:d,position:u,rate:El.observedRatePerHour(d.zhr,u.altitudeDeg,d.shower.populationIndex)}}).sort((d,u)=>u.rate-d.rate)[0];if(!c||c.rate<=0){this.sceneRenderer.setMeteorShower(l,0,0);return}const h=ro.schedule({ratePerHour:c.rate,durationMs:r,velocityKmS:c.entry.shower.velocityKmS,seed:o+1});this.sceneRenderer.setMeteorShower([...h,...l],c.position.altitudeDeg,c.position.azimuthDeg)}meteorByRank(e){this.ensureMeteorSchedule(this.ufoElement.sighting);const t=[...this.sceneRenderer.meteorSchedule].filter(s=>s.t+s.durationMs<=this.ufoElement.seekableDuration).sort((s,r)=>r.brightness-s.brightness);if(t.length===0)return;const i=t[e%t.length],n=this.sceneRenderer.meteorMidpoint(i);if(n)return{t:Math.round(i.t+i.durationMs*.45),...n}}lensOpticsAt(e){const t=this.ufoElement.sighting,i=t.instrument,n=i.frame,s=at(t,e),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const o=Rt.focalLengthMmFor(i,Ui.fovOf(t,e));if(o!==void 0)return{focalLengthMm:o,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return Ts.of(t.instrument,lt.CANVAS_HEIGHT_PX,Ui.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new wC,this.sizeEstimates.set(e,t)),t}}const Uu="rr0-scene";function FC(){qu(),customElements.get(Uu)||customElements.define(Uu,ei)}class UC{constructor(e,t){this.timeline=e,this.clock=t}currentPointer=null;shapePrototype=null;sourceId="";start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.clock.start(i=>this.recordSample(i))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop()}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=Ay(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class BC{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)}}const Bu="rr0-duration-input",zC=`
|
|
9652
|
+
`);let s=Hs.cache.get(n);return s||(s=Promise.all(i.map(r=>Hs.load(r.url))).then(r=>r.reduce((o,l)=>Hs.concat(o,l))),Hs.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 Nt{constructor(e){if(this.heights=e,e.length!==Nt.WIDTH*Nt.HEIGHT)throw new Error(`a lunar relief has ${Nt.WIDTH*Nt.HEIGHT} samples, not ${e.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*Nt.SAMPLES_PER_DEGREE;static HEIGHT=180*Nt.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=Nt.SAMPLES_PER_DEGREE,n=(t%360+360)%360*i-.5,s=(90-e)*i-.5,r=Math.floor(n),o=Math.floor(s),l=n-r,c=s-o,h=(p,f)=>{const g=(p%Nt.WIDTH+Nt.WIDTH)%Nt.WIDTH,m=Math.min(Nt.HEIGHT-1,Math.max(0,f));return this.heights[m*Nt.WIDTH+g]},d=h(r,o)*(1-l)+h(r+1,o)*l,u=h(r,o+1)*(1-l)+h(r+1,o+1)*l;return(d*(1-c)+u*c)*Nt.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>=Nt.BAND_FROM_DEG&&n<=Nt.BAND_TO_DEG}static withBump(e,t,i,n=.4){const s=new Int8Array(Nt.WIDTH*Nt.HEIGHT),r=Nt.SAMPLES_PER_DEGREE,o=Math.ceil(n*r),l=Math.floor(t*r),c=Math.floor((90-e)*r);for(let h=-o;h<=o;h++)for(let d=-o;d<=o;d++)Math.hypot(d,h)<=o&&(s[(c+h)*Nt.WIDTH+(l+d+Nt.WIDTH)%Nt.WIDTH]=Math.round(i/Nt.UNIT_KM));return new Nt(s)}static smooth(){return new Nt(new Int8Array(Nt.WIDTH*Nt.HEIGHT))}}class ss{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=ss.SAMPLES){const{s,u:r,w:o,distanceKm:l}=ss.frame(e,t),c=Math.PI/180,h=new Float32Array(n),d=Nt.REFERENCE_RADIUS_KM;for(let u=0;u<n;u++){const p=u/n*2*Math.PI,f=Math.cos(p),g=Math.sin(p),m=f*r[0]+g*o[0],v=f*r[1]+g*o[1],x=f*r[2]+g*o[2];let y=0;for(let b=ss.SEARCH_FROM_DEG;b<=ss.SEARCH_TO_DEG;b+=ss.SEARCH_STEP_DEG){const w=Math.cos(b*c),S=Math.sin(b*c),_=w*s[0]+S*m,M=w*s[1]+S*v,T=w*s[2]+S*x,A=Math.asin(Math.max(-1,Math.min(1,T)))/c,R=Math.atan2(M,_)/c,C=d+i.heightKm(A,R),k=Math.atan2(C*S,l-C*w);k>y&&(y=k)}h[u]=y/c}return{radiusDeg:h,meanRadiusDeg:Math.asin(d/l)/c}}static frame(e,t){const i=new ha(t.lat,t.lng,t.elevationM),n=Tr(e),s=rm(e,i,!1),r=new Mt(s.x-n.x,s.y-n.y,s.z-n.z,n.t),o=Math.hypot(r.x,r.y,r.z)*ss.AU_KM,l=ss.bodyFixed(e),c=l(r),h=Math.hypot(c[0],c[1],c[2]),d=[c[0]/h,c[1]/h,c[2]/h],u=YD(e,i),p=pg(u),f=_r(u,new Mt(-r.x,-r.y,-r.z,n.t)),g=Math.asin(f.z/Math.hypot(f.x,f.y,f.z)),m=Math.atan2(-f.y,f.x),v=new Mt(-Math.sin(g)*Math.cos(m),Math.sin(g)*Math.sin(m),Math.cos(g),n.t),x=new Mt(-Math.sin(m),-Math.cos(m),0,n.t);return{s:d,u:l(_r(p,v)),w:l(_r(p,x)),distanceKm:o}}static surfacePoint(e,t,i,n){const{s,u:r,w:o}=ss.frame(e,t),l=Math.PI/180,c=[0,1,2].map(d=>Math.cos(i*l)*r[d]+Math.sin(i*l)*o[d]),h=[0,1,2].map(d=>Math.cos(n*l)*s[d]+Math.sin(n*l)*c[d]);return{latDeg:Math.asin(h[2])/l,lonDeg:Math.atan2(h[1],h[0])/l}}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 o=0;o<n;o++){const l=o/n*2*Math.PI,c=Math.cos(l),h=Math.sin(l),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 g=Math.max(0,d-p),m=Math.max(g,e.radiusDeg[o]);f>m&&(r+=.5*(f*f-m*m))}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=c4(ue.Moon,e),i=Math.PI/180,n=t.ra*15*i,s=t.dec*i,r=t.spin*i,o=(c,[h,d,u])=>[Math.cos(c)*h+Math.sin(c)*d,-Math.sin(c)*h+Math.cos(c)*d,u],l=(c,[h,d,u])=>[h,Math.cos(c)*d+Math.sin(c)*u,-Math.sin(c)*d+Math.cos(c)*u];return c=>o(r,l(Math.PI/2-s,o(Math.PI/2+n,[c.x,c.y,c.z])))}static subObserverPoint(e,t){const i=new ha(t.lat,t.lng,t.elevationM),n=Tr(e),s=rm(e,i,!1),r=ss.bodyFixed(e)(new Mt(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),o=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/o)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class Lc{static cache=new Map;static load(e){let t=Lc.cache.get(e);return t||(t=Lc.fetchRelief(e).catch(()=>{}),Lc.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 Nt(new Int8Array(i.buffer,i.byteOffset,i.length))}}class Nu{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 so.point(e,this.names?.compassPoints)}towards(e){return so.towards(e,this.names)}}const cC="Global Meteor Network",hC="https://globalmeteornetwork.org/data/",dC="“Thunder” by Jerimee",uC="https://creativecommons.org/licenses/by/3.0/",pC="CC BY 3.0";class Dn{static fill(e,t){e.innerHTML="";const i=h=>e.appendChild(h),n=t.currentTerrainAttribution;n&&i(Dn.text(n));const s=t.currentRoadAttribution;s&&i(Dn.text(s));const r=t.ufoElement.observerMapCredit;r&&!n?.includes(r)&&i(Dn.text(r));for(const h of t.decorModelCredits){const d=h.author?` — ${h.author}`:"",u=document.createElement("li");h.sourceUrl?u.append(Dn.link(h.sourceUrl,h.title),document.createTextNode(`${d} (${h.license})`)):u.textContent=`${h.title}${d} (${h.license})`,i(u)}for(const h of t.ufoElement.sighting.references){if(!h.credit)continue;const d=document.createElement("li");h.creditUrl?d.appendChild(Dn.link(h.creditUrl,h.credit)):d.textContent=h.credit,i(d)}if(t.ufoElement.sighting.traces.length>0){const h=new qn(hs.preferencesFor(t)),d=new Set(t.ufoElement.sighting.traces.map(u=>h.read(u.source)).filter(u=>!!u));for(const u of d)i(Dn.text(u))}const o=t.satelliteState;if(o.status==="ready"&&o.credit){const h=document.createElement("li");h.appendChild(Dn.link(o.creditUrl??"",o.credit)),i(h)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const h=document.createElement("li");h.append(Dn.link(hC,cC),document.createTextNode(" (CC BY 4.0)")),i(h)}const l=t.aircraftState;if(l.status==="ready"&&l.shown>0){const h=document.createElement("li");if(h.appendChild(Dn.link(l.creditUrl,l.credit)),i(h),l.trailCredit){const d=document.createElement("li");d.appendChild(Dn.link(l.trailCredit.creditUrl,l.trailCredit.credit)),i(d)}}const c=Dn.text(`${dC} (`);c.append(Dn.link(uC,pC),document.createTextNode(")")),i(c)}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 fC=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,mC=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,gC=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,vC=20,bC=1;class yC{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}}to.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(fC,this.ambientVolume).then(o=>this.applyIfCurrent(o,r,()=>this.ambientToken,l=>{this.ambientSource=l?.source,this.ambientGain=l?.gain,l&&(l.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/vC,1);const s=i>bC;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(mC,this.windVolume).then(o=>this.applyIfCurrent(o,r,()=>this.windToken,l=>{this.windSource=l?.source,this.windGain=l?.gain,l&&(l.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(gC,.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 Mr{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[n,s]=this.perifocalAxes(),r=Math.sqrt(Mr.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*Mr.stumpffC(n),o=t-i*i*i/Math.sqrt(Mr.SUN_GM_AU3_PER_DAY2)*Mr.stumpffS(n);return{x:r*this.perihelionPosition.x+o*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+o*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+o*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(Mr.SUN_GM_AU3_PER_DAY2)*Math.abs(e),n=o=>{const l=this.inverseSemiMajorAxis*o*o,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*o*o*o*Mr.stumpffS(l)+c*o};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let o=0;o<Mr.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);o++){const l=(r+s)/2;n(l)<i?r=l:s=l}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),o=Math.sin(t),l=Math.cos(i),c=Math.sin(i);return[{x:n*r-s*o*l,y:s*r+n*o*l,z:o*c},{x:-n*o-s*r*l,y:-s*o+n*r*l,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 Nw=[{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 kd{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 Nw.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=Ht(t),s=this.earthPositionAt(n),r=this.apparentPositionOf(e,2451545+n.tt,s),o=this.subtract(r,s),l=this.length(r),c=this.length(o),h=this.tailEndAt(e,r,s,l,n,t,i),d=this.horizontalOf(o,n,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:l,earthDistanceAu:c,elongationDeg:this.angleBetween(o,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(e,l,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,o){if(e.tailLengthAu===void 0)return{};const l=1+e.tailLengthAu/n,c=this.subtract({x:t.x*l,y:t.y*l,z:t.z*l},i),h=this.subtract(t,i);return{tailEnd:this.horizontalOf(c,s,r,o),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 o=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(t-o)}return s}static horizontalOf(e,t,i,n){const s=_r(VD(),new Mt(e.x,e.y,e.z,t)),r=_r(bw(t),s),o=rm(t,new ha(n.lat,n.lng,n.elevationM),!0),l=new Mt(r.x-o.x,r.y-o.y,r.z-o.z,t),c=op(l);return gg(c.ra,c.dec,i,n)}static earthPositionAt(e){return _r(GD(),oa(ue.Earth,e))}static julianDayOf(e){return 2451545+Ht(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new Mr(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 Cf=[{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 Fu{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return Cf.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),n=[];for(const s of Cf){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Ss.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 Cf.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,o]=i[s-1]??i[0],[l,c]=i[s]??i[0];if(l===r)return o;const h=Math.min(1,Math.max(0,(n-r)/(l-r)));return o+h*(c-o)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const MC=[{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}],Fl=6.5;class El{static activeAt(e){return MC.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)),o=this.wrappedDelta(i,s),l=this.wrappedDelta(s,n),c=this.wrappedDelta(r,s);return o<0?o<-l?0:1+o/l:o>0?o>c?0:1-o/c:1}static observedRatePerHour(e,t,i,n=Fl){if(t<=0)return 0;const s=Fl-n;return e*Math.sin(t*Math.PI/180)/Math.pow(i,s)}static radiantPosition(e,t,i){return Ss.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 oi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=Ht(e),n=new np(0,wD(e).elon-90,1),s=_r(qD(i),mg(n,i)),r=op(s);return gg(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=Fl){const i=oi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),n=Fl-t;return(oi.QUIET_RATE_PER_HOUR+i)/Math.pow(oi.POPULATION_INDEX,n)}static schedule(e){const t=new lp(e.seed^1542469173);return ro.schedule(e).map(i=>{const n=oi.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=oi.turnAround(n,t.between(0,360)),o={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:oi.toHorizontal(o),bearingDeg:oi.bearingFrom(o,n)}})}static turnAround(e,t){const[i,n]=oi.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]=oi.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,r=oi.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=oi.normalise(oi.cross(e,t));return[i,oi.normalise(oi.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=oi.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=oi.turnAround(t,e.bearingDeg),n=e.fromRadiantDeg*Math.PI/180;return oi.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 ey="https://ufoathome.org/tle/index.json";class en{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??en.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(ey)||e.push(ey),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${en.FIRST_SNAPSHOT}T00:00:00Z`)-en.MAX_ELEMENT_AGE_DAYS*en.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)-en.MAX_ELEMENT_AGE_DAYS*en.DAY_MS&&e.getTime()<=Date.parse(n.to)+en.MAX_ELEMENT_AGE_DAYS*en.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:i,base:n}=t,s=[],r=[];for(const o of Object.keys(i.kinds)){const l=await this.kindAt(o,e,i,n);s.push(...l),r.push(this.coverageOf(o,e,i,l.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*en.DAY_MS,o=Math.floor(s/r),l=s-o*r<r/2?o-1:o+1,c=new Set(i.kinds[e].bins),h=[o,l].map(g=>new Date(g*r).toISOString().slice(0,10)).filter(g=>c.has(g));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,n).href),...h.map(g=>this.binary(new URL(`${e}/${g}.bin`,n).href))]),p=new Map;for(const g of u)for(const m of en.decode(g,i.recordBytes)){const v=p.get(m.norad);(!v||Math.abs(m.epochMs-s)<Math.abs(v.epochMs-s))&&p.set(m.norad,m)}const f=[];for(const g of p.values()){const m=Math.abs(g.epochMs-s)/en.DAY_MS;if(m>en.MAX_ELEMENT_AGE_DAYS)continue;const v=d[g.norad]??{name:String(g.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>s||f.push({norad:g.norad,name:v.name,kind:e,launch:v.launch,stdMag:v.stdMag,elements:g,ageDays:m})}return f}coverageOf(e,t,i,n){const{from:s,to:r}=i.kinds[e],o=t.getTime(),l=en.MAX_ELEMENT_AGE_DAYS*en.DAY_MS,c=n?"covered":o<Date.parse(s)-l?"before":o>Date.parse(r)+l?"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 wC{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const i=lt.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(t.inFrontM!==void 0){const i=lt.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:lt.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:lt.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class oo{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*oo.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=oo.degOver(e)/t;return i<1?1:Math.min(oo.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class nn{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 oo.DEG_PER_SECOND*3600}static graspOf(e,t={}){const i=t.exposureSeconds??e.exposureSeconds,n=t.fNumber??e.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return nn.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??nn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,o=nn.resolutionArcsec(e,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,nn.trailLimitedSeconds(o)),resolutionArcsec:o}}static resolutionArcsec(e,t,i){const s=(e.detailUm??nn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*nn.ARCSEC_PER_RADIAN,r=1.22*nn.WAVELENGTH_M/(i/1e3)*nn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(e){return e/nn.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=nn.graspOf(e,t),n=nn.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,o=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*o)}static gainFor(e,t){const i=t.fieldOfViewDeg===void 0?void 0:Rt.focalLengthMmFor(e,t.fieldOfViewDeg);return nn.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const ty=111320,dc=Math.PI/180,xC=1.02,SC=1;class kc{static of(e,t){const i=kc.sightings(e,t);if(i.length<2)return;const n=kc.baseline(i);if(!n)return;const{near:s,far:r,closedM:o}=n,l=Math.tan(r.widthDeg/2*dc)===0?0:Math.tan(s.widthDeg/2*dc)/Math.tan(r.widthDeg/2*dc);if(l<xC)return;const c=o/(l-1),h=lt.sizeMAt(c,s.widthDeg),d=i.map(u=>({t:u.t,m:lt.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.m)),fromT:r.t,toT:s.t,closedM:o}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(o=>o.sourceId===t)?.shape,s=n?.angular?.widthDeg,r=at(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=kc.closedAlongSight(i,n),[r,o,l]=s>=0?[n,i,s]:[i,n,-s];l<SC||r.widthDeg<=o.widthDeg||(!t||l>t.closedM)&&(t={near:r,far:o,closedM:l})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*ty,n=(t.lng-e.lng)*ty*Math.cos(e.lat*dc),s=(e.sightAzimuthDeg??0)*dc;return i*Math.cos(s)+n*Math.sin(s)}}class gn{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:gn.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:gn.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:gn.atLeastNearest(e.derivedM),basis:"derived"};const t=gn.largest(e.range?.minM,e.crossing?.behindM),i=gn.smallest(e.range?.maxM,e.crossing?.inFrontM),n=t===void 0?void 0:t*gn.MARGIN,s=i===void 0?void 0:i/gn.MARGIN;return n!==void 0&&s!==void 0?{distanceM:gn.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:gn.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<gn.CONVENTIONAL_M?{distanceM:gn.atLeastNearest(s),basis:"bounded"}:{distanceM:gn.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(gn.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 Pf=Math.PI/180;class dt{constructor(e,t,i){this.body=e,this.ground=t;const n=[...e.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)dt.collect(this.motionKeys,s.t,s.motions),dt.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};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 dt.channelsAt(this.motionKeys,e,0)}lightsAt(e){return this.lightKeys.size>0?dt.channelsAt(this.lightKeys,e,void 0):void 0}static channelsAt(e,t,i){const n={};for(const[s,r]of e){let o=r.length-1;for(;o>=0&&r[o].t>t;)o--;if(o<0){i!==void 0&&(n[s]=i);continue}const l=r[o],c=r[Math.min(o+1,r.length-1)],h=c===l||c.t===l.t?0:Math.min(1,(t-l.t)/(c.t-l.t));n[s]=dt.lerp(l.value,c.value,h)}return n}static eyeOf(e,t,i){const n=at(e,0),s=at(e,t),o=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ci(s.lat,s.lng,n.lat,n.lng):void 0,l=o?o.x:0,c=o?-o.z:0;return{eastM:l,northM:c,upM:i.heightAt(l,c)+dt.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(e,t,i,n){const s=dt.directionOf(t,i),r=c=>e.upM+s.upM*c-n.heightAt(e.eastM+s.eastM*c,e.northM+s.northM*c);let o=0,l=0;for(;l<dt.MAX_RANGE_M;){if(l=o+Math.max(.5,o*.01),r(l)<=0){for(let c=0;c<30;c++){const h=(o+l)/2;r(h)<=0?l=h:o=h}return l}o=l}}static directionOf(e,t){const i=e*Pf,n=t*Pf;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=t.length-1;for(;i>0&&t[i].t>e;)i--;const n=t[i];if(!n.present)return;const s=t[Math.min(i+1,t.length-1)],r=s===n||s.t===n.t?0:Math.min(1,(e-n.t)/(s.t-n.t)),o=dt.lerp(n.eastM,s.eastM,r),l=dt.lerp(n.northM,s.northM,r),c={widthM:dt.lerp(n.sizeM.widthM,s.sizeM.widthM,r),lengthM:dt.lerp(n.sizeM.lengthM,s.sizeM.lengthM,r),heightM:dt.lerp(n.sizeM.heightM,s.sizeM.heightM,r)},h={headingDeg:dt.lerpAngle(n.attitude.headingDeg,s.attitude.headingDeg,r),pitchDeg:dt.lerp(n.attitude.pitchDeg,s.attitude.pitchDeg,r),rollDeg:dt.lerp(n.attitude.rollDeg,s.attitude.rollDeg,r)};let d;if("aboveGroundM"in n.vertical&&"aboveGroundM"in s.vertical){const u=dt.lerp(n.vertical.aboveGroundM,s.vertical.aboveGroundM,r);d=this.groundUnderFootprint(o,l,c,h.headingDeg)+u+c.heightM/2}else d=dt.lerp(this.centreUpOf(n),this.centreUpOf(s),r);return{id:this.body.id,model:this.body.model,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:o,northM:l,upM:d,sizeM:c,attitude:h,appearance:{color:(r<1?n:s).appearance.color,albedo:dt.lerp(n.appearance.albedo,s.appearance.albedo,r),luminanceCdM2:dt.lerp(n.appearance.luminanceCdM2,s.appearance.luminanceCdM2,r)},flame:dt.flameBetween(n.flame,s.flame,r),motions:this.motionsAt(e),lights:this.lightsAt(e),throwsFlame:this.body.track.some(u=>u.flame!==void 0&&u.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:dt.lerp(n.lengthM,s.lengthM,i),widthM:dt.lerp(n.widthM,s.widthM,i),luminanceCdM2:dt.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(e){return"upM"in e.vertical?e.vertical.upM:this.groundUnderFootprint(e.eastM,e.northM,e.sizeM,e.attitude.headingDeg)+e.vertical.aboveGroundM+e.sizeM.heightM/2}groundUnderFootprint(e,t,i,n){const s=n*Pf,r={eastM:Math.cos(s),northM:-Math.sin(s)},o={eastM:Math.sin(s),northM:Math.cos(s)};let l=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;l=Math.max(l,this.ground.heightAt(e+r.eastM*d+o.eastM*u,t+r.northM*d+o.northM*u))}return l}place(e,t){const i=[];let n;for(const s of e){const r=s.sizeM??n?.sizeM??dt.DEFAULT_SIZE,o={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},l={color:s.appearance?.color??n?.appearance.color??dt.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??dt.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??dt.DEFAULT_APPEARANCE.luminanceCdM2},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;n={t:s.t,...c,sizeM:r,attitude:o,appearance:l,flame:h,present:d},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}}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?dt.lineOfSightMeetsGround(n,e.azimuthDeg,e.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=dt.directionOf(e.azimuthDeg,e.altitudeDeg),o=n.eastM+r.eastM*s,l=n.northM+r.northM*s;return{eastM:o,northM:l,vertical:this.verticalOf(e,t)??{upM:n.upM+r.upM*s}}}static lerp(e,t,i){return e+(t-e)*i}static lerpAngle(e,t,i){const n=((t-e)%360+540)%360-180;return((e+n*i)%360+360)%360}}class At{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=1.5;static FADE_MS=600;static TRAIN_POINTS=8;static leadAt(e,t){const i=e.track;if(i.length<2||t<i[0].t||t>i[i.length-1].t)return;let n=0;for(;n<i.length-2&&i[n+1].t<t;)n++;const s=i[n],r=i[n+1],o=r.t-s.t,l=o>0?(t-s.t)/o:0,[c,h]=At.alongGreatCircle(s,r,l);return{lat:c,lng:h,heightM:(s.altitudeKm+(r.altitudeKm-s.altitudeKm)*l)*1e3}}static viewsAt(e,t,i){const n=[];for(const s of e){const r=s.track[0]?.t??0,o=s.track[s.track.length-1]?.t??0;s.fragments.forEach((l,c)=>{const h=l.fromT??r,d=l.untilT??o;if(t<h||t>d)return;const u=(l.lagS??0)*1e3,p=At.leadAt(s,t-u);if(!p)return;const f=At.seenFrom(i,p);if(f.altitudeDeg<0)return;const g=Math.min(At.FADE_MS,(d-h)/4),m=g>0?Math.min(1,(t-h)/g,(d-t)/g):1,v=-2.5*Math.log10(Math.max(m,.001)),x=l.absoluteMagnitude+5*Math.log10(f.distanceKm/At.STANDARD_DISTANCE_KM)+v,y=[f],b=(l.trainS??At.DEFAULT_TRAIN_S)*1e3;for(let w=1;w<=At.TRAIN_POINTS;w++){const S=Math.min(b*w/At.TRAIN_POINTS,t-h),_=At.leadAt(s,t-u-S);if(!_||(y.push(At.seenFrom(i,_)),S>=t-h))break}n.push({reentryId:s.id,fragmentId:l.id??String(c),head:f,magnitude:x,color:l.color??At.DEFAULT_COLOR,train:y})})}return n}static seenFrom(e,t){const i=At.ecef(e),n=At.ecef(t),s=n[0]-i[0],r=n[1]-i[1],o=n[2]-i[2],l=e.lat*At.DEG,c=e.lng*At.DEG,h=-Math.sin(c)*s+Math.cos(c)*r,d=-Math.sin(l)*Math.cos(c)*s-Math.sin(l)*Math.sin(c)*r+Math.cos(l)*o,u=Math.cos(l)*Math.cos(c)*s+Math.cos(l)*Math.sin(c)*r+Math.sin(l)*o,p=Math.hypot(h,d,u);return{altitudeDeg:Math.asin(u/p)/At.DEG,azimuthDeg:(Math.atan2(h,d)/At.DEG+360)%360,distanceKm:p/1e3}}static ecef(e){const t=e.lat*At.DEG,i=e.lng*At.DEG,n=Math.sin(t),s=At.A/Math.sqrt(1-At.E2*n*n);return[(s+e.heightM)*Math.cos(t)*Math.cos(i),(s+e.heightM)*Math.cos(t)*Math.sin(i),(s*(1-At.E2)+e.heightM)*n]}static alongGreatCircle(e,t,i){const n=h=>{const d=h.lat*At.DEG,u=h.lng*At.DEG;return[Math.cos(d)*Math.cos(u),Math.cos(d)*Math.sin(u),Math.sin(d)]},s=n(e),r=n(t),o=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),l=Math.acos(o);let c;if(l<1e-12)c=s;else{const h=Math.sin((1-i)*l)/Math.sin(l),d=Math.sin(i*l)/Math.sin(l);c=[s[0]*h+r[0]*d,s[1]*h+r[1]*d,s[2]*h+r[2]*d]}return[Math.atan2(c[2],Math.hypot(c[0],c[1]))/At.DEG,Math.atan2(c[1],c[0])/At.DEG]}}class yg{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=yg.FIRST_DAY}}class EC{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 _C="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",Mm=[{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 EC(_C,a=>yg.mayCover(a),async()=>new(await je(async()=>{const{AdsbLolArchiveProvider:a}=await import("./AdsbLolArchiveProvider-Ir8tinqO.js");return{AdsbLolArchiveProvider:a}},[],import.meta.url)).AdsbLolArchiveProvider)}];class vn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const n=vn.positionAt(e,i);if(!n)return;const s=At.seenFrom(t,n.geo);if(!(s.altitudeDeg<0))return{track:e,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:vn.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(n=>vn.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*vn.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,o=r.t-s.t;if(o>vn.MAX_GAP_S*1e3)return;const l=o>0?(t-s.t)/o:0,c=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*l,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*l,lng:vn.wrapLongitude(s.lng+h*l),heightM:c*vn.FT_TO_M},altitudeFt:c,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(e,t,i){const n=vn.positionAt(e,i-500),s=vn.positionAt(e,i+500);if(!n||!s)return;const r=vn.unit(At.seenFrom(t,n.geo)),o=vn.unit(At.seenFrom(t,s.geo)),l=Math.min(1,Math.max(-1,r[0]*o[0]+r[1]*o[1]+r[2]*o[2]));return Math.acos(l)*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 iy="https://ufoathome.org/fireballs/index.json";class os{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??os.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(iy)||e.push(iy),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=os.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!os.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=os.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=At.seenFrom(t,n);if(!(s.altitudeDeg<0))return{record:e,peak:s,magnitude:e.peakMagnitude+5*Math.log10(s.distanceKm/At.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:os.COLOR,trainS:os.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}}const $o=Math.PI/180,uc=180/Math.PI;class vi{constructor(e){this.timeline=e}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;at(e,t,i,n){const s=[];for(const r of t){const o=vi.projectionOf(r,i,n?.(r));if(o)for(const l of r.explains){const c=this.timeline.getInterpolatedShapeAt(e,l);!c||c.transparency>=1||s.push({...vi.compare(l,r.id,{aim:c.aim,angular:c.angular},o),title:c.title})}}return s}static compare(e,t,i,n){const s=[],r=i.aim?vi.separationDeg(i.aim,n.aim):void 0;if(r!==void 0){const c=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;r>Math.max(vi.DIRECTION_TOLERANCE_DEG,c)&&s.push("direction")}const o=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,l=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0;return o!==void 0&&!vi.withinSize(o)&&s.push("width"),l!==void 0&&!vi.withinSize(l)&&s.push("height"),{sourceId:e,bodyId:t,stated:i,predicted:n,separationDeg:r,widthRatio:o,heightRatio:l,disagreements:s}}static projectionOf(e,t,i){const n=i&&i.length>0?i:vi.outlineOf(e),s=i&&i.length>0?vi.centreOf(i):e,r=vi.normalized({eastM:s.eastM-t.eastM,northM:s.northM-t.northM,upM:s.upM-t.upM});if(!r)return;const o=vi.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},l=vi.cross(o,r);let c=1/0,h=-1/0,d=1/0,u=-1/0;for(const p of n){const f={eastM:p.eastM-t.eastM,northM:p.northM-t.northM,upM:p.upM-t.upM},g=vi.dot(f,r);if(g<=0)return;const m=Math.atan2(vi.dot(f,o),g),v=Math.atan2(vi.dot(f,l),g);c=Math.min(c,m),h=Math.max(h,m),d=Math.min(d,v),u=Math.max(u,v)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*uc+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*uc},angular:{widthDeg:(h-c)*uc,heightDeg:(u-d)*uc}}}static centreOf(e){const t=i=>(Math.min(...e.map(n=>n[i]))+Math.max(...e.map(n=>n[i])))/2;return{eastM:t("eastM"),northM:t("northM"),upM:t("upM")}}static separationDeg(e,t){const i=e.altitudeDeg*$o,n=t.altitudeDeg*$o,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((e.azimuthDeg-t.azimuthDeg)*$o);return Math.acos(Math.max(-1,Math.min(1,s)))*uc}static withinSize(e){return e<=vi.SIZE_TOLERANCE&&e>=1/vi.SIZE_TOLERANCE}static outlineOf(e){const t=e.sizeM.widthM/2,i=e.sizeM.lengthM/2,n=e.sizeM.heightM/2,s=[],r=e.model.url===void 0?e.model.id:void 0;if(r!==void 0&&r!=="box"&&Pw.includes(r))for(let d=0;d<=vi.RINGS;d++){const u=d/vi.RINGS*Math.PI;for(let p=0;p<vi.SEGMENTS;p++){const f=p/vi.SEGMENTS*2*Math.PI;s.push([t*Math.sin(u)*Math.cos(f),i*Math.sin(u)*Math.sin(f),n*Math.cos(u)])}}else for(const d of[-t,t])for(const u of[-i,i])for(const p of[-n,n])s.push([d,u,p]);const l=e.attitude.headingDeg*$o,c=e.attitude.pitchDeg*$o,h=e.attitude.rollDeg*$o;return s.map(([d,u,p])=>{const f=d*Math.cos(h)+p*Math.sin(h),g=-d*Math.sin(h)+p*Math.cos(h),m=u*Math.cos(c)-g*Math.sin(c),v=u*Math.sin(c)+g*Math.cos(c);return{eastM:e.eastM+f*Math.cos(l)+m*Math.sin(l),northM:e.northM-f*Math.sin(l)+m*Math.cos(l),upM:e.upM+v}})}static dot(e,t){return e.eastM*t.eastM+e.northM*t.northM+e.upM*t.upM}static cross(e,t){return{eastM:e.northM*t.upM-e.upM*t.northM,northM:e.upM*t.eastM-e.eastM*t.upM,upM:e.eastM*t.northM-e.northM*t.eastM}}static normalized(e){const t=Math.hypot(e.eastM,e.northM,e.upM);return t>1e-9?{eastM:e.eastM/t,northM:e.northM/t,upM:e.upM/t}:void 0}}qu();const AC={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},TC="{name} — mag {mag}, {alt}° above the horizon",IC="{name} — satellite, mag {mag}, {height} km up",Fw="satellites-change",Uw="fireballs-change",DC="aircraft-change",RC="rr0-confrontation",CC="{name} — mag {mag}, {alt}° below the horizontal",Lf="Credits",ny="comet:",sy="nova:",ry={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",streetlight:"Streetlight",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},PC=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,LC=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,kC=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,OC=-18,NC={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},md={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class ei 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",pl,fl]}shadow;stageElement;frameElement;sceneCanvas;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new D;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new en;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new os;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=Mm[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return ei.trafficRuntimeLoading??=je(()=>import("./trafficRuntime-Ce_f9RDO.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>ei.trafficRuntime=e),ei.trafficRuntimeLoading.catch(()=>{ei.trafficRuntimeLoading=void 0}),ei.trafficRuntimeLoading}traffic;lastSun;decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new yC;vehicleAudio=new fS;aircraftAudio;vehicleHearing=new du;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{this.sceneRenderer.setCompassHovered(!0);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,o=-((e.clientY-i.top)/i.height*2-1),l=this.naming,c=l.names,h=this.sceneRenderer.pickBodyAt(r,o);if(h){this.showHoverTooltip(e,this.bodyName(h));return}const d=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(r,o):void 0,u=d?this.interpretationShown?.bodies.find(y=>y.id===d):void 0,p=u?this.said.read(u.title)||(u.model.id==="figure"?l.decorKind("entity",ry.entity):void 0):void 0;if(p){this.showHoverTooltip(e,p);return}const f=this.sceneRenderer.pickDecorAt(r,o),g=f?this.ufoElement.sighting.decor.find(y=>y.id===f):void 0;if(g){this.showHoverTooltip(e,this.said.read(g.title)||l.decorKind(g.kind,ry[g.kind]));return}const m=this.trafficTooltipAt(r,o);if(m){this.showHoverTooltip(e,m);return}const v=this.sceneRenderer.pickSatelliteAt(r,o);if(v){this.showHoverTooltip(e,(c?.satelliteTooltip??IC).replace("{name}",v.name).replace("{mag}",v.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(v.heightKm).toLocaleString()));return}const x=this.sceneRenderer.pickStarAt(r,o);if(x){const y=x.star.mag,b=x.altitudeDeg,w=b<0?c?.starTooltipBelow??CC:c?.starTooltip??TC;this.showHoverTooltip(e,w.replace("{name}",l.star(x.star)).replace("{mag}",y.toLocaleString(void 0,{maximumFractionDigits:Math.abs(y)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(b)))));return}this.hoverTooltip.hidden=!0};bodyName(e){const t=e.startsWith(ny)?e.slice(ny.length):void 0,i=t?Nw.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const n=e.startsWith(sy)?Fu.byId(e.slice(sy.length)):void 0;if(n)return this.naming.nova(n);const s=AC[e];return s===void 0?e:this.naming.body(e,s)}get naming(){return this.sceneNaming}sceneNaming=new Nu;namesLanguage="en";async loadSceneNames(){const e=Fc(hs.preferencesFor(this),Hc);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await Gy(e);e===this.namesLanguage&&this.applySceneNaming(new Nu(t))}renderLoaderText(e,t){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((o,l)=>{l>0&&s.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of o){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??Lf;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();this.hoverTooltip.style.left=`${e.clientX-i.left+12}px`,this.hoverTooltip.style.top=`${e.clientY-i.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash(e){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),Oi.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(uh(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=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"&&this.sceneRenderer.frame(performance.now())};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>${gS}</style>${mS}`,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 ut(this.sceneCanvas);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.sceneRenderer.onFirstFrameHold=s=>{t.hidden=!s,this.ufoElement.captionHeld=s,this.ufoElement.holdClock(s)},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(jf),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,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"&&Dn.fill(n,this)}),this.creditsButton.title=Lf,this.creditsButton.setAttribute("aria-label",Lf),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),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 ei.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new qn(hs.preferencesFor(this))}saidTexts;traceLabelsFor;traceLabels(e){const t=hs.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 ei.GESTURES)document.addEventListener(t,this.handlePageGesture,!0);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u")&&(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 ei.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===pl||e===fl)&&i!==t&&this.forwardPlayerAttributes()}forwardPlayerAttributes(){for(const e of[pl,fl]){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=at(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}=ci(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)}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=Nc.json(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.sightingData=i}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.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?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 Ou(this,()=>document.createElement(Uu))}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.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)}referenceFailedToLoad(e){return this.sceneRenderer.referenceFailedToLoad(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}setTerrainProviders(e){this.sceneRenderer.setTerrainProviders(e)}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=lt.CANVAS_HEIGHT_PX,i=Rt.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:Rf,url:this.getAttribute("star-catalog-src")??LC},{magnitudeLimit:Pc,url:this.getAttribute("deep-star-catalog-src")??kC}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>Rf?Pc:Rf;const n=await Hs.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=Pc||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=nn.gainFor(e.instrument,{fNumber:at(e,0)?.fNumber,fieldOfViewDeg:Ui.fovOf(e,0),exposureSeconds:e.exposure});return sa(OC,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=xs.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,n=this.degreesPerPixelAt(e),s=oo.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(e).length,xs.instants(this.decorWithTraffic(this.ufoElement.sighting),at(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,o=>this.applySceneAt(t.fromMs+t.ms*o/(r-1),{sky:Math.floor(o*s/r)!==Math.floor((o-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:Ui.fovOf(this.ufoElement.sighting,e)/t}roadGradeAt(e,t){return e.observerTrack.allKeyframes.length<2?0:Qo.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(uh(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??ei.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(e)),this.sceneRenderer.setContrails(this.traffic?.contrails??ei.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(e));const n=at(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=at(i,0),r=hi(i,0),o=Yn(i.event.time??{},n?.lng??md.lng,i.event.utcOffsetHours),l=i.weatherSource!==void 0&&o?vx(o):void 0,c=Object.fromEntries(Ks(hi(i,e)).map(T=>[T.id,su(e,i.weatherTrack,r,s,n,T.id,T.instances?.length?void 0:l)]));this.sceneRenderer.setCloudOffset(su(e,i.weatherTrack,r,s,n,void 0,l),c),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,e)}:md),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(nn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:Ui.fovOf(i,e),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,Si.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso),this.sceneRenderer.setGait(Ft.bodyAt(i,e,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(at(i,0),n,e),this.placeBodiesAt(e,t===void 0),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),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??md.lat,d=n?.lng??md.lng,u=Yn(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=[...this.interpretationShown?.reentries??[],...this.fireballs?.reentries??[]];if(this.sceneRenderer.setReentries(f.length===0?[]:At.viewsAt(f,e,{lat:h,lng:d,heightM:p.elevationM})),t&&!t.sky)return;if(!u){this.sceneRenderer.setAstronomy(NC);return}const g=new Date(u.getTime()+e),m=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/oo.DEG_PER_SECOND*1e3)),v=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),x=`${Math.floor(g.getTime()/m)}|${Math.round(h/v)}|${Math.round(d/v)}|${Math.round(p.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(x===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=x;const y=Ni("Sun",g,p),b=Ni("Moon",g,p);let w=bi.separationOf(y,b)<1?bi.viewAt(g,p):void 0;if(w){const T=bi.offsetOf(y,b,w.separationDeg);if(w.obscuration>ei.LIMB_FROM_OBSCURATION){const A=this.limbFor(g,p);A&&(w={...w,obscuration:1-ss.uncoveredFraction(A,w.sunRadiusDeg,T),limb:A})}w={...w,horizonShare:bi.horizonShare(w,T,y.altitudeDeg,y.azimuthDeg,cn.distanceKm(g,p))}}const S={...y,magnitude:rf("Sun",g)-2.5*Math.log10(bi.beamFraction(w))};this.lastSun={altitudeDeg:S.altitudeDeg,azimuthDeg:S.azimuthDeg};const _={...b,phase:Ca(g),magnitude:rf("Moon",g),radiusDeg:cn.apparentRadiusDeg(g,p)},M=h4.map(T=>({body:T,position:Ni(T,g,p),magnitude:rf(T,g)}));this.sceneRenderer.setAstronomy({sun:S,moon:_,planets:M,comet:this.cometAt(g,p),novae:Fu.appearancesAt(g,p).map(({outburst:T,position:A,magnitude:R})=>({id:T.id,position:A,magnitude:R})),stars:this.starCatalog?{catalog:this.starCatalog,date:g,observer:p}:void 0,frame:{date:g,observer:p},eclipse:w}),this.ufoElement.setSunAltitude(S.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(e,t){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,Lc.load(PC).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=ss.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||!os.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,ei.fireballArchive.between(n,n+i).then(o=>{r.status=o?"ready":"unavailable",r.records=o??[],r.reentries=r.records.map(l=>os.asReentry(l,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(Uw)),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 o=lv(r,t);return`${o.side??"-"}/${o.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 o=lv(r,t);return{...r,observerSide:o.side,observerFacing:o.facing}});return this.seatedMemo={base:e,seats:i,seated:s},s}ensureTraffic(e){const t=at(e,0),i=t?.lng===void 0?void 0:Yn(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(r===""||s===void 0||t?.lat===void 0||t.lng===void 0){this.traffic={key:r,status:"outside"};return}let o=ei.aircraftProviders.get(this.aircraftSource.id);if(o||ei.aircraftProviders.set(this.aircraftSource.id,o=this.aircraftSource.create()),o.mayCover&&!o.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const l={key:r,status:"loading",startMs:s,observer:{lat:t.lat,lng:t.lng}};this.traffic=l;const c={lat:t.lat,lng:t.lng,heightM:t.elevationM??0},h=vn.MAX_GAP_S*1e3,d=ei.SOUND_LOOKBACK_MS,u={lat:t.lat,lng:t.lng,elevationM:t.elevationM??0},p=(f,g)=>f.TrafficDecor.from(l.tracks??[],c,s,f.TrafficDecor.MAX_OBJECTS,{models:g,sunElevationAt:m=>this.sunElevationAt(m,u)});o.between(c,s-d,s+n+h).then(async f=>{if(this.traffic!==l)return;if(f.status!=="found"){l.status=f.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let g;try{g=await ei.loadTrafficRuntime()}catch{this.traffic===l&&(l.status="unavailable",this.announceTraffic());return}this.traffic===l&&(l.status="ready",l.tracks=f.tracks,l.set=p(g),this.startAircraftSound(l,g),this.announceTraffic(),this.describeTraffic(o,l,g,p),l.set.shown>0&&this.readUpperAir(l,g,s-d,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,o]of n.presence){if(e<o.fromMs||e>o.untilMs)continue;const l=n.flights.get(r),c=l?vn.positionAt(l,i.startMs+e):void 0;c&&t.set(r,{heightM:c.geo.heightM,sunElevationDeg:Xn.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=ei.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,o=>s.towards(o))}trafficInfoAt(e){const t=this.traffic,i=t?.set?.flights.get(e);if(!t||!i||t.startMs===void 0||!t.observer)return;const n=ei.trafficRuntime;if(!n)return;const s=t.descriptions?.get(as.keyOf(i)),r=at(this.ufoElement.sighting,this.lastTimeMs),o={lat:t.observer.lat,lng:t.observer.lng,heightM:r?.elevationM??0},l=n.AmbientNoise.dbA(uh(this.ufoElement.sighting,this.lastTimeMs)),c=n.TrafficInfos.at(i,s,o,t.startMs+this.lastTimeMs,{ambientDbA:l}),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.aircraftAudio=new t.AircraftAudio,this.aircraftAudio.setLevel(this.ufoElement.level),this.interacted&&this.aircraftAudio.resume(),this.aircraftAudio.setPaused(this.ufoElement.playbackState!=="playing")),this.sortOutAudible(e,t)}sortOutAudible(e,t){!e.set||!e.observer||(e.audible=t.TrafficSound.candidates(e.set.flights,e.descriptions??new Map,as.keyOf,{...e.observer,heightM:0},{ambientDbA:t.AmbientNoise.BASE_DB_A}))}pushAircraftSound(e,t){const i=this.aircraftAudio;if(!i)return;const n=ei.trafficRuntime,s=this.traffic,r=s?.set;if(!n||!s||!r||!s.audible||s.startMs===void 0||!s.observer){i.setVoices([]);return}const o=at(e,t),l={lat:s.observer.lat,lng:s.observer.lng,heightM:o?.elevationM??0},c=uh(e,t),h=n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,as.keyOf,l,s.startMs+t,{ambientDbA:n.AmbientNoise.dbA(c),referenceAmplitude:n.AmbientNoise.referenceAmplitude(c)});i.setVoices(h,o?.headingDeg??0)}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(DC)),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=>as.keyOf(c))),r=t.tracks.filter(c=>s.has(as.keyOf(c))&&c.points.length>0),o=new Map,l=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&&(l.set(as.keyOf(c),d),o.set(as.keyOf(c),i.AircraftModels.of(d)))})),!(this.traffic!==t||o.size===0)&&(t.descriptions=l,t.models=o,t.set=n(i,o),this.planContrails(t,i),this.sortOutAudible(t,i),this.announceTraffic())}async readUpperAir(e,t,i,n){if(!e.observer)return;const s=this.upperAirSource??t.UPPER_AIR_SOURCES[0];let r=ei.upperAirProviders.get(s.id);r||ei.upperAirProviders.set(s.id,r=s.create());const o=await r.between(e.observer,i,n);this.traffic!==e||o.status!=="found"||(e.air=o.samples,e.airSource=o.source,this.planContrails(e,t),this.announceTraffic())}planContrails(e,t){!e.set||!e.air||e.startMs===void 0||(e.contrails=t.AircraftContrails.plan(e.set,e.models,e.air,e.startMs))}contrailSunlight(e){const t=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return t;for(const r of i.contrails){const o=n.presence.get(r.id),l=n.flights.get(r.id);if(!o||!l)continue;const c=vn.positionAt(l,i.startMs+Math.min(o.untilMs,Math.max(o.fromMs,e)));c&&t.set(r.id,{heightM:c.geo.heightM,sunElevationDeg:Xn.sunElevationDeg(s,i.observer,c.geo)})}return t}sunElevationAt(e,t){const i=Ni("Sun",new Date(e.t),t);return Xn.sunElevationDeg(i,t,e)}upperAirSource;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??ei.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(Fw)))},s=ei.tleArchive;(async()=>{if(!await s.covers(e))return n("outside");const[r,o]=await Promise.all([s.at(e),je(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new o.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}}satellitePassesDuring(e){const t=this.satellites,i=this.ufoElement.sighting,n=at(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,o=n?.lng??s?.lng;if(!t||r===void 0||o===void 0)return[];const l=Yn(i.event.time??{},o,i.event.utcOffsetHours);if(!l)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:o,elevationM:n?.elevationM??0},d=JSON.stringify([this.satellitesFor,l.getTime(),r,o,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(l,new Date(l.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:p},p}cometAt(e,t){const i=kd.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),o=new Map,l=new Map,c=new Set;for(const f of i.sourceIds){const g=i.getInterpolatedShapeAt(e,f);if(!g)continue;const m={...g,bounds:{...g.bounds,x:g.bounds.x+s.x,y:g.bounds.y+s.y}};o.set(f,m);const v=g.aim?this.sceneRenderer.screenPointOf(ys.directionOf(g.aim,this.directionScratch)):{ndcX:(m.bounds.x+m.bounds.width/2)/n.width*2-1,ndcY:-((m.bounds.y+m.bounds.height/2)/n.height*2-1)},x=v!==void 0&&Math.abs(v.ndcX)<=1&&Math.abs(v.ndcY)<=1,y=x?this.sceneRenderer.decorDistancesAt(v.ndcX,v.ndcY,f):{};c.add(f),(x||g.aim)&&c.delete(f);const b=g.angular?.widthDeg??r.pxToDeg(g.bounds.width),w=this.sizeEstimateOf(f);w.add(b,y);const S=kc.of(t,f);l.set(f,gn.resolve({hypothesisM:this.distanceHypotheses.get(f),derivedM:S&&b>0?lt.distanceMAt(S.widthM,b):void 0,range:w.distanceRangeAt(b),crossing:y}))}for(const[f,g]of o)for(const[m,v]of o){if(m===f||v.transparency>=1||v.bounds.width*v.bounds.height<=g.bounds.width*g.bounds.height||!(g.bounds.x>=v.bounds.x&&g.bounds.y>=v.bounds.y&&g.bounds.x+g.bounds.width<=v.bounds.x+v.bounds.width&&g.bounds.y+g.bounds.height<=v.bounds.y+v.bounds.height))continue;const y=l.get(m);y&&l.set(f,{distanceM:y.distanceM*.999,basis:y.basis});break}this.depths=l;const h=i.sourceIds,d=[];for(const[f,g]of o)d.push({sourceId:f,shape:g,distanceM:l.get(f).distanceM,renderOrder:h.indexOf(f),aim:g.aim,hidden:c.has(f)||this.interpretationShown!==void 0&&(!this.comparing||g.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const p=(at(t,e)?.rollDeg??0)+Ft.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:Rt.starPointsOf(t.instrument),rollRad:p*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(e){this.interpretationShown=e,this.syncAccountHidden(),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){this.comparing=e,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs)}get confrontation(){return this.confrontationReadings}groundAlong(e,t,i){const n=this.sceneRenderer.bodyGround,s=dt.eyeOf(this.ufoElement.sighting,i,n);return s?dt.lineOfSightMeetsGround(s,e,t,n):void 0}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=u=>dt.eyeOf(n,u,i),r=new dt(e,i,s).at(t),o=s(t);if(!r||!o)return;const l=r.eastM-o.eastM,c=r.northM-o.northM,h=r.upM-o.upM,d=Math.hypot(l,c);return{azimuthDeg:(Math.atan2(l,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}}directionToBody(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=f=>dt.eyeOf(n,f,i),r=new dt(e,i,s),o=r.at(t)?t:e.track[0]?.t,l=o===void 0?void 0:r.at(o),c=o===void 0?void 0:s(o);if(!l||!c)return;const h=l.eastM-c.eastM,d=l.northM-c.northM,u=l.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 o=this.sceneRenderer.bodyGround,l=f=>dt.eyeOf(n,f,o);i&&(s=i.bodies.map(f=>new dt(f,o,l).at(e)).filter(f=>f!==void 0));const c=hi(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?l(e):void 0;if(u&&(r=new vi(n.timeline).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(RC,{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&&hi(e,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(e){const t=hi(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?Yn(n,s?.lng??0,e.event.utcOffsetHours):void 0,o=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,l=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=Oi.schedule({durationMs:o,seed:l,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?Yn(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,o=Math.round(n.getTime()/1e3)+Math.round(t.lat*1e3),l=oi.schedule({ratePerHour:oi.observedRatePerHour(oi.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:oi.TYPICAL_VELOCITY_KM_S,seed:o}),c=El.activeAt(n).map(d=>{const u=El.radiantPosition(d.shower,n,s);return{entry:d,position:u,rate:El.observedRatePerHour(d.zhr,u.altitudeDeg,d.shower.populationIndex)}}).sort((d,u)=>u.rate-d.rate)[0];if(!c||c.rate<=0){this.sceneRenderer.setMeteorShower(l,0,0);return}const h=ro.schedule({ratePerHour:c.rate,durationMs:r,velocityKmS:c.entry.shower.velocityKmS,seed:o+1});this.sceneRenderer.setMeteorShower([...h,...l],c.position.altitudeDeg,c.position.azimuthDeg)}meteorByRank(e){this.ensureMeteorSchedule(this.ufoElement.sighting);const t=[...this.sceneRenderer.meteorSchedule].filter(s=>s.t+s.durationMs<=this.ufoElement.seekableDuration).sort((s,r)=>r.brightness-s.brightness);if(t.length===0)return;const i=t[e%t.length],n=this.sceneRenderer.meteorMidpoint(i);if(n)return{t:Math.round(i.t+i.durationMs*.45),...n}}lensOpticsAt(e){const t=this.ufoElement.sighting,i=t.instrument,n=i.frame,s=at(t,e),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const o=Rt.focalLengthMmFor(i,Ui.fovOf(t,e));if(o!==void 0)return{focalLengthMm:o,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return Ts.of(t.instrument,lt.CANVAS_HEIGHT_PX,Ui.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new wC,this.sizeEstimates.set(e,t)),t}}const Uu="rr0-scene";function FC(){qu(),customElements.get(Uu)||customElements.define(Uu,ei)}class UC{constructor(e,t){this.timeline=e,this.clock=t}currentPointer=null;shapePrototype=null;sourceId="";start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.clock.start(i=>this.recordSample(i))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop()}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=Ay(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class BC{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)}}const Bu="rr0-duration-input",zC=`
|
|
9653
9653
|
rr0-duration-input { position: relative; display: inline-flex; align-items: center; gap: .3em; }
|
|
9654
9654
|
rr0-duration-input .duration-field { position: relative; display: inline-flex; align-items: center; gap: .25em; }
|
|
9655
9655
|
rr0-duration-input .duration-field input[type="text"] { padding-right: 1.6em; }
|
|
@@ -9689,7 +9689,7 @@ rr0-duration-input [hidden] { display: none !important; }
|
|
|
9689
9689
|
.model-picker .model-thumb img { width: 100%; height: 100%; object-fit: contain; }
|
|
9690
9690
|
.model-picker .model-name { font-weight: 600; }
|
|
9691
9691
|
.model-picker .model-credit { font-size: .8em; color: #666; }
|
|
9692
|
-
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await je(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-BMvmda-2.js");return{ModelThumbnails:i}},__vite__mapDeps([3,4]),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;const r=()=>{const l=++s,c=e.selectedOptions[0],h=e.value===""?i?.current():void 0;n.replaceChildren();const d=document.createElement("span");d.textContent=`${h?h.title||h.url:c?.textContent??""} …`,n.title=this.messages().choose,n.append(d);const u=e.value;(h?Promise.resolve({url:h.url}):t(u)).then(p=>Oc.pictureOf(p)).then(p=>{if(!p||l!==s)return;const f=new Image;f.src=p,f.alt="",n.prepend(f)})};e.addEventListener("change",r),new MutationObserver(r).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:l=>{i.apply(l),r()}};n.addEventListener("click",()=>void this.open(e,t,o)),r()}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=Oc.STYLE,t.append(i)}open(e,t,i){const n=this.messages(),s=document.createElement("div");s.className="model-picker-backdrop";const r=document.createElement("div");r.className="model-picker",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=n.title;const l=document.createElement("button");l.type="button",l.className="model-picker-close",l.setAttribute("aria-label",n.close),l.title=n.close,l.textContent="✕";const c=document.createElement("header");c.append(o,l);const h=document.createElement("div");h.className="model-picker-body",r.append(c,h),s.append(r);const d=()=>{s.remove(),document.removeEventListener("keydown",u,!0),je(async()=>{const{ModelViewer:S}=await import("./ModelViewer-O9_A3wzF.js");return{ModelViewer:S}},__vite__mapDeps([5,4]),import.meta.url).then(({ModelViewer:S})=>S.end())},u=S=>{S.key==="Escape"&&(S.stopPropagation(),d())},p=i?.current(),f="\0address",g=S=>S===f&&p?Promise.resolve({url:p.url}):t(S),m=S=>{d(),!(S===f||S===e.value)&&(e.value=S,e.dispatchEvent(new Event("change",{bubbles:!0})))};let v;const x=new Map,y=S=>{const _=document.createElement("button");_.type="button",_.className="model-card",_.setAttribute("aria-pressed",String(S.value===f||S.value===e.value&&!p));const M=document.createElement("div");M.className="model-thumb";const T=document.createElement("span");if(T.className="model-name",T.textContent=S.textContent,_.append(M,T),S.title){const z=document.createElement("span");z.className="model-credit",z.textContent=S.title,_.append(z)}g(S.value).then(z=>Oc.pictureOf(z)).then(z=>{if(!z)return;const L=new Image;L.src=z,L.alt="",M.append(L)});let A,R=!1;const C=()=>{R&&!(A&&!A.active)||(R=!0,Promise.all([g(S.value),je(()=>import("./ModelViewer-O9_A3wzF.js"),__vite__mapDeps([5,4]),import.meta.url)]).then(([z,{ModelViewer:L}])=>{!z||!R||(A=L.show(M,z))}).catch(()=>{}))},k=()=>{R=!1,A?.stop(),A=void 0};return x.set(_,C),_.addEventListener("pointerenter",C),_.addEventListener("focus",C),_.addEventListener("pointerleave",()=>{document.activeElement!==_&&k()}),_.addEventListener("blur",k),_.addEventListener("click",z=>{if(A?.consumeDrag()){z.preventDefault();return}m(S.value)}),_},b=()=>(v=document.createElement("div"),v.className="model-picker-grid",h.append(v),v);if(p){const S=new Option(p.title||p.url,f);S.title=[p.author,p.license].filter(Boolean).join(" — "),b().append(y(S))}for(const S of Array.from(e.children))if(S instanceof HTMLOptGroupElement){const _=document.createElement("h3");_.textContent=S.label,h.append(_);const M=b();for(const T of Array.from(S.children))M.append(y(T));v=void 0}else S instanceof HTMLOptionElement&&(v??b()).append(y(S));i&&this.addAddressForm(c,l,r,h,i,n,d),l.addEventListener("click",d),s.addEventListener("click",S=>{S.target===s&&d()}),document.addEventListener("keydown",u,!0),this.root.append(s);const w=r.querySelector('.model-card[aria-pressed="true"]');(w??l).focus(),w&&x.get(w)?.()}addAddressForm(e,t,i,n,s,r,o){const l=document.createElement("button");l.type="button",l.className="model-picker-add",l.textContent="+",l.title=r.address,l.setAttribute("aria-label",r.address),l.setAttribute("aria-expanded","false"),e.insertBefore(l,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(y,b,w="")=>{const S=document.createElement("label"),_=document.createElement("span");_.textContent=y;const M=document.createElement("input");return M.type=b,M.placeholder=w,S.append(_,M),c.append(S),M},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"),g=h(r.addressSource,"url","https://…"),m=document.createElement("p");m.textContent=r.addressIncomplete;const v=document.createElement("button");v.type="submit",v.className="model-picker-use",v.textContent=r.addressUse,c.append(m,v),i.insertBefore(c,n);const x=()=>{v.disabled=d.value.trim()==="",m.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const y of[d,u,p,f,g])y.addEventListener("input",x);l.addEventListener("click",()=>{const y=c.hidden;if(c.hidden=!y,l.setAttribute("aria-expanded",String(y)),!y)return;const b=s.current();d.value=b?.url??"",u.value=b?.title??"",p.value=b?.author??"",f.value=b?.license??"",g.value=b?.source??"",x(),d.focus()}),c.addEventListener("submit",y=>{y.preventDefault(),d.value.trim()!==""&&(s.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:g.value.trim()}),o())}),x()}}class Hu{static of(e,t){const i=Hu.drawnAsModel(e);return{color:t?.color??!i,lit:t?.lit??Hu.litByDefault(e.kind,i),lights:(t?.lights??!0)&&Md.forKind(e.kind).length>0,windows:!i&&Cm(e.kind),floors:!i&&e.kind==="building",observerSide:eo(e.kind)}}static drawnAsModel(e){return lu(e)!==void 0&&!(e.observerSide!==void 0&&eo(e.kind))}static litByDefault(e,t){return e==="streetlight"||e==="vehicle"&&!t}}class Mg{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=Mg.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 f6{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)}}function mr(a,e){return a.find(t=>t.id===e)??a[0]}class m6{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 g6=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new m6}],vy=new Set;qu();FC();const qo={width:48,height:28},v6=2500,by=40,b6=10,yy=600,My=900,Ko=2e-4,y6=900,M6=-1.46,w6=3,Bf=.2,x6=.5,S6=3,E6=.01,_6=1.6,zf=2e3,A6=250,wy=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),Wr=4,fc="ufo-1",xy=["oval","polygon"],T6={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function I6(a){return a.kind==="oval"?"oval":"polygon"}const D6=-6,R6=21;class Di extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=g6[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new f6;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;durationElement;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=h6();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;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;fileEditor;fileEditorLoading;fileEditorHost;fileNote;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 kf(l6());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;labelShape;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;labelImportFile;labelImportUrl;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;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;highCloudCoverInput;iceCrystalAlignmentInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorObserverButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorColorInput;decorLitInput;decorLightRigSelect;lookAtDecorButton;decorAltitudeInput;labelDecorAltitude;decorSightingUrlInput;decorModelProvider=Pd[0].create();milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorWidthInput;decorLengthInput;decorHeightInput;decorModelSelect;decorModelAdvanced;decorModelCatalogueNote;decorModelUrlInput;decorModelTitleInput;decorModelAuthorInput;decorModelLicenseInput;decorModelSourceInput;decorFloorsInput;decorOccupiedFloorInput;decorObserverSideSelect;decorWindowInputs;labelDecorSide;optionObserverSide;labelDecor;labelDecorGroup;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorColor;labelDecorLit;labelDecorSightingUrl;labelMilestones;labelMilestoneLabel;labelMilestoneNote;labelDecorWidth;labelDecorLength;labelDecorHeight;labelDecorModel;labelDecorModelAdvanced;labelDecorModelUrl;labelDecorModelTitle;labelDecorModelAuthor;labelDecorModelLicense;labelDecorModelSource;labelDecorFloors;labelDecorOccupiedFloor;labelDecorObserverSide;labelDecorWindows;optionObserverSideNone;optionDecorBuilding;optionDecorTree;optionDecorShrub;optionDecorBridge;optionDecorWire;optionDecorCrop;optionDecorTerrace;optionDecorMound;optionDecorStreetlight;optionDecorVehicle;optionDecorAircraft;optionDecorEntity;labelDecorLights;optionDecorObserver;recorder;isRecording=!1;messages=Il;currentAppearance={...T6};currentSourceId=fc;selectedSourceIds=new Set([fc]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSrcInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;addReferenceUrlButton;addReferenceFileInput;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;referenceStreetSearchButton;addTraceFileInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;labelTrace;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$=new ol;referenceFields;labelReferenceGroup;labelReference;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;labelAddReferenceFile;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(wy.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;wy.has(e.key)?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;this.endDrag(),e!==void 0&&this.selectDecor(e)};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${Bx}</style>${Ux}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const i of this.shadow.querySelectorAll(iu))i.build();for(const i of this.shadow.querySelectorAll(Bu))i.build();this.sceneElement=document.createElement(Uu),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",i=>{this.ufoElement.sighting.observerMap=i.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",i=>{const{lat:n,lng:s}=i.detail;this.latInput.value=String(Number(n.toFixed(6))),this.lngInput.value=String(Number(s.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.presetsGroup=this.shadow.getElementById("presets-group"),this.presetButtons={oval:this.shadow.getElementById("preset-oval"),polygon:this.shadow.getElementById("preset-polygon")},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.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.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 Sc(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const i of[this.timeStartLabel,this.timeEndLabel])i.addEventListener("click",()=>this.switchTimeDisplay()),i.addEventListener("keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.durationElement=this.shadow.querySelector(Bu),this.durationInput=this.durationElement.input,this.exportButton=this.shadow.getElementById("export"),this.importFileInput=this.shadow.getElementById("import-file"),this.importUrlInput=this.shadow.getElementById("import-url"),this.importUrlButton=this.shadow.getElementById("import-url-button"),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.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.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.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.labelShape=this.shadow.getElementById("label-shape"),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.labelReference=this.shadow.getElementById("label-reference"),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.labelAddReferenceFile=this.shadow.getElementById("label-add-reference-file"),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.labelLatitude=this.shadow.getElementById("label-lat"),this.labelLongitude=this.shadow.getElementById("label-lng"),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.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.labelImportUrl=this.shadow.getElementById("label-import-url"),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.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.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.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),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.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorObserverButton=this.shadow.getElementById("add-decor-observer"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),this.decorSelect=this.shadow.getElementById("decor"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSrcInput=this.shadow.getElementById("referenceSrc"),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.addReferenceUrlButton=this.shadow.getElementById("add-reference-url"),this.addReferenceFileInput=this.shadow.getElementById("add-reference-file"),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.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.referenceStreetSearchButton=this.shadow.getElementById("reference-street-search"),this.addTraceFileInput=this.shadow.getElementById("add-trace-file"),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.labelTrace=this.shadow.getElementById("label-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.referenceSrcInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.decorTitleInput=this.shadow.getElementById("decorTitle"),this.decorEastInput=this.shadow.getElementById("decorEast"),this.decorNorthInput=this.shadow.getElementById("decorNorth"),this.decorHeadingInput=this.shadow.getElementById("decorHeading"),this.decorColorInput=this.shadow.getElementById("decorColor"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorLightRigSelect=this.shadow.getElementById("decorLightRig"),this.lookAtDecorButton=this.shadow.getElementById("look-at-decor"),this.decorAltitudeInput=this.shadow.getElementById("decorAltitude"),this.labelDecorAltitude=this.shadow.getElementById("label-decor-altitude"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),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.decorWidthInput=this.shadow.getElementById("decorWidth"),this.decorLengthInput=this.shadow.getElementById("decorLength"),this.decorHeightInput=this.shadow.getElementById("decorHeight"),this.decorModelSelect=this.shadow.getElementById("decorModel"),this.modelPicker=new Oc(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.modelPicker.enhance(this.decorModelSelect,async i=>{const n=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),s=i!==""?i:n?ou[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 n=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId)?.model;return n?.url===void 0?void 0:{url:n.url,title:n.credit?.title??"",author:n.credit?.author??"",license:n.credit?.license??"",source:n.credit?.sourceUrl??""}},apply:i=>{this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.title,this.decorModelAuthorInput.value=i.author,this.decorModelLicenseInput.value=i.license,this.decorModelSourceInput.value=i.source,this.shownDecorEntry=void 0,this.decorModelSelect.value="",this.updateDecor()}}),this.decorModelAdvanced=this.shadow.getElementById("decor-model-advanced"),this.decorModelCatalogueNote=this.shadow.getElementById("decor-model-catalogue"),this.decorModelUrlInput=this.shadow.getElementById("decorModelUrl"),this.decorModelTitleInput=this.shadow.getElementById("decorModelTitle"),this.decorModelAuthorInput=this.shadow.getElementById("decorModelAuthor"),this.decorModelLicenseInput=this.shadow.getElementById("decorModelLicense"),this.decorModelSourceInput=this.shadow.getElementById("decorModelSource"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorObserverSideSelect=this.shadow.getElementById("decorObserverSide"),this.decorWindowInputs={front:this.shadow.getElementById("decorWindowFront"),behind:this.shadow.getElementById("decorWindowBehind"),left:this.shadow.getElementById("decorWindowLeft"),right:this.shadow.getElementById("decorWindowRight"),"front-left":this.shadow.getElementById("decorWindowFrontLeft"),"front-right":this.shadow.getElementById("decorWindowFrontRight"),"behind-left":this.shadow.getElementById("decorWindowBehindLeft"),"behind-right":this.shadow.getElementById("decorWindowBehindRight")},this.labelDecorSide={front:this.shadow.getElementById("label-decor-window-front"),behind:this.shadow.getElementById("label-decor-window-behind"),left:this.shadow.getElementById("label-decor-window-left"),right:this.shadow.getElementById("label-decor-window-right"),"front-left":this.shadow.getElementById("label-decor-window-front-left"),"front-right":this.shadow.getElementById("label-decor-window-front-right"),"behind-left":this.shadow.getElementById("label-decor-window-behind-left"),"behind-right":this.shadow.getElementById("label-decor-window-behind-right")},this.optionObserverSide={front:this.shadow.getElementById("option-observer-side-front"),behind:this.shadow.getElementById("option-observer-side-behind"),left:this.shadow.getElementById("option-observer-side-left"),right:this.shadow.getElementById("option-observer-side-right"),"front-left":this.shadow.getElementById("option-observer-side-front-left"),"front-right":this.shadow.getElementById("option-observer-side-front-right"),"behind-left":this.shadow.getElementById("option-observer-side-behind-left"),"behind-right":this.shadow.getElementById("option-observer-side-behind-right")},this.optionObserverSideNone=this.shadow.getElementById("option-observer-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelDecorTitle=this.shadow.getElementById("label-decor-title"),this.labelDecorEast=this.shadow.getElementById("label-decor-east"),this.labelDecorNorth=this.shadow.getElementById("label-decor-north"),this.labelDecorHeading=this.shadow.getElementById("label-decor-heading"),this.labelDecorColor=this.shadow.getElementById("label-decor-color"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.labelDecorWidth=this.shadow.getElementById("label-decor-width"),this.labelDecorLength=this.shadow.getElementById("label-decor-length"),this.labelDecorHeight=this.shadow.getElementById("label-decor-height"),this.labelDecorModel=this.shadow.getElementById("label-decor-model"),this.labelDecorModelAdvanced=this.shadow.getElementById("label-decor-model-advanced"),this.labelDecorModelUrl=this.shadow.getElementById("label-decor-model-url"),this.labelDecorModelTitle=this.shadow.getElementById("label-decor-model-title"),this.labelDecorModelAuthor=this.shadow.getElementById("label-decor-model-author"),this.labelDecorModelLicense=this.shadow.getElementById("label-decor-model-license"),this.labelDecorModelSource=this.shadow.getElementById("label-decor-model-source"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorObserverSide=this.shadow.getElementById("label-decor-observer-side"),this.labelDecorWindows=this.shadow.getElementById("label-decor-windows"),this.optionDecorBuilding=this.shadow.getElementById("option-decor-building"),this.optionDecorTree=this.shadow.getElementById("option-decor-tree"),this.optionDecorShrub=this.shadow.getElementById("option-decor-shrub"),this.optionDecorBridge=this.shadow.getElementById("option-decor-bridge"),this.optionDecorWire=this.shadow.getElementById("option-decor-wire"),this.optionDecorCrop=this.shadow.getElementById("option-decor-crop"),this.optionDecorTerrace=this.shadow.getElementById("option-decor-terrace"),this.optionDecorMound=this.shadow.getElementById("option-decor-mound"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorAircraft=this.shadow.getElementById("option-decor-aircraft"),this.optionDecorEntity=this.shadow.getElementById("option-decor-entity"),this.labelDecorLights=this.shadow.getElementById("label-decor-lights"),this.optionDecorObserver=this.shadow.getElementById("option-decor-observer"),this.ufoElement.canvasElement.addEventListener("pointerdown",i=>{this.focus({preventScroll:!0}),this.onPointerDown(i)}),this.ufoElement.canvasElement.addEventListener("pointermove",i=>this.onPointerMove(i)),this.ufoElement.canvasElement.addEventListener("contextmenu",i=>this.onContextMenu(i)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),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.addShapeButton.addEventListener("click",()=>this.addShape()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.importFileInput.addEventListener("change",()=>this.importFromFile()),this.importUrlButton.addEventListener("click",()=>this.importFromUrl()),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()}),this.lightPollutionInput.addEventListener("input",()=>{const i=this.ufoElement.sighting;i.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),i.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),i.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",i=>{const{seconds:n,text:s}=i.detail;this.ufoElement.sighting.event.durationText=s,this.ufoElement.durationSeconds=n,this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),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.addDecorObserverButton.addEventListener("click",()=>this.addDecor("observer")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value)),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const i of this.referenceFields)i.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.addReferenceUrlButton.addEventListener("click",()=>this.addReferenceFromAddress()),this.addReferenceFileInput.addEventListener("change",()=>void this.addReferenceFromFile()),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.referenceStreetSearchButton.addEventListener("click",()=>void this.searchStreetPictures()),this.addTraceFileInput.addEventListener("change",()=>void this.addTracesFromFile()),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",i=>this.onReferenceWheel(i),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",i=>this.onBodyWheel(i),{passive:!1});for(const i of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorAltitudeInput,this.decorHeadingInput,this.decorColorInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput])i.addEventListener("input",()=>this.updateDecor());this.decorObserverSideSelect.addEventListener("change",()=>this.updateDecor()),this.decorModelSelect.addEventListener("change",()=>this.updateDecorModelChoice()),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 i of[this.milestoneLabelInput,this.milestoneNoteInput])i.addEventListener("input",()=>this.updateMilestone());for(const i of Mo)this.decorWindowInputs[i].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.decorLightRigSelect.addEventListener("change",()=>this.updateDecorLightRig()),this.lookAtDecorButton.addEventListener("click",()=>this.lookAtDecor()),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(Uw,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(Fw,()=>{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);for(const i of xy)this.presetButtons[i].addEventListener("click",()=>this.setAppearance({presetId:i}));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 i of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])i.addEventListener("input",()=>this.updateObserver());for(const i of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])i.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",i=>{i.key==="Enter"&&(i.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 i=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const n=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(s=>[s.t,Ui.fovOf(this.ufoElement.sighting,s.t)]));this.retuneFieldOfView(i),this.retuneExposure(i),Ui.reproject(this.ufoElement.sighting,i,n),this.sceneElement.applyFrameFormat(),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 t=i=>this.shadow.querySelector(`${iu}[name="${i}"]`);this.startDate=t("obs-time"),this.endDate=t("obs-end-time"),this.startDate.messages=this.messages,this.endDate.messages=this.messages,this.startDate.addEventListener("datechange",i=>{const{time:n}=i.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=n})}),this.endDate.addEventListener("datechange",i=>{const{time:n}=i.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=n})});for(const i of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])i.addEventListener("input",()=>this.updateObserverMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const i of this.weatherFields){if(i===this.iceCrystalAlignmentInput){i.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}i.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const i of this.soundFields)i.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.skyDetailsButton=this.shadow.getElementById("sky-details"),this.clampedLines=[this.shadow.getElementById("weather-source"),this.shadow.getElementById("sky-candidates")],this.skyDetailsButton.addEventListener("click",()=>this.toggleSkyDetails()),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(i=>this.shadow.getElementById(i.getAttribute("aria-controls")));for(const i of this.groupTabs)i.addEventListener("click",()=>this.toggleGroup(i,!this.isGroupOpen(i)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const i of this.subgroupTabs)i.addEventListener("click",()=>this.openSubgroup(i));tn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new dl(this.messages,this.naming,this.said,this.tagNames,{messages:this.messages,locale:this.language}),this.paramSummary.addEventListener("click",i=>this.onParamSummaryClick(i)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(i=>i.id==="group-shape")],!0),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),this.updatePresetButtons(),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=Tx(this.shadow.getElementById("cloud-editor"),this.sceneElement,(i=!0)=>{i&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(i,n)=>{this.headingInput.value=String(this.rounded(i)),this.pitchInput.value=String(this.rounded(n)),this.updateObserver()},Fc(hs.preferencesFor(this),Hc)),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),hs.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()}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.endDrag(),this.ufoElement.sightingData=e,this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??fc,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(),this.syncWeatherOwnership(),this.markClean()}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&JSON.stringify(this.sightingData)!==this.baseline}get edited(){return this.touched}markClean(){this.baseline=JSON.stringify(this.sightingData),this.touched=!1}touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>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.text=t,this.syncHistoryButtons())}undo(){this.stepHistory(e=>e.undo())}redo(){this.stepHistory(e=>e.redo())}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),this.historyAnswering=!0,this.syncHistoryButtons())}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.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(),()=>{})}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=this.sightingData,t=`${e.observer?.id??"sighting"}-sighting.json`,i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,s.click(),URL.revokeObjectURL(n),this.markClean()}async importFromFile(){const e=this.importFileInput.files?.[0];if(e){if(this.holdLoad(()=>void this.loadFile(e))){this.importFileInput.value="";return}await this.loadFile(e)}}async loadFile(e){try{const t=await new Promise((n,s)=>{const r=new FileReader;r.onload=()=>n(r.result),r.onerror=()=>s(r.error),r.readAsText(e)}),i=JSON.parse(t);if(Es.isCase(i)){if(this.offerCase(i,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=i,this.resetHistory(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importUrlInput.value=""}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}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.importUrlInput.value.trim()){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){try{const t=await Nc.json(e);if(Es.isCase(t)){const n=new URL(e,location.href).href;if(this.offerCase(t,n)){this.importUrlInput.value=n;return}throw new Error("A case has no recording to edit here")}const i=t;this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.resetHistory(),this.importUrlInput.value=new URL(e,location.href).href,this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof xa))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";narrativeProvider=fh[0].create();get narrativeSourceId(){return mr(fh,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:Di.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const n=i instanceof Bn&&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,o=Gs.stated(r);if(o.length>0){const l=this.ufoElement.sighting.provenance,c=Zf(this.ufoElement.sighting);this.sightingData=Gs.apply(c,hu.loadable(r),o),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.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:Di.valueAt(Zf(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[C6[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 o=document.createElement(t==="stated"?"q":"span");o.textContent=n.rationale,s.append(r,o),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=mr(fh,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(),o=r===""?void 0:n.suspect(r);s.classList.toggle("invalid",o!==void 0),s.title=o?this.said.read(o)??"":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 l of i.choices??[]){const c=document.createElement("option");c.value=l.value,c.textContent=this.said.read(l.label)??l.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 o=e[i.id]??this.storedNarrativeSetting(i.id);return o!==void 0&&(r.value=o),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 Bn))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(Di.NARRATIVE_KEY_STORAGE),localStorage.removeItem(Di.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"?Di.NARRATIVE_KEY_STORAGE:e==="workspace"?Di.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} `),this.sourcePicker("place",d6,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",u6,e=>{this.weatherInference=new kf(e.create()),this.scheduleWeatherLookup()})),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("light-pollution",ly,e=>{this.lightPollutionProvider=e.create(),this.scheduleLightPollutionLookup()})),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",fh,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,Uf,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,gy,()=>this.applyTerrainSources()),this.labelledPicker("aircraft",this.messages.sourceAircraft,Mm,()=>this.applyAircraftSource()),this.labelledPicker("decor-model",this.messages.decorModel,Pd,()=>this.applyDecorModelSource()))}sourcePicker(e,t,i){const n=document.createDocumentFragment(),s=document.createElement("select");s.id=`${e}Source`;for(const l of t){const c=document.createElement("option");c.value=l.id,c.textContent=l.name,c.title=l.credit,s.appendChild(c)}s.value=this.chosenSourceId.get(e)??t[0].id;const r=document.createElement("a");r.className="source-credit",r.target="_blank",r.rel="noopener noreferrer";const o=()=>{const l=mr(t,s.value);s.title=l.credit,r.href=l.creditUrl,r.textContent=l.credit};return o(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),o(),i(mr(t,s.value))}),n.append(s,document.createTextNode(" "),r),n}labelledPicker(e,t,i,n){const s=document.createElement("label"),r=document.createElement("span");return r.textContent=t,s.append(r,this.sourcePicker(e,i,n)),s}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:mr(Uf,this.chosenSourceId.get("elevation")).create(),imagery:mr(gy,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(mr(Mm,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=mr(Pd,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.refreshDecorModelOptions(),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==="")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)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)<Ko&&Math.abs(t-this.namedCoordinates.lng)<Ko||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),My))}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)<Ko&&Math.abs(t-i.lng)<Ko||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),My))}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}i===this.placeSearchToken&&(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,this.updateObserver())}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,o=Math.max(0,r-(this.groundElevationM??0)),l=this.ufoElement.sighting.event,c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());l.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?Rt.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),g=this.numberOrUndefined(this.fNumberInput.value),m=this.filterSelect.value,v=Si.byId(c.getLatestPoseAt(h-1)?.filter),x=m===Si.NONE.id||m===""?v===Si.NONE?void 0:Si.NONE.id:m,y=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=y===u.exposureSeconds?void 0:y;const b=this.numberOrUndefined(this.focusDistanceInput.value),w=Math.abs(f-Rt.fieldOfViewDeg(u))>.01||g!==u.fNumber||b!==void 0||x!==void 0;e===void 0&&t===void 0&&i===void 0&&n===0&&s===0&&o===0&&!w?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:o,headingDeg:i,pitchDeg:n,rollDeg:s===0?void 0:s,fovDeg:f,fNumber:g,focusDistanceM:b,filter:x}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&Tl({...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.stringOrUndefined(this.observerTitleInput.value),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),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"};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??{},o=t===""?r:{...r,url:t},l=Object.keys(o).length>0?[o,...n]:n;e.sources=l.length>0?l: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());const e={...hi(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={...hi(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.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;this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const n of[this.referenceSelect,...this.referenceFields])n.disabled=!t,this.setRowVisible(n,t);this.setRowVisible(this.referenceUsePoseButton,t);for(const n of[this.referenceLandmarksSelect,this.addReferenceLandmarkButton,this.deleteReferenceLandmarkButton,this.referenceLandmarkLabelInput])this.setRowVisible(n,t);if(this.refreshLandmarkList(),this.setRowVisible(this.referenceAdoptPoseButton,t),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSrcInput.value=i?"":e.src,this.referenceSrcInput.disabled=i,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.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){if(this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const t=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>YC?this.messages.referenceEmbedded.replace("{kb}",String(t)):"";return}this.referenceStatus.textContent=this.sceneElement.referenceFailedToLoad(e.src)?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.startsWith("data:")?s.src:this.referenceSrcInput.value.trim(),o={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)||gd))},l=s.registration,c=o.headingDeg!==l.headingDeg||o.pitchDeg!==l.pitchDeg||o.rollDeg!==l.rollDeg||o.fovDeg!==l.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:o,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=at(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=at(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=at(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${n.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:$C,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:gd},from:this.observerPositionNow(),...i};n.references=[...n.references,o],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSrcInput.focus()}async addReferenceFromFile(){const e=this.addReferenceFileInput.files?.[0];if(!e)return;const t=await new Promise((i,n)=>{const s=new FileReader;s.onload=()=>i(s.result),s.onerror=()=>n(s.error),s.readAsDataURL(e)});this.addReferenceFileInput.value="",this.addReference(t,e.name.replace(/\.[^.]+$/,""))}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.sceneElement.referenceAspect(t.id);if(!(n!==void 0&&An.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.sceneElement.referenceAspect(t.id):void 0;if(!t||i===void 0)return;const n=8;for(const s of this.currentLandmarks()){const r=this.canvasPointOfDirection(An.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 o=this.canvasPointOfDirection(An.worldDirection(s.scene));if(o&&Math.hypot(o.x-e.x,o.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.sceneElement.referenceAspect(n.id):void 0;if(!n||s===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:An.aimOf(r)};const l=An.picturePointOf(r,n.registration,s);return l?{...o,picture:l}:o})),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)||gd,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.sceneElement.referenceAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const o=An.picturePointOf(i,t.registration,r);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,this.syncRegisterStatus(),this.ufoElement.refresh();return}const n=this.currentLandmarks(),s=this.nextLandmarkId(n);this.writeLandmarks([...n,{id:s,picture:this.pendingLandmark,scene:An.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.sceneElement.referenceAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),n=An.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 An.worldDirectionOf(e.picture,t.registration,i).angleTo(An.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.sceneElement.referenceAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[s,r]of t.entries()){const o=document.createElement("option");o.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,s)+l,this.referenceLandmarksSelect.appendChild(o)}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);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(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),n=i.findIndex(o=>o.id===e),s=this.currentReference(),r=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&n>=0){const o=s&&r!==void 0?` · ${this.landmarkResidualDeg(i[n],s,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[n],n)+o}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.sceneElement.referenceAspect(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(o=>this.canvasPointOfDirection(An.worldDirectionOf(o,n,i))),r=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(An.worldDirectionOf(o.picture,n,i)),scene:this.canvasPointOfDirection(An.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(An.worldDirectionOf(this.pendingLandmark,n,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(o=>o!==void 0)?s:void 0,r.filter(o=>o.picture!==void 0),this.landmarkHint())};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 o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",i],["rollDeg",n??0]];for(const[c,h]of l)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${c}`,{basis:"derived",rationale:o,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceStreetSearchButton.disabled=!e}async searchStreetPictures(){const e=at(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.referenceStreetSearchButton.disabled=!0;try{this.streetPictures=await this.streetPictures$.nearby(t,i,n)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.referenceStreetSearchButton.disabled=!1;return}this.referenceStreetSearchButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}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:gd}})}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;for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t,this.setRowVisible(i,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 addTracesFromFile(){const e=this.addTraceFileInput.files?.[0];if(!e)return;this.addTraceFileInput.value="";let t;try{const{KmlImport:c}=await je(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url),h=await new Promise((d,u)=>{const p=new FileReader;p.onload=()=>d(p.result),p.onerror=()=>u(p.error),p.readAsArrayBuffer(e)});t=await c.fromBytes(new Uint8Array(h))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(t.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const i=this.ufoElement.sighting,n=new Set(i.traces.map(c=>c.id));let s=1;const r=this.said.write(void 0,t.documentName??e.name,this.writingLanguage),o=t.traces.map(c=>{for(;n.has(`trace-${s}`);)s++;const h=`trace-${s}`;return n.add(h),{...c,id:h,title:c.title===void 0?void 0:this.said.write(void 0,c.title,this.writingLanguage),source:r}});i.traces=[...i.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const l=t.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",t.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",e.name)+l,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 p2){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(),v6)}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=Dm(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 kf(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup():(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(){this.weatherFromRecords&&(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),yy))}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(){if(!this.weatherFromRecords||this.ufoElement.sighting.weatherSource===void 0)return;const e=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||e===this.weatherTrackSpan||(this.weatherTrackSpan=e,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const o of this.weatherFields)o.disabled=t&&e!==void 0&&o!==this.iceCrystalAlignmentInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting);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;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=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""}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&&Yn(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.weatherLookupResult=void 0,this.weatherFromRecords=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=ly[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;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(),yy)}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 o=await n.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=o,o.status==="found"?(e.lightPollution=o.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${n.citation}, at ${o.lat.toFixed(4)}, ${o.lng.toFixed(4)}: ${Math.round(o.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:o.lightPollution}),this.lightPollutionInput.value=String(o.lightPollution),this.ufoElement.refresh()):o.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=Tl(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=cx(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;this.playPauseButton.textContent=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(Gn.opensPrecise(e.time)),this.endDate.setPrecise(Gn.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)>w6;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),y6))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Ko&&Math.abs(e.lng-i)<Ko}async applyGroundElevation(e,t){const i=++this.groundElevationToken,n=mr(Uf,this.chosenSourceId.get("elevation")),s=await new Mg(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),this.updateObserver()}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?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(at(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(){const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=e.observer?.title??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",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()??"",this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=hi(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??Od)),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):""),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.updatePresetButtons(),!(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=Cg(e,this.currentAppearance);return t?{...n,angle:t.angle,title:t.title,selected:t.selected}:n}toggleSkyDetails(){const e=this.skyDetailsButton.getAttribute("aria-expanded")!=="true";this.skyDetailsButton.setAttribute("aria-expanded",String(e)),this.skyDetailsButton.textContent=e?"▴":"▾",this.skyDetailsButton.title=e?this.messages.skyDetailsHide:this.messages.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title);for(const t of this.clampedLines)t.classList.toggle("clamped",!e)}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){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}this.syncCanvasMode(),this.refreshTimelineMarks(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>this.syncFileEditor(),()=>this.showFileNote(this.messages.importError))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await je(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-BUpjvTYf.js");return{SightingFileEditor:t}},__vite__mapDeps([6,7]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}showFileNote(e){this.fileNote.textContent=e??"",this.fileNote.hidden=e===void 0}fileText(){return JSON.stringify(this.sightingData,null,2)}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(){const e=this.fileEditor;if(!(e===void 0||!this.isGroupIdOpen("group-file")||e.focused)&&!this.historyAnswering){try{JSON.parse(e.text)}catch{return}e.text=this.fileText()}}onFileTextEdited(e){clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e){this.fileApplyTimer=void 0;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null||Array.isArray(t)||JSON.stringify(t)===JSON.stringify(this.sightingData))return;const i=this.ufoElement.currentTime;try{this.sightingData=t,this.ufoElement.currentTime=i,this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch{this.showFileNote(this.messages.importErrorMalformed)}}leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(),0))}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(l,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${l})`})),i=l=>t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(c=>!l||c.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(c=>c.t)),n=()=>t(this.messages.observerTrack,e.observerTrack.allKeyframes.map(l=>l.t)),s=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(l=>l.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(l=>l.t)),o=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 l of e.milestones)o.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(o,this.ufoElement.seekableDuration)}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-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":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",this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,n&&this.ufoElement.refresh(),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()}syncBodiesShown(){const i=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading?this.ufoElement.sighting.interpretation:void 0;this.sceneElement.compareAccount=i!==void 0,this.sceneElement.interpretation!==i&&(this.sceneElement.interpretation=i),this.accountViewSelect.value=i!==void 0?"bodies":"shapes",this.shadow.getElementById("account-view-row").hidden=this.isReading}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.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()),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)}static SUMMARY_GROUPS=["observation","observer","location","decor","temporal","weather","sound"];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(){const e=Di.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 o=document.createElement("span");o.className="param-nest-label",o.textContent=n.group==="assessment"?this.messages.assessmentGroup:n.group==="summary"?this.messages.summaryGroup:Di.tabLabel(this.groupTabs[this.summaryPanelIndex(n.group)]),r.append(o),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.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),Yy.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 e==="phenomenon"?this.panelIndex("shape"):Di.SUMMARY_GROUPS.indexOf(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 Lx(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.renderParamSummary())}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=Di.QUESTION_FIELDS[s];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[s,r]of Object.entries(Di.QUESTION_FIELDS))for(const o of Di.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",c),(c||l.title===this.messages.questionUnanswered)&&(l.title=c?this.messages.questionUnanswered:"")}const i=new Map;let n;for(const[s,r]of Object.entries(Di.QUESTION_FIELDS))for(const o of r.fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=l.classList.contains("missing-required");!c&&!l.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),o=i.get(r)??0,l=r===n,c=Di.badgeOn(s);c.hidden=o===0,c.textContent=String(o),c.classList.toggle("optional",!l),s.title=o===0?"":l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o))}}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(o=>o.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 o=this.subgroupTabs.find(l=>l.getAttribute("aria-controls")==="shape-bodies");o&&this.openSubgroup(o),this.loadBodyEditor().then(l=>l.show(s.slice(5)));return}if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorSelect.focus();return}const r=this.shadow.getElementById(s);r===null||!n.contains(r)||(this.revealSubgroupOf(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.syncDecorLitFromTimeline(),this.syncDecorPlacementFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),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()}updateAppearanceFieldsDisabledState(){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.sourceSelect,...Object.values(this.presetButtons)])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:I6(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.updatePresetButtons(),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.refreshApparentSize())}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,lt.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,lt.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(lt.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(lt.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),o=n.bounds.height*(n.bounds.width===0?1:r/n.bounds.width),l={x:n.bounds.x+(n.bounds.width-r)/2,y:n.bounds.y+(n.bounds.height-o)/2,width:r,height:o},c=s.ofBounds(l),h=n.kind==="oval"?{...n,bounds:l,angular:c}:{...n,bounds:l,angular:c,points:this.scalePoints(n,l)};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={[Si.NONE.id]:this.messages.filterNone,[Si.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[Si.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=this.filterSelect.value||Si.NONE.id;this.filterSelect.replaceChildren();for(const i of Si.ALL){const n=document.createElement("option");n.value=i.id,n.textContent=e[i.id]??i.name,this.filterSelect.appendChild(n)}this.filterSelect.value=t}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=Rt.availableAt(t),n=e.instrument,s=i.includes(n)?i:[...i,n],r=this.instrumentSelect.value||n.id;this.instrumentSelect.replaceChildren();for(const o of s){const l=document.createElement("option");l.value=o.id;const c=this.naming.instrument(o);l.textContent=i.includes(o)?c:this.messages.instrumentOutOfPeriod.replace("{name}",c),this.instrumentSelect.appendChild(l)}this.instrumentSelect.value=s.some(o=>o.id===r)?r:n.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Di.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=at(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??Rt.fieldOfViewDeg(t),r=n?Rt.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),tn.fit(this.focalLengthInput.parentElement??this.shadow),this.focalFovOutput.textContent=n&&s!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(s,s<10?1:0)):"";const o=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),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 l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":Di.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0),this.exposureInput.disabled=t.exposureRangeSeconds===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=Si.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Rt.fieldOfViewDeg(e),n=Rt.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>E6||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 at(e,this.ufoElement.currentTime)?.fovDeg??Rt.fieldOfViewDeg(e.instrument)}currentProjection(){return Ts.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=lt.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=at(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?Rt.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,o=n?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*Xf*e/l*i.heightMm,h=r*r/(o*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),o=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))+o+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=(g,m)=>Number(g.toFixed(m)),s=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??b6,o=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),l=o!==void 0&&o<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(lt.sizeMAt(c,h),2),lengthM:n(lt.sizeMAt(c,h),2),heightM:n(lt.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},f={t,...p,distanceM:c,...l?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=je(async()=>{const{BodyEditor:e}=await import("./BodyEditor-CiPDf3PA.js");return{BodyEditor:e}},__vite__mapDeps([8,9]),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,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,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}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:lt.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=Ts.of(i.instrument,lt.CANVAS_HEIGHT_PX,Ui.fovOf(i,e));i.timeline.addKeyframe(e,t.map(s=>{const r=Ui.aimOf(i,e,s.shape.bounds),o=n.ofBounds(s.shape.bounds);return{...s,shape:r?{...s.shape,aim:r,angular:o}:{...s.shape,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.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;if(e.sourceIds.length>0||this.currentSourceId===void 0){const t=new Set([...e.sourceIds,this.currentSourceId]);let i=t.size+1;for(;t.has(`ufo-${i}`);)i++;this.currentSourceId=`ufo-${i}`}this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}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]??fc,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.decorKindSelect.querySelector(`option[value="${e.kind}"]`)?.textContent??e.kind} ${n}`}addDecor(e=this.decorKindSelect.value){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==="building"?{floors:hl}:{},windows:Xy(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(n.id,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.syncDecorModelFields(this.ufoElement.sighting.decor.find(s=>s.id===e)),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*zf,t=Math.round(e/A6*1e3);return{lights:Md.byId("airliner")?.create(),track:[{t:0,eastM:-zf,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:zf,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.kind===e).length;return`${this.decorKindSelect.querySelector(`option[value="${e}"]`)?.textContent??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.decorSelect.value=e,this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,i=this.decorObserverSideSelect.value;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=eo(n.kind)&&i!==""?i:void 0,r=Number(this.decorEastInput.value),o=Number(this.decorNorthInput.value),l=Number(this.decorAltitudeInput.value),c=n.track??(l!==0?[]:void 0);if(c){const h=this.ufoElement.currentTime,d={t:h,eastM:r,northM:o,altitudeM:l,headingDeg:t},u=c.filter(p=>p.t!==h);return{...n,title:this.said.write(n.title,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),track:[...u,d].sort((p,f)=>p.t-f.t),sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}return{...n,title:this.said.write(void 0,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),eastM:r,northM:o,headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(n=>n.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}syncDecorSizeFields(e){const t=e?$t.naturalSize(e.kind,e.floors):void 0,i=[[this.decorWidthInput,e?.sizeM?.widthM,t?.widthM],[this.decorLengthInput,e?.sizeM?.lengthM,t?.lengthM],[this.decorHeightInput,e?.sizeM?.heightM,t?.heightM]];for(const[n,s,r]of i)n.value=s===void 0?"":String(this.roundedMeters(s)),n.placeholder=r===void 0?"":String(this.roundedMeters(r))}syncDecorModelFields(e){this.refreshDecorModelOptions(e),this.decorModelSelect.value=e?.model?.id??"",this.decorModelUrlInput.value=e?.model?.url??"",this.decorModelTitleInput.value=e?.model?.credit?.title??"",this.decorModelAuthorInput.value=e?.model?.credit?.author??"",this.decorModelLicenseInput.value=e?.model?.credit?.license??"",this.decorModelSourceInput.value=e?.model?.credit?.sourceUrl??"",this.decorModelAdvanced.open=e?.model?.url!==void 0,this.showDecorCatalogueModel(e)}async showDecorCatalogueModel(e){const t=e?.model?.url===void 0?e?.model?.id:void 0,i=t===void 0?void 0:await this.decorModelProvider.entry(t).catch(()=>{});e?.id===this.currentDecorId&&(this.shownDecorEntry=i,this.decorModelCatalogueNote.hidden=i===void 0,i&&(this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.credit.title,this.decorModelAuthorInput.value=i.credit.author??"",this.decorModelLicenseInput.value=i.credit.license,this.decorModelSourceInput.value=i.credit.sourceUrl??"",this.syncDecorVisibility()))}shownDecorEntry;modelPicker;async refreshDecorModelOptions(e){const t=e??this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),i=t?await this.decorModelProvider.entries(t.kind).catch(()=>[]):[],n=t?.model?.id??"",s=document.createElement("option");s.value="",s.textContent=t&&ou[t.kind]?this.messages.decorModelDefault:this.messages.decorModelNone,this.decorModelSelect.replaceChildren(s,...i.map(r=>{const o=document.createElement("option");return o.value=r.id,o.textContent=r.name,o.title=`${r.credit.title}${r.credit.author?` — ${r.credit.author}`:""} (${r.credit.license})`,o})),this.decorModelSelect.value=n}updateDecorModelChoice(){const e=this.decorModelSelect.value;(async()=>{const t=e?await this.decorModelProvider.entry(e).catch(()=>{}):void 0,i=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),n=this.shownDecorEntry;this.shownDecorEntry=t,this.decorModelCatalogueNote.hidden=t===void 0,this.decorModelUrlInput.value=t?.url??"",this.decorModelTitleInput.value=t?.credit.title??"",this.decorModelAuthorInput.value=t?.credit.author??"",this.decorModelLicenseInput.value=t?.credit.license??"",this.decorModelSourceInput.value=t?.credit.sourceUrl??"";const s=i?.sizeM!==void 0&&n?.sizeM!==void 0&&i.sizeM.widthM===n.sizeM.widthM&&i.sizeM.lengthM===n.sizeM.lengthM&&i.sizeM.heightM===n.sizeM.heightM;if(t?.sizeM&&i&&(!i.sizeM||s)){const r=[[this.decorWidthInput,t.sizeM.widthM],[this.decorLengthInput,t.sizeM.lengthM],[this.decorHeightInput,t.sizeM.heightM]];for(const[o,l]of r)l!==void 0&&(o.value=String(this.roundedMeters(l)))}this.updateDecor()})()}roundedMeters(e){return Math.round(e*100)/100}positiveMeters(e){const t=Number(e);return e.trim()===""||!Number.isFinite(t)||t<=0?void 0:t}statedDecorColor(e){const t=this.decorColorInput.value;return t==="#808080"&&e.color===void 0?void 0:t}statedDecorSize(){const e=this.positiveMeters(this.decorWidthInput.value),t=this.positiveMeters(this.decorLengthInput.value),i=this.positiveMeters(this.decorHeightInput.value);return e===void 0&&t===void 0&&i===void 0?void 0:{widthM:e,lengthM:t,heightM:i}}statedDecorModel(){const e=this.stringOrUndefined(this.decorModelUrlInput.value),t=this.shownDecorEntry;if(t&&e===t.url&&this.stringOrUndefined(this.decorModelTitleInput.value)===t.credit.title&&this.stringOrUndefined(this.decorModelAuthorInput.value)===t.credit.author&&this.stringOrUndefined(this.decorModelLicenseInput.value)===t.credit.license&&this.stringOrUndefined(this.decorModelSourceInput.value)===t.credit.sourceUrl)return{id:t.id};if(e){const n=this.stringOrUndefined(this.decorModelTitleInput.value),s=this.stringOrUndefined(this.decorModelLicenseInput.value);return{url:e,credit:n!==void 0&&s!==void 0?{title:n,license:s,author:this.stringOrUndefined(this.decorModelAuthorInput.value),sourceUrl:this.stringOrUndefined(this.decorModelSourceInput.value)}:void 0}}const i=this.stringOrUndefined(this.decorModelSelect.value);return i===void 0?void 0:{id:i}}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=io([...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=io(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;for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.milestoneLabelInput,this.milestoneNoteInput,this.deleteMilestoneButton])i.disabled=!t,this.setRowVisible(i,t);this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}updateDecorTitleValidity(){const e=this.currentDecorId!==void 0&&this.decorTitleInput.value==="";this.decorTitleInput.classList.toggle("invalid",e),this.decorTitleInput.setAttribute("aria-invalid",String(e))}updateDecorWindows(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.map(t=>{if(t.id!==this.currentDecorId)return t;const i={};for(const n of Mo){const s=this.decorWindowInputs[n];if(s.value==="")continue;const r=Yf(t.kind,n)?0:$f,o=Math.max(r,Math.min(100,Number(s.value)));i[n]=o,String(o)!==s.value&&(s.value=String(o))}return{...t,windows:i}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,i=this.decorLitInput.checked;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=[...(n.litKeyframes??[]).filter(r=>r.t!==t),{t,lit:i}].sort((r,o)=>r.t-o.t);return{...n,litKeyframes:s}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.decorLabel(t),this.decorSelect.appendChild(i)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const i of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelSelect,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorObserverSideSelect,this.decorLightRigSelect,this.decorAltitudeInput,this.lookAtDecorButton])i.disabled=!t;this.decorTitleInput.value=this.said.read(e?.title)??"",this.decorColorInput.value=e?.color??"#808080",this.showDecorPlacement(e),this.decorLitInput.checked=e?cu(e,this.ufoElement.currentTime):!1,this.refreshDecorLightRigOptions(e),this.decorSightingUrlInput.value=e?.sightingUrl??"",this.syncDecorSizeFields(e),this.syncDecorModelFields(e),this.decorFloorsInput.value=String(e?.floors??hl),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorObserverSideSelect.value=e?.observerSide??"";for(const i of Mo){const n=e?.windows?.[i];this.decorWindowInputs[i].value=n===void 0?"":String(n)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(h=>h.id===this.currentDecorId),t=e!==void 0,i=e?.kind;this.setRowVisible(this.decorSelect,t),this.setRowVisible(this.deleteDecorButton,t),this.setRowVisible(this.decorTitleInput,t),this.setRowVisible(this.decorEastInput,t),this.setRowVisible(this.decorNorthInput,t),this.setRowVisible(this.decorAltitudeInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorWidthInput,t),this.setRowVisible(this.decorLengthInput,t),this.setRowVisible(this.decorHeightInput,t);const n=e?Hu.of(e,this.shownDecorEntry?.id===e.model?.id?this.shownDecorEntry?.parameters:void 0):void 0;this.setRowVisible(this.decorColorInput,n?.color===!0),this.setRowVisible(this.decorModelSelect,t),this.decorModelAdvanced.hidden=!0,this.setRowVisible(this.decorLitInput,n?.lit===!0),this.setRowVisible(this.decorLightRigSelect,n?.lights===!0);const s=n?.windows===!0;this.setRowVisible(this.labelDecorWindows,s);const r=i!==void 0?Rm(i):[];for(const h of Mo)this.decorWindowInputs[h].disabled=!t,this.decorWindowInputs[h].min=String(i!==void 0&&Yf(i,h)?0:$f),this.setRowVisible(this.decorWindowInputs[h],s&&r.includes(h));const o=n?.observerSide===!0;this.setRowVisible(this.decorObserverSideSelect,o);const l=i!==void 0?kx(i):[];for(const h of Mo)this.optionObserverSide[h].hidden=!l.includes(h);const c=n?.floors===!0;this.setRowVisible(this.decorFloorsInput,c),this.setRowVisible(this.decorOccupiedFloorInput,c),this.decorOccupiedFloorInput.max=String(e?.floors??hl)}showDecorPlacement(e){const t=e?tr(e,this.ufoElement.currentTime):void 0,i=[[this.decorEastInput,t?.eastM??0],[this.decorNorthInput,t?.northM??0],[this.decorAltitudeInput,t?.altitudeM??0],[this.decorHeadingInput,t?.headingDeg??0]];for(const[n,s]of i)this.shadow.activeElement!==n&&(n.value=String(this.rounded(s)))}syncDecorPlacementFromTimeline(){this.ufoElement.playbackState!=="playing"&&this.showDecorPlacement(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++);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),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;skyCandidatesKey;static reentryArchive=new Rn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Nu;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new qn(["en"]);tagNames=new Kf({});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?Yn(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,hi(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!n||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.hidden=!0,this.showCometButton.hidden=!0,this.showNovaButton.hidden=!0,this.showSatelliteButton.hidden=!0,this.showFireballButton.hidden=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown);return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=[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(l=>l!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return nn.gainFor(e.instrument,{fNumber:at(e,0)?.fNumber,fieldOfViewDeg:Ui.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Ni("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=sa(i,n,s),o=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<M6)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",o(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",o(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",o(Math.abs(n))).replace("{eye}",o(sa(i,0,s)));return r<=Pc?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Pc))}showerClause(e,t){const i=oi.observedRatePerHour(oi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=El.activeAt(e);if(n.length===0)return this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyNothingActive.replace("{sporadic}",i);const s=n.map(r=>{const o=El.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:El.observedRatePerHour(r.zhr,o.altitudeDeg,r.shower.populationIndex)}}).sort((r,o)=>o.rate-r.rate)[0];return s.rate<=0?(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(s.entry.shower))):(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),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=kd.brightestAt(e,t);if(!i||i.magnitude>Fl){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=i.position.altitudeDeg<=0,this.cometText(i)}novaClause(e,t){const i=Fu.brightestAt(e,t);if(!i||i.magnitude>Fl){this.showNovaButton.hidden=!0;return}return this.showNovaButton.hidden=i.position.altitudeDeg<=0,this.novaText(i)}eclipseClause(e,t){const i=bi.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const n=Ni("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),o=Math.round(i.totality.seconds%60);return s(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${o} 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=Ni("Moon",e,t);if(i.altitudeDeg<=0||Ca(e).illuminatedFraction<.97)return;const n=[],s=cn.distanceKm(e,t),r=cn.relativeToMean(cn.radiusAtKm(s)),o=s<=cn.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:s>=cn.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return o&&n.push(o.replace("{distance}",(Math.round(s/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(cn.radiusAtKm(s)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),zu.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=Ms.visibilityAt(e,t),n=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(n!==void 0)return n;if(this.showSatelliteButton.hidden=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=sa(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),o=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}",o);const l=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",l).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",o):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,Di.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=Ms.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(o.length===0)return;const l=o.slice(0,3).map(c=>this.reentryText(c));return o.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",l.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 o=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",o)}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(h=>h.status!=="covered"))return this.showSatelliteButton.hidden=!0,t.coverage.some(h=>h.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses(),n=i.filter(h=>this.passTimelineMs(h)<=this.ufoElement.seekableDuration);if(this.showSatelliteButton.hidden=n.length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const r=i[0].peak,l=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",r.object.name).replace("{magnitude}",r.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(r.altitudeDeg))).replace("{bearing}",this.naming.towards(r.azimuthDeg)).replace("{time}",this.observerClock(r.date)),c=this.starlinkTrain(i);return c?`${l}, ${c}`:l}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=Ni("Sun",i.peak.date,t);return n<=sa(s.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,n)=>i.peak.magnitude-n.peak.magnitude)}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:o,launch:l}=r.peak.object;o!=="starlink"||!l||(r.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[i,n]=[...t.entries()].sort((r,o)=>o[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=at(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=Yn(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.visibleSatellitePasses().filter(n=>this.passTimelineMs(n)<=this.ufoElement.seekableDuration);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=>os.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=os.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,n)=>i.magnitude-n.magnitude)}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.hidden=!i.some(r=>this.fireballTimelineMs(r,e)<=this.ufoElement.seekableDuration),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=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.strikingFireballs(n,this.observerAtStart()).filter(o=>this.fireballTimelineMs(o,n)<=this.ufoElement.seekableDuration);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=hi(this.ufoElement.sighting,0),n=Ni("Sun",e,t),s=Ni("Moon",e,t),r=bt.deckLitUntilDeg(bt.DECK_HEIGHT_M),o=n.altitudeDeg>-r,l=o?n:s;if(l.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(bt.strength(c,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(bt.formsAt(l.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??Od;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=hi(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Ni("Sun",e,t),s=Ni("Moon",e,t),r=n.altitudeDeg>0,o=r?n:s;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(rn.strength(i.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=rn.formsAt(o.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(rn.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(Ca(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Ni("Sun",e,t);if(i.altitudeDeg>D6)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<=_t.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),o=Ni("Moon",e,t),l=n.darkestSkyMagPerArcsec2<R6,c=this.ufoElement.sighting.lightPollution,h=ce.scatteringAt(90-o.altitudeDeg)*ce.moonOutput(ce.phaseAngleOf(Ca(e).illuminatedFraction),o.altitudeDeg)*ce.scatteredFraction(90),d=ce.artificialZenithNanolamberts(c)>h;if(l&&o.altitudeDeg>0&&!d){const p=Math.round(Ca(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=ce.artificialZenithNanolamberts(c)>ce.twilightExcessNanolamberts(i.altitudeDeg);return l&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):l?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Ni("Sun",e,t),n=Ni("Moon",e,t);return ce.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(Ca(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new _t;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<kd.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=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=kd.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(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=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Fu.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(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(l=>l.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:n}=tr(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,o=Math.atan2(n-_6,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}refreshDecorLightRigOptions(e){const t=e?Md.forKind(e.kind):[],i=document.createElement("option");i.value="",i.textContent=this.messages.decorLightsNone,this.decorLightRigSelect.replaceChildren(i,...t.map(s=>{const r=document.createElement("option");return r.value=s.id,r.textContent=this.naming.lightRig(s),r}));const n=e?.lights?.map(s=>s.id).join()??"";this.decorLightRigSelect.value=t.find(s=>s.create().map(r=>r.id).join()===n)?.id??""}updateDecorLightRig(){const e=this.ufoElement.sighting,t=e.decor.find(n=>n.id===this.currentDecorId);if(!t)return;const i=Md.byId(this.decorLightRigSelect.value);e.decor=e.decor.map(n=>n.id===t.id?{...n,lights:i?i.create():void 0}:n),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorLitFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.shadow.activeElement===this.decorLitInput)return;const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);e&&(this.decorLitInput.checked=cu(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of xy)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return Cg(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-qo.width/2,y:e.height/2-qo.height/2,width:qo.width,height:qo.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 UC(this.ufoElement.sighting.timeline,new BC(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){this.recordButton.textContent=e?"⏹":"⏺";const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t)}async loadLocaleMessages(){const e=++this.localeToken,t=hs.preferencesFor(this);this.preferences=t;const i=Fc(t,Hc),n=this.narrativeProvider.localize?.(i),[s,r,o]=i==="en"?[Il,{},void 0]:await Promise.all([Hy(i),xx(i),Gy(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.naming=new Nu(o),this.said=new qn(t),this.tagNames=new Kf(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new dl(s,this.naming,this.said,this.tagNames,{messages:s,locale:this.language}),this.refreshParamSummary()),l?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===fc&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.presetButtons.oval.textContent=e.oval,this.presetButtons.polygon.textContent=e.polygon,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.labelShape.textContent=e.shape,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.labelSizeLock.textContent=e.sizeLock;for(const[n,s]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(n).textContent=s;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.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.labelImportFile.textContent=e.importFile,this.labelImportUrl.textContent=e.importUrl,this.importUrlInput.placeholder=e.importUrlPlaceholder,this.importUrlButton.textContent=e.importButton,this.labelObserverAge.textContent=e.observerAge,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,this.labelAccountUrl.textContent=e.accountUrl,this.labelAccountFollowedUp.textContent=e.accountFollowedUp;for(const[n,s]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 r=this.shadow.getElementById(n);r&&(r.textContent=s)}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.labelLatitude.textContent=e.latitude,this.labelLongitude.textContent=e.longitude,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.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.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorGroup.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorShrub.textContent=e.decorShrub,this.optionDecorBridge.textContent=e.decorBridge,this.optionDecorWire.textContent=e.decorWire,this.optionDecorCrop.textContent=e.decorCrop,this.optionDecorTerrace.textContent=e.decorTerrace,this.optionDecorMound.textContent=e.decorMound,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorAircraft.textContent=e.decorAircraft,this.optionDecorEntity.textContent=e.decorEntity,this.labelDecorLights.textContent=e.decorLights,this.labelDecorAltitude.textContent=e.decorAltitude,this.showMeteorButton.title=e.showMeteor,this.showMeteorButton.setAttribute("aria-label",e.showMeteor),this.showCometButton.title=e.showComet,this.showCometButton.setAttribute("aria-label",e.showComet),this.showNovaButton.title=e.showNova,this.showNovaButton.setAttribute("aria-label",e.showNova),this.showSatelliteButton.title=e.showSatellite,this.showSatelliteButton.setAttribute("aria-label",e.showSatellite),this.showFireballButton.title=e.showFireball,this.showFireballButton.setAttribute("aria-label",e.showFireball),this.lookAtDecorButton.title=e.lookAtDecor,this.lookAtDecorButton.setAttribute("aria-label",e.lookAtDecor),this.optionDecorObserver.textContent=e.decorObserver,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.deleteDecorButton.title=e.deleteDecor,this.deleteDecorButton.setAttribute("aria-label",e.deleteDecor),this.labelDecorTitle.textContent=e.decorTitle,this.labelDecorEast.textContent=e.decorEast,this.labelDecorNorth.textContent=e.decorNorth,this.labelDecorHeading.textContent=e.decorHeading,this.labelDecorColor.textContent=e.decorColor,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorObserverButton.textContent=e.addObserver,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote;for(const[n,s]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=s,n.setAttribute("aria-label",s);this.labelDecorWidth.textContent=e.decorWidth,this.labelDecorLength.textContent=e.decorLength,this.labelDecorHeight.textContent=e.decorHeight,this.labelDecorModel.textContent=e.decorModel,this.labelDecorModelAdvanced.textContent=e.decorModelAdvanced,this.decorModelCatalogueNote.textContent=e.decorModelFromCatalogue,this.labelDecorModelUrl.textContent=e.decorModelUrl,this.labelDecorModelTitle.textContent=e.decorModelTitle,this.labelDecorModelAuthor.textContent=e.decorModelAuthor,this.labelDecorModelLicense.textContent=e.decorModelLicense,this.labelDecorModelSource.textContent=e.decorModelSource,this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorObserverSide.textContent=e.decorObserverSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionObserverSideNone.textContent=e.decorObserverSideNone;const t={front:e.decorSideFront,behind:e.decorSideBehind,left:e.decorSideLeft,right:e.decorSideRight,"front-left":e.decorSideFrontLeft,"front-right":e.decorSideFrontRight,"behind-left":e.decorSideBehindLeft,"behind-right":e.decorSideBehindRight};for(const n of Mo)this.labelDecorSide[n].textContent=t[n],this.optionObserverSide[n].textContent=t[n];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.bodyEditor?.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.observerGroup,this.labelWeatherGroup.textContent=e.weather,this.startDate.messages=e,this.endDate.messages=e,this.paramSummaryBuilder=new dl(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),this.refreshParamSummary();const i=this.skyDetailsButton.getAttribute("aria-expanded")==="true";this.skyDetailsButton.title=i?e.skyDetailsHide:e.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,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.labelReference.textContent=e.reference,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSrcInput.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.addReferenceUrlButton.textContent=e.addReferenceUrl,this.labelAddReferenceFile.textContent=e.addReferenceFile,this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.textContent=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.referenceStreetSearchButton.textContent=e.referenceStreetSearch,this.labelTraceImport.textContent=e.traceImport,this.labelTrace.textContent=e.trace,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[n,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}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;!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)&&this.beginCameraDrag(t);return}if(i==="decor"&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t))return;const n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const h=new dp(this.selectedMembers()),d=Tt.hitTestHandle({bounds:h.bounds(),angle:0},t);if(d==="rotate"){if(r)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(d){if(r)return;this.dragState={kind:"group-resize",group:h,handle:d},this.startDragListening();return}}else{const h=n.getInterpolatedShapeAt(s,this.currentSourceId),d=h?.kind==="polygon"?Tt.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&d!==void 0){if(r)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:d},this.startDragListening();return}const u=h&&Tt.hitTestHandle(h,t);if(h&&u){if(r)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const l=this.ufoElement.shapeAt(t.x,t.y,vy);if(!l){const h=this.pickDecorAt(e);if(h!==void 0){r?this.selectDecor(h):this.beginCameraDrag(t,h);return}r||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(l.sourceId):this.selectedSourceIds.has(l.sourceId)||this.selectUnit(l.sourceId),r||!o)return;const c=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===l.sourceId?l.shape:n.getInterpolatedShapeAt(s,h)??l.shape}));this.dragState={kind:"move",sources:c,startPointer:t},this.startDragListening()}revealShapePanel(){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.refreshSourceList(),this.onSelectionOrTimeChanged())}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,o)=>s.indexOf(r)-s.indexOf(o)).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,o=s?.kind==="polygon"&&Tt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,vy);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),c=l?this.ufoElement.sighting.decor.find(h=>h.id===l):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)),o=n.length>0&&i.slice(0,n.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||o,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,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?Tt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=Wy;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];if(t.length===0){const i=document.createElement("span");i.className="submenu-empty",i.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(i)}for(const i of t){const n=document.createElement("label"),s=document.createElement("input");s.type="checkbox",s.checked=e.occludesSourceIds?.includes(i)??!1,s.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,i,s.checked)),n.appendChild(s),n.appendChild(document.createTextNode(this.shapeLabel(i))),this.contextMasksSubmenu.appendChild(n)}}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(o=>o!==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=Tt.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=Tt.hitTestVertex(i,e);if(n===void 0)return;const s=Tt.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(by,(e.maxX-e.minX)/2*t.width),n=Math.max(by,(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=Tt.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:o}=t,l=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=o==="e"||o==="w",h=o==="n"||o==="s",d=c?l(i.x-n.x,s.x-n.x):h?l(i.y-n.y,s.y-n.y):l(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:Bf};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.editableDecor()===void 0?void 0:{sizeM:{widthM:this.decorSizeFieldM(this.decorWidthInput),lengthM:this.decorSizeFieldM(this.decorLengthInput),heightM:this.decorSizeFieldM(this.decorHeightInput)},attitude:{headingDeg:this.numberOrUndefined(this.decorHeadingInput.value)??0,pitchDeg:0,rollDeg:0}},resize:e=>{this.decorWidthInput.value=String(this.roundedMeters(e.widthM)),this.decorLengthInput.value=String(this.roundedMeters(e.lengthM)),this.decorHeightInput.value=String(this.roundedMeters(e.heightM)),this.updateDecor()},turnTo:e=>{this.decorHeadingInput.value=String(this.rounded((e.headingDeg%360+360)%360)),this.updateDecor()},rotateDegPerPx:x6};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)};decorSizeFieldM(e){return this.positiveMeters(e.value)??this.positiveMeters(e.placeholder)??1}beginDecorDrag(e,t){const i=this.editableDecor();if(!i)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.pickDecorAt(e)!==i.id)return!1;const n=this.ndcOf(e),s=n&&this.sceneElement.decorGroundPointAt(i.id,n.x,n.y);return s?(this.dragState={kind:"decor-move",id:i.id,startGround:s,startEastM:Number(this.decorEastInput.value)||0,startNorthM:Number(this.decorNorthInput.value)||0},this.setCanvasCursor("move"),this.startDragListening(),!0):!1}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e),n=i&&this.sceneElement.decorGroundPointAt(t.id,i.x,i.y);n&&(this.decorEastInput.value=String(this.roundedMeters(t.startEastM+n.x-t.startGround.x)),this.decorNorthInput.value=String(this.roundedMeters(t.startNorthM-(n.z-t.startGround.z))),this.updateDecor())}beginCameraDrag(e,t){const i=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,moved:!1,startPointer:e,startHeadingDeg:i?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:i?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:i},i||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&eo(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&eo(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,o=t.y-s.y,l=n.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+o}}}));this.commitShapes(i,l)}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,o=Tt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}else{const{kind:n,sourceId:s,original:r,handle:o}=this.dragState,l=n==="resize"?Tt.resizeShape(r,o,t):Tt.rotateShape(r,t);this.commitShapes(i,[{sourceId:s,shape:l}])}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)<S6)return;this.cameraDragState.moved=!0}const o=n+(t.x-i.x)*Bf,l=Math.max(-90,Math.min(90,s-(t.y-i.y)*Bf));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),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))}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ta,i.width-Wr);break;case"ArrowRight":i.width+=Wr;break;case"ArrowUp":i.height=Math.max(ta,i.height-Wr);break;case"ArrowDown":i.height+=Wr;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Wr;break;case"ArrowRight":i.x+=Wr;break;case"ArrowUp":i.y-=Wr;break;case"ArrowDown":i.y+=Wr;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 dp(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 l=r?this.bodyCanvasBounds():void 0,c=l&&Tt.hitTestHandle({bounds:l,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){const l=this.decorCanvasBounds(),c=l&&Tt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);if(this.pickDecorAt(e)===this.currentDecorId)return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const l=Tt.hitTestHandle({bounds:new dp(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=n.getInterpolatedShapeAt(s,this.currentSourceId);if(l?.kind==="polygon"&&Tt.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&Tt.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return n.hitTest(s,t.x,t.y)?r&&o?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${Tt.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(Ay(this.buildPrototype({x:0,y:0,width:qo.width,height:qo.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 C6={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},Sy="rr0-sighting-editor",Ey="rr0-ufo-recorder";class P6 extends Di{}function Hw(){Fy(),GC(),qu(),customElements.get(Sy)||customElements.define(Sy,Di),customElements.get(Ey)||customElements.define(Ey,P6)}const wm={recording:"Recording",untitledReading:"Reading {n}",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 observation",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"A JSON file",sourceUrl:"An address",observerField:"Observer",fileField:"File",urlField:"Address",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",caseTitle:"Title",caseTime:"When",recordingsHeading:"Observations",add:"Add",addHint:"Add",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"},L6=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:wm},Symbol.toStringTag,{value:"Module"})),_y="rr0-case-editor",k6=`
|
|
9692
|
+
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await je(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-BMvmda-2.js");return{ModelThumbnails:i}},__vite__mapDeps([3,4]),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;const r=()=>{const l=++s,c=e.selectedOptions[0],h=e.value===""?i?.current():void 0;n.replaceChildren();const d=document.createElement("span");d.textContent=`${h?h.title||h.url:c?.textContent??""} …`,n.title=this.messages().choose,n.append(d);const u=e.value;(h?Promise.resolve({url:h.url}):t(u)).then(p=>Oc.pictureOf(p)).then(p=>{if(!p||l!==s)return;const f=new Image;f.src=p,f.alt="",n.prepend(f)})};e.addEventListener("change",r),new MutationObserver(r).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:l=>{i.apply(l),r()}};n.addEventListener("click",()=>void this.open(e,t,o)),r()}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=Oc.STYLE,t.append(i)}open(e,t,i){const n=this.messages(),s=document.createElement("div");s.className="model-picker-backdrop";const r=document.createElement("div");r.className="model-picker",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=n.title;const l=document.createElement("button");l.type="button",l.className="model-picker-close",l.setAttribute("aria-label",n.close),l.title=n.close,l.textContent="✕";const c=document.createElement("header");c.append(o,l);const h=document.createElement("div");h.className="model-picker-body",r.append(c,h),s.append(r);const d=()=>{s.remove(),document.removeEventListener("keydown",u,!0),je(async()=>{const{ModelViewer:S}=await import("./ModelViewer-O9_A3wzF.js");return{ModelViewer:S}},__vite__mapDeps([5,4]),import.meta.url).then(({ModelViewer:S})=>S.end())},u=S=>{S.key==="Escape"&&(S.stopPropagation(),d())},p=i?.current(),f="\0address",g=S=>S===f&&p?Promise.resolve({url:p.url}):t(S),m=S=>{d(),!(S===f||S===e.value)&&(e.value=S,e.dispatchEvent(new Event("change",{bubbles:!0})))};let v;const x=new Map,y=S=>{const _=document.createElement("button");_.type="button",_.className="model-card",_.setAttribute("aria-pressed",String(S.value===f||S.value===e.value&&!p));const M=document.createElement("div");M.className="model-thumb";const T=document.createElement("span");if(T.className="model-name",T.textContent=S.textContent,_.append(M,T),S.title){const z=document.createElement("span");z.className="model-credit",z.textContent=S.title,_.append(z)}g(S.value).then(z=>Oc.pictureOf(z)).then(z=>{if(!z)return;const L=new Image;L.src=z,L.alt="",M.append(L)});let A,R=!1;const C=()=>{R&&!(A&&!A.active)||(R=!0,Promise.all([g(S.value),je(()=>import("./ModelViewer-O9_A3wzF.js"),__vite__mapDeps([5,4]),import.meta.url)]).then(([z,{ModelViewer:L}])=>{!z||!R||(A=L.show(M,z))}).catch(()=>{}))},k=()=>{R=!1,A?.stop(),A=void 0};return x.set(_,C),_.addEventListener("pointerenter",C),_.addEventListener("focus",C),_.addEventListener("pointerleave",()=>{document.activeElement!==_&&k()}),_.addEventListener("blur",k),_.addEventListener("click",z=>{if(A?.consumeDrag()){z.preventDefault();return}m(S.value)}),_},b=()=>(v=document.createElement("div"),v.className="model-picker-grid",h.append(v),v);if(p){const S=new Option(p.title||p.url,f);S.title=[p.author,p.license].filter(Boolean).join(" — "),b().append(y(S))}for(const S of Array.from(e.children))if(S instanceof HTMLOptGroupElement){const _=document.createElement("h3");_.textContent=S.label,h.append(_);const M=b();for(const T of Array.from(S.children))M.append(y(T));v=void 0}else S instanceof HTMLOptionElement&&(v??b()).append(y(S));i&&this.addAddressForm(c,l,r,h,i,n,d),l.addEventListener("click",d),s.addEventListener("click",S=>{S.target===s&&d()}),document.addEventListener("keydown",u,!0),this.root.append(s);const w=r.querySelector('.model-card[aria-pressed="true"]');(w??l).focus(),w&&x.get(w)?.()}addAddressForm(e,t,i,n,s,r,o){const l=document.createElement("button");l.type="button",l.className="model-picker-add",l.textContent="+",l.title=r.address,l.setAttribute("aria-label",r.address),l.setAttribute("aria-expanded","false"),e.insertBefore(l,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(y,b,w="")=>{const S=document.createElement("label"),_=document.createElement("span");_.textContent=y;const M=document.createElement("input");return M.type=b,M.placeholder=w,S.append(_,M),c.append(S),M},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"),g=h(r.addressSource,"url","https://…"),m=document.createElement("p");m.textContent=r.addressIncomplete;const v=document.createElement("button");v.type="submit",v.className="model-picker-use",v.textContent=r.addressUse,c.append(m,v),i.insertBefore(c,n);const x=()=>{v.disabled=d.value.trim()==="",m.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const y of[d,u,p,f,g])y.addEventListener("input",x);l.addEventListener("click",()=>{const y=c.hidden;if(c.hidden=!y,l.setAttribute("aria-expanded",String(y)),!y)return;const b=s.current();d.value=b?.url??"",u.value=b?.title??"",p.value=b?.author??"",f.value=b?.license??"",g.value=b?.source??"",x(),d.focus()}),c.addEventListener("submit",y=>{y.preventDefault(),d.value.trim()!==""&&(s.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:g.value.trim()}),o())}),x()}}class Hu{static of(e,t){const i=Hu.drawnAsModel(e);return{color:t?.color??!i,lit:t?.lit??Hu.litByDefault(e.kind,i),lights:(t?.lights??!0)&&Md.forKind(e.kind).length>0,windows:!i&&Cm(e.kind),floors:!i&&e.kind==="building",observerSide:eo(e.kind)}}static drawnAsModel(e){return lu(e)!==void 0&&!(e.observerSide!==void 0&&eo(e.kind))}static litByDefault(e,t){return e==="streetlight"||e==="vehicle"&&!t}}class Mg{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=Mg.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 f6{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)}}function mr(a,e){return a.find(t=>t.id===e)??a[0]}class m6{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 g6=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new m6}],vy=new Set;qu();FC();const qo={width:48,height:28},v6=2500,by=40,b6=10,yy=600,My=900,Ko=2e-4,y6=900,M6=-1.46,w6=3,Bf=.2,x6=.5,S6=3,E6=.01,_6=1.6,zf=2e3,A6=250,wy=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),Wr=4,fc="ufo-1",xy=["oval","polygon"],T6={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function I6(a){return a.kind==="oval"?"oval":"polygon"}const D6=-6,R6=21;class Ri extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=g6[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new f6;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;durationElement;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=h6();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;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;fileEditor;fileEditorLoading;fileEditorHost;fileNote;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 kf(l6());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;labelShape;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;labelImportFile;labelImportUrl;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;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;highCloudCoverInput;iceCrystalAlignmentInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorObserverButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorColorInput;decorLitInput;decorLightRigSelect;lookAtDecorButton;decorAltitudeInput;labelDecorAltitude;decorSightingUrlInput;decorModelProvider=Pd[0].create();milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorWidthInput;decorLengthInput;decorHeightInput;decorModelSelect;decorModelAdvanced;decorModelCatalogueNote;decorModelUrlInput;decorModelTitleInput;decorModelAuthorInput;decorModelLicenseInput;decorModelSourceInput;decorFloorsInput;decorOccupiedFloorInput;decorObserverSideSelect;decorWindowInputs;labelDecorSide;optionObserverSide;labelDecor;labelDecorGroup;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorColor;labelDecorLit;labelDecorSightingUrl;labelMilestones;labelMilestoneLabel;labelMilestoneNote;labelDecorWidth;labelDecorLength;labelDecorHeight;labelDecorModel;labelDecorModelAdvanced;labelDecorModelUrl;labelDecorModelTitle;labelDecorModelAuthor;labelDecorModelLicense;labelDecorModelSource;labelDecorFloors;labelDecorOccupiedFloor;labelDecorObserverSide;labelDecorWindows;optionObserverSideNone;optionDecorBuilding;optionDecorTree;optionDecorShrub;optionDecorBridge;optionDecorWire;optionDecorCrop;optionDecorTerrace;optionDecorMound;optionDecorStreetlight;optionDecorVehicle;optionDecorAircraft;optionDecorEntity;labelDecorLights;optionDecorObserver;recorder;isRecording=!1;messages=Il;currentAppearance={...T6};currentSourceId=fc;selectedSourceIds=new Set([fc]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSrcInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;addReferenceUrlButton;addReferenceFileInput;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;referenceStreetSearchButton;addTraceFileInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;labelTrace;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$=new ol;referenceFields;labelReferenceGroup;labelReference;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;labelAddReferenceFile;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(wy.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;wy.has(e.key)?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;this.endDrag(),e!==void 0&&(this.selectDecor(e),this.revealDecorPanel())};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${Bx}</style>${Ux}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const i of this.shadow.querySelectorAll(iu))i.build();for(const i of this.shadow.querySelectorAll(Bu))i.build();this.sceneElement=document.createElement(Uu),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",i=>{this.ufoElement.sighting.observerMap=i.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",i=>{const{lat:n,lng:s}=i.detail;this.latInput.value=String(Number(n.toFixed(6))),this.lngInput.value=String(Number(s.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.presetsGroup=this.shadow.getElementById("presets-group"),this.presetButtons={oval:this.shadow.getElementById("preset-oval"),polygon:this.shadow.getElementById("preset-polygon")},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.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.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 Sc(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const i of[this.timeStartLabel,this.timeEndLabel])i.addEventListener("click",()=>this.switchTimeDisplay()),i.addEventListener("keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.durationElement=this.shadow.querySelector(Bu),this.durationInput=this.durationElement.input,this.exportButton=this.shadow.getElementById("export"),this.importFileInput=this.shadow.getElementById("import-file"),this.importUrlInput=this.shadow.getElementById("import-url"),this.importUrlButton=this.shadow.getElementById("import-url-button"),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.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.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.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.labelShape=this.shadow.getElementById("label-shape"),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.labelReference=this.shadow.getElementById("label-reference"),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.labelAddReferenceFile=this.shadow.getElementById("label-add-reference-file"),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.labelLatitude=this.shadow.getElementById("label-lat"),this.labelLongitude=this.shadow.getElementById("label-lng"),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.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.labelImportUrl=this.shadow.getElementById("label-import-url"),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.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.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.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),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.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorObserverButton=this.shadow.getElementById("add-decor-observer"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),this.decorSelect=this.shadow.getElementById("decor"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSrcInput=this.shadow.getElementById("referenceSrc"),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.addReferenceUrlButton=this.shadow.getElementById("add-reference-url"),this.addReferenceFileInput=this.shadow.getElementById("add-reference-file"),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.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.referenceStreetSearchButton=this.shadow.getElementById("reference-street-search"),this.addTraceFileInput=this.shadow.getElementById("add-trace-file"),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.labelTrace=this.shadow.getElementById("label-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.referenceSrcInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.decorTitleInput=this.shadow.getElementById("decorTitle"),this.decorEastInput=this.shadow.getElementById("decorEast"),this.decorNorthInput=this.shadow.getElementById("decorNorth"),this.decorHeadingInput=this.shadow.getElementById("decorHeading"),this.decorColorInput=this.shadow.getElementById("decorColor"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorLightRigSelect=this.shadow.getElementById("decorLightRig"),this.lookAtDecorButton=this.shadow.getElementById("look-at-decor"),this.decorAltitudeInput=this.shadow.getElementById("decorAltitude"),this.labelDecorAltitude=this.shadow.getElementById("label-decor-altitude"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),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.decorWidthInput=this.shadow.getElementById("decorWidth"),this.decorLengthInput=this.shadow.getElementById("decorLength"),this.decorHeightInput=this.shadow.getElementById("decorHeight"),this.decorModelSelect=this.shadow.getElementById("decorModel"),this.modelPicker=new Oc(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.modelPicker.enhance(this.decorModelSelect,async i=>{const n=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),s=i!==""?i:n?ou[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 n=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId)?.model;return n?.url===void 0?void 0:{url:n.url,title:n.credit?.title??"",author:n.credit?.author??"",license:n.credit?.license??"",source:n.credit?.sourceUrl??""}},apply:i=>{this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.title,this.decorModelAuthorInput.value=i.author,this.decorModelLicenseInput.value=i.license,this.decorModelSourceInput.value=i.source,this.shownDecorEntry=void 0,this.decorModelSelect.value="",this.updateDecor()}}),this.decorModelAdvanced=this.shadow.getElementById("decor-model-advanced"),this.decorModelCatalogueNote=this.shadow.getElementById("decor-model-catalogue"),this.decorModelUrlInput=this.shadow.getElementById("decorModelUrl"),this.decorModelTitleInput=this.shadow.getElementById("decorModelTitle"),this.decorModelAuthorInput=this.shadow.getElementById("decorModelAuthor"),this.decorModelLicenseInput=this.shadow.getElementById("decorModelLicense"),this.decorModelSourceInput=this.shadow.getElementById("decorModelSource"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorObserverSideSelect=this.shadow.getElementById("decorObserverSide"),this.decorWindowInputs={front:this.shadow.getElementById("decorWindowFront"),behind:this.shadow.getElementById("decorWindowBehind"),left:this.shadow.getElementById("decorWindowLeft"),right:this.shadow.getElementById("decorWindowRight"),"front-left":this.shadow.getElementById("decorWindowFrontLeft"),"front-right":this.shadow.getElementById("decorWindowFrontRight"),"behind-left":this.shadow.getElementById("decorWindowBehindLeft"),"behind-right":this.shadow.getElementById("decorWindowBehindRight")},this.labelDecorSide={front:this.shadow.getElementById("label-decor-window-front"),behind:this.shadow.getElementById("label-decor-window-behind"),left:this.shadow.getElementById("label-decor-window-left"),right:this.shadow.getElementById("label-decor-window-right"),"front-left":this.shadow.getElementById("label-decor-window-front-left"),"front-right":this.shadow.getElementById("label-decor-window-front-right"),"behind-left":this.shadow.getElementById("label-decor-window-behind-left"),"behind-right":this.shadow.getElementById("label-decor-window-behind-right")},this.optionObserverSide={front:this.shadow.getElementById("option-observer-side-front"),behind:this.shadow.getElementById("option-observer-side-behind"),left:this.shadow.getElementById("option-observer-side-left"),right:this.shadow.getElementById("option-observer-side-right"),"front-left":this.shadow.getElementById("option-observer-side-front-left"),"front-right":this.shadow.getElementById("option-observer-side-front-right"),"behind-left":this.shadow.getElementById("option-observer-side-behind-left"),"behind-right":this.shadow.getElementById("option-observer-side-behind-right")},this.optionObserverSideNone=this.shadow.getElementById("option-observer-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelDecorTitle=this.shadow.getElementById("label-decor-title"),this.labelDecorEast=this.shadow.getElementById("label-decor-east"),this.labelDecorNorth=this.shadow.getElementById("label-decor-north"),this.labelDecorHeading=this.shadow.getElementById("label-decor-heading"),this.labelDecorColor=this.shadow.getElementById("label-decor-color"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.labelDecorWidth=this.shadow.getElementById("label-decor-width"),this.labelDecorLength=this.shadow.getElementById("label-decor-length"),this.labelDecorHeight=this.shadow.getElementById("label-decor-height"),this.labelDecorModel=this.shadow.getElementById("label-decor-model"),this.labelDecorModelAdvanced=this.shadow.getElementById("label-decor-model-advanced"),this.labelDecorModelUrl=this.shadow.getElementById("label-decor-model-url"),this.labelDecorModelTitle=this.shadow.getElementById("label-decor-model-title"),this.labelDecorModelAuthor=this.shadow.getElementById("label-decor-model-author"),this.labelDecorModelLicense=this.shadow.getElementById("label-decor-model-license"),this.labelDecorModelSource=this.shadow.getElementById("label-decor-model-source"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorObserverSide=this.shadow.getElementById("label-decor-observer-side"),this.labelDecorWindows=this.shadow.getElementById("label-decor-windows"),this.optionDecorBuilding=this.shadow.getElementById("option-decor-building"),this.optionDecorTree=this.shadow.getElementById("option-decor-tree"),this.optionDecorShrub=this.shadow.getElementById("option-decor-shrub"),this.optionDecorBridge=this.shadow.getElementById("option-decor-bridge"),this.optionDecorWire=this.shadow.getElementById("option-decor-wire"),this.optionDecorCrop=this.shadow.getElementById("option-decor-crop"),this.optionDecorTerrace=this.shadow.getElementById("option-decor-terrace"),this.optionDecorMound=this.shadow.getElementById("option-decor-mound"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorAircraft=this.shadow.getElementById("option-decor-aircraft"),this.optionDecorEntity=this.shadow.getElementById("option-decor-entity"),this.labelDecorLights=this.shadow.getElementById("label-decor-lights"),this.optionDecorObserver=this.shadow.getElementById("option-decor-observer"),this.ufoElement.canvasElement.addEventListener("pointerdown",i=>{this.focus({preventScroll:!0}),this.onPointerDown(i)}),this.ufoElement.canvasElement.addEventListener("pointermove",i=>this.onPointerMove(i)),this.ufoElement.canvasElement.addEventListener("contextmenu",i=>this.onContextMenu(i)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),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.addShapeButton.addEventListener("click",()=>this.addShape()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.importFileInput.addEventListener("change",()=>this.importFromFile()),this.importUrlButton.addEventListener("click",()=>this.importFromUrl()),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()}),this.lightPollutionInput.addEventListener("input",()=>{const i=this.ufoElement.sighting;i.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),i.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),i.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",i=>{const{seconds:n,text:s}=i.detail;this.ufoElement.sighting.event.durationText=s,this.ufoElement.durationSeconds=n,this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),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.addDecorObserverButton.addEventListener("click",()=>this.addDecor("observer")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value)),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const i of this.referenceFields)i.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.addReferenceUrlButton.addEventListener("click",()=>this.addReferenceFromAddress()),this.addReferenceFileInput.addEventListener("change",()=>void this.addReferenceFromFile()),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.referenceStreetSearchButton.addEventListener("click",()=>void this.searchStreetPictures()),this.addTraceFileInput.addEventListener("change",()=>void this.addTracesFromFile()),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",i=>this.onReferenceWheel(i),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",i=>this.onBodyWheel(i),{passive:!1});for(const i of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorAltitudeInput,this.decorHeadingInput,this.decorColorInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput])i.addEventListener("input",()=>this.updateDecor());this.decorObserverSideSelect.addEventListener("change",()=>this.updateDecor()),this.decorModelSelect.addEventListener("change",()=>this.updateDecorModelChoice()),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 i of[this.milestoneLabelInput,this.milestoneNoteInput])i.addEventListener("input",()=>this.updateMilestone());for(const i of Mo)this.decorWindowInputs[i].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.decorLightRigSelect.addEventListener("change",()=>this.updateDecorLightRig()),this.lookAtDecorButton.addEventListener("click",()=>this.lookAtDecor()),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(Uw,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(Fw,()=>{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);for(const i of xy)this.presetButtons[i].addEventListener("click",()=>this.setAppearance({presetId:i}));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 i of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])i.addEventListener("input",()=>this.updateObserver());for(const i of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])i.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",i=>{i.key==="Enter"&&(i.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 i=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const n=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(s=>[s.t,Ui.fovOf(this.ufoElement.sighting,s.t)]));this.retuneFieldOfView(i),this.retuneExposure(i),Ui.reproject(this.ufoElement.sighting,i,n),this.sceneElement.applyFrameFormat(),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 t=i=>this.shadow.querySelector(`${iu}[name="${i}"]`);this.startDate=t("obs-time"),this.endDate=t("obs-end-time"),this.startDate.messages=this.messages,this.endDate.messages=this.messages,this.startDate.addEventListener("datechange",i=>{const{time:n}=i.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=n})}),this.endDate.addEventListener("datechange",i=>{const{time:n}=i.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=n})});for(const i of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])i.addEventListener("input",()=>this.updateObserverMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const i of this.weatherFields){if(i===this.iceCrystalAlignmentInput){i.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}i.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const i of this.soundFields)i.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.skyDetailsButton=this.shadow.getElementById("sky-details"),this.clampedLines=[this.shadow.getElementById("weather-source"),this.shadow.getElementById("sky-candidates")],this.skyDetailsButton.addEventListener("click",()=>this.toggleSkyDetails()),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(i=>this.shadow.getElementById(i.getAttribute("aria-controls")));for(const i of this.groupTabs)i.addEventListener("click",()=>this.toggleGroup(i,!this.isGroupOpen(i)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const i of this.subgroupTabs)i.addEventListener("click",()=>this.openSubgroup(i));tn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new dl(this.messages,this.naming,this.said,this.tagNames,{messages:this.messages,locale:this.language}),this.paramSummary.addEventListener("click",i=>this.onParamSummaryClick(i)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(i=>i.id==="group-shape")],!0),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),this.updatePresetButtons(),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=Tx(this.shadow.getElementById("cloud-editor"),this.sceneElement,(i=!0)=>{i&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(i,n)=>{this.headingInput.value=String(this.rounded(i)),this.pitchInput.value=String(this.rounded(n)),this.updateObserver()},Fc(hs.preferencesFor(this),Hc)),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),hs.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()}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.endDrag(),this.ufoElement.sightingData=e,this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??fc,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(),this.syncWeatherOwnership(),this.markClean()}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&JSON.stringify(this.sightingData)!==this.baseline}get edited(){return this.touched}markClean(){this.baseline=JSON.stringify(this.sightingData),this.touched=!1}touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>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.text=t,this.syncHistoryButtons())}undo(){this.stepHistory(e=>e.undo())}redo(){this.stepHistory(e=>e.redo())}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),this.historyAnswering=!0,this.syncHistoryButtons())}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.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(),()=>{})}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=this.sightingData,t=`${e.observer?.id??"sighting"}-sighting.json`,i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,s.click(),URL.revokeObjectURL(n),this.markClean()}async importFromFile(){const e=this.importFileInput.files?.[0];if(e){if(this.holdLoad(()=>void this.loadFile(e))){this.importFileInput.value="";return}await this.loadFile(e)}}async loadFile(e){try{const t=await new Promise((n,s)=>{const r=new FileReader;r.onload=()=>n(r.result),r.onerror=()=>s(r.error),r.readAsText(e)}),i=JSON.parse(t);if(Es.isCase(i)){if(this.offerCase(i,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=i,this.resetHistory(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importUrlInput.value=""}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}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.importUrlInput.value.trim()){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){try{const t=await Nc.json(e);if(Es.isCase(t)){const n=new URL(e,location.href).href;if(this.offerCase(t,n)){this.importUrlInput.value=n;return}throw new Error("A case has no recording to edit here")}const i=t;this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.resetHistory(),this.importUrlInput.value=new URL(e,location.href).href,this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof xa))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";narrativeProvider=fh[0].create();get narrativeSourceId(){return mr(fh,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:Ri.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const n=i instanceof Bn&&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,o=Gs.stated(r);if(o.length>0){const l=this.ufoElement.sighting.provenance,c=Zf(this.ufoElement.sighting);this.sightingData=Gs.apply(c,hu.loadable(r),o),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.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:Ri.valueAt(Zf(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[C6[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 o=document.createElement(t==="stated"?"q":"span");o.textContent=n.rationale,s.append(r,o),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=mr(fh,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(),o=r===""?void 0:n.suspect(r);s.classList.toggle("invalid",o!==void 0),s.title=o?this.said.read(o)??"":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 l of i.choices??[]){const c=document.createElement("option");c.value=l.value,c.textContent=this.said.read(l.label)??l.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 o=e[i.id]??this.storedNarrativeSetting(i.id);return o!==void 0&&(r.value=o),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 Bn))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(Ri.NARRATIVE_KEY_STORAGE),localStorage.removeItem(Ri.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"?Ri.NARRATIVE_KEY_STORAGE:e==="workspace"?Ri.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} `),this.sourcePicker("place",d6,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",u6,e=>{this.weatherInference=new kf(e.create()),this.scheduleWeatherLookup()})),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("light-pollution",ly,e=>{this.lightPollutionProvider=e.create(),this.scheduleLightPollutionLookup()})),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",fh,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,Uf,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,gy,()=>this.applyTerrainSources()),this.labelledPicker("aircraft",this.messages.sourceAircraft,Mm,()=>this.applyAircraftSource()),this.labelledPicker("decor-model",this.messages.decorModel,Pd,()=>this.applyDecorModelSource()))}sourcePicker(e,t,i){const n=document.createDocumentFragment(),s=document.createElement("select");s.id=`${e}Source`;for(const l of t){const c=document.createElement("option");c.value=l.id,c.textContent=l.name,c.title=l.credit,s.appendChild(c)}s.value=this.chosenSourceId.get(e)??t[0].id;const r=document.createElement("a");r.className="source-credit",r.target="_blank",r.rel="noopener noreferrer";const o=()=>{const l=mr(t,s.value);s.title=l.credit,r.href=l.creditUrl,r.textContent=l.credit};return o(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),o(),i(mr(t,s.value))}),n.append(s,document.createTextNode(" "),r),n}labelledPicker(e,t,i,n){const s=document.createElement("label"),r=document.createElement("span");return r.textContent=t,s.append(r,this.sourcePicker(e,i,n)),s}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:mr(Uf,this.chosenSourceId.get("elevation")).create(),imagery:mr(gy,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(mr(Mm,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=mr(Pd,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.refreshDecorModelOptions(),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==="")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)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)<Ko&&Math.abs(t-this.namedCoordinates.lng)<Ko||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),My))}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)<Ko&&Math.abs(t-i.lng)<Ko||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),My))}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}i===this.placeSearchToken&&(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,this.updateObserver())}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,o=Math.max(0,r-(this.groundElevationM??0)),l=this.ufoElement.sighting.event,c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());l.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?Rt.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),g=this.numberOrUndefined(this.fNumberInput.value),m=this.filterSelect.value,v=Si.byId(c.getLatestPoseAt(h-1)?.filter),x=m===Si.NONE.id||m===""?v===Si.NONE?void 0:Si.NONE.id:m,y=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=y===u.exposureSeconds?void 0:y;const b=this.numberOrUndefined(this.focusDistanceInput.value),w=Math.abs(f-Rt.fieldOfViewDeg(u))>.01||g!==u.fNumber||b!==void 0||x!==void 0;e===void 0&&t===void 0&&i===void 0&&n===0&&s===0&&o===0&&!w?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:o,headingDeg:i,pitchDeg:n,rollDeg:s===0?void 0:s,fovDeg:f,fNumber:g,focusDistanceM:b,filter:x}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&Tl({...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.stringOrUndefined(this.observerTitleInput.value),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),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"};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??{},o=t===""?r:{...r,url:t},l=Object.keys(o).length>0?[o,...n]:n;e.sources=l.length>0?l: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());const e={...hi(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={...hi(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.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;this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const n of[this.referenceSelect,...this.referenceFields])n.disabled=!t,this.setRowVisible(n,t);this.setRowVisible(this.referenceUsePoseButton,t);for(const n of[this.referenceLandmarksSelect,this.addReferenceLandmarkButton,this.deleteReferenceLandmarkButton,this.referenceLandmarkLabelInput])this.setRowVisible(n,t);if(this.refreshLandmarkList(),this.setRowVisible(this.referenceAdoptPoseButton,t),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSrcInput.value=i?"":e.src,this.referenceSrcInput.disabled=i,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.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){if(this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const t=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>YC?this.messages.referenceEmbedded.replace("{kb}",String(t)):"";return}this.referenceStatus.textContent=this.sceneElement.referenceFailedToLoad(e.src)?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.startsWith("data:")?s.src:this.referenceSrcInput.value.trim(),o={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)||gd))},l=s.registration,c=o.headingDeg!==l.headingDeg||o.pitchDeg!==l.pitchDeg||o.rollDeg!==l.rollDeg||o.fovDeg!==l.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:o,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=at(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=at(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=at(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${n.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:$C,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:gd},from:this.observerPositionNow(),...i};n.references=[...n.references,o],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSrcInput.focus()}async addReferenceFromFile(){const e=this.addReferenceFileInput.files?.[0];if(!e)return;const t=await new Promise((i,n)=>{const s=new FileReader;s.onload=()=>i(s.result),s.onerror=()=>n(s.error),s.readAsDataURL(e)});this.addReferenceFileInput.value="",this.addReference(t,e.name.replace(/\.[^.]+$/,""))}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.sceneElement.referenceAspect(t.id);if(!(n!==void 0&&An.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.sceneElement.referenceAspect(t.id):void 0;if(!t||i===void 0)return;const n=8;for(const s of this.currentLandmarks()){const r=this.canvasPointOfDirection(An.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 o=this.canvasPointOfDirection(An.worldDirection(s.scene));if(o&&Math.hypot(o.x-e.x,o.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.sceneElement.referenceAspect(n.id):void 0;if(!n||s===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:An.aimOf(r)};const l=An.picturePointOf(r,n.registration,s);return l?{...o,picture:l}:o})),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)||gd,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.sceneElement.referenceAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const o=An.picturePointOf(i,t.registration,r);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,this.syncRegisterStatus(),this.ufoElement.refresh();return}const n=this.currentLandmarks(),s=this.nextLandmarkId(n);this.writeLandmarks([...n,{id:s,picture:this.pendingLandmark,scene:An.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.sceneElement.referenceAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),n=An.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 An.worldDirectionOf(e.picture,t.registration,i).angleTo(An.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.sceneElement.referenceAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[s,r]of t.entries()){const o=document.createElement("option");o.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,s)+l,this.referenceLandmarksSelect.appendChild(o)}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);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(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),n=i.findIndex(o=>o.id===e),s=this.currentReference(),r=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&n>=0){const o=s&&r!==void 0?` · ${this.landmarkResidualDeg(i[n],s,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[n],n)+o}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.sceneElement.referenceAspect(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(o=>this.canvasPointOfDirection(An.worldDirectionOf(o,n,i))),r=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(An.worldDirectionOf(o.picture,n,i)),scene:this.canvasPointOfDirection(An.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(An.worldDirectionOf(this.pendingLandmark,n,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(o=>o!==void 0)?s:void 0,r.filter(o=>o.picture!==void 0),this.landmarkHint())};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 o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",i],["rollDeg",n??0]];for(const[c,h]of l)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${c}`,{basis:"derived",rationale:o,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceStreetSearchButton.disabled=!e}async searchStreetPictures(){const e=at(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.referenceStreetSearchButton.disabled=!0;try{this.streetPictures=await this.streetPictures$.nearby(t,i,n)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.referenceStreetSearchButton.disabled=!1;return}this.referenceStreetSearchButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}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:gd}})}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;for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t,this.setRowVisible(i,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 addTracesFromFile(){const e=this.addTraceFileInput.files?.[0];if(!e)return;this.addTraceFileInput.value="";let t;try{const{KmlImport:c}=await je(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url),h=await new Promise((d,u)=>{const p=new FileReader;p.onload=()=>d(p.result),p.onerror=()=>u(p.error),p.readAsArrayBuffer(e)});t=await c.fromBytes(new Uint8Array(h))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(t.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const i=this.ufoElement.sighting,n=new Set(i.traces.map(c=>c.id));let s=1;const r=this.said.write(void 0,t.documentName??e.name,this.writingLanguage),o=t.traces.map(c=>{for(;n.has(`trace-${s}`);)s++;const h=`trace-${s}`;return n.add(h),{...c,id:h,title:c.title===void 0?void 0:this.said.write(void 0,c.title,this.writingLanguage),source:r}});i.traces=[...i.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const l=t.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",t.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",e.name)+l,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 p2){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(),v6)}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=Dm(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 kf(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup():(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(){this.weatherFromRecords&&(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),yy))}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(){if(!this.weatherFromRecords||this.ufoElement.sighting.weatherSource===void 0)return;const e=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||e===this.weatherTrackSpan||(this.weatherTrackSpan=e,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const o of this.weatherFields)o.disabled=t&&e!==void 0&&o!==this.iceCrystalAlignmentInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting);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;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=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""}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&&Yn(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.weatherLookupResult=void 0,this.weatherFromRecords=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=ly[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;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(),yy)}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 o=await n.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=o,o.status==="found"?(e.lightPollution=o.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${n.citation}, at ${o.lat.toFixed(4)}, ${o.lng.toFixed(4)}: ${Math.round(o.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:o.lightPollution}),this.lightPollutionInput.value=String(o.lightPollution),this.ufoElement.refresh()):o.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=Tl(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=cx(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;this.playPauseButton.textContent=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(Gn.opensPrecise(e.time)),this.endDate.setPrecise(Gn.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)>w6;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),y6))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Ko&&Math.abs(e.lng-i)<Ko}async applyGroundElevation(e,t){const i=++this.groundElevationToken,n=mr(Uf,this.chosenSourceId.get("elevation")),s=await new Mg(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),this.updateObserver()}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?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(at(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(){const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=e.observer?.title??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",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()??"",this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=hi(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??Od)),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):""),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.updatePresetButtons(),!(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=Cg(e,this.currentAppearance);return t?{...n,angle:t.angle,title:t.title,selected:t.selected}:n}toggleSkyDetails(){const e=this.skyDetailsButton.getAttribute("aria-expanded")!=="true";this.skyDetailsButton.setAttribute("aria-expanded",String(e)),this.skyDetailsButton.textContent=e?"▴":"▾",this.skyDetailsButton.title=e?this.messages.skyDetailsHide:this.messages.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title);for(const t of this.clampedLines)t.classList.toggle("clamped",!e)}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){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}this.syncCanvasMode(),this.refreshTimelineMarks(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>this.syncFileEditor(),()=>this.showFileNote(this.messages.importError))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await je(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-BUpjvTYf.js");return{SightingFileEditor:t}},__vite__mapDeps([6,7]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}showFileNote(e){this.fileNote.textContent=e??"",this.fileNote.hidden=e===void 0}fileText(){return JSON.stringify(this.sightingData,null,2)}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(){const e=this.fileEditor;if(!(e===void 0||!this.isGroupIdOpen("group-file")||e.focused)&&!this.historyAnswering){try{JSON.parse(e.text)}catch{return}e.text=this.fileText()}}onFileTextEdited(e){clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e){this.fileApplyTimer=void 0;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null||Array.isArray(t)||JSON.stringify(t)===JSON.stringify(this.sightingData))return;const i=this.ufoElement.currentTime;try{this.sightingData=t,this.ufoElement.currentTime=i,this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch{this.showFileNote(this.messages.importErrorMalformed)}}leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(),0))}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(l,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${l})`})),i=l=>t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(c=>!l||c.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(c=>c.t)),n=()=>t(this.messages.observerTrack,e.observerTrack.allKeyframes.map(l=>l.t)),s=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(l=>l.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(l=>l.t)),o=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 l of e.milestones)o.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(o,this.ufoElement.seekableDuration)}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-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":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",this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,n&&this.ufoElement.refresh(),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()}syncBodiesShown(){const i=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading?this.ufoElement.sighting.interpretation:void 0;this.sceneElement.compareAccount=i!==void 0,this.sceneElement.interpretation!==i&&(this.sceneElement.interpretation=i),this.accountViewSelect.value=i!==void 0?"bodies":"shapes",this.shadow.getElementById("account-view-row").hidden=this.isReading}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.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()),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)}static SUMMARY_GROUPS=["observation","observer","location","decor","temporal","weather","sound"];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(){const e=Ri.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 o=document.createElement("span");o.className="param-nest-label",o.textContent=n.group==="assessment"?this.messages.assessmentGroup:n.group==="summary"?this.messages.summaryGroup:Ri.tabLabel(this.groupTabs[this.summaryPanelIndex(n.group)]),r.append(o),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.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),Yy.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 e==="phenomenon"?this.panelIndex("shape"):Ri.SUMMARY_GROUPS.indexOf(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 Lx(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.renderParamSummary())}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=Ri.QUESTION_FIELDS[s];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[s,r]of Object.entries(Ri.QUESTION_FIELDS))for(const o of Ri.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",c),(c||l.title===this.messages.questionUnanswered)&&(l.title=c?this.messages.questionUnanswered:"")}const i=new Map;let n;for(const[s,r]of Object.entries(Ri.QUESTION_FIELDS))for(const o of r.fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=l.classList.contains("missing-required");!c&&!l.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),o=i.get(r)??0,l=r===n,c=Ri.badgeOn(s);c.hidden=o===0,c.textContent=String(o),c.classList.toggle("optional",!l),s.title=o===0?"":l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o))}}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(o=>o.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 o=this.subgroupTabs.find(l=>l.getAttribute("aria-controls")==="shape-bodies");o&&this.openSubgroup(o),this.loadBodyEditor().then(l=>l.show(s.slice(5)));return}if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorSelect.focus();return}const r=this.shadow.getElementById(s);r===null||!n.contains(r)||(this.revealSubgroupOf(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.syncDecorLitFromTimeline(),this.syncDecorPlacementFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),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()}updateAppearanceFieldsDisabledState(){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.sourceSelect,...Object.values(this.presetButtons)])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:I6(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.updatePresetButtons(),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.refreshApparentSize())}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,lt.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,lt.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(lt.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(lt.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),o=n.bounds.height*(n.bounds.width===0?1:r/n.bounds.width),l={x:n.bounds.x+(n.bounds.width-r)/2,y:n.bounds.y+(n.bounds.height-o)/2,width:r,height:o},c=s.ofBounds(l),h=n.kind==="oval"?{...n,bounds:l,angular:c}:{...n,bounds:l,angular:c,points:this.scalePoints(n,l)};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={[Si.NONE.id]:this.messages.filterNone,[Si.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[Si.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=this.filterSelect.value||Si.NONE.id;this.filterSelect.replaceChildren();for(const i of Si.ALL){const n=document.createElement("option");n.value=i.id,n.textContent=e[i.id]??i.name,this.filterSelect.appendChild(n)}this.filterSelect.value=t}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=Rt.availableAt(t),n=e.instrument,s=i.includes(n)?i:[...i,n],r=this.instrumentSelect.value||n.id;this.instrumentSelect.replaceChildren();for(const o of s){const l=document.createElement("option");l.value=o.id;const c=this.naming.instrument(o);l.textContent=i.includes(o)?c:this.messages.instrumentOutOfPeriod.replace("{name}",c),this.instrumentSelect.appendChild(l)}this.instrumentSelect.value=s.some(o=>o.id===r)?r:n.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Ri.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=at(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??Rt.fieldOfViewDeg(t),r=n?Rt.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),tn.fit(this.focalLengthInput.parentElement??this.shadow),this.focalFovOutput.textContent=n&&s!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(s,s<10?1:0)):"";const o=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),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 l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":Ri.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0),this.exposureInput.disabled=t.exposureRangeSeconds===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=Si.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Rt.fieldOfViewDeg(e),n=Rt.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>E6||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 at(e,this.ufoElement.currentTime)?.fovDeg??Rt.fieldOfViewDeg(e.instrument)}currentProjection(){return Ts.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=lt.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=at(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?Rt.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,o=n?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*Xf*e/l*i.heightMm,h=r*r/(o*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),o=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))+o+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=(g,m)=>Number(g.toFixed(m)),s=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??b6,o=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),l=o!==void 0&&o<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(lt.sizeMAt(c,h),2),lengthM:n(lt.sizeMAt(c,h),2),heightM:n(lt.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},f={t,...p,distanceM:c,...l?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=je(async()=>{const{BodyEditor:e}=await import("./BodyEditor-CiPDf3PA.js");return{BodyEditor:e}},__vite__mapDeps([8,9]),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,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,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}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:lt.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=Ts.of(i.instrument,lt.CANVAS_HEIGHT_PX,Ui.fovOf(i,e));i.timeline.addKeyframe(e,t.map(s=>{const r=Ui.aimOf(i,e,s.shape.bounds),o=n.ofBounds(s.shape.bounds);return{...s,shape:r?{...s.shape,aim:r,angular:o}:{...s.shape,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.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;if(e.sourceIds.length>0||this.currentSourceId===void 0){const t=new Set([...e.sourceIds,this.currentSourceId]);let i=t.size+1;for(;t.has(`ufo-${i}`);)i++;this.currentSourceId=`ufo-${i}`}this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}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]??fc,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.decorKindSelect.querySelector(`option[value="${e.kind}"]`)?.textContent??e.kind} ${n}`}addDecor(e=this.decorKindSelect.value){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==="building"?{floors:hl}:{},windows:Xy(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(n.id,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.syncDecorModelFields(this.ufoElement.sighting.decor.find(s=>s.id===e)),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*zf,t=Math.round(e/A6*1e3);return{lights:Md.byId("airliner")?.create(),track:[{t:0,eastM:-zf,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:zf,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.kind===e).length;return`${this.decorKindSelect.querySelector(`option[value="${e}"]`)?.textContent??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.decorSelect.value=e,this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,i=this.decorObserverSideSelect.value;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=eo(n.kind)&&i!==""?i:void 0,r=Number(this.decorEastInput.value),o=Number(this.decorNorthInput.value),l=Number(this.decorAltitudeInput.value),c=n.track??(l!==0?[]:void 0);if(c){const h=this.ufoElement.currentTime,d={t:h,eastM:r,northM:o,altitudeM:l,headingDeg:t},u=c.filter(p=>p.t!==h);return{...n,title:this.said.write(n.title,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),track:[...u,d].sort((p,f)=>p.t-f.t),sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}return{...n,title:this.said.write(void 0,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),eastM:r,northM:o,headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(n=>n.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}syncDecorSizeFields(e){const t=e?$t.naturalSize(e.kind,e.floors):void 0,i=[[this.decorWidthInput,e?.sizeM?.widthM,t?.widthM],[this.decorLengthInput,e?.sizeM?.lengthM,t?.lengthM],[this.decorHeightInput,e?.sizeM?.heightM,t?.heightM]];for(const[n,s,r]of i)n.value=s===void 0?"":String(this.roundedMeters(s)),n.placeholder=r===void 0?"":String(this.roundedMeters(r))}syncDecorModelFields(e){this.refreshDecorModelOptions(e),this.decorModelSelect.value=e?.model?.id??"",this.decorModelUrlInput.value=e?.model?.url??"",this.decorModelTitleInput.value=e?.model?.credit?.title??"",this.decorModelAuthorInput.value=e?.model?.credit?.author??"",this.decorModelLicenseInput.value=e?.model?.credit?.license??"",this.decorModelSourceInput.value=e?.model?.credit?.sourceUrl??"",this.decorModelAdvanced.open=e?.model?.url!==void 0,this.showDecorCatalogueModel(e)}async showDecorCatalogueModel(e){const t=e?.model?.url===void 0?e?.model?.id:void 0,i=t===void 0?void 0:await this.decorModelProvider.entry(t).catch(()=>{});e?.id===this.currentDecorId&&(this.shownDecorEntry=i,this.decorModelCatalogueNote.hidden=i===void 0,i&&(this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.credit.title,this.decorModelAuthorInput.value=i.credit.author??"",this.decorModelLicenseInput.value=i.credit.license,this.decorModelSourceInput.value=i.credit.sourceUrl??"",this.syncDecorVisibility()))}shownDecorEntry;modelPicker;async refreshDecorModelOptions(e){const t=e??this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),i=t?await this.decorModelProvider.entries(t.kind).catch(()=>[]):[],n=t?.model?.id??"",s=document.createElement("option");s.value="",s.textContent=t&&ou[t.kind]?this.messages.decorModelDefault:this.messages.decorModelNone,this.decorModelSelect.replaceChildren(s,...i.map(r=>{const o=document.createElement("option");return o.value=r.id,o.textContent=r.name,o.title=`${r.credit.title}${r.credit.author?` — ${r.credit.author}`:""} (${r.credit.license})`,o})),this.decorModelSelect.value=n}updateDecorModelChoice(){const e=this.decorModelSelect.value;(async()=>{const t=e?await this.decorModelProvider.entry(e).catch(()=>{}):void 0,i=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),n=this.shownDecorEntry;this.shownDecorEntry=t,this.decorModelCatalogueNote.hidden=t===void 0,this.decorModelUrlInput.value=t?.url??"",this.decorModelTitleInput.value=t?.credit.title??"",this.decorModelAuthorInput.value=t?.credit.author??"",this.decorModelLicenseInput.value=t?.credit.license??"",this.decorModelSourceInput.value=t?.credit.sourceUrl??"";const s=i?.sizeM!==void 0&&n?.sizeM!==void 0&&i.sizeM.widthM===n.sizeM.widthM&&i.sizeM.lengthM===n.sizeM.lengthM&&i.sizeM.heightM===n.sizeM.heightM;if(t?.sizeM&&i&&(!i.sizeM||s)){const r=[[this.decorWidthInput,t.sizeM.widthM],[this.decorLengthInput,t.sizeM.lengthM],[this.decorHeightInput,t.sizeM.heightM]];for(const[o,l]of r)l!==void 0&&(o.value=String(this.roundedMeters(l)))}this.updateDecor()})()}roundedMeters(e){return Math.round(e*100)/100}positiveMeters(e){const t=Number(e);return e.trim()===""||!Number.isFinite(t)||t<=0?void 0:t}statedDecorColor(e){const t=this.decorColorInput.value;return t==="#808080"&&e.color===void 0?void 0:t}statedDecorSize(){const e=this.positiveMeters(this.decorWidthInput.value),t=this.positiveMeters(this.decorLengthInput.value),i=this.positiveMeters(this.decorHeightInput.value);return e===void 0&&t===void 0&&i===void 0?void 0:{widthM:e,lengthM:t,heightM:i}}statedDecorModel(){const e=this.stringOrUndefined(this.decorModelUrlInput.value),t=this.shownDecorEntry;if(t&&e===t.url&&this.stringOrUndefined(this.decorModelTitleInput.value)===t.credit.title&&this.stringOrUndefined(this.decorModelAuthorInput.value)===t.credit.author&&this.stringOrUndefined(this.decorModelLicenseInput.value)===t.credit.license&&this.stringOrUndefined(this.decorModelSourceInput.value)===t.credit.sourceUrl)return{id:t.id};if(e){const n=this.stringOrUndefined(this.decorModelTitleInput.value),s=this.stringOrUndefined(this.decorModelLicenseInput.value);return{url:e,credit:n!==void 0&&s!==void 0?{title:n,license:s,author:this.stringOrUndefined(this.decorModelAuthorInput.value),sourceUrl:this.stringOrUndefined(this.decorModelSourceInput.value)}:void 0}}const i=this.stringOrUndefined(this.decorModelSelect.value);return i===void 0?void 0:{id:i}}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=io([...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=io(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;for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.milestoneLabelInput,this.milestoneNoteInput,this.deleteMilestoneButton])i.disabled=!t,this.setRowVisible(i,t);this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}updateDecorTitleValidity(){const e=this.currentDecorId!==void 0&&this.decorTitleInput.value==="";this.decorTitleInput.classList.toggle("invalid",e),this.decorTitleInput.setAttribute("aria-invalid",String(e))}updateDecorWindows(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.map(t=>{if(t.id!==this.currentDecorId)return t;const i={};for(const n of Mo){const s=this.decorWindowInputs[n];if(s.value==="")continue;const r=Yf(t.kind,n)?0:$f,o=Math.max(r,Math.min(100,Number(s.value)));i[n]=o,String(o)!==s.value&&(s.value=String(o))}return{...t,windows:i}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,i=this.decorLitInput.checked;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=[...(n.litKeyframes??[]).filter(r=>r.t!==t),{t,lit:i}].sort((r,o)=>r.t-o.t);return{...n,litKeyframes:s}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.decorLabel(t),this.decorSelect.appendChild(i)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const i of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelSelect,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorObserverSideSelect,this.decorLightRigSelect,this.decorAltitudeInput,this.lookAtDecorButton])i.disabled=!t;this.decorTitleInput.value=this.said.read(e?.title)??"",this.decorColorInput.value=e?.color??"#808080",this.showDecorPlacement(e),this.decorLitInput.checked=e?cu(e,this.ufoElement.currentTime):!1,this.refreshDecorLightRigOptions(e),this.decorSightingUrlInput.value=e?.sightingUrl??"",this.syncDecorSizeFields(e),this.syncDecorModelFields(e),this.decorFloorsInput.value=String(e?.floors??hl),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorObserverSideSelect.value=e?.observerSide??"";for(const i of Mo){const n=e?.windows?.[i];this.decorWindowInputs[i].value=n===void 0?"":String(n)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(h=>h.id===this.currentDecorId),t=e!==void 0,i=e?.kind;this.setRowVisible(this.decorSelect,t),this.setRowVisible(this.deleteDecorButton,t),this.setRowVisible(this.decorTitleInput,t),this.setRowVisible(this.decorEastInput,t),this.setRowVisible(this.decorNorthInput,t),this.setRowVisible(this.decorAltitudeInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorWidthInput,t),this.setRowVisible(this.decorLengthInput,t),this.setRowVisible(this.decorHeightInput,t);const n=e?Hu.of(e,this.shownDecorEntry?.id===e.model?.id?this.shownDecorEntry?.parameters:void 0):void 0;this.setRowVisible(this.decorColorInput,n?.color===!0),this.setRowVisible(this.decorModelSelect,t),this.decorModelAdvanced.hidden=!0,this.setRowVisible(this.decorLitInput,n?.lit===!0),this.setRowVisible(this.decorLightRigSelect,n?.lights===!0);const s=n?.windows===!0;this.setRowVisible(this.labelDecorWindows,s);const r=i!==void 0?Rm(i):[];for(const h of Mo)this.decorWindowInputs[h].disabled=!t,this.decorWindowInputs[h].min=String(i!==void 0&&Yf(i,h)?0:$f),this.setRowVisible(this.decorWindowInputs[h],s&&r.includes(h));const o=n?.observerSide===!0;this.setRowVisible(this.decorObserverSideSelect,o);const l=i!==void 0?kx(i):[];for(const h of Mo)this.optionObserverSide[h].hidden=!l.includes(h);const c=n?.floors===!0;this.setRowVisible(this.decorFloorsInput,c),this.setRowVisible(this.decorOccupiedFloorInput,c),this.decorOccupiedFloorInput.max=String(e?.floors??hl)}showDecorPlacement(e){const t=e?tr(e,this.ufoElement.currentTime):void 0,i=[[this.decorEastInput,t?.eastM??0],[this.decorNorthInput,t?.northM??0],[this.decorAltitudeInput,t?.altitudeM??0],[this.decorHeadingInput,t?.headingDeg??0]];for(const[n,s]of i)this.shadow.activeElement!==n&&(n.value=String(this.rounded(s)))}syncDecorPlacementFromTimeline(){this.ufoElement.playbackState!=="playing"&&this.showDecorPlacement(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++);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),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;skyCandidatesKey;static reentryArchive=new Rn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Nu;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new qn(["en"]);tagNames=new Kf({});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?Yn(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,hi(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!n||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.hidden=!0,this.showCometButton.hidden=!0,this.showNovaButton.hidden=!0,this.showSatelliteButton.hidden=!0,this.showFireballButton.hidden=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown);return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=[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(l=>l!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return nn.gainFor(e.instrument,{fNumber:at(e,0)?.fNumber,fieldOfViewDeg:Ui.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Ni("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=sa(i,n,s),o=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<M6)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",o(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",o(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",o(Math.abs(n))).replace("{eye}",o(sa(i,0,s)));return r<=Pc?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Pc))}showerClause(e,t){const i=oi.observedRatePerHour(oi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=El.activeAt(e);if(n.length===0)return this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyNothingActive.replace("{sporadic}",i);const s=n.map(r=>{const o=El.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:El.observedRatePerHour(r.zhr,o.altitudeDeg,r.shower.populationIndex)}}).sort((r,o)=>o.rate-r.rate)[0];return s.rate<=0?(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(s.entry.shower))):(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),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=kd.brightestAt(e,t);if(!i||i.magnitude>Fl){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=i.position.altitudeDeg<=0,this.cometText(i)}novaClause(e,t){const i=Fu.brightestAt(e,t);if(!i||i.magnitude>Fl){this.showNovaButton.hidden=!0;return}return this.showNovaButton.hidden=i.position.altitudeDeg<=0,this.novaText(i)}eclipseClause(e,t){const i=bi.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const n=Ni("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),o=Math.round(i.totality.seconds%60);return s(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${o} 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=Ni("Moon",e,t);if(i.altitudeDeg<=0||Ca(e).illuminatedFraction<.97)return;const n=[],s=cn.distanceKm(e,t),r=cn.relativeToMean(cn.radiusAtKm(s)),o=s<=cn.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:s>=cn.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return o&&n.push(o.replace("{distance}",(Math.round(s/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(cn.radiusAtKm(s)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),zu.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=Ms.visibilityAt(e,t),n=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(n!==void 0)return n;if(this.showSatelliteButton.hidden=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=sa(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),o=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}",o);const l=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",l).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",o):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,Ri.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=Ms.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(o.length===0)return;const l=o.slice(0,3).map(c=>this.reentryText(c));return o.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",l.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 o=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",o)}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(h=>h.status!=="covered"))return this.showSatelliteButton.hidden=!0,t.coverage.some(h=>h.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses(),n=i.filter(h=>this.passTimelineMs(h)<=this.ufoElement.seekableDuration);if(this.showSatelliteButton.hidden=n.length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const r=i[0].peak,l=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",r.object.name).replace("{magnitude}",r.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(r.altitudeDeg))).replace("{bearing}",this.naming.towards(r.azimuthDeg)).replace("{time}",this.observerClock(r.date)),c=this.starlinkTrain(i);return c?`${l}, ${c}`:l}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=Ni("Sun",i.peak.date,t);return n<=sa(s.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,n)=>i.peak.magnitude-n.peak.magnitude)}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:o,launch:l}=r.peak.object;o!=="starlink"||!l||(r.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[i,n]=[...t.entries()].sort((r,o)=>o[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=at(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=Yn(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.visibleSatellitePasses().filter(n=>this.passTimelineMs(n)<=this.ufoElement.seekableDuration);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=>os.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=os.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,n)=>i.magnitude-n.magnitude)}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.hidden=!i.some(r=>this.fireballTimelineMs(r,e)<=this.ufoElement.seekableDuration),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=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.strikingFireballs(n,this.observerAtStart()).filter(o=>this.fireballTimelineMs(o,n)<=this.ufoElement.seekableDuration);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=hi(this.ufoElement.sighting,0),n=Ni("Sun",e,t),s=Ni("Moon",e,t),r=bt.deckLitUntilDeg(bt.DECK_HEIGHT_M),o=n.altitudeDeg>-r,l=o?n:s;if(l.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(bt.strength(c,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(bt.formsAt(l.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??Od;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=hi(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Ni("Sun",e,t),s=Ni("Moon",e,t),r=n.altitudeDeg>0,o=r?n:s;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(rn.strength(i.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=rn.formsAt(o.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(rn.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(Ca(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Ni("Sun",e,t);if(i.altitudeDeg>D6)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<=_t.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),o=Ni("Moon",e,t),l=n.darkestSkyMagPerArcsec2<R6,c=this.ufoElement.sighting.lightPollution,h=ce.scatteringAt(90-o.altitudeDeg)*ce.moonOutput(ce.phaseAngleOf(Ca(e).illuminatedFraction),o.altitudeDeg)*ce.scatteredFraction(90),d=ce.artificialZenithNanolamberts(c)>h;if(l&&o.altitudeDeg>0&&!d){const p=Math.round(Ca(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=ce.artificialZenithNanolamberts(c)>ce.twilightExcessNanolamberts(i.altitudeDeg);return l&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):l?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Ni("Sun",e,t),n=Ni("Moon",e,t);return ce.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(Ca(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new _t;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<kd.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=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=kd.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(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=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Fu.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(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(l=>l.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:n}=tr(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,o=Math.atan2(n-_6,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}refreshDecorLightRigOptions(e){const t=e?Md.forKind(e.kind):[],i=document.createElement("option");i.value="",i.textContent=this.messages.decorLightsNone,this.decorLightRigSelect.replaceChildren(i,...t.map(s=>{const r=document.createElement("option");return r.value=s.id,r.textContent=this.naming.lightRig(s),r}));const n=e?.lights?.map(s=>s.id).join()??"";this.decorLightRigSelect.value=t.find(s=>s.create().map(r=>r.id).join()===n)?.id??""}updateDecorLightRig(){const e=this.ufoElement.sighting,t=e.decor.find(n=>n.id===this.currentDecorId);if(!t)return;const i=Md.byId(this.decorLightRigSelect.value);e.decor=e.decor.map(n=>n.id===t.id?{...n,lights:i?i.create():void 0}:n),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorLitFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.shadow.activeElement===this.decorLitInput)return;const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);e&&(this.decorLitInput.checked=cu(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of xy)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return Cg(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-qo.width/2,y:e.height/2-qo.height/2,width:qo.width,height:qo.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 UC(this.ufoElement.sighting.timeline,new BC(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){this.recordButton.textContent=e?"⏹":"⏺";const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t)}async loadLocaleMessages(){const e=++this.localeToken,t=hs.preferencesFor(this);this.preferences=t;const i=Fc(t,Hc),n=this.narrativeProvider.localize?.(i),[s,r,o]=i==="en"?[Il,{},void 0]:await Promise.all([Hy(i),xx(i),Gy(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.naming=new Nu(o),this.said=new qn(t),this.tagNames=new Kf(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new dl(s,this.naming,this.said,this.tagNames,{messages:s,locale:this.language}),this.refreshParamSummary()),l?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===fc&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.presetButtons.oval.textContent=e.oval,this.presetButtons.polygon.textContent=e.polygon,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.labelShape.textContent=e.shape,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.labelSizeLock.textContent=e.sizeLock;for(const[n,s]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(n).textContent=s;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.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.labelImportFile.textContent=e.importFile,this.labelImportUrl.textContent=e.importUrl,this.importUrlInput.placeholder=e.importUrlPlaceholder,this.importUrlButton.textContent=e.importButton,this.labelObserverAge.textContent=e.observerAge,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,this.labelAccountUrl.textContent=e.accountUrl,this.labelAccountFollowedUp.textContent=e.accountFollowedUp;for(const[n,s]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 r=this.shadow.getElementById(n);r&&(r.textContent=s)}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.labelLatitude.textContent=e.latitude,this.labelLongitude.textContent=e.longitude,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.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.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorGroup.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorShrub.textContent=e.decorShrub,this.optionDecorBridge.textContent=e.decorBridge,this.optionDecorWire.textContent=e.decorWire,this.optionDecorCrop.textContent=e.decorCrop,this.optionDecorTerrace.textContent=e.decorTerrace,this.optionDecorMound.textContent=e.decorMound,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorAircraft.textContent=e.decorAircraft,this.optionDecorEntity.textContent=e.decorEntity,this.labelDecorLights.textContent=e.decorLights,this.labelDecorAltitude.textContent=e.decorAltitude,this.showMeteorButton.title=e.showMeteor,this.showMeteorButton.setAttribute("aria-label",e.showMeteor),this.showCometButton.title=e.showComet,this.showCometButton.setAttribute("aria-label",e.showComet),this.showNovaButton.title=e.showNova,this.showNovaButton.setAttribute("aria-label",e.showNova),this.showSatelliteButton.title=e.showSatellite,this.showSatelliteButton.setAttribute("aria-label",e.showSatellite),this.showFireballButton.title=e.showFireball,this.showFireballButton.setAttribute("aria-label",e.showFireball),this.lookAtDecorButton.title=e.lookAtDecor,this.lookAtDecorButton.setAttribute("aria-label",e.lookAtDecor),this.optionDecorObserver.textContent=e.decorObserver,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.deleteDecorButton.title=e.deleteDecor,this.deleteDecorButton.setAttribute("aria-label",e.deleteDecor),this.labelDecorTitle.textContent=e.decorTitle,this.labelDecorEast.textContent=e.decorEast,this.labelDecorNorth.textContent=e.decorNorth,this.labelDecorHeading.textContent=e.decorHeading,this.labelDecorColor.textContent=e.decorColor,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorObserverButton.textContent=e.addObserver,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote;for(const[n,s]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=s,n.setAttribute("aria-label",s);this.labelDecorWidth.textContent=e.decorWidth,this.labelDecorLength.textContent=e.decorLength,this.labelDecorHeight.textContent=e.decorHeight,this.labelDecorModel.textContent=e.decorModel,this.labelDecorModelAdvanced.textContent=e.decorModelAdvanced,this.decorModelCatalogueNote.textContent=e.decorModelFromCatalogue,this.labelDecorModelUrl.textContent=e.decorModelUrl,this.labelDecorModelTitle.textContent=e.decorModelTitle,this.labelDecorModelAuthor.textContent=e.decorModelAuthor,this.labelDecorModelLicense.textContent=e.decorModelLicense,this.labelDecorModelSource.textContent=e.decorModelSource,this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorObserverSide.textContent=e.decorObserverSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionObserverSideNone.textContent=e.decorObserverSideNone;const t={front:e.decorSideFront,behind:e.decorSideBehind,left:e.decorSideLeft,right:e.decorSideRight,"front-left":e.decorSideFrontLeft,"front-right":e.decorSideFrontRight,"behind-left":e.decorSideBehindLeft,"behind-right":e.decorSideBehindRight};for(const n of Mo)this.labelDecorSide[n].textContent=t[n],this.optionObserverSide[n].textContent=t[n];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.bodyEditor?.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.observerGroup,this.labelWeatherGroup.textContent=e.weather,this.startDate.messages=e,this.endDate.messages=e,this.paramSummaryBuilder=new dl(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),this.refreshParamSummary();const i=this.skyDetailsButton.getAttribute("aria-expanded")==="true";this.skyDetailsButton.title=i?e.skyDetailsHide:e.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,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.labelReference.textContent=e.reference,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSrcInput.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.addReferenceUrlButton.textContent=e.addReferenceUrl,this.labelAddReferenceFile.textContent=e.addReferenceFile,this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.textContent=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.referenceStreetSearchButton.textContent=e.referenceStreetSearch,this.labelTraceImport.textContent=e.traceImport,this.labelTrace.textContent=e.trace,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[n,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}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;!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)&&this.beginCameraDrag(t);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,o=this.ufoElement.playbackState==="playing",l=i==="shape";if(l)if(this.selectedSourceIds.size>1){const d=new dp(this.selectedMembers()),u=Tt.hitTestHandle({bounds:d.bounds(),angle:0},t);if(u==="rotate"){if(o)return;this.dragState={kind:"group-rotate",group:d,startPointer:t},this.startDragListening();return}if(u){if(o)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"?Tt.hitTestVertex(d,t):void 0;if(d?.kind==="polygon"&&u!==void 0){if(o)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:d,vertexIndex:u},this.startDragListening();return}const p=d&&Tt.hitTestHandle(d,t);if(d&&p){if(o)return;this.beginDrag(p==="rotate"?"rotate":"resize",this.currentSourceId,d,t,p);return}}const c=this.ufoElement.shapeAt(t.x,t.y,vy);if(!c){const d=n==="ground"?this.pickDecorAt(e):void 0;if(d!==void 0){o?(this.selectDecor(d),this.revealDecorPanel()):this.beginCameraDrag(t,d);return}o||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(c.sourceId):this.selectedSourceIds.has(c.sourceId)||this.selectUnit(c.sourceId),o||!l)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()}revealDecorPanel(){const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-decor");e&&this.toggleGroup(e,!0)}revealShapePanel(){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.refreshSourceList(),this.onSelectionOrTimeChanged())}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,o)=>s.indexOf(r)-s.indexOf(o)).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,o=s?.kind==="polygon"&&Tt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,vy);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),c=l?this.ufoElement.sighting.decor.find(h=>h.id===l):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)),o=n.length>0&&i.slice(0,n.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||o,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,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?Tt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=Wy;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];if(t.length===0){const i=document.createElement("span");i.className="submenu-empty",i.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(i)}for(const i of t){const n=document.createElement("label"),s=document.createElement("input");s.type="checkbox",s.checked=e.occludesSourceIds?.includes(i)??!1,s.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,i,s.checked)),n.appendChild(s),n.appendChild(document.createTextNode(this.shapeLabel(i))),this.contextMasksSubmenu.appendChild(n)}}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(o=>o!==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=Tt.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=Tt.hitTestVertex(i,e);if(n===void 0)return;const s=Tt.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(by,(e.maxX-e.minX)/2*t.width),n=Math.max(by,(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=Tt.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:o}=t,l=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=o==="e"||o==="w",h=o==="n"||o==="s",d=c?l(i.x-n.x,s.x-n.x):h?l(i.y-n.y,s.y-n.y):l(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:Bf};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.editableDecor()===void 0?void 0:{sizeM:{widthM:this.decorSizeFieldM(this.decorWidthInput),lengthM:this.decorSizeFieldM(this.decorLengthInput),heightM:this.decorSizeFieldM(this.decorHeightInput)},attitude:{headingDeg:this.numberOrUndefined(this.decorHeadingInput.value)??0,pitchDeg:0,rollDeg:0}},resize:e=>{this.decorWidthInput.value=String(this.roundedMeters(e.widthM)),this.decorLengthInput.value=String(this.roundedMeters(e.lengthM)),this.decorHeightInput.value=String(this.roundedMeters(e.heightM)),this.updateDecor()},turnTo:e=>{this.decorHeadingInput.value=String(this.rounded((e.headingDeg%360+360)%360)),this.updateDecor()},rotateDegPerPx:x6};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)};decorSizeFieldM(e){return this.positiveMeters(e.value)??this.positiveMeters(e.placeholder)??1}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(o=>o.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.grabsDecor(e,t,n))return!1;const s=this.ndcOf(e),r=s?this.sceneElement.decorGrabHeightAt?.(n.id,s.x,s.y)??0:0,o=s&&this.sceneElement.decorGroundPointAt(n.id,s.x,s.y,r);return!s||!o?!1:(this.dragState={kind:"decor-move",id:n.id,startGround:o,grabHeightM:r,axis:i,startAltitudeM:Number(this.decorAltitudeInput.value)||0,startNdcY:s.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(n.id)??0,startEastM:Number(this.decorEastInput.value)||0,startNorthM:Number(this.decorNorthInput.value)||0},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"||(n&&(t.axis==="ground"||t.axis==="east")&&(this.decorEastInput.value=String(this.roundedMeters(t.startEastM+n.x-t.startGround.x))),n&&(t.axis==="ground"||t.axis==="north")&&(this.decorNorthInput.value=String(this.roundedMeters(t.startNorthM-(n.z-t.startGround.z)))),t.axis==="up"&&(this.decorAltitudeInput.value=String(this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))),this.updateDecor())}beginCameraDrag(e,t){const i=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,moved:!1,startPointer:e,startHeadingDeg:i?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:i?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:i},i||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&eo(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&eo(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,o=t.y-s.y,l=n.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+o}}}));this.commitShapes(i,l)}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,o=Tt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}else{const{kind:n,sourceId:s,original:r,handle:o}=this.dragState,l=n==="resize"?Tt.resizeShape(r,o,t):Tt.rotateShape(r,t);this.commitShapes(i,[{sourceId:s,shape:l}])}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)<S6)return;this.cameraDragState.moved=!0}const o=n+(t.x-i.x)*Bf,l=Math.max(-90,Math.min(90,s-(t.y-i.y)*Bf));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),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))}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ta,i.width-Wr);break;case"ArrowRight":i.width+=Wr;break;case"ArrowUp":i.height=Math.max(ta,i.height-Wr);break;case"ArrowDown":i.height+=Wr;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Wr;break;case"ArrowRight":i.x+=Wr;break;case"ArrowUp":i.y-=Wr;break;case"ArrowDown":i.y+=Wr;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 dp(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 l=r?this.bodyCanvasBounds():void 0,c=l&&Tt.hitTestHandle({bounds:l,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 l=this.decorCanvasBounds(),c=l&&Tt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.editableDecor();if(h&&this.grabsDecor(e,t,h))return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const l=Tt.hitTestHandle({bounds:new dp(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=n.getInterpolatedShapeAt(s,this.currentSourceId);if(l?.kind==="polygon"&&Tt.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&Tt.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return n.hitTest(s,t.x,t.y)?r&&o?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${Tt.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(Ay(this.buildPrototype({x:0,y:0,width:qo.width,height:qo.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 C6={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},Sy="rr0-sighting-editor",Ey="rr0-ufo-recorder";class P6 extends Ri{}function Hw(){Fy(),GC(),qu(),customElements.get(Sy)||customElements.define(Sy,Ri),customElements.get(Ey)||customElements.define(Ey,P6)}const wm={recording:"Recording",untitledReading:"Reading {n}",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 observation",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"A JSON file",sourceUrl:"An address",observerField:"Observer",fileField:"File",urlField:"Address",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",caseTitle:"Title",caseTime:"When",recordingsHeading:"Observations",add:"Add",addHint:"Add",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"},L6=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:wm},Symbol.toStringTag,{value:"Module"})),_y="rr0-case-editor",k6=`
|
|
9693
9693
|
<style>
|
|
9694
9694
|
:host { display: block; }
|
|
9695
9695
|
[hidden] { display: none !important; }
|