@rr0/ufoathome 0.161.0 → 0.162.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed-scene/rr0-scene.mjs +4 -4
- package/dist-embed-sighting/{AdsbLolArchiveProvider-CQ9jtd4F.js → AdsbLolArchiveProvider-CX1R8zJF.js} +1 -1
- package/dist-embed-sighting/BallesterGuaspAssessor-CCjRjJck.js +1 -0
- package/dist-embed-sighting/BeamSystem-B0H346X_.js +1 -0
- package/dist-embed-sighting/{ContrailSystem-BqRjqAEx.js → ContrailSystem-BeK11Jxe.js} +1 -1
- package/dist-embed-sighting/GLTFLoader-B_T3zy3i.js +1 -0
- package/dist-embed-sighting/HeadlightSystem-DjtbpwEp.js +34 -0
- package/dist-embed-sighting/HynekAssessor-B8Iw0Cbz.js +1 -0
- package/dist-embed-sighting/NearestApproach-B5s-b6tU.js +1 -0
- package/dist-embed-sighting/PoherAssessor-CwQN9pB1.js +1 -0
- package/dist-embed-sighting/{RailwaySystem-YNlv2jnz.js → RailwaySystem-9blFcIdg.js} +1 -1
- package/dist-embed-sighting/ReferenceSystem-DFM_jZ-Q.js +1 -0
- package/dist-embed-sighting/SightingMessages_es-Dsr6169b.js +1 -0
- package/dist-embed-sighting/SightingMessages_fr-DQNbBD0c.js +1 -0
- package/dist-embed-sighting/{SightingMessages_it-BC3oCPqe.js → SightingMessages_it-WE-_Cuu4.js} +1 -1
- package/dist-embed-sighting/{TraceSystem-Cr68QBMq.js → TraceSystem-CLYZFxAf.js} +2 -2
- package/dist-embed-sighting/{WaterSystem-DSCbpNaj.js → WaterSystem-BulddAwi.js} +1 -1
- package/dist-embed-sighting/rr0-sighting.mjs +17 -17
- package/dist-embed-sighting-editor/BallesterGuaspAssessor-gX_y6kL8.js +1 -0
- package/dist-embed-sighting-editor/{BeamSystem-CFF1njA3.js → BeamSystem-BBonCZQ1.js} +1 -1
- package/dist-embed-sighting-editor/{ContrailSystem-B99N4pbI.js → ContrailSystem-BXARgrR4.js} +1 -1
- package/dist-embed-sighting-editor/{GLTFLoader-BrPQY4ob.js → GLTFLoader-BVRuOnnK.js} +1 -1
- package/dist-embed-sighting-editor/{HeadlightSystem-BYTfcIPd.js → HeadlightSystem-9ywZKJNB.js} +1 -1
- package/dist-embed-sighting-editor/HynekAssessor-B9lO770Q.js +1 -0
- package/dist-embed-sighting-editor/NearestApproach-DCFh8vV6.js +1 -0
- package/dist-embed-sighting-editor/PoherAssessor-CzLQhAxP.js +1 -0
- package/dist-embed-sighting-editor/{RailwaySystem-CCk8DP7w.js → RailwaySystem-BfDjza60.js} +1 -1
- package/dist-embed-sighting-editor/{ReferenceSystem-BDjiP56B.js → ReferenceSystem-DHPnvAXN.js} +1 -1
- package/dist-embed-sighting-editor/{RoadMarkings-V8WtA9-k.js → RoadMarkings-HF9xJtTp.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_es-C5pk12_g.js → SightingEditorMessages_es-DGdkm-Yt.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_fr-Cevzw3sm.js → SightingEditorMessages_fr-thlWKHJq.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_it-r9D_FMqz.js → SightingEditorMessages_it-dkt2lxRe.js} +1 -1
- package/dist-embed-sighting-editor/{TraceSystem-C7ya-Gvd.js → TraceSystem-C1HaC0DX.js} +2 -2
- package/dist-embed-sighting-editor/{WaterSystem-HW6EhABp.js → WaterSystem-BDkfNF8C.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +16 -16
- package/package.json +1 -1
- package/dist-embed-sighting/BallesterGuaspAssessor-E4mL2MjD.js +0 -1
- package/dist-embed-sighting/BeamSystem-CVcdt0fc.js +0 -1
- package/dist-embed-sighting/GLTFLoader-CWl8CQPI.js +0 -1
- package/dist-embed-sighting/HeadlightSystem-xiiaXn1a.js +0 -34
- package/dist-embed-sighting/HynekAssessor-DPsLpEGQ.js +0 -1
- package/dist-embed-sighting/ReferenceSystem-By8XvGKa.js +0 -1
- package/dist-embed-sighting/SightingMessages_es-dFoOi4Xe.js +0 -1
- package/dist-embed-sighting/SightingMessages_fr-DK90WaSj.js +0 -1
- package/dist-embed-sighting-editor/BallesterGuaspAssessor-DUq2LwUo.js +0 -1
- package/dist-embed-sighting-editor/HynekAssessor-BtF8_xV5.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ShareCodeEditor-CF7IVeXv.js","./index-DSNA74v6.js","./BallesterGuaspAssessor-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ShareCodeEditor-CF7IVeXv.js","./index-DSNA74v6.js","./HynekAssessor-B9lO770Q.js","./NearestApproach-DCFh8vV6.js","./BallesterGuaspAssessor-gX_y6kL8.js","./CoverageAssessor-mvpHgNx3.js","./ContrailSystem-BXARgrR4.js","./ContrailGrowth-DwHS8If9.js","./BeamSystem-BBonCZQ1.js","./LaserBeam-DZ6ILkZ8.js","./ReferenceSystem-DHPnvAXN.js","./PictureFetch-X3UpM6JV.js","./trafficRuntime-DVOOnJGD.js","./ModelThumbnails-BA3zFrn5.js","./ModelSource-D0ZuOymh.js","./ModelViewer-BDorZEms.js","./SightingFileEditor-BekK-f3R.js","./sightingSchema-CnDwuCov.js","./BodyEditor-D5VXWcru.js","./BodyEditorMessages_en-DmM8Dasm.js","./LanternEditor-C60IT7Cv.js","./LanternEditorMessages_en-3XzIx2c4.js","./BeamEditor-BzrEOJOy.js","./BeamEditorMessages_en-DBs2OUXJ.js","./LaunchEditor-DcYWYLQN.js","./LaunchEditorMessages_en-DH8gI1vo.js","./GhostSearchView-UG9G-yF8.js","./InterviewEditorElement-Cpu0vwrk.js","./InterviewMessages_en-CC5D0e6J.js","./InterviewMedia-CvAxC62V.js","./interviewJson-DXD8FSBX.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
const dT="modulepreload",uT=function(c,e){return new URL(c,e).href},S1={},oe=function(e,t,i){let s=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 a=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");s=r(t.map(h=>{if(h=uT(h,i),h in S1)return;S1[h]=!0;const d=h.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(!!i)for(let m=a.length-1;m>=0;m--){const v=a[m];if(v.href===h&&(!d||v.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":dT,d||(f.as="script"),f.crossOrigin="",f.href=h,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((m,v)=>{f.addEventListener("load",m),f.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${h}`)))})}))}function n(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return s.then(r=>{for(const a of r||[])a.status==="rejected"&&n(a.reason);return e().catch(n)})};class Un{constructor(e){this.entries=e}static empty(){return new Un(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&&t.how===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 Un(new Map);return{recording:Un.stripValue(e,[],t),provenance:t}}static restore(e,t){if(t.size===0)return e;const i={...e},s=new Set([i]);for(const n of t.paths()){const r=t.at(n),a=n.split("."),o=Un.writableHolderOf(i,a,s);if(!o)continue;const l=a[a.length-1],h=o[l];h!==void 0&&(r.of!==void 0&&JSON.stringify(r.of)!==JSON.stringify(h)||(o[l]={value:h,...r.basis==="stated"?{}:{basis:r.basis},...r.rationale===void 0?{}:{rationale:r.rationale},...r.how===void 0?{}:{how:r.how}}))}return i}static isWrapper(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&"value"in e}static stripValue(e,t,i){return Un.isWrapper(e)?(i.set(t.join("."),{basis:e.basis??"stated",...e.rationale===void 0?{}:{rationale:e.rationale},...e.how===void 0?{}:{how:e.how},of:e.value}),Un.stripValue(e.value,t,i)):Array.isArray(e)?e.map((s,n)=>Un.stripValue(s,[...t,String(n)],i)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([s,n])=>[s,Un.stripValue(n,[...t,s],i)])):e}static writableHolderOf(e,t,i){let s=e;for(const n of t.slice(0,-1)){const r=s[n];if(typeof r!="object"||r===null)return;if(i.has(r)){s=r;continue}const a=Array.isArray(r)?[...r]:{...r};i.add(a),s[n]=a,s=a}return s}}class wu extends Error{constructor(e,t,i){super(typeof t=="number"&&Number.isInteger(t)&&t>i?`This ${e} file is in version ${t} of its format; this UFO@home reads up to version ${i}. Read it with a newer UFO@home.`:`This ${e} file states ${JSON.stringify(t)} as its format version, which is not a version.`),this.format=e,this.found=t,this.supported=i,this.name="FormatVersionError"}said(e){return e.replace("{found}",typeof this.found=="number"?String(this.found):JSON.stringify(this.found)).replace("{supported}",String(this.supported))}}class il{static CURRENT={sighting:3,case:1,interview:1};static SCHEMA_BASE="https://ufoathome.org/schema";static schemaUrl(e,t=il.CURRENT[e]){return`${il.SCHEMA_BASE}/${t}/${e}.schema.json`}static of(e){if(typeof e!="object"||e===null)return 1;const t=e.version;return t===void 0?1:typeof t=="object"&&t!==null&&"value"in t?t.value:t}static check(e,t){const i=il.of(e),s=il.CURRENT[t];if(typeof i!="number"||!Number.isInteger(i)||i<1||i>s)throw new wu(t,i,s);return e}}class Hi{static SIGHTING_EVENT="sighting";static INTERPRETATION_EVENT="interpretation";static INTERVIEW_EVENT="interview";static check(e){return il.check(e,"case")}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===Hi.SIGHTING_EVENT&&!i.interpretationOf&&typeof i.url=="string"&&i.url!=="").map(i=>new URL(i.url,t).href)}static accountIds(e,t,i,s){const n=(e.events??[]).filter(r=>r.eventType===Hi.SIGHTING_EVENT&&r.id!==void 0&&typeof r.url=="string"&&i!==void 0&&new URL(r.url,t).href===i).map(r=>r.id);return s!==void 0&&n.push(s),n}static interpretationEvents(e,t){const i=[t].flat().filter(s=>!!s);return i.length===0?[]:(e.events??[]).filter(s=>s.eventType===Hi.INTERPRETATION_EVENT?s.sighting!==void 0&&i.includes(s.sighting):s.eventType!==Hi.SIGHTING_EVENT||s.interpretationOf===void 0?!1:[s.interpretationOf].flat().some(n=>i.includes(n))).map(s=>s)}static problems(e,t){const i=e.events??[],s=new Set,n=new Set;for(const a of i)a.id!==void 0&&(s.has(a.id)&&n.add(a.id),s.add(a.id));const r=[];for(const a of i){const o=a.eventType===Hi.SIGHTING_EVENT?a.interpretationOf:a.eventType===Hi.INTERVIEW_EVENT?a.interviewOf:void 0;if(o!==void 0)for(const l of[o].flat())!s.has(l)&&!t.includes(l)&&r.push({reading:a.url??a.id??"",reference:l})}return{duplicateIds:[...n],unresolved:r}}static async interpretationOf(e,t,i){if(e.bodies)return Hi.withModelsFrom(Un.strip({title:e.title,bodies:e.bodies??[],smoke:e.smoke,flares:e.flares,lanterns:e.lanterns}).recording,t);if(!e.url)return{title:e.title,bodies:[]};const s=new URL(e.url,t).href,n=await i(s),r="timeline"in n&&n.interpretation?n.interpretation:n;return Hi.withModelsFrom(Un.strip({title:e.title??r.title,bodies:r.bodies??[],smoke:r.smoke,flares:r.flares,lanterns:r.lanterns}).recording,s)}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 Nn{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=Nn.ISO.exec(t);if(!i||t==="P"||t.endsWith("T"))return;const[,s,n,r,a,o]=i,l=d=>d===void 0?0:Number(d.replace(",",".")),h=l(s)*604800+l(n)*86400+l(r)*3600+l(a)*60+l(o);return Number.isFinite(h)?h:void 0}static parse(e){let t=e.trim();if(t==="")return;const i=t.slice(-1),s="?~%".includes(i)?i:"";s!==""&&(t=t.slice(0,-1).trim());const n=t.split("/");if(n.length>2)return;const r=n.map(d=>Nn.seconds(d));if(r.some(d=>d===void 0))return;const[a,o]=r,l=Math.min(a,o??a),h=Math.max(a,o??a);return{doubt:s,minSeconds:l,maxSeconds:h,chosenSeconds:(l+h)/2}}static isExact(e){const t=Nn.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),s=Math.floor(t%3600/60),n=Math.round(t%60*10)/10;return`PT${`${i>0?`${i}H`:""}${s>0?`${s}M`:""}${n>0||i===0&&s===0?`${n}S`:""}`}`}static say(e){const t=Math.round(e*10)/10;if(t<60)return`${t} s`;const i=Math.floor(t/3600),s=Math.floor(t%3600/60),n=Math.round(t%60*10)/10,r=[];return i>0&&r.push(`${i} h`),s>0&&r.push(`${s} min`),n>0&&r.push(`${n} 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 pT(c,e,t){if(!c||!e)return t<1?c:e;const i=((e.azimuthDeg-c.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((c.azimuthDeg+i*t)%360+360)%360,altitudeDeg:c.altitudeDeg+(e.altitudeDeg-c.altitudeDeg)*t}}function oE(c,e="#39ff14"){return{kind:"oval",bounds:c,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function lE(c,e,t="#39ff14"){return{kind:"polygon",bounds:c,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function fT(c,e="#39ff14"){const{width:t,height:i}=c;return lE(c,[{x:0,y:0},{x:t,y:0},{x:t,y:i},{x:0,y:i}],e)}const mT={oval:oE,polygon:fT};function E1(c,e){return{...mT[e.presetId](c,e.color),transparency:e.transparency,haloScale:e.haloScale,blur:e.blur,brightness:e.brightness}}function gT(c,e,t){const{bounds:i}=c;return e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height}function cE(c,e,t){const i=c.bounds.width,s=c.bounds.height;return{...c,bounds:{x:e-i/2,y:t-s/2,width:i,height:s}}}function Qn(c,e,t){return c+(e-c)*t}function A1(c){const e=/^#([0-9a-f]{6})$/i.exec(c);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function vT(c){return`#${c.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function bT(c,e,t){const i=A1(c),s=A1(e);return!i||!s?t<1?c:e:vT([Qn(i[0],s[0],t),Qn(i[1],s[1],t),Qn(i[2],s[2],t)])}function yT(c,e,t){const i={x:Qn(c.bounds.x,e.bounds.x,t),y:Qn(c.bounds.y,e.bounds.y,t),width:Qn(c.bounds.width,e.bounds.width,t),height:Qn(c.bounds.height,e.bounds.height,t)},s=Qn(c.angle,e.angle,t),n=Qn(c.transparency,e.transparency,t),r=Qn(c.haloScale,e.haloScale,t),a=Qn(c.blur??0,e.blur??0,t),o=Qn(c.brightness??0,e.brightness??0,t),l=bT(c.color,e.color,t),h=Lt.lerpAngular(c.angular,e.angular,t),d=pT(c.aim,e.aim,t);return c.kind==="polygon"&&e.kind==="polygon"&&c.points.length===e.points.length?{...c,bounds:i,angle:s,transparency:n,haloScale:r,blur:a,brightness:o,color:l,angular:h,aim:d,points:c.points.map((u,p)=>({x:Qn(u.x,e.points[p].x,t),y:Qn(u.y,e.points[p].y,t)}))}:{...t<1?c:e,bounds:i,angle:s,transparency:n,haloScale:r,blur:a,brightness:o,color:l,angular:h,aim:d}}class no{static DEFAULT_COLOR="#e8e6df";static complete(e,t=[]){const i=new Map;return e.map((s,n)=>({keyframe:s,index:n})).sort((s,n)=>s.keyframe.t-n.keyframe.t).map(({keyframe:s,index:n})=>({t:s.t,shapes:(s.shapes??[]).map((r,a)=>{const o=`timeline.keyframes.${n}.shapes.${a}.shape`,l=no.completed(r,i.get(r.sourceId),o,t);return i.set(r.sourceId,l),{sourceId:r.sourceId,shape:l}})}))}static thin(e,t){const i=new Map,s=new Set;return e.map((n,r)=>({t:n.t,shapes:n.shapes.map(a=>{const o=i.get(a.sourceId);if(i.set(a.sourceId,a.shape),!o)return{sourceId:a.sourceId,shape:a.shape};const l=no.thinned(a.shape,o);if(t){const h=l;t(r,a.sourceId)?(delete h.bounds,delete h.points,s.add(a.sourceId)):s.delete(a.sourceId)&&(h.bounds=a.shape.bounds,a.shape.kind==="polygon"&&(h.points=a.shape.points),a.shape.aim&&(h.aim=a.shape.aim),a.shape.angular&&(h.angular=a.shape.angular))}return{sourceId:a.sourceId,shape:l}})}))}static thinned(e,t){const i=t,s={};for(const[n,r]of Object.entries(e))(typeof r=="object"&&r!==null&&!Array.isArray(r)&&"value"in r||r!==i[n]&&JSON.stringify(r)!==JSON.stringify(i[n]))&&(s[n]=r);return"bounds"in s&&(e.aim&&(s.aim=e.aim),e.angular&&(s.angular=e.angular)),s}static completed(e,t,i,s){const n=e.shape??{},r=t??no.firstAppearance(n,i,s),a={...r};n.bounds&&t&&(t.aim||t.angular)&&!n.aim&&!n.angular&&s.push({kind:"pixels-over-angles",path:i}),n.bounds&&(n.aim||delete a.aim,n.angular||delete a.angular);const o=n.kind??r.kind??"oval",l={...a,...n,kind:o};if(o==="polygon"&&!l.points){s.push({kind:"defaulted",path:`${i}.points`,expected:"rectangle"});const{width:h,height:d}=l.bounds;return{...l,points:[{x:0,y:0},{x:h,y:0},{x:h,y:d},{x:0,y:d}]}}return l}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:`"${no.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:{...no.NEUTRAL_BOUNDS},color:no.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 dp{keyframes=[];order=[];groups=[];span=0;addKeyframe(e,t){const i=this.findInsertIndex(e);if(this.keyframes[i]?.t===e){const s=new Set(t.map(n=>n.sourceId));this.keyframes[i]={t:e,shapes:[...this.keyframes[i].shapes.filter(n=>!s.has(n.sourceId)),...t]}}else this.keyframes.splice(i,0,{t:e,shapes:[...t]});for(const s of t)this.order.includes(s.sourceId)||this.order.push(s.sourceId)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const s=t+i>>>1;this.keyframes[s].t<e?t=s+1:i=s}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 s=this.keyframes[i].shapes.find(n=>n.sourceId===t);if(s)return s.shape}}getInterpolatedShapeAt(e,t){const i=this.findShapeAtOrBefore(e,t);if(i?.t===e)return i.shape;const s=this.findShapeAtOrAfter(e,t);return i?s?yT(i.shape,s.shape,(e-i.t)/(s.t-i.t)):i.shape:s?.shape}findShapeAtOrBefore(e,t){let i=this.findInsertIndex(e);for(this.keyframes[i]?.t!==e&&(i-=1);i>=0;i--){const s=this.keyframes[i].shapes.find(n=>n.sourceId===t);if(s)return{t:this.keyframes[i].t,shape:s.shape}}}findShapeAtOrAfter(e,t){for(let i=this.findInsertIndex(e);i<this.keyframes.length;i++){const s=this.keyframes[i].shapes.find(n=>n.sourceId===t);if(s)return{t:this.keyframes[i].t,shape:s.shape}}}hitTest(e,t,i,s){const n=this.sourceIds;for(let r=n.length-1;r>=0;r--){if(s?.has(n[r]))continue;const a=this.getInterpolatedShapeAt(e,n[r]);if(a&&gT(a,t,i))return{sourceId:n[r],shape:a}}}removeSource(e){for(let t=this.keyframes.length-1;t>=0;t--){const i=this.keyframes[t].shapes.filter(s=>s.sourceId!==e);i.length===0?this.keyframes.splice(t,1):i.length!==this.keyframes[t].shapes.length&&(this.keyframes[t]={t:this.keyframes[t].t,shapes:i})}this.order=this.order.filter(t=>t!==e),this.removeFromGroup(e)}removeShapeAt(e,t){const i=this.findInsertIndex(e),s=this.keyframes[i];if(s?.t!==e)return;const n=s.shapes.filter(r=>r.sourceId!==t);n.length===0?this.keyframes.splice(i,1):n.length!==s.shapes.length&&(this.keyframes[i]={t:e,shapes:n})}group(e,t){const i=new Set(e),s=[];for(const r of e){const a=this.topOf(r),o=a!==r&&this.leavesOf(a).every(l=>i.has(l))?a:r;o===r&&a!==r&&this.removeFromGroup(r),s.includes(o)||s.push(o)}if(s.length<2)return;const n=t??this.freshGroupId();return this.groups.push({id:n,members:s}),n}ungroup(e){const t=this.topOf(e);t!==e&&(this.groups=this.groups.filter(i=>i.id!==t))}groupMembers(e){const t=this.topOf(e);return t===e?void 0:this.leavesOf(t)}get allGroups(){return this.groups}setGroups(e,t=!0){this.groups=e.map(i=>({...i,members:[...i.members]})),t&&this.pruneGroups()}groupOf(e){return this.groups.find(t=>t.id===e)}leavesOf(e,t=new Set){const i=this.groupOf(e);return i?t.has(e)?[]:(t.add(e),i.members.flatMap(s=>this.leavesOf(s,t))):[e]}parentOf(e){return this.groups.find(t=>t.members.includes(e))}topOf(e){let t=e;for(let i=this.parentOf(t),s=0;i&&s<100;i=this.parentOf(t),s++)t=i.id;return t}freshGroupId(){for(let e=this.groups.length+1;;e++){const t=`group-${e}`;if(!this.groupOf(t)&&!this.order.includes(t))return t}}removeFromGroup(e){const t=this.parentOf(e);t&&(t.members=t.members.filter(i=>i!==e),this.collapse())}pruneGroups(){const e=t=>this.order.includes(t)||this.groupOf(t)!==void 0;for(const t of this.groups)t.members=t.members.filter(e);this.collapse()}collapse(){for(let e=this.groups.find(t=>t.members.length<2);e;e=this.groups.find(t=>t.members.length<2)){const t=e;this.groups=this.groups.filter(i=>i!==t);for(const i of this.groups)i.members=i.members.flatMap(s=>s===t.id?t.members:[s])}}bringToFront(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.push(e))}sendToBack(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.unshift(e))}get duration(){const e=this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t;return Math.max(e,this.span)}get hasSpan(){return this.span>0}setSpan(e){this.span=Math.max(0,e)}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return this.span>0?{keyframes:this.keyframes,order:this.order,groups:this.groupsJson(),span:this.span}:{keyframes:this.keyframes,order:this.order,groups:this.groupsJson()}}groupsJson(){return this.groups.map(e=>({...e,members:[...e.members]}))}static fromJSON(e,t,i=!0){const s=new dp;for(const n of no.complete(e.keyframes??[],t))s.addKeyframe(n.t,n.shapes);if(e.span!==void 0&&e.span>0&&(s.span=e.span),e.order){const n=s.order.filter(r=>!e.order.includes(r));s.order=[...e.order,...n]}return e.groups&&(s.groups=e.groups.filter(n=>typeof n?.id=="string"&&Array.isArray(n.members)).map(n=>({...n,members:[...n.members]})),i&&s.pruneGroups()),s}}function wT(c,e,t){return Math.max(e,Math.min(t,c))}function MT(c,e,t){const i=((e-c)%360+540)%360-180;return((c+i*t)%360+360)%360}function Ic(c,e,t){return c+(e-c)*t}function xT(c,e,t){return{lat:c.lat===void 0||e.lat===void 0?void 0:Ic(c.lat,e.lat,t),lng:c.lng===void 0||e.lng===void 0?void 0:Ic(c.lng,e.lng,t),elevationM:Ic(c.elevationM,e.elevationM,t),headingDeg:c.headingDeg===void 0||e.headingDeg===void 0?void 0:MT(c.headingDeg,e.headingDeg,t),pitchDeg:Ic(c.pitchDeg,e.pitchDeg,t),rollDeg:Ic(c.rollDeg??0,e.rollDeg??0,t),fovDeg:Ic(c.fovDeg,e.fovDeg,t),fNumber:c.fNumber,focusDistanceM:c.focusDistanceM,filter:c.filter}}class Ps{static at(e,t,i,s,n){const r=e[i],o=e[i+1]-r;if(o<=0)return t[i];const l=Ps.tangent(e,t,i,n),h=Ps.tangent(e,t,i+1,n),d=(s-r)/o,u=d*d,p=u*d;return(2*p-3*u+1)*t[i]+(p-2*u+d)*o*l+(-2*p+3*u)*t[i+1]+(p-u)*o*h}static SETTLE_MS=120;static ARRIVAL=.5;static gaze(e,t,i,s){const n=e[i],a=e[i+1]-n;if(a<=0)return t[i];const o=h=>h+1<t.length?t[h+1]===t[h]:!0,l=t[i+1]!==t[i];if(l&&o(i+1)){const h=Ps.tangent(e,t,i,!0),d=Ps.ARRIVAL*(t[i+1]-t[i])/a;return Ps.hermite(t[i],h,t[i+1],d,a,(s-n)/a)}return!l&&i>0&&t[i-1]!==t[i]?t[i]+Ps.settle(e,t,i,s-n,a):Ps.at(e,t,i,s,!0)}static settle(e,t,i,s,n){const r=e[i]-e[i-1];if(r<=0||s<=0)return 0;const a=Ps.ARRIVAL*(t[i]-t[i-1])/r,o=Math.min(Ps.SETTLE_MS,.4*r),l=Number.isFinite(n)?(1-Math.min(1,s/n))**2:1;return a*s*Math.exp(-s/o)*l}static hermite(e,t,i,s,n,r){const a=r*r,o=a*r;return(2*o-3*a+1)*e+(o-2*a+r)*n*t+(-2*o+3*a)*i+(o-a)*n*s}static BRAKE_S=.8;static paced(e,t,i,s){if(!i&&!s)return e;const n=t>0?Math.min(.5,Ps.BRAKE_S/t):.5;if(i&&s){const a=1/(1-n);return e<=n?a*e*e/(2*n):e>=1-n?1-a*(1-e)*(1-e)/(2*n):a*(e-n/2)}const r=a=>{const o=1/(1-n/2);if(a<=1-n)return o*a;const l=a-(1-n);return o*(1-n)+o*(l-l*l/(2*n))};return s?r(e):1-r(1-e)}static tangent(e,t,i,s){const n=e.length-1,r=p=>(t[p+1]-t[p])/(e[p+1]-e[p]||1);if(i===0)return s?0:r(0);if(i===n)return s?0:r(n-1);const a=r(i-1),o=r(i);if(a*o<=0)return 0;const l=e[i]-e[i-1],h=e[i+1]-e[i],d=2*h+l,u=h+2*l;return(d+u)/(d/a+u/o)}}class Mu{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 s=t+i>>>1;this.keyframes[s].t<e?t=s+1:i=s}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 s=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return s?.pose;if(!s)return this.settledAfterEnd(t-1,e);const n=xT(i.pose,s.pose,wT((e-i.t)/(s.t-i.t),0,1));return this.humanly(t-1,e,n)}settledAfterEnd(e,t){const i=this.keyframes[e];if(e<1)return i.pose;const s=this.keyframes[e-1],n=[s.t,i.t],r=(h,d)=>h===void 0||d===void 0?0:Ps.settle(n,[h,d],1,t-i.t,1/0),a=s.pose.headingDeg===void 0||i.pose.headingDeg===void 0?void 0:((i.pose.headingDeg-s.pose.headingDeg)%360+540)%360-180,o=i.pose.headingDeg===void 0||a===void 0?i.pose.headingDeg:((i.pose.headingDeg+r(0,a))%360+360)%360,l=i.pose.pitchDeg+r(s.pose.pitchDeg,i.pose.pitchDeg);return o===i.pose.headingDeg&&l===i.pose.pitchDeg?i.pose:{...i.pose,headingDeg:o,pitchDeg:l}}humanly(e,t,i){const s=Math.max(0,e-1),n=Math.min(this.keyframes.length-1,e+2),r=this.keyframes.slice(s,n+1),a=e-s,o=r.map(y=>y.t),l=(y,M)=>{const S=r.map(E=>y(E.pose));if(!S.some(E=>E===void 0))return Ps.at(o,S,a,t,M)},h=y=>{const M=r.map(S=>y(S.pose));if(!M.some(S=>S===void 0))return Ps.gaze(o,M,a,t)},d=r.map(y=>y.pose.headingDeg);let u;if(d.every(y=>y!==void 0)){const y=[d[0]];for(let M=1;M<d.length;M++)y.push(y[M-1]+((d[M]-d[M-1])%360+540)%360-180);u=(Ps.gaze(o,y,a,t)%360+360)%360}const p=this.keyframes[e],f=this.keyframes[e+1],m=(y,M)=>y.lat===M.lat&&y.lng===M.lng&&y.elevationM===M.elevationM,v=!m(p.pose,f.pose),g=v&&e>0&&m(this.keyframes[e-1].pose,p.pose),b=v&&e+2<this.keyframes.length&&m(f.pose,this.keyframes[e+2].pose);let w;if(g||b){const y=Ps.paced((t-p.t)/(f.t-p.t),(f.t-p.t)/1e3,g,b),M=(S,E)=>S===void 0||E===void 0?void 0:S+(E-S)*y;w={lat:M(p.pose.lat,f.pose.lat),lng:M(p.pose.lng,f.pose.lng),elevationM:M(p.pose.elevationM,f.pose.elevationM)}}return{...i,lat:w?w.lat:l(y=>y.lat,!1)??i.lat,lng:w?w.lng:l(y=>y.lng,!1)??i.lng,elevationM:w?w.elevationM:l(y=>y.elevationM,!1)??i.elevationM,headingDeg:u??i.headingDeg,pitchDeg:h(y=>y.pitchDeg)??i.pitchDeg,rollDeg:l(y=>y.rollDeg??0,!0)??i.rollDeg,fovDeg:l(y=>y.fovDeg,!0)??i.fovDeg}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new Mu;for(const i of e.keyframes)t.addKeyframe(i.t,i.pose);return t}}class Vo{static MAX_CHANGE_PER_S=.05;points;followed;constructor(e){let t="none",i=0;this.points=e.map(({t:s,weather:n})=>(n.precipitationType!=="none"&&(t=n.precipitationType,i=n.precipitationIntensity),{t:s,lastFalling:t,lastFallingIntensity:i,intensity:n.precipitationType==="none"?0:n.precipitationIntensity,type:n.precipitationType})),this.followed=[];for(let s=0;s<this.points.length;s++){if(s===0){this.followed.push(this.points[0].intensity);continue}const n=this.points[s-1],r=this.points[s];this.followed.push(Vo.follow(this.followed[s-1],n.intensity,r.intensity,(r.t-n.t)/1e3,(r.t-n.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],s=this.points[t+1],n=s?Vo.follow(this.followed[t],i.intensity,s.intensity,(s.t-i.t)/1e3,(e-i.t)/1e3):Vo.follow(this.followed[t],i.intensity,i.intensity,1,(e-i.t)/1e3);return{type:Vo.typeBetween(i,s,e,n),intensity:n,character:Vo.characterBetween(i,s,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,s){return e.type==="none"?t&&t.type!=="none"&&i>e.t?t.type:s>0?e.lastFalling:"none":t&&t.type==="none"&&s<=0?"none":e.type}static follow(e,t,i,s,n){const r=Vo.MAX_CHANGE_PER_S,a=s>0?(i-t)/s:0,o=d=>t+a*Math.min(Math.max(d,0),s);let l=e,h=0;for(let d=0;d<8&&h<n;d++){const u=o(h)-l;if(Math.abs(u)<1e-9){const w=h<s?a:0;if(Math.abs(w)<=r){const M=h<s?Math.min(n,s):n;l=o(M),h=M;continue}const y=Math.min(n,s);l+=Math.sign(w)*r*(y-h),h=y;continue}const p=Math.sign(u),f=h<s?a:0,m=r-p*f,v=m>0?h+Math.abs(u)/m:1/0,g=h<s?s:1/0,b=Math.min(n,v,g);l+=p*r*(b-h),h=b,b===v&&(l=o(h))}return Math.min(1,Math.max(0,l))}}const ry=1e3,qf=.65,hE=.05,Zm={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function ml(c){if(c.cloudLayers!==void 0)return c.cloudLayers;const e=[],t=c.lowerCloudCover??c.cloudCover;return t>0&&e.push({id:"lower",type:"cumulus",baseM:c.cloudBaseM??ry,thicknessM:650,coverage:t,sizeM:1400,density:1,darkness:c.cloudDarkness}),(c.highCloudCover??0)>0&&e.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:c.highCloudCover,sizeM:2200,density:.35,darkness:c.cloudDarkness,iceCrystalAlignment:c.iceCrystalAlignment}),e}function Bi(c,e,t){return c+(e-c)*t}function ay(c,e,t){const i=((e-c)%360+540)%360-180;return((c+i*t)%360+360)%360}function ST(c,e,t){return Math.max(e,Math.min(t,c))}function ET(c=[],e=[],t){if(!(!c.length&&!e.length))return[...new Set([...c.map(i=>i.id),...e.map(i=>i.id)])].map(i=>{const s=c.find(o=>o.id===i),n=e.find(o=>o.id===i),r=s??{...n,density:0},a=n??{...s,density:0};return{...r,eastM:Bi(r.eastM,a.eastM,t),northM:Bi(r.northM,a.northM,t),baseM:Bi(r.baseM,a.baseM,t),thicknessM:Bi(r.thicknessM,a.thicknessM,t),widthM:Bi(r.widthM,a.widthM,t),depthM:Bi(r.depthM,a.depthM,t),rotationDeg:ay(r.rotationDeg,a.rotationDeg,t),density:Bi(r.density,a.density,t),darkness:Bi(r.darkness??0,a.darkness??0,t)}})}function AT(c,e,t){if(c.cloudLayers===void 0&&e.cloudLayers===void 0)return;const i=ml(c),s=ml(e);return t>=1?s.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...s.map(r=>r.id)])].map(r=>{const a=i.find(d=>d.id===r),o=s.find(d=>d.id===r),l=a??{...o,coverage:0},h=o??{...a,coverage:0};return{...l,instances:ET(a?.instances,o?.instances,t),baseM:Bi(l.baseM,h.baseM,t),thicknessM:Bi(l.thicknessM,h.thicknessM,t),coverage:Bi(l.coverage,h.coverage,t),sizeM:Bi(l.sizeM,h.sizeM,t),density:Bi(l.density,h.density,t),darkness:Bi(l.darkness??c.cloudDarkness,h.darkness??e.cloudDarkness,t),iceCrystalAlignment:l.iceCrystalAlignment===void 0||h.iceCrystalAlignment===void 0?void 0:Bi(l.iceCrystalAlignment,h.iceCrystalAlignment,t),windSpeed:l.windSpeed===void 0&&h.windSpeed===void 0?void 0:Bi(l.windSpeed??c.windSpeed,h.windSpeed??e.windSpeed,t),windDirectionDeg:l.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:ay(l.windDirectionDeg??c.windDirectionDeg,h.windDirectionDeg??e.windDirectionDeg,t)}})}function TT(c,e,t){return{cloudLayers:AT(c,e,t),cloudCover:Bi(c.cloudCover,e.cloudCover,t),cloudDarkness:Bi(c.cloudDarkness,e.cloudDarkness,t),highCloudCover:c.highCloudCover===void 0||e.highCloudCover===void 0?void 0:Bi(c.highCloudCover,e.highCloudCover,t),iceCrystalAlignment:c.iceCrystalAlignment===void 0||e.iceCrystalAlignment===void 0?void 0:Bi(c.iceCrystalAlignment,e.iceCrystalAlignment,t),rareIceCrystals:c.rareIceCrystals===void 0||e.rareIceCrystals===void 0?void 0:Bi(c.rareIceCrystals,e.rareIceCrystals,t),lowerCloudCover:c.lowerCloudCover===void 0||e.lowerCloudCover===void 0?void 0:Bi(c.lowerCloudCover,e.lowerCloudCover,t),cloudBaseM:c.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:Bi(c.cloudBaseM,e.cloudBaseM,t),relativeHumidity:c.relativeHumidity===void 0||e.relativeHumidity===void 0?void 0:Bi(c.relativeHumidity,e.relativeHumidity,t),precipitationType:t<1?c.precipitationType:e.precipitationType,precipitationIntensity:Bi(c.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:ay(c.windDirectionDeg,e.windDirectionDeg,t),windSpeed:Bi(c.windSpeed,e.windSpeed,t),storm:t<1?c.storm:e.storm}}class xu{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 s=t+i>>>1;this.keyframes[s].t<e?t=s+1:i=s}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 s=this.keyframes[t]?.t===e?void 0:this.keyframes[t];return i?s?TT(i.weather,s.weather,ST((e-i.t)/(s.t-i.t),0,1)):i.weather:s?.weather}getActualWeatherAt(e){const t=this.getInterpolatedWeatherAt(e);if(!t)return;const i=(this.ramp??=new Vo(this.keyframes)).at(e);if(!i)return t;const{type:s,intensity:n,character:r}=i,a=r>0?Math.min(1,n/r):s==="none"?0:1;return{...t,precipitationType:s,precipitationIntensity:r,precipitationAmount:a}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new xu;for(const i of e.keyframes)t.addKeyframe(i.t,{...Zm,...i.weather});return t}}class Su{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 s=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return s?.sound;if(!s)return i.sound;const n=(e-i.t)/(s.t-i.t);return this.lerp(i.sound,s.sound,Math.max(0,Math.min(1,n)))}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 Su;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 s=t+i>>>1;this.keyframes[s].t<e?t=s+1:i=s}return t}}const IT=["none","hum","whistle","rumble","crackle"],_T=100,DT={kind:"none",volume:0,pitchHz:_T};class lh{static DEFAULT_FOCAL_MM=50;static FOCAL_RANGE_MM={minMm:14,maxMm:135};static BODIES=[{id:"eos-450d",name:"Canon EOS 450D (APS-C)",widthMm:22.2,heightMm:14.8,pixelUm:5.2,year:2008},{id:"eos-60da",name:"Canon EOS 60Da (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.3,year:2012},{id:"eos-70d",name:"Canon EOS 70D (APS-C)",widthMm:22.5,heightMm:15,pixelUm:4.1,year:2013},{id:"eos-80d",name:"Canon EOS 80D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:3.7,year:2016},{id:"eos-7d",name:"Canon EOS 7D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.1,year:2009},{id:"eos-7d-ii",name:"Canon EOS 7D Mark II (APS-C)",widthMm:22.4,heightMm:15,pixelUm:4.1,year:2014},{id:"eos-5d",name:"Canon EOS 5D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:8.2,year:2005},{id:"eos-5d-ii",name:"Canon EOS 5D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:6.4,year:2008},{id:"eos-5d-iii",name:"Canon EOS 5D Mark III (full frame)",widthMm:36,heightMm:24,pixelUm:6.25,year:2012},{id:"eos-5d-iv",name:"Canon EOS 5D Mark IV (full frame)",widthMm:36,heightMm:24,pixelUm:5.36,year:2016},{id:"eos-6d",name:"Canon EOS 6D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:6.55,year:2012},{id:"eos-6d-ii",name:"Canon EOS 6D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:5.77,year:2017},{id:"nikon-d3",name:"Nikon D3 / D700 (full frame)",widthMm:36,heightMm:23.9,pixelUm:8.44,year:2007},{id:"nikon-d7000",name:"Nikon D7000 (DX)",widthMm:23.6,heightMm:15.6,pixelUm:4.78,year:2010},{id:"nikon-d7100",name:"Nikon D7100 / D7200 (DX)",widthMm:23.5,heightMm:15.6,pixelUm:3.9,year:2013},{id:"nikon-d500",name:"Nikon D500 / D7500 (DX)",widthMm:23.5,heightMm:15.7,pixelUm:4.2,year:2016}];static instruments(){return lh.BODIES.map(e=>({id:e.id,category:"dslr",name:e.name,projection:"rectilinear",frame:{widthMm:e.widthMm,heightMm:e.heightMm,focalLengthMm:lh.DEFAULT_FOCAL_MM,focalRangeMm:lh.FOCAL_RANGE_MM},fNumber:8,fNumberRange:{min:1.4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/8e3,max:3600},years:{from:e.year},apertureBlades:7,detailUm:e.pixelUm,medium:{kind:"sensor",iso:100}}))}static names(){return Object.fromEntries(lh.BODIES.map(e=>[e.id,e.name]))}}class Wr{static DEFAULT_EYEPIECE_MM=26;static DEFAULT_APPARENT_FIELD_DEG=52;static FIELD_STOP_MM=2*Wr.DEFAULT_EYEPIECE_MM*Math.tan(Wr.DEFAULT_APPARENT_FIELD_DEG*Math.PI/360);static RANGE={min:26/40*.63,max:26/6*3};static BINOCULARS=[{id:"binoculars-zeiss-6x30",name:"Carl Zeiss 6x30",magnification:6,apertureMm:30,trueFieldDeg:5,fromYear:1960},{id:"binoculars-zeiss-dialyt-10x40",name:"Carl Zeiss Dialyt 10x40 B T*",magnification:10,apertureMm:40,trueFieldDeg:6.3,fromYear:1975},{id:"binoculars-jenoptem-10x50",name:"Jenoptem 10x50 W",magnification:10,apertureMm:50,trueFieldDeg:7.3,fromYear:1960},{id:"binoculars-swarovski-7x50-habicht",name:"Swarovski 7x50 SL Habicht",magnification:7,apertureMm:50,trueFieldDeg:6.6,fromYear:1960},{id:"binoculars-swarovski-7x50-slc",name:"Swarovski 7x50 SLC",magnification:7,apertureMm:50,trueFieldDeg:7.1,fromYear:1990},{id:"binoculars-nikon-10x42-edg",name:"Nikon 10x42 EDG",magnification:10,apertureMm:42,trueFieldDeg:6.5,fromYear:2011},{id:"binoculars-canon-15x50-is",name:"Canon 15x50 IS All Weather",magnification:15,apertureMm:50,trueFieldDeg:4.5,fromYear:2008},{id:"binoculars-celestron-15x70",name:"Celestron 15x70 SkyMaster",magnification:15,apertureMm:70,trueFieldDeg:4.4,fromYear:1990},{id:"binoculars-miyauchi-25x141",name:"Miyauchi BR-141 Galaxy 45 25x141",magnification:25,apertureMm:141,trueFieldDeg:2.6,fromYear:2e3}];static TELESCOPES=[{id:"telescope-generic-60-700",name:"Telescope 60/700",apertureMm:60,focalLengthMm:700},{id:"telescope-generic-60-1000",name:"Telescope 60/1000",apertureMm:60,focalLengthMm:1e3},{id:"telescope-celestron-onyx-80edf",name:"Celestron Onyx 80EDF",apertureMm:80,focalLengthMm:500,fromYear:2010},{id:"telescope-celestron-c5",name:"Celestron C5 f/10",apertureMm:125,focalLengthMm:1250,fromYear:1970},{id:"telescope-celestron-c8",name:"Celestron C8 f/10",apertureMm:203,focalLengthMm:2032,fromYear:1970},{id:"telescope-celestron-c11",name:"Celestron C11 f/10",apertureMm:280,focalLengthMm:2800,fromYear:1970},{id:"telescope-celestron-c14",name:"Celestron C14 f/11",apertureMm:355.6,focalLengthMm:3910,fromYear:1970},{id:"telescope-meade-etx-80",name:"Meade ETX 80 f/5",apertureMm:80,focalLengthMm:400,fromYear:1996},{id:"telescope-meade-etx-90",name:"Meade ETX 90 f/13.8",apertureMm:90,focalLengthMm:1242,fromYear:1996},{id:"telescope-meade-etx-125",name:"Meade ETX 125 f/15",apertureMm:127,focalLengthMm:1900,fromYear:1996},{id:"telescope-meade-lx200-8",name:"Meade LX200 8 in f/10",apertureMm:200,focalLengthMm:2e3,fromYear:1992},{id:"telescope-meade-lx200-10",name:"Meade LX200 10 in f/10",apertureMm:250,focalLengthMm:2500,fromYear:1992},{id:"telescope-meade-lx200-12",name:"Meade LX200 12 in f/10",apertureMm:305,focalLengthMm:3048,fromYear:1992},{id:"telescope-meade-lx200-14",name:"Meade LX200 14 in f/10",apertureMm:355,focalLengthMm:3556,fromYear:1992},{id:"telescope-meade-lx200-16",name:"Meade LX200 16 in f/10",apertureMm:406,focalLengthMm:4064,fromYear:1992}];static instruments(){const e=Wr.BINOCULARS.map(s=>({id:s.id,category:"binoculars",name:s.name,projection:"rectilinear",visualAid:{apertureMm:s.apertureMm,magnification:s.magnification,trueFieldDeg:s.trueFieldDeg},...s.fromYear!==void 0?{years:{from:s.fromYear}}:{}})),t=Wr.FIELD_STOP_MM,i=Wr.TELESCOPES.map(s=>({id:s.id,category:"telescope",name:s.name,projection:"rectilinear",frame:{widthMm:t*16/9,heightMm:t,focalLengthMm:s.focalLengthMm,focalRangeMm:{minMm:s.focalLengthMm*Wr.RANGE.min,maxMm:s.focalLengthMm*Wr.RANGE.max}},visualAid:{apertureMm:s.apertureMm,eyepieceFocalMm:Wr.DEFAULT_EYEPIECE_MM},...s.fromYear!==void 0?{years:{from:s.fromYear}}:{}}));return[...e,...i]}static names(){return Object.fromEntries(Wr.instruments().map(e=>[e.id,e.name]))}}const $d=[{id:"eye",category:"eye",name:"Naked eye",projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",category:"camera",name:"Camera, unknown device",projection:"rectilinear",fNumber:8,fNumberRange:{min:2,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:8},apertureBlades:6},{id:"roamer-1-120",category:"camera",name:"Roamer 1, 120 film",projection:"rectilinear",frame:{widthMm:74,heightMm:60,focalLengthMm:100},fNumber:11,exposureSeconds:1/50,years:{from:1930,to:1965},detailUm:40,medium:{kind:"negative",iso:125}},{id:"instamatic-126",category:"camera",name:"Instamatic, 126 film",projection:"rectilinear",frame:{widthMm:28,heightMm:28,focalLengthMm:43},fNumber:11,exposureSeconds:1/90,years:{from:1963,to:1988},apertureBlades:5,detailUm:20,medium:{kind:"negative",iso:64}},{id:"slr-35mm-50",category:"camera",name:"35 mm SLR, 50 mm lens",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:50},fNumber:8,fNumberRange:{min:2,max:16},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},years:{from:1959},apertureBlades:6,detailUm:20,medium:{kind:"negative",iso:100}},{id:"slr-35mm-zoom",category:"camera",name:"35 mm SLR, 70-210 mm zoom",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:135,focalRangeMm:{minMm:70,maxMm:210}},fNumber:8,fNumberRange:{min:4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},apertureBlades:8,years:{from:1975},detailUm:20,medium:{kind:"negative",iso:100}},{id:"phone-landscape",category:"phone",name:"Phone, held sideways",projection:"rectilinear",frame:{widthMm:7.6,heightMm:5.7,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"phone-portrait",category:"phone",name:"Phone, held upright",projection:"rectilinear",frame:{widthMm:5.7,heightMm:7.6,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"dashcam",mounted:!0,category:"video",name:"Dashcam",projection:"equidistant",frame:{widthMm:5.76,heightMm:3.24,focalLengthMm:3.2},fNumber:2,exposureSeconds:1/30,exposureRangeSeconds:{min:1/1e4,max:1/30},years:{from:2008},apertureBlades:void 0,detailUm:3,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},{id:"cctv",mounted:!0,category:"video",name:"Security camera",projection:"rectilinear",frame:{widthMm:4.8,heightMm:3.6,focalLengthMm:3.6},fNumber:2,exposureSeconds:1/50,exposureRangeSeconds:{min:1/1e5,max:1/50},years:{from:1990},apertureBlades:void 0,detailUm:6,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},...lh.instruments(),...Wr.instruments()];class Qt{static get default(){return $d[0]}static byId(e){return $d.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?Qt.fieldOf(e.projection,t.heightMm,t.focalLengthMm):e.visualAid?.trueFieldDeg??Qt.UNAIDED_FIELD_DEG}static fieldOf(e,t,i){return(e==="equidistant"?t/i:2*Math.atan(t/(2*i)))*180/Math.PI}static aspectOf(e){const t=e.frame;return t?t.widthMm/t.heightMm:Qt.UNAIDED_ASPECT}static frameWidthPx(e,t){return Math.round(t*Qt.aspectOf(e))}static CATEGORIES=["eye","camera","dslr","phone","video","binoculars","telescope"];static unavailability(e,t){const i=e.years;if(!(t===void 0||!i)){if(t<i.from)return{kind:"before",from:i.from};if(i.to!==void 0&&t>i.to)return{kind:"after",to:i.to}}}static availableAt(e){return e===void 0?$d:$d.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 Qt.fieldOf(e.projection,i.heightMm,t)}static focalLengthMmFor(e,t){const i=e.frame;if(!(!i||t<=0||t>=180))return e.projection==="equidistant"?i.heightMm/(t*Math.PI/180):i.heightMm/(2*Math.tan(t*Math.PI/360))}static bladesShowing(e,t){if(e.apertureBlades===void 0)return 0;const i=t??e.fNumber,s=e.fNumberRange?.min;if(i===void 0||s===void 0)return 1;const n=Math.max(0,Math.min(1,(i/s-1)/.3));return n*n*(3-2*n)}static starPointsOf(e,t){const i=e.apertureBlades;return i===void 0||i<3||Qt.bladesShowing(e,t)<.5?0:i%2===0?i:i*2}}class hr extends Error{}class Jm{constructor(e){this.name=e}validate(e){return!0}}class dE extends Jm{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new hr(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new hr(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class Ii{name;min;max;duration;subUnit;validator;constructor(e,t,i,s,n=new dE(e,t,i)){this.name=e,this.min=t,this.max=i,this.subUnit=s,this.duration=s?(s.max-s.min+1)*s.duration:1,this.validator=n}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 oy{millisecond;second;minute;hour;day;month;year}class RT extends oy{}class uE extends RT{millisecond=new Ii("millisecond",0,999,void 0);second=new Ii("second",0,59,this.millisecond);minute=new Ii("minute",0,59,this.second);hour=new Ii("hour",0,23,this.minute);day=new Ii("day",1,31,this.hour);month=new Ii("month",1,12,this.day);year=new Ii("year",0,9999,this.month)}const dt=new uE;class pE extends dE{constructor(e=1,t=12){super("month",e,t)}}class ch extends Ii{static Month28=new ch(28);static Month29=new ch(29);static ThirtyDays=new ch(30);static ThirtyOneDays=new ch(31);constructor(e,t=new pE(1,e)){super("month",1,e,dt.day,t)}static create(e,t){switch(e){case 1:case 3:case 5:case 7:case 8:case 10:case 12:return this.ThirtyOneDays;case 2:return t%4===0?this.Month29:this.Month28;case 4:case 6:case 9:case 11:return this.ThirtyDays;default:throw new hr("Unsupported month",e,t)}}}class La{static instance=new La;render(e){return e.value.toString()}}class xn{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 Jm(`${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=La.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Ne{static#e=new Map;static register(e,t){Ne.#e.set(e,t)}static get(e){const t=Ne.#e.get(e);if(!t)throw new hr(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class Kh extends xn{constructor(e=new Date().getFullYear(),t=dt.year){super(e,t)}static fromString(e,t=Ne.get(Kh)){return new Kh(t.parse(e))}}class Wa extends La{static default=new Wa("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class Xh extends xn{constructor(e=new Date().getMonth()+1,t=dt.month){super(e,t)}static fromString(e,t=Ne.get(Xh)){return new Xh(t.parse(e))}toString(e=Wa.default){return super.toString(e)}}class Yh extends xn{constructor(e=new Date().getDate(),t=dt.day){super(e,t)}static fromString(e,t=Ne.get(Yh)){const i=t.parse(e);return new Yh(i)}toString(e=Wa.default){return super.toString(e)}}class qh extends xn{constructor(e=new Date().getHours(),t=dt.hour){super(e,t)}static fromString(e,t=Ne.get(qh)){return new qh(t.parse(e))}toString(e=Wa.default){return super.toString(e)}}class jh extends xn{constructor(e=new Date().getMinutes(),t=dt.minute){super(e,t)}static fromString(e,t=Ne.get(jh)){return new jh(t.parse(e))}toString(e=Wa.default){return super.toString(e)}}class Zh extends xn{constructor(e=new Date().getSeconds(),t=dt.second){super(e,t)}static fromString(e,t=Ne.get(Zh)){return new Zh(t.parse(e),dt.second)}toString(e=Wa.default){return super.toString(e)}}class Il extends xn{static renderer=new Wa("0",3);constructor(e,t=dt.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=Il.renderer){return super.toString(e)}}class kT{render(e){return e.toString()}}class CT extends kT{render(e){const t=e.value,i=Math.abs(t),s=Math.floor(i/60),n=i%60;if(s===0&&n===0)return"Z";{const r=t<0?"-":"+",a=s.toString().padStart(2,"0"),o=n>0?":"+n.toString().padEnd(2,"0"):"";return r+a+o}}}class wl{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=Ne.get(wl),i=void 0){const s=t.parse(e,i);return new wl(s)}toString(e=new CT){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class gn{static timeshift(e,t){return e+(gn.isDaylight(t)?60:0)}static isDaylight(e){const{year:t,month:i,day:s}=e,n=e.hour??12;if(![t,i,s].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=gn.rule(t);if(!r)return!1;const a=gn.rank(i,s,n);return a>=gn.rank(r.start.month,r.start.day,2)&&a<gn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:gn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:gn.sunday(e,3,2)},end:{month:11,day:gn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:gn.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:gn.sunday(e,4,-1)},end:t}}static sunday(e,t,i){const s=new Date(Date.UTC(2e3,t-1,1));s.setUTCFullYear(e);const n=1+(7-s.getUTCDay())%7;if(i>0)return n+7*(i-1);const r=[31,gn.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let a=n;for(;a+7<=r;)a+=7;return a}static isLeap(e){return e%4===0&&(e%100!==0||e%400===0)}static rank(e,t,i){return(e*100+t)*100+i}}const LT={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},OT={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},PT={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},NT={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},FT={name:"PT",timeshift:c=>gn.timeshift(-480,c),title:"Pacific Time (US)"},UT={name:"MT",timeshift:c=>gn.timeshift(-420,c),title:"Mountain Time (US)"},zT={name:"CT",timeshift:c=>gn.timeshift(-360,c),title:"Central Time (US)"},BT={name:"ET",timeshift:c=>gn.timeshift(-300,c),title:"Eastern Time (US)"},HT={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},GT={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},VT={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},WT={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},$T={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},KT={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},XT={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},YT={name:"Z",timeshift:"Z",title:"UTC"},qT={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},jT={name:"BST",timeshift:"+01",title:"British Summer Time"},ZT={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},JT={name:"CET",timeshift:"+01",title:"Central European Time"},QT={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},e3={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},t3={name:"BJT",timeshift:"+08",title:"Beijing Time"},i3={name:"CST",timeshift:"-06",title:"Central Standard Time"},s3={name:"JST",timeshift:"+09",title:"Japan Standard Time"},n3={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},r3={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},a3={name:"LST",timeshift:"?",title:"Local Sideral Time"},T1=[KT,n3,$T,t3,jT,i3,GT,JT,ZT,zT,HT,WT,VT,BT,qT,e3,s3,a3,PT,QT,NT,UT,r3,OT,LT,FT,XT,YT];class Qm{static instance=new Qm;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 s=t.join("-"),n=e.timeshift?e.timeshift.toString():"",r=i.join(":")+n;return s+(r.length>0?"T"+r:"")}}class zl extends hr{constructor(e="method is abstract"){super(e)}}class ly{units;constructor(e){this.units=e}newYear(e){throw new zl}newMonth(e){throw new zl}newDay(e){throw new zl}newHour(e){throw new zl}newMinute(e){throw new zl}newSecond(e){throw new zl}}class o3 extends oy{millisecond=new Ii("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new Ii("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Ii("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new Ii("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new Ii("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new Ii("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new Ii("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const up=new o3;class e0{static instance=new e0;render(e){const t=sa.toSpec(e);let i="P";const s=t.years;s&&(i+=s.toString()+"Y");const n=t.months;n&&(i+=n.toString(La.instance)+"MM");const r=t.days;r&&(i+=r.toString(La.instance)+"D");const a=t.hours;a&&(i+=a.toString(La.instance)+"H");const o=t.minutes;o&&(i+=o.toString(La.instance)+"M");const l=t.seconds;return l&&(i+=l.toString(La.instance)+"S"),i}}class sa extends xn{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*dt.year.duration:0)+(e.months?e.months*dt.month.duration:0)+(e.days?e.days*dt.day.duration:0)+(e.hours?e.hours*dt.hour.duration:0)+(e.minutes?e.minutes*dt.minute.duration:0)+(e.seconds?e.seconds*dt.second.duration:0)},new Ii("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=c3){let i=typeof e=="number"?e:e.value;const s=i>0?1:-1;i=Math.abs(i);const n={},r=i/dt.year.duration,a=Math.floor(r);a>0&&(n.years=t.newYear(s*a),i-=a*dt.year.duration);const o=i/dt.month.duration,l=Math.floor(o);l>0&&(n.months=t.newMonth(s*l),i-=l*dt.month.duration);const h=i/dt.day.duration,d=Math.floor(h);d>0&&(n.days=t.newDay(s*d),i-=d*dt.day.duration);const u=i/dt.hour.duration,p=Math.floor(u);p>0&&(n.hours=t.newHour(s*p),i-=p*dt.hour.duration);const f=i/dt.minute.duration,m=Math.floor(f);m>0&&(n.minutes=t.newMinute(s*m),i-=m*dt.minute.duration);const v=i/dt.second.duration,g=Math.floor(s*v);return g>0&&(n.seconds=t.newSecond(g)),n}static fromString(e,t=Ne.get(sa)){return new sa(t.parse(e))}static between(e,t){const i=t.getTime(),s=e.getTime();return new sa(i-s)}toSpec(){return sa.toSpec(this)}toString(e=e0.instance){return e.render(this)}}class fE extends ly{constructor(e){super(e)}newYear(e){return new Kh(e,this.units.year)}newMonth(e){return new Xh(e,this.units.month)}newDay(e){return new Yh(e,this.units.day)}newHour(e){return new qh(e,this.units.hour)}newMinute(e){return new jh(e,this.units.minute)}newSecond(e){return new Zh(e,this.units.second)}newMillisecond(e){return new Il(e,this.units.millisecond)}newTimeshift(e){return new wl(typeof e=="number"?e:e.value)}}const l3=new fE(dt),c3=new fE(up);class Xs{#e;#t;#i;#s;#n;#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:Xs.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 xn?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 xn?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 xn?e:this.factory.newDay(e)}get hour(){return this.#s}set hour(e){const t=typeof e=="number";this.#s&&t?this.#s.value=e:this.#s=t?this.factory.newHour(e):!e||e.start||e instanceof xn?e:this.factory.newHour(e)}get minute(){return this.#n}set minute(e){const t=typeof e=="number";this.#n&&t?this.#n.value=e:this.#n=t?this.factory.newMinute(e):!e||e.start||e instanceof xn?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 xn?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 xn)?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 wl)?this.factory.newTimeshift(e):e}get factory(){return l3}static fromString(e,t=Ne.get(Xs)){const{year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:l,timeshift:h}=t.parse(e);return new Xs({year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:l,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new Xs({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Xs.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Xs.fromString(i)}#l(e){if(this.constructor.name!==e.constructor.name)throw new Jm(`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 sa(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 Xs(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=Qm.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 s=this.day?.toSpec();s&&(e.day=s);const n=this.hour?.toSpec();n&&(e.hour=n);const r=this.minute?.toSpec();r&&(e.minute=r);const a=this.second?.toSpec();a&&(e.second=a);const o=this.millisecond?.toSpec();o&&(e.millisecond=o);const l=this.timeshift?.toSpec();return l&&(e.timeshift=l),e}toJSON(){return this.toSpec()}}class cy{static instance=new cy;render(e){return(e.start?e.start.toString():"")+"/"+(e.end?e.end.toString():"")}}class Eu{constructor(e,t){this.start=e,this.end=t}_start;get start(){return this._start}set start(e){if(typeof e=="string"&&(e=Xs.fromString(e)),e&&!(e instanceof Xs)&&!(e instanceof sa))throw new hr("Interval start is not a level 0 date or duration: "+e);this._start=e}_end;get end(){return this._end}set end(e){if(typeof e=="string"&&(e=Xs.fromString(e)),e&&!(e instanceof Xs)&&!(e instanceof sa))throw new hr("Interval end is not a level 0 date or duration: "+e);this._end=e}static fromString(e,t=Ne.get(Eu)){const{start:i,end:s}=t.parse(e);return new Eu(i,s)}toString(e=cy.instance){return e.render(this)}[Symbol.iterator](){let e=this.start;return{next:()=>{const t={done:e>this.end,value:e};return e++,t}}}}class pp extends La{static instance=new pp(Wa.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 Ha extends xn{#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=pp.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class mE extends uE{year=new Ii("year",-9999,9999,this.month);yearExtended=new Ii("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const kf=new mE;class sl extends Ha{constructor(e,t=kf.year){super(e,t)}static fromString(e,t=kf.year,i=Ne.get(sl)){const s=i.parse(e),n=s.value.start;if(e.startsWith("Y")&&(t=kf.yearExtended),n!==void 0){const r=new sl(Object.assign({...s},{value:Math.max(n,t.min)})),a=new sl(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new sl(s,t)}}class gE extends Jm{monthValidator=new pE;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class nl extends Ha{constructor(e,t=new Ii(dt.month.name,1,24,dt.day,new gE)){super(e,t)}static fromString(e,t=Ne.get(nl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=dt.month;const r=new nl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new nl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new nl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class rl extends Ha{constructor(e,t=dt.day){super(e,t)}static fromString(e,t=Ne.get(rl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=dt.day;const r=new rl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new rl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new rl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class al extends Ha{constructor(e,t=dt.hour){super(e,t)}static fromString(e,t=Ne.get(al)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=dt.hour;const r=new al(Object.assign({...i},{value:Math.max(s,n.min)})),a=new al(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new al(i)}}class ol extends Ha{constructor(e,t=dt.minute){super(e,t)}static fromString(e,t=Ne.get(ol)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=dt.minute,r=new ol(Object.assign({...i},{value:Math.max(s,n.min)})),a=new ol(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new ol(i)}toString(e=pp.instance){return super.toString(e)}}class ll extends Ha{constructor(e,t=dt.second){super(e,t)}static fromString(e,t=Ne.get(ll)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=dt.second,r=new ll(Object.assign({...i},{value:Math.max(s,n.min)})),a=new ll(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new ll(i)}}class vc extends wl{static fromString(e,t=Ne.get(vc),i=void 0){return new vc(t.parse(e,i))}}class vE extends ly{constructor(e){super(e)}newYear(e){return new sl(e,this.units.year)}newMonth(e){return new nl(e,this.units.month)}newDay(e){return new rl(e,this.units.day)}newHour(e){return new al(e,this.units.hour)}newMinute(e){return new ol(e,this.units.minute)}newSecond(e){return new ll(e,this.units.second)}newMillisecond(e){return new Il(e,this.units.millisecond)}newTimeshift(e){return new vc(typeof e=="number"?e:e.value)}}const h3=new vE(kf),d3=new vE(up);class rr extends Xs{constructor(e){super(e)}get factory(){return h3}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 rr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Xs.timeshiftOf(e)})}static fromString(e,t=Ne.get(rr)){const i=t.parse(e);return new rr(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return rr.fromString(i)}clone(){return new rr(this.toSpec())}}const Os=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class t0 extends e0{static instance=new t0;render(e){return super.render(e)}}class ks extends Ha{constructor(e){super(typeof e=="number"||e.hasOwnProperty("value")?e:{value:ks.getValue(e,Os.year)+ks.getValue(e,Os.month)+ks.getValue(e,Os.day)+ks.getValue(e,Os.hour)+ks.getValue(e,Os.minute)+ks.getValue(e,Os.second),uncertain:ks.getBoolean(e,Os.uncertain),approximate:ks.getBoolean(e,"approximate")},up.millisecond)}static getBoolean(e,t){return e[t]||e[Os.year+"s"]?.[t]||e[Os.month+"s"]?.[t]||e[Os.day+"s"]?.[t]||e[Os.hour+"s"]?.[t]||e[Os.minute+"s"]?.[t]||e[Os.second+"s"]?.[t]||!1}static getValue(e,t){let i=0,s=e[t+"s"];if(s instanceof Ha?s=s.value:typeof e=="number"&&(s=e),s){const n=dt[t];i=s*n.duration}return i}static toSpec(e,t=d3){return{...sa.toSpec(e,t),uncertain:e.uncertain||!1,approximate:e.approximate||!1}}static fromString(e,t=Ne.get(ks)){const i=t.parse(e);return new ks(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new ks(i-s)}toString(e=t0.instance){return super.toString(e)}toSpec(){return ks.toSpec(this)}}class Au extends Eu{constructor(e,t){super(e,t)}get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=rr.fromString(e)),e&&!(e instanceof rr)&&!(e instanceof ks))throw new hr("Interval start is not a level 1 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=rr.fromString(e)),e&&!(e instanceof rr)&&!(e instanceof ks))throw new hr("Interval end is not a level 1 date or duration: "+e);this._end=e}static fromString(e,t=Ne.get(Au)){const{start:i,end:s}=t.parse(e);return new Au(i,s)}}class pd extends Ha{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 u3 extends mE{year=new Ii("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const xv=new u3;class ho extends pd{constructor(e,t=xv.year){super(e,t)}static fromString(e,t=xv.year,i=Ne.get(ho)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new ho(Object.assign({...s},{value:Math.max(n,t.min)})),a=new ho(Object.assign({...s},{value:Math.min(s.value.end,t.max)})),o={start:r,end:a},l=s.value.estimate;return l&&(o.estimate=l),o}else return new ho(s)}}class p3 extends gE{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 uo extends pd{constructor(e,t=new Ii(dt.month.name,1,41,dt.day,new p3)){super(e,t)}static fromString(e,t=Ne.get(uo)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=dt.month,r=new uo(Object.assign({...i},{value:Math.max(s,n.min)})),a=new uo(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new uo(i)}toString(e){return super.toString(e).padStart(2,"0")}}class po extends pd{constructor(e,t=dt.day){super(e,t)}static fromString(e,t=Ne.get(po)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=dt.day,r=new po(Object.assign({...i},{value:Math.max(s,n.min)})),a=new po(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new po(i)}toString(e){return super.toString(e).padStart(2,"0")}}class fo extends pd{constructor(e,t=dt.hour){super(e,t)}static fromString(e,t=Ne.get(fo)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=dt.hour,r=new fo(Object.assign({...i},{value:Math.max(s,n.min)})),a=new fo(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new fo(i)}}class mo extends pd{constructor(e,t=dt.minute){super(e,t)}static fromString(e,t=Ne.get(mo)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=dt.minute,r=new mo(Object.assign({...i},{value:Math.max(s,n.min)})),a=new mo(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new mo(i)}}class go extends pd{constructor(e,t=dt.second){super(e,t)}static fromString(e,t=dt.second,i=Ne.get(go)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new go(Object.assign({...s},{value:Math.max(n,t.min)})),a=new go(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new go(s,t)}}class bE extends vc{}class f3 extends pp{qualifier(){return""}}class Wo extends Qm{static instance=new Wo;static valueRenderer=new f3(Wa.default);static names=["year","month","day","hour","minute","second"];static qualifier(e,t){return e?t?"%":"?":t?"~":""}renderComponent(e,t){const i=e[t],s=Wo.names.slice(Wo.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),n=Wo.qualifier(i.uncertainComponent,i.approximateComponent),r=Wo.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!s.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!s.some(a=>a.approximate));return n+i.toString(Wo.valueRenderer)+r}}class yE extends ly{constructor(e){super(e)}newYear(e){return new ho(e,this.units.year)}newMonth(e){return new uo(e,this.units.month)}newDay(e){return new po(e,this.units.day)}newHour(e){return new fo(e,this.units.hour)}newMinute(e){return new mo(e,this.units.minute)}newSecond(e){return new go(e,this.units.second)}newMillisecond(e){return new Il(e,this.units.millisecond)}newTimeshift(e){return new bE(typeof e=="number"?e:e.value)}}const m3=new yE(xv),g3=new yE(up);class Gn extends rr{constructor(e){super(e)}toString(e=Wo.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 m3}static fromDate(e){return new Gn({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Xs.timeshiftOf(e)})}static fromString(e,t=Ne.get(Gn)){const i=t.parse(e);return new Gn(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Gn.fromString(i)}clone(){return new Gn(this.toSpec())}}class Io{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new hr(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new zl(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class hh extends t0{static instance=new hh;static designators=[["years","Y"],["months","MM"],["days","D"],["hours","H"],["minutes","M"],["seconds","S"]];static qualifier(e,t){return e?t?"%":"?":t?"~":""}render(e){const t=hh.qualifier(e.uncertainDuration,e.approximateDuration);if(!e.hasQualifiedComponent)return t+super.render(e);let i=t+"P";for(const[s,n]of hh.designators){const r=e.components[s];r&&(i+=hh.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+n)}return i}}class Rs extends ks{#e;constructor(e){if(super(typeof e=="number"?e:{value:Rs.valueFromSpec(e),uncertain:e.uncertain===!0,approximate:e.approximate===!0},up.millisecond),typeof e!="number"){const t={};for(const i of Rs.componentNames)e[i]instanceof Ha&&(t[i]=e[i]);Object.keys(t).length>0&&(this.#e=t)}}static componentNames=["years","months","days","hours","minutes","seconds"];get components(){return this.#e}#t(e){return this.#e?Object.values(this.#e).some(t=>t[e]):!1}get uncertainDuration(){return super.uncertain}get approximateDuration(){return super.approximate}get uncertain(){return super.uncertain||this.#t("uncertain")}set uncertain(e){super.uncertain=e}get approximate(){return super.approximate||this.#t("approximate")}set approximate(e){super.approximate=e}get hasQualifiedComponent(){return this.#e?Object.values(this.#e).some(e=>e.uncertainComponent||e.approximateComponent):!1}static valueFromSpec(e){return Rs.getValue(e,Os.year)+Rs.getValue(e,Os.month)+Rs.getValue(e,Os.day)+Rs.getValue(e,Os.hour)+Rs.getValue(e,Os.minute)+Rs.getValue(e,Os.second)}static toSpec(e,t=g3){const i=ks.toSpec(e,t);if(e instanceof Rs&&e.hasQualifiedComponent)for(const s of Rs.componentNames)delete i[s],e.components[s]&&(i[s]=e.components[s]);return i}static fromString(e,t=Ne.get(Rs)){const i=t.parse(e);return new Rs(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new Rs(i-s)}toSpec(){return Rs.toSpec(this)}toString(e=hh.instance){return super.toString(e)}}class Tu extends Au{get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=Gn.fromString(e)),e&&!(e instanceof Gn)&&!(e instanceof Rs))throw new hr("Interval start is not a level 2 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=Gn.fromString(e)),e&&!(e instanceof Gn)&&!(e instanceof Rs))throw new hr("Interval end is not a level 2 date or duration: "+e);this._end=e}static fromString(e,t=Ne.get(Tu)){const{start:i,end:s}=t.parse(e);return new Tu(i,s)}}class jf extends Set{constructor(e,t){super(e),this.exclusive=t}has(e){const t=e.toString().replace("..","/");for(const i of this)if(i.toString()===t)return!0;return!1}static fromString(e,t=Ne.get(jf)){const{exclusive:i,values:s}=t.parse(e);return new jf(s,i)}}class _o extends Io{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return _o.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new hr(`${this.name} cannot be negative`);return super.parse(e)}}class U{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 U.optional(U.group(e,...t))}static optionalNonCapturingGroup(...e){return U.optional(U.nonCapturingGroup(...e))}static numberGroup(e,t,i,s="\\d"){return U.group(e,`${i||""}[${s}]${t}`)}}const I1="yearValue";class Iu extends _o{static format(e=""){return U.numberGroup(U.groupName(e,I1),"{4}",void 0)}constructor(){super(I1,Iu.format())}}const _1="monthValue";class _u extends _o{static format(e=""){return U.numberGroup(U.groupName(e,_1),"{1,2}",void 0)}constructor(){super(_1,_u.format())}}const D1="dayValue";class Ih extends _o{static format(e=""){return U.numberGroup(U.groupName(e,D1),"{1,2}",void 0)}constructor(){super(D1,Ih.format())}}const R1="hourValue";class _h extends _o{static format(e=""){return U.numberGroup(U.groupName(e,R1),"{1,2}",void 0)}constructor(){super(R1,_h.format())}}const k1="minuteValue";class Du extends _o{static format(e=""){return U.numberGroup(U.groupName(e,k1),"{1,2}",void 0)}constructor(){super(k1,Du.format())}}const C1="secondValue";class Ru extends _o{static format(e=""){return U.numberGroup(U.groupName(e,C1),"{1,2}",void 0)}constructor(){super(C1,Ru.format())}}const L1="timeshiftValue",O1="shiftHour",P1="shiftMinute";class Jh extends Io{static format(e=""){return T1.map(t=>t.name).join("|")+"|"+U.nonCapturingGroup(U.group(e+O1,U.numberGroup(U.groupName(e,L1),"{2}","[+-]")),U.optionalNonCapturingGroup(":?",U.numberGroup(U.groupName(e,P1),"{2}",void 0)))}constructor(){super(L1,Jh.format())}parse(e,t){let i=0;const s=T1.find(n=>n.name===e);if(s){if(typeof s.timeshift=="function")try{return s.timeshift(t??{})}catch(n){throw new hr(`The time zone ${e} depends on the date: ${n.message}`)}e=s.timeshift}if(e!=="Z"){const n=this.regexGroups(e),r=n[O1];r&&(i+=parseInt(r,10)*60);const a=n[P1];a&&(i+=parseInt(a,10))}return i}}const N1="year",F1="month",U1="day",z1="hour",B1="minute",H1="second",G1="millisecond",V1="timeshift";class Yl extends Io{static format(e=""){return U.group(U.groupName(e,N1),Iu.format(e))+U.optionalNonCapturingGroup("-",U.group(U.groupName(e,F1),_u.format(e)),U.optionalNonCapturingGroup("-",U.group(U.groupName(e,U1),Ih.format(e)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(e,z1),_h.format(e)),":?",U.group(U.groupName(e,B1),Du.format(e)),U.optionalNonCapturingGroup(":",U.group(U.groupName(e,H1),Ru.format(e)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(e,G1),"\\d+"))),"\\s*",U.optionalGroup(U.groupName(e,V1),Jh.format(e)))))}constructor(){super("date",Yl.format())}parse(e){const t=this.regexGroups(e),i=t[N1],s=t[F1],n=t[U1],r=t[z1],a=t[B1],o=t[H1],l=t[G1],h=t[V1],d=i?new Kh(Iu.read(i)):void 0,u=s?_u.read(s):void 0;return{year:d,month:u?new Xh(u,ch.create(u.value,d?.value)):void 0,day:n?new Yh(Ih.read(n)):void 0,hour:r?new qh(_h.read(r)):void 0,minute:a?new jh(Du.read(a)):void 0,second:o?new Zh(Ru.read(o)):void 0,millisecond:l?Il.parseFraction(l):void 0,timeshift:h?wl.fromString(h,new Jh,{year:d?.value,month:u?.value,day:n?Ih.read(n).value:void 0,hour:r?_h.read(r).value:void 0}):void 0}}}const W1="years",I0="months",v3="days",$1="hours",K1="minutes",X1="seconds";class hy extends Io{static format(e=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,W1),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,I0),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,v3),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,$1),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,K1),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,X1),"+",void 0,"\\d"),"S")}constructor(){super("duration",hy.format())}parseGroups(e){return{years:e[W1],months:e[I0],days:e[I0],hours:e[$1],minutes:e[K1],seconds:e[X1]}}}const _0="start",D0="end";class dy extends Io{static format=U.group(_0,Yl.format(_0))+"/"+U.group(D0,Yl.format(D0));constructor(){super("interval",dy.format)}parse(e){const t=this.regexGroups(e),i=t[_0],s=t[D0];return{start:i?Xs.fromString(i,new Yl):void 0,end:s?Xs.fromString(s,new Yl):void 0}}}class Gi extends _o{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Gi.uncertainGroup+Gi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return U.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(U.groupName(Gi.uncertainGroup,e),"?")+this.qualifierFormat(U.groupName(Gi.approximateGroup,e),"~")+this.qualifierFormat(U.groupName(Gi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return U.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 s=0,n;for(n=0;n<t.length;n++){const l=t[n];if(l==="X")break;s=s*10+parseInt(l,10)}if(n<t.length){let l=1;for(let u=0;u<t.length-n;u++)l*=10;const h=i*s*l,d=h+l-1;s={start:h,end:d}}else s*=i;const r=e[U.groupName(Gi.uncertainAndApproximateGroup,this.name)],a=e[U.groupName(Gi.approximateGroup,this.name)]||r,o=e[U.groupName(Gi.uncertainGroup,this.name)]||r;return{value:s,approximate:a?!!a:!1,uncertain:o?!!o:!1}}}const Y1="yearValue";class ku extends Gi{constructor(){super(Y1,ku.format())}static format(e=""){return"Y?"+Gi.numberFormat(U.groupName(e,Y1),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const q1="monthValue";class Cu extends Gi{static format(e=""){return Gi.numberFormat(U.groupName(e,q1),"{1,2}",void 0)}constructor(){super(q1,Cu.format())}}const j1="dayValue";class Lu extends Gi{static format(e=""){return Gi.numberFormat(U.groupName(e,j1),"{1,2}",void 0)}constructor(){super(j1,Lu.format())}}const Z1="hourValue";class Ou extends Gi{static format(e=""){return Gi.numberFormat(U.groupName(e,Z1),"{1,2}",void 0)}constructor(){super(Z1,Ou.format())}}const J1="minuteValue";class Pu extends Gi{static format(e=""){return Gi.numberFormat(U.groupName(e,J1),"{1,2}",void 0)}constructor(){super(J1,Pu.format())}}const Q1="secondValue";class Nu extends Gi{static format(e=""){return Gi.numberFormat(U.groupName(e,Q1),"{1,2}",void 0)}constructor(){super(Q1,Nu.format())}}class Fu extends Jh{}class Zi extends Io{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=Zi.format()){super("date",e)}static format(e=""){return U.group(U.groupName(e,Zi.yearGroup),ku.format(e))+U.optionalNonCapturingGroup("-",U.group(U.groupName(e,Zi.monthGroup),Cu.format(e)),U.optionalNonCapturingGroup("-",U.group(U.groupName(e,Zi.dayGroup),Lu.format(e)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(e,Zi.hourGroup),Ou.format(e)),":",U.group(U.groupName(e,Zi.minuteGroup),Pu.format(e)),U.optionalNonCapturingGroup(":",U.group(U.groupName(e,Zi.secondGroup),Nu.format(e)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(e,Zi.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(e,Zi.timeshiftGroup),Fu.format(e)))))}parseGroups(e){const t=e[Zi.millisecondGroup],i=t?Il.parseFraction(t):void 0,s=e[Zi.secondGroup],n=s?ll.fromString(s,new Nu):void 0,r=e[Zi.minuteGroup];let a;r&&(a=ol.fromString(r,new Pu),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[Zi.hourGroup];let l;o&&(l=al.fromString(o,new Ou),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=e[Zi.dayGroup];let d;h&&(d=rl.fromString(h,new Lu),d.uncertain=d.uncertain||l?.uncertain||!1,d.approximate=d.approximate||l?.approximate||!1);const u=e[Zi.monthGroup];let p;u&&(p=nl.fromString(u,new Cu),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[Zi.yearGroup];let m;f&&(m=sl.fromString(f,void 0,new ku),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const v=e[Zi.timeshiftGroup],g=v?vc.fromString(v,new Fu,{year:m?.value,month:p?.value,day:d?.value,hour:l?.value}):void 0;return{year:m,month:p,day:d,hour:l,minute:a,second:n,millisecond:i,timeshift:g}}}const ew="years",tw="months",iw="days",sw="hours",nw="minutes",rw="seconds";class ql extends Gi{static format(e=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,ew),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,tw),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,iw),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,sw),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,nw),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,rw),"+",void 0,"\\d"),"S")+this.formatSuffix(e)}constructor(){super("duration",ql.format())}parseGroups(e){return{years:e[ew],months:e[tw],days:e[iw],hours:e[sw],minutes:e[nw],seconds:e[rw],uncertain:!!e[Gi.uncertainGroup],approximate:!!e[Gi.approximateGroup]}}}const b3="dates",R0="start",k0="end",aw="durations",C0="durationMin",L0="durationMax";class uy extends Io{static format=U.group(b3,U.optionalGroup(R0,U.group("openStart","\\.\\.")+"|"+Zi.format(R0))+"/"+U.optionalGroup(k0,U.group("openEnd","\\.\\.")+"|"+Zi.format(k0)))+"|"+U.group(aw,U.group(C0,ql.format(C0))+"/"+U.group(L0,ql.format(L0)));constructor(e="interval",t=uy.format){super(e,t)}parseGroups(e){let t,i;if(e[aw]){const n=e[C0];t=ks.fromString(n,new ql);const r=e[L0];i=ks.fromString(r,new ql)}else{const n=e[R0];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=rr.fromString(n,new Zi)}const r=e[k0];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=rr.fromString(r,new Zi)}}return{start:t,end:i}}}class ei extends Gi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=ei.uncertainGroup+ei.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(U.groupName(ei.uncertainGroup,e),"?")+this.qualifierFormat(U.groupName(ei.approximateGroup,e),"~")+this.qualifierFormat(U.groupName(ei.uncertainAndApproximateGroup,e),"%")+Gi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[U.groupName(ei.uncertainAndApproximateGroup,this.name)];return(e[U.groupName(ei.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[U.groupName(ei.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const yd="yearValue",ow="exp",lw="signif";class Uu extends ei{constructor(){super(yd,Uu.format())}static format(e=""){return"Y?"+U.nonCapturingGroup(U.group(U.groupName(e,ow),"[-]?\\d+E\\d+")+"|"+ei.numberFormat(U.groupName(e,yd),"+","[-]?")+U.optionalGroup(U.groupName(e,lw),"S\\d+"))}parseGroups(e){const t=e[ow];if(t){const r=t.indexOf("E"),a=parseInt(t.substring(r+1),10),l=parseInt(t.substring(0,r),10)*Math.pow(10,a);e[yd]=l.toString()}const i=e[lw],s=e[yd];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:o}=this.getValueAndSign(e);let l="";for(let h=0;h<a.length;h++)l+=h<r?a.charAt(h):"X";e[yd]=(o<0?"-":"")+l}const n=super.parseGroups(e);return i&&(n.value.estimate=parseInt(s,10)),n}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const cw="monthValue";class zu extends ei{static format(e=""){return ei.numberFormat(U.groupName(e,cw),"{1,2}",void 0)}constructor(){super(cw,zu.format())}}const hw="dayValue";class Bu extends ei{static format(e=""){return ei.numberFormat(U.groupName(e,hw),"{1,2}",void 0)}constructor(){super(hw,Bu.format())}}const dw="hourValue";class Hu extends ei{static format(e=""){return ei.numberFormat(U.groupName(e,dw),"{1,2}",void 0)}constructor(){super(dw,Hu.format())}}const uw="secondValue";class Gu extends ei{static format(e=""){return ei.numberFormat(U.groupName(e,uw),"{1,2}",void 0)}constructor(){super(uw,Gu.format())}}const pw="minuteValue";class Vu extends ei{static format(e=""){return ei.numberFormat(U.groupName(e,pw),"{1,2}",void 0)}constructor(){super(pw,Vu.format())}}class y3 extends Fu{}class ni extends Io{static yearGroup=Zi.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",ni.format())}static format(e=""){return U.group(U.groupName(e,ni.yearGroup),Uu.format(e))+U.optionalNonCapturingGroup("-",U.group(U.groupName(e,ni.monthGroup),zu.format(e)),U.optionalNonCapturingGroup("-",U.group(U.groupName(e,ni.dayGroup),Bu.format(e)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(e,ni.hourGroup),Hu.format(e)),":",U.group(U.groupName(e,ni.minuteGroup),Vu.format(e)),U.optionalNonCapturingGroup(":",U.group(U.groupName(e,ni.secondGroup),Gu.format(e)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(e,ni.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(e,ni.timeshiftGroup),y3.format(e)))))}parseGroups(e){const t=e[ni.millisecondGroup],i=t?Il.parseFraction(t):void 0,s=e[ni.secondGroup];let n;s&&(n=go.fromString(s,void 0,new Gu),n.uncertain=n?.uncertain||!1,n.approximate=n?.approximate||!1);const r=e[ni.minuteGroup];let a;r&&(a=mo.fromString(r,new Vu),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[ni.hourGroup];let l;o&&(l=fo.fromString(o,new Hu),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=e[ni.dayGroup];let d;h&&(d=po.fromString(h,new Bu),d.uncertain=d.uncertain||l?.uncertain||!1,d.approximate=d.approximate||l?.approximate||!1);const u=e[ni.monthGroup];let p;u&&(p=uo.fromString(u,new zu),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ni.yearGroup];let m;f&&(m=ho.fromString(f,void 0,new Uu),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const v=e[ni.timeshiftGroup],g=v?bE.fromString(v,new Fu,{year:m?.value,month:p?.value,day:d?.value,hour:l?.value}):void 0;return{year:m,month:p,day:d,hour:l,minute:a,second:n,millisecond:i,timeshift:g}}}const fw="durationValue";class py extends ei{static format(e=""){return"^"+ei.numberFormat(U.groupName(e,fw),"+",void 0)}constructor(){super(fw,py.format())}}class w3 extends oy{millisecond=new Ii("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new Ii("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Ii("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new Ii("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new Ii("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new Ii("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new Ii("year",0,Number.MAX_SAFE_INTEGER,this.month)}const _c=new w3;class nt extends ei{static yearsGroup="years";static monthsGroup="months";static isoMonthsGroup="isoMonths";static daysGroup="days";static hoursGroup="hours";static minutesGroup="minutes";static secondsGroup="seconds";static durationGroup="duration";static suffixGroup="durationSuffix";static componentParser=new py;static componentFormat(e,t,i,s,n=""){const r=U.group(U.groupName(e,nt.quantityGroup(t)),ei.numberFormat(U.groupName(e,i),"+",void 0,"\\d"));return U.group(U.groupName(e,t),r,s,n)}static quantityGroup(e){return e+"Quantity"}static isoMonthsLookahead="(?=[?~%]?\\d+D|T)";constructor(){super("duration",nt.format())}static format(e=""){const t=U.groupName(e,nt.durationGroup);return this.qualifierFormat(U.groupName(ei.uncertainGroup,t),"?")+this.qualifierFormat(U.groupName(ei.approximateGroup,t),"~")+this.qualifierFormat(U.groupName(ei.uncertainAndApproximateGroup,t),"%")+"P"+U.optional(nt.componentFormat(e,nt.yearsGroup,ni.yearGroup,"Y"))+U.optionalNonCapturingGroup(nt.componentFormat(e,nt.monthsGroup,ni.monthGroup,"MM")+"|"+nt.componentFormat(e,nt.isoMonthsGroup,"isoMonth","M",nt.isoMonthsLookahead))+U.optional(nt.componentFormat(e,nt.daysGroup,ni.dayGroup,"D"))+"T?"+U.optional(nt.componentFormat(e,nt.hoursGroup,ni.hourGroup,"H"))+U.optional(nt.componentFormat(e,nt.minutesGroup,ni.minuteGroup,"M"))+U.optional(nt.componentFormat(e,nt.secondsGroup,ni.secondGroup,"S"))+U.optionalGroup(U.groupName(e,nt.suffixGroup),"[?~%]")}static parseComponent(e,t,i){const s=nt.componentParser.parse(e);return new t(s,i)}parseGroups(e){const t=e[nt.quantityGroup(nt.secondsGroup)];let i;t&&(i=nt.parseComponent(t,go,_c.second),i.uncertain=!!e[U.groupName(ei.uncertainGroup,nt.secondsGroup)]||!1,i.approximate=!!e[U.groupName(ei.approximateGroup,nt.secondsGroup)]||!1);const s=e[nt.quantityGroup(nt.minutesGroup)];let n;s&&(n=nt.parseComponent(s,mo,_c.minute),n.uncertain=n.uncertain||i?.uncertain||!1,n.approximate=n.approximate||i?.approximate||!1);const r=e[nt.quantityGroup(nt.hoursGroup)];let a;r&&(a=nt.parseComponent(r,fo,_c.hour),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[nt.quantityGroup(nt.daysGroup)];let l;o&&(l=nt.parseComponent(o,po,_c.day),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=e[nt.quantityGroup(nt.monthsGroup)]||e[nt.quantityGroup(nt.isoMonthsGroup)];let d;h&&(d=nt.parseComponent(h,uo,_c.month),d.uncertain=d.uncertain||l?.uncertain||!1,d.approximate=d.approximate||l?.approximate||!1);const u=e[nt.quantityGroup(nt.yearsGroup)];let p;u&&(p=nt.parseComponent(u,ho,_c.year),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[nt.suffixGroup],m=!!e[U.groupName(ei.uncertainAndApproximateGroup,nt.durationGroup)]||f==="%",v=m||!!e[U.groupName(ei.uncertainGroup,nt.durationGroup)]||f==="?",g=m||!!e[U.groupName(ei.approximateGroup,nt.durationGroup)]||f==="~";return{years:p,months:d,days:l,hours:a,minutes:n,seconds:i,uncertain:v,approximate:g}}}const M3="dates",O0="start",P0="end",mw="durations",N0="durationMin",F0="durationMax";class i0 extends Io{static format=U.group(M3,U.optionalGroup(O0,U.group("openStart","\\.\\.")+"|"+ni.format(O0))+"/"+U.optionalGroup(P0,U.group("openEnd","\\.\\.")+"|"+ni.format(P0)))+"|"+U.group(mw,U.group(N0,nt.format(N0))+"/"+U.group(F0,nt.format(F0)));constructor(e="interval",t=i0.format){super(e,t)}parseGroups(e){let t,i;if(e[mw]){const n=e[N0];t=Rs.fromString(n,new nt);const r=e[F0];i=Rs.fromString(r,new nt)}else{const n=e[O0];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=Gn.fromString(n,new ni)}const r=e[P0];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=Gn.fromString(r,new ni)}}return{start:t,end:i}}}class x3{parse(e){e=e.trim();const t=e.startsWith("["),s=e.substring(1,e.length-1).split(","),n=[];for(const r of s){let a;r.includes("..")?a=Tu.fromString(r.replace("..","/"),new i0):a=Gn.fromString(r,new ni),n.push(a)}return{values:n,exclusive:t}}}const wE=["spring","summer","autumn","winter"],Sv=21,S3=32,E3=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let A3;function T3(){return A3??=new ni}function Dc(c){return typeof c?.value=="number"?c.value:void 0}function Jd(c){const e=c.trim();if(/^\d{1,2}:/.test(e)){const r=E3.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=Gn.fromString(e,T3())}catch{return}const i=Dc(t.year),s=Dc(t.month),n=s!==void 0&&s>=Sv&&s<=S3;if(!(t.timeshift||i!==void 0&&Math.abs(i)>9999)&&!(s!==void 0&&s>12&&!n)&&!(n&&(t.day||t.hour)))return{year:i,month:n?void 0:s,...n?{season:wE[(s-Sv)%4]}:{},day:Dc(t.day),hour:Dc(t.hour),minute:Dc(t.minute),second:Dc(t.second),raw:e}}function cl(c){if(c.raw!==void 0)return c.raw;if(c.year===void 0){if(c.hour===void 0)return"";let t=`${String(c.hour).padStart(2,"0")}:${String(c.minute??0).padStart(2,"0")}`;return c.second!==void 0&&(t+=`:${String(c.second).padStart(2,"0")}`),t}let e=String(c.year).padStart(4,"0");return c.season!==void 0?`${e}-${Sv+wE.indexOf(c.season)}`:(c.month===void 0||(e+=`-${String(c.month).padStart(2,"0")}`,c.day===void 0)||(e+=`-${String(c.day).padStart(2,"0")}`,c.hour===void 0)||(e+=`T${String(c.hour).padStart(2,"0")}:${String(c.minute??0).padStart(2,"0")}`,c.second!==void 0&&(e+=`:${String(c.second).padStart(2,"0")}`)),e)}function Ev(c){if(c.year!==void 0)return Date.UTC(c.year,(c.month??1)-1,c.day??1,c.hour??0,c.minute??0,c.second??0)}function gw(c){return(((c.day??0)*24+(c.hour??0))*60+(c.minute??0))*6e4+(c.second??0)*1e3}const I3=["year","month","day","hour","minute"],_3=["day","hour","minute"];function vw(c,e){return e.filter(t=>c[t]!==void 0).join(",")}function Qh(c){if(c.durationSeconds!==void 0)return c.durationSeconds*1e3;const e=c.durationText===void 0?void 0:Nn.parse(c.durationText);if(e)return e.chosenSeconds*1e3;if(!c.time||!c.endTime)return;const t=c.time.year!==void 0&&c.endTime.year!==void 0,i=t?I3:_3,s=vw(c.time,i);if(!(s===""||s!==vw(c.endTime,i)))return t?Ev(c.endTime)-Ev(c.time):gw(c.endTime)-gw(c.time)}function D3(c){if(c.durationSeconds===void 0&&!(!c.time||!c.endTime))return Qh(c)===void 0?"imprecise":void 0}class s0{constructor(e,t,i,s,n,r,a,o,l=[],h,d,u,p=[],f=[],m=[],v=[]){this.event=e,this.timeline=t,this.observerTrack=i,this.weatherTrack=s,this.soundTrack=n,this.observer=r,this.id=a,this.weather=o,this.decor=l,this.weatherSource=h,this.instrumentId=d,this.exposureSeconds=u,this.milestones=p,this.references=f,this.roads=m,this.traces=v}provenance=Un.empty();loadIssues=[];account;sources;interpretation;variants=[];skyEvents;frozen;sway;lightPollution;observerMap;iso;metering;lens;vehicle;events;eventsExpansion;sampleMs;get observerCount(){return 1+this.decor.filter(e=>e.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return Qt.byId(this.instrumentId)}static create(e,t,i){return new s0({eventType:"sighting",time:e,place:t},new dp,new Mu,new xu,new Su,i)}}const R3=0,k3=0;function st(c,e){const t=c.observerTrack.getInterpolatedPoseAt(e);if(t)return t;const i=c.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:R3,headingDeg:void 0,pitchDeg:k3,fovDeg:Qt.fieldOfViewDeg(c.instrument)}}function fs(c,e){return c.weatherTrack.getInterpolatedWeatherAt(e)??c.weather??Zm}function wd(c,e){return c.weatherTrack.getActualWeatherAt(e)??c.weather??Zm}function fy(c,e){return c.soundTrack.getInterpolatedSoundAt(e)??DT}class Ui{static toCurrent(e){const t=e.version,i=typeof t=="object"&&t!==null&&"value"in t?t.value:t;if(i!==void 0&&i!==1&&i!==2)return e;const s=i===2?e:Ui.fromVersion1(e);return Ui.fromVersion2(s)}static observerIdOf(e){return e.observer?.id??"observer"}static fromVersion2(e){const t={...e,version:3},i={...e.timeline??{keyframes:[]}},s=new Set,n=i.keyframes??[];for(const h of n)for(const d of h.shapes??[])s.add(d.sourceId);const r=[],a=h=>{let d=h;for(let u=r.length+1;d===void 0||s.has(d);u++)d=`group-${u}`;return s.add(d),d},o=Array.isArray(i.groups)?i.groups:[];for(const h of o)Array.isArray(h)?r.push({id:a(),members:[...h]}):typeof h=="object"&&h!==null&&r.push(h);const l=Array.isArray(e.events)?e.events.map(h=>({...h})):void 0;if(l){const h=Ui.observerIdOf(e),d=l.filter(g=>g.who==="phenomenon"),u=new Set(s);for(const g of d){const b=Ui.unwrapped(g.params?.parts);if(g.eventType==="appearance"&&Array.isArray(b))for(const w of b)w.sourceId&&u.add(w.sourceId)}for(const g of u)s.add(g);const p=g=>r.find(b=>b.members.includes(g)),f=g=>{const b=p(g);return b?f(b.id):g},m=[...new Set([...u].map(f))],v=m.length===1?m[0]:m.length>1?a("phenomenon"):"phenomenon";m.length>1&&r.push({id:v,members:m});for(const g of l)if(g.who===void 0||g.who==="observer")g.who=h;else if(g.who==="phenomenon"){g.who=v;const b=g.params;if(g.eventType!=="blink"||!b||!Array.isArray(b.parts))continue;const w=b.parts,{parts:y,...M}=b;g.params=M,g.who=Ui.groupFor(w,r,a)??v}t.events=l}return(r.length>0||o.length>0)&&(t.timeline={...i,groups:r}),t}static groupFor(e,t,i){if(e.length===1)return e[0];const s=l=>{const h=t.find(d=>d.id===l);return h?h.members.flatMap(s):[l]},n=t.find(l=>{const h=s(l.id);return h.length===e.length&&e.every(d=>h.includes(d))});if(n)return n.id;const r=new Set(e.map(l=>t.find(h=>h.members.includes(l))));if(r.size!==1)return;const[a]=r,o=i();if(a){const l=a.members.findIndex(h=>e.includes(h));a.members=a.members.filter(h=>!e.includes(h)),a.members.splice(l,0,o)}return t.push({id:o,members:[...e]}),o}static unwrapped(e){return Ui.isWrapped(e)?e.value:e}static fromVersion1(e){const t={...e,version:2};for(const i of["time","endTime"])e[i]!==void 0&&(t[i]=Ui.edtf(e[i]));if(Array.isArray(e.place)){const i=Ui.place(e.place);i===void 0?delete t.place:t.place=i}return t}static edtf(e){if(Ui.isWrapped(e)){const l=Ui.edtf(e.value);return l===void 0?void 0:{...e,value:l}}if(typeof e=="string")return e;const t=e,i=Object.values(t).find(l=>Ui.isWrapped(l)),s=Object.fromEntries(Object.entries(t).map(([l,h])=>[l,Ui.isWrapped(h)?h.value:h])),n=cl(s);if(n==="")return;if(!i)return n;const{basis:r,rationale:a,how:o}=i;return{value:n,...r===void 0?{}:{basis:r},...a===void 0?{}:{rationale:a},...o===void 0?{}:{how:o}}}static place(e){if(e.length===0)return;const t=e.map(l=>Ui.isWrapped(l)?l.value:l),i=t.find(l=>l.name)?.name,s={...i?{name:i}:{},locations:t.map(({lat:l,lng:h})=>({lat:l,lng:h}))},n=e.find(l=>Ui.isWrapped(l));if(!n)return s;const{basis:r,rationale:a,how:o}=n;return{value:s,...r===void 0?{}:{basis:r},...a===void 0?{}:{rationale:a},...o===void 0?{}:{how:o}}}static isWrapped(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&"value"in e}}class Ee{static draw(e,t="none"){return`<svg class="icon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="${t}" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">${e}</svg>`}static TRASH=Ee.draw('<path d="M2.5 4.5h11"/><path d="M6 4.5V3h4v1.5"/><path d="M4 4.5l.7 9h6.6l.7-9"/><path d="M6.8 7v4.5M9.2 7v4.5"/>');static TARGET=Ee.draw('<circle cx="8" cy="8" r="5"/><circle cx="8" cy="8" r="1.6"/><path d="M8 1v2.2M8 12.8V15M1 8h2.2M12.8 8H15"/>');static PLAY=Ee.draw('<path d="M5 3.2v9.6L12.6 8z"/>',"currentColor");static PAUSE=Ee.draw('<path d="M5.5 3.5v9M10.5 3.5v9"/>');static RECORD=Ee.draw('<circle cx="8" cy="8" r="4.2" fill="var(--error, #d93025)" stroke="none"/>');static STOP=Ee.draw('<rect x="4" y="4" width="8" height="8" rx="1.2"/>',"currentColor");static PREVIOUS_MARK=Ee.draw('<path d="M6.5 4 2.5 8l4 4"/><path d="M11 5.2 13.8 8 11 10.8 8.2 8z"/>');static NEXT_MARK=Ee.draw('<path d="M9.5 4l4 4-4 4"/><path d="M5 5.2 7.8 8 5 10.8 2.2 8z"/>');static CLOSE=Ee.draw('<path d="M4 4l8 8M12 4l-8 8"/>');static PLUS=Ee.draw('<path d="M8 3v10M3 8h10"/>');static METEOR=Ee.draw('<path d="M2.5 2.5l7 7"/><path d="M5.5 2.5l5 5"/><circle cx="11.5" cy="11.5" r="2"/>');static COMET=Ee.draw('<circle cx="11" cy="11" r="2.4"/><path d="M9.3 9.3 2.5 2.5M9 11.2 3 7M11.2 9 7 3"/>');static STAR=Ee.draw('<path d="M8 2.2l1.7 3.6 3.9.5-2.9 2.7.8 3.9L8 11l-3.5 1.9.8-3.9-2.9-2.7 3.9-.5z"/>');static SATELLITE=Ee.draw('<rect x="6.3" y="6.3" width="3.4" height="3.4" transform="rotate(45 8 8)"/><path d="M5.4 5.4 3 3M10.6 10.6 13 13"/><path d="M1.8 4.2 4.2 1.8M11.8 14.2l2.4-2.4"/><path d="M10.5 3.5a3 3 0 0 1 2 2"/>');static FIREBALL=Ee.draw('<circle cx="10.5" cy="10.5" r="2.6"/><path d="M8.6 8.6 3 3M8 10.6 4.5 8.5M10.6 8 8.5 4.5"/>');static SUMMARY=Ee.draw('<rect x="3" y="2" width="10" height="12" rx="1.5"/><path d="M5.5 5.5h5M5.5 8h5M5.5 10.5h3"/>');static WITNESS=Ee.draw('<circle cx="8" cy="5" r="2.6"/><path d="M2.8 14c.6-3 2.6-4.6 5.2-4.6s4.6 1.6 5.2 4.6"/>');static LOCATION=Ee.draw('<path d="M8 14.3s4.5-4.3 4.5-7.8a4.5 4.5 0 0 0-9 0c0 3.5 4.5 7.8 4.5 7.8z"/><circle cx="8" cy="6.5" r="1.6"/>');static DATE=Ee.draw('<rect x="2.3" y="3.3" width="11.4" height="10.4" rx="1.5"/><path d="M2.3 6.6h11.4M5.3 1.8v2.8M10.7 1.8v2.8"/>');static ENVIRONMENT=Ee.draw('<path d="M1.5 14h13"/><path d="M2.8 14V8.3L6.3 5.5l3.5 2.8V14"/><path d="M12.2 14V9.4"/><circle cx="12.2" cy="7.4" r="2.1"/>');static SKY=Ee.draw('<path d="M4.6 12.5h7a2.6 2.6 0 0 0 .3-5.2 3.8 3.8 0 0 0-7.3-.6 2.9 2.9 0 0 0 0 5.8z"/>');static PHENOMENON=Ee.draw('<ellipse cx="8" cy="9" rx="6.3" ry="2.1"/><path d="M4.6 7.8a3.4 3.4 0 0 1 6.8 0"/><path d="M5 13.4l.6-1.4M11 13.4l-.6-1.4M8 14v-1.4"/>');static SOUND=Ee.draw('<path d="M2.5 6.2h2.3L8 3.5v9L4.8 9.8H2.5z"/><path d="M10.5 6a2.8 2.8 0 0 1 0 4M12.3 4.2a5.4 5.4 0 0 1 0 7.6"/>');static PICTURES=Ee.draw('<rect x="2" y="3" width="12" height="10" rx="1.5"/><circle cx="5.8" cy="6.4" r="1.2"/><path d="M2.5 12l3.8-3.6 2.4 2.2 2.2-1.8 2.6 2.5"/>');static FILES=Ee.draw('<path d="M4 1.8h5.2L12.5 5v9.2H4z"/><path d="M9 1.8V5.2h3.5"/>');static BY_GLYPH={"🗑":Ee.TRASH,"🎯":Ee.TARGET,"+":Ee.PLUS,"✕":Ee.CLOSE,"▶":Ee.PLAY,"⏸":Ee.PAUSE,"⏺":Ee.RECORD,"⏹":Ee.STOP};static show(e,t){if(e.dataset.icon===t&&e.firstChild)return;const i=Ee.BY_GLYPH[t];i?e.innerHTML=i:e.textContent=t,e.dataset.icon=t}static CSS=`
|
|
3
3
|
.icon { display: block; flex: none; }
|
|
4
4
|
button:has(> .icon:only-child) { display: inline-flex; align-items: center; justify-content: center; }
|
|
@@ -105,7 +105,7 @@ ${e} :is(select:not([multiple]):not([size]), .rr0-select) {
|
|
|
105
105
|
:where(${e}) :where(.icon-btn) { min-width: 36px; padding: 0; border-radius: 8px; }
|
|
106
106
|
:where(${e}) input[type="range"] { accent-color: var(--glow-solid); }
|
|
107
107
|
:where(${e}) input[type="checkbox"], :where(${e}) input[type="radio"] { accent-color: var(--glow-solid); }
|
|
108
|
-
`}}class Ns{static NAMES=["weather","place","lightPollution","decor"];static KEYS={weather:["weatherTrack","weatherSource"],place:["place"],lightPollution:["lightPollution"],decor:["decor"]};static annexName(e,t){return`${e}.${t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}.json`}static fromFile(e,t){return e?.[t]!==void 0&&e[t].live!==!0}}class ts{static NAMES=["relief","imagery","roads","water","railways","upperAir","map"];static TERRAIN=["relief","imagery","roads","water","railways"];static held(e,t){if(!e||e.live)return;const i=e[t];return i&&!i.live&&!i.refresh&&i.src!==void 0?i:void 0}static isLive(e,t){return e?.live===!0||e?.[t]?.live===!0}static annexName(e,t){const i=t==="relief"||t==="imagery"||t==="map"?"zip":"json",s=t.replace(/[A-Z]/g,n=>`-${n.toLowerCase()}`);return`${e}.${s}.${i}`}static isEmpty(e){return!e||!e.live&&ts.NAMES.every(t=>!e[t])&&Ns.NAMES.every(t=>!e[t])}}class Bl 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 na{static async recording(e){const t=await na.json(e);for(const i of Ns.NAMES){const s=t?.frozen?.[i];if(!(!s?.src||s.live))try{const n=Ui.toCurrent(await na.json(new URL(s.src,new URL(e,location.href)).href));for(const r of Ns.KEYS[i])n[r]!==void 0&&(t[r]=n[r])}catch{}}return t}static async json(e){const t=new URL(e,location.href);if(location.protocol==="https:"&&t.protocol==="http:")throw new Bl("mixed-content",e);let i;try{i=await fetch(e)}catch{throw await this.diagnose(e,t)}if(!i.ok)throw new Bl("status",e,i.status);try{return await i.json()}catch{throw new Bl("malformed",e)}}static async diagnose(e,t){if(t.origin===location.origin)return new Bl("unreachable",e);try{return await fetch(e,{mode:"no-cors"}),new Bl("cors",e)}catch{return new Bl("unreachable",e)}}}class Ea{static PACKAGE="@rr0/ufoathome";static CDN="https://cdn.jsdelivr.net/npm";static DIRECTORIES={"rr0-sighting":"dist-embed-sighting","rr0-sighting-editor":"dist-embed-sighting-editor"};static current(e,t,i){const s=new URL(`${e}.mjs`,t);return s.href.startsWith(`${Ea.CDN}/`)?`${i}/lib/${e}.mjs`:(s.pathname=s.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),s.href)}static VERSION_PARAMETER="v";static freezable(e){return e in Ea.DIRECTORIES}static frozenLink(e,t){const i=new URL(e);return i.searchParams.set(Ea.VERSION_PARAMETER,t),i.href}static frozen(e,t){return`${Ea.CDN}/${Ea.PACKAGE}@${t}/${Ea.DIRECTORIES[e]}/${e}.mjs`}}class ed{static PRODUCTION="https://ufoathome.org";static home(){try{const e=new URL(import.meta.url),t=new URL(location.href);return(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]"||t.hostname.endsWith(".localhost"))&&e.origin===t.origin?t.origin:ed.PRODUCTION}catch{return ed.PRODUCTION}}}const Av={share:"Share",close:"Close",link:"Link",embed:"Embed",copy:"Copy",copied:"Copied",freeze:"Freeze version {version}",freezeHint:"The embed keeps the rendering of this version of UFO@home, loaded from jsDelivr, and gets none of the later fixes. Unticked, it follows each release.",unsaved:"The link opens the file at its address: your unsaved changes are not in it. Save the file there first.",unavailable:"Only a file loaded from an address can be shared: put it online, then open it from its address."},C3=Object.freeze(Object.defineProperty({__proto__:null,shareMessages_en:Av},Symbol.toStringTag,{value:"Module"})),Wu=["en","fr","es","it"],L3={en:()=>oe(()=>Promise.resolve().then(()=>Z5),void 0,import.meta.url).then(c=>c.ufoMessages_en),fr:()=>oe(()=>import("./UfoMessages_fr-Cs2GCHEt.js"),[],import.meta.url).then(c=>c.ufoMessages_fr),es:()=>oe(()=>import("./UfoMessages_es-BRCWkzr3.js"),[],import.meta.url).then(c=>c.ufoMessages_es),it:()=>oe(()=>import("./UfoMessages_it-B2hvjhgb.js"),[],import.meta.url).then(c=>c.ufoMessages_it)};function O3(c){return L3[c]()}const P3={en:()=>oe(()=>Promise.resolve().then(()=>J3),void 0,import.meta.url).then(c=>c.sightingEditorMessages_en),fr:()=>oe(()=>import("./SightingEditorMessages_fr-
|
|
108
|
+
`}}class Ns{static NAMES=["weather","place","lightPollution","decor"];static KEYS={weather:["weatherTrack","weatherSource"],place:["place"],lightPollution:["lightPollution"],decor:["decor"]};static annexName(e,t){return`${e}.${t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}.json`}static fromFile(e,t){return e?.[t]!==void 0&&e[t].live!==!0}}class ts{static NAMES=["relief","imagery","roads","water","railways","upperAir","map"];static TERRAIN=["relief","imagery","roads","water","railways"];static held(e,t){if(!e||e.live)return;const i=e[t];return i&&!i.live&&!i.refresh&&i.src!==void 0?i:void 0}static isLive(e,t){return e?.live===!0||e?.[t]?.live===!0}static annexName(e,t){const i=t==="relief"||t==="imagery"||t==="map"?"zip":"json",s=t.replace(/[A-Z]/g,n=>`-${n.toLowerCase()}`);return`${e}.${s}.${i}`}static isEmpty(e){return!e||!e.live&&ts.NAMES.every(t=>!e[t])&&Ns.NAMES.every(t=>!e[t])}}class Bl 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 na{static async recording(e){const t=await na.json(e);for(const i of Ns.NAMES){const s=t?.frozen?.[i];if(!(!s?.src||s.live))try{const n=Ui.toCurrent(await na.json(new URL(s.src,new URL(e,location.href)).href));for(const r of Ns.KEYS[i])n[r]!==void 0&&(t[r]=n[r])}catch{}}return t}static async json(e){const t=new URL(e,location.href);if(location.protocol==="https:"&&t.protocol==="http:")throw new Bl("mixed-content",e);let i;try{i=await fetch(e)}catch{throw await this.diagnose(e,t)}if(!i.ok)throw new Bl("status",e,i.status);try{return await i.json()}catch{throw new Bl("malformed",e)}}static async diagnose(e,t){if(t.origin===location.origin)return new Bl("unreachable",e);try{return await fetch(e,{mode:"no-cors"}),new Bl("cors",e)}catch{return new Bl("unreachable",e)}}}class Ea{static PACKAGE="@rr0/ufoathome";static CDN="https://cdn.jsdelivr.net/npm";static DIRECTORIES={"rr0-sighting":"dist-embed-sighting","rr0-sighting-editor":"dist-embed-sighting-editor"};static current(e,t,i){const s=new URL(`${e}.mjs`,t);return s.href.startsWith(`${Ea.CDN}/`)?`${i}/lib/${e}.mjs`:(s.pathname=s.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),s.href)}static VERSION_PARAMETER="v";static freezable(e){return e in Ea.DIRECTORIES}static frozenLink(e,t){const i=new URL(e);return i.searchParams.set(Ea.VERSION_PARAMETER,t),i.href}static frozen(e,t){return`${Ea.CDN}/${Ea.PACKAGE}@${t}/${Ea.DIRECTORIES[e]}/${e}.mjs`}}class ed{static PRODUCTION="https://ufoathome.org";static home(){try{const e=new URL(import.meta.url),t=new URL(location.href);return(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]"||t.hostname.endsWith(".localhost"))&&e.origin===t.origin?t.origin:ed.PRODUCTION}catch{return ed.PRODUCTION}}}const Av={share:"Share",close:"Close",link:"Link",embed:"Embed",copy:"Copy",copied:"Copied",freeze:"Freeze version {version}",freezeHint:"The embed keeps the rendering of this version of UFO@home, loaded from jsDelivr, and gets none of the later fixes. Unticked, it follows each release.",unsaved:"The link opens the file at its address: your unsaved changes are not in it. Save the file there first.",unavailable:"Only a file loaded from an address can be shared: put it online, then open it from its address."},C3=Object.freeze(Object.defineProperty({__proto__:null,shareMessages_en:Av},Symbol.toStringTag,{value:"Module"})),Wu=["en","fr","es","it"],L3={en:()=>oe(()=>Promise.resolve().then(()=>Z5),void 0,import.meta.url).then(c=>c.ufoMessages_en),fr:()=>oe(()=>import("./UfoMessages_fr-Cs2GCHEt.js"),[],import.meta.url).then(c=>c.ufoMessages_fr),es:()=>oe(()=>import("./UfoMessages_es-BRCWkzr3.js"),[],import.meta.url).then(c=>c.ufoMessages_es),it:()=>oe(()=>import("./UfoMessages_it-B2hvjhgb.js"),[],import.meta.url).then(c=>c.ufoMessages_it)};function O3(c){return L3[c]()}const P3={en:()=>oe(()=>Promise.resolve().then(()=>J3),void 0,import.meta.url).then(c=>c.sightingEditorMessages_en),fr:()=>oe(()=>import("./SightingEditorMessages_fr-thlWKHJq.js"),[],import.meta.url).then(c=>c.sightingEditorMessages_fr),es:()=>oe(()=>import("./SightingEditorMessages_es-DGdkm-Yt.js"),[],import.meta.url).then(c=>c.sightingEditorMessages_es),it:()=>oe(()=>import("./SightingEditorMessages_it-dkt2lxRe.js"),[],import.meta.url).then(c=>c.sightingEditorMessages_it)};function ME(c){return P3[c]()}const N3={en:()=>oe(()=>Promise.resolve().then(()=>C3),void 0,import.meta.url).then(c=>c.shareMessages_en),fr:()=>oe(()=>import("./ShareMessages_fr-DyOB2E5o.js"),[],import.meta.url).then(c=>c.shareMessages_fr),es:()=>oe(()=>import("./ShareMessages_es-BM5hHumO.js"),[],import.meta.url).then(c=>c.shareMessages_es),it:()=>oe(()=>import("./ShareMessages_it-C9F8UHk_.js"),[],import.meta.url).then(c=>c.shareMessages_it)};function F3(c){return N3[c]()}function U3(c){switch(c){case"fr":return oe(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(e=>e.tagNames_fr);case"es":return oe(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(e=>e.tagNames_es);case"it":return oe(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(e=>e.tagNames_it);default:return Promise.resolve({})}}const z3={en:()=>oe(()=>import("./BodyEditorMessages_en-DmM8Dasm.js"),[],import.meta.url).then(c=>c.bodyEditorMessages_en),fr:()=>oe(()=>import("./BodyEditorMessages_fr-D03RAZjQ.js"),[],import.meta.url).then(c=>c.bodyEditorMessages_fr),es:()=>oe(()=>import("./BodyEditorMessages_es-BiV1oFuY.js"),[],import.meta.url).then(c=>c.bodyEditorMessages_es),it:()=>oe(()=>import("./BodyEditorMessages_it-34r0JMIX.js"),[],import.meta.url).then(c=>c.bodyEditorMessages_it)},B3={en:()=>oe(()=>import("./BeamEditorMessages_en-DBs2OUXJ.js"),[],import.meta.url).then(c=>c.beamEditorMessages_en),fr:()=>oe(()=>import("./BeamEditorMessages_fr-D1j_IF07.js"),[],import.meta.url).then(c=>c.beamEditorMessages_fr),es:()=>oe(()=>import("./BeamEditorMessages_es-DB8K5GtE.js"),[],import.meta.url).then(c=>c.beamEditorMessages_es),it:()=>oe(()=>import("./BeamEditorMessages_it-BT3ezMwC.js"),[],import.meta.url).then(c=>c.beamEditorMessages_it)};function S9(c){return B3[c]()}const H3={en:()=>oe(()=>import("./LanternEditorMessages_en-3XzIx2c4.js"),[],import.meta.url).then(c=>c.lanternEditorMessages_en),fr:()=>oe(()=>import("./LanternEditorMessages_fr-Cf444dJM.js"),[],import.meta.url).then(c=>c.lanternEditorMessages_fr),es:()=>oe(()=>import("./LanternEditorMessages_es-BwzbSSd3.js"),[],import.meta.url).then(c=>c.lanternEditorMessages_es),it:()=>oe(()=>import("./LanternEditorMessages_it-Bhk0A4Ug.js"),[],import.meta.url).then(c=>c.lanternEditorMessages_it)};function E9(c){return H3[c]()}const G3={en:()=>oe(()=>import("./LaunchEditorMessages_en-DH8gI1vo.js"),[],import.meta.url).then(c=>c.launchEditorMessages_en),fr:()=>oe(()=>import("./LaunchEditorMessages_fr-CWCGUG_A.js"),[],import.meta.url).then(c=>c.launchEditorMessages_fr),es:()=>oe(()=>import("./LaunchEditorMessages_es-WCfaY4uY.js"),[],import.meta.url).then(c=>c.launchEditorMessages_es),it:()=>oe(()=>import("./LaunchEditorMessages_it-DxSSiAd7.js"),[],import.meta.url).then(c=>c.launchEditorMessages_it)};function A9(c){return G3[c]()}const V3={en:()=>oe(()=>Promise.resolve().then(()=>w9),void 0,import.meta.url).then(c=>c.caseEditorMessages_en),fr:()=>oe(()=>import("./CaseEditorMessages_fr-BppxXK1E.js"),[],import.meta.url).then(c=>c.caseEditorMessages_fr),es:()=>oe(()=>import("./CaseEditorMessages_es-DUelIN8x.js"),[],import.meta.url).then(c=>c.caseEditorMessages_es),it:()=>oe(()=>import("./CaseEditorMessages_it-BIYStAk9.js"),[],import.meta.url).then(c=>c.caseEditorMessages_it)},W3={en:()=>oe(()=>import("./InterviewMessages_en-CC5D0e6J.js"),[],import.meta.url).then(c=>c.interviewMessages_en),fr:()=>oe(()=>import("./InterviewMessages_fr-mhX8Zuyu.js"),[],import.meta.url).then(c=>c.interviewMessages_fr),es:()=>oe(()=>import("./InterviewMessages_es-B0Ut-uel.js"),[],import.meta.url).then(c=>c.interviewMessages_es),it:()=>oe(()=>import("./InterviewMessages_it-DaxIoAIG.js"),[],import.meta.url).then(c=>c.interviewMessages_it)};function T9(c){return W3[c]()}function $3(c){return V3[c]()}function I9(c){return z3[c]()}function xE(c){switch(c){case"fr":return oe(()=>import("./SceneNames_fr-hz4p4u7a.js"),[],import.meta.url).then(e=>e.sceneNames_fr);case"es":return oe(()=>import("./SceneNames_es-CtE-QSrH.js"),[],import.meta.url).then(e=>e.sceneNames_es);case"it":return oe(()=>import("./SceneNames_it-CRn1NGKM.js"),[],import.meta.url).then(e=>e.sceneNames_it);default:return Promise.resolve(void 0)}}function K3(c){switch(c){case"fr":return oe(()=>import("./CloudEditorMessages_fr-SvL-CR04.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_fr);case"es":return oe(()=>import("./CloudEditorMessages_es-DFCuS9Qg.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_es);case"it":return oe(()=>import("./CloudEditorMessages_it-BvfiHWV9.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_it);default:return Promise.resolve(void 0)}}const X3=`
|
|
109
109
|
<style>
|
|
110
110
|
/* What the dialog is drawn with: light by default, and the dark set when the system asks for it, as the player and the editors
|
|
111
111
|
are. The form controls follow through color-scheme. Defined here and not by the host, so that any element can hold this dialog;
|
|
@@ -331,8 +331,8 @@ ${e} :is(select:not([multiple]):not([size]), .rr0-select) {
|
|
|
331
331
|
<button id="copy" class="share-copy" type="button">Copy</button>
|
|
332
332
|
</div>
|
|
333
333
|
</dialog>
|
|
334
|
-
`;class Rh extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Rh.TAG)||customElements.define(Rh.TAG,Rh)}subject;messages=Av;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;freeze;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=X3;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.freeze=e("freeze"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.freeze.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=e==="en"?Av:await F3(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.freeze.checked;this.linkField.value=t?Ea.frozenLink(e.link(),"0.
|
|
335
|
-
${e.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const e=this.messages,t=(i,s)=>{this.shadow.getElementById(i).textContent=s};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("freeze-label",e.freeze.replace("{version}","0.161.0")),this.freeze.parentElement.title=e.freezeHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=oe(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([0,1]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages.embed),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages.copied,window.setTimeout(()=>this.copyButton.textContent=this.messages.copy,1500)}catch{t.select()}}}Ne.register(Xs,()=>new Yl);Ne.register(Yh,()=>new Ih);Ne.register(sa,()=>new hy);Ne.register(qh,()=>new _h);Ne.register(Eu,()=>new dy);Ne.register(jh,()=>new Du);Ne.register(Xh,()=>new _u);Ne.register(Zh,()=>new Ru);Ne.register(wl,()=>new Jh);Ne.register(Kh,()=>new Iu);Ne.register(rr,()=>new Zi);Ne.register(rl,()=>new Lu);Ne.register(ks,()=>new ql);Ne.register(al,()=>new Ou);Ne.register(Au,()=>new uy);Ne.register(ol,()=>new Pu);Ne.register(nl,()=>new Cu);Ne.register(ll,()=>new Nu);Ne.register(vc,()=>new Fu);Ne.register(sl,()=>new ku);Ne.register(Gn,()=>new ni);Ne.register(po,()=>new Bu);Ne.register(Rs,()=>new nt);Ne.register(fo,()=>new Hu);Ne.register(Tu,()=>new i0);Ne.register(mo,()=>new Vu);Ne.register(uo,()=>new zu);Ne.register(go,()=>new Gu);Ne.register(jf,()=>new x3);Ne.register(ho,()=>new Uu);class rn{constructor(e){this.preferences=e}read(e){var t,i;if(e===void 0)return;if(typeof e=="string")return e===""?void 0:e;for(const n of this.preferences){const r=(t=e[n])!==null&&t!==void 0?t:e[rn.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>rn.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(rn.base(n)))return r;return(i=Object.values(e).find(n=>n))!==null&&i!==void 0?i:void 0}write(e,t,i){var s,n;const r=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return r;const a={...e},o=(n=(s=Object.keys(a).find(l=>l===i))!==null&&s!==void 0?s:Object.keys(a).find(l=>rn.base(l)===rn.base(i)))!==null&&n!==void 0?n:i;return r===void 0?delete a[o]:a[o]=r,Object.keys(a).length===0?void 0:a}static base(e){return e.toLowerCase().split("-")[0]}}rn.any=new rn([]);var bw;(function(c){c.abductee="abductee",c.actor="actor",c.artist="artist",c.anthropologist="anthropologist",c.archeologist="archeologist",c.astronaut="astronaut",c.astronomer="astronomer",c.astrologist="astrologist",c.astrophysicist="astrophysicist",c.banker="banker",c.barman="barman",c.biologist="biologist",c.biochemist="biochemist",c.biophysicist="biophysicist",c.bishop="bishop",c.businessman="businessman",c.botanist="botanist",c.cameraman="cameraman",c.chemist="chemist",c.contactee="contactee",c.cryptozoologist="cryptozoologist",c.dentist="dentist",c.director="director",c.diplomat="diplomat",c.diver="diver",c.electronics="electronics",c.engineer="engineer",c.ethnologist="ethnologist",c.exobiologist="exobiologist",c.farmer="farmer",c.firefighter="firefighter",c.flightAttendant="flightAttendant",c.geologist="geologist",c.geophysicist="geophysicist",c.geographer="geographer",c.historian="historian",c.houseWife="houseWife",c.hypnotherapist="hypnotherapist",c.illusionist="illusionist",c.journalist="journalist",c.judge="judge",c.lawyer="lawyer",c.leader="leader",c.librarian="librarian",c.logger="logger",c.mathematician="mathematician",c.mechanic="mechanic",c.meteorologist="meteorologist",c.military="military",c.musician="musician",c.neurologist="neurologist",c.neuroscientist="neuroscientist",c.neuropsychiatrist="neuropsychiatrist",c.nurse="nurse",c.oceanographer="oceanographer",c.painter="painter",c.parapsychologist="parapsychologist",c.philosopher="philosopher",c.photographer="photographer",c.physician="physician",c.physicist="physicist",c.pilot="pilot",c.politician="politician",c.policeman="policeman",c.priest="priest",c.producer="producer",c.prospector="prospector",c.psychologist="psychologist",c.psychiatrist="psychiatrist",c.radioastronomer="radioastronomer",c.radioamateur="radioamateur",c.salesman="salesman",c.sailor="sailor",c.sociologist="sociologist",c.softwareEngineer="softwareEngineer",c.stuntman="stuntman",c.taxiDriver="taxiDriver",c.teacher="teacher",c.telegrapher="telegrapher",c.truckDriver="truckDriver",c.ufologist="ufologist",c.ufoWitness="ufoWitness",c.ufoWitness2="ufoWitness2",c.worker="worker",c.writer="writer"})(bw||(bw={}));var yw;(function(c){c.neutral="neutral",c.male="male",c.female="female"})(yw||(yw={}));class Y3 extends Error{constructor(e,t){super(e),this.cause=t}}class my extends Y3{constructor(e=my.defaultMessage,t){super(e,t)}}my.defaultMessage="Assertion failed";var ww;(function(c){c.country="country",c.region="region",c.department="department",c.city="city",c.company="company"})(ww||(ww={}));var Mw;(function(c){c.at="at",c.au="au",c.ar="ar",c.be="be",c.br="br",c.ca="ca",c.ch="ch",c.cn="cn",c.cl="cl",c.co="co",c.cy="cy",c.de="de",c.dk="dk",c.do="do",c.dz="dz",c.gr="gr",c.ec="ec",c.eg="eg",c.es="es",c.fi="fi",c.fr="fr",c.ga="ga",c.ge="ge",c.hu="hu",c.in="in",c.ie="ie",c.ir="ir",c.il="il",c.it="it",c.jp="jp",c.kr="kr",c.ma="ma",c.mx="mx",c.my="my",c.mz="mz",c.nl="nl",c.no="no",c.nz="nz",c.pa="pa",c.pe="pe",c.ph="ph",c.pl="pl",c.pt="pt",c.ro="ro",c.ru="ru",c.sc="sc",c.tr="tr",c.ua="ua",c.uk="uk",c.us="us",c.sa="sa",c.se="se",c.su="su",c.tn="tn",c.tw="tw",c.ve="ve",c.za="za"})(Mw||(Mw={}));function $u(c,e){for(const t of c){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class Sr{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 s=t.getRootNode();t=s instanceof ShadowRoot?s.host:void 0}}}class Ku{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Hi.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,s,n){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",a={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Hi.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new Ku(a,new URL("case.json",n).href),l=o.tracks[0];return l.recording=e,l.base={url:s},l.event.id=o.proposedId(l),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(s=>s.kind==="observer");return i.find(s=>s.event.id!==void 0&&t.includes(s.event.id))??i.find(s=>s.recording?.id!==void 0&&t.includes(s.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===Hi.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const l={type:"event",eventType:Hi.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...n!==void 0?{medium:n}:{},...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{}};return this.json.events=[...this.json.events??[],l],this.caseChanged=!0,l}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}keep(e,t,i=!1){t=Ui.toCurrent(t),e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title)}replaceJson(e){const i=(e.events??[]).filter(n=>n.eventType===Hi.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,a=n.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(l=>l.url===r);return o?(o.event=n,o.kind=a,o):{event:n,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===Hi.INTERVIEW_EVENT&&(n.id!==void 0&&o.id===n.id||n.url!==void 0&&o.url===n.url));a&&s.set(a,r)}this.transcripts.clear();for(const[n,r]of s)this.transcripts.set(n,r);this.json=e,this.caseChanged=!0}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))||[...this.transcripts.values()].some(e=>this.transcriptChanged(e))}markExported(e){if(this.caseChanged=!1,!!e){for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording));for(const t of this.transcripts.values())t.loaded=t.text}}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}static ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;eventIds(e){return new Set((this.json.events??[]).filter(t=>t!==e?.event).map(t=>t.id).filter(t=>t!==void 0))}proposedId(e){const t=a=>(a??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let a=s;for(let o=2;n.has(a);o++)a=`${s}-${o}`;return a}let r=1;for(;n.has(`sighting-${r}`);)r++;return`sighting-${r}`}ensureId(e){return e.event.id===void 0&&(e.event.id=this.proposedId(e),this.caseChanged=!0),e.event.id}setId(e,t){const i=e.event.id,s=a=>a===i||a===e.recording?.id,n=(this.json.events??[]).filter(a=>a.eventType===Hi.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&s(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&s(o)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!Ku.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of n){const o=[a.interpretationOf].flat().map(l=>s(l)?t:l);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(l=>l!==void 0&&s(l)?t:l);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return Hi.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),a=new Set(this.tracks.map(D=>D.event.url)),o=new Set(this.tracks.map(D=>D.recording?.id));let l=this.tracks.filter(D=>D.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${l}.json`)||o.has(`${n.id??r}-interpretation-${l}`);)l++;const h=`interpretation-${r}-${l}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:m,description:v,sources:g,tags:b,timeline:w,milestones:y,interpretation:M,...S}=structuredClone(n),E={version:3,id:`${n.id??r}-interpretation-${l}`,...S,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},x={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],x],this.caseChanged=!0;const A={event:x,url:new URL(x.url,this.url).href,kind:"reading",recording:E};return this.tracks.push(A),A}idsOf(e){return[e.event.id,e.recording?.id].filter(t=>t!==void 0)}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(s=>s!==void 0&&t.includes(s)))}addObservation(e,t,i,s){const n=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=s?"interpretation":"observer";let l=`${o}-${a}.json`,h=e.id??a;for(let m=2;n.has(l)||r.has(h);m++)l=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...s?{interpretationOf:this.ensureId(s.account)}:{},...t!==void 0?{time:t}:{},...s?.by&&s.by.length>0?{by:s.by}:{},...i!==void 0?{title:i}:{},url:u+l};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:s?"reading":"observer",recording:d};return this.tracks.push(f),s||(p.id=this.proposedId(f)),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(s=>s!==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(/[^/]*$/,""),s=o=>o.startsWith(i)?o.slice(i.length):o,n=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:s(o.url),content:JSON.stringify(o.recording,null,2)+`
|
|
334
|
+
`;class Rh extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Rh.TAG)||customElements.define(Rh.TAG,Rh)}subject;messages=Av;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;freeze;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=X3;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.freeze=e("freeze"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.freeze.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=e==="en"?Av:await F3(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.freeze.checked;this.linkField.value=t?Ea.frozenLink(e.link(),"0.162.0"):e.link(),this.fitLink();const s=`<script type="module" src="${t?Ea.frozen(e.module,"0.162.0"):Ea.current(e.module,import.meta.url,ed.home())}"><\/script>
|
|
335
|
+
${e.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const e=this.messages,t=(i,s)=>{this.shadow.getElementById(i).textContent=s};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("freeze-label",e.freeze.replace("{version}","0.162.0")),this.freeze.parentElement.title=e.freezeHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=oe(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([0,1]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages.embed),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages.copied,window.setTimeout(()=>this.copyButton.textContent=this.messages.copy,1500)}catch{t.select()}}}Ne.register(Xs,()=>new Yl);Ne.register(Yh,()=>new Ih);Ne.register(sa,()=>new hy);Ne.register(qh,()=>new _h);Ne.register(Eu,()=>new dy);Ne.register(jh,()=>new Du);Ne.register(Xh,()=>new _u);Ne.register(Zh,()=>new Ru);Ne.register(wl,()=>new Jh);Ne.register(Kh,()=>new Iu);Ne.register(rr,()=>new Zi);Ne.register(rl,()=>new Lu);Ne.register(ks,()=>new ql);Ne.register(al,()=>new Ou);Ne.register(Au,()=>new uy);Ne.register(ol,()=>new Pu);Ne.register(nl,()=>new Cu);Ne.register(ll,()=>new Nu);Ne.register(vc,()=>new Fu);Ne.register(sl,()=>new ku);Ne.register(Gn,()=>new ni);Ne.register(po,()=>new Bu);Ne.register(Rs,()=>new nt);Ne.register(fo,()=>new Hu);Ne.register(Tu,()=>new i0);Ne.register(mo,()=>new Vu);Ne.register(uo,()=>new zu);Ne.register(go,()=>new Gu);Ne.register(jf,()=>new x3);Ne.register(ho,()=>new Uu);class rn{constructor(e){this.preferences=e}read(e){var t,i;if(e===void 0)return;if(typeof e=="string")return e===""?void 0:e;for(const n of this.preferences){const r=(t=e[n])!==null&&t!==void 0?t:e[rn.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>rn.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(rn.base(n)))return r;return(i=Object.values(e).find(n=>n))!==null&&i!==void 0?i:void 0}write(e,t,i){var s,n;const r=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return r;const a={...e},o=(n=(s=Object.keys(a).find(l=>l===i))!==null&&s!==void 0?s:Object.keys(a).find(l=>rn.base(l)===rn.base(i)))!==null&&n!==void 0?n:i;return r===void 0?delete a[o]:a[o]=r,Object.keys(a).length===0?void 0:a}static base(e){return e.toLowerCase().split("-")[0]}}rn.any=new rn([]);var bw;(function(c){c.abductee="abductee",c.actor="actor",c.artist="artist",c.anthropologist="anthropologist",c.archeologist="archeologist",c.astronaut="astronaut",c.astronomer="astronomer",c.astrologist="astrologist",c.astrophysicist="astrophysicist",c.banker="banker",c.barman="barman",c.biologist="biologist",c.biochemist="biochemist",c.biophysicist="biophysicist",c.bishop="bishop",c.businessman="businessman",c.botanist="botanist",c.cameraman="cameraman",c.chemist="chemist",c.contactee="contactee",c.cryptozoologist="cryptozoologist",c.dentist="dentist",c.director="director",c.diplomat="diplomat",c.diver="diver",c.electronics="electronics",c.engineer="engineer",c.ethnologist="ethnologist",c.exobiologist="exobiologist",c.farmer="farmer",c.firefighter="firefighter",c.flightAttendant="flightAttendant",c.geologist="geologist",c.geophysicist="geophysicist",c.geographer="geographer",c.historian="historian",c.houseWife="houseWife",c.hypnotherapist="hypnotherapist",c.illusionist="illusionist",c.journalist="journalist",c.judge="judge",c.lawyer="lawyer",c.leader="leader",c.librarian="librarian",c.logger="logger",c.mathematician="mathematician",c.mechanic="mechanic",c.meteorologist="meteorologist",c.military="military",c.musician="musician",c.neurologist="neurologist",c.neuroscientist="neuroscientist",c.neuropsychiatrist="neuropsychiatrist",c.nurse="nurse",c.oceanographer="oceanographer",c.painter="painter",c.parapsychologist="parapsychologist",c.philosopher="philosopher",c.photographer="photographer",c.physician="physician",c.physicist="physicist",c.pilot="pilot",c.politician="politician",c.policeman="policeman",c.priest="priest",c.producer="producer",c.prospector="prospector",c.psychologist="psychologist",c.psychiatrist="psychiatrist",c.radioastronomer="radioastronomer",c.radioamateur="radioamateur",c.salesman="salesman",c.sailor="sailor",c.sociologist="sociologist",c.softwareEngineer="softwareEngineer",c.stuntman="stuntman",c.taxiDriver="taxiDriver",c.teacher="teacher",c.telegrapher="telegrapher",c.truckDriver="truckDriver",c.ufologist="ufologist",c.ufoWitness="ufoWitness",c.ufoWitness2="ufoWitness2",c.worker="worker",c.writer="writer"})(bw||(bw={}));var yw;(function(c){c.neutral="neutral",c.male="male",c.female="female"})(yw||(yw={}));class Y3 extends Error{constructor(e,t){super(e),this.cause=t}}class my extends Y3{constructor(e=my.defaultMessage,t){super(e,t)}}my.defaultMessage="Assertion failed";var ww;(function(c){c.country="country",c.region="region",c.department="department",c.city="city",c.company="company"})(ww||(ww={}));var Mw;(function(c){c.at="at",c.au="au",c.ar="ar",c.be="be",c.br="br",c.ca="ca",c.ch="ch",c.cn="cn",c.cl="cl",c.co="co",c.cy="cy",c.de="de",c.dk="dk",c.do="do",c.dz="dz",c.gr="gr",c.ec="ec",c.eg="eg",c.es="es",c.fi="fi",c.fr="fr",c.ga="ga",c.ge="ge",c.hu="hu",c.in="in",c.ie="ie",c.ir="ir",c.il="il",c.it="it",c.jp="jp",c.kr="kr",c.ma="ma",c.mx="mx",c.my="my",c.mz="mz",c.nl="nl",c.no="no",c.nz="nz",c.pa="pa",c.pe="pe",c.ph="ph",c.pl="pl",c.pt="pt",c.ro="ro",c.ru="ru",c.sc="sc",c.tr="tr",c.ua="ua",c.uk="uk",c.us="us",c.sa="sa",c.se="se",c.su="su",c.tn="tn",c.tw="tw",c.ve="ve",c.za="za"})(Mw||(Mw={}));function $u(c,e){for(const t of c){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class Sr{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 s=t.getRootNode();t=s instanceof ShadowRoot?s.host:void 0}}}class Ku{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Hi.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,s,n){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",a={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Hi.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new Ku(a,new URL("case.json",n).href),l=o.tracks[0];return l.recording=e,l.base={url:s},l.event.id=o.proposedId(l),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(s=>s.kind==="observer");return i.find(s=>s.event.id!==void 0&&t.includes(s.event.id))??i.find(s=>s.recording?.id!==void 0&&t.includes(s.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===Hi.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const l={type:"event",eventType:Hi.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...n!==void 0?{medium:n}:{},...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{}};return this.json.events=[...this.json.events??[],l],this.caseChanged=!0,l}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}keep(e,t,i=!1){t=Ui.toCurrent(t),e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title)}replaceJson(e){const i=(e.events??[]).filter(n=>n.eventType===Hi.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,a=n.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(l=>l.url===r);return o?(o.event=n,o.kind=a,o):{event:n,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===Hi.INTERVIEW_EVENT&&(n.id!==void 0&&o.id===n.id||n.url!==void 0&&o.url===n.url));a&&s.set(a,r)}this.transcripts.clear();for(const[n,r]of s)this.transcripts.set(n,r);this.json=e,this.caseChanged=!0}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))||[...this.transcripts.values()].some(e=>this.transcriptChanged(e))}markExported(e){if(this.caseChanged=!1,!!e){for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording));for(const t of this.transcripts.values())t.loaded=t.text}}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}static ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;eventIds(e){return new Set((this.json.events??[]).filter(t=>t!==e?.event).map(t=>t.id).filter(t=>t!==void 0))}proposedId(e){const t=a=>(a??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let a=s;for(let o=2;n.has(a);o++)a=`${s}-${o}`;return a}let r=1;for(;n.has(`sighting-${r}`);)r++;return`sighting-${r}`}ensureId(e){return e.event.id===void 0&&(e.event.id=this.proposedId(e),this.caseChanged=!0),e.event.id}setId(e,t){const i=e.event.id,s=a=>a===i||a===e.recording?.id,n=(this.json.events??[]).filter(a=>a.eventType===Hi.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&s(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&s(o)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!Ku.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of n){const o=[a.interpretationOf].flat().map(l=>s(l)?t:l);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(l=>l!==void 0&&s(l)?t:l);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return Hi.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),a=new Set(this.tracks.map(D=>D.event.url)),o=new Set(this.tracks.map(D=>D.recording?.id));let l=this.tracks.filter(D=>D.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${l}.json`)||o.has(`${n.id??r}-interpretation-${l}`);)l++;const h=`interpretation-${r}-${l}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:m,description:v,sources:g,tags:b,timeline:w,milestones:y,interpretation:M,...S}=structuredClone(n),E={version:3,id:`${n.id??r}-interpretation-${l}`,...S,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},x={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],x],this.caseChanged=!0;const A={event:x,url:new URL(x.url,this.url).href,kind:"reading",recording:E};return this.tracks.push(A),A}idsOf(e){return[e.event.id,e.recording?.id].filter(t=>t!==void 0)}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(s=>s!==void 0&&t.includes(s)))}addObservation(e,t,i,s){const n=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=s?"interpretation":"observer";let l=`${o}-${a}.json`,h=e.id??a;for(let m=2;n.has(l)||r.has(h);m++)l=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...s?{interpretationOf:this.ensureId(s.account)}:{},...t!==void 0?{time:t}:{},...s?.by&&s.by.length>0?{by:s.by}:{},...i!==void 0?{title:i}:{},url:u+l};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:s?"reading":"observer",recording:d};return this.tracks.push(f),s||(p.id=this.proposedId(f)),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(s=>s!==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(/[^/]*$/,""),s=o=>o.startsWith(i)?o.slice(i.length):o,n=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:s(o.url),content:JSON.stringify(o.recording,null,2)+`
|
|
336
336
|
`})),r=decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",a=[...this.transcripts].filter(([o,l])=>e&&o.url!==void 0&&(t||this.transcriptChanged(l))).map(([o,l])=>({path:s(new URL(o.url,this.url).href),content:l.text}));return[{path:r,content:JSON.stringify(this.json,null,2)+`
|
|
337
337
|
`},...n,...a]}}class Zf{constructor(e,t,i,s){this.button=e,this.onPick=i,this.idOf=s;const n=this.panel=e.ownerDocument.createElement("div");n.id=t,n.className="add-menu",n.setAttribute("popover",""),n.setAttribute("role","menu");const r=`--add-menu-${t}`;e.style.setProperty("anchor-name",r),n.style.setProperty("position-anchor",r),e.setAttribute("popovertarget",t),e.setAttribute("aria-haspopup","menu"),e.after(n)}static CSS=`
|
|
338
338
|
.add-menu { padding: .3em 0; border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); border-radius: 4px; background: Canvas; color: CanvasText;
|
|
@@ -358,7 +358,7 @@ ${e.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=
|
|
|
358
358
|
align-items: center; gap: .5em; }
|
|
359
359
|
.element-list-picker select { border-bottom-left-radius: 0; border-bottom-right-radius: 0; }
|
|
360
360
|
.element-list-row [hidden], .element-list-body[hidden] { display: none !important; }
|
|
361
|
-
${Zf.CSS}`;static showPresence(e,t,i,s=!1){for(const n of e.children)if(!n.matches(".element-list-add, .add-menu, .add-reason")){if(n.matches(".element-list-empty")){n.hidden=i||s;continue}if(n.matches(".element-list-picker")){n.hidden=!i&&!s;continue}n.hidden=!i&&!s,n instanceof HTMLButtonElement&&!i&&(n.disabled=!0)}t&&(t.hidden=!i,i&&wn.glue(t))}static glue(e){const t=e.parentElement,i=e.ownerDocument.defaultView;if(!t||!i)return;const s=i.getComputedStyle(t),n=/flex|grid/.test(s.display)&&parseFloat(s.rowGap)||0;e.style.marginTop=`${-n}px`}select;row;pickerRow;emptyText;removeButton;addButton;addReason;kindMenu;previousButton;nextButton;actionButtons=new Map;items=[];noneLabel="—";addLabel="";removeEnabled=!0;actionEnabled=new Map;iconButton(e,t){const i=document.createElement("button");return i.type="button",i.className="icon-btn",i.id=e,Ee.show(i,t),i}setLabels(e){if(this.previousButton&&this.nextButton)for(const[t,i,s]of[[this.previousButton,e.previous??"","Alt+↑"],[this.nextButton,e.next??"","Alt+↓"]]){const n=i===""?s:`${i} (${s})`;t.title=n,t.setAttribute("aria-label",i||n),t.setAttribute("aria-keyshortcuts",s.replace("↑","ArrowUp").replace("↓","ArrowDown"))}this.select.setAttribute("aria-label",e.list),this.emptyText.textContent=e.empty??"",this.noneLabel=e.none??this.noneLabel,this.addLabel=e.add,this.kindMenu?.panel.setAttribute("aria-label",e.add),this.options.optional&&this.listed(this.items,this.select.value);for(const[t,i]of[[this.removeButton,e.remove],[this.addButton,e.add],...[...this.actionButtons].map(([s,n])=>[n,e.actions?.[s]??""])])t.title=i,t.setAttribute("aria-label",i)}setKinds(e){this.kindMenu?.setKinds(e)}kindLabel(e){return this.kindMenu?.labelOf(e)??e}get pickedKind(){return this.kindMenu?.lastPicked}setItems(e,t){this.items=e,this.listed(e,t)}listed(e,t){this.select.replaceChildren(...this.options.optional?[new Option(this.noneLabel,"")]:[],...e.map(i=>new Option(i.label,i.id))),t!==void 0&&(this.select.value=t),this.select.selectedIndex<0&&(this.select.selectedIndex=0),this.setPresent(this.options.optional?this.select.value!=="":e.length>0)}setStepState(e,t){this.previousButton&&(this.previousButton.disabled=!e),this.nextButton&&(this.nextButton.disabled=!t)}setActionEnabled(e,t){const i=this.actionButtons.get(e);i&&(i.disabled=!t||this.select.disabled),this.actionEnabled.set(e,t)}setRemoveEnabled(e){this.removeEnabled=e,this.removeButton.disabled=!e||this.select.value===""&&this.options.optional===!0}get value(){return this.select.value}setAddState(e,t){this.addButton.disabled=!e;const i=t??this.addLabel;this.addButton.title=i,this.addButton.setAttribute("aria-label",i),this.addReason||(this.addReason=this.addButton.ownerDocument.createElement("span"),this.addReason.className="add-reason",this.addReason.style.cssText="font-size: .85em; opacity: .8; align-self: center;",this.row.append(this.addReason)),this.addReason.textContent=!e&&t?t:"",this.addReason.hidden=e||!t}rename(e,t){const i=[...this.select.options].find(s=>s.value===e);i&&(i.textContent=t)}show(e){this.select.value=e,this.options.optional&&this.setPresent(this.select.value!=="")}setPresent(e){const t=this.options.optional===!0;if(wn.showPresence(this.row,this.options.body,e,t),this.select.disabled=!e&&!t,!!e){this.removeButton.disabled=!this.removeEnabled;for(const[i,s]of this.actionButtons)s.disabled=this.actionEnabled.get(i)===!1}}focus(){this.select.focus()}}class Ks{constructor(e,t,i,s="en"){this.parts=e,this.messages=t,this.onChange=i,this.locale=s,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.type!=="date"&&(i.step=Ks.stepFor(e)),i.value=i.type==="date"?Ks.pickerDateOf(e):Ks.pickerValueOf(e),t.setCustomValidity(""),t.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...e){return e.every(t=>t===void 0||Ks.isPickable(t)&&Ks.qualifierOf(cl(t))==="")}static opensPreciseDate(...e){return e.every(t=>t===void 0||Ks.isFullDate(t)&&Ks.qualifierOf(cl(t))==="")}static isFullDate(e){return!!e&&e.year!==void 0&&e.month!==void 0&&e.day!==void 0}static pickerDateOf(e){if(!Ks.isFullDate(e))return"";const t=(i,s=2)=>String(i).padStart(s,"0");return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}`}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(!Ks.isPickable(e))return"";const t=(s,n=2)=>String(s).padStart(n,"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 Ks.describeTime(e,this.messages,this.locale)}static describeTime(e,t,i){const s=cl(e),n=Ks.qualifierOf(s),r=h=>String(h).padStart(2,"0"),a=[];if(e.season!==void 0){const h={spring:t.timeSeasonSpring,summer:t.timeSeasonSummer,autumn:t.timeSeasonAutumn,winter:t.timeSeasonWinter}[e.season];a.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));a.push(new Intl.DateTimeFormat(i,{...h,timeZone:"UTC"}).format(d))}e.hour!==void 0&&a.push(`${r(e.hour)}:${r(e.minute??0)}${e.second!==void 0?`:${r(e.second)}`:""}`);const o=a.join(", "),l=n==="~"?t.timeQualifierApproximate:n==="?"?t.timeQualifierUncertain:n==="%"?t.timeQualifierBoth:"";return l?`${o} — ${l.toLowerCase()}`:o}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=Jd(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=Jd(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===""||Jd(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}}class An{static count=0;static css(e){return`${e}:popover-open { position: fixed; inset: auto; margin: 0 0 .35em; border: 0; position-area: top span-right; position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline; }`}static attach(e,t){const i=`--rr0-help-${++An.count}`;e.style.setProperty("anchor-name",i),t.style.setProperty("position-anchor",i),t.setAttribute("popover","manual"),t.hidden=!0}static show(e,t){e.hidden=!t,!(typeof e.showPopover!="function"||!e.isConnected)&&(t&&!e.matches(":popover-open")?e.showPopover():!t&&e.matches(":popover-open")&&e.hidePopover())}}const q3={title:"Observer's events",phenomenonTitle:"Phenomenon's events",bodyTitle:"Events of {body}",derivedNote:"The observer's poses are worked out from these events. Moving the observer or turning their gaze by hand writes poses of your own, which win over them.",overriddenNote:"This recording's own poses win over its events.",derivedShapesNote:"The account's shapes are worked out from what the phenomenon did. Drawing them by hand writes shapes of your own, which win over these events.",overriddenShapesNote:"This recording's own shapes win over the phenomenon's events.",parts:"{n} parts",who:"Subject",part:"Part",partHint:"A node, a bone or a light of its model (legs, head, front-red), or a group of its parts (rear): it alone, the rest of the body as it is",wholeBody:"the whole body",derivedBodiesNote:"These bodies' keyframes are worked out from what they did. Keyframes set by hand win over these events.",overriddenBodiesNote:"Keyframes of its own win over these events.",add:"Add an event",remove:"Remove the event",none:"No event",resetToEvents:"Back to the events",kinds:{drive:"Drives",lookAhead:"Looks down the road",lean:"Leans",watch:"Watches in the mirror",stand:"Stands",look:"Looks at",appearance:"Looks like",walk:"Walks",follow:"Follows with the eyes",blink:"Blinks",vanish:"Is lost",motion:"Moves",spin:"Turns",rise:"Rises",ride:"Rides in",turn:"Turns",light:"Light",travel:"Crosses the sky",roll:"Banks",vibrate:"Vibrates",spiral:"Spirals"},params:{vehicle:"Vehicle",path:"Route",speeds:"Speeds",speedDivisors:"Speeds divided by",through:"Goes through",eye:"Eye in the vehicle",fovDeg:"Field of view",target:"Watching",pitchShare:"Looks up to",keepDeg:"Keeps it within",glanceBeyondDeg:"Glances beyond",glanceS:"Glance",roadS:"Back on the road",offsetM:"Moves the eye by",holdS:"For",turnS:"In",mirror:"Mirror",firstS:"First",mirrorS:"In the mirror",glancesUntil:"Glances at it until",place:"Where",metres:"Size",parts:"Parts",onS:"On",offS:"Off",off:"Off, it is",motion:"Movement",turnsPerS:"Turns a second",distanceM:"Distance",angleDeg:"Off the vertical",stops:"Stops",in:"In",aboveM:"Above it",from:"From",to:"To",headingDeg:"Heading",pitchDeg:"Tilt",cdM2:"Luminance",towards:"Towards",sizeDeg:"Size at the zenith",sizeBy:"Size by",byDeg:"By",side:"Side",seenFrom:"Seen from",reactionS:"Reacts after",lagS:"Behind it by",toDeg:"To",andBack:"And back",hz:"Times a second",amplitudeShare:"Amplitude",riseS:"Rises in",turns:"Turns",radiusDeg:"Radius",shrink:"Narrows by",clockwise:"Clockwise",rollDeg:"Barrel roll",azimuthDeg:"Azimuth",altitudeDeg:"Altitude"},from:"from",to:"to",points:"{n} points",at:"at",paramHints:{pitchShare:"share of its height",metres:"width, and height above the eye",amplitudeShare:"share of its size"},basisTitle:"How this value was obtained",basisField:"Basis",howField:"How",rationaleField:"Rationale",choices:{"sizeBy.":"always the same","sizeBy.altitude":"its altitude (smaller towards the horizon)","side.left":"left","side.right":"right","seenFrom.":"the ground (as the observer sees it)","seenFrom.craft":"the craft (as its pilot would say it)"},zenith:"zenith",lookedAt:"Where they look",lookedAtHint:"Takes the direction the observer looks at the playhead",atOnce:"at once",atOnceHint:"Ticked: the value stays the previous row's until this instant, then becomes this row's at once (braking, a sudden start). Unticked: it gets there gradually from the previous row.",addRow:"Add a row",removeRow:"Remove this row",basis:{stated:"stated",derived:"derived",assumed:"assumed",measured:"measured"}},j3={basisTitle:"How this value was obtained",basisField:"Basis",howField:"How",rationaleField:"Why",basisReset:"Basis back to “stated”: the value was typed again (it was: {basis}).",lawSources:"Sources: {sources}",extrapolation:"These laws were measured on night sightings: applying them to a daylight sighting is an extrapolation.",sectionAccountConditions:"Conditions of the account",sectionViewing:"Viewing conditions",sectionMoon:"Moon gauge",sectionErrorParameters:"This witness's error parameters",errorModelField:"Error model",delayField:"Delay before this account",delayUnit:"days",versionField:"Version",wordField:"Word used",exposureField:"Exposure",independenceField:"Independence",independentYes:"without talking to the other witnesses",independentNo:"after talking to the other witnesses",unknownChoice:"unknown",darkAdapted:"Dark-adapted",correctedVision:"Corrected vision",correctedVisionHint:"glasses, lenses",glare:"Bright light just before",viewingNote:"The window or windscreen and the binoculars are set in “Vision” above.",moonIntro:"The witness shows the full Moon the way they showed the object. The ratio is their own angular-size factor: the one measure that makes the general law individual. To take once per witness.",moonField:"Moon as shown",moonHint:"At arm's length, 1 cm ≈ 1°",moonNone:"Not measured yet: the general law applies ({law}).",moonFactor:"Factor ×{k}: it replaces the general law in every angular size this witness gives.",moonReal:"Real Moon · 0.52°",parametersIntro:"One witness's errors are tied: the same factor on every size, the same offset on every time. Computed, never typed: no “±” margin is entered by hand.",showMore:"Show",basis:{measured:"◆ measured",stated:"stated",derived:"derived",assumed:"assumed"},how:{clock:"read on a clock",anchored:"anchored to a dated event",estimated:"estimated","shown-on-the-spot":"shown on the spot","arm-length-gauge":"arm's-length gauge","recalled-object":"through a familiar object",instrument:"instrument",landmark:"landmark",occlusion:"occlusion","known-size":"known size",triangulation:"triangulation"},status:{consolidated:"consolidated",individual:"individual",single:"single study",argued:"argued",contested:"contested"},laws:{timeClock:"± {minutes} min (read on a clock)",timeAnchored:"± {minutes} min (anchored to a dated event)",timeEstimated:"± {minutes} min for 9 witnesses in 10 (estimated)",duration:"{low} to {high}: ×/÷{factor} (log-normal)",elevationOver:"{low} to {high}: elevation overestimated",measuredInstrument:"± {degrees}° (measured)",measuredLandmark:"± {degrees}° (from a landmark)",headingCross:"{low} to {high}: ± {degrees}°, sense sometimes reversed",sizeMoon:"{low} to {high}: Moon gauge factor ×{factor}",sizeShown:"{low} to {high}: shown on the spot, +2 to +17 %",sizeRecalled:"{low} to {high}: through a familiar object, ~30 % too large",sizeArm:"{low} to {high}: overestimated ×{from} to ×{to} at arm's length",sizeGauge:"{low} to {high}: gauge, ± {percent} %",distanceAnchored:"Anchored: its error follows that of what it is derived from",distanceNotData:"No data: wrong by a factor {factor} or more unless anchored"},parameterNames:{clock:"Clock offset",date:"Date shift",heading:"Heading rotation",elevation:"Elevation compression",size:"Angular size factor",duration:"Duration factor"},parameterScopes:{clock:"every time",date:"the date",heading:"every bearing",elevation:"every elevation",size:"every angular size",duration:"the duration and the timeline's scale"},parameters:{clockClock:"± {minutes} min (clock)",clockAnchored:"± {minutes} min (anchored)",clockEstimated:"± {minutes} min (estimated)",dateShift:"±1 day, month or year; summer time ({percent} % of dates)",headingRotation:"± {degrees}°, mirror possible",elevationCompression:"overestimated, never underestimated",sizeMoon:"×{factor} (Moon gauge)",sizeArm:"×{from} to ×{to} at arm's length",sizeShown:"+2 to +17 % shown on the spot",durationFactor:"×/÷{factor} (log-normal)"},words:{light:"light",object:"object",craft:"craft",ufo:"UFO",other:"other"},exposures:{none:"none",press:"press",broadcast:"radio, television","other-witnesses":"other witnesses",investigators:"investigators"},models:{consolidated:"Consolidated readings (UFO@home)",keul:"Keul (sizes shown on the spot)"},candidates:{title:"Candidate explanations",verdicts:{consolidated:"Compatible with consolidated biases",contested:"Only by invoking contested biases",incompatible:"Incompatible even at the bounds"},cost:"cost {x} σ",seeVariant:"See this variant",variantLabel:"Variant: {name}",backToAccount:"Back to the account",costNote:"A cost is not a probability: it says which biases have to be invoked, and how far.",scopeNote:"Poher matrix (1977) for the starting list; the Moon, the planets, satellite passes, re-entries, recorded fireballs and the aircraft of the traffic record are computed and confronted with the account.",fields:{time:"Time",heading:"Azimuth",elevation:"Elevation",size:"Apparent width",duration:"Duration",sweep:"Sweep across the sky"},biases:{clock:"clock offset {x} min",heading:"heading rotation {x}°",elevation:"elevation overestimated ×{x}",size:"size overestimated ×{x}",duration:"duration misjudged ×{x}",sweep:"sweep misjudged {x}°"},reasons:{"never-seen":"Never visible from this place within the margin of the time given.",direction:"Too far from the direction given, even at the bounds of the laws.",size:"Size too different, even at the bounds of the laws.",motion:"It does not move the way the account says, and nothing reads one as the other.",growth:"It does not grow as the account says, nor grow brighter."},readingTitle:"Reading",readings:{grouped:"lights read as one body","still-seen-moving":"a still light seen moving (autokinetic effect, drifting clouds)","moving-seen-still":"a moving light seen hovering (coming head on)","brightening-as-approach":"growing brighter read as coming nearer"},notAgainst:"This is no argument against the account.",noDirection:"The account does not place the phenomenon in the sky: there is nothing to confront.",noSky:"Without a date, a time and a place, no celestial body can be placed.",bodies:{Moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},aircraft:"Aircraft {name}",interpretation:"Interpretation: {name}",keepVariant:"Keep this variant",keptTitle:"Variants kept ({n})",seeKept:"See",removeVariant:"Remove",keptRecomputed:"computed again: {verdict}, cost {x} σ",keptModel:"model: {model}",reentry:"Re-entry {name}",star:"Star {name}",fireball:"Fireball {name}",poherLoading:"Loading the Poher matrix…",poherFailed:"The Poher matrix could not be read: only celestial bodies are offered.",poherTitle:"From the matrix of {version}",poherIntro:"The other known phenomena of the matrix, with no track computed here: their score is Poher's judgment, to confront by hand.",poherIntroRr0:"The other known phenomena of the matrix, with no track computed here: each score is Poher's, or RR0's for what RR0 adds, with its reason; to confront by hand.",poherVersion:"Matrix",poherVersions:{"poher-1977":"Poher (1977)","rr0-2026":"Poher extended by RR0 (2026)"},poherAdded:"added by RR0",poherRr0Reason:"RR0 score: {why}",poherPossible:"Possible",poherExcluded:"Ruled out ({n})",poherExcludedBy:"ruled out by: {list}",poherDoubted:"doubtful from estimates: {list}",poherScore:"score {x}",poherTag:"Poher: {state}",poherStatePossible:"possible, score {x}",poherStateExcluded:"ruled out",answersTitle:"Answers drawn from the recording ({n})",firm:"firm",soft:"an estimate, rules nothing out alone"}},Z3={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",speed:"Speed",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)",referenceGhosts:"Ghosts in the picture",referenceFindGhosts:"Look for ghosts",referenceGhostsSearching:"Looking…",referenceGhostsFound:"{count} ghosts found, each across the lens's axis from its light.",referenceGhostsFoundScaled:"{count} ghosts found, each at {scale} times its light's offset from the lens's axis.",referenceGhostsLow:"Perhaps {count} ghost(s): too few to be sure.",referenceGhostsNone:"No ghost found: no faint spot lies across one point from a light.",referenceGhostsCropped:"The lens's axis is off the picture's centre: the picture was cropped.",referenceGhostsHide:"Hide ghosts",referenceGhostsShow:"Show ghosts",iso:"Sensitivity",isoTitle:"The film's speed, or the sensor's gain. Left empty, a device that sets its own exposure sets it; stated, it is set by hand, as in a phone's manual mode.",metering:"Metering",meteringDevice:"the device's own",meteringAverage:"the whole frame (older phones, camcorders)",meteringHighlights:"keeping highlights (recent phones)",meteringTitle:"How a device that sets its own exposure reads the light: by the mean of its whole frame, which burns out a bright light in a dark frame, or holding back so that a light taking up a fair part of it keeps its colour.",lensGlass:"Taken through",lensGlassNone:"the lens alone",lensGlassFilter:"a filter on the lens",lensGlassWindow:"a window",lensGlassWindscreen:"a windscreen",lensDrops:"Drops on the glass",lensDropsTitle:"0 to 1: how much of the outermost glass drops of water cover. Blank: from the rain or snow falling, unless the glass is sheltered",lensCondensation:"Condensation",lensCondensationTitle:"0 to 1: condensation on the glass, as on a lens taken from the warm into the cold. Blank: none",lensDirt:"Dirt",lensDirtTitle:"0 to 1: dirt, grease or fingerprints on the glass. Blank: none",lensSheltered:"Sheltered from the rain",lensShelteredTitle:"The outermost glass was out of the rain or snow: under a roof, or behind a windscreen whose wipers run",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",rareIceCrystals:"Rare crystals",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",decorWall:"Dry-stone wall",decorStreetlight:"Streetlight",decorTrafficLight:"Traffic light",decorCrossing:"Pedestrian crossing",decorRoadSign:"Road sign",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",decorModelAdvanced:"Model from an address",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},gl={...Z3,oval:"Oval",polygon:"Polygon",modelTriangle:"Triangle",modelSaucer:"Saucer",modelCigar:"Cigar",modelChevron:"Chevron",modelLight:"Light",modelPartDisc:"disc",modelPartDome:"dome",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",shapeRotation:"Rotation",shapeRotationTitle:"How far the shape is turned on the drawing, clockwise, in degrees: what its rotation handle sets",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",bodiesTrack:"bodies",observerTrack:"observer",weatherTrack:"weather",soundTrack:"sound",group:"Group",ungroup:"Ungroup",duplicate:"Duplicate",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",samplingRateHint:"Empty: each event at its own step (25 ms for a motion across the sky), the recorder every {n} ms",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",frozenTitle:"Frozen data",frozenHint:"What the scene would otherwise ask third parties for at every play (relief, photograph of the ground, roads, water, railways, air aloft), taken when the recording is saved and kept in files beside it, so that it plays the same way without asking anybody.",frozenLive:"Ask the sources at every play (freeze nothing)",frozenRelief:"Relief",frozenImagery:"Photograph of the ground",frozenRoads:"Roads",frozenWater:"Water",frozenRailways:"Railways",frozenUpperAir:"Air aloft",frozenMap:"Map photograph",fileItemRecording:"Recording",fileItemWeather:"Weather",fileItemPlace:"Place",fileItemLightPollution:"Light pollution",fileItemDecor:"Scenery",weatherStatedByObserver:"as the observer stated it",annexSource:"File",annexStorageInline:"inside the recording",annexEditorLabel:"The annex as JSON text",annexUnreadable:"This file is not an annex of this kind: nothing was changed.",frozenTakenOn:"taken on {date}",frozenPending:"taken at save",frozenLiveState:"asked live",frozenRefresh:"Refresh",frozenTaking:"Taking: {group}… {done}/{of}",frozenFailed:"{group}: its source did not answer, nothing was taken.",frozenMissing:"{file} could not be read: left out of the archive.",frozenExported:"Saved with {count} annexes ({size}), in one archive to unpack beside where the recording is published.",identityHint:"Name someone only if they agreed to it or published their own account; otherwise initials are enough.",identityAsk:"This recording names or locates a person. You answer for what you publish: name someone only if they agreed to it, or published their own account. Otherwise initials are enough.",identityLastName:"Last name: {value}",identityFirstNames:"First name: {value}",identityNameInId:"Name in an identifier: {value}",identityNameInText:"Name in the text: {value}",identityAddress:"Address: {value}",identityEmail:"E-mail address: {value}",identityPhone:"Telephone number: {value}",identityInitials:"Replace with initials",identityKeep:"Save anyway",identityBack:"Go back",importFile:"Load sighting file",paramSummaryTitle:"What the recording states ({n})",wholeKeyframes:"Every keyframe whole",wholeKeyframesHint:"Otherwise a keyframe states only what changed since the one before, as a recording is written by hand. Changing this starts the history of Undo afresh.",importUrlPlaceholder:"https://…/sighting.json",inputFileFromFile:"from your disk",inputFileFromUrl:"from an address",inputFileModeHint:"Click to give it the other way: a file of yours, or an address",inputFileLoad:"Load",positionRelative:"relative",positionAbsolute:"absolute",positionModeHint:"Click to say it the other way: from something else, or as a latitude and a longitude",positionNoPlace:"The recording has no place yet: give the observer a latitude and a longitude first",positionFrom:"from",positionObserver:"the observer",positionEast:"East",positionNorth:"North",positionLatitude:"Latitude",positionLongitude:"Longitude",positionLabel:"Position",positionBasisHint:"Where this position comes from",positionBasisStated:"stated",positionBasisMeasured:"measured",positionBasisDerived:"derived",positionBasisAssumed:"assumed",positionBasisField:"Basis",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.",formatVersionError:"This file states version {found} of its format; this UFO@home reads up to version {supported}. Open it with a newer UFO@home.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",sourceAircraft:"Air traffic",sourceFile:"File",sourceKind:"Data",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",launchesSubgroup:"Launches",sky:"Sky",dataSources:"Data sources",beamsSubgroup:"Beams",lanternsSubgroup:"Lanterns",soundGroup:"Sound",close:"Close",editorKicker:"Sighting editor",witnessError:j3,events:q3,expandTracks:"Expand the tracks",resizeScene:"Drag to make the scene taller or shorter (double-click: back to its own size)",saveRefused:"Not saved: {reasons}.",duplicateId:"“{id}” is the id of several things ({kinds})",unknownWho:"event no. {n} ({kind}) is about “{id}”, which nothing has as its id",actorKinds:{observer:"the observer",shape:"a shape",group:"a group of shapes",body:"a body",decor:"a decor object"},collapseTracks:"Collapse the tracks",addKeyframeHere:"Add a keyframe here",keyframeHere:"A keyframe is here: editing it changes it",zoomHint:"Pinch or Ctrl + wheel: zoom · swipe sideways or Shift + wheel: scroll",overlayHorizon:"Horizon · tilt {deg}°",overlayFov:"Field of view {v}° × {h}°",overlayWind:"Blowing toward {point} · {speed} m/s",sectionIdentity:"Identity",sectionProfile:"Profile",sectionTestimony:"Testimony",sectionVision:"Vision",sectionPerception:"Perception",sectionCoordinates:"Coordinates",sectionGaze:"Gaze",sectionNightSky:"Night sky",sectionPeriod:"Period",sectionSurvey:"Scenery from a survey",sectionHeard:"What was heard",sectionSoundRecording:"Recording",sectionPicture:"Picture",sectionPose:"Pose",sectionAppearance:"Appearance",sectionSize:"Size and distance",sectionPath:"Path",moreSettings:"More settings ({n})",lessSettings:"Fewer settings",showSettings:"Show ({n} settings)",showSettingsOne:"Show (1 setting)",showSettingsAny:"Show",hideSettings:"Hide",save:"Save",stateNew:"New recording",panelIntroObservation:"What happened, in a few lines, and what is left to fill in.",panelIntroObserver:"Who saw it, and through what. Each observer has their own point of view in the scene.",panelIntroLocation:"Where the observer was looking from, and in which direction.",panelIntroTemporal:"When it began, how long it lasted, and the moments of the account.",panelIntroDecor:"What surrounded the observer: vehicles, buildings, vegetation.",panelIntroWeather:"The weather, and what crossed the sky without being the phenomenon: launches, beams.",panelIntroShape:"What was seen, drawn in the scene from the observer's point of view.",panelIntroSound:"What was heard.",panelIntroReference:"Photos and sketches, registered on the scene to compare it.",panelIntroFile:"The whole recording, to save or to load again.",temporalGroup:"Date",fileGroup:"Files",fileLoading:"Loading the editor…",weatherEditedAsk:"This edit touches the weather, data read dynamically from {source}. Stop reading it from {source}?",weatherEditedStop:"Stop reading it",weatherEditedKeep:"Keep reading it (undo my edit)",fileEditorLabel:"The recording as JSON text",fileSearchPhrases:{},timeQualifierExact:"Exact",durationPrecise:"precise",durationIso:"imprecise",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
|
|
361
|
+
${Zf.CSS}`;static showPresence(e,t,i,s=!1){for(const n of e.children)if(!n.matches(".element-list-add, .add-menu, .add-reason")){if(n.matches(".element-list-empty")){n.hidden=i||s;continue}if(n.matches(".element-list-picker")){n.hidden=!i&&!s;continue}n.hidden=!i&&!s,n instanceof HTMLButtonElement&&!i&&(n.disabled=!0)}t&&(t.hidden=!i,i&&wn.glue(t))}static glue(e){const t=e.parentElement,i=e.ownerDocument.defaultView;if(!t||!i)return;const s=i.getComputedStyle(t),n=/flex|grid/.test(s.display)&&parseFloat(s.rowGap)||0;e.style.marginTop=`${-n}px`}select;row;pickerRow;emptyText;removeButton;addButton;addReason;kindMenu;previousButton;nextButton;actionButtons=new Map;items=[];noneLabel="—";addLabel="";removeEnabled=!0;actionEnabled=new Map;iconButton(e,t){const i=document.createElement("button");return i.type="button",i.className="icon-btn",i.id=e,Ee.show(i,t),i}setLabels(e){if(this.previousButton&&this.nextButton)for(const[t,i,s]of[[this.previousButton,e.previous??"","Alt+↑"],[this.nextButton,e.next??"","Alt+↓"]]){const n=i===""?s:`${i} (${s})`;t.title=n,t.setAttribute("aria-label",i||n),t.setAttribute("aria-keyshortcuts",s.replace("↑","ArrowUp").replace("↓","ArrowDown"))}this.select.setAttribute("aria-label",e.list),this.emptyText.textContent=e.empty??"",this.noneLabel=e.none??this.noneLabel,this.addLabel=e.add,this.kindMenu?.panel.setAttribute("aria-label",e.add),this.options.optional&&this.listed(this.items,this.select.value);for(const[t,i]of[[this.removeButton,e.remove],[this.addButton,e.add],...[...this.actionButtons].map(([s,n])=>[n,e.actions?.[s]??""])])t.title=i,t.setAttribute("aria-label",i)}setKinds(e){this.kindMenu?.setKinds(e)}kindLabel(e){return this.kindMenu?.labelOf(e)??e}get pickedKind(){return this.kindMenu?.lastPicked}setItems(e,t){this.items=e,this.listed(e,t)}listed(e,t){this.select.replaceChildren(...this.options.optional?[new Option(this.noneLabel,"")]:[],...e.map(i=>new Option(i.label,i.id))),t!==void 0&&(this.select.value=t),this.select.selectedIndex<0&&(this.select.selectedIndex=0),this.setPresent(this.options.optional?this.select.value!=="":e.length>0)}setStepState(e,t){this.previousButton&&(this.previousButton.disabled=!e),this.nextButton&&(this.nextButton.disabled=!t)}setActionEnabled(e,t){const i=this.actionButtons.get(e);i&&(i.disabled=!t||this.select.disabled),this.actionEnabled.set(e,t)}setRemoveEnabled(e){this.removeEnabled=e,this.removeButton.disabled=!e||this.select.value===""&&this.options.optional===!0}get value(){return this.select.value}setAddState(e,t){this.addButton.disabled=!e;const i=t??this.addLabel;this.addButton.title=i,this.addButton.setAttribute("aria-label",i),this.addReason||(this.addReason=this.addButton.ownerDocument.createElement("span"),this.addReason.className="add-reason",this.addReason.style.cssText="font-size: .85em; opacity: .8; align-self: center;",this.row.append(this.addReason)),this.addReason.textContent=!e&&t?t:"",this.addReason.hidden=e||!t}rename(e,t){const i=[...this.select.options].find(s=>s.value===e);i&&(i.textContent=t)}show(e){this.select.value=e,this.options.optional&&this.setPresent(this.select.value!=="")}setPresent(e){const t=this.options.optional===!0;if(wn.showPresence(this.row,this.options.body,e,t),this.select.disabled=!e&&!t,!!e){this.removeButton.disabled=!this.removeEnabled;for(const[i,s]of this.actionButtons)s.disabled=this.actionEnabled.get(i)===!1}}focus(){this.select.focus()}}class Ks{constructor(e,t,i,s="en"){this.parts=e,this.messages=t,this.onChange=i,this.locale=s,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.type!=="date"&&(i.step=Ks.stepFor(e)),i.value=i.type==="date"?Ks.pickerDateOf(e):Ks.pickerValueOf(e),t.setCustomValidity(""),t.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...e){return e.every(t=>t===void 0||Ks.isPickable(t)&&Ks.qualifierOf(cl(t))==="")}static opensPreciseDate(...e){return e.every(t=>t===void 0||Ks.isFullDate(t)&&Ks.qualifierOf(cl(t))==="")}static isFullDate(e){return!!e&&e.year!==void 0&&e.month!==void 0&&e.day!==void 0}static pickerDateOf(e){if(!Ks.isFullDate(e))return"";const t=(i,s=2)=>String(i).padStart(s,"0");return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}`}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(!Ks.isPickable(e))return"";const t=(s,n=2)=>String(s).padStart(n,"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 Ks.describeTime(e,this.messages,this.locale)}static describeTime(e,t,i){const s=cl(e),n=Ks.qualifierOf(s),r=h=>String(h).padStart(2,"0"),a=[];if(e.season!==void 0){const h={spring:t.timeSeasonSpring,summer:t.timeSeasonSummer,autumn:t.timeSeasonAutumn,winter:t.timeSeasonWinter}[e.season];a.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));a.push(new Intl.DateTimeFormat(i,{...h,timeZone:"UTC"}).format(d))}e.hour!==void 0&&a.push(`${r(e.hour)}:${r(e.minute??0)}${e.second!==void 0?`:${r(e.second)}`:""}`);const o=a.join(", "),l=n==="~"?t.timeQualifierApproximate:n==="?"?t.timeQualifierUncertain:n==="%"?t.timeQualifierBoth:"";return l?`${o} — ${l.toLowerCase()}`:o}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=Jd(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=Jd(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===""||Jd(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}}class An{static count=0;static css(e){return`${e}:popover-open { position: fixed; inset: auto; margin: 0 0 .35em; border: 0; position-area: top span-right; position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline; }`}static attach(e,t){const i=`--rr0-help-${++An.count}`;e.style.setProperty("anchor-name",i),t.style.setProperty("position-anchor",i),t.setAttribute("popover","manual"),t.hidden=!0}static show(e,t){e.hidden=!t,!(typeof e.showPopover!="function"||!e.isConnected)&&(t&&!e.matches(":popover-open")?e.showPopover():!t&&e.matches(":popover-open")&&e.hidePopover())}}const q3={title:"Observer's events",phenomenonTitle:"Phenomenon's events",bodyTitle:"Events of {body}",derivedNote:"The observer's poses are worked out from these events. Moving the observer or turning their gaze by hand writes poses of your own, which win over them.",overriddenNote:"This recording's own poses win over its events.",derivedShapesNote:"The account's shapes are worked out from what the phenomenon did. Drawing them by hand writes shapes of your own, which win over these events.",overriddenShapesNote:"This recording's own shapes win over the phenomenon's events.",parts:"{n} parts",who:"Subject",part:"Part",partHint:"A node, a bone or a light of its model (legs, head, front-red), or a group of its parts (rear): it alone, the rest of the body as it is",wholeBody:"the whole body",derivedBodiesNote:"These bodies' keyframes are worked out from what they did. Keyframes set by hand win over these events.",overriddenBodiesNote:"Keyframes of its own win over these events.",add:"Add an event",remove:"Remove the event",none:"No event",resetToEvents:"Back to the events",kinds:{drive:"Drives",lookAhead:"Looks down the road",lean:"Leans",watch:"Watches in the mirror",stand:"Stands",look:"Looks at",appearance:"Looks like",walk:"Walks",follow:"Follows with the eyes",blink:"Blinks",vanish:"Is lost",motion:"Moves",spin:"Turns",rise:"Rises",ride:"Rides in",turn:"Turns",light:"Light",travel:"Crosses the sky",roll:"Banks",vibrate:"Vibrates",spiral:"Spirals"},params:{vehicle:"Vehicle",path:"Route",speeds:"Speeds",speedDivisors:"Speeds divided by",through:"Goes through",eye:"Eye in the vehicle",fovDeg:"Field of view",target:"Watching",pitchShare:"Looks up to",keepDeg:"Keeps it within",glanceBeyondDeg:"Glances beyond",glanceS:"Glance",roadS:"Back on the road",offsetM:"Moves the eye by",holdS:"For",turnS:"In",mirror:"Mirror",firstS:"First",mirrorS:"In the mirror",glancesUntil:"Glances at it until",place:"Where",metres:"Size",parts:"Parts",onS:"On",offS:"Off",off:"Off, it is",motion:"Movement",turnsPerS:"Turns a second",distanceM:"Distance",angleDeg:"Off the vertical",stops:"Stops",in:"In",aboveM:"Above it",from:"From",to:"To",headingDeg:"Heading",pitchDeg:"Tilt",cdM2:"Luminance",towards:"Towards",sizeDeg:"Size at the zenith",sizeBy:"Size by",byDeg:"By",side:"Side",seenFrom:"Seen from",reactionS:"Reacts after",lagS:"Behind it by",toDeg:"To",andBack:"And back",hz:"Times a second",amplitudeShare:"Amplitude",riseS:"Rises in",turns:"Turns",radiusDeg:"Radius",shrink:"Narrows by",clockwise:"Clockwise",rollDeg:"Barrel roll",azimuthDeg:"Azimuth",altitudeDeg:"Altitude"},from:"from",to:"to",points:"{n} points",at:"at",paramHints:{pitchShare:"share of its height",metres:"width, and height above the eye",amplitudeShare:"share of its size"},basisTitle:"How this value was obtained",basisField:"Basis",howField:"How",rationaleField:"Rationale",choices:{"sizeBy.":"always the same","sizeBy.altitude":"its altitude (smaller towards the horizon)","side.left":"left","side.right":"right","seenFrom.":"the ground (as the observer sees it)","seenFrom.craft":"the craft (as its pilot would say it)"},zenith:"zenith",lookedAt:"Where they look",lookedAtHint:"Takes the direction the observer looks at the playhead",atOnce:"at once",atOnceHint:"Ticked: the value stays the previous row's until this instant, then becomes this row's at once (braking, a sudden start). Unticked: it gets there gradually from the previous row.",addRow:"Add a row",removeRow:"Remove this row",basis:{stated:"stated",derived:"derived",assumed:"assumed",measured:"measured"}},j3={basisTitle:"How this value was obtained",basisField:"Basis",howField:"How",rationaleField:"Why",basisReset:"Basis back to “stated”: the value was typed again (it was: {basis}).",lawSources:"Sources: {sources}",extrapolation:"These laws were measured on night sightings: applying them to a daylight sighting is an extrapolation.",sectionAccountConditions:"Conditions of the account",sectionViewing:"Viewing conditions",sectionMoon:"Moon gauge",sectionErrorParameters:"This witness's error parameters",errorModelField:"Error model",delayField:"Delay before this account",delayUnit:"days",versionField:"Version",wordField:"Word used",exposureField:"Exposure",independenceField:"Independence",independentYes:"without talking to the other witnesses",independentNo:"after talking to the other witnesses",unknownChoice:"unknown",darkAdapted:"Dark-adapted",correctedVision:"Corrected vision",correctedVisionHint:"glasses, lenses",glare:"Bright light just before",viewingNote:"The window or windscreen and the binoculars are set in “Vision” above.",moonIntro:"The witness shows the full Moon the way they showed the object. The ratio is their own angular-size factor: the one measure that makes the general law individual. To take once per witness.",moonField:"Moon as shown",moonHint:"At arm's length, 1 cm ≈ 1°",moonNone:"Not measured yet: the general law applies ({law}).",moonFactor:"Factor ×{k}: it replaces the general law in every angular size this witness gives.",moonReal:"Real Moon · 0.52°",parametersIntro:"One witness's errors are tied: the same factor on every size, the same offset on every time. Computed, never typed: no “±” margin is entered by hand.",showMore:"Show",basis:{measured:"◆ measured",stated:"stated",derived:"derived",assumed:"assumed"},how:{clock:"read on a clock",anchored:"anchored to a dated event",estimated:"estimated","shown-on-the-spot":"shown on the spot","arm-length-gauge":"arm's-length gauge","recalled-object":"through a familiar object",instrument:"instrument",landmark:"landmark",occlusion:"occlusion","known-size":"known size",triangulation:"triangulation"},status:{consolidated:"consolidated",individual:"individual",single:"single study",argued:"argued",contested:"contested"},laws:{timeClock:"± {minutes} min (read on a clock)",timeAnchored:"± {minutes} min (anchored to a dated event)",timeEstimated:"± {minutes} min for 9 witnesses in 10 (estimated)",duration:"{low} to {high}: ×/÷{factor} (log-normal)",elevationOver:"{low} to {high}: elevation overestimated",measuredInstrument:"± {degrees}° (measured)",measuredLandmark:"± {degrees}° (from a landmark)",headingCross:"{low} to {high}: ± {degrees}°, sense sometimes reversed",sizeMoon:"{low} to {high}: Moon gauge factor ×{factor}",sizeShown:"{low} to {high}: shown on the spot, +2 to +17 %",sizeRecalled:"{low} to {high}: through a familiar object, ~30 % too large",sizeArm:"{low} to {high}: overestimated ×{from} to ×{to} at arm's length",sizeGauge:"{low} to {high}: gauge, ± {percent} %",distanceAnchored:"Anchored: its error follows that of what it is derived from",distanceNotData:"No data: wrong by a factor {factor} or more unless anchored"},parameterNames:{clock:"Clock offset",date:"Date shift",heading:"Heading rotation",elevation:"Elevation compression",size:"Angular size factor",duration:"Duration factor"},parameterScopes:{clock:"every time",date:"the date",heading:"every bearing",elevation:"every elevation",size:"every angular size",duration:"the duration and the timeline's scale"},parameters:{clockClock:"± {minutes} min (clock)",clockAnchored:"± {minutes} min (anchored)",clockEstimated:"± {minutes} min (estimated)",dateShift:"±1 day, month or year; summer time ({percent} % of dates)",headingRotation:"± {degrees}°, mirror possible",elevationCompression:"overestimated, never underestimated",sizeMoon:"×{factor} (Moon gauge)",sizeArm:"×{from} to ×{to} at arm's length",sizeShown:"+2 to +17 % shown on the spot",durationFactor:"×/÷{factor} (log-normal)"},words:{light:"light",object:"object",craft:"craft",ufo:"UFO",other:"other"},exposures:{none:"none",press:"press",broadcast:"radio, television","other-witnesses":"other witnesses",investigators:"investigators"},models:{consolidated:"Consolidated readings (UFO@home)",keul:"Keul (sizes shown on the spot)"},candidates:{title:"Candidate explanations",verdicts:{consolidated:"Compatible with consolidated biases",contested:"Only by invoking contested biases",incompatible:"Incompatible even at the bounds"},cost:"cost {x} σ",seeVariant:"See this variant",variantLabel:"Variant: {name}",backToAccount:"Back to the account",costNote:"A cost is not a probability: it says which biases have to be invoked, and how far.",scopeNote:"Poher matrix (1977) for the starting list; the Moon, the planets, satellite passes, re-entries, recorded fireballs and the aircraft of the traffic record are computed and confronted with the account.",fields:{time:"Time",heading:"Azimuth",elevation:"Elevation",size:"Apparent width",duration:"Duration",sweep:"Sweep across the sky"},biases:{clock:"clock offset {x} min",heading:"heading rotation {x}°",elevation:"elevation overestimated ×{x}",size:"size overestimated ×{x}",duration:"duration misjudged ×{x}",sweep:"sweep misjudged {x}°"},reasons:{"never-seen":"Never visible from this place within the margin of the time given.",direction:"Too far from the direction given, even at the bounds of the laws.",size:"Size too different, even at the bounds of the laws.",motion:"It does not move the way the account says, and nothing reads one as the other.",growth:"It does not grow as the account says, nor grow brighter."},readingTitle:"Reading",readings:{grouped:"lights read as one body","still-seen-moving":"a still light seen moving (autokinetic effect, drifting clouds)","moving-seen-still":"a moving light seen hovering (coming head on)","brightening-as-approach":"growing brighter read as coming nearer"},notAgainst:"This is no argument against the account.",noDirection:"The account does not place the phenomenon in the sky: there is nothing to confront.",noSky:"Without a date, a time and a place, no celestial body can be placed.",bodies:{Moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},aircraft:"Aircraft {name}",interpretation:"Interpretation: {name}",keepVariant:"Keep this variant",keptTitle:"Variants kept ({n})",seeKept:"See",removeVariant:"Remove",keptRecomputed:"computed again: {verdict}, cost {x} σ",keptModel:"model: {model}",reentry:"Re-entry {name}",star:"Star {name}",fireball:"Fireball {name}",poherLoading:"Loading the Poher matrix…",poherFailed:"The Poher matrix could not be read: only celestial bodies are offered.",poherTitle:"From the matrix of {version}",poherIntro:"The other known phenomena of the matrix, with no track computed here: their score is Poher's judgment, to confront by hand.",poherIntroRr0:"The other known phenomena of the matrix, with no track computed here: each score is Poher's, or RR0's for what RR0 adds, with its reason; to confront by hand.",poherVersion:"Matrix",poherVersions:{"poher-1977":"Poher (1977)","rr0-2026":"Poher extended by RR0 (2026)"},poherAdded:"added by RR0",poherRr0Reason:"RR0 score: {why}",poherPossible:"Possible",poherExcluded:"Ruled out ({n})",poherExcludedBy:"ruled out by: {list}",poherDoubted:"doubtful from estimates: {list}",poherScore:"score {x}",poherTag:"Poher: {state}",poherStatePossible:"possible, score {x}",poherStateExcluded:"ruled out",answersTitle:"Answers drawn from the recording ({n})",firm:"firm",soft:"an estimate, rules nothing out alone"}},Z3={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",speed:"Speed",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)",referenceGhosts:"Ghosts in the picture",referenceFindGhosts:"Look for ghosts",referenceGhostsSearching:"Looking…",referenceGhostsFound:"{count} ghosts found, each across the lens's axis from its light.",referenceGhostsFoundScaled:"{count} ghosts found, each at {scale} times its light's offset from the lens's axis.",referenceGhostsLow:"Perhaps {count} ghost(s): too few to be sure.",referenceGhostsNone:"No ghost found: no faint spot lies across one point from a light.",referenceGhostsCropped:"The lens's axis is off the picture's centre: the picture was cropped.",referenceGhostsHide:"Hide ghosts",referenceGhostsShow:"Show ghosts",iso:"Sensitivity",isoTitle:"The film's speed, or the sensor's gain. Left empty, a device that sets its own exposure sets it; stated, it is set by hand, as in a phone's manual mode.",metering:"Metering",meteringDevice:"the device's own",meteringAverage:"the whole frame (older phones, camcorders)",meteringHighlights:"keeping highlights (recent phones)",meteringTitle:"How a device that sets its own exposure reads the light: by the mean of its whole frame, which burns out a bright light in a dark frame, or holding back so that a light taking up a fair part of it keeps its colour.",lensGlass:"Taken through",lensGlassNone:"the lens alone",lensGlassFilter:"a filter on the lens",lensGlassWindow:"a window",lensGlassWindscreen:"a windscreen",lensDrops:"Drops on the glass",lensDropsTitle:"0 to 1: how much of the outermost glass drops of water cover. Blank: from the rain or snow falling, unless the glass is sheltered",lensCondensation:"Condensation",lensCondensationTitle:"0 to 1: condensation on the glass, as on a lens taken from the warm into the cold. Blank: none",lensDirt:"Dirt",lensDirtTitle:"0 to 1: dirt, grease or fingerprints on the glass. Blank: none",lensSheltered:"Sheltered from the rain",lensShelteredTitle:"The outermost glass was out of the rain or snow: under a roof, or behind a windscreen whose wipers run",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","ballester-guasp.pending":"to be assessed","poher.0":"0/5 · not strange, or not classifiable","poher.1":"1/5 · a point in a straight line","poher.2":"2/5 · an abnormal trajectory","poher.3":"3/5 · strange: erratic, landed or vanished","poher.4":"4/5 · landing with traces","poher.5":"5/5 · landing with occupants"},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",rareIceCrystals:"Rare crystals",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",decorWall:"Dry-stone wall",decorStreetlight:"Streetlight",decorTrafficLight:"Traffic light",decorCrossing:"Pedestrian crossing",decorRoadSign:"Road sign",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",decorModelAdvanced:"Model from an address",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},gl={...Z3,oval:"Oval",polygon:"Polygon",modelTriangle:"Triangle",modelSaucer:"Saucer",modelCigar:"Cigar",modelChevron:"Chevron",modelLight:"Light",modelPartDisc:"disc",modelPartDome:"dome",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",shapeRotation:"Rotation",shapeRotationTitle:"How far the shape is turned on the drawing, clockwise, in degrees: what its rotation handle sets",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",bodiesTrack:"bodies",observerTrack:"observer",weatherTrack:"weather",soundTrack:"sound",group:"Group",ungroup:"Ungroup",duplicate:"Duplicate",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",samplingRateHint:"Empty: each event at its own step (25 ms for a motion across the sky), the recorder every {n} ms",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",frozenTitle:"Frozen data",frozenHint:"What the scene would otherwise ask third parties for at every play (relief, photograph of the ground, roads, water, railways, air aloft), taken when the recording is saved and kept in files beside it, so that it plays the same way without asking anybody.",frozenLive:"Ask the sources at every play (freeze nothing)",frozenRelief:"Relief",frozenImagery:"Photograph of the ground",frozenRoads:"Roads",frozenWater:"Water",frozenRailways:"Railways",frozenUpperAir:"Air aloft",frozenMap:"Map photograph",fileItemRecording:"Recording",fileItemWeather:"Weather",fileItemPlace:"Place",fileItemLightPollution:"Light pollution",fileItemDecor:"Scenery",weatherStatedByObserver:"as the observer stated it",annexSource:"File",annexStorageInline:"inside the recording",annexEditorLabel:"The annex as JSON text",annexUnreadable:"This file is not an annex of this kind: nothing was changed.",frozenTakenOn:"taken on {date}",frozenPending:"taken at save",frozenLiveState:"asked live",frozenRefresh:"Refresh",frozenTaking:"Taking: {group}… {done}/{of}",frozenFailed:"{group}: its source did not answer, nothing was taken.",frozenMissing:"{file} could not be read: left out of the archive.",frozenExported:"Saved with {count} annexes ({size}), in one archive to unpack beside where the recording is published.",identityHint:"Name someone only if they agreed to it or published their own account; otherwise initials are enough.",identityAsk:"This recording names or locates a person. You answer for what you publish: name someone only if they agreed to it, or published their own account. Otherwise initials are enough.",identityLastName:"Last name: {value}",identityFirstNames:"First name: {value}",identityNameInId:"Name in an identifier: {value}",identityNameInText:"Name in the text: {value}",identityAddress:"Address: {value}",identityEmail:"E-mail address: {value}",identityPhone:"Telephone number: {value}",identityInitials:"Replace with initials",identityKeep:"Save anyway",identityBack:"Go back",importFile:"Load sighting file",paramSummaryTitle:"What the recording states ({n})",wholeKeyframes:"Every keyframe whole",wholeKeyframesHint:"Otherwise a keyframe states only what changed since the one before, as a recording is written by hand. Changing this starts the history of Undo afresh.",importUrlPlaceholder:"https://…/sighting.json",inputFileFromFile:"from your disk",inputFileFromUrl:"from an address",inputFileModeHint:"Click to give it the other way: a file of yours, or an address",inputFileLoad:"Load",positionRelative:"relative",positionAbsolute:"absolute",positionModeHint:"Click to say it the other way: from something else, or as a latitude and a longitude",positionNoPlace:"The recording has no place yet: give the observer a latitude and a longitude first",positionFrom:"from",positionObserver:"the observer",positionEast:"East",positionNorth:"North",positionLatitude:"Latitude",positionLongitude:"Longitude",positionLabel:"Position",positionBasisHint:"Where this position comes from",positionBasisStated:"stated",positionBasisMeasured:"measured",positionBasisDerived:"derived",positionBasisAssumed:"assumed",positionBasisField:"Basis",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.",formatVersionError:"This file states version {found} of its format; this UFO@home reads up to version {supported}. Open it with a newer UFO@home.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",sourceAircraft:"Air traffic",sourceFile:"File",sourceKind:"Data",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",launchesSubgroup:"Launches",sky:"Sky",dataSources:"Data sources",beamsSubgroup:"Beams",lanternsSubgroup:"Lanterns",soundGroup:"Sound",close:"Close",editorKicker:"Sighting editor",witnessError:j3,events:q3,expandTracks:"Expand the tracks",resizeScene:"Drag to make the scene taller or shorter (double-click: back to its own size)",saveRefused:"Not saved: {reasons}.",duplicateId:"“{id}” is the id of several things ({kinds})",unknownWho:"event no. {n} ({kind}) is about “{id}”, which nothing has as its id",actorKinds:{observer:"the observer",shape:"a shape",group:"a group of shapes",body:"a body",decor:"a decor object"},collapseTracks:"Collapse the tracks",addKeyframeHere:"Add a keyframe here",keyframeHere:"A keyframe is here: editing it changes it",zoomHint:"Pinch or Ctrl + wheel: zoom · swipe sideways or Shift + wheel: scroll",overlayHorizon:"Horizon · tilt {deg}°",overlayFov:"Field of view {v}° × {h}°",overlayWind:"Blowing toward {point} · {speed} m/s",sectionIdentity:"Identity",sectionProfile:"Profile",sectionTestimony:"Testimony",sectionVision:"Vision",sectionPerception:"Perception",sectionCoordinates:"Coordinates",sectionGaze:"Gaze",sectionNightSky:"Night sky",sectionPeriod:"Period",sectionSurvey:"Scenery from a survey",sectionHeard:"What was heard",sectionSoundRecording:"Recording",sectionPicture:"Picture",sectionPose:"Pose",sectionAppearance:"Appearance",sectionSize:"Size and distance",sectionPath:"Path",moreSettings:"More settings ({n})",lessSettings:"Fewer settings",showSettings:"Show ({n} settings)",showSettingsOne:"Show (1 setting)",showSettingsAny:"Show",hideSettings:"Hide",save:"Save",stateNew:"New recording",panelIntroObservation:"What happened, in a few lines, and what is left to fill in.",panelIntroObserver:"Who saw it, and through what. Each observer has their own point of view in the scene.",panelIntroLocation:"Where the observer was looking from, and in which direction.",panelIntroTemporal:"When it began, how long it lasted, and the moments of the account.",panelIntroDecor:"What surrounded the observer: vehicles, buildings, vegetation.",panelIntroWeather:"The weather, and what crossed the sky without being the phenomenon: launches, beams.",panelIntroShape:"What was seen, drawn in the scene from the observer's point of view.",panelIntroSound:"What was heard.",panelIntroReference:"Photos and sketches, registered on the scene to compare it.",panelIntroFile:"The whole recording, to save or to load again.",temporalGroup:"Date",fileGroup:"Files",fileLoading:"Loading the editor…",weatherEditedAsk:"This edit touches the weather, data read dynamically from {source}. Stop reading it from {source}?",weatherEditedStop:"Stop reading it",weatherEditedKeep:"Keep reading it (undo my edit)",fileEditorLabel:"The recording as JSON text",fileSearchPhrases:{},timeQualifierExact:"Exact",durationPrecise:"precise",durationIso:"imprecise",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
|
|
362
362
|
PT10M — 10 minutes
|
|
363
363
|
PT1H30M — 1 hour 30 minutes
|
|
364
364
|
PT5M/PT10M — between 5 and 10 minutes
|
|
@@ -785,7 +785,7 @@ ${JSON.stringify(i)}`),t.push(`The account:
|
|
|
785
785
|
|
|
786
786
|
${e.ask}`,"Answer by calling draft_recording."),t.join(`
|
|
787
787
|
|
|
788
|
-
`)}static imageBlock(e){return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}}}async clientFor(e,t){if(!e)throw new fr("credential");const i=`${e}\0${t??""}`;if(this.client&&this.clientFor_===i)return this.client;const{default:s}=await oe(async()=>{const{default:n}=await import("./index-DQDuRMiM.js").then(r=>r.i);return{default:n}},[],import.meta.url);return this.client=new s({apiKey:e,...t?{defaultHeaders:{"anthropic-workspace-id":t}}:{},dangerouslyAllowBrowser:!0,maxRetries:1}),this.clientFor_=i,this.client}static read(e){if(e.stop_reason==="refusal")throw new fr("refused");const t=e.content.find(s=>s.type==="tool_use"&&s.name===jw.name);if(!t||t.type!=="tool_use")throw new fr("malformed");const i=t.input;if(typeof i?.recording!="object"||i.recording===null||Array.isArray(i.recording))throw new fr("malformed");return{recording:i.recording,claims:Array.isArray(i.claims)?i.claims.flatMap(s=>{const{path:n,basis:r,rationale:a}=s??{};return typeof n!="string"||typeof a!="string"?[]:[{path:n,basis:r==="derived"||r==="assumed"?r:"stated",rationale:a}]}):[],gaps:Array.isArray(i.gaps)?i.gaps.filter(s=>typeof s=="string"):[]}}static async diagnose(e,t){if(e instanceof fr)return e;if(t?.aborted)return new fr("cancelled",e);const{default:i}=await oe(async()=>{const{default:s}=await import("./index-DQDuRMiM.js").then(n=>n.i);return{default:s}},[],import.meta.url);return e instanceof i.AuthenticationError||e instanceof i.PermissionDeniedError?new fr("credential",e):e instanceof i.RateLimitError?new fr("rate-limited",e):e instanceof i.BadRequestError||e instanceof i.NotFoundError?new fr("rejected",e.message,e):e instanceof i.APIConnectionError?new fr("unreachable",e):new fr("malformed",e)}}const _p=[{id:"claude",name:"Claude",credit:"Anthropic",creditUrl:"https://www.anthropic.com/legal/consumer-terms",create:()=>new ga}],B5=[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async c=>{const{CoverageAssessor:e}=await oe(async()=>{const{CoverageAssessor:t}=await import("./CoverageAssessor-mvpHgNx3.js");return{CoverageAssessor:t}},[],import.meta.url);return new e().assess(c)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async c=>{const{HynekAssessor:e}=await oe(async()=>{const{HynekAssessor:t}=await import("./HynekAssessor-
|
|
788
|
+
`)}static imageBlock(e){return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}}}async clientFor(e,t){if(!e)throw new fr("credential");const i=`${e}\0${t??""}`;if(this.client&&this.clientFor_===i)return this.client;const{default:s}=await oe(async()=>{const{default:n}=await import("./index-DQDuRMiM.js").then(r=>r.i);return{default:n}},[],import.meta.url);return this.client=new s({apiKey:e,...t?{defaultHeaders:{"anthropic-workspace-id":t}}:{},dangerouslyAllowBrowser:!0,maxRetries:1}),this.clientFor_=i,this.client}static read(e){if(e.stop_reason==="refusal")throw new fr("refused");const t=e.content.find(s=>s.type==="tool_use"&&s.name===jw.name);if(!t||t.type!=="tool_use")throw new fr("malformed");const i=t.input;if(typeof i?.recording!="object"||i.recording===null||Array.isArray(i.recording))throw new fr("malformed");return{recording:i.recording,claims:Array.isArray(i.claims)?i.claims.flatMap(s=>{const{path:n,basis:r,rationale:a}=s??{};return typeof n!="string"||typeof a!="string"?[]:[{path:n,basis:r==="derived"||r==="assumed"?r:"stated",rationale:a}]}):[],gaps:Array.isArray(i.gaps)?i.gaps.filter(s=>typeof s=="string"):[]}}static async diagnose(e,t){if(e instanceof fr)return e;if(t?.aborted)return new fr("cancelled",e);const{default:i}=await oe(async()=>{const{default:s}=await import("./index-DQDuRMiM.js").then(n=>n.i);return{default:s}},[],import.meta.url);return e instanceof i.AuthenticationError||e instanceof i.PermissionDeniedError?new fr("credential",e):e instanceof i.RateLimitError?new fr("rate-limited",e):e instanceof i.BadRequestError||e instanceof i.NotFoundError?new fr("rejected",e.message,e):e instanceof i.APIConnectionError?new fr("unreachable",e):new fr("malformed",e)}}const _p=[{id:"claude",name:"Claude",credit:"Anthropic",creditUrl:"https://www.anthropic.com/legal/consumer-terms",create:()=>new ga}],B5=[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async c=>{const{CoverageAssessor:e}=await oe(async()=>{const{CoverageAssessor:t}=await import("./CoverageAssessor-mvpHgNx3.js");return{CoverageAssessor:t}},[],import.meta.url);return new e().assess(c)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async c=>{const{HynekAssessor:e}=await oe(async()=>{const{HynekAssessor:t}=await import("./HynekAssessor-B9lO770Q.js");return{HynekAssessor:t}},__vite__mapDeps([2,3]),import.meta.url);return new e().assess(c)}})},{id:"ballester-guasp",name:"Ballester-Guasp",credit:"V.-J. Ballester-Olmos & M. Guasp",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Ballester-Guasp.html",create:()=>({about:"observer",assess:async c=>{const{BallesterGuaspAssessor:e}=await oe(async()=>{const{BallesterGuaspAssessor:t}=await import("./BallesterGuaspAssessor-gX_y6kL8.js");return{BallesterGuaspAssessor:t}},__vite__mapDeps([4,3,5]),import.meta.url);return new e().assess(c)}})},{id:"poher",name:"Poher",credit:"Claude Poher",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Poher-Criteres.html",create:()=>({about:"shape",assess:async c=>{const{PoherAssessor:e}=await oe(async()=>{const{PoherAssessor:t}=await import("./PoherAssessor-CzLQhAxP.js");return{PoherAssessor:t}},[],import.meta.url);return new e().assess(c)}})}];class Ry{constructor(e){this.labels=e}async read(e){const t=[],i=new Set;for(const s of B5){let n;try{n=await s.create().assess(e)}catch{continue}for(const a of n.criteria)a.basis===void 0&&!a.unsupported&&i.add(a.id);const r=n.score===void 0?n.verdict===void 0?"":this.verdictName(s.id,n.verdict):`${Math.round(n.score*100)}%`;r!==""&&t.push({group:"assessment",field:s.id,label:this.labels.assessmentNames[s.id]??s.name,value:r,unit:"",fromSource:!1,about:s.create().about,...n.factors?{detail:Ry.factorsText(n.factors)}:{}})}return{entries:t,unanswered:i}}static factorsText(e){const t={q:"Q",sigma:"Σ",pi:"Π"};return Object.entries(e).map(([i,s])=>`${t[i]??i} ${s.toFixed(2)}`).join(" × ")}verdictName(e,t){return this.labels.assessmentVerdicts[`${e}.${t}`]??t.toUpperCase()}}class Ma{static stated(e){return Ma.statedIn(e,[])}static apply(e,t,i){const s=structuredClone(e);for(const n of i){const r=n.split("."),a=Ma.read(t,r);a!==void 0&&Ma.write(s,r,structuredClone(a))}return s}static statedIn(e,t){const i=[];for(const[s,n]of Object.entries(e)){if(n===void 0)continue;const r=[...t,s];Ma.isPlainObject(n)?i.push(...Ma.statedIn(n,r)):i.push(r.join("."))}return i}static isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static read(e,t){let i=e;for(const s of t){if(!Ma.isPlainObject(i))return;i=i[s]}return i}static write(e,t,i){let s=e;for(const n of t.slice(0,-1)){const r=s[n];Ma.isPlainObject(r)||(s[n]={}),s=s[n]}s[t[t.length-1]]=i}}const H5={x:Lt.CANVAS_WIDTH_PX/2,y:Lt.CANVAS_HEIGHT_PX/2,width:1,height:1};class dm{static loadable(e){const t=e.decor?{decor:e.decor.map((s,n)=>dm.decor(s,n))}:{},i=e.timeline?.keyframes;return i?{...e,...t,timeline:{...e.timeline,keyframes:i.map(s=>({t:s.t??0,shapes:(s.shapes??[]).map(n=>({sourceId:n.sourceId,shape:dm.shape(n.shape)}))}))}}:{...e,...t}}static decor(e,t){const i=e.kind??"vehicle";return{...d0(i)?{windows:r2(i)}:{},...i==="building"?{floors:sd}:{},...e,id:e.id??`decor-${t+1}`,kind:i,eastM:e.eastM??0,northM:e.northM??0}}static shape(e){const t=e?.kind==="polygon"?"polygon":"oval";return{...t==="polygon"?{points:[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}]}:{},...e,kind:t,bounds:{...H5},color:typeof e?.color=="string"?e.color:"#e8e6df",angle:0,transparency:0,haloScale:0,selected:!1}}}class d2{static sync(e,t,i,s,n){if(e.querySelector(".param-description")?.remove(),t===void 0){e.removeAttribute("data-describing");return}const r=document.createElement("div");r.className="param-description";const a=document.createElement("div");a.className="param-description-head";const o=document.createElement("span");o.className="param-nest-label",o.textContent=i;const l=document.createElement("button");l.type="button",l.className="param-description-close",l.textContent="×",l.title=s,l.setAttribute("aria-label",s),l.addEventListener("click",n),a.append(o,l);const h=document.createElement("p");h.className="param-description-text",h.textContent=t,r.append(a,h),r.addEventListener("keydown",d=>{d.key==="Escape"&&n()}),e.setAttribute("data-describing",""),e.append(r),l.focus({preventScroll:!0})}static CSS=`
|
|
789
789
|
.param-summary[data-describing] > :not(.param-description) {
|
|
790
790
|
display: none;
|
|
791
791
|
}
|
|
@@ -4323,9 +4323,9 @@ canvas[data-cursor="rotate"] {
|
|
|
4323
4323
|
`;class oc{constructor(e){this.points=e}static STATIONARY_M=5;static of(e){const t=[];for(const i of e.observerTrack.allKeyframes){const{lat:s,lng:n,headingDeg:r}=i.pose;s===void 0||n===void 0||t.push({t:i.t,lat:s,lng:n,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 oc(t)}static TRAVEL_M=50;get travels(){return this.spanM>oc.TRAVEL_M}get moved(){return this.spanM>oc.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(ut(t,e.east,t,e.west).x),Math.abs(ut(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:s}=this.center,n=Math.max(this.spanM*(1+t),e)/2;return{north:Wn(0,-n,i,s).lat,south:Wn(0,n,i,s).lat,east:Wn(n,0,i,s).lng,west:Wn(-n,0,i,s).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 Dr{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){if(e.instrument.mounted)return;const t=e.event.tags?.includes("paralysis")||(e.exposure??0)>Dr.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new Dr(Math.max(1-(e.instrument.stabilization??0),Dr.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,s=(d,u)=>Math.sin(2*Math.PI*d*t+u),[n,r,a,o,l,h]=Dr.HZ;return{eastM:i*Dr.SWAY_M*(.7*s(n,.3)+.3*s(o,1.9)),northM:i*Dr.SWAY_M*(.6*s(a,2.2)+.4*s(l,.8)),upM:i*Dr.BREATH_M*s(r,0),yawDeg:i*this.rotationPassed*Dr.DRIFT_YAW_DEG*(.6*s(h,1.1)+.4*s(o,2.7)),pitchDeg:i*this.rotationPassed*Dr.DRIFT_PITCH_DEG*(.5*s(r,1.6)+.5*s(a,.4)),rollDeg:i*this.rotationPassed*Dr.DRIFT_ROLL_DEG*s(n,2.9)}}}class bi{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=oc.of(e);if(!t||t.points.length<2)return;const i=[];let s=0;for(let n=1;n<t.points.length;n++){const r=t.points[n-1],a=t.points[n],o=(a.t-r.t)/1e3;if(o<=0)continue;const l=ut(a.lat,a.lng,r.lat,r.lng),h=l.x,d=-l.z,u=Math.hypot(h,d),p=u/o,f=bi.stepHzFor(p);i.push({startMs:r.t,endMs:a.t,speedMPerS:p,eastUnit:u>0?h/u:0,northUnit:u>0?d/u:0,stepHz:f,stepsBefore:s,rampsIn:!0,rampsOut:!0}),s+=f*o}for(let n=0;n<i.length;n++){const r=i[n-1],a=i[n+1];i[n].rampsIn=r===void 0||r.stepHz===0,i[n].rampsOut=a===void 0||a.stepHz===0}if(i.some(n=>n.stepHz>0))return new bi(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const s=bi.of(e)?.offsetAt(t)??bi.STILL;return i?s:bi.add(s,Dr.of(e)?.offsetAt(t))}static stepHzFor(e){return e<bi.SLOWEST_WALK_M_PER_S||e>bi.FASTEST_WALK_M_PER_S?0:bi.REFERENCE_STEP_HZ*Math.pow(e/bi.REFERENCE_SPEED_M_PER_S,bi.CADENCE_EXPONENT)}offsetAt(e){return bi.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/bi.REFERENCE_SPEED_M_PER_S,s=(a,o,l,h)=>{if(a<0||a>bi.JOLT_LASTS_MS)return;const d=a/1e3,u=Math.exp(-d/bi.JOLT_DECAY_S)*Math.sin(2*Math.PI*bi.JOLT_HZ*d),p=h*o*i*u;return{eastM:p*t.eastUnit,northM:p*t.northUnit,upM:-Math.abs(p)*.3,rollDeg:0,pitchDeg:-h*l*i*u*this.rotationPassed,yawDeg:0}},n=t.rampsOut?s(e-t.endMs,bi.STOP_LURCH_M,bi.STOP_PITCH_DEG,1):void 0;if(n)return n;const r=t.rampsIn?s(e-t.startMs,bi.START_LURCH_M,bi.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(e,t){return t?{eastM:e.eastM+t.eastM,northM:e.northM+t.northM,upM:e.upM+t.upM,rollDeg:e.rollDeg+t.rollDeg,pitchDeg:e.pitchDeg+t.pitchDeg,yawDeg:e.yawDeg+t.yawDeg}:e}cycleAt(e){const t=this.stretches.find(o=>e>=o.startMs&&e<=o.endMs);if(!t||t.stepHz===0)return bi.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,s=2*Math.PI*i,n=this.amplitudeAt(t,e),r=bi.SWAY_M*n*Math.cos(s/2),a=n*this.rotationPassed*t.speedMPerS/bi.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:bi.RISE_M_PER_M_PER_S*t.speedMPerS*n*Math.cos(s),rollDeg:bi.HEAD_ROLL_DEG*a*Math.cos(s/2),pitchDeg:-1.25*a*Math.cos(s),yawDeg:bi.HEAD_YAW_DEG*a*Math.cos(s/2)}}amplitudeAt(e,t){const i=1e3/e.stepHz,s=Math.min(i,(e.endMs-e.startMs)/2);if(s<=0)return 1;const n=t-e.startMs,r=e.endMs-t,a=Math.min(e.rampsIn?n/s:1,e.rampsOut?r/s:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class K5{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 s=this.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}this.onFrame(e,t)}}class lc{static sessionDeclared=!1;static unlock(e){if(lc.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(!(lc.sessionDeclared||typeof navigator>"u")){lc.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const Zw=.05,Jw=.08,Qw=2,eM=3,X5=14,Y5=.02;class q5{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}}lc.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 s=i.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,s,Zw);for(const{param:n,ratio:r}of e.pitch)n.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),s,Zw)}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 s=e.createOscillator();s.type="sawtooth";const n=e.createBiquadFilter();n.type="lowpass",n.Q.value=1;const r=e.createGain();return r.gain.value=0,i.connect(n),s.connect(n),n.connect(r).connect(this.output(e)),i.start(),s.start(),{key:t,nodes:[n,r],sources:[i,s],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:s.frequency,ratio:1.006},{param:n.frequency,ratio:6}]}}buildWhistle(e,t){const i=e.createOscillator();i.type="sine";const s=e.createOscillator();s.type="sine",s.frequency.value=5;const n=e.createGain(),r=e.createGain();return r.gain.value=0,s.connect(n).connect(i.frequency),i.connect(r).connect(this.output(e)),i.start(),s.start(),{key:t,nodes:[n,r],sources:[i,s],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:n.gain,ratio:.012}]}}buildRumble(e,t){const i=e.createBufferSource();i.buffer=this.brownNoise(e),i.loop=!0;const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=.8;const n=e.createGain();return n.gain.value=0,i.connect(s).connect(n).connect(this.output(e)),i.start(),{key:t,nodes:[s,n],sources:[i],volumeParam:n.gain,gainScale:1.4,pitch:[{param:s.frequency,ratio:1}]}}buildCrackle(e,t){const i=e.createBufferSource();i.buffer=this.whiteNoise(e),i.loop=!0;const s=e.createBiquadFilter();s.type="bandpass",s.Q.value=1.2;const n=e.createGain();n.gain.value=0;const r=e.createBufferSource();r.buffer=this.crackleEnvelope(e),r.loop=!0;const a=e.createGain();return a.gain.value=0,r.connect(a).connect(n.gain),i.connect(s).connect(n).connect(this.output(e)),i.start(),r.start(),{key:t,nodes:[s,n,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:s.frequency,ratio:4}]}}async buildRecordedVoice(e,t,i){const s=this.context;if(!s)return;let n;try{n=await this.getBuffer(e)}catch(o){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",o);return}if(i!==this.voiceToken||!this.context)return;const r=s.createBufferSource();r.buffer=n,r.loop=!0;const a=s.createGain();a.gain.value=0,r.connect(a).connect(this.output(s)),r.start(),this.voice={key:t,nodes:[a],sources:[r],volumeParam:a.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(e){const t=this.context;if(!t)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,i)),i}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*Qw),e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*Qw),e.sampleRate),i=t.getChannelData(0);let s=0,n=0;for(let r=0;r<i.length;r++)s=(s+.02*(Math.random()*2-1))/1.02,i[r]=s,n=Math.max(n,Math.abs(s));if(n>0)for(let r=0;r<i.length;r++)i[r]/=n;return t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*eM),e.sampleRate),i=t.getChannelData(0),s=Math.max(1,Math.floor(Y5*e.sampleRate)),n=Math.round(eM*X5);for(let r=0;r<n;r++){const a=Math.floor(Math.random()*i.length),o=.4+Math.random()*.6;for(let l=0;l<s&&a+l<i.length;l++)i[a+l]=Math.max(i[a+l],o*(1-l/s))}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,Jw/3);const s=i+Jw;for(const n of e.sources){n.onended=()=>{n.disconnect();for(const r of e.nodes)r.disconnect()};try{n.stop(s)}catch{n.disconnect();for(const r of e.nodes)r.disconnect()}}}}class xa{static KINDS=["beams","launches","reentries"];static isEmpty(e){return!e||xa.KINDS.every(t=>!e[t]?.length)}static written(e){if(xa.isEmpty(e))return;const t={};for(const i of xa.KINDS)e[i]?.length&&(t[i]=e[i]);return t}static read(e,t){const i=t,s={};for(const r of xa.KINDS){const a=[...e?.[r]??[],...i?.[r]??[]];a.length>0&&(s[r]=a)}let n=t;if(i&&xa.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:o,...l}=i;n=xa.isReading(l)?l:void 0}return{skyEvents:xa.written(s),interpretation:n}}static isReading(e){return(e.bodies?.length??0)>0||e.title!==void 0||(e.smoke?.length??0)>0}}function cc(c){return[...c].sort((e,t)=>e.t-t.t)}function V0(c,e){let t;for(const i of cc(c)){if(i.t>e)break;t=i}return t}class vn{static restatedDecor(e){const t=vn.originOf(e);return e.decor.map(i=>{let s=i;if(i.saidPosition){const n=vn.restated(i.saidPosition,i,vn.frameAt(e,0,t,i.id));JSON.stringify(n)!==JSON.stringify(i.saidPosition)&&(s={...i,saidPosition:n},n||delete s.saidPosition)}if(i.track?.some(n=>n.saidPosition)){const n=i.track.map(r=>{if(!r.saidPosition)return r;const a=vn.restated(r.saidPosition,r,vn.frameAt(e,r.t,t,i.id));if(JSON.stringify(a)===JSON.stringify(r.saidPosition))return r;const o={...r,saidPosition:a};return a||delete o.saidPosition,o});s={...s,track:n}}return s})}static restatedObserverTrack(e){const t=e.observerTrack.toJSON(),i=vn.originOf(e);return!i||!t.keyframes.some(s=>s.pose.saidPosition)?t:{...t,keyframes:t.keyframes.map(s=>{const{pose:n}=s;if(!n.saidPosition||n.lat===void 0||n.lng===void 0)return s;const r=si.toLocal({lat:n.lat,lng:n.lng},i),a=vn.restated(n.saidPosition,r,vn.frameAt(e,s.t,i));if(JSON.stringify(a)===JSON.stringify(n.saidPosition))return s;const o={...n,saidPosition:a};return a||delete o.saidPosition,{...s,pose:o}})}}static restatedInterpretation(e){const t=e.interpretation;if(!t?.bodies.some(s=>s.track.some(n=>n.saidPosition)))return t;const i=vn.originOf(e);return{...t,bodies:t.bodies.map(s=>s.track.some(n=>n.saidPosition)?{...s,track:s.track.map(n=>{if(!n.saidPosition)return n;const r=n.eastM!==void 0&&n.northM!==void 0?vn.restated(n.saidPosition,{eastM:n.eastM,northM:n.northM},vn.frameAt(e,n.t,i)):void 0;if(JSON.stringify(r)===JSON.stringify(n.saidPosition))return n;const a={...n,saidPosition:r};return r||delete a.saidPosition,a})}:s)}}static originOf(e){const t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return typeof s=="number"&&typeof n=="number"?{lat:s,lng:n}:void 0}static frameAt(e,t,i,s){const n=[{label:"",eastM:0,northM:0},...e.decor.filter(r=>r.id!==s).map(r=>{const{eastM:a,northM:o}=Mr(r,t);return{id:r.id,label:r.id,eastM:a,northM:o}})];return{origin:i,references:n}}static restated(e,t,i){return si.restated(e,{eastM:t.eastM,northM:t.northM},i)}}function um(c){return Un.restore(Yv(c),c.provenance)}function Yv(c,e=!1){return Si.toAngular(c),Si.toAim(c),{version:3,id:c.id,time:pm.write(c.event.time),endTime:pm.write(c.event.endTime),durationSeconds:c.event.durationSeconds,durationText:c.event.durationText,utcOffsetHours:c.event.utcOffsetHours,timeZone:c.event.timeZone,place:u2.write(c.event.place),observer:c.observer,account:c.account,sources:c.sources?.length?c.sources:void 0,sway:c.sway,vehicle:c.vehicle,description:c.event.description,image:c.event.image,summary:c.event.summary,summaryTime:c.event.summaryTime,tags:c.event.tags,timeline:!e&<.timelineIsExpanded(c)?lt.timelineWithoutShapes(c):c.timeline.toJSON(),observerTrack:!e&<.observerTrackIsExpanded(c)?void 0:vn.restatedObserverTrack(c),events:c.events?.length?c.events:void 0,weatherTrack:c.weatherTrack.toJSON(),soundTrack:c.soundTrack.toJSON(),weather:c.weather,decor:vn.restatedDecor(c).map(t=>{if(!e&&t.lights&&(t={...t,lights:lt.writtenLights(c,t.id,t.lights)}),e||!lt.decorTrackIsExpanded(c,t.id,t.track))return t;const{track:i,...s}=t;return s}),milestones:c.milestones.length>0?c.milestones:void 0,references:c.references.length>0?c.references:void 0,roads:c.roads.length>0?c.roads:void 0,traces:c.traces.length>0?c.traces:void 0,weatherSource:c.weatherSource,instrument:c.instrumentId,exposureSeconds:c.exposureSeconds,iso:c.iso,metering:c.metering,sampleMs:c.sampleMs,lens:c.lens,lightPollution:c.lightPollution,observerMap:c.observerMap,interpretation:e?vn.restatedInterpretation(c):lt.writtenInterpretation(c,vn.restatedInterpretation(c)),variants:c.variants.length>0?c.variants:void 0,skyEvents:xa.written(c.skyEvents),frozen:c.frozen}}function ky(c){il.check(c,"sighting");const e=Ui.toCurrent(c),{recording:t,provenance:i}=Un.strip(e),s=j5(t);return s.provenance=i,s}function j5(c){const e=[],t=new s0({eventType:"sighting",time:pm.read(c.time),endTime:pm.read(c.endTime),durationSeconds:c.durationSeconds,durationText:c.durationText,utcOffsetHours:c.utcOffsetHours,timeZone:c.timeZone,place:u2.read(c.place),description:c.description,image:c.image,summary:c.summary,summaryTime:c.summaryTime,tags:c.tags},dp.fromJSON(c.timeline,e,!1),c.observerTrack?Mu.fromJSON(c.observerTrack):new Mu,c.weatherTrack?xu.fromJSON(c.weatherTrack):new xu,c.soundTrack?Su.fromJSON(c.soundTrack):new Su,c.observer&&{id:c.observer.id,title:c.observer.title,lastName:c.observer.lastName,firstNames:c.observer.firstNames},c.id,c.weather,(c.decor??[]).map(s=>{if(!s.facade?.plain)return s;const{plain:n,...r}=s.facade;return{...s,facade:{...r,openings:"plain"}}}),c.weatherSource,c.instrument,c.exposureSeconds??c.observerTrack?.keyframes.map(s=>s.pose.exposureSeconds).find(s=>s!==void 0),cc(c.milestones??[]),c.references??[],c.roads??[],c.traces??[]);t.account=c.account,t.sources=c.sources,t.sway=c.sway,t.iso=c.iso,t.metering=c.metering,t.sampleMs=c.sampleMs,t.lens=c.lens,t.lightPollution=c.lightPollution,t.observerMap=c.observerMap,t.vehicle=c.vehicle,t.events=c.events?.map(s=>s.who===void 0?{...s,who:Ui.observerIdOf(c)}:s);const i=xa.read(c.skyEvents,c.interpretation);return t.interpretation=i.interpretation,t.variants=Array.isArray(c.variants)?c.variants:[],t.skyEvents=i.skyEvents,t.frozen=c.frozen,t.loadIssues=e,lt.expand(t),t.timeline.pruneGroups(),Si.toBounds(t),Si.toPosition(t),lt.settle(t),t}class pm{static read(e){return e===void 0||e.trim()===""?void 0:Jd(e)}static write(e){if(e===void 0)return;const t=cl(e);return t===""?void 0:t}}class u2{static read(e){if(e?.locations?.length)return e.locations.map(({lat:t,lng:i})=>({lat:t,lng:i,...e.name===void 0?{}:{name:e.name}}))}static write(e){if(!e?.length)return;const t=e.find(i=>i.name)?.name;return{...t===void 0?{}:{name:t},locations:e.map(({lat:i,lng:s})=>({lat:i,lng:s}))}}}class rd{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=rd.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(s=>` ${rd.text(s)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
|
|
4324
4324
|
${i.join(`
|
|
4325
4325
|
`)}`)}}class $r{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,s){if(!$r.isObject(e)){s.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:$r.typeOf(e)});return}for(const[n,r]of Object.entries(e)){const a=i?`${i}.${n}`:n,o=t[n];o?this.field(r,o,a,s):s.push({kind:"unknown-key",path:a})}}field(e,t,i,s){if($r.isStated(e)){this.field(e.value,t,i,s);return}if(!(t.loose||e===void 0||e===null))switch(t.type){case"enum":(typeof e!="string"||!t.values?.includes(e))&&s.push({kind:"not-in-list",path:i,expected:(t.values??[]).map(n=>`"${n}"`).join(", "),found:JSON.stringify(e)});return;case"object":t.fields?this.object(e,t.fields,i,s):$r.isObject(e)||s.push({kind:"wrong-type",path:i,expected:"object",found:$r.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((n,r)=>{const a=$r.isStated(n)?n.value:n;this.object(a,t.fields,`${i}.${r}`,s)}):s.push({kind:"wrong-type",path:i,expected:"array",found:$r.typeOf(e)});return;default:typeof e!==t.type&&s.push({kind:"wrong-type",path:i,expected:t.type,found:$r.typeOf(e)})}}static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return $r.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 Zr{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,s=Math.max(0,e-i*1e3),n=Math.max(0,e-s);return{fromMs:s,toMs:e,ms:n,seconds:n/1e3}}static instants(e,t,i,s,n){if(!(s>0))return 1;const r=n>0?Zr.travelDegOver(e,t,i,i+s*1e3)/n/Zr.PIXELS_PER_INSTANT:0,a=Zr.flashesOver(e,s)*Zr.INSTANTS_PER_FLASH,o=Math.ceil(Math.max(r,a));return o<2?1:Math.min(Zr.MAX_INSTANTS,o)}static travelDegOver(e,t,i,s){let n=0;for(const r of e){if(!r.track||r.track.length<2)continue;const a=Zr.directionAt(r,t,i),o=Zr.directionAt(r,t,s),l=Math.min(1,Math.max(-1,a.x*o.x+a.y*o.y+a.z*o.z));n=Math.max(n,Math.acos(l)*180/Math.PI)}return n}static flashesOver(e,t){let i=0;for(const s of e)for(const n of s.lights??[])n.pattern.kind==="flash"&&(i=Math.max(i,n.pattern.perMinute));return i/60*t}static directionAt(e,t,i){const s=Mr(e,i),n=s.eastM,r=s.altitudeM-t,a=s.northM,o=Math.hypot(n,r,a);return o===0?{x:0,y:1,z:0}:{x:n/o,y:r/o,z:a/o}}}const p2={play:"Play",clickToPlay:"Click to play",pause:"Pause",noDuration:"No observation duration",currentPosition:"Current position",duration:"Duration",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",mute:"Mute",unmute:"Unmute",noSound:"No sound recorded",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",referencesMenu:"Pictures of the place",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:rd.EN},Z5=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:p2},Symbol.toStringTag,{value:"Module"})),f2=Math.PI/180,J5=180/Math.PI,Q5=256,m2=19,e_=1.25;function g2(c,e){return 156543.03392*Math.cos(c*f2)/2**e}function v2(c,e){return g2(c,e)*Q5}function t_(c,e){let t=0;for(;t<m2&&v2(c,t+1)>=e;)t++;return t}function b2(c,e){return v2(c,e)}function i_(c,e){const t=e*e_;let i=0;for(;i<m2&&g2(c,i)>t;)i++;return i}function Pf(c){const e=c*f2;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function y2(c,e,t){const i=2**t;return{x:(c+180)/360*i,y:Pf(e)*i}}function w2(c,e,t){const i=Pf(c.north),s=Pf(c.south);return{x:(e-c.west)/(c.east-c.west),y:(Pf(t)-i)/(s-i)}}function s_(c,e,t){const{x:i,y:s}=y2(c,e,t);return{x:Math.floor(i),y:Math.floor(s),z:t}}function n_(c){const e=2**c.z,t=c.x/e*360-180,i=(c.x+1)/e*360-180,s=tM(c.y,e);return{south:tM(c.y+1,e),north:s,west:t,east:i}}function tM(c,e){const t=c/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*J5}function M2(c,e,t,i){const s=s_(c,e,t),n=Math.floor(i/2),r=[];for(let l=-n;l<=n;l++)for(let h=-n;h<=n;h++)r.push({x:s.x+h,y:s.y+l,z:t});const a=r.map(n_),o={south:Math.min(...a.map(l=>l.south)),north:Math.max(...a.map(l=>l.north)),west:Math.min(...a.map(l=>l.west)),east:Math.max(...a.map(l=>l.east))};return{tiles:r,bounds:o}}const r_="#2ec4ff";class Vl{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,s=1/0;for(const n of this.targets){const r=Math.hypot(n.x-e,n.y-t);r>n.radius||r>s||(i=n,s=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 s=w2(e,i,t);return{x:s.x*this.width,y:s.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 s=this.toCanvas(e.bounds,i.bounds.north,i.bounds.west),n=this.toCanvas(e.bounds,i.bounds.south,i.bounds.east);t.drawImage(i.source,s.x,s.y,n.x-s.x,n.y-s.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 s=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:s.x,y:s.y,radius:7}),t.beginPath(),t.rect(s.x-3.5,s.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 n=(i.headingDeg-90)*Math.PI/180;t.beginPath(),t.moveTo(s.x,s.y),t.lineTo(s.x+Math.cos(n)*10,s.y+Math.sin(n)*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(s=>this.toCanvas(e.bounds,s.lat,s.lng));t.beginPath(),t.moveTo(i[0].x,i[0].y);for(const s of i.slice(1))t.lineTo(s.x,s.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 s=i.points.map(r=>this.toCanvas(e.bounds,r.lat,r.lng));if(s.length===0)continue;const n=i.color??r_;if(i.kind==="point")t.beginPath(),t.moveTo(s[0].x,s[0].y-6),t.lineTo(s[0].x+6,s[0].y),t.lineTo(s[0].x,s[0].y+6),t.lineTo(s[0].x-6,s[0].y),t.closePath(),t.fillStyle=n,t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.8)",t.stroke();else{t.beginPath(),t.moveTo(s[0].x,s[0].y);for(const r of s.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=n,t.lineWidth=2.5,t.stroke(),t.setLineDash([])}if(i.label){t.font="11px sans-serif",t.textAlign="left",t.textBaseline="middle";let r=s[0];if(i.kind==="line"&&e.position){const a=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=s.reduce((o,l)=>Math.hypot(l.x-a.x,l.y-a.y)>Math.hypot(o.x-a.x,o.y-a.y)?l:o)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(e,t){const{headingDeg:i,coneHalfAngleDeg:s}=e;if(i===void 0||s===void 0)return;const{ctx:n}=this,r=this.toCanvas(e.bounds,t.lat,t.lng),a=Math.hypot(this.width,this.height),o=(i-90)*Math.PI/180,l=s*Math.PI/180;n.save(),n.beginPath(),n.moveTo(r.x,r.y),n.arc(r.x,r.y,a,o-l,o+l),n.closePath();const h=n.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),n.fillStyle=h,n.fill(),n.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((s,n)=>Number(s.current)-Number(n.current))){const s=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:s.x,y:s.y,radius:Vl.MARKER_RADIUS_PX}),t.beginPath(),t.arc(s.x,s.y,Vl.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,s.x,s.y)}}paintObserver(e,t){const{ctx:i}=this,s=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:s.x,y:s.y,radius:8});const n=e.markers.some(r=>{if(!r.current)return!1;const a=ut(r.lat,r.lng,t.lat,t.lng);return Math.hypot(a.x,a.z)<=Vl.ON_MARKER_M});i.beginPath(),i.arc(s.x,s.y,n?Vl.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),n||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=n?3:2.5,i.strokeStyle=n?"#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 s=t?this.wrap(t,this.width-20):[];let n=this.height-4;i.textAlign="right";for(const p of s.slice().reverse())this.paintOutlinedText(p,this.width-6,n),n-=11;const r=(e.south+e.north)/2,o=Math.abs(ut(r,e.east,r,e.west).x)/this.width,l=Vl.SCALE_STEPS_M.find(p=>p/o<=this.width/3);if(l===void 0)return;const h=l/o,d=8,u=n-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(l>=1e3?`${l/1e3} km`:`${l} m`,d,u-3)}paintOutlinedText(e,t,i){const{ctx:s}=this;s.lineWidth=3,s.strokeStyle="rgba(0, 0, 0, 0.75)",s.strokeText(e,t,i),s.fillStyle="#fff",s.fillText(e,t,i)}wrap(e,t){const i=[];let s="";for(const n of e.split(" ")){const r=s?`${s} ${n}`:n;s&&this.ctx.measureText(r).width>t?(i.push(s),s=n):s=r}return s&&i.push(s),i}}class hi{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(e,t){return hi.including(e.boundsAround(hi.MIN_SPAN_M,hi.MARGIN),t)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(e,t,i){const s=Math.min(hi.MAX_ZOOM,Math.max(hi.MIN_ZOOM,this.zoom*i)),n=this.centerX+(e-.5)/this.zoom,r=this.centerY+(t-.5)/this.zoom;this.centerX=n-(e-.5)/s,this.centerY=r-(t-.5)/s,this.zoom=s}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),s=hi.mercatorY01(t.north),n=hi.mercatorY01(t.south),r=hi.mercatorY01(i.north),a=hi.mercatorY01(i.south);this.zoom=(t.east-t.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-t.west)/(t.east-t.west),this.centerY=((r+a)/2-s)/(n-s)}keepInView(e,t,i){if(!this.changed)return!1;const s=this.boundsWithin(e),n=hi.mercatorY01(s.north),r=hi.mercatorY01(s.south),a=(t.lng-s.west)/(s.east-s.west),o=(hi.mercatorY01(t.lat)-n)/(r-n);return a>=i&&a<=1-i&&o>=i&&o<=1-i?!1:(this.panBy(.5-a,.5-o),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=hi.mercatorY01(e.north),s=hi.mercatorY01(e.south),n=e.east-e.west;return{west:e.west+(this.centerX-t)*n,east:e.west+(this.centerX+t)*n,north:hi.latitudeAt(i+(this.centerY-t)*(s-i)),south:hi.latitudeAt(i+(this.centerY+t)*(s-i))}}static including(e,t,i=3){const s=(e.north+e.south)/2,n=(e.east+e.west)/2,r=ut(s,e.east,s,n).x;let a=r;for(const o of t){const{x:l,z:h}=ut(o.lat,o.lng,s,n),d=Math.max(Math.abs(l),Math.abs(h));d<=r*i&&(a=Math.max(a,d*1.15))}return a<=r?e:{north:Wn(0,-a,s,n).lat,south:Wn(0,a,s,n).lat,east:Wn(a,0,s,n).lng,west:Wn(-a,0,s,n).lng}}static expand(e,t){const i=e.east-e.west,s=e.north-e.south;return{west:e.west-i*t,east:e.east+i*t,south:e.south-s*t,north:e.north+s*t}}static pointAt(e,t,i){const s=hi.mercatorY01(e.north),n=hi.mercatorY01(e.south);return{lat:hi.latitudeAt(s+i*(n-s)),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 Ir=256,iM=3,a_=32768;class x2{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,s=(e.west+e.east)/2,n=Math.abs(ut(i,e.east,i,e.west).x),r=Math.abs(ut(e.north,s,e.south,s).z),a=t_(i,Math.max(n,r)),{tiles:o}=M2(s,i,a,iM),l=iM*Ir,h=new Float32Array(l*l),d=o[0];await Promise.all(o.map(p=>this.decodeTileInto(p,d,h,l)));const u=new Float32Array(t.width*t.height);for(let p=0;p<t.height;p++){const f=e.north+(e.south-e.north)*(p/(t.height-1));for(let m=0;m<t.width;m++){const v=e.west+(e.east-e.west)*(m/(t.width-1));u[p*t.width+m]=this.sampleAt(f,v,a,d,h,l)}}return{heights:u,width:t.width,height:t.height,bounds:e}}async decodeTileInto(e,t,i,s){const n=this.tileUrlTemplate.replace("{z}",String(e.z)).replace("{x}",String(e.x)).replace("{y}",String(e.y)),r=await this.fetchImpl(n);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${n}`);const a=await createImageBitmap(await r.blob()),o=document.createElement("canvas");o.width=Ir,o.height=Ir;const l=o.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(a,0,0);const{data:h}=l.getImageData(0,0,Ir,Ir),d=(e.x-t.x)*Ir,u=(e.y-t.y)*Ir;for(let p=0;p<Ir;p++)for(let f=0;f<Ir;f++){const m=(p*Ir+f)*4,v=h[m]*256+h[m+1]+h[m+2]/256-a_,g=d+f,b=u+p;i[b*s+g]=v}}sampleAt(e,t,i,s,n,r){const{x:a,y:o}=y2(t,e,i),l=(a-s.x)*Ir,h=(o-s.y)*Ir,d=Math.max(0,Math.min(r-1,Math.floor(l))),u=Math.max(0,Math.min(r-1,Math.floor(h))),p=Math.min(r-1,d+1),f=Math.min(r-1,u+1),m=l-d,v=h-u,g=n[u*r+d],b=n[u*r+p],w=n[f*r+d],y=n[f*r+p],M=g+(b-g)*m,S=w+(y-w)*m;return M+(S-M)*v}}class p0{constructor(e,t,i,s){this.width=e,this.height=t,this.samples=i,this.values=s}at(e,t,i=0){return this.values[(t*this.width+e)*this.samples+i]}static parse(e){const t=new DataView(e);if(e.byteLength<8||t.getUint16(0)!==18761||t.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=t.getUint32(4,!0),s=t.getUint16(i,!0),n=new Map;for(let g=0;g<s;g++){const b=i+2+g*12;n.set(t.getUint16(b,!0),{type:t.getUint16(b+2,!0),count:t.getUint32(b+4,!0),value:t.getUint32(b+8,!0)})}const r=(g,b)=>{const w=n.get(g);if(w===void 0){if(b===void 0)throw new Error(`TIFF without tag ${g}`);return b}return w.type===3?w.value&65535:w.value},a=g=>{const b=n.get(g);if(b===void 0)throw new Error(`TIFF without tag ${g}`);const w=b.type===3?2:4,y=[];if(b.count*w<=4){const M=new DataView(new ArrayBuffer(4));M.setUint32(0,b.value,!0);for(let S=0;S<b.count;S++)y.push(w===2?M.getUint16(S*2,!0):M.getUint32(0,!0))}else for(let M=0;M<b.count;M++)y.push(w===2?t.getUint16(b.value+M*2,!0):t.getUint32(b.value+M*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(n.has(322))throw new Error("Tiled TIFF");const o=r(256),l=r(257),h=r(277,1),d=a(258)[0],u=r(339,1)===3;if(!(u&&d===32||!u&&d===8))throw new Error(`Unsupported TIFF samples: ${d} bits`);const p=a(273),f=a(279),m=new Uint8Array(o*l*h*(d/8));let v=0;for(let g=0;g<p.length&&v<m.length;g++){const b=Math.min(f[g],m.length-v);m.set(new Uint8Array(e,p[g],b),v),v+=b}if(v<m.length)throw new Error("Truncated TIFF");return new p0(o,l,h,u?new Float32Array(m.buffer):m)}}class o_{constructor(e,t,i,s,n){this.heights=e,this.plants=t,this.buildings=i,this.size=s,this.metresPerPixel=n}structureAt(e,t){const i=Math.floor(e/this.metresPerPixel+this.size/2),s=Math.floor(this.size/2-t/this.metresPerPixel);if(i<0||s<0||i>=this.size||s>=this.size)return;const n=s*this.size+i;if(!(this.plants[n]||this.buildings[n]))return this.heights[n]}tallestStructureNear(e,t,i){let s;const n=Math.ceil(i/this.metresPerPixel);for(let r=-n;r<=n;r++)for(let a=-n;a<=n;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const o=this.structureAt(e+a*this.metresPerPixel,t+r*this.metresPerPixel);o!==void 0&&(s===void 0||o>s)&&(s=o)}return s}}class ke{static METRES_PER_DEGREE=111320;static MIN_BRIDGE_M=4;static DEFAULT_DECK_M=6;static FOOTBRIDGE_DECK_M=2.5;static DECK_MARGIN_M=2.4;static JOIN_M=1;static JOIN_DEG=25;static RAIL_MATCH_M=6;static ROAD_MATCH_M=12;static DECK_SEEN_M=1.5;static DECK_STEP_M=.5;static DECK_GAP_M=2;static DECK_REACH_M=20;static DECK_MEETS_M=.3;static DECK_BEARING_M=4;static DEFAULT_DECK_HEIGHT_M=4;static MIN_POLE_M=6;static MAX_POLE_M=70;static MAX_SPAN_M=800;static MAX_LINES=16;static BY_VOLTAGE=[{upToKv:25,poleM:11,dropM:1.2,spreadM:.8},{upToKv:70,poleM:20,dropM:3,spreadM:3},{upToKv:100,poleM:22,dropM:3.5,spreadM:3.5},{upToKv:170,poleM:27,dropM:4.5,spreadM:4.5},{upToKv:250,poleM:32,dropM:5.5,spreadM:5.5},{upToKv:1e3,poleM:42,dropM:7,spreadM:7.5}];static toMetres(e,t){const[i,s]=e;return{east:(i-t.lng)*ke.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180),north:(s-t.lat)*ke.METRES_PER_DEGREE}}static path(e,t){return e.geometry.type!=="LineString"?[]:e.geometry.coordinates.map(i=>ke.toMetres(i,t))}static bearing(e,t){return(Math.atan2(t.east-e.east,t.north-e.north)*180/Math.PI+360)%360}static distanceToSegment(e,t,i){const s=i.east-t.east,n=i.north-t.north,r=s*s+n*n,a=r===0?0:Math.max(0,Math.min(1,((e.east-t.east)*s+(e.north-t.north)*n)/r));return Math.hypot(e.east-(t.east+a*s),e.north-(t.north+a*n))}static bridges(e,t,i,s){const n=e.elevatedRoads.map(o=>({path:ke.path(o,t),properties:o.properties})),r=(e.elevatedRailways??[]).map(o=>ke.path(o,t)),a=[];for(const o of ke.joined(e.bridges.map(l=>ke.path(l,t)))){const l=o[0],h=o[o.length-1],d=Math.hypot(h.east-l.east,h.north-l.north);if(d<ke.MIN_BRIDGE_M)continue;const u={east:(l.east+h.east)/2,north:(l.north+h.north)/2};if(Math.hypot(u.east,u.north)>i+d/2||ke.carriesRailway(l,h,r))continue;const[p,f]=ke.deckReach(l,h,s);a.push({eastM:ke.tenth((p.east+f.east)/2),northM:ke.tenth((p.north+f.north)/2),lengthM:ke.tenth(Math.hypot(f.east-p.east,f.north-p.north)),widthM:ke.roadOf(u,n).width,heightM:ke.tenth(ke.deckHeight(l,h,s)),headingDeg:ke.tenth(ke.bearing(l,h)%180),...ke.roadOf(u,n).name?{name:ke.roadOf(u,n).name}:{}})}return a.sort((o,l)=>Math.hypot(o.eastM,o.northM)-Math.hypot(l.eastM,l.northM)),a}static carriesRailway(e,t,i){const s={east:(e.east+t.east)/2,north:(e.north+t.north)/2},n=ke.bearing(e,t)%180;for(const r of i)for(let a=0;a+1<r.length;a++){if(ke.distanceToSegment(s,r[a],r[a+1])>ke.RAIL_MATCH_M)continue;const o=Math.abs(ke.bearing(r[a],r[a+1])%180-n);if(Math.min(o,180-o)<=ke.JOIN_DEG)return!0}return!1}static joined(e){const t=e.filter(i=>i.length>=2);for(let i=0;i<t.length;i++)for(let s=i+1;s<t.length;s++){const n=ke.join(t[i],t[s]);n!==void 0&&(t[i]=n,t.splice(s,1),s=i)}return t}static join(e,t){for(const i of[e,[...e].reverse()])for(const s of[t,[...t].reverse()]){const n=i[i.length-1],r=s[0];if(Math.hypot(n.east-r.east,n.north-r.north)>ke.JOIN_M)continue;const a=Math.abs(ke.bearing(i[0],n)-ke.bearing(r,s[s.length-1]));if(Math.min(a,360-a)<=ke.JOIN_DEG)return[...i,...s.slice(1)]}}static roadOf(e,t){let i;for(const a of t)for(let o=0;o+1<a.path.length;o++){const l=ke.distanceToSegment(e,a.path[o],a.path[o+1]);(i===void 0||l<i.distance)&&(i={distance:l,properties:a.properties})}if(i===void 0||i.distance>ke.ROAD_MATCH_M)return{width:ke.DEFAULT_DECK_M};const s=[i.properties.nom_voie_ban_gauche,i.properties.nom_voie_ban_droite,i.properties.cpx_toponyme_route_nommee].find(a=>typeof a=="string"&&a.length>0),n=Number(i.properties.largeur_de_chaussee),r=Number.isFinite(n)&&n>0?ke.tenth(n+ke.DECK_MARGIN_M):i.properties.nature==="Sentier"?ke.FOOTBRIDGE_DECK_M:ke.DEFAULT_DECK_M;return s?{width:r,name:s}:{width:r}}static deckReach(e,t,i){const s=Math.hypot(t.east-e.east,t.north-e.north);if(i===void 0||s===0)return[e,t];const n={east:(e.east+t.east)/2,north:(e.north+t.north)/2},r={east:(t.east-e.east)/s,north:(t.north-e.north)/s},a=u=>(i.structureAt(n.east+r.east*u,n.north+r.north*u)??0)>=ke.DECK_SEEN_M,o=u=>i.structureAt(n.east+r.east*u,n.north+r.north*u)??0,l=u=>{let p;for(let m=0;m<=s/2+ke.DECK_REACH_M;m+=ke.DECK_STEP_M)if(a(u*m))p=m;else if(p!==void 0&&m-p>ke.DECK_GAP_M)break;if(p===void 0)return s/2;let f=p;for(;f-p<ke.DECK_REACH_M&&o(u*(f+ke.DECK_STEP_M))>=ke.DECK_MEETS_M;)f+=ke.DECK_STEP_M;return Math.max(s/2,f+ke.DECK_BEARING_M)},h=l(-1),d=l(1);return[{east:n.east-r.east*h,north:n.north-r.north*h},{east:n.east+r.east*d,north:n.north+r.north*d}]}static deckHeight(e,t,i){if(i===void 0)return ke.DEFAULT_DECK_HEIGHT_M;const s=[],n=20;for(let r=4;r<=n-4;r++){const a=i.structureAt(e.east+(t.east-e.east)*r/n,e.north+(t.north-e.north)*r/n);a!==void 0&&a>=1.5&&s.push(a)}return s.length===0?ke.DEFAULT_DECK_HEIGHT_M:(s.sort((r,a)=>r-a),s[Math.floor(s.length/2)])}static lines(e,t,i,s){const n=[];for(const r of e.lines){const a=String(r.properties.voltage??""),o=ke.kilovolts(a);if(o===void 0)continue;const l=ke.BY_VOLTAGE.find(d=>o<=d.upToKv)??ke.BY_VOLTAGE[ke.BY_VOLTAGE.length-1],h=ke.path(r,t);for(let d=0;d+1<h.length;d++){const u=h[d],p=h[d+1],f=Math.hypot(p.east-u.east,p.north-u.north);if(f<5||f>ke.MAX_SPAN_M||ke.distanceToSegment({east:0,north:0},u,p)>i)continue;const m=ke.poleHeight(u,p,s)??l.poleM;n.push({eastM:ke.tenth((u.east+p.east)/2),northM:ke.tenth((u.north+p.north)/2),lengthM:ke.tenth(f),headingDeg:ke.tenth(ke.bearing(u,p)),heightM:ke.tenth(Math.max(4,m-l.dropM)),poleHeightM:ke.tenth(m),acrossM:[-l.spreadM,0,l.spreadM],voltage:a})}}return n.sort((r,a)=>Math.hypot(r.eastM,r.northM)-Math.hypot(a.eastM,a.northM)),n.slice(0,ke.MAX_LINES)}static kilovolts(e){const t=/([\d.,]+)\s*kV/i.exec(e);if(t===null)return;const i=Number(t[1].replace(",","."));return Number.isFinite(i)&&i>0?i:void 0}static poleHeight(e,t,i){if(i===void 0)return;const s=[e,t].map(n=>i.tallestStructureNear(n.east,n.north,3)).filter(n=>n!==void 0&&n>=ke.MIN_POLE_M&&n<=ke.MAX_POLE_M);return s.length===0?void 0:s.reduce((n,r)=>n+r,0)/s.length}static tenth(e){return Math.round(e*10)/10}}class Gt{static covers(e,t){return e>=41.2&&e<=51.3&&t>=-5.4&&t<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??Gt.WMS,this.wfs=e.wfsEndpoint??Gt.WFS}static radius(e){return Math.min(e,Gt.MAX_RADIUS_M)}static lidarRadius(e){return Math.min(e,Gt.MAX_LIDAR_RADIUS_M)}async lidar(e,t){const i=Gt.lidarRadius(t),s=Math.ceil(2*i/Gt.METRES_PER_PIXEL),[n,r]=await Promise.all([this.raster(e,i,s,Gt.HEIGHT_LAYER),this.raster(e,i,s,Gt.CLASS_LAYER)]);if(n.samples!==1||r.samples<3)throw new Xr("unreachable","The survey answered in a layout this does not read");const a=n.values;if(a.every(d=>d===Gt.NO_DATA))throw new Xr("no-coverage","No LiDAR HD survey here yet");const o=new Uint8Array(s*s),l=new Uint8Array(s*s);for(let d=0;d<s*s;d++){const u=r.values[d*r.samples],p=r.values[d*r.samples+1],f=r.values[d*r.samples+2];o[d]=p>u&&p>f?1:0,l[d]=u>120&&p<90&&f<90?1:0}const h=2*i/s;return{size:s,metresPerPixel:h,heights:a,vegetation:o,building:l,structures:new o_(a,o,l,s,h)}}async laserDate(e){return Gt.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",e))}async photoDate(e){return Gt.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",e))}static latest(e){return e.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(e,t,i,s){const r=[s.lng-1e-4,s.lat-1e-4,s.lng+1e-4,s.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(e,`BBOX(${t},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(e,t){const i=Gt.radius(t),s=Math.min(Gt.MAX_PHOTO_PIXELS,Math.ceil(2*i/Gt.METRES_PER_PIXEL)),n=await this.raster(e,i,s,Gt.PHOTO_LAYER);if(n.samples<3)throw new Xr("unreachable","The photograph came in a layout this does not read");return{size:s,metresPerPixel:2*i/s,samples:n.samples,values:n.values}}async vectors(e,t,i){const s=Gt.radius(t),n=s/Gt.METRES_PER_DEGREE,r=s/(Gt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),o=`BBOX(geometrie,${[e.lng-r,e.lat-n,e.lng+r,e.lat+n].map(g=>g.toFixed(6)).join(",")},'EPSG:4326')`,[l,h,d,u,p,f]=await Promise.all([this.features("construction_lineaire",`${o} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${o} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${o} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",o,"voltage,geometrie"),i?this.features("batiment",o,Gt.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",o,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(f,p,[e.lng-r,e.lat-n,e.lng+r,e.lat+n]):[],v=[...p,...m];return{bridges:l,elevatedRoads:h,elevatedRailways:d,lines:u,buildings:v,zones:f,mapDate:Gt.latest(v.map(g=>g.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(e,t,i){const[s,n,r,a]=i,o=Gt.MAX_WHOLE_M/Gt.METRES_PER_DEGREE;let l;for(const d of e){if(d.properties.categorie!=="Religieux")continue;const[u,p,f,m]=Gt.extent(d);if(u>=s&&p>=n&&f<=r&&m<=a)continue;const v=[Math.max(u,s-o),Math.max(p,n-o),Math.min(f,r+o),Math.min(m,a+o)];l=l?[Math.min(l[0],v[0]),Math.min(l[1],v[1]),Math.max(l[2],v[2]),Math.max(l[3],v[3])]:v}if(!l)return[];const h=new Set(t.map(d=>d.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${l.map(u=>u.toFixed(6)).join(",")},'EPSG:4326')`,Gt.BUILDING_PROPERTIES,1e3)).filter(u=>!h.has(u.properties.cleabs))}catch{return[]}}static extent(e){let t=1/0,i=1/0,s=-1/0,n=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(t=Math.min(t,a[0]),s=Math.max(s,a[0]),i=Math.min(i,a[1]),n=Math.max(n,a[1])):Array.isArray(a)&&a.forEach(r)};return r(e.geometry.coordinates),[t,i,s,n]}async elevatedRoadLines(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(n=>n.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${t} AND position_par_rapport_au_sol>'0'`,"geometrie",300),s=[];for(const n of i){const{type:r,coordinates:a}=n.geometry,o=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const l of o)s.push(l.map(h=>({lat:h[1],lng:h[0]})))}return s}async waterSurfaces(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${t} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${t} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${t} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(e,t,i,s){const n=t/Gt.METRES_PER_DEGREE,r=t/(Gt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:s,STYLES:"",CRS:"EPSG:4326",BBOX:[e.lat-n,e.lng-r,e.lat+n,e.lng+r].map(l=>l.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let o;try{o=await this.fetchImpl(`${this.wms}?${a}`)}catch(l){throw new Xr("unreachable",l instanceof Error?l.message:String(l))}if(!o.ok)throw new Xr("unreachable",`The survey answered ${o.status}`);try{return p0.parse(await o.arrayBuffer())}catch(l){throw new Xr("unreachable",l instanceof Error?l.message:String(l))}}async features(e,t,i,s=200){const n=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:e.includes(":")?e:`BDTOPO_V3:${e}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(s),CQL_FILTER:t,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${n}`)}catch(o){throw new Xr("unreachable",o instanceof Error?o.message:String(o))}if(!r.ok)throw new Xr("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class Xo{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(e,t){if(e.length<2||t.length<2)return!1;const i=t[0],s=t.map(a=>ut(a.lat,a.lng,i.lat,i.lng)),n=e.map(a=>ut(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<n.length-1;a++){const o=n[a],l=n[a+1],h=Math.hypot(l.x-o.x,l.z-o.z);if(h<1e-6)continue;const d=Math.max(1,Math.ceil(h/Xo.SAMPLE_M)),u=Math.atan2(l.x-o.x,-(l.z-o.z));for(let p=0;p<=d;p++){const f=p/d,m=Xo.nearest(s,o.x+(l.x-o.x)*f,o.z+(l.z-o.z)*f);m.distanceM>Xo.NEAR_M||Xo.angleBetween(u,m.heading)<=Xo.ALIGNED_DEG&&(r+=h/d)}}return r>=Xo.LONG_ENOUGH_M}static nearest(e,t,i){let s={distanceM:1/0,heading:0};for(let n=0;n<e.length-1;n++){const r=e[n],a=e[n+1],o=a.x-r.x,l=a.z-r.z,h=o*o+l*l,d=h<1e-9?0:Math.max(0,Math.min(1,((t-r.x)*o+(i-r.z)*l)/h)),u=Math.hypot(t-(r.x+o*d),i-(r.z+l*d));u<s.distanceM&&(s={distanceM:u,heading:Math.atan2(o,-l)})}return s}static angleBetween(e,t){const i=Math.abs((e-t)*180/Math.PI%180);return Math.min(i,180-i)}}class Ut{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??Ut.WMS,this.timeoutMs=e.timeoutMs??Ut.DEFAULT_TIMEOUT_MS,this.maxWindowM=e.maxWindowM??Ut.MAX_WINDOW_M,this.geoplatform=new Gt({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:e.wfsEndpoint})}async getElevationGrid(e,t,i){const s={lat:(e.south+e.north)/2,lng:(e.west+e.east)/2};if(!Gt.covers(s.lat,s.lng))throw new Error("The IGN's relief covers France only");const n=Math.abs(ut(s.lat,e.east,s.lat,e.west).x),r=Math.abs(ut(e.north,s.lng,e.south,s.lng).z);t=this.finer(t,n,r);const a={x:n/Math.max(1,t.width-1),y:r/Math.max(1,t.height-1)},o={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},l={south:e.south-o.y/Ut.METRES_PER_DEGREE,north:e.north+o.y/Ut.METRES_PER_DEGREE,west:e.west-o.x/(Ut.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180)),east:e.east+o.x/(Ut.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180))},h=m=>Math.min(Ut.MAX_PIXELS,Math.max(Ut.MIN_PIXELS,Math.ceil(m/Ut.METRES_PER_PIXEL))),d={width:h(n+2*o.x),height:h(r+2*o.y)},u={x:(n+2*o.x)/d.width,y:(r+2*o.y)/d.height};let p=new Error("No layer of the IGN's relief answered");const f=Math.max(u.x,u.y)>Ut.COARSE_METRES_PER_PIXEL;for(const m of f?[...Ut.LAYERS].reverse():Ut.LAYERS)try{const v=await this.heights(l,d,m);m===Ut.LAYERS[0]&&await this.layBridgeDecks(v,l,d,i?.route);const g=this.sample(v,t,e,l,u,a);if(g)return{heights:g,width:t.width,height:t.height,bounds:e};p=new Error(`${m} does not cover this place`)}catch(v){p=v}throw p}finer(e,t,i){if(e.width<Ut.MESH_FROM_VERTICES||e.height<Ut.MESH_FROM_VERTICES)return e;const s=(n,r)=>{const a=Math.ceil(n/Ut.FINE_SPACING_M),o=Math.max(r-1,Math.min(Ut.MAX_SEGMENTS,a));return o%2===0?o:o+1};return{width:s(t,e.width)+1,height:s(i,e.height)+1}}async raster(e,t,i){const s=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[e.south,e.west,e.north,e.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(t.width),HEIGHT:String(t.height),FORMAT:"image/geotiff"}),n=await this.fetchImpl(`${this.wms}?${s}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok)throw new Error(`The IGN's relief answered ${n.status}`);return p0.parse(await n.arrayBuffer())}async heights(e,t,i){const s=await this.raster(e,t,i);if(s.samples!==1||!(s.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return s}async layBridgeDecks(e,t,i,s){if(!(!s||s.length<2)&&!(!(e.values instanceof Float32Array)||!e.values.some(n=>n>Ut.NO_DATA_BELOW)))try{const n=(await this.geoplatform.elevatedRoadLines({west:t.west,south:t.south,east:t.east,north:t.north})).filter(a=>Xo.follows(s,a));if(n.length===0)return;const r=Float32Array.from(e.values);await this.layClassifiedDecks(e,t,i,n),this.layRouteDecks(e,r,t,n)}catch{}}async layClassifiedDecks(e,t,i,s){try{const n=await this.raster(t,i,Ut.CLASS_LAYER);if(n.samples<3||n.width!==e.width||n.height!==e.height)return;const r=(v,[g,b,w])=>n.values[v*n.samples]===g&&n.values[v*n.samples+1]===b&&n.values[v*n.samples+2]===w,a=e.width,o=e.height,l=new Uint8Array(a*o);let h=!1;for(let v=0;v<l.length;v++)r(v,Ut.DECK)&&(l[v]=1,h=!0);if(!h)return;const d=Ut.DECK_END_PIXELS,u=[];for(let v=0;v<l.length;v++){if(l[v]!==1)continue;const g=v%a,b=(v-g)/a;for(let w=-d;w<=d;w++)for(let y=-d;y<=d;y++){const M=g+y,S=b+w;if(M<0||S<0||M>=a||S>=o)continue;const E=S*a+M;l[E]===0&&r(E,Ut.NO_CLASS)&&u.push(E)}}for(const v of u)l[v]=1;const p=this.paint(s,t,a,o),f=this.touching(l,p,a,o);if(f.every(v=>v===0))return;const m=await this.heights(t,i,Ut.SURFACE_LAYER);if(m.width!==a||m.height!==o)return;for(let v=0;v<f.length;v++){if(f[v]===0)continue;const g=m.values[v];Number.isFinite(g)&&g>Ut.NO_DATA_BELOW&&g>e.values[v]&&(e.values[v]=g)}}catch{}}layRouteDecks(e,t,i,s){const{width:n,height:r}=e,a=(i.north+i.south)/2,o=(i.east-i.west)*Ut.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),l=(i.north-i.south)*Ut.METRES_PER_DEGREE,h=o/n,d=l/r,u=g=>({x:(g.lng-i.west)/(i.east-i.west)*o,y:(i.north-g.lat)/(i.north-i.south)*l}),p=(g,b)=>{const w=Math.floor(g/h),y=Math.floor(b/d);if(w<0||y<0||w>=n||y>=r)return;const M=t[y*n+w];return Number.isFinite(M)&&M>Ut.NO_DATA_BELOW?M:void 0},f=Ut.DECK_HALF_WIDTH_M,m=Ut.DECK_APPROACH_M,v=(g,b)=>{const w=Math.hypot(g.x-b.x,g.y-b.y)||1,y={x:(g.x-b.x)/w,y:(g.y-b.y)/w},M=[0,m/2,m].map(S=>p(g.x+y.x*S,g.y+y.y*S)).filter(S=>S!==void 0);return M.length>0?Math.max(...M):void 0};for(const g of Ut.chains(s.map(b=>b.map(u)))){const b=[0];for(let R=1;R<g.length;R++)b.push(b[R-1]+Math.hypot(g[R].x-g[R-1].x,g[R].y-g[R-1].y));const w=b[b.length-1];if(w<1||w>Ut.DECK_STRAIGHT_MAX_M)continue;const y=v(g[0],g[1]),M=v(g[g.length-1],g[g.length-2]);if(y===void 0||M===void 0)continue;const S=f+m,E=Math.max(0,Math.floor((Math.min(...g.map(R=>R.x))-S)/h)),x=Math.min(n-1,Math.ceil((Math.max(...g.map(R=>R.x))+S)/h)),A=Math.max(0,Math.floor((Math.min(...g.map(R=>R.y))-S)/d)),D=Math.min(r-1,Math.ceil((Math.max(...g.map(R=>R.y))+S)/d));for(let R=A;R<=D;R++)for(let L=E;L<=x;L++){const N=Ut.nearestAlong(g,b,{x:(L+.5)*h,y:(R+.5)*d});if(N.distance>f||N.s<-m||N.s>w+m)continue;const k=y+(M-y)*Math.min(1,Math.max(0,N.s/w)),C=R*n+L;t[C]>=k||(e.values[C]=k)}}}static chains(e){const t=e.filter(n=>n.length>=2).map(n=>[...n]),i=[],s=(n,r)=>Math.hypot(n.x-r.x,n.y-r.y)<=1;for(;t.length>0;){let n=t.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<t.length;a++){const o=t[a],l=n[0],h=n[n.length-1];if(s(h,o[0]))n=[...n,...o.slice(1)];else if(s(h,o[o.length-1]))n=[...n,...[...o].reverse().slice(1)];else if(s(l,o[o.length-1]))n=[...o.slice(0,-1),...n];else if(s(l,o[0]))n=[...[...o].reverse().slice(0,-1),...n];else continue;t.splice(a,1),r=!0;break}}i.push(n)}return i}static nearestAlong(e,t,i){let s={s:0,distance:1/0};for(let n=0;n<e.length-1;n++){const r=e[n],a=e[n+1],o=a.x-r.x,l=a.y-r.y,h=o*o+l*l;if(h<1e-9)continue;let d=((i.x-r.x)*o+(i.y-r.y)*l)/h;n>0&&(d=Math.max(0,d)),n<e.length-2&&(d=Math.min(1,d));const u=Math.hypot(i.x-(r.x+o*d),i.y-(r.y+l*d));u<s.distance&&(s={s:t[n]+d*Math.sqrt(h),distance:u})}return s}paint(e,t,i,s){const n=new Uint8Array(i*s),r=o=>(o-t.west)/(t.east-t.west)*i,a=o=>(t.north-o)/(t.north-t.south)*s;for(const o of e)for(let l=0;l<o.length-1;l++){const h=r(o[l].lng),d=a(o[l].lat),u=r(o[l+1].lng),p=a(o[l+1].lat),f=Math.max(1,Math.ceil(Math.hypot(u-h,p-d)*2));for(let m=0;m<=f;m++){const v=Math.floor(h+(u-h)*m/f),g=Math.floor(d+(p-d)*m/f);for(let b=-1;b<=1;b++)for(let w=-1;w<=1;w++){const y=v+w,M=g+b;y>=0&&M>=0&&y<i&&M<s&&(n[M*i+y]=1)}}}return n}touching(e,t,i,s){const n=new Uint8Array(e.length),r=new Uint8Array(e.length);for(let a=0;a<e.length;a++){if(e[a]===0||r[a]===1)continue;const o=[],l=[a];r[a]=1;let h=!1;for(;l.length>0;){const d=l.pop();o.push(d),t[d]===1&&(h=!0);const u=d%i,p=(d-u)/i;for(let f=-1;f<=1;f++)for(let m=-1;m<=1;m++){const v=u+m,g=p+f;if(v<0||g<0||v>=i||g>=s)continue;const b=g*i+v;e[b]===1&&r[b]===0&&(r[b]=1,l.push(b))}}if(h)for(const d of o)n[d]=1}return n}sample(e,t,i,s,n,r){const{width:a,height:o}=t,l=new Float32Array(a*o),h=new Uint8Array(a*o),d=Math.min(r.x,this.maxWindowM)/n.x,u=Math.min(r.y,this.maxWindowM)/n.y;let p=0;for(let f=0;f<o;f++){const m=i.north+(i.south-i.north)*(o===1?.5:f/(o-1)),v=(s.north-m)/(s.north-s.south)*e.height-.5;for(let g=0;g<a;g++){const w=(i.west+(i.east-i.west)*(a===1?.5:g/(a-1))-s.west)/(s.east-s.west)*e.width-.5,y=d>1||u>1?this.tent(e,w,v,Math.max(1,d),Math.max(1,u)):this.bilinear(e,w,v),M=f*a+g;y===void 0?p++:(l[M]=y,h[M]=1)}}if(!(p===a*o||p/(a*o)>Ut.MAX_HOLE_SHARE))return this.fill(l,h,a,o),l}tent(e,t,i,s,n){let r=0,a=0,o=0;const l=Math.max(0,Math.ceil(i-n)),h=Math.min(e.height-1,Math.floor(i+n)),d=Math.max(0,Math.ceil(t-s)),u=Math.min(e.width-1,Math.floor(t+s));for(let p=l;p<=h;p++){const f=1-Math.abs(p-i)/n;if(!(f<=0))for(let m=d;m<=u;m++){const v=f*(1-Math.abs(m-t)/s);if(v<=0)continue;o+=v;const g=e.at(m,p);!Number.isFinite(g)||g<Ut.NO_DATA_BELOW||(r+=v*g,a+=v)}}return o>0&&a>=o*.5?r/a:void 0}bilinear(e,t,i){const s=Math.max(0,Math.min(e.width-1,Math.floor(t))),n=Math.max(0,Math.min(e.height-1,Math.floor(i))),r=Math.min(e.width-1,s+1),a=Math.min(e.height-1,n+1),o=Math.max(0,Math.min(1,t-s)),l=Math.max(0,Math.min(1,i-n)),h=e.at(s,n),d=e.at(r,n),u=e.at(s,a),p=e.at(r,a);for(const v of[h,d,u,p])if(!Number.isFinite(v)||v<Ut.NO_DATA_BELOW)return;const f=h+(d-h)*o,m=u+(p-u)*o;return f+(m-f)*l}fill(e,t,i,s){let n=t.reduce((r,a)=>r+(a?0:1),0);for(;n>0;){const r=[];for(let a=0;a<s;a++)for(let o=0;o<i;o++){const l=a*i+o;if(t[l])continue;let h=0,d=0;for(let u=-1;u<=1;u++)for(let p=-1;p<=1;p++){const f=a+u,m=o+p;f<0||m<0||f>=s||m>=i||!t[f*i+m]||(h+=e[f*i+m],d++)}d>0&&r.push([l,h/d])}if(r.length===0)return;for(const[a,o]of r)e[a]=o,t[a]=1;n-=r.length}}}class l_{providers;constructor(...e){this.providers=e}async getElevationGrid(e,t,i){let s=new Error("No source of relief to ask");for(const n of this.providers)try{return await n.getElevationGrid(e,t,i)}catch(r){s=r}throw s}}const Nf=256,c_=5;async function S2(c,e,t,i){const s=(c.south+c.north)/2,n=(c.west+c.east)/2,r=Math.abs(ut(s,c.east,s,c.west).x),a=Math.abs(ut(c.north,n,c.south,n).z),o=Math.max(r,a),{zoom:l,gridSize:h}=h_(s,o,Math.max(e.width,e.height)),{tiles:d,bounds:u}=M2(n,s,l,h),p=h*Nf,f=document.createElement("canvas");f.width=p,f.height=p;const m=f.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const v=d[0];await Promise.all(d.map(async y=>{const M=t(y),S=await i(M);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${M}`);const E=await createImageBitmap(await S.blob());m.drawImage(E,(y.x-v.x)*Nf,(y.y-v.y)*Nf)}));const g=Math.min(Math.max(e.width,e.height),p);if(g===p)return{source:f,width:p,height:p,bounds:u};const b=document.createElement("canvas");b.width=g,b.height=g;const w=b.getContext("2d");if(!w)throw new Error("2D canvas context unavailable");return w.drawImage(f,0,0,p,p,0,0,g,g),{source:b,width:g,height:g,bounds:u}}function h_(c,e,t){let i=i_(c,e/Math.max(1,t)),s=sM(c,i,e);for(;s>c_&&i>0;)i--,s=sM(c,i,e);return{zoom:i,gridSize:s,mPerPixel:b2(c,i)/Nf}}function sM(c,e,t){const i=Math.ceil(t/2/b2(c,e));return Math.max(3,2*i+1)}class E2{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 S2(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class ir{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(e,t=ir.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(e);if(!i)return[...t];const[s,n,r,a]=i.slice(1).map(Number),o=(s+r)/2,l=(n+a)/2,h=ir.FRANCE;return o>=h.south&&o<=h.north&&l>=h.west&&l<=h.east?[ir.FRANCE_ENDPOINT,...t.filter(u=>u!==ir.FRANCE_ENDPOINT)]:[...t]}fetchImpl;endpoints;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.endpoints=e.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(e){return this.queued(()=>this.ask(e))}queued(e){const t=ir.queue.then(e,e);return ir.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints??ir.endpointsFor(e))for(let s=0;s<2;s++){try{const n=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(ir.HANG_MS)});if(n.ok)return await n.json();if(t=new Error(`${new URL(i).host} refused (${n.status})`),n.status!==429&&n.status!==504)break}catch(n){t=new Error(`${new URL(i).host} unreachable (${String(n)})`);break}await new Promise(n=>setTimeout(n,ir.RETRY_MS))}throw t??new Error("No Overpass instance answered")}}class Yo{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;client;constructor(e={}){this.client=new ir(e)}async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${Yo.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(e){const t=[];for(const i of e.elements??[]){const s=i.geometry,n=i.tags;!n||!s||s.length<2||t.push({id:`osm-${i.id??t.length}`,name:n.name,surface:Yo.surfaceOf(n),widthM:Yo.widthOf(n),...Yo.paintOf(n),points:s.map(r=>({lat:r.lat,lng:r.lon}))})}return t}static paintOf(e){const t=e.highway??"",i=e.junction==="roundabout"||e.junction==="circular",s=e.oneway,n=s==="yes"||s==="1"||s==="true"||s===void 0&&(t==="motorway"||i),r=s==="-1"||s==="reverse",a=Number.parseInt(e.lanes??"",10),o=Number.parseInt(e.maxspeed??"",10),l=i?"roundabout":t==="motorway"?"motorway":t.endsWith("_link")?"slip":(t==="trunk"||t==="primary")&&(n||r)?"dual":t?"road":void 0;return{...l?{kind:l}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...s!==void 0||t==="motorway"||i?{direction:r?"backward":n?"forward":"both"}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{}}}static widthOf(e){const t=Number.parseFloat(e.width??e.est_width??"");if(Number.isFinite(t)&&t>0)return t;const i=Number.parseInt(e.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:Yo.WIDTH_M[e.highway]??Yo.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 W0="https://ufoathome.org/roads/index.json";class ph{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??ph.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:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.ways)?(this.attributionRead=n.attribution,this.contemporaryRead=n.contemporary,n.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(`
|
|
4326
|
-
`);let t=ph.shared.get(e);return t||(t=this.fetchFirstAvailable(),ph.shared.set(e,t),t.then(i=>{i.length===0&&ph.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.
|
|
4327
|
-
`);let t=fh.shared.get(e);return t||(t=this.fetchFirstAvailable(),fh.shared.set(e,t),t.then(i=>{i.length===0&&fh.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.161.0")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==$0?[t,$0]:[$0]).map(i=>i+e)}}class qn{constructor(e){this.water=e}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(e){const t=qn.key(e);let i=qn.asked.get(t);return i===void 0&&(i=this.recalled(t,e),qn.asked.set(t,i),i.catch(()=>qn.asked.delete(t))),structuredClone(await i)}static forget(){qn.asked.clear()}static key(e){return`v${qn.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await qn.openCache(),s=qn.request(e);if(i)try{const r=await i.match(s);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<qn.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&qn.store(i,s,n),n}static async store(e,t,i){try{const s={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const r of n.slice(0,Math.max(0,n.length-qn.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(qn.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class Jo{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(e={}){this.platform=new Gt(e)}static covers(e){return Gt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>Jo.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=Jo.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),l=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=Jo.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=Jo.electrificationOf(r.kind,d,e.properties.electrifie);return n.flatMap((p,f)=>{const m=p.map(v=>({lat:v[1],lng:v[0],...v.length>2&&Number.isFinite(v[2])&&v[2]>Jo.NO_ALTITUDE?{altitudeM:v[2]}:{}}));return m.length<2?[]:[{id:n.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(l)?l:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class Qs{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(e={}){this.client=new ir(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:120];way["railway"~"^(${Qs.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Qs.ROUTES})$"];out body;`;return Qs.apply(e,await this.client.query(s),t)}static apply(e,t,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=Qs.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(g=>ut(g.lat,g.lng,s.lat,s.lng)),o=new Map,l=new Map,h=new Map;let d=0;const u=n.filter(g=>g.service===!!r.service);for(const g of Qs.samples(a)){d++;const b=Qs.waysAt(u,g);if(b.length===0)continue;const[w]=b;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&l.set(w.voltageV,(l.get(w.voltageV)??0)+1);for(const y of new Set(b.flatMap(M=>M.services)))h.set(y,(h.get(y)??0)+1)}const p=g=>[...g.entries()].sort((b,w)=>w[1]-b[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(l)),v=[...h.entries()].filter(([,g])=>g*4>=d).sort((g,b)=>b[1]-g[1]||g[0].localeCompare(b[0])).map(([g])=>g);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...v.length>0?{services:v}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=Qs.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const r=t.get(n.ref)??new Set;r.add(s),t.set(n.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=Qs.servicesByWay(e),s=[];for(const n of e.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const r=n.tags??{},a=Qs.voltageOf(r);s.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>ut(o.lat,o.lon,t.lat,t.lng))})}return s}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const s=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(s<1e-6)continue;const n=(e[i+1].x-e[i].x)/s,r=(e[i+1].z-e[i].z)/s;for(let a=Qs.SAMPLE_M/2;a<s;a+=Qs.SAMPLE_M)t.push({x:e[i].x+n*a,z:e[i].z+r*a,dx:n,dz:r})}return t}static waysAt(e,t){const i=Math.cos(Qs.ALIGNED_DEG*Math.PI/180),s=[];for(const n of e){let r;for(let a=0;a<n.path.length-1;a++){const o=n.path[a],l=n.path[a+1],h=l.x-o.x,d=l.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=Qs.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&s.push({way:n,distance:r})}return s.sort((n,r)=>n.distance-r.distance).map(({way:n})=>n)}}class mh{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new ir(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${mh.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Qs.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=Qs.servicesByWay(e);for(const s of e.elements??[]){const n=s.geometry,r=s.tags;if(s.type==="relation"||!r||!n||n.length<2)continue;const a=[...i.get(s.id??-1)??[]].sort(),o=Qs.voltageOf(r),l=mh.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=mh.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${s.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:mh.levelOf(r),points:n.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class p_{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!Jo.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class _s{constructor(e,t=Date.now){this.railways=e,this.now=t}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(e){const t=_s.key(e);let i=_s.asked.get(t)??_s.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},_s.asked.set(t,i),s.catch(()=>_s.asked.delete(t))}return structuredClone(await i.answer)}static forget(){_s.asked.clear(),_s.failedAt=-1/0}static key(e){return`v${_s.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of _s.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await _s.openCache(),s=_s.request(e);let n;if(i)try{const a=await i.match(s);if(a){const{savedAt:o,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-o<_s.MAX_AGE_MS)return l;n=l}}}catch{}if(this.now()-_s.failedAt<_s.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(t)}catch(a){if(_s.failedAt=this.now(),n)return n;throw a}return i&&_s.store(i,s,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const n of s.slice(0,Math.max(0,s.length-_s.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(_s.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const K0="https://ufoathome.org/railways/index.json";class gh{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??gh.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
4328
|
-
`);let t=gh.shared.get(e);return t||(t=this.fetchFirstAvailable(),gh.shared.set(e,t),t.then(i=>{i.length===0&&gh.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.161.0")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==K0?[t,K0]:[K0]).map(i=>i+e)}}function A2(){return{elevation:T2(),imagery:I2(),roads:_2(),water:D2(),railways:R2()}}function T2(){return new l_(new Ut,new x2)}function I2(){return new E2}function _2(){return new ph({fallback:new d_(new Zo,new Yo)})}function D2(){return new fh({fallback:new qn(new u_(new Zu,new Wl))})}function R2(){return new gh({fallback:new _s(new p_(new Jo,new mh))})}const f_=new Set,Fh="show-observer-map",Uh="hide-milestones",Jl="minified";class qt extends HTMLElement{static get observedAttributes(){return["src",Fh,Uh,Jl]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new hi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=s0.create();issues=[];issueCheck=0;sightingAudio=new q5;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>qt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=p2;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,s=!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 n of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(n)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");qt.setIcon(this.moreButton,e?tt.UNFOLDED:tt.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),s=this.said.read(i?.shape.title);if(!s){this.tooltip.hidden=!0;return}this.tooltip.textContent=s,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-n.left+12}px`,this.tooltip.style.top=`${e.clientY-n.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)<qt.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>=hi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=hi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},qt.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 s=hi.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:s,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${$5}</style>${W5}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new nd(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Vl(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),s=a=>{const o=i.getBoundingClientRect(),l=this.player.seekableDuration;if(o.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&s(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===Fh&&this.applyObserverMapDefault(),e===Uh&&this.setMilestonesShown(!this.hasAttribute(Uh)),e===Jl){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Jl)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(k2)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages.clickToPlay:this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await na.recording(e)}get sightingData(){return um(this.currentSighting)}set sightingData(e){const t=Ui.toCurrent(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=ky(t),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let s=[];try{const{default:n}=await oe(async()=>{const{default:r}=await import("./sightingSchema-CnDwuCov.js");return{default:r}},[],import.meta.url);s=new $r(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],rd.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(m_,{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 s=document.createElement("li");return s.textContent=rd.text(i,this.messages.issueTemplates),s}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}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(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const s of t)this.controlsRight.insertBefore(s,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 s=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),s=this.said.read(t.title)??t.id,n=document.createElement("div");n.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,r.append(a,o);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages.referenceOpacity,l.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${s}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),n.append(r,l),n});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(n=>this.viewOfReference(n).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"),qt.setIcon(this.referencesButton,i?tt.PICTURES_ON:tt.PICTURES_OFF);const s=t?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=s,this.referencesButton.setAttribute("aria-label",s),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)),qt.setIcon(this.tracesButton,this.tracesShownState?tt.TRACES_ON:tt.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?cc(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const n=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${n} — ${r}`:n;return s.title=a,s.setAttribute("aria-label",a),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),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 s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return n.textContent=a?`${r} — ${a}`:r,n.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),s.appendChild(n),s})),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 s of this.momentsMenu.querySelectorAll("button")){const n=e!==void 0&&Number(s.dataset.t)===e.t;s.getAttribute("aria-current")==="true"!==n&&s.setAttribute("aria-current",String(n))}}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 s=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,a)=>r-a):[],Math.max(e,0)];this.seekSegmentList=[];const n=[];for(let r=0;r<s.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(s[r+1]-s[r],1));const o=document.createElement("i");o.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(o,l),n.push(a),this.seekSegmentList.push({start:s[r],end:s[r+1],element:a,played:l,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,s=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=qt.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 s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),n=s*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=qt.fillOf(p,n),p.element.classList.toggle("hovered",n>=p.start&&(n<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?V0(a,n):void 0,l=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(n)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}paintChrome(e){const t=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||s===0||n===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(s*r)),o=Math.max(1,Math.round(n*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new nd(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(s*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 s=qt.MARK_SNAP_PX/i*t;let n;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>s||(!n||Math.abs(a-e)<Math.abs(n.t-e))&&(n={t:a,name:r.title})}return n}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 s=(e.clientX-t.left)/t.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?V0(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 s=this.said.read(t.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(e=this.currentTime){const t=Zr.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<qt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(qt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/qt.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/qt.EXPOSURE_STEP_PX),n=Math.min(qt.MAX_TRAVEL_STEPS,Math.max(i,s)),r=[];for(let a=0;a<n;a++)r.push(t.fromMs+t.ms*a/(n-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),s=this.shapesAt(e+t);let n=0;for(const[r,a]of i){const o=s.get(r);if(!o)continue;const l=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);n=Math.max(n,Math.hypot(l,h))}return n}shapeAt(e,t,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,e,t,i);if(n)return n}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}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=Qt.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:f_;this.canvasRenderer.setStarPoints(Qt.starPointsOf(this.sighting.instrument,st(this.sighting,e)?.fNumber));const s=(st(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,l]of o.shapes){const h=o.share,d=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,l]of n[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)));const a=this.selectionShown&&i.size>1?Jt.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.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.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(fy(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new K5(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*qt.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?tt.PLAY:tt.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){qt.icons.get(e)!==t&&(qt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},qt.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,this.updateStartState(),qt.setIcon(this.playPauseButton,e?tt.PAUSE:tt.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(Fh),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;qt.setIcon(this.observerMapButton,e?tt.MAP_ON:tt.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[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=oc.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(s=>s.points):[],i=hi.fitted(this.observerPath,t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapFrozenImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?hi.expand(e,qt.OBSERVER_MAP_IMAGERY_AHEAD):e,s=hi.IMAGERY_PX*(t?1+2*qt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const n=this.observerMapFrozenImagery,r=n?void 0:I2();try{const a=r?await r.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??n).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,s=this.observerMapView.changed?hi.expand(e,qt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!n||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapFrozen(e){e!==this.observerMapFrozenImagery&&(this.observerMapFrozenImagery=e,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapFrozen(){return this.observerMapFrozenImagery}observerMapFrozenImagery;observerMapFrozenSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,d)=>{for(const u of t)if(!(u.x+u.width<l-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},s=[this.canvas.width-e.width,this.canvas.width],n=[0,e.width],r=qt.OBSERVER_MAP_CLEARANCE_PX,a=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!i(s[0],s[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(s[0],s[1],0)&&!i(n[0],n[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,s=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*s,bottom:(e.bottom-t.top)*s}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=st(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},qt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?V0(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?cc(this.currentSighting.milestones):[]){const a=st(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||s.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===n})}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?ar.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Qt.aspectOf(i)):void 0,markers:s,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,cc(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,qt.setIcon(this.milestonesButton,this.milestonesShown?tt.MILESTONES_ON:tt.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=st(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=Mr(i,e),{lat:n,lng:r}=Wn(s.eastM,-s.northM,t.lat,t.lng);return{lat:n,lng:r,headingDeg:s.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 s=st(this.currentSighting,this.currentTime),n=ar.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return bi.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=qt.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),qt.setIcon(this.miniMuteButton,this.mutedState?tt.MUTED:tt.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){qt.setIcon(this.muteButton,tt.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}qt.setIcon(this.muteButton,this.mutedState?tt.MUTED:tt.VOLUME);const i=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;qt.setIcon(this.fullscreenButton,e?tt.EXIT_FULLSCREEN:tt.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 rn(Sr.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=$u(Sr.preferencesFor(this),Wu);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await O3(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=Qh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Ev(e.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return Lo(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?rM(nM(this.realStartMs+i)):Lo(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Lo(e):Lo(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Lo(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Lo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Lo(this.currentSighting.timeline.duration):this.canShowClockTime?rM(nM(this.realStartMs+this.realDurationMs)):Lo(this.realDurationMs)}}function nM(c){const e=new Date(c);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function rM(c){if(c.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return c.second?`${e(c.hour)}:${e(c.minute??0)}:${e(c.second)}`:`${e(c.hour)}:${e(c.minute??0)}`}function Lo(c){const e=Math.round(c/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const qv="rr0-ufo";function f0(){customElements.get(qv)||customElements.define(qv,qt)}const m_="recordingissues",k2="minifiedreset";class Qd{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((n,r)=>n.t-r.t):[],s=`${t}|${i.map(n=>`${n.kind}:${n.t}:${n.label}`).join("|")}`;s!==this.drawn&&(this.drawn=s,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(n=>{const r=document.createElement("span");return r.className=`timeline-mark ${n.kind}`,r.style.left=`${Math.min(Math.max(n.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+Qd.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Qd.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Qd.SNAP_PX/t*this.duration;let s;for(const n of this.marks)Math.abs(n.t-e)>i||(!s||Math.abs(n.t-e)<Math.abs(s.t-e)||n.t===s.t&&n.kind==="milestone")&&(s=n);return s}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 vh{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const s=e.event.place?.[0],n=e.observerTrack;if(!s)return 0;const r=m=>{const v=n.getInterpolatedPoseAt(Math.max(0,m));if(!v||v.lat===void 0||v.lng===void 0)return;const g=ut(v.lat,v.lng,s.lat,s.lng);return{eastM:g.x,northM:-g.z,heading:v.headingDeg}},a=r(t-vh.HALF_SPAN_MS),o=r(t+vh.HALF_SPAN_MS),l=r(t);if(!a||!o||!l)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*vh.HALF_SPAN_MS/1e3;if(h/d<vh.MIN_SPEED_MS)return 0;const u=i.heightAt(o.eastM,o.northM)-i.heightAt(a.eastM,a.northM),p=Math.atan2(u,h)*180/Math.PI;if(l.heading===void 0)return p;const f=Math.atan2(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((l.heading-f)*Math.PI/180))}}const g_=.08,aM=.15,oM=2,v_=2e3;class b_{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}}lc.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(s=>s.inside||s.distanceM<v_),i=new Set(t.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of t){const n=this.voices.get(s.id)??this.build(e,s.id);this.retarget(e,n,s)}}build(e,t){const i=e.createGain();i.gain.value=0;const s=e.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(e));const n=e.createOscillator();n.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),r.connect(o),o.connect(a).connect(s);const l=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*oM*.5,M},h=l(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(s);const p=l(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(s);const v=l(),g=e.createBiquadFilter();g.type="bandpass",g.frequency.value=1400,g.Q.value=.7;const b=e.createGain();v.connect(g).connect(b).connect(s);const w=[n,r,h,p,v];for(const M of w)M.start();const y={nodes:[i,s,a,o,d,u,f,m,g,b,...w],sources:w,firing:n,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:b,cabin:s,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:s,noise:n,inside:r,windowsOpen:a,distanceM:o}){const l=e.currentTime,h=(b,w)=>b.setTargetAtTime(w,l,g_),d=s.rpm/60,u=d*i.cylinders/2,p=Math.min(1,s.rpm/i.shiftUpRpm),f=Math.min(1.5,s.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*s.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const v=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,v);const g=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,g*n)}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,aM/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},aM*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*oM,e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Ju{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 Ju.BY_KIND[e??"generic"]??Ju.BY_KIND.generic}}class Ql{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,s){const n=Ql.SAMPLE_MS,r=[];for(let l=i;l<=s+n/2;l+=n){const h=t(l-n/2),d=t(l+n/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(n/1e3))}const a=[];let o=1;for(let l=0;l<r.length;l++){const h=r[l],d=(r[Math.min(l+1,r.length-1)]-r[Math.max(l-1,0)])/(2*n/1e3);if(h<Ql.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=g=>u/e.kmhPer1000Rpm[g-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),v=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:v,gear:o})}return new Ql(a,i)}at(e){const t=(e-this.startMs)/Ql.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*r,rpm:s.rpm+(n.rpm-s.rpm)*r,load:s.load+(n.load-s.load)*r,gear:r<.5?s.gear:n.gear}}}class fm{drives=new Map;at(e,t){const i=[],s=e.event.place?.[0],n=l=>{const h=e.observerTrack.getInterpolatedPoseAt(l),d=h?.lat??s?.lat,u=h?.lng??s?.lng;if(d===void 0||u===void 0||!s)return;const p=ut(d,u,s.lat,s.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle;if(a){const l=Ju.of(a.kind),h=this.drive(`observer:${a.kind}`,fm.trackKey(e),()=>Ql.of(l,n,0,r));h&&i.push({id:"observer",profile:l,state:h.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const o=n(t);for(const l of e.decor){if(!l.engine||!o)continue;const h=Ju.of(l.engine.kind),d=m=>{const v=Mr(l,m);return{eastM:v.eastM,northM:v.northM}},u=this.drive(`decor:${l.id}`,fm.decorKey(l,r),()=>Ql.of(h,d,0,r));if(!u)continue;const p=Mr(l,t),f=Math.hypot(p.eastM-o.eastM,p.northM-o.northM,p.altitudeM);i.push({id:`decor:${l.id}`,profile:h,state:u.at(t),noise:l.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:f})}return i}drive(e,t,i){const s=this.drives.get(e);if(s&&s.key===t)return s.drive;const n=i();return this.drives.set(e,{key:t,drive:n}),n}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 y_="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",w_=`
|
|
4326
|
+
`);let t=ph.shared.get(e);return t||(t=this.fetchFirstAvailable(),ph.shared.set(e,t),t.then(i=>{i.length===0&&ph.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.162.0")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==W0?[t,W0]:[W0]).map(i=>i+e)}}class Zo{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(e={}){this.platform=new Gt(e)}static covers(e){return Gt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRoads(e){return(await this.platform.roads(e)).flatMap((i,s)=>Zo.wayOf(i,s))}static wayOf(e,t){if(e.geometry.type!=="LineString")return[];const i=e.geometry.coordinates.map(([u,p])=>({lat:p,lng:u}));if(i.length<2)return[];const s=String(e.properties.nature??""),n=Zo.BY_NATURE[s]??Zo.DEFAULT,r=Number(e.properties.largeur_de_chaussee),a=Number(e.properties.nombre_de_voies),o=Number(e.properties.vitesse_moyenne_vl),l=Zo.DIRECTIONS[String(e.properties.sens_de_circulation??"")],h=Zo.KINDS[s],d=[e.properties.cpx_toponyme_route_nommee,e.properties.nom_voie_ban_gauche,e.properties.nom_voie_ban_droite].find(u=>typeof u=="string"&&u.length>0);return[{id:String(e.properties.cleabs??`ign-${t}`),...d?{name:d}:{},surface:n.surface,widthM:Number.isFinite(r)&&r>0?r:n.widthM,...e.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...l?{direction:l}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{},points:i}]}}class d_{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(e){if(Zo.covers(e))try{const t=await this.regional.getRoads(e);if(t.length>0)return t}catch{}return this.worldwide.getRoads(e)}}class Zu{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(e={}){this.platform=new Gt(e)}static covers(e){return Gt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getWater(e){return(await this.platform.waterSurfaces(e)).flatMap((i,s)=>Zu.surfacesOf(i,s))}static surfacesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="Polygon"?[s]:i==="MultiPolygon"?s:[],r=String(e.properties.cleabs??`ign-water-${t}`);return n.flatMap((a,o)=>{const l=a.map(h=>Zu.open(h.map(d=>({lat:d[1],lng:d[0]})))).filter(h=>h.length>=3);return l.length>0?[{id:n.length>1?`${r}-${o}`:r,rings:l}]:[]})}static open(e){const t=e[0],i=e[e.length-1];return e.length>1&&t.lat===i.lat&&t.lng===i.lng?e.slice(0,-1):e}}class Wl{attribution="Water © OpenStreetMap contributors";client;constructor(e={}){this.client=new ir(e)}async getWater(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${t});way["waterway"="riverbank"](${t});)->.w;(relation["natural"="water"](${t});relation["waterway"="riverbank"](${t});)->.r;.w out geom;.r out body;way(r.r)(${t});out geom;`;return Wl.surfacesFrom(await this.client.query(i))}static surfacesFrom(e){const t=e.elements??[],i=new Map;for(const r of t)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const s=[],n=new Set;for(const r of t){if(r.type!=="relation")continue;const a=l=>(r.members??[]).filter(h=>h.type==="way"&&h.role===l&&h.ref!==void 0&&i.has(h.ref)).map(h=>(n.add(h.ref),i.get(h.ref))),o=Wl.rings(a("inner"));for(const[l,h]of Wl.rings(a("outer")).entries()){const d=o.filter(u=>Wl.contains(h,u[0]));s.push({id:`osm-r${r.id}-${l}`,rings:[h,...d]})}}for(const r of t)if(!(r.type!=="way"||!r.tags||r.id===void 0||n.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of Wl.rings([i.get(r.id)??[]]))s.push({id:`osm-w${r.id}`,rings:[a]});return s}static rings(e){const t=(n,r)=>n.lat===r.lat&&n.lng===r.lng,i=e.filter(n=>n.length>=2).map(n=>[...n]),s=[];for(;i.length>0;){let n=i.pop(),r=!0;for(;!t(n[0],n[n.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const o=i[a],l=n[n.length-1];if(t(l,o[0]))n=[...n,...o.slice(1)];else if(t(l,o[o.length-1]))n=[...n,...[...o].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}n.length>=4&&t(n[0],n[n.length-1])&&s.push(n.slice(0,-1))}return s}static contains(e,t){let i=!1;for(let s=0,n=e.length-1;s<e.length;n=s++){const r=e[s],a=e[n];r.lat>t.lat!=a.lat>t.lat&&t.lng<(a.lng-r.lng)*(t.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class u_{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(e){if(Zu.covers(e))try{const t=await this.regional.getWater(e);if(t.length>0)return t}catch{}return this.worldwide.getWater(e)}}const $0="https://ufoathome.org/water/index.json";class fh{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??fh.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getWater(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.surfaces)?(this.attributionRead=n.attribution,n.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
4327
|
+
`);let t=fh.shared.get(e);return t||(t=this.fetchFirstAvailable(),fh.shared.set(e,t),t.then(i=>{i.length===0&&fh.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.162.0")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==$0?[t,$0]:[$0]).map(i=>i+e)}}class qn{constructor(e){this.water=e}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(e){const t=qn.key(e);let i=qn.asked.get(t);return i===void 0&&(i=this.recalled(t,e),qn.asked.set(t,i),i.catch(()=>qn.asked.delete(t))),structuredClone(await i)}static forget(){qn.asked.clear()}static key(e){return`v${qn.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await qn.openCache(),s=qn.request(e);if(i)try{const r=await i.match(s);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<qn.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&qn.store(i,s,n),n}static async store(e,t,i){try{const s={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const r of n.slice(0,Math.max(0,n.length-qn.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(qn.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class Jo{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(e={}){this.platform=new Gt(e)}static covers(e){return Gt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>Jo.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=Jo.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),l=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=Jo.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=Jo.electrificationOf(r.kind,d,e.properties.electrifie);return n.flatMap((p,f)=>{const m=p.map(v=>({lat:v[1],lng:v[0],...v.length>2&&Number.isFinite(v[2])&&v[2]>Jo.NO_ALTITUDE?{altitudeM:v[2]}:{}}));return m.length<2?[]:[{id:n.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(l)?l:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class Qs{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(e={}){this.client=new ir(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:120];way["railway"~"^(${Qs.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Qs.ROUTES})$"];out body;`;return Qs.apply(e,await this.client.query(s),t)}static apply(e,t,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=Qs.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(g=>ut(g.lat,g.lng,s.lat,s.lng)),o=new Map,l=new Map,h=new Map;let d=0;const u=n.filter(g=>g.service===!!r.service);for(const g of Qs.samples(a)){d++;const b=Qs.waysAt(u,g);if(b.length===0)continue;const[w]=b;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&l.set(w.voltageV,(l.get(w.voltageV)??0)+1);for(const y of new Set(b.flatMap(M=>M.services)))h.set(y,(h.get(y)??0)+1)}const p=g=>[...g.entries()].sort((b,w)=>w[1]-b[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(l)),v=[...h.entries()].filter(([,g])=>g*4>=d).sort((g,b)=>b[1]-g[1]||g[0].localeCompare(b[0])).map(([g])=>g);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...v.length>0?{services:v}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=Qs.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const r=t.get(n.ref)??new Set;r.add(s),t.set(n.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=Qs.servicesByWay(e),s=[];for(const n of e.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const r=n.tags??{},a=Qs.voltageOf(r);s.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>ut(o.lat,o.lon,t.lat,t.lng))})}return s}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const s=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(s<1e-6)continue;const n=(e[i+1].x-e[i].x)/s,r=(e[i+1].z-e[i].z)/s;for(let a=Qs.SAMPLE_M/2;a<s;a+=Qs.SAMPLE_M)t.push({x:e[i].x+n*a,z:e[i].z+r*a,dx:n,dz:r})}return t}static waysAt(e,t){const i=Math.cos(Qs.ALIGNED_DEG*Math.PI/180),s=[];for(const n of e){let r;for(let a=0;a<n.path.length-1;a++){const o=n.path[a],l=n.path[a+1],h=l.x-o.x,d=l.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=Qs.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&s.push({way:n,distance:r})}return s.sort((n,r)=>n.distance-r.distance).map(({way:n})=>n)}}class mh{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new ir(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${mh.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Qs.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=Qs.servicesByWay(e);for(const s of e.elements??[]){const n=s.geometry,r=s.tags;if(s.type==="relation"||!r||!n||n.length<2)continue;const a=[...i.get(s.id??-1)??[]].sort(),o=Qs.voltageOf(r),l=mh.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=mh.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${s.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:mh.levelOf(r),points:n.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class p_{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!Jo.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class _s{constructor(e,t=Date.now){this.railways=e,this.now=t}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(e){const t=_s.key(e);let i=_s.asked.get(t)??_s.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},_s.asked.set(t,i),s.catch(()=>_s.asked.delete(t))}return structuredClone(await i.answer)}static forget(){_s.asked.clear(),_s.failedAt=-1/0}static key(e){return`v${_s.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of _s.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await _s.openCache(),s=_s.request(e);let n;if(i)try{const a=await i.match(s);if(a){const{savedAt:o,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-o<_s.MAX_AGE_MS)return l;n=l}}}catch{}if(this.now()-_s.failedAt<_s.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(t)}catch(a){if(_s.failedAt=this.now(),n)return n;throw a}return i&&_s.store(i,s,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const n of s.slice(0,Math.max(0,s.length-_s.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(_s.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const K0="https://ufoathome.org/railways/index.json";class gh{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??gh.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
4328
|
+
`);let t=gh.shared.get(e);return t||(t=this.fetchFirstAvailable(),gh.shared.set(e,t),t.then(i=>{i.length===0&&gh.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.162.0")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==K0?[t,K0]:[K0]).map(i=>i+e)}}function A2(){return{elevation:T2(),imagery:I2(),roads:_2(),water:D2(),railways:R2()}}function T2(){return new l_(new Ut,new x2)}function I2(){return new E2}function _2(){return new ph({fallback:new d_(new Zo,new Yo)})}function D2(){return new fh({fallback:new qn(new u_(new Zu,new Wl))})}function R2(){return new gh({fallback:new _s(new p_(new Jo,new mh))})}const f_=new Set,Fh="show-observer-map",Uh="hide-milestones",Jl="minified";class qt extends HTMLElement{static get observedAttributes(){return["src",Fh,Uh,Jl]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new hi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=s0.create();issues=[];issueCheck=0;sightingAudio=new q5;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>qt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=p2;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,s=!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 n of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(n)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");qt.setIcon(this.moreButton,e?tt.UNFOLDED:tt.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),s=this.said.read(i?.shape.title);if(!s){this.tooltip.hidden=!0;return}this.tooltip.textContent=s,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-n.left+12}px`,this.tooltip.style.top=`${e.clientY-n.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)<qt.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>=hi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=hi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},qt.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 s=hi.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:s,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${$5}</style>${W5}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new nd(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Vl(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),s=a=>{const o=i.getBoundingClientRect(),l=this.player.seekableDuration;if(o.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&s(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===Fh&&this.applyObserverMapDefault(),e===Uh&&this.setMilestonesShown(!this.hasAttribute(Uh)),e===Jl){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Jl)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(k2)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages.clickToPlay:this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await na.recording(e)}get sightingData(){return um(this.currentSighting)}set sightingData(e){const t=Ui.toCurrent(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=ky(t),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let s=[];try{const{default:n}=await oe(async()=>{const{default:r}=await import("./sightingSchema-CnDwuCov.js");return{default:r}},[],import.meta.url);s=new $r(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],rd.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(m_,{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 s=document.createElement("li");return s.textContent=rd.text(i,this.messages.issueTemplates),s}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}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(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const s of t)this.controlsRight.insertBefore(s,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 s=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),s=this.said.read(t.title)??t.id,n=document.createElement("div");n.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,r.append(a,o);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages.referenceOpacity,l.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${s}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),n.append(r,l),n});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(n=>this.viewOfReference(n).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"),qt.setIcon(this.referencesButton,i?tt.PICTURES_ON:tt.PICTURES_OFF);const s=t?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=s,this.referencesButton.setAttribute("aria-label",s),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)),qt.setIcon(this.tracesButton,this.tracesShownState?tt.TRACES_ON:tt.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?cc(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const n=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${n} — ${r}`:n;return s.title=a,s.setAttribute("aria-label",a),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),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 s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return n.textContent=a?`${r} — ${a}`:r,n.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),s.appendChild(n),s})),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 s of this.momentsMenu.querySelectorAll("button")){const n=e!==void 0&&Number(s.dataset.t)===e.t;s.getAttribute("aria-current")==="true"!==n&&s.setAttribute("aria-current",String(n))}}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 s=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,a)=>r-a):[],Math.max(e,0)];this.seekSegmentList=[];const n=[];for(let r=0;r<s.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(s[r+1]-s[r],1));const o=document.createElement("i");o.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(o,l),n.push(a),this.seekSegmentList.push({start:s[r],end:s[r+1],element:a,played:l,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,s=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=qt.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 s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),n=s*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=qt.fillOf(p,n),p.element.classList.toggle("hovered",n>=p.start&&(n<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?V0(a,n):void 0,l=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(n)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}paintChrome(e){const t=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||s===0||n===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(s*r)),o=Math.max(1,Math.round(n*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new nd(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(s*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 s=qt.MARK_SNAP_PX/i*t;let n;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>s||(!n||Math.abs(a-e)<Math.abs(n.t-e))&&(n={t:a,name:r.title})}return n}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 s=(e.clientX-t.left)/t.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?V0(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 s=this.said.read(t.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(e=this.currentTime){const t=Zr.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<qt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(qt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/qt.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/qt.EXPOSURE_STEP_PX),n=Math.min(qt.MAX_TRAVEL_STEPS,Math.max(i,s)),r=[];for(let a=0;a<n;a++)r.push(t.fromMs+t.ms*a/(n-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),s=this.shapesAt(e+t);let n=0;for(const[r,a]of i){const o=s.get(r);if(!o)continue;const l=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);n=Math.max(n,Math.hypot(l,h))}return n}shapeAt(e,t,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,e,t,i);if(n)return n}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}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=Qt.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:f_;this.canvasRenderer.setStarPoints(Qt.starPointsOf(this.sighting.instrument,st(this.sighting,e)?.fNumber));const s=(st(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,l]of o.shapes){const h=o.share,d=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,l]of n[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)));const a=this.selectionShown&&i.size>1?Jt.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.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.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(fy(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new K5(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*qt.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?tt.PLAY:tt.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){qt.icons.get(e)!==t&&(qt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},qt.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,this.updateStartState(),qt.setIcon(this.playPauseButton,e?tt.PAUSE:tt.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(Fh),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;qt.setIcon(this.observerMapButton,e?tt.MAP_ON:tt.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[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=oc.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(s=>s.points):[],i=hi.fitted(this.observerPath,t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapFrozenImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?hi.expand(e,qt.OBSERVER_MAP_IMAGERY_AHEAD):e,s=hi.IMAGERY_PX*(t?1+2*qt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const n=this.observerMapFrozenImagery,r=n?void 0:I2();try{const a=r?await r.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??n).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,s=this.observerMapView.changed?hi.expand(e,qt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!n||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapFrozen(e){e!==this.observerMapFrozenImagery&&(this.observerMapFrozenImagery=e,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapFrozen(){return this.observerMapFrozenImagery}observerMapFrozenImagery;observerMapFrozenSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,d)=>{for(const u of t)if(!(u.x+u.width<l-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},s=[this.canvas.width-e.width,this.canvas.width],n=[0,e.width],r=qt.OBSERVER_MAP_CLEARANCE_PX,a=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!i(s[0],s[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(s[0],s[1],0)&&!i(n[0],n[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,s=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*s,bottom:(e.bottom-t.top)*s}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=st(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},qt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?V0(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?cc(this.currentSighting.milestones):[]){const a=st(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||s.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===n})}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?ar.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Qt.aspectOf(i)):void 0,markers:s,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,cc(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,qt.setIcon(this.milestonesButton,this.milestonesShown?tt.MILESTONES_ON:tt.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=st(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=Mr(i,e),{lat:n,lng:r}=Wn(s.eastM,-s.northM,t.lat,t.lng);return{lat:n,lng:r,headingDeg:s.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 s=st(this.currentSighting,this.currentTime),n=ar.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return bi.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=qt.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),qt.setIcon(this.miniMuteButton,this.mutedState?tt.MUTED:tt.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){qt.setIcon(this.muteButton,tt.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}qt.setIcon(this.muteButton,this.mutedState?tt.MUTED:tt.VOLUME);const i=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;qt.setIcon(this.fullscreenButton,e?tt.EXIT_FULLSCREEN:tt.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 rn(Sr.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=$u(Sr.preferencesFor(this),Wu);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await O3(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=Qh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Ev(e.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return Lo(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?rM(nM(this.realStartMs+i)):Lo(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Lo(e):Lo(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Lo(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Lo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Lo(this.currentSighting.timeline.duration):this.canShowClockTime?rM(nM(this.realStartMs+this.realDurationMs)):Lo(this.realDurationMs)}}function nM(c){const e=new Date(c);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function rM(c){if(c.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return c.second?`${e(c.hour)}:${e(c.minute??0)}:${e(c.second)}`:`${e(c.hour)}:${e(c.minute??0)}`}function Lo(c){const e=Math.round(c/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const qv="rr0-ufo";function f0(){customElements.get(qv)||customElements.define(qv,qt)}const m_="recordingissues",k2="minifiedreset";class Qd{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((n,r)=>n.t-r.t):[],s=`${t}|${i.map(n=>`${n.kind}:${n.t}:${n.label}`).join("|")}`;s!==this.drawn&&(this.drawn=s,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(n=>{const r=document.createElement("span");return r.className=`timeline-mark ${n.kind}`,r.style.left=`${Math.min(Math.max(n.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+Qd.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Qd.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Qd.SNAP_PX/t*this.duration;let s;for(const n of this.marks)Math.abs(n.t-e)>i||(!s||Math.abs(n.t-e)<Math.abs(s.t-e)||n.t===s.t&&n.kind==="milestone")&&(s=n);return s}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 vh{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const s=e.event.place?.[0],n=e.observerTrack;if(!s)return 0;const r=m=>{const v=n.getInterpolatedPoseAt(Math.max(0,m));if(!v||v.lat===void 0||v.lng===void 0)return;const g=ut(v.lat,v.lng,s.lat,s.lng);return{eastM:g.x,northM:-g.z,heading:v.headingDeg}},a=r(t-vh.HALF_SPAN_MS),o=r(t+vh.HALF_SPAN_MS),l=r(t);if(!a||!o||!l)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*vh.HALF_SPAN_MS/1e3;if(h/d<vh.MIN_SPEED_MS)return 0;const u=i.heightAt(o.eastM,o.northM)-i.heightAt(a.eastM,a.northM),p=Math.atan2(u,h)*180/Math.PI;if(l.heading===void 0)return p;const f=Math.atan2(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((l.heading-f)*Math.PI/180))}}const g_=.08,aM=.15,oM=2,v_=2e3;class b_{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}}lc.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(s=>s.inside||s.distanceM<v_),i=new Set(t.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of t){const n=this.voices.get(s.id)??this.build(e,s.id);this.retarget(e,n,s)}}build(e,t){const i=e.createGain();i.gain.value=0;const s=e.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(e));const n=e.createOscillator();n.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),r.connect(o),o.connect(a).connect(s);const l=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*oM*.5,M},h=l(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(s);const p=l(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(s);const v=l(),g=e.createBiquadFilter();g.type="bandpass",g.frequency.value=1400,g.Q.value=.7;const b=e.createGain();v.connect(g).connect(b).connect(s);const w=[n,r,h,p,v];for(const M of w)M.start();const y={nodes:[i,s,a,o,d,u,f,m,g,b,...w],sources:w,firing:n,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:b,cabin:s,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:s,noise:n,inside:r,windowsOpen:a,distanceM:o}){const l=e.currentTime,h=(b,w)=>b.setTargetAtTime(w,l,g_),d=s.rpm/60,u=d*i.cylinders/2,p=Math.min(1,s.rpm/i.shiftUpRpm),f=Math.min(1.5,s.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*s.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const v=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,v);const g=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,g*n)}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,aM/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},aM*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*oM,e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Ju{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 Ju.BY_KIND[e??"generic"]??Ju.BY_KIND.generic}}class Ql{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,s){const n=Ql.SAMPLE_MS,r=[];for(let l=i;l<=s+n/2;l+=n){const h=t(l-n/2),d=t(l+n/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(n/1e3))}const a=[];let o=1;for(let l=0;l<r.length;l++){const h=r[l],d=(r[Math.min(l+1,r.length-1)]-r[Math.max(l-1,0)])/(2*n/1e3);if(h<Ql.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=g=>u/e.kmhPer1000Rpm[g-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),v=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:v,gear:o})}return new Ql(a,i)}at(e){const t=(e-this.startMs)/Ql.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*r,rpm:s.rpm+(n.rpm-s.rpm)*r,load:s.load+(n.load-s.load)*r,gear:r<.5?s.gear:n.gear}}}class fm{drives=new Map;at(e,t){const i=[],s=e.event.place?.[0],n=l=>{const h=e.observerTrack.getInterpolatedPoseAt(l),d=h?.lat??s?.lat,u=h?.lng??s?.lng;if(d===void 0||u===void 0||!s)return;const p=ut(d,u,s.lat,s.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle;if(a){const l=Ju.of(a.kind),h=this.drive(`observer:${a.kind}`,fm.trackKey(e),()=>Ql.of(l,n,0,r));h&&i.push({id:"observer",profile:l,state:h.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const o=n(t);for(const l of e.decor){if(!l.engine||!o)continue;const h=Ju.of(l.engine.kind),d=m=>{const v=Mr(l,m);return{eastM:v.eastM,northM:v.northM}},u=this.drive(`decor:${l.id}`,fm.decorKey(l,r),()=>Ql.of(h,d,0,r));if(!u)continue;const p=Mr(l,t),f=Math.hypot(p.eastM-o.eastM,p.northM-o.northM,p.altitudeM);i.push({id:`decor:${l.id}`,profile:h,state:u.at(t),noise:l.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:f})}return i}drive(e,t,i){const s=this.drives.get(e);if(s&&s.key===t)return s.drive;const n=i();return this.drives.set(e,{key:t,drive:n}),n}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 y_="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",w_=`
|
|
4329
4329
|
<div class="stage" id="stage">
|
|
4330
4330
|
<div class="frame" id="frame">
|
|
4331
4331
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -9811,7 +9811,7 @@ float grassNoise(vec2 p) {
|
|
|
9811
9811
|
+ (grassNoise(vGrassPatchXZ * 21.0) - 0.5) * 0.6 * (1.0 - smoothstep(2.5, 12.0, eye));
|
|
9812
9812
|
float d = grain * uGrassContrast * grass;
|
|
9813
9813
|
diffuseColor.rgb *= vec3(1.0 + d * 1.1, 1.0 + d, 1.0 + d * 1.25);
|
|
9814
|
-
}`)},e.customProgramCacheKey=()=>t?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class va{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(e,t,i){const s=i&&i.length>=2?va.alongRoute(e,i):void 0;let n=0;for(const r of t){const a=va.fill(e,r).filter(h=>!s?.[h]);if(a.length===0)continue;const o=a.map(h=>e.heights[h]).filter(Number.isFinite).sort((h,d)=>h-d);if(o.length===0)continue;const l=o[Math.floor((o.length-1)*va.LEVEL_QUANTILE)];for(const h of a)e.heights[h]>l&&(e.heights[h]=l,n++)}return n}static fill(e,t){const{width:i,height:s,bounds:n}=e,r=u=>(u-n.west)/(n.east-n.west)*(i-1),a=u=>(n.north-u)/(n.north-n.south)*(s-1),o=[];for(const u of t.rings)for(let p=0;p<u.length;p++){const f=u[p],m=u[(p+1)%u.length],v={r0:a(f.lat),c0:r(f.lng),r1:a(m.lat),c1:r(m.lng)};v.r0!==v.r1&&o.push(v)}const l=[];if(o.length===0)return l;const h=Math.max(0,Math.ceil(Math.min(...o.map(u=>Math.min(u.r0,u.r1))))),d=Math.min(s-1,Math.floor(Math.max(...o.map(u=>Math.max(u.r0,u.r1)))));for(let u=h;u<=d;u++){const p=[];for(const{r0:f,c0:m,r1:v,c1:g}of o)f<=u!=v<=u&&p.push(m+(g-m)*(u-f)/(v-f));p.sort((f,m)=>f-m);for(let f=0;f+1<p.length;f+=2){const m=Math.max(0,Math.ceil(p[f])),v=Math.min(i-1,Math.floor(p[f+1]));for(let g=m;g<=v;g++)l.push(u*i+g)}}return l}static alongRoute(e,t){const{width:i,height:s,bounds:n}=e,r=(n.east-n.west)*va.METRES_PER_DEGREE*Math.cos((n.north+n.south)/2*Math.PI/180)/(i-1),a=(n.north-n.south)*va.METRES_PER_DEGREE/(s-1),o=Math.ceil(va.ROUTE_CLEARANCE_M/r),l=Math.ceil(va.ROUTE_CLEARANCE_M/a),h=new Uint8Array(i*s),d=p=>(p-n.west)/(n.east-n.west)*(i-1),u=p=>(n.north-p)/(n.north-n.south)*(s-1);for(let p=0;p+1<t.length;p++){const[f,m,v,g]=[d(t[p].lng),u(t[p].lat),d(t[p+1].lng),u(t[p+1].lat)];if(Math.max(f,v)<-o||Math.min(f,v)>i-1+o||Math.max(m,g)<-l||Math.min(m,g)>s-1+l)continue;const b=Math.max(1,Math.ceil(Math.hypot(v-f,g-m)*2));for(let w=0;w<=b;w++){const y=Math.round(f+(v-f)*w/b),M=Math.round(m+(g-m)*w/b);for(let S=-l;S<=l;S++)for(let E=-o;E<=o;E++){const x=M+S,A=y+E;x<0||A<0||x>=s||A>=i||Math.hypot(E*r,S*a)<=va.ROUTE_CLEARANCE_M&&(h[x*i+A]=1)}}}return h}}const LP=64,Om=LP+1,Pm=2048,OP=900,PP=700/900,NP=0,FP=.01,UP=1500;function cu(c,e,t){return{north:Wn(0,-t,c,e).lat,south:Wn(0,t,c,e).lat,east:Wn(t,0,c,e).lng,west:Wn(-t,0,c,e).lng}}async function Hx(c,e,t,i=OP,s,n){const r=i,a=i*PP,o=cu(c,e,r),l={width:Om,height:Om},h=n?void 0:t.water?.getWater(o).catch(N=>(console.warn("Water unavailable, drawing none:",N),[])),[d,u]=await Promise.all([t.elevation.getElevationGrid(o,l,s),t.imagery.getImageryTexture(o,{width:Pm,height:Pm})]);let p;const f=h?await Promise.race([h,new Promise(N=>{p=setTimeout(()=>N(void 0),UP)})]):void 0;if(clearTimeout(p),d.width!==d.height||d.width<3||d.heights.length!==d.width*d.height)throw new Error("The ground came as a grid that is not square");Nm.fill(d.heights,d.width),f&&f.length>0&&va.flatten(d,f,s?.route);const m=d.width,v=m-1,g=Math.floor(m/2),b=d.heights[g*m+g],w=n?.referenceElevationM??b,y=new Float32Array(m*m*3),M=new Float32Array(m*m*2),S=new Float32Array(m*m*4);for(let N=0;N<m;N++){const k=N/(m-1),C=o.north+(o.south-o.north)*k;for(let P=0;P<m;P++){const F=P/(m-1),V=o.west+(o.east-o.west)*F,{x:j,z:$}=ut(C,V,c,e),ee=d.heights[N*m+P],re=Math.max(Math.abs(j),Math.abs($)),Fe=n&&re<n.innerM?0:1-zP((re-a)/(r-a),0,1),Ve=NP+FP+(ee-w),Je=N*m+P;y[Je*3]=j,y[Je*3+1]=Ve,y[Je*3+2]=$;const Z=w2(u.bounds,V,C);M[Je*2]=Z.x,M[Je*2+1]=Z.y,S[Je*4]=1,S[Je*4+1]=1,S[Je*4+2]=1,S[Je*4+3]=Fe}}const E=m*m>65535?new Uint32Array(v*v*6):new Uint16Array(v*v*6);let x=0;for(let N=0;N<v;N++)for(let k=0;k<v;k++){const C=N*m+k,P=C+1,F=C+m,V=F+1;E[x++]=C,E[x++]=F,E[x++]=P,E[x++]=P,E[x++]=F,E[x++]=V}const A=new xt;A.setAttribute("position",new wt(y,3)),A.setAttribute("uv",new wt(M,2)),A.setAttribute("color",new wt(S,4)),A.setIndex(new wt(E,1)),A.computeVertexNormals();const D=new Dl(u.source);D.flipY=!1,D.colorSpace=Ys,D.anisotropy=8;const R=new Br({map:D,color:new ae(1,1,1),vertexColors:!0,transparent:!0,fog:!0});n||Vh.install(R);const L=new we(A,R);return L.receiveShadow=!n,L.castShadow=!n,{mesh:L,attribution:t.imagery.attribution,originElevationM:Number.isFinite(b)?b:void 0,...f?{water:f}:h?{waterLater:h}:{}}}class Nm{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(e,t){const i=n=>!Number.isFinite(n)||n<Nm.LOWEST_GROUND_M;let s=0;for(let n=0;n<e.length;n++)i(e[n])&&s++;for(let n=0;s>0&&n<Nm.MAX_PASSES;n++){const r=[];for(let a=0;a<t;a++)for(let o=0;o<t;o++){const l=a*t+o;if(!i(e[l]))continue;let h=0,d=0;for(const[u,p]of[[-1,0],[1,0],[0,-1],[0,1]]){const f=a+u,m=o+p;if(f<0||m<0||f>=t||m>=t)continue;const v=e[f*t+m];i(v)||(h+=v,d++)}d>0&&r.push([l,h/d])}for(const[a,o]of r)e[a]=o;if(s-=r.length,r.length===0)break}if(s>0)for(let n=0;n<e.length;n++)i(e[n])&&(e[n]=0)}}function zP(c,e,t){return Math.max(e,Math.min(t,c))}class At{static STEP_M=8;stepM=At.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new se;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new Kt;surveyed=new Kt;stated=new Kt;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(e){this.stepM=Number.isFinite(e)&&e>0?Math.min(At.STEP_M,Math.max(1.5,e/2)):At.STEP_M}set(e,t,i,s,n,r=1/0,a){const o=At.within(e,t,i,r);At.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(t,i);const l=new Map,h=o.map(p=>p.points.map(f=>ut(f.lat,f.lng,t,i))),d=o.map((p,f)=>this.streetOf(p,h[f],a));for(const[p,f]of o.entries()){const m=l.get(f.surface)??At.batchFor(f.surface);l.set(f.surface,m);const v=d[p];this.appendPath(h[p],f.widthM,s,m,v?{lateralAt:(g,b,w,y)=>v(g,b,w,y).carriageway}:{})}for(const[p,f]of l){const m=this.meshOf(p,f,n);m&&this.surveyed.add(m)}const u=this.sidewalks(o,h,d,s);if(u.indices.length>0){const p=this.meshOf("paved",u,!1,At.SIDEWALK_ALBEDO,!1);p&&(p.name="roads sidewalks",this.surveyed.add(p))}this.paint(o,t,i,s,n)}paint(e,t,i,s,n){if(!e.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(At.markingsModule??=oe(()=>import("./RoadMarkings-V8WtA9-k.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const o={positions:[],indices:[]};if(a.lay(e,t,i,(d,u,p)=>this.appendPath(d,u,s,o,{offsetM:p.offsetM,liftM:At.LIFT_M+p.liftM,minHalfM:p.minHalfM}))>0&&o.indices.length>0){const d=this.meshOf("paved",o,n,At.MARKINGS_ALBEDO,!1);d&&(d.name="roads markings",d.renderOrder=At.MARKINGS_RENDER_ORDER,d.material.polygonOffsetFactor=-4,d.material.polygonOffsetUnits=-4,this.surveyed.add(d))}const h=a.barrierGeometry(a.barriers(e,t,i),s);if(h.indices.length>0){const d=this.meshOf("paved",h,n,At.BARRIER_ALBEDO,!1);d&&(d.name="roads barriers",d.material.polygonOffset=!1,d.castShadow=!0,this.surveyed.add(d))}this.onMarkings?.()})}onMarkings;anchorGrain(e,t){if(this.grainReference){const s=ut(this.grainReference.lat,this.grainReference.lng,e,t);Math.hypot(s.x,s.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:e,lng:t};const i=ut(this.grainReference.lat,this.grainReference.lng,e,t);this.grainOrigin.set(-i.x,-i.z)}static within(e,t,i,s){if(!Number.isFinite(s))return e;const n=s*1.1+100;return e.filter(r=>{let a;for(const o of r.points){const l=ut(o.lat,o.lng,t,i);if(Math.hypot(l.x,l.z)<=n||a&&Math.hypot((l.x+a.x)/2,(l.z+a.z)/2)<=n)return!0;a=l}return!1})}streetOf(e,t,i){if(!e.urban||e.surface!=="paved")return;const s=At.surveyedAcross(e);if(!i||!i.near(t))return()=>s;const n=new Map,r=(p,f,m,v)=>{const g=`${p.toFixed(2)}:${f.toFixed(2)}`;let b=n.get(g);return b||(b=i.across(p,f,m,v),n.set(g,b)),b},a=this.rungsOf(t),o=a.flatMap(p=>{const f=r(p.x,p.z,p.dirX,p.dirZ);return f.leftM!==void 0&&f.rightM!==void 0?[(f.leftM-f.rightM)/2]:[]}).sort((p,f)=>p-f),l=i.lampsAlong(t);if(o.length===0&&l.length===0)return()=>s;const h=o.length>0?o[Math.floor((o.length-1)/2)]:0,d=At.clearOf(l,e.widthM/2,Math.max(-2.5,Math.min(At.STREET_MIDDLE_MOST_M,h))),u={rungs:a,across:(p,f,m,v)=>At.betweenWalls(e,d,r(p,f,m,v).leftM,r(p,f,m,v).rightM)};return this.laidStreets.push(u),(p,f,m,v)=>{const g=r(p,f,m,v);return At.betweenWalls(e,d,g.leftM,g.rightM)}}static clearOf(e,t,i){const s=r=>e.every(a=>Math.abs(a-r)>=t+At.LAMP_CLEARANCE_M);if(s(i))return i;const n=At.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*n;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=n&&s(a))return a;return i}atKerb(e,t){let i;for(const u of this.laidStreets)for(const p of u.rungs){const f=Math.hypot(e-p.x,t-p.z);f<=At.KERB_REACH_M&&(!i||f<i.distance)&&(i={rung:p,across:u.across(p.x,p.z,p.dirX,p.dirZ),distance:f})}if(!i)return{x:e,z:t};const{rung:s,across:n}=i,r=(e-s.x)*-s.dirZ+(t-s.z)*s.dirX,a=(e-s.x)*s.dirX+(t-s.z)*s.dirZ,l=(r>=n.carriageway.offsetM?n.left:n.right)??n.left??n.right;if(!l)return{x:e,z:t};const h=Math.sign(l.outerM-l.kerbM),d=l.kerbM+h*Math.min(At.LAMP_FROM_KERB_M,Math.abs(l.outerM-l.kerbM)/2);return{x:s.x+s.dirX*a-s.dirZ*d,z:s.z+s.dirZ*a+s.dirX*d}}rungsOf(e){const t=this.resample(e);return t.map((i,s)=>{const n=t[Math.max(0,s-1)],r=t[Math.min(t.length-1,s+1)],a=r.x-n.x,o=r.z-n.z,l=Math.hypot(a,o);return l<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/l,dirZ:o/l}})}static surveyedAcross(e){const t=e.widthM/2,i={offsetM:0,halfM:t};return e.widthM<At.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:t,outerM:t+At.SIDEWALK_WIDTH_M},right:{kerbM:-t,outerM:-t-At.SIDEWALK_WIDTH_M}}}static betweenWalls(e,t,i,s){const n=e.widthM/2,r={offsetM:t,halfM:n},a=t+n,o=t-n,l=i??a+At.SIDEWALK_WIDTH_M,h=-(s??-o+At.SIDEWALK_WIDTH_M);return{carriageway:r,...l-a>=At.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:l}}:{},...o-h>=At.SIDEWALK_NONE_M?{right:{kerbM:o,outerM:h}}:{}}}sidewalks(e,t,i,s){const n={positions:[],indices:[]},r=new ba(e,t);return e.forEach((a,o)=>{const l=i[o];if(!l)return;const h=(d,u)=>r.onAnotherCarriageway(d,u,o);for(const d of["left","right"]){const u=(p,f,m,v)=>{const g=l(p,f,m,v)[d];return g&&{offsetM:(g.kerbM+g.outerM)/2,halfM:Math.abs(g.outerM-g.kerbM)/2}};this.appendPath(t[o],0,s,n,{lateralAt:u,liftM:At.LIFT_M+At.SIDEWALK_KERB_M,minHalfM:0,skip:h}),this.appendKerb(t[o],s,n,(p,f,m,v)=>l(p,f,m,v)[d]?.kerbM,d==="left",h)}}),n}setStated(e,t){At.empty(this.stated);const i=new Map;for(const s of e){const n=i.get(s.surface)??At.batchFor(s.surface);i.set(s.surface,n),this.appendPath(s.path.map(r=>({x:r.eastM,z:-r.northM})),s.widthM,t,n)}for(const[s,n]of i){const r=this.meshOf(s,n,!1);r&&this.stated.add(r)}}clear(){At.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(e){for(const t of[...e.children]){e.remove(t);const i=t;i.geometry?.dispose(),i.material?.dispose()}}dispose(){At.empty(this.surveyed),At.empty(this.stated)}appendPath(e,t,i,s,n={}){const r=this.resample(e);if(r.length<2)return;const a=Math.max(n.minHalfM??.5,t/2),o=n.liftM??At.LIFT_M,l=n.offsetM??0,h=s.positions.length/3,d=[],u=[],p=[];for(let m=0;m<r.length;m++){const v=r[Math.max(0,m-1)],g=r[Math.min(r.length-1,m+1)];let b=g.x-v.x,w=g.z-v.z;const y=Math.hypot(b,w);y<1e-6?(b=1,w=0):(b/=y,w/=y);const M=n.lateralAt?n.lateralAt(r[m].x,r[m].z,b,w):{offsetM:l,halfM:a},S=M?Math.max(n.minHalfM??.5,M.halfM):a,E=M?.offsetM??l,x=-w*S,A=b*S,D={x:r[m].x+-w*E,z:r[m].z+b*E};d.push(M!==void 0&&M.halfM>0&&!n.skip?.(D.x,D.z)),u.push([{x:D.x+x,z:D.z+A},D,{x:D.x-x,z:D.z-A}]),p.push(S)}const f=u.map(m=>m.map(v=>i(v.x,v.z)));for(let m=0;m<u.length-1;m++)for(let v=0;v<3;v++){const g=u[m][v],b=u[m+1][v],w=i((g.x+b.x)/2,(g.z+b.z)/2)-(f[m][v]+f[m+1][v])/2;w>0&&(f[m][v]+=w,f[m+1][v]+=w)}for(let m=0;m<u.length;m++){for(let v=0;v<3;v++)s.positions.push(u[m][v].x,f[m][v]+o,u[m][v].z);s.edges?.push(p[m],p[m],0,p[m],-p[m],p[m])}for(let m=0;m<r.length-1;m++){if(!d[m]||!d[m+1])continue;const v=h+m*3;s.indices.push(v,v+3,v+1,v+1,v+3,v+4),s.indices.push(v+1,v+4,v+2,v+2,v+4,v+5)}}appendKerb(e,t,i,s,n,r){const a=this.resample(e);if(a.length<2)return;const o=i.positions.length/3,l=[];for(let h=0;h<a.length;h++){const d=a[Math.max(0,h-1)],u=a[Math.min(a.length-1,h+1)];let p=u.x-d.x,f=u.z-d.z;const m=Math.hypot(p,f);m<1e-6?(p=1,f=0):(p/=m,f/=m);const v=s(a[h].x,a[h].z,p,f),g=a[h].x+-f*(v??0),b=a[h].z+p*(v??0);l.push(v!==void 0&&!r(g,b));const w=t(g,b)+At.LIFT_M;i.positions.push(g,w,b,g,w+At.SIDEWALK_KERB_M,b)}for(let h=0;h<a.length-1;h++){if(!l[h]||!l[h+1])continue;const d=o+h*2;n?i.indices.push(d,d+1,d+2,d+1,d+3,d+2):i.indices.push(d,d+2,d+1,d+1,d+2,d+3)}}static batchFor(e){return e==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(e,t,i,s,n=!0){if(t.indices.length===0)return;const r=new xt;r.setAttribute("position",new wt(new Float32Array(t.positions),3));const a=t.edges!==void 0&&t.edges.length*3===t.positions.length*2;a&&r.setAttribute("aEdge",new wt(new Float32Array(t.edges),2)),r.setIndex(new wt(new Uint32Array(t.indices),1)),r.computeVertexNormals();const o=s??At.ALBEDO[e],l=new Br({color:new ae(o[0],o[1],o[2]),transparent:i,opacity:i?At.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});n&&this.addGrain(l,At.GRAIN_CONTRAST[e],a);const h=new we(r,l);return h.name=`roads ${e}`,h.renderOrder=At.RENDER_ORDER,h.receiveShadow=!0,h.castShadow=!1,h}addGrain(e,t,i=!1){const s=this.grainOrigin;e.onBeforeCompile=n=>{n.uniforms.uRoadOrigin={value:s},n.uniforms.uRoadContrast={value:t},i&&(n.defines={...n.defines,ROAD_VERGE:""}),n.vertexShader=n.vertexShader.replace("#include <common>",`#include <common>
|
|
9814
|
+
}`)},e.customProgramCacheKey=()=>t?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class va{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(e,t,i){const s=i&&i.length>=2?va.alongRoute(e,i):void 0;let n=0;for(const r of t){const a=va.fill(e,r).filter(h=>!s?.[h]);if(a.length===0)continue;const o=a.map(h=>e.heights[h]).filter(Number.isFinite).sort((h,d)=>h-d);if(o.length===0)continue;const l=o[Math.floor((o.length-1)*va.LEVEL_QUANTILE)];for(const h of a)e.heights[h]>l&&(e.heights[h]=l,n++)}return n}static fill(e,t){const{width:i,height:s,bounds:n}=e,r=u=>(u-n.west)/(n.east-n.west)*(i-1),a=u=>(n.north-u)/(n.north-n.south)*(s-1),o=[];for(const u of t.rings)for(let p=0;p<u.length;p++){const f=u[p],m=u[(p+1)%u.length],v={r0:a(f.lat),c0:r(f.lng),r1:a(m.lat),c1:r(m.lng)};v.r0!==v.r1&&o.push(v)}const l=[];if(o.length===0)return l;const h=Math.max(0,Math.ceil(Math.min(...o.map(u=>Math.min(u.r0,u.r1))))),d=Math.min(s-1,Math.floor(Math.max(...o.map(u=>Math.max(u.r0,u.r1)))));for(let u=h;u<=d;u++){const p=[];for(const{r0:f,c0:m,r1:v,c1:g}of o)f<=u!=v<=u&&p.push(m+(g-m)*(u-f)/(v-f));p.sort((f,m)=>f-m);for(let f=0;f+1<p.length;f+=2){const m=Math.max(0,Math.ceil(p[f])),v=Math.min(i-1,Math.floor(p[f+1]));for(let g=m;g<=v;g++)l.push(u*i+g)}}return l}static alongRoute(e,t){const{width:i,height:s,bounds:n}=e,r=(n.east-n.west)*va.METRES_PER_DEGREE*Math.cos((n.north+n.south)/2*Math.PI/180)/(i-1),a=(n.north-n.south)*va.METRES_PER_DEGREE/(s-1),o=Math.ceil(va.ROUTE_CLEARANCE_M/r),l=Math.ceil(va.ROUTE_CLEARANCE_M/a),h=new Uint8Array(i*s),d=p=>(p-n.west)/(n.east-n.west)*(i-1),u=p=>(n.north-p)/(n.north-n.south)*(s-1);for(let p=0;p+1<t.length;p++){const[f,m,v,g]=[d(t[p].lng),u(t[p].lat),d(t[p+1].lng),u(t[p+1].lat)];if(Math.max(f,v)<-o||Math.min(f,v)>i-1+o||Math.max(m,g)<-l||Math.min(m,g)>s-1+l)continue;const b=Math.max(1,Math.ceil(Math.hypot(v-f,g-m)*2));for(let w=0;w<=b;w++){const y=Math.round(f+(v-f)*w/b),M=Math.round(m+(g-m)*w/b);for(let S=-l;S<=l;S++)for(let E=-o;E<=o;E++){const x=M+S,A=y+E;x<0||A<0||x>=s||A>=i||Math.hypot(E*r,S*a)<=va.ROUTE_CLEARANCE_M&&(h[x*i+A]=1)}}}return h}}const LP=64,Om=LP+1,Pm=2048,OP=900,PP=700/900,NP=0,FP=.01,UP=1500;function cu(c,e,t){return{north:Wn(0,-t,c,e).lat,south:Wn(0,t,c,e).lat,east:Wn(t,0,c,e).lng,west:Wn(-t,0,c,e).lng}}async function Hx(c,e,t,i=OP,s,n){const r=i,a=i*PP,o=cu(c,e,r),l={width:Om,height:Om},h=n?void 0:t.water?.getWater(o).catch(N=>(console.warn("Water unavailable, drawing none:",N),[])),[d,u]=await Promise.all([t.elevation.getElevationGrid(o,l,s),t.imagery.getImageryTexture(o,{width:Pm,height:Pm})]);let p;const f=h?await Promise.race([h,new Promise(N=>{p=setTimeout(()=>N(void 0),UP)})]):void 0;if(clearTimeout(p),d.width!==d.height||d.width<3||d.heights.length!==d.width*d.height)throw new Error("The ground came as a grid that is not square");Nm.fill(d.heights,d.width),f&&f.length>0&&va.flatten(d,f,s?.route);const m=d.width,v=m-1,g=Math.floor(m/2),b=d.heights[g*m+g],w=n?.referenceElevationM??b,y=new Float32Array(m*m*3),M=new Float32Array(m*m*2),S=new Float32Array(m*m*4);for(let N=0;N<m;N++){const k=N/(m-1),C=o.north+(o.south-o.north)*k;for(let P=0;P<m;P++){const F=P/(m-1),V=o.west+(o.east-o.west)*F,{x:j,z:$}=ut(C,V,c,e),ee=d.heights[N*m+P],re=Math.max(Math.abs(j),Math.abs($)),Fe=n&&re<n.innerM?0:1-zP((re-a)/(r-a),0,1),Ve=NP+FP+(ee-w),Je=N*m+P;y[Je*3]=j,y[Je*3+1]=Ve,y[Je*3+2]=$;const Z=w2(u.bounds,V,C);M[Je*2]=Z.x,M[Je*2+1]=Z.y,S[Je*4]=1,S[Je*4+1]=1,S[Je*4+2]=1,S[Je*4+3]=Fe}}const E=m*m>65535?new Uint32Array(v*v*6):new Uint16Array(v*v*6);let x=0;for(let N=0;N<v;N++)for(let k=0;k<v;k++){const C=N*m+k,P=C+1,F=C+m,V=F+1;E[x++]=C,E[x++]=F,E[x++]=P,E[x++]=P,E[x++]=F,E[x++]=V}const A=new xt;A.setAttribute("position",new wt(y,3)),A.setAttribute("uv",new wt(M,2)),A.setAttribute("color",new wt(S,4)),A.setIndex(new wt(E,1)),A.computeVertexNormals();const D=new Dl(u.source);D.flipY=!1,D.colorSpace=Ys,D.anisotropy=8;const R=new Br({map:D,color:new ae(1,1,1),vertexColors:!0,transparent:!0,fog:!0});n||Vh.install(R);const L=new we(A,R);return L.receiveShadow=!n,L.castShadow=!n,{mesh:L,attribution:t.imagery.attribution,originElevationM:Number.isFinite(b)?b:void 0,...f?{water:f}:h?{waterLater:h}:{}}}class Nm{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(e,t){const i=n=>!Number.isFinite(n)||n<Nm.LOWEST_GROUND_M;let s=0;for(let n=0;n<e.length;n++)i(e[n])&&s++;for(let n=0;s>0&&n<Nm.MAX_PASSES;n++){const r=[];for(let a=0;a<t;a++)for(let o=0;o<t;o++){const l=a*t+o;if(!i(e[l]))continue;let h=0,d=0;for(const[u,p]of[[-1,0],[1,0],[0,-1],[0,1]]){const f=a+u,m=o+p;if(f<0||m<0||f>=t||m>=t)continue;const v=e[f*t+m];i(v)||(h+=v,d++)}d>0&&r.push([l,h/d])}for(const[a,o]of r)e[a]=o;if(s-=r.length,r.length===0)break}if(s>0)for(let n=0;n<e.length;n++)i(e[n])&&(e[n]=0)}}function zP(c,e,t){return Math.max(e,Math.min(t,c))}class At{static STEP_M=8;stepM=At.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new se;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new Kt;surveyed=new Kt;stated=new Kt;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(e){this.stepM=Number.isFinite(e)&&e>0?Math.min(At.STEP_M,Math.max(1.5,e/2)):At.STEP_M}set(e,t,i,s,n,r=1/0,a){const o=At.within(e,t,i,r);At.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(t,i);const l=new Map,h=o.map(p=>p.points.map(f=>ut(f.lat,f.lng,t,i))),d=o.map((p,f)=>this.streetOf(p,h[f],a));for(const[p,f]of o.entries()){const m=l.get(f.surface)??At.batchFor(f.surface);l.set(f.surface,m);const v=d[p];this.appendPath(h[p],f.widthM,s,m,v?{lateralAt:(g,b,w,y)=>v(g,b,w,y).carriageway}:{})}for(const[p,f]of l){const m=this.meshOf(p,f,n);m&&this.surveyed.add(m)}const u=this.sidewalks(o,h,d,s);if(u.indices.length>0){const p=this.meshOf("paved",u,!1,At.SIDEWALK_ALBEDO,!1);p&&(p.name="roads sidewalks",this.surveyed.add(p))}this.paint(o,t,i,s,n)}paint(e,t,i,s,n){if(!e.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(At.markingsModule??=oe(()=>import("./RoadMarkings-HF9xJtTp.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const o={positions:[],indices:[]};if(a.lay(e,t,i,(d,u,p)=>this.appendPath(d,u,s,o,{offsetM:p.offsetM,liftM:At.LIFT_M+p.liftM,minHalfM:p.minHalfM}))>0&&o.indices.length>0){const d=this.meshOf("paved",o,n,At.MARKINGS_ALBEDO,!1);d&&(d.name="roads markings",d.renderOrder=At.MARKINGS_RENDER_ORDER,d.material.polygonOffsetFactor=-4,d.material.polygonOffsetUnits=-4,this.surveyed.add(d))}const h=a.barrierGeometry(a.barriers(e,t,i),s);if(h.indices.length>0){const d=this.meshOf("paved",h,n,At.BARRIER_ALBEDO,!1);d&&(d.name="roads barriers",d.material.polygonOffset=!1,d.castShadow=!0,this.surveyed.add(d))}this.onMarkings?.()})}onMarkings;anchorGrain(e,t){if(this.grainReference){const s=ut(this.grainReference.lat,this.grainReference.lng,e,t);Math.hypot(s.x,s.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:e,lng:t};const i=ut(this.grainReference.lat,this.grainReference.lng,e,t);this.grainOrigin.set(-i.x,-i.z)}static within(e,t,i,s){if(!Number.isFinite(s))return e;const n=s*1.1+100;return e.filter(r=>{let a;for(const o of r.points){const l=ut(o.lat,o.lng,t,i);if(Math.hypot(l.x,l.z)<=n||a&&Math.hypot((l.x+a.x)/2,(l.z+a.z)/2)<=n)return!0;a=l}return!1})}streetOf(e,t,i){if(!e.urban||e.surface!=="paved")return;const s=At.surveyedAcross(e);if(!i||!i.near(t))return()=>s;const n=new Map,r=(p,f,m,v)=>{const g=`${p.toFixed(2)}:${f.toFixed(2)}`;let b=n.get(g);return b||(b=i.across(p,f,m,v),n.set(g,b)),b},a=this.rungsOf(t),o=a.flatMap(p=>{const f=r(p.x,p.z,p.dirX,p.dirZ);return f.leftM!==void 0&&f.rightM!==void 0?[(f.leftM-f.rightM)/2]:[]}).sort((p,f)=>p-f),l=i.lampsAlong(t);if(o.length===0&&l.length===0)return()=>s;const h=o.length>0?o[Math.floor((o.length-1)/2)]:0,d=At.clearOf(l,e.widthM/2,Math.max(-2.5,Math.min(At.STREET_MIDDLE_MOST_M,h))),u={rungs:a,across:(p,f,m,v)=>At.betweenWalls(e,d,r(p,f,m,v).leftM,r(p,f,m,v).rightM)};return this.laidStreets.push(u),(p,f,m,v)=>{const g=r(p,f,m,v);return At.betweenWalls(e,d,g.leftM,g.rightM)}}static clearOf(e,t,i){const s=r=>e.every(a=>Math.abs(a-r)>=t+At.LAMP_CLEARANCE_M);if(s(i))return i;const n=At.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*n;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=n&&s(a))return a;return i}atKerb(e,t){let i;for(const u of this.laidStreets)for(const p of u.rungs){const f=Math.hypot(e-p.x,t-p.z);f<=At.KERB_REACH_M&&(!i||f<i.distance)&&(i={rung:p,across:u.across(p.x,p.z,p.dirX,p.dirZ),distance:f})}if(!i)return{x:e,z:t};const{rung:s,across:n}=i,r=(e-s.x)*-s.dirZ+(t-s.z)*s.dirX,a=(e-s.x)*s.dirX+(t-s.z)*s.dirZ,l=(r>=n.carriageway.offsetM?n.left:n.right)??n.left??n.right;if(!l)return{x:e,z:t};const h=Math.sign(l.outerM-l.kerbM),d=l.kerbM+h*Math.min(At.LAMP_FROM_KERB_M,Math.abs(l.outerM-l.kerbM)/2);return{x:s.x+s.dirX*a-s.dirZ*d,z:s.z+s.dirZ*a+s.dirX*d}}rungsOf(e){const t=this.resample(e);return t.map((i,s)=>{const n=t[Math.max(0,s-1)],r=t[Math.min(t.length-1,s+1)],a=r.x-n.x,o=r.z-n.z,l=Math.hypot(a,o);return l<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/l,dirZ:o/l}})}static surveyedAcross(e){const t=e.widthM/2,i={offsetM:0,halfM:t};return e.widthM<At.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:t,outerM:t+At.SIDEWALK_WIDTH_M},right:{kerbM:-t,outerM:-t-At.SIDEWALK_WIDTH_M}}}static betweenWalls(e,t,i,s){const n=e.widthM/2,r={offsetM:t,halfM:n},a=t+n,o=t-n,l=i??a+At.SIDEWALK_WIDTH_M,h=-(s??-o+At.SIDEWALK_WIDTH_M);return{carriageway:r,...l-a>=At.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:l}}:{},...o-h>=At.SIDEWALK_NONE_M?{right:{kerbM:o,outerM:h}}:{}}}sidewalks(e,t,i,s){const n={positions:[],indices:[]},r=new ba(e,t);return e.forEach((a,o)=>{const l=i[o];if(!l)return;const h=(d,u)=>r.onAnotherCarriageway(d,u,o);for(const d of["left","right"]){const u=(p,f,m,v)=>{const g=l(p,f,m,v)[d];return g&&{offsetM:(g.kerbM+g.outerM)/2,halfM:Math.abs(g.outerM-g.kerbM)/2}};this.appendPath(t[o],0,s,n,{lateralAt:u,liftM:At.LIFT_M+At.SIDEWALK_KERB_M,minHalfM:0,skip:h}),this.appendKerb(t[o],s,n,(p,f,m,v)=>l(p,f,m,v)[d]?.kerbM,d==="left",h)}}),n}setStated(e,t){At.empty(this.stated);const i=new Map;for(const s of e){const n=i.get(s.surface)??At.batchFor(s.surface);i.set(s.surface,n),this.appendPath(s.path.map(r=>({x:r.eastM,z:-r.northM})),s.widthM,t,n)}for(const[s,n]of i){const r=this.meshOf(s,n,!1);r&&this.stated.add(r)}}clear(){At.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(e){for(const t of[...e.children]){e.remove(t);const i=t;i.geometry?.dispose(),i.material?.dispose()}}dispose(){At.empty(this.surveyed),At.empty(this.stated)}appendPath(e,t,i,s,n={}){const r=this.resample(e);if(r.length<2)return;const a=Math.max(n.minHalfM??.5,t/2),o=n.liftM??At.LIFT_M,l=n.offsetM??0,h=s.positions.length/3,d=[],u=[],p=[];for(let m=0;m<r.length;m++){const v=r[Math.max(0,m-1)],g=r[Math.min(r.length-1,m+1)];let b=g.x-v.x,w=g.z-v.z;const y=Math.hypot(b,w);y<1e-6?(b=1,w=0):(b/=y,w/=y);const M=n.lateralAt?n.lateralAt(r[m].x,r[m].z,b,w):{offsetM:l,halfM:a},S=M?Math.max(n.minHalfM??.5,M.halfM):a,E=M?.offsetM??l,x=-w*S,A=b*S,D={x:r[m].x+-w*E,z:r[m].z+b*E};d.push(M!==void 0&&M.halfM>0&&!n.skip?.(D.x,D.z)),u.push([{x:D.x+x,z:D.z+A},D,{x:D.x-x,z:D.z-A}]),p.push(S)}const f=u.map(m=>m.map(v=>i(v.x,v.z)));for(let m=0;m<u.length-1;m++)for(let v=0;v<3;v++){const g=u[m][v],b=u[m+1][v],w=i((g.x+b.x)/2,(g.z+b.z)/2)-(f[m][v]+f[m+1][v])/2;w>0&&(f[m][v]+=w,f[m+1][v]+=w)}for(let m=0;m<u.length;m++){for(let v=0;v<3;v++)s.positions.push(u[m][v].x,f[m][v]+o,u[m][v].z);s.edges?.push(p[m],p[m],0,p[m],-p[m],p[m])}for(let m=0;m<r.length-1;m++){if(!d[m]||!d[m+1])continue;const v=h+m*3;s.indices.push(v,v+3,v+1,v+1,v+3,v+4),s.indices.push(v+1,v+4,v+2,v+2,v+4,v+5)}}appendKerb(e,t,i,s,n,r){const a=this.resample(e);if(a.length<2)return;const o=i.positions.length/3,l=[];for(let h=0;h<a.length;h++){const d=a[Math.max(0,h-1)],u=a[Math.min(a.length-1,h+1)];let p=u.x-d.x,f=u.z-d.z;const m=Math.hypot(p,f);m<1e-6?(p=1,f=0):(p/=m,f/=m);const v=s(a[h].x,a[h].z,p,f),g=a[h].x+-f*(v??0),b=a[h].z+p*(v??0);l.push(v!==void 0&&!r(g,b));const w=t(g,b)+At.LIFT_M;i.positions.push(g,w,b,g,w+At.SIDEWALK_KERB_M,b)}for(let h=0;h<a.length-1;h++){if(!l[h]||!l[h+1])continue;const d=o+h*2;n?i.indices.push(d,d+1,d+2,d+1,d+3,d+2):i.indices.push(d,d+2,d+1,d+1,d+2,d+3)}}static batchFor(e){return e==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(e,t,i,s,n=!0){if(t.indices.length===0)return;const r=new xt;r.setAttribute("position",new wt(new Float32Array(t.positions),3));const a=t.edges!==void 0&&t.edges.length*3===t.positions.length*2;a&&r.setAttribute("aEdge",new wt(new Float32Array(t.edges),2)),r.setIndex(new wt(new Uint32Array(t.indices),1)),r.computeVertexNormals();const o=s??At.ALBEDO[e],l=new Br({color:new ae(o[0],o[1],o[2]),transparent:i,opacity:i?At.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});n&&this.addGrain(l,At.GRAIN_CONTRAST[e],a);const h=new we(r,l);return h.name=`roads ${e}`,h.renderOrder=At.RENDER_ORDER,h.receiveShadow=!0,h.castShadow=!1,h}addGrain(e,t,i=!1){const s=this.grainOrigin;e.onBeforeCompile=n=>{n.uniforms.uRoadOrigin={value:s},n.uniforms.uRoadContrast={value:t},i&&(n.defines={...n.defines,ROAD_VERGE:""}),n.vertexShader=n.vertexShader.replace("#include <common>",`#include <common>
|
|
9815
9815
|
varying vec2 vRoadXZ;
|
|
9816
9816
|
uniform vec2 uRoadOrigin;
|
|
9817
9817
|
#ifdef ROAD_VERGE
|
|
@@ -10817,7 +10817,7 @@ ${l.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
10817
10817
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
10818
10818
|
}
|
|
10819
10819
|
`,transparent:!0,depthWrite:!1,side:qs,fog:!1,blending:wc,blendSrc:Mc,blendDst:Qu})}static wallReflectance(e,t,i){const s=i(e,1,t);return 2*s/(1+s)}setSurroundings(e){this.uniforms.uSurroundings.value=e}static reflectedResponse(e,t){return Be.respond(t*Be.relativeOfResponse(Math.max(e,1e-5)))}}class Zn{static SIZE=64;static MOVE_M=.01;holder=new qi;cameras=[];faces=[];target=new ai(Zn.SIZE,Zn.SIZE);white=new $n({color:new ae(1,1,1),side:qs});scene=new Er;cabin;meshes=0;eye=new I;scratch=new I;constructor(){const e=[[new I(1,0,0),new I(0,1,0)],[new I(-1,0,0),new I(0,1,0)],[new I(0,1,0),new I(0,0,1)],[new I(0,-1,0),new I(0,0,-1)],[new I(0,0,1),new I(0,1,0)],[new I(0,0,-1),new I(0,1,0)]];for(const[t,i]of e){const s=new nn(90,1,.02,20);s.up.copy(i),s.lookAt(t),this.holder.add(s),this.cameras.push(s),this.faces.push(new Uint8Array(Zn.SIZE*Zn.SIZE*4))}this.scene.background=new ae(0,0,0)}get any(){return this.cabin!==void 0}update(e,t,i){if(!t){this.forget();return}t.updateWorldMatrix(!0,!0);const s=this.scratch.copy(i);t.worldToLocal(s);let n=0;t.traverse(r=>{r.isMesh&&n++}),!(t===this.cabin&&n===this.meshes&&s.distanceTo(this.eye)<Zn.MOVE_M)&&(this.cabin=t,this.meshes=n,this.eye.copy(s),this.draw(e,t))}hides(e){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let t=0;t<6;t++){const i=this.cameras[t],s=this.scratch.copy(e).transformDirection(i.matrixWorldInverse);if(s.z>=0)continue;const n=s.x/-s.z,r=s.y/-s.z;if(Math.abs(n)>1||Math.abs(r)>1)continue;const a=Math.min(Zn.SIZE-1,Math.floor((n+1)/2*Zn.SIZE)),o=Math.min(Zn.SIZE-1,Math.floor((r+1)/2*Zn.SIZE));return this.faces[t][(o*Zn.SIZE+a)*4]>127}return!1}forget(){this.holder.removeFromParent(),this.cabin=void 0,this.meshes=0}dispose(){this.forget(),this.target.dispose(),this.white.dispose()}draw(e,t){t.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];t.traverse(r=>{const a=r;if(!a.isMesh||!a.visible||(Array.isArray(a.material)?a.material:[a.material]).every(h=>h instanceof xo))return;const l=new we(a.geometry,this.white);l.matrixAutoUpdate=!1,l.matrix.copy(a.matrixWorld),l.matrixWorld.copy(a.matrixWorld),i.push(l)});for(const r of i)this.scene.add(r);const s=e.getRenderTarget(),n=e.shadowMap.autoUpdate;e.shadowMap.autoUpdate=!1;for(let r=0;r<6;r++){const a=this.cameras[r];a.updateMatrixWorld(!0),e.setRenderTarget(this.target),e.clear(),e.render(this.scene,a),e.readRenderTargetPixels(this.target,0,0,Zn.SIZE,Zn.SIZE,this.faces[r])}e.setRenderTarget(s),e.shadowMap.autoUpdate=n;for(const r of i)r.removeFromParent()}}const Wg="https://ufoathome.org/models/index.json";class pu{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??k6()}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(`
|
|
10820
|
-
`);let t=pu.shared.get(e);return t||(t=this.fetchFirstAvailable(),pu.shared.set(e,t),t.then(i=>{i.length===0&&pu.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:s,...n})=>({...n,url:new URL(s,e).href})):void 0}catch{return}}}function k6(){const c=`?v=${encodeURIComponent("0.
|
|
10820
|
+
`);let t=pu.shared.get(e);return t||(t=this.fetchFirstAvailable(),pu.shared.set(e,t),t.then(i=>{i.length===0&&pu.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:s,...n})=>({...n,url:new URL(s,e).href})):void 0}catch{return}}}function k6(){const c=`?v=${encodeURIComponent("0.162.0")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==Wg?[e,Wg]:[Wg]).map(t=>t+c)}const Kf=[{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 pu}];async function $g(c){const{GLTFLoader:e}=await oe(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-BVRuOnnK.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,s)=>{t.load(c,n=>i(Object.assign(n.scene,{animations:n.animations})),void 0,n=>s(new Error(`Could not load 3D model ${c}: ${n instanceof Error?n.message:String(n)}`)))})}class yr{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new we(new _n(2,2),new Pt({uniforms:{uColor:{value:new ae(0,0,0)},uRadius:{value:1}},vertexShader:yr.VERTEX,fragmentShader:yr.FRAGMENT,transparent:!0,depthWrite:!1,blending:zs,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,s){const n=Math.max(e,s*yr.MIN_ANGLE_RAD),r=yr.FILL*Math.PI*n*n;return{radiusM:n,luminanceCdM2:i*Math.min(yr.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(yr.MAX_SHARE*yr.FILL*Math.PI))}static VERTEX=`
|
|
10821
10821
|
uniform float uRadius;
|
|
10822
10822
|
varying vec2 vOffset;
|
|
10823
10823
|
void main() {
|
|
@@ -11426,7 +11426,7 @@ void main() {`).replace("#include <opaque_fragment>",`
|
|
|
11426
11426
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
11427
11427
|
gl_FragColor = vec4(light, 1.0);
|
|
11428
11428
|
}
|
|
11429
|
-
`,transparent:!0,blending:zs,depthWrite:!1,side:is,fog:!1});this.object=new we(new As(a1.RADIUS,128,32,0,Math.PI*2,0,Vt.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<Vt.STEPS;i++){for(let s=0;s<3;s++)this.texels[i*4+s]=js.toHalfFloat(Math.min(t[i*3+s],6e4));this.texels[i*4+3]=js.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class zm{constructor(e){this.generator=e}static SIZE=128;target=new op(zm.SIZE,{type:ti,generateMipmaps:!0,minFilter:xr,magFilter:Tt});camera=new i1(.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,s=[]){const n=e.shadowMap.autoUpdate;let r=!1;t.traverse(o=>{const l=o;l.isLight&&l.castShadow&&l.shadow&&!l.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?n:!1;const a=s.map(o=>o.visible);for(const o of s)o.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),s.forEach((o,l)=>{o.visible=a[l]}),e.shadowMap.autoUpdate=n,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class yn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){yn.install(),this.generator=new Gb(e),this.eye=new zm(this.generator)}static decor;refresh(e,t,i,s,n,r,a,o=[],l,h=yn.REFRESH_MS){for(const v of[...this.probes.keys()])s.some(g=>g.id===v&&g.shiny)||(this.probes.get(v).dispose(),this.probes.delete(v));const d=[{probe:this.eye}];for(const v of s){if(!v.shiny)continue;let g=this.probes.get(v.id);g||(g=new zm(this.generator),this.probes.set(v.id,g)),d.push({probe:g,reflector:v})}const u=performance.now(),p=()=>d.filter(({probe:v})=>v.capturedVersion!==a),f=p().filter(({probe:v})=>u-v.capturedAtMs>=h);if(f.length>0){const v=f.reduce((g,b)=>b.probe.capturedAtMs<g.probe.capturedAtMs?b:g);if(v.reflector){const g=v.reflector.holder.getWorldPosition(this.scratch);v.probe.capture(e,t,g,[v.reflector.holder,...n]),yn.reflectOn(v.reflector.holder,v.probe)}else{v.probe.capture(e,t,i,[...n,...o]),l?.(v.probe.sharp),yn.decor=v.probe.filtered;for(const g of r)yn.reflectOn(g,v.probe);for(const g of s)g.shiny||yn.reflectOn(g.holder,v.probe)}v.probe.capturedVersion=a}const m=p();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:v})=>h-(u-v.capturedAtMs))))}scratch=new I;static reflectOn(e,t={filtered:yn.decor}){e.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[])n instanceof xo?t.sharp&&n.setSurroundings(t.sharp):n instanceof el&&t.filtered&&n.envMap!==t.filtered&&(n.envMap=t.filtered,n.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const e of this.probes.values())e.dispose();this.generator.dispose()}static installed=!1;static install(){if(yn.installed)return;yn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!vt.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}vt.lights_fragment_maps=vt.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function O6(c,e){return JSON.stringify(c.cloudLayers)===JSON.stringify(e.cloudLayers)&&c.cloudCover===e.cloudCover&&c.cloudDarkness===e.cloudDarkness&&c.cloudBaseM===e.cloudBaseM&&c.highCloudCover===e.highCloudCover&&c.iceCrystalAlignment===e.iceCrystalAlignment&&c.rareIceCrystals===e.rareIceCrystals&&c.lowerCloudCover===e.lowerCloudCover&&c.relativeHumidity===e.relativeHumidity&&c.precipitationType===e.precipitationType&&c.precipitationIntensity===e.precipitationIntensity&&c.precipitationAmount===e.precipitationAmount&&c.windDirectionDeg===e.windDirectionDeg&&c.windSpeed===e.windSpeed&&c.storm===e.storm}const pf=900,Kg=1,aS=4,Xg=5,ff=.5,mf=ri.GROUND_RADIUS_M;function oS(c){return ri.groundRadiusFor(c)}const Yg=.5,qg=850,gf=.03,P6=.015,Rn=850,ih=300,Qa=120,N6=700,jg=.03,F6=3.5,vf=20,Zg=.04,U6=.26,lS=4,Jg=1.5,cS=-1,z6=.01,Xf=-4,B6=2,H6=20,bf=2600,G6=.97,V6=.38,Hd=Xf,W6=8,$6=2,hS=1500,K6=.7,X6=.3,Y6=.32,q6=.65,dS=2.4,j6=.9,Z6=400,J6=[0,45,90,135,180,225,270,315],Q6=2,eN=16,uS=4e3,pS=880,yf=40,fS=60,tN=10,iN=1,sN=ri.REBUILD_DISTANCE_M,mS=.265,gS=[[0,0],...Array.from({length:8},(c,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*mS,Math.sin(t)*mS]})],Qg=700,ev=250/ry,nN=12,vS=5,tv=6,Fl=[.92,.92,.95],iv=[.15,.15,.19],sv={snow:{fallSpeedMPerS:2,size:.3,color:new ae(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new ae(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},ah=0,nv=0,rN=150,rv=3e3,Gd=20,aN=15,bS=ah,oN=40,yS=1,lN=9;function av(c){return yS+(lN-yS)*c}const wS=new ae(.75,.82,.92),cN=10,hN=.5;function MS(c){return ya(c/cN,hN,1)}const Ul=200,xS=.18,SS=.32,dN=.35,ES=new ae(.85,.9,.98),AS=5,TS=.85,IS=.01;function uN(c,e,t=1){return Math.round(c*(IS+(1-IS)*e)*t)}function pN(c,e){return JSON.stringify(c.cloudLayers)===JSON.stringify(e.cloudLayers)&&c.cloudCover===e.cloudCover&&c.cloudDarkness===e.cloudDarkness&&c.cloudBaseM===e.cloudBaseM&&c.highCloudCover===e.highCloudCover&&c.iceCrystalAlignment===e.iceCrystalAlignment&&c.lowerCloudCover===e.lowerCloudCover}const _S=230,DS=.7,RS=.05,fN=.6,mN=.7,gN=.15,kS=.35,vN=3,bN=1/12,yN=.5,fa=new ae(.82,.86,1),wN=2500,MN=1.6,ov=15,xN={Venus:new ae(1,.96,.85),Mars:new ae(1,.55,.4),Jupiter:new ae(.95,.87,.72),Saturn:new ae(.92,.86,.68)};class de{renderer;scene=new Er;phenomena=new qr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;onReferencesSettled;camera;celestialGroup=new Kt;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(e,t){if(this.skyHoldUntilMs===null)return e;this.arrivalsPending++;let i=!0;const s=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},n=t===void 0?void 0:setTimeout(s,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(n),s()})}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()+uS,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),uS+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new At;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new se;decorModelProvider=Kf[0].create();decorModelToken=0;decorModelCredits=new Map;emitterLights=new Cn(this.scene,()=>this.relativeScale,{halfExtentM:Qa,depthHalfRangeM:ih,biasM:jg,normalBiasM:Zg,mapSize:1024});bodySystem=new ht(e=>this.awaitArrival(this.loadBodyModel(e)),()=>this.render(),()=>this.relativeScale,e=>this.emitterLights.set("bodies",e));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??de.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*de.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;beams=[];beamSystem;beamSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new _m(16777215,0);celestialLightTarget=new qi;skyLight=new YR(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new Gf;weather=Zm;observerElevationM=0;siteElevationM=0;air=new Lr;groundRadius=mf;terrainRadius=mf;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new I;cloudFieldOffset=new I;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new I;rainLastVerticalFacing=-1;rainViewportSize=new se;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new _m(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new I;sunVisible=!1;lensFlareScratch=new I;sunOcclusionRaycaster=new Gf;sunOcclusionDirectionScratch=new I;sunOcclusionRightScratch=new I;sunOcclusionUpScratch=new I;ufoOcclusionRaycaster=new Gf;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=Ci.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(e){return Math.max(3,Math.round(6e6/Math.max(1,e)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;reentrySystem;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new lp;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=A2()){lu.install(),this.renderer=new cP({canvas:e,antialias:!0}),this.resolution=new ci(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=eu,this.camera=new nn(60,e.width/Math.max(e.height,1),.1,pf*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=-Qa,this.celestialLight.shadow.camera.right=Qa,this.celestialLight.shadow.camera.top=Qa,this.celestialLight.shadow.camera.bottom=-Qa,this.celestialLight.shadow.camera.near=Rn-ih,this.celestialLight.shadow.camera.far=Rn+ih,this.celestialLight.shadow.bias=-jg/(2*ih),this.celestialLight.shadow.normalBias=Zg,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(fa),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new yt(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(e,t){this.cssSize.width=e,this.cssSize.height=t,this.renderer.setSize(e,t,!1),this.camera.aspect=e/Math.max(t,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(e){e!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=e,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(e,t={}){this.cloudOffsetM.set(e.x,0,e.z),this.cloudLayerOffsetsM=t,this.layeredClouds?.setOffsets(e,t),this.cloudFieldOffset.set(e.x*ev,0,e.z*ev);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)*Ti,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Ti;e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Ti,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(oS(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/mf),this.camera.far=Math.max(pf*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),e.lat!==void 0&&e.lng!==void 0&&this.placeTerrain(e.lat,e.lng,0,0),this.poseElevationM=e.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+e.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==e.fovDeg&&(this.camera.fov=e.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(e){this.stopTerrainFade(),this.terrainProviders=e,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(e){this.observerRoute=e,this.decorTerrainRadiusM=de.terrainReachFor(this.decorObjects,e)}decorTerrainRadiusM=0;static terrainReachFor(e,t){return ri.decorReachFor(e,t)}placeTerrain(e,t,i,s){const n=(r,a)=>{const o=ut(a.lat,a.lng,e,t);r.position.x=o.x-i,r.position.z=o.z+s};if(this.terrainMesh&&this.terrainMeshOrigin&&n(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&n(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;n(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const s=this.terrainProviders.patches;let n;if(s){if(!s.loaded){if(this.patchesAwaitedFor={lat:e,lng:t,onSettled:i},this.patchesAwaited!==s){this.patchesAwaited=s;const u=this.terrainProviders;this.awaitArrival(s.ready.then(()=>{const p=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===u&&p&&this.setTerrainOrigin(p.lat,p.lng,p.onSettled)}),de.TERRAIN_PATIENCE_MS)}return}const d=s.nearest(e,t);d&&(e=d.lat,t=d.lng,n=d.radiusM)}const r=n??Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:d,z:u}=ut(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(d*d+u*u)<sN*(r/mf))return}const a=this.terrainRadius,o=this.terrainMeshOrigin;o!==void 0&&Math.hypot(ut(e,t,o.lat,o.lng).x,ut(e,t,o.lat,o.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(Hx(e,t,this.terrainProviders,r,{route:this.observerRoute}),de.TERRAIN_PATIENCE_MS).then(({mesh:d,attribution:u,originElevationM:p,water:f,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(p??0),this.anchorGrassTo(d,e,t);const v=this.terrainMesh,g=this.terrainMeshOrigin,b=g?ut(e,t,g.lat,g.lng):void 0;v&&b&&Math.hypot(b.x,b.z)<=a&&(d.position.y=v.position.y+this.groundYOfPatch(v,b.x,b.z)),v&&g&&b&&Math.hypot(b.x,b.z)<=a?this.crossfadeTerrain(d,v,g):this.disposeMesh(this.terrainMesh),d.renderOrder=iN,this.terrainMesh=d,this.terrainMeshOrigin={lat:e,lng:t},this.compileNextFrameOffThread(),this.terrainAttribution=u,this.scene.add(d),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,r),this.buildWater(e,t,r,f,m),this.buildRailways(e,t,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(e,t,r,d,p),this.render(),i?.()}).catch(d=>{console.warn("Terrain build failed, keeping the flat ground fallback:",d),i?.()})}buildFarRing(e,t,i,s,n){s.geometry.computeBoundingBox();const r=s.position.y+(s.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,o=ri.beamReachFor(this.beams,{lat:e,lng:t});if(!ri.needsFarRing(i,a,o)){this.dropFarRing();return}if(this.farRing){const{x:f,z:m}=ut(e,t,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(f,m)<i*de.FAR_RING_KEPT_SHARE)return}const l=this.terrainProviders.patches,h=l?.farRingOf?.(e,t);if(l&&!h){this.dropFarRing();return}const d=h?.radiusM??ri.FAR_RING_RADIUS_M,u=++this.farRingToken,p=this.terrainProviders;this.awaitArrival(Hx(e,t,{elevation:p.elevation,imagery:p.imagery},d,void 0,{innerM:i*de.FAR_RING_OPEN_SHARE,referenceElevationM:n}),de.TERRAIN_PATIENCE_MS).then(({mesh:f})=>{if(u!==this.farRingToken||this.terrainProviders!==p){this.disposeMesh(f);return}this.dropFarRing(),this.farRingToken=u,f.renderOrder=de.FAR_RING_RENDER_ORDER,f.position.y=s.position.y-de.FAR_RING_DROP_M;const m=f.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:f,origin:{lat:e,lng:t}},this.farRingRadiusM=d,this.scene.add(f),f.position.x=s.position.x,f.position.z=s.position.z,this.compileNextFrameOffThread(),this.render()},f=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",f))}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(e,t,i){if(this.grassReference){const r=ut(this.grassReference.lat,this.grassReference.lng,t,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:t,lng:i};const s=ut(this.grassReference.lat,this.grassReference.lng,t,i);e.material.userData?.grassOrigin?.set(s.x,s.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t,i){this.stopTerrainFade();const s=e.material;s.opacity=0,s.polygonOffset=!0,s.polygonOffsetFactor=-1,s.polygonOffsetUnits=-4;const n=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-n)/de.TERRAIN_CROSSFADE_MS);if(s.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}s.polygonOffset=!1,s.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:t,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const e=this.terrainMesh?.material;e&&(e.opacity=1,e.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=ri.ROADS_MAX_RADIUS_M;buildRoads(e,t,i){const s=this.terrainProviders.roads;if(!s||i>de.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const n=this.roadWays;if(n&&n.lat===e&&n.lng===t&&n.radiusM===i){this.drapeRoads(n.ways,e,t,s.contemporary);return}n&&Math.hypot(ut(e,t,n.lat,n.lng).x,ut(e,t,n.lat,n.lng).z)<=n.radiusM&&this.drapeRoads(n.ways,e,t,s.contemporary),this.awaitArrival(s.getRoads(cu(e,t,i)),de.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,s.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(e,t,i,s,n){const r=this.terrainProviders.water;if(!r||i>de.ROADS_MAX_RADIUS_M){this.clearWater();return}if(s){this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:s},this.awaitArrival(this.drapeWater(s,e,t,i),de.ROADS_PATIENCE_MS).catch(o=>console.warn("Water not drawn:",o));return}const a=this.waterSurfaces;if(a&&a.lat===e&&a.lng===t&&a.radiusM===i){this.drapeWater(a.surfaces,e,t,i);return}a&&Math.hypot(ut(e,t,a.lat,a.lng).x,ut(e,t,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,e,t,i),this.awaitArrival((n??r.getWater(cu(e,t,i))).then(o=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:o},this.drapeWater(o,e,t,i)}),de.ROADS_PATIENCE_MS).catch(o=>{console.warn("Water unavailable, drawing none:",o)})}async drapeWater(e,t,i,s){if(e.length===0&&!this.waterSystem)return;const n=await this.loadWaterSystem(),r=this.terrainMesh;r&&(n.group.position.copy(r.position),n.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),s,this.patchSpacingM(r)),yn.reflectOn(n.group),this.waterAttribution=n.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=oe(async()=>{const{WaterSystem:e}=await import("./WaterSystem-HW6EhABp.js");return{WaterSystem:e}},[],import.meta.url).then(({WaterSystem:e})=>{const t=new e;return this.scene.add(t.group),this.waterSystem=t,t})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(e,t,i){const s=this.terrainProviders.railways;if(!s||i>de.ROADS_MAX_RADIUS_M){this.clearRailways();return}const n=this.railwayLines;if(n&&n.lat===e&&n.lng===t&&n.radiusM===i){this.drapeRailways(n.lines,e,t,i);return}n&&Math.hypot(ut(e,t,n.lat,n.lng).x,ut(e,t,n.lat,n.lng).z)<=n.radiusM&&this.drapeRailways(n.lines,e,t,i),this.awaitArrival(s.getRailways(cu(e,t,i)).then(r=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.railwayLines={lat:e,lng:t,radiusM:i,lines:r},this.drapeRailways(r,e,t,i)}),de.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(e,t,i,s){if(!this.railwaySystem&&!e.some(a=>a.level>=0))return;const n=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(n.group.position.copy(r.position),n.setGroundSpacing(this.patchSpacingM(r)),n.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),s),yn.reflectOn(n.group),this.railwayAttribution=n.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=oe(async()=>{const{RailwaySystem:e}=await import("./RailwaySystem-CCk8DP7w.js");return{RailwaySystem:e}},[],import.meta.url).then(({RailwaySystem:e})=>{const t=new e;return this.scene.add(t.group),this.railwaySystem=t,t})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(e){e!==this.statedRoads&&(this.statedRoads=e,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const e=this.terrainMesh;e&&(this.roadSystem.group.position.copy(e.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(e)),this.roadSystem.setStated(this.statedRoads,(t,i)=>this.groundYOfPatch(e,t,i)))}setTraces(e,t=new Map){e===this.traces&&t===this.traceLabels||(this.traces=e,this.traceLabels=t,!(e.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(e){e!==this.tracesShown&&(this.tracesShown=e,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=oe(async()=>{const{TraceSystem:e}=await import("./TraceSystem-C7ya-Gvd.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(Xg);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainMeshOrigin;!e||!t||!i||(e.group.position.copy(t.position),e.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(s,n)=>this.groundYOfPatch(t,s,n)))}buildingFootprints(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(s=>s.kind==="building"&&!s.observerSide&&!s.track).map(s=>{const n=ue.naturalSize(s.kind,s.floors),r=(s.headingDeg??0)*Math.PI/180;return{x:i.x+s.eastM,z:i.z-s.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(s.sizeM?.lengthM??n.lengthM)/2,halfAcrossM:(s.sizeM?.widthM??n.widthM)/2}})}decorOriginInRoads(e,t){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ut(i.lat,i.lng,e,t):{x:0,z:0}}surveyedLamps(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(s=>s.kind==="streetlight"&&!s.lamp?.supposed&&!s.track).map(s=>({x:i.x+s.eastM,z:i.z-s.northM}))}lampNudges=new Map;lampsToKerb(e,t){this.lampNudges.clear();const i=this.decorOriginInRoads(e,t);for(const s of this.decorObjects){if(s.kind!=="streetlight"||!s.lamp?.supposed||s.track)continue;const n=i.x+s.eastM,r=i.z-s.northM,a=this.roadSystem.atKerb(n,r);(a.x!==n||a.z!==r)&&this.lampNudges.set(s.id,{eastM:a.x-n,northM:-(a.z-r)})}}static onlyMoved(e,t){return e.length!==t.length||e.length===0?!1:e.every((i,s)=>{const n=t[s];if(i.id!==n.id||(i.track?.length??-1)!==(n.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(n)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==n[a])return!1;return!0})}layStreetsIfWallsMoved(e){const t=this.roadWays,i=this.terrainProviders.roads;if(!t||!i)return;const s=this.wallsOf(e,t.lat,t.lng),n=this.roadWalls;n?.lat===t.lat&&n.lng===t.lng&&n.walls.length===s.length&&n.walls.every((a,o)=>a.what===s[o].what&&Math.hypot(a.x-s[o].x,a.z-s[o].z)<.1)||this.drapeRoads(t.ways,t.lat,t.lng,i.contemporary)}wallsOf(e,t,i){const s=this.decorOriginInRoads(t,i);return e.filter(n=>n.kind==="building"||n.kind==="streetlight").map(n=>({what:`${n.kind}:${n.lamp?.supposed?"s":""}${n.headingDeg??0}:${n.sizeM?.widthM??""}:${n.sizeM?.lengthM??""}`,x:s.x+n.eastM,z:s.z-n.northM}))}roadWalls;drapeRoads(e,t,i,s){const n=this.terrainMesh;n&&(this.roadSystem.group.position.copy(n.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(n)),this.roadSystem.set(e,t,i,(r,a)=>this.groundYOfPatch(n,r,a),s,this.terrainRadius,new Pi(this.buildingFootprints(t,i),this.surveyedLamps(t,i))),this.roadWalls={lat:t,lng:i,walls:this.wallsOf(this.decorObjects,t,i)},this.lampsToKerb(t,i),this.roadAttribution=e.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(e){this.showCompass!==e&&(this.showCompass=e,this.disposeCompassLabels(),e&&this.buildCompassLabels(),this.render())}setCompassPoints(e){this.compassPoints!==e&&(this.compassPoints=e,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[e,t,i]=this.sunArriving,s=Math.max(t,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(e/s,1,i/s),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?Fs.LENS_K:Fs.K)*t*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(e){this.compassHovered!==e&&(this.compassHovered=e,this.updateCompassVisibility())}setCompassForced(e){this.compassForced!==e&&(this.compassForced=e,this.updateCompassVisibility())}updateCompassVisibility(){const e=this.compassHovered||this.compassForced;if(this.compassSprites.some(t=>t.visible!==e)){for(const t of this.compassSprites)t.visible=e;this.developingExposure&&!this.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(e){if(O6(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!pN(t,e),s=t.precipitationType!==e.precipitationType,n=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||s||n)&&(this.air=Lr.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:yo.steppedOpticalDepth(e.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),s?this.buildPrecipitation():n&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||s||n)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=e.storm&&e.cloudDarkness>=yN,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects===e)return;if(de.onlyMoved(this.decorObjects,e)){this.decorObjects=e,this.decorTerrainRadiusM=de.terrainReachFor(e,this.observerRoute),this.layStreetsIfWallsMoved(e);return}this.decorObjects=e,this.decorTerrainRadiusM=de.terrainReachFor(e,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ue.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const t=e.filter(i=>i.kind==="streetlight").sort((i,s)=>Math.hypot(i.eastM,i.northM)-Math.hypot(s.eastM,s.northM)).slice(0,W6);for(const i of e){const s=ue.build(i,i.lit??!1);this.scene.add(s),this.decorGroups.set(i.id,s),i.kind==="streetlight"&&t.includes(i)&&this.addStreetlightLight(i.id,s,t.indexOf(i)<$6,i.lamp),i.model&&i.id.startsWith(tn.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,s)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=de.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(e),e.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(e){this.decorSunlight=e}setContrails(e){e!==this.contrails&&(this.contrails=e,!(e.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(e){this.contrailSunlight=e}loadContrailSystem(){return this.contrailSystemLoading??=oe(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-B99N4pbI.js");return{ContrailSystem:e}},__vite__mapDeps([4,5]),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,s=de.CONTRAIL_SCATTERING,n=this.skyLight.color,r=[n.r*s*.5,n.g*s*.5,n.b*s*.5];if(t&&i){const a=zn.litFraction(t.sunElevationDeg,t.heightM);if(a>0){const o=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),l=Vt.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=s*l*o[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setBeams(e){e!==this.beams&&(this.beams=e,this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),!(e.length===0&&!this.beamSystem)&&this.loadBeamSystem().then(()=>{this.updateBeams(),this.render()}))}get beamSegmentCount(){return this.beamSystem?.segmentCount??0}loadBeamSystem(){return this.beamSystemLoading??=oe(async()=>{const{BeamSystem:e}=await import("./BeamSystem-CFF1njA3.js");return{BeamSystem:e}},__vite__mapDeps([6,7]),import.meta.url).then(({BeamSystem:e})=>{const t=new e;this.scene.add(t.group),this.beamSystem=t})}updateBeams(){const e=this.decorReferencePose;!this.beamSystem||e?.lat===void 0||e.lng===void 0||this.beamSystem.update(this.beams,this.decorTime,{reference:{lat:e.lat,lng:e.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(t,i,s)=>this.transmittanceTo(t,i,s),groundYAt:(t,i)=>this.groundYUnder(t,i)})}updateContrails(){const e=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:e?Zt(e.altitudeDeg,e.azimuthDeg,1):void 0},t=>this.contrailTint(t))}contrailPixelRad(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/e)}setDecorPresence(e){this.decorPresence=e}entryOfDecorModel(e){return this.decorModelProvider.entry(e).catch(()=>{})}setDecorModelProvider(e){this.decorModelProvider=e;const t=this.decorObjects;this.decorObjects=[],this.setDecor(t)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:e,z:t}=this.bodyOrigin,i=this.groundYUnder(e,t),s=this.bodyEastScale;return{heightAt:(n,r)=>this.groundYUnder(e+n*s,t-r)-i}}get bodyEastScale(){const e=this.decorReferencePose,t=this.decorCurrentPose;return e?.lat===void 0||t?.lat===void 0?1:Math.cos(t.lat*Ti)/Math.cos(e.lat*Ti)}bodyMaskedByDecor(e,t){const i=this.decorGroups.get(t);return i?this.bodySystem.maskedShare(e,i):void 0}setBodies(e,t=0,i=e.map(r=>r.id),s=[],n){const{x:r,z:a}=this.bodyOrigin,o=this.scatteredSky,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(e=e.map(d=>({...d,eastM:d.eastM*l}))),this.bodySystem.set(e,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(d,u)=>this.groundYUnder(d,u),wind:n,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(d,u,p)=>this.transmittanceTo(d,u,p),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},t,o?Object.assign((d,u)=>o.relativeOfLuminance(d,u),{recorded:o.recorded}):void 0,i),this.bodySystem.setSmoke(s,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}plumeLight(){const e=this.celestialLight.color,t=this.celestialLight.intensity*.5,i=this.skyLight.color,s=this.skyLight.groundColor,n=this.skyLight.intensity,r=(a,o,l)=>(a*t+(o+l)/2*n)/Math.PI;return[r(e.r,i.r,s.r),r(e.g,i.g,s.g),r(e.b,i.b,s.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,s=e.credit??t?.credit;if(!(!i||!s))return{scene:await $g(i),credit:s,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg,bindings:t?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(ju(e))||!ue.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const s=$A(i.scene);s.traverse(n=>{n instanceof we&&(n.userData.sharedModel=!0)}),ue.applyModelParameters(s,e.modelParameters,i.bindings),ue.applyModel(t,e,s,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(s),this.decorModelCredits.set(e.id,i.credit)}mirrors=new tr;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(e,t,i=!1){const s=i?lm[e.kind]:ju(e);if(!(!s||!ue.usesModel(e)))try{const n=s.url?void 0:s.id?await this.decorModelProvider.entry(s.id):void 0,r=this.modelUrl(s)??n?.url,a=s.credit??n?.credit;if(!r||!a)return;const o=i||e.kind==="tree"?await this.standInScene(r):await $g(r);if(t!==this.decorModelToken||i&&!this.pendingTrafficModels.has(e.id))return;const l=this.decorGroups.get(e.id);if(!l)return;!i&&e.kind!=="tree"&&(ht.glaze(o),yn.reflectOn(o));const h={ref:JSON.stringify(s),scene:o,headingOffsetDeg:s.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM,credit:a,bindings:n?.parameters?.bindings};i||this.loadedDecorModels.set(e.id,h),this.applyLoadedDecorModel(e,l,h),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${e.id}":`,n)}}standInScene(e){let t=this.standInScenes.get(e);return t||(t=$g(e).then(i=>(/jungle-jim-realistic-trees/.test(e)||yn.reflectOn(i),i)),this.standInScenes.set(e,t)),t}updateDecorAnchoring(e,t,i=0){this.decorReferencePose=e,this.decorCurrentPose=t,this.decorTime=i;const s=e?.lat!==void 0&&e.lng!==void 0&&t?.lat!==void 0&&t?.lng!==void 0?ut(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},n=this.decorObjects.find(f=>f.observerSide!==void 0&&Sl(f.kind));this.terrainMesh&&t?.lat!==void 0&&t.lng!==void 0&&(this.placeTerrain(t.lat,t.lng,n?0:this.gaitOffset.eastM,n?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),n||(s.x-=this.gaitOffset.eastM,s.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let a=0,o;if(n){const f=Mr(n,i),m=ue.occupantView(n,f.headingDeg),v=-(f.headingDeg??0)*Ti,g=m.x*Math.cos(v)+m.z*Math.sin(v),b=-m.x*Math.sin(v)+m.z*Math.cos(v),w=f.eastM+s.x,y=-f.northM+s.z;r.x=-(w+g),r.z=-(y+b),this.camera.position.y=this.groundYUnder(w,y)+m.eyeY,o=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Ti,-(m.headingDeg+this.indoorLookYawDeg)*Ti,0,"YXZ")}this.bodyOrigin={x:s.x+r.x,z:s.z+r.z};const l=this.findCabin(i,s,r);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,s,r);const h=this.terraces.map(f=>[f.x,f.z,f.cos,f.sin,f.halfWidthM,f.halfLengthM,f.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!n&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const f of this.decorObjects){if(f.kind==="terrace")continue;const m=this.decorGroups.get(f.id);if(!m)continue;const v=Mr(f,i),g=this.lampNudges.get(f.id),b=v.eastM+(g?.eastM??0)+s.x+r.x,w=-(v.northM+(g?.northM??0))+s.z+r.z,y=this.terrainMesh,M=`${y?.geometry.uuid}:${(b-(y?.position.x??0)).toFixed(3)}:${(w-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${v.headingDeg}:${v.altitudeM}:${h}`;if(m.userData.footprintKey!==M){if(f.kind==="wire"){const L=ue.wireGround(f,b,w,v.headingDeg,(N,k)=>this.groundYUnder(N,k));m.userData.footprintGroundY=L.startY,ue.shearWire(m,ue.sizeOf(f).lengthM,L.dropM)}else if(f.kind==="crossing"){const L=this.groundYUnder(b,w),N=-(v.headingDeg??0)*Ti,k=Math.cos(N),C=Math.sin(N);m.userData.footprintGroundY=L,kt.drape(ue.bodyOf(m),(P,F)=>this.groundYUnder(b+P*k+F*C,w-P*C+F*k)-L)}else m.userData.footprintGroundY=this.groundUnderFootprint(f,b,w,v.headingDeg,v.altitudeM);m.userData.footprintKey=M}const E=v.altitudeM>de.AIRBORNE_M&&Math.hypot(b,w)<de.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY;if(m.position.set(b,E+v.altitudeM,w),f.kind==="crop"){const L=Math.hypot(b,w);m.visible=L<=rN}const x=this.decorPresence.get(f.id),A=x!==void 0&&(i<x.fromMs||i>x.untilMs);x&&(m.visible=!A);const D=this.decorSunlight.get(f.id);D&&!A&&this.lightFromAbove(m,D),v.headingDeg!==void 0&&(m.rotation.y=-v.headingDeg*Ti);const R=P5(f,i);if(R!==void 0&&de.turnHead(m,v.headingDeg??0,R),f.kind==="crop"&&m.visible){const L=this.terrainMesh,N=[L?.geometry.uuid,b-(L?.position.x??0),w-(L?.position.z??0),m.position.y-(L?.position.y??0),v.headingDeg,v.altitudeM].map(k=>typeof k=="number"?k.toFixed(4):k).join(":");m.userData.cropGroundKey!==N&&(ue.fitCropToGround(m,(k,C)=>this.groundYUnder(k,C)+v.altitudeM),m.userData.cropGroundKey=N)}if(!A){const L=m.position.distanceTo(this.camera.position);a=Math.max(a,L),L<de.trafficModelRangeM(f)&&this.pendingTrafficModels.delete(f.id)&&this.loadDecorModel(f,this.decorModelToken)}}if(n&&o!==void 0){const f=this.decorGroups.get(n.id);f&&(this.camera.position.y=f.position.y+o)}this.updateContrails(),this.updateBeams();const d=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,u=this.beams?.length&&this.terrainMeshOrigin?ri.beamReachFor(this.beams,this.terrainMeshOrigin):0,p=Math.max(pf*1.2,this.groundRadius*2.5,a*1.2,d*1.05,u*1.2);Math.abs(this.camera.far-p)>1&&(this.camera.far=p,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainYUnder(e,t);let s=i;for(const n of this.terraces){const r=e-n.x,a=t-n.z,o=r*n.cos-a*n.sin,l=r*n.sin+a*n.cos;if(Math.abs(o)<=n.halfWidthM&&Math.abs(l)<=n.halfLengthM){const h=Math.min(1,Math.max(0,(n.halfWidthM-Math.abs(o))/n.bankM)),d=h*h*(3-2*h);s=Math.max(s,d*n.levelY+(1-d)*Math.min(n.levelY,i))}}return s}placeTerraces(e,t,i){this.terraces=[];const s=this.terrainMesh;for(const n of this.decorObjects){if(n.kind!=="terrace")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=Mr(n,e),o=a.eastM+t.x+i.x,l=-a.northM+t.z+i.z,h=ue.sizeOf(n),d=-(a.headingDeg??0)*Ti,u=Math.cos(d),p=Math.sin(d),f=`${s?.geometry.uuid}:${(o-(s?.position.x??0)).toFixed(3)}:${(l-(s?.position.z??0)).toFixed(3)}:${(s?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(o,0,l),a.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=ue.fitTerrace(r,n,(m,v)=>this.terrainYUnder(o+m*u+v*p,l-m*p+v*u)),r.userData.terraceKey=f),this.terraces.push({x:o,z:l,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):nv}horizonAltitudeDeg(e){const t=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(t.x)}|${Math.round(t.y*10)}|${Math.round(t.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const s=this.horizonByBearing.length,n=Math.round((e%360+360)%360/(360/s))%s;let r=this.horizonByBearing[n];return Number.isNaN(r)&&(r=this.horizonByBearing[n]=this.marchHorizon(n*360/s)),r}groundHidesDirection(e,t){return e<Math.max(0,this.horizonAltitudeDeg(t))+de.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(e){const t=this.terrainMesh;if(!t)return Number.NEGATIVE_INFINITY;const i=this.camera.position,s=e*Math.PI/180,n=Math.sin(s),r=-Math.cos(s),a=this.farRing?.mesh,o=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(t),1),50);let h=Number.NEGATIVE_INFINITY;for(let d=l;d<=o;d=Math.max(d+l,d*1.02)){const u=i.x+n*d,p=i.z+r*d,f=d<=this.terrainRadius?this.terrainYUnder(u,p):a.position.y+this.groundYOfPatch(a,u-a.position.x,p-a.position.z),m=d*d/(2*de.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(f-m-i.y,d))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(e){const t=e.geometry.getAttribute("position");return t&&t.count>=2?Math.abs(t.getX(1)-t.getX(0)):1/0}groundYOfPatch(e,t,i){const s=e.geometry.getAttribute("position"),n=Math.round(Math.sqrt(s.count));if(n<2||n*n!==s.count)return nv;const r=s.getX(0),a=s.getX(n-1),o=s.getZ(0),l=s.getZ((n-1)*n),h=ya((t-r)/(a-r)*(n-1),0,n-1),d=ya((i-o)/(l-o)*(n-1),0,n-1);if(!Number.isFinite(h)||!Number.isFinite(d))return nv;const u=Math.min(Math.floor(h),n-2),p=Math.min(Math.floor(d),n-2),f=h-u,m=d-p,v=(M,S)=>s.getY(M*n+S),g=v(p,u),b=v(p,u+1),w=v(p+1,u),y=v(p+1,u+1);return f+m<=1?g+(b-g)*f+(w-g)*m:y+(w-y)*(1-f)+(b-y)*(1-m)}groundUnderFootprint(e,t,i,s,n=0){return ue.groundUnderFootprint(e,t,i,s,(r,a)=>this.groundYUnder(r,a),n)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(e){this.gaitOffset=e}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(e,t){this.lookYawDeg=e,this.lookPitchDeg=t}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(e,t){this.indoorLookYawDeg=e,this.indoorLookPitchDeg=t}skyUnknown=!1;setSkyUnknown(e){e!==this.skyUnknown&&(this.skyUnknown=e,this.render())}perception=cr.NONE;setPerception(e){JSON.stringify(e)!==JSON.stringify(this.perception)&&(this.perception=e,this.render())}medium;setMedium(e,t,i,s,n){const r=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:s??e.iso,autoExposure:e.autoExposure===!0&&s===void 0,maxIso:e.maxIso,metering:n??e.metering??"average",exposureSeconds:t,fNumber:i,development:e.development,exposureFollowMs:e.exposureFollowMs}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30),i=e?cr.NONE:this.perception??cr.NONE;if(Ki.uColorVision.value.set(...i.colorMatrix),Ki.uContrast.value=i.contrastGain,!e){Ki.uMedium.value=0;return}const s=e.kind==="sensor"&&e.development==="computational";Ki.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:s?4:3;const n=e.autoExposure?this.frameLight:void 0,r=e.autoExposure||this.skyUnknown?n?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),o=r===void 0?void 0:r+a.mean,l=u=>.065*e.exposureSeconds*u*this.filterTransmittance/(e.fNumber*e.fNumber*t);let h=o!==void 0&&o>0?1/(t*o):void 0;h!==void 0&&e.metering==="highlights"&&a.brightest>0&&(h=Math.min(h,de.HIGHLIGHT_KEPT_AT/(.18*t*a.brightest))),h!==void 0&&e.metering==="highlights"&&n&&n.brightest>0&&(h=Math.min(h,de.ZONE_KEPT_AT/(.18*t*n.brightest)));const d=h!==void 0?Math.min(h,e.maxIso!==void 0?l(e.maxIso):1/0):l(e.iso);Ki.uMediumExposure.value=d,Ki.uPhoneStrength.value=s&&o!==void 0&&o>0?Yr.strengthFor(Yr.MID_GREY*d*t*o):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const e=this.camera;e.updateMatrixWorld();const t=e.fov*Math.PI/180,i=2*Math.atan(Math.tan(t/2)*e.aspect),s=4*Math.asin(Math.sin(i/2)*Math.sin(t/2)),n=new I;let r=0,a=0;for(const{position:o,luminanceCdM2:l,solidAngleSr:h}of this.bodySystem.metered.values())n.copy(o).project(e),n.z<1&&Math.abs(n.x)<=1&&Math.abs(n.y)<=1&&(r+=l*h,a=Math.max(a,l*Math.min(1,h/(de.HIGHLIGHT_SHARE*s))**2));return{mean:r/s,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const e=this.camera.fov*Math.PI/180,t=this.grain.frameHeightMm/(2*Math.tan(e/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/t,e/i)}bloomSize=new se;lampTransmittance(e){const t=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+e.position.y;return this.air.transmittance(t,i,e.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(e,t=0){this.decorLitAt={t:e,stepMs:t};const i=this.lampBloomRadiusRad();for(const s of this.decorObjects){const n=this.decorGroups.get(s.id);if(n&&s.lights?.length&&ue.setLights(n,s.lights,e,n.position.distanceTo(this.camera.position),t,this.relativeScale,i,this.lampTransmittance(n),this.camera.position),s.kind!=="streetlight"&&s.kind!=="vehicle")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=s.kind==="vehicle"?o2(s,e):void 0,o=a!==void 0?xl.lamps(a):u0(s,e,this.lastAstronomy?.sun.altitudeDeg);ue.setLit(r,s.kind,o,this.relativeScale,s.lamp);const l=this.streetlightLights.get(s.id);l&&(l.visible=o),a!==void 0&&(this.headlightSettings.set(s.id,a),this.aimDecorBeam(s,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=oe(async()=>{const{HeadlightSystem:e}=await import("./HeadlightSystem-BYTfcIPd.js");return{HeadlightSystem:e}},[],import.meta.url).then(({HeadlightSystem:e})=>{this.headlightSystem??=new e(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const e=this.headlightSystem;if(e){for(const t of this.decorObjects)t.kind==="vehicle"&&e.add(t.id);this.observerHeadlights&&e.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const e of this.decorObjects){const t=this.headlightSettings.get(e.id),i=this.decorGroups.get(e.id);t!==void 0&&i&&this.aimDecorBeam(e,i,t)}this.aimObserverBeam()}}headlightScatterPerM(){const e=this.siteElevationM+this.camera.position.y,t=200,i=this.air.transmittance(e,e,t)[1];return i>0?-Math.log(Math.min(1,i))/t:.05}aimDecorBeam(e,t,i){if(!this.headlightSystem?.has(e.id))return;t.updateMatrixWorld(!0);const s=new I(0,0,-1).transformDirection(t.matrixWorld);if(s.y=0,s.lengthSq()<1e-9)return;s.normalize();const n=ue.sizeOf(e).lengthM,r=t.getWorldPosition(new I).addScaledVector(s,n/2-X6);r.y+=K6;const a=ue.sizeOf(e).widthM;this.headlightSystem.aim(e.id,i,r,s,a*Y6,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(e){this.observerHeadlights=e,e&&this.loadHeadlights(),this.headlightSystem&&(e?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const e=this.observerHeadlights;if(!e||!this.headlightSystem?.has("observer"))return;const t=e.setting==="auto"?this.lastAstronomy?xl.auto(this.lastAstronomy.sun.altitudeDeg):"off":e.setting,i=e.headingDeg*Math.PI/180,s=new I(Math.sin(i),0,-Math.cos(i)),n=new I(s.x*dS,this.camera.position.y-j6,s.z*dS);this.headlightSystem.aim("observer",t,n,s,q6,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(e,t,i,s){const n=ue.bodyOf(t),r=n.children.find(l=>l.userData.emissive);if(!r)return;const a=hS*ue.lampShare(s),o=new bA(16764006,a*this.relativeScale,Z6);s?.colorTemperatureK&&o.color.setRGB(...ue.lampHue(s)),o.userData.candela=a,o.position.copy(r.position).multiply(n.scale),o.castShadow=i,o.shadow.mapSize.set(512,512),o.shadow.bias=-.002,t.add(o),this.streetlightLights.set(e,o)}applyWindowGlow(){const e=this.lastAstronomy;ue.setLitWindowShare(e?Js.share(e.sun.altitudeDeg,e.localHour):0)}setAstronomy(e){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-e.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=e,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(e)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=e.sun,this.buildSky(e.sun),this.buildGround();const t=this.magnitudeLimitOf(e);this.buildStars(e.stars,t),this.placeBodies(e,t),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.applySkyColours(e),this.syncAnimationLoop(),this.render()}static relativeSkyOf(e,t){const i=r=>{const a=nr.luminanceOf(r);if(!(a>0))return[0,0,0];const o=Be.relativeOfResponse(a)/a;return[r[0]*o,r[1]*o,r[2]*o]},s=i(e.zenith),n=i(e.horizon);return{zenith:s,horizon:n,airlight:n,skyIrradiance:[s[0]*Math.PI,s[1]*Math.PI,s[2]*Math.PI],scale:t}}placeBodies(e,t){this.bodiesScale=this.relativeScale,this.sunBeamFraction=ps.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,lS,new ae(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<Xf){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=lS/Rn*(180/Math.PI),s=i/t.sunRadiusDeg,n=Zt(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=Zt(e.moon.altitudeDeg,e.moon.azimuthDeg,1),a=Math.acos(ya(n.x*r.x+n.y*r.y+n.z*r.z,-1,1)),o=a>1e-9?ya(t.separationDeg*s*Ti/a,0,2):0,l=Math.sin(a),[h,d]=a>1e-9?[Math.sin((1-o)*a)/l,Math.sin(o*a)/l]:[1,0],u={x:n.x*h+r.x*d,y:n.y*h+r.y*d,z:n.z*h+r.z*d},p=t.moonRadiusDeg*s;this.eclipseDiscs={sun:new I(n.x,n.y,n.z).normalize(),moon:new I(u.x,u.y,u.z).normalize(),sunRadiusRad:i*Ti,moonRadiusRad:p*Ti};const f=.01,m=(b,w)=>Zt(e.sun.altitudeDeg+b,e.sun.azimuthDeg+w,1),v={x:m(f,0).x-m(-f,0).x,y:m(f,0).y-m(-f,0).y,z:m(f,0).z-m(-f,0).z},g={x:m(0,f).x-m(0,-f).x,y:m(0,f).y-m(0,-f).y,z:m(0,f).z-m(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:s,up:v,right:g}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Sh(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(n,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(e){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(e,this.magnitudeLimitOf(e)),this.applyDazzleStrength(),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.updateBeams());const t=this.scatteredSky?.ambient??de.relativeSkyOf(Zb(e.sun.altitudeDeg),this.relativeScale),i=t,s=this.lightUnderClouds(e),n=r=>s?[0,1,2].map(a=>r[a]*s.through+s.radiance[a]*(1-s.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=n(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),ze.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??hS)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(e,i.zenith),this.applyAir(),this.buildLunarDiffraction(e.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(e){const t=this.scatteredSky?.ready?this.scatteredSky:void 0;if(e.altitudeDeg<-.5||!t){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,s=(i===void 0?Ze.DEFAULT_AEROSOL_OPTICAL_DEPTH:yo.opticalDepth(i))*Ze.aerosolDensity(this.siteElevationM+this.observerElevationM),n=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),a=Vt.aureoleScale(s,Vt.airMass(e.altitudeDeg))*n,o=Vt.coronaScale(r),l=Vt.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),a.toExponential(2),o.toExponential(2),Math.log10(Math.max(t.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new a1,this.celestialGroup.add(this.lunarDiffraction.object));const d=Vt.profile(Vt.HAZE_COARSE_MODE),u=Vt.profile(Vt.CLOUD_DROPLETS),p=CP(e.altitudeDeg),f=new Float32Array(Vt.STEPS*3);let m=0;for(let w=0;w<Vt.STEPS;w++){const y=w*3,M=[0,1,2].map(E=>l*p[E]*(a*d[y+E]+o*u[y+E])),S=nr.shown(M,nr.luminanceOf(M),(E,x)=>t.relativeOfLuminance(E,x));f.set(S,y),m=Math.max(m,nr.response(S))}const{x:v,y:g,z:b}=Zt(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:v,y:g,z:b}:void 0,f)}applyAir(){this.scene.fog instanceof pc||(this.scene.fog=new pc),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(e,t,i){const s=this.camera.position;return this.air.transmittance(this.siteElevationM+s.y,this.siteElevationM+t,Math.hypot(e-s.x,t-s.y,i-s.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,s]=this.air.transmittance(e,e,de.UMBRA_PATH_M),n=.2126*t+.7152*i+.0722*s;return n>0?[(.4124*t+.3576*i+.1805*s)/n,1,(.0193*t+.1192*i+.9505*s)/n]:[.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:ps.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?ps.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction)},flare:this.skyFlare}}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?eN:Q6),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 e6(qg),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Ta(-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,s)=>this.arrivingIlluminance(i,s,1)),this.render()}setReentries(e){if(e.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new un,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Ta(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,s=>this.cloudTransmission(s),(s,n)=>this.arrivingIlluminance(s,n,1)),this.emitterLights.set("reentries",[],e.map(s=>this.farEmitterOf(s.head,s.magnitude)).filter(s=>s!==void 0)),this.refreshSkyFlare();const i=new Set;for(const s of e){const n=`reentry:${s.reentryId}:${s.fragmentId}`,{x:r,y:a,z:o}=Zt(s.head.altitudeDeg,s.head.azimuthDeg,Rn);this.setGlare(n,r,a,o,this.arrivingIlluminance(s.head,s.magnitude,this.cloudTransmission(s.head)),0,de.POINT_VEIL_HOLD_DEG),i.add(n)}for(const s of[...this.glareSprites.keys()])s.startsWith("reentry:")&&!i.has(s)&&this.disposeGlare(s);this.render()}setLaunchPlumes(e){e.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new Ri,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(e,this.relativeScale,t=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),t=>this.cloudTransmission(t)),this.render())}pickPlumeAt(e,t){if(!this.plumeSystem?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,s=this.plumeSystem.pickAt(i,de.BEAM_PICK_PIXELS*this.contrailPixelRad(),this.skyLightTowards(i));return s&&this.groundHides(e,t)?void 0:s}get plumePuffCount(){return this.plumeSystem?.count??0}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,s=Math.cos(gf*this.camera.fov*Math.PI/180);let n,r=s;const a=new I;for(const[o,l]of this.decorGroups){if(!l.visible||!o.startsWith(tn.ID_PREFIX))continue;a.copy(l.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,n=o)}return n&&!this.groundHides(e,t)?n:void 0}pickReentryAt(e,t){if(!this.reentrySystem?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(gf*this.camera.fov*Math.PI/180),s=this.reentrySystem.nearest(this.raycaster.ray.direction,i);return s&&this.groundHides(e,t)?void 0:s}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(gf*this.camera.fov*Math.PI/180),s=this.satelliteField.nearest(this.raycaster.ray.direction,i);return s&&this.groundHides(e,t)?void 0:s}updateCelestialLight(e,t){const i=this.relativeScale,s=e.sun.altitudeDeg>=Hd,n=!s&&e.moon.altitudeDeg>=Hd,r=s?e.sun:e.moon,a=[0,0,0],o=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Ti)),l=this.siteElevationM+this.observerElevationM;let h=r,d=s||n?rS.directFraction(r.altitudeDeg,l):0;s&&d<=0&&e.moon.altitudeDeg>=Hd&&(h=e.moon,d=rS.directFraction(h.altitudeDeg,l));const u=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Ti)),p=s||n?this.cloudTransmission(r):1,f=-Math.log(Math.max(p,1e-6)),m=Math.max(0,1/(1+.1125*f)-p),v=[0,0,0];if(s||n){const S=Vt.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let R=0;R<3;R++)v[R]=S*E[R]*m*o,this.cloudBeam[R]=S*E[R];const{x,y:A,z:D}=Zt(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(x,A,D),d>0){const R=Vt.illuminanceOf(h.magnitude)*i,L=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),N=h===r?p:this.cloudTransmission(h);for(let k=0;k<3;k++)a[k]=R*L[k]*N*d}}else this.cloudBeam.fill(0);const g=this.surroundings;if(g)this.skyLight.color.setRGB(g.up[0]*i,g.up[1]*i,g.up[2]*i),this.skyLight.groundColor.setRGB(g.down[0]*i,g.down[1]*i,g.down[2]*i);else{const S=this.skyCloudTransmission(),E=t.skyIrradiance,x=[0,1,2].map(D=>E[D]*S+v[D]);this.skyLight.color.setRGB(x[0],x[1],x[2]);const A=rt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(x[0]+a[0]*u),A*(x[1]+a[1]*u),A*(x[2]+a[2]*u))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===e.sun?[a[0],a[1],a[2]]:[0,0,0],!s&&!n||d<=0){this.celestialLight.intensity=0;return}const{x:b,y:w,z:y}=Zt(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(b,w,y),this.celestialLight.shadow.normalBias=Zg*ya(w/U6,.1,1),this.placeShadowFrustum();const M=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/M,a[1]/M,a[2]/M),this.celestialLight.intensity=M,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(e,t){const i=this.lastAstronomy?.sun,s=[0,0,0];if(i){const n=zn.litFraction(t.sunElevationDeg,t.heightM);if(n>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),a=Vt.illuminanceOf(i.magnitude)*this.relativeScale,o=t.heightM>=de.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)s[l]=Math.max(0,a*r[l]*n*o-this.sceneSunBeam[l])}}e.traverse(n=>{const r=n.material;if(!(r instanceof Br||r instanceof el)||n.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=de.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*s[0]*a,r.color.g*s[1]*a,r.color.b*s[2]*a)})}lightDirection=new I(0,1,0);placeShadowFrustum(){const e=this.lightDirection,t=this.celestialLight.shadow.camera,i=(t.right-t.left)/this.celestialLight.shadow.mapSize.x,s=this.shadowAxisX.crossVectors(this.shadowUp,e);s.lengthSq()<1e-8&&s.set(1,0,0),s.normalize();const n=this.shadowAxisY.crossVectors(e,s).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*i},o=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(s,a(s)).addScaledVector(n,a(n));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(o).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToCabin(e){if(e===this.cabinShadow)return;this.cabinShadow=e;const t=this.celestialLight.shadow;if(!e){this.shadowHalfExtentM=-1;return}const i=t.camera,s=F6;i.left=-s,i.right=s,i.top=s,i.bottom=-s,this.shadowHalfExtentM=s,this.shadowLightDistanceM=vf+5,i.near=this.shadowLightDistanceM-vf,i.far=this.shadowLightDistanceM+vf,i.updateProjectionMatrix(),t.bias=-.004/(2*vf),t.mapSize.x!==2048&&(t.mapSize.set(2048,2048),t.map?.dispose(),t.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(e){for(const t of e)t.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[]){const r=n;r.isMeshStandardMaterial&&r.envMapIntensity!==de.CABIN_SKY_SHARE&&(r.envMapIntensity=de.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(N6,Math.max(Qa,Math.ceil(e*1.25/20)*20));if(t===this.shadowHalfExtentM)return;this.shadowHalfExtentM=t;const i=this.celestialLight.shadow,s=i.camera;s.left=-t,s.right=t,s.top=t,s.bottom=-t;const n=Math.max(ih,t*(ih/Qa));this.shadowLightDistanceM=Math.max(Rn,n+10),s.near=this.shadowLightDistanceM-n,s.far=this.shadowLightDistanceM+n,s.updateProjectionMatrix(),i.bias=-jg/(2*n);const r=t>2*Qa?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=Qa;shadowLightDistanceM=Rn;shadowUp=new I(0,1,0);shadowAxisX=new I;shadowAxisY=new I;shadowWorld=new I;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const s=i*Ti,n=Math.sin(s)*Math.cos(s)*2;for(let r=0;r<360;r+=60)e+=n*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),t+=n}return e/t}cloudBeam=[0,0,0];cloudBeamDirection=new I(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Be.semiSaturation(Be.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new Vs,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&&(this.meteorSystem.update(e),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(t=>this.farEmitterOf(t,t.magnitude)).filter(t=>t!==void 0)),this.refreshSkyFlare())}farEmitterOf(e,t){if(!(e.altitudeDeg>0)||!Number.isFinite(t))return;const i=Math.max(this.relativeScale,1e-30),s=this.arrivingIlluminance(e,t,this.cloudTransmission(e)),{x:n,y:r,z:a}=Zt(e.altitudeDeg,e.azimuthDeg,1);return{direction:new I(n,r,a),lux:[s[0]/i,s[1]/i,s[2]/i],sky:{altitudeDeg:e.altitudeDeg,azimuthDeg:e.azimuthDeg,magnitude:t}}}skyFlare;refreshSkyFlare(){const e=this.emitterLights.brightestInSky;e===this.skyFlare||!e&&!this.skyFlare||(this.skyFlare=e,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(e,t){this.projectionKind=e.projection,this.grain=e.detailUm!==void 0&&e.frame?{detailUm:e.detailUm,frameHeightMm:e.frame.heightMm}:void 0;const i=Qt.starPointsOf(e,t);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(e){const t=pe.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return Ta(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 s=Number.isFinite(e)?e:0;this.instrumentMagnitudeGain=s-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(t,s,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const e=this.compileOffThread().then(()=>{this.compiling===e&&(this.compiling=void 0,this.render())});this.compiling=e;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{const e=this.usableGhostPass();e?(this.exposureSubjectBounds=[],this.renderOnce(e.frame),e.develop(this.renderer,e.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const e=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const t=this.renderer.properties,i=performance.now()+de.COMPILE_WAIT_MS;return new Promise(s=>{const n=()=>{if(this.contextReleased)return s();for(const r of e){const a=t.get(r)?.currentProgram;(!a||a.isReady())&&e.delete(r)}e.size===0||performance.now()>i?s():setTimeout(n,10)};n()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(e){if(this.animationsRunning){const t=this.lastFrameTimeMs===void 0?0:e-this.lastFrameTimeMs;this.lastFrameTimeMs=e,this.hasAnimations()&&this.animate(e,t);const i=this.resolution.ratioFor(e,t);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(e,t,i){const s=[];for(const n of this.decorObjects){if(n.kind!=="aircraft"&&n.kind!=="vehicle"||n.observerSide!==void 0&&Sl(n.kind))continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=Mr(n,e),o=a.eastM+t.x+i.x,l=-a.northM+t.z+i.z,h=ue.sizeOf(n),d=Math.max(h.widthM,h.lengthM)/2;Math.hypot(o,l)<d&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<d&&s.push(r)}return this.cabinGroups=s,s}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(e=!1){this.reflections??=new yn(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 sr),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(o=>o!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(o=>o.name.startsWith("body:")),...[this.meteorSystem?.object,this.reentrySystem?.object].filter(o=>o!==void 0)],s=this.relativeScale,n=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],n,i,o=>this.measureSurroundings(o,s,n,r),e?0:yn.REFRESH_MS);a===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},a))}static adaptingLuminance(e,t){const i=(.2126*t[0]+.7152*t[1]+.0722*t[2])/Math.PI;return Math.max(e,de.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(e,t,i,s){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new wh,this.framePhotograph={texture:e,scale:t,atMs:s};const r=[n.sun,n.moon].filter(a=>a.altitudeDeg>-2).map(a=>Zt(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,r,a=>{const o=f=>f.map(m=>m/t),l=this.surroundings,h={up:o(a.up),down:o(a.down)},d=(f,m)=>f.some((v,g)=>Math.abs(v-m[g])>.03*Math.max(Math.abs(v),Math.abs(m[g]),1e-12)),u=!l||d(l.up,h.up)||d(l.down,h.down);u&&(this.surroundings=h),this.eyeSettledVersion=-1;const p=this.scatteredSky?.adaptToSurroundings(de.adaptingLuminance(Math.exp(a.logAverage)/t,h.down))??!1;if(!u&&!p){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>=Hd?e.sun:e.moon.altitudeDeg>=Hd?e.moon:void 0;if(!i)return;const s=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[t.up[0]*s,t.up[1]*s,t.up[2]*s]}}probeIrradiance;meterFrame(){const e=this.framePhotograph;if(!this.medium?.autoExposure||!e)return;this.frameMeter??=new Kr;const t=this.lastAstronomy?.sun,i=t&&t.altitudeDeg>-2?Zt(t.altitudeDeg,t.azimuthDeg,1):void 0,s=this.medium.exposureFollowMs??de.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,e.texture,this.camera,i,n=>{const r={mean:n.mean/e.scale,brightest:n.brightest/e.scale},a=this.frameLight,o=e.atMs,l=a?o-a.atMs:1/0,h=l<0||l>de.EXPOSURE_JUMP_MS,d=h||l===0&&a?.jumped?1:1-Math.exp(-l/s),u=(m,v)=>m>0&&v>0?m*(v/m)**d:v,p={mean:u(a?.mean??0,r.mean),brightest:u(a?.brightest??0,r.brightest),atMs:o,jumped:h||l===0&&(a?.jumped??!1)};this.frameLight=p;const f=(m,v)=>Math.abs(m-v)>.01*Math.max(m,v);(!a||f(a.mean,p.mean)||f(a.brightest,p.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Ki.uRetinaOn.value=0,this.medium)return;const e=[];for(const a of this.emitterLights.farEmitters){const o=this.screenPointOf(a.direction);!o||Math.abs(o.ndcX)>1.2||Math.abs(o.ndcY)>1.2||e.push({ndcX:o.ndcX,ndcY:o.ndcY,lux:nr.luminanceOf(a.lux)})}const t=this.renderer.getDrawingBufferSize(this.retinaSize),i=t.x/Math.max(t.y,1),s={width:this.camera.fov*i,height:this.camera.fov},n=this.retina?.atMs;if((n===void 0||this.recordingTimeMs<n||this.recordingTimeMs-n>mt.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new mt,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),s,this.retinaHistoryOf);else{if(!this.retina&&e.length===0)return;this.retina??=new mt,this.retina.advance(this.recordingTimeMs,e,s)}this.retina.any&&(Ki.uRetina.value=this.retina.texture,Ki.uRetinaOn.value=1,Ki.uRetinaViewport.value.copy(t))}retinaSize=new se;retinaHistory;setRetinaHistory(e,t){this.retinaHistory=e,this.retinaHistoryOf=t}retinaHistoryOf;historicBleachingAt(e,t){const i=this.retinaHistory?.(e);if(!i||i.views.length===0)return[];const s=i.pose,n=this.historicQuaternion.setFromEuler(this.historicEuler.set((s?.pitchDeg??0)*Ti,-(s?.headingDeg??0)*Ti,(s?.rollDeg??0)*Ti,"YXZ")).invert(),r=s?.fovDeg??this.camera.fov,a=[];for(const o of i.views){const l=this.farEmitterOf(o.head,o.magnitude);if(!l)continue;const h=this.screenPointIn(this.historicDirection.copy(l.direction).applyQuaternion(n),r,t);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||a.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:nr.luminanceOf(l.lux)})}return a}historicQuaternion=new Tn;historicEuler=new Va;historicDirection=new I;pickAfterimageAt(e,t){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(e,t)<de.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(e){this.recordingTimeMs=e}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(e){const t=[];for(const i of e)i.traverse(s=>{s.userData.emissive===!0&&t.push(s)});return t}surroundings;animate(e,t){const i=Math.min(t/1e3,bN);this.twinkleSeconds=e/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(e/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=e/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(e){this.resolution.maximum=e,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(e){this.renderer.setPixelRatio(e),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(e,t){const i=t?Math.max(1,Math.round(e)):1;if(i===this.exposureInstants&&(i===1||t===this.exposureInstantAt)){this.exposureInstantAt=t;return}this.exposureInstants=i,this.exposureInstantAt=t,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(e){if(this.aimBeams(),ue.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();e?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const t=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,o)=>this.directionAtScreenPoint(r,a,o),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[iy]:[],!e)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},tr.INTERVAL_MS)),Ki.uRodShare.value=this.scatteredSky?.rodShare??0,Ki.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const s=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Ki.uHasOverlay.value=s?1:0;const n=s?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,n,e):this.usableFinishPass().render(this.renderer,this.scene,this.camera,n,void 0,e);return}t.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),n,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 sr&&t.userData.pointSource||t instanceof we&&t.userData.skyRibbon)&&e.push(t)}),[...e,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(e=this.camera){this.renderReferencesPass(e),this.renderBodiesOverReferences(e),this.renderPhenomenaPass(e),this.renderHudPass(e)}renderHudPass(e){const t=this.traceSystem?.any&&this.tracesShown;if(!t&&!this.compassSprites.some(n=>n.visible))return;t&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),e.fov);const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(Xg),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}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(XA),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 $n({blending:wc,blendSrc:Na,blendDst:Na,blendSrcAlpha:Na,blendDstAlpha:Na,toneMapped:!1});renderReferencesPass(e){if(!this.references?.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(this.references.layer),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){const i=e.map(s=>{const n=this.documentRelative(s.src);return n===s.src?s:{...s,src:n}});if(this.references){this.references.set(i,void 0,t);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:t},this.referencesLoading??=oe(async()=>{const{ReferenceSystem:s}=await import("./ReferenceSystem-BDjiP56B.js");return{ReferenceSystem:s}},__vite__mapDeps([8,9]),import.meta.url).then(({ReferenceSystem:s})=>{const n=new s(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=n;for(const[a,o]of this.referenceViews)n.setView(a,o);n.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&n.set(r.references,void 0,r.observerAt),this.render(),n})}referenceAspect(e){return this.references?.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new I)}referenceFailure(e){return this.references?.failureOf(this.documentRelative(e))}setReferencesShown(e){this.referencesShown=e,this.references?.setShown(e),this.render()}setReferenceView(e,t){this.referenceViews.set(e,t),this.references?.setView(e,t),this.render()}renderPhenomenaPass(e){if(!this.phenomena.any)return;e.updateMatrixWorld();const t=this.phenomena.screenBox(e);if(t&&(t.x0>1||t.x1<-1||t.y0>1||t.y1<-1))return;const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const n=t?this.narrowTo(e,t):e,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse)),a=this.phenomena.furthestM;let o=0;for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const d=l.kind!=="crop"&&this.mayHide(h,e,r,a);de.markDecorDepth(h,d),d&&o++}o>0&&(e.layers.set(Kg),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null),e.layers.set(iy),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}phenomenaFrustum=new g0;phenomenaViewProjection=new ft;occluderSphere=new aa;localBounds=new WeakMap;mayHide(e,t,i,s){let n=0;e.traverse(()=>n++);let r=this.localBounds.get(e);if(!r||r.objects!==n){e.updateMatrixWorld(!0);const o=new Ss().setFromObject(e);if(o.isEmpty())return!1;r={sphere:o.getBoundingSphere(new aa).applyMatrix4(new ft().copy(e.matrixWorld).invert()),objects:n},this.localBounds.set(e,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(e.matrixWorld);return a.center.distanceTo(t.position)-a.radius>s?!1:i.intersectsSphere(a)}narrowTo(e,t){const i=this.renderer.getDrawingBufferSize(new se),s=de.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),n=Math.max(0,Math.floor((Math.max(-1,t.x0)+1)/2*i.x-s)),r=Math.max(0,Math.floor((Math.max(-1,t.y0)+1)/2*i.y-s)),a=Math.min(i.x,Math.ceil((Math.min(1,t.x1)+1)/2*i.x+s)),o=Math.min(i.y,Math.ceil((Math.min(1,t.y1)+1)/2*i.y+s)),l=this.narrowCamera.copy(e);return l.setViewOffset(i.x,i.y,n,i.y-o,Math.max(1,a-n),Math.max(1,o-r)),l.updateMatrixWorld(),l}narrowCamera=new nn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new $n({colorWrite:!1,side:qs});static HEAD_TURN_LIMIT_DEG=85;static turnHead(e,t,i){const s=e.getObjectByName("head");if(!s)return;const n=((i-t)%360+540)%360-180,r=Math.max(-85,Math.min(de.HEAD_TURN_LIMIT_DEG,n));s.rotation.y=-r*Ti}static isSolidSurface(e){if(!(e instanceof we))return!0;const t=Array.isArray(e.material)?e.material[0]:e.material;return t.depthWrite!==!1&&t.blending!==zs}static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof we))return;t&&de.isSolidSurface(i)?i.layers.enable(Kg):i.layers.disable(Kg)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new se),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new yP(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 s=performance.now()+de.EXPOSURE_BUDGET_MS,n=de.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const a=this.compassSprites.map(o=>o.visible);for(const o of this.compassSprites)o.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((o,l)=>{o.visible=a[l]})}t.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<s&&r<n);this.restateAt(e,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Ki.uRodShare.value=this.scatteredSky?.rodShare??0,Ki.uHasOverlay.value=1,Ki.uRelativeScale.value=this.relativeScale,this.applyMedium();const e=this.exposureInstants/this.exposureInstantsDone,t=this.usableGhostPass();if(t&&this.exposureAccumulation?t.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,e,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,e),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Er,s=new Ar(-1,1,1,-1,0,2),n=yf/(pS*Math.tan(fS*Ti/2));for(const a of this.compassSprites){if(!a.visible)continue;const o=a.getWorldPosition(new I).sub(this.camera.position).normalize(),l=this.screenPointOf(o);if(!l)continue;const h=new Rd(a.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(n/this.camera.aspect,n,1),i.add(h)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,s)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const e=[],t=new Ss,i=new I,s=this.camera.getWorldDirection(new I),n=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...n,...r]){if(!a?.visible||(t.setFromObject(a),t.isEmpty())||t.distanceToPoint(this.camera.position)<de.MAP_SUBJECT_NEAREST_M)continue;let o=1/0,l=-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(s)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const v=(m.ndcX+1)/2,g=(1-m.ndcY)/2;o=Math.min(o,v),l=Math.max(l,v),h=Math.min(h,g),d=Math.max(d,g)}o=Math.max(o,0),l=Math.min(l,1),h=Math.max(h,0),d=Math.min(d,1),l>=o&&d>=h&&e.push({x:o,y:h,width:l-o,height:d-h})}return e}restateAt(e,t){this.restatingExposure=!0;try{e(t)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(e){const t=this.lensOptics;this.lensOptics=e,(t===void 0!=(e===void 0)||t&&e&&(t.focalLengthMm!==e.focalLengthMm||t.fNumber!==e.fNumber||t.focusDistance!==e.focusDistance||t.frameHeightMm!==e.frameHeightMm))&&(e&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.render())}usableDepthOfFieldPass(){const e=this.lensOptics;if(!e)return;const t=this.renderer.getDrawingBufferSize(new se),i=Math.max(1,Math.round(t.x)),s=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new du(i,s)),this.depthOfFieldPass.resize(i,s),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}setLensGhosts(e){JSON.stringify(e)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=e,e.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(e,t){return this.ghostPass?.holdsPictureAt(this.renderer,e,t)??!1}pickGhostAt(e,t){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,e,t,this.ghostOptics,Ki.uMediumExposure.value)}pickDropAt(e,t){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,e,t)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const e=this.renderer.getDrawingBufferSize(new se);return this.ghostPass?this.ghostPass.resize(e.x,e.y):this.ghostPass=new ws(e.x,e.y),this.ghostPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new se);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new r1(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new se);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new $i(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){this.aimStraightAtScreenPoint(e,t,i),e===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(e,s=>{const n=de.firstSolid(e.intersectObjects(this.cabinGroups,!0));return!n||n.distance>=s-.001||this.mirrors.isMirror(n.object)})}aimStraightAtScreenPoint(e,t,i){const s=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!s){e.setFromCamera(new se(t,i),this.camera);return}const n=s.directionFor(t,i,this.camera.fov);this.camera.updateMatrixWorld(),e.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),e.ray.direction.set(n.x,n.y,n.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 I)}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),s=i.x/Math.max(i.y,1);return this.screenPointIn(t,this.camera.fov,s)}screenPointIn(e,t,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return $i.ndcFor(e,t,i);if(e.z>=0)return;const s=Math.tan(t/2*Ti);return{ndcX:e.x/-e.z/(i*s),ndcY:e.y/-e.z/s}}screenPointScratch=new I;screenPointQuaternion=new Tn;screenPointSize=new se;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 s=this.renderer.domElement.width,n=this.renderer.domElement.height;e.uniforms.uResolution.value.set(s,n),e.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const e=this.lensFlare;if(!e||!e.mesh.visible)return;const t=this.sunDiscRadiance.map(r=>Math.max(0,r-de.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(t[1]<=0)return;const i=Math.tan(e.uniforms.uSourceRadiusDeg.value*Math.PI/180)/e.uniforms.uTanHalfFov.value/2,s=Math.PI*i*i,n=e.uniforms.uLensPosition.value;return{x:n.x,y:n.y,radius:i,flux:[t[0]*s,t[1]*s,t[2]*s]}}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 s=this.renderer.getDrawingBufferSize(this.screenPointSize);e.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),e.uniforms.uResolution.value.set(s.x,s.y),e.uniforms.uEquidistant.value=1,e.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const n=this.renderer.autoClear;this.renderer.autoClear=!1,e.mesh.visible=!0,e.mesh.layers.enable(aS),this.camera.layers.set(aS),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),e.mesh.visible=!1,e.uniforms.uEquidistant.value=0,this.renderer.autoClear=n}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let e=0;for(const t of gS)this.isSunOccluded(t[0],t[1])||e++;return e/gS.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){return this.isOccludedToward(this.sunWorldPosition,e,t)}isOccludedToward(e,t=0,i=0){const s=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&s.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(e).sub(this.camera.position),r=n.length();if(n.normalize(),t!==0||i!==0){const l=Math.PI/180,h=this.sunOcclusionRightScratch.set(n.z,0,-n.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const d=this.sunOcclusionUpScratch.crossVectors(h,n).normalize();n.addScaledVector(h,t*l).addScaledVector(d,i*l).normalize()}if(this.groundBlocks(this.camera.position,n,r)||this.cabinMask.hides(n))return!0;const a=this.cabinMask.any?s.filter(l=>!this.cabinGroups.includes(l)):s;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const o=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(l=>!(l.object.material instanceof xo));return o!==void 0&&o.distance<r}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let e=!1;for(const t of this.glareSprites.values()){if(!t.mesh.visible)continue;e||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),e=!0);const i=t.mesh.getWorldPosition(this.veilTargetScratch),s=t.mesh.material.uniforms.uSourceDeg.value,n=s>.05?de.VEIL_SAMPLES:de.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,o]of n)this.isOccludedToward(i,a*s,o*s)||r++;t.share=r/n.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new Zn;veilTargetScratch=new I;groundBlocks(e,t,i,s=0){const n=this.groundMesh;if(n&&t.y<0){const v=(n.position.y-e.y)/t.y;if(v>s&&v<i){const g=e.x+t.x*v-n.position.x,b=e.z+t.z*v-n.position.z;if(Math.hypot(g,b)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),o=Math.round(Math.sqrt(a.count));if(o<2||o*o!==a.count)return!1;const l=[r.position.x+a.getX(0),r.position.x+a.getX(o-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((o-1)*o)],d=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(o-1);if(!(d>0))return!1;let u=s,p=i;for(const[v,g,b]of[[e.x,t.x,l],[e.z,t.z,h]]){const w=Math.min(b[0],b[1]),y=Math.max(b[0],b[1]);if(Math.abs(g)<1e-12){if(v<w||v>y)return!1;continue}const M=(w-v)/g,S=(y-v)/g;u=Math.max(u,Math.min(M,S)),p=Math.min(p,Math.max(M,S))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),m=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let v=0;v<=m;v++){const g=u+(p-u)*v/m,b=e.x+t.x*g,w=e.y+t.y*g,y=e.z+t.z*g;if(w<=this.groundYUnder(b,y))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=ff;let s,n;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const o=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(l=>de.isSolidSurface(l.object));o&&(r.occludesSourceIds?.includes(i)?s=s===void 0?o.distance:Math.max(s,o.distance):n=n===void 0?o.distance:Math.min(n,o.distance))}return{behindM:s,inFrontM:n}}pickBodyAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.origin,s=this.raycaster.ray.direction,n=z6*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,d])=>{const u=d.getWorldPosition(new I).sub(i);return{key:h,direction:u.clone().normalize(),radiusRad:Math.atan2(d.scale.x/2,u.length())}}),a=this.eclipseDiscs,o=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],l=de.nearestBody(s,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...o],n);if(l)return this.groundHides(e,t)?void 0:l}pickOpticsAt(e,t){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(e,t)?i:void 0}static nearestBody(e,t,i){let s,n=1/0,r=1/0,a=!1;for(const o of t){const l=Math.acos(ya(o.direction.dot(e),-1,1))-o.radiusRad;if(l>i)continue;const h=l<=0,d=n<=0,u=o.inFront===!0;(h!==d?h:h?u!==a?u:o.radiusRad<r:l<n)&&(s=o.key,n=l,r=o.radiusRad,a=u)}return s}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 s=this.raycaster.ray.direction,n=this.raycaster.ray.origin,r=P6*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],o=a.length>0?de.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const d=new Ss,u=new I;for(const p of i){if(d.setFromObject(p),d.isEmpty())continue;d.getCenter(u);const f=d.getSize(new I).length()/2,m=u.clone().sub(n),v=m.length();if(v===0||m.dot(s)<=0||o!==void 0&&o<v-f)continue;const g=Math.acos(Math.min(1,m.normalize().dot(s))),b=Math.atan(f/v);if(b>r){const w=this.raycaster.intersectObject(p,!0)[0];if(!w||o!==void 0&&o<w.distance)continue}else if(g>r)continue;b<h&&(h=b,l=p.name.slice(5))}return l}pickStarAt(e,t){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,s=Math.cos(gf*this.camera.fov*Math.PI/180);let n,r=s;for(const a of this.namedStars){const o=a.direction.dot(i);o>r&&(r=o,n={star:a.star,altitudeDeg:a.altitudeDeg})}return n&&this.groundHides(e,t)?void 0:n}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,ff)}bodyScreenBox(e){const t=this.bodySystem.boxOf(e,this.bodyBoxScratch);if(!t)return;let i=1/0,s=1/0,n=-1/0,r=-1/0;for(let a=0;a<8;a++){const o=this.bodyCornerScratch.set(a&1?t.max.x:t.min.x,a&2?t.max.y:t.min.y,a&4?t.max.z:t.min.z),l=this.screenPointOf(o.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),n=Math.max(n,l.ndcX),s=Math.min(s,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:i,minY:s,maxX:n,maxY:r}}bodyBoxScratch=new Ss;bodyCornerScratch=new I;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 s=1/0,n=1/0,r=-1/0,a=-1/0;for(let o=0;o<8;o++){const l=this.bodyCornerScratch.set(o&1?i.max.x:i.min.x,o&2?i.max.y:i.min.y,o&4?i.max.z:i.min.z),h=this.screenPointOf(l.sub(this.camera.position).normalize());if(!h)return;s=Math.min(s,h.ndcX),r=Math.max(r,h.ndcX),n=Math.min(n,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:s,minY:n,maxX:r,maxY:a}}decorDrawnOffset(e){return this.lampNudges.get(e)}decorGroundPointAt(e,t,i,s=0){const n=this.decorGroups.get(e);if(!n)return;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(n.position.y+s)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(e){const t=this.decorGroups.get(e);return t?Math.hypot(t.position.x-this.camera.position.x,t.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(e){const t=this.decorGroups.get(e);return t?t.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Ti/2):0}decorGrabHeightAt(e,t,i){const s=this.decorGroups.get(e);if(!s)return 0;const n=this.bodyBoxScratch.setFromObject(s).max.y-s.position.y;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.decorHitScratch.set(this.camera.position.x-s.position.x,0,this.camera.position.z-s.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,s.position),o=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return o?Math.min(Math.max(o.y-s.position.y,0),Math.max(n,0)):0}decorPlaneScratch=new ro;decorHitScratch=new I;static firstSolid(e){return e.find(t=>{const i=t.object.material;return!(Array.isArray(i)?i:[i]).some(n=>n&&(n.transparent&&n.opacity<de.SEE_THROUGH_BELOW||n instanceof xo))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],s=de.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!s)return;const n=this.bodySystem.pickHit(this.raycaster);if(n!==void 0&&n.distance<s.distance)return;let r=s.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(e,t){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const s=this.raycaster.ray;i.group.updateMatrixWorld();const n=new fd().copy(s).applyMatrix4(new ft().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(u,p)=>{const f=new I(u,0,p).applyMatrix4(r);return this.groundYUnder(f.x,f.z)-r.elements[13]};if(!i.mayMeet(n.origin,n.direction,a,de.RAILWAY_PICK_ABOVE_M))return;const o=de.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!o||this.terrainMesh&&this.groundBlocks(s.origin,s.direction,o.distance-de.RAILWAY_GROUND_MARGIN_M,ff))return;const l=i.group.worldToLocal(o.point.clone()),h=i.lineAt(l.x,l.z);if(!h)return;const d=i.contactHeightM(h);return{line:h,distanceM:o.distance,...d!==void 0?{contactM:d}:{}}}pickBeamAt(e,t){const i=this.beamSystem;if(!i||i.segmentCount===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const s=this.raycaster.ray,n=i.pickAt(s.origin,s.direction,de.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!n||this.terrainMesh&&this.groundBlocks(s.origin,s.direction,n.distanceM-1,ff))return;const r=de.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<n.distanceM))return n}skyLightTowards(e){const t=this.scatteredSky?.ambient;if(!t)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],s=Math.hypot(e.x,e.y,e.z)||1,n=Math.max(0,Math.min(1,e.y/s));return i(t.horizon)+(i(t.zenith)-i(t.horizon))*Math.sqrt(n)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0,this.beamSystem?.dispose(),this.beamSystem=void 0,this.beamSystemLoading=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.reentrySystem?.dispose(),this.reentrySystem=void 0,this.plumeSystem?.dispose(),this.plumeSystem=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const e of this.bodyMeshes.values())this.disposeMesh(e);this.bodyMeshes.clear(),this.novaKeys.clear();for(const e of[...this.hitAreas.keys()])this.disposeHitArea(e);for(const e of[...this.glareSprites.keys()])this.disposeGlare(e);this.disposeCompassLabels();for(const e of this.decorGroups.values())ue.dispose(e);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const 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 s=this.animationsRunning;this.animationsRunning=e,this.framesDriven=i,e&&!s&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const n=!e&&this.renderer.getPixelRatio()!==this.resolution.maximum;n&&this.applyPixelRatio(this.resolution.maximum),!e&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!e||this.frameDirty)&&this.render(),n&&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 I;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const e=this.lastAstronomy?.sun;return e!==void 0&&e.altitudeDeg<de.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 As(pf,32,16),i=t.attributes.position,s=t.getAttribute("color")??new Mt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:o}=FA(i.getX(r),i.getY(r),i.getZ(r)),l=DP(a,o,e.azimuthDeg,e.altitudeDeg);s.setXYZ(r,l[0],l[1],l[2])}if(s.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",s);const n=new $n({vertexColors:!0,side:is,fog:!1,depthWrite:!1});this.skyGradientMaterial=n,this.skyMesh=new we(t,n),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=oS(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Yy(this.groundRadius,48),i=new Br({color:new ae(Yg,Yg,Yg),fog:!0});pc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new we(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 s=0;if(i){const n=i.geometry.getAttribute("position");s=1/0;for(let r=0;r<n.count;r++)Math.abs(n.getX(r)+i.position.x)>600||Math.abs(n.getZ(r)+i.position.z)>600||(s=Math.min(s,n.getY(r)+i.position.y));s=Number.isFinite(s)?Math.min(0,s)-1:0}this.groundMesh.position.y=s,this.groundMesh.renderOrder=0,e.depthTest=!0,e.needsUpdate=!0}cloudTransmission(e,t=!1){const i=`${e.altitudeDeg.toFixed(1)}:${e.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(t?":water":""),s=this.cloudTransmissionMemo.get(i);if(s!==void 0)return s;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const n=this.computeCloudTransmission(e,t);return this.cloudTransmissionMemo.set(i,n),n}cloudTransmissionMemo=new Map;computeCloudTransmission(e,t=!1){const i=Zt(e.altitudeDeg,e.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,t);let s=1;const n=this.lowerCloudCover();n>0&&(s*=1-Bt.alphaAt(i,Math.abs(this.cloudLayerOffset()),n,this.cloudFieldOffset)*G6);const r=t?0:this.weather.highCloudCover??0;return r>0&&(s*=1-Bt.iceAlphaAt(i,bf,r,this.cloudFieldOffset)*V6),Math.max(0,Math.min(1,s))}setBodyMesh(e,t,i,s,n){if(t.altitudeDeg<Xf){this.disposeMesh(this.bodyMeshes.get(e)),this.bodyMeshes.delete(e),this.disposeHitArea(e),this.disposeGlare(e),e==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:o}=Zt(t.altitudeDeg,t.azimuthDeg,Rn),l=this.cloudTransmission(t),h=this.arrivingIlluminance(t,n,l),d=de.unitLuminance(s);let u=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/Rn)**2,f=[0,1,2].map(v=>d[v]*h[v]/(this.sunBeamFraction*p));this.sunDiscRadiance=f;const m=f.map(v=>Math.min(de.BRIGHTEST_RELATIVE,v));u instanceof we||(this.disposeMesh(u),u=new we(new As(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)),u.material.color.setRGB(m[0],m[1],m[2]),u.scale.setScalar(i)}else{if(!(u instanceof sr)){this.disposeMesh(u);const m=new xt;m.setAttribute("position",new wt(new Float32Array(3),3)),m.setAttribute("color",new wt(new Float32Array(3),3)),u=new sr(m,ze.material(dc[dc.length-1].size,!1)),ze.track(u),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)}const p=u.geometry.getAttribute("color"),f=e.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*h[0]*f,d[1]*h[1]*f,d[2]*h[2]*f),p.needsUpdate=!0}if(u.position.set(r,a,o),this.setHitArea(e,r,a,o,i),e==="sun"&&(this.sunArriving=h),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,a,o,h,i/Rn*(180/Math.PI),de.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,a*p+this.celestialGroup.position.y,o*p),this.lensFlare||(this.lensFlare=QP(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<Xf){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:s,y:n,z:r}=Zt(e.altitudeDeg,e.azimuthDeg,Rn),a=this.cloudTransmission(e),o=this.arrivingIlluminance(e,e.magnitude,a),l=e.radiusDeg??Sn.MEAN_RADIUS_DEG,h=Rn*Math.tan(l*Ti),d=Math.max(ya(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Rn)**2,u=new ae(...o.map(m=>Math.min(de.BRIGHTEST_RELATIVE,m/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(ya(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof Rd?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=LS(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new Rd(new Hf({map:LS(e.phase),color:u,fog:!1,blending:zs,depthWrite:!1})),f.userData.phaseKey=p,this.celestialGroup.add(f),this.bodyMeshes.set(i,f)),f.scale.set(h*2,h*2,1),f.position.set(s,n,r),this.setHitArea(i,s,n,r,h),this.setGlare(i,s,n,r,o,l)}bentLight(e,t,i=B6){const[s,n,r]=this.arrivingIlluminance(e,t,1),a=Math.max(n,1e-30);return{scale:n/i,tint:[s/a,1,r/a]}}static litBySky(e,t){return de.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new ae;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,ze.CONE_SOLID_ANGLE/t)}pointScratch=new se;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(e,t,i){const s=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),n=Vt.illuminanceOf(t)*i*this.relativeScale;return[s[0]*n,s[1]*n,s[2]*n]}static unitLuminance(e){const t=nr.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,s,n){let r=this.hitAreas.get(e);if(!r){const o=new Hf({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Rd(o),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,s);const a=n*2;r.scale.set(a,a,1)}disposeHitArea(e){const t=this.hitAreas.get(e);t&&(t.removeFromParent(),t.material.dispose(),this.hitAreas.delete(e))}setGlare(e,t,i,s,n,r,a=0){if(Fs.radiusDeg(Fs.K*Math.max(...n))<=Math.max(r,a)){this.disposeGlare(e);return}let o=this.glareSprites.get(e);o||(o=new Fs(`veil:${e}`),this.celestialGroup.add(o.mesh),this.glareSprites.set(e,o)),o.shine({x:t,y:i,z:s},n,r,a)}disposeGlare(e){const t=this.glareSprites.get(e);t&&(t.mesh.removeFromParent(),t.dispose(),this.glareSprites.delete(e))}buildComet(e,t){const i=e&&`comet:${e.id}`;if(!e||!i||e.magnitude>t){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const s=ic(e.magnitude,t),n=Fg(s);this.cometKey=i,this.setBodyMesh(i,e.position,Jg*(.5+.5*s),new ae(n,n,n),e.magnitude),this.cometTail||(this.cometTail=new mr(Rn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,s)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new hs,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(),s=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(s?.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:bf},0);return}const n=this.lowerCloudCover(),r=St.deckLitUntilDeg(St.DECK_HEIGHT_M),a=e.altitudeDeg>-r?e:t,o=this.bentLight(a,a===e?yt.SUN_MAGNITUDE:t.magnitude),l=St.strength(i,n,a.altitudeDeg,r)*o.scale,{x:h,y:d,z:u}=Zt(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},a.altitudeDeg,l,o.tint,{cover:s?.cover??i,layerHeight:s?.layerHeight??bf},s?.iceCrystalAlignment??this.weather.iceCrystalAlignment??qf,this.weather.rareIceCrystals)}buildRainbow(e,t){this.rainbow||(this.rainbow=new tc,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,s=e.altitudeDeg>0,n=s?e:t,r=this.lowerCloudCover(),a=this.bentLight(n,s?yt.SUN_MAGNITUDE:t.magnitude,H6),o=bn.strength(i,r,n.altitudeDeg)*a.scale;if(o<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:l,y:h,z:d}=Zt(n.altitudeDeg,n.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:d},o,a.tint,s)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new qo,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:s}=e.frame,n=br.galactic(i,s),r=de.directionOf(n.centre),a=de.directionOf(n.rotation),o=de.directionOf(n.pole),l=new bt().set(r.x,r.y,r.z,a.x,a.y,a.z,o.x,o.y,o.z),h=de.directionOf(br.eclipticPole(i,s)),d=de.directionOf(e.sun),u=d.clone().addScaledVector(h,-d.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:u,sunDirection:d,sunAltitudeDeg:e.sun.altitudeDeg,moon:{direction:de.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new I(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:s}=Zt(e.altitudeDeg,e.azimuthDeg,1);return new I(t,i,s).normalize()}buildNovae(e,t){const i=new Set;for(const s of e){if(s.magnitude>t)continue;const n=`nova:${s.id}`;i.add(n);const r=ic(s.magnitude,t),a=Fg(r);this.setBodyMesh(n,s.position,Jg*(.5+.5*r),new ae(a,a,a),s.magnitude)}for(const s of this.novaKeys)i.has(s)||(this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s));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 s of e){if(s.magnitude>t)continue;i.add(s.body);const n=ic(s.magnitude,t),r=Fg(n),a=xN[s.body]??new ae(1,1,1),o=new ae(a.r*r,a.g*r,a.b*r),l=Jg*(.5+.5*n);this.setBodyMesh(s.body,s.position,l,o,s.magnitude)}for(const s of[...this.bodyMeshes.keys()])i.has(s)||(this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s))}buildStars(e,t){if(this.namedStars=[],!e||e.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:s,observer:n}=e,r=new Qr(s,n),a=lv(1337),o=[],l=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<cS)continue;const{x:f,y:m,z:v}=Zt(u,p,qg);o.push({x:f,y:m,z:v,brightness:ic(d,t),illuminance:this.air.transmittanceFromSpace(l,u).map(g=>g*Vt.illuminanceOf(d)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of t2){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<cS)continue;const{x:p,y:f,z:m}=Zt(d,u,qg);this.namedStars.push({star:h,direction:new I(p,f,m).normalize(),altitudeDeg:d})}this.starTiers=dc.map((h,d)=>{const u=o.filter(M=>x0(M.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),m=new Float32Array(u.length*3),v=new Float32Array(u.length),g=new Float32Array(u.length);u.forEach((M,S)=>{p[S*3]=M.x,p[S*3+1]=M.y,p[S*3+2]=M.z,f[S]=M.brightness,m.set(M.illuminance,S*3),v[S]=M.phase,g[S]=M.speedFactor});const b=new xt;b.setAttribute("position",new wt(p,3)),b.setAttribute("seed",new wt(v.map(M=>M/(2*Math.PI)),1));const w=new wt(new Float32Array(u.length*3),3);b.setAttribute("color",w);let y=this.starTiers[d]?.points;return y?(y.geometry.dispose(),y.geometry=b):(y=new sr(b,ze.material(h.size)),ze.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:w,brightness:f,illuminance:m,phase:v,speedFactor:g}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){ze.setTime(e);const t=this.relativeScale;if(t!==this.starColoursRelative){this.starColoursRelative=t;for(const i of this.starTiers){const s=i.colorAttribute.array;for(let n=0;n<i.brightness.length;n++)s[n*3]=i.illuminance[n*3]*t,s[n*3+1]=i.illuminance[n*3+1]*t,s[n*3+2]=i.illuminance[n*3+2]*t;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Gh(this.celestialGroup,Qg,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 ae(Fl[0]+(iv[0]-Fl[0])*t,Fl[1]+(iv[1]-Fl[1])*t,Fl[2]+(iv[2]-Fl[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:s,uniforms:n}=Kb(i,e,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=s,this.cloudUniforms=n,n.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=Xb(Qg);this.cloudMesh=new we(r,s),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}=Kb(new ae(...Fl),e,bf,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new we(Xb(Qg*1.04),t),this.cirrusMesh.renderOrder=vS-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?Gh.deckOrder(!0,0,1):vS}cloudLayerOffset(){const t=((this.weather.cloudBaseM??ry)-this.observerElevationM)*ev;return Math.sign(t||1)*Math.max(Math.abs(t),nN)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(d=>d!==void 0);if(i.length===0&&!this.layeredClouds)return;const s=this.cloudBeamDirection,[n,r,a]=this.cloudBeam.map(d=>d/Math.PI),o=this.lightningLevel*ov*this.relativeScale/Math.PI,l=new ae(t[0]+fa.r*o,t[1]+fa.g*o,t[2]+fa.b*o);this.layeredClouds?.setLighting(s.clone(),new ae(n,r,a),l,l);const h=Math.max(0,s.y);for(const d of i)d.sunDir.value.copy(s),d.sunColor.value.setRGB(n*h,r*h,a*h),d.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(e){return uN(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,rv],[this.rainSplashSystem?.points,Ul],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:sv[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=MS(av(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=sv[e],i=t.poolSize,s=lv(9001),n=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),o=new Float32Array(i),l=new Float32Array(i),h=new Float32Array(i),d=new Float32Array(i),u=new Float32Array(i),p=new Float32Array(i),f=new Float32Array(i);for(let w=0;w<i;w++){const y=s()*Math.PI*2,M=s()*t.radiusM;n[w*3]=Math.cos(y)*M,n[w*3+1]=ah+s()*(t.topYM-ah),n[w*3+2]=Math.sin(y)*M,r[w]=s()*Math.PI*2,a[w]=.7+s()*.6,o[w]=.6+s()*.8,l[w]=.4+s()*1.2}const m=new xt;m.setAttribute("position",new wt(n,3)),m.setDrawRange(0,this.precipitationCount(i));const v={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new ae(...this.baseFogColor)},uTexture:{value:SN(e)},uNearFocusDistance:{value:AS},uHazeDistance:{value:t.radiusM*TS}},g=new Pt({uniforms:v,vertexShader:DN,fragmentShader:RN,transparent:!0,depthWrite:!1});this.precipitationUniforms=v;const b=new sr(m,g);b.renderOrder=tv,this.scene.add(b),this.precipitationPoints=b,this.precipitationPositions=n,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=o,this.precipitationWobbleAmpJitter=l,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 s=sv[i];if(this.precipitationUniforms?.uColor.value.copy(de.litBySky(s.color,this.baseFogColor)),t<=0)return;const n=this.weather.windDirectionDeg*Ti,r=Math.sin(n)*this.weather.windSpeed*s.driftSensitivity,a=-Math.cos(n)*this.weather.windSpeed*s.driftSensitivity,o=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,m=this.precipitationBounceDuration,v=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,b=i==="snow"&&d&&u,w=i==="hail"&&p&&f&&m&&v&&g;for(let y=0,M=0;y<o.length;y+=3,M++){if(w&&p[M]>0){if(p[M]-=t,p[M]<=0){const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(x)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(x)*A,p[M]=0}else{const x=1-p[M]/m[M];o[y+1]=ah+Math.sin(Math.PI*x)*f[M],o[y]=wf(o[y]+(r+v[M])*t,s.radiusM),o[y+2]=wf(o[y+2]+(a+g[M])*t,s.radiusM)}continue}let S=0,E=0;if(b){const x=fN*d[M],A=mN*u[M];S=Math.sin(e*x*Math.PI*2+l[M])*A,E=Math.sin(e*x*Math.PI*2+l[M]+Math.PI/2)*A}if(o[y]+=(r+S)*t,o[y+1]-=s.fallSpeedMPerS*h[M]*t,o[y+2]+=(a+E)*t,o[y]=wf(o[y],s.radiusM),o[y+2]=wf(o[y+2],s.radiusM),o[y+1]<ah){if(w){f[M]=kS*(.2+Math.random()*1.6),m[M]=gN*(.5+Math.random()),p[M]=m[M];const D=Math.random()*Math.PI*2,R=vN*(f[M]/kS);v[M]=Math.cos(D)*R,g[M]=Math.sin(D)*R,o[y+1]=ah;continue}const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(x)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(x)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=av(this.weather.precipitationIntensity);this.rainSystem=jP({count:rv,radiusM:Gd,heightM:aN,bottomYM:bS,overallSpeed:oN,color:wS.clone(),opacity:.85,visibleCount:this.precipitationCount(rv),speedStreak:MS(e),pixelSize:_S,seed:9001,nearFocusDistanceM:AS,hazeDistanceM:Gd*TS,hazeColor:new ae(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=tv,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=lv(4242),t=new Float32Array(Ul*3),i=new Float32Array(Ul),s=new Float32Array(Ul),n=new Float32Array(Ul);for(let h=0;h<Ul;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*Gd;t[h*3]=Math.cos(d)*u,t[h*3+1]=bS,t[h*3+2]=Math.sin(d)*u,s[h]=CS(xS,SS),i[h]=e()*s[h],n[h]=i[h]/s[h]}const r=new xt;r.setAttribute("position",new wt(t,3));const a=new wt(n,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Ul));const o=new Pt({uniforms:{uMaxSize:{value:dN},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:ES.clone()},uTexture:{value:TN()}},vertexShader:IN,fragmentShader:_N,transparent:!0,depthWrite:!1}),l=new sr(r,o);l.renderOrder=tv,this.scene.add(l),this.rainSplashSystem={points:l,positions:t,life:i,duration:s,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const e=this.rainSystem;if(!e)return;const t=this.weather.windDirectionDeg*Ti;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-av(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(de.litBySky(wS,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(de.litBySky(ES,this.baseFogColor));const s=this.weather.windDirectionDeg*Ti,n=Math.sin(s)*this.weather.windSpeed,r=-Math.cos(s)*this.weather.windSpeed,a=Gd,o=h=>(h%(a*2)+a*3)%(a*2)-a;t.uniforms.uWindOffset.value.set(o(t.uniforms.uWindOffset.value.x+n*e),o(t.uniforms.uWindOffset.value.y+r*e)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=DS+(1-DS)*(1-l),d=RS+(1-RS)*(1-l);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=_S*h*(.5+.5*d)}this.updateRainSplashes(e)}updateRainSplashes(e){const t=this.rainSplashSystem;if(!t||e<=0)return;const{positions:i,life:s,duration:n,lifeAttribute:r}=t,a=r.array;for(let o=0,l=0;o<i.length;o+=3,l++){if(s[l]+=e,s[l]>=n[l]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*Gd;i[o]=Math.cos(h)*d,i[o+2]=Math.sin(h)*d,n[l]=CS(xS,SS),s[l]=0}a[l]=s[l]/n[l]}t.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(e){this.lightningFlashes=e}updateLightning(e){let t,i=0;if(this.lightningArmed)for(const o of this.lightningFlashes){if(o.t>e)break;const l=Ls.brightnessAt(o,e);l>i&&(t=o,i=l)}const s=t?Math.min(1,Math.max(.1,(wN/t.distanceM)**2)):0,n=i*s*(t?.cloudToGround?1:.6);if(n===this.lightningLevel&&!t?.cloudToGround)return;if(this.lightningLevel=n,this.scene.fog){const o=this.scene.fog,l=n*ov*this.relativeScale/Math.PI;o.color.setRGB(this.airlight[0]+fa.r*l,this.airlight[1]+fa.g*l,this.airlight[2]+fa.b*l)}const r=this.skyMesh?.material?.color;if(r){const o=n*MN;r.setRGB(1+o*fa.r,1+o*fa.g,1+o*fa.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=n*ov*this.relativeScale,t){const{x:o,y:l,z:h}=Zt(25,t.azimuthDeg,Rn);this.lightningLight.position.set(o,l,h)}this.lightningBolt||(this.lightningBolt=new jo(Rn*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,a),this.render()}buildCompassLabels(){this.compassSprites=J6.map(e=>{const t=uc.point(e,this.compassPoints),i=new Hf({map:kN(t),depthTest:!1,fog:!1}),s=new Rd(i),{x:n,y:r,z:a}=Zt(0,e,pS);return s.position.set(n,r,a),s.scale.set(yf,yf,1),s.renderOrder=tN,s.layers.set(Xg),s.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(s),s}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=fS*Math.PI/360,i=yf*Math.tan(e)/Math.tan(t);for(const s of this.compassSprites)s.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 s=i.map;s&&s.dispose(),i.dispose()}}}const Ti=Math.PI/180;function ya(c,e,t){return Math.max(e,Math.min(t,c))}function CS(c,e){return c+Math.random()*(e-c)}function wf(c,e){return(c%(e*2)+e*3)%(e*2)-e}let Mf,xf;function SN(c){switch(c){case"snow":return EN();case"hail":return AN()}}function EN(){if(Mf)return Mf;const c=64,e=document.createElement("canvas");e.width=c,e.height=c;const t=e.getContext("2d"),i=t.createRadialGradient(c/2,c/2,0,c/2,c/2,c/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,c,c),Mf=new Dl(e),Mf}function AN(){if(xf)return xf;const c=64,e=document.createElement("canvas");e.width=c,e.height=c;const t=e.getContext("2d"),i=t.createRadialGradient(c/2,c/2,0,c/2,c/2,c/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,c,c),xf=new Dl(e),xf}let Sf;function TN(){if(Sf)return Sf;const c=64,e=document.createElement("canvas");e.width=c,e.height=c;const t=e.getContext("2d"),i=t.createRadialGradient(c/2,c/2,0,c/2,c/2,c/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,c,c),Sf=new Dl(e),Sf}const IN=`
|
|
11429
|
+
`,transparent:!0,blending:zs,depthWrite:!1,side:is,fog:!1});this.object=new we(new As(a1.RADIUS,128,32,0,Math.PI*2,0,Vt.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<Vt.STEPS;i++){for(let s=0;s<3;s++)this.texels[i*4+s]=js.toHalfFloat(Math.min(t[i*3+s],6e4));this.texels[i*4+3]=js.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class zm{constructor(e){this.generator=e}static SIZE=128;target=new op(zm.SIZE,{type:ti,generateMipmaps:!0,minFilter:xr,magFilter:Tt});camera=new i1(.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,s=[]){const n=e.shadowMap.autoUpdate;let r=!1;t.traverse(o=>{const l=o;l.isLight&&l.castShadow&&l.shadow&&!l.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?n:!1;const a=s.map(o=>o.visible);for(const o of s)o.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),s.forEach((o,l)=>{o.visible=a[l]}),e.shadowMap.autoUpdate=n,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class yn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){yn.install(),this.generator=new Gb(e),this.eye=new zm(this.generator)}static decor;refresh(e,t,i,s,n,r,a,o=[],l,h=yn.REFRESH_MS){for(const v of[...this.probes.keys()])s.some(g=>g.id===v&&g.shiny)||(this.probes.get(v).dispose(),this.probes.delete(v));const d=[{probe:this.eye}];for(const v of s){if(!v.shiny)continue;let g=this.probes.get(v.id);g||(g=new zm(this.generator),this.probes.set(v.id,g)),d.push({probe:g,reflector:v})}const u=performance.now(),p=()=>d.filter(({probe:v})=>v.capturedVersion!==a),f=p().filter(({probe:v})=>u-v.capturedAtMs>=h);if(f.length>0){const v=f.reduce((g,b)=>b.probe.capturedAtMs<g.probe.capturedAtMs?b:g);if(v.reflector){const g=v.reflector.holder.getWorldPosition(this.scratch);v.probe.capture(e,t,g,[v.reflector.holder,...n]),yn.reflectOn(v.reflector.holder,v.probe)}else{v.probe.capture(e,t,i,[...n,...o]),l?.(v.probe.sharp),yn.decor=v.probe.filtered;for(const g of r)yn.reflectOn(g,v.probe);for(const g of s)g.shiny||yn.reflectOn(g.holder,v.probe)}v.probe.capturedVersion=a}const m=p();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:v})=>h-(u-v.capturedAtMs))))}scratch=new I;static reflectOn(e,t={filtered:yn.decor}){e.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[])n instanceof xo?t.sharp&&n.setSurroundings(t.sharp):n instanceof el&&t.filtered&&n.envMap!==t.filtered&&(n.envMap=t.filtered,n.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const e of this.probes.values())e.dispose();this.generator.dispose()}static installed=!1;static install(){if(yn.installed)return;yn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!vt.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}vt.lights_fragment_maps=vt.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function O6(c,e){return JSON.stringify(c.cloudLayers)===JSON.stringify(e.cloudLayers)&&c.cloudCover===e.cloudCover&&c.cloudDarkness===e.cloudDarkness&&c.cloudBaseM===e.cloudBaseM&&c.highCloudCover===e.highCloudCover&&c.iceCrystalAlignment===e.iceCrystalAlignment&&c.rareIceCrystals===e.rareIceCrystals&&c.lowerCloudCover===e.lowerCloudCover&&c.relativeHumidity===e.relativeHumidity&&c.precipitationType===e.precipitationType&&c.precipitationIntensity===e.precipitationIntensity&&c.precipitationAmount===e.precipitationAmount&&c.windDirectionDeg===e.windDirectionDeg&&c.windSpeed===e.windSpeed&&c.storm===e.storm}const pf=900,Kg=1,aS=4,Xg=5,ff=.5,mf=ri.GROUND_RADIUS_M;function oS(c){return ri.groundRadiusFor(c)}const Yg=.5,qg=850,gf=.03,P6=.015,Rn=850,ih=300,Qa=120,N6=700,jg=.03,F6=3.5,vf=20,Zg=.04,U6=.26,lS=4,Jg=1.5,cS=-1,z6=.01,Xf=-4,B6=2,H6=20,bf=2600,G6=.97,V6=.38,Hd=Xf,W6=8,$6=2,hS=1500,K6=.7,X6=.3,Y6=.32,q6=.65,dS=2.4,j6=.9,Z6=400,J6=[0,45,90,135,180,225,270,315],Q6=2,eN=16,uS=4e3,pS=880,yf=40,fS=60,tN=10,iN=1,sN=ri.REBUILD_DISTANCE_M,mS=.265,gS=[[0,0],...Array.from({length:8},(c,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*mS,Math.sin(t)*mS]})],Qg=700,ev=250/ry,nN=12,vS=5,tv=6,Fl=[.92,.92,.95],iv=[.15,.15,.19],sv={snow:{fallSpeedMPerS:2,size:.3,color:new ae(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new ae(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},ah=0,nv=0,rN=150,rv=3e3,Gd=20,aN=15,bS=ah,oN=40,yS=1,lN=9;function av(c){return yS+(lN-yS)*c}const wS=new ae(.75,.82,.92),cN=10,hN=.5;function MS(c){return ya(c/cN,hN,1)}const Ul=200,xS=.18,SS=.32,dN=.35,ES=new ae(.85,.9,.98),AS=5,TS=.85,IS=.01;function uN(c,e,t=1){return Math.round(c*(IS+(1-IS)*e)*t)}function pN(c,e){return JSON.stringify(c.cloudLayers)===JSON.stringify(e.cloudLayers)&&c.cloudCover===e.cloudCover&&c.cloudDarkness===e.cloudDarkness&&c.cloudBaseM===e.cloudBaseM&&c.highCloudCover===e.highCloudCover&&c.iceCrystalAlignment===e.iceCrystalAlignment&&c.lowerCloudCover===e.lowerCloudCover}const _S=230,DS=.7,RS=.05,fN=.6,mN=.7,gN=.15,kS=.35,vN=3,bN=1/12,yN=.5,fa=new ae(.82,.86,1),wN=2500,MN=1.6,ov=15,xN={Venus:new ae(1,.96,.85),Mars:new ae(1,.55,.4),Jupiter:new ae(.95,.87,.72),Saturn:new ae(.92,.86,.68)};class de{renderer;scene=new Er;phenomena=new qr(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;onReferencesSettled;camera;celestialGroup=new Kt;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(e,t){if(this.skyHoldUntilMs===null)return e;this.arrivalsPending++;let i=!0;const s=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},n=t===void 0?void 0:setTimeout(s,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(n),s()})}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()+uS,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),uS+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new At;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new se;decorModelProvider=Kf[0].create();decorModelToken=0;decorModelCredits=new Map;emitterLights=new Cn(this.scene,()=>this.relativeScale,{halfExtentM:Qa,depthHalfRangeM:ih,biasM:jg,normalBiasM:Zg,mapSize:1024});bodySystem=new ht(e=>this.awaitArrival(this.loadBodyModel(e)),()=>this.render(),()=>this.relativeScale,e=>this.emitterLights.set("bodies",e));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??de.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*de.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;beams=[];beamSystem;beamSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new _m(16777215,0);celestialLightTarget=new qi;skyLight=new YR(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new Gf;weather=Zm;observerElevationM=0;siteElevationM=0;air=new Lr;groundRadius=mf;terrainRadius=mf;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new I;cloudFieldOffset=new I;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new I;rainLastVerticalFacing=-1;rainViewportSize=new se;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new _m(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new I;sunVisible=!1;lensFlareScratch=new I;sunOcclusionRaycaster=new Gf;sunOcclusionDirectionScratch=new I;sunOcclusionRightScratch=new I;sunOcclusionUpScratch=new I;ufoOcclusionRaycaster=new Gf;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=Ci.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(e){return Math.max(3,Math.round(6e6/Math.max(1,e)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;reentrySystem;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new lp;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=A2()){lu.install(),this.renderer=new cP({canvas:e,antialias:!0}),this.resolution=new ci(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=eu,this.camera=new nn(60,e.width/Math.max(e.height,1),.1,pf*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=-Qa,this.celestialLight.shadow.camera.right=Qa,this.celestialLight.shadow.camera.top=Qa,this.celestialLight.shadow.camera.bottom=-Qa,this.celestialLight.shadow.camera.near=Rn-ih,this.celestialLight.shadow.camera.far=Rn+ih,this.celestialLight.shadow.bias=-jg/(2*ih),this.celestialLight.shadow.normalBias=Zg,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(fa),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new yt(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(e,t){this.cssSize.width=e,this.cssSize.height=t,this.renderer.setSize(e,t,!1),this.camera.aspect=e/Math.max(t,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(e){e!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=e,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(e,t={}){this.cloudOffsetM.set(e.x,0,e.z),this.cloudLayerOffsetsM=t,this.layeredClouds?.setOffsets(e,t),this.cloudFieldOffset.set(e.x*ev,0,e.z*ev);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)*Ti,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Ti;e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Ti,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(oS(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/mf),this.camera.far=Math.max(pf*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),e.lat!==void 0&&e.lng!==void 0&&this.placeTerrain(e.lat,e.lng,0,0),this.poseElevationM=e.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+e.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==e.fovDeg&&(this.camera.fov=e.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(e){this.stopTerrainFade(),this.terrainProviders=e,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(e){this.observerRoute=e,this.decorTerrainRadiusM=de.terrainReachFor(this.decorObjects,e)}decorTerrainRadiusM=0;static terrainReachFor(e,t){return ri.decorReachFor(e,t)}placeTerrain(e,t,i,s){const n=(r,a)=>{const o=ut(a.lat,a.lng,e,t);r.position.x=o.x-i,r.position.z=o.z+s};if(this.terrainMesh&&this.terrainMeshOrigin&&n(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&n(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;n(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const s=this.terrainProviders.patches;let n;if(s){if(!s.loaded){if(this.patchesAwaitedFor={lat:e,lng:t,onSettled:i},this.patchesAwaited!==s){this.patchesAwaited=s;const u=this.terrainProviders;this.awaitArrival(s.ready.then(()=>{const p=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===u&&p&&this.setTerrainOrigin(p.lat,p.lng,p.onSettled)}),de.TERRAIN_PATIENCE_MS)}return}const d=s.nearest(e,t);d&&(e=d.lat,t=d.lng,n=d.radiusM)}const r=n??Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:d,z:u}=ut(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(d*d+u*u)<sN*(r/mf))return}const a=this.terrainRadius,o=this.terrainMeshOrigin;o!==void 0&&Math.hypot(ut(e,t,o.lat,o.lng).x,ut(e,t,o.lat,o.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(Hx(e,t,this.terrainProviders,r,{route:this.observerRoute}),de.TERRAIN_PATIENCE_MS).then(({mesh:d,attribution:u,originElevationM:p,water:f,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(p??0),this.anchorGrassTo(d,e,t);const v=this.terrainMesh,g=this.terrainMeshOrigin,b=g?ut(e,t,g.lat,g.lng):void 0;v&&b&&Math.hypot(b.x,b.z)<=a&&(d.position.y=v.position.y+this.groundYOfPatch(v,b.x,b.z)),v&&g&&b&&Math.hypot(b.x,b.z)<=a?this.crossfadeTerrain(d,v,g):this.disposeMesh(this.terrainMesh),d.renderOrder=iN,this.terrainMesh=d,this.terrainMeshOrigin={lat:e,lng:t},this.compileNextFrameOffThread(),this.terrainAttribution=u,this.scene.add(d),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,r),this.buildWater(e,t,r,f,m),this.buildRailways(e,t,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(e,t,r,d,p),this.render(),i?.()}).catch(d=>{console.warn("Terrain build failed, keeping the flat ground fallback:",d),i?.()})}buildFarRing(e,t,i,s,n){s.geometry.computeBoundingBox();const r=s.position.y+(s.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,o=ri.beamReachFor(this.beams,{lat:e,lng:t});if(!ri.needsFarRing(i,a,o)){this.dropFarRing();return}if(this.farRing){const{x:f,z:m}=ut(e,t,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(f,m)<i*de.FAR_RING_KEPT_SHARE)return}const l=this.terrainProviders.patches,h=l?.farRingOf?.(e,t);if(l&&!h){this.dropFarRing();return}const d=h?.radiusM??ri.FAR_RING_RADIUS_M,u=++this.farRingToken,p=this.terrainProviders;this.awaitArrival(Hx(e,t,{elevation:p.elevation,imagery:p.imagery},d,void 0,{innerM:i*de.FAR_RING_OPEN_SHARE,referenceElevationM:n}),de.TERRAIN_PATIENCE_MS).then(({mesh:f})=>{if(u!==this.farRingToken||this.terrainProviders!==p){this.disposeMesh(f);return}this.dropFarRing(),this.farRingToken=u,f.renderOrder=de.FAR_RING_RENDER_ORDER,f.position.y=s.position.y-de.FAR_RING_DROP_M;const m=f.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:f,origin:{lat:e,lng:t}},this.farRingRadiusM=d,this.scene.add(f),f.position.x=s.position.x,f.position.z=s.position.z,this.compileNextFrameOffThread(),this.render()},f=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",f))}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(e,t,i){if(this.grassReference){const r=ut(this.grassReference.lat,this.grassReference.lng,t,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:t,lng:i};const s=ut(this.grassReference.lat,this.grassReference.lng,t,i);e.material.userData?.grassOrigin?.set(s.x,s.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t,i){this.stopTerrainFade();const s=e.material;s.opacity=0,s.polygonOffset=!0,s.polygonOffsetFactor=-1,s.polygonOffsetUnits=-4;const n=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-n)/de.TERRAIN_CROSSFADE_MS);if(s.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}s.polygonOffset=!1,s.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:t,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const e=this.terrainMesh?.material;e&&(e.opacity=1,e.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=ri.ROADS_MAX_RADIUS_M;buildRoads(e,t,i){const s=this.terrainProviders.roads;if(!s||i>de.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const n=this.roadWays;if(n&&n.lat===e&&n.lng===t&&n.radiusM===i){this.drapeRoads(n.ways,e,t,s.contemporary);return}n&&Math.hypot(ut(e,t,n.lat,n.lng).x,ut(e,t,n.lat,n.lng).z)<=n.radiusM&&this.drapeRoads(n.ways,e,t,s.contemporary),this.awaitArrival(s.getRoads(cu(e,t,i)),de.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,s.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(e,t,i,s,n){const r=this.terrainProviders.water;if(!r||i>de.ROADS_MAX_RADIUS_M){this.clearWater();return}if(s){this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:s},this.awaitArrival(this.drapeWater(s,e,t,i),de.ROADS_PATIENCE_MS).catch(o=>console.warn("Water not drawn:",o));return}const a=this.waterSurfaces;if(a&&a.lat===e&&a.lng===t&&a.radiusM===i){this.drapeWater(a.surfaces,e,t,i);return}a&&Math.hypot(ut(e,t,a.lat,a.lng).x,ut(e,t,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,e,t,i),this.awaitArrival((n??r.getWater(cu(e,t,i))).then(o=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:o},this.drapeWater(o,e,t,i)}),de.ROADS_PATIENCE_MS).catch(o=>{console.warn("Water unavailable, drawing none:",o)})}async drapeWater(e,t,i,s){if(e.length===0&&!this.waterSystem)return;const n=await this.loadWaterSystem(),r=this.terrainMesh;r&&(n.group.position.copy(r.position),n.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),s,this.patchSpacingM(r)),yn.reflectOn(n.group),this.waterAttribution=n.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=oe(async()=>{const{WaterSystem:e}=await import("./WaterSystem-BDkfNF8C.js");return{WaterSystem:e}},[],import.meta.url).then(({WaterSystem:e})=>{const t=new e;return this.scene.add(t.group),this.waterSystem=t,t})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(e,t,i){const s=this.terrainProviders.railways;if(!s||i>de.ROADS_MAX_RADIUS_M){this.clearRailways();return}const n=this.railwayLines;if(n&&n.lat===e&&n.lng===t&&n.radiusM===i){this.drapeRailways(n.lines,e,t,i);return}n&&Math.hypot(ut(e,t,n.lat,n.lng).x,ut(e,t,n.lat,n.lng).z)<=n.radiusM&&this.drapeRailways(n.lines,e,t,i),this.awaitArrival(s.getRailways(cu(e,t,i)).then(r=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.railwayLines={lat:e,lng:t,radiusM:i,lines:r},this.drapeRailways(r,e,t,i)}),de.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(e,t,i,s){if(!this.railwaySystem&&!e.some(a=>a.level>=0))return;const n=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(n.group.position.copy(r.position),n.setGroundSpacing(this.patchSpacingM(r)),n.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),s),yn.reflectOn(n.group),this.railwayAttribution=n.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=oe(async()=>{const{RailwaySystem:e}=await import("./RailwaySystem-BfDjza60.js");return{RailwaySystem:e}},[],import.meta.url).then(({RailwaySystem:e})=>{const t=new e;return this.scene.add(t.group),this.railwaySystem=t,t})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(e){e!==this.statedRoads&&(this.statedRoads=e,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const e=this.terrainMesh;e&&(this.roadSystem.group.position.copy(e.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(e)),this.roadSystem.setStated(this.statedRoads,(t,i)=>this.groundYOfPatch(e,t,i)))}setTraces(e,t=new Map){e===this.traces&&t===this.traceLabels||(this.traces=e,this.traceLabels=t,!(e.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(e){e!==this.tracesShown&&(this.tracesShown=e,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=oe(async()=>{const{TraceSystem:e}=await import("./TraceSystem-C1HaC0DX.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(Xg);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainMeshOrigin;!e||!t||!i||(e.group.position.copy(t.position),e.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(s,n)=>this.groundYOfPatch(t,s,n)))}buildingFootprints(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(s=>s.kind==="building"&&!s.observerSide&&!s.track).map(s=>{const n=ue.naturalSize(s.kind,s.floors),r=(s.headingDeg??0)*Math.PI/180;return{x:i.x+s.eastM,z:i.z-s.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(s.sizeM?.lengthM??n.lengthM)/2,halfAcrossM:(s.sizeM?.widthM??n.widthM)/2}})}decorOriginInRoads(e,t){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ut(i.lat,i.lng,e,t):{x:0,z:0}}surveyedLamps(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(s=>s.kind==="streetlight"&&!s.lamp?.supposed&&!s.track).map(s=>({x:i.x+s.eastM,z:i.z-s.northM}))}lampNudges=new Map;lampsToKerb(e,t){this.lampNudges.clear();const i=this.decorOriginInRoads(e,t);for(const s of this.decorObjects){if(s.kind!=="streetlight"||!s.lamp?.supposed||s.track)continue;const n=i.x+s.eastM,r=i.z-s.northM,a=this.roadSystem.atKerb(n,r);(a.x!==n||a.z!==r)&&this.lampNudges.set(s.id,{eastM:a.x-n,northM:-(a.z-r)})}}static onlyMoved(e,t){return e.length!==t.length||e.length===0?!1:e.every((i,s)=>{const n=t[s];if(i.id!==n.id||(i.track?.length??-1)!==(n.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(n)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==n[a])return!1;return!0})}layStreetsIfWallsMoved(e){const t=this.roadWays,i=this.terrainProviders.roads;if(!t||!i)return;const s=this.wallsOf(e,t.lat,t.lng),n=this.roadWalls;n?.lat===t.lat&&n.lng===t.lng&&n.walls.length===s.length&&n.walls.every((a,o)=>a.what===s[o].what&&Math.hypot(a.x-s[o].x,a.z-s[o].z)<.1)||this.drapeRoads(t.ways,t.lat,t.lng,i.contemporary)}wallsOf(e,t,i){const s=this.decorOriginInRoads(t,i);return e.filter(n=>n.kind==="building"||n.kind==="streetlight").map(n=>({what:`${n.kind}:${n.lamp?.supposed?"s":""}${n.headingDeg??0}:${n.sizeM?.widthM??""}:${n.sizeM?.lengthM??""}`,x:s.x+n.eastM,z:s.z-n.northM}))}roadWalls;drapeRoads(e,t,i,s){const n=this.terrainMesh;n&&(this.roadSystem.group.position.copy(n.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(n)),this.roadSystem.set(e,t,i,(r,a)=>this.groundYOfPatch(n,r,a),s,this.terrainRadius,new Pi(this.buildingFootprints(t,i),this.surveyedLamps(t,i))),this.roadWalls={lat:t,lng:i,walls:this.wallsOf(this.decorObjects,t,i)},this.lampsToKerb(t,i),this.roadAttribution=e.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(e){this.showCompass!==e&&(this.showCompass=e,this.disposeCompassLabels(),e&&this.buildCompassLabels(),this.render())}setCompassPoints(e){this.compassPoints!==e&&(this.compassPoints=e,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[e,t,i]=this.sunArriving,s=Math.max(t,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(e/s,1,i/s),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?Fs.LENS_K:Fs.K)*t*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(e){this.compassHovered!==e&&(this.compassHovered=e,this.updateCompassVisibility())}setCompassForced(e){this.compassForced!==e&&(this.compassForced=e,this.updateCompassVisibility())}updateCompassVisibility(){const e=this.compassHovered||this.compassForced;if(this.compassSprites.some(t=>t.visible!==e)){for(const t of this.compassSprites)t.visible=e;this.developingExposure&&!this.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(e){if(O6(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!pN(t,e),s=t.precipitationType!==e.precipitationType,n=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||s||n)&&(this.air=Lr.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:yo.steppedOpticalDepth(e.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),s?this.buildPrecipitation():n&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||s||n)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=e.storm&&e.cloudDarkness>=yN,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects===e)return;if(de.onlyMoved(this.decorObjects,e)){this.decorObjects=e,this.decorTerrainRadiusM=de.terrainReachFor(e,this.observerRoute),this.layStreetsIfWallsMoved(e);return}this.decorObjects=e,this.decorTerrainRadiusM=de.terrainReachFor(e,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ue.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const t=e.filter(i=>i.kind==="streetlight").sort((i,s)=>Math.hypot(i.eastM,i.northM)-Math.hypot(s.eastM,s.northM)).slice(0,W6);for(const i of e){const s=ue.build(i,i.lit??!1);this.scene.add(s),this.decorGroups.set(i.id,s),i.kind==="streetlight"&&t.includes(i)&&this.addStreetlightLight(i.id,s,t.indexOf(i)<$6,i.lamp),i.model&&i.id.startsWith(tn.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,s)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=de.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(e),e.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(e){this.decorSunlight=e}setContrails(e){e!==this.contrails&&(this.contrails=e,!(e.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(e){this.contrailSunlight=e}loadContrailSystem(){return this.contrailSystemLoading??=oe(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-BXARgrR4.js");return{ContrailSystem:e}},__vite__mapDeps([6,7]),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,s=de.CONTRAIL_SCATTERING,n=this.skyLight.color,r=[n.r*s*.5,n.g*s*.5,n.b*s*.5];if(t&&i){const a=zn.litFraction(t.sunElevationDeg,t.heightM);if(a>0){const o=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),l=Vt.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=s*l*o[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setBeams(e){e!==this.beams&&(this.beams=e,this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),!(e.length===0&&!this.beamSystem)&&this.loadBeamSystem().then(()=>{this.updateBeams(),this.render()}))}get beamSegmentCount(){return this.beamSystem?.segmentCount??0}loadBeamSystem(){return this.beamSystemLoading??=oe(async()=>{const{BeamSystem:e}=await import("./BeamSystem-BBonCZQ1.js");return{BeamSystem:e}},__vite__mapDeps([8,9]),import.meta.url).then(({BeamSystem:e})=>{const t=new e;this.scene.add(t.group),this.beamSystem=t})}updateBeams(){const e=this.decorReferencePose;!this.beamSystem||e?.lat===void 0||e.lng===void 0||this.beamSystem.update(this.beams,this.decorTime,{reference:{lat:e.lat,lng:e.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(t,i,s)=>this.transmittanceTo(t,i,s),groundYAt:(t,i)=>this.groundYUnder(t,i)})}updateContrails(){const e=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:e?Zt(e.altitudeDeg,e.azimuthDeg,1):void 0},t=>this.contrailTint(t))}contrailPixelRad(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/e)}setDecorPresence(e){this.decorPresence=e}entryOfDecorModel(e){return this.decorModelProvider.entry(e).catch(()=>{})}setDecorModelProvider(e){this.decorModelProvider=e;const t=this.decorObjects;this.decorObjects=[],this.setDecor(t)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:e,z:t}=this.bodyOrigin,i=this.groundYUnder(e,t),s=this.bodyEastScale;return{heightAt:(n,r)=>this.groundYUnder(e+n*s,t-r)-i}}get bodyEastScale(){const e=this.decorReferencePose,t=this.decorCurrentPose;return e?.lat===void 0||t?.lat===void 0?1:Math.cos(t.lat*Ti)/Math.cos(e.lat*Ti)}bodyMaskedByDecor(e,t){const i=this.decorGroups.get(t);return i?this.bodySystem.maskedShare(e,i):void 0}setBodies(e,t=0,i=e.map(r=>r.id),s=[],n){const{x:r,z:a}=this.bodyOrigin,o=this.scatteredSky,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(e=e.map(d=>({...d,eastM:d.eastM*l}))),this.bodySystem.set(e,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(d,u)=>this.groundYUnder(d,u),wind:n,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(d,u,p)=>this.transmittanceTo(d,u,p),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},t,o?Object.assign((d,u)=>o.relativeOfLuminance(d,u),{recorded:o.recorded}):void 0,i),this.bodySystem.setSmoke(s,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}plumeLight(){const e=this.celestialLight.color,t=this.celestialLight.intensity*.5,i=this.skyLight.color,s=this.skyLight.groundColor,n=this.skyLight.intensity,r=(a,o,l)=>(a*t+(o+l)/2*n)/Math.PI;return[r(e.r,i.r,s.r),r(e.g,i.g,s.g),r(e.b,i.b,s.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,s=e.credit??t?.credit;if(!(!i||!s))return{scene:await $g(i),credit:s,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg,bindings:t?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(ju(e))||!ue.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const s=$A(i.scene);s.traverse(n=>{n instanceof we&&(n.userData.sharedModel=!0)}),ue.applyModelParameters(s,e.modelParameters,i.bindings),ue.applyModel(t,e,s,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(s),this.decorModelCredits.set(e.id,i.credit)}mirrors=new tr;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(e,t,i=!1){const s=i?lm[e.kind]:ju(e);if(!(!s||!ue.usesModel(e)))try{const n=s.url?void 0:s.id?await this.decorModelProvider.entry(s.id):void 0,r=this.modelUrl(s)??n?.url,a=s.credit??n?.credit;if(!r||!a)return;const o=i||e.kind==="tree"?await this.standInScene(r):await $g(r);if(t!==this.decorModelToken||i&&!this.pendingTrafficModels.has(e.id))return;const l=this.decorGroups.get(e.id);if(!l)return;!i&&e.kind!=="tree"&&(ht.glaze(o),yn.reflectOn(o));const h={ref:JSON.stringify(s),scene:o,headingOffsetDeg:s.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM,credit:a,bindings:n?.parameters?.bindings};i||this.loadedDecorModels.set(e.id,h),this.applyLoadedDecorModel(e,l,h),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${e.id}":`,n)}}standInScene(e){let t=this.standInScenes.get(e);return t||(t=$g(e).then(i=>(/jungle-jim-realistic-trees/.test(e)||yn.reflectOn(i),i)),this.standInScenes.set(e,t)),t}updateDecorAnchoring(e,t,i=0){this.decorReferencePose=e,this.decorCurrentPose=t,this.decorTime=i;const s=e?.lat!==void 0&&e.lng!==void 0&&t?.lat!==void 0&&t?.lng!==void 0?ut(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},n=this.decorObjects.find(f=>f.observerSide!==void 0&&Sl(f.kind));this.terrainMesh&&t?.lat!==void 0&&t.lng!==void 0&&(this.placeTerrain(t.lat,t.lng,n?0:this.gaitOffset.eastM,n?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),n||(s.x-=this.gaitOffset.eastM,s.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let a=0,o;if(n){const f=Mr(n,i),m=ue.occupantView(n,f.headingDeg),v=-(f.headingDeg??0)*Ti,g=m.x*Math.cos(v)+m.z*Math.sin(v),b=-m.x*Math.sin(v)+m.z*Math.cos(v),w=f.eastM+s.x,y=-f.northM+s.z;r.x=-(w+g),r.z=-(y+b),this.camera.position.y=this.groundYUnder(w,y)+m.eyeY,o=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Ti,-(m.headingDeg+this.indoorLookYawDeg)*Ti,0,"YXZ")}this.bodyOrigin={x:s.x+r.x,z:s.z+r.z};const l=this.findCabin(i,s,r);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,s,r);const h=this.terraces.map(f=>[f.x,f.z,f.cos,f.sin,f.halfWidthM,f.halfLengthM,f.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!n&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const f of this.decorObjects){if(f.kind==="terrace")continue;const m=this.decorGroups.get(f.id);if(!m)continue;const v=Mr(f,i),g=this.lampNudges.get(f.id),b=v.eastM+(g?.eastM??0)+s.x+r.x,w=-(v.northM+(g?.northM??0))+s.z+r.z,y=this.terrainMesh,M=`${y?.geometry.uuid}:${(b-(y?.position.x??0)).toFixed(3)}:${(w-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${v.headingDeg}:${v.altitudeM}:${h}`;if(m.userData.footprintKey!==M){if(f.kind==="wire"){const L=ue.wireGround(f,b,w,v.headingDeg,(N,k)=>this.groundYUnder(N,k));m.userData.footprintGroundY=L.startY,ue.shearWire(m,ue.sizeOf(f).lengthM,L.dropM)}else if(f.kind==="crossing"){const L=this.groundYUnder(b,w),N=-(v.headingDeg??0)*Ti,k=Math.cos(N),C=Math.sin(N);m.userData.footprintGroundY=L,kt.drape(ue.bodyOf(m),(P,F)=>this.groundYUnder(b+P*k+F*C,w-P*C+F*k)-L)}else m.userData.footprintGroundY=this.groundUnderFootprint(f,b,w,v.headingDeg,v.altitudeM);m.userData.footprintKey=M}const E=v.altitudeM>de.AIRBORNE_M&&Math.hypot(b,w)<de.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY;if(m.position.set(b,E+v.altitudeM,w),f.kind==="crop"){const L=Math.hypot(b,w);m.visible=L<=rN}const x=this.decorPresence.get(f.id),A=x!==void 0&&(i<x.fromMs||i>x.untilMs);x&&(m.visible=!A);const D=this.decorSunlight.get(f.id);D&&!A&&this.lightFromAbove(m,D),v.headingDeg!==void 0&&(m.rotation.y=-v.headingDeg*Ti);const R=P5(f,i);if(R!==void 0&&de.turnHead(m,v.headingDeg??0,R),f.kind==="crop"&&m.visible){const L=this.terrainMesh,N=[L?.geometry.uuid,b-(L?.position.x??0),w-(L?.position.z??0),m.position.y-(L?.position.y??0),v.headingDeg,v.altitudeM].map(k=>typeof k=="number"?k.toFixed(4):k).join(":");m.userData.cropGroundKey!==N&&(ue.fitCropToGround(m,(k,C)=>this.groundYUnder(k,C)+v.altitudeM),m.userData.cropGroundKey=N)}if(!A){const L=m.position.distanceTo(this.camera.position);a=Math.max(a,L),L<de.trafficModelRangeM(f)&&this.pendingTrafficModels.delete(f.id)&&this.loadDecorModel(f,this.decorModelToken)}}if(n&&o!==void 0){const f=this.decorGroups.get(n.id);f&&(this.camera.position.y=f.position.y+o)}this.updateContrails(),this.updateBeams();const d=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,u=this.beams?.length&&this.terrainMeshOrigin?ri.beamReachFor(this.beams,this.terrainMeshOrigin):0,p=Math.max(pf*1.2,this.groundRadius*2.5,a*1.2,d*1.05,u*1.2);Math.abs(this.camera.far-p)>1&&(this.camera.far=p,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainYUnder(e,t);let s=i;for(const n of this.terraces){const r=e-n.x,a=t-n.z,o=r*n.cos-a*n.sin,l=r*n.sin+a*n.cos;if(Math.abs(o)<=n.halfWidthM&&Math.abs(l)<=n.halfLengthM){const h=Math.min(1,Math.max(0,(n.halfWidthM-Math.abs(o))/n.bankM)),d=h*h*(3-2*h);s=Math.max(s,d*n.levelY+(1-d)*Math.min(n.levelY,i))}}return s}placeTerraces(e,t,i){this.terraces=[];const s=this.terrainMesh;for(const n of this.decorObjects){if(n.kind!=="terrace")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=Mr(n,e),o=a.eastM+t.x+i.x,l=-a.northM+t.z+i.z,h=ue.sizeOf(n),d=-(a.headingDeg??0)*Ti,u=Math.cos(d),p=Math.sin(d),f=`${s?.geometry.uuid}:${(o-(s?.position.x??0)).toFixed(3)}:${(l-(s?.position.z??0)).toFixed(3)}:${(s?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(o,0,l),a.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=ue.fitTerrace(r,n,(m,v)=>this.terrainYUnder(o+m*u+v*p,l-m*p+v*u)),r.userData.terraceKey=f),this.terraces.push({x:o,z:l,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):nv}horizonAltitudeDeg(e){const t=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(t.x)}|${Math.round(t.y*10)}|${Math.round(t.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const s=this.horizonByBearing.length,n=Math.round((e%360+360)%360/(360/s))%s;let r=this.horizonByBearing[n];return Number.isNaN(r)&&(r=this.horizonByBearing[n]=this.marchHorizon(n*360/s)),r}groundHidesDirection(e,t){return e<Math.max(0,this.horizonAltitudeDeg(t))+de.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(e){const t=this.terrainMesh;if(!t)return Number.NEGATIVE_INFINITY;const i=this.camera.position,s=e*Math.PI/180,n=Math.sin(s),r=-Math.cos(s),a=this.farRing?.mesh,o=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(t),1),50);let h=Number.NEGATIVE_INFINITY;for(let d=l;d<=o;d=Math.max(d+l,d*1.02)){const u=i.x+n*d,p=i.z+r*d,f=d<=this.terrainRadius?this.terrainYUnder(u,p):a.position.y+this.groundYOfPatch(a,u-a.position.x,p-a.position.z),m=d*d/(2*de.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(f-m-i.y,d))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(e){const t=e.geometry.getAttribute("position");return t&&t.count>=2?Math.abs(t.getX(1)-t.getX(0)):1/0}groundYOfPatch(e,t,i){const s=e.geometry.getAttribute("position"),n=Math.round(Math.sqrt(s.count));if(n<2||n*n!==s.count)return nv;const r=s.getX(0),a=s.getX(n-1),o=s.getZ(0),l=s.getZ((n-1)*n),h=ya((t-r)/(a-r)*(n-1),0,n-1),d=ya((i-o)/(l-o)*(n-1),0,n-1);if(!Number.isFinite(h)||!Number.isFinite(d))return nv;const u=Math.min(Math.floor(h),n-2),p=Math.min(Math.floor(d),n-2),f=h-u,m=d-p,v=(M,S)=>s.getY(M*n+S),g=v(p,u),b=v(p,u+1),w=v(p+1,u),y=v(p+1,u+1);return f+m<=1?g+(b-g)*f+(w-g)*m:y+(w-y)*(1-f)+(b-y)*(1-m)}groundUnderFootprint(e,t,i,s,n=0){return ue.groundUnderFootprint(e,t,i,s,(r,a)=>this.groundYUnder(r,a),n)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(e){this.gaitOffset=e}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(e,t){this.lookYawDeg=e,this.lookPitchDeg=t}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(e,t){this.indoorLookYawDeg=e,this.indoorLookPitchDeg=t}skyUnknown=!1;setSkyUnknown(e){e!==this.skyUnknown&&(this.skyUnknown=e,this.render())}perception=cr.NONE;setPerception(e){JSON.stringify(e)!==JSON.stringify(this.perception)&&(this.perception=e,this.render())}medium;setMedium(e,t,i,s,n){const r=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:s??e.iso,autoExposure:e.autoExposure===!0&&s===void 0,maxIso:e.maxIso,metering:n??e.metering??"average",exposureSeconds:t,fNumber:i,development:e.development,exposureFollowMs:e.exposureFollowMs}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30),i=e?cr.NONE:this.perception??cr.NONE;if(Ki.uColorVision.value.set(...i.colorMatrix),Ki.uContrast.value=i.contrastGain,!e){Ki.uMedium.value=0;return}const s=e.kind==="sensor"&&e.development==="computational";Ki.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:s?4:3;const n=e.autoExposure?this.frameLight:void 0,r=e.autoExposure||this.skyUnknown?n?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),o=r===void 0?void 0:r+a.mean,l=u=>.065*e.exposureSeconds*u*this.filterTransmittance/(e.fNumber*e.fNumber*t);let h=o!==void 0&&o>0?1/(t*o):void 0;h!==void 0&&e.metering==="highlights"&&a.brightest>0&&(h=Math.min(h,de.HIGHLIGHT_KEPT_AT/(.18*t*a.brightest))),h!==void 0&&e.metering==="highlights"&&n&&n.brightest>0&&(h=Math.min(h,de.ZONE_KEPT_AT/(.18*t*n.brightest)));const d=h!==void 0?Math.min(h,e.maxIso!==void 0?l(e.maxIso):1/0):l(e.iso);Ki.uMediumExposure.value=d,Ki.uPhoneStrength.value=s&&o!==void 0&&o>0?Yr.strengthFor(Yr.MID_GREY*d*t*o):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const e=this.camera;e.updateMatrixWorld();const t=e.fov*Math.PI/180,i=2*Math.atan(Math.tan(t/2)*e.aspect),s=4*Math.asin(Math.sin(i/2)*Math.sin(t/2)),n=new I;let r=0,a=0;for(const{position:o,luminanceCdM2:l,solidAngleSr:h}of this.bodySystem.metered.values())n.copy(o).project(e),n.z<1&&Math.abs(n.x)<=1&&Math.abs(n.y)<=1&&(r+=l*h,a=Math.max(a,l*Math.min(1,h/(de.HIGHLIGHT_SHARE*s))**2));return{mean:r/s,brightest:a}}grain;lampBloomRadiusRad(){if(!this.grain)return;const e=this.camera.fov*Math.PI/180,t=this.grain.frameHeightMm/(2*Math.tan(e/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/t,e/i)}bloomSize=new se;lampTransmittance(e){const t=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+e.position.y;return this.air.transmittance(t,i,e.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(e,t=0){this.decorLitAt={t:e,stepMs:t};const i=this.lampBloomRadiusRad();for(const s of this.decorObjects){const n=this.decorGroups.get(s.id);if(n&&s.lights?.length&&ue.setLights(n,s.lights,e,n.position.distanceTo(this.camera.position),t,this.relativeScale,i,this.lampTransmittance(n),this.camera.position),s.kind!=="streetlight"&&s.kind!=="vehicle")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=s.kind==="vehicle"?o2(s,e):void 0,o=a!==void 0?xl.lamps(a):u0(s,e,this.lastAstronomy?.sun.altitudeDeg);ue.setLit(r,s.kind,o,this.relativeScale,s.lamp);const l=this.streetlightLights.get(s.id);l&&(l.visible=o),a!==void 0&&(this.headlightSettings.set(s.id,a),this.aimDecorBeam(s,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=oe(async()=>{const{HeadlightSystem:e}=await import("./HeadlightSystem-9ywZKJNB.js");return{HeadlightSystem:e}},[],import.meta.url).then(({HeadlightSystem:e})=>{this.headlightSystem??=new e(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const e=this.headlightSystem;if(e){for(const t of this.decorObjects)t.kind==="vehicle"&&e.add(t.id);this.observerHeadlights&&e.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const e of this.decorObjects){const t=this.headlightSettings.get(e.id),i=this.decorGroups.get(e.id);t!==void 0&&i&&this.aimDecorBeam(e,i,t)}this.aimObserverBeam()}}headlightScatterPerM(){const e=this.siteElevationM+this.camera.position.y,t=200,i=this.air.transmittance(e,e,t)[1];return i>0?-Math.log(Math.min(1,i))/t:.05}aimDecorBeam(e,t,i){if(!this.headlightSystem?.has(e.id))return;t.updateMatrixWorld(!0);const s=new I(0,0,-1).transformDirection(t.matrixWorld);if(s.y=0,s.lengthSq()<1e-9)return;s.normalize();const n=ue.sizeOf(e).lengthM,r=t.getWorldPosition(new I).addScaledVector(s,n/2-X6);r.y+=K6;const a=ue.sizeOf(e).widthM;this.headlightSystem.aim(e.id,i,r,s,a*Y6,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(e){this.observerHeadlights=e,e&&this.loadHeadlights(),this.headlightSystem&&(e?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const e=this.observerHeadlights;if(!e||!this.headlightSystem?.has("observer"))return;const t=e.setting==="auto"?this.lastAstronomy?xl.auto(this.lastAstronomy.sun.altitudeDeg):"off":e.setting,i=e.headingDeg*Math.PI/180,s=new I(Math.sin(i),0,-Math.cos(i)),n=new I(s.x*dS,this.camera.position.y-j6,s.z*dS);this.headlightSystem.aim("observer",t,n,s,q6,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(e,t,i,s){const n=ue.bodyOf(t),r=n.children.find(l=>l.userData.emissive);if(!r)return;const a=hS*ue.lampShare(s),o=new bA(16764006,a*this.relativeScale,Z6);s?.colorTemperatureK&&o.color.setRGB(...ue.lampHue(s)),o.userData.candela=a,o.position.copy(r.position).multiply(n.scale),o.castShadow=i,o.shadow.mapSize.set(512,512),o.shadow.bias=-.002,t.add(o),this.streetlightLights.set(e,o)}applyWindowGlow(){const e=this.lastAstronomy;ue.setLitWindowShare(e?Js.share(e.sun.altitudeDeg,e.localHour):0)}setAstronomy(e){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-e.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=e,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(e)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=e.sun,this.buildSky(e.sun),this.buildGround();const t=this.magnitudeLimitOf(e);this.buildStars(e.stars,t),this.placeBodies(e,t),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.applySkyColours(e),this.syncAnimationLoop(),this.render()}static relativeSkyOf(e,t){const i=r=>{const a=nr.luminanceOf(r);if(!(a>0))return[0,0,0];const o=Be.relativeOfResponse(a)/a;return[r[0]*o,r[1]*o,r[2]*o]},s=i(e.zenith),n=i(e.horizon);return{zenith:s,horizon:n,airlight:n,skyIrradiance:[s[0]*Math.PI,s[1]*Math.PI,s[2]*Math.PI],scale:t}}placeBodies(e,t){this.bodiesScale=this.relativeScale,this.sunBeamFraction=ps.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,lS,new ae(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<Xf){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=lS/Rn*(180/Math.PI),s=i/t.sunRadiusDeg,n=Zt(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=Zt(e.moon.altitudeDeg,e.moon.azimuthDeg,1),a=Math.acos(ya(n.x*r.x+n.y*r.y+n.z*r.z,-1,1)),o=a>1e-9?ya(t.separationDeg*s*Ti/a,0,2):0,l=Math.sin(a),[h,d]=a>1e-9?[Math.sin((1-o)*a)/l,Math.sin(o*a)/l]:[1,0],u={x:n.x*h+r.x*d,y:n.y*h+r.y*d,z:n.z*h+r.z*d},p=t.moonRadiusDeg*s;this.eclipseDiscs={sun:new I(n.x,n.y,n.z).normalize(),moon:new I(u.x,u.y,u.z).normalize(),sunRadiusRad:i*Ti,moonRadiusRad:p*Ti};const f=.01,m=(b,w)=>Zt(e.sun.altitudeDeg+b,e.sun.azimuthDeg+w,1),v={x:m(f,0).x-m(-f,0).x,y:m(f,0).y-m(-f,0).y,z:m(f,0).z-m(-f,0).z},g={x:m(0,f).x-m(0,-f).x,y:m(0,f).y-m(0,-f).y,z:m(0,f).z-m(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:s,up:v,right:g}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Sh(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(n,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(e){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(e,this.magnitudeLimitOf(e)),this.applyDazzleStrength(),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.updateBeams());const t=this.scatteredSky?.ambient??de.relativeSkyOf(Zb(e.sun.altitudeDeg),this.relativeScale),i=t,s=this.lightUnderClouds(e),n=r=>s?[0,1,2].map(a=>r[a]*s.through+s.radiance[a]*(1-s.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=n(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),ze.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??hS)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(e,i.zenith),this.applyAir(),this.buildLunarDiffraction(e.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(e){const t=this.scatteredSky?.ready?this.scatteredSky:void 0;if(e.altitudeDeg<-.5||!t){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,s=(i===void 0?Ze.DEFAULT_AEROSOL_OPTICAL_DEPTH:yo.opticalDepth(i))*Ze.aerosolDensity(this.siteElevationM+this.observerElevationM),n=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),a=Vt.aureoleScale(s,Vt.airMass(e.altitudeDeg))*n,o=Vt.coronaScale(r),l=Vt.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),a.toExponential(2),o.toExponential(2),Math.log10(Math.max(t.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new a1,this.celestialGroup.add(this.lunarDiffraction.object));const d=Vt.profile(Vt.HAZE_COARSE_MODE),u=Vt.profile(Vt.CLOUD_DROPLETS),p=CP(e.altitudeDeg),f=new Float32Array(Vt.STEPS*3);let m=0;for(let w=0;w<Vt.STEPS;w++){const y=w*3,M=[0,1,2].map(E=>l*p[E]*(a*d[y+E]+o*u[y+E])),S=nr.shown(M,nr.luminanceOf(M),(E,x)=>t.relativeOfLuminance(E,x));f.set(S,y),m=Math.max(m,nr.response(S))}const{x:v,y:g,z:b}=Zt(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:v,y:g,z:b}:void 0,f)}applyAir(){this.scene.fog instanceof pc||(this.scene.fog=new pc),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(e,t,i){const s=this.camera.position;return this.air.transmittance(this.siteElevationM+s.y,this.siteElevationM+t,Math.hypot(e-s.x,t-s.y,i-s.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,s]=this.air.transmittance(e,e,de.UMBRA_PATH_M),n=.2126*t+.7152*i+.0722*s;return n>0?[(.4124*t+.3576*i+.1805*s)/n,1,(.0193*t+.1192*i+.9505*s)/n]:[.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:ps.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?ps.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction)},flare:this.skyFlare}}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?eN:Q6),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 e6(qg),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Ta(-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,s)=>this.arrivingIlluminance(i,s,1)),this.render()}setReentries(e){if(e.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new un,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Ta(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,s=>this.cloudTransmission(s),(s,n)=>this.arrivingIlluminance(s,n,1)),this.emitterLights.set("reentries",[],e.map(s=>this.farEmitterOf(s.head,s.magnitude)).filter(s=>s!==void 0)),this.refreshSkyFlare();const i=new Set;for(const s of e){const n=`reentry:${s.reentryId}:${s.fragmentId}`,{x:r,y:a,z:o}=Zt(s.head.altitudeDeg,s.head.azimuthDeg,Rn);this.setGlare(n,r,a,o,this.arrivingIlluminance(s.head,s.magnitude,this.cloudTransmission(s.head)),0,de.POINT_VEIL_HOLD_DEG),i.add(n)}for(const s of[...this.glareSprites.keys()])s.startsWith("reentry:")&&!i.has(s)&&this.disposeGlare(s);this.render()}setLaunchPlumes(e){e.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new Ri,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(e,this.relativeScale,t=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),t=>this.cloudTransmission(t)),this.render())}pickPlumeAt(e,t){if(!this.plumeSystem?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,s=this.plumeSystem.pickAt(i,de.BEAM_PICK_PIXELS*this.contrailPixelRad(),this.skyLightTowards(i));return s&&this.groundHides(e,t)?void 0:s}get plumePuffCount(){return this.plumeSystem?.count??0}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,s=Math.cos(gf*this.camera.fov*Math.PI/180);let n,r=s;const a=new I;for(const[o,l]of this.decorGroups){if(!l.visible||!o.startsWith(tn.ID_PREFIX))continue;a.copy(l.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,n=o)}return n&&!this.groundHides(e,t)?n:void 0}pickReentryAt(e,t){if(!this.reentrySystem?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(gf*this.camera.fov*Math.PI/180),s=this.reentrySystem.nearest(this.raycaster.ray.direction,i);return s&&this.groundHides(e,t)?void 0:s}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(gf*this.camera.fov*Math.PI/180),s=this.satelliteField.nearest(this.raycaster.ray.direction,i);return s&&this.groundHides(e,t)?void 0:s}updateCelestialLight(e,t){const i=this.relativeScale,s=e.sun.altitudeDeg>=Hd,n=!s&&e.moon.altitudeDeg>=Hd,r=s?e.sun:e.moon,a=[0,0,0],o=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Ti)),l=this.siteElevationM+this.observerElevationM;let h=r,d=s||n?rS.directFraction(r.altitudeDeg,l):0;s&&d<=0&&e.moon.altitudeDeg>=Hd&&(h=e.moon,d=rS.directFraction(h.altitudeDeg,l));const u=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Ti)),p=s||n?this.cloudTransmission(r):1,f=-Math.log(Math.max(p,1e-6)),m=Math.max(0,1/(1+.1125*f)-p),v=[0,0,0];if(s||n){const S=Vt.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let R=0;R<3;R++)v[R]=S*E[R]*m*o,this.cloudBeam[R]=S*E[R];const{x,y:A,z:D}=Zt(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(x,A,D),d>0){const R=Vt.illuminanceOf(h.magnitude)*i,L=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),N=h===r?p:this.cloudTransmission(h);for(let k=0;k<3;k++)a[k]=R*L[k]*N*d}}else this.cloudBeam.fill(0);const g=this.surroundings;if(g)this.skyLight.color.setRGB(g.up[0]*i,g.up[1]*i,g.up[2]*i),this.skyLight.groundColor.setRGB(g.down[0]*i,g.down[1]*i,g.down[2]*i);else{const S=this.skyCloudTransmission(),E=t.skyIrradiance,x=[0,1,2].map(D=>E[D]*S+v[D]);this.skyLight.color.setRGB(x[0],x[1],x[2]);const A=rt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(x[0]+a[0]*u),A*(x[1]+a[1]*u),A*(x[2]+a[2]*u))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===e.sun?[a[0],a[1],a[2]]:[0,0,0],!s&&!n||d<=0){this.celestialLight.intensity=0;return}const{x:b,y:w,z:y}=Zt(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(b,w,y),this.celestialLight.shadow.normalBias=Zg*ya(w/U6,.1,1),this.placeShadowFrustum();const M=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/M,a[1]/M,a[2]/M),this.celestialLight.intensity=M,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(e,t){const i=this.lastAstronomy?.sun,s=[0,0,0];if(i){const n=zn.litFraction(t.sunElevationDeg,t.heightM);if(n>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),a=Vt.illuminanceOf(i.magnitude)*this.relativeScale,o=t.heightM>=de.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)s[l]=Math.max(0,a*r[l]*n*o-this.sceneSunBeam[l])}}e.traverse(n=>{const r=n.material;if(!(r instanceof Br||r instanceof el)||n.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=de.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*s[0]*a,r.color.g*s[1]*a,r.color.b*s[2]*a)})}lightDirection=new I(0,1,0);placeShadowFrustum(){const e=this.lightDirection,t=this.celestialLight.shadow.camera,i=(t.right-t.left)/this.celestialLight.shadow.mapSize.x,s=this.shadowAxisX.crossVectors(this.shadowUp,e);s.lengthSq()<1e-8&&s.set(1,0,0),s.normalize();const n=this.shadowAxisY.crossVectors(e,s).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*i},o=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(s,a(s)).addScaledVector(n,a(n));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(o).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToCabin(e){if(e===this.cabinShadow)return;this.cabinShadow=e;const t=this.celestialLight.shadow;if(!e){this.shadowHalfExtentM=-1;return}const i=t.camera,s=F6;i.left=-s,i.right=s,i.top=s,i.bottom=-s,this.shadowHalfExtentM=s,this.shadowLightDistanceM=vf+5,i.near=this.shadowLightDistanceM-vf,i.far=this.shadowLightDistanceM+vf,i.updateProjectionMatrix(),t.bias=-.004/(2*vf),t.mapSize.x!==2048&&(t.mapSize.set(2048,2048),t.map?.dispose(),t.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(e){for(const t of e)t.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[]){const r=n;r.isMeshStandardMaterial&&r.envMapIntensity!==de.CABIN_SKY_SHARE&&(r.envMapIntensity=de.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(N6,Math.max(Qa,Math.ceil(e*1.25/20)*20));if(t===this.shadowHalfExtentM)return;this.shadowHalfExtentM=t;const i=this.celestialLight.shadow,s=i.camera;s.left=-t,s.right=t,s.top=t,s.bottom=-t;const n=Math.max(ih,t*(ih/Qa));this.shadowLightDistanceM=Math.max(Rn,n+10),s.near=this.shadowLightDistanceM-n,s.far=this.shadowLightDistanceM+n,s.updateProjectionMatrix(),i.bias=-jg/(2*n);const r=t>2*Qa?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=Qa;shadowLightDistanceM=Rn;shadowUp=new I(0,1,0);shadowAxisX=new I;shadowAxisY=new I;shadowWorld=new I;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const s=i*Ti,n=Math.sin(s)*Math.cos(s)*2;for(let r=0;r<360;r+=60)e+=n*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),t+=n}return e/t}cloudBeam=[0,0,0];cloudBeamDirection=new I(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Be.semiSaturation(Be.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new Vs,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&&(this.meteorSystem.update(e),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(t=>this.farEmitterOf(t,t.magnitude)).filter(t=>t!==void 0)),this.refreshSkyFlare())}farEmitterOf(e,t){if(!(e.altitudeDeg>0)||!Number.isFinite(t))return;const i=Math.max(this.relativeScale,1e-30),s=this.arrivingIlluminance(e,t,this.cloudTransmission(e)),{x:n,y:r,z:a}=Zt(e.altitudeDeg,e.azimuthDeg,1);return{direction:new I(n,r,a),lux:[s[0]/i,s[1]/i,s[2]/i],sky:{altitudeDeg:e.altitudeDeg,azimuthDeg:e.azimuthDeg,magnitude:t}}}skyFlare;refreshSkyFlare(){const e=this.emitterLights.brightestInSky;e===this.skyFlare||!e&&!this.skyFlare||(this.skyFlare=e,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(e,t){this.projectionKind=e.projection,this.grain=e.detailUm!==void 0&&e.frame?{detailUm:e.detailUm,frameHeightMm:e.frame.heightMm}:void 0;const i=Qt.starPointsOf(e,t);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(e){const t=pe.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return Ta(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 s=Number.isFinite(e)?e:0;this.instrumentMagnitudeGain=s-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(t,s,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const e=this.compileOffThread().then(()=>{this.compiling===e&&(this.compiling=void 0,this.render())});this.compiling=e;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{const e=this.usableGhostPass();e?(this.exposureSubjectBounds=[],this.renderOnce(e.frame),e.develop(this.renderer,e.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const e=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const t=this.renderer.properties,i=performance.now()+de.COMPILE_WAIT_MS;return new Promise(s=>{const n=()=>{if(this.contextReleased)return s();for(const r of e){const a=t.get(r)?.currentProgram;(!a||a.isReady())&&e.delete(r)}e.size===0||performance.now()>i?s():setTimeout(n,10)};n()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(e){if(this.animationsRunning){const t=this.lastFrameTimeMs===void 0?0:e-this.lastFrameTimeMs;this.lastFrameTimeMs=e,this.hasAnimations()&&this.animate(e,t);const i=this.resolution.ratioFor(e,t);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(e,t,i){const s=[];for(const n of this.decorObjects){if(n.kind!=="aircraft"&&n.kind!=="vehicle"||n.observerSide!==void 0&&Sl(n.kind))continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=Mr(n,e),o=a.eastM+t.x+i.x,l=-a.northM+t.z+i.z,h=ue.sizeOf(n),d=Math.max(h.widthM,h.lengthM)/2;Math.hypot(o,l)<d&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<d&&s.push(r)}return this.cabinGroups=s,s}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(e=!1){this.reflections??=new yn(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 sr),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(o=>o!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(o=>o.name.startsWith("body:")),...[this.meteorSystem?.object,this.reentrySystem?.object].filter(o=>o!==void 0)],s=this.relativeScale,n=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],n,i,o=>this.measureSurroundings(o,s,n,r),e?0:yn.REFRESH_MS);a===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},a))}static adaptingLuminance(e,t){const i=(.2126*t[0]+.7152*t[1]+.0722*t[2])/Math.PI;return Math.max(e,de.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(e,t,i,s){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new wh,this.framePhotograph={texture:e,scale:t,atMs:s};const r=[n.sun,n.moon].filter(a=>a.altitudeDeg>-2).map(a=>Zt(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,r,a=>{const o=f=>f.map(m=>m/t),l=this.surroundings,h={up:o(a.up),down:o(a.down)},d=(f,m)=>f.some((v,g)=>Math.abs(v-m[g])>.03*Math.max(Math.abs(v),Math.abs(m[g]),1e-12)),u=!l||d(l.up,h.up)||d(l.down,h.down);u&&(this.surroundings=h),this.eyeSettledVersion=-1;const p=this.scatteredSky?.adaptToSurroundings(de.adaptingLuminance(Math.exp(a.logAverage)/t,h.down))??!1;if(!u&&!p){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>=Hd?e.sun:e.moon.altitudeDeg>=Hd?e.moon:void 0;if(!i)return;const s=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[t.up[0]*s,t.up[1]*s,t.up[2]*s]}}probeIrradiance;meterFrame(){const e=this.framePhotograph;if(!this.medium?.autoExposure||!e)return;this.frameMeter??=new Kr;const t=this.lastAstronomy?.sun,i=t&&t.altitudeDeg>-2?Zt(t.altitudeDeg,t.azimuthDeg,1):void 0,s=this.medium.exposureFollowMs??de.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,e.texture,this.camera,i,n=>{const r={mean:n.mean/e.scale,brightest:n.brightest/e.scale},a=this.frameLight,o=e.atMs,l=a?o-a.atMs:1/0,h=l<0||l>de.EXPOSURE_JUMP_MS,d=h||l===0&&a?.jumped?1:1-Math.exp(-l/s),u=(m,v)=>m>0&&v>0?m*(v/m)**d:v,p={mean:u(a?.mean??0,r.mean),brightest:u(a?.brightest??0,r.brightest),atMs:o,jumped:h||l===0&&(a?.jumped??!1)};this.frameLight=p;const f=(m,v)=>Math.abs(m-v)>.01*Math.max(m,v);(!a||f(a.mean,p.mean)||f(a.brightest,p.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Ki.uRetinaOn.value=0,this.medium)return;const e=[];for(const a of this.emitterLights.farEmitters){const o=this.screenPointOf(a.direction);!o||Math.abs(o.ndcX)>1.2||Math.abs(o.ndcY)>1.2||e.push({ndcX:o.ndcX,ndcY:o.ndcY,lux:nr.luminanceOf(a.lux)})}const t=this.renderer.getDrawingBufferSize(this.retinaSize),i=t.x/Math.max(t.y,1),s={width:this.camera.fov*i,height:this.camera.fov},n=this.retina?.atMs;if((n===void 0||this.recordingTimeMs<n||this.recordingTimeMs-n>mt.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new mt,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),s,this.retinaHistoryOf);else{if(!this.retina&&e.length===0)return;this.retina??=new mt,this.retina.advance(this.recordingTimeMs,e,s)}this.retina.any&&(Ki.uRetina.value=this.retina.texture,Ki.uRetinaOn.value=1,Ki.uRetinaViewport.value.copy(t))}retinaSize=new se;retinaHistory;setRetinaHistory(e,t){this.retinaHistory=e,this.retinaHistoryOf=t}retinaHistoryOf;historicBleachingAt(e,t){const i=this.retinaHistory?.(e);if(!i||i.views.length===0)return[];const s=i.pose,n=this.historicQuaternion.setFromEuler(this.historicEuler.set((s?.pitchDeg??0)*Ti,-(s?.headingDeg??0)*Ti,(s?.rollDeg??0)*Ti,"YXZ")).invert(),r=s?.fovDeg??this.camera.fov,a=[];for(const o of i.views){const l=this.farEmitterOf(o.head,o.magnitude);if(!l)continue;const h=this.screenPointIn(this.historicDirection.copy(l.direction).applyQuaternion(n),r,t);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||a.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:nr.luminanceOf(l.lux)})}return a}historicQuaternion=new Tn;historicEuler=new Va;historicDirection=new I;pickAfterimageAt(e,t){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(e,t)<de.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(e){this.recordingTimeMs=e}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(e){const t=[];for(const i of e)i.traverse(s=>{s.userData.emissive===!0&&t.push(s)});return t}surroundings;animate(e,t){const i=Math.min(t/1e3,bN);this.twinkleSeconds=e/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(e/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=e/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(e){this.resolution.maximum=e,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(e){this.renderer.setPixelRatio(e),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(e,t){const i=t?Math.max(1,Math.round(e)):1;if(i===this.exposureInstants&&(i===1||t===this.exposureInstantAt)){this.exposureInstantAt=t;return}this.exposureInstants=i,this.exposureInstantAt=t,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(e){if(this.aimBeams(),ue.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();e?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const t=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,o)=>this.directionAtScreenPoint(r,a,o),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[iy]:[],!e)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},tr.INTERVAL_MS)),Ki.uRodShare.value=this.scatteredSky?.rodShare??0,Ki.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const s=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Ki.uHasOverlay.value=s?1:0;const n=s?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,n,e):this.usableFinishPass().render(this.renderer,this.scene,this.camera,n,void 0,e);return}t.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),n,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 sr&&t.userData.pointSource||t instanceof we&&t.userData.skyRibbon)&&e.push(t)}),[...e,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(e=this.camera){this.renderReferencesPass(e),this.renderBodiesOverReferences(e),this.renderPhenomenaPass(e),this.renderHudPass(e)}renderHudPass(e){const t=this.traceSystem?.any&&this.tracesShown;if(!t&&!this.compassSprites.some(n=>n.visible))return;t&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),e.fov);const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(Xg),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}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(XA),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 $n({blending:wc,blendSrc:Na,blendDst:Na,blendSrcAlpha:Na,blendDstAlpha:Na,toneMapped:!1});renderReferencesPass(e){if(!this.references?.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(this.references.layer),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){const i=e.map(s=>{const n=this.documentRelative(s.src);return n===s.src?s:{...s,src:n}});if(this.references){this.references.set(i,void 0,t);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:t},this.referencesLoading??=oe(async()=>{const{ReferenceSystem:s}=await import("./ReferenceSystem-DHPnvAXN.js");return{ReferenceSystem:s}},__vite__mapDeps([10,11]),import.meta.url).then(({ReferenceSystem:s})=>{const n=new s(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=n;for(const[a,o]of this.referenceViews)n.setView(a,o);n.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&n.set(r.references,void 0,r.observerAt),this.render(),n})}referenceAspect(e){return this.references?.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new I)}referenceFailure(e){return this.references?.failureOf(this.documentRelative(e))}setReferencesShown(e){this.referencesShown=e,this.references?.setShown(e),this.render()}setReferenceView(e,t){this.referenceViews.set(e,t),this.references?.setView(e,t),this.render()}renderPhenomenaPass(e){if(!this.phenomena.any)return;e.updateMatrixWorld();const t=this.phenomena.screenBox(e);if(t&&(t.x0>1||t.x1<-1||t.y0>1||t.y1<-1))return;const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const n=t?this.narrowTo(e,t):e,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse)),a=this.phenomena.furthestM;let o=0;for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const d=l.kind!=="crop"&&this.mayHide(h,e,r,a);de.markDecorDepth(h,d),d&&o++}o>0&&(e.layers.set(Kg),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null),e.layers.set(iy),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}phenomenaFrustum=new g0;phenomenaViewProjection=new ft;occluderSphere=new aa;localBounds=new WeakMap;mayHide(e,t,i,s){let n=0;e.traverse(()=>n++);let r=this.localBounds.get(e);if(!r||r.objects!==n){e.updateMatrixWorld(!0);const o=new Ss().setFromObject(e);if(o.isEmpty())return!1;r={sphere:o.getBoundingSphere(new aa).applyMatrix4(new ft().copy(e.matrixWorld).invert()),objects:n},this.localBounds.set(e,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(e.matrixWorld);return a.center.distanceTo(t.position)-a.radius>s?!1:i.intersectsSphere(a)}narrowTo(e,t){const i=this.renderer.getDrawingBufferSize(new se),s=de.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),n=Math.max(0,Math.floor((Math.max(-1,t.x0)+1)/2*i.x-s)),r=Math.max(0,Math.floor((Math.max(-1,t.y0)+1)/2*i.y-s)),a=Math.min(i.x,Math.ceil((Math.min(1,t.x1)+1)/2*i.x+s)),o=Math.min(i.y,Math.ceil((Math.min(1,t.y1)+1)/2*i.y+s)),l=this.narrowCamera.copy(e);return l.setViewOffset(i.x,i.y,n,i.y-o,Math.max(1,a-n),Math.max(1,o-r)),l.updateMatrixWorld(),l}narrowCamera=new nn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new $n({colorWrite:!1,side:qs});static HEAD_TURN_LIMIT_DEG=85;static turnHead(e,t,i){const s=e.getObjectByName("head");if(!s)return;const n=((i-t)%360+540)%360-180,r=Math.max(-85,Math.min(de.HEAD_TURN_LIMIT_DEG,n));s.rotation.y=-r*Ti}static isSolidSurface(e){if(!(e instanceof we))return!0;const t=Array.isArray(e.material)?e.material[0]:e.material;return t.depthWrite!==!1&&t.blending!==zs}static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof we))return;t&&de.isSolidSurface(i)?i.layers.enable(Kg):i.layers.disable(Kg)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new se),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new yP(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 s=performance.now()+de.EXPOSURE_BUDGET_MS,n=de.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const a=this.compassSprites.map(o=>o.visible);for(const o of this.compassSprites)o.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((o,l)=>{o.visible=a[l]})}t.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<s&&r<n);this.restateAt(e,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Ki.uRodShare.value=this.scatteredSky?.rodShare??0,Ki.uHasOverlay.value=1,Ki.uRelativeScale.value=this.relativeScale,this.applyMedium();const e=this.exposureInstants/this.exposureInstantsDone,t=this.usableGhostPass();if(t&&this.exposureAccumulation?t.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,e,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,e),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Er,s=new Ar(-1,1,1,-1,0,2),n=yf/(pS*Math.tan(fS*Ti/2));for(const a of this.compassSprites){if(!a.visible)continue;const o=a.getWorldPosition(new I).sub(this.camera.position).normalize(),l=this.screenPointOf(o);if(!l)continue;const h=new Rd(a.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(n/this.camera.aspect,n,1),i.add(h)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,s)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const e=[],t=new Ss,i=new I,s=this.camera.getWorldDirection(new I),n=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...n,...r]){if(!a?.visible||(t.setFromObject(a),t.isEmpty())||t.distanceToPoint(this.camera.position)<de.MAP_SUBJECT_NEAREST_M)continue;let o=1/0,l=-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(s)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const v=(m.ndcX+1)/2,g=(1-m.ndcY)/2;o=Math.min(o,v),l=Math.max(l,v),h=Math.min(h,g),d=Math.max(d,g)}o=Math.max(o,0),l=Math.min(l,1),h=Math.max(h,0),d=Math.min(d,1),l>=o&&d>=h&&e.push({x:o,y:h,width:l-o,height:d-h})}return e}restateAt(e,t){this.restatingExposure=!0;try{e(t)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(e){const t=this.lensOptics;this.lensOptics=e,(t===void 0!=(e===void 0)||t&&e&&(t.focalLengthMm!==e.focalLengthMm||t.fNumber!==e.fNumber||t.focusDistance!==e.focusDistance||t.frameHeightMm!==e.frameHeightMm))&&(e&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.render())}usableDepthOfFieldPass(){const e=this.lensOptics;if(!e)return;const t=this.renderer.getDrawingBufferSize(new se),i=Math.max(1,Math.round(t.x)),s=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new du(i,s)),this.depthOfFieldPass.resize(i,s),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}setLensGhosts(e){JSON.stringify(e)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=e,e.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(e,t){return this.ghostPass?.holdsPictureAt(this.renderer,e,t)??!1}pickGhostAt(e,t){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,e,t,this.ghostOptics,Ki.uMediumExposure.value)}pickDropAt(e,t){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,e,t)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const e=this.renderer.getDrawingBufferSize(new se);return this.ghostPass?this.ghostPass.resize(e.x,e.y):this.ghostPass=new ws(e.x,e.y),this.ghostPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new se);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new r1(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new se);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new $i(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){this.aimStraightAtScreenPoint(e,t,i),e===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(e,s=>{const n=de.firstSolid(e.intersectObjects(this.cabinGroups,!0));return!n||n.distance>=s-.001||this.mirrors.isMirror(n.object)})}aimStraightAtScreenPoint(e,t,i){const s=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!s){e.setFromCamera(new se(t,i),this.camera);return}const n=s.directionFor(t,i,this.camera.fov);this.camera.updateMatrixWorld(),e.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),e.ray.direction.set(n.x,n.y,n.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 I)}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),s=i.x/Math.max(i.y,1);return this.screenPointIn(t,this.camera.fov,s)}screenPointIn(e,t,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return $i.ndcFor(e,t,i);if(e.z>=0)return;const s=Math.tan(t/2*Ti);return{ndcX:e.x/-e.z/(i*s),ndcY:e.y/-e.z/s}}screenPointScratch=new I;screenPointQuaternion=new Tn;screenPointSize=new se;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 s=this.renderer.domElement.width,n=this.renderer.domElement.height;e.uniforms.uResolution.value.set(s,n),e.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const e=this.lensFlare;if(!e||!e.mesh.visible)return;const t=this.sunDiscRadiance.map(r=>Math.max(0,r-de.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(t[1]<=0)return;const i=Math.tan(e.uniforms.uSourceRadiusDeg.value*Math.PI/180)/e.uniforms.uTanHalfFov.value/2,s=Math.PI*i*i,n=e.uniforms.uLensPosition.value;return{x:n.x,y:n.y,radius:i,flux:[t[0]*s,t[1]*s,t[2]*s]}}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 s=this.renderer.getDrawingBufferSize(this.screenPointSize);e.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),e.uniforms.uResolution.value.set(s.x,s.y),e.uniforms.uEquidistant.value=1,e.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const n=this.renderer.autoClear;this.renderer.autoClear=!1,e.mesh.visible=!0,e.mesh.layers.enable(aS),this.camera.layers.set(aS),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),e.mesh.visible=!1,e.uniforms.uEquidistant.value=0,this.renderer.autoClear=n}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let e=0;for(const t of gS)this.isSunOccluded(t[0],t[1])||e++;return e/gS.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){return this.isOccludedToward(this.sunWorldPosition,e,t)}isOccludedToward(e,t=0,i=0){const s=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&s.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(e).sub(this.camera.position),r=n.length();if(n.normalize(),t!==0||i!==0){const l=Math.PI/180,h=this.sunOcclusionRightScratch.set(n.z,0,-n.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const d=this.sunOcclusionUpScratch.crossVectors(h,n).normalize();n.addScaledVector(h,t*l).addScaledVector(d,i*l).normalize()}if(this.groundBlocks(this.camera.position,n,r)||this.cabinMask.hides(n))return!0;const a=this.cabinMask.any?s.filter(l=>!this.cabinGroups.includes(l)):s;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const o=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(l=>!(l.object.material instanceof xo));return o!==void 0&&o.distance<r}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let e=!1;for(const t of this.glareSprites.values()){if(!t.mesh.visible)continue;e||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),e=!0);const i=t.mesh.getWorldPosition(this.veilTargetScratch),s=t.mesh.material.uniforms.uSourceDeg.value,n=s>.05?de.VEIL_SAMPLES:de.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,o]of n)this.isOccludedToward(i,a*s,o*s)||r++;t.share=r/n.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new Zn;veilTargetScratch=new I;groundBlocks(e,t,i,s=0){const n=this.groundMesh;if(n&&t.y<0){const v=(n.position.y-e.y)/t.y;if(v>s&&v<i){const g=e.x+t.x*v-n.position.x,b=e.z+t.z*v-n.position.z;if(Math.hypot(g,b)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),o=Math.round(Math.sqrt(a.count));if(o<2||o*o!==a.count)return!1;const l=[r.position.x+a.getX(0),r.position.x+a.getX(o-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((o-1)*o)],d=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(o-1);if(!(d>0))return!1;let u=s,p=i;for(const[v,g,b]of[[e.x,t.x,l],[e.z,t.z,h]]){const w=Math.min(b[0],b[1]),y=Math.max(b[0],b[1]);if(Math.abs(g)<1e-12){if(v<w||v>y)return!1;continue}const M=(w-v)/g,S=(y-v)/g;u=Math.max(u,Math.min(M,S)),p=Math.min(p,Math.max(M,S))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),m=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let v=0;v<=m;v++){const g=u+(p-u)*v/m,b=e.x+t.x*g,w=e.y+t.y*g,y=e.z+t.z*g;if(w<=this.groundYUnder(b,y))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=ff;let s,n;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const o=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(l=>de.isSolidSurface(l.object));o&&(r.occludesSourceIds?.includes(i)?s=s===void 0?o.distance:Math.max(s,o.distance):n=n===void 0?o.distance:Math.min(n,o.distance))}return{behindM:s,inFrontM:n}}pickBodyAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.origin,s=this.raycaster.ray.direction,n=z6*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,d])=>{const u=d.getWorldPosition(new I).sub(i);return{key:h,direction:u.clone().normalize(),radiusRad:Math.atan2(d.scale.x/2,u.length())}}),a=this.eclipseDiscs,o=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],l=de.nearestBody(s,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...o],n);if(l)return this.groundHides(e,t)?void 0:l}pickOpticsAt(e,t){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(e,t)?i:void 0}static nearestBody(e,t,i){let s,n=1/0,r=1/0,a=!1;for(const o of t){const l=Math.acos(ya(o.direction.dot(e),-1,1))-o.radiusRad;if(l>i)continue;const h=l<=0,d=n<=0,u=o.inFront===!0;(h!==d?h:h?u!==a?u:o.radiusRad<r:l<n)&&(s=o.key,n=l,r=o.radiusRad,a=u)}return s}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 s=this.raycaster.ray.direction,n=this.raycaster.ray.origin,r=P6*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],o=a.length>0?de.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const d=new Ss,u=new I;for(const p of i){if(d.setFromObject(p),d.isEmpty())continue;d.getCenter(u);const f=d.getSize(new I).length()/2,m=u.clone().sub(n),v=m.length();if(v===0||m.dot(s)<=0||o!==void 0&&o<v-f)continue;const g=Math.acos(Math.min(1,m.normalize().dot(s))),b=Math.atan(f/v);if(b>r){const w=this.raycaster.intersectObject(p,!0)[0];if(!w||o!==void 0&&o<w.distance)continue}else if(g>r)continue;b<h&&(h=b,l=p.name.slice(5))}return l}pickStarAt(e,t){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,s=Math.cos(gf*this.camera.fov*Math.PI/180);let n,r=s;for(const a of this.namedStars){const o=a.direction.dot(i);o>r&&(r=o,n={star:a.star,altitudeDeg:a.altitudeDeg})}return n&&this.groundHides(e,t)?void 0:n}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,ff)}bodyScreenBox(e){const t=this.bodySystem.boxOf(e,this.bodyBoxScratch);if(!t)return;let i=1/0,s=1/0,n=-1/0,r=-1/0;for(let a=0;a<8;a++){const o=this.bodyCornerScratch.set(a&1?t.max.x:t.min.x,a&2?t.max.y:t.min.y,a&4?t.max.z:t.min.z),l=this.screenPointOf(o.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),n=Math.max(n,l.ndcX),s=Math.min(s,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:i,minY:s,maxX:n,maxY:r}}bodyBoxScratch=new Ss;bodyCornerScratch=new I;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 s=1/0,n=1/0,r=-1/0,a=-1/0;for(let o=0;o<8;o++){const l=this.bodyCornerScratch.set(o&1?i.max.x:i.min.x,o&2?i.max.y:i.min.y,o&4?i.max.z:i.min.z),h=this.screenPointOf(l.sub(this.camera.position).normalize());if(!h)return;s=Math.min(s,h.ndcX),r=Math.max(r,h.ndcX),n=Math.min(n,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:s,minY:n,maxX:r,maxY:a}}decorDrawnOffset(e){return this.lampNudges.get(e)}decorGroundPointAt(e,t,i,s=0){const n=this.decorGroups.get(e);if(!n)return;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(n.position.y+s)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(e){const t=this.decorGroups.get(e);return t?Math.hypot(t.position.x-this.camera.position.x,t.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(e){const t=this.decorGroups.get(e);return t?t.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Ti/2):0}decorGrabHeightAt(e,t,i){const s=this.decorGroups.get(e);if(!s)return 0;const n=this.bodyBoxScratch.setFromObject(s).max.y-s.position.y;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.decorHitScratch.set(this.camera.position.x-s.position.x,0,this.camera.position.z-s.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,s.position),o=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return o?Math.min(Math.max(o.y-s.position.y,0),Math.max(n,0)):0}decorPlaneScratch=new ro;decorHitScratch=new I;static firstSolid(e){return e.find(t=>{const i=t.object.material;return!(Array.isArray(i)?i:[i]).some(n=>n&&(n.transparent&&n.opacity<de.SEE_THROUGH_BELOW||n instanceof xo))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],s=de.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!s)return;const n=this.bodySystem.pickHit(this.raycaster);if(n!==void 0&&n.distance<s.distance)return;let r=s.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(e,t){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const s=this.raycaster.ray;i.group.updateMatrixWorld();const n=new fd().copy(s).applyMatrix4(new ft().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(u,p)=>{const f=new I(u,0,p).applyMatrix4(r);return this.groundYUnder(f.x,f.z)-r.elements[13]};if(!i.mayMeet(n.origin,n.direction,a,de.RAILWAY_PICK_ABOVE_M))return;const o=de.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!o||this.terrainMesh&&this.groundBlocks(s.origin,s.direction,o.distance-de.RAILWAY_GROUND_MARGIN_M,ff))return;const l=i.group.worldToLocal(o.point.clone()),h=i.lineAt(l.x,l.z);if(!h)return;const d=i.contactHeightM(h);return{line:h,distanceM:o.distance,...d!==void 0?{contactM:d}:{}}}pickBeamAt(e,t){const i=this.beamSystem;if(!i||i.segmentCount===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const s=this.raycaster.ray,n=i.pickAt(s.origin,s.direction,de.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!n||this.terrainMesh&&this.groundBlocks(s.origin,s.direction,n.distanceM-1,ff))return;const r=de.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<n.distanceM))return n}skyLightTowards(e){const t=this.scatteredSky?.ambient;if(!t)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],s=Math.hypot(e.x,e.y,e.z)||1,n=Math.max(0,Math.min(1,e.y/s));return i(t.horizon)+(i(t.zenith)-i(t.horizon))*Math.sqrt(n)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0,this.beamSystem?.dispose(),this.beamSystem=void 0,this.beamSystemLoading=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.reentrySystem?.dispose(),this.reentrySystem=void 0,this.plumeSystem?.dispose(),this.plumeSystem=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const e of this.bodyMeshes.values())this.disposeMesh(e);this.bodyMeshes.clear(),this.novaKeys.clear();for(const e of[...this.hitAreas.keys()])this.disposeHitArea(e);for(const e of[...this.glareSprites.keys()])this.disposeGlare(e);this.disposeCompassLabels();for(const e of this.decorGroups.values())ue.dispose(e);this.decorGroups.clear(),this.mirrors.clear(),this.decorLamps=[],this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const 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 s=this.animationsRunning;this.animationsRunning=e,this.framesDriven=i,e&&!s&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const n=!e&&this.renderer.getPixelRatio()!==this.resolution.maximum;n&&this.applyPixelRatio(this.resolution.maximum),!e&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!e||this.frameDirty)&&this.render(),n&&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 I;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const e=this.lastAstronomy?.sun;return e!==void 0&&e.altitudeDeg<de.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 As(pf,32,16),i=t.attributes.position,s=t.getAttribute("color")??new Mt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:o}=FA(i.getX(r),i.getY(r),i.getZ(r)),l=DP(a,o,e.azimuthDeg,e.altitudeDeg);s.setXYZ(r,l[0],l[1],l[2])}if(s.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",s);const n=new $n({vertexColors:!0,side:is,fog:!1,depthWrite:!1});this.skyGradientMaterial=n,this.skyMesh=new we(t,n),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=oS(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Yy(this.groundRadius,48),i=new Br({color:new ae(Yg,Yg,Yg),fog:!0});pc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new we(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 s=0;if(i){const n=i.geometry.getAttribute("position");s=1/0;for(let r=0;r<n.count;r++)Math.abs(n.getX(r)+i.position.x)>600||Math.abs(n.getZ(r)+i.position.z)>600||(s=Math.min(s,n.getY(r)+i.position.y));s=Number.isFinite(s)?Math.min(0,s)-1:0}this.groundMesh.position.y=s,this.groundMesh.renderOrder=0,e.depthTest=!0,e.needsUpdate=!0}cloudTransmission(e,t=!1){const i=`${e.altitudeDeg.toFixed(1)}:${e.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(t?":water":""),s=this.cloudTransmissionMemo.get(i);if(s!==void 0)return s;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const n=this.computeCloudTransmission(e,t);return this.cloudTransmissionMemo.set(i,n),n}cloudTransmissionMemo=new Map;computeCloudTransmission(e,t=!1){const i=Zt(e.altitudeDeg,e.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,t);let s=1;const n=this.lowerCloudCover();n>0&&(s*=1-Bt.alphaAt(i,Math.abs(this.cloudLayerOffset()),n,this.cloudFieldOffset)*G6);const r=t?0:this.weather.highCloudCover??0;return r>0&&(s*=1-Bt.iceAlphaAt(i,bf,r,this.cloudFieldOffset)*V6),Math.max(0,Math.min(1,s))}setBodyMesh(e,t,i,s,n){if(t.altitudeDeg<Xf){this.disposeMesh(this.bodyMeshes.get(e)),this.bodyMeshes.delete(e),this.disposeHitArea(e),this.disposeGlare(e),e==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:o}=Zt(t.altitudeDeg,t.azimuthDeg,Rn),l=this.cloudTransmission(t),h=this.arrivingIlluminance(t,n,l),d=de.unitLuminance(s);let u=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/Rn)**2,f=[0,1,2].map(v=>d[v]*h[v]/(this.sunBeamFraction*p));this.sunDiscRadiance=f;const m=f.map(v=>Math.min(de.BRIGHTEST_RELATIVE,v));u instanceof we||(this.disposeMesh(u),u=new we(new As(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)),u.material.color.setRGB(m[0],m[1],m[2]),u.scale.setScalar(i)}else{if(!(u instanceof sr)){this.disposeMesh(u);const m=new xt;m.setAttribute("position",new wt(new Float32Array(3),3)),m.setAttribute("color",new wt(new Float32Array(3),3)),u=new sr(m,ze.material(dc[dc.length-1].size,!1)),ze.track(u),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)}const p=u.geometry.getAttribute("color"),f=e.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*h[0]*f,d[1]*h[1]*f,d[2]*h[2]*f),p.needsUpdate=!0}if(u.position.set(r,a,o),this.setHitArea(e,r,a,o,i),e==="sun"&&(this.sunArriving=h),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,a,o,h,i/Rn*(180/Math.PI),de.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,a*p+this.celestialGroup.position.y,o*p),this.lensFlare||(this.lensFlare=QP(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<Xf){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:s,y:n,z:r}=Zt(e.altitudeDeg,e.azimuthDeg,Rn),a=this.cloudTransmission(e),o=this.arrivingIlluminance(e,e.magnitude,a),l=e.radiusDeg??Sn.MEAN_RADIUS_DEG,h=Rn*Math.tan(l*Ti),d=Math.max(ya(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Rn)**2,u=new ae(...o.map(m=>Math.min(de.BRIGHTEST_RELATIVE,m/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(ya(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof Rd?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=LS(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new Rd(new Hf({map:LS(e.phase),color:u,fog:!1,blending:zs,depthWrite:!1})),f.userData.phaseKey=p,this.celestialGroup.add(f),this.bodyMeshes.set(i,f)),f.scale.set(h*2,h*2,1),f.position.set(s,n,r),this.setHitArea(i,s,n,r,h),this.setGlare(i,s,n,r,o,l)}bentLight(e,t,i=B6){const[s,n,r]=this.arrivingIlluminance(e,t,1),a=Math.max(n,1e-30);return{scale:n/i,tint:[s/a,1,r/a]}}static litBySky(e,t){return de.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new ae;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,ze.CONE_SOLID_ANGLE/t)}pointScratch=new se;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(e,t,i){const s=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),n=Vt.illuminanceOf(t)*i*this.relativeScale;return[s[0]*n,s[1]*n,s[2]*n]}static unitLuminance(e){const t=nr.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,s,n){let r=this.hitAreas.get(e);if(!r){const o=new Hf({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Rd(o),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,s);const a=n*2;r.scale.set(a,a,1)}disposeHitArea(e){const t=this.hitAreas.get(e);t&&(t.removeFromParent(),t.material.dispose(),this.hitAreas.delete(e))}setGlare(e,t,i,s,n,r,a=0){if(Fs.radiusDeg(Fs.K*Math.max(...n))<=Math.max(r,a)){this.disposeGlare(e);return}let o=this.glareSprites.get(e);o||(o=new Fs(`veil:${e}`),this.celestialGroup.add(o.mesh),this.glareSprites.set(e,o)),o.shine({x:t,y:i,z:s},n,r,a)}disposeGlare(e){const t=this.glareSprites.get(e);t&&(t.mesh.removeFromParent(),t.dispose(),this.glareSprites.delete(e))}buildComet(e,t){const i=e&&`comet:${e.id}`;if(!e||!i||e.magnitude>t){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const s=ic(e.magnitude,t),n=Fg(s);this.cometKey=i,this.setBodyMesh(i,e.position,Jg*(.5+.5*s),new ae(n,n,n),e.magnitude),this.cometTail||(this.cometTail=new mr(Rn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,s)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new hs,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(),s=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(s?.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:bf},0);return}const n=this.lowerCloudCover(),r=St.deckLitUntilDeg(St.DECK_HEIGHT_M),a=e.altitudeDeg>-r?e:t,o=this.bentLight(a,a===e?yt.SUN_MAGNITUDE:t.magnitude),l=St.strength(i,n,a.altitudeDeg,r)*o.scale,{x:h,y:d,z:u}=Zt(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},a.altitudeDeg,l,o.tint,{cover:s?.cover??i,layerHeight:s?.layerHeight??bf},s?.iceCrystalAlignment??this.weather.iceCrystalAlignment??qf,this.weather.rareIceCrystals)}buildRainbow(e,t){this.rainbow||(this.rainbow=new tc,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,s=e.altitudeDeg>0,n=s?e:t,r=this.lowerCloudCover(),a=this.bentLight(n,s?yt.SUN_MAGNITUDE:t.magnitude,H6),o=bn.strength(i,r,n.altitudeDeg)*a.scale;if(o<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:l,y:h,z:d}=Zt(n.altitudeDeg,n.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:d},o,a.tint,s)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new qo,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:s}=e.frame,n=br.galactic(i,s),r=de.directionOf(n.centre),a=de.directionOf(n.rotation),o=de.directionOf(n.pole),l=new bt().set(r.x,r.y,r.z,a.x,a.y,a.z,o.x,o.y,o.z),h=de.directionOf(br.eclipticPole(i,s)),d=de.directionOf(e.sun),u=d.clone().addScaledVector(h,-d.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:u,sunDirection:d,sunAltitudeDeg:e.sun.altitudeDeg,moon:{direction:de.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new I(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:s}=Zt(e.altitudeDeg,e.azimuthDeg,1);return new I(t,i,s).normalize()}buildNovae(e,t){const i=new Set;for(const s of e){if(s.magnitude>t)continue;const n=`nova:${s.id}`;i.add(n);const r=ic(s.magnitude,t),a=Fg(r);this.setBodyMesh(n,s.position,Jg*(.5+.5*r),new ae(a,a,a),s.magnitude)}for(const s of this.novaKeys)i.has(s)||(this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s));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 s of e){if(s.magnitude>t)continue;i.add(s.body);const n=ic(s.magnitude,t),r=Fg(n),a=xN[s.body]??new ae(1,1,1),o=new ae(a.r*r,a.g*r,a.b*r),l=Jg*(.5+.5*n);this.setBodyMesh(s.body,s.position,l,o,s.magnitude)}for(const s of[...this.bodyMeshes.keys()])i.has(s)||(this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s))}buildStars(e,t){if(this.namedStars=[],!e||e.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:s,observer:n}=e,r=new Qr(s,n),a=lv(1337),o=[],l=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<cS)continue;const{x:f,y:m,z:v}=Zt(u,p,qg);o.push({x:f,y:m,z:v,brightness:ic(d,t),illuminance:this.air.transmittanceFromSpace(l,u).map(g=>g*Vt.illuminanceOf(d)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of t2){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<cS)continue;const{x:p,y:f,z:m}=Zt(d,u,qg);this.namedStars.push({star:h,direction:new I(p,f,m).normalize(),altitudeDeg:d})}this.starTiers=dc.map((h,d)=>{const u=o.filter(M=>x0(M.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),m=new Float32Array(u.length*3),v=new Float32Array(u.length),g=new Float32Array(u.length);u.forEach((M,S)=>{p[S*3]=M.x,p[S*3+1]=M.y,p[S*3+2]=M.z,f[S]=M.brightness,m.set(M.illuminance,S*3),v[S]=M.phase,g[S]=M.speedFactor});const b=new xt;b.setAttribute("position",new wt(p,3)),b.setAttribute("seed",new wt(v.map(M=>M/(2*Math.PI)),1));const w=new wt(new Float32Array(u.length*3),3);b.setAttribute("color",w);let y=this.starTiers[d]?.points;return y?(y.geometry.dispose(),y.geometry=b):(y=new sr(b,ze.material(h.size)),ze.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:w,brightness:f,illuminance:m,phase:v,speedFactor:g}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){ze.setTime(e);const t=this.relativeScale;if(t!==this.starColoursRelative){this.starColoursRelative=t;for(const i of this.starTiers){const s=i.colorAttribute.array;for(let n=0;n<i.brightness.length;n++)s[n*3]=i.illuminance[n*3]*t,s[n*3+1]=i.illuminance[n*3+1]*t,s[n*3+2]=i.illuminance[n*3+2]*t;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Gh(this.celestialGroup,Qg,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 ae(Fl[0]+(iv[0]-Fl[0])*t,Fl[1]+(iv[1]-Fl[1])*t,Fl[2]+(iv[2]-Fl[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:s,uniforms:n}=Kb(i,e,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=s,this.cloudUniforms=n,n.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=Xb(Qg);this.cloudMesh=new we(r,s),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}=Kb(new ae(...Fl),e,bf,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new we(Xb(Qg*1.04),t),this.cirrusMesh.renderOrder=vS-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?Gh.deckOrder(!0,0,1):vS}cloudLayerOffset(){const t=((this.weather.cloudBaseM??ry)-this.observerElevationM)*ev;return Math.sign(t||1)*Math.max(Math.abs(t),nN)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(d=>d!==void 0);if(i.length===0&&!this.layeredClouds)return;const s=this.cloudBeamDirection,[n,r,a]=this.cloudBeam.map(d=>d/Math.PI),o=this.lightningLevel*ov*this.relativeScale/Math.PI,l=new ae(t[0]+fa.r*o,t[1]+fa.g*o,t[2]+fa.b*o);this.layeredClouds?.setLighting(s.clone(),new ae(n,r,a),l,l);const h=Math.max(0,s.y);for(const d of i)d.sunDir.value.copy(s),d.sunColor.value.setRGB(n*h,r*h,a*h),d.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(e){return uN(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,rv],[this.rainSplashSystem?.points,Ul],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:sv[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=MS(av(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=sv[e],i=t.poolSize,s=lv(9001),n=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),o=new Float32Array(i),l=new Float32Array(i),h=new Float32Array(i),d=new Float32Array(i),u=new Float32Array(i),p=new Float32Array(i),f=new Float32Array(i);for(let w=0;w<i;w++){const y=s()*Math.PI*2,M=s()*t.radiusM;n[w*3]=Math.cos(y)*M,n[w*3+1]=ah+s()*(t.topYM-ah),n[w*3+2]=Math.sin(y)*M,r[w]=s()*Math.PI*2,a[w]=.7+s()*.6,o[w]=.6+s()*.8,l[w]=.4+s()*1.2}const m=new xt;m.setAttribute("position",new wt(n,3)),m.setDrawRange(0,this.precipitationCount(i));const v={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new ae(...this.baseFogColor)},uTexture:{value:SN(e)},uNearFocusDistance:{value:AS},uHazeDistance:{value:t.radiusM*TS}},g=new Pt({uniforms:v,vertexShader:DN,fragmentShader:RN,transparent:!0,depthWrite:!1});this.precipitationUniforms=v;const b=new sr(m,g);b.renderOrder=tv,this.scene.add(b),this.precipitationPoints=b,this.precipitationPositions=n,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=o,this.precipitationWobbleAmpJitter=l,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 s=sv[i];if(this.precipitationUniforms?.uColor.value.copy(de.litBySky(s.color,this.baseFogColor)),t<=0)return;const n=this.weather.windDirectionDeg*Ti,r=Math.sin(n)*this.weather.windSpeed*s.driftSensitivity,a=-Math.cos(n)*this.weather.windSpeed*s.driftSensitivity,o=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,m=this.precipitationBounceDuration,v=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,b=i==="snow"&&d&&u,w=i==="hail"&&p&&f&&m&&v&&g;for(let y=0,M=0;y<o.length;y+=3,M++){if(w&&p[M]>0){if(p[M]-=t,p[M]<=0){const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(x)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(x)*A,p[M]=0}else{const x=1-p[M]/m[M];o[y+1]=ah+Math.sin(Math.PI*x)*f[M],o[y]=wf(o[y]+(r+v[M])*t,s.radiusM),o[y+2]=wf(o[y+2]+(a+g[M])*t,s.radiusM)}continue}let S=0,E=0;if(b){const x=fN*d[M],A=mN*u[M];S=Math.sin(e*x*Math.PI*2+l[M])*A,E=Math.sin(e*x*Math.PI*2+l[M]+Math.PI/2)*A}if(o[y]+=(r+S)*t,o[y+1]-=s.fallSpeedMPerS*h[M]*t,o[y+2]+=(a+E)*t,o[y]=wf(o[y],s.radiusM),o[y+2]=wf(o[y+2],s.radiusM),o[y+1]<ah){if(w){f[M]=kS*(.2+Math.random()*1.6),m[M]=gN*(.5+Math.random()),p[M]=m[M];const D=Math.random()*Math.PI*2,R=vN*(f[M]/kS);v[M]=Math.cos(D)*R,g[M]=Math.sin(D)*R,o[y+1]=ah;continue}const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(x)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(x)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=av(this.weather.precipitationIntensity);this.rainSystem=jP({count:rv,radiusM:Gd,heightM:aN,bottomYM:bS,overallSpeed:oN,color:wS.clone(),opacity:.85,visibleCount:this.precipitationCount(rv),speedStreak:MS(e),pixelSize:_S,seed:9001,nearFocusDistanceM:AS,hazeDistanceM:Gd*TS,hazeColor:new ae(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=tv,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=lv(4242),t=new Float32Array(Ul*3),i=new Float32Array(Ul),s=new Float32Array(Ul),n=new Float32Array(Ul);for(let h=0;h<Ul;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*Gd;t[h*3]=Math.cos(d)*u,t[h*3+1]=bS,t[h*3+2]=Math.sin(d)*u,s[h]=CS(xS,SS),i[h]=e()*s[h],n[h]=i[h]/s[h]}const r=new xt;r.setAttribute("position",new wt(t,3));const a=new wt(n,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Ul));const o=new Pt({uniforms:{uMaxSize:{value:dN},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:ES.clone()},uTexture:{value:TN()}},vertexShader:IN,fragmentShader:_N,transparent:!0,depthWrite:!1}),l=new sr(r,o);l.renderOrder=tv,this.scene.add(l),this.rainSplashSystem={points:l,positions:t,life:i,duration:s,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const e=this.rainSystem;if(!e)return;const t=this.weather.windDirectionDeg*Ti;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-av(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(de.litBySky(wS,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(de.litBySky(ES,this.baseFogColor));const s=this.weather.windDirectionDeg*Ti,n=Math.sin(s)*this.weather.windSpeed,r=-Math.cos(s)*this.weather.windSpeed,a=Gd,o=h=>(h%(a*2)+a*3)%(a*2)-a;t.uniforms.uWindOffset.value.set(o(t.uniforms.uWindOffset.value.x+n*e),o(t.uniforms.uWindOffset.value.y+r*e)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=DS+(1-DS)*(1-l),d=RS+(1-RS)*(1-l);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=_S*h*(.5+.5*d)}this.updateRainSplashes(e)}updateRainSplashes(e){const t=this.rainSplashSystem;if(!t||e<=0)return;const{positions:i,life:s,duration:n,lifeAttribute:r}=t,a=r.array;for(let o=0,l=0;o<i.length;o+=3,l++){if(s[l]+=e,s[l]>=n[l]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*Gd;i[o]=Math.cos(h)*d,i[o+2]=Math.sin(h)*d,n[l]=CS(xS,SS),s[l]=0}a[l]=s[l]/n[l]}t.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(e){this.lightningFlashes=e}updateLightning(e){let t,i=0;if(this.lightningArmed)for(const o of this.lightningFlashes){if(o.t>e)break;const l=Ls.brightnessAt(o,e);l>i&&(t=o,i=l)}const s=t?Math.min(1,Math.max(.1,(wN/t.distanceM)**2)):0,n=i*s*(t?.cloudToGround?1:.6);if(n===this.lightningLevel&&!t?.cloudToGround)return;if(this.lightningLevel=n,this.scene.fog){const o=this.scene.fog,l=n*ov*this.relativeScale/Math.PI;o.color.setRGB(this.airlight[0]+fa.r*l,this.airlight[1]+fa.g*l,this.airlight[2]+fa.b*l)}const r=this.skyMesh?.material?.color;if(r){const o=n*MN;r.setRGB(1+o*fa.r,1+o*fa.g,1+o*fa.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=n*ov*this.relativeScale,t){const{x:o,y:l,z:h}=Zt(25,t.azimuthDeg,Rn);this.lightningLight.position.set(o,l,h)}this.lightningBolt||(this.lightningBolt=new jo(Rn*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,a),this.render()}buildCompassLabels(){this.compassSprites=J6.map(e=>{const t=uc.point(e,this.compassPoints),i=new Hf({map:kN(t),depthTest:!1,fog:!1}),s=new Rd(i),{x:n,y:r,z:a}=Zt(0,e,pS);return s.position.set(n,r,a),s.scale.set(yf,yf,1),s.renderOrder=tN,s.layers.set(Xg),s.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(s),s}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=fS*Math.PI/360,i=yf*Math.tan(e)/Math.tan(t);for(const s of this.compassSprites)s.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 s=i.map;s&&s.dispose(),i.dispose()}}}const Ti=Math.PI/180;function ya(c,e,t){return Math.max(e,Math.min(t,c))}function CS(c,e){return c+Math.random()*(e-c)}function wf(c,e){return(c%(e*2)+e*3)%(e*2)-e}let Mf,xf;function SN(c){switch(c){case"snow":return EN();case"hail":return AN()}}function EN(){if(Mf)return Mf;const c=64,e=document.createElement("canvas");e.width=c,e.height=c;const t=e.getContext("2d"),i=t.createRadialGradient(c/2,c/2,0,c/2,c/2,c/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,c,c),Mf=new Dl(e),Mf}function AN(){if(xf)return xf;const c=64,e=document.createElement("canvas");e.width=c,e.height=c;const t=e.getContext("2d"),i=t.createRadialGradient(c/2,c/2,0,c/2,c/2,c/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,c,c),xf=new Dl(e),xf}let Sf;function TN(){if(Sf)return Sf;const c=64,e=document.createElement("canvas");e.width=c,e.height=c;const t=e.getContext("2d"),i=t.createRadialGradient(c/2,c/2,0,c/2,c/2,c/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,c,c),Sf=new Dl(e),Sf}const IN=`
|
|
11430
11430
|
uniform float uMaxSize;
|
|
11431
11431
|
uniform float uScale;
|
|
11432
11432
|
attribute float aLife;
|
|
@@ -11492,7 +11492,7 @@ void main() {
|
|
|
11492
11492
|
gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
|
|
11493
11493
|
}
|
|
11494
11494
|
`;function LS(c){const t=document.createElement("canvas");t.width=128,t.height=128;const i=t.getContext("2d"),s=128/2-2,n=128/2,r=128/2,a="#010101",o="#f4f1e2";i.fillStyle=a,i.beginPath(),i.arc(n,r,s,0,Math.PI*2),i.fill();const l=ya(c.illuminatedFraction,0,1),h=c.phaseFraction<.5,d=s*Math.abs(1-2*l),u=l<.5;return i.save(),i.beginPath(),i.arc(n,r,s,0,Math.PI*2),i.clip(),i.fillStyle=o,i.beginPath(),h?(i.arc(n,r,s,-Math.PI/2,Math.PI/2,!1),i.ellipse(n,r,d,s,0,Math.PI/2,-Math.PI/2,u)):(i.arc(n,r,s,Math.PI/2,-Math.PI/2,!1),i.ellipse(n,r,d,s,0,-Math.PI/2,Math.PI/2,u)),i.fill(),i.restore(),new Dl(t)}function kN(c){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(c,64,68),new Dl(e)}function lv(c){let e=c;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 Bm{constructor(e,t){this.source=e,this.create=t}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=480;paint(e,t){this.disposed||(this.wanted={t:e,canvas:t},this.pumping||this.pump())}recordingChanged(e){this.scene&&(this.scene.sightingData=e)}dispose(){this.disposed=!0,this.scene?.remove(),this.scene=void 0}ensureScene(){if(this.scene)return this.scene;const e=this.create();return e.setAttribute("max-pixel-ratio","1"),e.setAttribute("always-live",""),Object.assign(e.style,{position:"fixed",left:"-10000px",top:"0",width:`${Bm.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 s=0;s<Bm.PATIENCE_FRAMES&&!this.wanted&&!this.disposed&&(await new Promise(n=>requestAnimationFrame(()=>n())),!this.wanted);s++)if(i.snapshotTo(t)){t.dataset.ready="true";break}}}finally{this.pumping=!1}}}class Ct{static held=new Map;static loaded=new Map;static generation=0;static address(e,t){const i=t??(typeof location>"u"?"http://localhost/":location.href);return new URL(e,i).href}static hold(e,t){Ct.held.set(e,t),Ct.loaded.delete(e),Ct.generation++}static release(){if(Ct.held.size!==0){for(const e of Ct.held.keys())Ct.loaded.delete(e);Ct.held.clear(),Ct.generation++}}static bytes(e,t=fetch.bind(globalThis)){const i=Ct.held.get(e);if(i)return Promise.resolve(i);let s=Ct.loaded.get(e);return s||(s=t(e).then(async n=>{if(!n.ok)throw new Error(`Frozen data not found (${n.status}): ${e}`);return new Uint8Array(await n.arrayBuffer())}),Ct.loaded.set(e,s),s.catch(()=>Ct.loaded.delete(e))),s}static async json(e){return JSON.parse(new TextDecoder().decode(await Ct.bytes(e)))}static async zip(e){const t=await Ct.bytes(e),{unzipSync:i}=await oe(async()=>{const{unzipSync:s}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:s}},[],import.meta.url);return i(t)}}class Kn{static SAME_BOUNDS_DEG=1e-9;loaded=!1;ready;list=[];constructor(e){this.ready=e.then(t=>{this.list=t},()=>{}).finally(()=>{this.loaded=!0})}nearest(e,t){let i,s=1/0;for(const n of this.list){if(n.far)continue;const{x:r,z:a}=ut(n.lat,n.lng,e,t),o=Math.hypot(r,a);o<s&&(s=o,i=n)}return i}farRingOf(e,t){return this.list.find(i=>i.far&&Math.abs(i.lat-e)<=Kn.SAME_BOUNDS_DEG&&Math.abs(i.lng-t)<=Kn.SAME_BOUNDS_DEG)}static boundsOf(e){return cu(e.lat,e.lng,e.radiusM)}static sameBounds(e,t){const i=(s,n)=>Math.abs(s-n)<=Kn.SAME_BOUNDS_DEG;return i(e.north,t.north)&&i(e.south,t.south)&&i(e.east,t.east)&&i(e.west,t.west)}static contains(e,t){return e.north>=t.north&&e.south<=t.south&&e.east>=t.east&&e.west<=t.west}static samePatches(e,t){return e.length===t.length&&e.every((i,s)=>i.lat===t[s].lat&&i.lng===t[s].lng&&i.radiusM===t[s].radiusM&&i.far===t[s].far)}}class cp{static async encode(e){const{zipSync:t,strToU8:i}=await oe(async()=>{const{zipSync:r,strToU8:a}=await import("./browser-_Ncw3Jhn.js");return{zipSync:r,strToU8:a}},[],import.meta.url),s={},n={version:1,takenOn:e.takenOn,attribution:e.attribution,patches:e.patches.map((r,a)=>{const o=`${a}.f32`;return s[o]=cp.byPlane(r.grid.heights),{lat:r.lat,lng:r.lng,radiusM:r.radiusM,...r.far?{far:r.far}:{},bounds:r.grid.bounds,width:r.grid.width,height:r.grid.height,file:o}})};return s["index.json"]=i(JSON.stringify(n,null,1)),t(s,{level:9})}static decode(e){const t=e["index.json"];if(!t)throw new Error("A relief annex without its index");const i=JSON.parse(new TextDecoder().decode(t));return{takenOn:i.takenOn,attribution:i.attribution,patches:i.patches.flatMap(s=>{const n=e[s.file];if(!n||n.length!==s.width*s.height*4)return[];const r={heights:cp.fromPlanes(n),width:s.width,height:s.height,bounds:s.bounds};return[{lat:s.lat,lng:s.lng,radiusM:s.radiusM,...s.far?{far:s.far}:{},grid:r}]})}}static byPlane(e){const t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=e.length,s=new Uint8Array(t.length);for(let n=0;n<i;n++)for(let r=0;r<4;r++)s[r*i+n]=t[n*4+r];return s}static fromPlanes(e){const t=e.length/4,i=new Uint8Array(e.length);for(let s=0;s<t;s++)for(let n=0;n<4;n++)i[s*4+n]=e[n*t+s];return new Float32Array(i.buffer)}}class o1{constructor(e){this.annex=e}async getElevationGrid(e,t,i){const{patches:s}=await this.annex,n=s.find(a=>Kn.sameBounds(Kn.boundsOf(a),e));if(n)return{...n.grid,heights:new Float32Array(n.grid.heights)};const r=s.find(a=>Kn.contains(a.grid.bounds,e));if(r)return o1.resample(r.grid,e,t);throw new Error("The frozen relief does not hold this ground")}static resample(e,t,i){const{width:s,height:n}=i,r=new Float32Array(s*n),a=e.bounds.east-e.bounds.west,o=e.bounds.north-e.bounds.south;for(let l=0;l<n;l++){const h=t.north-(t.north-t.south)*(n>1?l/(n-1):0),d=Math.min(e.height-1,Math.max(0,(e.bounds.north-h)/o*(e.height-1))),u=Math.floor(d),p=Math.min(e.height-1,u+1),f=d-u;for(let m=0;m<s;m++){const v=t.west+(t.east-t.west)*(s>1?m/(s-1):0),g=Math.min(e.width-1,Math.max(0,(v-e.bounds.west)/a*(e.width-1))),b=Math.floor(g),w=Math.min(e.width-1,b+1),y=g-b,M=(x,A)=>e.heights[x*e.width+A],S=M(u,b)*(1-y)+M(u,w)*y,E=M(p,b)*(1-y)+M(p,w)*y;r[l*s+m]=S*(1-f)+E*f}}return{heights:r,width:s,height:n,bounds:t}}}function ds(c,e){return c.find(t=>t.id===e)??c[0]}class CN{attribution;fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis);const t=e.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${t}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${t})`}async getImageryTexture(e,t){return S2(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const Ef=[{id:"ign-mnt",name:"IGN LiDAR HD / RGE ALTI",credit:"Relief © IGN, LiDAR HD and RGE ALTI (Licence Ouverte 2.0) in France; © AWS Open Data (SRTM, ETOPO1) elsewhere",creditUrl:"https://geoservices.ign.fr/lidarhd",create:()=>T2()},{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new x2}],fc=[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:c=>new E2({fetchImpl:c})},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:c=>new CN({fetchImpl:c})}];class OS{constructor(e=fetch.bind(globalThis)){this.fetchImpl=e}tiles=new Map;fetch=async(e,t)=>{const i=await this.fetchImpl(e,t);if(i.ok){const s=typeof e=="string"?e:e instanceof URL?e.href:e.url,n=new Uint8Array(await i.clone().arrayBuffer());this.tiles.set(s,{bytes:n,type:i.headers.get("content-type")??"image/jpeg"})}return i}}class Hm{static async encode(e){const{zipSync:t,strToU8:i}=await oe(async()=>{const{zipSync:o,strToU8:l}=await import("./browser-_Ncw3Jhn.js");return{zipSync:o,strToU8:l}},[],import.meta.url),s={},n={};let r=0;for(const[o,l]of e.tiles){const h=`tiles/${r++}`;s[h]=l.bytes,n[o]={file:h,type:l.type}}const a={version:1,takenOn:e.takenOn,source:e.source,attribution:e.attribution,patches:e.patches,map:e.map,tiles:n};return s["index.json"]=i(JSON.stringify(a,null,1)),t(s,{level:0})}static decode(e){const t=e["index.json"];if(!t)throw new Error("An imagery annex without its index");const i=JSON.parse(new TextDecoder().decode(t)),s=new Map;for(const[n,{file:r,type:a}]of Object.entries(i.tiles)){const o=e[r];o&&s.set(n,{bytes:o,type:a})}return{takenOn:i.takenOn,source:i.source,attribution:i.attribution,patches:i.patches,map:i.map,tiles:s}}}class E0{constructor(e,t=""){this.annex=e,this.attributionStated=t}provider;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}async getImageryTexture(e,t){return(await(this.provider??=this.annex.then(s=>(this.attributionRead=s.attribution,ds(fc,s.source).create(E0.fetchFrom(s.tiles)))))).getImageryTexture(e,t)}static fetchFrom(e){return async t=>{const i=typeof t=="string"?t:t instanceof URL?t.href:t.url,s=e.get(i);return s?new Response(s.bytes,{status:200,headers:{"content-type":s.type}}):new Response(null,{status:404})}}}class LN{constructor(e,t=""){this.annex=e,this.attributionStated=t}picture;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}getImagery(){return this.picture??=this.annex.then(e=>{if(!e.map)throw new Error("An imagery annex that holds no map");return this.attributionRead=e.attribution,ds(fc,e.source).create(E0.fetchFrom(e.tiles)).getImageryTexture(e.map.bounds,{width:e.map.pixels,height:e.map.pixels})})}}class l1{constructor(e){this.annex=e}attributionRead;contemporaryRead;async itemsFor(e){const t=await this.annex;return this.attributionRead=t.attribution,this.contemporaryRead=t.contemporary,t.patches.find(i=>Kn.sameBounds(Kn.boundsOf(i),e))?.items??[]}}class ON{constructor(e,t=""){this.attributionStated=t,this.reader=new l1(e)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRoads(e){return this.reader.itemsFor(e)}}class PN{constructor(e,t=""){this.attributionStated=t,this.reader=new l1(e)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}getWater(e){return this.reader.itemsFor(e)}}class NN{constructor(e,t=""){this.attributionStated=t,this.reader=new l1(e)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRailways(e){return this.reader.itemsFor(e)}}class Gm{static providers(e,t,i){const s=p=>ts.held(e,p),n=s("relief"),r=s("imagery"),a=s("roads"),o=s("water"),l=s("railways");if(!n&&!r&&!a&&!o&&!l)return i;const h=p=>Ct.address(p.src,t),d=[],u={...i};if(n){const p=Ct.zip(h(n)).then(f=>cp.decode(f));u.elevation=new o1(p),d.push(p.then(f=>f.patches))}if(r){const p=Ct.zip(h(r)).then(f=>Hm.decode(f));u.imagery=new E0(p,r.attribution),d.push(p.then(f=>f.patches))}if(a){const p=Ct.json(h(a));u.roads=new ON(p,a.attribution),d.push(p.then(f=>f.patches))}if(o){const p=Ct.json(h(o));u.water=new PN(p,o.attribution),d.push(p.then(f=>f.patches))}if(l){const p=Ct.json(h(l));u.railways=new NN(p,l.attribution),d.push(p.then(f=>f.patches))}return u.patches=new Kn(Gm.firstRead(d)),u}static map(e,t){const i=Ct.zip(Ct.address(e.src,t)).then(s=>Hm.decode(s));return new LN(i,e.attribution)}static async firstRead(e){for(const t of e)try{const i=await t;if(i.length>0)return i.map(({lat:s,lng:n,radiusM:r,far:a})=>({lat:s,lng:n,radiusM:r,...a?{far:a}:{}}))}catch{}return[]}}class Eh{constructor(e){this.annex=e}static SAME_PLACE_DEG=1e-6;static SAME_TIME_MS=1e3;async between(e,t,i){let s;try{s=await this.annex}catch{return{status:"failed"}}const n=o=>Math.abs(o.lat-e.lat)<=Eh.SAME_PLACE_DEG&&Math.abs(o.lng-e.lng)<=Eh.SAME_PLACE_DEG,a=s.answers.find(o=>n(o)&&Math.abs(o.startMs-t)<=Eh.SAME_TIME_MS&&Math.abs(o.endMs-i)<=Eh.SAME_TIME_MS)??s.answers.find(o=>o.startMs<=t&&o.endMs>=i);return a?a.answer:{status:"failed"}}}const cv=7.5,mu=9;class wa{static cache=new Map;static load(e){let t=wa.cache.get(e);return t||(t=fetch(e).then(i=>i.arrayBuffer()).then(i=>wa.parse(i)),wa.cache.set(e,t)),t}static upTo(e,t){const i=e.filter((r,a)=>a===0||e[a-1].magnitudeLimit<t);if(i.length<=1)return wa.load(e[0].url);const s=i.map(r=>r.url).join(`
|
|
11495
|
-
`);let n=wa.cache.get(s);return n||(n=Promise.all(i.map(r=>wa.load(r.url))).then(r=>r.reduce((a,o)=>wa.concat(a,o))),wa.cache.set(s,n)),n}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=(s,n)=>{const r=new Float32Array(s.length+n.length);return r.set(s,0),r.set(n,s.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 mi{constructor(e){if(this.heights=e,e.length!==mi.WIDTH*mi.HEIGHT)throw new Error(`a lunar relief has ${mi.WIDTH*mi.HEIGHT} samples, not ${e.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*mi.SAMPLES_PER_DEGREE;static HEIGHT=180*mi.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=mi.SAMPLES_PER_DEGREE,s=(t%360+360)%360*i-.5,n=(90-e)*i-.5,r=Math.floor(s),a=Math.floor(n),o=s-r,l=n-a,h=(p,f)=>{const m=(p%mi.WIDTH+mi.WIDTH)%mi.WIDTH,v=Math.min(mi.HEIGHT-1,Math.max(0,f));return this.heights[v*mi.WIDTH+m]},d=h(r,a)*(1-o)+h(r+1,a)*o,u=h(r,a+1)*(1-o)+h(r+1,a+1)*o;return(d*(1-l)+u*l)*mi.UNIT_KM}static inBand(e,t){const i=Math.PI/180,s=Math.acos(Math.cos(e*i)*Math.cos(t*i))*180/Math.PI;return s>=mi.BAND_FROM_DEG&&s<=mi.BAND_TO_DEG}static withBump(e,t,i,s=.4){const n=new Int8Array(mi.WIDTH*mi.HEIGHT),r=mi.SAMPLES_PER_DEGREE,a=Math.ceil(s*r),o=Math.floor(t*r),l=Math.floor((90-e)*r);for(let h=-a;h<=a;h++)for(let d=-a;d<=a;d++)Math.hypot(d,h)<=a&&(n[(l+h)*mi.WIDTH+(o+d+mi.WIDTH)%mi.WIDTH]=Math.round(i/mi.UNIT_KM));return new mi(n)}static smooth(){return new mi(new Int8Array(mi.WIDTH*mi.HEIGHT))}}class Cr{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(e,t,i,s=Cr.SAMPLES){const{s:n,u:r,w:a,distanceKm:o}=Cr.frame(e,t),l=Math.PI/180,h=new Float32Array(s),d=mi.REFERENCE_RADIUS_KM;for(let u=0;u<s;u++){const p=u/s*2*Math.PI,f=Math.cos(p),m=Math.sin(p),v=f*r[0]+m*a[0],g=f*r[1]+m*a[1],b=f*r[2]+m*a[2];let w=0;for(let y=Cr.SEARCH_FROM_DEG;y<=Cr.SEARCH_TO_DEG;y+=Cr.SEARCH_STEP_DEG){const M=Math.cos(y*l),S=Math.sin(y*l),E=M*n[0]+S*v,x=M*n[1]+S*g,A=M*n[2]+S*b,D=Math.asin(Math.max(-1,Math.min(1,A)))/l,R=Math.atan2(x,E)/l,L=d+i.heightKm(D,R),N=Math.atan2(L*S,o-L*M);N>w&&(w=N)}h[u]=w/l}return{radiusDeg:h,meanRadiusDeg:Math.asin(d/o)/l}}static frame(e,t){const i=new So(t.lat,t.lng,t.elevationM),s=Eo(e),n=Lv(e,i,!1),r=new $t(n.x-s.x,n.y-s.y,n.z-s.z,s.t),a=Math.hypot(r.x,r.y,r.z)*Cr.AU_KM,o=Cr.bodyFixed(e),l=o(r),h=Math.hypot(l[0],l[1],l[2]),d=[l[0]/h,l[1]/h,l[2]/h],u=a5(e,i),p=Ay(u),f=wo(u,new $t(-r.x,-r.y,-r.z,s.t)),m=Math.asin(f.z/Math.hypot(f.x,f.y,f.z)),v=Math.atan2(-f.y,f.x),g=new $t(-Math.sin(m)*Math.cos(v),Math.sin(m)*Math.sin(v),Math.cos(m),s.t),b=new $t(-Math.sin(v),-Math.cos(v),0,s.t);return{s:d,u:o(wo(p,g)),w:o(wo(p,b)),distanceKm:a}}static surfacePoint(e,t,i,s){const{s:n,u:r,w:a}=Cr.frame(e,t),o=Math.PI/180,l=[0,1,2].map(d=>Math.cos(i*o)*r[d]+Math.sin(i*o)*a[d]),h=[0,1,2].map(d=>Math.cos(s*o)*n[d]+Math.sin(s*o)*l[d]);return{latDeg:Math.asin(h[2])/o,lonDeg:Math.atan2(h[1],h[0])/o}}static radiusAt(e,t){const i=e.radiusDeg.length,s=(t/360*i%i+i)%i,n=Math.floor(s),r=s-n;return e.radiusDeg[n]*(1-r)+e.radiusDeg[(n+1)%i]*r}static uncoveredFraction(e,t,i){const s=e.radiusDeg.length,n=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<s;a++){const o=a/s*2*Math.PI,l=Math.cos(o),h=Math.sin(o),d=l*i.upDeg+h*i.rightDeg,u=d*d-n+t*t;if(u<=0)continue;const p=Math.sqrt(u),f=d+p;if(f<=0)continue;const m=Math.max(0,d-p),v=Math.max(m,e.radiusDeg[a]);f>v&&(r+=.5*(f*f-v*v))}return Math.min(1,Math.max(0,r*(2*Math.PI/s)/(Math.PI*t*t)))}static AU_KM=1495978707e-1;static bodyFixed(e){const t=x5(me.Moon,e),i=Math.PI/180,s=t.ra*15*i,n=t.dec*i,r=t.spin*i,a=(l,[h,d,u])=>[Math.cos(l)*h+Math.sin(l)*d,-Math.sin(l)*h+Math.cos(l)*d,u],o=(l,[h,d,u])=>[h,Math.cos(l)*d+Math.sin(l)*u,-Math.sin(l)*d+Math.cos(l)*u];return l=>a(r,o(Math.PI/2-n,a(Math.PI/2+s,[l.x,l.y,l.z])))}static subObserverPoint(e,t){const i=new So(t.lat,t.lng,t.elevationM),s=Eo(e),n=Lv(e,i,!1),r=Cr.bodyFixed(e)(new $t(n.x-s.x,n.y-s.y,n.z-s.z,s.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class gu{static cache=new Map;static load(e){let t=gu.cache.get(e);return t||(t=gu.fetchRelief(e).catch(()=>{}),gu.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 s=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(s).arrayBuffer())}return new mi(new Int8Array(i.buffer,i.byteOffset,i.length))}}class Vm{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=Vm.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(e){const t=Vm.MATRICES[String(e.type)];if(!t)return cr.NONE;const i=Number(e.severity??100),s=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:t.map((r,a)=>cr.IDENTITY[a]+(r-cr.IDENTITY[a])*s),contrastGain:1}}}class c1{static ID="fatigue";id=c1.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(e){return cr.NONE}}class Kl{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=Kl.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary), drawn up to 0.1 % at most: a higher level is recorded but shown as 0.1 %, since nothing was measured past it. Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:Kl.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(e){const t=Number(e.bloodAlcohol??0),i=Math.max(0,Math.min(Kl.MAX_EFFECT_LEVEL,Number.isFinite(t)?t:0));if(i===0)return cr.NONE;const s=i/Kl.MEASURED_LEVEL*Kl.MEASURED_LOSS_DB;return{colorMatrix:cr.IDENTITY,contrastGain:10**(-s/20)}}}class mc{static ALL=[new Vm,new Kl,new c1];static byId(e){return mc.ALL.find(t=>t.id===e)}static perceptionOf(e){return mc.ALL.reduce((t,i)=>cr.combine(t,i.perceive(e?.[i.id]??{})),cr.NONE)}static compact(e){const t={};for(const i of mc.ALL){const s=e[i.id]??{},n=Object.fromEntries(i.settings.filter(r=>s[r.id]!==void 0&&s[r.id]!==r.default).map(r=>[r.id,s[r.id]]));Object.keys(n).length>0&&(t[i.id]=n)}return Object.keys(t).length>0?t:void 0}}class Wm{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 uc.point(e,this.names?.compassPoints)}towards(e){return uc.towards(e,this.names)}}class Jr{static ENGLISH={kinds:{rail:"Railway",light_rail:"Light rail",tram:"Tramway",subway:"Metro",funicular:"Funicular"},highSpeed:"High-speed line",service:"Siding",singleTrack:"single track",tracks:"{count} tracks",overhead:"overhead wire {height} m above the rail",overheadVoltage:"overhead wire at {voltage}, {height} m above the rail",thirdRail:"third rail",thirdRailVoltage:"third rail at {voltage}",notElectrified:"not electrified",gauge:"{mm} mm gauge",metreGauge:"metre gauge",distance:"{distance} away"};static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(e,t){return e.highSpeed?t.highSpeed:e.service?t.service:t.kinds[e.kind]}static name(e,t){const i=e.name??Jr.kind(e,t);return e.services?.length?`${i} — ${e.services.join(", ")}`:i}static voltage(e,t){return e>=1e3?`${(e/1e3).toLocaleString(t,{maximumFractionDigits:1})} kV`:`${e.toLocaleString(t)} V`}static detail(e,t,i,s){const{line:n}=e,r=[];n.name&&r.push(Jr.kind(n,t).toLocaleLowerCase(s)),r.push(n.tracks>1?t.tracks.replace("{count}",String(n.tracks)):t.singleTrack);const a=n.voltageV?Jr.voltage(n.voltageV,s):void 0;if(e.contactM!==void 0){const o=e.contactM.toLocaleString(s,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?t.overheadVoltage.replace("{voltage}",a):t.overhead).replace("{height}",o))}else n.electrification==="third_rail"?r.push(a?t.thirdRailVoltage.replace("{voltage}",a):t.thirdRail):n.electrification==="none"&&r.push(t.notElectrified);return n.gaugeMm===Jr.METRE_GAUGE_MM?r.push(t.metreGauge):n.gaugeMm!==Jr.STANDARD_GAUGE_MM&&r.push(t.gauge.replace("{mm}",n.gaugeMm.toLocaleString(s))),r.push(t.distance.replace("{distance}",i(e.distanceM))),n.services?.length?`${Jr.name(n,t)}; ${r.join(", ")}`:`${Jr.name(n,t)} — ${r.join(", ")}`}}class vu{constructor(e,t){this.element=e,this.onChange=t,e.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(e,t,i=!0){const s=vu.resolve(e,t);if(this.url=s,!s||!i){this.release();return}this.element.src=s,this.element.hidden=!1;const n=this.shown;this.shown=!0,n||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(e,t){if(!(typeof e!="string"||e.trim()===""))try{const i=new URL(e.trim(),t??location.href);return i.protocol!=="https:"&&i.protocol!=="http:"?void 0:i.origin===vu.PUBLISHED_ORIGIN&&vu.isDevelopmentHost(location.hostname)?location.origin+i.pathname:i.href}catch{return}}static PUBLISHED_ORIGIN="https://ufoathome.org";static isDevelopmentHost(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e.endsWith(".localhost")}}const FN={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},UN="Global Meteor Network",zN="https://globalmeteornetwork.org/data/",BN="“Thunder” by Jerimee",HN="https://creativecommons.org/licenses/by/3.0/",GN="CC BY 3.0";class pn{static fill(e,t){e.innerHTML="";const i=u=>e.appendChild(u),s=t.currentTerrainAttribution;s&&i(pn.text(s));const n=t.currentRoadAttribution;n&&i(pn.text(n));const r=t.currentWaterAttribution;r&&i(pn.text(r));const a=t.currentRailwayAttribution;a&&i(pn.text(a));const o=t.ufoElement.observerMapCredit;o&&!s?.includes(o)&&i(pn.text(o));for(const u of t.decorModelCredits){const p=u.author?` — ${u.author}`:"",f=document.createElement("li");u.sourceUrl?f.append(pn.link(u.sourceUrl,u.title),document.createTextNode(`${p} (${u.license})`)):f.textContent=`${u.title}${p} (${u.license})`,i(f)}for(const u of t.ufoElement.sighting.references){if(!u.credit)continue;const p=document.createElement("li");u.creditUrl?p.appendChild(pn.link(u.creditUrl,u.credit)):p.textContent=u.credit,i(p)}if(t.ufoElement.sighting.traces.length>0){const u=new rn(Sr.preferencesFor(t)),p=new Set(t.ufoElement.sighting.traces.map(f=>u.read(f.source)).filter(f=>!!f));for(const f of p)i(pn.text(f))}const l=t.satelliteState;if(l.status==="ready"&&l.credit){const u=document.createElement("li");u.appendChild(pn.link(l.creditUrl??"",l.credit)),i(u)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const u=document.createElement("li");u.append(pn.link(zN,UN),document.createTextNode(" (CC BY 4.0)")),i(u)}const h=t.aircraftState;if(h.status==="ready"&&h.shown>0){const u=document.createElement("li");if(u.appendChild(pn.link(h.creditUrl,h.credit)),i(u),h.trailCredit){const p=document.createElement("li");p.appendChild(pn.link(h.trailCredit.creditUrl,h.trailCredit.credit)),i(p)}}const d=pn.text(`${BN} (`);d.append(pn.link(HN,GN),document.createTextNode(")")),i(d)}static text(e){const t=document.createElement("li");return t.textContent=e,t}static link(e,t){const i=document.createElement("a");return i.href=e,i.target="_blank",i.rel="noopener",i.textContent=t,i}}const VN=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,WN=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,PS=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,$N=20,KN=1;class Ah{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}}lc.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 s=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=s==="hail"?Math.min(1,t*1.3+.2):s==="rain"?t:0,s!==this.ambientKey){this.ambientKey=s;const r=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,s!=="none"&&this.startLoop(VN,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,o=>{this.ambientSource=o?.source,this.ambientGain=o?.gain,o&&(o.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/$N,1);const n=i>KN;if(n!==this.windActive){this.windActive=n;const r=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,n&&this.startLoop(WN,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,o=>{this.windSource=o?.source,this.windGain=o?.gain,o&&(o.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:i,windSpeed:s}=this.requested;this.setAmbient(t,i,s)}playThunder(){!this.context||this.paused||this.playOneShot(PS,.9)}playDetonation(e){const t=this.context;if(!t||this.paused)return;const i=Math.min(1,Math.max(0,e)),s=t.createBufferSource();s.buffer=this.crackBuffer(t);const n=t.createBiquadFilter();n.type="lowpass",n.frequency.value=Ah.CRACK_CUTOFF_HZ;const r=t.createGain();r.gain.value=i,s.connect(n).connect(r).connect(this.output(t)),s.start(),this.playOneShot(PS,i,Ah.DETONATION_RATE)}static DETONATION_RATE=.8;static CRACK_CUTOFF_HZ=2500;static CRACK_DECAY_S=.25;crackBuffer(e){if(this.crack?.sampleRate===e.sampleRate)return this.crack;const t=Math.round(e.sampleRate*Ah.CRACK_DECAY_S*6),i=e.createBuffer(1,t,e.sampleRate),s=i.getChannelData(0);for(let n=0;n<t;n++){const r=n/e.sampleRate;s[n]=(Math.random()*2-1)*Math.min(1,r/.005)*Math.exp(-r/Ah.CRACK_DECAY_S)}return this.crack=i,i}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(e,t,i,s){if(t!==i()){e?.source.stop();return}s(e)}async startLoop(e,t){const i=this.context;if(i)try{const s=await this.getBuffer(e),n=i.createBufferSource();n.buffer=s,n.loop=!0;const r=i.createGain();return r.gain.value=t,n.connect(r).connect(this.output(i)),n.start(),{source:n,gain:r}}catch(s){console.warn("Weather ambient sound failed to load, staying silent:",s);return}}async playOneShot(e,t,i=1){const s=this.context;if(s)try{const n=await this.getBuffer(e),r=s.createBufferSource();r.buffer=n,r.playbackRate.value=i;const a=s.createGain();a.gain.value=t,r.connect(a).connect(this.output(s)),r.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(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,i)),i}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}class so{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[s,n]=this.perifocalAxes(),r=Math.sqrt(so.SUN_GM_AU3_PER_DAY2*(1+t)/i);this.perihelionPosition=this.scale(s,i),this.perihelionVelocity=this.scale(n,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),s=this.inverseSemiMajorAxis*i*i,n=this.elements.perihelionAu,r=1-i*i/n*so.stumpffC(s),a=t-i*i*i/Math.sqrt(so.SUN_GM_AU3_PER_DAY2)*so.stumpffS(s);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(e){const t=this.positionAt(e);return Math.hypot(t.x,t.y,t.z)}universalAnomaly(e){if(e===0)return 0;const t=Math.sign(e),i=Math.sqrt(so.SUN_GM_AU3_PER_DAY2)*Math.abs(e),s=a=>{const o=this.inverseSemiMajorAxis*a*a,l=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*l)*a*a*a*so.stumpffS(o)+l*a};let n=Math.max(1,i/this.elements.perihelionAu);for(;s(n)<i;)n*=2;let r=0;for(let a=0;a<so.MAX_ITERATIONS&&n-r>1e-13*Math.max(1,n);a++){const o=(r+n)/2;s(o)<i?r=o:n=o}return t*(r+n)/2}perifocalAxes(){const e=this.elements.ascendingNodeDeg*Math.PI/180,t=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,s=Math.cos(e),n=Math.sin(e),r=Math.cos(t),a=Math.sin(t),o=Math.cos(i),l=Math.sin(i);return[{x:s*r-n*a*o,y:n*r+s*a*o,z:a*l},{x:-s*a-n*r*o,y:-n*a+s*r*o,z:r*l}]}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 YA=[{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 Yf{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 YA.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,s)=>i.magnitude-s.magnitude)[0]}static appearanceOf(e,t,i){const s=Ei(t),n=this.earthPositionAt(s),r=this.apparentPositionOf(e,2451545+s.tt,n),a=this.subtract(r,n),o=this.length(r),l=this.length(a),h=this.tailEndAt(e,r,n,o,s,t,i),d=this.horizontalOf(a,s,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:o,earthDistanceAu:l,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},n)),magnitude:this.magnitudeAt(e,o,l)}}static magnitudeAt(e,t,i){const s=e.absoluteMagnitude+5*Math.log10(i)+2.5*e.activityExponent*Math.log10(t);return Math.max(s,e.peakMagnitude)}static tailEndAt(e,t,i,s,n,r,a){if(e.tailLengthAu===void 0)return{};const o=1+e.tailLengthAu/s,l=this.subtract({x:t.x*o,y:t.y*o,z:t.z*o},i),h=this.subtract(t,i);return{tailEnd:this.horizontalOf(l,n,r,a),tailLengthDeg:this.angleBetween(h,l)}}static apparentPositionOf(e,t,i){const s=this.orbitOf(e);let n=s.positionAt(t);for(let r=0;r<2;r++){const a=this.length(this.subtract(n,i))/this.LIGHT_SPEED_AU_PER_DAY;n=s.positionAt(t-a)}return n}static horizontalOf(e,t,i,s){const n=wo(i5(),new $t(e.x,e.y,e.z,t)),r=wo(qE(t),n),a=Lv(t,new So(s.lat,s.lng,s.elevationM),!0),o=new $t(r.x-a.x,r.y-a.y,r.z-a.z,t),l=c0(o);return Yu(l.ra,l.dec,i,s)}static earthPositionAt(e){return wo(t5(),vl(me.Earth,e))}static julianDayOf(e){return 2451545+Ei(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new so(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 hv=[{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 $m{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return hv.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),s=[];for(const n of hv){const r=this.magnitudeAt(n,i);r!==void 0&&s.push({outburst:n,position:Qr.ofJ2000(n.raHours,n.decDeg,e,t),magnitude:r})}return s.sort((n,r)=>n.magnitude-r.magnitude)}static brightestAt(e,t){return this.appearancesAt(e,t)[0]}static byId(e){return hv.find(t=>t.id===e)}static magnitudeAt(e,t){const i=e.lightCurve,s=t-e.startJd;if(i.length===0||s<i[0][0]||s>i[i.length-1][0])return;let n=1;for(;n<i.length-1&&i[n][0]<s;)n++;const[r,a]=i[n-1]??i[0],[o,l]=i[n]??i[0];if(o===r)return a;const h=Math.min(1,Math.max(0,(s-r)/(o-r)));return a+h*(l-a)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const XN=[{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}],ud=6.5;class $h{static activeAt(e){return XN.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),s=this.dayOfYear(this.asDate(e.start)),n=this.dayOfYear(this.asDate(e.peak)),r=this.dayOfYear(this.asDate(e.end)),a=this.wrappedDelta(i,n),o=this.wrappedDelta(n,s),l=this.wrappedDelta(r,n);return a<0?a<-o?0:1+a/o:a>0?a>l?0:1-a/l:1}static observedRatePerHour(e,t,i,s=ud){if(t<=0)return 0;const n=ud-s;return e*Math.sin(t*Math.PI/180)/Math.pow(i,n)}static radiantPosition(e,t,i){return Qr.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 Qi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=Ei(e),s=new r0(0,OI(e).elon-90,1),n=wo(o5(i),Iy(s,i)),r=c0(n);return Yu(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=ud){const i=Qi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),s=ud-t;return(Qi.QUIET_RATE_PER_HOUR+i)/Math.pow(Qi.POPULATION_INDEX,s)}static schedule(e){const t=new S0(e.seed^1542469173);return Or.schedule(e).map(i=>{const s=Qi.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),n=i.fromRadiantDeg*Math.PI/180,r=Qi.turnAround(s,t.between(0,360)),a={x:s.x*Math.cos(n)+r.x*Math.sin(n),y:s.y*Math.cos(n)+r.y*Math.sin(n),z:s.z*Math.cos(n)+r.z*Math.sin(n)};return{...i,radiant:Qi.toHorizontal(a),bearingDeg:Qi.bearingFrom(a,s)}})}static turnAround(e,t){const[i,s]=Qi.basisAround(e),n=t*Math.PI/180;return{x:i.x*Math.cos(n)+s.x*Math.sin(n),y:i.y*Math.cos(n)+s.y*Math.sin(n),z:i.z*Math.cos(n)+s.z*Math.sin(n)}}static bearingFrom(e,t){const[i,s]=Qi.basisAround(e),n=e.x*t.x+e.y*t.y+e.z*t.z,r=Qi.normalise({x:t.x-e.x*n,y:t.y-e.y*n,z:t.z-e.z*n});return(Math.atan2(r.x*s.x+r.y*s.y+r.z*s.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=Qi.normalise(Qi.cross(e,t));return[i,Qi.normalise(Qi.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=Qi.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Qi.turnAround(t,e.bearingDeg),s=e.fromRadiantDeg*Math.PI/180;return Qi.toHorizontal({x:t.x*Math.cos(s)+i.x*Math.sin(s),y:t.y*Math.cos(s)+i.y*Math.sin(s),z:t.z*Math.cos(s)+i.z*Math.sin(s)})}static toCartesian(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180,s=Math.cos(t);return{x:s*Math.sin(i),y:Math.sin(t),z:-s*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 NS="https://ufoathome.org/tle/index.json";class fn{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??fn.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(NS)||e.push(NS),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${fn.FIRST_SNAPSHOT}T00:00:00Z`)-fn.MAX_ELEMENT_AGE_DAYS*fn.DAY_MS;if(e.getTime()<t)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(s=>e.getTime()>=Date.parse(s.from)-fn.MAX_ELEMENT_AGE_DAYS*fn.DAY_MS&&e.getTime()<=Date.parse(s.to)+fn.MAX_ELEMENT_AGE_DAYS*fn.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:i,base:s}=t,n=[],r=[];for(const a of Object.keys(i.kinds)){const o=await this.kindAt(a,e,i,s);n.push(...o),r.push(this.coverageOf(a,e,i,o.length>0))}return{objects:n,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(e,t,i,s){const n=t.getTime(),r=i.binDays*fn.DAY_MS,a=Math.floor(n/r),o=n-a*r<r/2?a-1:a+1,l=new Set(i.kinds[e].bins),h=[a,o].map(m=>new Date(m*r).toISOString().slice(0,10)).filter(m=>l.has(m));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,s).href),...h.map(m=>this.binary(new URL(`${e}/${m}.bin`,s).href))]),p=new Map;for(const m of u)for(const v of fn.decode(m,i.recordBytes)){const g=p.get(v.norad);(!g||Math.abs(v.epochMs-n)<Math.abs(g.epochMs-n))&&p.set(v.norad,v)}const f=[];for(const m of p.values()){const v=Math.abs(m.epochMs-n)/fn.DAY_MS;if(v>fn.MAX_ELEMENT_AGE_DAYS)continue;const g=d[m.norad]??{name:String(m.norad)};g.launch&&Date.parse(`${g.launch}T00:00:00Z`)>n||f.push({norad:m.norad,name:g.name,kind:e,launch:g.launch,stdMag:g.stdMag,elements:m,ageDays:v})}return f}coverageOf(e,t,i,s){const{from:n,to:r}=i.kinds[e],a=t.getTime(),o=fn.MAX_ELEMENT_AGE_DAYS*fn.DAY_MS,l=s?"covered":a<Date.parse(n)-o?"before":a>Date.parse(r)+o?"after":"gap";return{kind:e,status:l,from:n,to:r}}static decode(e,t){const i=new DataView(e),s=[];for(let n=0;n+t<=e.byteLength;n+=t)s.push({norad:i.getUint32(n,!0),epochMs:i.getFloat64(n+4,!0),bstar:i.getFloat32(n+12,!0),inclinationDeg:i.getFloat32(n+16,!0),raanDeg:i.getFloat32(n+20,!0),eccentricity:i.getFloat32(n+24,!0),argOfPerigeeDeg:i.getFloat32(n+28,!0),meanAnomalyDeg:i.getFloat32(n+32,!0),meanMotion:i.getFloat64(n+36,!0)});return s}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(s=>{if(!s.ok)throw new Error(`${e}: ${s.status}`);return t(s)}),i.catch(()=>this.files.delete(e)),this.files.set(e,i)),i}}class YN{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 gc{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*gc.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=gc.degOver(e)/t;return i<1?1:Math.min(gc.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Ws{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 gc.DEG_PER_SECOND*3600}static graspOf(e,t={}){if(e.visualAid)return Ws.visualAidGrasp(e,t.focalLengthMm);const i=t.exposureSeconds??e.exposureSeconds,s=t.fNumber??e.fNumber;if(i===void 0||s===void 0||!(i>0)||!(s>0))return Ws.EYE;const n=t.focalLengthMm??e.frame?.focalLengthMm??Ws.UNKNOWN_CAMERA_FOCAL_MM,r=n/s,a=Ws.resolutionArcsec(e,n,r);return{apertureMm:r,exposureSeconds:Math.min(i,Ws.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(e,t){const i=e.visualAid,s=Ws.EYE,n=t??e.frame?.focalLengthMm,r=i.magnification??(n!==void 0&&i.eyepieceFocalMm?n/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,s.apertureMm*r);return{apertureMm:Math.max(a,s.apertureMm),exposureSeconds:s.exposureSeconds,resolutionArcsec:s.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/s.apertureMm))}}static resolutionArcsec(e,t,i){const n=(e.detailUm??Ws.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*Ws.ARCSEC_PER_RADIAN,r=1.22*Ws.WAVELENGTH_M/(i/1e3)*Ws.ARCSEC_PER_RADIAN;return Math.max(n,r)}static trailLimitedSeconds(e){return e/Ws.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=Ws.graspOf(e,t),s=Ws.EYE,n=(i.apertureMm/s.apertureMm)**2,r=i.exposureSeconds/s.exposureSeconds,a=(s.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(n*r*a)}static gainFor(e,t){const i=t.fieldOfViewDeg===void 0?void 0:Qt.focalLengthMmFor(e,t.fieldOfViewDeg);return Ws.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const FS=111320,Vd=Math.PI/180,qN=1.02,jN=1;class bu{static of(e,t){const i=bu.sightings(e,t);if(i.length<2)return;const s=bu.baseline(i);if(!s)return;const{near:n,far:r,closedM:a}=s,o=Math.tan(r.widthDeg/2*Vd)===0?0:Math.tan(n.widthDeg/2*Vd)/Math.tan(r.widthDeg/2*Vd);if(o<qN)return;const l=a/(o-1),h=Lt.sizeMAt(l,n.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:n.t,closedM:a}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(i=>{const s=i.shapes.find(a=>a.sourceId===t)?.shape,n=s?.angular?.widthDeg,r=st(e,i.t);return n===void 0||n<=0||r?.lat===void 0||r.lng===void 0?[]:[{t:i.t,widthDeg:n,lat:r.lat,lng:r.lng,sightAzimuthDeg:s?.aim?.azimuthDeg??r.headingDeg}]}).sort((i,s)=>i.t-s.t)}static baseline(e){let t;for(const i of e)for(const s of e){if(i.t>=s.t)continue;const n=bu.closedAlongSight(i,s),[r,a,o]=n>=0?[s,i,n]:[i,s,-n];o<jN||r.widthDeg<=a.widthDeg||(!t||o>t.closedM)&&(t={near:r,far:a,closedM:o})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*FS,s=(t.lng-e.lng)*FS*Math.cos(e.lat*Vd),n=(e.sightAzimuthDeg??0)*Vd;return i*Math.cos(n)+s*Math.sin(n)}}class Ln{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:Ln.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:Ln.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:Ln.atLeastNearest(e.derivedM),basis:"derived"};const t=Ln.largest(e.range?.minM,e.crossing?.behindM),i=Ln.smallest(e.range?.maxM,e.crossing?.inFrontM),s=t===void 0?void 0:t*Ln.MARGIN,n=i===void 0?void 0:i/Ln.MARGIN;return s!==void 0&&n!==void 0?{distanceM:Ln.atLeastNearest(s<=n?Math.sqrt(s*n):s),basis:"bounded"}:s!==void 0?{distanceM:Ln.atLeastNearest(s),basis:"bounded"}:n!==void 0&&n<Ln.CONVENTIONAL_M?{distanceM:Ln.atLeastNearest(n),basis:"bounded"}:{distanceM:Ln.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(Ln.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)}}class On{static MJU_7={massKg:.37,burnedKg:.26,dragAreaM2:1.2*.0508*.2032,ejectionMS:30,burnS:4.5,luminousIntensityCd:2e4,flameSizeM:1.5,color:"#ffd9a0"};static SAMPLE_MS=100;static STEP_S=.002;static G=9.81;static expand(e){const t=e?.flares;return!e||!t||t.length===0?e:{...e,bodies:[...e.bodies,...t.flatMap(i=>On.bodiesOf(i))]}}static bodiesOf(e){const t={...On.MJU_7,...e.flare},i=[],s=e.aircraft;if(s.model||s.sound){const n=e.releases.map(h=>h.t),r=Math.min(s.t,...n)-12e4,a=Math.max(s.t,...n)+12e4,o=s.model?{color:"#30333a",albedo:.15}:{transparency:1},l=h=>{const d=On.aircraftAt(s,h);return{t:h,eastM:d.x,northM:d.y,altitudeM:d.z,attitude:{headingDeg:s.headingDeg},sizeM:s.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:o}};i.push({id:`${e.id}-aircraft`,title:e.title,model:s.model??{id:"sphere"},track:[l(r),l(a)],sound:s.sound})}return s.glow&&i.push(On.glowBody(e,s.glow)),e.releases.forEach((n,r)=>i.push(On.flareBody(e,t,n,r))),i}static aircraftAt(e,t){const i=e.headingDeg*Math.PI/180,s=(t-e.t)/1e3*e.speedMS;return{x:e.eastM+Math.sin(i)*s,y:e.northM+Math.cos(i)*s,z:e.altitudeM}}static burnShare(e,t){if(t<0||t>=e.burnS)return 0;if(t<.2)return t/.2;const i=e.burnS*.75;return t<=i?1:(e.burnS-t)/(e.burnS-i)}static trajectory(e,t,i,s=On.SAMPLE_MS){const n=e.aircraft,r=n.headingDeg*Math.PI/180,o={...On.aircraftAt(n,i),vx:Math.sin(r)*n.speedMS,vy:Math.cos(r)*n.speedMS,vz:-t.ejectionMS},l=(e.wind?.towardDeg??0)*Math.PI/180,h=e.wind?.speedMS??0,d=Math.sin(l)*h,u=Math.cos(l)*h,p=n.originElevationM??1e3,f=[{t:i,x:o.x,y:o.y,z:o.z}],m=On.STEP_S,v=Math.round(s/1e3/m),g=Math.ceil(t.burnS/m);for(let b=1;b<=g;b++){const w=b*m,y=t.massKg-t.burnedKg*Math.min(1,w/t.burnS),M=1.225*Math.exp(-(o.z+p)/8500),S=o.vx-d,E=o.vy-u,x=o.vz,A=Math.hypot(S,E,x),D=.5*M*t.dragAreaM2*A/y;o.vx=(o.vx+D*m*d)/(1+D*m),o.vy=(o.vy+D*m*u)/(1+D*m),o.vz=(o.vz-On.G*m)/(1+D*m),o.x+=o.vx*m,o.y+=o.vy*m,o.z+=o.vz*m,(b%v===0||b===g)&&f.push({t:i+Math.round(w*1e3),x:o.x,y:o.y,z:o.z})}return f}static glowBody(e,t){const i=t.sizeM/2,s=t.luminousIntensityCd/(Math.PI*i*i),n=[{t:t.fromT,lit:!0}];if(t.onS&&t.offS)for(let l=t.fromT,h=!0;l<t.untilT;h=!h)l+=(h?t.onS:t.offS)*1e3,l<t.untilT&&n.push({t:l,lit:!h});const r=(l,h)=>{const d=On.aircraftAt(e.aircraft,l);return{t:l,eastM:d.x,northM:d.y,altitudeM:d.z,appearance:{color:t.color,luminanceCdM2:h?s:0}}},a=[];n.forEach(({t:l,lit:h},d)=>{d>0&&a.push(r(l-1,!h)),a.push(r(l,h))}),a[0]={...a[0],sizeM:{widthM:t.sizeM,lengthM:t.sizeM,heightM:t.sizeM},present:!0};const o=n[n.length-1];return a.push(r(t.untilT,o.lit),{t:t.untilT+1,present:!1}),{id:`${e.id}-glow`,title:e.title,explains:t.explains,model:{id:"sphere"},track:a}}static flareBody(e,t,i,s){const n=t.flameSizeM,r=n/2,a=t.luminousIntensityCd/(Math.PI*r*r),o=On.trajectory(e,t,i.t),l=o.map((h,d)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...d===0?{sizeM:{widthM:n,lengthM:n,heightM:n},present:!0}:{},appearance:{color:t.color,luminanceCdM2:a*On.burnShare(t,(h.t-i.t)/1e3),...d===0?{haloScale:1}:{}}}));return l.push({t:o[o.length-1].t+1,present:!1}),{id:`${e.id}-flare-${s+1}`,title:e.title,explains:i.explains,model:{id:"sphere"},track:l}}}class Nt{static COMMON={envelopeVolumeM3:.19,massKg:.065,fuelKg:.03,burnS:600,insideExcessK:150,dragAreaM2:.25,luminousIntensityCd:10,widthM:.6,heightM:1,color:"#ff8a24",shape:"classic",paperColor:"#ffffff"};static FLAME_CDM2=5e3;static TITLE={en:"Sky lantern",fr:"Lanterne céleste",es:"Farolillo volador",it:"Lanterna volante"};static FLICKER=.15;static INSIDE_SHARE=2;static PAPER_FULL_CDM2=Nt.COMMON.luminousIntensityCd/(Math.PI*Nt.COMMON.widthM/2*Nt.COMMON.heightM/2);static SAMPLE_MS=1e3;static STEP_S=.05;static COOLING_S=20;static TURBULENCE={horizontalMS:.8,verticalMS:.3,timescaleS:30};static G=9.81;static R_AIR=287.05;static LAPSE=.0065;static expand(e){const t=e?.lanterns;return!e||!t||t.length===0?e:{...e,bodies:[...e.bodies,...t.flatMap(i=>Nt.bodiesOf(i))]}}static bodiesOf(e){return Nt.releasesOf(e).map((t,i)=>Nt.lanternBody(e,t,i))}static releasesOf(e){const t=[...e.releases??[]],i=e.group;if(!i||!(i.count>0))return t;const s=Nt.randomFrom(i.seed??1),n=o=>o.min+(o.max-o.min)*s(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let o=0;o<i.count;o++){const l=i.fromT+r*o+(s()-.5)*r,h=a*Math.sqrt(s()),d=2*Math.PI*s();t.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,l))),explains:i.explains,eastM:Math.round(h*Math.sin(d)*10)/10,northM:Math.round(h*Math.cos(d)*10)/10,burnedS:i.burnedS,seed:Math.floor(s()*4294967296),lantern:{burnS:Math.round(n(i.burnS??{min:480,max:900})),insideExcessK:Math.round(n(i.insideExcessK??{min:125,max:175}))}})}return t}static randomFrom(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let i=t;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}static typeOf(e,t){return{...Nt.COMMON,...e.lantern,...t.lantern}}static heatShare(e,t){if(t<0||t>=e.burnS)return 0;const i=e.burnS*.75;return t<=i?1:(e.burnS-t)/(e.burnS-i)}static windAt(e,t){const i=Nt.componentsOf(e.wind),s=e.windAloft;if(!s)return i;const n=Nt.componentsOf(s),r=Math.max(0,Math.min(1,t/s.atM));return{x:i.x+(n.x-i.x)*r,y:i.y+(n.y-i.y)*r}}static trajectory(e,t,i=Nt.SAMPLE_MS){const s=Nt.typeOf(e,t),n=e.site,r=n.altitudeM??0,a=Math.max(0,t.burnedS??0),o=n.originElevationM??0,l=(e.airTemperatureC??10)+273.15,h={x:n.eastM+(t.eastM??0),y:n.northM+(t.northM??0),z:t.altitudeM??r,vx:0,vy:0,vz:0,excessK:s.insideExcessK*Nt.heatShare(s,a)},d=Nt.STEP_S,u=Math.max(1,Math.round(i/1e3/d)),p=Math.ceil(Math.max(0,s.burnS-a)/d),f=[{t:t.t,x:h.x,y:h.y,z:h.z,light:Nt.heatShare(s,a),tiltDeg:0,tiltTowardDeg:0}],m=Nt.gusts(e.turbulence??Nt.TURBULENCE,Nt.seedOf(t),d);for(let v=1;v<=p;v++){const g=v*d,b=a+g,w=Nt.heatShare(s,b);h.excessK+=(s.insideExcessK*w-h.excessK)*Math.min(1,d/Nt.COOLING_S);const y=h.z-r,M=l-Nt.LAPSE*Math.max(0,y),S=101325*Math.exp(-(h.z+o)/8400),E=S/(Nt.R_AIR*M),x=S/(Nt.R_AIR*(M+h.excessK)),A=s.massKg-s.fuelKg*Math.min(1,b/s.burnS),D=(E-x)*s.envelopeVolumeM3*Nt.G,R=A+x*s.envelopeVolumeM3+.5*E*s.envelopeVolumeM3,L=Nt.windAt(e,y),N=m(),k={x:L.x+N.x,y:L.y+N.y,z:N.z},C=h.vx-k.x,P=h.vy-k.y,F=h.vz-k.z,V=.5*E*s.dragAreaM2*Math.hypot(C,P,F)/R;h.vx=(h.vx+V*d*k.x)/(1+V*d),h.vy=(h.vy+V*d*k.y)/(1+V*d),h.vz=(h.vz+V*d*k.z+(D-A*Nt.G)/R*d)/(1+V*d);const j=h.z<=r&&h.vz<=0;if(j&&(h.vx=0,h.vy=0,h.vz=0),h.x+=h.vx*d,h.y+=h.vy*d,h.z=Math.max(r,h.z+h.vz*d),v%u===0||v===p){const $=k.x-h.vx,ee=k.y-h.vy,re=.5*E*s.dragAreaM2*Math.hypot($,ee,k.z-h.vz)*Math.hypot($,ee);f.push({t:t.t+Math.round(g*1e3),x:h.x,y:h.y,z:h.z,light:w,tiltDeg:j?0:Math.atan2(re,A*Nt.G)*180/Math.PI,tiltTowardDeg:(Math.atan2($,ee)*180/Math.PI+360)%360})}}return f}static seedOf(e){return e.seed!==void 0?e.seed:Math.round(e.t)*2654435761+Math.round((e.eastM??0)*100)*40503+Math.round((e.northM??0)*100)>>>0}static gusts(e,t,i){const s=Nt.randomFrom(t),n=()=>Math.sqrt(-2*Math.log(Math.max(1e-12,s())))*Math.cos(2*Math.PI*s()),r=e.timescaleS>0?Math.exp(-i/e.timescaleS):0,a=Math.sqrt(1-r*r),o={x:e.horizontalMS*n(),y:e.horizontalMS*n(),z:e.verticalMS*n()};return()=>(o.x=r*o.x+a*e.horizontalMS*n(),o.y=r*o.y+a*e.horizontalMS*n(),o.z=r*o.z+a*e.verticalMS*n(),o)}static componentsOf(e){if(!e)return{x:0,y:0};const t=e.towardDeg*Math.PI/180;return{x:Math.sin(t)*e.speedMS,y:Math.cos(t)*e.speedMS}}static lanternBody(e,t,i){const s=Nt.typeOf(e,t),n=s.luminousIntensityCd/(Math.PI*s.widthM/2*s.heightM/2),r=Nt.trajectory(e,t),a={widthM:s.widthM,lengthM:s.widthM,heightM:s.heightM},o=Nt.through(s.color,s.paperColor),l=r.map((h,d)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...d===0?{sizeM:a,present:!0}:{},attitude:{headingDeg:Math.round(h.tiltTowardDeg),pitchDeg:-Math.round(h.tiltDeg*10)/10},appearance:{color:o,luminanceCdM2:n*h.light,...d===0?{albedo:.6,haloScale:1}:{}},lights:Nt.lightsOf(n*h.light)}));return l.push({t:r[r.length-1].t+1,present:!1}),{id:`${e.id}-lantern-${i+1}`,title:Nt.TITLE,explains:t.explains,model:{id:`ufoathome-sky-lantern-${s.shape}`},modelParameters:{paperColor:s.paperColor},flicker:Nt.FLICKER,altitudeFrom:{eastM:r[0].x,northM:r[0].y},track:l}}static lightsOf(e){return{paper:e,"paper-inside":e*Nt.INSIDE_SHARE,flame:e>0?Nt.FLAME_CDM2*e/Nt.PAPER_FULL_CDM2:0}}static through(e,t){const i=o=>[1,3,5].map(l=>parseInt(o.slice(l,l+2),16)/255),s=i(e),n=i(t),r=s.map((o,l)=>o*n[l]),a=Math.max(...s)/(Math.max(...r)||1);return"#"+r.map(o=>Math.round(Math.min(1,o*a)*255).toString(16).padStart(2,"0")).join("")}}class h1{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=h1.FIRST_DAY}}class ZN{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,s){try{return await(await this.provider()).between(e,t,i,s)}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 JN="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",sy=[{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 ZN(JN,c=>h1.mayCover(c),async()=>new(await oe(async()=>{const{AdsbLolArchiveProvider:c}=await import("./AdsbLolArchiveProvider-DS9ev-HU.js");return{AdsbLolArchiveProvider:c}},[],import.meta.url)).AdsbLolArchiveProvider)}];class Pn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const s=Pn.positionAt(e,i);if(!s)return;const n=De.seenFrom(t,s.geo);if(!(n.altitudeDeg<0))return{track:e,sky:n,altitudeFt:s.altitudeFt,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg,angularRateDegPerS:Pn.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(s=>Pn.seenFrom(s,t,i)??[])}static groundDistanceKm(e,t){const i=Math.PI/180,s=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*Pn.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(s)))}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 s=0;for(;s<i.length-1&&i[s+1].t<=t;)s++;const n=i[s],r=i[s+1]??n,a=r.t-n.t;if(a>Pn.MAX_GAP_S*1e3)return;const o=a>0?(t-n.t)/a:0,l=n.altitudeFt+(r.altitudeFt-n.altitudeFt)*o,h=(r.lng-n.lng+540)%360-180;return{geo:{lat:n.lat+(r.lat-n.lat)*o,lng:Pn.wrapLongitude(n.lng+h*o),heightM:l*Pn.FT_TO_M},altitudeFt:l,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg}}static angularRate(e,t,i){const s=Pn.positionAt(e,i-500),n=Pn.positionAt(e,i+500);if(!s||!n)return;const r=Pn.unit(De.seenFrom(t,s.geo)),a=Pn.unit(De.seenFrom(t,n.geo)),o=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(o)*180/Math.PI}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180;return[Math.cos(t)*Math.sin(i),Math.cos(t)*Math.cos(i),Math.sin(t)]}}const US="https://ufoathome.org/fireballs/index.json";class Pr{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??Pr.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(US)||e.push(US),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=Pr.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!Pr.mayCover(t))return;const i=await this.loadIndex();if(!i)return;const s=new Set([new Date(e).toISOString().slice(0,7),new Date(t).toISOString().slice(0,7)]);return[...s].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...s].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=Pr.peakFraction(e),s={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},n=De.seenFrom(t,s);if(!(n.altitudeDeg<0))return{record:e,peak:n,magnitude:e.peakMagnitude+5*Math.log10(n.distanceKm/De.STANDARD_DISTANCE_KM)}}static asReentry(e,t){const i=e.t-t,s=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:s,lat:e.to[0],lng:e.to[1],altitudeKm:e.to[2]}],fragments:[{absoluteMagnitude:e.peakMagnitude,color:Pr.COLOR,trainS:Pr.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(s=>s.ok?s.json():[]).catch(()=>[]),this.months.set(e,i)),i}}f0();const QN={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},e8="{name} — mag {mag}, {alt}° above the horizon",t8="{name} — {size}, {distance} away",i8="{name} — satellite, mag {mag}, {height} km up",s8={name:"Re-entry",piece:"{name} — mag {mag}, {height} km up, {distance} km away",fragment:"{name}, a fragment — mag {mag}, {height} km up, {distance} km away"},zS={ghost:"Ghost: {name}",halo:"Halo: {name}",double:"Double: {name}",unnamed:"a light",detail:"{name}. {cause}, {where}.",causes:{lens:"A reflection between two surfaces of the lens",sensor:"The sensor's reflection, sent back by its cover glass",filter:"The sensor's reflection, sent back by the filter",glass:"A reflection between the two faces of the glass in front of the lens",drops:"Light scattered by drops on the glass",condensation:"Light scattered by condensation on the glass",dirt:"Light scattered by dirt on the glass"},opposite:"across the centre of the picture from the light",sameSide:"on the same side of the centre as the light",around:"round the light",drop:{lens:"Drop on the lens",filter:"Drop on the filter",window:"Drop on the window",windscreen:"Drop on the windscreen"},dropDetail:"{name}. Like a small lens, it shows upside down and blurred what is on the other side of it, rather than what is behind it."},n8={name:"Afterimage, in the eye",detail:"{name}: where the image of a light brighter than the Sun fell, the retina's pigment is bleached: for a few seconds it goes on glowing, white then coloured, and then what is seen there looks darker. It stays where it is in the field of view whichever way the eye turns, and takes minutes to fade."},r8={name:"Rocket plume",detail:"{name} — {part}, {distance} away, {height} km up",ascent:"exhaust of the ascent",burn:"exhaust of an engine burn",vent:"vented propellant"},qA="satellites-change",jA="fireballs-change",ZA="references-change",a8="aircraft-change",o8="rr0-confrontation",l8="{name} — mag {mag}, {alt}° below the horizontal",dv="Credits",BS="comet:",HS="nova:",uv={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",trafficlight:"Traffic light",crossing:"Pedestrian crossing",roadsign:"Road sign",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},c8=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,h8=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,d8=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,u8=-18,p8={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Af={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Rt 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",Fh,Uh,Jl]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new I;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new fn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Pr;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static NO_BEAMS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=sy[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return Rt.trafficRuntimeLoading??=oe(()=>import("./trafficRuntime-DVOOnJGD.js"),__vite__mapDeps([10,5]),import.meta.url).then(e=>Rt.trafficRuntime=e),Rt.trafficRuntimeLoading.catch(()=>{Rt.trafficRuntimeLoading=void 0}),Rt.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new Ah;vehicleAudio=new b_;aircraftAudio;vehicleHearing=new fm;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{if(this.lastHover={clientX:e.clientX,clientY:e.clientY,altKey:e.altKey},this.ghostMissedSinceMs=void 0,this.hoverFrame!==void 0&&e.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=e.altKey,this.hoverAt(this.lastHover),this.hoverFrame===void 0&&(this.hoverFrame=requestAnimationFrame(()=>{this.hoverFrame=void 0,this.hoverPending&&this.lastHover&&this.hoverAt(this.lastHover),this.hoverPending=!1}))};ghostMissedSinceMs;static GHOST_KEPT_MS=600;ghostStillUnder(e,t){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return!0;const s=(e.clientX-i.left)/i.width*2-1,n=1-(e.clientY-i.top)/i.height*2;return this.sceneRenderer.ghostsReadableAt(s,n)?this.sceneRenderer.pickGhostAt(s,n)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=t,t-this.ghostMissedSinceMs>Rt.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;hoverAt(e){if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(i.width===0||i.height===0)return;const s=(e.clientX-i.left)/i.width*t.width,n=(e.clientY-i.top)/i.height*t.height;if(this.ufoElement.hasVisibleShapeAt(s,n)){this.hoverTooltip.hidden=!0;return}const r=(e.clientX-i.left)/i.width*2-1,a=-((e.clientY-i.top)/i.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(r,a))return;const o=this.pickAt(r,a,!0,e.altKey);o?this.showHoverTooltip(e,e.altKey&&o.detail?o.detail():o.name):this.hoverTooltip.hidden=!0,this.showGhostPath(o?.path,i)}showGhostPath(e,t){if(!e){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),s=u=>({x:t.left-i.left+(u.x+1)/2*t.width,y:t.top-i.top+(1-u.y)/2*t.height}),n=s(e.from),r=s(e.to),a=s({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[o,l,h,d]=Array.from(this.ghostPath.children);for(const u of[o,l])u.setAttribute("x1",String(n.x)),u.setAttribute("y1",String(n.y)),u.setAttribute("x2",String(r.x)),u.setAttribute("y2",String(r.y));h.setAttribute("cx",String(a.x)),h.setAttribute("cy",String(a.y)),d.setAttribute("cx",String(r.x)),d.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(e,t,i=!0,s=!1){const n=this.naming,r=n.names;if(s&&this.sceneRenderer.pickDropAt(e,t)){const x=r?.ghostTooltip??zS,A=x.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:A,detail:()=>x.dropDetail.replace("{name}",A)}}const a=this.sceneRenderer.pickBodyAt(e,t);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const o=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(e,t):void 0,l=o?this.interpretationShown?.bodies.find(x=>x.id===o):void 0,h=l?this.said.read(l.title)||(l.model.id==="figure"?n.decorKind("entity",uv.entity):void 0):void 0;if(o!==void 0&&h)return{kind:"body",id:o,name:h};const d=this.ufoElement.sighting.skyEvents?.beams,u=d?.length?this.sceneRenderer.pickBeamAt(e,t):void 0,p=u?d?.find(x=>x.id===u.id):void 0;if(u&&p){const x=this.said.read(p.title)||"Laser";return{kind:"beam",id:p.id,name:x,detail:()=>`${x} (${p.wavelengthNm} nm, ${p.powerW.toLocaleString()} W), ${this.distanceText(u.distanceM)}`}}const f=i?this.ghostPick(e,t):void 0;if(f)return f;if(this.sceneRenderer.pickAfterimageAt(e,t)){const x=this.naming.names?.afterimageTooltip??n8;return{kind:"afterimage",name:x.name,detail:()=>x.detail.replace("{name}",x.name)}}const m=this.pickDecorAt(e,t),v=m?this.ufoElement.sighting.decor.find(x=>x.id===m):void 0;if(v){const x=this.said.read(v.title)||n.decorKind(v.kind,uv[v.kind]);return{kind:"decor",id:v.id,name:x,detail:()=>this.decorTooltip(v,x)}}const g=this.sceneRenderer.pickRailwayAt(e,t);if(g){const x=r?.railwayTooltip??Jr.ENGLISH;return{kind:"railway",id:g.line.id,name:Jr.name(g.line,x),detail:()=>Jr.detail(g,x,A=>this.distanceText(A))}}const b=this.trafficTooltipAt(e,t);if(b)return{kind:"traffic",name:b};const w=this.plumePickAt(e,t);if(w)return w;const y=this.sceneRenderer.pickSatelliteAt(e,t);if(y)return{kind:"satellite",name:(r?.satelliteTooltip??i8).replace("{name}",y.name).replace("{mag}",y.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(y.heightKm).toLocaleString())};const M=this.reentryPickAt(e,t);if(M)return M;const S=this.sceneRenderer.pickOpticsAt(e,t);if(S){const x=(r?.opticsTooltips??FN)[S.id].replace("{angle}",String(Math.round(S.angleDeg??0)));return{kind:"optics",id:S.id,name:x.split(" — ")[0],detail:()=>x}}const E=this.sceneRenderer.pickStarAt(e,t);if(E){const x=E.star.mag,A=E.altitudeDeg,D=A<0?r?.starTooltipBelow??l8:r?.starTooltip??e8,R=n.star(E.star);return{kind:"star",name:R,detail:()=>D.replace("{name}",R).replace("{mag}",x.toLocaleString(void 0,{maximumFractionDigits:Math.abs(x)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(A))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(e,t){const i=this.ufoElement.canvasElement,s={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},n=`${Math.round(e/s.x)}:${Math.round(t/s.y)}`,r=performance.now(),a=this.ghostLights.get(n);if(a&&r-a.atMs<Rt.GHOST_LIGHT_KEPT_MS)return a.light;let o=this.shiningDecorNear(e,t,2*Math.max(s.x,s.y)),l;if(!o)for(const[h,d]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const u=this.pickAt(e+h*s.x,t+d*s.y,!1);if(u?.kind==="star")l??=u;else if(u){o=u;break}}return o??=this.shiningDecorNear(e,t,6*Math.max(s.x,s.y)),o??=l,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(n,{light:o??null,atMs:r}),o??null}ghostPick(e,t){const i=this.sceneRenderer.pickGhostAt(e,t);if(!i)return;const s=this.naming.names?.ghostTooltip??zS,n=this.lightOfGhost(i.source.x,i.source.y)??void 0,r=(n?.kind==="star"?n.name.split(" — ")[0]:n?.name)??s.unnamed,a=i.ghost,l=(Ci.scatters(a)?s.halo:a.cause==="glass"?s.double:s.ghost).replace("{name}",r),h=a.scale<0?s.opposite:a.scale===1?s.around:s.sameSide;return{kind:"ghost",id:n?.id,name:l,detail:()=>s.detail.replace("{name}",l).replace("{cause}",s.causes[a.cause??"lens"]).replace("{where}",h),path:{from:{x:a.scale*i.source.x,y:a.scale*i.source.y},to:i.source}}}shiningDecorNear(e,t,i){let s;for(const n of this.ufoElement.sighting.decor){if(!(n.kind==="streetlight"||n.kind==="trafficlight"||(n.lights?.length??0)>0||n.kind==="vehicle"&&n.lit))continue;const a=this.sceneRenderer.decorScreenBox(n.id);if(!a)continue;const o=Math.hypot(Math.max(a.minX-e,0,e-a.maxX),Math.max(a.minY-t,0,t-a.maxY));if(o>i||s&&o>=s.distance)continue;const l=this.said.read(n.title)||this.naming.decorKind(n.kind,uv[n.kind]);s={distance:o,pick:{kind:"decor",id:n.id,name:l}}}return s?.pick}glassWettingOf(e){const t=JSON.stringify([e.lens,e.instrumentId,e.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==e||this.glassWetting.key!==t){const i=new jl(s=>{if(!Ci.records(e.instrument)||!Ci.falling(e.lens))return 0;const n=wd(e,s*1e3),r=st(e,s*1e3);return(n.precipitationAmount??1)*Ci.impactRate(n,e.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:n.windDirectionDeg,windSpeedMS:n.windSpeed})});this.glassWetting={sighting:e,key:t,wetting:i}}return this.glassWetting.wetting}glassWetting;plumePickAt(e,t){const i=this.ufoElement.sighting.skyEvents?.launches,s=i?.length?this.sceneRenderer.pickPlumeAt(e,t):void 0,n=s?i?.find(l=>l.id===s.launchId):void 0;if(!s||!n)return;const r=this.naming.names?.plumeTooltip??r8,a=this.said.read(n.title)||n.vehicle?.mission||r.name,o=()=>s.release===void 0||s.release==="burn"?r.ascent:n.jets?.find((h,d)=>`jet:${h.id??d}`===s.release)?.kind==="vent"?r.vent:r.burn;return{kind:"plume",id:n.id,name:a,detail:()=>r.detail.replace("{name}",a).replace("{part}",o()).replace("{distance}",this.distanceText(s.centre.distanceKm*1e3)).replace("{height}",Math.round(s.heightKm??0).toLocaleString())}}distanceText(e){return e>=1e3?`${(e/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${e.toLocaleString(void 0,{maximumFractionDigits:e<10?1:0})} m`}decorTooltip(e,t){const i=l=>l.toLocaleString(void 0,{maximumFractionDigits:l<10?1:0}),s=ue.sizeOf(e),n=this.sceneRenderer.decorDistanceM(e.id),r=n===void 0?"":this.distanceText(n);return(this.naming.names?.decorTooltip??t8).replace("{name}",t).replace("{size}",`${i(s.widthM)} × ${i(s.lengthM)} × ${i(s.heightM)} m`).replace("{distance}",r)}bodyName(e){const t=e.startsWith(BS)?e.slice(BS.length):void 0,i=t?YA.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const s=e.startsWith(HS)?$m.byId(e.slice(HS.length)):void 0;if(s)return this.naming.nova(s);const n=QN[e];return n===void 0?e:this.naming.body(e,n)}get naming(){return this.sceneNaming}sceneNaming=new Wm;namesLanguage="en";async loadSceneNames(){const e=$u(Sr.preferencesFor(this),Wu);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await xE(e);e===this.namesLanguage&&this.applySceneNaming(new Wm(t))}setBusy(e,t=""){this.busyElement.hidden=!e,this.busyNote.textContent=e?t:"",this.busyElement.setAttribute("aria-label",t),this.busyElement.setAttribute("aria-busy",String(e))}renderLoaderText(e,t){let i=0;const s=(n,r)=>{n.setAttribute("aria-label",r),n.replaceChildren(),r.split(" ").forEach((a,o)=>{o>0&&n.append(" ");const l=document.createElement("span");l.className="scene-loader-word",l.setAttribute("aria-hidden","true");for(const h of a){const d=document.createElement("span");d.className="scene-loader-letter",d.style.setProperty("--i",String(i++)),d.textContent=h,l.append(d)}n.append(l),i++})};s(this.loaderNotVideo,e),i+=6,s(this.loaderNote,t)}applySceneNaming(e){this.sceneNaming=e;const t=e.names?.credits??dv;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(),s=e.clientX-i.left+12,n=s+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${n>0?Math.max(0,s-n-4):s}px`,this.hoverTooltip.style.top=`${e.clientY-i.top+12}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};hearDetonations(e,t,i,s){const n=`${i.lat.toFixed(4)},${i.lng.toFixed(4)}`,r=this.detonationsFor;(!r||n!==r.key||e.length!==r.reentries.length||e.some((l,h)=>l!==r.reentries[h]))&&(this.detonationsFor={reentries:[...e],key:n,detonations:e.length?De.detonationsOf(e,i):[]});const a=this.detonationsFor.detonations;if(s)return;const o=this.lastDetonationT;if(this.lastDetonationT=t,!(o===void 0||t<o||t-o>Rt.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const l of a)l.t>o&&l.t<=t&&this.weatherAudio.playDetonation(l.loudness)}reentryPickAt(e,t){const i=this.sceneRenderer.pickReentryAt(e,t);if(!i)return;const s=this.naming.names?.reentryTooltip??s8,n=this.detonationsFor?.reentries.find(d=>d.id===i.view.reentryId),r=(n?.title?this.said.read(n.title):"")||n?.object?.name||s.name,a=i.view.head,o=6371,l=Math.sqrt(o**2+a.distanceKm**2+2*o*a.distanceKm*Math.sin(a.altitudeDeg*Math.PI/180))-o;return{kind:"reentry",name:(i.view.fragmentId.includes(".")?s.fragment:s.piece).replace("{name}",r).replace("{mag}",i.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(l).toLocaleString()).replace("{distance}",Math.round(a.distanceKm).toLocaleString())}}detonates(e){const t=[...e.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],i=st(e,0),s=e.event.place?.[0],n=i?.lat??s?.lat,r=i?.lng??s?.lng;return t.length>0&&n!==void 0&&r!==void 0&&De.detonationsOf(t,{lat:n,lng:r,heightM:i?.elevationM??0}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(e){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),Ls.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(wd(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const e=this.ufoElement.level;this.weatherAudio.setLevel(e),this.vehicleAudio.setLevel(e),this.aircraftAudio?.setLevel(e)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=e=>{if(this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const t=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&t-this.lastPlayingHoverMs>=Rt.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=t,this.ghostStillUnder(this.lastHover,t)&&this.hoverAt(this.lastHover))}this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(e,e),this.weatherAudio.setPaused(!e),this.vehicleAudio.setPaused(!e),this.aircraftAudio?.setPaused(!e),e&&this.unlockIfAlreadyActivated(),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${M_}</style>${w_}`,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 de(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(ZA));const t=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.renderLoaderText("This is not a video","It is a real-time simulation."),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=t,this.poster=new vu(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=n=>{this.holding=n,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.ufoElement=document.createElement(qv),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapFrozenSource=n=>this.frozenMapOf(n),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",n=>this.lookToward(n.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"),s=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",n=>{n.newState==="open"&&pn.fill(s,this)}),this.creditsButton.title=dv,this.creditsButton.setAttribute("aria-label",dv),this.sceneRenderer.onMapSubjectBounds=n=>this.ufoElement.setMapSubjectBounds(n),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(k2,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(n,r)=>this.seekPreviewOf(r).paint(n,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=n=>n.vehicle!==void 0||n.decor.some(r=>r.engine!==void 0)||n.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1)||this.detonates(n),this.ufoElement.addEventListener("referenceview",n=>this.applyReferenceView(n.detail)),this.ufoElement.addEventListener("traceview",n=>this.sceneRenderer.setTracesShown(n.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const n of Rt.GESTURES)this.addEventListener(n,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new rn(Sr.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(e,t){const i=e.vehicle;return i?{setting:xl.at(i.headlights??"auto",i.headlightKeyframes,t)??"auto",headingDeg:this.travelHeadingAt(e,t)}:void 0}travelHeadingAt(e,t){const i=st(e,t);if(!i)return 0;for(const s of[400,-400]){const n=st(e,t+s);if(!n||i.lat===void 0||i.lng===void 0||n.lat===void 0||n.lng===void 0)break;const r=ut(n.lat,n.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(s<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(e){const t=e.allKeyframes;if(this.routeCache?.track===e&&this.routeCache.count===t.length)return this.routeCache.route;const i=t.flatMap(n=>n.pose.lat!==void 0&&n.pose.lng!==void 0?[{lat:n.pose.lat,lng:n.pose.lng}]:[]),s=i.length>=2?i:void 0;return this.routeCache={track:e,count:t.length,route:s},s}traceLabels(e){const t=Sr.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==e||this.traceLabelsFor.language!==t){const i=new Map;for(const s of e){const n=this.said.read(s.title);n&&i.set(s.id,n)}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 Rt.GESTURES)document.addEventListener(t,this.handlePageGesture,!0);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(e=>{if(e[e.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of Rt.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 s=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(s)&&s>0?s:Math.min(window.devicePixelRatio||1,2))}(e===Fh||e===Uh||e===Jl)&&i!==t&&this.forwardPlayerAttributes(),e===Jl&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const e of[Fh,Uh,Jl]){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=st(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:s}=ut(e.lat,e.lng,t.lat,t.lng);if(Math.hypot(i,s)<1)return this.setLookOffset(0,0);const n=(Math.atan2(i,-s)*180/Math.PI+360)%360;this.setLookOffset(((n-t.headingDeg)%360+540)%360-180,-t.pitchDeg)}setLookOffset(e,t){this.sceneRenderer.setLookOffset(e,t),this.ufoElement.setLookOffset(e,t),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setCloudRendering(e){this.sceneRenderer.setCloudRendering(e)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity*(e.precipitationAmount??1),e.windSpeed)}pickCloudAt(e,t){return this.sceneRenderer.pickCloudAt(e,t)}cloudDirectionAt(e,t){return this.sceneRenderer.cloudDirectionAt(e,t)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}decorScreenBox(e){return this.sceneRenderer.decorScreenBox(e)}decorDrawnOffset(e){return this.sceneRenderer.decorDrawnOffset(e)}decorGroundPointAt(e,t,i,s=0){return this.sceneRenderer.decorGroundPointAt(e,t,i,s)}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=na.recording(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(e,t,i=!0){this.poster.show(e,t,i)}applyHold(){const e=this.holding,t=this.poster.up;this.loader.hidden=!e||t,e&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=e||t,this.ufoElement.controlsHeld=e||t,this.ufoElement.holdClock(e)}holdForNewScene(e){this.sceneRenderer.holdForNewScene(e)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(e){this.sceneRenderer.documentUrl=e}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){const t=Ui.toCurrent(e);this.ufoElement.sightingData=t,this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(t),this.interpretationShown=this.inTheRound?Nt.expand(On.expand(this.ufoElement.sighting.interpretation)):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(e){const t=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(e.width/t);return e.height!==i&&(e.height=i),this.seekPreview??=new Bm(this,()=>document.createElement(Km))}showAt(e){this.ufoElement.currentTime=e,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(e){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const t=e.getContext("2d");return t?(t.imageSmoothingQuality="high",t.drawImage(this.sceneCanvas,0,0,e.width,e.height),!0):!1}referenceAspect(e){return this.sceneRenderer.referenceAspect(e)}screenPointOf(e){return this.sceneRenderer.screenPointOf(e)}directionAt(e,t){return this.sceneRenderer.directionAt(e,t)}referenceFailure(e){return this.sceneRenderer.referenceFailure(e)}applyReferenceView(e){this.sceneRenderer.setReferencesShown(e.shown);for(const t of this.ufoElement.sighting.references){const i=e.views?.[t.id];this.sceneRenderer.setReferenceView(t.id,{opacity:i?i.shown?i.opacity:0:e.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(e){this.liveTerrainProviders=e,this.frozenKey=void 0,this.applyFrozen(this.ufoElement.sighting.frozen)}liveTerrainProviders;frozenKey="none";applyFrozen(e){const t=ts.isEmpty(e)?"none":`${JSON.stringify(e)}
|
|
11495
|
+
`);let n=wa.cache.get(s);return n||(n=Promise.all(i.map(r=>wa.load(r.url))).then(r=>r.reduce((a,o)=>wa.concat(a,o))),wa.cache.set(s,n)),n}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=(s,n)=>{const r=new Float32Array(s.length+n.length);return r.set(s,0),r.set(n,s.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 mi{constructor(e){if(this.heights=e,e.length!==mi.WIDTH*mi.HEIGHT)throw new Error(`a lunar relief has ${mi.WIDTH*mi.HEIGHT} samples, not ${e.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*mi.SAMPLES_PER_DEGREE;static HEIGHT=180*mi.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=mi.SAMPLES_PER_DEGREE,s=(t%360+360)%360*i-.5,n=(90-e)*i-.5,r=Math.floor(s),a=Math.floor(n),o=s-r,l=n-a,h=(p,f)=>{const m=(p%mi.WIDTH+mi.WIDTH)%mi.WIDTH,v=Math.min(mi.HEIGHT-1,Math.max(0,f));return this.heights[v*mi.WIDTH+m]},d=h(r,a)*(1-o)+h(r+1,a)*o,u=h(r,a+1)*(1-o)+h(r+1,a+1)*o;return(d*(1-l)+u*l)*mi.UNIT_KM}static inBand(e,t){const i=Math.PI/180,s=Math.acos(Math.cos(e*i)*Math.cos(t*i))*180/Math.PI;return s>=mi.BAND_FROM_DEG&&s<=mi.BAND_TO_DEG}static withBump(e,t,i,s=.4){const n=new Int8Array(mi.WIDTH*mi.HEIGHT),r=mi.SAMPLES_PER_DEGREE,a=Math.ceil(s*r),o=Math.floor(t*r),l=Math.floor((90-e)*r);for(let h=-a;h<=a;h++)for(let d=-a;d<=a;d++)Math.hypot(d,h)<=a&&(n[(l+h)*mi.WIDTH+(o+d+mi.WIDTH)%mi.WIDTH]=Math.round(i/mi.UNIT_KM));return new mi(n)}static smooth(){return new mi(new Int8Array(mi.WIDTH*mi.HEIGHT))}}class Cr{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(e,t,i,s=Cr.SAMPLES){const{s:n,u:r,w:a,distanceKm:o}=Cr.frame(e,t),l=Math.PI/180,h=new Float32Array(s),d=mi.REFERENCE_RADIUS_KM;for(let u=0;u<s;u++){const p=u/s*2*Math.PI,f=Math.cos(p),m=Math.sin(p),v=f*r[0]+m*a[0],g=f*r[1]+m*a[1],b=f*r[2]+m*a[2];let w=0;for(let y=Cr.SEARCH_FROM_DEG;y<=Cr.SEARCH_TO_DEG;y+=Cr.SEARCH_STEP_DEG){const M=Math.cos(y*l),S=Math.sin(y*l),E=M*n[0]+S*v,x=M*n[1]+S*g,A=M*n[2]+S*b,D=Math.asin(Math.max(-1,Math.min(1,A)))/l,R=Math.atan2(x,E)/l,L=d+i.heightKm(D,R),N=Math.atan2(L*S,o-L*M);N>w&&(w=N)}h[u]=w/l}return{radiusDeg:h,meanRadiusDeg:Math.asin(d/o)/l}}static frame(e,t){const i=new So(t.lat,t.lng,t.elevationM),s=Eo(e),n=Lv(e,i,!1),r=new $t(n.x-s.x,n.y-s.y,n.z-s.z,s.t),a=Math.hypot(r.x,r.y,r.z)*Cr.AU_KM,o=Cr.bodyFixed(e),l=o(r),h=Math.hypot(l[0],l[1],l[2]),d=[l[0]/h,l[1]/h,l[2]/h],u=a5(e,i),p=Ay(u),f=wo(u,new $t(-r.x,-r.y,-r.z,s.t)),m=Math.asin(f.z/Math.hypot(f.x,f.y,f.z)),v=Math.atan2(-f.y,f.x),g=new $t(-Math.sin(m)*Math.cos(v),Math.sin(m)*Math.sin(v),Math.cos(m),s.t),b=new $t(-Math.sin(v),-Math.cos(v),0,s.t);return{s:d,u:o(wo(p,g)),w:o(wo(p,b)),distanceKm:a}}static surfacePoint(e,t,i,s){const{s:n,u:r,w:a}=Cr.frame(e,t),o=Math.PI/180,l=[0,1,2].map(d=>Math.cos(i*o)*r[d]+Math.sin(i*o)*a[d]),h=[0,1,2].map(d=>Math.cos(s*o)*n[d]+Math.sin(s*o)*l[d]);return{latDeg:Math.asin(h[2])/o,lonDeg:Math.atan2(h[1],h[0])/o}}static radiusAt(e,t){const i=e.radiusDeg.length,s=(t/360*i%i+i)%i,n=Math.floor(s),r=s-n;return e.radiusDeg[n]*(1-r)+e.radiusDeg[(n+1)%i]*r}static uncoveredFraction(e,t,i){const s=e.radiusDeg.length,n=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<s;a++){const o=a/s*2*Math.PI,l=Math.cos(o),h=Math.sin(o),d=l*i.upDeg+h*i.rightDeg,u=d*d-n+t*t;if(u<=0)continue;const p=Math.sqrt(u),f=d+p;if(f<=0)continue;const m=Math.max(0,d-p),v=Math.max(m,e.radiusDeg[a]);f>v&&(r+=.5*(f*f-v*v))}return Math.min(1,Math.max(0,r*(2*Math.PI/s)/(Math.PI*t*t)))}static AU_KM=1495978707e-1;static bodyFixed(e){const t=x5(me.Moon,e),i=Math.PI/180,s=t.ra*15*i,n=t.dec*i,r=t.spin*i,a=(l,[h,d,u])=>[Math.cos(l)*h+Math.sin(l)*d,-Math.sin(l)*h+Math.cos(l)*d,u],o=(l,[h,d,u])=>[h,Math.cos(l)*d+Math.sin(l)*u,-Math.sin(l)*d+Math.cos(l)*u];return l=>a(r,o(Math.PI/2-n,a(Math.PI/2+s,[l.x,l.y,l.z])))}static subObserverPoint(e,t){const i=new So(t.lat,t.lng,t.elevationM),s=Eo(e),n=Lv(e,i,!1),r=Cr.bodyFixed(e)(new $t(n.x-s.x,n.y-s.y,n.z-s.z,s.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class gu{static cache=new Map;static load(e){let t=gu.cache.get(e);return t||(t=gu.fetchRelief(e).catch(()=>{}),gu.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 s=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(s).arrayBuffer())}return new mi(new Int8Array(i.buffer,i.byteOffset,i.length))}}class Vm{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=Vm.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(e){const t=Vm.MATRICES[String(e.type)];if(!t)return cr.NONE;const i=Number(e.severity??100),s=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:t.map((r,a)=>cr.IDENTITY[a]+(r-cr.IDENTITY[a])*s),contrastGain:1}}}class c1{static ID="fatigue";id=c1.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(e){return cr.NONE}}class Kl{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=Kl.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary), drawn up to 0.1 % at most: a higher level is recorded but shown as 0.1 %, since nothing was measured past it. Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:Kl.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(e){const t=Number(e.bloodAlcohol??0),i=Math.max(0,Math.min(Kl.MAX_EFFECT_LEVEL,Number.isFinite(t)?t:0));if(i===0)return cr.NONE;const s=i/Kl.MEASURED_LEVEL*Kl.MEASURED_LOSS_DB;return{colorMatrix:cr.IDENTITY,contrastGain:10**(-s/20)}}}class mc{static ALL=[new Vm,new Kl,new c1];static byId(e){return mc.ALL.find(t=>t.id===e)}static perceptionOf(e){return mc.ALL.reduce((t,i)=>cr.combine(t,i.perceive(e?.[i.id]??{})),cr.NONE)}static compact(e){const t={};for(const i of mc.ALL){const s=e[i.id]??{},n=Object.fromEntries(i.settings.filter(r=>s[r.id]!==void 0&&s[r.id]!==r.default).map(r=>[r.id,s[r.id]]));Object.keys(n).length>0&&(t[i.id]=n)}return Object.keys(t).length>0?t:void 0}}class Wm{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 uc.point(e,this.names?.compassPoints)}towards(e){return uc.towards(e,this.names)}}class Jr{static ENGLISH={kinds:{rail:"Railway",light_rail:"Light rail",tram:"Tramway",subway:"Metro",funicular:"Funicular"},highSpeed:"High-speed line",service:"Siding",singleTrack:"single track",tracks:"{count} tracks",overhead:"overhead wire {height} m above the rail",overheadVoltage:"overhead wire at {voltage}, {height} m above the rail",thirdRail:"third rail",thirdRailVoltage:"third rail at {voltage}",notElectrified:"not electrified",gauge:"{mm} mm gauge",metreGauge:"metre gauge",distance:"{distance} away"};static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(e,t){return e.highSpeed?t.highSpeed:e.service?t.service:t.kinds[e.kind]}static name(e,t){const i=e.name??Jr.kind(e,t);return e.services?.length?`${i} — ${e.services.join(", ")}`:i}static voltage(e,t){return e>=1e3?`${(e/1e3).toLocaleString(t,{maximumFractionDigits:1})} kV`:`${e.toLocaleString(t)} V`}static detail(e,t,i,s){const{line:n}=e,r=[];n.name&&r.push(Jr.kind(n,t).toLocaleLowerCase(s)),r.push(n.tracks>1?t.tracks.replace("{count}",String(n.tracks)):t.singleTrack);const a=n.voltageV?Jr.voltage(n.voltageV,s):void 0;if(e.contactM!==void 0){const o=e.contactM.toLocaleString(s,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?t.overheadVoltage.replace("{voltage}",a):t.overhead).replace("{height}",o))}else n.electrification==="third_rail"?r.push(a?t.thirdRailVoltage.replace("{voltage}",a):t.thirdRail):n.electrification==="none"&&r.push(t.notElectrified);return n.gaugeMm===Jr.METRE_GAUGE_MM?r.push(t.metreGauge):n.gaugeMm!==Jr.STANDARD_GAUGE_MM&&r.push(t.gauge.replace("{mm}",n.gaugeMm.toLocaleString(s))),r.push(t.distance.replace("{distance}",i(e.distanceM))),n.services?.length?`${Jr.name(n,t)}; ${r.join(", ")}`:`${Jr.name(n,t)} — ${r.join(", ")}`}}class vu{constructor(e,t){this.element=e,this.onChange=t,e.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(e,t,i=!0){const s=vu.resolve(e,t);if(this.url=s,!s||!i){this.release();return}this.element.src=s,this.element.hidden=!1;const n=this.shown;this.shown=!0,n||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(e,t){if(!(typeof e!="string"||e.trim()===""))try{const i=new URL(e.trim(),t??location.href);return i.protocol!=="https:"&&i.protocol!=="http:"?void 0:i.origin===vu.PUBLISHED_ORIGIN&&vu.isDevelopmentHost(location.hostname)?location.origin+i.pathname:i.href}catch{return}}static PUBLISHED_ORIGIN="https://ufoathome.org";static isDevelopmentHost(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e.endsWith(".localhost")}}const FN={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},UN="Global Meteor Network",zN="https://globalmeteornetwork.org/data/",BN="“Thunder” by Jerimee",HN="https://creativecommons.org/licenses/by/3.0/",GN="CC BY 3.0";class pn{static fill(e,t){e.innerHTML="";const i=u=>e.appendChild(u),s=t.currentTerrainAttribution;s&&i(pn.text(s));const n=t.currentRoadAttribution;n&&i(pn.text(n));const r=t.currentWaterAttribution;r&&i(pn.text(r));const a=t.currentRailwayAttribution;a&&i(pn.text(a));const o=t.ufoElement.observerMapCredit;o&&!s?.includes(o)&&i(pn.text(o));for(const u of t.decorModelCredits){const p=u.author?` — ${u.author}`:"",f=document.createElement("li");u.sourceUrl?f.append(pn.link(u.sourceUrl,u.title),document.createTextNode(`${p} (${u.license})`)):f.textContent=`${u.title}${p} (${u.license})`,i(f)}for(const u of t.ufoElement.sighting.references){if(!u.credit)continue;const p=document.createElement("li");u.creditUrl?p.appendChild(pn.link(u.creditUrl,u.credit)):p.textContent=u.credit,i(p)}if(t.ufoElement.sighting.traces.length>0){const u=new rn(Sr.preferencesFor(t)),p=new Set(t.ufoElement.sighting.traces.map(f=>u.read(f.source)).filter(f=>!!f));for(const f of p)i(pn.text(f))}const l=t.satelliteState;if(l.status==="ready"&&l.credit){const u=document.createElement("li");u.appendChild(pn.link(l.creditUrl??"",l.credit)),i(u)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const u=document.createElement("li");u.append(pn.link(zN,UN),document.createTextNode(" (CC BY 4.0)")),i(u)}const h=t.aircraftState;if(h.status==="ready"&&h.shown>0){const u=document.createElement("li");if(u.appendChild(pn.link(h.creditUrl,h.credit)),i(u),h.trailCredit){const p=document.createElement("li");p.appendChild(pn.link(h.trailCredit.creditUrl,h.trailCredit.credit)),i(p)}}const d=pn.text(`${BN} (`);d.append(pn.link(HN,GN),document.createTextNode(")")),i(d)}static text(e){const t=document.createElement("li");return t.textContent=e,t}static link(e,t){const i=document.createElement("a");return i.href=e,i.target="_blank",i.rel="noopener",i.textContent=t,i}}const VN=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,WN=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,PS=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,$N=20,KN=1;class Ah{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}}lc.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 s=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=s==="hail"?Math.min(1,t*1.3+.2):s==="rain"?t:0,s!==this.ambientKey){this.ambientKey=s;const r=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,s!=="none"&&this.startLoop(VN,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,o=>{this.ambientSource=o?.source,this.ambientGain=o?.gain,o&&(o.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/$N,1);const n=i>KN;if(n!==this.windActive){this.windActive=n;const r=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,n&&this.startLoop(WN,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,o=>{this.windSource=o?.source,this.windGain=o?.gain,o&&(o.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:i,windSpeed:s}=this.requested;this.setAmbient(t,i,s)}playThunder(){!this.context||this.paused||this.playOneShot(PS,.9)}playDetonation(e){const t=this.context;if(!t||this.paused)return;const i=Math.min(1,Math.max(0,e)),s=t.createBufferSource();s.buffer=this.crackBuffer(t);const n=t.createBiquadFilter();n.type="lowpass",n.frequency.value=Ah.CRACK_CUTOFF_HZ;const r=t.createGain();r.gain.value=i,s.connect(n).connect(r).connect(this.output(t)),s.start(),this.playOneShot(PS,i,Ah.DETONATION_RATE)}static DETONATION_RATE=.8;static CRACK_CUTOFF_HZ=2500;static CRACK_DECAY_S=.25;crackBuffer(e){if(this.crack?.sampleRate===e.sampleRate)return this.crack;const t=Math.round(e.sampleRate*Ah.CRACK_DECAY_S*6),i=e.createBuffer(1,t,e.sampleRate),s=i.getChannelData(0);for(let n=0;n<t;n++){const r=n/e.sampleRate;s[n]=(Math.random()*2-1)*Math.min(1,r/.005)*Math.exp(-r/Ah.CRACK_DECAY_S)}return this.crack=i,i}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(e,t,i,s){if(t!==i()){e?.source.stop();return}s(e)}async startLoop(e,t){const i=this.context;if(i)try{const s=await this.getBuffer(e),n=i.createBufferSource();n.buffer=s,n.loop=!0;const r=i.createGain();return r.gain.value=t,n.connect(r).connect(this.output(i)),n.start(),{source:n,gain:r}}catch(s){console.warn("Weather ambient sound failed to load, staying silent:",s);return}}async playOneShot(e,t,i=1){const s=this.context;if(s)try{const n=await this.getBuffer(e),r=s.createBufferSource();r.buffer=n,r.playbackRate.value=i;const a=s.createGain();a.gain.value=t,r.connect(a).connect(this.output(s)),r.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(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,i)),i}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}class so{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[s,n]=this.perifocalAxes(),r=Math.sqrt(so.SUN_GM_AU3_PER_DAY2*(1+t)/i);this.perihelionPosition=this.scale(s,i),this.perihelionVelocity=this.scale(n,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),s=this.inverseSemiMajorAxis*i*i,n=this.elements.perihelionAu,r=1-i*i/n*so.stumpffC(s),a=t-i*i*i/Math.sqrt(so.SUN_GM_AU3_PER_DAY2)*so.stumpffS(s);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(e){const t=this.positionAt(e);return Math.hypot(t.x,t.y,t.z)}universalAnomaly(e){if(e===0)return 0;const t=Math.sign(e),i=Math.sqrt(so.SUN_GM_AU3_PER_DAY2)*Math.abs(e),s=a=>{const o=this.inverseSemiMajorAxis*a*a,l=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*l)*a*a*a*so.stumpffS(o)+l*a};let n=Math.max(1,i/this.elements.perihelionAu);for(;s(n)<i;)n*=2;let r=0;for(let a=0;a<so.MAX_ITERATIONS&&n-r>1e-13*Math.max(1,n);a++){const o=(r+n)/2;s(o)<i?r=o:n=o}return t*(r+n)/2}perifocalAxes(){const e=this.elements.ascendingNodeDeg*Math.PI/180,t=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,s=Math.cos(e),n=Math.sin(e),r=Math.cos(t),a=Math.sin(t),o=Math.cos(i),l=Math.sin(i);return[{x:s*r-n*a*o,y:n*r+s*a*o,z:a*l},{x:-s*a-n*r*o,y:-n*a+s*r*o,z:r*l}]}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 YA=[{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 Yf{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 YA.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,s)=>i.magnitude-s.magnitude)[0]}static appearanceOf(e,t,i){const s=Ei(t),n=this.earthPositionAt(s),r=this.apparentPositionOf(e,2451545+s.tt,n),a=this.subtract(r,n),o=this.length(r),l=this.length(a),h=this.tailEndAt(e,r,n,o,s,t,i),d=this.horizontalOf(a,s,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:o,earthDistanceAu:l,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},n)),magnitude:this.magnitudeAt(e,o,l)}}static magnitudeAt(e,t,i){const s=e.absoluteMagnitude+5*Math.log10(i)+2.5*e.activityExponent*Math.log10(t);return Math.max(s,e.peakMagnitude)}static tailEndAt(e,t,i,s,n,r,a){if(e.tailLengthAu===void 0)return{};const o=1+e.tailLengthAu/s,l=this.subtract({x:t.x*o,y:t.y*o,z:t.z*o},i),h=this.subtract(t,i);return{tailEnd:this.horizontalOf(l,n,r,a),tailLengthDeg:this.angleBetween(h,l)}}static apparentPositionOf(e,t,i){const s=this.orbitOf(e);let n=s.positionAt(t);for(let r=0;r<2;r++){const a=this.length(this.subtract(n,i))/this.LIGHT_SPEED_AU_PER_DAY;n=s.positionAt(t-a)}return n}static horizontalOf(e,t,i,s){const n=wo(i5(),new $t(e.x,e.y,e.z,t)),r=wo(qE(t),n),a=Lv(t,new So(s.lat,s.lng,s.elevationM),!0),o=new $t(r.x-a.x,r.y-a.y,r.z-a.z,t),l=c0(o);return Yu(l.ra,l.dec,i,s)}static earthPositionAt(e){return wo(t5(),vl(me.Earth,e))}static julianDayOf(e){return 2451545+Ei(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new so(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 hv=[{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 $m{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return hv.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),s=[];for(const n of hv){const r=this.magnitudeAt(n,i);r!==void 0&&s.push({outburst:n,position:Qr.ofJ2000(n.raHours,n.decDeg,e,t),magnitude:r})}return s.sort((n,r)=>n.magnitude-r.magnitude)}static brightestAt(e,t){return this.appearancesAt(e,t)[0]}static byId(e){return hv.find(t=>t.id===e)}static magnitudeAt(e,t){const i=e.lightCurve,s=t-e.startJd;if(i.length===0||s<i[0][0]||s>i[i.length-1][0])return;let n=1;for(;n<i.length-1&&i[n][0]<s;)n++;const[r,a]=i[n-1]??i[0],[o,l]=i[n]??i[0];if(o===r)return a;const h=Math.min(1,Math.max(0,(s-r)/(o-r)));return a+h*(l-a)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const XN=[{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}],ud=6.5;class $h{static activeAt(e){return XN.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),s=this.dayOfYear(this.asDate(e.start)),n=this.dayOfYear(this.asDate(e.peak)),r=this.dayOfYear(this.asDate(e.end)),a=this.wrappedDelta(i,n),o=this.wrappedDelta(n,s),l=this.wrappedDelta(r,n);return a<0?a<-o?0:1+a/o:a>0?a>l?0:1-a/l:1}static observedRatePerHour(e,t,i,s=ud){if(t<=0)return 0;const n=ud-s;return e*Math.sin(t*Math.PI/180)/Math.pow(i,n)}static radiantPosition(e,t,i){return Qr.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 Qi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=Ei(e),s=new r0(0,OI(e).elon-90,1),n=wo(o5(i),Iy(s,i)),r=c0(n);return Yu(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=ud){const i=Qi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),s=ud-t;return(Qi.QUIET_RATE_PER_HOUR+i)/Math.pow(Qi.POPULATION_INDEX,s)}static schedule(e){const t=new S0(e.seed^1542469173);return Or.schedule(e).map(i=>{const s=Qi.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),n=i.fromRadiantDeg*Math.PI/180,r=Qi.turnAround(s,t.between(0,360)),a={x:s.x*Math.cos(n)+r.x*Math.sin(n),y:s.y*Math.cos(n)+r.y*Math.sin(n),z:s.z*Math.cos(n)+r.z*Math.sin(n)};return{...i,radiant:Qi.toHorizontal(a),bearingDeg:Qi.bearingFrom(a,s)}})}static turnAround(e,t){const[i,s]=Qi.basisAround(e),n=t*Math.PI/180;return{x:i.x*Math.cos(n)+s.x*Math.sin(n),y:i.y*Math.cos(n)+s.y*Math.sin(n),z:i.z*Math.cos(n)+s.z*Math.sin(n)}}static bearingFrom(e,t){const[i,s]=Qi.basisAround(e),n=e.x*t.x+e.y*t.y+e.z*t.z,r=Qi.normalise({x:t.x-e.x*n,y:t.y-e.y*n,z:t.z-e.z*n});return(Math.atan2(r.x*s.x+r.y*s.y+r.z*s.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=Qi.normalise(Qi.cross(e,t));return[i,Qi.normalise(Qi.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=Qi.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Qi.turnAround(t,e.bearingDeg),s=e.fromRadiantDeg*Math.PI/180;return Qi.toHorizontal({x:t.x*Math.cos(s)+i.x*Math.sin(s),y:t.y*Math.cos(s)+i.y*Math.sin(s),z:t.z*Math.cos(s)+i.z*Math.sin(s)})}static toCartesian(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180,s=Math.cos(t);return{x:s*Math.sin(i),y:Math.sin(t),z:-s*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 NS="https://ufoathome.org/tle/index.json";class fn{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??fn.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(NS)||e.push(NS),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${fn.FIRST_SNAPSHOT}T00:00:00Z`)-fn.MAX_ELEMENT_AGE_DAYS*fn.DAY_MS;if(e.getTime()<t)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(s=>e.getTime()>=Date.parse(s.from)-fn.MAX_ELEMENT_AGE_DAYS*fn.DAY_MS&&e.getTime()<=Date.parse(s.to)+fn.MAX_ELEMENT_AGE_DAYS*fn.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:i,base:s}=t,n=[],r=[];for(const a of Object.keys(i.kinds)){const o=await this.kindAt(a,e,i,s);n.push(...o),r.push(this.coverageOf(a,e,i,o.length>0))}return{objects:n,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(e,t,i,s){const n=t.getTime(),r=i.binDays*fn.DAY_MS,a=Math.floor(n/r),o=n-a*r<r/2?a-1:a+1,l=new Set(i.kinds[e].bins),h=[a,o].map(m=>new Date(m*r).toISOString().slice(0,10)).filter(m=>l.has(m));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,s).href),...h.map(m=>this.binary(new URL(`${e}/${m}.bin`,s).href))]),p=new Map;for(const m of u)for(const v of fn.decode(m,i.recordBytes)){const g=p.get(v.norad);(!g||Math.abs(v.epochMs-n)<Math.abs(g.epochMs-n))&&p.set(v.norad,v)}const f=[];for(const m of p.values()){const v=Math.abs(m.epochMs-n)/fn.DAY_MS;if(v>fn.MAX_ELEMENT_AGE_DAYS)continue;const g=d[m.norad]??{name:String(m.norad)};g.launch&&Date.parse(`${g.launch}T00:00:00Z`)>n||f.push({norad:m.norad,name:g.name,kind:e,launch:g.launch,stdMag:g.stdMag,elements:m,ageDays:v})}return f}coverageOf(e,t,i,s){const{from:n,to:r}=i.kinds[e],a=t.getTime(),o=fn.MAX_ELEMENT_AGE_DAYS*fn.DAY_MS,l=s?"covered":a<Date.parse(n)-o?"before":a>Date.parse(r)+o?"after":"gap";return{kind:e,status:l,from:n,to:r}}static decode(e,t){const i=new DataView(e),s=[];for(let n=0;n+t<=e.byteLength;n+=t)s.push({norad:i.getUint32(n,!0),epochMs:i.getFloat64(n+4,!0),bstar:i.getFloat32(n+12,!0),inclinationDeg:i.getFloat32(n+16,!0),raanDeg:i.getFloat32(n+20,!0),eccentricity:i.getFloat32(n+24,!0),argOfPerigeeDeg:i.getFloat32(n+28,!0),meanAnomalyDeg:i.getFloat32(n+32,!0),meanMotion:i.getFloat64(n+36,!0)});return s}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(s=>{if(!s.ok)throw new Error(`${e}: ${s.status}`);return t(s)}),i.catch(()=>this.files.delete(e)),this.files.set(e,i)),i}}class YN{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 gc{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*gc.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=gc.degOver(e)/t;return i<1?1:Math.min(gc.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Ws{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 gc.DEG_PER_SECOND*3600}static graspOf(e,t={}){if(e.visualAid)return Ws.visualAidGrasp(e,t.focalLengthMm);const i=t.exposureSeconds??e.exposureSeconds,s=t.fNumber??e.fNumber;if(i===void 0||s===void 0||!(i>0)||!(s>0))return Ws.EYE;const n=t.focalLengthMm??e.frame?.focalLengthMm??Ws.UNKNOWN_CAMERA_FOCAL_MM,r=n/s,a=Ws.resolutionArcsec(e,n,r);return{apertureMm:r,exposureSeconds:Math.min(i,Ws.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(e,t){const i=e.visualAid,s=Ws.EYE,n=t??e.frame?.focalLengthMm,r=i.magnification??(n!==void 0&&i.eyepieceFocalMm?n/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,s.apertureMm*r);return{apertureMm:Math.max(a,s.apertureMm),exposureSeconds:s.exposureSeconds,resolutionArcsec:s.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/s.apertureMm))}}static resolutionArcsec(e,t,i){const n=(e.detailUm??Ws.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*Ws.ARCSEC_PER_RADIAN,r=1.22*Ws.WAVELENGTH_M/(i/1e3)*Ws.ARCSEC_PER_RADIAN;return Math.max(n,r)}static trailLimitedSeconds(e){return e/Ws.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=Ws.graspOf(e,t),s=Ws.EYE,n=(i.apertureMm/s.apertureMm)**2,r=i.exposureSeconds/s.exposureSeconds,a=(s.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(n*r*a)}static gainFor(e,t){const i=t.fieldOfViewDeg===void 0?void 0:Qt.focalLengthMmFor(e,t.fieldOfViewDeg);return Ws.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const FS=111320,Vd=Math.PI/180,qN=1.02,jN=1;class bu{static of(e,t){const i=bu.sightings(e,t);if(i.length<2)return;const s=bu.baseline(i);if(!s)return;const{near:n,far:r,closedM:a}=s,o=Math.tan(r.widthDeg/2*Vd)===0?0:Math.tan(n.widthDeg/2*Vd)/Math.tan(r.widthDeg/2*Vd);if(o<qN)return;const l=a/(o-1),h=Lt.sizeMAt(l,n.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:n.t,closedM:a}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(i=>{const s=i.shapes.find(a=>a.sourceId===t)?.shape,n=s?.angular?.widthDeg,r=st(e,i.t);return n===void 0||n<=0||r?.lat===void 0||r.lng===void 0?[]:[{t:i.t,widthDeg:n,lat:r.lat,lng:r.lng,sightAzimuthDeg:s?.aim?.azimuthDeg??r.headingDeg}]}).sort((i,s)=>i.t-s.t)}static baseline(e){let t;for(const i of e)for(const s of e){if(i.t>=s.t)continue;const n=bu.closedAlongSight(i,s),[r,a,o]=n>=0?[s,i,n]:[i,s,-n];o<jN||r.widthDeg<=a.widthDeg||(!t||o>t.closedM)&&(t={near:r,far:a,closedM:o})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*FS,s=(t.lng-e.lng)*FS*Math.cos(e.lat*Vd),n=(e.sightAzimuthDeg??0)*Vd;return i*Math.cos(n)+s*Math.sin(n)}}class Ln{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:Ln.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:Ln.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:Ln.atLeastNearest(e.derivedM),basis:"derived"};const t=Ln.largest(e.range?.minM,e.crossing?.behindM),i=Ln.smallest(e.range?.maxM,e.crossing?.inFrontM),s=t===void 0?void 0:t*Ln.MARGIN,n=i===void 0?void 0:i/Ln.MARGIN;return s!==void 0&&n!==void 0?{distanceM:Ln.atLeastNearest(s<=n?Math.sqrt(s*n):s),basis:"bounded"}:s!==void 0?{distanceM:Ln.atLeastNearest(s),basis:"bounded"}:n!==void 0&&n<Ln.CONVENTIONAL_M?{distanceM:Ln.atLeastNearest(n),basis:"bounded"}:{distanceM:Ln.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(Ln.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)}}class On{static MJU_7={massKg:.37,burnedKg:.26,dragAreaM2:1.2*.0508*.2032,ejectionMS:30,burnS:4.5,luminousIntensityCd:2e4,flameSizeM:1.5,color:"#ffd9a0"};static SAMPLE_MS=100;static STEP_S=.002;static G=9.81;static expand(e){const t=e?.flares;return!e||!t||t.length===0?e:{...e,bodies:[...e.bodies,...t.flatMap(i=>On.bodiesOf(i))]}}static bodiesOf(e){const t={...On.MJU_7,...e.flare},i=[],s=e.aircraft;if(s.model||s.sound){const n=e.releases.map(h=>h.t),r=Math.min(s.t,...n)-12e4,a=Math.max(s.t,...n)+12e4,o=s.model?{color:"#30333a",albedo:.15}:{transparency:1},l=h=>{const d=On.aircraftAt(s,h);return{t:h,eastM:d.x,northM:d.y,altitudeM:d.z,attitude:{headingDeg:s.headingDeg},sizeM:s.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:o}};i.push({id:`${e.id}-aircraft`,title:e.title,model:s.model??{id:"sphere"},track:[l(r),l(a)],sound:s.sound})}return s.glow&&i.push(On.glowBody(e,s.glow)),e.releases.forEach((n,r)=>i.push(On.flareBody(e,t,n,r))),i}static aircraftAt(e,t){const i=e.headingDeg*Math.PI/180,s=(t-e.t)/1e3*e.speedMS;return{x:e.eastM+Math.sin(i)*s,y:e.northM+Math.cos(i)*s,z:e.altitudeM}}static burnShare(e,t){if(t<0||t>=e.burnS)return 0;if(t<.2)return t/.2;const i=e.burnS*.75;return t<=i?1:(e.burnS-t)/(e.burnS-i)}static trajectory(e,t,i,s=On.SAMPLE_MS){const n=e.aircraft,r=n.headingDeg*Math.PI/180,o={...On.aircraftAt(n,i),vx:Math.sin(r)*n.speedMS,vy:Math.cos(r)*n.speedMS,vz:-t.ejectionMS},l=(e.wind?.towardDeg??0)*Math.PI/180,h=e.wind?.speedMS??0,d=Math.sin(l)*h,u=Math.cos(l)*h,p=n.originElevationM??1e3,f=[{t:i,x:o.x,y:o.y,z:o.z}],m=On.STEP_S,v=Math.round(s/1e3/m),g=Math.ceil(t.burnS/m);for(let b=1;b<=g;b++){const w=b*m,y=t.massKg-t.burnedKg*Math.min(1,w/t.burnS),M=1.225*Math.exp(-(o.z+p)/8500),S=o.vx-d,E=o.vy-u,x=o.vz,A=Math.hypot(S,E,x),D=.5*M*t.dragAreaM2*A/y;o.vx=(o.vx+D*m*d)/(1+D*m),o.vy=(o.vy+D*m*u)/(1+D*m),o.vz=(o.vz-On.G*m)/(1+D*m),o.x+=o.vx*m,o.y+=o.vy*m,o.z+=o.vz*m,(b%v===0||b===g)&&f.push({t:i+Math.round(w*1e3),x:o.x,y:o.y,z:o.z})}return f}static glowBody(e,t){const i=t.sizeM/2,s=t.luminousIntensityCd/(Math.PI*i*i),n=[{t:t.fromT,lit:!0}];if(t.onS&&t.offS)for(let l=t.fromT,h=!0;l<t.untilT;h=!h)l+=(h?t.onS:t.offS)*1e3,l<t.untilT&&n.push({t:l,lit:!h});const r=(l,h)=>{const d=On.aircraftAt(e.aircraft,l);return{t:l,eastM:d.x,northM:d.y,altitudeM:d.z,appearance:{color:t.color,luminanceCdM2:h?s:0}}},a=[];n.forEach(({t:l,lit:h},d)=>{d>0&&a.push(r(l-1,!h)),a.push(r(l,h))}),a[0]={...a[0],sizeM:{widthM:t.sizeM,lengthM:t.sizeM,heightM:t.sizeM},present:!0};const o=n[n.length-1];return a.push(r(t.untilT,o.lit),{t:t.untilT+1,present:!1}),{id:`${e.id}-glow`,title:e.title,explains:t.explains,model:{id:"sphere"},track:a}}static flareBody(e,t,i,s){const n=t.flameSizeM,r=n/2,a=t.luminousIntensityCd/(Math.PI*r*r),o=On.trajectory(e,t,i.t),l=o.map((h,d)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...d===0?{sizeM:{widthM:n,lengthM:n,heightM:n},present:!0}:{},appearance:{color:t.color,luminanceCdM2:a*On.burnShare(t,(h.t-i.t)/1e3),...d===0?{haloScale:1}:{}}}));return l.push({t:o[o.length-1].t+1,present:!1}),{id:`${e.id}-flare-${s+1}`,title:e.title,explains:i.explains,model:{id:"sphere"},track:l}}}class Nt{static COMMON={envelopeVolumeM3:.19,massKg:.065,fuelKg:.03,burnS:600,insideExcessK:150,dragAreaM2:.25,luminousIntensityCd:10,widthM:.6,heightM:1,color:"#ff8a24",shape:"classic",paperColor:"#ffffff"};static FLAME_CDM2=5e3;static TITLE={en:"Sky lantern",fr:"Lanterne céleste",es:"Farolillo volador",it:"Lanterna volante"};static FLICKER=.15;static INSIDE_SHARE=2;static PAPER_FULL_CDM2=Nt.COMMON.luminousIntensityCd/(Math.PI*Nt.COMMON.widthM/2*Nt.COMMON.heightM/2);static SAMPLE_MS=1e3;static STEP_S=.05;static COOLING_S=20;static TURBULENCE={horizontalMS:.8,verticalMS:.3,timescaleS:30};static G=9.81;static R_AIR=287.05;static LAPSE=.0065;static expand(e){const t=e?.lanterns;return!e||!t||t.length===0?e:{...e,bodies:[...e.bodies,...t.flatMap(i=>Nt.bodiesOf(i))]}}static bodiesOf(e){return Nt.releasesOf(e).map((t,i)=>Nt.lanternBody(e,t,i))}static releasesOf(e){const t=[...e.releases??[]],i=e.group;if(!i||!(i.count>0))return t;const s=Nt.randomFrom(i.seed??1),n=o=>o.min+(o.max-o.min)*s(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let o=0;o<i.count;o++){const l=i.fromT+r*o+(s()-.5)*r,h=a*Math.sqrt(s()),d=2*Math.PI*s();t.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,l))),explains:i.explains,eastM:Math.round(h*Math.sin(d)*10)/10,northM:Math.round(h*Math.cos(d)*10)/10,burnedS:i.burnedS,seed:Math.floor(s()*4294967296),lantern:{burnS:Math.round(n(i.burnS??{min:480,max:900})),insideExcessK:Math.round(n(i.insideExcessK??{min:125,max:175}))}})}return t}static randomFrom(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let i=t;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}static typeOf(e,t){return{...Nt.COMMON,...e.lantern,...t.lantern}}static heatShare(e,t){if(t<0||t>=e.burnS)return 0;const i=e.burnS*.75;return t<=i?1:(e.burnS-t)/(e.burnS-i)}static windAt(e,t){const i=Nt.componentsOf(e.wind),s=e.windAloft;if(!s)return i;const n=Nt.componentsOf(s),r=Math.max(0,Math.min(1,t/s.atM));return{x:i.x+(n.x-i.x)*r,y:i.y+(n.y-i.y)*r}}static trajectory(e,t,i=Nt.SAMPLE_MS){const s=Nt.typeOf(e,t),n=e.site,r=n.altitudeM??0,a=Math.max(0,t.burnedS??0),o=n.originElevationM??0,l=(e.airTemperatureC??10)+273.15,h={x:n.eastM+(t.eastM??0),y:n.northM+(t.northM??0),z:t.altitudeM??r,vx:0,vy:0,vz:0,excessK:s.insideExcessK*Nt.heatShare(s,a)},d=Nt.STEP_S,u=Math.max(1,Math.round(i/1e3/d)),p=Math.ceil(Math.max(0,s.burnS-a)/d),f=[{t:t.t,x:h.x,y:h.y,z:h.z,light:Nt.heatShare(s,a),tiltDeg:0,tiltTowardDeg:0}],m=Nt.gusts(e.turbulence??Nt.TURBULENCE,Nt.seedOf(t),d);for(let v=1;v<=p;v++){const g=v*d,b=a+g,w=Nt.heatShare(s,b);h.excessK+=(s.insideExcessK*w-h.excessK)*Math.min(1,d/Nt.COOLING_S);const y=h.z-r,M=l-Nt.LAPSE*Math.max(0,y),S=101325*Math.exp(-(h.z+o)/8400),E=S/(Nt.R_AIR*M),x=S/(Nt.R_AIR*(M+h.excessK)),A=s.massKg-s.fuelKg*Math.min(1,b/s.burnS),D=(E-x)*s.envelopeVolumeM3*Nt.G,R=A+x*s.envelopeVolumeM3+.5*E*s.envelopeVolumeM3,L=Nt.windAt(e,y),N=m(),k={x:L.x+N.x,y:L.y+N.y,z:N.z},C=h.vx-k.x,P=h.vy-k.y,F=h.vz-k.z,V=.5*E*s.dragAreaM2*Math.hypot(C,P,F)/R;h.vx=(h.vx+V*d*k.x)/(1+V*d),h.vy=(h.vy+V*d*k.y)/(1+V*d),h.vz=(h.vz+V*d*k.z+(D-A*Nt.G)/R*d)/(1+V*d);const j=h.z<=r&&h.vz<=0;if(j&&(h.vx=0,h.vy=0,h.vz=0),h.x+=h.vx*d,h.y+=h.vy*d,h.z=Math.max(r,h.z+h.vz*d),v%u===0||v===p){const $=k.x-h.vx,ee=k.y-h.vy,re=.5*E*s.dragAreaM2*Math.hypot($,ee,k.z-h.vz)*Math.hypot($,ee);f.push({t:t.t+Math.round(g*1e3),x:h.x,y:h.y,z:h.z,light:w,tiltDeg:j?0:Math.atan2(re,A*Nt.G)*180/Math.PI,tiltTowardDeg:(Math.atan2($,ee)*180/Math.PI+360)%360})}}return f}static seedOf(e){return e.seed!==void 0?e.seed:Math.round(e.t)*2654435761+Math.round((e.eastM??0)*100)*40503+Math.round((e.northM??0)*100)>>>0}static gusts(e,t,i){const s=Nt.randomFrom(t),n=()=>Math.sqrt(-2*Math.log(Math.max(1e-12,s())))*Math.cos(2*Math.PI*s()),r=e.timescaleS>0?Math.exp(-i/e.timescaleS):0,a=Math.sqrt(1-r*r),o={x:e.horizontalMS*n(),y:e.horizontalMS*n(),z:e.verticalMS*n()};return()=>(o.x=r*o.x+a*e.horizontalMS*n(),o.y=r*o.y+a*e.horizontalMS*n(),o.z=r*o.z+a*e.verticalMS*n(),o)}static componentsOf(e){if(!e)return{x:0,y:0};const t=e.towardDeg*Math.PI/180;return{x:Math.sin(t)*e.speedMS,y:Math.cos(t)*e.speedMS}}static lanternBody(e,t,i){const s=Nt.typeOf(e,t),n=s.luminousIntensityCd/(Math.PI*s.widthM/2*s.heightM/2),r=Nt.trajectory(e,t),a={widthM:s.widthM,lengthM:s.widthM,heightM:s.heightM},o=Nt.through(s.color,s.paperColor),l=r.map((h,d)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...d===0?{sizeM:a,present:!0}:{},attitude:{headingDeg:Math.round(h.tiltTowardDeg),pitchDeg:-Math.round(h.tiltDeg*10)/10},appearance:{color:o,luminanceCdM2:n*h.light,...d===0?{albedo:.6,haloScale:1}:{}},lights:Nt.lightsOf(n*h.light)}));return l.push({t:r[r.length-1].t+1,present:!1}),{id:`${e.id}-lantern-${i+1}`,title:Nt.TITLE,explains:t.explains,model:{id:`ufoathome-sky-lantern-${s.shape}`},modelParameters:{paperColor:s.paperColor},flicker:Nt.FLICKER,altitudeFrom:{eastM:r[0].x,northM:r[0].y},track:l}}static lightsOf(e){return{paper:e,"paper-inside":e*Nt.INSIDE_SHARE,flame:e>0?Nt.FLAME_CDM2*e/Nt.PAPER_FULL_CDM2:0}}static through(e,t){const i=o=>[1,3,5].map(l=>parseInt(o.slice(l,l+2),16)/255),s=i(e),n=i(t),r=s.map((o,l)=>o*n[l]),a=Math.max(...s)/(Math.max(...r)||1);return"#"+r.map(o=>Math.round(Math.min(1,o*a)*255).toString(16).padStart(2,"0")).join("")}}class h1{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=h1.FIRST_DAY}}class ZN{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,s){try{return await(await this.provider()).between(e,t,i,s)}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 JN="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",sy=[{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 ZN(JN,c=>h1.mayCover(c),async()=>new(await oe(async()=>{const{AdsbLolArchiveProvider:c}=await import("./AdsbLolArchiveProvider-DS9ev-HU.js");return{AdsbLolArchiveProvider:c}},[],import.meta.url)).AdsbLolArchiveProvider)}];class Pn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const s=Pn.positionAt(e,i);if(!s)return;const n=De.seenFrom(t,s.geo);if(!(n.altitudeDeg<0))return{track:e,sky:n,altitudeFt:s.altitudeFt,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg,angularRateDegPerS:Pn.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(s=>Pn.seenFrom(s,t,i)??[])}static groundDistanceKm(e,t){const i=Math.PI/180,s=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*Pn.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(s)))}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 s=0;for(;s<i.length-1&&i[s+1].t<=t;)s++;const n=i[s],r=i[s+1]??n,a=r.t-n.t;if(a>Pn.MAX_GAP_S*1e3)return;const o=a>0?(t-n.t)/a:0,l=n.altitudeFt+(r.altitudeFt-n.altitudeFt)*o,h=(r.lng-n.lng+540)%360-180;return{geo:{lat:n.lat+(r.lat-n.lat)*o,lng:Pn.wrapLongitude(n.lng+h*o),heightM:l*Pn.FT_TO_M},altitudeFt:l,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg}}static angularRate(e,t,i){const s=Pn.positionAt(e,i-500),n=Pn.positionAt(e,i+500);if(!s||!n)return;const r=Pn.unit(De.seenFrom(t,s.geo)),a=Pn.unit(De.seenFrom(t,n.geo)),o=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(o)*180/Math.PI}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180;return[Math.cos(t)*Math.sin(i),Math.cos(t)*Math.cos(i),Math.sin(t)]}}const US="https://ufoathome.org/fireballs/index.json";class Pr{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??Pr.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(US)||e.push(US),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=Pr.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!Pr.mayCover(t))return;const i=await this.loadIndex();if(!i)return;const s=new Set([new Date(e).toISOString().slice(0,7),new Date(t).toISOString().slice(0,7)]);return[...s].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...s].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=Pr.peakFraction(e),s={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},n=De.seenFrom(t,s);if(!(n.altitudeDeg<0))return{record:e,peak:n,magnitude:e.peakMagnitude+5*Math.log10(n.distanceKm/De.STANDARD_DISTANCE_KM)}}static asReentry(e,t){const i=e.t-t,s=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:s,lat:e.to[0],lng:e.to[1],altitudeKm:e.to[2]}],fragments:[{absoluteMagnitude:e.peakMagnitude,color:Pr.COLOR,trainS:Pr.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(s=>s.ok?s.json():[]).catch(()=>[]),this.months.set(e,i)),i}}f0();const QN={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},e8="{name} — mag {mag}, {alt}° above the horizon",t8="{name} — {size}, {distance} away",i8="{name} — satellite, mag {mag}, {height} km up",s8={name:"Re-entry",piece:"{name} — mag {mag}, {height} km up, {distance} km away",fragment:"{name}, a fragment — mag {mag}, {height} km up, {distance} km away"},zS={ghost:"Ghost: {name}",halo:"Halo: {name}",double:"Double: {name}",unnamed:"a light",detail:"{name}. {cause}, {where}.",causes:{lens:"A reflection between two surfaces of the lens",sensor:"The sensor's reflection, sent back by its cover glass",filter:"The sensor's reflection, sent back by the filter",glass:"A reflection between the two faces of the glass in front of the lens",drops:"Light scattered by drops on the glass",condensation:"Light scattered by condensation on the glass",dirt:"Light scattered by dirt on the glass"},opposite:"across the centre of the picture from the light",sameSide:"on the same side of the centre as the light",around:"round the light",drop:{lens:"Drop on the lens",filter:"Drop on the filter",window:"Drop on the window",windscreen:"Drop on the windscreen"},dropDetail:"{name}. Like a small lens, it shows upside down and blurred what is on the other side of it, rather than what is behind it."},n8={name:"Afterimage, in the eye",detail:"{name}: where the image of a light brighter than the Sun fell, the retina's pigment is bleached: for a few seconds it goes on glowing, white then coloured, and then what is seen there looks darker. It stays where it is in the field of view whichever way the eye turns, and takes minutes to fade."},r8={name:"Rocket plume",detail:"{name} — {part}, {distance} away, {height} km up",ascent:"exhaust of the ascent",burn:"exhaust of an engine burn",vent:"vented propellant"},qA="satellites-change",jA="fireballs-change",ZA="references-change",a8="aircraft-change",o8="rr0-confrontation",l8="{name} — mag {mag}, {alt}° below the horizontal",dv="Credits",BS="comet:",HS="nova:",uv={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",trafficlight:"Traffic light",crossing:"Pedestrian crossing",roadsign:"Road sign",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},c8=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,h8=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,d8=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,u8=-18,p8={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Af={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Rt 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",Fh,Uh,Jl]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new I;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new fn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Pr;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static NO_BEAMS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=sy[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return Rt.trafficRuntimeLoading??=oe(()=>import("./trafficRuntime-DVOOnJGD.js"),__vite__mapDeps([12,7]),import.meta.url).then(e=>Rt.trafficRuntime=e),Rt.trafficRuntimeLoading.catch(()=>{Rt.trafficRuntimeLoading=void 0}),Rt.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new Ah;vehicleAudio=new b_;aircraftAudio;vehicleHearing=new fm;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{if(this.lastHover={clientX:e.clientX,clientY:e.clientY,altKey:e.altKey},this.ghostMissedSinceMs=void 0,this.hoverFrame!==void 0&&e.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=e.altKey,this.hoverAt(this.lastHover),this.hoverFrame===void 0&&(this.hoverFrame=requestAnimationFrame(()=>{this.hoverFrame=void 0,this.hoverPending&&this.lastHover&&this.hoverAt(this.lastHover),this.hoverPending=!1}))};ghostMissedSinceMs;static GHOST_KEPT_MS=600;ghostStillUnder(e,t){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return!0;const s=(e.clientX-i.left)/i.width*2-1,n=1-(e.clientY-i.top)/i.height*2;return this.sceneRenderer.ghostsReadableAt(s,n)?this.sceneRenderer.pickGhostAt(s,n)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=t,t-this.ghostMissedSinceMs>Rt.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;hoverAt(e){if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(i.width===0||i.height===0)return;const s=(e.clientX-i.left)/i.width*t.width,n=(e.clientY-i.top)/i.height*t.height;if(this.ufoElement.hasVisibleShapeAt(s,n)){this.hoverTooltip.hidden=!0;return}const r=(e.clientX-i.left)/i.width*2-1,a=-((e.clientY-i.top)/i.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(r,a))return;const o=this.pickAt(r,a,!0,e.altKey);o?this.showHoverTooltip(e,e.altKey&&o.detail?o.detail():o.name):this.hoverTooltip.hidden=!0,this.showGhostPath(o?.path,i)}showGhostPath(e,t){if(!e){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),s=u=>({x:t.left-i.left+(u.x+1)/2*t.width,y:t.top-i.top+(1-u.y)/2*t.height}),n=s(e.from),r=s(e.to),a=s({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[o,l,h,d]=Array.from(this.ghostPath.children);for(const u of[o,l])u.setAttribute("x1",String(n.x)),u.setAttribute("y1",String(n.y)),u.setAttribute("x2",String(r.x)),u.setAttribute("y2",String(r.y));h.setAttribute("cx",String(a.x)),h.setAttribute("cy",String(a.y)),d.setAttribute("cx",String(r.x)),d.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(e,t,i=!0,s=!1){const n=this.naming,r=n.names;if(s&&this.sceneRenderer.pickDropAt(e,t)){const x=r?.ghostTooltip??zS,A=x.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:A,detail:()=>x.dropDetail.replace("{name}",A)}}const a=this.sceneRenderer.pickBodyAt(e,t);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const o=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(e,t):void 0,l=o?this.interpretationShown?.bodies.find(x=>x.id===o):void 0,h=l?this.said.read(l.title)||(l.model.id==="figure"?n.decorKind("entity",uv.entity):void 0):void 0;if(o!==void 0&&h)return{kind:"body",id:o,name:h};const d=this.ufoElement.sighting.skyEvents?.beams,u=d?.length?this.sceneRenderer.pickBeamAt(e,t):void 0,p=u?d?.find(x=>x.id===u.id):void 0;if(u&&p){const x=this.said.read(p.title)||"Laser";return{kind:"beam",id:p.id,name:x,detail:()=>`${x} (${p.wavelengthNm} nm, ${p.powerW.toLocaleString()} W), ${this.distanceText(u.distanceM)}`}}const f=i?this.ghostPick(e,t):void 0;if(f)return f;if(this.sceneRenderer.pickAfterimageAt(e,t)){const x=this.naming.names?.afterimageTooltip??n8;return{kind:"afterimage",name:x.name,detail:()=>x.detail.replace("{name}",x.name)}}const m=this.pickDecorAt(e,t),v=m?this.ufoElement.sighting.decor.find(x=>x.id===m):void 0;if(v){const x=this.said.read(v.title)||n.decorKind(v.kind,uv[v.kind]);return{kind:"decor",id:v.id,name:x,detail:()=>this.decorTooltip(v,x)}}const g=this.sceneRenderer.pickRailwayAt(e,t);if(g){const x=r?.railwayTooltip??Jr.ENGLISH;return{kind:"railway",id:g.line.id,name:Jr.name(g.line,x),detail:()=>Jr.detail(g,x,A=>this.distanceText(A))}}const b=this.trafficTooltipAt(e,t);if(b)return{kind:"traffic",name:b};const w=this.plumePickAt(e,t);if(w)return w;const y=this.sceneRenderer.pickSatelliteAt(e,t);if(y)return{kind:"satellite",name:(r?.satelliteTooltip??i8).replace("{name}",y.name).replace("{mag}",y.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(y.heightKm).toLocaleString())};const M=this.reentryPickAt(e,t);if(M)return M;const S=this.sceneRenderer.pickOpticsAt(e,t);if(S){const x=(r?.opticsTooltips??FN)[S.id].replace("{angle}",String(Math.round(S.angleDeg??0)));return{kind:"optics",id:S.id,name:x.split(" — ")[0],detail:()=>x}}const E=this.sceneRenderer.pickStarAt(e,t);if(E){const x=E.star.mag,A=E.altitudeDeg,D=A<0?r?.starTooltipBelow??l8:r?.starTooltip??e8,R=n.star(E.star);return{kind:"star",name:R,detail:()=>D.replace("{name}",R).replace("{mag}",x.toLocaleString(void 0,{maximumFractionDigits:Math.abs(x)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(A))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(e,t){const i=this.ufoElement.canvasElement,s={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},n=`${Math.round(e/s.x)}:${Math.round(t/s.y)}`,r=performance.now(),a=this.ghostLights.get(n);if(a&&r-a.atMs<Rt.GHOST_LIGHT_KEPT_MS)return a.light;let o=this.shiningDecorNear(e,t,2*Math.max(s.x,s.y)),l;if(!o)for(const[h,d]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const u=this.pickAt(e+h*s.x,t+d*s.y,!1);if(u?.kind==="star")l??=u;else if(u){o=u;break}}return o??=this.shiningDecorNear(e,t,6*Math.max(s.x,s.y)),o??=l,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(n,{light:o??null,atMs:r}),o??null}ghostPick(e,t){const i=this.sceneRenderer.pickGhostAt(e,t);if(!i)return;const s=this.naming.names?.ghostTooltip??zS,n=this.lightOfGhost(i.source.x,i.source.y)??void 0,r=(n?.kind==="star"?n.name.split(" — ")[0]:n?.name)??s.unnamed,a=i.ghost,l=(Ci.scatters(a)?s.halo:a.cause==="glass"?s.double:s.ghost).replace("{name}",r),h=a.scale<0?s.opposite:a.scale===1?s.around:s.sameSide;return{kind:"ghost",id:n?.id,name:l,detail:()=>s.detail.replace("{name}",l).replace("{cause}",s.causes[a.cause??"lens"]).replace("{where}",h),path:{from:{x:a.scale*i.source.x,y:a.scale*i.source.y},to:i.source}}}shiningDecorNear(e,t,i){let s;for(const n of this.ufoElement.sighting.decor){if(!(n.kind==="streetlight"||n.kind==="trafficlight"||(n.lights?.length??0)>0||n.kind==="vehicle"&&n.lit))continue;const a=this.sceneRenderer.decorScreenBox(n.id);if(!a)continue;const o=Math.hypot(Math.max(a.minX-e,0,e-a.maxX),Math.max(a.minY-t,0,t-a.maxY));if(o>i||s&&o>=s.distance)continue;const l=this.said.read(n.title)||this.naming.decorKind(n.kind,uv[n.kind]);s={distance:o,pick:{kind:"decor",id:n.id,name:l}}}return s?.pick}glassWettingOf(e){const t=JSON.stringify([e.lens,e.instrumentId,e.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==e||this.glassWetting.key!==t){const i=new jl(s=>{if(!Ci.records(e.instrument)||!Ci.falling(e.lens))return 0;const n=wd(e,s*1e3),r=st(e,s*1e3);return(n.precipitationAmount??1)*Ci.impactRate(n,e.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:n.windDirectionDeg,windSpeedMS:n.windSpeed})});this.glassWetting={sighting:e,key:t,wetting:i}}return this.glassWetting.wetting}glassWetting;plumePickAt(e,t){const i=this.ufoElement.sighting.skyEvents?.launches,s=i?.length?this.sceneRenderer.pickPlumeAt(e,t):void 0,n=s?i?.find(l=>l.id===s.launchId):void 0;if(!s||!n)return;const r=this.naming.names?.plumeTooltip??r8,a=this.said.read(n.title)||n.vehicle?.mission||r.name,o=()=>s.release===void 0||s.release==="burn"?r.ascent:n.jets?.find((h,d)=>`jet:${h.id??d}`===s.release)?.kind==="vent"?r.vent:r.burn;return{kind:"plume",id:n.id,name:a,detail:()=>r.detail.replace("{name}",a).replace("{part}",o()).replace("{distance}",this.distanceText(s.centre.distanceKm*1e3)).replace("{height}",Math.round(s.heightKm??0).toLocaleString())}}distanceText(e){return e>=1e3?`${(e/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${e.toLocaleString(void 0,{maximumFractionDigits:e<10?1:0})} m`}decorTooltip(e,t){const i=l=>l.toLocaleString(void 0,{maximumFractionDigits:l<10?1:0}),s=ue.sizeOf(e),n=this.sceneRenderer.decorDistanceM(e.id),r=n===void 0?"":this.distanceText(n);return(this.naming.names?.decorTooltip??t8).replace("{name}",t).replace("{size}",`${i(s.widthM)} × ${i(s.lengthM)} × ${i(s.heightM)} m`).replace("{distance}",r)}bodyName(e){const t=e.startsWith(BS)?e.slice(BS.length):void 0,i=t?YA.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const s=e.startsWith(HS)?$m.byId(e.slice(HS.length)):void 0;if(s)return this.naming.nova(s);const n=QN[e];return n===void 0?e:this.naming.body(e,n)}get naming(){return this.sceneNaming}sceneNaming=new Wm;namesLanguage="en";async loadSceneNames(){const e=$u(Sr.preferencesFor(this),Wu);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await xE(e);e===this.namesLanguage&&this.applySceneNaming(new Wm(t))}setBusy(e,t=""){this.busyElement.hidden=!e,this.busyNote.textContent=e?t:"",this.busyElement.setAttribute("aria-label",t),this.busyElement.setAttribute("aria-busy",String(e))}renderLoaderText(e,t){let i=0;const s=(n,r)=>{n.setAttribute("aria-label",r),n.replaceChildren(),r.split(" ").forEach((a,o)=>{o>0&&n.append(" ");const l=document.createElement("span");l.className="scene-loader-word",l.setAttribute("aria-hidden","true");for(const h of a){const d=document.createElement("span");d.className="scene-loader-letter",d.style.setProperty("--i",String(i++)),d.textContent=h,l.append(d)}n.append(l),i++})};s(this.loaderNotVideo,e),i+=6,s(this.loaderNote,t)}applySceneNaming(e){this.sceneNaming=e;const t=e.names?.credits??dv;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(),s=e.clientX-i.left+12,n=s+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${n>0?Math.max(0,s-n-4):s}px`,this.hoverTooltip.style.top=`${e.clientY-i.top+12}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};hearDetonations(e,t,i,s){const n=`${i.lat.toFixed(4)},${i.lng.toFixed(4)}`,r=this.detonationsFor;(!r||n!==r.key||e.length!==r.reentries.length||e.some((l,h)=>l!==r.reentries[h]))&&(this.detonationsFor={reentries:[...e],key:n,detonations:e.length?De.detonationsOf(e,i):[]});const a=this.detonationsFor.detonations;if(s)return;const o=this.lastDetonationT;if(this.lastDetonationT=t,!(o===void 0||t<o||t-o>Rt.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const l of a)l.t>o&&l.t<=t&&this.weatherAudio.playDetonation(l.loudness)}reentryPickAt(e,t){const i=this.sceneRenderer.pickReentryAt(e,t);if(!i)return;const s=this.naming.names?.reentryTooltip??s8,n=this.detonationsFor?.reentries.find(d=>d.id===i.view.reentryId),r=(n?.title?this.said.read(n.title):"")||n?.object?.name||s.name,a=i.view.head,o=6371,l=Math.sqrt(o**2+a.distanceKm**2+2*o*a.distanceKm*Math.sin(a.altitudeDeg*Math.PI/180))-o;return{kind:"reentry",name:(i.view.fragmentId.includes(".")?s.fragment:s.piece).replace("{name}",r).replace("{mag}",i.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(l).toLocaleString()).replace("{distance}",Math.round(a.distanceKm).toLocaleString())}}detonates(e){const t=[...e.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],i=st(e,0),s=e.event.place?.[0],n=i?.lat??s?.lat,r=i?.lng??s?.lng;return t.length>0&&n!==void 0&&r!==void 0&&De.detonationsOf(t,{lat:n,lng:r,heightM:i?.elevationM??0}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(e){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),Ls.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(wd(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const e=this.ufoElement.level;this.weatherAudio.setLevel(e),this.vehicleAudio.setLevel(e),this.aircraftAudio?.setLevel(e)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=e=>{if(this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const t=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&t-this.lastPlayingHoverMs>=Rt.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=t,this.ghostStillUnder(this.lastHover,t)&&this.hoverAt(this.lastHover))}this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(e,e),this.weatherAudio.setPaused(!e),this.vehicleAudio.setPaused(!e),this.aircraftAudio?.setPaused(!e),e&&this.unlockIfAlreadyActivated(),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${M_}</style>${w_}`,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 de(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(ZA));const t=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.renderLoaderText("This is not a video","It is a real-time simulation."),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=t,this.poster=new vu(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=n=>{this.holding=n,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.ufoElement=document.createElement(qv),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapFrozenSource=n=>this.frozenMapOf(n),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",n=>this.lookToward(n.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"),s=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",n=>{n.newState==="open"&&pn.fill(s,this)}),this.creditsButton.title=dv,this.creditsButton.setAttribute("aria-label",dv),this.sceneRenderer.onMapSubjectBounds=n=>this.ufoElement.setMapSubjectBounds(n),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(k2,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(n,r)=>this.seekPreviewOf(r).paint(n,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=n=>n.vehicle!==void 0||n.decor.some(r=>r.engine!==void 0)||n.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1)||this.detonates(n),this.ufoElement.addEventListener("referenceview",n=>this.applyReferenceView(n.detail)),this.ufoElement.addEventListener("traceview",n=>this.sceneRenderer.setTracesShown(n.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const n of Rt.GESTURES)this.addEventListener(n,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new rn(Sr.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(e,t){const i=e.vehicle;return i?{setting:xl.at(i.headlights??"auto",i.headlightKeyframes,t)??"auto",headingDeg:this.travelHeadingAt(e,t)}:void 0}travelHeadingAt(e,t){const i=st(e,t);if(!i)return 0;for(const s of[400,-400]){const n=st(e,t+s);if(!n||i.lat===void 0||i.lng===void 0||n.lat===void 0||n.lng===void 0)break;const r=ut(n.lat,n.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(s<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(e){const t=e.allKeyframes;if(this.routeCache?.track===e&&this.routeCache.count===t.length)return this.routeCache.route;const i=t.flatMap(n=>n.pose.lat!==void 0&&n.pose.lng!==void 0?[{lat:n.pose.lat,lng:n.pose.lng}]:[]),s=i.length>=2?i:void 0;return this.routeCache={track:e,count:t.length,route:s},s}traceLabels(e){const t=Sr.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==e||this.traceLabelsFor.language!==t){const i=new Map;for(const s of e){const n=this.said.read(s.title);n&&i.set(s.id,n)}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 Rt.GESTURES)document.addEventListener(t,this.handlePageGesture,!0);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(e=>{if(e[e.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of Rt.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 s=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(s)&&s>0?s:Math.min(window.devicePixelRatio||1,2))}(e===Fh||e===Uh||e===Jl)&&i!==t&&this.forwardPlayerAttributes(),e===Jl&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const e of[Fh,Uh,Jl]){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=st(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:s}=ut(e.lat,e.lng,t.lat,t.lng);if(Math.hypot(i,s)<1)return this.setLookOffset(0,0);const n=(Math.atan2(i,-s)*180/Math.PI+360)%360;this.setLookOffset(((n-t.headingDeg)%360+540)%360-180,-t.pitchDeg)}setLookOffset(e,t){this.sceneRenderer.setLookOffset(e,t),this.ufoElement.setLookOffset(e,t),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setCloudRendering(e){this.sceneRenderer.setCloudRendering(e)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity*(e.precipitationAmount??1),e.windSpeed)}pickCloudAt(e,t){return this.sceneRenderer.pickCloudAt(e,t)}cloudDirectionAt(e,t){return this.sceneRenderer.cloudDirectionAt(e,t)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}decorScreenBox(e){return this.sceneRenderer.decorScreenBox(e)}decorDrawnOffset(e){return this.sceneRenderer.decorDrawnOffset(e)}decorGroundPointAt(e,t,i,s=0){return this.sceneRenderer.decorGroundPointAt(e,t,i,s)}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=na.recording(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(e,t,i=!0){this.poster.show(e,t,i)}applyHold(){const e=this.holding,t=this.poster.up;this.loader.hidden=!e||t,e&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=e||t,this.ufoElement.controlsHeld=e||t,this.ufoElement.holdClock(e)}holdForNewScene(e){this.sceneRenderer.holdForNewScene(e)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(e){this.sceneRenderer.documentUrl=e}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){const t=Ui.toCurrent(e);this.ufoElement.sightingData=t,this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(t),this.interpretationShown=this.inTheRound?Nt.expand(On.expand(this.ufoElement.sighting.interpretation)):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(e){const t=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(e.width/t);return e.height!==i&&(e.height=i),this.seekPreview??=new Bm(this,()=>document.createElement(Km))}showAt(e){this.ufoElement.currentTime=e,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(e){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const t=e.getContext("2d");return t?(t.imageSmoothingQuality="high",t.drawImage(this.sceneCanvas,0,0,e.width,e.height),!0):!1}referenceAspect(e){return this.sceneRenderer.referenceAspect(e)}screenPointOf(e){return this.sceneRenderer.screenPointOf(e)}directionAt(e,t){return this.sceneRenderer.directionAt(e,t)}referenceFailure(e){return this.sceneRenderer.referenceFailure(e)}applyReferenceView(e){this.sceneRenderer.setReferencesShown(e.shown);for(const t of this.ufoElement.sighting.references){const i=e.views?.[t.id];this.sceneRenderer.setReferenceView(t.id,{opacity:i?i.shown?i.opacity:0:e.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(e){this.liveTerrainProviders=e,this.frozenKey=void 0,this.applyFrozen(this.ufoElement.sighting.frozen)}liveTerrainProviders;frozenKey="none";applyFrozen(e){const t=ts.isEmpty(e)?"none":`${JSON.stringify(e)}
|
|
11496
11496
|
${this.documentUrl??""}
|
|
11497
11497
|
${Ct.generation}`;if(t===this.frozenKey)return;const i=this.frozenKey!==void 0&&this.traffic?.set!==void 0;this.frozenKey=t,this.sceneRenderer.setTerrainProviders(Gm.providers(e,this.documentUrl,this.liveTerrainProviders??A2())),this.ufoElement.observerMapFrozen=this.frozenMapOf(e),i&&(this.traffic=void 0,this.decorMemo=void 0)}frozenMapOf(e){const t=ts.held(e,"map");if(!t)return;const i=`${Ct.address(t.src,this.documentUrl)}
|
|
11498
11498
|
${Ct.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery:Gm.map(t,this.documentUrl)}),this.frozenMap.imagery}frozenMap;setDecorModelProvider(e){this.sceneRenderer.setDecorModelProvider(e)}get decorModelCredits(){return[...new Map(this.sceneRenderer.currentDecorModelCredits.map(t=>[`${t.title}|${t.author??""}|${t.license}|${t.sourceUrl??""}`,t])).values()]}applyFrameFormat(){const e=this.ufoElement.sighting.instrument,t=Lt.CANVAS_HEIGHT_PX,i=Qt.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:cv,url:this.getAttribute("star-catalog-src")??h8},{magnitudeLimit:mu,url:this.getAttribute("deep-star-catalog-src")??d8}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>cv?mu:cv;const s=await wa.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=s,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=mu||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=Ws.gainFor(e.instrument,{fNumber:st(e,0)?.fNumber,fieldOfViewDeg:Si.fovOf(e,0),exposureSeconds:e.exposure});return Ta(u8,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=Zr.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,s=this.degreesPerPixelAt(e),n=gc.instants(i,s),r=Math.max(n,this.ufoElement.exposureTimes(e).length,Zr.instants(this.decorWithTraffic(this.ufoElement.sighting),st(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,i,s));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(t.fromMs+t.ms*a/(r-1),{sky:Math.floor(a*n/r)!==Math.floor((a-1)*n/r),stepMs:t.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(e){const t=this.sceneCanvas.height;return t<=0?0:Si.fovOf(this.ufoElement.sighting,e)/t}roadGradeAt(e,t){return e.observerTrack.allKeyframes.length<2?0:vh.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;t||this.sceneRenderer.setRecordingTime(e),this.setWeather(wd(i,e)),this.sceneRenderer.setInstrument(i.instrument,st(i,e)?.fNumber),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??Rt.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(e)),this.sceneRenderer.setContrails(this.traffic?.contrails??Rt.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(e));const s=st(i,e);this.sceneRenderer.setReferences(i.references,s?.lat!==void 0&&s.lng!==void 0?{lat:s.lat,lng:s.lng}:void 0);const n=st(i,0),r=fs(i,0),a=sn(i.event.time??{},s?.lng??Af.lng,i.event.utcOffsetHours),o=i.weatherSource!==void 0&&a?nI(a):void 0,l=Object.fromEntries(ml(fs(i,e)).map(L=>[L.id,em(e,i.weatherTrack,r,n,s,L.id,L.instances?.length?void 0:o)]));this.sceneRenderer.setCloudOffset(em(e,i.weatherTrack,r,n,s,void 0,o),l),this.sceneRenderer.setObserverPose(s?{...s,pitchDeg:s.pitchDeg+this.roadGradeAt(i,e)}:Af),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(Ws.gainFor(i.instrument,{fNumber:s?.fNumber,fieldOfViewDeg:Si.fovOf(i,e),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,Xi.byId(s?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,s?.fNumber??i.instrument.fNumber,i.iso,i.metering),this.sceneRenderer.setLensGhosts(Ci.optics(i.instrument,s?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(e/1e3))),this.sceneRenderer.setPerception(mc.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(bi.bodyAt(i,e,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(st(i,0),s,e),this.placeBodiesAt(e,t===void 0),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),this.applyFrozen(i.frozen),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,e)),this.sceneRenderer.setTerrainOrigin(s?.lat,s?.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=s?.lat??Af.lat,d=s?.lng??Af.lng,u=sn(i.event.time??{},d,i.event.utcOffsetHours),p={lat:h,lng:d,elevationM:s?.elevationM??0};this.pushSatellitesAt(u,e,p),this.ensureFireballs(u);const f=i.skyEvents,m=[...f?.reentries??[],...this.fireballs?.reentries??[]];this.sceneRenderer.setReentries(m.length===0?[]:De.viewsAt(m,e,{lat:h,lng:d,heightM:p.elevationM})),this.hearDetonations(m,e,{lat:h,lng:d,heightM:p.elevationM},t!==void 0);const v=m.filter(L=>De.mayDazzle(L));this.sceneRenderer.setRetinaHistory(v.length===0?void 0:L=>{const N=st(i,L),k={lat:N?.lat??h,lng:N?.lng??d,heightM:N?.elevationM??p.elevationM};return{views:De.viewsAt(v,L,k),pose:N}},i),this.sceneRenderer.setBeams(f?.beams??Rt.NO_BEAMS);const g=f?.launches??[];if(this.sceneRenderer.setLaunchPlumes(g.length===0||!u?[]:Oe.viewsAt(g,e,{lat:h,lng:d,heightM:p.elevationM},Oe.sunDirectionAt(new Date(u.getTime()+e)))),t&&!t.sky)return;if(this.sceneRenderer.setSkyUnknown(!u),!u){this.sceneRenderer.setAstronomy(p8);return}const b=new Date(u.getTime()+e),w=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/gc.DEG_PER_SECOND*1e3)),y=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),M=`${Math.floor(b.getTime()/w)}|${Math.round(h/y)}|${Math.round(d/y)}|${Math.round(p.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(M===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=M;const S=zi("Sun",b,p),E=zi("Moon",b,p);let x=ps.separationOf(S,E)<1?ps.viewAt(b,p):void 0;if(x){const L=ps.offsetOf(S,E,x.separationDeg);if(x.obscuration>Rt.LIMB_FROM_OBSCURATION){const N=this.limbFor(b,p);N&&(x={...x,obscuration:1-Cr.uncoveredFraction(N,x.sunRadiusDeg,L),limb:N})}x={...x,horizonShare:ps.horizonShare(x,L,S.altitudeDeg,S.azimuthDeg,Sn.distanceKm(b,p))}}const A={...S,magnitude:Of("Sun",b)-2.5*Math.log10(ps.beamFraction(x))};this.lastSun={altitudeDeg:A.altitudeDeg,azimuthDeg:A.azimuthDeg};const D={...E,phase:Hl(b),magnitude:Of("Moon",b),radiusDeg:Sn.apparentRadiusDeg(b,p)},R=S5.map(L=>({body:L,position:zi(L,b,p),magnitude:Of(L,b)}));this.sceneRenderer.setAstronomy({sun:A,moon:D,planets:R,comet:this.cometAt(b,p),novae:$m.appearancesAt(b,p).map(({outburst:L,position:N,magnitude:k})=>({id:L.id,position:N,magnitude:k})),stars:this.starCatalog?{catalog:this.starCatalog,date:b,observer:p}:void 0,frame:{date:b,observer:p},localHour:((b.getUTCHours()+b.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(d/15)))%24+24)%24,eclipse:x}),this.ufoElement.setSunAltitude(A.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(e,t){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,gu.load(c8).then(n=>{this.limbRelief=n,this.lastSkyKey="",n&&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 s=Cr.profile(e,t,this.limbRelief);return this.limbCache={profile:s,atMs:e.getTime(),lat:t.lat,lng:t.lng,elevationM:t.elevationM},s}pushSatellitesAt(e,t,i){if(this.ensureSatellites(e),!e||!this.satellites){this.sceneRenderer.setSatellites([]);return}const s=new Date(e.getTime()+t),n=[];for(const r of this.satellites.passes.positionsAt(s,i,-1))r.magnitude!==void 0&&n.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(n)}ensureFireballs(e){const t=this.ufoElement.sighting,i=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=e?.getTime(),n=s===void 0?"":`${s}+${i}`;if(this.fireballs?.key===n)return;if(s===void 0||!Pr.mayCover(s+i)){this.fireballs={key:n,status:"outside",reentries:[]};return}const r={key:n,status:"loading",reentries:[]};this.fireballs=r,Rt.fireballArchive.between(s,s+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(o=>Pr.asReentry(o,s)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(jA)),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 s=[...e.decor,...t.objects];return this.decorMemo={base:e.decor,traffic:t.objects,merged:s},s}seatedDecor(e,t){if(!e.some(r=>r.observerKeyframes?.length))return e;const i=e.map(r=>{if(!r.observerKeyframes?.length)return"";const a=Vw(r,t);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),s=this.seatedMemo;if(s&&s.base===e&&s.seats===i)return s.seated;const n=e.map(r=>{if(!r.observerKeyframes?.length)return r;const a=Vw(r,t);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:e,seats:i,seated:n},n}ensureTraffic(e){const t=st(e,0),i=t?.lng===void 0?void 0:sn(e.event.time??{},t.lng,e.event.utcOffsetHours),s=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=i?.getTime(),r=n===void 0||t?.lat===void 0||t.lng===void 0?"":`${this.aircraftSource.id}|${n}+${s}|${t.lat.toFixed(3)},${t.lng.toFixed(3)}|${Math.round(t.elevationM??0)}`;if(this.traffic?.key===r)return this.traffic.set;if(this.upperAirHeardLive=void 0,r===""||n===void 0||t?.lat===void 0||t.lng===void 0){this.traffic={key:r,status:"outside"};return}let a=Rt.aircraftProviders.get(this.aircraftSource.id);if(a||Rt.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.mayCover(n+s)){this.traffic={key:r,status:"outside"};return}const o={key:r,status:"loading",startMs:n,observer:{lat:t.lat,lng:t.lng}};this.traffic=o;const l={lat:t.lat,lng:t.lng,heightM:t.elevationM??0},h=Pn.MAX_GAP_S*1e3,d=Rt.SOUND_LOOKBACK_MS,u={lat:t.lat,lng:t.lng,elevationM:t.elevationM??0},p=(f,m)=>f.TrafficDecor.from(o.tracks??[],l,n,f.TrafficDecor.MAX_OBJECTS,{models:m,sunElevationAt:v=>this.sunElevationAt(v,u)});a.between(l,n-d,n+s+h).then(async f=>{if(this.traffic!==o)return;if(f.status!=="found"){o.status=f.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let m;try{m=await Rt.loadTrafficRuntime()}catch{this.traffic===o&&(o.status="unavailable",this.announceTraffic());return}this.traffic===o&&(o.status="ready",o.tracks=f.tracks,o.set=p(m),this.startAircraftSound(o,m),this.announceTraffic(),this.describeTraffic(a,o,m,p),o.set.shown>0&&(this.readUpperAir(o,m,n-d,n+s+h),this.readTrailTraffic(a,o,m,l,n-Rt.TRAIL_LOOKBACK_MS,n+s+h)))})}trafficSunlight(e){const t=new Map,i=this.traffic,s=i?.set,n=this.lastSun;if(!s||!n||i.startMs===void 0||!i.observer)return t;for(const[r,a]of s.presence){if(e<a.fromMs||e>a.untilMs)continue;const o=s.flights.get(r),l=o?Pn.positionAt(o,i.startMs+e):void 0;l&&t.set(r,{heightM:l.geo.heightM,sunElevationDeg:zn.sunElevationDeg(n,i.observer,l.geo)})}return t}trafficTooltipAt(e,t){const i=this.sceneRenderer.pickTrafficAt(e,t),s=i?this.trafficInfoAt(i):void 0;if(!s)return;const n=this.naming,r=Rt.trafficRuntime;return r?.TrafficTooltip.text(s,n.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,a=>n.towards(a))}trafficInfoAt(e){const t=this.traffic,i=t?.set?.flights.get(e);if(!t||!i||t.startMs===void 0||!t.observer)return;const s=Rt.trafficRuntime;if(!s)return;const n=t.descriptions?.get(tn.keyOf(i)),r=st(this.ufoElement.sighting,this.lastTimeMs),a={lat:t.observer.lat,lng:t.observer.lng,heightM:r?.elevationM??0},o=s.AmbientNoise.dbA(wd(this.ufoElement.sighting,this.lastTimeMs)),l=s.TrafficInfos.at(i,n,a,t.startMs+this.lastTimeMs,{ambientDbA:o}),h=l&&this.contrailAt(e,this.lastTimeMs);return l&&h?{...l,contrail:h}:l}contrailAt(e,t){const i=this.traffic?.contrails?.find(n=>n.id===e);if(!i)return;let s;for(const n of i.points){if(n.tMs>t)break;s=n}return s?.forms?{persistent:s.persistent,iceRelativeHumidity:s.iceRelativeHumidity}:void 0}startAircraftSound(e,t){this.aircraftAudio??=this.newAircraftAudio(t),this.sortOutAudible(e,t)}sortOutAudible(e,t){!e.set||!e.observer||(e.audible=t.TrafficSound.candidates(e.set.flights,e.descriptions??new Map,tn.keyOf,{...e.observer,heightM:0},{ambientDbA:t.AmbientNoise.BASE_DB_A}))}pushAircraftSound(e,t){this.startDecorAircraftSound(e),this.startBodySound();const i=this.aircraftAudio;if(!i)return;const s=Rt.trafficRuntime;if(!s){i.setVoices([]);return}const n=st(e,t),r=wd(e,t),a={ambientDbA:s.AmbientNoise.dbA(r),referenceAmplitude:s.AmbientNoise.referenceAmplitude(r)},o=this.trafficVoices(t,n,a,s),l=e.event.place?.[0],h={lat:n?.lat??l?.lat,lng:n?.lng??l?.lng};h.lat!==void 0&&h.lng!==void 0&&(this.decorAircraftHearing??=new s.DecorAircraftHearing,o.push(...this.decorAircraftHearing.voices(e,t,{lat:h.lat,lng:h.lng,heightM:n?.elevationM??0},a,d=>this.decorModelSounds.get(d.model?.id??""))),o.push(...this.bodyVoices(e,t,a,s)),o.sort((d,u)=>u.levelDbA-d.levelDbA),o.length=Math.min(o.length,4)),i.setVoices(o,n?.headingDeg??0)}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(e=>e.sound)||(Rt.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(Rt.trafficRuntime):Rt.loadTrafficRuntime().catch(()=>{}))}bodyVoices(e,t,i,s){const n=this.interpretationShown,r=e.event.place?.[0];if(!n||!r||!n.bodies.some(p=>p.sound))return[];const a=this.sceneRenderer.bodyGround,o=p=>$e.eyeOf(e,p,a),l=o(t);if(!l)return[];const h=new Map,d=(p,f)=>{let m=h.get(p.id);return m||h.set(p.id,m=new $e(p,a,o)),m.at(f)};this.bodyHearing??=new s.BodyHearing;const u=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(n.bodies,d,l,r,t,u,i)}trafficVoices(e,t,i,s){const n=this.traffic,r=n?.set;if(!n||!r||!n.audible||n.startMs===void 0||!n.observer)return[];const a={lat:n.observer.lat,lng:n.observer.lng,heightM:t?.elevationM??0};return s.TrafficSound.voices(n.audible,r.flights,n.descriptions??new Map,tn.keyOf,a,n.startMs+e,i)}startDecorAircraftSound(e){const t=e.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(s=>(s.altitudeM??0)>0));if(t.length!==0){for(const i of t){const s=i.model?.id;!s||i.model?.url!==void 0||this.decorModelSounds.has(s)||(this.decorModelSounds.set(s,void 0),this.sceneRenderer.entryOfDecorModel(s).then(n=>{this.decorModelSounds.set(s,n?.parameters?.sound)}))}if(this.aircraftAudio||Rt.trafficRuntime){!this.aircraftAudio&&Rt.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(Rt.trafficRuntime));return}Rt.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(e){const t=new e.AircraftAudio;return t.setLevel(this.ufoElement.level),this.interacted&&t.resume(),t.setPaused(this.ufoElement.playbackState!=="playing"),t}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(a8)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(e,t,i,s){if(!e.describe||!t.set||!t.tracks)return;const n=new Set([...t.set.flights.values()].map(l=>tn.keyOf(l))),r=t.tracks.filter(l=>n.has(tn.keyOf(l))&&l.points.length>0),a=new Map,o=new Map;await Promise.all(r.map(async l=>{const h=new Date(l.points[0].t).toISOString().slice(0,10),d=await e.describe(l,h).catch(()=>{});d&&(o.set(tn.keyOf(l),d),a.set(tn.keyOf(l),i.AircraftModels.of(d)))})),!(this.traffic!==t||a.size===0)&&(t.descriptions=o,t.models=a,t.set=s(i,a),this.planContrails(t,i),this.sortOutAudible(t,i),this.announceTraffic())}async readTrailTraffic(e,t,i,s,n,r){if(t.startMs===void 0)return;const a=await e.between(s,n,r).catch(()=>{});if(this.traffic!==t||a?.status!=="found")return;const o=a.tracks.filter(d=>d.points.some(u=>u.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),l=new Map(t.models??[]);if(e.describe&&await Promise.all(o.filter(d=>d.points.length>0&&!l.has(tn.keyOf(d))).map(async d=>{const u=await e.describe(d,new Date(d.points[0].t).toISOString().slice(0,10)).catch(()=>{});u&&l.set(tn.keyOf(d),i.AircraftModels.of(u))})),this.traffic!==t||t.startMs===void 0)return;const h=i.TrafficDecor.from(o,s,t.startMs,Rt.TRAIL_MAX_AIRCRAFT,{models:l});t.trailSet=Rt.alignTrailIds(h,t.set),t.models=new Map([...l,...t.models??[]]),this.planContrails(t,i),this.announceTraffic()}static alignTrailIds(e,t){if(!t)return e;const i=new Map;for(const[a,o]of t.flights){const l=t.presence.get(a);if(l)for(const[h,d]of e.flights){const u=e.presence.get(h);!u||tn.keyOf(d)!==tn.keyOf(o)||u.fromMs<=l.untilMs&&l.fromMs<=u.untilMs&&i.set(h,a)}}const s=a=>i.get(a)??`${a}-trail`,n=new Set(i.values()),r=t.objects.filter(a=>!n.has(a.id));return{...e,objects:[...e.objects.map(a=>({...a,id:s(a.id)})),...r],presence:new Map([...[...e.presence].map(([a,o])=>[s(a),o]),...r.map(a=>[a.id,t.presence.get(a.id)])]),flights:new Map([...[...e.flights].map(([a,o])=>[s(a),o]),...r.map(a=>[a.id,t.flights.get(a.id)])])}}async readUpperAir(e,t,i,s){if(!e.observer)return;const n=ts.held(this.ufoElement.sighting.frozen,"upperAir");let r;if(n){const l=Ct.address(n.src,this.documentUrl);r=Rt.upperAirProviders.get(l),r||Rt.upperAirProviders.set(l,r=new Eh(Ct.json(l)))}else{const l=this.upperAirSource??t.UPPER_AIR_SOURCES[0];r=Rt.upperAirProviders.get(l.id),r||Rt.upperAirProviders.set(l.id,r=l.create())}const a={lat:e.observer.lat,lng:e.observer.lng},o=await r.between(a,i,s);this.traffic!==e||o.status!=="found"||(n||(this.upperAirHeardLive={...a,startMs:i,endMs:s,answer:o}),e.air=o.samples,e.airSource=o.source,this.planContrails(e,t),this.announceTraffic())}planContrails(e,t){const i=e.trailSet??e.set;!i||!e.air||e.startMs===void 0||(e.contrails=t.AircraftContrails.plan(i,e.models,e.air,e.startMs))}contrailSunlight(e){const t=new Map,i=this.traffic,s=i?.trailSet??i?.set,n=this.lastSun;if(!i||!s||!n||!i.contrails?.length||i.startMs===void 0||!i.observer)return t;for(const r of i.contrails){const a=s.presence.get(r.id),o=s.flights.get(r.id);if(!a||!o)continue;const l=Pn.positionAt(o,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,e)));l&&t.set(r.id,{heightM:l.geo.heightM,sunElevationDeg:zn.sunElevationDeg(n,i.observer,l.geo)})}return t}sunElevationAt(e,t){const i=zi("Sun",new Date(e.t),t);return zn.sunElevationDeg(i,t,e)}upperAirSource;upperAirHeardLive;get upperAirHeard(){return this.upperAirHeardLive}setUpperAirSource(e){e.id!==this.upperAirSource?.id&&(this.upperAirSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(e){e.id!==this.aircraftSource.id&&(this.aircraftSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const e=this.traffic?.contrails?.length?this.upperAirSource??Rt.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 s=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(qA)))},n=Rt.tleArchive;(async()=>{if(!await n.covers(e))return s("outside");const[r,a]=await Promise.all([n.at(e),oe(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return s("unavailable");this.satellites={snapshot:r,passes:new a.SatellitePasses(r.objects)},s("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>s("unavailable"))}get satelliteState(){const e=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:e?.coverage,credit:e?.credit,creditUrl:e?.creditUrl}}burningCandidates(){return{reentries:this.ufoElement.sighting.skyEvents?.reentries??[],fireballs:this.fireballs?.reentries??[]}}trafficCandidates(){const e=this.traffic;if(!(e?.status!=="ready"||!e.tracks||e.startMs===void 0))return{tracks:e.tracks,startMs:e.startMs,describe:t=>e.descriptions?.get(tn.keyOf(t))}}satellitePositionsAt(e){const t=this.satellites,i=this.ufoElement.sighting,s=st(i,0),n=i.event.place?.[0],r=s?.lat??n?.lat,a=s?.lng??n?.lng;if(!(!t||r===void 0||a===void 0))return t.passes.positionsAt(e,{lat:r,lng:a,elevationM:s?.elevationM??0})}satellitePassesDuring(e){const t=this.satellites,i=this.ufoElement.sighting,s=st(i,0),n=i.event.place?.[0],r=s?.lat??n?.lat,a=s?.lng??n?.lng;if(!t||r===void 0||a===void 0)return[];const o=sn(i.event.time??{},a,i.event.utcOffsetHours);if(!o)return[];const l=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:a,elevationM:s?.elevationM??0},d=JSON.stringify([this.satellitesFor,o.getTime(),r,a,h.elevationM,l]);if(this.satellitePassesMemo?.key===d)return this.satellitePassesMemo.passes;const u=Math.max(10,Math.ceil(l/1e3/600)),p=t.passes.passesDuring(o,new Date(o.getTime()+l),h,u);return this.satellitePassesMemo={key:d,passes:p},p}cometAt(e,t){const i=Yf.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,s=this.ufoElement.canvasElement,n=this.ufoElement.frameShiftPx,r=this.projectionAt(e),a=new Map,o=new Map,l=new Set;for(const f of i.sourceIds){const m=i.getInterpolatedShapeAt(e,f);if(!m)continue;const v={...m,bounds:{...m.bounds,x:m.bounds.x+n.x,y:m.bounds.y+n.y}};a.set(f,v);const g=m.aim?this.sceneRenderer.screenPointOf(qr.directionOf(m.aim,this.directionScratch)):{ndcX:(v.bounds.x+v.bounds.width/2)/s.width*2-1,ndcY:-((v.bounds.y+v.bounds.height/2)/s.height*2-1)},b=g!==void 0&&Math.abs(g.ndcX)<=1&&Math.abs(g.ndcY)<=1,w=b?this.sceneRenderer.decorDistancesAt(g.ndcX,g.ndcY,f):{};l.add(f),(b||m.aim)&&l.delete(f);const y=m.angular?.widthDeg??r.pxToDeg(m.bounds.width),M=this.sizeEstimateOf(f);M.add(y,w);const S=bu.of(t,f);o.set(f,Ln.resolve({hypothesisM:this.distanceHypotheses.get(f),derivedM:S&&y>0?Lt.distanceMAt(S.widthM,y):void 0,range:M.distanceRangeAt(y),crossing:w}))}for(const[f,m]of a)for(const[v,g]of a){if(v===f||g.transparency>=1||g.bounds.width*g.bounds.height<=m.bounds.width*m.bounds.height||!(m.bounds.x>=g.bounds.x&&m.bounds.y>=g.bounds.y&&m.bounds.x+m.bounds.width<=g.bounds.x+g.bounds.width&&m.bounds.y+m.bounds.height<=g.bounds.y+g.bounds.height))continue;const w=o.get(v);w&&o.set(f,{distanceM:w.distanceM*.999,basis:w.basis});break}this.depths=o;const h=i.sourceIds,d=[];for(const[f,m]of a)d.push({sourceId:f,shape:m,distanceM:o.get(f).distanceM,renderOrder:h.indexOf(f),aim:m.aim,hidden:l.has(f)||this.interpretationShown!==void 0&&(!this.comparing||m.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const u=st(t,e),p=(u?.rollDeg??0)+bi.bodyAt(t,e,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(d,{projection:r,canvasWidthPx:s.width,canvasHeightPx:s.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,s.height)),starPoints:Qt.starPointsOf(t.instrument,u?.fNumber),rollRad:p*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(e){this.interpretationShown=Nt.expand(On.expand(e)),this.ufoElement.playerTitle=e?.title,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}redrawSky(){this.updateAstronomy(this.lastTimeMs)}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(e){this.inTheRound=e}get compareAccount(){return this.comparing}set compareAccount(e){e!==this.comparing&&(this.comparing=e,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())}get confrontation(){return this.confrontationReadings}groundAlong(e,t,i){const s=this.sceneRenderer.bodyGround,n=$e.eyeOf(this.ufoElement.sighting,i,s);return n?$e.lineOfSightMeetsGround(n,e,t,s):void 0}bodyMaskedBy(e,t){return this.sceneRenderer.bodyMaskedByDecor(e,t)}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,s=this.ufoElement.sighting,n=u=>$e.eyeOf(s,u,i),r=new $e(e,i,n).at(t),a=n(t);if(!r||!a)return;const o=r.eastM-a.eastM,l=r.northM-a.northM,h=r.upM-a.upM,d=Math.hypot(o,l);return{azimuthDeg:(Math.atan2(o,l)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,d)*180/Math.PI,distanceM:Math.hypot(d,h),eastM:r.eastM,northM:r.northM,aboveGroundM:r.upM-r.sizeM.heightM/2-i.heightAt(r.eastM,r.northM),sizeM:r.sizeM,attitude:r.attitude,appearance:r.appearance}}bodyProjectionAt(e,t){const i=this.sceneRenderer.bodyGround,s=this.ufoElement.sighting,n=o=>$e.eyeOf(s,o,i),r=new $e(e,i,n).at(t),a=n(t);return r&&a?Fi.projectionOf(r,a):void 0}directionToBody(e,t){const i=this.sceneRenderer.bodyGround,s=this.ufoElement.sighting,n=f=>$e.eyeOf(s,f,i),r=new $e(e,i,n),a=r.at(t)?t:e.track[0]?.t,o=a===void 0?void 0:r.at(a),l=a===void 0?void 0:n(a);if(!o||!l)return;const h=o.eastM-l.eastM,d=o.northM-l.northM,u=o.upM-l.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,s=this.ufoElement.sighting;let n=[],r=[];const a=this.sceneRenderer.bodyGround,o=f=>$e.eyeOf(s,f,a);i&&(n=i.bodies.map(f=>new $e(f,a,o).at(e)).filter(f=>f!==void 0));const l=fs(s,e),h=l.windDirectionDeg*Math.PI/180,d={x:l.windSpeed*Math.sin(h),z:-l.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(n,e/1e3,i?.bodies.map(f=>f.id)??[],i?.smoke??[],d);const u=i&&this.comparing?o(e):void 0;if(u&&(r=new Fi(s.timeline,this.confrontationTolerance).at(e,n,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(o8,{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 s=i.angular?.widthDeg??this.projectionAt(t).pxToDeg(i.bounds.width);return this.sizeEstimateOf(e).distanceRangeAt(s)}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 s=this.lastLightningT;if(this.lastLightningT=t,s===void 0||t<s||this.ufoElement.playbackState!=="playing")return;const n=this.lightningFlashes.filter(r=>r.t>s&&r.t<=t).pop();n&&fs(e,n.t).storm&&this.handleLightningFlash(n)}ensureLightningSchedule(e){const t=fs(e,0).precipitationIntensity,i=`${this.meteorInputsOf(e)}|${t}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const s=e.event.time,n=e.event.place?.[0],r=s?.year!==void 0?sn(s,n?.lng??0,e.event.utcOffsetHours):void 0,a=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,o=Math.round((r?.getTime()??0)/1e3)+Math.round((n?.lat??0)*1e3)+7;this.lightningFlashes=Ls.schedule({durationMs:a,seed:o,intensity:t}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(e){const t=this.meteorInputsOf(e);t!==this.meteorScheduleFor&&(this.meteorScheduleFor=t,this.scheduleMeteors(e))}meteorInputsOf(e){const t=e.event.place?.[0],i=e.event.time;return JSON.stringify([t?.lat,t?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,e.event.utcOffsetHours,e.event.durationSeconds,e.timeline.duration])}scheduleMeteors(e){const t=e.event.place?.[0],i=e.event.time,s=t?.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?sn(i,t.lng,e.event.utcOffsetHours):void 0;if(!s||t?.lat===void 0||t.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const n={lat:t.lat,lng:t.lng,elevationM:0},r=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,a=Math.round(s.getTime()/1e3)+Math.round(t.lat*1e3),o=Qi.schedule({ratePerHour:Qi.observedRatePerHour(Qi.apexPosition(s,n).altitudeDeg),durationMs:r,velocityKmS:Qi.TYPICAL_VELOCITY_KM_S,seed:a}),l=$h.activeAt(s).map(d=>{const u=$h.radiantPosition(d.shower,s,n);return{entry:d,position:u,rate:$h.observedRatePerHour(d.zhr,u.altitudeDeg,d.shower.populationIndex)}}).sort((d,u)=>u.rate-d.rate)[0];if(!l||l.rate<=0){this.sceneRenderer.setMeteorShower(o,0,0);return}const h=Or.schedule({ratePerHour:l.rate,durationMs:r,velocityKmS:l.entry.shower.velocityKmS,seed:a+1});this.sceneRenderer.setMeteorShower([...h,...o],l.position.altitudeDeg,l.position.azimuthDeg)}groundHides(e,t){return this.sceneRenderer.groundHidesDirection(e,t)}get groundKey(){return this.sceneRenderer.groundKey}meteorByRank(e,t=Number.POSITIVE_INFINITY){this.ensureMeteorSchedule(this.ufoElement.sighting);const i=[...this.sceneRenderer.meteorSchedule].filter(r=>r.t+r.durationMs<=this.ufoElement.seekableDuration).filter(r=>Or.magnitudeOf(r)<=t).filter(r=>{const a=this.sceneRenderer.meteorMidpoint(r);return a!==void 0&&!this.sceneRenderer.groundHidesDirection(a.altitudeDeg,a.azimuthDeg)}).sort((r,a)=>a.brightness-r.brightness);if(i.length===0)return;const s=i[e%i.length],n=this.sceneRenderer.meteorMidpoint(s);if(n)return{t:Math.round(s.t+s.durationMs*.45),...n}}lensOpticsAt(e){const t=this.ufoElement.sighting,i=t.instrument,s=i.frame,n=st(t,e),r=n?.fNumber??i.fNumber;if(!s||r===void 0)return;const a=Qt.focalLengthMmFor(i,Si.fovOf(t,e));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:n?.focusDistanceM??0,frameHeightMm:s.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return ar.of(t.instrument,Lt.CANVAS_HEIGHT_PX,Si.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new YN,this.sizeEstimates.set(e,t)),t}}const Km="rr0-scene";function f8(){f0(),customElements.get(Km)||customElements.define(Km,Rt)}class d1{constructor(e,t,i=d1.TOLERANCE_PX){this.timeline=e,this.clock=t,this.tolerancePx=i}static TOLERANCE_PX=1;currentPointer=null;shapePrototype=null;sourceId="";samples=[];start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.samples=[],this.clock.start(i=>this.recordSample(i))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop(),this.thin()}thin(){const e=this.samples;if(e.length<=2)return;const t=new Set([0,e.length-1]),i=[[0,e.length-1]];for(;i.length>0;){const[s,n]=i.pop(),r=e[s],a=e[n];let o=0,l=-1;for(let h=s+1;h<n;h++){const d=e[h],u=(d.t-r.t)/(a.t-r.t),p=Math.hypot(r.x+(a.x-r.x)*u-d.x,r.y+(a.y-r.y)*u-d.y);p>o&&(o=p,l=h)}l!==-1&&o>this.tolerancePx&&(t.add(l),i.push([s,l],[l,n]))}e.forEach((s,n)=>{t.has(n)||this.timeline.removeShapeAt(s.t,this.sourceId)}),this.samples=[]}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=cE(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}]),this.samples[this.samples.length-1]?.t===e&&this.samples.pop(),this.samples.push({t:e,x:this.currentPointer.x,y:this.currentPointer.y})}}class m8{constructor(e){this.intervalMs=e}rafId=null;startTime=0;lastTick=0;start(e){this.startTime=performance.now(),this.lastTick=0;const t=()=>{const i=performance.now()-this.startTime;i-this.lastTick>=this.intervalMs&&(this.lastTick=i,e(i)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}class ao{constructor(e,t,i,s={}){this.id=e,this.aspect=t,this.parts=i,this.minimum=s}static ALL=[new ao("triangle",.9,[{points:[[.5,0],[1,1],[0,1]],fx:0,fy:0,fw:1,fh:1}]),new ao("saucer",.6,[{part:"dome",fx:.28,fy:0,fw:.44,fh:.62},{part:"disc",fx:0,fy:.42,fw:1,fh:.42}]),new ao("cigar",.25,[{fx:0,fy:0,fw:1,fh:1}]),new ao("chevron",.55,[{points:[[.5,0],[1,1],[.5,.6],[0,1]],fx:0,fy:0,fw:1,fh:1}]),new ao("light",1,[{fx:.3,fy:.3,fw:.4,fh:.4}],{haloScale:2.5,brightness:.5})];static byId(e){return ao.ALL.find(t=>t.id===e)}get partNames(){return this.parts.map(e=>e.part)}boundsAt(e){const t=e.width*this.aspect;return{x:e.x,y:e.y+e.height/2-t/2,width:e.width,height:t}}shapesIn(e,t){return this.parts.map(i=>{const s={x:e.x+i.fx*e.width,y:e.y+i.fy*e.height,width:i.fw*e.width,height:i.fh*e.height};return{...i.points?lE(s,i.points.map(([r,a])=>({x:r*s.width,y:a*s.height})),t.color):oE(s,t.color),transparency:t.transparency,haloScale:Math.max(t.haloScale,this.minimum.haloScale??0),blur:t.blur,brightness:Math.max(t.brightness,this.minimum.brightness??0)}})}}const GS="rr0-provider-settings",g8=`
|
|
@@ -11570,8 +11570,8 @@ ${Xt.rules([],[".model-picker .model-picker-address p"])}
|
|
|
11570
11570
|
.model-picker .model-thumb img { width: 100%; height: 100%; object-fit: contain; }
|
|
11571
11571
|
.model-picker .model-name { font-weight: 600; }
|
|
11572
11572
|
.model-picker .model-credit { font-size: .8em; color: #666; }
|
|
11573
|
-
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await oe(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-BA3zFrn5.js");return{ModelThumbnails:i}},__vite__mapDeps([11,12]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const s=document.createElement("button");s.type="button",s.className="model-picker-button",e.after(s),e.hidden=!0;let n=0,r;const a=()=>{const l=++n,h=e.selectedOptions[0],d=e.value===""?i?.current():void 0,u=JSON.stringify([e.value,h?.textContent,d?.url,d?.title,this.messages().choose,[...e.options].map(m=>m.value).join()]);if(u===r){--n;return}r=u,s.replaceChildren();const p=document.createElement("span");p.textContent=`${d?d.title||d.url:h?.textContent??""} …`,s.title=this.messages().choose,s.append(p);const f=e.value;(d?Promise.resolve({url:d.url}):t(f)).then(m=>yu.pictureOf(m)).then(m=>{if(!m||l!==n)return;const v=new Image;v.src=m,v.alt="",s.prepend(v)})};e.addEventListener("change",a),new MutationObserver(a).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:l=>{i.apply(l),a()}};s.addEventListener("click",()=>void this.open(e,t,o)),a()}chooseFrom(e,t,i,s){this.ensureStyle(),this.open(e,t,s,i)}ensureStyle(){const e=this.root instanceof ShadowRoot?this.root:this.root.getRootNode(),t=e instanceof ShadowRoot?e:document.head;if(t.querySelector("style[data-model-picker]"))return;const i=document.createElement("style");i.dataset.modelPicker="",i.textContent=yu.STYLE,t.append(i)}open(e,t,i,s){const n=this.messages(),r=document.createElement("div");r.className="model-picker-backdrop";const a=document.createElement("div");a.className="model-picker",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=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.innerHTML=Ee.CLOSE;const h=document.createElement("header");h.append(o,l);const d=document.createElement("div");d.className="model-picker-body",a.append(h,d),r.append(a);const u=()=>{r.remove(),document.removeEventListener("keydown",p,!0),oe(async()=>{const{ModelViewer:E}=await import("./ModelViewer-BDorZEms.js");return{ModelViewer:E}},__vite__mapDeps([13,12]),import.meta.url).then(({ModelViewer:E})=>E.end())},p=E=>{E.key==="Escape"&&(E.stopPropagation(),u())},f=i?.current(),m="\0address",v=E=>E===m&&f?Promise.resolve({url:f.url}):t(E),g=E=>{if(u(),s){E!==m&&s(E);return}E===m||E===e.value||(e.value=E,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const w=new Map,y=E=>{const x=document.createElement("button");x.type="button",x.className="model-card",x.dataset.value=E.value,x.setAttribute("aria-pressed",String(!s&&(E.value===m||E.value===e.value&&!f)));const A=document.createElement("div");A.className="model-thumb";const D=document.createElement("span");if(D.className="model-name",D.textContent=E.textContent,x.append(A,D),E.title){const C=document.createElement("span");C.className="model-credit",C.textContent=E.title,x.append(C)}v(E.value).then(C=>yu.pictureOf(C)).then(C=>{if(!C)return;const P=new Image;P.src=C,P.alt="",A.append(P)});let R,L=!1;const N=()=>{L&&!(R&&!R.active)||(L=!0,Promise.all([v(E.value),oe(()=>import("./ModelViewer-BDorZEms.js"),__vite__mapDeps([13,12]),import.meta.url)]).then(([C,{ModelViewer:P}])=>{!C||!L||(R=P.show(A,C))}).catch(()=>{}))},k=()=>{L=!1,R?.stop(),R=void 0};return w.set(x,N),x.addEventListener("pointerenter",N),x.addEventListener("focus",N),x.addEventListener("pointerleave",()=>{document.activeElement!==x&&k()}),x.addEventListener("blur",k),x.addEventListener("click",C=>{if(R?.consumeDrag()){C.preventDefault();return}g(E.value)}),x},M=()=>(b=document.createElement("div"),b.className="model-picker-grid",d.append(b),b);if(f){const E=new Option(f.title||f.url,m);E.title=[f.author,f.license].filter(Boolean).join(" — "),M().append(y(E))}for(const E of Array.from(e.children))if(E instanceof HTMLOptGroupElement){const x=document.createElement("h3");x.textContent=E.label,d.append(x);const A=M();for(const D of Array.from(E.children))A.append(y(D));b=void 0}else E instanceof HTMLOptionElement&&(b??M()).append(y(E));i&&this.addAddressForm(h,l,a,d,i,n,u),l.addEventListener("click",u),r.addEventListener("click",E=>{E.target===r&&u()}),document.addEventListener("keydown",p,!0),this.root.append(r);const S=a.querySelector('.model-card[aria-pressed="true"]');(S??l).focus(),S&&w.get(S)?.()}addAddressForm(e,t,i,s,n,r,a){const o=document.createElement("button");o.type="button",o.className="model-picker-add",o.textContent="+",o.title=r.address,o.setAttribute("aria-label",r.address),o.setAttribute("aria-expanded","false"),e.insertBefore(o,t);const l=document.createElement("form");l.className="model-picker-address",l.hidden=!0;const h=(w,y,M="")=>{const S=document.createElement("label"),E=document.createElement("span");E.textContent=w;const x=document.createElement("input");return x.type=y,x.placeholder=M,S.append(E,x),l.append(S),x},d=h(r.addressUrl,"url","https://…/model.glb"),u=h(r.addressName,"text"),p=h(r.addressAuthor,"text"),f=h(r.addressLicense,"text","CC0 1.0"),m=h(r.addressSource,"url","https://…"),v=document.createElement("p");v.textContent=r.addressIncomplete;const g=document.createElement("button");g.type="submit",g.className="model-picker-use",g.textContent=r.addressUse,l.append(v,g),i.insertBefore(l,s);const b=()=>{g.disabled=d.value.trim()==="",v.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const w of[d,u,p,f,m])w.addEventListener("input",b);o.addEventListener("click",()=>{const w=l.hidden;if(l.hidden=!w,o.setAttribute("aria-expanded",String(w)),!w)return;const y=n.current();d.value=y?.url??"",u.value=y?.title??"",p.value=y?.author??"",f.value=y?.license??"",m.value=y?.source??"",b(),d.focus()}),l.addEventListener("submit",w=>{w.preventDefault(),d.value.trim()!==""&&(n.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:m.value.trim()}),a())}),b()}}class p1{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=p1.SPAN_DEG;try{const n=(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(n)?n:void 0}catch{return}}}class Z8{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),s=this.zoneOffsetHours(e,new Date(i));if(s!==void 0)return this.zoneOffsetHours(e,new Date(i-s*36e5))??s}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 s=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",n=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(s);if(n)return n[1]?(n[1]==="-"?-1:1)*(Number(n[2])+Number(n[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(s=>this.offsetHoursAt(s,i)===e)}}class Bn{static STEP_MS=100;static plan(e){const t=Bn.routeOf(e),i=ri.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const a=(l,h,d,u)=>{if(Math.abs(l.radiusM-u)>=u*.1)return!1;const{x:p,z:f}=ut(h,d,l.lat,l.lng);return Math.hypot(p,f)<ri.rebuildDistanceFor(u)};for(let l=0;;l=Math.min(s,l+Bn.STEP_MS)){const h=st(e,l);if(h?.lat!==void 0&&h.lng!==void 0){const d=Math.max(ri.groundRadiusFor(h.elevationM??0),i);(!r||!a(r,h.lat,h.lng,d))&&(r=n.find(u=>a(u,h.lat,h.lng,d)),r||n.push(r={lat:h.lat,lng:h.lng,radiusM:d}))}if(l>=s)break}const o=e.skyEvents?.beams??[];if(o.length>0)for(const l of[...n])ri.needsFarRing(l.radiusM,0,ri.beamReachFor(o,l))&&n.push({lat:l.lat,lng:l.lng,radiusM:ri.FAR_RING_RADIUS_M,far:!0});return n}static routeOf(e){const t=e.observerTrack.allKeyframes.flatMap(i=>i.pose.lat!==void 0&&i.pose.lng!==void 0?[{lat:i.pose.lat,lng:i.pose.lng}]:[]);return t.length>=2?t:void 0}static async freeze(e,t,i,s,n){const r=new Date().toISOString().slice(0,10),a=o=>n?.(o,i.length);switch(e){case"relief":{const o=Bn.routeOf(t),l=[];for(const[u,p]of i.entries()){try{const f=await s.elevation.getElevationGrid(Kn.boundsOf(p),{width:Om,height:Om},{route:o});l.push({...p,grid:f})}catch(f){console.warn("Relief not frozen for a patch:",f)}a(u+1)}if(l.length===0)return;const h=s.elevationCredit;return{bytes:await cp.encode({takenOn:r,attribution:h,patches:l}),attribution:h,takenOn:r,answered:l.length,patches:i.length}}case"imagery":{const o=new OS,l=ds(fc,s.imagery),h=l.create(o.fetch);let d=0;for(const[f,m]of i.entries()){try{await h.getImageryTexture(Kn.boundsOf(m),{width:Pm,height:Pm}),d++}catch(v){console.warn("Imagery not frozen for a patch:",v)}a(f+1)}if(o.tiles.size===0)return;const u=h.attribution;return{bytes:await Hm.encode({takenOn:r,source:l.id,attribution:u,patches:[...i],tiles:o.tiles}),attribution:u,takenOn:r,answered:d,patches:i.length}}case"roads":return Bn.vector(s.roads,i,r,a,(o,l)=>o.getRoads(l),o=>o.contemporary);case"water":return Bn.vector(s.water,i,r,a,(o,l)=>o.getWater(l));case"railways":return Bn.vector(s.railways,i,r,a,(o,l)=>o.getRailways(l),o=>o.contemporary)}}static mapGround(e){const t=oc.of(e);return t&&hi.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=Bn.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new OS,r=ds(fc,t),a=r.create(n.fetch),o=hi.IMAGERY_PX;try{await a.getImageryTexture(i,{width:o,height:o})}catch(d){console.warn("Map imagery not frozen:",d);return}const l=a.attribution;return{bytes:await Hm.encode({takenOn:s,source:r.id,attribution:l,patches:[],map:{bounds:i,pixels:o},tiles:n.tiles}),attribution:l,takenOn:s,answered:1,patches:1}}static async vector(e,t,i,s,n,r){if(!e)return;const a=[];for(const[h,d]of t.entries()){if(d.radiusM<=ri.ROADS_MAX_RADIUS_M)try{a.push({...d,items:await n(e,Kn.boundsOf(d))})}catch(u){console.warn("Not frozen for a patch:",u)}s(h+1)}if(a.length===0)return;const o={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:a};return{bytes:new TextEncoder().encode(JSON.stringify(o)),attribution:e.attribution,takenOn:i,answered:a.length,patches:t.length}}}class ss{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.replace(this.shown,i.detail)),this.root.querySelector("#frozen-refresh").addEventListener("click",()=>void this.refresh(this.shown)),this.root.querySelector("#annex-export").addEventListener("click",()=>void this.exportAnnex(this.shown))}messages;busy=!1;shown="relief";editor;editorFor;editTimer;get sourceInput(){return this.root.querySelector("#annex-source")}get editorHost(){return this.root.querySelector("#annex-editor")}get note(){return this.root.querySelector("#frozen-note")}localize(e){this.messages=e,this.root.title=e.frozenHint;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-annex-source",e.annexSource),t("frozen-refresh",e.frozenRefresh),t("annex-export",e.export),this.sourceInput.messages=e,this.render()}itemLabel(e){return this.groupName(e)}where(e){const t=this.annex(e);return this.isLive(e)?this.messages.frozenLiveState:!t||t.refresh?this.messages.frozenPending:ss.isInline(t.src)?this.messages.annexStorageInline:t.src}isInlineGroup(e){const t=this.annex(e);return t!==void 0&&!this.isLive(e)&&ss.isInline(t.src)}annex(e){const t=this.host.sighting().frozen?.[e];return t?.src!==void 0?t:void 0}isLive(e){return ts.isLive(this.host.sighting().frozen,e)}setLive(e,t){if(this.isLive(e)===t)return;const i={...this.host.sighting().frozen??{}};if(i.live){delete i.live;for(const n of ts.NAMES)i[n]={...i[n]??{},live:!0}}const s={...i[e]??{}};t?s.live=!0:delete s.live,i[e]=Object.keys(s).length>0?s:void 0,this.setFrozen(i)}show(e){this.shown=e,this.render()}render(){if(!this.messages)return;const e=this.shown,t=this.isLive(e),i=this.annex(e),s=this.root.querySelector("#frozen-state");s.textContent=t?this.messages.frozenLiveState:i&&!i.refresh?[this.messages.frozenTakenOn.replaceAll("{date}",i.takenOn??"?"),i.attribution].filter(Boolean).join(" · "):this.messages.frozenPending;const n=this.root.querySelector("#frozen-refresh");n.disabled=this.busy||t;const r=i!==void 0&&!i.refresh&&!t,a=r&&ss.isInline(i.src);this.sourceInput.url=r?a?this.host.masterUrl():this.address(i.src):"",r||(this.sourceInput.mode="file"),this.sourceInput.disabled=this.busy||t,this.root.querySelector("#annex-export").disabled=i===void 0||this.busy,this.renderEditor(r&&!a?i:void 0)}async renderEditor(e){const t=this.shown,i=e&&!ss.isZip(t)?await this.textOf(e).catch(()=>{}):void 0;if(t!==this.shown||(this.editorHost.hidden=i===void 0,i===void 0))return;const s=`${t}|${e.src}`;if(this.editor&&this.editorFor===s)return;if(this.editorFor=s,this.editor){this.editor.replaceText(i,!1);return}const{SightingFileEditor:n}=await oe(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-BekK-f3R.js");return{SightingFileEditor:r}},__vite__mapDeps([14,1,15]),import.meta.url);this.editor??=new n(this.editorHost,i,r=>this.edited(r),this.messages.annexEditorLabel,{schema:{},phrases:this.messages.fileSearchPhrases})}async textOf(e){return JSON.stringify(JSON.parse(new TextDecoder().decode(await this.bytesOf(e))),null,1)}edited(e){const t=this.shown;clearTimeout(this.editTimer),this.editTimer=setTimeout(()=>{let i;try{i=JSON.parse(e)}catch{return}this.write(t,new TextEncoder().encode(JSON.stringify(i)),{keepEditor:!0})},600)}async replace(e,t){if(t.url){if(this.address(t.url)===new URL(this.host.masterUrl(),location.href).href){await this.setStorage(e,!0);return}const s={...this.host.sighting().frozen??{}};let n;try{n=await this.bytesAt(t.url)}catch{n=void 0}if(n!==void 0)try{s[e]={src:t.url,...await ss.describe(e,n)}}catch{Xt.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){Xt.show(this.note,this.messages.frozenMissing.replaceAll("{file}",t.url),"warning");return}Ct.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}Xt.show(this.note,void 0),this.setFrozen(s);return}const{InputFileElement:i}=await oe(async()=>{const{InputFileElement:s}=await Promise.resolve().then(()=>eT);return{InputFileElement:s}},void 0,import.meta.url);await this.write(e,await i.bytesOf(t))}async write(e,t,i={}){const s={...this.host.sighting().frozen??{}},n=this.annex(e);let r;try{r=await ss.describe(e,t)}catch{Xt.show(this.note,this.messages.annexUnreadable,"warning");return}const a=n!==void 0&&ss.isInline(n.src),o=a?ss.dataUrl(e,t):n?.src??ts.annexName(this.host.base(),e);a||Ct.hold(this.address(o),t),s[e]={...s[e]?.live?{live:!0}:{},src:o,...r},Xt.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${o}`),this.setFrozen(s)}async setStorage(e,t){const i={...this.host.sighting().frozen??{}},s=this.annex(e);if(!s||ss.isInline(s.src)===t)return;const n=await this.bytesOf(s);let r;t?r=ss.dataUrl(e,n):(r=ts.annexName(this.host.base(),e),Ct.hold(this.address(r),n)),i[e]={...s,src:r},this.editorFor=`${e}|${r}`,this.setFrozen(i)}async exportAnnex(e){const t=this.annex(e);if(!t)return;const i=await this.bytesOf(t),s=ss.isInline(t.src)?ts.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:ss.isZip(e)?"application/zip":"application/json"}),s)}static async describe(e,t){let i;if(ss.isZip(e)){const{unzipSync:s}=await oe(async()=>{const{unzipSync:n}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:n}},[],import.meta.url);i=JSON.parse(new TextDecoder().decode(s(t)["index.json"]))}else i=JSON.parse(new TextDecoder().decode(t));if(typeof i!="object"||i===null)throw new Error("Not an annex");return{takenOn:typeof i.takenOn=="string"?i.takenOn:void 0,attribution:typeof i.attribution=="string"?i.attribution:void 0}}async bytesAt(e){return Ct.bytes(this.address(e))}static isInline(e){return e.startsWith("data:")}static isZip(e){return e==="relief"||e==="imagery"||e==="map"}static dataUrl(e,t){let i="";for(let s=0;s<t.length;s+=32768)i+=String.fromCharCode(...t.subarray(s,s+32768));return`data:${ss.isZip(e)?"application/zip":"application/json"};base64,${btoa(i)}`}async refresh(e){if(this.busy)return;const t={...this.host.sighting().frozen??{}};if(e==="upperAir"){const i=t.upperAir;i&&(t.upperAir={...i,refresh:!0}),this.setFrozen(t);return}this.busy=!0,this.render();try{const i=t[e]?.src,s=(i&&!ss.isInline(i)?ss.baseOf(i):void 0)??this.host.base();(e==="map"?await this.takeMap(t,this.host.sources(),s):await this.take(e,t,Bn.plan(this.host.sighting()),this.host.sources(),s))?Xt.show(this.note,void 0):Xt.show(this.note,this.messages.frozenFailed.replaceAll("{group}",this.groupName(e)),"warning")}finally{this.busy=!1}this.setFrozen(t)}hasWork(){const e=this.host.sighting();return ts.isEmpty(e.frozen)?this.host.upperAirHeard()!==void 0||Bn.plan(e).length>0:!0}async prepare(e){const t=this.host.sighting(),i={...t.frozen??{}},s=new Map;this.busy=!0,this.render();try{const n=d=>ts.isLive(i,d),r=d=>i[d]?.src!==void 0?i[d]:void 0;for(const d of ts.NAMES)!i.live&&i[d]?.live&&(i[d]={live:!0});const a=Bn.plan(t);let o;for(const d of ts.TERRAIN){if(n(d))continue;const u=r(d);if(a.length>0&&(!u||u.refresh||!await this.fits(d,u,a))&&await this.take(d,i,a,o??=this.host.sources(),e)){await this.keep(r(d),s);continue}u?.refresh&&(i[d]={...u,refresh:void 0}),r(d)&&await this.keep(r(d),s)}if(!n("map")){const d=r("map");Bn.mapGround(t)!==void 0&&(!d||d.refresh||!await this.fitsMap(d))&&await this.takeMap(i,o??=this.host.sources(),e)?await this.keep(r("map"),s):d&&(d.refresh&&(i.map={...d,refresh:void 0}),await this.keep(r("map"),s))}const l=this.host.upperAirHeard(),h=r("upperAir");if(!n("upperAir")&&l&&(!h||h.refresh)){const d=new Date().toISOString().slice(0,10),u={version:1,takenOn:d,attribution:l.answer.source.name,answers:[l]},p=new TextEncoder().encode(JSON.stringify(u)),f=this.place("upperAir",h?.src,e,p);i.upperAir={src:f,takenOn:d,attribution:l.answer.source.name},ss.isInline(f)||s.set(f,p)}else h&&!n("upperAir")&&(h.refresh&&(i.upperAir={...h,refresh:void 0}),await this.keep(r("upperAir"),s))}finally{this.busy=!1}return this.setFrozen(i),s}async take(e,t,i,s,n){const r=this.groupName(e),a=await Bn.freeze(e,this.host.sighting(),i,s,(o,l)=>Xt.show(this.note,this.messages.frozenTaking.replaceAll("{group}",r).replaceAll("{done}",String(o)).replaceAll("{of}",String(l))));return Xt.show(this.note,void 0),a?(t[e]={src:this.place(e,t[e]?.src,n,a.bytes),takenOn:a.takenOn,attribution:a.attribution},!0):!1}async takeMap(e,t,i){Xt.show(this.note,this.messages.frozenTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await Bn.freezeMap(this.host.sighting(),t.imagery);return Xt.show(this.note,void 0),s?(e.map={src:this.place("map",e.map?.src,i,s.bytes),takenOn:s.takenOn,attribution:s.attribution},!0):!1}async fitsMap(e){const t=Bn.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await Ct.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&Kn.sameBounds(i.map.bounds,t)}catch{return!1}}async fits(e,t,i){try{const s=this.address(t.src),n=t.src.endsWith(".zip")?JSON.parse(new TextDecoder().decode((await Ct.zip(s))["index.json"])).patches:(await Ct.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(a=>a.radiusM<=ri.ROADS_MAX_RADIUS_M);return Kn.samePatches(n.map(({lat:a,lng:o,radiusM:l})=>({lat:a,lng:o,radiusM:l})),r)}catch{return!1}}place(e,t,i,s){if(t!==void 0&&ss.isInline(t))return ss.dataUrl(e,s);const n=t??ts.annexName(i,e);return Ct.hold(this.address(n),s),n}async keep(e,t){if(!ss.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{Xt.show(this.note,this.messages.frozenMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return Ct.bytes(this.address(e.src))}address(e){return Ct.address(e,this.host.documentUrl())}setFrozen(e){for(const t of ts.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().frozen=ts.isEmpty(e)?void 0:e,this.render(),this.host.changed()}destroy(){clearTimeout(this.editTimer),this.editor?.destroy(),this.editor=void 0,this.editorFor=void 0}static baseOf(e){return e?.match(/^(.*)\.[a-z-]+\.(zip|json)$/)?.[1]}static size(e){return e<1e6?`${Math.max(1,Math.round(e/1e3))} kB`:`${(e/1e6).toFixed(1)} MB`}groupName(e){return{relief:this.messages.frozenRelief,imagery:this.messages.frozenImagery,roads:this.messages.frozenRoads,water:this.messages.frozenWater,railways:this.messages.frozenRailways,upperAir:this.messages.frozenUpperAir,map:this.messages.frozenMap}[e]}}class jm{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.take(this.shown,i.detail)),this.root.querySelector("#section-annex-export").addEventListener("click",()=>this.exportAnnex(this.shown))}messages;shown="weather";get sourceInput(){return this.root.querySelector("#section-annex-source")}get note(){return this.root.querySelector("#section-annex-note")}localize(e){this.messages=e;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-section-annex-source",e.annexSource),t("section-annex-export",e.export),this.sourceInput.messages=e,this.render()}show(e){this.shown=e,Xt.show(this.note,void 0),this.render()}srcOf(e){return this.host.sighting().frozen?.[e]?.src}itemLabel(e){return{weather:this.messages.fileItemWeather,place:this.messages.fileItemPlace,lightPollution:this.messages.fileItemLightPollution,decor:this.messages.fileItemDecor}[e]}where(e){return this.srcOf(e)??this.messages.annexStorageInline}isInline(e){return this.srcOf(e)===void 0}static pathOf(e){return[Ns.KEYS[e][0]]}render(){if(!this.messages)return;const e=this.srcOf(this.shown);this.sourceInput.url=e?this.resolve(e):this.host.masterUrl(),this.root.querySelector("#section-annex-state").textContent=this.state(this.shown)}state(e){const t=this.host.sighting();switch(e){case"weather":return t.weatherSource?.name??this.messages.weatherStatedByObserver;case"place":return t.event.place?.[0]?.name??"";case"lightPollution":return t.provenance.at("lightPollution")?.rationale??(t.lightPollution===void 0?"":String(t.lightPollution));case"decor":return""}}setStorage(e,t){const i={...this.host.sighting().frozen??{}};if(t===(i[e]?.src===void 0))return;const{src:s,...n}=i[e]??{};i[e]=t?n:{...n,src:Ns.annexName(this.host.base(),e)},this.write(e,i)}annex(e){const t=this.srcOf(e);return t===void 0?void 0:{src:t,bytes:this.bytesOf(e)}}bytesOf(e){const t=um(this.host.sighting()),i={version:il.CURRENT.sighting};for(const s of Ns.KEYS[e])t[s]!==void 0&&(i[s]=t[s]);return new TextEncoder().encode(JSON.stringify(i))}resolve(e){return new URL(e,this.host.documentUrl()??location.href).href}exportAnnex(e){const t=this.srcOf(e)??Ns.annexName(this.host.base(),e);this.host.download(new Blob([this.bytesOf(e)],{type:"application/json"}),decodeURIComponent(t.split("/").pop()??t))}async take(e,t){if(t.url&&this.resolve(t.url)===this.resolve(this.host.masterUrl())){this.setStorage(e,!0);return}if(t.url)try{await fetch(this.resolve(t.url),{method:"HEAD"}).then(o=>{if(!o.ok)throw new Error(String(o.status))})}catch{const o={...this.host.sighting().frozen??{}};o[e]={...o[e]??{},src:t.url},Xt.show(this.note,void 0),this.write(e,o);return}let i;try{const{InputFileElement:o}=await oe(async()=>{const{InputFileElement:h}=await Promise.resolve().then(()=>eT);return{InputFileElement:h}},void 0,import.meta.url),l=await o.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=Ui.toCurrent(JSON.parse(new TextDecoder().decode(l))),typeof i!="object"||i===null||Ns.KEYS[e].every(h=>i[h]===void 0))throw new Error("Not this section")}catch{Xt.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...um(s)};for(const o of Ns.KEYS[e])n[o]=i[o];const r=ky(n);jm.copy(e,r,s);const a={...s.frozen??{}};t.url?a[e]={...a[e]??{},src:t.url}:a[e]=a[e]??{},Xt.show(this.note,void 0),this.write(e,a)}write(e,t){this.host.sighting().frozen=ts.isEmpty(t)?void 0:t,this.render(),this.host.changed(e)}static copy(e,t,i){switch(e){case"weather":i.weatherTrack.clear();for(const s of t.weatherTrack.allKeyframes)i.weatherTrack.addKeyframe(s.t,s.weather);i.weatherSource=t.weatherSource;break;case"place":i.event.place=t.event.place;break;case"lightPollution":i.lightPollution=t.lightPollution;break;case"decor":i.decor=t.decor;break}for(const s of Ns.KEYS[e]){i.provenance.clear(s);for(const n of t.provenance.paths())(n===s||n.startsWith(`${s}.`))&&i.provenance.set(n,t.provenance.at(n))}}}class J8{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 s=await fetch(i.toString());if(!s.ok)return;const n=await s.json();return n.timezone&&n.timezone!=="GMT"?n.timezone:void 0}catch{return}}}const Q8=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new J8}],e9=["appearance","movement","incongruity","detection","close","beings","traces"];class yv{static OCCUPATIONS={student:!0,worker:!0,farmer:!0,homemaker:!0,merchant:!0,business:!0,employee:!0,artist:!0,technician:!0,police:!0,pilot:!0,military:!0};static RELATIONS=["friends","family","professional","none"];static ACTIVITIES=["leisure","travelling","cultural","working"]}class cs{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=cs.select("observerOccupationKind");graduate=cs.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=cs.select("observersRelation");activity=cs.select("observerActivity");factors=new Map(e9.map(e=>[e,cs.select(`strangeness-${e}`)]));labels=new Map;unit=document.createTextNode(" min");strangenessTitle=document.createElement("span");strangenessIntro=Object.assign(document.createElement("p"),{className:"section-intro"});wording;constructor(e,t,i,s){Hn.register(),e.append(this.label(this.occupationKind,h=>[h.occupationKind,h.occupationKindHint]),this.label(this.graduate,h=>[h.graduate]));const n=this.label(this.enquiryMinutes,h=>[h.enquiryMinutes,h.enquiryMinutesHint]);n.append(this.unit);const r=t.querySelector("#accountSource")?.closest("label");r?r.after(n):t.append(n),t.append(this.label(this.relation,h=>[h.relation]),this.label(this.activity,h=>[h.activity]));const a=Object.assign(document.createElement("h3"),{className:"section-title"});a.append(this.strangenessTitle),i.append(a,this.strangenessIntro,...[...this.factors].map(([h,d])=>this.label(d,u=>[u.factors[h],u.factorHints[h]])));const o=[["yes","yes"],["no","no"]],l=h=>h.map(d=>[d,d]);cs.choices(this.occupationKind,"",l(Object.keys(yv.OCCUPATIONS))),cs.choices(this.graduate,"",o),cs.choices(this.relation,"",l(yv.RELATIONS)),cs.choices(this.activity,"",l(yv.ACTIVITIES));for(const h of this.factors.values())cs.choices(h,"",o);for(const h of[this.occupationKind,this.graduate,this.enquiryMinutes,this.relation,this.activity,...this.factors.values()])h.addEventListener("change",s)}set messages(e){this.wording=e;for(const t of this.labels.values())t();this.unit.textContent=` ${e.minutes}`,this.strangenessTitle.textContent=e.strangenessSection,this.strangenessIntro.textContent=e.strangenessIntro,cs.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),cs.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),cs.choices(this.relation,e.unknown,Object.entries(e.relations)),cs.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)cs.choices(i,cs.READ_FROM_RECORDING.includes(t)?e.fromRecording:e.unknown,[["yes",e.yes],["no",e.no]])}show(e){this.occupationKind.value=e?.observerOccupationKind??"",this.graduate.value=cs.yesNo(e?.observerGraduate),this.enquiryMinutes.value=e?.enquiryMinutes?.toString()??"",this.relation.value=e?.observersRelation??"",this.activity.value=e?.activity??"";for(const[t,i]of this.factors)i.value=cs.yesNo(e?.strangeness?.[t])}values(){const e=this.enquiryMinutes.value.trim()===""?void 0:Number(this.enquiryMinutes.value),t={};for(const[i,s]of this.factors){const n=cs.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:cs.boolean(this.graduate.value),enquiryMinutes:e!==void 0&&Number.isFinite(e)&&e>=0?e:void 0,observersRelation:this.relation.value||void 0,activity:this.activity.value||void 0,strangeness:Object.keys(t).length>0?t:void 0}}label(e,t){const i=document.createElement("label"),s=document.createElement("span");return i.append(s," ",e),this.labels.set(s,()=>{if(!this.wording)return;const[n,r]=t(this.wording);Hn.say(s,n,r)}),i}static select(e){return Object.assign(document.createElement("select"),{id:e})}static choices(e,t,i){const s=e.value;e.replaceChildren(new Option(t,""),...i.map(([n,r])=>new Option(r,n))),e.value=s}static yesNo(e){return e===void 0?"":e?"yes":"no"}static boolean(e){return e===""?void 0:e==="yes"}}const Rf=new Set;f0();f8();Rh.register();const sh={width:48,height:28},t9=2500,eE=40,i9=10,tE=600,iE=900,nh=2e-4,s9=900,n9=-1.46,r9=3,wv=.2,a9=.5,o9=3,l9=.01,c9=1.6,Mv=2e3,h9=250,sE=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),d9=1,u9=5,p9=10,Ho=4,Wd="ufo-1",f9={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function m9(c){return c.kind==="oval"?"oval":"polygon"}const g9=-6,v9=21;class _e extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=Q8[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new Z8;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;candidatesView;sectionFolds;frozenPanel;sectionFilePanel;eventsPanel;phenomenonEventsPanel;bodiesEventsPanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=K8();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lensGlassSelect;isoInput;meteringSelect;lensDropsInput;lensCondensationInput;lensDirtInput;lensShelteredInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;evaluationFields;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;launchEditor;launchEditorLoading;beamEditor;beamEditorLoading;lanternEditor;lanternEditorLoading;fileEditor;fileEditorLoading;fileEditorHost;fileNote;fileAsk;identityAsk;fileSyncTimer;fileApplyTimer;historySnapshot;historyTimer;historyAnswering=!1;undoButton;redoButton;labelFileGroup;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new pv(W8());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelPosition;observerSaid;observerSaidShown;observerPosition;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;wholeKeyframesInput;labelImportFile;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;accountShapeIds;labelNarrativeSource;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;labelRareIce;highCloudCoverInput;iceCrystalAlignmentInput;rareIceCrystalsInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelLaunchesSubgroup;labelBeamsSubgroup;labelLanternsSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;weatherProviderSelect;weatherFileLink;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorList;observerList;observerShown="principal";static CLICK_SLOP_PX=5;static OBSERVER_PRINCIPAL="principal";surroundings;surroundingsProvider;sceneryStatus;scenerySource;labelScenerySource;sceneryWarning;sceneryRadius;labelSceneryRadius;sceneryChoice;decorModelProvider=Kf[0].create();milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=gl;currentAppearance={...f9};currentSourceId=Wd;selectedSourceIds=new Set([Wd]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSourceInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;referenceFailure;addReferenceButton;referenceAddMenu;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;findGhostsButton;searchingGhosts=!1;ghostsStatus;ghostFinding;ghostsShown=!0;ghostsShownButton;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;traceImportInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;addTraceButton;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$;pictureRegistration;pictureRegistrationLoading;referenceFields;labelReferenceGroup;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),(e.ctrlKey||e.metaKey)&&!e.altKey&&["z","y"].includes(e.key.toLowerCase())){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;e.preventDefault(),e.key.toLowerCase()==="y"||e.shiftKey?this.redo():this.undo();return}if(sE.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;sE.has(e.key)?this.selectedMembers().length===0&&t===this?this.walkOrTurn(e):this.moveOrResizeSelectedShapes(e):this.canvasMode()==="decor"?this.deleteDecor():this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0,t=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedBodyId:void 0;this.endDrag(),t!==void 0&&this.showBody(t),e!==void 0&&(this.selectDecor(e),this.revealDecorPanel(),this.flash(this.shadow.querySelector("#decor-item label, #decor-item .field")))};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${V5}</style>${G5}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const a of this.shadow.querySelectorAll(Jf))a.build();for(const a of this.shadow.querySelectorAll(Ym))a.build();for(const a of this.shadow.querySelectorAll(hp))a.build();for(const a of this.shadow.querySelectorAll(tm))a.build();this.sceneElement=document.createElement(Km),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",a=>{this.ufoElement.sighting.observerMap=a.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",a=>{const{lat:o,lng:l}=a.detail;this.latInput.value=String(Number(o.toFixed(6))),this.lngInput.value=String(Number(l.toFixed(6))),this.updateObserver()}),this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.shapeRotationInput=this.shadow.getElementById("shapeRotation"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextDuplicateButton=this.shadow.getElementById("context-duplicate"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewAccountButton=this.shadow.getElementById("context-view-account"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.previousMarkButton=this.shadow.getElementById("previous-mark"),this.nextMarkButton=this.shadow.getElementById("next-mark"),this.timelineMarks=new Qd(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const a of[this.timeStartLabel,this.timeEndLabel])a.addEventListener("click",()=>this.switchTimeDisplay()),a.addEventListener("keydown",o=>{o.key!=="Enter"&&o.key!==" "||(o.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.accountCompareInput=this.shadow.getElementById("account-compare"),this.durationElement=this.shadow.querySelector(Ym),this.durationInput=this.durationElement.input,this.exportButton=this.shadow.getElementById("export"),this.saveButton=this.shadow.getElementById("save"),this.shareButton=this.shadow.getElementById("share"),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.sectionFolds=new IE(this.shadow);const t=this;this.witnessErrorView=new e2({get sighting(){return t.ufoElement.sighting},messages:()=>this.messages.witnessError,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:a=>{const o=this.ufoElement.sighting,{conditions:l,...h}=o.account??{},d={...h,...a?{conditions:a}:{}};o.account=Object.values(d).some(u=>u!==void 0)?d:void 0},recordingJson:()=>this.sightingData,lawsChanged:()=>{this.sceneElement.confrontationTolerance=Fi.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new h0(this.shadow.getElementById("timeline-tracks"),a=>this.goToMark(a),this.messages),this.tracksToggle=this.shadow.getElementById("toggle-tracks"),this.tracksToggle.addEventListener("click",()=>this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")!=="true")),this.resizeScene(this.shadow.getElementById("scene-resize")),this.shadow.querySelector(".scene-card").addEventListener("pointerdown",a=>{a.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new s2(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",a=>{const o=a.target.id;_e.SCENE_LINKED.includes(o)&&this.setActiveSceneField(o)}),this.shadow.addEventListener("focusout",a=>{const o=a.relatedTarget;(!o||!_e.SCENE_LINKED.includes(o.id))&&this.setActiveSceneField(void 0)}),this.shadow.addEventListener("input",()=>this.refreshSceneField()),this.importInput=this.shadow.getElementById("import"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeRememberInput=this.shadow.getElementById("narrativeRemember"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lensGlassSelect=this.shadow.getElementById("lens-glass"),this.isoInput=this.shadow.getElementById("iso"),this.meteringSelect=this.shadow.getElementById("metering"),this.lensDropsInput=this.shadow.getElementById("lens-drops"),this.lensCondensationInput=this.shadow.getElementById("lens-condensation"),this.lensDirtInput=this.shadow.getElementById("lens-dirt"),this.lensShelteredInput=this.shadow.getElementById("lens-sheltered"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.evaluationFields=new cs(this.shadow.getElementById("profile-section"),this.shadow.getElementById("testimony-section"),this.shadow.getElementById("strangeness-section"),()=>this.updateObserverMetadata()),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.rareIceCrystalsInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${tm}[name="observer"]`),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),this.labelRoll=this.shadow.getElementById("label-roll"),this.labelSway=this.shadow.getElementById("label-sway"),this.labelLightPollution=this.shadow.getElementById("label-light-pollution"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelObserverId=this.shadow.getElementById("label-observer-id"),this.labelObserverTitle=this.shadow.getElementById("label-observer-title"),this.labelObserverLastName=this.shadow.getElementById("label-observer-last-name"),this.labelObserverFirstNames=this.shadow.getElementById("label-observer-first-names"),this.labelObserverAge=this.shadow.getElementById("label-observer-age"),this.labelObserverBirth=this.shadow.getElementById("label-observer-birth"),this.labelObserverOccupation=this.shadow.getElementById("label-observer-occupation"),this.labelAccountSource=this.shadow.getElementById("label-account-source"),this.labelAccountFollowedUp=this.shadow.getElementById("label-account-followed-up"),this.labelSightingId=this.shadow.getElementById("label-sighting-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.wholeKeyframesInput=this.shadow.getElementById("whole-keyframes");try{this.wholeKeyframesInput.checked=localStorage.getItem(_e.WHOLE_KEYFRAMES_STORAGE)==="true"}catch{}this.wholeKeyframesInput.addEventListener("change",()=>this.setKeyframesWritten()),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),this.labelNarrativeRemember=this.shadow.getElementById("label-narrative-remember"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelFileGroup=this.shadow.getElementById("label-file-group"),this.fileEditorHost=this.shadow.getElementById("file-editor"),this.fileNote=this.shadow.getElementById("file-note"),this.frozenPanel=new ss(this.shadow.getElementById("frozen-data"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,sources:()=>this.freezerSources(),upperAirHeard:()=>this.sceneElement.upperAirHeard,changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleFileSync(),this.refreshFileItems()},base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,o)=>this.download(a,o)}),this.sectionFilePanel=new jm(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,o)=>this.download(a,o),changed:a=>{if(this.touch(),this.ufoElement.refresh(),a==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),a==="place"&&this.syncPlaceNameField(),a==="lightPollution"){const o=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=o===void 0?"":String(o),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}}),this.sectionFilePanel.localize(this.messages);const i={sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.refreshTimelineMarks(),this.scheduleFileSync(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render()},seek:a=>this.goToMark(a),now:()=>this.ufoElement.currentTime,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const a=this.ufoElement.sighting.timeline;return a.sourceIds.includes(this.currentSourceId)?a.topOf(this.currentSourceId):void 0},shapesLabel:a=>this.shapesLabel(a),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:a=>this.naming.point(a),lookedAt:()=>{const a=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return a?.headingDeg===void 0||a.pitchDeg===void 0?void 0:{azimuthDeg:a.headingDeg,altitudeDeg:a.pitchDeg}},bodyLabel:a=>{const o=this.ufoElement.sighting.interpretation?.bodies.find(l=>l.id===a);return this.said.read(o?.title)??a}};this.eventsPanel=new Pa(this.shadow.getElementById("events-section"),i,this.messages.events),this.phenomenonEventsPanel=new Pa(this.shadow.getElementById("phenomenon-events-section"),i,this.messages.events,"phenomenon"),this.bodiesEventsPanel=new Pa(this.shadow.getElementById("bodies-events-section"),i,this.messages.events,"bodies"),this.samplingRateInput.addEventListener("change",()=>{const a=Number(this.samplingRateInput.value);i.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(a)&&a>0?a:void 0,lt.refresh(this.ufoElement.sighting),i.changed()}),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.frozenPanel.localize(this.messages),this.refreshFileItems(),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",a=>{a.preventDefault(),this.keepReadingWeather()}),this.shadow.getElementById("file-ask-stop").addEventListener("click",()=>this.stopReadingWeather()),this.shadow.getElementById("file-ask-keep").addEventListener("click",()=>this.keepReadingWeather()),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelObserverGroup=this.shadow.getElementById("label-observer-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelRareIce=this.shadow.getElementById("label-rare-ice"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelShapesSubgroup=this.shadow.getElementById("label-shapes-subgroup"),this.labelBodiesSubgroup=this.shadow.getElementById("label-bodies-subgroup"),this.labelLaunchesSubgroup=this.shadow.getElementById("label-launches-subgroup"),this.labelBeamsSubgroup=this.shadow.getElementById("label-beams-subgroup"),this.labelLanternsSubgroup=this.shadow.getElementById("label-lanterns-subgroup"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.weatherProviderSelect=this.shadow.getElementById("weatherSource"),this.weatherFileLink=this.shadow.getElementById("weather-file-link"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorList=new wn({header:this.shadow.getElementById("decor-list-header"),body:this.shadow.getElementById("decor-item"),ids:{list:"decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind:a=>`option-decor-${a}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectDecor(a),onAdd:a=>this.addDecor(a),onRemove:()=>this.deleteDecor()}),this.decorList.setKinds([{value:"building",label:"Building"},{value:"tree",label:"Tree"},{value:"shrub",label:"Shrub"},{value:"bridge",label:"Bridge"},{value:"wire",label:"Overhead line"},{value:"crop",label:"Crop row"},{value:"terrace",label:"Terrace (restanque)"},{value:"mound",label:"Stone heap"},{value:"wall",label:"Dry-stone wall"},{value:"streetlight",label:"Streetlight"},{value:"trafficlight",label:"Traffic light"},{value:"crossing",label:"Pedestrian crossing"},{value:"roadsign",label:"Road sign"},{value:"vehicle",label:"Vehicle"},{value:"aircraft",label:"Aircraft"},{value:"entity",label:"Being"},{value:"observer",label:"Other observer",hidden:!0}]),this.decorList.setLabels({list:"Environment",remove:"Delete decor",add:"Add",empty:"No decor",actions:{"look-at-decor":"Look at it"}}),this.observerList=new wn({header:this.shadow.getElementById("observer-list-header"),body:this.shadow.getElementById("observer-item"),ids:{list:"observer-pick",remove:"delete-observer",add:"add-decor-observer"},actions:[{id:"look-at-observer",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectObserver(a),onAdd:()=>this.addDecor("observer"),onRemove:()=>this.deleteDecor()}),this.observerList.setLabels({list:"Observer",remove:"Delete observer",add:"Add observer",actions:{"look-at-observer":"Look at it"}}),this.sceneryStatus=this.shadow.getElementById("scenery-status"),this.sceneryWarning=this.shadow.getElementById("scenery-warning"),this.scenerySource=this.shadow.getElementById("scenery-source"),this.labelScenerySource=this.shadow.getElementById("label-scenery-source"),this.sceneryRadius=this.shadow.getElementById("scenery-radius"),this.labelSceneryRadius=this.shadow.getElementById("label-scenery-radius"),this.sceneryRadius.value=this.readSceneryRadius(),this.surroundings=new Zs(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:a=>this.setPlantedDecor(a),kindName:a=>this.decorList.kindLabel(a),cite:a=>this.citeSource(a),busy:(a,o)=>this.sceneElement.setBusy(a,o),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(a=>({lat:a.pose.lat,lng:a.pose.lng})).filter(a=>typeof a.lat=="number"&&typeof a.lng=="number")},gl,async(a,o)=>this.surroundingsProvider?this.surroundingsProvider.covers(a,o)?this.surroundingsProvider:void 0:(await oe(async()=>{const{SurroundingsSources:l}=await import("./surroundingsSources-Bq5A0HA5.js");return{SurroundingsSources:l}},[],import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,a,o),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-file-link").addEventListener("click",()=>this.openFileItem("decor")),this.scenerySource.addEventListener("change",()=>{const a=this.scenerySource.value===_e.FILE_SOURCE;if(this.setDecorFromFile(a),a){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===_e.NO_SCENERY){this.surroundings.withdraw();return}const o=this.plantingCentre();o&&this.surroundings.survey(o.lat,o.lng)}),this.sceneryRadius.addEventListener("input",()=>{const a=Number(this.sceneryRadius.value);if(!Number.isFinite(a)||a<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const o=this.plantingCentre();this.surroundings.radiusChanged(a,o?.lat,o?.lng)}),this.fillScenerySources(),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSourceInput=this.shadow.getElementById("reference-source"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.referenceFailure=this.shadow.getElementById("reference-failure"),this.addReferenceButton=this.shadow.getElementById("add-reference"),this.referenceAddMenu=new Zf(this.addReferenceButton,"reference-add-kind",a=>this.addReferenceOfKind(a),a=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[a]??`reference-add-${a}`),this.setReferenceAddKinds("From an address","From a file","Street-level pictures nearby"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.findGhostsButton=this.shadow.getElementById("reference-find-ghosts"),this.ghostsStatus=this.shadow.getElementById("reference-ghosts-status"),this.findGhostsButton.addEventListener("click",()=>void this.findGhosts()),this.ghostsShownButton=this.shadow.getElementById("reference-ghosts-shown"),this.ghostsShownButton.addEventListener("click",()=>{this.ghostsShown=!this.ghostsShown,this.syncGhostsShown(),this.ufoElement.refresh()}),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.traceImportInput=this.shadow.getElementById("trace-import"),this.traceSelect=this.shadow.getElementById("trace"),this.deleteTraceButton=this.shadow.getElementById("delete-trace"),this.traceTitleInput=this.shadow.getElementById("traceTitle"),this.traceSourceInput=this.shadow.getElementById("traceSource"),this.traceStatus=this.shadow.getElementById("trace-status"),this.labelTraceImport=this.shadow.getElementById("label-trace-import"),this.addTraceButton=this.shadow.getElementById("add-trace"),this.labelTraceTitle=this.shadow.getElementById("label-trace-title"),this.labelTraceSource=this.shadow.getElementById("label-trace-source"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.goToMilestoneButton=this.shadow.getElementById("go-to-milestone"),this.modelPicker=new yu(this.shadow,()=>({title:this.messages.modelPickerTitle,close:this.messages.modelPickerClose,choose:this.messages.modelPickerChoose,address:this.messages.decorModelAdvanced,addressUrl:this.messages.decorModelUrl,addressName:this.messages.decorModelTitle,addressAuthor:this.messages.decorModelAuthor,addressLicense:this.messages.decorModelLicense,addressSource:this.messages.decorModelSource,addressUse:this.messages.modelPickerUse,addressIncomplete:this.messages.modelPickerIncomplete})),this.decorParametersHost=this.shadow.getElementById("decor-parameters"),this.decorParameterForm=new ea(this.decorParametersHost,"en","decorParam.");const s={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new ea(this.decorBaseHost,"en","decorBase.",s,(a,o)=>this.enhanceDecorModelChoice(a,o)),this.decorStateForm=new ea(this.decorStateHost,"en","decorState.",s),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{this.focus({preventScroll:!0}),this.onPointerDown(a)}),this.ufoElement.canvasElement.addEventListener("pointermove",a=>this.onPointerMove(a));let n;this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{n={x:a.clientX,y:a.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",a=>{const o=n;n=void 0,!(!o?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(a.clientX-o.x,a.clientY-o.y)>_e.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",a=>this.onContextMenu(a)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextDuplicateButton.addEventListener("click",()=>this.duplicateSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.saveButton.addEventListener("click",()=>this.exportJson()),this.shareButton.addEventListener("click",()=>this.openShare()),this.importInput.addEventListener("filepick",a=>{const o=a.detail;o.file?this.importFromFile(o.file):this.importFromUrl(o.url)}),this.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()});for(const a of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])a.addEventListener(a instanceof HTMLSelectElement||a.type==="checkbox"?"change":"input",()=>this.updateLens());this.lightPollutionInput.addEventListener("input",()=>{const a=this.ufoElement.sighting;a.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),a.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),a.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",a=>{const{seconds:o,text:l}=a.detail;this.ufoElement.sighting.event.durationText=l,this.ufoElement.durationSeconds=o,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((o??0)*1e3),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.shapeRotationInput.addEventListener("input",()=>this.updateShapeRotation()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const a of this.referenceFields)a.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceSourceInput.addEventListener("filepick",a=>void this.setReferenceSource(a.detail)),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.addTraceButton.addEventListener("click",()=>{const a=this.shadow.getElementById("trace-import-row");a.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",a=>void this.addTraces(a.detail)),this.traceSelect.addEventListener("change",()=>this.selectTrace(this.traceSelect.value)),this.deleteTraceButton.addEventListener("click",()=>this.deleteTrace()),this.traceTitleInput.addEventListener("input",()=>this.writeTraceFields()),this.traceSourceInput.addEventListener("input",()=>this.writeTraceFields()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",a=>this.onReferenceWheel(a),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",a=>this.onBodyWheel(a),{passive:!1}),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.goToMilestoneButton.addEventListener("click",()=>{this.currentMilestoneT!==void 0&&this.goToMark(this.currentMilestoneT)}),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const a of[this.milestoneLabelInput,this.milestoneNoteInput])a.addEventListener("input",()=>this.updateMilestone());this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showNovaButton.addEventListener("click",()=>this.lookAtNova()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.showFireballButton.addEventListener("click",()=>this.showNextFireball()),this.sceneElement.addEventListener(ZA,()=>{const a=this.currentReference();a&&this.syncReferenceStatus(a)}),this.sceneElement.addEventListener(jA,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(qA,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown),this.shapeAddMenu=new Zf(this.addShapeButton,"add-shape-kind",a=>{const o=ao.byId(a);if(o){this.addModel(o);return}this.currentAppearance={...this.currentAppearance,presetId:a},this.addShape()},a=>`add-shape-${a}`),this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const a of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])a.addEventListener("input",()=>this.updateObserver());for(const a of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])a.addEventListener("input",()=>this.updateObserver());this.isoInput.addEventListener("input",()=>this.updateExposureSettings()),this.meteringSelect.addEventListener("change",()=>this.updateExposureSettings()),this.observerPosition.addEventListener("positionchange",a=>{if(this.observerSaid=a.detail.said,!this.observerPosition.relative)return;const o=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(o,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",a=>this.writeObserverBasis(a.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",a=>{a.key==="Enter"&&(a.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 a=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const o=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(l=>[l.t,Si.fovOf(this.ufoElement.sighting,l.t)]));this.retuneFieldOfView(a),this.retuneExposure(a),Si.reproject(this.ufoElement.sighting,a,o),this.sceneElement.applyFrameFormat(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.accountCompareInput.addEventListener("change",()=>this.syncBodiesShown()),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const r=a=>this.shadow.querySelector(`${Jf}[name="${a}"]`);this.startDate=r("obs-time"),this.endDate=r("obs-end-time"),this.birthDate=r("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=mc.ALL,this.perceptionSettings.labels=this.messages.observerPerception,this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata()),this.startDate.messages=this.messages,this.endDate.messages=this.messages,this.birthDate.messages=this.messages;for(const a of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(a,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",a=>{const{time:o}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=o}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",a=>{this.birth=a.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",a=>{const{time:o}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=o})});for(const a of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])a.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(_e.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const a of this.weatherFields){if(a===this.iceCrystalAlignmentInput||a===this.rareIceCrystalsInput){a.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}a.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const a of this.soundFields)a.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.weatherProviderSelect.addEventListener("change",()=>this.onWeatherProviderChosen()),this.weatherFileLink.addEventListener("click",()=>this.openFileItem("weather")),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(a=>this.shadow.getElementById(a.getAttribute("aria-controls")));for(const a of this.groupTabs)a.addEventListener("click",()=>this.toggleGroup(a,!this.isGroupOpen(a)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const a of this.subgroupTabs)a.addEventListener("click",()=>this.openSubgroup(a));en.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new oo(this.messages,this.naming,this.said,this.tagNames,{messages:this.messages,locale:this.language}),this.paramSummary.addEventListener("click",a=>this.onParamSummaryClick(a)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(a=>a.id==="group-shape")],!0),this.sectionChosen=!1,this.opensMostLacking=!0,this.attachWitnessErrors(),this.labelPanels(this.messages),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),this.setRecordButtonLabel(!1),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=lI(this.shadow.getElementById("cloud-editor"),this.sceneElement,(a=!0)=>{a&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(a,o)=>{this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()},$u(Sr.preferencesFor(this),Wu),this.framePlace()),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),Sr.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages(),this.shadow.addEventListener("pointerdown",this.armHistory,!0),this.shadow.addEventListener("keydown",this.armHistory,!0);for(const t of["input","change","click","keyup","pointerup"])this.shadow.addEventListener(t,this.scheduleHistoryRecord,!0);this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),this.shadow.removeEventListener("pointerdown",this.armHistory,!0),this.shadow.removeEventListener("keydown",this.armHistory,!0);for(const e of["input","change","click","keyup","pointerup"])this.shadow.removeEventListener(e,this.scheduleHistoryRecord,!0);clearTimeout(this.historyTimer),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag(),queueMicrotask(()=>{this.isConnected||this.releaseFileEditor()})}releaseFileEditor(){this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileEditorLoading=void 0}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){const t=Ui.toCurrent(e);this.sourceUrl=void 0,this.endDrag(),this.ufoElement.sightingData=t,this.sceneElement.applyFrameFormat(),this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.isGroupIdOpen("group-shape")&&this.showPhenomenonPartWithContent(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??Wd,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncObserverMetadataFields(),this.offsetIsAuthors=!1,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField();const i=this.plantingCentre();this.surroundings.placeLoaded(i?.lat,i?.lng),this.syncSceneryPicker(),this.syncWeatherOwnership(),this.frozenPanel.render(),this.refreshFileItems(),this.markClean(),this.sectionChosen||(this.opensMostLacking=!0)}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&this.fileText()!==this.baseline}get edited(){return this.touched}markClean(){this.applyingFileText||(this.baseline=this.fileText(),this.touched=!1,this.savedFileText=this.baseline,this.fileEditor?.markSaved(),this.refreshEditorHead())}set embedded(e){this.shadow.getElementById("editor-head").hidden=e,this.shadow.querySelector(".app").classList.toggle("embedded",e),e||this.shadow.querySelector("#editor-head .head-actions").prepend(this.historyControls)}get historyControls(){return this.undoButton.parentElement}refreshEditorHead(){this.saveButton&&(this.refreshEditorTitle(),this.saveButton.disabled=!this.dirty,this.shareButton.disabled=this.sourceUrl===void 0,this.shareButton.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"")}sourceUrl;shareButton;shareDialog;shareMessages;shareSubject={module:"rr0-sighting-editor",link:()=>`${ed.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}`,element:()=>`<rr0-sighting-editor src="${this.sourceUrl??""}"></rr0-sighting-editor>`};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}refreshEditorTitle(){const e=this.ufoElement.sighting.event,t=e.place?.[0]?.name?.split(",")[0].trim(),i=e.time;let s="";i?.year!==void 0&&(s=i.month!==void 0&&i.day!==void 0?new Date(Date.UTC(i.year,i.month-1,i.day)).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"}):String(i.year));const n=[t,s].filter(Boolean).join(", ")||this.sightingIdInput.value||this.messages.stateNew,r=this.shadow.getElementById("editor-title");r.textContent!==n&&(r.textContent=n)}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.historySnapshot!==void 0&&(clearTimeout(this.historyTimer),this.historyTimer=setTimeout(()=>this.recordHistory(),350))};recordHistory(){this.historyTimer=void 0;const e=this.fileEditor;if(e===void 0||this.historySnapshot===void 0)return;const t=this.fileText();t!==this.historySnapshot&&(this.historySnapshot=t,this.historyAnswering=!1,e.replaceText(t,this.fileSyncActive()),this.fileTextApplied=e.text,this.syncHistoryButtons(),this.refreshEditorHead())}undo(){this.stepHistory(e=>e.undo(this.fileSyncActive()))}redo(){this.stepHistory(e=>e.redo(this.fileSyncActive()))}stepHistory(e){this.historyTimer!==void 0&&(clearTimeout(this.historyTimer),this.recordHistory());const t=this.fileEditor;t===void 0||this.isRecording||this.ufoElement.playbackState==="playing"||e(t)&&(clearTimeout(this.fileApplyTimer),this.applyFileText(t.text,!0),this.historyAnswering=!0,this.syncHistoryButtons(),this.refreshEditorHead())}syncHistoryButtons(){this.undoButton.disabled=!(this.fileEditor?.canUndo??!1),this.redoButton.disabled=!(this.fileEditor?.canRedo??!1)}resetHistory(){clearTimeout(this.historyTimer),this.historyTimer=void 0,this.historySnapshot=void 0,this.historyAnswering=!1,this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileTextApplied=void 0,this.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>{})}touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=this.shadow.getElementById("save-refused"),t=Ht.issues(this.ufoElement.sighting);if(Xt.show(e,t.length===0?void 0:this.messages.saveRefused.replace("{reasons}",t.map(s=>this.actorIssue(s)).join(" ; ")),"error"),t.length>0)return;const i=es.inspect(this.sightingData,this.loadedJson());if(i.length===0){this.downloadJson();return}this.askAboutIdentity(i)}actorIssue(e){const t=this.messages;if(e.kind==="duplicate-id")return t.duplicateId.replace("{id}",e.id).replace("{kinds}",e.path.split(", ").map(n=>t.actorKinds[n]??n).join(", "));const i=Number(e.path.split(".")[1]),s=this.ufoElement.sighting.events?.[i];return t.unknownWho.replace("{n}",String(i+1)).replace("{kind}",(s&&t.events.kinds[s.eventType])??s?.eventType??"").replace("{id}",e.id)}loadedJson(){try{return this.baseline?JSON.parse(this.baseline):void 0}catch{return}}askAboutIdentity(e){const t={lastName:this.messages.identityLastName,firstNames:this.messages.identityFirstNames,nameInId:this.messages.identityNameInId,nameInText:this.messages.identityNameInText,address:this.messages.identityAddress,email:this.messages.identityEmail,phone:this.messages.identityPhone};this.shadow.getElementById("identity-ask-text").textContent=this.messages.identityAsk,this.shadow.getElementById("identity-ask-found").replaceChildren(...e.map(n=>{const r=document.createElement("li");return r.textContent=t[n.kind].replaceAll("{value}",n.found),r}));const s=e.some(n=>["lastName","firstNames","nameInId","nameInText"].includes(n.kind));this.shadow.getElementById("identity-ask-initials").hidden=!s,typeof this.identityAsk.showModal=="function"?this.identityAsk.showModal():this.identityAsk.setAttribute("open","")}closeIdentityAsk(){typeof this.identityAsk.close=="function"?this.identityAsk.close():this.identityAsk.removeAttribute("open")}writeNamesAsInitials(){const e=es.namesOf(this.sightingData);this.observerLastNameInput.value=es.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>es.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=es.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=es.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=es.withInitials(this.descriptionInput.value,e),this.touch(),this.updateObserverMetadata(),this.descriptionInput.dispatchEvent(new Event("input"))}async downloadJson(){const e=this.fileBase();let t=new Map;if(this.frozenPanel.hasWork()){this.exportButton.disabled=!0;try{t=await this.frozenPanel.prepare(e)}finally{this.exportButton.disabled=!1}}const i=this.sightingData;for(const r of Ns.NAMES){const a=this.sectionFilePanel.annex(r);if(a){/^[a-z][a-z0-9+.-]*:/i.test(a.src)||t.set(a.src,a.bytes);for(const o of Ns.KEYS[r])delete i[o]}}const s=`${e}.json`,n=this.writtenText(i);if(t.size===0)this.download(new Blob([n],{type:"application/json"}),s);else{const{zipSync:r,strToU8:a}=await oe(async()=>{const{zipSync:h,strToU8:d}=await import("./browser-_Ncw3Jhn.js");return{zipSync:h,strToU8:d}},[],import.meta.url),o={[s]:a(n)};for(const[h,d]of t)o[h]=d;const l=r(o,{level:0});this.download(new Blob([l],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.frozenExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",ss.size(l.length)))}this.markClean()}fileBase(){const e=this.sceneElement.documentUrl?.split(/[?#]/)[0].split("/").pop();return e?.endsWith(".json")&&e.length>5?decodeURIComponent(e.slice(0,-5)):`${this.sightingData.observer?.id??"sighting"}-sighting`}refreshFileItems(){const e=this.fileItemSelect;if(!e)return;this.syncFilePickers();const t=e.value||"recording";e.replaceChildren(new Option(this.messages.fileItemRecording,"recording"),...Ns.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...ts.NAMES.map(i=>new Option(this.frozenPanel.itemLabel(i),i))),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=ts.NAMES.includes(e),i=Ns.NAMES.includes(e)?e:void 0;this.shadow.getElementById("file-recording").hidden=t||i!==void 0,this.shadow.getElementById("frozen-data").hidden=!t,this.shadow.getElementById("file-section").hidden=i===void 0;for(const n of["file-recording","frozen-data","file-section"]){const r=this.shadow.getElementById(n);r.hidden||wn.glue(r)}t&&this.frozenPanel.show(e),i&&this.sectionFilePanel.show(i);const s=t&&this.frozenPanel.isInlineGroup(e)?["frozen",e,"src"]:i&&this.sectionFilePanel.isInline(i)?jm.pathOf(i):void 0;this.fileEditorHost.hidden=(t||i!==void 0)&&s===void 0,s&&this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(n=>{this.syncFileEditor(!1),n.reveal(s)},()=>{})}sectionFromFile(e){return Ns.fromFile(this.ufoElement.sighting.frozen,e)}masterUrl(){return this.sceneElement.documentUrl??new URL(`${this.fileBase()}.json`,location.href).href}weatherFileItemLabel(){return this.sectionFilePanel?.itemLabel("weather")??""}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}freezerSources(){const e=ds(Ef,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:ds(fc,this.chosenSourceId.get("imagery")).id,roads:_2(),water:D2(),railways:R2()}}async importFromFile(e){this.holdLoad(()=>void this.loadFile(e))||await this.loadFile(e)}async loadFile(e){try{const t=new Uint8Array(await new Promise((n,r)=>{const a=new FileReader;a.onload=()=>n(a.result),a.onerror=()=>r(a.error),a.readAsArrayBuffer(e)}));Ct.release();const i=await this.recordingText(t),s=JSON.parse(i);if(Hi.isCase(s)){if(Hi.check(s),this.offerCase(s,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=s,this.resetHistory(),this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importInput.url=""}catch(t){window.alert(this.importErrorFor(t))}}async recordingText(e){if(e[0]!==80||e[1]!==75)return new TextDecoder().decode(e);const{unzipSync:t,strFromU8:i}=await oe(async()=>{const{unzipSync:d,strFromU8:u}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:d,strFromU8:u}},[],import.meta.url),s=t(e),n=/\.(relief|imagery|map)\.zip$|\.(roads|water|railways|upper-air|weather)\.json$/,r=Object.keys(s).find(d=>d.endsWith(".json")&&!n.test(d));if(!r)throw new Error("No recording in this archive");const a=r.includes("/")?r.slice(0,r.lastIndexOf("/")+1):"";for(const[d,u]of Object.entries(s))d!==r&&d.startsWith(a)&&Ct.hold(Ct.address(d.slice(a.length),void 0),u);const o=i(s[r]),l=JSON.parse(o);let h=!1;for(const d of Ns.NAMES){const u=l.frozen?.[d]?.src,p=u!==void 0?s[a+u]:void 0;if(!p)continue;const f=Ui.toCurrent(JSON.parse(i(p)));for(const m of Ns.KEYS[d])f[m]!==void 0&&(l[m]=f[m]);h=!0}return h?JSON.stringify(l):o}offerCase(e,t){return!this.dispatchEvent(new CustomEvent("caseloaded",{detail:{json:e,url:t},bubbles:!0,composed:!0,cancelable:!0}))}bodyShapeIds(){return this.accountShapeIds?[...this.accountShapeIds]:this.ufoElement.sighting.timeline.sourceIds}set documentUrl(e){this.sceneElement.documentUrl=e}async importFromUrl(e=this.importInput.url){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){try{const t=await na.recording(e);if(Hi.isCase(t)){Hi.check(t);const s=new URL(e,location.href).href;if(this.offerCase(t,s)){this.importInput.url=s;return}throw new Error("A case has no recording to edit here")}const i=t;Ct.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=new URL(e,location.href).href,this.resetHistory(),this.importInput.url=new URL(e,location.href).href,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(e instanceof wu)return e.said(this.messages.formatVersionError);if(!(e instanceof Bl))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";static SCENERY_STORAGE="rr0-sighting-editor.surroundings";static SCENERY_RADIUS_STORAGE="rr0-sighting-editor.surroundings-radius";static NO_SCENERY="none";narrativeProvider=_p[0].create();get narrativeSourceId(){return ds(_p,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:_e.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof fr&&i.kind==="cancelled";this.narrativeStatus.textContent=s?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!s)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:s,...n}=i,r=i.timeZone?n:i,a=Ma.stated(r);if(a.length>0){const o=this.ufoElement.sighting.provenance,l=Yv(this.ufoElement.sighting);this.sightingData=Ma.apply(l,dm.loadable(r),a),this.ufoElement.sighting.provenance=o,this.recordNarrativeProvenance(e,a),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=a.length>0?this.messages.narrativeApplied.replace("{count}",String(a.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const i=this.ufoElement.sighting,s=new Set(t);for(const n of e.claims)!s.has(n.path)&&!t.some(r=>n.path.startsWith(`${r}.`))||i.provenance.set(n.path,{basis:n.basis,rationale:n.rationale,of:_e.valueAt(Yv(this.ufoElement.sighting),n.path)})}static valueAt(e,t){let i=e;for(const s of t.split(".")){if(typeof i!="object"||i===null)return;i=i[s]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(s=>s.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[b9[t]]));for(const s of i){const n=document.createElement("div");n.className=`claim ${t}`;const r=document.createElement("code");r.textContent=s.path;const a=document.createElement(t==="stated"?"q":"span");a.textContent=s.rationale,n.append(r,a),this.narrativeReport.append(n)}}}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 s=document.createElement("li");s.textContent=i,t.append(s)}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=ds(_p,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(s=>s.required&&(this.narrativeSettingInputs.get(s.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(s=>s.remembered==="credential");for(const s of this.narrativeProvider.settings){const n=this.narrativeSettingInputs.get(s.id);if(!n||!s.suspect)continue;const r=n.value.trim(),a=r===""?void 0:s.suspect(r);n.classList.toggle("invalid",a!==void 0),n.title=a?this.said.read(a)??"":this.said.read(s.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const s=document.createElement("label"),n=document.createElement("span");n.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const o of i.choices??[]){const l=document.createElement("option");l.value=o.value,l.textContent=this.said.read(o.label)??o.value,r.appendChild(l)}}else r=document.createElement("input"),r.type=i.kind==="secret"?"password":"text",r.autocomplete="off",r.spellcheck=!1,r.placeholder=this.said.read(i.placeholder)??"";r.id=`narrative-${i.id}`,r.title=this.said.read(i.hint)??"";const a=e[i.id]??this.storedNarrativeSetting(i.id);return a!==void 0&&(r.value=a),r.addEventListener(i.kind==="choice"?"change":"input",()=>{this.rememberNarrativeSettings(),this.syncNarrativeEnabled()}),this.narrativeSettingInputs.set(i.id,r),s.append(n,document.createTextNode(" "),r),s});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 s=i.value.trim();s!==""&&(e[t]=s)}return e}narrativeErrorFor(e){if(!(e instanceof fr))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(_e.NARRATIVE_KEY_STORAGE),localStorage.removeItem(_e.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"?_e.NARRATIVE_KEY_STORAGE:e==="workspace"?_e.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} `),_e.creditLink(ds(vv,this.chosenSourceId.get("place")))),this.weatherSourceRow.replaceChildren(),this.fillWeatherProvider(),this.sourcePickers(this.shadow.getElementById("weather-source-rows"),"weather-source-kind","weather",[["weather",this.messages.fileItemWeather,this.shadow.getElementById("weather-picker")],["upper-air",this.messages.frozenUpperAir,this.sourcePicker("upper-air",j8,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),_e.creditLink(ds(If,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",_p,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.sourcePickers(this.terrainSourceRows,"source-kind","location",[["place",this.messages.fileItemPlace,this.sourcePicker("place",vv,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",If,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",Ef,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",fc,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.frozenRoads,this.sourcePicker("roads",[_e.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.frozenWater,this.sourcePicker("water",[_e.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.frozenRailways,this.sourcePicker("railways",[_e.LIVE_RAILWAYS],()=>{},this.groupChoice(["railways"]))]]),this.sourcePickers(this.shadow.getElementById("decor-source-rows"),"decor-source-kind","decor",[["scenery",this.messages.fileItemDecor,this.shadow.getElementById("scenery-picker")],["aircraft",this.messages.sourceAircraft,this.sourcePicker("aircraft",sy,()=>this.applyAircraftSource())],["decor-model",this.messages.decorModel,this.sourcePicker("decor-model",Kf,()=>this.applyDecorModelSource())]])}sourcePicker(e,t,i,s){const n=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;for(const d of t){const u=document.createElement("option");u.value=d.id,u.textContent=d.name,u.title=d.credit,r.appendChild(u)}s&&r.appendChild(new Option(this.messages.sourceFile,_e.FILE_SOURCE));const a=()=>this.chosenSourceId.get(e)??t[0].id;r.value=s?.fromFile()?_e.FILE_SOURCE:a();const o=document.createElement("a");o.className="source-credit",o.target="_blank",o.rel="noopener noreferrer";const l=document.createElement("button");l.type="button",l.className="link source-file-link",l.addEventListener("click",()=>this.openFileItem(s.item));const h=()=>{const d=r.value===_e.FILE_SOURCE,u=ds(t,d?a():r.value);r.title=d?s.where():u.credit,o.hidden=d,o.href=u.creditUrl,o.textContent=u.credit,l.hidden=!d,d&&(l.textContent=s.label(),l.title=s.where())};return h(),r.addEventListener("change",()=>{const d=r.value===_e.FILE_SOURCE;d||this.chosenSourceId.set(e,r.value),s?.setFromFile(d),h(),d||i(ds(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?_e.FILE_SOURCE:a(),h()}),n.append(r,document.createTextNode(" "),o,l),n}groupChoice(e){return{item:e[0],fromFile:()=>!this.frozenPanel.isLive(e[0]),setFromFile:t=>{for(const i of e)this.frozenPanel.setLive(i,!t)},label:()=>this.frozenPanel.itemLabel(e[0]),where:()=>this.frozenPanel.where(e[0])}}sectionChoice(e,t){return{item:e,fromFile:()=>this.sectionFromFile(e),setFromFile:i=>{const s={...this.ufoElement.sighting.frozen??{}};i?s[e]=s[e]??{}:delete s[e],this.ufoElement.sighting.frozen=ts.isEmpty(s)?void 0:s,this.touch(),this.scheduleFileSync(),this.refreshFileItems(),i||t()},label:()=>this.sectionFilePanel.itemLabel(e),where:()=>this.sectionFilePanel.where(e)}}static FILE_SOURCE="file";filePickers=new Map;syncFilePickers(){for(const e of this.filePickers.values())e()}openFileItem(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-file");t&&this.toggleGroup(t,!0),this.fileItemSelect.value=e,this.showFileItem(e)}static LIVE_ROADS={id:"ign-osm",name:"IGN BD TOPO / OpenStreetMap",credit:"© IGN, BD TOPO (Licence Ouverte 2.0) in France; © OpenStreetMap contributors (ODbL) elsewhere",creditUrl:"https://www.openstreetmap.org/copyright",create:()=>{}};static LIVE_WATER=_e.LIVE_ROADS;static LIVE_RAILWAYS=_e.LIVE_ROADS;sourcePickers(e,t,i,s){const n=document.createElement("label"),r=document.createElement("span");r.id=`label-${t}`,r.textContent=this.messages.sourceKind;const a=document.createElement("select");a.id=t;const o=s.map(([h,d,u])=>{a.append(new Option(d,h));const p=document.createElement("span");return p.className="source-picker",p.dataset.kind=h,p.append(u),p});a.value=this.sourceKindShown.get(i)??s[0][0];const l=()=>{this.sourceKindShown.set(i,a.value);for(const h of o)h.hidden=h.dataset.kind!==a.value};a.addEventListener("change",l),l(),n.append(r,document.createTextNode(" "),a),e.replaceChildren(n,...o)}sourceKindShown=new Map;static creditLink(e){const t=document.createElement("a");return t.className="source-credit",t.target="_blank",t.rel="noopener noreferrer",t.href=e.creditUrl,t.textContent=e.credit,t}refreshSourceCredits(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),_e.creditLink(ds(vv,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),_e.creditLink(ds(If,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:ds(Ef,this.chosenSourceId.get("elevation")).create(),imagery:ds(fc,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(ds(sy,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=ds(Kf,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.decorModelEntries=void 0,this.refreshDecorModelOptions(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId)),this.ufoElement.refresh()}get placeSearchLanguage(){return navigator.languages?.[0]}set placeSearchProvider(e){this.placeProvider=e}async searchPlace(){const e=this.placeNameInput.value.trim();if(e===""||this.sectionFromFile("place"))return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let i;try{i=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=i,this.refreshPlaceMatches(),i.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const i=document.createElement("option");return i.textContent=t.name,i.title=t.name,i})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates||this.sectionFromFile("place"))return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||Math.abs(e-this.namedCoordinates.lat)<nh&&Math.abs(t-this.namedCoordinates.lng)<nh||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),iE))}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)<nh&&Math.abs(t-i.lng)<nh||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),iE))}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 s;try{s=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}if(i!==this.placeSearchToken)return;this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=s?.name??"",this.placeNameInput.title=s?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=s?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!s;const n=this.ufoElement.sighting.event.place?.[0]??{lat:e,lng:t};this.ufoElement.sighting.event.place=[{lat:n.lat,lng:n.lng,name:this.stringOrUndefined(this.placeNameInput.value.trim())}]}updateObserver(){if(this.refreshHeadingPoint(),this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),i=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),s=this.numberOrUndefined(this.pitchInput.value)??0,n=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,a=Math.max(0,r-(this.groundElevationM??0)),o=this.ufoElement.sighting.event,l=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());o.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),f=(u.frame&&p!==void 0?Qt.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),m=this.numberOrUndefined(this.fNumberInput.value),v=this.filterSelect.value,g=Xi.byId(l.getLatestPoseAt(h-1)?.filter),b=v===Xi.NONE.id||v===""?g===Xi.NONE?void 0:Xi.NONE.id:v,w=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=w===u.exposureSeconds?void 0:w;const y=this.numberOrUndefined(this.focusDistanceInput.value),M=Math.abs(f-Qt.fieldOfViewDeg(u))>.01||m!==u.fNumber||y!==void 0||b!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&a===0&&!M?l.removeKeyframeAt(h):l.addKeyframe(h,{lat:e,lng:t,elevationM:a,headingDeg:i,pitchDeg:s,rollDeg:n===0?void 0:n,...this.observerSaid&&e!==void 0?{saidPosition:this.observerSaid}:{},fovDeg:f,fNumber:m,focusDistanceM:y,filter:b});const E=this.plantingCentre();this.surroundings.placeChanged(E?.lat,E?.lng),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}syncAgeFromBirth(e){const t=this.birth,i=this.ufoElement.sighting.event.time;if(!t||!i||e&&!Tf.isFirm(t))return;const s=Tf.at(t,i);s!==void 0&&(this.observerAgeInput.value=String(s),this.updateObserverMetadata())}syncBirthFromAge(){const e=this.ufoElement.sighting.event.time,t=this.numberOrUndefined(this.observerAgeInput.value);if(!e||t===void 0)return;const i=this.birth;if(i&&Tf.at(i,e)===t)return;const s=Tf.birthFor(t,e);s&&(this.birthDate.setPrecise(!1),this.birth=s,this.birthDate.time=s,this.updateObserverMetadata())}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.refreshSceneryWarning(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&Qh({...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(s=>{const n=document.createElement("option");return n.value=s,n.textContent=s,n})),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 s=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return s&&t.includes(s)?s:t[0]}updateUtcOffset(){const e=this.ufoElement.sighting.event,t=this.numberOrUndefined(this.utcOffsetInput.value);if(t===void 0)e.utcOffsetHours=void 0,e.timeZone=void 0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value="";else{const i=this.preferredZoneFor(t);if(i===void 0){this.utcOffsetInput.classList.add("invalid"),this.utcOffsetInput.title=this.messages.utcOffsetNoZone;return}e.utcOffsetHours=t,e.timeZone=i,this.offsetIsAuthors=!0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value=i}this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObserverMetadata(){const e=this.ufoElement.sighting,t=this.observerFirstNamesInput.value.split(",").map(n=>n.trim()).filter(n=>n.length>0),i={id:this.stringOrUndefined(this.observerIdInput.value),title:this.observerTitleInput.value.trim()===""?void 0:this.said.write(e.observer?.title,this.observerTitleInput.value.trim(),this.writingLanguage),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0},s=Ht.observerId(e);e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,Ht.renamed(e,s,Ht.observerId(e)),e.id=this.stringOrUndefined(this.sightingIdInput.value),this.updateAccount(),this.ufoElement.refresh()}updateAccount(){const e=this.ufoElement.sighting,t=this.accountFollowedUpSelect.value,i={observerAgeYears:this.numberOrUndefined(this.observerAgeInput.value),observerBirth:this.birth,observerPerception:mc.compact(this.perceptionSettings.values),observerOccupation:this.observerOccupationInput.value.trim()===""?void 0:this.said.write(e.account?.observerOccupation,this.observerOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.accountSourceSelect.value),followedUp:t===""?void 0:t==="yes",...this.evaluationFields.values(),conditions:e.account?.conditions};e.account=Object.values(i).some(s=>s!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...s]=e.sources??[],{url:n,...r}=i??{},a=t===""?r:{...r,url:t},o=Object.keys(a).length>0?[a,...s]:s;e.sources=o.length>0?o:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState()):this.ufoElement.sighting.weatherSource!==void 0&&(this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...fs(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={...fs(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value),rareIceCrystals:Number(this.rareIceCrystalsInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(s=>s.id===this.currentReferenceId),t=e!==void 0;wn.showPresence(this.shadow.getElementById("reference-row"),this.shadow.getElementById("reference-item"),t),this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const s of[this.referenceSelect,...this.referenceFields])s.disabled=!t;if(this.referenceSourceInput.disabled=!t,this.refreshLandmarkList(),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSourceInput.url=i?"":e.src,this.referenceSourceInput.mode=i?"file":"url",this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.ghostFinding&&(this.ghostFinding.referenceId!==e.id||this.ghostFinding.src!==e.src)&&(this.ghostFinding=void 0,this.ghostsStatus.textContent="",this.syncGhostsShown(),this.ufoElement.refresh()),this.referenceOpacityInput.value=String(e.opacity),this.referenceHeadingInput.value=String(e.registration.headingDeg),this.referencePitchInput.value=String(e.registration.pitchDeg),this.referenceRollInput.value=String(e.registration.rollDeg??0),this.referenceFovInput.value=String(e.registration.fovDeg),this.syncReferenceStatus(e)}syncReferenceStatus(e){const t=this.sceneElement.referenceFailure(e.src);if(Xt.show(this.referenceFailure,t?this.pictureFailureText(t):void 0,"error"),this.syncFindGhosts(e),this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const i=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>D8?this.messages.referenceEmbedded.replace("{kb}",String(i)):"";return}this.referenceStatus.textContent=""}pictureFailureText(e){switch(e.kind){case"notShared":return this.messages.referenceNotShared;case"status":return this.messages.referenceNotFound.replace("{status}",String(e.status));case"notPicture":return this.messages.referenceNotPicture;default:return this.messages.referenceUnreachable}}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,i=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(n=>{if(n.id!==this.currentReferenceId)return n;const r=n.src,a={headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||_f))},o=n.registration,l=a.headingDeg!==o.headingDeg||a.pitchDeg!==o.pitchDeg||a.rollDeg!==o.rollDeg||a.fovDeg!==o.fovDeg;return{...n,kind:this.referenceKindSelect.value,src:r,title:this.said.write(n.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:i===void 0||Number.isNaN(i)?void 0:Math.round(i*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:a,from:l?this.observerPositionNow()??n.from:n.from}});const s=e.references.find(n=>n.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(s),this.syncReferenceStatus(s),this.ufoElement.refresh()}useObserverPoseForReference(){const e=st(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=st(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 s=this.ufoElement.sighting,n=st(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${s.references.length+1}`,a={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:_8,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:_f},from:this.observerPositionNow(),...i};s.references=[...s.references,a],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSourceInput.mode="url",this.referenceSourceInput.focus()}addReferenceFromFile(){this.addReference(""),this.referenceSourceInput.mode="file",this.referenceSourceInput.openPicker()}async setReferenceSource(e){const t=this.currentReferenceId;if(t===void 0)return;let i;if(e.file){const n=e.file;i=await new Promise((r,a)=>{const o=new FileReader;o.onload=()=>r(o.result),o.onerror=()=>a(o.error),o.readAsDataURL(n)})}else i=e.url;const s=this.ufoElement.sighting;s.references=s.references.map(n=>n.id!==t?n:{...n,src:i,title:n.title??(e.file?this.said.write(void 0,e.file.name.replace(/\.[^.]+$/,""),this.writingLanguage):void 0)}),this.touch(),this.refreshReferenceList(),this.ufoElement.refresh()}pictureAspect(e){if(!this.pictureRegistration){this.loadPictureRegistration();return}return this.sceneElement.referenceAspect(e)}loadPictureRegistration(){return this.pictureRegistrationLoading??=oe(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-cp0utyhJ.js");return{PictureRegistration:e}},[],import.meta.url).then(({PictureRegistration:e})=>{this.pictureRegistration=e,this.ufoElement.refresh()})}currentReference(){return this.ufoElement.sighting.references.find(e=>e.id===this.currentReferenceId)}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const s=this.pictureAspect(t.id);if(!(s!==void 0&&this.pictureRegistration.picturePointOf(this.directionAtCanvasPoint(e),t.registration,s)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.pictureAspect(t.id):void 0;if(!t||i===void 0)return;const s=8;for(const n of this.currentLandmarks()){const r=this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(n.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=s)return{landmarkId:n.id,end:"picture"};const a=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(n.scene));if(a&&Math.hypot(a.x-e.x,a.y-e.y)<=s)return{landmarkId:n.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 s=i.x-t.startPointer.x,n=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(s,n)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+s*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-n*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const s=this.currentReference(),n=s?this.pictureAspect(s.id):void 0;if(!s||n===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(a=>{if(a.id!==e)return a;if(t==="scene")return{...a,scene:this.pictureRegistration.aimOf(r)};const o=this.pictureRegistration.picturePointOf(r,s.registration,n);return o?{...a,picture:o}:a})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||_f,i=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(i)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const i=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const r=this.pictureAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const a=this.pictureRegistration.picturePointOf(i,t.registration,r);if(!a){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=a,this.syncRegisterStatus(),this.ufoElement.refresh();return}const s=this.currentLandmarks(),n=this.nextLandmarkId(s);this.writeLandmarks([...s,{id:n,picture:this.pendingLandmark,scene:this.pictureRegistration.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=n,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(i=>i.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.pictureAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),s=this.pictureRegistration.solve(i,t,e.registration.fovDeg);s?(this.referenceFit={n:i.length,residualDeg:s.residualDeg},this.referenceHeadingInput.value=String(this.rounded(s.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(s.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(s.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(s.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return this.pictureRegistration.worldDirectionOf(e.picture,t.registration,i).angleTo(this.pictureRegistration.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const i=this.said.read(e.label);return i?`${t+1} · ${i}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),i=e?this.pictureAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[n,r]of t.entries()){const a=document.createElement("option");a.value=r.id;const o=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";a.textContent=this.landmarkLabel(r,n)+o,this.referenceLandmarksSelect.appendChild(a)}this.currentLandmarkId!==void 0&&!t.some(n=>n.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const s=t.find(n=>n.id===this.currentLandmarkId);wn.showPresence(this.shadow.getElementById("reference-landmark-row"),this.shadow.getElementById("reference-landmark-item"),t.length>0),this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=s===void 0,this.referenceLandmarkLabelInput.disabled=s===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(s?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(a=>a.id===e?{...a,label:this.said.write(a.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:a));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),s=i.findIndex(a=>a.id===e),n=this.currentReference(),r=n?this.pictureAspect(n.id):void 0;if(t&&s>=0){const a=n&&r!==void 0?` · ${this.landmarkResidualDeg(i[s],n,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[s],s)+a}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.pictureAspect(t.id);if(i===void 0)return;const{registration:s}=t,n=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(a=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a,s,i))),r=this.currentLandmarks().map((a,o)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a.picture,s,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(a.scene)),label:this.landmarkLabel(a,o),selected:a.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(a,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(this.pendingLandmark,s,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(n.every(a=>a!==void 0)?n:void 0,r.filter(a=>a.picture!==void 0),this.landmarkHint()),this.paintGhostFinding(e,t,i)};paintGhostFinding(e,t,i){const s=this.ghostFinding;if(!s||!this.ghostsShown||s.referenceId!==t.id||s.src!==t.src)return;const{search:n}=s,r=t.registration,a=d=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf({u:d.x/n.width,v:d.y/n.height},r,i)),o=[];for(const d of n.pairs){const u=a(d.ghost),p=a(d.light),f=a({x:d.ghost.x+d.ghost.radius,y:d.ghost.y});!u||!p||o.push({ghost:u,light:p,ghostRadius:f?Math.hypot(f.x-u.x,f.y-u.y):0})}const l=n.centre?a(n.centre):void 0,h=n.cropped?a({x:n.width/2,y:n.height/2}):void 0;e.paintGhosts(o,l,h)}adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:s}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(s??0)),this.updateObserver();const n=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(l=>l.t===n);if(r<0)return;const a=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),o=[["headingDeg",t],["pitchDeg",i],["rollDeg",s??0]];for(const[l,h]of o)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${l}`,{basis:"derived",rationale:a,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceAddMenu.setDisabled("street",e?void 0:this.messages.referenceStreetNoPlace)}setReferenceAddKinds(e,t,i){const s=this.numberOrUndefined(this.latInput?.value??"")!==void 0&&this.numberOrUndefined(this.lngInput?.value??"")!==void 0;this.referenceAddMenu.setKinds([{value:"address",label:e},{value:"file",label:t},{value:"street",label:i,...s?{}:{disabledReason:this.messages?.referenceStreetNoPlace??""}}])}addReferenceOfKind(e){switch(e){case"file":this.addReferenceFromFile();break;case"street":this.searchStreetPictures();break;default:this.addReferenceFromAddress()}}async searchStreetPictures(){const e=st(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 s=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.addReferenceButton.disabled=!0;try{this.streetPictures$??=new(await oe(async()=>{const{PanoramaxPictures:r}=await import("./PanoramaxPictures-CELY3Ecc.js");return{PanoramaxPictures:r}},[],import.meta.url)).PanoramaxPictures,this.streetPictures=await this.streetPictures$.nearby(t,i,s)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.addReferenceButton.disabled=!1;return}this.addReferenceButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,a]of this.streetPictures.entries()){const o=document.createElement("option");o.value=String(r),o.textContent=this.streetPictureLabel(a,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(o)}const n=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!n,this.referenceStreetAddButton.hidden=!n,this.referenceStatus.textContent=n?"":this.messages.referenceStreetNone.replace("{m}",String(s))}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:_f}})}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;wn.showPresence(this.shadow.getElementById("trace-row"),this.shadow.getElementById("trace-item"),t);for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t;this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(s=>s.id!==this.currentTraceId?s:{...s,title:this.said.write(s.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(s.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(s=>s.value===this.currentTraceId),i=e.traces.find(s=>s.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTraces(e){const t=e.file?.name??decodeURIComponent(e.url.split("/").pop()??e.url);let i;try{const{KmlImport:h}=await oe(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url);i=await h.fromBytes(await u1.bytesOf(e))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(i.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const s=this.ufoElement.sighting,n=new Set(s.traces.map(h=>h.id));let r=1;const a=this.said.write(void 0,i.documentName??t,this.writingLanguage),o=i.traces.map(h=>{for(;n.has(`trace-${r}`);)r++;const d=`trace-${r}`;return n.add(d),{...h,id:d,title:h.title===void 0?void 0:this.said.write(void 0,h.title,this.writingLanguage),source:a}});s.traces=[...s.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const l=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",t)+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 IT){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(),t9)}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=fy(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 pv(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===_e.FILE_SOURCE;if(!e){const t=ds(oh,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new pv(t.create()))}if(this.setWeatherFromFile(e),this.weatherInferredInput.checked!==!e){this.weatherInferredInput.checked=!e,this.keepWeatherSource=e;try{this.weatherInferredInput.dispatchEvent(new Event("change"))}finally{this.keepWeatherSource=!1}}}keepWeatherSource=!1;setWeatherFromFile(e){const t=this.ufoElement.sighting;if(Ns.fromFile(t.frozen,"weather")===e)return;const i={...t.frozen??{}};e?i.weather={...i.weather??{},live:void 0}:delete i.weather,i.weather&&i.weather.live===void 0&&delete i.weather.live,t.frozen=ts.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...oh.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,_e.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked;this.weatherProviderSelect.value=e?_e.FILE_SOURCE:ds(oh,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const t=ds(oh,this.chosenSourceId.get("weather")),i=this.shadow.getElementById("weather-credit");i.hidden=e,i.href=t.creditUrl,i.textContent=t.credit,this.weatherFileLink.hidden=!e,e&&(this.weatherFileLink.textContent=this.weatherFileItemLabel(),this.weatherFileLink.title=this.sectionFilePanel?.where("weather")??"")}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.setWeatherFromFile(!this.weatherFromRecords),this.weatherFromRecords?this.scheduleWeatherLookup(!0):(this.cancelWeatherLookup(),this.keepWeatherSource||(this.ufoElement.sighting.weatherSource=void 0),this.syncWeatherSourceState())}scheduleWeatherLookup(e=!1){if(!this.weatherFromRecords||this.pendingWeatherEdit!==void 0)return;const t=this.ufoElement.sighting.weatherSource;!e&&t!==void 0&&!bv(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),tE))}cancelWeatherLookup(){clearTimeout(this.weatherLookupTimer),this.weatherLookupToken++,this.weatherLookupPending=!1}async inferWeather(){if(!this.weatherFromRecords)return;const e=++this.weatherLookupToken;this.weatherLookupPending=!0,this.syncWeatherSourceState();const t=await this.weatherInference.infer(this.ufoElement.sighting);e!==this.weatherLookupToken||!this.weatherFromRecords||(this.weatherLookupPending=!1,this.weatherLookupResult=t,t.status==="inferred"?(this.weatherInference.applyTo(this.ufoElement.sighting,t),this.weatherTrackSpan=this.ufoElement.seekableDuration,this.ufoElement.refresh(),this.syncWeatherFromTimeline()):this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}ensureWeatherTrackSpan(){const e=this.ufoElement.sighting.weatherSource;if(!this.weatherFromRecords||e===void 0||!bv(e))return;const t=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||t===this.weatherTrackSpan||(this.weatherTrackSpan=t,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const a of this.weatherFields)a.disabled=t&&e!==void 0&&a!==this.iceCrystalAlignmentInput&&a!==this.rareIceCrystalsInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?a.title=this.messages.weatherWhilePlaying:a.title===this.messages.weatherWhilePlaying&&(a.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&bv(e)){this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState();return}this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const s=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=s,this.labelWeatherInferred.title=s,this.syncWeatherProvider();const n=t&&e!==void 0;if(this.weatherSourceLink.hidden=!n,n){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const r=i?t?this.weatherStatusMessage():"":this.weatherUnavailableMessage();this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""||!i}startDateHalfEntered(){return this.shadow.getElementById("obs-time-native")?.validity.badInput===!0}weatherUnavailableMessage(){const e=this.weatherInference.missingOf(this.ufoElement.sighting);return this.startDateHalfEntered()&&(e.date=!0),e.date&&e.place?this.messages.weatherNeedsDateAndPlace:e.date?this.messages.weatherNeedsDate:this.messages.weatherNeedsPlace}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&sn(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`, ${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherLookupResult=void 0,this.weatherFromRecords=!Ns.fromFile(e.frozen,"weather")&&(e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0),this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=If[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(this.sectionFromFile("lightPollution"))return!1;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),tE)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,s=this.lightPollutionProvider,n=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||n===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(n<s.year){r(),this.lightPollutionLookup={status:"too-early",year:n},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const a=await s.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=a,a.status==="found"?(e.lightPollution=a.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${s.citation}, at ${a.lat.toFixed(4)}, ${a.lng.toFixed(4)}: ${Math.round(a.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:a.lightPollution}),this.lightPollutionInput.value=String(a.lightPollution),this.ufoElement.refresh()):a.status==="natural"&&r(),this.syncLightPollutionStatus())}syncLightPollutionStatus(){const e=this.lightPollutionLookup,t=this.messages;let i="";switch(e?.status){case"pending":i=t.lightPollutionLookingUp;break;case"found":i=t.lightPollutionFound.replace("{artificial}",Math.round(e.artificialMcdPerM2*1e3).toLocaleString(this.language));break;case"natural":i=t.lightPollutionNatural;break;case"outside":i=t.lightPollutionOutside;break;case"failed":i=t.lightPollutionFailed;break;case"too-early":i=t.lightPollutionTooEarly.replace("{atlasYear}",String(this.lightPollutionProvider.year)).replace("{year}",String(e.year));break}this.lightPollutionStatusText.textContent=i===""?"":`${i} `,this.lightPollutionSourceRow.hidden=!(e?.status==="found"||e?.status==="natural"||e?.status==="outside")}syncDurationField(){const e=this.shadow.activeElement;if(e!==this.durationInput&&e!==this.durationElement.textField){const t=this.ufoElement.sighting.event,i=Qh(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=D3(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;Ee.show(this.playPauseButton,e?"⏸":"▶"),this.playPauseButton.disabled=!t;const i=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch();for(const[s,n]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])s.title=n,s.setAttribute("aria-label",n);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,s]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${s} — ${t}`:s,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(Ks.opensPrecise(e.time)),this.endDate.setPrecise(Ks.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),s=e!==void 0&&i!==void 0&&Math.abs(e-i)>r9;this.utcOffsetInput.classList.toggle("invalid",s),this.utcOffsetInput.title=s?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),s9))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<nh&&Math.abs(e.lng-i)<nh}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=ds(Ef,this.chosenSourceId.get("elevation")),n=await new p1(s.create()).at(e,t);if(i!==this.groundElevationToken||n===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(n),this.syncElevationField(r)}syncElevationField(e){const t=this.groundElevationM;this.elevationInput.value=String(Math.round((t??0)+e)),this.elevationInput.min=t===void 0?"":String(t),this.elevationInput.title=t===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=t===void 0||Math.round(e)===0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(st(this.ufoElement.sighting,0)?.elevationM??0),this.scheduleGroundElevation()}syncPlaceNameField(){const e=this.ufoElement.sighting.event.place?.[0],t=e?.name??"";this.placeNameInput.value=t,this.placeNameInput.title=t,this.namedCoordinates=e&&t?{lat:e.lat,lng:e.lng}:void 0,this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=""}syncObserverMetadataFields(){this.witnessErrorView?.refresh();const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=this.said.read(e.observer?.title)??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.observerList.rename(_e.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(Ks.opensPreciseDate(e.account?.observerBirth)),this.perceptionSettings.values=e.account?.observerPerception??{},this.birth=e.account?.observerBirth,this.birthDate.time=this.birth,this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.evaluationFields.show(e.account),this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"";const t=e.lens;this.lensGlassSelect.value=t?.glass??"",this.lensDropsInput.value=t?.drops?.toString()??"",this.lensCondensationInput.value=t?.condensation?.toString()??"",this.lensDirtInput.value=t?.dirt?.toString()??"",this.lensShelteredInput.checked=t?.sheltered===!0,this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=fs(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??qf)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??hE)),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],s=this.shadow.activeElement;s!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),s!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),this.syncObserverPosition(),s!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),s!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),s!==this.elevationInput&&this.syncElevationField(t?.elevationM??0)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,n=i.getInterpolatedShapeAt(s,this.currentSourceId),r=this.buildAppearanceShape(e??n?.bounds??this.defaultBounds(),n,t);this.commitShapes(s,[{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 s=E1(e,this.currentAppearance);return t?{...s,angle:t.angle,title:t.title,selected:t.selected}:s}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();for(const[i,s]of this.groupTabs.entries()){const n=s===e&&t;s.setAttribute("aria-expanded",String(n)),this.groupPanels[i].hidden=!n}if(t){const i=e.parentElement.getBoundingClientRect(),s=e.getBoundingClientRect();(s.left<i.left||s.right>i.right)&&(e.parentElement.scrollLeft+=s.left-i.left-(i.width-s.width)/2)}if(t&&e.getAttribute("aria-controls")==="group-decor"){const i=this.decorList.value;i!==""&&i!==this.currentDecorId&&this.selectDecor(i)}t&&e.getAttribute("aria-controls")==="group-observer"&&this.observerShown!==_e.OBSERVER_PRINCIPAL&&this.selectDecor(this.observerShown),t&&e.getAttribute("aria-controls")==="group-weather"&&this.syncSkyParts(),t&&e.getAttribute("aria-controls")==="group-shape"&&this.showPhenomenonPartWithContent(),t&&e.getAttribute("aria-controls")==="group-observation"&&this.candidatesView?.refresh(),this.placeDecorItem(),this.syncCanvasMode(),this.refreshTimelineMarks(),t&&this.sectionFolds.refresh(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>{this.syncFileEditor(!1),this.showFileItem(this.fileItemSelect.value)},()=>this.showFileNote(this.messages.importError,"error"))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await oe(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-BekK-f3R.js");return{SightingFileEditor:t}},__vite__mapDeps([14,1,15]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileTextApplied=this.historySnapshot,this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel,{baseline:this.touched?this.savedFileText:this.fileText(),phrases:this.messages.fileSearchPhrases,caretMoved:t=>this.onFileCaret(t)}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}fileSyncActive(){return this.fileEditor!==void 0&&this.isGroupIdOpen("group-file")}fileFocus;caretTimer;followingCaret=!1;onFileCaret(e){clearTimeout(this.caretTimer),this.caretTimer=setTimeout(()=>this.focusFromFile(e),120)}focusFromFile(e){if(!this.fileSyncActive())return;const t=this.ufoElement.sighting;this.followingCaret=!0;try{const i=e[0]==="decor"&&typeof e[1]=="number"?t.decor[e[1]]:void 0;if(i!==void 0){this.fileFocus="decor",this.selectDecor(i.id);return}const s=e[0]==="timeline"&&e[1]==="keyframes"&&typeof e[2]=="number"&&e[3]==="shapes"&&typeof e[4]=="number"?t.timeline.allKeyframes[e[2]]?.shapes[e[4]]:void 0;if(s!==void 0){this.fileFocus="shape",this.selectUnit(s.sourceId),this.syncCanvasMode(),this.ufoElement.refresh();return}this.fileFocus=void 0,this.syncCanvasMode(),this.ufoElement.refresh()}finally{this.followingCaret=!1}}showInFile(e){this.followingCaret||e===void 0||!this.fileSyncActive()||this.fileEditor.reveal(e)}bodyPath(e){try{const i=(JSON.parse(this.fileEditor.text).interpretation?.bodies??[]).findIndex(s=>s.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,s]of t.entries()){const n=s.shapes.findIndex(r=>r.sourceId===e);if(n>=0)return["timeline","keyframes",i,"shapes",n]}}showFileNote(e,t="info"){Xt.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.sightingData)}writtenText(e){const t=this.keyframesWritten();return xw.of(e,t,t==="thin"?Si.derivable(this.ufoElement.sighting):void 0)}keyframesWritten(){return this.wholeKeyframesInput.checked?"whole":"thin"}static WHOLE_KEYFRAMES_STORAGE="rr0-sighting-editor.whole-keyframes";setKeyframesWritten(){try{this.wholeKeyframesInput.checked?localStorage.setItem(_e.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(_e.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=ky(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=xw.of(um(e),t,t==="thin"?Si.derivable(e):void 0),this.savedFileText=this.baseline}this.resetHistory()}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(e=!0){const t=this.fileEditor;if(!(t===void 0||!this.isGroupIdOpen("group-file")||t.focused)&&!this.historyAnswering){if(t.edited)try{JSON.parse(t.text)}catch{return}t.replaceText(this.fileText(),e),this.fileTextApplied=t.text}}onFileTextEdited(e){this.syncHistoryButtons(),clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e,t=!1){this.fileApplyTimer=void 0;let i;try{i=JSON.parse(e)}catch{return}if(typeof i!="object"||i===null||Array.isArray(i)||!t&&JSON.stringify(i)===JSON.stringify(this.sightingData))return;const s=this.ufoElement.currentTime,n=!t&&this.fileTextApplied!==void 0&&JSON.stringify(i.weatherTrack)!==JSON.stringify(_e.weatherOf(this.fileTextApplied)),r={track:this.sightingData.weatherTrack,source:this.sightingData.weatherSource};this.applyingFileText=!0;try{if(this.sightingData=i,this.touched=!0,this.ufoElement.currentTime=s,n&&!this.restoringWeather&&this.weatherFromRecords){const a=this.ufoElement.sighting.weatherSource;a===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):oh.some(o=>o.id===a.id)&&this.askAboutWeather(r,a.name??a.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(a){this.showFileNote(a instanceof wu?a.said(this.messages.formatVersionError):this.messages.importErrorMalformed,"error"),this.fileTextApplied=e}finally{this.applyingFileText=!1}}fileTextApplied;static weatherOf(e){try{return JSON.parse(e).weatherTrack}catch{return}}pendingWeatherEdit;restoringWeather=!1;askAboutWeather(e,t){this.cancelWeatherLookup(),this.pendingWeatherEdit=e,this.shadow.getElementById("file-ask-text").textContent=this.messages.weatherEditedAsk.replaceAll("{source}",t),this.shadow.getElementById("file-ask-stop").textContent=this.messages.weatherEditedStop,this.shadow.getElementById("file-ask-keep").textContent=this.messages.weatherEditedKeep,typeof this.fileAsk.showModal=="function"?this.fileAsk.showModal():this.fileAsk.setAttribute("open","")}closeFileAsk(){typeof this.fileAsk.close=="function"?this.fileAsk.close():this.fileAsk.removeAttribute("open")}stopReadingWeather(){this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState(),this.ufoElement.refresh(),this.syncFileEditor(!1)}keepReadingWeather(){const e=this.pendingWeatherEdit;if(this.pendingWeatherEdit=void 0,this.closeFileAsk(),e!==void 0){this.restoringWeather=!0;try{this.applyFileText(JSON.stringify({...this.sightingData,weatherTrack:e.track,weatherSource:e.source}))}finally{this.restoringWeather=!1}this.syncFileEditor(!1)}}applyingFileText=!1;leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(!1),0))}static SCENE_LINKED=["heading","pitch","focalLength","apparentWidth","realWidth","objectDistance","color","haloScale","cloudCover","windDirection","windSpeed","referenceOpacity"];setActiveSceneField(e){e!==this.activeSceneField&&(this.activeSceneField=e,e==="referenceOpacity"&&!this.ufoElement.referencesShown?(this.ufoElement.toggleReferences(),this.referencesShownForField=!0):e!=="referenceOpacity"&&this.referencesShownForField&&(this.ufoElement.referencesShown&&this.ufoElement.toggleReferences(),this.referencesShownForField=!1),this.refreshSceneField())}refreshSceneField(){const e=this.sceneFieldOverlay;if(!e)return;const t=this.activeSceneField,i=this.ufoElement.sighting,s=this.ufoElement.currentTime,n=this.ufoElement.canvasElement,r=this.messages,a=l=>this.numberOrUndefined(l.value),o=(l,h=1)=>l===void 0?"?":l.toLocaleString(this.language,{maximumFractionDigits:h});if(t==="pitch"){const l=a(this.pitchInput)??0,h=ar.of(i.instrument,n.height,Si.fovOf(i,s)),d=Math.sign(l)*h.angleDegToRadiusPx(Math.min(89,Math.abs(l))),u=Math.min(1,Math.max(0,(n.height/2+d)/n.height));e.horizon(u,r.overlayHorizon.replaceAll("{deg}",o(l)))}else if(t==="focalLength"){const l=Si.fovOf(i,s),d=2*ar.of(i.instrument,n.height,l).halfWidthAngleDeg(n.width/n.height);e.frame(r.overlayFov.replaceAll("{v}",o(l)).replaceAll("{h}",o(d)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const l=i.timeline.getInterpolatedShapeAt(s,this.currentSourceId);if(!l){e.hide();return}const h=l.bounds,u=[[a(this.apparentWidthInput),"°",1],[a(this.realWidthInput)," m",1],[a(this.objectDistanceInput)," m",0]].filter(([p])=>p!==void 0).map(([p,f,m])=>`${o(p,m)}${f}`).join(" · ");e.measure((h.x+h.width/2)/n.width,(h.y+h.height/2)/n.height,Math.max(h.width,h.height)*1.3/n.width,u)}else if(t==="windDirection"||t==="windSpeed"){const l=a(this.windDirectionInput)??0,h=l-(a(this.headingInput)??0);e.wind(h,r.overlayWind.replaceAll("{point}",this.naming.point(l)).replaceAll("{speed}",o(a(this.windSpeedInput))))}else e.hide()}attachWitnessErrors(){const e=this,t=()=>this.ufoElement.sighting,i=()=>this.ufoElement.currentTime,s=this.shadow.querySelector('rr0-date-input[name="obs-time"]');this.witnessErrorView.attach({kind:"time",label:s.closest("label"),input:s,path:()=>t().event.time?"time":void 0,value:()=>t().event.time?.hour!==void 0?0:void 0}),this.witnessErrorView.attach({kind:"duration",label:this.durationElement.closest("label"),input:this.durationElement,path:()=>t().event.durationSeconds!==void 0?"durationSeconds":void 0,value:()=>t().event.durationSeconds});const n=l=>{let h=-1;return l.forEach((d,u)=>{d<=i()&&(h=u)}),h===-1&&l.length>0?0:h};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const l=n(t().observerTrack.allKeyframes.map(h=>h.t));return l===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${l}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const l=t().timeline.allKeyframes,h=n(l.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId)).map(f=>f.t));if(h===-1||this.apparentWidthInput.value==="")return;const d=l.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId))[h],u=l.indexOf(d),p=d.shapes.findIndex(f=>f.sourceId===this.currentSourceId);return`timeline.keyframes.${u}.shapes.${p}.shape.angular`},value:()=>this.numberOrUndefined(this.apparentWidthInput.value)});const r=this.shadow.getElementById("observerPerception").closest(".form-section");this.witnessErrorView.placeObserverSections(r);const a=document.createElement("div");a.className="form-section candidates-section",this.shadow.getElementById("group-observation").append(a);const o=l=>l?.closest("label")??void 0;this.candidatesView=new mn({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const l=this.ufoElement.sighting.event,h=l.place?.[0];if(!h||l.time?.year===void 0||l.time.hour===void 0)return;const d=sn(l.time,h.lng,l.utcOffsetHours);return d?{date:d,observer:{lat:h.lat,lng:h.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:l=>Ta(l,this.instrumentGain()),fieldLabels:()=>({time:o(s),heading:o(this.headingInput),size:o(this.apparentWidthInput),duration:o(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:l=>{const h=`${l}/${this.language}`;return this.poherMatrix?.key!==h&&(this.poherMatrix={key:h,loaded:bl.load(l,this.language,d=>na.json(d))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const l=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,h=this.sceneElement.satellitePassesDuring(l);return h.length>0?{passes:h,positionsAt:d=>this.sceneElement.satellitePositionsAt(d)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const l=this.ufoElement.sighting.interpretation;return[...l&&l.bodies.length>0?[{id:"own",label:this.said.read(l.title)??this.principalObserverLabel(),interpretation:l}]:[],...this.readings]},starName:l=>this.naming.star({name:l}),projectionAt:(l,h)=>this.sceneElement.bodyProjectionAt(l,h),variants:()=>this.ufoElement.sighting.variants,keep:l=>this.editVariants(h=>[...h,l]),remove:l=>this.editVariants(h=>h.filter((d,u)=>u!==l))},a)}readings=[];editVariants(e){this.touch(),this.armHistory(),this.ufoElement.sighting.variants=e(this.ufoElement.sighting.variants),this.scheduleHistoryRecord()}poherMatrix;poherFacts(){const e=this.ufoElement.sighting,t={},i=e.event,s=i.place?.[0];if(s&&i.time?.year!==void 0&&i.time.hour!==void 0){const h=sn(i.time,s.lng,i.utcOffsetHours);h&&(t.sunAltitudeDeg=zi("Sun",h,{lat:s.lat,lng:s.lng,elevationM:this.groundElevationM??0}).altitudeDeg)}if(i.durationSeconds!==void 0&&(t.durationSeconds=i.durationSeconds),e.weatherTrack.allKeyframes.length>0){const h=fs(e,0);t.cloudCover=h.cloudCover,t.lightning=h.storm,t.lowVisibility=h.precipitationType!=="none"&&h.precipitationIntensity>.3}const n=e.timeline,r=n.sourceIds[0];if(r){const h=n.allKeyframes.filter(p=>p.shapes.some(f=>f.sourceId===r)),d=h.map(p=>({t:p.t,shape:n.getShapeAt(p.t,r)})).filter(p=>p.shape?.aim),u=n.getInterpolatedShapeAt(h[0]?.t??0,r);if(u?.aim&&(t.elevationDeg=u.aim.altitudeDeg),u?.angular){t.widthDeg=u.angular.widthDeg;const p=u.angular.heightDeg>0?u.angular.widthDeg/u.angular.heightDeg:1;t.round=u.kind==="oval"&&p>.8&&p<1.25}if(u?.brightness!==void 0&&(t.brightness=u.brightness),d.length>1){const p=(g,b)=>{const w=Math.PI/180,y=Math.sin(g.altitudeDeg*w)*Math.sin(b.altitudeDeg*w)+Math.cos(g.altitudeDeg*w)*Math.cos(b.altitudeDeg*w)*Math.cos((g.azimuthDeg-b.azimuthDeg)*w);return Math.acos(Math.max(-1,Math.min(1,y)))/w},f=d.slice(1).map((g,b)=>({deg:p(d[b].shape.aim,g.shape.aim),s:(g.t-d[b].t)/1e3}));t.sweepDeg=p(d[0].shape.aim,d[d.length-1].shape.aim);const m=f.reduce((g,b)=>g+b.deg,0);t.straysDeg=Math.max(0,m-t.sweepDeg)/2;const v=(d[d.length-1].t-d[0].t)/1e3;if(v>0){t.speedDegPerS=m/v;const g=Math.max(...f.filter(b=>b.s>0).map(b=>b.deg/b.s));t.speedVariation=t.speedDegPerS>0?g/t.speedDegPerS:0}}}const a=new Set(n.sourceIds.map(h=>n.groupMembers(h)?.[0]??h));a.size>0&&(t.count=a.size);const o=[...a].map(h=>n.getInterpolatedShapeAt(0,h)?.aim).filter(h=>h!==void 0);if(o.length>=3){const h=Math.PI/180,d=o.map(m=>({x:(((m.azimuthDeg-o[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*h),y:m.altitudeDeg}));let[u,p]=[d[0],d[1]];for(const m of d)for(const v of d)Math.hypot(m.x-v.x,m.y-v.y)>Math.hypot(u.x-p.x,u.y-p.y)&&([u,p]=[m,v]);const f=Math.hypot(u.x-p.x,u.y-p.y);t.aligned=f>0&&d.every(m=>Math.abs((p.x-u.x)*(u.y-m.y)-(u.x-m.x)*(p.y-u.y))/f<=Math.max(.5,f*.1))}const l=new Set([...a].map(h=>n.getInterpolatedShapeAt(0,h)?.color).filter(h=>h!==void 0));return l.size>0&&(t.colors=[...l]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(h=>h.sound.kind!=="none")&&(t.sound=!0),t}candidatesTimer;refreshCandidatesSoon(){clearTimeout(this.candidatesTimer),this.isGroupIdOpen("group-observation")&&(this.candidatesTimer=setTimeout(()=>this.candidatesView?.refresh(),150))}showOverlays(){const e=this.shadow.querySelector(".scene-card");e.dataset.shown="",clearTimeout(this.overlayTimer),this.overlayTimer=setTimeout(()=>delete e.dataset.shown,3500)}static SCENE_HEIGHT_KEY="rr0-editor-scene-height";resizeScene(e){const t=this.shadow.querySelector(".app"),i=this.sceneElement,s=n=>{n===void 0?t.style.removeProperty("--rr0-scene-max-height"):t.style.setProperty("--rr0-scene-max-height",`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,n)))}px`);try{n===void 0?localStorage.removeItem(_e.SCENE_HEIGHT_KEY):localStorage.setItem(_e.SCENE_HEIGHT_KEY,t.style.getPropertyValue("--rr0-scene-max-height"))}catch{}};try{const n=localStorage.getItem(_e.SCENE_HEIGHT_KEY);n&&/^\d+px$/.test(n)&&t.style.setProperty("--rr0-scene-max-height",n)}catch{}e.addEventListener("pointerdown",n=>{n.preventDefault();const r=n.clientY,a=i.getBoundingClientRect().height;e.setPointerCapture?.(n.pointerId),e.classList.add("dragging");const o=h=>s(a+h.clientY-r),l=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",l),e.removeEventListener("pointercancel",l)};e.addEventListener("pointermove",o),e.addEventListener("pointerup",l),e.addEventListener("pointercancel",l)}),e.addEventListener("keydown",n=>{n.key!=="ArrowUp"&&n.key!=="ArrowDown"||(n.preventDefault(),s(i.getBoundingClientRect().height+(n.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>s(void 0))}setTracksShown(e){this.shadow.querySelector(".scene-card").toggleAttribute("data-tracks",e),this.shadow.getElementById("timeline-tracks").hidden=!e,this.tracksToggle.setAttribute("aria-expanded",String(e));const i=e?this.messages.collapseTracks:this.messages.expandTracks;this.tracksToggle.title=i,this.tracksToggle.setAttribute("aria-label",i),this.refreshTracks()}flash(e){e&&(e.classList.add("flash"),setTimeout(()=>e.classList.remove("flash"),1800))}refreshTracks(){if(!this.timelineTracks||this.tracksToggle.getAttribute("aria-expanded")!=="true")return;const e=this.ufoElement.sighting,t=this.messages,i=a=>{const o=this.groupTabs.find(l=>l.getAttribute("aria-controls")===a);o&&this.toggleGroup(o,!0)},s=a=>()=>{this.touch(),this.armHistory(),a(),this.scheduleHistoryRecord(),this.refreshTimelineMarks()},r=[this.showsBodies?{id:"bodies",label:t.bodiesTrack,color:"#f5c451",...this.eventMarks("bodies"),open:()=>this.chooseAccountView(!0),selected:this.pickedEvent(this.bodiesEventsPanel),select:a=>this.pickEvent(Number(a)),add:()=>this.bodyEditor?s(()=>this.bodyEditor.keyframeHere())():this.chooseAccountView(!0)}:{id:"shapes",label:t.shapesTrack,color:"#f5c451",...this.eventMarks("phenomenon"),open:()=>this.revealShapePanel(),selected:this.pickedEvent(this.phenomenonEventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>{e.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,!1)})},{id:"observer",label:t.observerTrack,color:"#7fd4ff",...this.eventMarks("observer"),open:()=>i("group-location"),selected:this.pickedEvent(this.eventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>this.updateObserver())},{id:"weather",label:t.weatherTrack,color:"#b9c8d8",times:e.weatherTrack.allKeyframes.map(a=>a.t),open:()=>i("group-weather"),add:s(()=>this.applyWeatherAtPlayhead())},{id:"sound",label:t.soundTrack,color:"#9fd9a8",times:e.soundTrack.allKeyframes.map(a=>a.t),open:()=>i("group-sound"),add:s(()=>this.applySoundAtPlayhead())}];this.timelineTracks.show(r,this.ufoElement.seekableDuration,this.ufoElement.currentTime)}eventMarks(e){const t=this.ufoElement.sighting;if(e==="bodies")return this.bodyMarks();const i=e==="observer"?lt.observerTrackIsExpanded(t):lt.timelineIsExpanded(t),s=e==="observer"?t.observerTrack.allKeyframes:t.timeline.allKeyframes;if(!i)return{times:s.map(h=>h.t)};const n=this.ufoElement.seekableDuration,r=h=>e==="observer"?Ht.isObserver(t,h):Ht.isPhenomenon(t,h),a=(t.events??[]).map((h,d)=>({event:h,index:d})).filter(({event:h})=>r(h)),o=new Set(a.map(({event:h})=>h.who)).size>1,l=a.map(({event:h,index:d})=>{const u=this.messages.events.kinds[h.eventType]??h.eventType;return{id:String(d),t:h.t,until:h.until??n,label:e==="phenomenon"&&o?`${this.shapesLabel(h.who??"")} · ${u}`:u}});return{times:[],spans:l}}bodyMarks(){const e=this.ufoElement.sighting,t=e.interpretation?.bodies??[],i=new Set(t.map(o=>o.id)),s=o=>Ht.partOf(o)?.element??o??"",n=(e.events??[]).map((o,l)=>({event:o,index:l})).filter(({event:o})=>i.has(s(o.who)));if(n.length===0||!lt.bodiesAreExpanded(e))return{times:[...new Set(t.flatMap(o=>o.track.map(l=>l.t)))].sort((o,l)=>o-l)};const r=this.ufoElement.seekableDuration,a=n.map(({event:o,index:l})=>{const h=t.find(f=>f.id===s(o.who)),d=Ht.partOf(o.who)?.part,u=this.messages.events.kinds[o.eventType]??o.eventType,p=[...t.length>1?[this.said.read(h?.title)??s(o.who)]:[],...d?[d]:[]];return{id:String(l),t:o.t,until:o.until??r,label:[...p,u].join(" · ")}});return{times:[],spans:a}}pickedEvent(e){const t=e?.pickedIndex,i=e===this.eventsPanel?"events-section":e===this.phenomenonEventsPanel?"phenomenon-events-section":"bodies-events-section",s=this.shadow.getElementById(i);return t===void 0||!s||s.closest("[hidden]")?void 0:String(t)}pickEvent(e){const t=this.ufoElement.sighting,i=t.events?.[e];if(!i)return;const s=i.who??Ht.observerId(t);if(Ht.isObserver(t,i)){const n=this.groupTabs.find(r=>r.getAttribute("aria-controls")==="group-location");n&&this.toggleGroup(n,!0),this.eventsPanel.pick(e)}else Ht.isPhenomenon(t,i)?(this.revealShapePanel(),this.phenomenonEventsPanel.pick(e)):(this.chooseAccountView(!0),this.loadBodyEditor().then(n=>{n.show(Ht.partOf(s)?.element??s),this.bodiesEventsPanel.pick(e),this.refreshTracks()}));this.goToMark(i.t),this.refreshTracks()}shapesLabel(e){const t=this.ufoElement.sighting,i=t.timeline.groupOf(e);if(i)return this.said.read(i.title)??e;const s=t.timeline.allKeyframes.map(n=>n.shapes.find(r=>r.sourceId===e)?.shape.title).find(n=>n!==void 0);return this.said.read(s)??e}get showsBodies(){return this.accountViewSelect.value==="bodies"}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(o,l)=>[...l].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${o})`})),i=o=>{if(this.showsBodies){const h=this.eventMarks("bodies");return h.spans?h.spans.map(d=>({t:d.t,kind:"event",label:d.label})):t(this.messages.bodiesTrack,h.times)}const{spans:l}=this.eventMarks("phenomenon");return l?l.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(h=>!o||h.shapes.some(d=>this.selectedSourceIds.has(d.sourceId))).map(h=>h.t))},s=()=>{const{times:o,spans:l}=this.eventMarks("observer");return l?l.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.observerTrack,o)},n=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(o=>o.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(o=>o.t)),a=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?s():this.isGroupIdOpen("group-weather")?n():this.isGroupIdOpen("group-sound")?r():[...i(!1),...s(),...n(),...r()];for(const o of e.milestones)a.push({t:o.t,kind:"milestone",label:this.said.read(o.label)??""});this.timelineMarks.show(a,this.ufoElement.seekableDuration),this.refreshTracks(),this.eventsPanel?.sync(),this.phenomenonEventsPanel?.sync(),this.bodiesEventsPanel?.sync(),this.witnessErrorView?.refreshFields(),this.activeSceneField&&this.refreshSceneField()}seekTo(e){this.goToMark(e*1e3)}set passages(e){const t=this.shadow.getElementById("moment-passages");t.replaceChildren(...(e??[]).map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.className="at",n.innerHTML=tt.PLAY,n.append(i.clock),n.addEventListener("click",()=>this.seekTo(i.at));const r=document.createElement("button");return r.type="button",r.className="excerpt",r.textContent=i.said,r.title=i.where,r.addEventListener("click",()=>i.open()),s.append(n,r),s})),t.hidden=t.childElementCount===0}openSection(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);t&&this.toggleGroup(t,!0)}showRender(){this.sceneElement.scrollIntoView?.({block:"center",behavior:"smooth"})}goToMark(e){e!==void 0&&(this.ufoElement.currentTime=e,this.syncPlaybackControls())}isGroupIdOpen(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-file")?this.fileFocus==="decor"&&this.editableDecor()!==void 0?"decor":this.fileFocus==="shape"&&this.selectedSourceIds.size>0?"shape":"scene":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-weather")&&(this.shadow.getElementById("sky-launches")?.hidden===!1||this.shadow.getElementById("sky-beams")?.hidden===!1)?"scene":this.isGroupIdOpen("group-shape")?"shape":this.isGroupIdOpen("group-decor")&&this.editableDecor()!==void 0?"decor":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",i=this.lastCanvasMode==="picture",s=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",t&&this.currentReference()&&this.loadPictureRegistration(),this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,s&&this.ufoElement.repaintOverlay(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const n=this.currentReference();n&&this.syncReferenceStatus(n),this.syncStreetSearchAvailability(),this.syncBodiesShown()}skyOf(e){if(!(!e||!e.lanterns?.length&&!e.flares?.length))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],lanterns:e.lanterns,flares:e.flares}}),this.skyPart.sky}skyPart;syncBodiesShown(){const t=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading,i=this.ufoElement.sighting.interpretation,s=t?i:this.skyOf(i);this.sceneElement.compareAccount=t&&s!==void 0&&this.accountCompareInput.checked,this.sceneElement.interpretation!==s&&(this.sceneElement.interpretation=s);const n=t&&s!==void 0?"bodies":"shapes",r=this.accountViewSelect.value!==n;this.accountViewSelect.value=n,r&&this.refreshTimelineMarks(),this.syncSkyParts(),this.shadow.getElementById("account-view-row").hidden=this.isReading,this.shadow.getElementById("account-compare-row").hidden=this.isReading||n!=="bodies"}syncSkyParts(){this.isGroupIdOpen("group-weather")&&(this.shadow.getElementById("sky-beams")?.hidden===!1&&this.loadBeamEditor().then(e=>e.refresh()),this.shadow.getElementById("sky-lanterns")?.hidden===!1&&this.loadLanternEditor().then(e=>e.refresh()),this.shadow.getElementById("sky-launches")?.hidden===!1&&this.loadLaunchEditor().then(e=>e.refresh()))}chooseAccountView(e){const t=this.groupTabs.find(s=>s.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}openSubgroup(e){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const i of this.subgroupTabs){if(i.parentElement!==t)continue;const s=i===e;i.setAttribute("aria-expanded",String(s)),this.shadow.getElementById(i.getAttribute("aria-controls")).hidden=!s}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(i=>i.sync()),e.getAttribute("aria-controls")==="sky-launches"&&this.loadLaunchEditor().then(i=>i.sync()),e.getAttribute("aria-controls")==="sky-beams"&&this.loadBeamEditor().then(i=>i.sync()),e.getAttribute("aria-controls")==="sky-lanterns"&&this.loadLanternEditor().then(i=>i.sync()),this.syncCanvasMode()}showPhenomenonPartWithContent(){const e=this.ufoElement.sighting,t=e.timeline.sourceIds.length>0,i=(e.interpretation?.bodies?.length??0)>0,n=this.shadow.getElementById("shape-bodies")?.hidden===!1?!i&&t?"shape-shapes":void 0:!t&&i?"shape-bodies":void 0,r=n&&this.subgroupTabs.find(l=>l.getAttribute("aria-controls")===n);if(!r)return;const{sectionChosen:a,opensMostLacking:o}=this;this.openSubgroup(r),this.sectionChosen=a,this.opensMostLacking=o}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|"),s=JSON.stringify(this.ufoElement.sighting.account??null);if(i===this.paramSummarySignature){s!==this.assessedAccount&&(this.assessedAccount=s,this.runAssessments());return}this.assessedAccount=s,this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.runAssessments()}paramChips=[];renderParamSummary(){this.saveButton&&this.refreshEditorTitle();const e=_e.NESTED_GROUPS,t=[];let i;for(const s of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==s.group&&(i=void 0),e.includes(s.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=s.group;const a=document.createElement("span");a.className="param-nest-label",a.textContent=s.group==="assessment"?this.messages.assessmentGroup:s.group==="summary"?this.messages.summaryGroup:_e.tabLabel(this.groupTabs[this.summaryPanelIndex(s.group)]),r.append(a),i={group:s.group,element:r},t.push(r)}const n=this.paramChip(s);i?i.element.append(n):t.push(n)}this.paramSummary.replaceChildren(...t),this.shadow.getElementById("label-param-summary").textContent=this.messages.paramSummaryTitle.replace("{n}",String(t.length)),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),d2.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return this.panelIndex(e==="phenomenon"?"shape":e)}static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]},"bg-information":{panel:"observer",fields:["accountSource"]},"bg-occupation":{panel:"observer",fields:["observerOccupationKind"]},"bg-relation":{panel:"observer",fields:["observersRelation"]},"bg-activity":{panel:"observer",fields:["observerActivity"]},"bg-age":{panel:"observer",fields:["observerAge"]},"bg-appearance":{panel:"observer",fields:["strangeness-appearance"]},"bg-movement":{panel:"observer",fields:["strangeness-movement"]},"bg-incongruity":{panel:"observer",fields:["strangeness-incongruity"]},"bg-close":{panel:"observer",fields:["strangeness-close"]},"bg-traces":{panel:"observer",fields:["strangeness-traces"]}};assessmentChips=[];assessmentToken=0;assessedAccount="";async runAssessments(){const e=++this.assessmentToken,t=await new Ry(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.openMostLackingGroup(),this.renderParamSummary())}opensMostLacking=!1;sectionChosen=!1;openMostLackingGroup(){if(!this.opensMostLacking)return;this.opensMostLacking=!1;const e=s=>{const n=s.querySelector(".tab-badge");return n&&!n.hidden?Number(n.textContent):0},t=this.groupTabs.find(s=>this.isGroupOpen(s));let i=t&&e(t)>0?t:void 0;for(const s of this.groupTabs)e(s)>(i?e(i):0)&&(i=s);i&&i!==t&&(this.toggleGroup(i,!0),this.sectionChosen=!1)}fitGroupTabs(){const e=this.groupTabs[0]?.parentElement;e&&(e.classList.add("measuring"),e.classList.remove("compact"),e.classList.toggle("compact",e.scrollWidth>e.clientWidth),e.offsetWidth,e.classList.remove("measuring"))}static titleGroupTab(e){e.title=[e.dataset.intro,e.dataset.unanswered].filter(Boolean).join(`
|
|
11574
|
-
`)}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 n of e){const r=_e.QUESTION_FIELDS[n];if(r&&!r.fields.some(a=>this.shadow.getElementById(a)?.classList.contains("missing-required")))for(const a of r.fields){const o=this.shadow.getElementById(a);o&&!o.hidden&&o.value===""&&t.add(a)}}for(const[n,r]of Object.entries(_e.QUESTION_FIELDS))for(const a of _e.QUESTION_FIELDS[n].fields){const o=this.shadow.getElementById(a);if(!o)continue;const l=t.has(a)&&!o.classList.contains("missing-required");o.classList.toggle("wanted",l),(l||o.title===this.messages.questionUnanswered)&&(o.title=l?this.messages.questionUnanswered:"")}const i=new Map;let s;for(const[n,r]of Object.entries(_e.QUESTION_FIELDS))for(const a of r.fields){const o=this.shadow.getElementById(a);if(!o)continue;const l=o.classList.contains("missing-required");!l&&!o.classList.contains("wanted")||(l&&(s=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const n of this.groupTabs){const r=this.panelOf(n),a=i.get(r)??0,o=r===s,l=_e.badgeOn(n);l.hidden=a===0,l.textContent=String(a),l.classList.toggle("optional",!o);const h=a===0?void 0:o?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(a));h?n.dataset.unanswered=h:delete n.dataset.unanswered,_e.titleGroupTab(n)}}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,e.detail&&(t.title=e.detail);const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const n=document.createElement("span");n.className="param-chip-swatch",n.style.background=e.color,t.append(n)}const s=document.createElement("span");return s.className="param-chip-value",s.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(s),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(a=>a.field==="description")?.full,this.syncDescription();return}const i=Number(t.dataset.panel);if(i<0)return;const s=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const n=t.dataset.field;if(n.startsWith("shape:")){this.selectedSourceIds=new Set([n.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(n.startsWith("body:")){const a=this.subgroupTabs.find(o=>o.getAttribute("aria-controls")==="shape-bodies");a&&this.openSubgroup(a),this.loadBodyEditor().then(o=>o.show(n.slice(5)));return}if(n.startsWith("decor:")){this.currentDecorId=n.slice(6),this.refreshDecorList(),this.decorList.focus();return}const r=this.shadow.getElementById(n);r===null||!s.contains(r)||(this.revealSubgroupOf(r),this.sectionFolds.reveal(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe(),this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorBaseFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.samplingRateInput!==this.shadow.activeElement&&(this.samplingRateInput.value=this.ufoElement.sighting.sampleMs===void 0?"":String(this.ufoElement.sighting.sampleMs)),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateShapeToolbarVisibility(){const e=this.ufoElement.sighting.timeline.sourceIds.length===0,t=this.shadow.getElementById("shape-row");t&&wn.showPresence(t,this.shadow.getElementById("shape-item")??void 0,!e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.shapeRotationInput])i.disabled=e,i.title=t}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:m9(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.shadow.activeElement!==this.shapeRotationInput&&(this.shapeRotationInput.value=String(_e.rotationDeg(e.angle))),this.refreshApparentSize())}static rotationDeg(e){const t=(e*180/Math.PI%360+540)%360-180;return Math.round((t===-180?180:t)*10)/10}updateShapeRotation(){const e=this.numberOrUndefined(this.shapeRotationInput.value);if(e===void 0)return;const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=t.getInterpolatedShapeAt(i,this.currentSourceId);s&&(this.commitShapes(i,[{sourceId:this.currentSourceId,shape:{...s,angle:e*Math.PI/180}}]),this.ufoElement.refresh())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,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,s=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!s)return;const n=this.currentProjection(),r=n.degToPx(e),a=s.bounds.height*(s.bounds.width===0?1:r/s.bounds.width),o={x:s.bounds.x+(s.bounds.width-r)/2,y:s.bounds.y+(s.bounds.height-a)/2,width:r,height:a},l=n.ofBounds(o),h=s.kind==="oval"?{...s,bounds:o,angular:l}:{...s,bounds:o,angular:l,points:this.scalePoints(s,o)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,s=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(n=>({x:n.x*i,y:n.y*s}))}refreshFilterOptions(){const e={[Xi.NONE.id]:this.messages.filterNone,[Xi.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[Xi.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==Xi.ALL.length||Xi.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||Xi.NONE.id;this.filterSelect.replaceChildren();for(const r of Xi.ALL){const a=document.createElement("option");a.value=r.id,a.textContent=t(r),this.filterSelect.appendChild(a)}this.filterSelect.value=n}const s=this.ufoElement?.sighting?.instrument;for(const n of this.filterSelect.options){const r=!s||Xi.usableWith(Xi.byId(n.value),s);n.disabled=!r,n.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,s={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,video:this.messages.instrumentCategoryVideo,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},n=r=>{const a=this.naming.instrument(r),o=Qt.unavailability(r,t);if(!o)return{id:r.id,label:a};const l=(o.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(o.from)).replace("{to}",String(o.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",a),hint:l}:{id:r.id,label:a,disabledReason:l}};this.instrumentSelect.choices=Qt.CATEGORIES.map(r=>({label:s[r],children:$d.filter(a=>a.category===r).map(n)})).filter(r=>r.children.length>0),this.instrumentSelect.value=this.instrumentSelect.value||i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=_e.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 n=Number(i[1]),r=Number(i[2]);return r>0?n/r:void 0}const s=Number(t);return Number.isFinite(s)&&s>0?s:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=st(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??Qt.fieldOfViewDeg(t),r=s?Qt.focalLengthMmFor(t,n):n;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=s?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=s?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=s!==void 0&&s.focalRangeMm===void 0,this.focalLengthInput.min=String(s?s.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(s?s.focalRangeMm?.maxMm??2e3:179),en.fit(this.focalLengthInput.parentElement??this.shadow),this.sectionFolds?.refresh(),this.focalFovOutput.textContent=s&&n!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(n,n<10?1:0)):"";const a=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=a===void 0?"":String(a)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const o=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=o===void 0?"":_e.exposureText(o)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const h of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(h,Ci.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const l=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.isoInput.placeholder=l?l.autoExposure?"auto":String(l.iso):"",this.setRowVisible(this.isoInput,l!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,l?.autoExposure===!0),this.meteringSelect.disabled=e.iso!==void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,s!==void 0&&t.fNumber!==void 0),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=Xi.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Qt.fieldOfViewDeg(e),s=Qt.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>l9||t.observerTrack.addKeyframe(n.t,{...n.pose,fovDeg:s})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,s=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!s){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(s.max,Math.max(s.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return st(e,this.ufoElement.currentTime)?.fovDeg??Qt.fieldOfViewDeg(e.instrument)}currentProjection(){return ar.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 s=st(this.ufoElement.sighting,this.ufoElement.currentTime),n=s?.focusDistanceM;if(n!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(n));return}const r=(s?Qt.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,a=s?.fNumber??t.fNumber;if(a===void 0||r<=0){this.blurBoundOutput.textContent="";return}const o=this.ufoElement.canvasElement.height;if(o<=0)return;const l=2*Kv*e/o*i.heightMm,h=r*r/(a*l)/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 s=this.numberOrUndefined(this.realWidthInput.value),n=s!==void 0&&(t!==void 0&&s<t||i!==void 0&&s>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),a=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+a+n;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+n}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),s=(m,v)=>Number(m.toFixed(v)),n=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??i9,a=this.sceneElement.groundAlong(n.azimuthDeg,n.altitudeDeg,t),o=a!==void 0&&a<r,l=s(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:s(Lt.sizeMAt(l,h),2),lengthM:s(Lt.sizeMAt(l,h),2),heightM:s(Lt.sizeMAt(l,d),2)}:void 0,p={azimuthDeg:s(n.azimuthDeg,2),altitudeDeg:s(n.altitudeDeg,2)},f={t,...p,distanceM:l,...o?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=oe(async()=>{const{BodyEditor:e}=await import("./BodyEditor-D5VXWcru.js");return{BodyEditor:e}},__vite__mapDeps([16,17]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,bodySelected:()=>this.bodiesEventsPanel.render(),said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,seekTo:t=>{this.ufoElement.currentTime=t},readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,s)=>this.sceneElement.groundAlong(t,i,s)},this.language),this.bodyEditor)),this.bodyEditorLoading}loadLanternEditor(){return this.lanternEditorLoading??=oe(async()=>{const{LanternEditor:e}=await import("./LanternEditor-C60IT7Cv.js");return{LanternEditor:e}},__vite__mapDeps([18,19]),import.meta.url).then(({LanternEditor:e})=>(this.lanternEditor=new e(this.shadow.getElementById("lantern-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()}},this.language),this.lanternEditor)),this.lanternEditorLoading}loadBeamEditor(){return this.beamEditorLoading??=oe(async()=>{const{BeamEditor:e}=await import("./BeamEditor-BzrEOJOy.js");return{BeamEditor:e}},__vite__mapDeps([20,7,21]),import.meta.url).then(({BeamEditor:e})=>(this.beamEditor=new e(this.shadow.getElementById("beam-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language),this.beamEditor)),this.beamEditorLoading}loadLaunchEditor(){return this.launchEditorLoading??=oe(async()=>{const{LaunchEditor:e}=await import("./LaunchEditor-DcYWYLQN.js");return{LaunchEditor:e}},__vite__mapDeps([22,23]),import.meta.url).then(({LaunchEditor:e})=>(this.launchEditor=new e(this.shadow.getElementById("launch-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language),this.launchEditor)),this.launchEditorLoading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const n=i===void 0||i<=0?void 0:Lt.sizeMAt(e.distanceM,i);this.realWidthInput.value=n===void 0?"":this.plain(n,n<1?2:n<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const s={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=s.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,s=ar.of(i.instrument,Lt.CANVAS_HEIGHT_PX,Si.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const a=Si.aimOf(i,e,r.shape.bounds),o=s.ofBounds(r.shape.bounds),{aim:l,...h}=r.shape;return{...r,shape:a?{...h,aim:a,angular:o}:{...h,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.ufoElement.sighting.timeline.sourceIds.length>0&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const s=/^ufo-(\d+)$/.exec(e);return s?`${this.messages.shape} ${s[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;this.currentSourceId=this.newSourceIds(1)[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}newSourceIds(e){const t=this.ufoElement.sighting.timeline,i=[];t.sourceIds.length===0&&this.currentSourceId!==void 0&&i.push(this.currentSourceId);const s=new Set([...t.sourceIds,this.currentSourceId]);let n=s.size+1;for(;i.length<e;){for(;s.has(`ufo-${n}`);)n++;i.push(`ufo-${n}`),s.add(`ufo-${n}`)}return i}shapeAddKinds(){const e=this.messages,t={triangle:e.modelTriangle,saucer:e.modelSaucer,cigar:e.modelCigar,chevron:e.modelChevron,light:e.modelLight};return[{value:"oval",label:e.oval},{value:"polygon",label:e.polygon},...ao.ALL.map(i=>({value:i.id,label:t[i.id]}))]}addModel(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,i=e.boundsAt(this.offsetDefaultBounds(t.sourceIds.length)),s=e.shapesIn(i,this.currentAppearance),n=this.newSourceIds(s.length),r=this.shapeAddKinds().find(h=>h.value===e.id).label,a=/^ufo-(\d+)$/.exec(n[0])?.[1]??"",o={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},l=s.map((h,d)=>{const u=e.partNames[d],p=u?`${r} ${a}, ${o[u]}`:`${r} ${a}`;return{sourceId:n[d],shape:{...h,title:this.said.write(void 0,p,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,l),n.length>1&&t.group(n),this.currentSourceId=n[n.length-1],this.selectedSourceIds=new Set(n),this.refreshSourceList(),this.ufoElement.refresh()}duplicateSelected(){if(this.hideContextMenu(),this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(r=>this.selectedSourceIds.has(r));if(t.length===0)return;const i=this.newSourceIds(t.length),s=24;for(const r of e.allKeyframes){const a=r.shapes.filter(o=>t.includes(o.sourceId)).map(o=>{const{bounds:l}=o.shape;return{sourceId:i[t.indexOf(o.sourceId)],shape:{...o.shape,bounds:{...l,x:l.x+s,y:l.y+s}}}});a.length>0&&this.commitShapes(r.t,a)}const n=e.groupMembers(t[0]);t.length>1&&n?.length===t.length&&t.every(r=>n.includes(r))&&e.group(i),this.currentSourceId=i[i.length-1],this.selectedSourceIds=new Set(i),this.refreshSourceList(),this.ufoElement.refresh()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i));t.length!==0&&this.removeShapes(t)}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??Wd,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 s=document.createElement("option");s.value=i,s.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(s)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const s=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorList.kindLabel(e.kind)} ${s}`}addDecor(e=this.decorList.pickedKind??"building"){this.observerAdded=e==="observer";const t=this.ufoElement.sighting,s={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="trafficlight"?{lights:id.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:sd}:{},windows:r2(e)};t.decor=[...t.decor,s],this.currentDecorId=s.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(s.id,e)}readSceneryChoice(){try{return localStorage.getItem(_e.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(_e.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(_e.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(_e.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await oe(()=>import("./surroundingsSources-Bq5A0HA5.js"),[],import.meta.url).catch(()=>{});if(!e)return;const{SURROUNDINGS_SOURCES:t,SurroundingsSources:i}=e;if(!this.isConnected)return;const s=document.createElement("option");s.value=_e.NO_SCENERY,s.id="option-scenery-none",s.textContent=this.messages.surveySourceNone;const n=t.map(a=>{const o=document.createElement("option");return o.value=a.id,o.textContent=a.name,o.title=a.credit,o}),r=new Option(this.messages.sourceFile,_e.FILE_SOURCE);r.id="option-scenery-file",this.scenerySource.replaceChildren(s,...n,r),this.surveyIds=t.map(a=>a.id),this.defaultSurveyId=i.DEFAULT_ID,this.syncSceneryPicker()}surveyIds;defaultSurveyId;sceneryAsked(){return this.sceneryChoice!==_e.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?_e.FILE_SOURCE:this.sceneryChoice===_e.NO_SCENERY?_e.NO_SCENERY:this.surveyIds.includes(this.sceneryChoice??"")?this.sceneryChoice:this.defaultSurveyId??this.surveyIds[0]),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-radius-row").hidden=e||this.sceneryChoice===_e.NO_SCENERY;const t=this.shadow.getElementById("scenery-file-link");t.hidden=!e,e&&(t.textContent=this.sectionFilePanel.itemLabel("decor"),t.title=this.sectionFilePanel.where("decor"))}setDecorFromFile(e){const t=this.ufoElement.sighting;if(this.sectionFromFile("decor")===e)return;const i={...t.frozen??{}};e?i.decor=i.decor??{}:delete i.decor,t.frozen=ts.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return typeof s=="number"&&typeof n=="number"?{lat:s,lng:n}:void 0}setPlantedDecor(e){this.ufoElement.sighting.decor=e,e.some(t=>t.id===this.currentDecorId)||(this.currentDecorId=e[0]?.id),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleHistoryRecord()}refreshSceneryWarning(){const e=this.ufoElement?.sighting,t=e?om.anachronism(e.decor,e.event.time):void 0;this.sceneryWarning.hidden=t===void 0,this.sceneryWarning.textContent=t?this.messages.surveyWarning.replace("{survey}",t.survey).replace("{observation}",t.observation):""}citeSource(e){const t=this.ufoElement.sighting;(t.sources??[]).some(i=>i.url===e.url)||(t.sources=[...t.sources??[],e])}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const s=this.ufoElement.sighting.decor.find(n=>n.id===e);!s||s.model||s.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(n=>n.id===e?{...n,model:{id:i.id},sizeM:i.sizeM}:n),this.currentDecorId===e&&this.syncDecorVisibility(),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*Mv,t=Math.round(e/h9*1e3);return{lights:id.byId("airliner")?.create(),track:[{t:0,eastM:-Mv,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:Mv,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(s=>s.kind===e).length;return`${this.decorList.kindLabel(e)} ${t+1}`}deleteDecor(){const t=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);t!==void 0&&this.removeDecor(t.id)}removeDecor(e){const t=this.ufoElement.sighting;t.decor=t.decor.filter(i=>i.id!==e),this.currentDecorId===e&&(this.currentDecorId=t.decor[0]?.id),this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="decor"),this.decorList.show(e),this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh();const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===e);t>=0&&this.showInFile(["decor",t])}updateDecor(e={}){if(this.currentDecorId===void 0)return;const t=this.ufoElement.sighting;t.decor=t.decor.map(i=>i.id!==this.currentDecorId?i:{...i,...e}),this.syncDecorVisibility(),this.ufoElement.refresh()}decorModelEntries;refreshDecorModelOptions(e){if(!e||this.decorModelEntries?.kind===e.kind)return;const t=e.kind;this.decorModelProvider.entries(t).catch(()=>[]).then(i=>{this.decorModelEntries={kind:t,entries:i},this.isConnected&&this.decorBaseForm.sync()})}drawnEntry;drawnEntryAsked;publishedParametersOf(e){const t=ju(e);if(!(!t?.id||t.url!==void 0)){if(this.drawnEntry?.id===t.id)return this.drawnEntry.parameters;if(this.drawnEntryAsked!==t.id){this.drawnEntryAsked=t.id;const i=t.id;this.decorModelProvider.entry(i).catch(()=>{}).then(s=>{this.drawnEntryAsked!==i||!s||(this.drawnEntry=s,this.isConnected&&this.syncDecorVisibility())})}}}modelPicker;enhanceDecorModelChoice(e,t){e.key==="model.id"&&(t.addEventListener("change",()=>t.dispatchEvent(new Event("input",{bubbles:!0}))),this.modelPicker.enhance(t,async i=>{const s=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),n=i!==""?i:s?lm[s.kind]?.id:void 0;return n!==void 0?this.decorModelProvider.entry(n).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):s===void 0?void 0:{decorKind:s.kind}},{current:()=>{const i=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId)?.model;return i?.url===void 0?void 0:{url:i.url,title:i.credit?.title??"",author:i.credit?.author??"",license:i.credit?.license??"",source:i.credit?.sourceUrl??""}},apply:i=>this.commitDecorBase(s=>{const n=this.stringOrUndefined(i.title),r=this.stringOrUndefined(i.license);s.model={url:i.url,credit:n!==void 0&&r!==void 0?{title:n,license:r,author:this.stringOrUndefined(i.author),sourceUrl:this.stringOrUndefined(i.source)}:void 0}},"model")}))}async adoptCatalogueSize(e,t){const[i,s]=await Promise.all([e.model?.id?this.decorModelProvider.entry(e.model.id).catch(()=>{}):void 0,t?this.decorModelProvider.entry(t).catch(()=>{}):void 0]),n=this.ufoElement.sighting.decor.find(o=>o.id===e.id);if(!n||n.model?.id!==t||!s?.sizeM)return;const r=n.sizeM!==void 0&&i?.sizeM!==void 0&&n.sizeM.widthM===i.sizeM.widthM&&n.sizeM.lengthM===i.sizeM.lengthM&&n.sizeM.heightM===i.sizeM.heightM;if(n.sizeM&&!r)return;const a={...n.sizeM,...Object.fromEntries(Object.entries(s.sizeM).filter(([,o])=>o!==void 0).map(([o,l])=>[o,this.roundedMeters(l)]))};this.updateDecor({sizeM:a})}roundedMeters(e){return Math.round(e*100)/100}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(s=>s.t===e)||(t.milestones=cc([...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(s=>s.t===e);i&&(t.milestones=t.milestones.filter(s=>s.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=cc(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;wn.showPresence(this.shadow.getElementById("milestone-row"),this.shadow.getElementById("milestone-item"),t);for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.deleteMilestoneButton])i.disabled=!t;this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.filter(e=>e.kind!=="observer").map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning(),this.refreshObserverList()}refreshObserverList(){const e=_e.OBSERVER_PRINCIPAL,t=this.ufoElement.sighting.decor.filter(s=>s.kind==="observer");this.currentDecorId!==void 0&&t.some(s=>s.id===this.currentDecorId)&&this.observerAdded&&(this.observerShown=this.currentDecorId),this.observerAdded=!1,t.some(s=>s.id===this.observerShown)||(this.observerShown=e),this.observerList.setItems([{id:e,label:this.principalObserverLabel()},...t.map(s=>({id:s.id,label:this.decorLabel(s)}))],this.observerShown);const i=this.observerShown!==e;this.observerList.setRemoveEnabled(i),this.observerList.setActionEnabled("look-at-observer",i),this.placeDecorItem()}principalObserverLabel(){const e=[this.observerTitleInput.value,this.observerFirstNamesInput.value,this.observerLastNameInput.value].map(t=>t.trim()).filter(Boolean).join(" ");return e===""?this.messages.principalObserver:`${e} (${this.messages.principalObserver.toLowerCase()})`}observerAdded=!1;selectObserver(e){this.observerShown=e,e!==_e.OBSERVER_PRINCIPAL&&this.selectDecor(e),this.refreshObserverList()}placeDecorItem(){const e=this.shadow.getElementById("decor-item"),t=this.shadow.getElementById("observer-decor-host"),i=this.shadow.getElementById("observer-principal");if(!e||!t||!i)return;const s=this.observerShown!==_e.OBSERVER_PRINCIPAL;if(i.hidden=s,s&&this.isGroupIdOpen("group-observer")){e.parentElement!==t&&t.append(e),e.hidden=!1;return}e.parentElement===t&&this.shadow.getElementById("decor-list-header").after(e),e.hidden=this.decorList.value===""}syncDecorFields(){this.syncDecorVisibility()}async findGhosts(){const e=this.currentReference();if(e?.src){this.searchingGhosts=!0,this.syncFindGhosts(e);try{const{GhostSearchView:t}=await oe(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-UG9G-yF8.js");return{GhostSearchView:r}},__vite__mapDeps([24,9]),import.meta.url),i=this.messages,s={searching:i.referenceGhostsSearching,found:i.referenceGhostsFound,foundScaled:i.referenceGhostsFoundScaled,low:i.referenceGhostsLow,none:i.referenceGhostsNone,cropped:i.referenceGhostsCropped},n=await new t(this.ghostsStatus,s).search(e.src);this.ghostFinding=n&&n.pairs.length>0?{referenceId:e.id,src:e.src,search:n}:void 0,this.ghostsShown=!0,this.syncGhostsShown(),this.ufoElement.refresh()}finally{this.searchingGhosts=!1,this.syncFindGhosts(this.currentReference())}}}syncGhostsShown(){this.ghostsShownButton.hidden=!this.ghostFinding,this.ghostsShownButton.setAttribute("aria-pressed",String(this.ghostsShown)),this.ghostsShownButton.textContent=this.ghostsShown?this.messages.referenceGhostsHide:this.messages.referenceGhostsShow}syncFindGhosts(e){const t=!e?.src||this.sceneElement.referenceFailure(e.src)!==void 0;this.findGhostsButton.disabled=this.searchingGhosts||t,this.addReferenceLandmarkButton.disabled=t,t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark()}updateExposureSettings(){const e=this.ufoElement.sighting;e.iso=this.numberOrUndefined(this.isoInput.value);const t=this.meteringSelect.value;e.metering=t==="average"||t==="highlights"?t:void 0,this.meteringSelect.disabled=e.iso!==void 0,this.ufoElement.refresh()}updateLens(){const e=this.lensGlassSelect.value,t={...e?{glass:e}:{},drops:this.numberOrUndefined(this.lensDropsInput.value),condensation:this.numberOrUndefined(this.lensCondensationInput.value),dirt:this.numberOrUndefined(this.lensDirtInput.value),...this.lensShelteredInput.checked?{sheltered:!0}:{}};for(const i of["drops","condensation","dirt"])t[i]===void 0&&delete t[i];this.ufoElement.sighting.lens=Object.keys(t).length>0?t:void 0,this.ufoElement.refresh()}label(e,t){const i=this.shadow.getElementById(e);i&&(i.textContent=t)}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}decorBaseShownFor;showDecorBase(e){if(this.decorBaseHost.hidden=e===void 0,this.decorStateHost.hidden=e===void 0,!e){this.decorBaseForm.clear(),this.decorStateForm.clear(),this.decorBaseShown=!1,this.decorBaseShownFor=void 0;return}const t=this.decorBaseShownFor!==e.id;if(this.decorBaseShownFor=e.id,this.decorBaseShown){this.decorBaseForm.sync(t),this.decorStateForm.sync(t);return}this.decorBaseShown=!0;const i=()=>new Ml(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?ta.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(gr.BASE,i(),()=>{}),this.decorStateForm.show(gr.STATE,i(),()=>{})}decorPositionPlace(){const e=()=>{const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===this.currentDecorId);return t<0?[]:[`decor.${t}.eastM`,`decor.${t}.northM`]};return{frame:()=>this.positionFrame(this.currentDecorId),messages:()=>this.messages,basis:{read:()=>this.ufoElement.sighting.provenance.at(e()[0]??"")?.basis,write:(t,i)=>this.writePositionBasis(e(),i)}}}framePlace(){return{frame:()=>this.positionFrame(),messages:()=>this.messages}}positionFrame(e){const t=this.ufoElement.currentTime,i=[{label:this.messages.positionObserver,eastM:0,northM:0}];for(const s of this.ufoElement.sighting.decor){if(s.id===e)continue;const{eastM:n,northM:r}=Mr(s,t);i.push({id:s.id,label:this.decorLabel(s),eastM:n,northM:r})}return{origin:this.plantingCentre(),references:i}}syncObserverPosition(){const e=this.ufoElement.sighting,t=this.ufoElement.currentTime;this.observerSaid=e.observerTrack.getLatestPoseAt(t)?.saidPosition;const i=this.positionFrame();this.observerPosition.frame={...i,references:i.references.filter(n=>n.id!==void 0)};const s=JSON.stringify(this.observerSaid??null);s!==this.observerSaidShown&&(this.observerSaidShown=s,this.observerPosition.said=this.observerSaid),this.observerPosition.basis=e.provenance.at(this.observerPositionPaths()[0]??"")?.basis}observerPositionPaths(){const e=this.ufoElement.currentTime,t=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(i=>i.t===e);return t<0?[]:[`observerTrack.keyframes.${t}.pose.lat`,`observerTrack.keyframes.${t}.pose.lng`]}writeObserverBasis(e){this.observerPositionPaths().length===0&&this.updateObserver(),this.writePositionBasis(this.observerPositionPaths(),e)}writePositionBasis(e,t){const i=this.ufoElement.sighting.provenance;for(const s of e)t===void 0||t==="stated"?i.clear(s):i.set(s,{basis:t});this.dispatchEvent(new CustomEvent("sightingchange"))}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=ac.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:ue.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:ac.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:gr.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:lm[e.kind]?.id}}placedByAuthor(e){if(!e.lamp?.supposed)return e;const t=this.sceneElement.decorDrawnOffset(e.id),{supposed:i,...s}=e.lamp,n={...e,eastM:e.eastM+(t?.eastM??0),northM:e.northM+(t?.northM??0),...Object.keys(s).length>0?{lamp:s}:{}};Object.keys(s).length===0&&delete n.lamp;const r=this.ufoElement.sighting;return r.decor=r.decor.map(a=>a.id===e.id?n:a),n}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!i)return;const s=t==="eastM"||t==="northM"?this.placedByAuthor(i):i;if((t==="lit"||t==="headlights")&&this.ufoElement.playbackState==="playing")return;const n=this.ufoElement.currentTime,r=ta.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const a=this.ufoElement.sighting;a.decor=a.decor.map(l=>l.id===s.id?ta.apply(l,r,t,n):l),t==="model.id"&&this.adoptCatalogueSize(s,r.model?.id);const o=a.decor.find(l=>l.id===s.id);t==="title"&&this.decorList.rename(o.id,this.decorLabel(o)),this.syncDecorVisibility(),this.ufoElement.refresh(),t==="lightRig"&&this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorBaseFromTimeline(){this.ufoElement.playbackState==="playing"||!this.decorBaseShown||(this.decorBaseForm.sync(),this.decorStateForm.sync())}showDecorParameters(e){const t=e?vi.of(e,this.publishedParametersOf(e)):void 0;if(!e||!t){this.decorParametersShownFor=void 0,this.decorParameterForm.clear(),this.decorParametersHost.hidden=!0;return}this.decorParametersHost.hidden=!1;const i=`${e.id}|${t.kind}|${t.parameters.map(r=>r.key).join(",")}`;if(i===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=i;const s=e.id,n=new Ml(()=>this.ufoElement.sighting.decor.find(r=>r.id===s),r=>{const a=this.ufoElement.sighting;a.decor=a.decor.map(o=>{if(o.id!==s)return o;const l=structuredClone(o);return r(l),l})});this.decorParameterForm.show(t,n,()=>{this.syncDecorVisibility(),this.ufoElement.refresh()})}syncDecorParameterVisibility(){this.showDecorParameters(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);this.refreshDecorModelOptions(e),this.showDecorBase(e),this.syncDecorParameterVisibility()}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++,this.meteorMagnitudeLimit());e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;meteorMagnitudeLimit(){const e=this.ufoElement.sighting,t=this.observerAtStart(),i=e.event.time?.year!==void 0?sn(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=zi("Sun",i,t).altitudeDeg;return Ta(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Jn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Wm;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new rn(["en"]);tagNames=new Xv({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,s=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?sn(i,t.lng,e.event.utcOffsetHours):void 0,n=JSON.stringify([s?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,fs(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status,this.sceneElement.groundKey]);if(n===this.skyCandidatesKey)return;if(this.skyCandidatesKey=n,!s||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.disabled=!0,this.showCometButton.disabled=!0,this.showNovaButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown),this.labelSkyButtons();return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},a=[this.starsClause(s,r),this.showerClause(s,r),this.cometClause(s,r),this.novaClause(s,r),this.eclipseClause(s,r),this.moonClause(s,r),this.satelliteClause(s,r),this.reentryClause(s,r),this.fireballClause(s,r),this.opticsClause(s,r),this.rainbowClause(s,r),this.glowClause(s,r)].filter(o=>o!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",a.join(" · ")),this.labelSkyButtons()}labelSkyButtons(){const e=this.messages,t=[[this.showMeteorButton,e.showMeteor,e.noMeteor],[this.showCometButton,e.showComet,e.noComet],[this.showNovaButton,e.showNova,e.noNova],[this.showSatelliteButton,e.showSatellite,e.noSatellite],[this.showFireballButton,e.showFireball,e.noFireball]];for(const[i,s,n]of t){const r=i.disabled?n:s;i.title=r,i.setAttribute("aria-label",r)}}instrumentGain(){const e=this.ufoElement.sighting;return Ws.gainFor(e.instrument,{fNumber:st(e,0)?.fNumber,fieldOfViewDeg:Si.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=zi("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=Ta(i,s,n),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<n9)return this.messages.skyStarsNone;const o=this.ufoElement.sighting.instrument,l=Math.abs(s)<.1?this.messages.skyStarsEye.replace("{limit}",a(r)):(s>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(r)).replace("{device}",this.naming.instrument(o)).replace("{gain}",a(Math.abs(s))).replace("{eye}",a(Ta(i,0,n)));return r<=mu?l:l+this.messages.skyStarsCatalogue.replace("{catalogue}",a(mu))}showerClause(e,t){const i=Qi.observedRatePerHour(Qi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=$h.activeAt(e);if(s.length===0)return this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyNothingActive.replace("{sporadic}",i);const n=s.map(r=>{const a=$h.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:$h.observedRatePerHour(r.zhr,a.altitudeDeg,r.shower.populationIndex)}}).sort((r,a)=>a.rate-r.rate)[0];return n.rate<=0?(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(n.entry.shower))):(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerActive.replace("{name}",this.naming.shower(n.entry.shower)).replace("{altitude}",String(Math.round(n.position.altitudeDeg))).replace("{bearing}",this.naming.towards(n.position.azimuthDeg)).replace("{rate}",n.rate.toLocaleString(void 0,{maximumFractionDigits:n.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=Yf.brightestAt(e,t);if(!i||i.magnitude>ud){this.showCometButton.disabled=!0;return}return this.showCometButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.cometText(i)}novaClause(e,t){const i=$m.brightestAt(e,t);if(!i||i.magnitude>ud){this.showNovaButton.disabled=!0;return}return this.showNovaButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.novaText(i)}eclipseClause(e,t){const i=ps.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=zi("Sun",i.peak,t),n=r=>r.replace("{altitude}",String(Math.round(s.altitudeDeg))).replace("{bearing}",this.naming.towards(s.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),a=Math.round(i.totality.seconds%60);return n(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${a} s`)}return n(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=zi("Moon",e,t);if(i.altitudeDeg<=0||Hl(e).illuminatedFraction<.97)return;const s=[],n=Sn.distanceKm(e,t),r=Sn.relativeToMean(Sn.radiusAtKm(n)),a=n<=Sn.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=Sn.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return a&&s.push(a.replace("{distance}",(Math.round(n/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(Sn.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),qm.isIn(e)&&s.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),s.length>0?s.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=jr.visibilityAt(e,t),s=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(s!==void 0)return s;if(this.showSatelliteButton.disabled=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const n=Ta(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=n),a=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",a);const o=Math.round(i.shadowHeightKm).toLocaleString(),l=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",o).replace("{count}",l);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",a):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),s=i+this.satelliteSpanMs(),n=[i,s,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==n){const l={key:n,status:"loading"};this.reentries=l,_e.reentryArchive.candidates(i,s,t).then(h=>{l.status=h?"ready":"unavailable",l.candidates=h,this.reentries===l&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=jr.visibilityAt(e,t).sunAltitudeDeg<-6,a=(this.reentries.candidates??[]).filter(l=>l.record.precision==="minute"||r);if(a.length===0)return;const o=a.slice(0,3).map(l=>this.reentryText(l));return a.length>3&&o.push(this.messages.skyReentriesMore.replace("{count}",String(a.length-3))),this.messages.skyReentries.replace("{list}",o.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,s=new Date(e.timeMs);if(t.precision==="day"){const a=s.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",a)}const n=this.observerClock(s).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",n).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}",n).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",n)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(l=>l.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(l=>l.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses();if(this.showSatelliteButton.disabled=this.aimableSatellitePasses(i).length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const n=i[0].peak,a=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",n.object.name).replace("{magnitude}",n.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg)).replace("{time}",this.observerClock(n.date)),o=this.starlinkTrain(i);return o?`${a}, ${o}`:a}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const s=i.peak.magnitude;if(s===void 0)return!1;const n=zi("Sun",i.peak.date,t);return s<=Ta(n.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,s)=>i.peak.magnitude-s.peak.magnitude)}aimableSatellitePasses(e){return e.filter(t=>this.passTimelineMs(t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(t.peak.altitudeDeg,t.peak.azimuthDeg))}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:a,launch:o}=r.peak.object;a!=="starlink"||!o||(r.peak.date.getTime()-Date.parse(`${o}T00:00:00Z`))/864e5>60||t.set(o,(t.get(o)??0)+1)}const[i,s]=[...t.entries()].sort((r,a)=>a[1]-r[1])[0]??[];if(!i||!s||s<3)return;const n=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(s)).replace("{date}",n)}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=st(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=sn(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.aimableSatellitePasses(this.visibleSatellitePasses());if(e.length===0)return;const t=e.map(s=>`${s.object.norad}@${s.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=>Pr.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Pr.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,s)=>i.magnitude-s.magnitude)}aimableFireballs(e,t){return e.filter(i=>this.fireballTimelineMs(i,t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(i.peak.altitudeDeg,i.peak.azimuthDeg))}fireballTimelineMs(e,t){const{record:i}=e,s=i.from[2]-i.to[2],n=Math.abs(s)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/s));return i.t-t.getTime()+n*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.disabled=this.aimableFireballs(i,e).length===0,i.length===0)return;const s=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",s.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(s.record.t))).replace("{altitude}",String(Math.round(s.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(s.peak.azimuthDeg)).replace("{distance}",String(Math.round(s.peak.distanceKm/10)*10)).replace("{stations}",String(s.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 s=sn(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=this.aimableFireballs(this.strikingFireballs(s,this.observerAtStart()),s);if(n.length===0)return;const r=n[this.fireballRank++%n.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,s),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=fs(this.ufoElement.sighting,0),s=zi("Sun",e,t),n=zi("Moon",e,t),r=St.deckLitUntilDeg(St.DECK_HEIGHT_M),a=s.altitudeDeg>-r,o=a?s:n;if(o.altitudeDeg<=-r)return;const l=i.highCloudCover;if(l===void 0||l<=0)return this.messages.skyOpticsNoIce;if(St.strength(l,i.lowerCloudCover??i.cloudCover,o.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=a?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(St.formsAt(o.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??qf;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=fs(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=zi("Sun",e,t),n=zi("Moon",e,t),r=s.altitudeDeg>0,a=r?s:n;if(a.altitudeDeg<=0)return this.messages.skyBowNoSource;const o=i.lowerCloudCover??i.cloudCover;if(bn.strength(i.precipitationIntensity,o,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const l=bn.formsAt(a.altitudeDeg);if(l.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(bn.primary().radiusDeg)));const h=this.listed(l.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(Hl(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=zi("Sun",e,t);if(i.altitudeDeg>g9)return;const s=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),n=[];if(s.milkyWay&&n.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(s.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(s.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(s.milkyWay.azimuthDeg))),s.zodiacal){const p=s.zodiacal.sunSeparationDeg<=jt.CONE_SEPARATION_DEG;n.push((p?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(s.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(s.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(s.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(s.zodiacal.sunSeparationDeg))))}if(n.length>0)return this.listed(n);const r=this.decimal(s.darkestSkyMagPerArcsec2,1),a=zi("Moon",e,t),o=s.darkestSkyMagPerArcsec2<v9,l=this.ufoElement.sighting.lightPollution,h=pe.scatteringAt(90-a.altitudeDeg)*pe.moonOutput(pe.phaseAngleOf(Hl(e).illuminatedFraction),a.altitudeDeg)*pe.scatteredFraction(90),d=pe.artificialZenithNanolamberts(l)>h;if(o&&a.altitudeDeg>0&&!d){const p=Math.round(Hl(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=pe.artificialZenithNanolamberts(l)>pe.twilightExcessNanolamberts(i.altitudeDeg);return o&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):o?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=zi("Sun",e,t),s=zi("Moon",e,t);return pe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(Hl(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new jt;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<Yf.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 s=sn(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=Yf.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.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 s=sn(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=$m.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(o=>o.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:s}=Mr(e,this.ufoElement.currentTime),n=Math.hypot(t,i);if(n===0&&s===0)return;const r=Math.atan2(t,i)*180/Math.PI,a=Math.atan2(s-c9,n)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(a*10)/10),this.updateObserver()}static DEFAULT_SAMPLE_MS=100;get samplingRate(){return this.ufoElement.sighting.sampleMs??_e.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return E1(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-sh.width/2,y:e.height/2-sh.height/2,width:sh.width,height:sh.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 d1(this.ufoElement.sighting.timeline,new m8(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t),this.recordButton.querySelector(".record-label")||this.recordButton.replaceChildren(Object.assign(document.createElement("span"),{className:"record-icon"}),Object.assign(document.createElement("span"),{className:"record-label"})),Ee.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=Sr.preferencesFor(this);this.preferences=t;const i=$u(t,Wu),s=this.narrativeProvider.localize?.(i),[n,r,a]=i==="en"?[gl,{},void 0]:await Promise.all([ME(i),U3(i),xE(i)]);if(await s,e!==this.localeToken)return;const o=i!==this.language;this.language=i,this.naming=new Wm(a),this.said=new rn(t),this.tagNames=new Xv(r),n!==this.messages?this.applyMessages(n):(this.paramSummaryBuilder=new oo(n,this.naming,this.said,this.tagNames,{messages:n,locale:this.language}),this.refreshParamSummary()),o?this.showSaidTexts():this.showTags()}preferences=[];language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===Wd&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.sourceSelect.setAttribute("aria-label",e.shape),this.shadow.getElementById("shape-empty").textContent=e.emptyShapes,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.shadow.getElementById("label-shape-rotation").textContent=e.shapeRotation,this.shapeRotationInput.title=e.shapeRotationTitle,this.labelSizeLock.textContent=e.sizeLock;for(const[s,n]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(s).textContent=n;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.samplingRateInput.placeholder=String(_e.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(_e.DEFAULT_SAMPLE_MS)),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.shadow.getElementById("label-account-compare").textContent=e.accountCompare,this.shadow.getElementById("account-compare-row").title=e.accountCompareHint;const t=this.shadow.getElementById("scene-resize");t&&(t.title=e.resizeScene,t.setAttribute("aria-label",e.resizeScene)),this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextDuplicateButton.textContent=e.duplicate,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.frozenPanel.localize(e),this.sectionFilePanel.localize(e),this.eventsPanel.localize(e.events),this.phenomenonEventsPanel.localize(e.events),this.bodiesEventsPanel.localize(e.events),this.shadow.getElementById("observer-identity-hint").textContent=e.identityHint,this.shadow.getElementById("identity-ask-initials").textContent=e.identityInitials,this.shadow.getElementById("identity-ask-keep").textContent=e.identityKeep,this.shadow.getElementById("identity-ask-back").textContent=e.identityBack,this.labelImportFile.textContent=e.importFile,this.shadow.getElementById("label-whole-keyframes").textContent=e.wholeKeyframes,this.wholeKeyframesInput.closest("label").title=e.wholeKeyframesHint,this.importInput.placeholder=e.importUrlPlaceholder;for(const s of this.shadow.querySelectorAll(hp))s.messages=e;this.labelObserverAge.textContent=e.observerAge,this.labelObserverBirth.textContent=e.observerBirth,this.perceptionSettings.labels=e.observerPerception,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,Hn.say(this.labelAccountUrl,e.accountUrl,e.accountUrlHint),this.labelAccountFollowedUp.textContent=e.accountFollowedUp,this.evaluationFields.messages=e.accountEvaluation;for(const[s,n]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const r=this.shadow.getElementById(s);r&&(r.textContent=n)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelPosition.textContent=e.positionLabel,this.observerPosition.messages=e,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.label("label-iso",e.iso),this.isoInput.title=e.isoTitle,this.label("label-metering",e.metering),this.meteringSelect.title=e.meteringTitle,this.label("metering-device",e.meteringDevice),this.label("metering-average",e.meteringAverage),this.label("metering-highlights",e.meteringHighlights),this.label("label-lens-glass",e.lensGlass),this.label("label-reference-ghosts",e.referenceGhosts),this.findGhostsButton.textContent=e.referenceFindGhosts,this.syncGhostsShown(),this.label("lens-glass-none",e.lensGlassNone),this.label("lens-glass-filter",e.lensGlassFilter),this.label("lens-glass-window",e.lensGlassWindow),this.label("lens-glass-windscreen",e.lensGlassWindscreen),this.label("label-lens-drops",e.lensDrops),this.lensDropsInput.title=e.lensDropsTitle,this.label("label-lens-condensation",e.lensCondensation),this.lensCondensationInput.title=e.lensCondensationTitle,this.label("label-lens-dirt",e.lensDirt),this.lensDirtInput.title=e.lensDirtTitle,this.label("label-lens-sheltered",e.lensSheltered),this.lensShelteredInput.title=e.lensShelteredTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.shapeAddMenu.panel.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"trafficlight",label:e.decorTrafficLight},{value:"crossing",label:e.decorCrossing},{value:"roadsign",label:e.decorRoadSign},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,empty:e.emptyDecor,actions:{"look-at-decor":e.lookAtDecor}}),this.labelSkyButtons(),this.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.observerList.setLabels({list:e.observerGroup,remove:e.deleteObserver,add:e.addObserver,actions:{"look-at-observer":e.lookAtDecor}}),this.refreshObserverList(),this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const i=this.shadow.getElementById("option-scenery-none");i&&(i.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote,this.shadow.getElementById("milestone-empty").textContent=e.emptyMilestones;for(const[s,n]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])s.title=n,s.setAttribute("aria-label",n);this.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup,this.labelLaunchesSubgroup.textContent=e.launchesSubgroup,this.labelBeamsSubgroup.textContent=e.beamsSubgroup,this.labelLanternsSubgroup.textContent=e.lanternsSubgroup;for(const s of["location","decor","weather"]){const n=this.shadow.getElementById(`${s}-settings-button`);n?.setAttribute("title",e.dataSources),n?.setAttribute("aria-label",e.dataSources);const r=this.shadow.getElementById(`label-${s}-settings`);r&&(r.textContent=e.dataSources)}this.bodyEditor?.setLanguage(this.language),this.launchEditor?.setLanguage(this.language),this.beamEditor?.setLanguage(this.language),this.lanternEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerTab,this.labelWeatherGroup.textContent=e.sky,this.fitGroupTabs(),this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new oo(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),this.refreshParamSummary(),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelRareIce.textContent=e.rareIceCrystals,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.referenceSelect.setAttribute("aria-label",e.reference),this.shadow.getElementById("reference-empty").textContent=e.emptyReferences,this.shadow.getElementById("reference-landmark-empty").textContent=e.emptyReferenceLandmarks,this.shadow.getElementById("trace-empty").textContent=e.emptyTraces,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSourceInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.setReferenceAddKinds(e.addReferenceUrl,e.addReferenceFile,e.referenceStreetSearch),this.addReferenceButton.title=e.addReference,this.addReferenceButton.setAttribute("aria-label",e.addReference),this.referenceAddMenu.panel.setAttribute("aria-label",e.addReference),this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.title=e.addReferenceLandmark,this.addReferenceLandmarkButton.setAttribute("aria-label",e.addReferenceLandmark),this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,Hn.say(this.labelTraceImport,e.traceImport,e.traceImportHint),this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=`${e.traceImport} (${e.traceImportHint})`,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[s,n]of this.soundKindOptions)n.textContent=this.soundKindLabel(s,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e)}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[s,n]of Object.entries(t))this.shadow.getElementById(`label-section-${s}`).textContent=n;this.sectionFolds.setMessages(e),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const s of["location-settings","decor-settings","weather-settings"])Vn.popover(this.shadow.getElementById(s),e.close);Vn.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),Vn.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),Vn.button(this.contextMenu,e.close,()=>this.hideContextMenu()),Vn.button(this.decorContextMenu,e.close,()=>this.hideDecorContextMenu()),this.shadow.getElementById("label-editor-kicker").textContent=e.editorKicker,this.shadow.getElementById("label-save").textContent=e.save,this.shareDialog.useLanguage(this.language).then(s=>{s&&(this.shareMessages=s,this.shadow.getElementById("label-share").textContent=s.share,this.refreshEditorHead())});const i={observation:e.panelIntroObservation,observer:e.panelIntroObserver,location:e.panelIntroLocation,temporal:e.panelIntroTemporal,decor:e.panelIntroDecor,weather:e.panelIntroWeather,shape:e.panelIntroShape,sound:e.panelIntroSound,reference:e.panelIntroReference,file:e.panelIntroFile};for(const[s,n]of Object.entries(i)){const r=this.shadow.querySelector(`[aria-controls="group-${s}"]`);r.dataset.intro=n,_e.titleGroupTab(r)}this.refreshEditorHead()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;if(!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)){const d=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;this.beginCameraDrag(t,u?.kind==="decor"?u.id:void 0,u?.kind==="body"?u.id:void 0)}return}const s=this.decorMoveAxis(e);if(i==="decor"&&s&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t,s))return;const n=this.ufoElement.sighting.timeline,r=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const d=new G0(this.selectedMembers()),u=Jt.hitTestHandle({bounds:d.bounds(),angle:0},t);if(u==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:d,startPointer:t},this.startDragListening();return}if(u){if(a)return;this.dragState={kind:"group-resize",group:d,handle:u},this.startDragListening();return}}else{const d=n.getInterpolatedShapeAt(r,this.currentSourceId),u=d?.kind==="polygon"?Jt.hitTestVertex(d,t):void 0;if(d?.kind==="polygon"&&u!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:d,vertexIndex:u},this.startDragListening();return}const p=d&&Jt.hitTestHandle(d,t);if(d&&p){if(a)return;this.beginDrag(p==="rotate"?"rotate":"resize",this.currentSourceId,d,t,p);return}}const l=this.ufoElement.shapeAt(t.x,t.y,Rf);if(!l){const d=s==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;if(u?.kind==="body"&&u.id!==void 0){a?this.showBody(u.id):this.beginCameraDrag(t,void 0,u.id);return}const p=u?.kind==="decor"?u.id:void 0;if(p!==void 0){a?(this.selectDecor(p),this.revealDecorPanel()):this.beginCameraDrag(t,p);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),this.flash(this.shapeTitleInput.closest("label")),e.shiftKey?this.toggleUnitSelection(l.sourceId):this.selectedSourceIds.has(l.sourceId)||this.selectUnit(l.sourceId),a||!o)return;const h=[...this.selectedSourceIds].map(d=>({sourceId:d,original:d===l.sourceId?l.shape:n.getInterpolatedShapeAt(r,d)??l.shape}));this.dragState={kind:"move",sources:h,startPointer:t},this.startDragListening()}showBody(e){if(this.fileSyncActive()){this.showInFile(this.bodyPath(e));return}this.revealShapePanel();const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-bodies");t&&this.openSubgroup(t),this.loadBodyEditor().then(i=>i.show(e))}revealDecorPanel(){if(this.fileSyncActive()){this.fileFocus="decor",this.syncCanvasMode();return}const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-decor");e&&this.toggleGroup(e,!0)}revealShapePanel(){if(this.fileSyncActive()){this.fileFocus="shape",this.syncCanvasMode();return}const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="shape"),this.refreshSourceList(),this.onSelectionOrTimeChanged(),this.showInFile(this.shapePath(e)))}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(n=>this.selectedSourceIds.has(n))){if(i.length>=this.selectedSourceIds.size)return;for(const n of i)this.selectedSourceIds.delete(n);if(!this.selectedSourceIds.has(this.currentSourceId)){const n=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,a)=>n.indexOf(r)-n.indexOf(a)).pop()}}else{for(const n of i)this.selectedSourceIds.add(n);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,s=this.ufoElement.currentTime,n=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(s,this.currentSourceId):void 0,a=n?.kind==="polygon"&&Jt.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,Rf);if(a){this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),this.currentSourceId=a.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const o=this.pickDecorAt(e),l=o?this.ufoElement.sighting.decor.find(h=>h.id===o):void 0;l&&this.showDecorContextMenu(e.clientX,e.clientY,l)}pickDecorAt(e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const s=(e.clientX-i.left)/i.width*2-1,n=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(s,n)}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,s=i.filter(p=>this.selectedSourceIds.has(p)),n=i.length<=s.length,r=s.length>0&&i.slice(i.length-s.length).every(p=>this.selectedSourceIds.has(p)),a=s.length>0&&i.slice(0,s.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=n||r,this.contextSendToBackButton.disabled=n||a,this.contextBringToFrontButton.title=n?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=n?this.messages.onlyOneShape:a?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const o=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!o,this.contextUngroupButton.title=o?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const l=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&l?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?Jt.hitTestVertex(l,this.contextMenuPoint):void 0,u=h&&l.points.length<=h2;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";const t=[...this.ufoElement.sighting.timeline.sourceIds],i=this.ufoElement.sighting.interpretation?.bodies??[];if(t.length===0&&i.length===0){const s=document.createElement("span");s.className="submenu-empty",s.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(s)}for(const s of t){const n=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=e.occludesSourceIds?.includes(s)??!1,r.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,s,r.checked)),n.appendChild(r),n.appendChild(document.createTextNode(this.shapeLabel(s))),this.contextMasksSubmenu.appendChild(n)}for(const s of i){const n=this.sceneElement.bodyMaskedBy(s.id,e.id);if(n===void 0)continue;const r=document.createElement("span");r.className="submenu-empty submenu-fact";const a=this.said.read(s.title)??s.id,o=this.messages;r.textContent=`${a} — ${n>=.995?o.masksBodyFully:n>.005?o.masksBodyPartly.replace("{share}",String(Math.round(n*100))):o.masksBodyNot}`,this.contextMasksSubmenu.appendChild(r)}}updateDecorOccludesShape(e,t,i){const s=this.ufoElement.sighting;s.decor=s.decor.map(n=>{if(n.id!==e)return n;const r=i?[...new Set([...n.occludesSourceIds??[],t])]:(n.occludesSourceIds??[]).filter(a=>a!==t);return{...n,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 s=Jt.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),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 s=Jt.hitTestVertex(i,e);if(s===void 0)return;const n=Jt.deleteVertex(i,s);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),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,s,n){this.dragState={kind:e,sourceId:t,original:i,handle:n,startPointer:s},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,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!s||!i)return!1;i.show(s);const n=i.readingNow(),r=this.skyDirectionOf(e);return!n||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:n.azimuthDeg,bodyAltitudeDeg:n.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 s=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+s,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(eE,(e.maxX-e.minX)/2*t.width),s=Math.max(eE,(e.maxY-e.minY)/2*t.height),n=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return{x:n-i/2,y:r-s/2,width:i,height:s}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),s=e.reading();if(!i||!s)return!1;const n=Jt.hitTestHandle({bounds:i,angle:0},t);if(!n)return!1;if(n==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...s.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:n,centre:r,startPointer:t,startSizeM:{...s.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(n,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:s,startPointer:n,startSizeM:r,handle:a}=t,o=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),l=a==="e"||a==="w",h=a==="n"||a==="s",d=l?o(i.x-s.x,n.x-s.x):h?o(i.y-s.y,n.y-s.y):o(Math.hypot(i.x-s.x,i.y-s.y),Math.hypot(n.x-s.x,n.y-s.y));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:l?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:wv};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.decorReading(),resize:e=>this.commitDecorBase(t=>{Object.assign(t,{sizeM:{widthM:this.roundedMeters(e.widthM),lengthM:this.roundedMeters(e.lengthM),heightM:this.roundedMeters(e.heightM)}})},"sizeM.widthM"),turnTo:e=>this.commitDecorBase(t=>{t.headingDeg=this.rounded((e.headingDeg%360+360)%360)},"headingDeg"),rotateDegPerPx:a9};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=ue.naturalSize(e.kind,e.floors);return{sizeM:{widthM:e.sizeM?.widthM??t.widthM??1,lengthM:e.sizeM?.lengthM??t.lengthM??1,heightM:e.sizeM?.heightM??t.heightM??1},attitude:{headingDeg:ta.viewOf(e,this.ufoElement.currentTime).headingDeg,pitchDeg:0,rollDeg:0}}}onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!s||!i||(e.preventDefault(),i.show(s),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorMoveAxis(e){if(!(e.metaKey||[e.shiftKey,e.altKey,e.ctrlKey].filter(Boolean).length>1))return e.shiftKey?"east":e.altKey?"north":e.ctrlKey?"up":"ground"}grabsDecor(e,t,i){const s=this.pickDecorAt(e);if(s===i.id)return!0;const n=this.decorCanvasBounds();return n!==void 0&&t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+n.height?s===void 0||this.ufoElement.sighting.decor.find(a=>a.id===s)?.kind==="terrace":!1}beginDecorDrag(e,t,i){const s=this.editableDecor();if(!s)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.ufoElement.shapeAt(t.x,t.y,Rf)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=ta.viewOf(this.placedByAuthor(s),this.ufoElement.currentTime),a=n?this.sceneElement.decorGrabHeightAt?.(s.id,n.x,n.y)??0:0,o=n&&this.sceneElement.decorGroundPointAt(s.id,n.x,n.y,a);return!n||!o?!1:(this.dragState={kind:"decor-move",id:s.id,startGround:o,grabHeightM:a,axis:i,startAltitudeM:r.altitudeM,startNdcY:n.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(s.id)??0,startEastM:r.eastM,startNorthM:r.northM},this.setCanvasCursor("move"),this.startDragListening(),!0)}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e);if(!i)return;const s=this.sceneElement.decorGroundPointAt(t.id,i.x,i.y,t.grabHeightM);!s&&t.axis!=="up"||this.commitDecorBase(n=>{s&&(t.axis==="ground"||t.axis==="east")&&(n.eastM=this.roundedMeters(t.startEastM+s.x-t.startGround.x)),s&&(t.axis==="ground"||t.axis==="north")&&(n.northM=this.roundedMeters(t.startNorthM-(s.z-t.startGround.z))),t.axis==="up"&&(n.altitudeM=this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))},"eastM")}beginCameraDrag(e,t,i){const s=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,pressedBodyId:i,moved:!1,startPointer:e,startHeadingDeg:s?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:s?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:s},s||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&Sl(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Sl(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:s,startPointer:n}=this.dragState,r=t.x-n.x,a=t.y-n.y,o=s.map(({sourceId:l,original:h})=>({sourceId:l,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+a}}}));this.commitShapes(i,o)}else if(this.dragState.kind==="group-resize"){const{group:s,handle:n}=this.dragState;this.commitShapes(i,s.resize(n,t))}else if(this.dragState.kind==="group-rotate"){const{group:s,startPointer:n}=this.dragState;this.commitShapes(i,s.rotate(t,n))}else if(this.dragState.kind==="vertex"){const{sourceId:s,original:n,vertexIndex:r}=this.dragState,a=Jt.moveVertex(n,r,t);this.commitShapes(i,[{sourceId:s,shape:a}])}else{const{kind:s,sourceId:n,original:r,handle:a}=this.dragState,o=s==="resize"?Jt.resizeShape(r,a,t):Jt.rotateShape(r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:s,startPitchDeg:n,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<o9)return;this.cameraDragState.moved=!0}const a=s+(t.x-i.x)*wv,o=Math.max(-90,Math.min(90,n-(t.y-i.y)*wv));if(r){this.indoorLookYawDeg=a,this.indoorLookPitchDeg=o,this.sceneElement.setIndoorLook(a,o),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}walkOrTurn(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing"||this.isObserverInsideDecor())return;const t=e.shiftKey?p9:1,i=this.numberOrUndefined(this.headingInput.value)??0;if(e.key==="ArrowLeft"||e.key==="ArrowRight"){this.headingInput.value=String(this.rounded(i+(e.key==="ArrowRight"?1:-1)*u9*t)),this.updateObserver();return}const s=this.numberOrUndefined(this.latInput.value),n=this.numberOrUndefined(this.lngInput.value);if(s===void 0||n===void 0)return;const r=(e.key==="ArrowUp"?1:-1)*d9*t,a=i*Math.PI/180,o=Wn(Math.sin(a)*r,-Math.cos(a)*r,s,n);this.latInput.value=o.lat.toFixed(7),this.lngInput.value=o.lng.toFixed(7);const l=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(l,this.plantingCentre()),this.surroundings.walked(o.lat,o.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=ut(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(o,l)=>Math.round((o-l)*1e3)/1e3,a=this.ufoElement.sighting;a.decor=a.decor.map(o=>({...o,eastM:r(o.eastM,s),northM:r(o.northM,n),...o.track?{track:o.track.map(l=>({...l,eastM:r(l.eastM,s),northM:r(l.northM,n)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ul,i.width-Ho);break;case"ArrowRight":i.width+=Ho;break;case"ArrowUp":i.height=Math.max(ul,i.height-Ho);break;case"ArrowDown":i.height+=Ho;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Ho;break;case"ArrowRight":i.x+=Ho;break;case"ArrowUp":i.y-=Ho;break;case"ArrowDown":i.y+=Ho;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:s,shape:n}=i[0];this.commitShapes(t,[{sourceId:s,shape:{...n,bounds:this.nudgeBounds(n.bounds,e)}}])}else{const s=new G0(i),n=this.nudgeBounds(s.bounds(),e);this.commitShapes(t,s.scaleTo(n))}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(),s=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const o=r?this.bodyCanvasBounds():void 0,l=o&&Jt.hitTestHandle({bounds:o,angle:0},t);if(l)return this.cursorForHandle(l,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const o=this.decorCanvasBounds(),l=o&&Jt.hitTestHandle({bounds:o,angle:0},t);if(l)return this.cursorForHandle(l,0);const h=this.editableDecor();if(h&&!this.ufoElement.shapeAt(t.x,t.y,Rf)&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const o=Jt.hitTestHandle({bounds:new G0(this.selectedMembers()).bounds(),angle:0},t);if(o)return this.cursorForHandle(o,0)}else{const o=s.getInterpolatedShapeAt(n,this.currentSourceId);if(o?.kind==="polygon"&&Jt.hitTestVertex(o,t)!==void 0)return"vertex";const l=o&&Jt.hitTestHandle(o,t);if(o&&l)return this.cursorForHandle(l,o.angle)}return s.hitTest(n,t.x,t.y)?r&&a?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${Jt.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(),s=e.clientX-i.left,n=e.clientY-i.top;this.recorder?.onPointerMove(s,n),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(cE(this.buildPrototype({x:0,y:0,width:sh.width,height:sh.height}),s,n))}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 b9={measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},nE="rr0-sighting-editor",rE="rr0-ufo-recorder";class y9 extends _e{}function sT(){SE(),vy(),QA(),w8(),b8(),E8(),f0(),customElements.get(nE)||customElements.define(nE,_e),customElements.get(rE)||customElements.define(rE,y9)}const ny={event:"Event",accountOf:"Observation of",passagesHeading:"Reported in",interviewOf:"Interview of",untitledInterview:"Interview {n}",deleteInterviewQuestion:"Delete this interview from the case? Nothing is written until the case is saved.",untitledReading:"Reading {n}",eventsInTime:"Events · in the order of time",citedMoment:"Moment {k}, quoted in {title}: “{quote}”",backToInterview:"Back to the interview",openEvent:"Open",previousEvent:"Previous event",nextEvent:"Next event",kindReading:"Reading",readingsCount:"{n} reading(s)",untitledObservation:"Observation {n}",deleteRecording:"Delete this recording from the case",deleteReadingQuestion:"Delete this reading? Nothing is written until the case is saved.",deleteObservationQuestion:"Delete this observation from the case? Nothing is written until the case is saved.",deleteRefused:"This observation is interpreted by {n} reading(s): delete them first.",titleField:"Title of the interpretation",authorField:"Author",addTitle:"Add an event",kindField:"Type",kindObservation:"Observation",kindInterview:"Interview",witnessField:"Witness",mediumField:"Medium",interviewerField:"Interviewer",plainTitleField:"Title",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"An existing recording",observerField:"Observer",fileField:"File",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",recordingId:"ID",idTaken:"Another recording of the case has this ID.",idInvalid:"An ID is made of letters, digits, hyphens and underscores, and starts with a letter or a digit.",idNeeded:"A reading names this recording by its ID: it cannot be left empty.",idDuplicated:"Two events of the case have the ID “{id}”: a reading that names it is ambiguous.",readingUnresolved:"A reading names “{id}”, which no event of the case has as its ID, nor any recording it lists.",caseTitle:"Title",caseTime:"When",eventsTab:"Events",fileTab:"File",importFile:"Load case file",inputFileFromFile:"from your disk",inputFileFromUrl:"from an address",inputFileModeHint:"Click to give it the other way: a file of yours, or an address",inputFileLoad:"Load",fileNotACase:"That file is not a case (it has no events).",formatVersionError:"This file states version {found} of its format; this UFO@home reads up to version {supported}. Open it with a newer UFO@home.",fileInvalid:"This text is not valid JSON yet, or not a case: the case keeps what it last understood.",fileLoading:"Loading the editor…",add:"Add",addHint:"Add an event",interpretationOf:"Interpretation of",interpretationOfNone:"—",exportButton:"Save",exportTitle:"Save the case",exportAlso:"Also save the observations",addToCase:"Add to a case",unsavedChanges:"Changes not saved",discardQuestion:"Some changes are not saved yet. Load anyway and lose them?",discardTitle:"Unsaved changes",discardOk:"Load anyway",leaveQuestion:"Some changes are not saved yet. Leave anyway and lose them?",leaveOk:"Leave anyway"},w9=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:ny},Symbol.toStringTag,{value:"Module"})),aE="rr0-case-editor",M9=`
|
|
11573
|
+
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await oe(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-BA3zFrn5.js");return{ModelThumbnails:i}},__vite__mapDeps([13,14]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const s=document.createElement("button");s.type="button",s.className="model-picker-button",e.after(s),e.hidden=!0;let n=0,r;const a=()=>{const l=++n,h=e.selectedOptions[0],d=e.value===""?i?.current():void 0,u=JSON.stringify([e.value,h?.textContent,d?.url,d?.title,this.messages().choose,[...e.options].map(m=>m.value).join()]);if(u===r){--n;return}r=u,s.replaceChildren();const p=document.createElement("span");p.textContent=`${d?d.title||d.url:h?.textContent??""} …`,s.title=this.messages().choose,s.append(p);const f=e.value;(d?Promise.resolve({url:d.url}):t(f)).then(m=>yu.pictureOf(m)).then(m=>{if(!m||l!==n)return;const v=new Image;v.src=m,v.alt="",s.prepend(v)})};e.addEventListener("change",a),new MutationObserver(a).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:l=>{i.apply(l),a()}};s.addEventListener("click",()=>void this.open(e,t,o)),a()}chooseFrom(e,t,i,s){this.ensureStyle(),this.open(e,t,s,i)}ensureStyle(){const e=this.root instanceof ShadowRoot?this.root:this.root.getRootNode(),t=e instanceof ShadowRoot?e:document.head;if(t.querySelector("style[data-model-picker]"))return;const i=document.createElement("style");i.dataset.modelPicker="",i.textContent=yu.STYLE,t.append(i)}open(e,t,i,s){const n=this.messages(),r=document.createElement("div");r.className="model-picker-backdrop";const a=document.createElement("div");a.className="model-picker",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=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.innerHTML=Ee.CLOSE;const h=document.createElement("header");h.append(o,l);const d=document.createElement("div");d.className="model-picker-body",a.append(h,d),r.append(a);const u=()=>{r.remove(),document.removeEventListener("keydown",p,!0),oe(async()=>{const{ModelViewer:E}=await import("./ModelViewer-BDorZEms.js");return{ModelViewer:E}},__vite__mapDeps([15,14]),import.meta.url).then(({ModelViewer:E})=>E.end())},p=E=>{E.key==="Escape"&&(E.stopPropagation(),u())},f=i?.current(),m="\0address",v=E=>E===m&&f?Promise.resolve({url:f.url}):t(E),g=E=>{if(u(),s){E!==m&&s(E);return}E===m||E===e.value||(e.value=E,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const w=new Map,y=E=>{const x=document.createElement("button");x.type="button",x.className="model-card",x.dataset.value=E.value,x.setAttribute("aria-pressed",String(!s&&(E.value===m||E.value===e.value&&!f)));const A=document.createElement("div");A.className="model-thumb";const D=document.createElement("span");if(D.className="model-name",D.textContent=E.textContent,x.append(A,D),E.title){const C=document.createElement("span");C.className="model-credit",C.textContent=E.title,x.append(C)}v(E.value).then(C=>yu.pictureOf(C)).then(C=>{if(!C)return;const P=new Image;P.src=C,P.alt="",A.append(P)});let R,L=!1;const N=()=>{L&&!(R&&!R.active)||(L=!0,Promise.all([v(E.value),oe(()=>import("./ModelViewer-BDorZEms.js"),__vite__mapDeps([15,14]),import.meta.url)]).then(([C,{ModelViewer:P}])=>{!C||!L||(R=P.show(A,C))}).catch(()=>{}))},k=()=>{L=!1,R?.stop(),R=void 0};return w.set(x,N),x.addEventListener("pointerenter",N),x.addEventListener("focus",N),x.addEventListener("pointerleave",()=>{document.activeElement!==x&&k()}),x.addEventListener("blur",k),x.addEventListener("click",C=>{if(R?.consumeDrag()){C.preventDefault();return}g(E.value)}),x},M=()=>(b=document.createElement("div"),b.className="model-picker-grid",d.append(b),b);if(f){const E=new Option(f.title||f.url,m);E.title=[f.author,f.license].filter(Boolean).join(" — "),M().append(y(E))}for(const E of Array.from(e.children))if(E instanceof HTMLOptGroupElement){const x=document.createElement("h3");x.textContent=E.label,d.append(x);const A=M();for(const D of Array.from(E.children))A.append(y(D));b=void 0}else E instanceof HTMLOptionElement&&(b??M()).append(y(E));i&&this.addAddressForm(h,l,a,d,i,n,u),l.addEventListener("click",u),r.addEventListener("click",E=>{E.target===r&&u()}),document.addEventListener("keydown",p,!0),this.root.append(r);const S=a.querySelector('.model-card[aria-pressed="true"]');(S??l).focus(),S&&w.get(S)?.()}addAddressForm(e,t,i,s,n,r,a){const o=document.createElement("button");o.type="button",o.className="model-picker-add",o.textContent="+",o.title=r.address,o.setAttribute("aria-label",r.address),o.setAttribute("aria-expanded","false"),e.insertBefore(o,t);const l=document.createElement("form");l.className="model-picker-address",l.hidden=!0;const h=(w,y,M="")=>{const S=document.createElement("label"),E=document.createElement("span");E.textContent=w;const x=document.createElement("input");return x.type=y,x.placeholder=M,S.append(E,x),l.append(S),x},d=h(r.addressUrl,"url","https://…/model.glb"),u=h(r.addressName,"text"),p=h(r.addressAuthor,"text"),f=h(r.addressLicense,"text","CC0 1.0"),m=h(r.addressSource,"url","https://…"),v=document.createElement("p");v.textContent=r.addressIncomplete;const g=document.createElement("button");g.type="submit",g.className="model-picker-use",g.textContent=r.addressUse,l.append(v,g),i.insertBefore(l,s);const b=()=>{g.disabled=d.value.trim()==="",v.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const w of[d,u,p,f,m])w.addEventListener("input",b);o.addEventListener("click",()=>{const w=l.hidden;if(l.hidden=!w,o.setAttribute("aria-expanded",String(w)),!w)return;const y=n.current();d.value=y?.url??"",u.value=y?.title??"",p.value=y?.author??"",f.value=y?.license??"",m.value=y?.source??"",b(),d.focus()}),l.addEventListener("submit",w=>{w.preventDefault(),d.value.trim()!==""&&(n.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:m.value.trim()}),a())}),b()}}class p1{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=p1.SPAN_DEG;try{const n=(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(n)?n:void 0}catch{return}}}class Z8{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),s=this.zoneOffsetHours(e,new Date(i));if(s!==void 0)return this.zoneOffsetHours(e,new Date(i-s*36e5))??s}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 s=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",n=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(s);if(n)return n[1]?(n[1]==="-"?-1:1)*(Number(n[2])+Number(n[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(s=>this.offsetHoursAt(s,i)===e)}}class Bn{static STEP_MS=100;static plan(e){const t=Bn.routeOf(e),i=ri.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const a=(l,h,d,u)=>{if(Math.abs(l.radiusM-u)>=u*.1)return!1;const{x:p,z:f}=ut(h,d,l.lat,l.lng);return Math.hypot(p,f)<ri.rebuildDistanceFor(u)};for(let l=0;;l=Math.min(s,l+Bn.STEP_MS)){const h=st(e,l);if(h?.lat!==void 0&&h.lng!==void 0){const d=Math.max(ri.groundRadiusFor(h.elevationM??0),i);(!r||!a(r,h.lat,h.lng,d))&&(r=n.find(u=>a(u,h.lat,h.lng,d)),r||n.push(r={lat:h.lat,lng:h.lng,radiusM:d}))}if(l>=s)break}const o=e.skyEvents?.beams??[];if(o.length>0)for(const l of[...n])ri.needsFarRing(l.radiusM,0,ri.beamReachFor(o,l))&&n.push({lat:l.lat,lng:l.lng,radiusM:ri.FAR_RING_RADIUS_M,far:!0});return n}static routeOf(e){const t=e.observerTrack.allKeyframes.flatMap(i=>i.pose.lat!==void 0&&i.pose.lng!==void 0?[{lat:i.pose.lat,lng:i.pose.lng}]:[]);return t.length>=2?t:void 0}static async freeze(e,t,i,s,n){const r=new Date().toISOString().slice(0,10),a=o=>n?.(o,i.length);switch(e){case"relief":{const o=Bn.routeOf(t),l=[];for(const[u,p]of i.entries()){try{const f=await s.elevation.getElevationGrid(Kn.boundsOf(p),{width:Om,height:Om},{route:o});l.push({...p,grid:f})}catch(f){console.warn("Relief not frozen for a patch:",f)}a(u+1)}if(l.length===0)return;const h=s.elevationCredit;return{bytes:await cp.encode({takenOn:r,attribution:h,patches:l}),attribution:h,takenOn:r,answered:l.length,patches:i.length}}case"imagery":{const o=new OS,l=ds(fc,s.imagery),h=l.create(o.fetch);let d=0;for(const[f,m]of i.entries()){try{await h.getImageryTexture(Kn.boundsOf(m),{width:Pm,height:Pm}),d++}catch(v){console.warn("Imagery not frozen for a patch:",v)}a(f+1)}if(o.tiles.size===0)return;const u=h.attribution;return{bytes:await Hm.encode({takenOn:r,source:l.id,attribution:u,patches:[...i],tiles:o.tiles}),attribution:u,takenOn:r,answered:d,patches:i.length}}case"roads":return Bn.vector(s.roads,i,r,a,(o,l)=>o.getRoads(l),o=>o.contemporary);case"water":return Bn.vector(s.water,i,r,a,(o,l)=>o.getWater(l));case"railways":return Bn.vector(s.railways,i,r,a,(o,l)=>o.getRailways(l),o=>o.contemporary)}}static mapGround(e){const t=oc.of(e);return t&&hi.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=Bn.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new OS,r=ds(fc,t),a=r.create(n.fetch),o=hi.IMAGERY_PX;try{await a.getImageryTexture(i,{width:o,height:o})}catch(d){console.warn("Map imagery not frozen:",d);return}const l=a.attribution;return{bytes:await Hm.encode({takenOn:s,source:r.id,attribution:l,patches:[],map:{bounds:i,pixels:o},tiles:n.tiles}),attribution:l,takenOn:s,answered:1,patches:1}}static async vector(e,t,i,s,n,r){if(!e)return;const a=[];for(const[h,d]of t.entries()){if(d.radiusM<=ri.ROADS_MAX_RADIUS_M)try{a.push({...d,items:await n(e,Kn.boundsOf(d))})}catch(u){console.warn("Not frozen for a patch:",u)}s(h+1)}if(a.length===0)return;const o={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:a};return{bytes:new TextEncoder().encode(JSON.stringify(o)),attribution:e.attribution,takenOn:i,answered:a.length,patches:t.length}}}class ss{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.replace(this.shown,i.detail)),this.root.querySelector("#frozen-refresh").addEventListener("click",()=>void this.refresh(this.shown)),this.root.querySelector("#annex-export").addEventListener("click",()=>void this.exportAnnex(this.shown))}messages;busy=!1;shown="relief";editor;editorFor;editTimer;get sourceInput(){return this.root.querySelector("#annex-source")}get editorHost(){return this.root.querySelector("#annex-editor")}get note(){return this.root.querySelector("#frozen-note")}localize(e){this.messages=e,this.root.title=e.frozenHint;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-annex-source",e.annexSource),t("frozen-refresh",e.frozenRefresh),t("annex-export",e.export),this.sourceInput.messages=e,this.render()}itemLabel(e){return this.groupName(e)}where(e){const t=this.annex(e);return this.isLive(e)?this.messages.frozenLiveState:!t||t.refresh?this.messages.frozenPending:ss.isInline(t.src)?this.messages.annexStorageInline:t.src}isInlineGroup(e){const t=this.annex(e);return t!==void 0&&!this.isLive(e)&&ss.isInline(t.src)}annex(e){const t=this.host.sighting().frozen?.[e];return t?.src!==void 0?t:void 0}isLive(e){return ts.isLive(this.host.sighting().frozen,e)}setLive(e,t){if(this.isLive(e)===t)return;const i={...this.host.sighting().frozen??{}};if(i.live){delete i.live;for(const n of ts.NAMES)i[n]={...i[n]??{},live:!0}}const s={...i[e]??{}};t?s.live=!0:delete s.live,i[e]=Object.keys(s).length>0?s:void 0,this.setFrozen(i)}show(e){this.shown=e,this.render()}render(){if(!this.messages)return;const e=this.shown,t=this.isLive(e),i=this.annex(e),s=this.root.querySelector("#frozen-state");s.textContent=t?this.messages.frozenLiveState:i&&!i.refresh?[this.messages.frozenTakenOn.replaceAll("{date}",i.takenOn??"?"),i.attribution].filter(Boolean).join(" · "):this.messages.frozenPending;const n=this.root.querySelector("#frozen-refresh");n.disabled=this.busy||t;const r=i!==void 0&&!i.refresh&&!t,a=r&&ss.isInline(i.src);this.sourceInput.url=r?a?this.host.masterUrl():this.address(i.src):"",r||(this.sourceInput.mode="file"),this.sourceInput.disabled=this.busy||t,this.root.querySelector("#annex-export").disabled=i===void 0||this.busy,this.renderEditor(r&&!a?i:void 0)}async renderEditor(e){const t=this.shown,i=e&&!ss.isZip(t)?await this.textOf(e).catch(()=>{}):void 0;if(t!==this.shown||(this.editorHost.hidden=i===void 0,i===void 0))return;const s=`${t}|${e.src}`;if(this.editor&&this.editorFor===s)return;if(this.editorFor=s,this.editor){this.editor.replaceText(i,!1);return}const{SightingFileEditor:n}=await oe(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-BekK-f3R.js");return{SightingFileEditor:r}},__vite__mapDeps([16,1,17]),import.meta.url);this.editor??=new n(this.editorHost,i,r=>this.edited(r),this.messages.annexEditorLabel,{schema:{},phrases:this.messages.fileSearchPhrases})}async textOf(e){return JSON.stringify(JSON.parse(new TextDecoder().decode(await this.bytesOf(e))),null,1)}edited(e){const t=this.shown;clearTimeout(this.editTimer),this.editTimer=setTimeout(()=>{let i;try{i=JSON.parse(e)}catch{return}this.write(t,new TextEncoder().encode(JSON.stringify(i)),{keepEditor:!0})},600)}async replace(e,t){if(t.url){if(this.address(t.url)===new URL(this.host.masterUrl(),location.href).href){await this.setStorage(e,!0);return}const s={...this.host.sighting().frozen??{}};let n;try{n=await this.bytesAt(t.url)}catch{n=void 0}if(n!==void 0)try{s[e]={src:t.url,...await ss.describe(e,n)}}catch{Xt.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){Xt.show(this.note,this.messages.frozenMissing.replaceAll("{file}",t.url),"warning");return}Ct.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}Xt.show(this.note,void 0),this.setFrozen(s);return}const{InputFileElement:i}=await oe(async()=>{const{InputFileElement:s}=await Promise.resolve().then(()=>eT);return{InputFileElement:s}},void 0,import.meta.url);await this.write(e,await i.bytesOf(t))}async write(e,t,i={}){const s={...this.host.sighting().frozen??{}},n=this.annex(e);let r;try{r=await ss.describe(e,t)}catch{Xt.show(this.note,this.messages.annexUnreadable,"warning");return}const a=n!==void 0&&ss.isInline(n.src),o=a?ss.dataUrl(e,t):n?.src??ts.annexName(this.host.base(),e);a||Ct.hold(this.address(o),t),s[e]={...s[e]?.live?{live:!0}:{},src:o,...r},Xt.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${o}`),this.setFrozen(s)}async setStorage(e,t){const i={...this.host.sighting().frozen??{}},s=this.annex(e);if(!s||ss.isInline(s.src)===t)return;const n=await this.bytesOf(s);let r;t?r=ss.dataUrl(e,n):(r=ts.annexName(this.host.base(),e),Ct.hold(this.address(r),n)),i[e]={...s,src:r},this.editorFor=`${e}|${r}`,this.setFrozen(i)}async exportAnnex(e){const t=this.annex(e);if(!t)return;const i=await this.bytesOf(t),s=ss.isInline(t.src)?ts.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:ss.isZip(e)?"application/zip":"application/json"}),s)}static async describe(e,t){let i;if(ss.isZip(e)){const{unzipSync:s}=await oe(async()=>{const{unzipSync:n}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:n}},[],import.meta.url);i=JSON.parse(new TextDecoder().decode(s(t)["index.json"]))}else i=JSON.parse(new TextDecoder().decode(t));if(typeof i!="object"||i===null)throw new Error("Not an annex");return{takenOn:typeof i.takenOn=="string"?i.takenOn:void 0,attribution:typeof i.attribution=="string"?i.attribution:void 0}}async bytesAt(e){return Ct.bytes(this.address(e))}static isInline(e){return e.startsWith("data:")}static isZip(e){return e==="relief"||e==="imagery"||e==="map"}static dataUrl(e,t){let i="";for(let s=0;s<t.length;s+=32768)i+=String.fromCharCode(...t.subarray(s,s+32768));return`data:${ss.isZip(e)?"application/zip":"application/json"};base64,${btoa(i)}`}async refresh(e){if(this.busy)return;const t={...this.host.sighting().frozen??{}};if(e==="upperAir"){const i=t.upperAir;i&&(t.upperAir={...i,refresh:!0}),this.setFrozen(t);return}this.busy=!0,this.render();try{const i=t[e]?.src,s=(i&&!ss.isInline(i)?ss.baseOf(i):void 0)??this.host.base();(e==="map"?await this.takeMap(t,this.host.sources(),s):await this.take(e,t,Bn.plan(this.host.sighting()),this.host.sources(),s))?Xt.show(this.note,void 0):Xt.show(this.note,this.messages.frozenFailed.replaceAll("{group}",this.groupName(e)),"warning")}finally{this.busy=!1}this.setFrozen(t)}hasWork(){const e=this.host.sighting();return ts.isEmpty(e.frozen)?this.host.upperAirHeard()!==void 0||Bn.plan(e).length>0:!0}async prepare(e){const t=this.host.sighting(),i={...t.frozen??{}},s=new Map;this.busy=!0,this.render();try{const n=d=>ts.isLive(i,d),r=d=>i[d]?.src!==void 0?i[d]:void 0;for(const d of ts.NAMES)!i.live&&i[d]?.live&&(i[d]={live:!0});const a=Bn.plan(t);let o;for(const d of ts.TERRAIN){if(n(d))continue;const u=r(d);if(a.length>0&&(!u||u.refresh||!await this.fits(d,u,a))&&await this.take(d,i,a,o??=this.host.sources(),e)){await this.keep(r(d),s);continue}u?.refresh&&(i[d]={...u,refresh:void 0}),r(d)&&await this.keep(r(d),s)}if(!n("map")){const d=r("map");Bn.mapGround(t)!==void 0&&(!d||d.refresh||!await this.fitsMap(d))&&await this.takeMap(i,o??=this.host.sources(),e)?await this.keep(r("map"),s):d&&(d.refresh&&(i.map={...d,refresh:void 0}),await this.keep(r("map"),s))}const l=this.host.upperAirHeard(),h=r("upperAir");if(!n("upperAir")&&l&&(!h||h.refresh)){const d=new Date().toISOString().slice(0,10),u={version:1,takenOn:d,attribution:l.answer.source.name,answers:[l]},p=new TextEncoder().encode(JSON.stringify(u)),f=this.place("upperAir",h?.src,e,p);i.upperAir={src:f,takenOn:d,attribution:l.answer.source.name},ss.isInline(f)||s.set(f,p)}else h&&!n("upperAir")&&(h.refresh&&(i.upperAir={...h,refresh:void 0}),await this.keep(r("upperAir"),s))}finally{this.busy=!1}return this.setFrozen(i),s}async take(e,t,i,s,n){const r=this.groupName(e),a=await Bn.freeze(e,this.host.sighting(),i,s,(o,l)=>Xt.show(this.note,this.messages.frozenTaking.replaceAll("{group}",r).replaceAll("{done}",String(o)).replaceAll("{of}",String(l))));return Xt.show(this.note,void 0),a?(t[e]={src:this.place(e,t[e]?.src,n,a.bytes),takenOn:a.takenOn,attribution:a.attribution},!0):!1}async takeMap(e,t,i){Xt.show(this.note,this.messages.frozenTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await Bn.freezeMap(this.host.sighting(),t.imagery);return Xt.show(this.note,void 0),s?(e.map={src:this.place("map",e.map?.src,i,s.bytes),takenOn:s.takenOn,attribution:s.attribution},!0):!1}async fitsMap(e){const t=Bn.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await Ct.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&Kn.sameBounds(i.map.bounds,t)}catch{return!1}}async fits(e,t,i){try{const s=this.address(t.src),n=t.src.endsWith(".zip")?JSON.parse(new TextDecoder().decode((await Ct.zip(s))["index.json"])).patches:(await Ct.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(a=>a.radiusM<=ri.ROADS_MAX_RADIUS_M);return Kn.samePatches(n.map(({lat:a,lng:o,radiusM:l})=>({lat:a,lng:o,radiusM:l})),r)}catch{return!1}}place(e,t,i,s){if(t!==void 0&&ss.isInline(t))return ss.dataUrl(e,s);const n=t??ts.annexName(i,e);return Ct.hold(this.address(n),s),n}async keep(e,t){if(!ss.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{Xt.show(this.note,this.messages.frozenMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return Ct.bytes(this.address(e.src))}address(e){return Ct.address(e,this.host.documentUrl())}setFrozen(e){for(const t of ts.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().frozen=ts.isEmpty(e)?void 0:e,this.render(),this.host.changed()}destroy(){clearTimeout(this.editTimer),this.editor?.destroy(),this.editor=void 0,this.editorFor=void 0}static baseOf(e){return e?.match(/^(.*)\.[a-z-]+\.(zip|json)$/)?.[1]}static size(e){return e<1e6?`${Math.max(1,Math.round(e/1e3))} kB`:`${(e/1e6).toFixed(1)} MB`}groupName(e){return{relief:this.messages.frozenRelief,imagery:this.messages.frozenImagery,roads:this.messages.frozenRoads,water:this.messages.frozenWater,railways:this.messages.frozenRailways,upperAir:this.messages.frozenUpperAir,map:this.messages.frozenMap}[e]}}class jm{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.take(this.shown,i.detail)),this.root.querySelector("#section-annex-export").addEventListener("click",()=>this.exportAnnex(this.shown))}messages;shown="weather";get sourceInput(){return this.root.querySelector("#section-annex-source")}get note(){return this.root.querySelector("#section-annex-note")}localize(e){this.messages=e;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-section-annex-source",e.annexSource),t("section-annex-export",e.export),this.sourceInput.messages=e,this.render()}show(e){this.shown=e,Xt.show(this.note,void 0),this.render()}srcOf(e){return this.host.sighting().frozen?.[e]?.src}itemLabel(e){return{weather:this.messages.fileItemWeather,place:this.messages.fileItemPlace,lightPollution:this.messages.fileItemLightPollution,decor:this.messages.fileItemDecor}[e]}where(e){return this.srcOf(e)??this.messages.annexStorageInline}isInline(e){return this.srcOf(e)===void 0}static pathOf(e){return[Ns.KEYS[e][0]]}render(){if(!this.messages)return;const e=this.srcOf(this.shown);this.sourceInput.url=e?this.resolve(e):this.host.masterUrl(),this.root.querySelector("#section-annex-state").textContent=this.state(this.shown)}state(e){const t=this.host.sighting();switch(e){case"weather":return t.weatherSource?.name??this.messages.weatherStatedByObserver;case"place":return t.event.place?.[0]?.name??"";case"lightPollution":return t.provenance.at("lightPollution")?.rationale??(t.lightPollution===void 0?"":String(t.lightPollution));case"decor":return""}}setStorage(e,t){const i={...this.host.sighting().frozen??{}};if(t===(i[e]?.src===void 0))return;const{src:s,...n}=i[e]??{};i[e]=t?n:{...n,src:Ns.annexName(this.host.base(),e)},this.write(e,i)}annex(e){const t=this.srcOf(e);return t===void 0?void 0:{src:t,bytes:this.bytesOf(e)}}bytesOf(e){const t=um(this.host.sighting()),i={version:il.CURRENT.sighting};for(const s of Ns.KEYS[e])t[s]!==void 0&&(i[s]=t[s]);return new TextEncoder().encode(JSON.stringify(i))}resolve(e){return new URL(e,this.host.documentUrl()??location.href).href}exportAnnex(e){const t=this.srcOf(e)??Ns.annexName(this.host.base(),e);this.host.download(new Blob([this.bytesOf(e)],{type:"application/json"}),decodeURIComponent(t.split("/").pop()??t))}async take(e,t){if(t.url&&this.resolve(t.url)===this.resolve(this.host.masterUrl())){this.setStorage(e,!0);return}if(t.url)try{await fetch(this.resolve(t.url),{method:"HEAD"}).then(o=>{if(!o.ok)throw new Error(String(o.status))})}catch{const o={...this.host.sighting().frozen??{}};o[e]={...o[e]??{},src:t.url},Xt.show(this.note,void 0),this.write(e,o);return}let i;try{const{InputFileElement:o}=await oe(async()=>{const{InputFileElement:h}=await Promise.resolve().then(()=>eT);return{InputFileElement:h}},void 0,import.meta.url),l=await o.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=Ui.toCurrent(JSON.parse(new TextDecoder().decode(l))),typeof i!="object"||i===null||Ns.KEYS[e].every(h=>i[h]===void 0))throw new Error("Not this section")}catch{Xt.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...um(s)};for(const o of Ns.KEYS[e])n[o]=i[o];const r=ky(n);jm.copy(e,r,s);const a={...s.frozen??{}};t.url?a[e]={...a[e]??{},src:t.url}:a[e]=a[e]??{},Xt.show(this.note,void 0),this.write(e,a)}write(e,t){this.host.sighting().frozen=ts.isEmpty(t)?void 0:t,this.render(),this.host.changed(e)}static copy(e,t,i){switch(e){case"weather":i.weatherTrack.clear();for(const s of t.weatherTrack.allKeyframes)i.weatherTrack.addKeyframe(s.t,s.weather);i.weatherSource=t.weatherSource;break;case"place":i.event.place=t.event.place;break;case"lightPollution":i.lightPollution=t.lightPollution;break;case"decor":i.decor=t.decor;break}for(const s of Ns.KEYS[e]){i.provenance.clear(s);for(const n of t.provenance.paths())(n===s||n.startsWith(`${s}.`))&&i.provenance.set(n,t.provenance.at(n))}}}class J8{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 s=await fetch(i.toString());if(!s.ok)return;const n=await s.json();return n.timezone&&n.timezone!=="GMT"?n.timezone:void 0}catch{return}}}const Q8=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new J8}],e9=["appearance","movement","incongruity","detection","close","beings","traces"];class yv{static OCCUPATIONS={student:!0,worker:!0,farmer:!0,homemaker:!0,merchant:!0,business:!0,employee:!0,artist:!0,technician:!0,police:!0,pilot:!0,military:!0};static RELATIONS=["friends","family","professional","none"];static ACTIVITIES=["leisure","travelling","cultural","working"]}class cs{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=cs.select("observerOccupationKind");graduate=cs.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=cs.select("observersRelation");activity=cs.select("observerActivity");factors=new Map(e9.map(e=>[e,cs.select(`strangeness-${e}`)]));labels=new Map;unit=document.createTextNode(" min");strangenessTitle=document.createElement("span");strangenessIntro=Object.assign(document.createElement("p"),{className:"section-intro"});wording;constructor(e,t,i,s){Hn.register(),e.append(this.label(this.occupationKind,h=>[h.occupationKind,h.occupationKindHint]),this.label(this.graduate,h=>[h.graduate]));const n=this.label(this.enquiryMinutes,h=>[h.enquiryMinutes,h.enquiryMinutesHint]);n.append(this.unit);const r=t.querySelector("#accountSource")?.closest("label");r?r.after(n):t.append(n),t.append(this.label(this.relation,h=>[h.relation]),this.label(this.activity,h=>[h.activity]));const a=Object.assign(document.createElement("h3"),{className:"section-title"});a.append(this.strangenessTitle),i.append(a,this.strangenessIntro,...[...this.factors].map(([h,d])=>this.label(d,u=>[u.factors[h],u.factorHints[h]])));const o=[["yes","yes"],["no","no"]],l=h=>h.map(d=>[d,d]);cs.choices(this.occupationKind,"",l(Object.keys(yv.OCCUPATIONS))),cs.choices(this.graduate,"",o),cs.choices(this.relation,"",l(yv.RELATIONS)),cs.choices(this.activity,"",l(yv.ACTIVITIES));for(const h of this.factors.values())cs.choices(h,"",o);for(const h of[this.occupationKind,this.graduate,this.enquiryMinutes,this.relation,this.activity,...this.factors.values()])h.addEventListener("change",s)}set messages(e){this.wording=e;for(const t of this.labels.values())t();this.unit.textContent=` ${e.minutes}`,this.strangenessTitle.textContent=e.strangenessSection,this.strangenessIntro.textContent=e.strangenessIntro,cs.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),cs.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),cs.choices(this.relation,e.unknown,Object.entries(e.relations)),cs.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)cs.choices(i,cs.READ_FROM_RECORDING.includes(t)?e.fromRecording:e.unknown,[["yes",e.yes],["no",e.no]])}show(e){this.occupationKind.value=e?.observerOccupationKind??"",this.graduate.value=cs.yesNo(e?.observerGraduate),this.enquiryMinutes.value=e?.enquiryMinutes?.toString()??"",this.relation.value=e?.observersRelation??"",this.activity.value=e?.activity??"";for(const[t,i]of this.factors)i.value=cs.yesNo(e?.strangeness?.[t])}values(){const e=this.enquiryMinutes.value.trim()===""?void 0:Number(this.enquiryMinutes.value),t={};for(const[i,s]of this.factors){const n=cs.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:cs.boolean(this.graduate.value),enquiryMinutes:e!==void 0&&Number.isFinite(e)&&e>=0?e:void 0,observersRelation:this.relation.value||void 0,activity:this.activity.value||void 0,strangeness:Object.keys(t).length>0?t:void 0}}label(e,t){const i=document.createElement("label"),s=document.createElement("span");return i.append(s," ",e),this.labels.set(s,()=>{if(!this.wording)return;const[n,r]=t(this.wording);Hn.say(s,n,r)}),i}static select(e){return Object.assign(document.createElement("select"),{id:e})}static choices(e,t,i){const s=e.value;e.replaceChildren(new Option(t,""),...i.map(([n,r])=>new Option(r,n))),e.value=s}static yesNo(e){return e===void 0?"":e?"yes":"no"}static boolean(e){return e===""?void 0:e==="yes"}}const Rf=new Set;f0();f8();Rh.register();const sh={width:48,height:28},t9=2500,eE=40,i9=10,tE=600,iE=900,nh=2e-4,s9=900,n9=-1.46,r9=3,wv=.2,a9=.5,o9=3,l9=.01,c9=1.6,Mv=2e3,h9=250,sE=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),d9=1,u9=5,p9=10,Ho=4,Wd="ufo-1",f9={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function m9(c){return c.kind==="oval"?"oval":"polygon"}const g9=-6,v9=21;class _e extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=Q8[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new Z8;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;candidatesView;sectionFolds;frozenPanel;sectionFilePanel;eventsPanel;phenomenonEventsPanel;bodiesEventsPanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=K8();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lensGlassSelect;isoInput;meteringSelect;lensDropsInput;lensCondensationInput;lensDirtInput;lensShelteredInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;evaluationFields;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;launchEditor;launchEditorLoading;beamEditor;beamEditorLoading;lanternEditor;lanternEditorLoading;fileEditor;fileEditorLoading;fileEditorHost;fileNote;fileAsk;identityAsk;fileSyncTimer;fileApplyTimer;historySnapshot;historyTimer;historyAnswering=!1;undoButton;redoButton;labelFileGroup;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new pv(W8());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelPosition;observerSaid;observerSaidShown;observerPosition;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;wholeKeyframesInput;labelImportFile;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;accountShapeIds;labelNarrativeSource;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;labelRareIce;highCloudCoverInput;iceCrystalAlignmentInput;rareIceCrystalsInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelLaunchesSubgroup;labelBeamsSubgroup;labelLanternsSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;weatherProviderSelect;weatherFileLink;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorList;observerList;observerShown="principal";static CLICK_SLOP_PX=5;static OBSERVER_PRINCIPAL="principal";surroundings;surroundingsProvider;sceneryStatus;scenerySource;labelScenerySource;sceneryWarning;sceneryRadius;labelSceneryRadius;sceneryChoice;decorModelProvider=Kf[0].create();milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=gl;currentAppearance={...f9};currentSourceId=Wd;selectedSourceIds=new Set([Wd]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSourceInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;referenceFailure;addReferenceButton;referenceAddMenu;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;findGhostsButton;searchingGhosts=!1;ghostsStatus;ghostFinding;ghostsShown=!0;ghostsShownButton;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;traceImportInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;addTraceButton;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$;pictureRegistration;pictureRegistrationLoading;referenceFields;labelReferenceGroup;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),(e.ctrlKey||e.metaKey)&&!e.altKey&&["z","y"].includes(e.key.toLowerCase())){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;e.preventDefault(),e.key.toLowerCase()==="y"||e.shiftKey?this.redo():this.undo();return}if(sE.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;sE.has(e.key)?this.selectedMembers().length===0&&t===this?this.walkOrTurn(e):this.moveOrResizeSelectedShapes(e):this.canvasMode()==="decor"?this.deleteDecor():this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0,t=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedBodyId:void 0;this.endDrag(),t!==void 0&&this.showBody(t),e!==void 0&&(this.selectDecor(e),this.revealDecorPanel(),this.flash(this.shadow.querySelector("#decor-item label, #decor-item .field")))};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${V5}</style>${G5}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const a of this.shadow.querySelectorAll(Jf))a.build();for(const a of this.shadow.querySelectorAll(Ym))a.build();for(const a of this.shadow.querySelectorAll(hp))a.build();for(const a of this.shadow.querySelectorAll(tm))a.build();this.sceneElement=document.createElement(Km),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",a=>{this.ufoElement.sighting.observerMap=a.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",a=>{const{lat:o,lng:l}=a.detail;this.latInput.value=String(Number(o.toFixed(6))),this.lngInput.value=String(Number(l.toFixed(6))),this.updateObserver()}),this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.shapeRotationInput=this.shadow.getElementById("shapeRotation"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextDuplicateButton=this.shadow.getElementById("context-duplicate"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewAccountButton=this.shadow.getElementById("context-view-account"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.previousMarkButton=this.shadow.getElementById("previous-mark"),this.nextMarkButton=this.shadow.getElementById("next-mark"),this.timelineMarks=new Qd(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const a of[this.timeStartLabel,this.timeEndLabel])a.addEventListener("click",()=>this.switchTimeDisplay()),a.addEventListener("keydown",o=>{o.key!=="Enter"&&o.key!==" "||(o.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.accountCompareInput=this.shadow.getElementById("account-compare"),this.durationElement=this.shadow.querySelector(Ym),this.durationInput=this.durationElement.input,this.exportButton=this.shadow.getElementById("export"),this.saveButton=this.shadow.getElementById("save"),this.shareButton=this.shadow.getElementById("share"),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.sectionFolds=new IE(this.shadow);const t=this;this.witnessErrorView=new e2({get sighting(){return t.ufoElement.sighting},messages:()=>this.messages.witnessError,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:a=>{const o=this.ufoElement.sighting,{conditions:l,...h}=o.account??{},d={...h,...a?{conditions:a}:{}};o.account=Object.values(d).some(u=>u!==void 0)?d:void 0},recordingJson:()=>this.sightingData,lawsChanged:()=>{this.sceneElement.confrontationTolerance=Fi.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new h0(this.shadow.getElementById("timeline-tracks"),a=>this.goToMark(a),this.messages),this.tracksToggle=this.shadow.getElementById("toggle-tracks"),this.tracksToggle.addEventListener("click",()=>this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")!=="true")),this.resizeScene(this.shadow.getElementById("scene-resize")),this.shadow.querySelector(".scene-card").addEventListener("pointerdown",a=>{a.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new s2(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",a=>{const o=a.target.id;_e.SCENE_LINKED.includes(o)&&this.setActiveSceneField(o)}),this.shadow.addEventListener("focusout",a=>{const o=a.relatedTarget;(!o||!_e.SCENE_LINKED.includes(o.id))&&this.setActiveSceneField(void 0)}),this.shadow.addEventListener("input",()=>this.refreshSceneField()),this.importInput=this.shadow.getElementById("import"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeRememberInput=this.shadow.getElementById("narrativeRemember"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lensGlassSelect=this.shadow.getElementById("lens-glass"),this.isoInput=this.shadow.getElementById("iso"),this.meteringSelect=this.shadow.getElementById("metering"),this.lensDropsInput=this.shadow.getElementById("lens-drops"),this.lensCondensationInput=this.shadow.getElementById("lens-condensation"),this.lensDirtInput=this.shadow.getElementById("lens-dirt"),this.lensShelteredInput=this.shadow.getElementById("lens-sheltered"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.evaluationFields=new cs(this.shadow.getElementById("profile-section"),this.shadow.getElementById("testimony-section"),this.shadow.getElementById("strangeness-section"),()=>this.updateObserverMetadata()),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.rareIceCrystalsInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${tm}[name="observer"]`),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),this.labelRoll=this.shadow.getElementById("label-roll"),this.labelSway=this.shadow.getElementById("label-sway"),this.labelLightPollution=this.shadow.getElementById("label-light-pollution"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelObserverId=this.shadow.getElementById("label-observer-id"),this.labelObserverTitle=this.shadow.getElementById("label-observer-title"),this.labelObserverLastName=this.shadow.getElementById("label-observer-last-name"),this.labelObserverFirstNames=this.shadow.getElementById("label-observer-first-names"),this.labelObserverAge=this.shadow.getElementById("label-observer-age"),this.labelObserverBirth=this.shadow.getElementById("label-observer-birth"),this.labelObserverOccupation=this.shadow.getElementById("label-observer-occupation"),this.labelAccountSource=this.shadow.getElementById("label-account-source"),this.labelAccountFollowedUp=this.shadow.getElementById("label-account-followed-up"),this.labelSightingId=this.shadow.getElementById("label-sighting-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.wholeKeyframesInput=this.shadow.getElementById("whole-keyframes");try{this.wholeKeyframesInput.checked=localStorage.getItem(_e.WHOLE_KEYFRAMES_STORAGE)==="true"}catch{}this.wholeKeyframesInput.addEventListener("change",()=>this.setKeyframesWritten()),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),this.labelNarrativeRemember=this.shadow.getElementById("label-narrative-remember"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelFileGroup=this.shadow.getElementById("label-file-group"),this.fileEditorHost=this.shadow.getElementById("file-editor"),this.fileNote=this.shadow.getElementById("file-note"),this.frozenPanel=new ss(this.shadow.getElementById("frozen-data"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,sources:()=>this.freezerSources(),upperAirHeard:()=>this.sceneElement.upperAirHeard,changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleFileSync(),this.refreshFileItems()},base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,o)=>this.download(a,o)}),this.sectionFilePanel=new jm(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,o)=>this.download(a,o),changed:a=>{if(this.touch(),this.ufoElement.refresh(),a==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),a==="place"&&this.syncPlaceNameField(),a==="lightPollution"){const o=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=o===void 0?"":String(o),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}}),this.sectionFilePanel.localize(this.messages);const i={sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.refreshTimelineMarks(),this.scheduleFileSync(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render()},seek:a=>this.goToMark(a),now:()=>this.ufoElement.currentTime,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const a=this.ufoElement.sighting.timeline;return a.sourceIds.includes(this.currentSourceId)?a.topOf(this.currentSourceId):void 0},shapesLabel:a=>this.shapesLabel(a),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:a=>this.naming.point(a),lookedAt:()=>{const a=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return a?.headingDeg===void 0||a.pitchDeg===void 0?void 0:{azimuthDeg:a.headingDeg,altitudeDeg:a.pitchDeg}},bodyLabel:a=>{const o=this.ufoElement.sighting.interpretation?.bodies.find(l=>l.id===a);return this.said.read(o?.title)??a}};this.eventsPanel=new Pa(this.shadow.getElementById("events-section"),i,this.messages.events),this.phenomenonEventsPanel=new Pa(this.shadow.getElementById("phenomenon-events-section"),i,this.messages.events,"phenomenon"),this.bodiesEventsPanel=new Pa(this.shadow.getElementById("bodies-events-section"),i,this.messages.events,"bodies"),this.samplingRateInput.addEventListener("change",()=>{const a=Number(this.samplingRateInput.value);i.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(a)&&a>0?a:void 0,lt.refresh(this.ufoElement.sighting),i.changed()}),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.frozenPanel.localize(this.messages),this.refreshFileItems(),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",a=>{a.preventDefault(),this.keepReadingWeather()}),this.shadow.getElementById("file-ask-stop").addEventListener("click",()=>this.stopReadingWeather()),this.shadow.getElementById("file-ask-keep").addEventListener("click",()=>this.keepReadingWeather()),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelObserverGroup=this.shadow.getElementById("label-observer-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelRareIce=this.shadow.getElementById("label-rare-ice"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelShapesSubgroup=this.shadow.getElementById("label-shapes-subgroup"),this.labelBodiesSubgroup=this.shadow.getElementById("label-bodies-subgroup"),this.labelLaunchesSubgroup=this.shadow.getElementById("label-launches-subgroup"),this.labelBeamsSubgroup=this.shadow.getElementById("label-beams-subgroup"),this.labelLanternsSubgroup=this.shadow.getElementById("label-lanterns-subgroup"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.weatherProviderSelect=this.shadow.getElementById("weatherSource"),this.weatherFileLink=this.shadow.getElementById("weather-file-link"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorList=new wn({header:this.shadow.getElementById("decor-list-header"),body:this.shadow.getElementById("decor-item"),ids:{list:"decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind:a=>`option-decor-${a}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectDecor(a),onAdd:a=>this.addDecor(a),onRemove:()=>this.deleteDecor()}),this.decorList.setKinds([{value:"building",label:"Building"},{value:"tree",label:"Tree"},{value:"shrub",label:"Shrub"},{value:"bridge",label:"Bridge"},{value:"wire",label:"Overhead line"},{value:"crop",label:"Crop row"},{value:"terrace",label:"Terrace (restanque)"},{value:"mound",label:"Stone heap"},{value:"wall",label:"Dry-stone wall"},{value:"streetlight",label:"Streetlight"},{value:"trafficlight",label:"Traffic light"},{value:"crossing",label:"Pedestrian crossing"},{value:"roadsign",label:"Road sign"},{value:"vehicle",label:"Vehicle"},{value:"aircraft",label:"Aircraft"},{value:"entity",label:"Being"},{value:"observer",label:"Other observer",hidden:!0}]),this.decorList.setLabels({list:"Environment",remove:"Delete decor",add:"Add",empty:"No decor",actions:{"look-at-decor":"Look at it"}}),this.observerList=new wn({header:this.shadow.getElementById("observer-list-header"),body:this.shadow.getElementById("observer-item"),ids:{list:"observer-pick",remove:"delete-observer",add:"add-decor-observer"},actions:[{id:"look-at-observer",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectObserver(a),onAdd:()=>this.addDecor("observer"),onRemove:()=>this.deleteDecor()}),this.observerList.setLabels({list:"Observer",remove:"Delete observer",add:"Add observer",actions:{"look-at-observer":"Look at it"}}),this.sceneryStatus=this.shadow.getElementById("scenery-status"),this.sceneryWarning=this.shadow.getElementById("scenery-warning"),this.scenerySource=this.shadow.getElementById("scenery-source"),this.labelScenerySource=this.shadow.getElementById("label-scenery-source"),this.sceneryRadius=this.shadow.getElementById("scenery-radius"),this.labelSceneryRadius=this.shadow.getElementById("label-scenery-radius"),this.sceneryRadius.value=this.readSceneryRadius(),this.surroundings=new Zs(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:a=>this.setPlantedDecor(a),kindName:a=>this.decorList.kindLabel(a),cite:a=>this.citeSource(a),busy:(a,o)=>this.sceneElement.setBusy(a,o),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(a=>({lat:a.pose.lat,lng:a.pose.lng})).filter(a=>typeof a.lat=="number"&&typeof a.lng=="number")},gl,async(a,o)=>this.surroundingsProvider?this.surroundingsProvider.covers(a,o)?this.surroundingsProvider:void 0:(await oe(async()=>{const{SurroundingsSources:l}=await import("./surroundingsSources-Bq5A0HA5.js");return{SurroundingsSources:l}},[],import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,a,o),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-file-link").addEventListener("click",()=>this.openFileItem("decor")),this.scenerySource.addEventListener("change",()=>{const a=this.scenerySource.value===_e.FILE_SOURCE;if(this.setDecorFromFile(a),a){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===_e.NO_SCENERY){this.surroundings.withdraw();return}const o=this.plantingCentre();o&&this.surroundings.survey(o.lat,o.lng)}),this.sceneryRadius.addEventListener("input",()=>{const a=Number(this.sceneryRadius.value);if(!Number.isFinite(a)||a<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const o=this.plantingCentre();this.surroundings.radiusChanged(a,o?.lat,o?.lng)}),this.fillScenerySources(),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSourceInput=this.shadow.getElementById("reference-source"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.referenceFailure=this.shadow.getElementById("reference-failure"),this.addReferenceButton=this.shadow.getElementById("add-reference"),this.referenceAddMenu=new Zf(this.addReferenceButton,"reference-add-kind",a=>this.addReferenceOfKind(a),a=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[a]??`reference-add-${a}`),this.setReferenceAddKinds("From an address","From a file","Street-level pictures nearby"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.findGhostsButton=this.shadow.getElementById("reference-find-ghosts"),this.ghostsStatus=this.shadow.getElementById("reference-ghosts-status"),this.findGhostsButton.addEventListener("click",()=>void this.findGhosts()),this.ghostsShownButton=this.shadow.getElementById("reference-ghosts-shown"),this.ghostsShownButton.addEventListener("click",()=>{this.ghostsShown=!this.ghostsShown,this.syncGhostsShown(),this.ufoElement.refresh()}),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.traceImportInput=this.shadow.getElementById("trace-import"),this.traceSelect=this.shadow.getElementById("trace"),this.deleteTraceButton=this.shadow.getElementById("delete-trace"),this.traceTitleInput=this.shadow.getElementById("traceTitle"),this.traceSourceInput=this.shadow.getElementById("traceSource"),this.traceStatus=this.shadow.getElementById("trace-status"),this.labelTraceImport=this.shadow.getElementById("label-trace-import"),this.addTraceButton=this.shadow.getElementById("add-trace"),this.labelTraceTitle=this.shadow.getElementById("label-trace-title"),this.labelTraceSource=this.shadow.getElementById("label-trace-source"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.goToMilestoneButton=this.shadow.getElementById("go-to-milestone"),this.modelPicker=new yu(this.shadow,()=>({title:this.messages.modelPickerTitle,close:this.messages.modelPickerClose,choose:this.messages.modelPickerChoose,address:this.messages.decorModelAdvanced,addressUrl:this.messages.decorModelUrl,addressName:this.messages.decorModelTitle,addressAuthor:this.messages.decorModelAuthor,addressLicense:this.messages.decorModelLicense,addressSource:this.messages.decorModelSource,addressUse:this.messages.modelPickerUse,addressIncomplete:this.messages.modelPickerIncomplete})),this.decorParametersHost=this.shadow.getElementById("decor-parameters"),this.decorParameterForm=new ea(this.decorParametersHost,"en","decorParam.");const s={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new ea(this.decorBaseHost,"en","decorBase.",s,(a,o)=>this.enhanceDecorModelChoice(a,o)),this.decorStateForm=new ea(this.decorStateHost,"en","decorState.",s),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{this.focus({preventScroll:!0}),this.onPointerDown(a)}),this.ufoElement.canvasElement.addEventListener("pointermove",a=>this.onPointerMove(a));let n;this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{n={x:a.clientX,y:a.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",a=>{const o=n;n=void 0,!(!o?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(a.clientX-o.x,a.clientY-o.y)>_e.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",a=>this.onContextMenu(a)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextDuplicateButton.addEventListener("click",()=>this.duplicateSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.saveButton.addEventListener("click",()=>this.exportJson()),this.shareButton.addEventListener("click",()=>this.openShare()),this.importInput.addEventListener("filepick",a=>{const o=a.detail;o.file?this.importFromFile(o.file):this.importFromUrl(o.url)}),this.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()});for(const a of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])a.addEventListener(a instanceof HTMLSelectElement||a.type==="checkbox"?"change":"input",()=>this.updateLens());this.lightPollutionInput.addEventListener("input",()=>{const a=this.ufoElement.sighting;a.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),a.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),a.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",a=>{const{seconds:o,text:l}=a.detail;this.ufoElement.sighting.event.durationText=l,this.ufoElement.durationSeconds=o,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((o??0)*1e3),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.shapeRotationInput.addEventListener("input",()=>this.updateShapeRotation()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const a of this.referenceFields)a.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceSourceInput.addEventListener("filepick",a=>void this.setReferenceSource(a.detail)),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.addTraceButton.addEventListener("click",()=>{const a=this.shadow.getElementById("trace-import-row");a.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",a=>void this.addTraces(a.detail)),this.traceSelect.addEventListener("change",()=>this.selectTrace(this.traceSelect.value)),this.deleteTraceButton.addEventListener("click",()=>this.deleteTrace()),this.traceTitleInput.addEventListener("input",()=>this.writeTraceFields()),this.traceSourceInput.addEventListener("input",()=>this.writeTraceFields()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",a=>this.onReferenceWheel(a),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",a=>this.onBodyWheel(a),{passive:!1}),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.goToMilestoneButton.addEventListener("click",()=>{this.currentMilestoneT!==void 0&&this.goToMark(this.currentMilestoneT)}),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const a of[this.milestoneLabelInput,this.milestoneNoteInput])a.addEventListener("input",()=>this.updateMilestone());this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showNovaButton.addEventListener("click",()=>this.lookAtNova()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.showFireballButton.addEventListener("click",()=>this.showNextFireball()),this.sceneElement.addEventListener(ZA,()=>{const a=this.currentReference();a&&this.syncReferenceStatus(a)}),this.sceneElement.addEventListener(jA,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(qA,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown),this.shapeAddMenu=new Zf(this.addShapeButton,"add-shape-kind",a=>{const o=ao.byId(a);if(o){this.addModel(o);return}this.currentAppearance={...this.currentAppearance,presetId:a},this.addShape()},a=>`add-shape-${a}`),this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const a of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])a.addEventListener("input",()=>this.updateObserver());for(const a of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])a.addEventListener("input",()=>this.updateObserver());this.isoInput.addEventListener("input",()=>this.updateExposureSettings()),this.meteringSelect.addEventListener("change",()=>this.updateExposureSettings()),this.observerPosition.addEventListener("positionchange",a=>{if(this.observerSaid=a.detail.said,!this.observerPosition.relative)return;const o=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(o,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",a=>this.writeObserverBasis(a.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",a=>{a.key==="Enter"&&(a.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 a=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const o=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(l=>[l.t,Si.fovOf(this.ufoElement.sighting,l.t)]));this.retuneFieldOfView(a),this.retuneExposure(a),Si.reproject(this.ufoElement.sighting,a,o),this.sceneElement.applyFrameFormat(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.accountCompareInput.addEventListener("change",()=>this.syncBodiesShown()),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const r=a=>this.shadow.querySelector(`${Jf}[name="${a}"]`);this.startDate=r("obs-time"),this.endDate=r("obs-end-time"),this.birthDate=r("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=mc.ALL,this.perceptionSettings.labels=this.messages.observerPerception,this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata()),this.startDate.messages=this.messages,this.endDate.messages=this.messages,this.birthDate.messages=this.messages;for(const a of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(a,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",a=>{const{time:o}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=o}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",a=>{this.birth=a.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",a=>{const{time:o}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=o})});for(const a of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])a.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(_e.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const a of this.weatherFields){if(a===this.iceCrystalAlignmentInput||a===this.rareIceCrystalsInput){a.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}a.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const a of this.soundFields)a.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.weatherProviderSelect.addEventListener("change",()=>this.onWeatherProviderChosen()),this.weatherFileLink.addEventListener("click",()=>this.openFileItem("weather")),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(a=>this.shadow.getElementById(a.getAttribute("aria-controls")));for(const a of this.groupTabs)a.addEventListener("click",()=>this.toggleGroup(a,!this.isGroupOpen(a)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const a of this.subgroupTabs)a.addEventListener("click",()=>this.openSubgroup(a));en.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new oo(this.messages,this.naming,this.said,this.tagNames,{messages:this.messages,locale:this.language}),this.paramSummary.addEventListener("click",a=>this.onParamSummaryClick(a)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(a=>a.id==="group-shape")],!0),this.sectionChosen=!1,this.opensMostLacking=!0,this.attachWitnessErrors(),this.labelPanels(this.messages),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),this.setRecordButtonLabel(!1),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=lI(this.shadow.getElementById("cloud-editor"),this.sceneElement,(a=!0)=>{a&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(a,o)=>{this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()},$u(Sr.preferencesFor(this),Wu),this.framePlace()),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),Sr.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages(),this.shadow.addEventListener("pointerdown",this.armHistory,!0),this.shadow.addEventListener("keydown",this.armHistory,!0);for(const t of["input","change","click","keyup","pointerup"])this.shadow.addEventListener(t,this.scheduleHistoryRecord,!0);this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),this.shadow.removeEventListener("pointerdown",this.armHistory,!0),this.shadow.removeEventListener("keydown",this.armHistory,!0);for(const e of["input","change","click","keyup","pointerup"])this.shadow.removeEventListener(e,this.scheduleHistoryRecord,!0);clearTimeout(this.historyTimer),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag(),queueMicrotask(()=>{this.isConnected||this.releaseFileEditor()})}releaseFileEditor(){this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileEditorLoading=void 0}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){const t=Ui.toCurrent(e);this.sourceUrl=void 0,this.endDrag(),this.ufoElement.sightingData=t,this.sceneElement.applyFrameFormat(),this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.isGroupIdOpen("group-shape")&&this.showPhenomenonPartWithContent(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??Wd,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncObserverMetadataFields(),this.offsetIsAuthors=!1,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField();const i=this.plantingCentre();this.surroundings.placeLoaded(i?.lat,i?.lng),this.syncSceneryPicker(),this.syncWeatherOwnership(),this.frozenPanel.render(),this.refreshFileItems(),this.markClean(),this.sectionChosen||(this.opensMostLacking=!0)}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&this.fileText()!==this.baseline}get edited(){return this.touched}markClean(){this.applyingFileText||(this.baseline=this.fileText(),this.touched=!1,this.savedFileText=this.baseline,this.fileEditor?.markSaved(),this.refreshEditorHead())}set embedded(e){this.shadow.getElementById("editor-head").hidden=e,this.shadow.querySelector(".app").classList.toggle("embedded",e),e||this.shadow.querySelector("#editor-head .head-actions").prepend(this.historyControls)}get historyControls(){return this.undoButton.parentElement}refreshEditorHead(){this.saveButton&&(this.refreshEditorTitle(),this.saveButton.disabled=!this.dirty,this.shareButton.disabled=this.sourceUrl===void 0,this.shareButton.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"")}sourceUrl;shareButton;shareDialog;shareMessages;shareSubject={module:"rr0-sighting-editor",link:()=>`${ed.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}`,element:()=>`<rr0-sighting-editor src="${this.sourceUrl??""}"></rr0-sighting-editor>`};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}refreshEditorTitle(){const e=this.ufoElement.sighting.event,t=e.place?.[0]?.name?.split(",")[0].trim(),i=e.time;let s="";i?.year!==void 0&&(s=i.month!==void 0&&i.day!==void 0?new Date(Date.UTC(i.year,i.month-1,i.day)).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"}):String(i.year));const n=[t,s].filter(Boolean).join(", ")||this.sightingIdInput.value||this.messages.stateNew,r=this.shadow.getElementById("editor-title");r.textContent!==n&&(r.textContent=n)}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.historySnapshot!==void 0&&(clearTimeout(this.historyTimer),this.historyTimer=setTimeout(()=>this.recordHistory(),350))};recordHistory(){this.historyTimer=void 0;const e=this.fileEditor;if(e===void 0||this.historySnapshot===void 0)return;const t=this.fileText();t!==this.historySnapshot&&(this.historySnapshot=t,this.historyAnswering=!1,e.replaceText(t,this.fileSyncActive()),this.fileTextApplied=e.text,this.syncHistoryButtons(),this.refreshEditorHead())}undo(){this.stepHistory(e=>e.undo(this.fileSyncActive()))}redo(){this.stepHistory(e=>e.redo(this.fileSyncActive()))}stepHistory(e){this.historyTimer!==void 0&&(clearTimeout(this.historyTimer),this.recordHistory());const t=this.fileEditor;t===void 0||this.isRecording||this.ufoElement.playbackState==="playing"||e(t)&&(clearTimeout(this.fileApplyTimer),this.applyFileText(t.text,!0),this.historyAnswering=!0,this.syncHistoryButtons(),this.refreshEditorHead())}syncHistoryButtons(){this.undoButton.disabled=!(this.fileEditor?.canUndo??!1),this.redoButton.disabled=!(this.fileEditor?.canRedo??!1)}resetHistory(){clearTimeout(this.historyTimer),this.historyTimer=void 0,this.historySnapshot=void 0,this.historyAnswering=!1,this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileTextApplied=void 0,this.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>{})}touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=this.shadow.getElementById("save-refused"),t=Ht.issues(this.ufoElement.sighting);if(Xt.show(e,t.length===0?void 0:this.messages.saveRefused.replace("{reasons}",t.map(s=>this.actorIssue(s)).join(" ; ")),"error"),t.length>0)return;const i=es.inspect(this.sightingData,this.loadedJson());if(i.length===0){this.downloadJson();return}this.askAboutIdentity(i)}actorIssue(e){const t=this.messages;if(e.kind==="duplicate-id")return t.duplicateId.replace("{id}",e.id).replace("{kinds}",e.path.split(", ").map(n=>t.actorKinds[n]??n).join(", "));const i=Number(e.path.split(".")[1]),s=this.ufoElement.sighting.events?.[i];return t.unknownWho.replace("{n}",String(i+1)).replace("{kind}",(s&&t.events.kinds[s.eventType])??s?.eventType??"").replace("{id}",e.id)}loadedJson(){try{return this.baseline?JSON.parse(this.baseline):void 0}catch{return}}askAboutIdentity(e){const t={lastName:this.messages.identityLastName,firstNames:this.messages.identityFirstNames,nameInId:this.messages.identityNameInId,nameInText:this.messages.identityNameInText,address:this.messages.identityAddress,email:this.messages.identityEmail,phone:this.messages.identityPhone};this.shadow.getElementById("identity-ask-text").textContent=this.messages.identityAsk,this.shadow.getElementById("identity-ask-found").replaceChildren(...e.map(n=>{const r=document.createElement("li");return r.textContent=t[n.kind].replaceAll("{value}",n.found),r}));const s=e.some(n=>["lastName","firstNames","nameInId","nameInText"].includes(n.kind));this.shadow.getElementById("identity-ask-initials").hidden=!s,typeof this.identityAsk.showModal=="function"?this.identityAsk.showModal():this.identityAsk.setAttribute("open","")}closeIdentityAsk(){typeof this.identityAsk.close=="function"?this.identityAsk.close():this.identityAsk.removeAttribute("open")}writeNamesAsInitials(){const e=es.namesOf(this.sightingData);this.observerLastNameInput.value=es.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>es.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=es.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=es.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=es.withInitials(this.descriptionInput.value,e),this.touch(),this.updateObserverMetadata(),this.descriptionInput.dispatchEvent(new Event("input"))}async downloadJson(){const e=this.fileBase();let t=new Map;if(this.frozenPanel.hasWork()){this.exportButton.disabled=!0;try{t=await this.frozenPanel.prepare(e)}finally{this.exportButton.disabled=!1}}const i=this.sightingData;for(const r of Ns.NAMES){const a=this.sectionFilePanel.annex(r);if(a){/^[a-z][a-z0-9+.-]*:/i.test(a.src)||t.set(a.src,a.bytes);for(const o of Ns.KEYS[r])delete i[o]}}const s=`${e}.json`,n=this.writtenText(i);if(t.size===0)this.download(new Blob([n],{type:"application/json"}),s);else{const{zipSync:r,strToU8:a}=await oe(async()=>{const{zipSync:h,strToU8:d}=await import("./browser-_Ncw3Jhn.js");return{zipSync:h,strToU8:d}},[],import.meta.url),o={[s]:a(n)};for(const[h,d]of t)o[h]=d;const l=r(o,{level:0});this.download(new Blob([l],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.frozenExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",ss.size(l.length)))}this.markClean()}fileBase(){const e=this.sceneElement.documentUrl?.split(/[?#]/)[0].split("/").pop();return e?.endsWith(".json")&&e.length>5?decodeURIComponent(e.slice(0,-5)):`${this.sightingData.observer?.id??"sighting"}-sighting`}refreshFileItems(){const e=this.fileItemSelect;if(!e)return;this.syncFilePickers();const t=e.value||"recording";e.replaceChildren(new Option(this.messages.fileItemRecording,"recording"),...Ns.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...ts.NAMES.map(i=>new Option(this.frozenPanel.itemLabel(i),i))),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=ts.NAMES.includes(e),i=Ns.NAMES.includes(e)?e:void 0;this.shadow.getElementById("file-recording").hidden=t||i!==void 0,this.shadow.getElementById("frozen-data").hidden=!t,this.shadow.getElementById("file-section").hidden=i===void 0;for(const n of["file-recording","frozen-data","file-section"]){const r=this.shadow.getElementById(n);r.hidden||wn.glue(r)}t&&this.frozenPanel.show(e),i&&this.sectionFilePanel.show(i);const s=t&&this.frozenPanel.isInlineGroup(e)?["frozen",e,"src"]:i&&this.sectionFilePanel.isInline(i)?jm.pathOf(i):void 0;this.fileEditorHost.hidden=(t||i!==void 0)&&s===void 0,s&&this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(n=>{this.syncFileEditor(!1),n.reveal(s)},()=>{})}sectionFromFile(e){return Ns.fromFile(this.ufoElement.sighting.frozen,e)}masterUrl(){return this.sceneElement.documentUrl??new URL(`${this.fileBase()}.json`,location.href).href}weatherFileItemLabel(){return this.sectionFilePanel?.itemLabel("weather")??""}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}freezerSources(){const e=ds(Ef,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:ds(fc,this.chosenSourceId.get("imagery")).id,roads:_2(),water:D2(),railways:R2()}}async importFromFile(e){this.holdLoad(()=>void this.loadFile(e))||await this.loadFile(e)}async loadFile(e){try{const t=new Uint8Array(await new Promise((n,r)=>{const a=new FileReader;a.onload=()=>n(a.result),a.onerror=()=>r(a.error),a.readAsArrayBuffer(e)}));Ct.release();const i=await this.recordingText(t),s=JSON.parse(i);if(Hi.isCase(s)){if(Hi.check(s),this.offerCase(s,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=s,this.resetHistory(),this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importInput.url=""}catch(t){window.alert(this.importErrorFor(t))}}async recordingText(e){if(e[0]!==80||e[1]!==75)return new TextDecoder().decode(e);const{unzipSync:t,strFromU8:i}=await oe(async()=>{const{unzipSync:d,strFromU8:u}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:d,strFromU8:u}},[],import.meta.url),s=t(e),n=/\.(relief|imagery|map)\.zip$|\.(roads|water|railways|upper-air|weather)\.json$/,r=Object.keys(s).find(d=>d.endsWith(".json")&&!n.test(d));if(!r)throw new Error("No recording in this archive");const a=r.includes("/")?r.slice(0,r.lastIndexOf("/")+1):"";for(const[d,u]of Object.entries(s))d!==r&&d.startsWith(a)&&Ct.hold(Ct.address(d.slice(a.length),void 0),u);const o=i(s[r]),l=JSON.parse(o);let h=!1;for(const d of Ns.NAMES){const u=l.frozen?.[d]?.src,p=u!==void 0?s[a+u]:void 0;if(!p)continue;const f=Ui.toCurrent(JSON.parse(i(p)));for(const m of Ns.KEYS[d])f[m]!==void 0&&(l[m]=f[m]);h=!0}return h?JSON.stringify(l):o}offerCase(e,t){return!this.dispatchEvent(new CustomEvent("caseloaded",{detail:{json:e,url:t},bubbles:!0,composed:!0,cancelable:!0}))}bodyShapeIds(){return this.accountShapeIds?[...this.accountShapeIds]:this.ufoElement.sighting.timeline.sourceIds}set documentUrl(e){this.sceneElement.documentUrl=e}async importFromUrl(e=this.importInput.url){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){try{const t=await na.recording(e);if(Hi.isCase(t)){Hi.check(t);const s=new URL(e,location.href).href;if(this.offerCase(t,s)){this.importInput.url=s;return}throw new Error("A case has no recording to edit here")}const i=t;Ct.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=new URL(e,location.href).href,this.resetHistory(),this.importInput.url=new URL(e,location.href).href,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(e instanceof wu)return e.said(this.messages.formatVersionError);if(!(e instanceof Bl))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";static SCENERY_STORAGE="rr0-sighting-editor.surroundings";static SCENERY_RADIUS_STORAGE="rr0-sighting-editor.surroundings-radius";static NO_SCENERY="none";narrativeProvider=_p[0].create();get narrativeSourceId(){return ds(_p,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:_e.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof fr&&i.kind==="cancelled";this.narrativeStatus.textContent=s?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!s)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:s,...n}=i,r=i.timeZone?n:i,a=Ma.stated(r);if(a.length>0){const o=this.ufoElement.sighting.provenance,l=Yv(this.ufoElement.sighting);this.sightingData=Ma.apply(l,dm.loadable(r),a),this.ufoElement.sighting.provenance=o,this.recordNarrativeProvenance(e,a),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=a.length>0?this.messages.narrativeApplied.replace("{count}",String(a.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const i=this.ufoElement.sighting,s=new Set(t);for(const n of e.claims)!s.has(n.path)&&!t.some(r=>n.path.startsWith(`${r}.`))||i.provenance.set(n.path,{basis:n.basis,rationale:n.rationale,of:_e.valueAt(Yv(this.ufoElement.sighting),n.path)})}static valueAt(e,t){let i=e;for(const s of t.split(".")){if(typeof i!="object"||i===null)return;i=i[s]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(s=>s.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[b9[t]]));for(const s of i){const n=document.createElement("div");n.className=`claim ${t}`;const r=document.createElement("code");r.textContent=s.path;const a=document.createElement(t==="stated"?"q":"span");a.textContent=s.rationale,n.append(r,a),this.narrativeReport.append(n)}}}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 s=document.createElement("li");s.textContent=i,t.append(s)}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=ds(_p,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(s=>s.required&&(this.narrativeSettingInputs.get(s.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(s=>s.remembered==="credential");for(const s of this.narrativeProvider.settings){const n=this.narrativeSettingInputs.get(s.id);if(!n||!s.suspect)continue;const r=n.value.trim(),a=r===""?void 0:s.suspect(r);n.classList.toggle("invalid",a!==void 0),n.title=a?this.said.read(a)??"":this.said.read(s.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const s=document.createElement("label"),n=document.createElement("span");n.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const o of i.choices??[]){const l=document.createElement("option");l.value=o.value,l.textContent=this.said.read(o.label)??o.value,r.appendChild(l)}}else r=document.createElement("input"),r.type=i.kind==="secret"?"password":"text",r.autocomplete="off",r.spellcheck=!1,r.placeholder=this.said.read(i.placeholder)??"";r.id=`narrative-${i.id}`,r.title=this.said.read(i.hint)??"";const a=e[i.id]??this.storedNarrativeSetting(i.id);return a!==void 0&&(r.value=a),r.addEventListener(i.kind==="choice"?"change":"input",()=>{this.rememberNarrativeSettings(),this.syncNarrativeEnabled()}),this.narrativeSettingInputs.set(i.id,r),s.append(n,document.createTextNode(" "),r),s});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 s=i.value.trim();s!==""&&(e[t]=s)}return e}narrativeErrorFor(e){if(!(e instanceof fr))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(_e.NARRATIVE_KEY_STORAGE),localStorage.removeItem(_e.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"?_e.NARRATIVE_KEY_STORAGE:e==="workspace"?_e.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} `),_e.creditLink(ds(vv,this.chosenSourceId.get("place")))),this.weatherSourceRow.replaceChildren(),this.fillWeatherProvider(),this.sourcePickers(this.shadow.getElementById("weather-source-rows"),"weather-source-kind","weather",[["weather",this.messages.fileItemWeather,this.shadow.getElementById("weather-picker")],["upper-air",this.messages.frozenUpperAir,this.sourcePicker("upper-air",j8,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),_e.creditLink(ds(If,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",_p,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.sourcePickers(this.terrainSourceRows,"source-kind","location",[["place",this.messages.fileItemPlace,this.sourcePicker("place",vv,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",If,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",Ef,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",fc,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.frozenRoads,this.sourcePicker("roads",[_e.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.frozenWater,this.sourcePicker("water",[_e.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.frozenRailways,this.sourcePicker("railways",[_e.LIVE_RAILWAYS],()=>{},this.groupChoice(["railways"]))]]),this.sourcePickers(this.shadow.getElementById("decor-source-rows"),"decor-source-kind","decor",[["scenery",this.messages.fileItemDecor,this.shadow.getElementById("scenery-picker")],["aircraft",this.messages.sourceAircraft,this.sourcePicker("aircraft",sy,()=>this.applyAircraftSource())],["decor-model",this.messages.decorModel,this.sourcePicker("decor-model",Kf,()=>this.applyDecorModelSource())]])}sourcePicker(e,t,i,s){const n=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;for(const d of t){const u=document.createElement("option");u.value=d.id,u.textContent=d.name,u.title=d.credit,r.appendChild(u)}s&&r.appendChild(new Option(this.messages.sourceFile,_e.FILE_SOURCE));const a=()=>this.chosenSourceId.get(e)??t[0].id;r.value=s?.fromFile()?_e.FILE_SOURCE:a();const o=document.createElement("a");o.className="source-credit",o.target="_blank",o.rel="noopener noreferrer";const l=document.createElement("button");l.type="button",l.className="link source-file-link",l.addEventListener("click",()=>this.openFileItem(s.item));const h=()=>{const d=r.value===_e.FILE_SOURCE,u=ds(t,d?a():r.value);r.title=d?s.where():u.credit,o.hidden=d,o.href=u.creditUrl,o.textContent=u.credit,l.hidden=!d,d&&(l.textContent=s.label(),l.title=s.where())};return h(),r.addEventListener("change",()=>{const d=r.value===_e.FILE_SOURCE;d||this.chosenSourceId.set(e,r.value),s?.setFromFile(d),h(),d||i(ds(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?_e.FILE_SOURCE:a(),h()}),n.append(r,document.createTextNode(" "),o,l),n}groupChoice(e){return{item:e[0],fromFile:()=>!this.frozenPanel.isLive(e[0]),setFromFile:t=>{for(const i of e)this.frozenPanel.setLive(i,!t)},label:()=>this.frozenPanel.itemLabel(e[0]),where:()=>this.frozenPanel.where(e[0])}}sectionChoice(e,t){return{item:e,fromFile:()=>this.sectionFromFile(e),setFromFile:i=>{const s={...this.ufoElement.sighting.frozen??{}};i?s[e]=s[e]??{}:delete s[e],this.ufoElement.sighting.frozen=ts.isEmpty(s)?void 0:s,this.touch(),this.scheduleFileSync(),this.refreshFileItems(),i||t()},label:()=>this.sectionFilePanel.itemLabel(e),where:()=>this.sectionFilePanel.where(e)}}static FILE_SOURCE="file";filePickers=new Map;syncFilePickers(){for(const e of this.filePickers.values())e()}openFileItem(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-file");t&&this.toggleGroup(t,!0),this.fileItemSelect.value=e,this.showFileItem(e)}static LIVE_ROADS={id:"ign-osm",name:"IGN BD TOPO / OpenStreetMap",credit:"© IGN, BD TOPO (Licence Ouverte 2.0) in France; © OpenStreetMap contributors (ODbL) elsewhere",creditUrl:"https://www.openstreetmap.org/copyright",create:()=>{}};static LIVE_WATER=_e.LIVE_ROADS;static LIVE_RAILWAYS=_e.LIVE_ROADS;sourcePickers(e,t,i,s){const n=document.createElement("label"),r=document.createElement("span");r.id=`label-${t}`,r.textContent=this.messages.sourceKind;const a=document.createElement("select");a.id=t;const o=s.map(([h,d,u])=>{a.append(new Option(d,h));const p=document.createElement("span");return p.className="source-picker",p.dataset.kind=h,p.append(u),p});a.value=this.sourceKindShown.get(i)??s[0][0];const l=()=>{this.sourceKindShown.set(i,a.value);for(const h of o)h.hidden=h.dataset.kind!==a.value};a.addEventListener("change",l),l(),n.append(r,document.createTextNode(" "),a),e.replaceChildren(n,...o)}sourceKindShown=new Map;static creditLink(e){const t=document.createElement("a");return t.className="source-credit",t.target="_blank",t.rel="noopener noreferrer",t.href=e.creditUrl,t.textContent=e.credit,t}refreshSourceCredits(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),_e.creditLink(ds(vv,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),_e.creditLink(ds(If,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:ds(Ef,this.chosenSourceId.get("elevation")).create(),imagery:ds(fc,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(ds(sy,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=ds(Kf,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.decorModelEntries=void 0,this.refreshDecorModelOptions(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId)),this.ufoElement.refresh()}get placeSearchLanguage(){return navigator.languages?.[0]}set placeSearchProvider(e){this.placeProvider=e}async searchPlace(){const e=this.placeNameInput.value.trim();if(e===""||this.sectionFromFile("place"))return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let i;try{i=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=i,this.refreshPlaceMatches(),i.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const i=document.createElement("option");return i.textContent=t.name,i.title=t.name,i})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates||this.sectionFromFile("place"))return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||Math.abs(e-this.namedCoordinates.lat)<nh&&Math.abs(t-this.namedCoordinates.lng)<nh||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),iE))}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)<nh&&Math.abs(t-i.lng)<nh||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),iE))}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 s;try{s=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}if(i!==this.placeSearchToken)return;this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=s?.name??"",this.placeNameInput.title=s?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=s?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!s;const n=this.ufoElement.sighting.event.place?.[0]??{lat:e,lng:t};this.ufoElement.sighting.event.place=[{lat:n.lat,lng:n.lng,name:this.stringOrUndefined(this.placeNameInput.value.trim())}]}updateObserver(){if(this.refreshHeadingPoint(),this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),i=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),s=this.numberOrUndefined(this.pitchInput.value)??0,n=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,a=Math.max(0,r-(this.groundElevationM??0)),o=this.ufoElement.sighting.event,l=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());o.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),f=(u.frame&&p!==void 0?Qt.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),m=this.numberOrUndefined(this.fNumberInput.value),v=this.filterSelect.value,g=Xi.byId(l.getLatestPoseAt(h-1)?.filter),b=v===Xi.NONE.id||v===""?g===Xi.NONE?void 0:Xi.NONE.id:v,w=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=w===u.exposureSeconds?void 0:w;const y=this.numberOrUndefined(this.focusDistanceInput.value),M=Math.abs(f-Qt.fieldOfViewDeg(u))>.01||m!==u.fNumber||y!==void 0||b!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&a===0&&!M?l.removeKeyframeAt(h):l.addKeyframe(h,{lat:e,lng:t,elevationM:a,headingDeg:i,pitchDeg:s,rollDeg:n===0?void 0:n,...this.observerSaid&&e!==void 0?{saidPosition:this.observerSaid}:{},fovDeg:f,fNumber:m,focusDistanceM:y,filter:b});const E=this.plantingCentre();this.surroundings.placeChanged(E?.lat,E?.lng),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}syncAgeFromBirth(e){const t=this.birth,i=this.ufoElement.sighting.event.time;if(!t||!i||e&&!Tf.isFirm(t))return;const s=Tf.at(t,i);s!==void 0&&(this.observerAgeInput.value=String(s),this.updateObserverMetadata())}syncBirthFromAge(){const e=this.ufoElement.sighting.event.time,t=this.numberOrUndefined(this.observerAgeInput.value);if(!e||t===void 0)return;const i=this.birth;if(i&&Tf.at(i,e)===t)return;const s=Tf.birthFor(t,e);s&&(this.birthDate.setPrecise(!1),this.birth=s,this.birthDate.time=s,this.updateObserverMetadata())}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.refreshSceneryWarning(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&Qh({...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(s=>{const n=document.createElement("option");return n.value=s,n.textContent=s,n})),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 s=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return s&&t.includes(s)?s:t[0]}updateUtcOffset(){const e=this.ufoElement.sighting.event,t=this.numberOrUndefined(this.utcOffsetInput.value);if(t===void 0)e.utcOffsetHours=void 0,e.timeZone=void 0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value="";else{const i=this.preferredZoneFor(t);if(i===void 0){this.utcOffsetInput.classList.add("invalid"),this.utcOffsetInput.title=this.messages.utcOffsetNoZone;return}e.utcOffsetHours=t,e.timeZone=i,this.offsetIsAuthors=!0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value=i}this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObserverMetadata(){const e=this.ufoElement.sighting,t=this.observerFirstNamesInput.value.split(",").map(n=>n.trim()).filter(n=>n.length>0),i={id:this.stringOrUndefined(this.observerIdInput.value),title:this.observerTitleInput.value.trim()===""?void 0:this.said.write(e.observer?.title,this.observerTitleInput.value.trim(),this.writingLanguage),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0},s=Ht.observerId(e);e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,Ht.renamed(e,s,Ht.observerId(e)),e.id=this.stringOrUndefined(this.sightingIdInput.value),this.updateAccount(),this.ufoElement.refresh()}updateAccount(){const e=this.ufoElement.sighting,t=this.accountFollowedUpSelect.value,i={observerAgeYears:this.numberOrUndefined(this.observerAgeInput.value),observerBirth:this.birth,observerPerception:mc.compact(this.perceptionSettings.values),observerOccupation:this.observerOccupationInput.value.trim()===""?void 0:this.said.write(e.account?.observerOccupation,this.observerOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.accountSourceSelect.value),followedUp:t===""?void 0:t==="yes",...this.evaluationFields.values(),conditions:e.account?.conditions};e.account=Object.values(i).some(s=>s!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...s]=e.sources??[],{url:n,...r}=i??{},a=t===""?r:{...r,url:t},o=Object.keys(a).length>0?[a,...s]:s;e.sources=o.length>0?o:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState()):this.ufoElement.sighting.weatherSource!==void 0&&(this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...fs(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={...fs(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value),rareIceCrystals:Number(this.rareIceCrystalsInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(s=>s.id===this.currentReferenceId),t=e!==void 0;wn.showPresence(this.shadow.getElementById("reference-row"),this.shadow.getElementById("reference-item"),t),this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const s of[this.referenceSelect,...this.referenceFields])s.disabled=!t;if(this.referenceSourceInput.disabled=!t,this.refreshLandmarkList(),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSourceInput.url=i?"":e.src,this.referenceSourceInput.mode=i?"file":"url",this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.ghostFinding&&(this.ghostFinding.referenceId!==e.id||this.ghostFinding.src!==e.src)&&(this.ghostFinding=void 0,this.ghostsStatus.textContent="",this.syncGhostsShown(),this.ufoElement.refresh()),this.referenceOpacityInput.value=String(e.opacity),this.referenceHeadingInput.value=String(e.registration.headingDeg),this.referencePitchInput.value=String(e.registration.pitchDeg),this.referenceRollInput.value=String(e.registration.rollDeg??0),this.referenceFovInput.value=String(e.registration.fovDeg),this.syncReferenceStatus(e)}syncReferenceStatus(e){const t=this.sceneElement.referenceFailure(e.src);if(Xt.show(this.referenceFailure,t?this.pictureFailureText(t):void 0,"error"),this.syncFindGhosts(e),this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const i=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>D8?this.messages.referenceEmbedded.replace("{kb}",String(i)):"";return}this.referenceStatus.textContent=""}pictureFailureText(e){switch(e.kind){case"notShared":return this.messages.referenceNotShared;case"status":return this.messages.referenceNotFound.replace("{status}",String(e.status));case"notPicture":return this.messages.referenceNotPicture;default:return this.messages.referenceUnreachable}}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,i=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(n=>{if(n.id!==this.currentReferenceId)return n;const r=n.src,a={headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||_f))},o=n.registration,l=a.headingDeg!==o.headingDeg||a.pitchDeg!==o.pitchDeg||a.rollDeg!==o.rollDeg||a.fovDeg!==o.fovDeg;return{...n,kind:this.referenceKindSelect.value,src:r,title:this.said.write(n.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:i===void 0||Number.isNaN(i)?void 0:Math.round(i*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:a,from:l?this.observerPositionNow()??n.from:n.from}});const s=e.references.find(n=>n.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(s),this.syncReferenceStatus(s),this.ufoElement.refresh()}useObserverPoseForReference(){const e=st(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=st(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 s=this.ufoElement.sighting,n=st(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${s.references.length+1}`,a={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:_8,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:_f},from:this.observerPositionNow(),...i};s.references=[...s.references,a],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSourceInput.mode="url",this.referenceSourceInput.focus()}addReferenceFromFile(){this.addReference(""),this.referenceSourceInput.mode="file",this.referenceSourceInput.openPicker()}async setReferenceSource(e){const t=this.currentReferenceId;if(t===void 0)return;let i;if(e.file){const n=e.file;i=await new Promise((r,a)=>{const o=new FileReader;o.onload=()=>r(o.result),o.onerror=()=>a(o.error),o.readAsDataURL(n)})}else i=e.url;const s=this.ufoElement.sighting;s.references=s.references.map(n=>n.id!==t?n:{...n,src:i,title:n.title??(e.file?this.said.write(void 0,e.file.name.replace(/\.[^.]+$/,""),this.writingLanguage):void 0)}),this.touch(),this.refreshReferenceList(),this.ufoElement.refresh()}pictureAspect(e){if(!this.pictureRegistration){this.loadPictureRegistration();return}return this.sceneElement.referenceAspect(e)}loadPictureRegistration(){return this.pictureRegistrationLoading??=oe(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-cp0utyhJ.js");return{PictureRegistration:e}},[],import.meta.url).then(({PictureRegistration:e})=>{this.pictureRegistration=e,this.ufoElement.refresh()})}currentReference(){return this.ufoElement.sighting.references.find(e=>e.id===this.currentReferenceId)}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const s=this.pictureAspect(t.id);if(!(s!==void 0&&this.pictureRegistration.picturePointOf(this.directionAtCanvasPoint(e),t.registration,s)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.pictureAspect(t.id):void 0;if(!t||i===void 0)return;const s=8;for(const n of this.currentLandmarks()){const r=this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(n.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=s)return{landmarkId:n.id,end:"picture"};const a=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(n.scene));if(a&&Math.hypot(a.x-e.x,a.y-e.y)<=s)return{landmarkId:n.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 s=i.x-t.startPointer.x,n=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(s,n)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+s*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-n*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const s=this.currentReference(),n=s?this.pictureAspect(s.id):void 0;if(!s||n===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(a=>{if(a.id!==e)return a;if(t==="scene")return{...a,scene:this.pictureRegistration.aimOf(r)};const o=this.pictureRegistration.picturePointOf(r,s.registration,n);return o?{...a,picture:o}:a})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||_f,i=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(i)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const i=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const r=this.pictureAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const a=this.pictureRegistration.picturePointOf(i,t.registration,r);if(!a){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=a,this.syncRegisterStatus(),this.ufoElement.refresh();return}const s=this.currentLandmarks(),n=this.nextLandmarkId(s);this.writeLandmarks([...s,{id:n,picture:this.pendingLandmark,scene:this.pictureRegistration.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=n,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(i=>i.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.pictureAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),s=this.pictureRegistration.solve(i,t,e.registration.fovDeg);s?(this.referenceFit={n:i.length,residualDeg:s.residualDeg},this.referenceHeadingInput.value=String(this.rounded(s.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(s.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(s.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(s.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return this.pictureRegistration.worldDirectionOf(e.picture,t.registration,i).angleTo(this.pictureRegistration.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const i=this.said.read(e.label);return i?`${t+1} · ${i}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),i=e?this.pictureAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[n,r]of t.entries()){const a=document.createElement("option");a.value=r.id;const o=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";a.textContent=this.landmarkLabel(r,n)+o,this.referenceLandmarksSelect.appendChild(a)}this.currentLandmarkId!==void 0&&!t.some(n=>n.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const s=t.find(n=>n.id===this.currentLandmarkId);wn.showPresence(this.shadow.getElementById("reference-landmark-row"),this.shadow.getElementById("reference-landmark-item"),t.length>0),this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=s===void 0,this.referenceLandmarkLabelInput.disabled=s===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(s?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(a=>a.id===e?{...a,label:this.said.write(a.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:a));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),s=i.findIndex(a=>a.id===e),n=this.currentReference(),r=n?this.pictureAspect(n.id):void 0;if(t&&s>=0){const a=n&&r!==void 0?` · ${this.landmarkResidualDeg(i[s],n,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[s],s)+a}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.pictureAspect(t.id);if(i===void 0)return;const{registration:s}=t,n=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(a=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a,s,i))),r=this.currentLandmarks().map((a,o)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a.picture,s,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(a.scene)),label:this.landmarkLabel(a,o),selected:a.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(a,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(this.pendingLandmark,s,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(n.every(a=>a!==void 0)?n:void 0,r.filter(a=>a.picture!==void 0),this.landmarkHint()),this.paintGhostFinding(e,t,i)};paintGhostFinding(e,t,i){const s=this.ghostFinding;if(!s||!this.ghostsShown||s.referenceId!==t.id||s.src!==t.src)return;const{search:n}=s,r=t.registration,a=d=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf({u:d.x/n.width,v:d.y/n.height},r,i)),o=[];for(const d of n.pairs){const u=a(d.ghost),p=a(d.light),f=a({x:d.ghost.x+d.ghost.radius,y:d.ghost.y});!u||!p||o.push({ghost:u,light:p,ghostRadius:f?Math.hypot(f.x-u.x,f.y-u.y):0})}const l=n.centre?a(n.centre):void 0,h=n.cropped?a({x:n.width/2,y:n.height/2}):void 0;e.paintGhosts(o,l,h)}adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:s}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(s??0)),this.updateObserver();const n=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(l=>l.t===n);if(r<0)return;const a=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),o=[["headingDeg",t],["pitchDeg",i],["rollDeg",s??0]];for(const[l,h]of o)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${l}`,{basis:"derived",rationale:a,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceAddMenu.setDisabled("street",e?void 0:this.messages.referenceStreetNoPlace)}setReferenceAddKinds(e,t,i){const s=this.numberOrUndefined(this.latInput?.value??"")!==void 0&&this.numberOrUndefined(this.lngInput?.value??"")!==void 0;this.referenceAddMenu.setKinds([{value:"address",label:e},{value:"file",label:t},{value:"street",label:i,...s?{}:{disabledReason:this.messages?.referenceStreetNoPlace??""}}])}addReferenceOfKind(e){switch(e){case"file":this.addReferenceFromFile();break;case"street":this.searchStreetPictures();break;default:this.addReferenceFromAddress()}}async searchStreetPictures(){const e=st(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 s=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.addReferenceButton.disabled=!0;try{this.streetPictures$??=new(await oe(async()=>{const{PanoramaxPictures:r}=await import("./PanoramaxPictures-CELY3Ecc.js");return{PanoramaxPictures:r}},[],import.meta.url)).PanoramaxPictures,this.streetPictures=await this.streetPictures$.nearby(t,i,s)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.addReferenceButton.disabled=!1;return}this.addReferenceButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,a]of this.streetPictures.entries()){const o=document.createElement("option");o.value=String(r),o.textContent=this.streetPictureLabel(a,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(o)}const n=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!n,this.referenceStreetAddButton.hidden=!n,this.referenceStatus.textContent=n?"":this.messages.referenceStreetNone.replace("{m}",String(s))}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:_f}})}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;wn.showPresence(this.shadow.getElementById("trace-row"),this.shadow.getElementById("trace-item"),t);for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t;this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(s=>s.id!==this.currentTraceId?s:{...s,title:this.said.write(s.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(s.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(s=>s.value===this.currentTraceId),i=e.traces.find(s=>s.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTraces(e){const t=e.file?.name??decodeURIComponent(e.url.split("/").pop()??e.url);let i;try{const{KmlImport:h}=await oe(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url);i=await h.fromBytes(await u1.bytesOf(e))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(i.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const s=this.ufoElement.sighting,n=new Set(s.traces.map(h=>h.id));let r=1;const a=this.said.write(void 0,i.documentName??t,this.writingLanguage),o=i.traces.map(h=>{for(;n.has(`trace-${r}`);)r++;const d=`trace-${r}`;return n.add(d),{...h,id:d,title:h.title===void 0?void 0:this.said.write(void 0,h.title,this.writingLanguage),source:a}});s.traces=[...s.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const l=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",t)+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 IT){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(),t9)}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=fy(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 pv(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===_e.FILE_SOURCE;if(!e){const t=ds(oh,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new pv(t.create()))}if(this.setWeatherFromFile(e),this.weatherInferredInput.checked!==!e){this.weatherInferredInput.checked=!e,this.keepWeatherSource=e;try{this.weatherInferredInput.dispatchEvent(new Event("change"))}finally{this.keepWeatherSource=!1}}}keepWeatherSource=!1;setWeatherFromFile(e){const t=this.ufoElement.sighting;if(Ns.fromFile(t.frozen,"weather")===e)return;const i={...t.frozen??{}};e?i.weather={...i.weather??{},live:void 0}:delete i.weather,i.weather&&i.weather.live===void 0&&delete i.weather.live,t.frozen=ts.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...oh.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,_e.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked;this.weatherProviderSelect.value=e?_e.FILE_SOURCE:ds(oh,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const t=ds(oh,this.chosenSourceId.get("weather")),i=this.shadow.getElementById("weather-credit");i.hidden=e,i.href=t.creditUrl,i.textContent=t.credit,this.weatherFileLink.hidden=!e,e&&(this.weatherFileLink.textContent=this.weatherFileItemLabel(),this.weatherFileLink.title=this.sectionFilePanel?.where("weather")??"")}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.setWeatherFromFile(!this.weatherFromRecords),this.weatherFromRecords?this.scheduleWeatherLookup(!0):(this.cancelWeatherLookup(),this.keepWeatherSource||(this.ufoElement.sighting.weatherSource=void 0),this.syncWeatherSourceState())}scheduleWeatherLookup(e=!1){if(!this.weatherFromRecords||this.pendingWeatherEdit!==void 0)return;const t=this.ufoElement.sighting.weatherSource;!e&&t!==void 0&&!bv(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),tE))}cancelWeatherLookup(){clearTimeout(this.weatherLookupTimer),this.weatherLookupToken++,this.weatherLookupPending=!1}async inferWeather(){if(!this.weatherFromRecords)return;const e=++this.weatherLookupToken;this.weatherLookupPending=!0,this.syncWeatherSourceState();const t=await this.weatherInference.infer(this.ufoElement.sighting);e!==this.weatherLookupToken||!this.weatherFromRecords||(this.weatherLookupPending=!1,this.weatherLookupResult=t,t.status==="inferred"?(this.weatherInference.applyTo(this.ufoElement.sighting,t),this.weatherTrackSpan=this.ufoElement.seekableDuration,this.ufoElement.refresh(),this.syncWeatherFromTimeline()):this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}ensureWeatherTrackSpan(){const e=this.ufoElement.sighting.weatherSource;if(!this.weatherFromRecords||e===void 0||!bv(e))return;const t=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||t===this.weatherTrackSpan||(this.weatherTrackSpan=t,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const a of this.weatherFields)a.disabled=t&&e!==void 0&&a!==this.iceCrystalAlignmentInput&&a!==this.rareIceCrystalsInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?a.title=this.messages.weatherWhilePlaying:a.title===this.messages.weatherWhilePlaying&&(a.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&bv(e)){this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState();return}this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const s=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=s,this.labelWeatherInferred.title=s,this.syncWeatherProvider();const n=t&&e!==void 0;if(this.weatherSourceLink.hidden=!n,n){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const r=i?t?this.weatherStatusMessage():"":this.weatherUnavailableMessage();this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""||!i}startDateHalfEntered(){return this.shadow.getElementById("obs-time-native")?.validity.badInput===!0}weatherUnavailableMessage(){const e=this.weatherInference.missingOf(this.ufoElement.sighting);return this.startDateHalfEntered()&&(e.date=!0),e.date&&e.place?this.messages.weatherNeedsDateAndPlace:e.date?this.messages.weatherNeedsDate:this.messages.weatherNeedsPlace}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&sn(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`, ${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherLookupResult=void 0,this.weatherFromRecords=!Ns.fromFile(e.frozen,"weather")&&(e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0),this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=If[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(this.sectionFromFile("lightPollution"))return!1;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),tE)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,s=this.lightPollutionProvider,n=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||n===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(n<s.year){r(),this.lightPollutionLookup={status:"too-early",year:n},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const a=await s.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=a,a.status==="found"?(e.lightPollution=a.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${s.citation}, at ${a.lat.toFixed(4)}, ${a.lng.toFixed(4)}: ${Math.round(a.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:a.lightPollution}),this.lightPollutionInput.value=String(a.lightPollution),this.ufoElement.refresh()):a.status==="natural"&&r(),this.syncLightPollutionStatus())}syncLightPollutionStatus(){const e=this.lightPollutionLookup,t=this.messages;let i="";switch(e?.status){case"pending":i=t.lightPollutionLookingUp;break;case"found":i=t.lightPollutionFound.replace("{artificial}",Math.round(e.artificialMcdPerM2*1e3).toLocaleString(this.language));break;case"natural":i=t.lightPollutionNatural;break;case"outside":i=t.lightPollutionOutside;break;case"failed":i=t.lightPollutionFailed;break;case"too-early":i=t.lightPollutionTooEarly.replace("{atlasYear}",String(this.lightPollutionProvider.year)).replace("{year}",String(e.year));break}this.lightPollutionStatusText.textContent=i===""?"":`${i} `,this.lightPollutionSourceRow.hidden=!(e?.status==="found"||e?.status==="natural"||e?.status==="outside")}syncDurationField(){const e=this.shadow.activeElement;if(e!==this.durationInput&&e!==this.durationElement.textField){const t=this.ufoElement.sighting.event,i=Qh(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=D3(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;Ee.show(this.playPauseButton,e?"⏸":"▶"),this.playPauseButton.disabled=!t;const i=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch();for(const[s,n]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])s.title=n,s.setAttribute("aria-label",n);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,s]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${s} — ${t}`:s,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(Ks.opensPrecise(e.time)),this.endDate.setPrecise(Ks.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),s=e!==void 0&&i!==void 0&&Math.abs(e-i)>r9;this.utcOffsetInput.classList.toggle("invalid",s),this.utcOffsetInput.title=s?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),s9))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<nh&&Math.abs(e.lng-i)<nh}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=ds(Ef,this.chosenSourceId.get("elevation")),n=await new p1(s.create()).at(e,t);if(i!==this.groundElevationToken||n===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(n),this.syncElevationField(r)}syncElevationField(e){const t=this.groundElevationM;this.elevationInput.value=String(Math.round((t??0)+e)),this.elevationInput.min=t===void 0?"":String(t),this.elevationInput.title=t===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=t===void 0||Math.round(e)===0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(st(this.ufoElement.sighting,0)?.elevationM??0),this.scheduleGroundElevation()}syncPlaceNameField(){const e=this.ufoElement.sighting.event.place?.[0],t=e?.name??"";this.placeNameInput.value=t,this.placeNameInput.title=t,this.namedCoordinates=e&&t?{lat:e.lat,lng:e.lng}:void 0,this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=""}syncObserverMetadataFields(){this.witnessErrorView?.refresh();const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=this.said.read(e.observer?.title)??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.observerList.rename(_e.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(Ks.opensPreciseDate(e.account?.observerBirth)),this.perceptionSettings.values=e.account?.observerPerception??{},this.birth=e.account?.observerBirth,this.birthDate.time=this.birth,this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.evaluationFields.show(e.account),this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"";const t=e.lens;this.lensGlassSelect.value=t?.glass??"",this.lensDropsInput.value=t?.drops?.toString()??"",this.lensCondensationInput.value=t?.condensation?.toString()??"",this.lensDirtInput.value=t?.dirt?.toString()??"",this.lensShelteredInput.checked=t?.sheltered===!0,this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=fs(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??qf)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??hE)),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],s=this.shadow.activeElement;s!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),s!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),this.syncObserverPosition(),s!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),s!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),s!==this.elevationInput&&this.syncElevationField(t?.elevationM??0)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,n=i.getInterpolatedShapeAt(s,this.currentSourceId),r=this.buildAppearanceShape(e??n?.bounds??this.defaultBounds(),n,t);this.commitShapes(s,[{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 s=E1(e,this.currentAppearance);return t?{...s,angle:t.angle,title:t.title,selected:t.selected}:s}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();for(const[i,s]of this.groupTabs.entries()){const n=s===e&&t;s.setAttribute("aria-expanded",String(n)),this.groupPanels[i].hidden=!n}if(t){const i=e.parentElement.getBoundingClientRect(),s=e.getBoundingClientRect();(s.left<i.left||s.right>i.right)&&(e.parentElement.scrollLeft+=s.left-i.left-(i.width-s.width)/2)}if(t&&e.getAttribute("aria-controls")==="group-decor"){const i=this.decorList.value;i!==""&&i!==this.currentDecorId&&this.selectDecor(i)}t&&e.getAttribute("aria-controls")==="group-observer"&&this.observerShown!==_e.OBSERVER_PRINCIPAL&&this.selectDecor(this.observerShown),t&&e.getAttribute("aria-controls")==="group-weather"&&this.syncSkyParts(),t&&e.getAttribute("aria-controls")==="group-shape"&&this.showPhenomenonPartWithContent(),t&&e.getAttribute("aria-controls")==="group-observation"&&this.candidatesView?.refresh(),this.placeDecorItem(),this.syncCanvasMode(),this.refreshTimelineMarks(),t&&this.sectionFolds.refresh(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>{this.syncFileEditor(!1),this.showFileItem(this.fileItemSelect.value)},()=>this.showFileNote(this.messages.importError,"error"))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await oe(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-BekK-f3R.js");return{SightingFileEditor:t}},__vite__mapDeps([16,1,17]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileTextApplied=this.historySnapshot,this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel,{baseline:this.touched?this.savedFileText:this.fileText(),phrases:this.messages.fileSearchPhrases,caretMoved:t=>this.onFileCaret(t)}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}fileSyncActive(){return this.fileEditor!==void 0&&this.isGroupIdOpen("group-file")}fileFocus;caretTimer;followingCaret=!1;onFileCaret(e){clearTimeout(this.caretTimer),this.caretTimer=setTimeout(()=>this.focusFromFile(e),120)}focusFromFile(e){if(!this.fileSyncActive())return;const t=this.ufoElement.sighting;this.followingCaret=!0;try{const i=e[0]==="decor"&&typeof e[1]=="number"?t.decor[e[1]]:void 0;if(i!==void 0){this.fileFocus="decor",this.selectDecor(i.id);return}const s=e[0]==="timeline"&&e[1]==="keyframes"&&typeof e[2]=="number"&&e[3]==="shapes"&&typeof e[4]=="number"?t.timeline.allKeyframes[e[2]]?.shapes[e[4]]:void 0;if(s!==void 0){this.fileFocus="shape",this.selectUnit(s.sourceId),this.syncCanvasMode(),this.ufoElement.refresh();return}this.fileFocus=void 0,this.syncCanvasMode(),this.ufoElement.refresh()}finally{this.followingCaret=!1}}showInFile(e){this.followingCaret||e===void 0||!this.fileSyncActive()||this.fileEditor.reveal(e)}bodyPath(e){try{const i=(JSON.parse(this.fileEditor.text).interpretation?.bodies??[]).findIndex(s=>s.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,s]of t.entries()){const n=s.shapes.findIndex(r=>r.sourceId===e);if(n>=0)return["timeline","keyframes",i,"shapes",n]}}showFileNote(e,t="info"){Xt.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.sightingData)}writtenText(e){const t=this.keyframesWritten();return xw.of(e,t,t==="thin"?Si.derivable(this.ufoElement.sighting):void 0)}keyframesWritten(){return this.wholeKeyframesInput.checked?"whole":"thin"}static WHOLE_KEYFRAMES_STORAGE="rr0-sighting-editor.whole-keyframes";setKeyframesWritten(){try{this.wholeKeyframesInput.checked?localStorage.setItem(_e.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(_e.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=ky(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=xw.of(um(e),t,t==="thin"?Si.derivable(e):void 0),this.savedFileText=this.baseline}this.resetHistory()}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(e=!0){const t=this.fileEditor;if(!(t===void 0||!this.isGroupIdOpen("group-file")||t.focused)&&!this.historyAnswering){if(t.edited)try{JSON.parse(t.text)}catch{return}t.replaceText(this.fileText(),e),this.fileTextApplied=t.text}}onFileTextEdited(e){this.syncHistoryButtons(),clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e,t=!1){this.fileApplyTimer=void 0;let i;try{i=JSON.parse(e)}catch{return}if(typeof i!="object"||i===null||Array.isArray(i)||!t&&JSON.stringify(i)===JSON.stringify(this.sightingData))return;const s=this.ufoElement.currentTime,n=!t&&this.fileTextApplied!==void 0&&JSON.stringify(i.weatherTrack)!==JSON.stringify(_e.weatherOf(this.fileTextApplied)),r={track:this.sightingData.weatherTrack,source:this.sightingData.weatherSource};this.applyingFileText=!0;try{if(this.sightingData=i,this.touched=!0,this.ufoElement.currentTime=s,n&&!this.restoringWeather&&this.weatherFromRecords){const a=this.ufoElement.sighting.weatherSource;a===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):oh.some(o=>o.id===a.id)&&this.askAboutWeather(r,a.name??a.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(a){this.showFileNote(a instanceof wu?a.said(this.messages.formatVersionError):this.messages.importErrorMalformed,"error"),this.fileTextApplied=e}finally{this.applyingFileText=!1}}fileTextApplied;static weatherOf(e){try{return JSON.parse(e).weatherTrack}catch{return}}pendingWeatherEdit;restoringWeather=!1;askAboutWeather(e,t){this.cancelWeatherLookup(),this.pendingWeatherEdit=e,this.shadow.getElementById("file-ask-text").textContent=this.messages.weatherEditedAsk.replaceAll("{source}",t),this.shadow.getElementById("file-ask-stop").textContent=this.messages.weatherEditedStop,this.shadow.getElementById("file-ask-keep").textContent=this.messages.weatherEditedKeep,typeof this.fileAsk.showModal=="function"?this.fileAsk.showModal():this.fileAsk.setAttribute("open","")}closeFileAsk(){typeof this.fileAsk.close=="function"?this.fileAsk.close():this.fileAsk.removeAttribute("open")}stopReadingWeather(){this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState(),this.ufoElement.refresh(),this.syncFileEditor(!1)}keepReadingWeather(){const e=this.pendingWeatherEdit;if(this.pendingWeatherEdit=void 0,this.closeFileAsk(),e!==void 0){this.restoringWeather=!0;try{this.applyFileText(JSON.stringify({...this.sightingData,weatherTrack:e.track,weatherSource:e.source}))}finally{this.restoringWeather=!1}this.syncFileEditor(!1)}}applyingFileText=!1;leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(!1),0))}static SCENE_LINKED=["heading","pitch","focalLength","apparentWidth","realWidth","objectDistance","color","haloScale","cloudCover","windDirection","windSpeed","referenceOpacity"];setActiveSceneField(e){e!==this.activeSceneField&&(this.activeSceneField=e,e==="referenceOpacity"&&!this.ufoElement.referencesShown?(this.ufoElement.toggleReferences(),this.referencesShownForField=!0):e!=="referenceOpacity"&&this.referencesShownForField&&(this.ufoElement.referencesShown&&this.ufoElement.toggleReferences(),this.referencesShownForField=!1),this.refreshSceneField())}refreshSceneField(){const e=this.sceneFieldOverlay;if(!e)return;const t=this.activeSceneField,i=this.ufoElement.sighting,s=this.ufoElement.currentTime,n=this.ufoElement.canvasElement,r=this.messages,a=l=>this.numberOrUndefined(l.value),o=(l,h=1)=>l===void 0?"?":l.toLocaleString(this.language,{maximumFractionDigits:h});if(t==="pitch"){const l=a(this.pitchInput)??0,h=ar.of(i.instrument,n.height,Si.fovOf(i,s)),d=Math.sign(l)*h.angleDegToRadiusPx(Math.min(89,Math.abs(l))),u=Math.min(1,Math.max(0,(n.height/2+d)/n.height));e.horizon(u,r.overlayHorizon.replaceAll("{deg}",o(l)))}else if(t==="focalLength"){const l=Si.fovOf(i,s),d=2*ar.of(i.instrument,n.height,l).halfWidthAngleDeg(n.width/n.height);e.frame(r.overlayFov.replaceAll("{v}",o(l)).replaceAll("{h}",o(d)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const l=i.timeline.getInterpolatedShapeAt(s,this.currentSourceId);if(!l){e.hide();return}const h=l.bounds,u=[[a(this.apparentWidthInput),"°",1],[a(this.realWidthInput)," m",1],[a(this.objectDistanceInput)," m",0]].filter(([p])=>p!==void 0).map(([p,f,m])=>`${o(p,m)}${f}`).join(" · ");e.measure((h.x+h.width/2)/n.width,(h.y+h.height/2)/n.height,Math.max(h.width,h.height)*1.3/n.width,u)}else if(t==="windDirection"||t==="windSpeed"){const l=a(this.windDirectionInput)??0,h=l-(a(this.headingInput)??0);e.wind(h,r.overlayWind.replaceAll("{point}",this.naming.point(l)).replaceAll("{speed}",o(a(this.windSpeedInput))))}else e.hide()}attachWitnessErrors(){const e=this,t=()=>this.ufoElement.sighting,i=()=>this.ufoElement.currentTime,s=this.shadow.querySelector('rr0-date-input[name="obs-time"]');this.witnessErrorView.attach({kind:"time",label:s.closest("label"),input:s,path:()=>t().event.time?"time":void 0,value:()=>t().event.time?.hour!==void 0?0:void 0}),this.witnessErrorView.attach({kind:"duration",label:this.durationElement.closest("label"),input:this.durationElement,path:()=>t().event.durationSeconds!==void 0?"durationSeconds":void 0,value:()=>t().event.durationSeconds});const n=l=>{let h=-1;return l.forEach((d,u)=>{d<=i()&&(h=u)}),h===-1&&l.length>0?0:h};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const l=n(t().observerTrack.allKeyframes.map(h=>h.t));return l===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${l}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const l=t().timeline.allKeyframes,h=n(l.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId)).map(f=>f.t));if(h===-1||this.apparentWidthInput.value==="")return;const d=l.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId))[h],u=l.indexOf(d),p=d.shapes.findIndex(f=>f.sourceId===this.currentSourceId);return`timeline.keyframes.${u}.shapes.${p}.shape.angular`},value:()=>this.numberOrUndefined(this.apparentWidthInput.value)});const r=this.shadow.getElementById("observerPerception").closest(".form-section");this.witnessErrorView.placeObserverSections(r);const a=document.createElement("div");a.className="form-section candidates-section",this.shadow.getElementById("group-observation").append(a);const o=l=>l?.closest("label")??void 0;this.candidatesView=new mn({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const l=this.ufoElement.sighting.event,h=l.place?.[0];if(!h||l.time?.year===void 0||l.time.hour===void 0)return;const d=sn(l.time,h.lng,l.utcOffsetHours);return d?{date:d,observer:{lat:h.lat,lng:h.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:l=>Ta(l,this.instrumentGain()),fieldLabels:()=>({time:o(s),heading:o(this.headingInput),size:o(this.apparentWidthInput),duration:o(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:l=>{const h=`${l}/${this.language}`;return this.poherMatrix?.key!==h&&(this.poherMatrix={key:h,loaded:bl.load(l,this.language,d=>na.json(d))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const l=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,h=this.sceneElement.satellitePassesDuring(l);return h.length>0?{passes:h,positionsAt:d=>this.sceneElement.satellitePositionsAt(d)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const l=this.ufoElement.sighting.interpretation;return[...l&&l.bodies.length>0?[{id:"own",label:this.said.read(l.title)??this.principalObserverLabel(),interpretation:l}]:[],...this.readings]},starName:l=>this.naming.star({name:l}),projectionAt:(l,h)=>this.sceneElement.bodyProjectionAt(l,h),variants:()=>this.ufoElement.sighting.variants,keep:l=>this.editVariants(h=>[...h,l]),remove:l=>this.editVariants(h=>h.filter((d,u)=>u!==l))},a)}readings=[];editVariants(e){this.touch(),this.armHistory(),this.ufoElement.sighting.variants=e(this.ufoElement.sighting.variants),this.scheduleHistoryRecord()}poherMatrix;poherFacts(){const e=this.ufoElement.sighting,t={},i=e.event,s=i.place?.[0];if(s&&i.time?.year!==void 0&&i.time.hour!==void 0){const h=sn(i.time,s.lng,i.utcOffsetHours);h&&(t.sunAltitudeDeg=zi("Sun",h,{lat:s.lat,lng:s.lng,elevationM:this.groundElevationM??0}).altitudeDeg)}if(i.durationSeconds!==void 0&&(t.durationSeconds=i.durationSeconds),e.weatherTrack.allKeyframes.length>0){const h=fs(e,0);t.cloudCover=h.cloudCover,t.lightning=h.storm,t.lowVisibility=h.precipitationType!=="none"&&h.precipitationIntensity>.3}const n=e.timeline,r=n.sourceIds[0];if(r){const h=n.allKeyframes.filter(p=>p.shapes.some(f=>f.sourceId===r)),d=h.map(p=>({t:p.t,shape:n.getShapeAt(p.t,r)})).filter(p=>p.shape?.aim),u=n.getInterpolatedShapeAt(h[0]?.t??0,r);if(u?.aim&&(t.elevationDeg=u.aim.altitudeDeg),u?.angular){t.widthDeg=u.angular.widthDeg;const p=u.angular.heightDeg>0?u.angular.widthDeg/u.angular.heightDeg:1;t.round=u.kind==="oval"&&p>.8&&p<1.25}if(u?.brightness!==void 0&&(t.brightness=u.brightness),d.length>1){const p=(g,b)=>{const w=Math.PI/180,y=Math.sin(g.altitudeDeg*w)*Math.sin(b.altitudeDeg*w)+Math.cos(g.altitudeDeg*w)*Math.cos(b.altitudeDeg*w)*Math.cos((g.azimuthDeg-b.azimuthDeg)*w);return Math.acos(Math.max(-1,Math.min(1,y)))/w},f=d.slice(1).map((g,b)=>({deg:p(d[b].shape.aim,g.shape.aim),s:(g.t-d[b].t)/1e3}));t.sweepDeg=p(d[0].shape.aim,d[d.length-1].shape.aim);const m=f.reduce((g,b)=>g+b.deg,0);t.straysDeg=Math.max(0,m-t.sweepDeg)/2;const v=(d[d.length-1].t-d[0].t)/1e3;if(v>0){t.speedDegPerS=m/v;const g=Math.max(...f.filter(b=>b.s>0).map(b=>b.deg/b.s));t.speedVariation=t.speedDegPerS>0?g/t.speedDegPerS:0}}}const a=new Set(n.sourceIds.map(h=>n.groupMembers(h)?.[0]??h));a.size>0&&(t.count=a.size);const o=[...a].map(h=>n.getInterpolatedShapeAt(0,h)?.aim).filter(h=>h!==void 0);if(o.length>=3){const h=Math.PI/180,d=o.map(m=>({x:(((m.azimuthDeg-o[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*h),y:m.altitudeDeg}));let[u,p]=[d[0],d[1]];for(const m of d)for(const v of d)Math.hypot(m.x-v.x,m.y-v.y)>Math.hypot(u.x-p.x,u.y-p.y)&&([u,p]=[m,v]);const f=Math.hypot(u.x-p.x,u.y-p.y);t.aligned=f>0&&d.every(m=>Math.abs((p.x-u.x)*(u.y-m.y)-(u.x-m.x)*(p.y-u.y))/f<=Math.max(.5,f*.1))}const l=new Set([...a].map(h=>n.getInterpolatedShapeAt(0,h)?.color).filter(h=>h!==void 0));return l.size>0&&(t.colors=[...l]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(h=>h.sound.kind!=="none")&&(t.sound=!0),t}candidatesTimer;refreshCandidatesSoon(){clearTimeout(this.candidatesTimer),this.isGroupIdOpen("group-observation")&&(this.candidatesTimer=setTimeout(()=>this.candidatesView?.refresh(),150))}showOverlays(){const e=this.shadow.querySelector(".scene-card");e.dataset.shown="",clearTimeout(this.overlayTimer),this.overlayTimer=setTimeout(()=>delete e.dataset.shown,3500)}static SCENE_HEIGHT_KEY="rr0-editor-scene-height";resizeScene(e){const t=this.shadow.querySelector(".app"),i=this.sceneElement,s=n=>{n===void 0?t.style.removeProperty("--rr0-scene-max-height"):t.style.setProperty("--rr0-scene-max-height",`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,n)))}px`);try{n===void 0?localStorage.removeItem(_e.SCENE_HEIGHT_KEY):localStorage.setItem(_e.SCENE_HEIGHT_KEY,t.style.getPropertyValue("--rr0-scene-max-height"))}catch{}};try{const n=localStorage.getItem(_e.SCENE_HEIGHT_KEY);n&&/^\d+px$/.test(n)&&t.style.setProperty("--rr0-scene-max-height",n)}catch{}e.addEventListener("pointerdown",n=>{n.preventDefault();const r=n.clientY,a=i.getBoundingClientRect().height;e.setPointerCapture?.(n.pointerId),e.classList.add("dragging");const o=h=>s(a+h.clientY-r),l=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",l),e.removeEventListener("pointercancel",l)};e.addEventListener("pointermove",o),e.addEventListener("pointerup",l),e.addEventListener("pointercancel",l)}),e.addEventListener("keydown",n=>{n.key!=="ArrowUp"&&n.key!=="ArrowDown"||(n.preventDefault(),s(i.getBoundingClientRect().height+(n.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>s(void 0))}setTracksShown(e){this.shadow.querySelector(".scene-card").toggleAttribute("data-tracks",e),this.shadow.getElementById("timeline-tracks").hidden=!e,this.tracksToggle.setAttribute("aria-expanded",String(e));const i=e?this.messages.collapseTracks:this.messages.expandTracks;this.tracksToggle.title=i,this.tracksToggle.setAttribute("aria-label",i),this.refreshTracks()}flash(e){e&&(e.classList.add("flash"),setTimeout(()=>e.classList.remove("flash"),1800))}refreshTracks(){if(!this.timelineTracks||this.tracksToggle.getAttribute("aria-expanded")!=="true")return;const e=this.ufoElement.sighting,t=this.messages,i=a=>{const o=this.groupTabs.find(l=>l.getAttribute("aria-controls")===a);o&&this.toggleGroup(o,!0)},s=a=>()=>{this.touch(),this.armHistory(),a(),this.scheduleHistoryRecord(),this.refreshTimelineMarks()},r=[this.showsBodies?{id:"bodies",label:t.bodiesTrack,color:"#f5c451",...this.eventMarks("bodies"),open:()=>this.chooseAccountView(!0),selected:this.pickedEvent(this.bodiesEventsPanel),select:a=>this.pickEvent(Number(a)),add:()=>this.bodyEditor?s(()=>this.bodyEditor.keyframeHere())():this.chooseAccountView(!0)}:{id:"shapes",label:t.shapesTrack,color:"#f5c451",...this.eventMarks("phenomenon"),open:()=>this.revealShapePanel(),selected:this.pickedEvent(this.phenomenonEventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>{e.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,!1)})},{id:"observer",label:t.observerTrack,color:"#7fd4ff",...this.eventMarks("observer"),open:()=>i("group-location"),selected:this.pickedEvent(this.eventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>this.updateObserver())},{id:"weather",label:t.weatherTrack,color:"#b9c8d8",times:e.weatherTrack.allKeyframes.map(a=>a.t),open:()=>i("group-weather"),add:s(()=>this.applyWeatherAtPlayhead())},{id:"sound",label:t.soundTrack,color:"#9fd9a8",times:e.soundTrack.allKeyframes.map(a=>a.t),open:()=>i("group-sound"),add:s(()=>this.applySoundAtPlayhead())}];this.timelineTracks.show(r,this.ufoElement.seekableDuration,this.ufoElement.currentTime)}eventMarks(e){const t=this.ufoElement.sighting;if(e==="bodies")return this.bodyMarks();const i=e==="observer"?lt.observerTrackIsExpanded(t):lt.timelineIsExpanded(t),s=e==="observer"?t.observerTrack.allKeyframes:t.timeline.allKeyframes;if(!i)return{times:s.map(h=>h.t)};const n=this.ufoElement.seekableDuration,r=h=>e==="observer"?Ht.isObserver(t,h):Ht.isPhenomenon(t,h),a=(t.events??[]).map((h,d)=>({event:h,index:d})).filter(({event:h})=>r(h)),o=new Set(a.map(({event:h})=>h.who)).size>1,l=a.map(({event:h,index:d})=>{const u=this.messages.events.kinds[h.eventType]??h.eventType;return{id:String(d),t:h.t,until:h.until??n,label:e==="phenomenon"&&o?`${this.shapesLabel(h.who??"")} · ${u}`:u}});return{times:[],spans:l}}bodyMarks(){const e=this.ufoElement.sighting,t=e.interpretation?.bodies??[],i=new Set(t.map(o=>o.id)),s=o=>Ht.partOf(o)?.element??o??"",n=(e.events??[]).map((o,l)=>({event:o,index:l})).filter(({event:o})=>i.has(s(o.who)));if(n.length===0||!lt.bodiesAreExpanded(e))return{times:[...new Set(t.flatMap(o=>o.track.map(l=>l.t)))].sort((o,l)=>o-l)};const r=this.ufoElement.seekableDuration,a=n.map(({event:o,index:l})=>{const h=t.find(f=>f.id===s(o.who)),d=Ht.partOf(o.who)?.part,u=this.messages.events.kinds[o.eventType]??o.eventType,p=[...t.length>1?[this.said.read(h?.title)??s(o.who)]:[],...d?[d]:[]];return{id:String(l),t:o.t,until:o.until??r,label:[...p,u].join(" · ")}});return{times:[],spans:a}}pickedEvent(e){const t=e?.pickedIndex,i=e===this.eventsPanel?"events-section":e===this.phenomenonEventsPanel?"phenomenon-events-section":"bodies-events-section",s=this.shadow.getElementById(i);return t===void 0||!s||s.closest("[hidden]")?void 0:String(t)}pickEvent(e){const t=this.ufoElement.sighting,i=t.events?.[e];if(!i)return;const s=i.who??Ht.observerId(t);if(Ht.isObserver(t,i)){const n=this.groupTabs.find(r=>r.getAttribute("aria-controls")==="group-location");n&&this.toggleGroup(n,!0),this.eventsPanel.pick(e)}else Ht.isPhenomenon(t,i)?(this.revealShapePanel(),this.phenomenonEventsPanel.pick(e)):(this.chooseAccountView(!0),this.loadBodyEditor().then(n=>{n.show(Ht.partOf(s)?.element??s),this.bodiesEventsPanel.pick(e),this.refreshTracks()}));this.goToMark(i.t),this.refreshTracks()}shapesLabel(e){const t=this.ufoElement.sighting,i=t.timeline.groupOf(e);if(i)return this.said.read(i.title)??e;const s=t.timeline.allKeyframes.map(n=>n.shapes.find(r=>r.sourceId===e)?.shape.title).find(n=>n!==void 0);return this.said.read(s)??e}get showsBodies(){return this.accountViewSelect.value==="bodies"}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(o,l)=>[...l].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${o})`})),i=o=>{if(this.showsBodies){const h=this.eventMarks("bodies");return h.spans?h.spans.map(d=>({t:d.t,kind:"event",label:d.label})):t(this.messages.bodiesTrack,h.times)}const{spans:l}=this.eventMarks("phenomenon");return l?l.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(h=>!o||h.shapes.some(d=>this.selectedSourceIds.has(d.sourceId))).map(h=>h.t))},s=()=>{const{times:o,spans:l}=this.eventMarks("observer");return l?l.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.observerTrack,o)},n=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(o=>o.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(o=>o.t)),a=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?s():this.isGroupIdOpen("group-weather")?n():this.isGroupIdOpen("group-sound")?r():[...i(!1),...s(),...n(),...r()];for(const o of e.milestones)a.push({t:o.t,kind:"milestone",label:this.said.read(o.label)??""});this.timelineMarks.show(a,this.ufoElement.seekableDuration),this.refreshTracks(),this.eventsPanel?.sync(),this.phenomenonEventsPanel?.sync(),this.bodiesEventsPanel?.sync(),this.witnessErrorView?.refreshFields(),this.activeSceneField&&this.refreshSceneField()}seekTo(e){this.goToMark(e*1e3)}set passages(e){const t=this.shadow.getElementById("moment-passages");t.replaceChildren(...(e??[]).map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.className="at",n.innerHTML=tt.PLAY,n.append(i.clock),n.addEventListener("click",()=>this.seekTo(i.at));const r=document.createElement("button");return r.type="button",r.className="excerpt",r.textContent=i.said,r.title=i.where,r.addEventListener("click",()=>i.open()),s.append(n,r),s})),t.hidden=t.childElementCount===0}openSection(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);t&&this.toggleGroup(t,!0)}showRender(){this.sceneElement.scrollIntoView?.({block:"center",behavior:"smooth"})}goToMark(e){e!==void 0&&(this.ufoElement.currentTime=e,this.syncPlaybackControls())}isGroupIdOpen(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-file")?this.fileFocus==="decor"&&this.editableDecor()!==void 0?"decor":this.fileFocus==="shape"&&this.selectedSourceIds.size>0?"shape":"scene":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-weather")&&(this.shadow.getElementById("sky-launches")?.hidden===!1||this.shadow.getElementById("sky-beams")?.hidden===!1)?"scene":this.isGroupIdOpen("group-shape")?"shape":this.isGroupIdOpen("group-decor")&&this.editableDecor()!==void 0?"decor":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",i=this.lastCanvasMode==="picture",s=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",t&&this.currentReference()&&this.loadPictureRegistration(),this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,s&&this.ufoElement.repaintOverlay(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const n=this.currentReference();n&&this.syncReferenceStatus(n),this.syncStreetSearchAvailability(),this.syncBodiesShown()}skyOf(e){if(!(!e||!e.lanterns?.length&&!e.flares?.length))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],lanterns:e.lanterns,flares:e.flares}}),this.skyPart.sky}skyPart;syncBodiesShown(){const t=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading,i=this.ufoElement.sighting.interpretation,s=t?i:this.skyOf(i);this.sceneElement.compareAccount=t&&s!==void 0&&this.accountCompareInput.checked,this.sceneElement.interpretation!==s&&(this.sceneElement.interpretation=s);const n=t&&s!==void 0?"bodies":"shapes",r=this.accountViewSelect.value!==n;this.accountViewSelect.value=n,r&&this.refreshTimelineMarks(),this.syncSkyParts(),this.shadow.getElementById("account-view-row").hidden=this.isReading,this.shadow.getElementById("account-compare-row").hidden=this.isReading||n!=="bodies"}syncSkyParts(){this.isGroupIdOpen("group-weather")&&(this.shadow.getElementById("sky-beams")?.hidden===!1&&this.loadBeamEditor().then(e=>e.refresh()),this.shadow.getElementById("sky-lanterns")?.hidden===!1&&this.loadLanternEditor().then(e=>e.refresh()),this.shadow.getElementById("sky-launches")?.hidden===!1&&this.loadLaunchEditor().then(e=>e.refresh()))}chooseAccountView(e){const t=this.groupTabs.find(s=>s.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}openSubgroup(e){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const i of this.subgroupTabs){if(i.parentElement!==t)continue;const s=i===e;i.setAttribute("aria-expanded",String(s)),this.shadow.getElementById(i.getAttribute("aria-controls")).hidden=!s}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(i=>i.sync()),e.getAttribute("aria-controls")==="sky-launches"&&this.loadLaunchEditor().then(i=>i.sync()),e.getAttribute("aria-controls")==="sky-beams"&&this.loadBeamEditor().then(i=>i.sync()),e.getAttribute("aria-controls")==="sky-lanterns"&&this.loadLanternEditor().then(i=>i.sync()),this.syncCanvasMode()}showPhenomenonPartWithContent(){const e=this.ufoElement.sighting,t=e.timeline.sourceIds.length>0,i=(e.interpretation?.bodies?.length??0)>0,n=this.shadow.getElementById("shape-bodies")?.hidden===!1?!i&&t?"shape-shapes":void 0:!t&&i?"shape-bodies":void 0,r=n&&this.subgroupTabs.find(l=>l.getAttribute("aria-controls")===n);if(!r)return;const{sectionChosen:a,opensMostLacking:o}=this;this.openSubgroup(r),this.sectionChosen=a,this.opensMostLacking=o}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|"),s=JSON.stringify(this.ufoElement.sighting.account??null);if(i===this.paramSummarySignature){s!==this.assessedAccount&&(this.assessedAccount=s,this.runAssessments());return}this.assessedAccount=s,this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.runAssessments()}paramChips=[];renderParamSummary(){this.saveButton&&this.refreshEditorTitle();const e=_e.NESTED_GROUPS,t=[];let i;for(const s of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==s.group&&(i=void 0),e.includes(s.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=s.group;const a=document.createElement("span");a.className="param-nest-label",a.textContent=s.group==="assessment"?this.messages.assessmentGroup:s.group==="summary"?this.messages.summaryGroup:_e.tabLabel(this.groupTabs[this.summaryPanelIndex(s.group)]),r.append(a),i={group:s.group,element:r},t.push(r)}const n=this.paramChip(s);i?i.element.append(n):t.push(n)}this.paramSummary.replaceChildren(...t),this.shadow.getElementById("label-param-summary").textContent=this.messages.paramSummaryTitle.replace("{n}",String(t.length)),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),d2.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return this.panelIndex(e==="phenomenon"?"shape":e)}static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]},"bg-information":{panel:"observer",fields:["accountSource"]},"bg-occupation":{panel:"observer",fields:["observerOccupationKind"]},"bg-relation":{panel:"observer",fields:["observersRelation"]},"bg-activity":{panel:"observer",fields:["observerActivity"]},"bg-age":{panel:"observer",fields:["observerAge"]},"bg-appearance":{panel:"observer",fields:["strangeness-appearance"]},"bg-movement":{panel:"observer",fields:["strangeness-movement"]},"bg-incongruity":{panel:"observer",fields:["strangeness-incongruity"]},"bg-close":{panel:"observer",fields:["strangeness-close"]},"bg-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-occupants":{panel:"observer",fields:["strangeness-beings"]}};assessmentChips=[];assessmentToken=0;assessedAccount="";async runAssessments(){const e=++this.assessmentToken,t=await new Ry(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.openMostLackingGroup(),this.renderParamSummary())}opensMostLacking=!1;sectionChosen=!1;openMostLackingGroup(){if(!this.opensMostLacking)return;this.opensMostLacking=!1;const e=s=>{const n=s.querySelector(".tab-badge");return n&&!n.hidden?Number(n.textContent):0},t=this.groupTabs.find(s=>this.isGroupOpen(s));let i=t&&e(t)>0?t:void 0;for(const s of this.groupTabs)e(s)>(i?e(i):0)&&(i=s);i&&i!==t&&(this.toggleGroup(i,!0),this.sectionChosen=!1)}fitGroupTabs(){const e=this.groupTabs[0]?.parentElement;e&&(e.classList.add("measuring"),e.classList.remove("compact"),e.classList.toggle("compact",e.scrollWidth>e.clientWidth),e.offsetWidth,e.classList.remove("measuring"))}static titleGroupTab(e){e.title=[e.dataset.intro,e.dataset.unanswered].filter(Boolean).join(`
|
|
11574
|
+
`)}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 n of e){const r=_e.QUESTION_FIELDS[n];if(r&&!r.fields.some(a=>this.shadow.getElementById(a)?.classList.contains("missing-required")))for(const a of r.fields){const o=this.shadow.getElementById(a);o&&!o.hidden&&o.value===""&&t.add(a)}}for(const[n,r]of Object.entries(_e.QUESTION_FIELDS))for(const a of _e.QUESTION_FIELDS[n].fields){const o=this.shadow.getElementById(a);if(!o)continue;const l=t.has(a)&&!o.classList.contains("missing-required");o.classList.toggle("wanted",l),(l||o.title===this.messages.questionUnanswered)&&(o.title=l?this.messages.questionUnanswered:"")}const i=new Map;let s;for(const[n,r]of Object.entries(_e.QUESTION_FIELDS))for(const a of r.fields){const o=this.shadow.getElementById(a);if(!o)continue;const l=o.classList.contains("missing-required");!l&&!o.classList.contains("wanted")||(l&&(s=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const n of this.groupTabs){const r=this.panelOf(n),a=i.get(r)??0,o=r===s,l=_e.badgeOn(n);l.hidden=a===0,l.textContent=String(a),l.classList.toggle("optional",!o);const h=a===0?void 0:o?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(a));h?n.dataset.unanswered=h:delete n.dataset.unanswered,_e.titleGroupTab(n)}}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,e.detail&&(t.title=e.detail);const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const n=document.createElement("span");n.className="param-chip-swatch",n.style.background=e.color,t.append(n)}const s=document.createElement("span");return s.className="param-chip-value",s.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(s),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(a=>a.field==="description")?.full,this.syncDescription();return}const i=Number(t.dataset.panel);if(i<0)return;const s=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const n=t.dataset.field;if(n.startsWith("shape:")){this.selectedSourceIds=new Set([n.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(n.startsWith("body:")){const a=this.subgroupTabs.find(o=>o.getAttribute("aria-controls")==="shape-bodies");a&&this.openSubgroup(a),this.loadBodyEditor().then(o=>o.show(n.slice(5)));return}if(n.startsWith("decor:")){this.currentDecorId=n.slice(6),this.refreshDecorList(),this.decorList.focus();return}const r=this.shadow.getElementById(n);r===null||!s.contains(r)||(this.revealSubgroupOf(r),this.sectionFolds.reveal(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe(),this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorBaseFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.samplingRateInput!==this.shadow.activeElement&&(this.samplingRateInput.value=this.ufoElement.sighting.sampleMs===void 0?"":String(this.ufoElement.sighting.sampleMs)),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateShapeToolbarVisibility(){const e=this.ufoElement.sighting.timeline.sourceIds.length===0,t=this.shadow.getElementById("shape-row");t&&wn.showPresence(t,this.shadow.getElementById("shape-item")??void 0,!e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.shapeRotationInput])i.disabled=e,i.title=t}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:m9(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.shadow.activeElement!==this.shapeRotationInput&&(this.shapeRotationInput.value=String(_e.rotationDeg(e.angle))),this.refreshApparentSize())}static rotationDeg(e){const t=(e*180/Math.PI%360+540)%360-180;return Math.round((t===-180?180:t)*10)/10}updateShapeRotation(){const e=this.numberOrUndefined(this.shapeRotationInput.value);if(e===void 0)return;const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=t.getInterpolatedShapeAt(i,this.currentSourceId);s&&(this.commitShapes(i,[{sourceId:this.currentSourceId,shape:{...s,angle:e*Math.PI/180}}]),this.ufoElement.refresh())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,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,s=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!s)return;const n=this.currentProjection(),r=n.degToPx(e),a=s.bounds.height*(s.bounds.width===0?1:r/s.bounds.width),o={x:s.bounds.x+(s.bounds.width-r)/2,y:s.bounds.y+(s.bounds.height-a)/2,width:r,height:a},l=n.ofBounds(o),h=s.kind==="oval"?{...s,bounds:o,angular:l}:{...s,bounds:o,angular:l,points:this.scalePoints(s,o)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,s=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(n=>({x:n.x*i,y:n.y*s}))}refreshFilterOptions(){const e={[Xi.NONE.id]:this.messages.filterNone,[Xi.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[Xi.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==Xi.ALL.length||Xi.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||Xi.NONE.id;this.filterSelect.replaceChildren();for(const r of Xi.ALL){const a=document.createElement("option");a.value=r.id,a.textContent=t(r),this.filterSelect.appendChild(a)}this.filterSelect.value=n}const s=this.ufoElement?.sighting?.instrument;for(const n of this.filterSelect.options){const r=!s||Xi.usableWith(Xi.byId(n.value),s);n.disabled=!r,n.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,s={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,video:this.messages.instrumentCategoryVideo,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},n=r=>{const a=this.naming.instrument(r),o=Qt.unavailability(r,t);if(!o)return{id:r.id,label:a};const l=(o.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(o.from)).replace("{to}",String(o.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",a),hint:l}:{id:r.id,label:a,disabledReason:l}};this.instrumentSelect.choices=Qt.CATEGORIES.map(r=>({label:s[r],children:$d.filter(a=>a.category===r).map(n)})).filter(r=>r.children.length>0),this.instrumentSelect.value=this.instrumentSelect.value||i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=_e.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 n=Number(i[1]),r=Number(i[2]);return r>0?n/r:void 0}const s=Number(t);return Number.isFinite(s)&&s>0?s:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=st(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??Qt.fieldOfViewDeg(t),r=s?Qt.focalLengthMmFor(t,n):n;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=s?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=s?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=s!==void 0&&s.focalRangeMm===void 0,this.focalLengthInput.min=String(s?s.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(s?s.focalRangeMm?.maxMm??2e3:179),en.fit(this.focalLengthInput.parentElement??this.shadow),this.sectionFolds?.refresh(),this.focalFovOutput.textContent=s&&n!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(n,n<10?1:0)):"";const a=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=a===void 0?"":String(a)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const o=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=o===void 0?"":_e.exposureText(o)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const h of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(h,Ci.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const l=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.isoInput.placeholder=l?l.autoExposure?"auto":String(l.iso):"",this.setRowVisible(this.isoInput,l!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,l?.autoExposure===!0),this.meteringSelect.disabled=e.iso!==void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,s!==void 0&&t.fNumber!==void 0),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=Xi.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Qt.fieldOfViewDeg(e),s=Qt.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>l9||t.observerTrack.addKeyframe(n.t,{...n.pose,fovDeg:s})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,s=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!s){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(s.max,Math.max(s.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return st(e,this.ufoElement.currentTime)?.fovDeg??Qt.fieldOfViewDeg(e.instrument)}currentProjection(){return ar.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 s=st(this.ufoElement.sighting,this.ufoElement.currentTime),n=s?.focusDistanceM;if(n!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(n));return}const r=(s?Qt.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,a=s?.fNumber??t.fNumber;if(a===void 0||r<=0){this.blurBoundOutput.textContent="";return}const o=this.ufoElement.canvasElement.height;if(o<=0)return;const l=2*Kv*e/o*i.heightMm,h=r*r/(a*l)/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 s=this.numberOrUndefined(this.realWidthInput.value),n=s!==void 0&&(t!==void 0&&s<t||i!==void 0&&s>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),a=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+a+n;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+n}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),s=(m,v)=>Number(m.toFixed(v)),n=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??i9,a=this.sceneElement.groundAlong(n.azimuthDeg,n.altitudeDeg,t),o=a!==void 0&&a<r,l=s(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:s(Lt.sizeMAt(l,h),2),lengthM:s(Lt.sizeMAt(l,h),2),heightM:s(Lt.sizeMAt(l,d),2)}:void 0,p={azimuthDeg:s(n.azimuthDeg,2),altitudeDeg:s(n.altitudeDeg,2)},f={t,...p,distanceM:l,...o?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=oe(async()=>{const{BodyEditor:e}=await import("./BodyEditor-D5VXWcru.js");return{BodyEditor:e}},__vite__mapDeps([18,19]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,bodySelected:()=>this.bodiesEventsPanel.render(),said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,seekTo:t=>{this.ufoElement.currentTime=t},readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,s)=>this.sceneElement.groundAlong(t,i,s)},this.language),this.bodyEditor)),this.bodyEditorLoading}loadLanternEditor(){return this.lanternEditorLoading??=oe(async()=>{const{LanternEditor:e}=await import("./LanternEditor-C60IT7Cv.js");return{LanternEditor:e}},__vite__mapDeps([20,21]),import.meta.url).then(({LanternEditor:e})=>(this.lanternEditor=new e(this.shadow.getElementById("lantern-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()}},this.language),this.lanternEditor)),this.lanternEditorLoading}loadBeamEditor(){return this.beamEditorLoading??=oe(async()=>{const{BeamEditor:e}=await import("./BeamEditor-BzrEOJOy.js");return{BeamEditor:e}},__vite__mapDeps([22,9,23]),import.meta.url).then(({BeamEditor:e})=>(this.beamEditor=new e(this.shadow.getElementById("beam-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language),this.beamEditor)),this.beamEditorLoading}loadLaunchEditor(){return this.launchEditorLoading??=oe(async()=>{const{LaunchEditor:e}=await import("./LaunchEditor-DcYWYLQN.js");return{LaunchEditor:e}},__vite__mapDeps([24,25]),import.meta.url).then(({LaunchEditor:e})=>(this.launchEditor=new e(this.shadow.getElementById("launch-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language),this.launchEditor)),this.launchEditorLoading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const n=i===void 0||i<=0?void 0:Lt.sizeMAt(e.distanceM,i);this.realWidthInput.value=n===void 0?"":this.plain(n,n<1?2:n<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const s={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=s.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,s=ar.of(i.instrument,Lt.CANVAS_HEIGHT_PX,Si.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const a=Si.aimOf(i,e,r.shape.bounds),o=s.ofBounds(r.shape.bounds),{aim:l,...h}=r.shape;return{...r,shape:a?{...h,aim:a,angular:o}:{...h,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.ufoElement.sighting.timeline.sourceIds.length>0&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const s=/^ufo-(\d+)$/.exec(e);return s?`${this.messages.shape} ${s[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;this.currentSourceId=this.newSourceIds(1)[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}newSourceIds(e){const t=this.ufoElement.sighting.timeline,i=[];t.sourceIds.length===0&&this.currentSourceId!==void 0&&i.push(this.currentSourceId);const s=new Set([...t.sourceIds,this.currentSourceId]);let n=s.size+1;for(;i.length<e;){for(;s.has(`ufo-${n}`);)n++;i.push(`ufo-${n}`),s.add(`ufo-${n}`)}return i}shapeAddKinds(){const e=this.messages,t={triangle:e.modelTriangle,saucer:e.modelSaucer,cigar:e.modelCigar,chevron:e.modelChevron,light:e.modelLight};return[{value:"oval",label:e.oval},{value:"polygon",label:e.polygon},...ao.ALL.map(i=>({value:i.id,label:t[i.id]}))]}addModel(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,i=e.boundsAt(this.offsetDefaultBounds(t.sourceIds.length)),s=e.shapesIn(i,this.currentAppearance),n=this.newSourceIds(s.length),r=this.shapeAddKinds().find(h=>h.value===e.id).label,a=/^ufo-(\d+)$/.exec(n[0])?.[1]??"",o={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},l=s.map((h,d)=>{const u=e.partNames[d],p=u?`${r} ${a}, ${o[u]}`:`${r} ${a}`;return{sourceId:n[d],shape:{...h,title:this.said.write(void 0,p,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,l),n.length>1&&t.group(n),this.currentSourceId=n[n.length-1],this.selectedSourceIds=new Set(n),this.refreshSourceList(),this.ufoElement.refresh()}duplicateSelected(){if(this.hideContextMenu(),this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(r=>this.selectedSourceIds.has(r));if(t.length===0)return;const i=this.newSourceIds(t.length),s=24;for(const r of e.allKeyframes){const a=r.shapes.filter(o=>t.includes(o.sourceId)).map(o=>{const{bounds:l}=o.shape;return{sourceId:i[t.indexOf(o.sourceId)],shape:{...o.shape,bounds:{...l,x:l.x+s,y:l.y+s}}}});a.length>0&&this.commitShapes(r.t,a)}const n=e.groupMembers(t[0]);t.length>1&&n?.length===t.length&&t.every(r=>n.includes(r))&&e.group(i),this.currentSourceId=i[i.length-1],this.selectedSourceIds=new Set(i),this.refreshSourceList(),this.ufoElement.refresh()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i));t.length!==0&&this.removeShapes(t)}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??Wd,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 s=document.createElement("option");s.value=i,s.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(s)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const s=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorList.kindLabel(e.kind)} ${s}`}addDecor(e=this.decorList.pickedKind??"building"){this.observerAdded=e==="observer";const t=this.ufoElement.sighting,s={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="trafficlight"?{lights:id.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:sd}:{},windows:r2(e)};t.decor=[...t.decor,s],this.currentDecorId=s.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(s.id,e)}readSceneryChoice(){try{return localStorage.getItem(_e.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(_e.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(_e.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(_e.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await oe(()=>import("./surroundingsSources-Bq5A0HA5.js"),[],import.meta.url).catch(()=>{});if(!e)return;const{SURROUNDINGS_SOURCES:t,SurroundingsSources:i}=e;if(!this.isConnected)return;const s=document.createElement("option");s.value=_e.NO_SCENERY,s.id="option-scenery-none",s.textContent=this.messages.surveySourceNone;const n=t.map(a=>{const o=document.createElement("option");return o.value=a.id,o.textContent=a.name,o.title=a.credit,o}),r=new Option(this.messages.sourceFile,_e.FILE_SOURCE);r.id="option-scenery-file",this.scenerySource.replaceChildren(s,...n,r),this.surveyIds=t.map(a=>a.id),this.defaultSurveyId=i.DEFAULT_ID,this.syncSceneryPicker()}surveyIds;defaultSurveyId;sceneryAsked(){return this.sceneryChoice!==_e.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?_e.FILE_SOURCE:this.sceneryChoice===_e.NO_SCENERY?_e.NO_SCENERY:this.surveyIds.includes(this.sceneryChoice??"")?this.sceneryChoice:this.defaultSurveyId??this.surveyIds[0]),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-radius-row").hidden=e||this.sceneryChoice===_e.NO_SCENERY;const t=this.shadow.getElementById("scenery-file-link");t.hidden=!e,e&&(t.textContent=this.sectionFilePanel.itemLabel("decor"),t.title=this.sectionFilePanel.where("decor"))}setDecorFromFile(e){const t=this.ufoElement.sighting;if(this.sectionFromFile("decor")===e)return;const i={...t.frozen??{}};e?i.decor=i.decor??{}:delete i.decor,t.frozen=ts.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return typeof s=="number"&&typeof n=="number"?{lat:s,lng:n}:void 0}setPlantedDecor(e){this.ufoElement.sighting.decor=e,e.some(t=>t.id===this.currentDecorId)||(this.currentDecorId=e[0]?.id),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleHistoryRecord()}refreshSceneryWarning(){const e=this.ufoElement?.sighting,t=e?om.anachronism(e.decor,e.event.time):void 0;this.sceneryWarning.hidden=t===void 0,this.sceneryWarning.textContent=t?this.messages.surveyWarning.replace("{survey}",t.survey).replace("{observation}",t.observation):""}citeSource(e){const t=this.ufoElement.sighting;(t.sources??[]).some(i=>i.url===e.url)||(t.sources=[...t.sources??[],e])}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const s=this.ufoElement.sighting.decor.find(n=>n.id===e);!s||s.model||s.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(n=>n.id===e?{...n,model:{id:i.id},sizeM:i.sizeM}:n),this.currentDecorId===e&&this.syncDecorVisibility(),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*Mv,t=Math.round(e/h9*1e3);return{lights:id.byId("airliner")?.create(),track:[{t:0,eastM:-Mv,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:Mv,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(s=>s.kind===e).length;return`${this.decorList.kindLabel(e)} ${t+1}`}deleteDecor(){const t=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);t!==void 0&&this.removeDecor(t.id)}removeDecor(e){const t=this.ufoElement.sighting;t.decor=t.decor.filter(i=>i.id!==e),this.currentDecorId===e&&(this.currentDecorId=t.decor[0]?.id),this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="decor"),this.decorList.show(e),this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh();const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===e);t>=0&&this.showInFile(["decor",t])}updateDecor(e={}){if(this.currentDecorId===void 0)return;const t=this.ufoElement.sighting;t.decor=t.decor.map(i=>i.id!==this.currentDecorId?i:{...i,...e}),this.syncDecorVisibility(),this.ufoElement.refresh()}decorModelEntries;refreshDecorModelOptions(e){if(!e||this.decorModelEntries?.kind===e.kind)return;const t=e.kind;this.decorModelProvider.entries(t).catch(()=>[]).then(i=>{this.decorModelEntries={kind:t,entries:i},this.isConnected&&this.decorBaseForm.sync()})}drawnEntry;drawnEntryAsked;publishedParametersOf(e){const t=ju(e);if(!(!t?.id||t.url!==void 0)){if(this.drawnEntry?.id===t.id)return this.drawnEntry.parameters;if(this.drawnEntryAsked!==t.id){this.drawnEntryAsked=t.id;const i=t.id;this.decorModelProvider.entry(i).catch(()=>{}).then(s=>{this.drawnEntryAsked!==i||!s||(this.drawnEntry=s,this.isConnected&&this.syncDecorVisibility())})}}}modelPicker;enhanceDecorModelChoice(e,t){e.key==="model.id"&&(t.addEventListener("change",()=>t.dispatchEvent(new Event("input",{bubbles:!0}))),this.modelPicker.enhance(t,async i=>{const s=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),n=i!==""?i:s?lm[s.kind]?.id:void 0;return n!==void 0?this.decorModelProvider.entry(n).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):s===void 0?void 0:{decorKind:s.kind}},{current:()=>{const i=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId)?.model;return i?.url===void 0?void 0:{url:i.url,title:i.credit?.title??"",author:i.credit?.author??"",license:i.credit?.license??"",source:i.credit?.sourceUrl??""}},apply:i=>this.commitDecorBase(s=>{const n=this.stringOrUndefined(i.title),r=this.stringOrUndefined(i.license);s.model={url:i.url,credit:n!==void 0&&r!==void 0?{title:n,license:r,author:this.stringOrUndefined(i.author),sourceUrl:this.stringOrUndefined(i.source)}:void 0}},"model")}))}async adoptCatalogueSize(e,t){const[i,s]=await Promise.all([e.model?.id?this.decorModelProvider.entry(e.model.id).catch(()=>{}):void 0,t?this.decorModelProvider.entry(t).catch(()=>{}):void 0]),n=this.ufoElement.sighting.decor.find(o=>o.id===e.id);if(!n||n.model?.id!==t||!s?.sizeM)return;const r=n.sizeM!==void 0&&i?.sizeM!==void 0&&n.sizeM.widthM===i.sizeM.widthM&&n.sizeM.lengthM===i.sizeM.lengthM&&n.sizeM.heightM===i.sizeM.heightM;if(n.sizeM&&!r)return;const a={...n.sizeM,...Object.fromEntries(Object.entries(s.sizeM).filter(([,o])=>o!==void 0).map(([o,l])=>[o,this.roundedMeters(l)]))};this.updateDecor({sizeM:a})}roundedMeters(e){return Math.round(e*100)/100}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(s=>s.t===e)||(t.milestones=cc([...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(s=>s.t===e);i&&(t.milestones=t.milestones.filter(s=>s.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=cc(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;wn.showPresence(this.shadow.getElementById("milestone-row"),this.shadow.getElementById("milestone-item"),t);for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.deleteMilestoneButton])i.disabled=!t;this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.filter(e=>e.kind!=="observer").map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning(),this.refreshObserverList()}refreshObserverList(){const e=_e.OBSERVER_PRINCIPAL,t=this.ufoElement.sighting.decor.filter(s=>s.kind==="observer");this.currentDecorId!==void 0&&t.some(s=>s.id===this.currentDecorId)&&this.observerAdded&&(this.observerShown=this.currentDecorId),this.observerAdded=!1,t.some(s=>s.id===this.observerShown)||(this.observerShown=e),this.observerList.setItems([{id:e,label:this.principalObserverLabel()},...t.map(s=>({id:s.id,label:this.decorLabel(s)}))],this.observerShown);const i=this.observerShown!==e;this.observerList.setRemoveEnabled(i),this.observerList.setActionEnabled("look-at-observer",i),this.placeDecorItem()}principalObserverLabel(){const e=[this.observerTitleInput.value,this.observerFirstNamesInput.value,this.observerLastNameInput.value].map(t=>t.trim()).filter(Boolean).join(" ");return e===""?this.messages.principalObserver:`${e} (${this.messages.principalObserver.toLowerCase()})`}observerAdded=!1;selectObserver(e){this.observerShown=e,e!==_e.OBSERVER_PRINCIPAL&&this.selectDecor(e),this.refreshObserverList()}placeDecorItem(){const e=this.shadow.getElementById("decor-item"),t=this.shadow.getElementById("observer-decor-host"),i=this.shadow.getElementById("observer-principal");if(!e||!t||!i)return;const s=this.observerShown!==_e.OBSERVER_PRINCIPAL;if(i.hidden=s,s&&this.isGroupIdOpen("group-observer")){e.parentElement!==t&&t.append(e),e.hidden=!1;return}e.parentElement===t&&this.shadow.getElementById("decor-list-header").after(e),e.hidden=this.decorList.value===""}syncDecorFields(){this.syncDecorVisibility()}async findGhosts(){const e=this.currentReference();if(e?.src){this.searchingGhosts=!0,this.syncFindGhosts(e);try{const{GhostSearchView:t}=await oe(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-UG9G-yF8.js");return{GhostSearchView:r}},__vite__mapDeps([26,11]),import.meta.url),i=this.messages,s={searching:i.referenceGhostsSearching,found:i.referenceGhostsFound,foundScaled:i.referenceGhostsFoundScaled,low:i.referenceGhostsLow,none:i.referenceGhostsNone,cropped:i.referenceGhostsCropped},n=await new t(this.ghostsStatus,s).search(e.src);this.ghostFinding=n&&n.pairs.length>0?{referenceId:e.id,src:e.src,search:n}:void 0,this.ghostsShown=!0,this.syncGhostsShown(),this.ufoElement.refresh()}finally{this.searchingGhosts=!1,this.syncFindGhosts(this.currentReference())}}}syncGhostsShown(){this.ghostsShownButton.hidden=!this.ghostFinding,this.ghostsShownButton.setAttribute("aria-pressed",String(this.ghostsShown)),this.ghostsShownButton.textContent=this.ghostsShown?this.messages.referenceGhostsHide:this.messages.referenceGhostsShow}syncFindGhosts(e){const t=!e?.src||this.sceneElement.referenceFailure(e.src)!==void 0;this.findGhostsButton.disabled=this.searchingGhosts||t,this.addReferenceLandmarkButton.disabled=t,t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark()}updateExposureSettings(){const e=this.ufoElement.sighting;e.iso=this.numberOrUndefined(this.isoInput.value);const t=this.meteringSelect.value;e.metering=t==="average"||t==="highlights"?t:void 0,this.meteringSelect.disabled=e.iso!==void 0,this.ufoElement.refresh()}updateLens(){const e=this.lensGlassSelect.value,t={...e?{glass:e}:{},drops:this.numberOrUndefined(this.lensDropsInput.value),condensation:this.numberOrUndefined(this.lensCondensationInput.value),dirt:this.numberOrUndefined(this.lensDirtInput.value),...this.lensShelteredInput.checked?{sheltered:!0}:{}};for(const i of["drops","condensation","dirt"])t[i]===void 0&&delete t[i];this.ufoElement.sighting.lens=Object.keys(t).length>0?t:void 0,this.ufoElement.refresh()}label(e,t){const i=this.shadow.getElementById(e);i&&(i.textContent=t)}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}decorBaseShownFor;showDecorBase(e){if(this.decorBaseHost.hidden=e===void 0,this.decorStateHost.hidden=e===void 0,!e){this.decorBaseForm.clear(),this.decorStateForm.clear(),this.decorBaseShown=!1,this.decorBaseShownFor=void 0;return}const t=this.decorBaseShownFor!==e.id;if(this.decorBaseShownFor=e.id,this.decorBaseShown){this.decorBaseForm.sync(t),this.decorStateForm.sync(t);return}this.decorBaseShown=!0;const i=()=>new Ml(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?ta.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(gr.BASE,i(),()=>{}),this.decorStateForm.show(gr.STATE,i(),()=>{})}decorPositionPlace(){const e=()=>{const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===this.currentDecorId);return t<0?[]:[`decor.${t}.eastM`,`decor.${t}.northM`]};return{frame:()=>this.positionFrame(this.currentDecorId),messages:()=>this.messages,basis:{read:()=>this.ufoElement.sighting.provenance.at(e()[0]??"")?.basis,write:(t,i)=>this.writePositionBasis(e(),i)}}}framePlace(){return{frame:()=>this.positionFrame(),messages:()=>this.messages}}positionFrame(e){const t=this.ufoElement.currentTime,i=[{label:this.messages.positionObserver,eastM:0,northM:0}];for(const s of this.ufoElement.sighting.decor){if(s.id===e)continue;const{eastM:n,northM:r}=Mr(s,t);i.push({id:s.id,label:this.decorLabel(s),eastM:n,northM:r})}return{origin:this.plantingCentre(),references:i}}syncObserverPosition(){const e=this.ufoElement.sighting,t=this.ufoElement.currentTime;this.observerSaid=e.observerTrack.getLatestPoseAt(t)?.saidPosition;const i=this.positionFrame();this.observerPosition.frame={...i,references:i.references.filter(n=>n.id!==void 0)};const s=JSON.stringify(this.observerSaid??null);s!==this.observerSaidShown&&(this.observerSaidShown=s,this.observerPosition.said=this.observerSaid),this.observerPosition.basis=e.provenance.at(this.observerPositionPaths()[0]??"")?.basis}observerPositionPaths(){const e=this.ufoElement.currentTime,t=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(i=>i.t===e);return t<0?[]:[`observerTrack.keyframes.${t}.pose.lat`,`observerTrack.keyframes.${t}.pose.lng`]}writeObserverBasis(e){this.observerPositionPaths().length===0&&this.updateObserver(),this.writePositionBasis(this.observerPositionPaths(),e)}writePositionBasis(e,t){const i=this.ufoElement.sighting.provenance;for(const s of e)t===void 0||t==="stated"?i.clear(s):i.set(s,{basis:t});this.dispatchEvent(new CustomEvent("sightingchange"))}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=ac.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:ue.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:ac.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:gr.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:lm[e.kind]?.id}}placedByAuthor(e){if(!e.lamp?.supposed)return e;const t=this.sceneElement.decorDrawnOffset(e.id),{supposed:i,...s}=e.lamp,n={...e,eastM:e.eastM+(t?.eastM??0),northM:e.northM+(t?.northM??0),...Object.keys(s).length>0?{lamp:s}:{}};Object.keys(s).length===0&&delete n.lamp;const r=this.ufoElement.sighting;return r.decor=r.decor.map(a=>a.id===e.id?n:a),n}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!i)return;const s=t==="eastM"||t==="northM"?this.placedByAuthor(i):i;if((t==="lit"||t==="headlights")&&this.ufoElement.playbackState==="playing")return;const n=this.ufoElement.currentTime,r=ta.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const a=this.ufoElement.sighting;a.decor=a.decor.map(l=>l.id===s.id?ta.apply(l,r,t,n):l),t==="model.id"&&this.adoptCatalogueSize(s,r.model?.id);const o=a.decor.find(l=>l.id===s.id);t==="title"&&this.decorList.rename(o.id,this.decorLabel(o)),this.syncDecorVisibility(),this.ufoElement.refresh(),t==="lightRig"&&this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorBaseFromTimeline(){this.ufoElement.playbackState==="playing"||!this.decorBaseShown||(this.decorBaseForm.sync(),this.decorStateForm.sync())}showDecorParameters(e){const t=e?vi.of(e,this.publishedParametersOf(e)):void 0;if(!e||!t){this.decorParametersShownFor=void 0,this.decorParameterForm.clear(),this.decorParametersHost.hidden=!0;return}this.decorParametersHost.hidden=!1;const i=`${e.id}|${t.kind}|${t.parameters.map(r=>r.key).join(",")}`;if(i===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=i;const s=e.id,n=new Ml(()=>this.ufoElement.sighting.decor.find(r=>r.id===s),r=>{const a=this.ufoElement.sighting;a.decor=a.decor.map(o=>{if(o.id!==s)return o;const l=structuredClone(o);return r(l),l})});this.decorParameterForm.show(t,n,()=>{this.syncDecorVisibility(),this.ufoElement.refresh()})}syncDecorParameterVisibility(){this.showDecorParameters(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);this.refreshDecorModelOptions(e),this.showDecorBase(e),this.syncDecorParameterVisibility()}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++,this.meteorMagnitudeLimit());e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;meteorMagnitudeLimit(){const e=this.ufoElement.sighting,t=this.observerAtStart(),i=e.event.time?.year!==void 0?sn(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=zi("Sun",i,t).altitudeDeg;return Ta(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Jn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Wm;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new rn(["en"]);tagNames=new Xv({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,s=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?sn(i,t.lng,e.event.utcOffsetHours):void 0,n=JSON.stringify([s?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,fs(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status,this.sceneElement.groundKey]);if(n===this.skyCandidatesKey)return;if(this.skyCandidatesKey=n,!s||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.disabled=!0,this.showCometButton.disabled=!0,this.showNovaButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown),this.labelSkyButtons();return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},a=[this.starsClause(s,r),this.showerClause(s,r),this.cometClause(s,r),this.novaClause(s,r),this.eclipseClause(s,r),this.moonClause(s,r),this.satelliteClause(s,r),this.reentryClause(s,r),this.fireballClause(s,r),this.opticsClause(s,r),this.rainbowClause(s,r),this.glowClause(s,r)].filter(o=>o!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",a.join(" · ")),this.labelSkyButtons()}labelSkyButtons(){const e=this.messages,t=[[this.showMeteorButton,e.showMeteor,e.noMeteor],[this.showCometButton,e.showComet,e.noComet],[this.showNovaButton,e.showNova,e.noNova],[this.showSatelliteButton,e.showSatellite,e.noSatellite],[this.showFireballButton,e.showFireball,e.noFireball]];for(const[i,s,n]of t){const r=i.disabled?n:s;i.title=r,i.setAttribute("aria-label",r)}}instrumentGain(){const e=this.ufoElement.sighting;return Ws.gainFor(e.instrument,{fNumber:st(e,0)?.fNumber,fieldOfViewDeg:Si.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=zi("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=Ta(i,s,n),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<n9)return this.messages.skyStarsNone;const o=this.ufoElement.sighting.instrument,l=Math.abs(s)<.1?this.messages.skyStarsEye.replace("{limit}",a(r)):(s>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(r)).replace("{device}",this.naming.instrument(o)).replace("{gain}",a(Math.abs(s))).replace("{eye}",a(Ta(i,0,n)));return r<=mu?l:l+this.messages.skyStarsCatalogue.replace("{catalogue}",a(mu))}showerClause(e,t){const i=Qi.observedRatePerHour(Qi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=$h.activeAt(e);if(s.length===0)return this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyNothingActive.replace("{sporadic}",i);const n=s.map(r=>{const a=$h.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:$h.observedRatePerHour(r.zhr,a.altitudeDeg,r.shower.populationIndex)}}).sort((r,a)=>a.rate-r.rate)[0];return n.rate<=0?(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(n.entry.shower))):(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerActive.replace("{name}",this.naming.shower(n.entry.shower)).replace("{altitude}",String(Math.round(n.position.altitudeDeg))).replace("{bearing}",this.naming.towards(n.position.azimuthDeg)).replace("{rate}",n.rate.toLocaleString(void 0,{maximumFractionDigits:n.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=Yf.brightestAt(e,t);if(!i||i.magnitude>ud){this.showCometButton.disabled=!0;return}return this.showCometButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.cometText(i)}novaClause(e,t){const i=$m.brightestAt(e,t);if(!i||i.magnitude>ud){this.showNovaButton.disabled=!0;return}return this.showNovaButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.novaText(i)}eclipseClause(e,t){const i=ps.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=zi("Sun",i.peak,t),n=r=>r.replace("{altitude}",String(Math.round(s.altitudeDeg))).replace("{bearing}",this.naming.towards(s.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),a=Math.round(i.totality.seconds%60);return n(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${a} s`)}return n(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=zi("Moon",e,t);if(i.altitudeDeg<=0||Hl(e).illuminatedFraction<.97)return;const s=[],n=Sn.distanceKm(e,t),r=Sn.relativeToMean(Sn.radiusAtKm(n)),a=n<=Sn.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=Sn.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return a&&s.push(a.replace("{distance}",(Math.round(n/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(Sn.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),qm.isIn(e)&&s.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),s.length>0?s.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=jr.visibilityAt(e,t),s=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(s!==void 0)return s;if(this.showSatelliteButton.disabled=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const n=Ta(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=n),a=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",a);const o=Math.round(i.shadowHeightKm).toLocaleString(),l=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",o).replace("{count}",l);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",a):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),s=i+this.satelliteSpanMs(),n=[i,s,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==n){const l={key:n,status:"loading"};this.reentries=l,_e.reentryArchive.candidates(i,s,t).then(h=>{l.status=h?"ready":"unavailable",l.candidates=h,this.reentries===l&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=jr.visibilityAt(e,t).sunAltitudeDeg<-6,a=(this.reentries.candidates??[]).filter(l=>l.record.precision==="minute"||r);if(a.length===0)return;const o=a.slice(0,3).map(l=>this.reentryText(l));return a.length>3&&o.push(this.messages.skyReentriesMore.replace("{count}",String(a.length-3))),this.messages.skyReentries.replace("{list}",o.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,s=new Date(e.timeMs);if(t.precision==="day"){const a=s.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",a)}const n=this.observerClock(s).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",n).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}",n).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",n)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(l=>l.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(l=>l.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses();if(this.showSatelliteButton.disabled=this.aimableSatellitePasses(i).length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const n=i[0].peak,a=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",n.object.name).replace("{magnitude}",n.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg)).replace("{time}",this.observerClock(n.date)),o=this.starlinkTrain(i);return o?`${a}, ${o}`:a}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const s=i.peak.magnitude;if(s===void 0)return!1;const n=zi("Sun",i.peak.date,t);return s<=Ta(n.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,s)=>i.peak.magnitude-s.peak.magnitude)}aimableSatellitePasses(e){return e.filter(t=>this.passTimelineMs(t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(t.peak.altitudeDeg,t.peak.azimuthDeg))}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:a,launch:o}=r.peak.object;a!=="starlink"||!o||(r.peak.date.getTime()-Date.parse(`${o}T00:00:00Z`))/864e5>60||t.set(o,(t.get(o)??0)+1)}const[i,s]=[...t.entries()].sort((r,a)=>a[1]-r[1])[0]??[];if(!i||!s||s<3)return;const n=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(s)).replace("{date}",n)}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=st(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=sn(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.aimableSatellitePasses(this.visibleSatellitePasses());if(e.length===0)return;const t=e.map(s=>`${s.object.norad}@${s.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=>Pr.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Pr.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,s)=>i.magnitude-s.magnitude)}aimableFireballs(e,t){return e.filter(i=>this.fireballTimelineMs(i,t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(i.peak.altitudeDeg,i.peak.azimuthDeg))}fireballTimelineMs(e,t){const{record:i}=e,s=i.from[2]-i.to[2],n=Math.abs(s)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/s));return i.t-t.getTime()+n*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.disabled=this.aimableFireballs(i,e).length===0,i.length===0)return;const s=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",s.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(s.record.t))).replace("{altitude}",String(Math.round(s.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(s.peak.azimuthDeg)).replace("{distance}",String(Math.round(s.peak.distanceKm/10)*10)).replace("{stations}",String(s.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 s=sn(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=this.aimableFireballs(this.strikingFireballs(s,this.observerAtStart()),s);if(n.length===0)return;const r=n[this.fireballRank++%n.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,s),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=fs(this.ufoElement.sighting,0),s=zi("Sun",e,t),n=zi("Moon",e,t),r=St.deckLitUntilDeg(St.DECK_HEIGHT_M),a=s.altitudeDeg>-r,o=a?s:n;if(o.altitudeDeg<=-r)return;const l=i.highCloudCover;if(l===void 0||l<=0)return this.messages.skyOpticsNoIce;if(St.strength(l,i.lowerCloudCover??i.cloudCover,o.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=a?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(St.formsAt(o.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??qf;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=fs(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=zi("Sun",e,t),n=zi("Moon",e,t),r=s.altitudeDeg>0,a=r?s:n;if(a.altitudeDeg<=0)return this.messages.skyBowNoSource;const o=i.lowerCloudCover??i.cloudCover;if(bn.strength(i.precipitationIntensity,o,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const l=bn.formsAt(a.altitudeDeg);if(l.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(bn.primary().radiusDeg)));const h=this.listed(l.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(Hl(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=zi("Sun",e,t);if(i.altitudeDeg>g9)return;const s=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),n=[];if(s.milkyWay&&n.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(s.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(s.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(s.milkyWay.azimuthDeg))),s.zodiacal){const p=s.zodiacal.sunSeparationDeg<=jt.CONE_SEPARATION_DEG;n.push((p?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(s.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(s.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(s.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(s.zodiacal.sunSeparationDeg))))}if(n.length>0)return this.listed(n);const r=this.decimal(s.darkestSkyMagPerArcsec2,1),a=zi("Moon",e,t),o=s.darkestSkyMagPerArcsec2<v9,l=this.ufoElement.sighting.lightPollution,h=pe.scatteringAt(90-a.altitudeDeg)*pe.moonOutput(pe.phaseAngleOf(Hl(e).illuminatedFraction),a.altitudeDeg)*pe.scatteredFraction(90),d=pe.artificialZenithNanolamberts(l)>h;if(o&&a.altitudeDeg>0&&!d){const p=Math.round(Hl(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=pe.artificialZenithNanolamberts(l)>pe.twilightExcessNanolamberts(i.altitudeDeg);return o&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):o?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=zi("Sun",e,t),s=zi("Moon",e,t);return pe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(Hl(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new jt;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<Yf.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 s=sn(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=Yf.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.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 s=sn(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=$m.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(o=>o.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:s}=Mr(e,this.ufoElement.currentTime),n=Math.hypot(t,i);if(n===0&&s===0)return;const r=Math.atan2(t,i)*180/Math.PI,a=Math.atan2(s-c9,n)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(a*10)/10),this.updateObserver()}static DEFAULT_SAMPLE_MS=100;get samplingRate(){return this.ufoElement.sighting.sampleMs??_e.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return E1(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-sh.width/2,y:e.height/2-sh.height/2,width:sh.width,height:sh.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 d1(this.ufoElement.sighting.timeline,new m8(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t),this.recordButton.querySelector(".record-label")||this.recordButton.replaceChildren(Object.assign(document.createElement("span"),{className:"record-icon"}),Object.assign(document.createElement("span"),{className:"record-label"})),Ee.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=Sr.preferencesFor(this);this.preferences=t;const i=$u(t,Wu),s=this.narrativeProvider.localize?.(i),[n,r,a]=i==="en"?[gl,{},void 0]:await Promise.all([ME(i),U3(i),xE(i)]);if(await s,e!==this.localeToken)return;const o=i!==this.language;this.language=i,this.naming=new Wm(a),this.said=new rn(t),this.tagNames=new Xv(r),n!==this.messages?this.applyMessages(n):(this.paramSummaryBuilder=new oo(n,this.naming,this.said,this.tagNames,{messages:n,locale:this.language}),this.refreshParamSummary()),o?this.showSaidTexts():this.showTags()}preferences=[];language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===Wd&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.sourceSelect.setAttribute("aria-label",e.shape),this.shadow.getElementById("shape-empty").textContent=e.emptyShapes,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.shadow.getElementById("label-shape-rotation").textContent=e.shapeRotation,this.shapeRotationInput.title=e.shapeRotationTitle,this.labelSizeLock.textContent=e.sizeLock;for(const[s,n]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(s).textContent=n;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.samplingRateInput.placeholder=String(_e.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(_e.DEFAULT_SAMPLE_MS)),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.shadow.getElementById("label-account-compare").textContent=e.accountCompare,this.shadow.getElementById("account-compare-row").title=e.accountCompareHint;const t=this.shadow.getElementById("scene-resize");t&&(t.title=e.resizeScene,t.setAttribute("aria-label",e.resizeScene)),this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextDuplicateButton.textContent=e.duplicate,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.frozenPanel.localize(e),this.sectionFilePanel.localize(e),this.eventsPanel.localize(e.events),this.phenomenonEventsPanel.localize(e.events),this.bodiesEventsPanel.localize(e.events),this.shadow.getElementById("observer-identity-hint").textContent=e.identityHint,this.shadow.getElementById("identity-ask-initials").textContent=e.identityInitials,this.shadow.getElementById("identity-ask-keep").textContent=e.identityKeep,this.shadow.getElementById("identity-ask-back").textContent=e.identityBack,this.labelImportFile.textContent=e.importFile,this.shadow.getElementById("label-whole-keyframes").textContent=e.wholeKeyframes,this.wholeKeyframesInput.closest("label").title=e.wholeKeyframesHint,this.importInput.placeholder=e.importUrlPlaceholder;for(const s of this.shadow.querySelectorAll(hp))s.messages=e;this.labelObserverAge.textContent=e.observerAge,this.labelObserverBirth.textContent=e.observerBirth,this.perceptionSettings.labels=e.observerPerception,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,Hn.say(this.labelAccountUrl,e.accountUrl,e.accountUrlHint),this.labelAccountFollowedUp.textContent=e.accountFollowedUp,this.evaluationFields.messages=e.accountEvaluation;for(const[s,n]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const r=this.shadow.getElementById(s);r&&(r.textContent=n)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelPosition.textContent=e.positionLabel,this.observerPosition.messages=e,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.label("label-iso",e.iso),this.isoInput.title=e.isoTitle,this.label("label-metering",e.metering),this.meteringSelect.title=e.meteringTitle,this.label("metering-device",e.meteringDevice),this.label("metering-average",e.meteringAverage),this.label("metering-highlights",e.meteringHighlights),this.label("label-lens-glass",e.lensGlass),this.label("label-reference-ghosts",e.referenceGhosts),this.findGhostsButton.textContent=e.referenceFindGhosts,this.syncGhostsShown(),this.label("lens-glass-none",e.lensGlassNone),this.label("lens-glass-filter",e.lensGlassFilter),this.label("lens-glass-window",e.lensGlassWindow),this.label("lens-glass-windscreen",e.lensGlassWindscreen),this.label("label-lens-drops",e.lensDrops),this.lensDropsInput.title=e.lensDropsTitle,this.label("label-lens-condensation",e.lensCondensation),this.lensCondensationInput.title=e.lensCondensationTitle,this.label("label-lens-dirt",e.lensDirt),this.lensDirtInput.title=e.lensDirtTitle,this.label("label-lens-sheltered",e.lensSheltered),this.lensShelteredInput.title=e.lensShelteredTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.shapeAddMenu.panel.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"trafficlight",label:e.decorTrafficLight},{value:"crossing",label:e.decorCrossing},{value:"roadsign",label:e.decorRoadSign},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,empty:e.emptyDecor,actions:{"look-at-decor":e.lookAtDecor}}),this.labelSkyButtons(),this.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.observerList.setLabels({list:e.observerGroup,remove:e.deleteObserver,add:e.addObserver,actions:{"look-at-observer":e.lookAtDecor}}),this.refreshObserverList(),this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const i=this.shadow.getElementById("option-scenery-none");i&&(i.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote,this.shadow.getElementById("milestone-empty").textContent=e.emptyMilestones;for(const[s,n]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])s.title=n,s.setAttribute("aria-label",n);this.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup,this.labelLaunchesSubgroup.textContent=e.launchesSubgroup,this.labelBeamsSubgroup.textContent=e.beamsSubgroup,this.labelLanternsSubgroup.textContent=e.lanternsSubgroup;for(const s of["location","decor","weather"]){const n=this.shadow.getElementById(`${s}-settings-button`);n?.setAttribute("title",e.dataSources),n?.setAttribute("aria-label",e.dataSources);const r=this.shadow.getElementById(`label-${s}-settings`);r&&(r.textContent=e.dataSources)}this.bodyEditor?.setLanguage(this.language),this.launchEditor?.setLanguage(this.language),this.beamEditor?.setLanguage(this.language),this.lanternEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerTab,this.labelWeatherGroup.textContent=e.sky,this.fitGroupTabs(),this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new oo(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),this.refreshParamSummary(),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelRareIce.textContent=e.rareIceCrystals,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.referenceSelect.setAttribute("aria-label",e.reference),this.shadow.getElementById("reference-empty").textContent=e.emptyReferences,this.shadow.getElementById("reference-landmark-empty").textContent=e.emptyReferenceLandmarks,this.shadow.getElementById("trace-empty").textContent=e.emptyTraces,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSourceInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.setReferenceAddKinds(e.addReferenceUrl,e.addReferenceFile,e.referenceStreetSearch),this.addReferenceButton.title=e.addReference,this.addReferenceButton.setAttribute("aria-label",e.addReference),this.referenceAddMenu.panel.setAttribute("aria-label",e.addReference),this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.title=e.addReferenceLandmark,this.addReferenceLandmarkButton.setAttribute("aria-label",e.addReferenceLandmark),this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,Hn.say(this.labelTraceImport,e.traceImport,e.traceImportHint),this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=`${e.traceImport} (${e.traceImportHint})`,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[s,n]of this.soundKindOptions)n.textContent=this.soundKindLabel(s,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e)}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[s,n]of Object.entries(t))this.shadow.getElementById(`label-section-${s}`).textContent=n;this.sectionFolds.setMessages(e),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const s of["location-settings","decor-settings","weather-settings"])Vn.popover(this.shadow.getElementById(s),e.close);Vn.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),Vn.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),Vn.button(this.contextMenu,e.close,()=>this.hideContextMenu()),Vn.button(this.decorContextMenu,e.close,()=>this.hideDecorContextMenu()),this.shadow.getElementById("label-editor-kicker").textContent=e.editorKicker,this.shadow.getElementById("label-save").textContent=e.save,this.shareDialog.useLanguage(this.language).then(s=>{s&&(this.shareMessages=s,this.shadow.getElementById("label-share").textContent=s.share,this.refreshEditorHead())});const i={observation:e.panelIntroObservation,observer:e.panelIntroObserver,location:e.panelIntroLocation,temporal:e.panelIntroTemporal,decor:e.panelIntroDecor,weather:e.panelIntroWeather,shape:e.panelIntroShape,sound:e.panelIntroSound,reference:e.panelIntroReference,file:e.panelIntroFile};for(const[s,n]of Object.entries(i)){const r=this.shadow.querySelector(`[aria-controls="group-${s}"]`);r.dataset.intro=n,_e.titleGroupTab(r)}this.refreshEditorHead()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;if(!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)){const d=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;this.beginCameraDrag(t,u?.kind==="decor"?u.id:void 0,u?.kind==="body"?u.id:void 0)}return}const s=this.decorMoveAxis(e);if(i==="decor"&&s&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t,s))return;const n=this.ufoElement.sighting.timeline,r=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const d=new G0(this.selectedMembers()),u=Jt.hitTestHandle({bounds:d.bounds(),angle:0},t);if(u==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:d,startPointer:t},this.startDragListening();return}if(u){if(a)return;this.dragState={kind:"group-resize",group:d,handle:u},this.startDragListening();return}}else{const d=n.getInterpolatedShapeAt(r,this.currentSourceId),u=d?.kind==="polygon"?Jt.hitTestVertex(d,t):void 0;if(d?.kind==="polygon"&&u!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:d,vertexIndex:u},this.startDragListening();return}const p=d&&Jt.hitTestHandle(d,t);if(d&&p){if(a)return;this.beginDrag(p==="rotate"?"rotate":"resize",this.currentSourceId,d,t,p);return}}const l=this.ufoElement.shapeAt(t.x,t.y,Rf);if(!l){const d=s==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;if(u?.kind==="body"&&u.id!==void 0){a?this.showBody(u.id):this.beginCameraDrag(t,void 0,u.id);return}const p=u?.kind==="decor"?u.id:void 0;if(p!==void 0){a?(this.selectDecor(p),this.revealDecorPanel()):this.beginCameraDrag(t,p);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),this.flash(this.shapeTitleInput.closest("label")),e.shiftKey?this.toggleUnitSelection(l.sourceId):this.selectedSourceIds.has(l.sourceId)||this.selectUnit(l.sourceId),a||!o)return;const h=[...this.selectedSourceIds].map(d=>({sourceId:d,original:d===l.sourceId?l.shape:n.getInterpolatedShapeAt(r,d)??l.shape}));this.dragState={kind:"move",sources:h,startPointer:t},this.startDragListening()}showBody(e){if(this.fileSyncActive()){this.showInFile(this.bodyPath(e));return}this.revealShapePanel();const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-bodies");t&&this.openSubgroup(t),this.loadBodyEditor().then(i=>i.show(e))}revealDecorPanel(){if(this.fileSyncActive()){this.fileFocus="decor",this.syncCanvasMode();return}const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-decor");e&&this.toggleGroup(e,!0)}revealShapePanel(){if(this.fileSyncActive()){this.fileFocus="shape",this.syncCanvasMode();return}const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="shape"),this.refreshSourceList(),this.onSelectionOrTimeChanged(),this.showInFile(this.shapePath(e)))}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(n=>this.selectedSourceIds.has(n))){if(i.length>=this.selectedSourceIds.size)return;for(const n of i)this.selectedSourceIds.delete(n);if(!this.selectedSourceIds.has(this.currentSourceId)){const n=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,a)=>n.indexOf(r)-n.indexOf(a)).pop()}}else{for(const n of i)this.selectedSourceIds.add(n);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,s=this.ufoElement.currentTime,n=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(s,this.currentSourceId):void 0,a=n?.kind==="polygon"&&Jt.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,Rf);if(a){this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),this.currentSourceId=a.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const o=this.pickDecorAt(e),l=o?this.ufoElement.sighting.decor.find(h=>h.id===o):void 0;l&&this.showDecorContextMenu(e.clientX,e.clientY,l)}pickDecorAt(e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const s=(e.clientX-i.left)/i.width*2-1,n=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(s,n)}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,s=i.filter(p=>this.selectedSourceIds.has(p)),n=i.length<=s.length,r=s.length>0&&i.slice(i.length-s.length).every(p=>this.selectedSourceIds.has(p)),a=s.length>0&&i.slice(0,s.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=n||r,this.contextSendToBackButton.disabled=n||a,this.contextBringToFrontButton.title=n?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=n?this.messages.onlyOneShape:a?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const o=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!o,this.contextUngroupButton.title=o?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const l=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&l?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?Jt.hitTestVertex(l,this.contextMenuPoint):void 0,u=h&&l.points.length<=h2;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";const t=[...this.ufoElement.sighting.timeline.sourceIds],i=this.ufoElement.sighting.interpretation?.bodies??[];if(t.length===0&&i.length===0){const s=document.createElement("span");s.className="submenu-empty",s.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(s)}for(const s of t){const n=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=e.occludesSourceIds?.includes(s)??!1,r.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,s,r.checked)),n.appendChild(r),n.appendChild(document.createTextNode(this.shapeLabel(s))),this.contextMasksSubmenu.appendChild(n)}for(const s of i){const n=this.sceneElement.bodyMaskedBy(s.id,e.id);if(n===void 0)continue;const r=document.createElement("span");r.className="submenu-empty submenu-fact";const a=this.said.read(s.title)??s.id,o=this.messages;r.textContent=`${a} — ${n>=.995?o.masksBodyFully:n>.005?o.masksBodyPartly.replace("{share}",String(Math.round(n*100))):o.masksBodyNot}`,this.contextMasksSubmenu.appendChild(r)}}updateDecorOccludesShape(e,t,i){const s=this.ufoElement.sighting;s.decor=s.decor.map(n=>{if(n.id!==e)return n;const r=i?[...new Set([...n.occludesSourceIds??[],t])]:(n.occludesSourceIds??[]).filter(a=>a!==t);return{...n,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 s=Jt.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),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 s=Jt.hitTestVertex(i,e);if(s===void 0)return;const n=Jt.deleteVertex(i,s);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),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,s,n){this.dragState={kind:e,sourceId:t,original:i,handle:n,startPointer:s},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,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!s||!i)return!1;i.show(s);const n=i.readingNow(),r=this.skyDirectionOf(e);return!n||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:n.azimuthDeg,bodyAltitudeDeg:n.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 s=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+s,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(eE,(e.maxX-e.minX)/2*t.width),s=Math.max(eE,(e.maxY-e.minY)/2*t.height),n=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return{x:n-i/2,y:r-s/2,width:i,height:s}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),s=e.reading();if(!i||!s)return!1;const n=Jt.hitTestHandle({bounds:i,angle:0},t);if(!n)return!1;if(n==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...s.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:n,centre:r,startPointer:t,startSizeM:{...s.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(n,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:s,startPointer:n,startSizeM:r,handle:a}=t,o=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),l=a==="e"||a==="w",h=a==="n"||a==="s",d=l?o(i.x-s.x,n.x-s.x):h?o(i.y-s.y,n.y-s.y):o(Math.hypot(i.x-s.x,i.y-s.y),Math.hypot(n.x-s.x,n.y-s.y));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:l?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:wv};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.decorReading(),resize:e=>this.commitDecorBase(t=>{Object.assign(t,{sizeM:{widthM:this.roundedMeters(e.widthM),lengthM:this.roundedMeters(e.lengthM),heightM:this.roundedMeters(e.heightM)}})},"sizeM.widthM"),turnTo:e=>this.commitDecorBase(t=>{t.headingDeg=this.rounded((e.headingDeg%360+360)%360)},"headingDeg"),rotateDegPerPx:a9};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=ue.naturalSize(e.kind,e.floors);return{sizeM:{widthM:e.sizeM?.widthM??t.widthM??1,lengthM:e.sizeM?.lengthM??t.lengthM??1,heightM:e.sizeM?.heightM??t.heightM??1},attitude:{headingDeg:ta.viewOf(e,this.ufoElement.currentTime).headingDeg,pitchDeg:0,rollDeg:0}}}onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!s||!i||(e.preventDefault(),i.show(s),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorMoveAxis(e){if(!(e.metaKey||[e.shiftKey,e.altKey,e.ctrlKey].filter(Boolean).length>1))return e.shiftKey?"east":e.altKey?"north":e.ctrlKey?"up":"ground"}grabsDecor(e,t,i){const s=this.pickDecorAt(e);if(s===i.id)return!0;const n=this.decorCanvasBounds();return n!==void 0&&t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+n.height?s===void 0||this.ufoElement.sighting.decor.find(a=>a.id===s)?.kind==="terrace":!1}beginDecorDrag(e,t,i){const s=this.editableDecor();if(!s)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.ufoElement.shapeAt(t.x,t.y,Rf)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=ta.viewOf(this.placedByAuthor(s),this.ufoElement.currentTime),a=n?this.sceneElement.decorGrabHeightAt?.(s.id,n.x,n.y)??0:0,o=n&&this.sceneElement.decorGroundPointAt(s.id,n.x,n.y,a);return!n||!o?!1:(this.dragState={kind:"decor-move",id:s.id,startGround:o,grabHeightM:a,axis:i,startAltitudeM:r.altitudeM,startNdcY:n.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(s.id)??0,startEastM:r.eastM,startNorthM:r.northM},this.setCanvasCursor("move"),this.startDragListening(),!0)}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e);if(!i)return;const s=this.sceneElement.decorGroundPointAt(t.id,i.x,i.y,t.grabHeightM);!s&&t.axis!=="up"||this.commitDecorBase(n=>{s&&(t.axis==="ground"||t.axis==="east")&&(n.eastM=this.roundedMeters(t.startEastM+s.x-t.startGround.x)),s&&(t.axis==="ground"||t.axis==="north")&&(n.northM=this.roundedMeters(t.startNorthM-(s.z-t.startGround.z))),t.axis==="up"&&(n.altitudeM=this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))},"eastM")}beginCameraDrag(e,t,i){const s=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,pressedBodyId:i,moved:!1,startPointer:e,startHeadingDeg:s?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:s?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:s},s||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&Sl(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Sl(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:s,startPointer:n}=this.dragState,r=t.x-n.x,a=t.y-n.y,o=s.map(({sourceId:l,original:h})=>({sourceId:l,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+a}}}));this.commitShapes(i,o)}else if(this.dragState.kind==="group-resize"){const{group:s,handle:n}=this.dragState;this.commitShapes(i,s.resize(n,t))}else if(this.dragState.kind==="group-rotate"){const{group:s,startPointer:n}=this.dragState;this.commitShapes(i,s.rotate(t,n))}else if(this.dragState.kind==="vertex"){const{sourceId:s,original:n,vertexIndex:r}=this.dragState,a=Jt.moveVertex(n,r,t);this.commitShapes(i,[{sourceId:s,shape:a}])}else{const{kind:s,sourceId:n,original:r,handle:a}=this.dragState,o=s==="resize"?Jt.resizeShape(r,a,t):Jt.rotateShape(r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:s,startPitchDeg:n,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<o9)return;this.cameraDragState.moved=!0}const a=s+(t.x-i.x)*wv,o=Math.max(-90,Math.min(90,n-(t.y-i.y)*wv));if(r){this.indoorLookYawDeg=a,this.indoorLookPitchDeg=o,this.sceneElement.setIndoorLook(a,o),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}walkOrTurn(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing"||this.isObserverInsideDecor())return;const t=e.shiftKey?p9:1,i=this.numberOrUndefined(this.headingInput.value)??0;if(e.key==="ArrowLeft"||e.key==="ArrowRight"){this.headingInput.value=String(this.rounded(i+(e.key==="ArrowRight"?1:-1)*u9*t)),this.updateObserver();return}const s=this.numberOrUndefined(this.latInput.value),n=this.numberOrUndefined(this.lngInput.value);if(s===void 0||n===void 0)return;const r=(e.key==="ArrowUp"?1:-1)*d9*t,a=i*Math.PI/180,o=Wn(Math.sin(a)*r,-Math.cos(a)*r,s,n);this.latInput.value=o.lat.toFixed(7),this.lngInput.value=o.lng.toFixed(7);const l=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(l,this.plantingCentre()),this.surroundings.walked(o.lat,o.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=ut(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(o,l)=>Math.round((o-l)*1e3)/1e3,a=this.ufoElement.sighting;a.decor=a.decor.map(o=>({...o,eastM:r(o.eastM,s),northM:r(o.northM,n),...o.track?{track:o.track.map(l=>({...l,eastM:r(l.eastM,s),northM:r(l.northM,n)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ul,i.width-Ho);break;case"ArrowRight":i.width+=Ho;break;case"ArrowUp":i.height=Math.max(ul,i.height-Ho);break;case"ArrowDown":i.height+=Ho;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Ho;break;case"ArrowRight":i.x+=Ho;break;case"ArrowUp":i.y-=Ho;break;case"ArrowDown":i.y+=Ho;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:s,shape:n}=i[0];this.commitShapes(t,[{sourceId:s,shape:{...n,bounds:this.nudgeBounds(n.bounds,e)}}])}else{const s=new G0(i),n=this.nudgeBounds(s.bounds(),e);this.commitShapes(t,s.scaleTo(n))}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(),s=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const o=r?this.bodyCanvasBounds():void 0,l=o&&Jt.hitTestHandle({bounds:o,angle:0},t);if(l)return this.cursorForHandle(l,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const o=this.decorCanvasBounds(),l=o&&Jt.hitTestHandle({bounds:o,angle:0},t);if(l)return this.cursorForHandle(l,0);const h=this.editableDecor();if(h&&!this.ufoElement.shapeAt(t.x,t.y,Rf)&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const o=Jt.hitTestHandle({bounds:new G0(this.selectedMembers()).bounds(),angle:0},t);if(o)return this.cursorForHandle(o,0)}else{const o=s.getInterpolatedShapeAt(n,this.currentSourceId);if(o?.kind==="polygon"&&Jt.hitTestVertex(o,t)!==void 0)return"vertex";const l=o&&Jt.hitTestHandle(o,t);if(o&&l)return this.cursorForHandle(l,o.angle)}return s.hitTest(n,t.x,t.y)?r&&a?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${Jt.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(),s=e.clientX-i.left,n=e.clientY-i.top;this.recorder?.onPointerMove(s,n),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(cE(this.buildPrototype({x:0,y:0,width:sh.width,height:sh.height}),s,n))}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 b9={measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},nE="rr0-sighting-editor",rE="rr0-ufo-recorder";class y9 extends _e{}function sT(){SE(),vy(),QA(),w8(),b8(),E8(),f0(),customElements.get(nE)||customElements.define(nE,_e),customElements.get(rE)||customElements.define(rE,y9)}const ny={event:"Event",accountOf:"Observation of",passagesHeading:"Reported in",interviewOf:"Interview of",untitledInterview:"Interview {n}",deleteInterviewQuestion:"Delete this interview from the case? Nothing is written until the case is saved.",untitledReading:"Reading {n}",eventsInTime:"Events · in the order of time",citedMoment:"Moment {k}, quoted in {title}: “{quote}”",backToInterview:"Back to the interview",openEvent:"Open",previousEvent:"Previous event",nextEvent:"Next event",kindReading:"Reading",readingsCount:"{n} reading(s)",untitledObservation:"Observation {n}",deleteRecording:"Delete this recording from the case",deleteReadingQuestion:"Delete this reading? Nothing is written until the case is saved.",deleteObservationQuestion:"Delete this observation from the case? Nothing is written until the case is saved.",deleteRefused:"This observation is interpreted by {n} reading(s): delete them first.",titleField:"Title of the interpretation",authorField:"Author",addTitle:"Add an event",kindField:"Type",kindObservation:"Observation",kindInterview:"Interview",witnessField:"Witness",mediumField:"Medium",interviewerField:"Interviewer",plainTitleField:"Title",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"An existing recording",observerField:"Observer",fileField:"File",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",recordingId:"ID",idTaken:"Another recording of the case has this ID.",idInvalid:"An ID is made of letters, digits, hyphens and underscores, and starts with a letter or a digit.",idNeeded:"A reading names this recording by its ID: it cannot be left empty.",idDuplicated:"Two events of the case have the ID “{id}”: a reading that names it is ambiguous.",readingUnresolved:"A reading names “{id}”, which no event of the case has as its ID, nor any recording it lists.",caseTitle:"Title",caseTime:"When",eventsTab:"Events",fileTab:"File",importFile:"Load case file",inputFileFromFile:"from your disk",inputFileFromUrl:"from an address",inputFileModeHint:"Click to give it the other way: a file of yours, or an address",inputFileLoad:"Load",fileNotACase:"That file is not a case (it has no events).",formatVersionError:"This file states version {found} of its format; this UFO@home reads up to version {supported}. Open it with a newer UFO@home.",fileInvalid:"This text is not valid JSON yet, or not a case: the case keeps what it last understood.",fileLoading:"Loading the editor…",add:"Add",addHint:"Add an event",interpretationOf:"Interpretation of",interpretationOfNone:"—",exportButton:"Save",exportTitle:"Save the case",exportAlso:"Also save the observations",addToCase:"Add to a case",unsavedChanges:"Changes not saved",discardQuestion:"Some changes are not saved yet. Load anyway and lose them?",discardTitle:"Unsaved changes",discardOk:"Load anyway",leaveQuestion:"Some changes are not saved yet. Leave anyway and lose them?",leaveOk:"Leave anyway"},w9=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:ny},Symbol.toStringTag,{value:"Module"})),aE="rr0-case-editor",M9=`
|
|
11575
11575
|
<style>
|
|
11576
11576
|
:host { display: block; }
|
|
11577
11577
|
${Vn.CSS}
|
|
@@ -11848,4 +11848,4 @@ ${Xt.rules([],[".model-picker .model-picker-address p"])}
|
|
|
11848
11848
|
</form>
|
|
11849
11849
|
</dialog>
|
|
11850
11850
|
`;class Th extends HTMLElement{shadow=this.attachShadow({mode:"open"});editor;session;current;listShown=!0;currentInterview;interviewElement;interviewReady;group="events";fileEditor;fileEditorLoading;fileApplied="";editorMessages=gl;messages=ny;said=new rn(["en"]);localeToken=0;language="en";dialogMode="add";pendingLoad;dirtyTimer;caseDate;dateModeFor;constructor(){super(),sT(),SE(),Rh.register(),this.shadow.innerHTML=M9,customElements.upgrade(this.shadow),this.shadow.getElementById("case-date").build();for(const t of this.shadow.querySelectorAll("rr0-input-file"))t.build();this.editor=this.shadow.getElementById("editor"),this.interviewElement=this.shadow.getElementById("interview"),this.interviewElement.addEventListener(tI,t=>this.interviewChanged(t.detail)),this.interviewElement.addEventListener(iI,t=>void this.followToObservation(t.detail)),this.editor.addEventListener("caseloaded",t=>{t.preventDefault();const{json:i,url:s}=t.detail;this.openCase(i,s??location.href,s!==void 0)}),this.editor.addEventListener("recordingloaded",()=>this.closeCase()),this.editor.guardsLeaving=!1,this.editor.addEventListener("beforeload",t=>{this.dirty&&(t.preventDefault(),this.pendingLoad=t.detail.proceed,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion))});for(const t of["input","change","datechange","click","pointerup","keyup"])this.shadow.addEventListener(t,()=>this.scheduleDirtyCheck(),!0);for(const[t,i]of[["case-id","id"],["case-title","title"]])this.input(t).addEventListener("input",()=>this.writeCaseField(i,this.input(t).value));this.caseDate=this.byId("case-date"),this.caseDate.addEventListener("datechange",t=>{const{time:i}=t.detail;this.writeCaseField("time",i?Th.rr0TimeOf(cl(i)):"")}),this.byId("track").addEventListener("change",()=>{this.byId("cited").hidden=!0,this.listShown=!1,this.refreshOverview();const t=this.session?this.items(this.session)[Number(this.byId("track").value)]:void 0;t&&(t.interview?this.showInterview(t.interview):this.showTrack(t.track))});const e=this.input("recording-id");e.addEventListener("input",()=>this.writeRecordingId()),e.addEventListener("blur",()=>{this.showRecordingIdError(void 0),this.refreshRow()});for(const t of this.shadow.querySelectorAll("#case-tabs .group-tab"))t.addEventListener("click",()=>this.openGroup(t.getAttribute("aria-controls")==="group-case-file"?"file":"events"));this.inputFile("import").addEventListener("filepick",t=>{const i=t.detail;i.file?this.importFromFile(i.file):this.importFromUrl(i.url)}),this.byId("add").addEventListener("click",()=>this.askAdd()),this.byId("cited-back").addEventListener("click",()=>{const t=this.citedFrom;if(!t||!this.session)return;const i=this.items(this.session).findIndex(s=>s.interview===t);i>=0&&this.openEvent(i)}),this.byId("back-to-case").addEventListener("click",()=>{this.listShown=!0,this.refreshRow()}),this.byId("previous-event").addEventListener("click",()=>this.stepEvent(-1)),this.byId("next-event").addEventListener("click",()=>this.stepEvent(1)),this.shareDialog=this.byId("share-dialog"),this.shareDialog.subject=this.shareSubject,this.byId("share-case").addEventListener("click",()=>this.openShare()),this.byId("save-case").addEventListener("click",()=>void this.exportCase(this.input("save-also").checked).then(()=>this.refreshDirty())),this.byId("make-case").addEventListener("click",()=>this.makeCase()),this.byId("delete").addEventListener("click",()=>this.askDelete()),this.byId("export").addEventListener("click",()=>this.askExport()),this.byId("source").addEventListener("change",()=>this.syncSourceFields()),this.byId("kind").addEventListener("change",()=>this.syncSourceFields()),this.byId("of").addEventListener("change",()=>this.syncSourceFields()),this.byId("cancel").addEventListener("click",()=>this.closeDialog()),this.byId("dialog").addEventListener("close",()=>{this.pendingLoad=void 0}),this.byId("form").addEventListener("submit",t=>{t.preventDefault(),this.submitDialog()})}static get observedAttributes(){return["src"]}attributeChangedCallback(e,t,i){e==="src"&&i&&this.editor.setAttribute("src",i)}warnBeforeLeaving=e=>{this.leaving||!this.dirty||(e.preventDefault(),e.returnValue="")};disconnectedCallback(){document.removeEventListener("click",this.askBeforeFollowing,!0),window.removeEventListener("beforeunload",this.warnBeforeLeaving),window.clearTimeout(this.dirtyTimer)}get dirty(){return this.session?(this.commit(),this.session.dirty):this.editor.dirty}scheduleDirtyCheck(){window.clearTimeout(this.dirtyTimer),this.dirtyTimer=window.setTimeout(()=>this.refreshDirty(),600)}refreshDirty(){const e=this.session;e&&this.commit(),this.byId("dirty").hidden=!(e&&e.dirty),this.refreshCaseState();const t=e?this.current!==void 0&&e.changed(this.current):this.editor.dirty;this.byId("recording-dirty").hidden=!t}leaving=!1;askBeforeFollowing=e=>{if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const t=e.composedPath().find(s=>s instanceof HTMLAnchorElement);if(!t||!t.href||t.target&&t.target!=="_self"||t.hasAttribute("download"))return;const i=new URL(t.href,location.href);i.href===location.href||i.origin===location.origin&&i.pathname===location.pathname&&i.search===location.search&&i.hash!==""||this.dirty&&(e.preventDefault(),e.stopPropagation(),this.pendingLoad=()=>{this.leaving=!0,location.assign(i.href)},this.openDialog("discard",this.messages.discardTitle,this.messages.leaveQuestion,this.messages.leaveOk))};connectedCallback(){document.addEventListener("click",this.askBeforeFollowing,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.editor.getAttribute("src")!==e&&this.editor.setAttribute("src",e),this.loadLocale()}get sightingData(){return this.editor.sightingData}set sightingData(e){const t=Ui.toCurrent(e);this.closeCase(),this.editor.sightingData=t}get sightingEditor(){return this.editor}get caseSession(){return this.session}byId(e){return this.shadow.getElementById(e)}async loadLocale(){const e=++this.localeToken,t=Sr.preferencesFor(this),i=$u(t,Wu),[s,n]=i==="en"?[ny,gl]:await Promise.all([$3(i),ME(i)]);if(e!==this.localeToken)return;this.said=new rn(t),this.language=i,this.messages=s,this.caseDate.messages=n,this.editorMessages=n,this.applyMessages(),this.refreshRow();const r=await this.shareDialog.useLanguage(i);!r||e!==this.localeToken||(this.shareMessages=r,this.byId("label-share-case").textContent=r.share,this.refreshCaseState())}applyMessages(){Vn.dialog(this.dialog,this.messages.cancel,()=>this.closeDialog());const e=this.messages,t=(n,r)=>{this.byId(n).textContent=r};t("case-kicker",e.caseHeading),t("label-back-to-case",e.caseHeading),t("label-events-in-time",e.eventsInTime),t("label-back-to-interview",e.backToInterview),t("label-add",e.addTitle),t("label-save-also",e.exportAlso),t("label-save-case",e.exportButton);for(const[n,r]of[["previous-event",e.previousEvent],["next-event",e.nextEvent]])this.byId(n).title=r,this.byId(n).setAttribute("aria-label",r);t("label-case-id",e.caseId),t("label-case-title",e.caseTitle),t("label-case-time",e.caseTime),t("label-events-group",e.eventsTab),t("label-case-file-group",e.fileTab),t("label-import-file",e.importFile),this.byId("track").setAttribute("aria-label",e.event),t("label-kind",e.kindField),t("label-witness",e.witnessField),t("label-medium",e.mediumField),t("label-recording-id",e.recordingId),t("make-case",e.addToCase);for(const n of["dirty","recording-dirty"])this.byId(n).title=e.unsavedChanges,this.byId(n).setAttribute("aria-label",e.unsavedChanges);t("export",e.exportButton),t("label-export-recordings",e.exportAlso),t("label-title",e.titleField),t("label-author",e.authorField),t("label-date",e.caseTime),t("label-of",e.interpretationOf),t("label-source",e.sourceField),t("label-observer",e.observerField),t("label-file",e.fileField);for(const n of this.shadow.querySelectorAll("rr0-input-file"))n.messages=e;t("ok",e.ok),t("cancel",e.cancel);const i=this.byId("source");[e.sourceBlank,e.sourceFile].forEach((n,r)=>{i.options[r].textContent=n});const s=this.byId("kind");[e.kindObservation,e.kindInterview].forEach((n,r)=>{s.options[r].textContent=n}),this.byId("add").title=e.addHint,this.byId("add").setAttribute("aria-label",e.addHint),this.byId("delete").title=e.deleteRecording,this.byId("delete").setAttribute("aria-label",e.deleteRecording)}openGroup(e){this.group=e;for(const t of this.shadow.querySelectorAll("#case-tabs .group-tab"))t.setAttribute("aria-expanded",String(t.getAttribute("aria-controls")===(e==="file"?"group-case-file":"group-events")));e==="file"?this.loadFileEditor().then(()=>this.syncFileEditor(),()=>this.showFileNote(this.messages.loadFailed,"error")):this.leaveFile(),this.refreshRow()}applySections(){const e=this.session,t=e===void 0||this.group==="events";this.byId("events-row").hidden=e===void 0,this.byId("group-events").hidden=!t,this.byId("group-case-file").hidden=e===void 0||this.group!=="file",this.byId("recording").hidden=this.currentInterview!==void 0,this.byId("interview-section").hidden=this.currentInterview===void 0,this.byId("history-slot").hidden=this.currentInterview!==void 0}showFileNote(e,t="info"){Xt.show(this.byId("case-file-note"),e,t)}fileText(){return this.session?JSON.stringify(this.session.json,null,2)+`
|
|
11851
|
-
`:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([oe(()=>import("./SightingFileEditor-BekK-f3R.js"),__vite__mapDeps([14,1,15]),import.meta.url),oe(()=>import("./caseSchema-DixCNMzt.js"),[],import.meta.url)]),i=this.fileText();return this.fileApplied=i,this.fileEditor=new e(this.byId("case-file-editor"),i,s=>this.onFileEdited(s),this.editorMessages.fileEditorLabel,{baseline:i,phrases:this.editorMessages.fileSearchPhrases,schema:t}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}syncFileEditor(){if(!this.fileEditor||!this.session)return;this.commit();const e=this.fileText();this.fileApplied=e,this.fileEditor.replaceText(e,!1),this.showFileNote(void 0)}onFileEdited(e){const t=this.session;if(!t)return;if(e===this.fileApplied){this.showFileNote(void 0);return}let i;try{i=JSON.parse(e)}catch{this.showFileNote(this.messages.fileInvalid,"error");return}if(!Hi.isCase(i)){this.showFileNote(this.messages.fileInvalid,"error");return}try{Hi.check(i)}catch(s){this.showFileNote(s instanceof wu?s.said(this.messages.formatVersionError):this.messages.fileInvalid,"error");return}this.fileApplied=e,this.showFileNote(void 0),JSON.stringify(i)!==JSON.stringify(t.json)&&(t.replaceJson(i),this.current&&!t.tracks.includes(this.current)&&(this.current=void 0),this.currentInterview&&!t.interviews.includes(this.currentInterview)&&(this.currentInterview=void 0),this.refreshRow(),this.scheduleDirtyCheck())}leaveFile(){const e=this.session;if(e)if(this.current===void 0&&this.currentInterview===void 0){const t=e.tracks.find(i=>i.kind==="observer")??e.tracks[0];t&&this.showTrack(t)}else this.currentInterview&&(this.interviewElement.event=this.currentInterview)}guarded(e){if(!this.dirty){e();return}this.pendingLoad=e,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion)}async importFromFile(e){try{const t=JSON.parse(await e.text());this.guarded(()=>void this.importCase(t,new URL("case.json",location.href).href,!1))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importFromUrl(e){try{const t=new URL(e,location.href).href,i=await na.json(t);this.guarded(()=>void this.importCase(i,t,!0))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importCase(e,t,i){if(!Hi.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t,i)}catch(s){this.showFileNote(s instanceof wu?s.said(this.messages.formatVersionError):this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t,i){Hi.check(e);const s=new Ku(e,t);if(this.sourceUrl=i?t:void 0,s.tracks.length===0)throw new Error("A case with no recording has nothing to edit");this.session=s,this.current=void 0;const n=this.getAttribute("track"),r=n?new URL(n,t).href:void 0,a=s.tracks.find(o=>o.url===r)??s.tracks.find(o=>o.kind==="observer")??s.tracks[0];this.listShown=r===void 0,await this.showTrack(a)}closeCase(){this.session&&(this.session=void 0,this.current=void 0,this.currentInterview=void 0,this.editor.reading=!1,this.editor.accountShapeIds=void 0,this.refreshRow())}commit(){this.session&&this.current&&this.editor.edited&&this.session.keep(this.current,this.editor.sightingData)}async loadTrack(e){e.recording||(e.recording=Ui.toCurrent(await na.recording(e.url)),e.loaded=JSON.stringify(e.recording))}async showTrack(e){const t=this.session;if(t){this.commit(),this.currentInterview=void 0,this.editor.passages=void 0;try{const i=!e.recording;await this.loadTrack(e);const s=t.accountOf(e);s&&await this.loadTrack(s),this.current=e,this.editor.documentUrl=e.base?e.base.url:e.url,this.editor.reading=e.kind==="reading",this.editor.accountShapeIds=e.kind==="reading"&&s?.recording?Th.shapesOf(s.recording):void 0;const n=e.kind==="observer"?t.readingsOf(e):[];for(const r of n)await this.loadTrack(r).catch(()=>{});this.editor.readings=n.filter(r=>r.recording?.interpretation?.bodies.length||r.recording?.interpretation?.flares?.length||r.recording?.interpretation?.lanterns?.length).map(r=>({id:r.event.id??t.proposedId(r),label:this.labelOf(r,t.tracks.indexOf(r)),interpretation:r.recording.interpretation})),this.editor.sightingData=structuredClone(e.recording),i&&t.keep(e,this.editor.sightingData,!0),s&&s.loaded===void 0&&t.keep(s,s.recording,!0)}catch{this.showError(this.messages.loadFailed)}this.refreshRow(),this.showPassages(e)}}passagesToken=0;async transcriptOf(e){const t=this.session;if(t)try{const{InterviewFile:i}=await oe(async()=>{const{InterviewFile:n}=await import("./interviewJson-DXD8FSBX.js");return{InterviewFile:n}},[],import.meta.url),s=t.transcriptText(e);if(s!==void 0)return i.read(JSON.parse(s));if(e.url)return i.read(await na.json(new URL(e.url,t.url??location.href).href))}catch{}}async showPassages(e){const t=this.session,i=++this.passagesToken;if(this.editor.passages=void 0,!t||e.kind!=="observer"||t.interviews.length===0)return;const{InterviewFile:s}=await oe(async()=>{const{InterviewFile:o}=await import("./interviewJson-DXD8FSBX.js");return{InterviewFile:o}},[],import.meta.url);if(i!==this.passagesToken)return;const n=e.event.id??t.proposedId(e),r=[];for(const o of t.interviews){const l=await this.transcriptOf(o);if(!l||!Array.isArray(l.segments))continue;const h={...l,interviewOf:l.interviewOf??o.interviewOf};for(const d of s.passagesAbout(h,n))r.push({interview:o,json:l,passage:d})}if(i!==this.passagesToken||this.current!==e||r.length===0)return;const a=this.items(t);this.editor.passages=r.sort((o,l)=>o.passage.at-l.passage.at).map(({interview:o,json:l,passage:h})=>{const d=`${this.messages.passagesHeading} ${this.optionLabel({interview:o},a.findIndex(p=>p.interview===o))}`,u=h.text===void 0?"":h.range?h.text.slice(h.range[0],h.range[1]):h.text;return{at:h.at,clock:s.clock(h.at,!0),said:u===""?d:`${s.speakerName(l,h.speaker)} : « ${u.length>120?`${u.slice(0,117)}…`:u} »`,where:d,open:()=>void this.showInterview(o).then(()=>this.interviewElement.revealSegment(h.index))}})}async followToObservation(e){const t=this.session;if(!t)return;const i=t.tracks.find(n=>n.kind==="observer"&&(n.event.id??t.proposedId(n))===e.sighting)??t.tracks.find(n=>n.kind==="observer");if(!i)return;const s=this.currentInterview;this.listShown=!1,await this.showTrack(i),this.editor.openSection("group-temporal"),this.editor.seekTo(e.at),this.showCited(s,i,e),this.editor.showRender()}static shapesOf(e){const t=new Set;for(const i of e.timeline?.keyframes??[])for(const s of i.shapes??[])t.add(s.sourceId);return[...t]}items(e){return[...e.tracks.map(t=>({track:t})),...e.interviews.map(t=>({interview:t}))]}optionLabel(e,t){const i=this.session;if(e.interview){const r=i.intervieweesOf(e.interview),a=r.length>0?r.map(o=>this.labelOf(o,i.tracks.indexOf(o))).join(", "):this.said.read(e.interview.title);return a?`${this.messages.interviewOf} ${a}`:this.messages.untitledInterview.replace("{n}",String(i.interviews.indexOf(e.interview)+1))}const s=e.track,n=this.labelOf(s,t);return s.kind==="observer"?`${this.messages.accountOf} ${n}`:n}async showInterview(e){const t=this.session;if(t&&(this.commit(),this.current=void 0,this.passagesToken++,this.editor.passages=void 0,this.currentInterview=e,this.refreshRow(),await this.ensureInterview(),this.currentInterview===e)){for(const i of t.intervieweesOf(e))await this.loadTrack(i).catch(()=>{});this.currentInterview===e&&(this.interviewElement.witnesses=t.tracks.filter(i=>i.kind==="observer").map(i=>({id:i.event.id??t.proposedId(i),label:this.labelOf(i,t.tracks.indexOf(i)),moments:this.momentsOf(i)})),this.interviewElement.documentUrl=t.url,this.interviewElement.transcriptText=t.transcriptText(e),this.interviewElement.event=e)}}ensureInterview(){return this.interviewReady??=oe(async()=>{const{register:e}=await import("./InterviewEditorElement-Cpu0vwrk.js");return{register:e}},__vite__mapDeps([25,26,27,28]),import.meta.url).then(({register:e})=>{e(),customElements.upgrade(this.shadow)},e=>{throw this.interviewReady=void 0,e}),this.interviewReady}interviewChanged(e){const{field:t}=e,i=this.session,s=this.currentInterview;if(!(!i||!s)){t==="transcript"&&e.text!==void 0&&i.keepTranscript(s,e.text);for(const n of[s.interviewOf].flat()){const r=i.tracks.find(a=>a.kind==="observer"&&(a.event.id??i.proposedId(a))===n);r&&i.ensureId(r)}i.touch(),this.refreshRow(),this.scheduleDirtyCheck()}}eventsInTime(e){const t=this.items(e),i=s=>String((s.track?.event??s.interview)?.time??"");return t.map((s,n)=>({item:s,index:n})).sort((s,n)=>i(s.item).localeCompare(i(n.item)))}momentsOf(e){return(e.recording?.milestones??[]).map(t=>{const i=this.said.read(t.note);return{at:t.t/1e3,label:this.said.read(t.label)??"",...i?{note:i}:{}}})}citedFrom;showCited(e,t,i){const s=this.byId("cited");if(this.citedFrom=e,!e||!this.session){s.hidden=!0;return}const n=this.momentsOf(t).find(a=>Math.abs(a.at-i.at)<.05),r=(i.quote??"").length>120?`${i.quote.slice(0,117)}…`:i.quote??"";this.byId("cited-text").textContent=this.messages.citedMoment.replace("{k}",n?.label??`${Math.round(i.at)} s`).replace("{title}",this.optionLabel({interview:e},0)).replace("{quote}",r),s.hidden=!1}kindOf(e){return e.interview?"interview":e.track.kind==="reading"?"reading":"observation"}kindLabel(e){return{observation:this.messages.kindObservation,interview:this.messages.kindInterview,reading:this.messages.kindReading}[e]}refreshOverview(){const e=this.session,t=this.byId("case-overview"),i=this.byId("event-crumbs");if(t.hidden=!e||!this.listShown,i.hidden=!e||this.listShown,this.byId("event-item").hidden=e!==void 0&&this.listShown,this.byId("events-count").textContent=e?String(this.items(e).length):"",this.byId("case-heading").textContent=e&&String(e.json.title??"")||this.messages.caseHeading,!e)return;const s=this.eventsInTime(e);this.renderEvents(e,s);const n=s.findIndex(({item:a})=>a.interview?a.interview===this.currentInterview:a.track===this.current),r=s[n];if(r){const a=this.kindOf(r.item),o=this.byId("crumb-kind");o.textContent=this.kindLabel(a),o.dataset.kind=a,this.byId("crumb-title").textContent=this.optionLabel(r.item,r.index)}this.byId("previous-event").disabled=n<=0,this.byId("next-event").disabled=n<0||n>=s.length-1}renderEvents(e,t){const i=this.messages;this.byId("event-list").replaceChildren(...t.map(({item:n,index:r})=>{const a=this.kindOf(n),o=n.track?.event??n.interview,l=document.createElement("li");l.className="event-card",l.dataset.kind=a;const h=document.createElement("span");h.className="kind-pill",h.dataset.kind=a,h.textContent=this.kindLabel(a);const d=document.createElement("div");d.className="event-main";const u=document.createElement("button");u.type="button",u.className="event-open",u.textContent=this.optionLabel(n,r),u.title=i.openEvent,u.addEventListener("click",()=>this.openEvent(r));const p=document.createElement("span");p.className="event-meta",p.textContent=[o.time?String(o.time).replace("T"," "):"",o.id??""].filter(Boolean).join(" · "),d.append(u,p);const f=document.createElement("span");f.className="event-links";const m=[];if(n.track?.kind==="observer"){const b=e.interviews.filter(y=>e.intervieweesOf(y).includes(n.track)).map(y=>this.optionLabel({interview:y},0));b.length>0&&m.push(`${i.passagesHeading} : ${b.join(", ")}`);const w=e.readingsOf(n.track).length;w>0&&m.push(i.readingsCount.replace("{n}",String(w)))}else if(n.track){const b=e.accountOf(n.track);b&&m.push(`${i.interpretationOf} : ${this.optionLabel({track:b},e.tracks.indexOf(b))}`)}f.textContent=m.join(" · ");const v=document.createElement("button");v.type="button",v.className="icon-btn event-delete",v.innerHTML=Ee.TRASH,v.title=i.deleteRecording,v.setAttribute("aria-label",i.deleteRecording),v.addEventListener("click",()=>void this.deleteFromList(r));const g=document.createElement("div");return g.className="event-body",g.append(h,d,f),l.append(g,v),l}))}openEvent(e){const t=this.byId("track");t.value=String(e),t.dispatchEvent(new Event("change")),requestAnimationFrame(()=>this.bringEditorIntoView())}bringEditorIntoView(){const e=this.editor;if(!e.checkVisibility?.())return;const t=e.getBoundingClientRect();Math.abs(t.top)>1&&e.scrollIntoView?.({block:"start",behavior:"smooth"})}async deleteFromList(e){const t=this.session,i=t?this.items(t)[e]:void 0;i&&(this.byId("track").value=String(e),i.interview?await this.showInterview(i.interview):await this.showTrack(i.track),this.askDelete())}stepEvent(e){const t=this.session;if(!t)return;const i=this.eventsInTime(t),s=i.findIndex(({item:r})=>r.interview?r.interview===this.currentInterview:r.track===this.current),n=i[s+e];n&&this.openEvent(n.index)}refreshCaseState(){this.byId("save-case").disabled=!(this.session?.dirty??!1);const e=this.byId("share-case");e.disabled=this.sourceUrl===void 0,e.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":""}sourceUrl;shareDialog;shareMessages;get sharedTrack(){return this.currentInterview?void 0:this.current?.url}shareSubject={module:"rr0-sighting-editor",link:()=>{const e=this.sharedTrack;return`${ed.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}${e?`&track=${encodeURIComponent(e)}`:""}`},element:()=>{const e=this.sharedTrack;return`<rr0-case-editor src="${this.sourceUrl??""}"${e?` track="${e}"`:""}></rr0-case-editor>`}};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.session?.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}labelOf(e,t){const i=this.said.read(e.event.title)??this.said.read(e.recording?.interpretation?.title);if(i)return i;if(e.kind==="observer")return this.said.read(e.recording?.observer?.title)??e.event.url??"";const s=this.session.tracks.filter(n=>n.kind==="reading").indexOf(e)+1;return this.messages.untitledReading.replace("{n}",String(s||t+1))}makeCase(){if(this.session)return;const e=this.editor.sightingData,t=e.time,i=typeof t=="object"?t.value:t,s=i?Th.rr0TimeOf(i):void 0,n=this.said.read(e.observer?.title),r=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=Ku.around(e,s,n,r,location.href),this.listShown=!1,this.current=this.session.tracks[0],this.session.keep(this.current,e),this.dateModeFor=void 0,this.refreshRow()}writeCaseField(e,t){const i=this.session?.json;i&&(t.trim()===""?delete i[e]:i[e]=t,this.session?.touch(),this.scheduleDirtyCheck())}static rr0TimeOf(e){return e.replace(/^(\d{4}-\d\d-\d\d)T/,"$1 ")}static edtfOf(e){return e.replace(/^(\d{4}-\d\d-\d\d) (?=\d)/,"$1T")}showCaseTime(e){const t=String(e.json.time??""),i=t===""?void 0:Jd(Th.edtfOf(t));if(this.caseDate.time=i,t!==""&&!i){const s=this.input("case-time");s.value=t}this.dateModeFor!==e&&(this.caseDate.setPrecise(!(t!==""&&!i)&&Ks.opensPrecise(i)),this.dateModeFor=e)}refreshRow(){const e=this.session;if(this.applySections(),this.byId("case-panel").hidden=e===void 0,this.refreshOverview(),this.byId("make-case-row").hidden=e!==void 0,this.byId("case").classList.toggle("in-case",e!==void 0),this.byId("event-item").classList.toggle("in-case",e!==void 0),this.holdEditor(e!==void 0),!e){this.refreshDirty();return}const t=this.shadow.activeElement;for(const[r,a]of[["case-id","id"],["case-title","title"]]){const o=this.input(r);o!==t&&(o.value=String(e.json[a]??""))}t?.closest?.("rr0-date-input")||this.showCaseTime(e);const i=this.byId("track"),s=this.items(e);i.replaceChildren(...s.map((r,a)=>new Option(this.optionLabel(r,a),String(a))));const n=this.currentInterview?s.findIndex(r=>r.interview===this.currentInterview):this.current?s.findIndex(r=>r.track===this.current):0;i.value=String(Math.max(0,n)),this.byId("delete").disabled=this.currentInterview===void 0&&e.tracks.length<=1,this.refreshRecordingId(e),this.refreshDirty()}holdEditor(e){this.editor.embedded=e,e&&this.byId("history-slot").append(this.editor.historyControls),this.shadow.querySelector(".event-id-row").hidden=!e}refreshRecordingId(e){const t=this.current,i=t!==void 0&&t.kind==="observer";if(this.byId("row-recording-id").hidden=!i,i){const o=this.input("recording-id");this.shadow.activeElement!==o&&(o.value=t.event.id??""),o.placeholder=e.proposedId(t)}const{duplicateIds:s,unresolved:n}=e.problems(),r=[...s.map(o=>this.messages.idDuplicated.replace("{id}",o)),...n.map(({reference:o})=>this.messages.readingUnresolved.replace("{id}",o))],a=this.byId("case-problems");a.hidden=r.length===0,a.textContent=r.join(" ")}showRecordingIdError(e){const t=this.byId("recording-id-error");t.textContent=e??"",t.hidden=e===void 0}writeRecordingId(){const e=this.session,t=this.current;if(!e||!t)return;const i=e.setId(t,this.input("recording-id").value.trim());this.showRecordingIdError(i==="ok"?void 0:{empty:this.messages.idNeeded,invalid:this.messages.idInvalid,taken:this.messages.idTaken}[i]),this.scheduleDirtyCheck()}get dialog(){return this.byId("dialog")}openDialog(e,t,i,s){this.dialogMode=e,this.byId("dialog-title").textContent=t;const n=this.byId("dialog-message");n.textContent=i??"",n.hidden=i===void 0,this.showError(void 0),this.byId("fields-add").hidden=e!=="add",this.byId("fields-export").hidden=e!=="export",this.byId("ok").hidden=!1,this.byId("ok").textContent=s??(e==="discard"?this.messages.discardOk:this.messages.ok),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open","")}closeDialog(){this.pendingLoad=void 0,typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}showError(e){const t=this.byId("dialog-error");t.textContent=e??"",t.hidden=e===void 0}input(e){return this.byId(e)}inputFile(e){return this.byId(e)}today(){return new Date().toISOString().slice(0,10)}askAdd(){const e=this.session;if(!e)return;this.openDialog("add",this.messages.addTitle);const t=this.byId("of");t.replaceChildren(new Option(this.messages.interpretationOfNone,""),...e.tracks.filter(s=>s.kind==="observer").map(s=>new Option(this.labelOf(s,e.tracks.indexOf(s)),String(e.tracks.indexOf(s))))),t.value="",this.byId("kind").value="observation";const i=e.tracks.filter(s=>s.kind==="observer");this.byId("witness").replaceChildren(...i.map(s=>new Option(this.labelOf(s,e.tracks.indexOf(s)),String(e.tracks.indexOf(s))))),this.byId("medium").replaceChildren(),this.byId("source").value="blank";for(const s of["observer","title","author"])this.input(s).value="";this.inputFile("add-source").clear(),this.input("date").value="",this.syncSourceFields()}async fillMedia(){const{InterviewMedia:e}=await oe(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CvAxC62V.js");return{InterviewMedia:i}},[],import.meta.url),t=this.byId("medium");t.options.length>0||t.replaceChildren(...e.ALL.map(i=>new Option(e.label(i,this.language),i)))}syncSourceFields(){const e=this.byId("kind").value==="interview",t=this.byId("source").value,i=!e&&this.byId("of").value!=="";this.byId("row-source").hidden=e,this.byId("row-of").hidden=e,this.byId("row-witness").hidden=!e,this.byId("row-medium").hidden=!e,e&&this.fillMedia(),this.byId("row-file").hidden=e||t!=="file",this.byId("row-observer").hidden=e||i,this.byId("row-title").hidden=!(e||i),this.byId("row-author").hidden=!(e||i),this.byId("label-title").textContent=e?this.messages.plainTitleField:this.messages.titleField,this.byId("label-author").textContent=e?this.messages.interviewerField:this.messages.authorField}askExport(){this.session&&(this.openDialog("export",this.messages.exportTitle),this.input("export-recordings").checked=!0)}askDelete(){const e=this.session;if(e&&this.currentInterview){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteInterviewQuestion);return}const t=this.current;if(!(!e||!t)){if(t.kind==="observer"){const i=e.readingsOf(t).length;if(i>0){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteRefused.replace("{n}",String(i))),this.byId("ok").hidden=!0;return}}this.openDialog("delete",this.messages.deleteRecording,t.kind==="reading"?this.messages.deleteReadingQuestion:this.messages.deleteObservationQuestion)}}async submitDialog(){switch(this.dialogMode){case"delete":this.closeDialog(),this.deleteCurrent();return;case"discard":{const e=this.pendingLoad;this.closeDialog(),e?.();return}case"export":await this.exportCase(this.input("export-recordings").checked)?this.closeDialog():this.showError(this.messages.loadFailed);return;case"add":await this.addRecording()&&this.closeDialog()}}async addRecording(){const e=this.session;if(!e)return!1;if(this.commit(),this.byId("kind").value==="interview"){const u=e.tracks[Number(this.byId("witness").value)],p=this.input("title").value.trim(),f=this.input("author").value.trim(),m=e.addInterview(u,this.input("date").value||this.today(),p!==""?p:void 0,f!==""?f.split(",").map(v=>({people:v.trim()})).filter(v=>v.people!==""):void 0,this.byId("medium").value);return await this.showInterview(m),!0}const t=this.byId("of").value,i=t===""?void 0:e.tracks[Number(t)],s=this.byId("source").value;if(i&&s==="blank"){if(i.kind!=="observer"||!i.recording)return!1;const u=this.input("title").value.trim(),p=this.input("author").value.trim(),f=e.addReading(i,this.input("date").value||this.today(),u!==""?u:void 0,p!==""?[{title:p}]:void 0);return this.showTrack(f),!0}const n=this.input("observer").value.trim(),r=this.input("date").value.trim();let a;try{if(s==="blank"){const u=(n||"observation").replace(/[^A-Za-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation";a={version:3,id:`${r?`${r}-`:""}${u}`,...n?{observer:{title:n}}:{},...r?{time:r}:{},timeline:{keyframes:[],order:[],groups:[]}}}else{const u=await this.readFile();if(Hi.isCase(u))return this.showError(this.messages.isACase),!1;a=u,n&&!a.observer?.title&&(a={...a,observer:{...a.observer,title:n}})}}catch{return this.showError(this.messages.loadFailed),!1}const o=(i?this.input("title").value:n).trim(),l=o!==""?o:this.said.read(a.observer?.title),h=this.input("author").value.trim(),d=e.addObservation(a,r!==""?r:void 0,l,i?{account:i,by:h!==""?[{title:h}]:void 0}:void 0);return this.showTrack(d),!0}async readFile(){const e=this.inputFile("add-source").value;if(!e)throw new Error("No file");if(e.url)return na.recording(new URL(e.url,location.href).href);const t=e.file,i=await new Promise((s,n)=>{const r=new FileReader;r.onload=()=>s(r.result),r.onerror=()=>n(r.error),r.readAsText(t)});return JSON.parse(i)}deleteCurrent(){const e=this.session,t=this.currentInterview;if(e&&t){if(!e.deleteInterview(t))return;this.currentInterview=void 0;const r=e.tracks.find(a=>a.kind==="observer")??e.tracks[0];r&&this.showTrack(r);return}const i=this.current;if(!e||!i)return;const s=i.kind==="reading"?e.accountOf(i)??e.tracks.find(r=>r.kind==="observer"):e.tracks.find(r=>r!==i);(i.kind==="reading"?e.deleteReading(i):e.deleteObservation(i).deleted)&&(this.current=void 0,s&&this.showTrack(s))}async exportCase(e=!0){const t=this.session;if(!t)return!0;if(this.commit(),e)try{for(const a of t.tracks)await this.loadTrack(a)}catch{return!1}const i=t.files(e,!0);if(t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),i.length===1)return this.download(new Blob([i[0].content],{type:"application/json"}),i[0].path),!0;const{zipSync:s,strToU8:n}=await oe(async()=>{const{zipSync:a,strToU8:o}=await import("./browser-_Ncw3Jhn.js");return{zipSync:a,strToU8:o}},[],import.meta.url),r={};for(const a of i)r[a.path]=n(a.content);return this.download(new Blob([s(r)],{type:"application/zip"}),`${t.json.id??"case"}.zip`),!0}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}}function x9(){sT(),customElements.get(aE)||customElements.define(aE,Th)}x9();export{Wv as $,Zf as A,i2 as B,fs as C,S9 as D,Dh as E,il as F,xa as G,Sr as H,iI as I,A9 as J,Ze as K,Oe as L,Xt as M,Us as N,ir as O,tt as P,Tn as Q,De as R,rn as S,gt as T,Wu as U,I as V,Vn as W,Wr as X,lh as Y,lc as Z,oe as _,na as a,D9 as a$,tn as a0,Pn as a1,Mr as a2,j8 as a3,JN as a4,h1 as a5,cP as a6,Kt as a7,$g as a8,ue as a9,N9 as aA,Pt as aB,Aa as aC,RR as aD,Se as aE,Ot as aF,W9 as aG,k9 as aH,r_ as aI,Nb as aJ,sr as aK,Hf as aL,Dl as aM,Rd as aN,$n as aO,qs as aP,zs as aQ,z9 as aR,xl as aS,on as aT,Ys as aU,Tt as aV,is as aW,As as aX,_n as aY,_9 as aZ,R9 as a_,we as aa,ht as ab,el as ac,Ss as ad,aa as ae,Er as af,YR as ag,_m as ah,nn as ai,Yv as aj,bu as ak,sn as al,zi as am,e9 as an,LR as ao,ae as ap,ut as aq,se as ar,ru as as,xt as at,Mt as au,wt as av,Br as aw,H9 as ax,V9 as ay,Am as az,Ee as b,vp as b0,B9 as b1,F9 as b2,Mm as b3,bA as b4,L9 as b5,FM as b6,U9 as b7,G9 as b8,J2 as b9,El as bA,gp as bB,xr as ba,Dp as bb,q0 as bc,V_ as bd,di as be,Al as bf,sb as bg,ms as bh,$a as bi,qD as bj,xi as bk,C9 as bl,O9 as bm,tA as bn,P9 as bo,Ar as bp,eA as bq,sx as br,VD as bs,$A as bt,bm as bu,Ob as bv,gA as bw,Qy as bx,e1 as by,Wt as bz,vo as c,Hn as d,tI as e,ME as f,Xr as g,Yo as h,Gt as i,ke as j,Wn as k,T9 as l,Zo as m,qi as n,Va as o,ft as p,bt as q,QA as r,$u as s,I9 as t,wn as u,ea as v,Ml as w,Nt as x,Cf as y,E9 as z};
|
|
11851
|
+
`:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([oe(()=>import("./SightingFileEditor-BekK-f3R.js"),__vite__mapDeps([16,1,17]),import.meta.url),oe(()=>import("./caseSchema-DixCNMzt.js"),[],import.meta.url)]),i=this.fileText();return this.fileApplied=i,this.fileEditor=new e(this.byId("case-file-editor"),i,s=>this.onFileEdited(s),this.editorMessages.fileEditorLabel,{baseline:i,phrases:this.editorMessages.fileSearchPhrases,schema:t}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}syncFileEditor(){if(!this.fileEditor||!this.session)return;this.commit();const e=this.fileText();this.fileApplied=e,this.fileEditor.replaceText(e,!1),this.showFileNote(void 0)}onFileEdited(e){const t=this.session;if(!t)return;if(e===this.fileApplied){this.showFileNote(void 0);return}let i;try{i=JSON.parse(e)}catch{this.showFileNote(this.messages.fileInvalid,"error");return}if(!Hi.isCase(i)){this.showFileNote(this.messages.fileInvalid,"error");return}try{Hi.check(i)}catch(s){this.showFileNote(s instanceof wu?s.said(this.messages.formatVersionError):this.messages.fileInvalid,"error");return}this.fileApplied=e,this.showFileNote(void 0),JSON.stringify(i)!==JSON.stringify(t.json)&&(t.replaceJson(i),this.current&&!t.tracks.includes(this.current)&&(this.current=void 0),this.currentInterview&&!t.interviews.includes(this.currentInterview)&&(this.currentInterview=void 0),this.refreshRow(),this.scheduleDirtyCheck())}leaveFile(){const e=this.session;if(e)if(this.current===void 0&&this.currentInterview===void 0){const t=e.tracks.find(i=>i.kind==="observer")??e.tracks[0];t&&this.showTrack(t)}else this.currentInterview&&(this.interviewElement.event=this.currentInterview)}guarded(e){if(!this.dirty){e();return}this.pendingLoad=e,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion)}async importFromFile(e){try{const t=JSON.parse(await e.text());this.guarded(()=>void this.importCase(t,new URL("case.json",location.href).href,!1))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importFromUrl(e){try{const t=new URL(e,location.href).href,i=await na.json(t);this.guarded(()=>void this.importCase(i,t,!0))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importCase(e,t,i){if(!Hi.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t,i)}catch(s){this.showFileNote(s instanceof wu?s.said(this.messages.formatVersionError):this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t,i){Hi.check(e);const s=new Ku(e,t);if(this.sourceUrl=i?t:void 0,s.tracks.length===0)throw new Error("A case with no recording has nothing to edit");this.session=s,this.current=void 0;const n=this.getAttribute("track"),r=n?new URL(n,t).href:void 0,a=s.tracks.find(o=>o.url===r)??s.tracks.find(o=>o.kind==="observer")??s.tracks[0];this.listShown=r===void 0,await this.showTrack(a)}closeCase(){this.session&&(this.session=void 0,this.current=void 0,this.currentInterview=void 0,this.editor.reading=!1,this.editor.accountShapeIds=void 0,this.refreshRow())}commit(){this.session&&this.current&&this.editor.edited&&this.session.keep(this.current,this.editor.sightingData)}async loadTrack(e){e.recording||(e.recording=Ui.toCurrent(await na.recording(e.url)),e.loaded=JSON.stringify(e.recording))}async showTrack(e){const t=this.session;if(t){this.commit(),this.currentInterview=void 0,this.editor.passages=void 0;try{const i=!e.recording;await this.loadTrack(e);const s=t.accountOf(e);s&&await this.loadTrack(s),this.current=e,this.editor.documentUrl=e.base?e.base.url:e.url,this.editor.reading=e.kind==="reading",this.editor.accountShapeIds=e.kind==="reading"&&s?.recording?Th.shapesOf(s.recording):void 0;const n=e.kind==="observer"?t.readingsOf(e):[];for(const r of n)await this.loadTrack(r).catch(()=>{});this.editor.readings=n.filter(r=>r.recording?.interpretation?.bodies.length||r.recording?.interpretation?.flares?.length||r.recording?.interpretation?.lanterns?.length).map(r=>({id:r.event.id??t.proposedId(r),label:this.labelOf(r,t.tracks.indexOf(r)),interpretation:r.recording.interpretation})),this.editor.sightingData=structuredClone(e.recording),i&&t.keep(e,this.editor.sightingData,!0),s&&s.loaded===void 0&&t.keep(s,s.recording,!0)}catch{this.showError(this.messages.loadFailed)}this.refreshRow(),this.showPassages(e)}}passagesToken=0;async transcriptOf(e){const t=this.session;if(t)try{const{InterviewFile:i}=await oe(async()=>{const{InterviewFile:n}=await import("./interviewJson-DXD8FSBX.js");return{InterviewFile:n}},[],import.meta.url),s=t.transcriptText(e);if(s!==void 0)return i.read(JSON.parse(s));if(e.url)return i.read(await na.json(new URL(e.url,t.url??location.href).href))}catch{}}async showPassages(e){const t=this.session,i=++this.passagesToken;if(this.editor.passages=void 0,!t||e.kind!=="observer"||t.interviews.length===0)return;const{InterviewFile:s}=await oe(async()=>{const{InterviewFile:o}=await import("./interviewJson-DXD8FSBX.js");return{InterviewFile:o}},[],import.meta.url);if(i!==this.passagesToken)return;const n=e.event.id??t.proposedId(e),r=[];for(const o of t.interviews){const l=await this.transcriptOf(o);if(!l||!Array.isArray(l.segments))continue;const h={...l,interviewOf:l.interviewOf??o.interviewOf};for(const d of s.passagesAbout(h,n))r.push({interview:o,json:l,passage:d})}if(i!==this.passagesToken||this.current!==e||r.length===0)return;const a=this.items(t);this.editor.passages=r.sort((o,l)=>o.passage.at-l.passage.at).map(({interview:o,json:l,passage:h})=>{const d=`${this.messages.passagesHeading} ${this.optionLabel({interview:o},a.findIndex(p=>p.interview===o))}`,u=h.text===void 0?"":h.range?h.text.slice(h.range[0],h.range[1]):h.text;return{at:h.at,clock:s.clock(h.at,!0),said:u===""?d:`${s.speakerName(l,h.speaker)} : « ${u.length>120?`${u.slice(0,117)}…`:u} »`,where:d,open:()=>void this.showInterview(o).then(()=>this.interviewElement.revealSegment(h.index))}})}async followToObservation(e){const t=this.session;if(!t)return;const i=t.tracks.find(n=>n.kind==="observer"&&(n.event.id??t.proposedId(n))===e.sighting)??t.tracks.find(n=>n.kind==="observer");if(!i)return;const s=this.currentInterview;this.listShown=!1,await this.showTrack(i),this.editor.openSection("group-temporal"),this.editor.seekTo(e.at),this.showCited(s,i,e),this.editor.showRender()}static shapesOf(e){const t=new Set;for(const i of e.timeline?.keyframes??[])for(const s of i.shapes??[])t.add(s.sourceId);return[...t]}items(e){return[...e.tracks.map(t=>({track:t})),...e.interviews.map(t=>({interview:t}))]}optionLabel(e,t){const i=this.session;if(e.interview){const r=i.intervieweesOf(e.interview),a=r.length>0?r.map(o=>this.labelOf(o,i.tracks.indexOf(o))).join(", "):this.said.read(e.interview.title);return a?`${this.messages.interviewOf} ${a}`:this.messages.untitledInterview.replace("{n}",String(i.interviews.indexOf(e.interview)+1))}const s=e.track,n=this.labelOf(s,t);return s.kind==="observer"?`${this.messages.accountOf} ${n}`:n}async showInterview(e){const t=this.session;if(t&&(this.commit(),this.current=void 0,this.passagesToken++,this.editor.passages=void 0,this.currentInterview=e,this.refreshRow(),await this.ensureInterview(),this.currentInterview===e)){for(const i of t.intervieweesOf(e))await this.loadTrack(i).catch(()=>{});this.currentInterview===e&&(this.interviewElement.witnesses=t.tracks.filter(i=>i.kind==="observer").map(i=>({id:i.event.id??t.proposedId(i),label:this.labelOf(i,t.tracks.indexOf(i)),moments:this.momentsOf(i)})),this.interviewElement.documentUrl=t.url,this.interviewElement.transcriptText=t.transcriptText(e),this.interviewElement.event=e)}}ensureInterview(){return this.interviewReady??=oe(async()=>{const{register:e}=await import("./InterviewEditorElement-Cpu0vwrk.js");return{register:e}},__vite__mapDeps([27,28,29,30]),import.meta.url).then(({register:e})=>{e(),customElements.upgrade(this.shadow)},e=>{throw this.interviewReady=void 0,e}),this.interviewReady}interviewChanged(e){const{field:t}=e,i=this.session,s=this.currentInterview;if(!(!i||!s)){t==="transcript"&&e.text!==void 0&&i.keepTranscript(s,e.text);for(const n of[s.interviewOf].flat()){const r=i.tracks.find(a=>a.kind==="observer"&&(a.event.id??i.proposedId(a))===n);r&&i.ensureId(r)}i.touch(),this.refreshRow(),this.scheduleDirtyCheck()}}eventsInTime(e){const t=this.items(e),i=s=>String((s.track?.event??s.interview)?.time??"");return t.map((s,n)=>({item:s,index:n})).sort((s,n)=>i(s.item).localeCompare(i(n.item)))}momentsOf(e){return(e.recording?.milestones??[]).map(t=>{const i=this.said.read(t.note);return{at:t.t/1e3,label:this.said.read(t.label)??"",...i?{note:i}:{}}})}citedFrom;showCited(e,t,i){const s=this.byId("cited");if(this.citedFrom=e,!e||!this.session){s.hidden=!0;return}const n=this.momentsOf(t).find(a=>Math.abs(a.at-i.at)<.05),r=(i.quote??"").length>120?`${i.quote.slice(0,117)}…`:i.quote??"";this.byId("cited-text").textContent=this.messages.citedMoment.replace("{k}",n?.label??`${Math.round(i.at)} s`).replace("{title}",this.optionLabel({interview:e},0)).replace("{quote}",r),s.hidden=!1}kindOf(e){return e.interview?"interview":e.track.kind==="reading"?"reading":"observation"}kindLabel(e){return{observation:this.messages.kindObservation,interview:this.messages.kindInterview,reading:this.messages.kindReading}[e]}refreshOverview(){const e=this.session,t=this.byId("case-overview"),i=this.byId("event-crumbs");if(t.hidden=!e||!this.listShown,i.hidden=!e||this.listShown,this.byId("event-item").hidden=e!==void 0&&this.listShown,this.byId("events-count").textContent=e?String(this.items(e).length):"",this.byId("case-heading").textContent=e&&String(e.json.title??"")||this.messages.caseHeading,!e)return;const s=this.eventsInTime(e);this.renderEvents(e,s);const n=s.findIndex(({item:a})=>a.interview?a.interview===this.currentInterview:a.track===this.current),r=s[n];if(r){const a=this.kindOf(r.item),o=this.byId("crumb-kind");o.textContent=this.kindLabel(a),o.dataset.kind=a,this.byId("crumb-title").textContent=this.optionLabel(r.item,r.index)}this.byId("previous-event").disabled=n<=0,this.byId("next-event").disabled=n<0||n>=s.length-1}renderEvents(e,t){const i=this.messages;this.byId("event-list").replaceChildren(...t.map(({item:n,index:r})=>{const a=this.kindOf(n),o=n.track?.event??n.interview,l=document.createElement("li");l.className="event-card",l.dataset.kind=a;const h=document.createElement("span");h.className="kind-pill",h.dataset.kind=a,h.textContent=this.kindLabel(a);const d=document.createElement("div");d.className="event-main";const u=document.createElement("button");u.type="button",u.className="event-open",u.textContent=this.optionLabel(n,r),u.title=i.openEvent,u.addEventListener("click",()=>this.openEvent(r));const p=document.createElement("span");p.className="event-meta",p.textContent=[o.time?String(o.time).replace("T"," "):"",o.id??""].filter(Boolean).join(" · "),d.append(u,p);const f=document.createElement("span");f.className="event-links";const m=[];if(n.track?.kind==="observer"){const b=e.interviews.filter(y=>e.intervieweesOf(y).includes(n.track)).map(y=>this.optionLabel({interview:y},0));b.length>0&&m.push(`${i.passagesHeading} : ${b.join(", ")}`);const w=e.readingsOf(n.track).length;w>0&&m.push(i.readingsCount.replace("{n}",String(w)))}else if(n.track){const b=e.accountOf(n.track);b&&m.push(`${i.interpretationOf} : ${this.optionLabel({track:b},e.tracks.indexOf(b))}`)}f.textContent=m.join(" · ");const v=document.createElement("button");v.type="button",v.className="icon-btn event-delete",v.innerHTML=Ee.TRASH,v.title=i.deleteRecording,v.setAttribute("aria-label",i.deleteRecording),v.addEventListener("click",()=>void this.deleteFromList(r));const g=document.createElement("div");return g.className="event-body",g.append(h,d,f),l.append(g,v),l}))}openEvent(e){const t=this.byId("track");t.value=String(e),t.dispatchEvent(new Event("change")),requestAnimationFrame(()=>this.bringEditorIntoView())}bringEditorIntoView(){const e=this.editor;if(!e.checkVisibility?.())return;const t=e.getBoundingClientRect();Math.abs(t.top)>1&&e.scrollIntoView?.({block:"start",behavior:"smooth"})}async deleteFromList(e){const t=this.session,i=t?this.items(t)[e]:void 0;i&&(this.byId("track").value=String(e),i.interview?await this.showInterview(i.interview):await this.showTrack(i.track),this.askDelete())}stepEvent(e){const t=this.session;if(!t)return;const i=this.eventsInTime(t),s=i.findIndex(({item:r})=>r.interview?r.interview===this.currentInterview:r.track===this.current),n=i[s+e];n&&this.openEvent(n.index)}refreshCaseState(){this.byId("save-case").disabled=!(this.session?.dirty??!1);const e=this.byId("share-case");e.disabled=this.sourceUrl===void 0,e.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":""}sourceUrl;shareDialog;shareMessages;get sharedTrack(){return this.currentInterview?void 0:this.current?.url}shareSubject={module:"rr0-sighting-editor",link:()=>{const e=this.sharedTrack;return`${ed.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}${e?`&track=${encodeURIComponent(e)}`:""}`},element:()=>{const e=this.sharedTrack;return`<rr0-case-editor src="${this.sourceUrl??""}"${e?` track="${e}"`:""}></rr0-case-editor>`}};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.session?.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}labelOf(e,t){const i=this.said.read(e.event.title)??this.said.read(e.recording?.interpretation?.title);if(i)return i;if(e.kind==="observer")return this.said.read(e.recording?.observer?.title)??e.event.url??"";const s=this.session.tracks.filter(n=>n.kind==="reading").indexOf(e)+1;return this.messages.untitledReading.replace("{n}",String(s||t+1))}makeCase(){if(this.session)return;const e=this.editor.sightingData,t=e.time,i=typeof t=="object"?t.value:t,s=i?Th.rr0TimeOf(i):void 0,n=this.said.read(e.observer?.title),r=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=Ku.around(e,s,n,r,location.href),this.listShown=!1,this.current=this.session.tracks[0],this.session.keep(this.current,e),this.dateModeFor=void 0,this.refreshRow()}writeCaseField(e,t){const i=this.session?.json;i&&(t.trim()===""?delete i[e]:i[e]=t,this.session?.touch(),this.scheduleDirtyCheck())}static rr0TimeOf(e){return e.replace(/^(\d{4}-\d\d-\d\d)T/,"$1 ")}static edtfOf(e){return e.replace(/^(\d{4}-\d\d-\d\d) (?=\d)/,"$1T")}showCaseTime(e){const t=String(e.json.time??""),i=t===""?void 0:Jd(Th.edtfOf(t));if(this.caseDate.time=i,t!==""&&!i){const s=this.input("case-time");s.value=t}this.dateModeFor!==e&&(this.caseDate.setPrecise(!(t!==""&&!i)&&Ks.opensPrecise(i)),this.dateModeFor=e)}refreshRow(){const e=this.session;if(this.applySections(),this.byId("case-panel").hidden=e===void 0,this.refreshOverview(),this.byId("make-case-row").hidden=e!==void 0,this.byId("case").classList.toggle("in-case",e!==void 0),this.byId("event-item").classList.toggle("in-case",e!==void 0),this.holdEditor(e!==void 0),!e){this.refreshDirty();return}const t=this.shadow.activeElement;for(const[r,a]of[["case-id","id"],["case-title","title"]]){const o=this.input(r);o!==t&&(o.value=String(e.json[a]??""))}t?.closest?.("rr0-date-input")||this.showCaseTime(e);const i=this.byId("track"),s=this.items(e);i.replaceChildren(...s.map((r,a)=>new Option(this.optionLabel(r,a),String(a))));const n=this.currentInterview?s.findIndex(r=>r.interview===this.currentInterview):this.current?s.findIndex(r=>r.track===this.current):0;i.value=String(Math.max(0,n)),this.byId("delete").disabled=this.currentInterview===void 0&&e.tracks.length<=1,this.refreshRecordingId(e),this.refreshDirty()}holdEditor(e){this.editor.embedded=e,e&&this.byId("history-slot").append(this.editor.historyControls),this.shadow.querySelector(".event-id-row").hidden=!e}refreshRecordingId(e){const t=this.current,i=t!==void 0&&t.kind==="observer";if(this.byId("row-recording-id").hidden=!i,i){const o=this.input("recording-id");this.shadow.activeElement!==o&&(o.value=t.event.id??""),o.placeholder=e.proposedId(t)}const{duplicateIds:s,unresolved:n}=e.problems(),r=[...s.map(o=>this.messages.idDuplicated.replace("{id}",o)),...n.map(({reference:o})=>this.messages.readingUnresolved.replace("{id}",o))],a=this.byId("case-problems");a.hidden=r.length===0,a.textContent=r.join(" ")}showRecordingIdError(e){const t=this.byId("recording-id-error");t.textContent=e??"",t.hidden=e===void 0}writeRecordingId(){const e=this.session,t=this.current;if(!e||!t)return;const i=e.setId(t,this.input("recording-id").value.trim());this.showRecordingIdError(i==="ok"?void 0:{empty:this.messages.idNeeded,invalid:this.messages.idInvalid,taken:this.messages.idTaken}[i]),this.scheduleDirtyCheck()}get dialog(){return this.byId("dialog")}openDialog(e,t,i,s){this.dialogMode=e,this.byId("dialog-title").textContent=t;const n=this.byId("dialog-message");n.textContent=i??"",n.hidden=i===void 0,this.showError(void 0),this.byId("fields-add").hidden=e!=="add",this.byId("fields-export").hidden=e!=="export",this.byId("ok").hidden=!1,this.byId("ok").textContent=s??(e==="discard"?this.messages.discardOk:this.messages.ok),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open","")}closeDialog(){this.pendingLoad=void 0,typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}showError(e){const t=this.byId("dialog-error");t.textContent=e??"",t.hidden=e===void 0}input(e){return this.byId(e)}inputFile(e){return this.byId(e)}today(){return new Date().toISOString().slice(0,10)}askAdd(){const e=this.session;if(!e)return;this.openDialog("add",this.messages.addTitle);const t=this.byId("of");t.replaceChildren(new Option(this.messages.interpretationOfNone,""),...e.tracks.filter(s=>s.kind==="observer").map(s=>new Option(this.labelOf(s,e.tracks.indexOf(s)),String(e.tracks.indexOf(s))))),t.value="",this.byId("kind").value="observation";const i=e.tracks.filter(s=>s.kind==="observer");this.byId("witness").replaceChildren(...i.map(s=>new Option(this.labelOf(s,e.tracks.indexOf(s)),String(e.tracks.indexOf(s))))),this.byId("medium").replaceChildren(),this.byId("source").value="blank";for(const s of["observer","title","author"])this.input(s).value="";this.inputFile("add-source").clear(),this.input("date").value="",this.syncSourceFields()}async fillMedia(){const{InterviewMedia:e}=await oe(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CvAxC62V.js");return{InterviewMedia:i}},[],import.meta.url),t=this.byId("medium");t.options.length>0||t.replaceChildren(...e.ALL.map(i=>new Option(e.label(i,this.language),i)))}syncSourceFields(){const e=this.byId("kind").value==="interview",t=this.byId("source").value,i=!e&&this.byId("of").value!=="";this.byId("row-source").hidden=e,this.byId("row-of").hidden=e,this.byId("row-witness").hidden=!e,this.byId("row-medium").hidden=!e,e&&this.fillMedia(),this.byId("row-file").hidden=e||t!=="file",this.byId("row-observer").hidden=e||i,this.byId("row-title").hidden=!(e||i),this.byId("row-author").hidden=!(e||i),this.byId("label-title").textContent=e?this.messages.plainTitleField:this.messages.titleField,this.byId("label-author").textContent=e?this.messages.interviewerField:this.messages.authorField}askExport(){this.session&&(this.openDialog("export",this.messages.exportTitle),this.input("export-recordings").checked=!0)}askDelete(){const e=this.session;if(e&&this.currentInterview){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteInterviewQuestion);return}const t=this.current;if(!(!e||!t)){if(t.kind==="observer"){const i=e.readingsOf(t).length;if(i>0){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteRefused.replace("{n}",String(i))),this.byId("ok").hidden=!0;return}}this.openDialog("delete",this.messages.deleteRecording,t.kind==="reading"?this.messages.deleteReadingQuestion:this.messages.deleteObservationQuestion)}}async submitDialog(){switch(this.dialogMode){case"delete":this.closeDialog(),this.deleteCurrent();return;case"discard":{const e=this.pendingLoad;this.closeDialog(),e?.();return}case"export":await this.exportCase(this.input("export-recordings").checked)?this.closeDialog():this.showError(this.messages.loadFailed);return;case"add":await this.addRecording()&&this.closeDialog()}}async addRecording(){const e=this.session;if(!e)return!1;if(this.commit(),this.byId("kind").value==="interview"){const u=e.tracks[Number(this.byId("witness").value)],p=this.input("title").value.trim(),f=this.input("author").value.trim(),m=e.addInterview(u,this.input("date").value||this.today(),p!==""?p:void 0,f!==""?f.split(",").map(v=>({people:v.trim()})).filter(v=>v.people!==""):void 0,this.byId("medium").value);return await this.showInterview(m),!0}const t=this.byId("of").value,i=t===""?void 0:e.tracks[Number(t)],s=this.byId("source").value;if(i&&s==="blank"){if(i.kind!=="observer"||!i.recording)return!1;const u=this.input("title").value.trim(),p=this.input("author").value.trim(),f=e.addReading(i,this.input("date").value||this.today(),u!==""?u:void 0,p!==""?[{title:p}]:void 0);return this.showTrack(f),!0}const n=this.input("observer").value.trim(),r=this.input("date").value.trim();let a;try{if(s==="blank"){const u=(n||"observation").replace(/[^A-Za-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation";a={version:3,id:`${r?`${r}-`:""}${u}`,...n?{observer:{title:n}}:{},...r?{time:r}:{},timeline:{keyframes:[],order:[],groups:[]}}}else{const u=await this.readFile();if(Hi.isCase(u))return this.showError(this.messages.isACase),!1;a=u,n&&!a.observer?.title&&(a={...a,observer:{...a.observer,title:n}})}}catch{return this.showError(this.messages.loadFailed),!1}const o=(i?this.input("title").value:n).trim(),l=o!==""?o:this.said.read(a.observer?.title),h=this.input("author").value.trim(),d=e.addObservation(a,r!==""?r:void 0,l,i?{account:i,by:h!==""?[{title:h}]:void 0}:void 0);return this.showTrack(d),!0}async readFile(){const e=this.inputFile("add-source").value;if(!e)throw new Error("No file");if(e.url)return na.recording(new URL(e.url,location.href).href);const t=e.file,i=await new Promise((s,n)=>{const r=new FileReader;r.onload=()=>s(r.result),r.onerror=()=>n(r.error),r.readAsText(t)});return JSON.parse(i)}deleteCurrent(){const e=this.session,t=this.currentInterview;if(e&&t){if(!e.deleteInterview(t))return;this.currentInterview=void 0;const r=e.tracks.find(a=>a.kind==="observer")??e.tracks[0];r&&this.showTrack(r);return}const i=this.current;if(!e||!i)return;const s=i.kind==="reading"?e.accountOf(i)??e.tracks.find(r=>r.kind==="observer"):e.tracks.find(r=>r!==i);(i.kind==="reading"?e.deleteReading(i):e.deleteObservation(i).deleted)&&(this.current=void 0,s&&this.showTrack(s))}async exportCase(e=!0){const t=this.session;if(!t)return!0;if(this.commit(),e)try{for(const a of t.tracks)await this.loadTrack(a)}catch{return!1}const i=t.files(e,!0);if(t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),i.length===1)return this.download(new Blob([i[0].content],{type:"application/json"}),i[0].path),!0;const{zipSync:s,strToU8:n}=await oe(async()=>{const{zipSync:a,strToU8:o}=await import("./browser-_Ncw3Jhn.js");return{zipSync:a,strToU8:o}},[],import.meta.url),r={};for(const a of i)r[a.path]=n(a.content);return this.download(new Blob([s(r)],{type:"application/zip"}),`${t.json.id??"case"}.zip`),!0}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}}function x9(){sT(),customElements.get(aE)||customElements.define(aE,Th)}x9();export{Wv as $,Zf as A,i2 as B,fs as C,S9 as D,Dh as E,il as F,xa as G,Sr as H,iI as I,A9 as J,Ze as K,Oe as L,Xt as M,Us as N,ir as O,tt as P,Tn as Q,De as R,rn as S,gt as T,Wu as U,I as V,Vn as W,Wr as X,lh as Y,lc as Z,oe as _,na as a,_9 as a$,tn as a0,Pn as a1,Mr as a2,j8 as a3,JN as a4,h1 as a5,cP as a6,Kt as a7,$g as a8,ue as a9,V9 as aA,Am as aB,N9 as aC,Pt as aD,Aa as aE,RR as aF,Se as aG,Ot as aH,W9 as aI,k9 as aJ,r_ as aK,Nb as aL,sr as aM,Hf as aN,Dl as aO,Rd as aP,$n as aQ,qs as aR,zs as aS,z9 as aT,xl as aU,on as aV,Ys as aW,Tt as aX,is as aY,As as aZ,_n as a_,we as aa,ht as ab,el as ac,Ss as ad,aa as ae,Er as af,YR as ag,_m as ah,nn as ai,Yv as aj,sn as ak,zi as al,bu as am,$e as an,e9 as ao,Ht as ap,LR as aq,ae as ar,ut as as,se as at,ru as au,xt as av,Mt as aw,wt as ax,Br as ay,H9 as az,Ee as b,R9 as b0,D9 as b1,vp as b2,B9 as b3,F9 as b4,Mm as b5,bA as b6,L9 as b7,FM as b8,U9 as b9,e1 as bA,Wt as bB,El as bC,gp as bD,G9 as ba,J2 as bb,xr as bc,Dp as bd,q0 as be,V_ as bf,di as bg,Al as bh,sb as bi,ms as bj,$a as bk,qD as bl,xi as bm,C9 as bn,O9 as bo,tA as bp,P9 as bq,Ar as br,eA as bs,sx as bt,VD as bu,$A as bv,bm as bw,Ob as bx,gA as by,Qy as bz,vo as c,Hn as d,tI as e,ME as f,Xr as g,Yo as h,Gt as i,ke as j,Wn as k,T9 as l,Zo as m,qi as n,Va as o,ft as p,bt as q,QA as r,$u as s,I9 as t,wn as u,ea as v,Ml as w,Nt as x,Cf as y,E9 as z};
|