@rr0/ufoathome 0.194.0 → 0.195.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/{CaseReportExport-B9iaGKNP.js → CaseReportExport-BeKawC8S.js} +1 -1
- package/dist-embed-sighting/rr0-sighting.mjs +8 -8
- package/dist-embed-sighting-editor/{CaseElement-DzwFIDZZ.js → CaseElement-CVi_yfyW.js} +1 -1
- package/dist-embed-sighting-editor/{CaseReportExport-D0GXupCT.js → CaseReportExport-DisXbZ3b.js} +1 -1
- package/dist-embed-sighting-editor/{SightingElement-BfxNhmfn.js → SightingElement-Bdkf99VT.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +17 -16
- package/dist-embed-ufoathome/{AdsbLolArchiveProvider-DXRO-h2K.js → AdsbLolArchiveProvider-veDw9Mxo.js} +1 -1
- package/dist-embed-ufoathome/{BallesterGuaspAssessor-ZSDHMhXN.js → BallesterGuaspAssessor-BVygSN0R.js} +1 -1
- package/dist-embed-ufoathome/{BeamEditor-BvF4J204.js → BeamEditor-eDeeNBE9.js} +1 -1
- package/dist-embed-ufoathome/{BeamSystem-Yg5JRiCT.js → BeamSystem-B5u4ithz.js} +1 -1
- package/dist-embed-ufoathome/{BodyEditor-CRJFVGzZ.js → BodyEditor-23Dua2K5.js} +1 -1
- package/dist-embed-ufoathome/{CaseEditorElement-MwO-zwnP.js → CaseEditorElement-DYMt7oB4.js} +13 -12
- package/dist-embed-ufoathome/{CaseElement-Ch0QzF7-.js → CaseElement-C6KVIESP.js} +3 -3
- package/dist-embed-ufoathome/{CaseReportExport-D9YyGZHP.js → CaseReportExport-Cgs2Y0v3.js} +3 -3
- package/dist-embed-ufoathome/{CaseTimeline-CnP5rqaK.js → CaseTimeline-BwCuVg5N.js} +3 -3
- package/dist-embed-ufoathome/{ContrailSystem-O_yvjart.js → ContrailSystem-CtQPQFyc.js} +1 -1
- package/dist-embed-ufoathome/{ControlPasses-BaglOE-7.js → ControlPasses-B_uf1Wmh.js} +1 -1
- package/dist-embed-ufoathome/{CoverageAssessor-CBh0sDI1.js → CoverageAssessor-JQCFe16i.js} +1 -1
- package/dist-embed-ufoathome/{Flightradar24Provider-C8Uj-qTs.js → Flightradar24Provider-BR8_7wmx.js} +1 -1
- package/dist-embed-ufoathome/{GLTFLoader-B4SVqjkZ.js → GLTFLoader-DrBMau2Y.js} +1 -1
- package/dist-embed-ufoathome/{GeoJsonExport-C-daFhc2.js → GeoJsonExport-wUgEVyel.js} +1 -1
- package/dist-embed-ufoathome/{GeographicFigures-N4WyX3J_.js → GeographicFigures-CpbFopao.js} +1 -1
- package/dist-embed-ufoathome/{HeadlightSystem-7mtgTwud.js → HeadlightSystem-YXD1Zdpn.js} +1 -1
- package/dist-embed-ufoathome/{HynekAssessor-DdoHR-Qt.js → HynekAssessor-BV2nWUx8.js} +1 -1
- package/dist-embed-ufoathome/{InterviewEditorElement-BSXLlt4e.js → InterviewEditorElement-DiT6FZnj.js} +1 -1
- package/dist-embed-ufoathome/{InterviewElement-Dwk9iHNv.js → InterviewElement-DFcCnZtF.js} +1 -1
- package/dist-embed-ufoathome/{KmlExport-CX-tTjIv.js → KmlExport-wWr2S8H-.js} +1 -1
- package/dist-embed-ufoathome/{LaserBeam-DUL1O57g.js → LaserBeam-CejB0H9v.js} +1 -1
- package/dist-embed-ufoathome/{LaunchEditor-X_zWEOTY.js → LaunchEditor-ConcMLIe.js} +1 -1
- package/dist-embed-ufoathome/{LaunchPlume-CcfhClxb.js → LaunchPlume-BQEYjeSf.js} +1 -1
- package/dist-embed-ufoathome/{LaunchSimulation-C9gbGzGM.js → LaunchSimulation-BIiU6D8P.js} +1 -1
- package/dist-embed-ufoathome/{ModelSource-BtuW2Ztg.js → ModelSource-B93j0IA6.js} +1 -1
- package/dist-embed-ufoathome/{ModelThumbnails-CacTTCW4.js → ModelThumbnails-3U8M50_n.js} +1 -1
- package/dist-embed-ufoathome/{ModelViewer-BlFPQJAr.js → ModelViewer-Cnxj0Oi9.js} +1 -1
- package/dist-embed-ufoathome/{ModuleConformance-qYpBoQH9.js → ModuleConformance-BlrRirPF.js} +2 -2
- package/dist-embed-ufoathome/{ModuleSession-D4LhYKvL.js → ModuleSession-Cdilmebx.js} +3 -3
- package/dist-embed-ufoathome/{ModuleThree-DLikU-uy.js → ModuleThree-Dpv5uvYp.js} +1 -1
- package/dist-embed-ufoathome/{ModulesPanelElement-GY7cTQ5t.js → ModulesPanelElement-CwgqBVUI.js} +3 -3
- package/dist-embed-ufoathome/{NearestApproach-4ntSx6IQ.js → NearestApproach-CQ2w9ctm.js} +1 -1
- package/dist-embed-ufoathome/{PictureRegistration-BLs4DkTI.js → PictureRegistration-DOSDjiOf.js} +1 -1
- package/dist-embed-ufoathome/{PoherAssessor-6t5qvmJy.js → PoherAssessor-C8g5YvJi.js} +1 -1
- package/dist-embed-ufoathome/{RailwaySystem-Dm-PbG_D.js → RailwaySystem-D8B965iv.js} +1 -1
- package/dist-embed-ufoathome/{ReentryEditor-C7A3Kh3_.js → ReentryEditor-CEbb0oLd.js} +1 -1
- package/dist-embed-ufoathome/{ReentrySimulation-BlgfVSxb.js → ReentrySimulation-D_JX7wWS.js} +1 -1
- package/dist-embed-ufoathome/{ReferenceSystem-Bv62TprV.js → ReferenceSystem-xm8mzWiT.js} +1 -1
- package/dist-embed-ufoathome/{ShareDialogElement-DLr5u_tk.js → ShareDialogElement-BBMLOqSW.js} +11 -11
- package/dist-embed-ufoathome/{SightingElement-DuNE_Yt0.js → SightingElement-e9ZcWa58.js} +2 -2
- package/dist-embed-ufoathome/{TraceSystem-Cl5kzaIr.js → TraceSystem-BL6qfrHF.js} +1 -1
- package/dist-embed-ufoathome/{VideoButton-DXPI7_Vt.js → VideoButton-DA48Qz2E.js} +1 -1
- package/dist-embed-ufoathome/{WaterSystem-CTGGh-Y-.js → WaterSystem-BLy0L9qC.js} +1 -1
- package/dist-embed-ufoathome/rr0-ufoathome.mjs +2 -2
- package/dist-embed-ufoathome/{surroundingsSources-CVKKb8h6.js → surroundingsSources-Dlyt6moH.js} +1 -1
- package/dist-embed-ufoathome/{trafficRuntime-DvKPyJcx.js → trafficRuntime-B_bwWY8d.js} +1 -1
- package/package.json +1 -1
|
@@ -1932,9 +1932,9 @@ button:has(> .icon:only-child) { display: inline-flex; align-items: center; just
|
|
|
1932
1932
|
`}class Do{static DEFAULT_WITHIN_M=200;static DEFAULT_SPEED_KMH=50;static read(t){if(!t||typeof t!="object")return;const e=t,i=r=>typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0,n={};for(const r of["cars","trucks","people","talking","withinM"]){const a=i(e[r]);a!==void 0&&(n[r]=a)}const s=Array.isArray(e.roads)?e.roads.flatMap(r=>{if(!r||typeof r!="object")return[];const a=r,c=i(a.distanceM),l=i(a.vehiclesPerMinute);if(c===void 0||l===void 0)return[];const h={distanceM:c,vehiclesPerMinute:l},u=i(a.trucksPerMinute);u!==void 0&&(h.trucksPerMinute=u);const d=i(a.speedKmh);return d!==void 0&&(h.speedKmh=d),[h]}):[];return s.length>0&&(n.roads=s),Object.keys(n).length>0?n:void 0}static says(t){return t!==void 0&&Object.keys(t).some(e=>e!=="roads"||(t.roads?.length??0)>0)}}class Jr{static KINDS=["beams","launches","reentries"];static statedKinds(t){return Object.keys(t??{}).filter(e=>Array.isArray(t[e])&&t[e].length>0)}static isEmpty(t){return Jr.statedKinds(t).length===0}static written(t){const e=Jr.statedKinds(t);if(e.length===0)return;const i={};for(const n of e)i[n]=t[n];return i}static read(t,e){const i=e,n={};for(const r of Jr.statedKinds(t))n[r]=t[r];for(const r of Jr.KINDS){const a=[...t?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=e;if(i&&Jr.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:c,...l}=i;s=Jr.isReading(l)?l:void 0}return{skyEvents:Jr.written(n),interpretation:s}}static isReading(t){return(t.bodies?.length??0)>0||t.title!==void 0||(t.smoke?.length??0)>0}}function Gu(o){return[...o].sort((t,e)=>t.t-e.t)}function df(o,t){let e;for(const i of Gu(o)){if(i.t>t)break;e=i}return e}const xm=Math.PI/180,ff=180/Math.PI;class fa{constructor(t,e,i){this.kind=t,this.canvasHeightPx=e,this.fovDeg=i;const n=i*xm/2;this.focalPx=t==="equidistant"?e/2/n:e/2/Math.tan(n)}focalPx;static of(t,e,i){return new fa(t.projection,e,i)}degToPx(t){const e=t*xm;return this.kind==="equidistant"?this.focalPx*e:2*this.focalPx*Math.tan(e/2)}pxToDeg(t){return this.kind==="equidistant"?t/this.focalPx*ff:2*Math.atan(t/(2*this.focalPx))*ff}angleDegToRadiusPx(t){const e=t*xm;return this.kind==="equidistant"?this.focalPx*e:this.focalPx*Math.tan(e)}halfWidthAngleDeg(t){return this.radiusPxToAngleDeg(this.canvasHeightPx*t/2)}radiusPxToAngleDeg(t){return this.kind==="equidistant"?t/this.focalPx*ff:Math.atan(t/this.focalPx)*ff}ofBounds(t){return{widthDeg:this.pxToDeg(t.width),heightDeg:this.pxToDeg(t.height)}}toBoundsSize(t){return{width:this.degToPx(t.widthDeg),height:this.degToPx(t.heightDeg)}}widthPx(t){return this.degToPx(fi.angularWidthDeg(t))}}class vn{static fovOf(t,e){return ke(t,e)?.fovDeg??Ji.fieldOfViewDeg(t.instrument)}static toAngular(t){this.eachKeyframe(t,(e,i)=>{const n=i.ofBounds(e.bounds);return e.angular?.widthDeg===n.widthDeg&&e.angular.heightDeg===n.heightDeg?e:{...e,angular:n}})}static toBounds(t){this.eachKeyframe(t,(e,i)=>this.sizedFromAngle(e,i))}static sizedFromAngle(t,e){if(!t.angular)return t;const{width:i,height:n}=e.toBoundsSize(t.angular),s={x:t.bounds.x+(t.bounds.width-i)/2,y:t.bounds.y+(t.bounds.height-n)/2,width:i,height:n};if(t.kind!=="polygon")return{...t,bounds:s};const r=t.bounds.width===0?1:i/t.bounds.width,a=t.bounds.height===0?1:n/t.bounds.height;return{...t,bounds:s,points:t.points.map(c=>({x:c.x*r,y:c.y*a}))}}static toAim(t){this.eachKeyframe(t,(e,i,n)=>{const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);if(s&&Math.abs(s.x-e.bounds.x)<vn.UNMOVED_PX&&Math.abs(s.y-e.bounds.y)<vn.UNMOVED_PX)return e;const r=this.aimFrom(t,i,n,e.bounds);return r?{...e,aim:r}:e})}static UNMOVED_PX=.01;static aimOf(t,e,i){const n=fa.of(t.instrument,fi.CANVAS_HEIGHT_PX,this.fovOf(t,e));return this.aimFrom(t,n,ke(t,e),i)}static aimFrom(t,e,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(t),r=e.radiusPxToAngleDeg(n.x+n.width/2-s.x),a=e.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+a}}static toPosition(t){this.eachKeyframe(t,(e,i,n)=>this.placedByAim(t,e,i,n))}static placedByAim(t,e,i,n){const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);return s?{...e,bounds:{...e.bounds,...s}}:e}static derivable(t){const e=new Set,i=new Map,n=new Map;return t.timeline.allKeyframes.forEach((s,r)=>{const a=ke(t,s.t),c=fa.of(t.instrument,fi.CANVAS_HEIGHT_PX,this.fovOf(t,s.t));for(const{sourceId:l,shape:h}of s.shapes){const u=n.get(l),d=i.get(l);if(n.set(l,h),!u||!d){i.set(l,h);continue}const f=Object.fromEntries(Object.entries(h).filter(([m,M])=>m!=="bounds"&&m!=="points"&&JSON.stringify(M)!==JSON.stringify(u[m]))),p={...d,...f},g=this.placedByAim(t,this.sizedFromAngle(p,c),c,a);vn.near(g,h)?(e.add(`${r}:${l}`),i.set(l,p)):i.set(l,h)}}),(s,r)=>e.has(`${s}:${r}`)}static SAME_PX=1e-6;static near(t,e){const i=(r,a)=>Math.abs(r-a)<=vn.SAME_PX*Math.max(1,Math.abs(a)),n=t.bounds,s=e.bounds;return!i(n.x,s.x)||!i(n.y,s.y)||!i(n.width,s.width)||!i(n.height,s.height)?!1:e.kind!=="polygon"||t.kind!=="polygon"?!0:t.points.length===e.points.length&&t.points.every((r,a)=>i(r.x,e.points[a].x)&&i(r.y,e.points[a].y))}static positionOf(t,e,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(t),a=this.shortestArc(e.azimuthDeg-s.headingDeg),c=e.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,a)-i.width/2,y:r.y-this.offAxisPx(n,c)-i.height/2}}static frameCentre(t){return{x:Ji.frameWidthPx(t.instrument,fi.CANVAS_HEIGHT_PX)/2,y:fi.CANVAS_HEIGHT_PX/2}}static shortestArc(t){return(t%360+540)%360-180}static offAxisPx(t,e){return Math.abs(e)>=vn.OFF_CANVAS_DEG?Math.sign(e)*vn.OFF_CANVAS_PX:t.angleDegToRadiusPx(e)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(t,e,i){const n=Ji.frameWidthPx(e,fi.CANVAS_HEIGHT_PX)/2,s=Ji.frameWidthPx(t.instrument,fi.CANVAS_HEIGHT_PX)/2,r=fi.CANVAS_HEIGHT_PX/2;for(const a of[...t.timeline.allKeyframes]){const c=this.fovOf(t,a.t),l=i?.get(a.t)??c,h=fa.of(e,fi.CANVAS_HEIGHT_PX,l),u=fa.of(t.instrument,fi.CANVAS_HEIGHT_PX,c);t.timeline.addKeyframe(a.t,a.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,g=f.y+f.height/2-r,m=Math.hypot(p,g),M=m===0?1:u.angleDegToRadiusPx(h.radiusPxToAngleDeg(m))/m,v={...f,x:s+p*M-f.width/2,y:r+g*M-f.height/2};return{...d,shape:{...d.shape,bounds:v}}}))}this.toBounds(t)}static eachKeyframe(t,e){const{timeline:i}=t;for(const n of[...i.allKeyframes]){const s=ke(t,n.t),r=this.fovOf(t,n.t),a=fa.of(t.instrument,fi.CANVAS_HEIGHT_PX,r);let c=!1;const l=n.shapes.map(h=>{const u=e(h.shape,a,s);return u===h.shape?h:(c=!0,{...h,shape:u})});c&&i.addKeyframe(n.t,l)}}}class ys{static isRelative(t){return t!==void 0&&typeof t.eastM=="number"&&typeof t.northM=="number"}static isAbsolute(t){return t!==void 0&&typeof t.lat=="number"&&typeof t.lng=="number"}static referenceOf(t,e){return e.references.find(i=>(i.id??void 0)===(t.relativeTo??void 0))}static resolve(t,e){if(ys.isRelative(t)){const i=ys.referenceOf(t,e);return i?{eastM:i.eastM+t.eastM,northM:i.northM+t.northM}:void 0}return ys.isAbsolute(t)&&e.origin?ys.toLocal(t,e.origin):void 0}static restated(t,e,i){if(ys.isRelative(t)){const s=ys.referenceOf(t,i);return s?ys.relative(e.eastM-s.eastM,e.northM-s.northM,t.relativeTo):void 0}if(!i.origin)return t;const n=ys.toGeo(e,i.origin);return{lat:ys.degrees(n.lat),lng:ys.degrees(n.lng)}}static relative(t,e,i){const n={eastM:ys.metres(t),northM:ys.metres(e)};return i!==void 0&&(n.relativeTo=i),n}static toLocal(t,e){const i=ae(t.lat,t.lng,e.lat,e.lng);return{eastM:i.x,northM:-i.z}}static toGeo(t,e){return Bs(t.eastM,-t.northM,e.lat,e.lng)}static metres(t){return Math.round(t*100)/100}static degrees(t){return Math.round(t*1e7)/1e7}}class is{static restatedDecor(t){const e=is.originOf(t);return t.decor.map(i=>{let n=i;if(i.saidPosition){const s=is.restated(i.saidPosition,i,is.frameAt(t,0,e,i.id));JSON.stringify(s)!==JSON.stringify(i.saidPosition)&&(n={...i,saidPosition:s},s||delete n.saidPosition)}if(i.track?.some(s=>s.saidPosition)){const s=i.track.map(r=>{if(!r.saidPosition)return r;const a=is.restated(r.saidPosition,r,is.frameAt(t,r.t,e,i.id));if(JSON.stringify(a)===JSON.stringify(r.saidPosition))return r;const c={...r,saidPosition:a};return a||delete c.saidPosition,c});n={...n,track:s}}return n})}static restatedObserverTrack(t){const e=t.observerTrack.toJSON(),i=is.originOf(t);return!i||!e.keyframes.some(n=>n.pose.saidPosition)?e:{...e,keyframes:e.keyframes.map(n=>{const{pose:s}=n;if(!s.saidPosition||s.lat===void 0||s.lng===void 0)return n;const r=ys.toLocal({lat:s.lat,lng:s.lng},i),a=is.restated(s.saidPosition,r,is.frameAt(t,n.t,i));if(JSON.stringify(a)===JSON.stringify(s.saidPosition))return n;const c={...s,saidPosition:a};return a||delete c.saidPosition,{...n,pose:c}})}}static restatedInterpretation(t){const e=t.interpretation;if(!e?.bodies.some(n=>n.track.some(s=>s.saidPosition)))return e;const i=is.originOf(t);return{...e,bodies:e.bodies.map(n=>n.track.some(s=>s.saidPosition)?{...n,track:n.track.map(s=>{if(!s.saidPosition)return s;const r=s.eastM!==void 0&&s.northM!==void 0?is.restated(s.saidPosition,{eastM:s.eastM,northM:s.northM},is.frameAt(t,s.t,i)):void 0;if(JSON.stringify(r)===JSON.stringify(s.saidPosition))return s;const a={...s,saidPosition:r};return r||delete a.saidPosition,a})}:n)}}static originOf(t){const e=t.observerTrack.getInterpolatedPoseAt(0),i=t.event.place?.[0],n=e?.lat??i?.lat,s=e?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}static frameAt(t,e,i,n){const s=[{label:"",eastM:0,northM:0},...t.decor.filter(r=>r.id!==n).map(r=>{const{eastM:a,northM:c}=Ma(r,e);return{id:r.id,label:r.id,eastM:a,northM:c}})];return{origin:i,references:s}}static restated(t,e,i){return ys.restated(t,{eastM:e.eastM,northM:e.northM},i)}}class li{constructor(t,e,i){this.params=t,this.from=e,this.origin=t.path[0],this.cos0=Math.cos(t.path[0].lat*Math.PI/180),this.points=t.path.map(r=>this.local(r)),this.cumulative=[0];for(let r=1;r<this.points.length;r++){const a=this.points[r-1],c=this.points[r];this.cumulative.push(this.cumulative[r-1]+Math.hypot(c.e-a.e,c.n-a.n))}this.distances=[];let n=0;for(let r=e;r<=i+li.BEYOND_MS;r+=li.STEP_MS)this.distances.push(n),n+=this.speedAt(r)*li.STEP_MS/1e3;this.shift=this.project(this.local(t.through))-this.distanceAt(t.through.t);const s=[];for(let r=e;r<=i;r+=li.SAMPLE_MS)s.push({t:r,place:this.placeAt(r)});this.sampleOrigin=s[0].place,this.sampleCos=Math.cos(this.sampleOrigin.lat*Math.PI/180),this.samples=s.map(({t:r,place:a})=>({t:r,e:(a.lng-this.sampleOrigin.lng)*Math.PI/180*li.R*this.sampleCos,n:(a.lat-this.sampleOrigin.lat)*Math.PI/180*li.R}))}static R=63710088e-1;static STEP_MS=100;static SAMPLE_MS=2e3;static BEYOND_MS=8e4;origin;cos0;points;cumulative;distances;shift;samples;sampleOrigin;sampleCos;get start(){return this.sampleOrigin}stateAt(t){const e=this.samples,i=e.length-2;let n=0;for(;n<i&&e[n+1].t<t;)n++;const s=e[n],r=e[n+1],a=(t-s.t)/(r.t-s.t),c=p=>[n>0?p[n-1]:2*p[n]-p[n+1],p[n],p[n+1],n+2<p.length?p[n+2]:2*p[n+1]-p[n]],l=e.map(p=>p.e),h=e.map(p=>p.n),u=li.catmull(c(l),a),d=li.catmull(c(h),a),f=(Math.atan2(li.slope(c(l),a),li.slope(c(h),a))*180/Math.PI%360+360)%360;return{eastM:u,northM:d,roadDeg:f,lat:this.sampleOrigin.lat+d/li.R*180/Math.PI,lng:this.sampleOrigin.lng+u/(li.R*this.sampleCos)*180/Math.PI}}bearingAt(t,e){const i=this.local(this.placeAt(t)),n=this.local(e);return(Math.atan2(n.e-i.e,n.n-i.n)*180/Math.PI%360+360)%360}get sampleTimes(){return this.samples.map(t=>t.t)}placeAt(t){const e=this.along(this.distanceAt(t)+this.shift);return{lat:this.origin.lat+e.n/li.R*180/Math.PI,lng:this.origin.lng+e.e/(li.R*this.cos0)*180/Math.PI}}distanceAt(t){const e=Math.max(0,Math.min(this.distances.length-1,Math.round((t-this.from)/li.STEP_MS)));return this.distances[e]}speedAt(t){const e=this.params.speedDivisors?li.linear(this.params.speedDivisors.map(({t:i,divisor:n,step:s})=>({t:i,value:n,step:s})),t):1;return li.linear(this.params.speeds.map(({t:i,kmh:n,step:s})=>({t:i,value:n,step:s})),t)/3.6/e}local(t){return{e:(t.lng-this.origin.lng)*Math.PI/180*li.R*this.cos0,n:(t.lat-this.origin.lat)*Math.PI/180*li.R}}along(t){const e=this.points;let i=0;for(;i<e.length-2&&this.cumulative[i+1]<t;)i++;const n=e[i],s=e[i+1],r=(t-this.cumulative[i])/(this.cumulative[i+1]-this.cumulative[i]);return{e:n.e+(s.e-n.e)*r,n:n.n+(s.n-n.n)*r}}project(t){let e=1/0,i=0;for(let n=0;n<this.points.length-1;n++){const s=this.points[n],r=this.points[n+1],a=r.e-s.e,c=r.n-s.n,l=Math.max(0,Math.min(1,((t.e-s.e)*a+(t.n-s.n)*c)/(a*a+c*c))),h=Math.hypot(s.e+a*l-t.e,s.n+c*l-t.n);h<e&&(e=h,i=this.cumulative[n]+l*Math.hypot(a,c))}return i}static linear(t,e){if(e<=t[0].t)return t[0].value;for(let i=0;i<t.length-1;i++){const n=t[i],s=t[i+1];if(s.step&&e<s.t)return n.value;if(e<=s.t)return n.value+(s.value-n.value)*(e-n.t)/(s.t-n.t)}return t[t.length-1].value}static catmull([t,e,i,n],s){return .5*(2*e+(i-t)*s+(2*t-5*e+4*i-n)*s*s+(3*e-t-3*i+n)*s**3)}static slope([t,e,i,n],s){return .5*(i-t+2*(2*t-5*e+4*i-n)*s+3*(3*e-t-3*i+n)*s*s)}}class ti{constructor(t,e,i,n,s,r){this.drive=t,this.eye=e,this.lookAhead=i,this.lean=n,this.watch=s,this.times=t.sampleTimes;const a=i.pitchShare??1;this.aimed=[];for(const c of this.times){const l=t.bearingAt(c,i.target),h=this.aimed[this.aimed.length-1];this.aimed.push(h===void 0?l:h+ti.signed(l-h))}this.pitched=this.times.map(c=>r(c)*a)}static STEP_MS=250;static DENSE_MS=50;static SETTLED_MS=700;static TURN_S=.4;static TURN_S_PER_DEG=.5/150;static ROAD_PITCH_DEG=-1;static SHOULDER={x:-.08,y:0,z:-.07};static TWIST_FROM_DEG=60;aimed;pitched;times;poses(t,e){const i=[];for(let u=t;u<e;u+=ti.STEP_MS)i.push(u);i.push(e);const n=new Map(i.map(u=>{const d=this.sample(u);return[u,ti.signed(d.headingDeg-d.roadDeg)]})),s=u=>n.get(i.reduce((d,f)=>Math.abs(f-u)<Math.abs(d-u)?f:d)),r=this.schedule(s,e),a=this.watch?.t,c=r.map(([u,d],f)=>{if(f===0)return 0;if(u===a&&this.lean)return this.lean.params.turnS;const p=this.sample(u);return ti.turnS(this.target(r[f-1][1],p),this.target(d,p))}),l=new Set(i),h=r.map(([u],d)=>[u,c[d]]);this.lean&&h.push([this.lean.t,this.lean.params.turnS],[this.lean.t+this.lean.params.holdS*1e3,this.lean.params.turnS]);for(const[u,d]of h){const f=Math.round(u+d*1e3+ti.SETTLED_MS)+ti.DENSE_MS;for(let p=Math.round(u);p<f;p+=ti.DENSE_MS)p>=t&&p<=e&&l.add(p)}return[...l].sort((u,d)=>u-d).map(u=>{const d=this.sample(u),[f,p]=this.gaze(r,c,d),g=this.drive.stateAt(u);return{t:u,headingDeg:f,pitchDeg:p,eye:this.eyeAt(u,ti.signed(f-d.roadDeg)),roadDeg:g.roadDeg,lat:g.lat,lng:g.lng}})}schedule(t,e){const i=[],n=this.lookAhead,s=this.watch?.t??e;let r=0;for(;r<s;){if(Math.abs(t(r))<=n.glanceBeyondDeg){(i.length===0||i[i.length-1][1]!=="watch")&&i.push([r,"watch"]),r+=ti.STEP_MS;continue}if(i.push([r,"glance"]),r+=n.glanceS*1e3,r>=s)break;i.push([r,"road"]),r+=n.roadS*1e3}if(!this.watch)return i;const a=this.watch.params;r=s,i.push([r,"mirror"]),r+=a.firstS*1e3;let c=0;for(;r<e;){const l=r<a.glancesUntil&&c%2===0?"glance":"road";i.push([r,l]),r+=(l==="glance"?a.glanceS:a.roadS)*1e3,i.push([r,"mirror"]),r+=a.mirrorS*1e3,c++}return i}sample(t){const e=this.times,i=e.length-2;let n=0;for(;n<i&&e[n+1]<t;)n++;const s=(t-e[n])/(e[n+1]-e[n]),r=a=>[n>0?a[n-1]:2*a[n]-a[n+1],a[n],a[n+1],n+2<a.length?a[n+2]:2*a[n+1]-a[n]];return{t,roadDeg:this.drive.stateAt(t).roadDeg,headingDeg:(li.catmull(r(this.aimed),s)%360+360)%360,pitchDeg:li.catmull(r(this.pitched),s),eye:this.eyeAt(t,0)}}target(t,e){const{roadDeg:i,headingDeg:n,pitchDeg:s,eye:r}=e;if(t==="glance")return[n,s];if(t==="watch"){const u=ti.signed(n-i),d=this.lookAhead.keepDeg,f=u-d*Math.tanh(u/d),p=u?f/u:0;return[ti.normalized(i+f),ti.ROAD_PITCH_DEG+(s-ti.ROAD_PITCH_DEG)*p]}if(t==="road"||!this.watch)return[i,ti.ROAD_PITCH_DEG];const a=this.watch.params.mirror,c={x:a.x-r.x,y:a.y-r.y,z:a.z-r.z},l=Math.atan2(-c.x,-c.z)*180/Math.PI,h=Math.atan2(c.y,Math.hypot(c.x,c.z))*180/Math.PI;return[ti.normalized(i-l),h]}gaze(t,e,i,n){const s=i.t;let r=n??0;if(n===void 0&&s>=t[0][0])for(let m=0;m<t.length;m++)t[m][0]<=s&&(r=m);const[a,c]=this.target(t[r][1],i);if(r===0)return[a,c];const l=e[r]*1e3,h=s-t[r][0];if(h>l+ti.SETTLED_MS)return[a,c];const[u,d]=this.gaze(t,e,i,r-1);if(h<l){const m=h/l,M=-2*m**3+3*m*m+(m**3-m*m)*Sn.ARRIVAL;return[ti.normalized(u+ti.signed(a-u)*M),d+(c-d)*M]}const f=ti.signed(a-u),p=h-l,g=Sn.ARRIVAL/l*p*Math.exp(-p/Math.min(Sn.SETTLE_MS,.4*l));return[ti.normalized(a+f*g),c+(c-d)*g]}leanAt(t){if(!this.lean)return 0;const{holdS:e,turnS:i}=this.lean.params,n=(t-this.lean.t)/1e3;return n<0||n>e+i?0:ti.smooth(Math.min(1,n/i,(e+i-n)/i))}eyeAt(t,e){const i=this.leanAt(t),n=this.lean?.params.offsetM??{x:0,y:0,z:0},s=ti.smooth((Math.abs(e)-ti.TWIST_FROM_DEG)/(180-ti.TWIST_FROM_DEG)),r=ti.SHOULDER;return{x:this.eye.x+n.x*i+r.x*s,y:this.eye.y+n.y*i+r.y*s,z:this.eye.z+n.z*i+r.z*s}}static turnS(t,e){return ti.TURN_S+ti.TURN_S_PER_DEG*Math.hypot(ti.signed(e[0]-t[0]),e[1]-t[1])}static smooth(t){const e=Math.min(1,Math.max(0,t));return e*e*e*(10-15*e+6*e*e)}static signed(t){return((t+540)%360+360)%360-180}static normalized(t){return(t%360+360)%360}}const wm=Math.PI/180;class Lt{constructor(t,e,i){this.body=t,this.ground=e,this.eyeAt=i;const n=Lt.placedInWorld.get(t);if(n){this.keys=n.keys,this.motionKeys=n.motionKeys,this.turnKeys=n.turnKeys,this.lightKeys=n.lightKeys;return}const s=[...t.track].sort((r,a)=>r.t-a.t);this.keys=this.place(s,i),this.motionKeys=new Map,this.turnKeys=new Map,this.lightKeys=new Map;for(const r of s)Lt.collect(this.motionKeys,r.t,r.motions),Lt.collect(this.turnKeys,r.t,r.turns),Lt.collect(this.lightKeys,r.t,r.lights);!t.withObserver&&s.every(r=>r.azimuthDeg===void 0&&r.altitudeDeg===void 0)&&Lt.placedInWorld.set(t,{keys:this.keys,motionKeys:this.motionKeys,turnKeys:this.turnKeys,lightKeys:this.lightKeys})}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,finish:"matt",luminanceCdM2:0,transparency:0,haloScale:1};keys;static placedInWorld=new WeakMap;motionKeys;turnKeys;lightKeys;static collect(t,e,i){for(const[n,s]of Object.entries(i??{})){const r=t.get(n)??[];r.push({t:e,value:s}),t.set(n,r)}}motionsAt(t){return Lt.channelsAt(this.motionKeys,t,0)}lightsAt(t){return this.lightKeys.size>0?Lt.channelsAt(this.lightKeys,t,void 0):void 0}static channelsAt(t,e,i){const n={};for(const[s,r]of t){let a=r.length-1;for(;a>=0&&r[a].t>e;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const c=r[a],l=r[Math.min(a+1,r.length-1)],h=l===c||l.t===c.t?0:Math.min(1,(e-c.t)/(l.t-c.t));n[s]=Lt.lerp(c.value,l.value,h)}return n}static eyeOf(t,e,i){const n=ke(t,0),s=ke(t,e),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ae(s.lat,s.lng,n.lat,n.lng):void 0,c=a?a.x:0,l=a?-a.z:0;return{eastM:c,northM:l,upM:i.heightAt(c,l)+Lt.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(t,e,i,n){const s=Lt.directionOf(e,i),r=l=>t.upM+s.upM*l-n.heightAt(t.eastM+s.eastM*l,t.northM+s.northM*l);let a=0,c=0;for(;c<Lt.MAX_RANGE_M;){if(c=a+Math.max(.5,a*.01),r(c)<=0){for(let l=0;l<30;l++){const h=(a+c)/2;r(h)<=0?c=h:a=h}return c}a=c}}static directionOf(t,e){const i=t*wm,n=e*wm;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(t){const e=this.keys;if(e.length===0||t<e[0].t)return;let i=0,n=e.length-1;for(;i<n;){const g=i+n+1>>1;e[g].t>t?n=g-1:i=g}const s=i,r=e[s];if(!r.present)return;const a=e[Math.min(s+1,e.length-1)],c=a===r||a.t===r.t?0:Math.min(1,(t-r.t)/(a.t-r.t)),l=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(t):void 0,h=l?l.eastM+Lt.lerp(r.carried.eastM,a.carried.eastM,c):Lt.lerp(r.eastM,a.eastM,c),u=l?l.northM+Lt.lerp(r.carried.northM,a.carried.northM,c):Lt.lerp(r.northM,a.northM,c),d={widthM:Lt.lerp(r.sizeM.widthM,a.sizeM.widthM,c),lengthM:Lt.lerp(r.sizeM.lengthM,a.sizeM.lengthM,c),heightM:Lt.lerp(r.sizeM.heightM,a.sizeM.heightM,c)},f={headingDeg:Lt.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,c),pitchDeg:Lt.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,c),rollDeg:Lt.lerp(r.attitude.rollDeg,a.attitude.rollDeg,c)};let p;if(l)p=l.upM+Lt.lerp(r.carried.upM,a.carried.upM,c);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const g=Lt.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,c);p=this.groundUnderFootprint(h,u,d,f.headingDeg)+g+d.heightM/2}else p=Lt.lerp(this.centreUpOf(r),this.centreUpOf(a),c);return{id:this.body.id,model:this.body.model,modelParameters:this.body.modelParameters,flicker:this.body.flicker,explains:this.body.explains??[],...this.body.ensemble?{ensemble:this.body.ensemble}:{},...this.body.shadow===!1?{shadow:!1}:{},...this.body.lightFromBelow?{lightFromBelow:this.body.lightFromBelow}:{},outlineNode:this.body.outlineNode,eastM:h,northM:u,upM:p,sizeM:d,attitude:f,appearance:{color:Lt.lerpColor(r.appearance.color,a.appearance.color,c),albedo:Lt.lerp(r.appearance.albedo,a.appearance.albedo,c),finish:c<1?r.appearance.finish:a.appearance.finish,luminanceCdM2:Lt.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,c),transparency:Lt.lerp(r.appearance.transparency,a.appearance.transparency,c),haloScale:Lt.lerp(r.appearance.haloScale,a.appearance.haloScale,c)},flame:Lt.flameBetween(r.flame,a.flame,c),motions:this.motionsAt(t),...this.turnKeys.size>0?{turns:Lt.channelsAt(this.turnKeys,t,0)}:{},lights:this.lightsAt(t),...this.body.lamps?.length?{lamps:this.body.lamps}:{},throwsFlame:this.body.track.some(g=>g.flame!==void 0&&g.flame.luminanceCdM2>0)}}static flameBetween(t,e,i){if(!t||t.luminanceCdM2<=0)return i>=1&&e&&e.luminanceCdM2>0?e:void 0;const n=t,s=e??t,r={...i<1?n:s,lengthM:Lt.lerp(n.lengthM,s.lengthM,i),widthM:Lt.lerp(n.widthM,s.widthM,i),luminanceCdM2:Lt.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(t){if(!("upM"in t.vertical))return this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.vertical.aboveGroundM+t.sizeM.heightM/2;const e=t.vertical.fromGround;if(!e)return t.vertical.upM-(this.ground.dropAt?.(t.eastM,t.northM)??0);const i=t.vertical.upM+this.ground.heightAt(e.eastM,e.northM);return Math.max(i,this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.sizeM.heightM/2)}groundUnderFootprint(t,e,i,n){const s=n*wm,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let c=this.ground.heightAt(t,e);for(const[l,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const u=l*i.widthM/2,d=h*i.lengthM/2;c=Math.max(c,this.ground.heightAt(t+r.eastM*u+a.eastM*d,e+r.northM*u+a.northM*d))}return c}place(t,e){const i=[];let n;for(const s of t){const r=s.sizeM??n?.sizeM??Lt.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},c={color:s.appearance?.color??n?.appearance.color??Lt.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??Lt.DEFAULT_APPEARANCE.albedo,finish:s.appearance?.finish??n?.appearance.finish??Lt.DEFAULT_APPEARANCE.finish,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??Lt.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??Lt.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??Lt.DEFAULT_APPEARANCE.haloScale},l=this.positionOf(s,r,e)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!l)continue;const h=s.flame??n?.flame,u=s.present??n?.present??!0;if(n={t:s.t,...l,sizeM:r,attitude:a,appearance:c,flame:h,present:u},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const d=Lt.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:d.eastM*s.distanceM,northM:d.northM*s.distanceM,upM:d.upM*s.distanceM}}i.push(n)}return i}verticalOf(t,e){if(t.onGround)return{aboveGroundM:0};if(t.altitudeAboveGroundM!==void 0)return{aboveGroundM:t.altitudeAboveGroundM};if(t.altitudeM!==void 0)return{upM:t.altitudeM+e.heightM/2,fromGround:this.body.altitudeFrom}}positionOf(t,e,i){if(t.eastM!==void 0&&t.northM!==void 0)return{eastM:t.eastM,northM:t.northM,vertical:this.verticalOf(t,e)??{aboveGroundM:0}};if(t.azimuthDeg===void 0||t.altitudeDeg===void 0)return;const n=i(t.t);if(!n)return;const s=t.distanceM??(t.onGround?Lt.lineOfSightMeetsGround(n,t.azimuthDeg,t.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=Lt.directionOf(t.azimuthDeg,t.altitudeDeg),a=n.eastM+r.eastM*s,c=n.northM+r.northM*s;return{eastM:a,northM:c,vertical:this.verticalOf(t,e)??{upM:n.upM+r.upM*s}}}static lerp(t,e,i){return t+(e-t)*i}static lerpColor(t,e,i){const n=Lt.rgbOf(t),s=Lt.rgbOf(e);return!n||!s?i<1?t:e:"#"+n.map((r,a)=>Math.round(Lt.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(!e)return;const i=e[1].length===3?e[1].replace(/./g,"$&$&"):e[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(t,e,i){const n=((e-t)%360+540)%360-180;return((t+n*i)%360+360)%360}}class ks{static ANONYMOUS_OBSERVER="observer";static observerId(t){return t.observer?.id??ks.ANONYMOUS_OBSERVER}static shapeIds(t){const e=new Set(t.timeline.sourceIds);for(const i of t.events??[])if(i.eventType==="appearance")for(const n of i.params?.parts??[])e.add(n.sourceId);return[...e]}static ids(t){const e=new Map,i=(n,s)=>{n!==void 0&&e.set(n,[...e.get(n)??[],s])};i(ks.observerId(t),"observer");for(const n of ks.shapeIds(t))i(n,"shape");for(const n of t.timeline.allGroups)i(n.id,"group");for(const n of t.interpretation?.bodies??[])i(n.id,"body");for(const n of t.decor)i(n.id,"decor");return e}static kindOf(t,e){if(e===void 0)return;const i=ks.ids(t).get(e);return i?.length===1?i[0]:void 0}static partOf(t){const e=t?.indexOf("/")??-1;if(!(t===void 0||e<=0||e===t.length-1))return{element:t.slice(0,e),part:t.slice(e+1)}}static hasPart(t,e,i){if(e==="body")return!0;if(e!=="decor")return!1;const n=t.decor.find(s=>s.id===i.element);return!!(n?.lights?.some(s=>s.id===i.part)||n?.groups?.some(s=>s.id===i.part))}static isObserver(t,e){return e.who===ks.observerId(t)}static isPhenomenon(t,e){return e.who===void 0?!1:t.timeline.groupOf(e.who)!==void 0||ks.shapeIds(t).includes(e.who)}static within(t,e){const i=new Set([e]),n=s=>{for(const r of t.timeline.groupOf(s)?.members??[])i.has(r)||(i.add(r),n(r))};return n(e),i}static renamed(t,e,i){if(e!==i)for(const n of t.events??[])n.who===e&&(n.who=i)}static issues(t){const e=[],i=ks.ids(t);for(const[n,s]of i)s.length>1&&e.push({kind:"duplicate-id",id:n,path:s.join(", ")});return(t.events??[]).forEach((n,s)=>{const r=ks.partOf(n.who);r&&i.get(r.element)?.length===1&&ks.hasPart(t,i.get(r.element)[0],r)||(n.who===void 0||!i.has(n.who))&&e.push({kind:"unknown-who",id:n.who??"",path:`events.${s}.who`})}),e}}class Se{constructor(t,e,i){this.travel=t;const n=t.params,s=t.until??i;let r=Se.unit(n.from),a=Se.towards(r,Se.unit(n.towards));const c=e.map(h=>{const u=h.params,d=u.side==="left"?1:-1;return{from:h.t,to:h.until??h.t,radians:u.byDeg*Math.PI/180*(u.seenFrom==="craft"?-d:d)}}),l=Se.STEP_MS;for(let h=t.t;h<=s;h+=l){this.directions.push(Se.direction(r));for(const f of c){const p=f.to-f.from;if(p<=0)continue;const g=f.radians*(Se.smooth((h+l-f.from)/p)-Se.smooth((h-f.from)/p));g&&(a=Se.add(Se.scale(a,Math.cos(g)),Se.scale(Se.cross(a,r),Math.sin(g))))}const u=Se.speedAt(n.speeds,h)*l/1e3*Math.PI/180,d=Se.add(Se.scale(r,Math.cos(u)),Se.scale(a,Math.sin(u)));a=Se.add(Se.scale(a,Math.cos(u)),Se.scale(r,-Math.sin(u))),r=d}}static STEP_MS=5;directions=[];at(t){const e=Math.round((t-this.travel.t)/Se.STEP_MS);return this.directions[Math.max(0,Math.min(this.directions.length-1,e))]}sizeAt(t){const e=this.travel.params;return e.sizeBy!=="altitude"?e.sizeDeg:e.sizeDeg*Math.max(.1,Math.sin(Math.max(this.at(t).altitudeDeg,1)*Math.PI/180))}static speedAt(t,e){if(t.length===0)return 0;if(e<=t[0].t)return t[0].degPerS;for(let i=1;i<t.length;i++){const n=t[i-1],s=t[i];if(s.step&&e<s.t)return n.degPerS;if(e<s.t)return n.degPerS+(s.degPerS-n.degPerS)*Se.smooth((e-n.t)/(s.t-n.t))}return t[t.length-1].degPerS}static smooth(t){const e=Math.max(0,Math.min(1,t));return e*e*(3-2*e)}static unit(t){const e=t.azimuthDeg*Math.PI/180,i=t.altitudeDeg*Math.PI/180;return[Math.cos(i)*Math.sin(e),Math.cos(i)*Math.cos(e),Math.sin(i)]}static direction(t){return{azimuthDeg:(Math.atan2(t[0],t[1])*180/Math.PI%360+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,t[2])))*180/Math.PI}}static towards(t,e){const i=Se.add(e,Se.scale(t,-Se.dot(t,e))),n=Math.hypot(...i)||1;return Se.scale(i,1/n)}static toScreen(t,e,i){const[n,s,r]=Se.basis(e,i),a=Se.unit(t),c=Se.dot(a,n);return[Se.dot(a,s)/c,Se.dot(a,r)/c]}static fromScreen(t,e,i,n){const[s,r,a]=Se.basis(i,n),c=[s[0]+t*r[0]+e*a[0],s[1]+t*r[1]+e*a[1],s[2]+t*r[2]+e*a[2]],l=Math.hypot(...c);return Se.direction([c[0]/l,c[1]/l,c[2]/l])}static basis(t,e){const i=t*Math.PI/180,n=e*Math.PI/180;return[[Math.cos(n)*Math.sin(i),Math.cos(n)*Math.cos(i),Math.sin(n)],[Math.cos(i),-Math.sin(i),0],[-Math.sin(n)*Math.sin(i),-Math.sin(n)*Math.cos(i),Math.cos(n)]]}static dot(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}static cross(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}static add(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}static scale(t,e){return[t[0]*e,t[1]*e,t[2]*e]}}class Io{constructor(t,e){this.sighting=t,this.events=e}static FOV_DEG=60;keyframes(){const t=this.events.filter(c=>c.eventType==="look").sort((c,l)=>c.t-l.t),e=this.events.filter(c=>c.eventType==="walk").sort((c,l)=>c.t-l.t),i=this.events.filter(c=>c.eventType==="follow").sort((c,l)=>c.t-l.t);if(t.length===0&&e.length===0)return[];const n=new Set([0]);for(const c of[...t,...e,...i])n.add(c.t),c.until!==void 0&&n.add(c.until);const s=c=>{let l;for(const h of e){const u=h.params;if(c<=h.t)return l??u.from;if(h.until===void 0||c>=h.until)l=u.to;else return}return l??this.sighting.event.place?.[0]},r=c=>([...t].reverse().find(h=>h.t<=c)??t[0])?.params??{headingDeg:0,pitchDeg:0},a=[...n].sort((c,l)=>c-l).flatMap(c=>{const l=s(c);if(!l)return[];const h=r(c);return[{t:c,pose:Io.pose(l,h.headingDeg,h.pitchDeg,h.fovDeg)}]});for(const c of a)this.sighting.observerTrack.addKeyframe(c.t,c.pose);for(const c of i)this.follow(c,r(c.t));return[...this.sighting.observerTrack.allKeyframes]}follow(t,e){const i=t.params;if(this.followSky(t,e))return;const n=this.sighting.interpretation?.bodies.find(h=>h.id===i.target);if(!n)return;const s={heightAt:()=>0},r=h=>Lt.eyeOf(this.sighting,h,s),a=new Lt(n,s,r),c=t.until??1/0;let l=e;for(const h of n.track){if(h.t<=t.t||h.t>=c)continue;const u=a.at(h.t),d=r(h.t),f=this.sighting.observerTrack.getInterpolatedPoseAt(h.t);if(!u||!d||!f)continue;const p=u.eastM-d.eastM,g=u.northM-d.northM,m=u.upM-d.upM;l={headingDeg:(Math.atan2(p,g)*180/Math.PI%360+360)%360,pitchDeg:Math.atan2(m,Math.hypot(p,g))*180/Math.PI},this.sighting.observerTrack.addKeyframe(h.t,{...f,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}if(Number.isFinite(c)){const h=this.sighting.observerTrack.getInterpolatedPoseAt(c);h&&this.sighting.observerTrack.addKeyframe(c,{...h,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}}static FOLLOW_SKY_MS=25;static CATCH_UP_MS=900;static OVERHEAD_DEG=78;static HIGHEST_PITCH_DEG=88;followSky(t,e){const i=t.params,n=ks.within(this.sighting,i.target),s=this.sighting.events??[],r=s.find(M=>M.eventType==="travel"&&M.who!==void 0&&n.has(M.who));if(!r)return!1;const a=this.sighting.event.durationSeconds!==void 0?this.sighting.event.durationSeconds*1e3:r.until??t.t,c=new Se(r,s.filter(M=>M.eventType==="turn"&&M.who!==void 0&&n.has(M.who)),a),l=t.until??a,h=(i.lagS??0)*1e3,u=(i.reactionS??0)*1e3,d=[],f=this.sighting.sampleMs??Io.FOLLOW_SKY_MS;for(let M=t.t;M<=l;M+=f)d.push(M);const p=d.map(M=>c.at(Math.max(r.t,M-h))),g=p.map(M=>M.azimuthDeg),m=p.flatMap((M,v)=>M.altitudeDeg>Io.OVERHEAD_DEG?[v]:[]);if(m.length>0){const M=Math.max(0,m[0]-1),v=Math.min(d.length-1,m[m.length-1]+1),x=g[M],y=(g[v]-x+540)%360-180;for(let w=M;w<=v;w++)g[w]=((x+y*Se.smooth((w-M)/(v-M)))%360+360)%360}return d.forEach((M,v)=>{const x=Se.smooth((M-t.t-u)/Io.CATCH_UP_MS),y=(g[v]-e.headingDeg+540)%360-180,w=Math.min(p[v].altitudeDeg,Io.HIGHEST_PITCH_DEG),b=this.sighting.observerTrack.getInterpolatedPoseAt(M)??this.sighting.observerTrack.getLatestPoseAt(M);if(!b)return;const E=S=>Math.round(S*100)/100;this.sighting.observerTrack.addKeyframe(M,{...b,headingDeg:E(((e.headingDeg+y*x)%360+360)%360),pitchDeg:E(e.pitchDeg+(w-e.pitchDeg)*x)})}),!0}static pose(t,e,i,n=Io.FOV_DEG){return{lat:t.lat,lng:t.lng,elevationM:0,headingDeg:e,pitchDeg:i,fovDeg:n}}}class Ko{constructor(t,e,i,n){this.body=t,this.events=e,this.endMs=i,this.sampleMs=n}static SAMPLE_MS=250;track(){const t=new Map,e=l=>{const h=t.get(l.t);t.set(l.t,h?{...h,...l,motions:{...h.motions,...l.motions},...h.turns||l.turns?{turns:{...h.turns,...l.turns}}:{},...h.lights||l.lights?{lights:{...h.lights,...l.lights}}:{}}:l)};for(const l of this.body.track)e({...l});const i=[...this.events].sort((l,h)=>l.t-h.t),n=new Map,s=new Map,r=new Map;let a=0;for(const l of this.body.track){for(const[h,u]of Object.entries(l.motions??{}))n.set(h,u);for(const[h,u]of Object.entries(l.turns??{}))s.set(h,u);for(const[h,u]of Object.entries(l.lights??{}))r.set(h,u);l.attitude?.headingDeg!==void 0&&(a=l.attitude.headingDeg)}let c=this.startPlace();for(const l of i){const h=Ko.partOf(l.who,this.body.id);if(h!==void 0&&(l.eventType==="light"||l.eventType==="blink")){for(const u of this.leavesOf(h))this.switchLight(u,l,r,e,d=>t.get(d)?.lights?.[u]);continue}if(h!==void 0){if(l.eventType!=="spin"&&l.eventType!=="turn")continue;const u=s.get(h)??0,d=l.until??l.t,f=l.eventType==="spin"?u+360*l.params.turnsPerS*(d-l.t)/1e3:l.params.headingDeg;e({t:l.t,turns:{[h]:u}}),e({t:d,turns:{[h]:f}}),s.set(h,f);continue}if((l.eventType==="motion"||l.eventType==="spin")&&l.params?.motion){const u=l.params,d=u.motion,f=n.get(d)??0,p=l.until??l.t,g=l.eventType==="motion"?u.to:f+u.turnsPerS*(p-l.t)/1e3;e({t:l.t,motions:{[d]:f}}),e({t:p,motions:{[d]:g}}),n.set(d,g)}else if(l.eventType==="rise"&&c){const u=l.params,d=l.until??l.t,f=u.angleDeg*Math.PI/180,p=(u.headingDeg??0)*Math.PI/180,g=c,m=M=>{const v=u.stops===!1?M*M:M*M*M*(10-15*M+6*M*M),x=u.distanceM*v;return{eastM:g.eastM+x*Math.sin(f)*Math.sin(p),northM:g.northM+x*Math.sin(f)*Math.cos(p),aboveGroundM:g.aboveGroundM+x*Math.cos(f)}};for(let M=l.t;M<d;M+=this.sampleMs??Ko.SAMPLE_MS)e(Ko.key(M,m((M-l.t)/(d-l.t))));c=m(1),e(Ko.key(d,c))}else if(l.eventType==="turn"){const u=l.params;e({t:l.t,attitude:{headingDeg:a}}),e({t:l.until??l.t,attitude:{headingDeg:u.headingDeg}}),a=u.headingDeg}else l.eventType==="vanish"&&e({t:l.t,present:!1})}return[...t.values()].sort((l,h)=>l.t-h.t)}static ride(t,e,i){const n=e.params,s=e.until??1/0,r=new Map(t.track.map(a=>[a.t,{...a}]));for(const a of i.track){if(a.t<e.t||a.t>s||(a.present===!1&&r.set(a.t,{...r.get(a.t),t:a.t,present:!1}),a.eastM===void 0||a.northM===void 0))continue;const c=(a.onGround?0:a.altitudeAboveGroundM??0)+n.aboveM;r.set(a.t,{...r.get(a.t),t:a.t,eastM:a.eastM,northM:a.northM,altitudeAboveGroundM:c})}return[...r.values()].sort((a,c)=>a.t-c.t)}switchLight(t,e,i,n,s){const r=i.get(t)??0,a=e.eventType==="light"?e.until:e.until??this.endMs,c=(l,h)=>n({t:l,lights:{[t]:h}});if(e.t>0&&s(e.t-1)===void 0&&c(e.t-1,r),e.eventType==="light"){const l=e.params.cdM2;if(c(e.t,l),a===void 0){i.set(t,l);return}c(a-1,l)}else{const l=e.params;if(a===void 0)return;const h=l.cdM2??r;let u=e.t,d=!0;for(;u<a;){const f=Math.min(Math.round(u+1e3*(d?l.onS:l.offS)),a);if(f<=u)break;c(u,d?h:0),c(f-1,d?h:0),u=f,d=!d}}c(a,r),i.set(t,r)}leavesOf(t,e=new Set){const i=this.body.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}startPlace(){const t=this.body.track.find(e=>e.eastM!==void 0&&e.northM!==void 0);return t&&{eastM:t.eastM,northM:t.northM,aboveGroundM:t.onGround?0:t.altitudeAboveGroundM??0}}static key(t,e){return e.aboveGroundM<=0?{t,eastM:e.eastM,northM:e.northM,onGround:!0}:{t,eastM:e.eastM,northM:e.northM,altitudeAboveGroundM:e.aboveGroundM}}}class Ld{constructor(t,e,i){this.object=t,this.events=e,this.endMs=i}lights(){const t=new Map,e=[...this.events].sort((i,n)=>i.t-n.t);for(const i of e){const n=Ld.partOf(i.who,this.object.id);if(!(n===void 0||i.eventType!=="light"&&i.eventType!=="blink"))for(const s of this.leavesOf(n)){const r=this.object.lights?.find(a=>a.id===s);r&&t.set(s,this.switched(r,t.get(s)??[],i))}}return(this.object.lights??[]).map(i=>t.has(i.id)?{...i,keyframes:t.get(i.id)}:i)}switched(t,e,i){const n=Ld.stateAt(t,e,i.t),s=i.eventType==="light"?i.until:i.until??this.endMs,r=[];if(i.eventType==="light")r.push({t:i.t,intensity:i.params.intensity,pattern:n.pattern});else{const c=i.params,l=c.onS+c.offS;if(s===void 0||l<=0)return e;const h=l*1e3,u=(-i.t/h%1+1)%1,d={kind:"flash",perMinute:60/l,dutyCycle:c.onS/l,...u?{phase:u}:{}},f=c.intensity??(n.intensity>0?n.intensity:t.intensity??1);r.push({t:i.t,intensity:f,pattern:d})}s!==void 0&&r.push({t:s,intensity:n.intensity,pattern:n.pattern});const a=new Set(r.map(c=>c.t));return[...e.filter(c=>!a.has(c.t)),...r].sort((c,l)=>c.t-l.t)}static stateAt(t,e,i){const n=e.filter(s=>s.t<=i).at(-1);return{intensity:n?.intensity??t.intensity??1,pattern:n?.pattern??t.pattern}}leavesOf(t,e=new Set){const i=this.object.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}}class bh{static observer(t){const e=t.allKeyframes,i=e.map(s=>bh.said(s.pose)),n=e.filter((s,r)=>r>0&&r<e.length-1&&i[r]===i[r-1]&&i[r]===i[r+1]);for(const s of n)t.removeKeyframeAt(s.t)}static said(t){return JSON.stringify(t,(e,i)=>typeof i=="number"?Math.round(i*1e10)/1e10:i)}static timeline(t){const e=new Map;for(const i of t.allKeyframes)for(const n of i.shapes){const s=e.get(n.sourceId)??[];s.push({t:i.t,said:bh.said(n.shape)}),e.set(n.sourceId,s)}for(const[i,n]of e){const s=n.filter((r,a)=>a>0&&a<n.length-1&&r.said===n[a-1].said&&r.said===n[a+1].said);for(const r of s)t.removeShapeAt(r.t,i)}}}class j0{constructor(t,e){this.end=e;const i=[...t].sort((n,s)=>n.t-s.t);this.rolls=i.filter(n=>n.eventType==="roll"),this.vibrations=i.filter(n=>n.eventType==="vibrate"),this.spirals=i.filter(n=>n.eventType==="spiral")}static SPIRAL_OPENS=4;static THINNEST=.08;rolls;vibrations;spirals;rollAt(t){let e=0,i=0;for(const n of this.rolls){if(t<n.t)break;const s=n.params,r=this.progress(n,t);i=e+(s.toDeg-e)*(s.andBack?Math.sin(Math.PI*Se.smooth(r)):Se.smooth(r)),s.andBack||(e=s.toDeg)}for(const n of this.spirals){if(t<n.t)break;const s=n.params;i=e+(s.clockwise?1:-1)*s.rollDeg*this.progress(n,t)}return i}acrossShareAt(t){return Math.max(j0.THINNEST,Math.abs(Math.cos(this.rollAt(t)*Math.PI/180)))}sidewaysAt(t,e){let i=0;for(const n of this.vibrations){const s=n.until??this.end;if(t<n.t||t>=s)continue;const r=n.params,a=Se.smooth((t-n.t)/(r.riseS*1e3))*Math.max(0,1-(t-n.t)/(s-n.t));i+=r.amplitudeShare*e*a*Math.sin(2*Math.PI*r.hz*(t-n.t)/1e3)}return i}spiralAt(t){const e=[...this.spirals].reverse().find(a=>a.t<=t);if(!e)return;const i=e.params,n=this.progress(e,t),s=Math.tan(i.radiusDeg*Math.PI/180)*Se.smooth(n*j0.SPIRAL_OPENS)*(1-i.shrink*Se.smooth(n)),r=-(i.clockwise?1:-1)*2*Math.PI*i.turns*n;return[s*(Math.cos(r)-1),s*Math.sin(r)]}progress(t,e){const i=t.until??this.end;return i<=t.t?1:Math.max(0,Math.min(1,(e-t.t)/(i-t.t)))}}class Os{constructor(t,e,i,n){this.sighting=t,this.stand=e;const s=i.filter(a=>a.eventType==="appearance").sort((a,c)=>a.t-c.t);this.vanishAt=i.find(a=>a.eventType==="vanish")?.t;const r=this.vanishAt??n;this.path=e.eventType==="travel"?new Se(e,i.filter(a=>a.eventType==="turn"),n):void 0,this.motion=this.path?new j0(i,e.until??n):void 0,this.looks=s.map((a,c)=>({t:a.t,until:a.until??s[c+1]?.t??r,parts:a.params.parts})),this.blinks=i.filter(a=>a.eventType==="blink").map(a=>({t:a.t,until:a.until??r,parts:a.who===void 0?[]:t.timeline.leavesOf(a.who),params:a.params}))}static SAMPLE_MS=2e3;static TRAVEL_SAMPLE_MS=25;static MOTION_MS=40;static SPIRAL_AHEAD_MS=20;static R=63710088e-1;looks;blinks;vanishAt;path;motion;timeline(){const t=new Map,e=(r,a)=>{const c=this.state(a,r);c&&(t.has(r)||t.set(r,new Map),t.get(r).set(a,c))},i=[...new Set(this.looks.flatMap(r=>r.parts.map(a=>a.sourceId)))];this.looks.forEach((r,a)=>{const c=this.looks[a+1];for(const l of i){if(!r.parts.some(d=>d.sourceId===l)){e(r.t,l),c?.parts.some(d=>d.sourceId===l)&&e(c.t-1,l);continue}const u=this.sighting.sampleMs??(this.path?Os.TRAVEL_SAMPLE_MS:Os.SAMPLE_MS);for(let d=r.t;d<r.until;d+=u)e(d,l);e(r.until-1,l)}});for(const r of this.blinks)for(const[a,c]of this.phases(r))for(const l of r.parts)e(a,l),e(c-1,l);if(this.vanishAt!==void 0)for(const r of i)e(this.vanishAt,r);const n=[...t.keys()].sort((r,a)=>r-a).map(r=>({t:r,shapes:[...t.get(r).values()]})),s=new Map;for(const r of n)for(const a of r.shapes){const c=a.shape.angle,l=s.get(a.sourceId);if(c===void 0)continue;const h=l===void 0?c:c+2*Math.PI*Math.round((l-c)/(2*Math.PI));a.shape.angle=Math.round(h*1e4)/1e4,s.set(a.sourceId,h)}return{keyframes:n,order:i,groups:[]}}phases(t){const e=[];let i=!0;for(let n=t.t;n<t.until;){const s=Math.min(n+(i?t.params.onS:t.params.offS)*1e3,t.until);e.push([n,s]),n=s,i=!i}return e}off(t,e){for(const i of this.blinks){if(e<i.t||e>=i.until||!i.parts.includes(t))continue;if(this.phases(i).findIndex(([s,r])=>e>=s&&e<r)%2===1)return i.params.off}}state(t,e){const i=[...this.looks].reverse().find(l=>l.t<=e)??this.looks[0],n=i?.parts.find(l=>l.sourceId===t),r=(n?i:this.looks.find(l=>l.t>e&&l.parts.some(h=>h.sourceId===t))??[...this.looks].reverse().find(l=>l.parts.some(h=>h.sourceId===t)))?.parts.find(l=>l.sourceId===t);if(!r)return;const a=!n||this.vanishAt!==void 0&&e>=this.vanishAt,c=a?void 0:this.off(t,e);return this.path?{sourceId:t,shape:this.onPath(r,e,c,a)}:{sourceId:t,shape:Os.shape(r,this.geometry(e),c,a)}}onPath(t,e,i,n){const s=this.path,r=this.sighting.observerTrack.getInterpolatedPoseAt(e)??this.sighting.observerTrack.getLatestPoseAt(e),a=r?.headingDeg??0,c=r?.pitchDeg??0,l=this.motion,h=S=>Se.toScreen(s.at(S),a,c),u=(S,A)=>{const R=Math.hypot(A[0]-S[0],A[1]-S[1])||1;return[(A[0]-S[0])/R,(A[1]-S[1])/R]};let d=h(e),[f,p]=u(h(e-Os.MOTION_MS),h(e+Os.MOTION_MS));const g=s.sizeAt(e),m=Math.tan(l.sidewaysAt(e,g)*Math.PI/180);d=[d[0]-m*p,d[1]+m*f];const M=l.spiralAt(e);if(M){const S=l.spiralAt(e+Os.SPIRAL_AHEAD_MS),A=h(e),R=h(e+Os.SPIRAL_AHEAD_MS);d=[d[0]+M[0],d[1]+M[1]],[f,p]=u([A[0]+M[0],A[1]+M[1]],[R[0]+S[0],R[1]+S[1]])}const v=l.acrossShareAt(e),x={...t,heightShare:(t.heightShare??t.widthShare)*v,...t.upShare===void 0?{}:{upShare:t.upShare*v}},y=Math.tan(g*(x.alongShare??0)*Math.PI/180),w=Math.tan(g*(x.upShare??0)*Math.PI/180),b=Se.fromScreen(d[0]+y*f-w*p,d[1]+y*p+w*f,a,c),E=Os.shape(x,{...b,sizeDeg:g},i,n,!0);return E.angle=Math.atan2(-p,f),E}geometry(t){const e=this.stand.params,i=this.sighting.observerTrack.getInterpolatedPoseAt(t)??this.sighting.observerTrack.getLatestPoseAt(t),n=i?.lat!==void 0&&i.lng!==void 0?{lat:i.lat,lng:i.lng}:this.sighting.event.place?.[0]??e.place;return Os.seenFrom(e,n,t)}static seenFrom(t,e,i){const n=(t.place.lng-e.lng)*Math.PI/180*Os.R*Math.cos(e.lat*Math.PI/180),s=(t.place.lat-e.lat)*Math.PI/180*Os.R,r=Math.hypot(n,s),a=li.linear(t.metres.map(({t:l,widthM:h,step:u})=>({t:l,value:h,step:u})),i),c=li.linear(t.metres.map(({t:l,heightM:h,step:u})=>({t:l,value:h,step:u})),i);return{azimuthDeg:(Math.atan2(n,s)*180/Math.PI%360+360)%360,altitudeDeg:Math.atan2(c,r)*180/Math.PI,sizeDeg:2*Math.atan(a/(2*r))*180/Math.PI}}static shape(t,e,i,n,s=!1){const r=e.sizeDeg,a=Math.max(t.minWidthDeg??0,r*t.widthShare),c=t.kind==="oval"&&t.heightShare===void 0?a:Math.max(t.minHeightDeg??0,r*(t.heightShare??t.widthShare)),l=s?e.altitudeDeg:e.altitudeDeg+r*(t.upShare??0),h=s?e.azimuthDeg:e.azimuthDeg+r*(t.alongShare??0)/Math.cos(l*Math.PI/180),u=(p,g)=>Math.round(p*10**g)/10**g,d=t.kind==="polygon"?{kind:"polygon",bounds:{x:300,y:170,width:100,height:100*c/a},points:(t.points??[]).map(p=>({x:u(p.x*100,2),y:u(p.y*100*c/a,2)}))}:{kind:"oval",bounds:{x:320,y:180,width:2,height:2}};Object.assign(d,{color:i?.color??t.color,angle:0,transparency:n?1:i?.transparency??t.transparency??0,haloScale:t.halo??0,selected:!1,...t.blur===void 0?{}:{blur:t.blur},...t.title===void 0?{}:{title:t.title},angular:{widthDeg:u(a,4),heightDeg:u(c,4)},aim:{azimuthDeg:u((h%360+360)%360,3),altitudeDeg:u(l,3)}});const f=i&&"brightness"in i?i.brightness:t.brightness;return f!=null&&(d.brightness=n?0:f),d}}class Oe{static STANDING_EYE_M=1.6;static METERS_PER_DEGREE=111320;static expand(t){Oe.expandBodies(t),Oe.expandObserver(t),Oe.expandFlights(t),Oe.expandDecorLights(t),Oe.expandPhenomenon(t)}static expandDecorLights(t){for(const e of t.decor){if(!e.lights?.length||e.lights.some(s=>s.keyframes?.length))continue;const i=(t.events??[]).filter(s=>Ld.partOf(s.who,e.id)!==void 0);if(i.length===0)continue;const n=JSON.stringify(e.lights);e.lights=new Ld(e,i,Oe.endOf(t)).lights(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorLights={...t.eventsExpansion.decorLights,[e.id]:{stated:n,expanded:JSON.stringify(e.lights)}}}}static writtenLights(t,e,i){const n=t.eventsExpansion?.decorLights?.[e];return n&&JSON.stringify(i)===n.expanded?JSON.parse(n.stated):i}static expandPhenomenon(t){if(t.timeline.allKeyframes.length>0)return;const e=Oe.stands(t);for(const i of e){const n=ks.within(t,i.who),s=(t.events??[]).filter(a=>a.who!==void 0&&n.has(a.who)),r=new Os(t,i,s,i.until??Oe.endOf(t)).timeline();for(const a of Jd.fromJSON(r).allKeyframes)t.timeline.addKeyframe(a.t,a.shapes)}e.length!==0&&(bh.timeline(t.timeline),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.timelinePending=!0)}static stands(t){return(t.events??[]).filter(e=>(e.eventType==="stand"||e.eventType==="travel")&&ks.isPhenomenon(t,e))}static shapesOf(t){const{groups:e,...i}=t.timeline.toJSON();return JSON.stringify(i)}static timelineWithoutShapes(t){const e=t.timeline.toJSON().groups??[];return e.length>0?{keyframes:[],groups:e}:{keyframes:[]}}static settle(t){t.eventsExpansion?.timelinePending&&(vn.toAngular(t),vn.toAim(t),t.eventsExpansion.timeline=Oe.shapesOf(t),t.eventsExpansion.timelinePending=!1)}static timelineIsExpanded(t){return t.eventsExpansion?.timeline!==void 0&&t.eventsExpansion.timeline===Oe.shapesOf(t)}static expandFlights(t){const e=t.observerTrack.allKeyframes[0]?.pose??t.event.place?.[0];if(e?.lat===void 0||e.lng===void 0)return;const i=Math.cos(e.lat*Math.PI/180);for(const n of t.events??[]){if(n.eventType!=="fly"||n.who===void 0)continue;const s=t.decor.find(g=>g.id===n.who);if(!s||s.track?.length)continue;const r=n.params,a=n.until??Oe.endOf(t),c=r.headingDeg*Math.PI/180,l=(r.from.lng-e.lng)*Math.PI/180*Oe.R*i,h=(r.from.lat-e.lat)*Math.PI/180*Oe.R,u=r.speeds.map(({t:g,kmh:m,step:M})=>({t:g,value:m/3.6,step:M})),d=r.heights.map(({t:g,altitudeM:m,step:M})=>({t:g,value:m,step:M})),f=g=>{const m=Math.sign(g-r.at.t)*Oe.FLY_STEP_MS;let M=0;for(let v=r.at.t;m!==0&&(m>0?v<g:v>g);v+=m){const x=m>0?Math.min(g,v+m):Math.max(g,v+m);M+=(li.linear(u,v)+li.linear(u,x))/2*(x-v)/1e3}return M},p=[];for(let g=n.t;g<=a;g+=li.SAMPLE_MS){const m=r.at.metresBefore-f(g);p.push({t:g,eastM:l-Math.sin(c)*m,northM:h-Math.cos(c)*m,altitudeM:li.linear(d,g),headingDeg:r.headingDeg})}s.track=p,s.eastM=p[0].eastM,s.northM=p[0].northM,s.headingDeg=r.headingDeg,t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorTracks[s.id]=JSON.stringify(p)}}static R=63710088e-1;static FLY_STEP_MS=100;static expandObserver(t){const e=(t.events??[]).filter(g=>ks.isObserver(t,g)),i=e.find(g=>g.eventType==="drive"),n=e.find(g=>g.eventType==="lookAhead");if(t.observerTrack.allKeyframes.length>0)return;if(!i){new Io(t,e).keyframes().length>0&&(bh.observer(t.observerTrack),t.eventsExpansion={...t.eventsExpansion,observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:t.eventsExpansion?.decorTracks??{}});return}if(!n)return;const s=i.until??Oe.endOf(t),r=i.params,a=new li(r,i.t,s),c=e.find(g=>g.eventType==="lean"),l=e.find(g=>g.eventType==="watch"),u=new ti(a,r.eye,n.params,c&&{t:c.t,params:c.params},l&&{t:l.t,params:l.params},g=>{const m=Oe.stands(t).find(v=>v.eventType==="stand");if(!m)return Oe.phenomenonPitchAt(t,g);const M=a.stateAt(g);return Os.seenFrom(m.params,{lat:M.lat,lng:M.lng},g).altitudeDeg}).poses(i.t,s),d=u.map(g=>({t:g.t,pose:{lat:g.lat,lng:g.lng,elevationM:g.eye.y-Oe.STANDING_EYE_M,headingDeg:g.headingDeg,pitchDeg:g.pitchDeg,fovDeg:r.fovDeg??60}}));for(const g of d)t.observerTrack.addKeyframe(g.t,g.pose);bh.observer(t.observerTrack);const f={observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:{}},p=r.vehicle===void 0?void 0:t.decor.find(g=>g.id===r.vehicle);if(p&&!p.track?.length){const g=u[0],m=v=>Math.cos(v*Math.PI/180),M=u.map(v=>{const x=v.roadDeg*Math.PI/180,y=-v.eye.z,w=v.eye.x,b=(v.lng-g.lng)*Oe.METERS_PER_DEGREE*m(v.lat),E=(v.lat-g.lat)*Oe.METERS_PER_DEGREE;return{t:v.t,eastM:b-y*Math.sin(x)-w*Math.cos(x),northM:E-y*Math.cos(x)+w*Math.sin(x),altitudeM:0,headingDeg:v.roadDeg}});p.track=M,p.eastM=M[0].eastM,p.northM=M[0].northM,p.headingDeg=M[0].headingDeg,f.decorTracks[p.id]=JSON.stringify(M)}t.eventsExpansion={...t.eventsExpansion,...f}}static expandBodies(t){const e=t.interpretation?.bodies??[],i=n=>(t.events??[]).some(s=>s.who===n.id&&s.eventType==="ride");for(const n of[...e.filter(s=>!i(s)),...e.filter(i)]){const s=(t.events??[]).filter(h=>h.who===n.id||Ko.partOf(h.who,n.id)!==void 0);if(s.length===0)continue;const r=Math.min(...s.map(h=>h.t));if(n.track.some(h=>h.t>r))continue;const a=JSON.stringify(n.track),c=s.find(h=>h.eventType==="ride"),l=c&&e.find(h=>h.id===c.params.in);n.track=c?l?Ko.ride(n,c,l):n.track:new Ko(n,s,Oe.endOf(t),t.sampleMs).track(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.bodies={...t.eventsExpansion.bodies,[n.id]:{stated:a,expanded:JSON.stringify(n.track)}}}}static writtenInterpretation(t,e){const i=t.eventsExpansion?.bodies;return!e||!i?e:{...e,bodies:e.bodies.map(n=>{const s=i[n.id];return s&&JSON.stringify(n.track)===s.expanded?{...n,track:JSON.parse(s.stated)}:n})}}static refresh(t){const e=t.observerTrack.allKeyframes.length===0||Oe.observerTrackIsExpanded(t),i=t.timeline.allKeyframes.length===0||Oe.timelineIsExpanded(t);Oe.again(t,e,i)}static reset(t){Oe.again(t,!0,Oe.stands(t).length>0)}static again(t,e,i){for(const s of t.interpretation?.bodies??[]){const r=t.eventsExpansion?.bodies?.[s.id];r&&JSON.stringify(s.track)===r.expanded&&(s.track=JSON.parse(r.stated))}for(const s of t.decor)s.lights&&(s.lights=Oe.writtenLights(t,s.id,s.lights));if(e){for(const s of Object.keys(t.eventsExpansion?.decorTracks??{})){const r=t.decor.find(a=>a.id===s);r&&delete r.track}t.observerTrack.clear()}const n=t.timeline.toJSON().groups??[];if(i){for(const s of[...t.timeline.sourceIds])t.timeline.removeSource(s);t.timeline.setGroups(n,!1)}t.eventsExpansion=void 0,Oe.expand(t),i&&t.timeline.pruneGroups(),i&&(vn.toBounds(t),vn.toPosition(t)),Oe.settle(t)}static bodiesAreExpanded(t){const e=t.eventsExpansion?.bodies??{};return(t.interpretation?.bodies??[]).every(i=>!e[i.id]||JSON.stringify(i.track)===e[i.id].expanded)}static observerTrackIsExpanded(t){return t.eventsExpansion?.observerTrack!==void 0&&t.eventsExpansion.observerTrack===JSON.stringify(t.observerTrack.toJSON())}static decorTrackIsExpanded(t,e,i){const n=t.eventsExpansion?.decorTracks[e];return n!==void 0&&n===JSON.stringify(i)}static phenomenonPitchAt(t,e){let i;for(const n of t.timeline.sourceIds){const s=t.timeline.getInterpolatedShapeAt(e,n),r=s?.aim?.altitudeDeg;if(!s||s.transparency>=1||r===void 0)continue;const a=(s.angular?.widthDeg??0)*(s.angular?.heightDeg??0);(!i||a>i.area)&&(i={area:a,altitude:r})}return i?.altitude??0}static endOf(t){return t.event.durationSeconds!==void 0?t.event.durationSeconds*1e3:Math.max(...(t.events??[]).map(e=>e.until??e.t))}}function Nb(o){return pr.restore(Lb(o),o.provenance)}function Lb(o,t=!1){return vn.toAngular(o),vn.toAim(o),{version:4,id:o.id,time:Q0.write(o.event.time),endTime:Q0.write(o.event.endTime),durationSeconds:o.event.durationSeconds,durationText:o.event.durationText,utcOffsetHours:o.event.utcOffsetHours,timeZone:o.event.timeZone,place:Fb.write(o.event.place),observer:o.observer,account:o.account,sources:o.sources?.length?o.sources:void 0,sway:o.sway,vehicle:o.vehicle,description:o.event.description,image:o.event.image,summary:o.event.summary,summaryTime:o.event.summaryTime,tags:o.event.tags,timeline:!t&&Oe.timelineIsExpanded(o)?Oe.timelineWithoutShapes(o):o.timeline.toJSON(),observerTrack:!t&&Oe.observerTrackIsExpanded(o)?void 0:is.restatedObserverTrack(o),events:o.events?.length?o.events:void 0,weatherTrack:o.weatherTrack.toJSON(),soundTrack:o.soundTrack.toJSON(),weather:o.weather,decor:is.restatedDecor(o).map(e=>{if(!t&&e.lights&&(e={...e,lights:Oe.writtenLights(o,e.id,e.lights)}),t||!Oe.decorTrackIsExpanded(o,e.id,e.track))return e;const{track:i,...n}=e;return n}),milestones:o.milestones.length>0?o.milestones:void 0,references:o.references.length>0?o.references:void 0,roads:o.roads.length>0?o.roads:void 0,traces:o.traces.length>0?o.traces:void 0,weatherSource:o.weatherSource,instrument:o.instrumentId,exposureSeconds:o.exposureSeconds,iso:o.iso,film:o.film,metering:o.metering,sampleMs:o.sampleMs,lens:o.lens,lighting:o.lighting,lightPollution:o.lightPollution,around:Do.says(o.around)?o.around:void 0,observerMap:o.observerMap,interpretation:t?is.restatedInterpretation(o):Oe.writtenInterpretation(o,is.restatedInterpretation(o)),variants:o.variants.length>0?o.variants:void 0,skyEvents:Jr.written(o.skyEvents),skySources:o.skySources===!1?!1:void 0,snapshots:o.snapshots,modules:o.modules?.length?o.modules:void 0}}function $_(o){return o.observer?.id??"observer"}function kb(o){const t=ha.check(o,"sighting"),{recording:e,provenance:i}=pr.strip(t),n=q_(e);return n.provenance=i,n}function q_(o){const t=[],e=new Hp({eventType:"sighting",time:Q0.read(o.time),endTime:Q0.read(o.endTime),durationSeconds:o.durationSeconds,durationText:o.durationText,utcOffsetHours:o.utcOffsetHours,timeZone:o.timeZone,place:Fb.read(o.place),description:o.description,image:o.image,summary:o.summary,summaryTime:o.summaryTime,tags:o.tags},Jd.fromJSON(o.timeline,t,!1),o.observerTrack?dd.fromJSON(o.observerTrack):new dd,o.weatherTrack?fd.fromJSON(o.weatherTrack):new fd,o.soundTrack?pd.fromJSON(o.soundTrack):new pd,o.observer&&{id:o.observer.id,title:o.observer.title,lastName:o.observer.lastName,firstNames:o.observer.firstNames},o.id,o.weather,(o.decor??[]).map(n=>{if(!n.facade?.plain)return n;const{plain:s,...r}=n.facade;return{...n,facade:{...r,openings:"plain"}}}),o.weatherSource,o.instrument,o.exposureSeconds??o.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),Gu(o.milestones??[]),o.references??[],o.roads??[],o.traces??[]);e.account=o.account,e.sources=o.sources,e.sway=o.sway,e.iso=o.iso,e.film=o.film,e.metering=o.metering,e.sampleMs=o.sampleMs,e.lens=o.lens,e.lighting=o.lighting,e.lightPollution=o.lightPollution,e.around=Do.read(o.around),e.observerMap=o.observerMap,e.vehicle=o.vehicle,e.events=o.events?.map(n=>n.who===void 0?{...n,who:$_(o)}:n);const i=Jr.read(o.skyEvents,o.interpretation);return e.interpretation=i.interpretation,e.variants=Array.isArray(o.variants)?o.variants:[],e.skyEvents=i.skyEvents,e.skySources=o.skySources===!1?!1:void 0,e.snapshots=o.snapshots,e.modules=Array.isArray(o.modules)?o.modules.filter(n=>typeof n=="string"):void 0,e.loadIssues=t,Oe.expand(e),e.timeline.pruneGroups(),vn.toBounds(e),vn.toPosition(e),Oe.settle(e),e}class Q0{static read(t){return t===void 0||t.trim()===""?void 0:O_(t)}static write(t){if(t===void 0)return;const e=N_(t);return e===""?void 0:e}}class Fb{static read(t){if(t?.locations?.length)return t.locations.map(({lat:e,lng:i})=>({lat:e,lng:i,...t.name===void 0?{}:{name:t.name}}))}static write(t){if(!t?.length)return;const e=t.find(i=>i.name)?.name;return{...e===void 0?{}:{name:e},locations:t.map(({lat:i,lng:n})=>({lat:i,lng:n}))}}}const Z_=Object.freeze(Object.defineProperty({__proto__:null,fromSightingJson:kb,plainSightingJson:Lb,toSightingJson:Nb},Symbol.toStringTag,{value:"Module"}));class kd{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}","out-of-range":"{path}: {found} is outside {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(t,e=kd.EN){return e[t.kind].replace("{path}",t.path).replace("{expected}",t.expected??"").replace("{found}",t.found??"")}static warn(t,e){if(t.length===0)return;const i=t.map(n=>` ${kd.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
|
|
1933
1933
|
${i.join(`
|
|
1934
1934
|
`)}`)}}class hr{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!hr.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:hr.typeOf(t)});return}for(const[s,r]of Object.entries(t)){const a=i?`${i}.${s}`:s,c=e[s];c?this.field(r,c,a,n):n.push({kind:"unknown-key",path:a})}}field(t,e,i,n){if(hr.isStated(t)){this.field(t.value,e,i,n);return}if(!(e.loose||t===void 0||t===null))switch(e.type){case"enum":(typeof t!="string"||!e.values?.includes(t))&&n.push({kind:"not-in-list",path:i,expected:(e.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(t)});return;case"object":e.fields?this.object(t,e.fields,i,n):hr.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:hr.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=hr.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:hr.typeOf(t)});return;default:typeof t!==e.type?n.push({kind:"wrong-type",path:i,expected:e.type,found:hr.typeOf(t)}):typeof t=="number"&&(e.minimum!==void 0&&t<e.minimum||e.maximum!==void 0&&t>e.maximum)&&n.push({kind:"out-of-range",path:i,expected:`${e.minimum??"−∞"}–${e.maximum??"∞"}`,found:String(t)})}}static STATED_KEYS=new Set(["value","basis","rationale","how","range","source"]);static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return hr.isObject(t)&&"value"in t&&Object.keys(t).every(e=>hr.STATED_KEYS.has(e))}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class ns{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(t,e){const i=Number.isFinite(e)?Math.max(0,e):0,n=Math.max(0,t-i*1e3),s=Math.max(0,t-n);return{fromMs:n,toMs:t,ms:s,seconds:s/1e3}}static instants(t,e,i,n,s){if(!(n>0))return 1;const r=s>0?ns.travelDegOver(t,e,i,i+n*1e3)/s/ns.PIXELS_PER_INSTANT:0,a=ns.flashesOver(t,n)*ns.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(ns.MAX_INSTANTS,c)}static travelDegOver(t,e,i,n){let s=0;for(const r of t){if(!r.track||r.track.length<2)continue;const a=ns.directionAt(r,e,i),c=ns.directionAt(r,e,n),l=Math.min(1,Math.max(-1,a.x*c.x+a.y*c.y+a.z*c.z));s=Math.max(s,Math.acos(l)*180/Math.PI)}return s}static flashesOver(t,e){let i=0;for(const n of t)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*e}static directionAt(t,e,i){const n=Ma(t,i),s=n.eastM,r=n.altitudeM-e,a=n.northM,c=Math.hypot(s,r,a);return c===0?{x:0,y:1,z:0}:{x:s/c,y:r/c,z:a/c}}static bodyInstants(t,e,i,n,s){if(!(n>i)||!(s>0))return 1;let r=0;for(const c of t){const l=ns.bodyAt(c,i),h=ns.bodyAt(c,n);if(!l||!h)continue;const u={x:l.eastM,y:l.upM-e,z:l.northM},d={x:h.eastM,y:h.upM-e,z:h.northM},f=Math.hypot(u.x,u.y,u.z),p=Math.hypot(d.x,d.y,d.z);if(f===0||p===0)continue;const g=Math.min(1,Math.max(-1,(u.x*d.x+u.y*d.y+u.z*d.z)/f/p));let m=Math.acos(g)*180/Math.PI,M=0;for(const v of Object.keys(h.motions))M=Math.max(M,Math.abs(h.motions[v]-(l.motions[v]??h.motions[v])));M>0&&(m+=M*2*(h.halfWidthM/Math.max(p,.001))*180/Math.PI),r=Math.max(r,m)}const a=Math.ceil(r/s/ns.PIXELS_PER_INSTANT);return a<2?1:Math.min(ns.MAX_INSTANTS,a)}static bodyAt(t,e){const i=t.track;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let n=0,s=i.length-1;for(;s-n>1;){const d=n+s>>1;i[d].t<=e?n=d:s=d}const r=i[n],a=i[s];if(r.eastM===void 0||r.northM===void 0||a.eastM===void 0||a.northM===void 0)return;const c=a.t>r.t?(e-r.t)/(a.t-r.t):0,l=(d,f)=>d+(f-d)*c,h={};for(const d of Object.keys(a.motions??{})){const f=r.motions?.[d],p=a.motions[d];h[d]=f===void 0?p:l(f,p)}const u=i.find(d=>d.sizeM)?.sizeM?.widthM??1;return{eastM:l(r.eastM,a.eastM),northM:l(r.northM,a.northM),upM:l(r.altitudeM??0,a.altitudeM??0),halfWidthM:u/2,motions:h}}}function C0(o,t){for(const e of o){const i=e.toLowerCase().split("-")[0];if(t.includes(i))return i}return"en"}class ko{static preferencesFor(t){const e=navigator.languages??[],i=this.declaredFor(t);return i?[i,...e]:e}static declaredFor(t){for(let e=t;e;){const i=e.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=e.getRootNode();e=n instanceof ShadowRoot?n.host:void 0}}}Nt.register(Fn,()=>new Pc);Nt.register(Uh,()=>new wh);Nt.register(Nr,()=>new ov);Nt.register(zh,()=>new Sh);Nt.register(md,()=>new cv);Nt.register(Bh,()=>new xd);Nt.register(Fh,()=>new yd);Nt.register(Hh,()=>new wd);Nt.register(ec,()=>new Gh);Nt.register(kh,()=>new vd);Nt.register(zs,()=>new zi);Nt.register(Vo,()=>new Ed);Nt.register(Mn,()=>new Oc);Nt.register(Wo,()=>new Ad);Nt.register(gd,()=>new lv);Nt.register(Xo,()=>new _d);Nt.register(Go,()=>new bd);Nt.register(Yo,()=>new Td);Nt.register(Zc,()=>new Rd);Nt.register(Ho,()=>new Sd);Nt.register(Ss,()=>new je);Nt.register(Za,()=>new Cd);Nt.register(mn,()=>new ie);Nt.register(Ja,()=>new Pd);Nt.register(Md,()=>new Bp);Nt.register(ja,()=>new Nd);Nt.register(qa,()=>new Id);Nt.register(Qa,()=>new Od);Nt.register(J0,()=>new R_);Nt.register($a,()=>new Dd);class Pr{constructor(t){this.preferences=t}read(t){var e,i;if(t===void 0)return;if(typeof t=="string")return t===""?void 0:t;for(const s of this.preferences){const r=(e=t[s])!==null&&e!==void 0?e:t[Pr.base(s)];if(r)return r}const n=new Set(this.preferences.map(s=>Pr.base(s)));for(const[s,r]of Object.entries(t))if(r&&n.has(Pr.base(s)))return r;return(i=Object.values(t).find(s=>s))!==null&&i!==void 0?i:void 0}write(t,e,i){var n,s;const r=e?.trim()?e.trim():void 0;if(t===void 0||typeof t=="string")return r;const a={...t},c=(s=(n=Object.keys(a).find(l=>l===i))!==null&&n!==void 0?n:Object.keys(a).find(l=>Pr.base(l)===Pr.base(i)))!==null&&s!==void 0?s:i;return r===void 0?delete a[c]:a[c]=r,Object.keys(a).length===0?void 0:a}static base(t){return t.toLowerCase().split("-")[0]}}Pr.any=new Pr([]);var N2;(function(o){o.abductee="abductee",o.actor="actor",o.artist="artist",o.anthropologist="anthropologist",o.archeologist="archeologist",o.astronaut="astronaut",o.astronomer="astronomer",o.astrologist="astrologist",o.astrophysicist="astrophysicist",o.banker="banker",o.barman="barman",o.biologist="biologist",o.biochemist="biochemist",o.biophysicist="biophysicist",o.bishop="bishop",o.businessman="businessman",o.botanist="botanist",o.cameraman="cameraman",o.chemist="chemist",o.contactee="contactee",o.cryptozoologist="cryptozoologist",o.dentist="dentist",o.director="director",o.diplomat="diplomat",o.diver="diver",o.electronics="electronics",o.engineer="engineer",o.ethnologist="ethnologist",o.exobiologist="exobiologist",o.farmer="farmer",o.firefighter="firefighter",o.flightAttendant="flightAttendant",o.geologist="geologist",o.geophysicist="geophysicist",o.geographer="geographer",o.historian="historian",o.houseWife="houseWife",o.hypnotherapist="hypnotherapist",o.illusionist="illusionist",o.journalist="journalist",o.judge="judge",o.lawyer="lawyer",o.leader="leader",o.librarian="librarian",o.logger="logger",o.mathematician="mathematician",o.mechanic="mechanic",o.meteorologist="meteorologist",o.military="military",o.musician="musician",o.neurologist="neurologist",o.neuroscientist="neuroscientist",o.neuropsychiatrist="neuropsychiatrist",o.nurse="nurse",o.oceanographer="oceanographer",o.painter="painter",o.parapsychologist="parapsychologist",o.philosopher="philosopher",o.photographer="photographer",o.physician="physician",o.physicist="physicist",o.pilot="pilot",o.politician="politician",o.policeman="policeman",o.priest="priest",o.producer="producer",o.prospector="prospector",o.psychologist="psychologist",o.psychiatrist="psychiatrist",o.radioastronomer="radioastronomer",o.radioamateur="radioamateur",o.salesman="salesman",o.sailor="sailor",o.sociologist="sociologist",o.softwareEngineer="softwareEngineer",o.stuntman="stuntman",o.taxiDriver="taxiDriver",o.teacher="teacher",o.telegrapher="telegrapher",o.truckDriver="truckDriver",o.ufologist="ufologist",o.ufoWitness="ufoWitness",o.ufoWitness2="ufoWitness2",o.worker="worker",o.writer="writer"})(N2||(N2={}));var L2;(function(o){o.neutral="neutral",o.male="male",o.female="female"})(L2||(L2={}));class J_ extends Error{constructor(t,e){super(t),this.cause=e}}class uv extends J_{constructor(t=uv.defaultMessage,e){super(t,e)}}uv.defaultMessage="Assertion failed";var k2;(function(o){o.country="country",o.region="region",o.department="department",o.city="city",o.company="company"})(k2||(k2={}));var F2;(function(o){o.at="at",o.au="au",o.ar="ar",o.be="be",o.br="br",o.ca="ca",o.ch="ch",o.cn="cn",o.cl="cl",o.co="co",o.cy="cy",o.de="de",o.dk="dk",o.do="do",o.dz="dz",o.gr="gr",o.ec="ec",o.eg="eg",o.es="es",o.fi="fi",o.fr="fr",o.ga="ga",o.ge="ge",o.hu="hu",o.in="in",o.ie="ie",o.ir="ir",o.il="il",o.it="it",o.jp="jp",o.kr="kr",o.ma="ma",o.mx="mx",o.my="my",o.mz="mz",o.nl="nl",o.no="no",o.nz="nz",o.pa="pa",o.pe="pe",o.ph="ph",o.pl="pl",o.pt="pt",o.ro="ro",o.ru="ru",o.sc="sc",o.tr="tr",o.ua="ua",o.uk="uk",o.us="us",o.sa="sa",o.se="se",o.su="su",o.tn="tn",o.tw="tw",o.ve="ve",o.za="za"})(F2||(F2={}));const j_=["en","fr","es","it"];class Vs{static catalog(t){const e=new Map;return{load(i){const n=Vs.languageOf(i);let s=e.get(n);return s||(s=t[n](),e.set(n,s),s.catch(()=>e.delete(n))),s}}}static none(){return new Proxy({},{get:()=>""})}static blank(){const t=new Proxy(()=>t,{get:(e,i)=>i===Symbol.toPrimitive?()=>"":i===Symbol.iterator?function*(){}:i==="toString"||i==="valueOf"?()=>"":i==="then"?void 0:t,apply:()=>t,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{}});return t}static languageOf(t){const e=t.toLowerCase().split("-")[0];return j_.includes(e)?e:"en"}}const P0=["en","fr","es","it"],Q_={en:()=>dt(()=>import("./UfoMessages_en-A8Ku1B0Y.js"),[],import.meta.url).then(o=>o.ufoMessages_en),fr:()=>dt(()=>import("./UfoMessages_fr-CGkQBn5r.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>dt(()=>import("./UfoMessages_es-CO-v8Jl6.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>dt(()=>import("./UfoMessages_it-BScqxIaH.js"),[],import.meta.url).then(o=>o.ufoMessages_it)},t5=Vs.catalog(Q_),e5=Vs.catalog({en:()=>dt(()=>import("./SceneNames_en-Dn90NisJ.js"),[],import.meta.url).then(o=>o.sceneNames_en),fr:()=>dt(()=>import("./SceneNames_fr-rltu5c_j.js"),[],import.meta.url).then(o=>o.sceneNames_fr),es:()=>dt(()=>import("./SceneNames_es-DH6GZWja.js"),[],import.meta.url).then(o=>o.sceneNames_es),it:()=>dt(()=>import("./SceneNames_it-DsNshdIp.js"),[],import.meta.url).then(o=>o.sceneNames_it)});function i5(o){return e5.load(o)}const Ub=Math.PI/180,n5=180/Math.PI,s5=256,zb=19,r5=1.25;function Bb(o,t){return 156543.03392*Math.cos(o*Ub)/2**t}function Hb(o,t){return Bb(o,t)*s5}function a5(o,t){let e=0;for(;e<zb&&Hb(o,e+1)>=t;)e++;return e}function dv(o,t){return Hb(o,t)}function Gb(o,t){const e=t*r5;let i=0;for(;i<zb&&Bb(o,i)>e;)i++;return i}function O0(o){const t=o*Ub;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function Vb(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:O0(t)*i}}function Wb(o,t,e){const i=O0(o.north),n=O0(o.south);return{x:(t-o.west)/(o.east-o.west),y:(O0(e)-i)/(n-i)}}function o5(o,t,e){const{x:i,y:n}=Vb(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function c5(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=U2(o.y,t);return{south:U2(o.y+1,t),north:n,west:e,east:i}}function U2(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*n5}function Xb(o,t,e,i){const n=o5(o,t,e),s=Math.floor(i/2),r=[];for(let l=-s;l<=s;l++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+l,z:e});const a=r.map(c5),c={south:Math.min(...a.map(l=>l.south)),north:Math.max(...a.map(l=>l.north)),west:Math.min(...a.map(l=>l.west)),east:Math.max(...a.map(l=>l.east))};return{tiles:r,bounds:c}}const l5="#2ec4ff";class Ac{constructor(t){this.ctx=t}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(t,e){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-t,s.y-e);r>s.radius||r>n||(i=s,n=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(t){const{ctx:e}=this;e.save(),this.targets=[],e.clearRect(0,0,this.width,this.height),this.paintGround(t),this.paintNight(t.nightFraction),this.paintPath(t),this.paintTraces(t),t.position?(this.paintCone(t,t.position),this.paintDecor(t),this.paintMarkers(t),this.paintObserver(t,t.position)):(this.paintDecor(t),this.paintMarkers(t)),this.paintNorth(),this.paintFooter(t.bounds,t.attribution),e.restore()}toCanvas(t,e,i){const n=Wb(t,i,e);return{x:n.x*this.width,y:n.y*this.height}}paintGround(t){const{ctx:e}=this;e.fillStyle="#1d2321",e.fillRect(0,0,this.width,this.height);const i=t.imagery;if(!i)return;const n=this.toCanvas(t.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(t.bounds,i.bounds.south,i.bounds.east);e.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(t=0){if(t<=0)return;const{ctx:e}=this;e.save(),e.fillStyle=`rgba(6, 12, 30, ${Math.min(t,1)*.78})`,e.fillRect(0,0,this.width,this.height),e.restore()}paintDecor(t){const{ctx:e}=this;for(const i of t.decor){const n=this.toCanvas(t.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:n.x,y:n.y,radius:7}),e.beginPath(),e.rect(n.x-3.5,n.y-3.5,7,7),e.fillStyle="rgba(120, 220, 255, 0.85)",e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.7)",e.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),e.lineWidth=3,e.strokeStyle="rgba(0, 0, 0, 0.6)",e.stroke(),e.lineWidth=1.5,e.strokeStyle="rgba(120, 220, 255, 0.9)",e.stroke()}}paintPath(t){if(!t.path.moved)return;const{ctx:e}=this,i=t.path.points.map(n=>this.toCanvas(t.bounds,n.lat,n.lng));e.beginPath(),e.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))e.lineTo(n.x,n.y);e.lineJoin="round",e.lineCap="round",e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=5,e.stroke(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=2,e.stroke()}paintTraces(t){const{ctx:e}=this;for(const i of t.traces??[]){const n=i.points.map(r=>this.toCanvas(t.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??l5;if(i.kind==="point")e.beginPath(),e.moveTo(n[0].x,n[0].y-6),e.lineTo(n[0].x+6,n[0].y),e.lineTo(n[0].x,n[0].y+6),e.lineTo(n[0].x-6,n[0].y),e.closePath(),e.fillStyle=s,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))e.lineTo(r.x,r.y);i.kind==="polygon"&&e.closePath(),e.lineJoin="round",e.setLineDash([]),e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=4.5,e.stroke(),e.setLineDash([9,5]),e.strokeStyle=s,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(i.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let r=n[0];if(i.kind==="line"&&t.position){const a=this.toCanvas(t.bounds,t.position.lat,t.position.lng);r=n.reduce((c,l)=>Math.hypot(l.x-a.x,l.y-a.y)>Math.hypot(c.x-a.x,c.y-a.y)?l:c)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(t,e){const{headingDeg:i,coneHalfAngleDeg:n}=t;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(t.bounds,e.lat,e.lng),a=Math.hypot(this.width,this.height),c=(i-90)*Math.PI/180,l=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,a,c-l,c+l),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=h,s.fill(),s.restore()}paintMarkers(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const i of[...t.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(t.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:n.x,y:n.y,radius:Ac.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,Ac.MARKER_RADIUS_PX,0,Math.PI*2),e.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",e.fill(),e.lineWidth=2,e.strokeStyle="rgba(255, 255, 255, 0.9)",e.stroke(),e.fillStyle=i.current?"#1d2321":"#fff",e.fillText(i.label,n.x,n.y)}}paintObserver(t,e){const{ctx:i}=this,n=this.toCanvas(t.bounds,e.lat,e.lng);t.observerLabel&&this.targets.push({kind:"observer",label:t.observerLabel,lat:e.lat,lng:e.lng,x:n.x,y:n.y,radius:8});const s=t.markers.some(r=>{if(!r.current)return!1;const a=ae(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=Ac.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?Ac.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),s||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=s?3:2.5,i.strokeStyle=s?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:t}=this,e=this.width-14,i=16;t.beginPath(),t.moveTo(e,i-9),t.lineTo(e-4.5,i+5),t.lineTo(e,i+2),t.lineTo(e+4.5,i+5),t.closePath(),t.fillStyle="rgba(255, 255, 255, 0.92)",t.strokeStyle="rgba(0, 0, 0, 0.6)",t.lineWidth=1,t.fill(),t.stroke(),t.font="bold 9px sans-serif",t.textAlign="center",t.textBaseline="top",t.strokeText("N",e,i+6),t.fillText("N",e,i+6)}paintFooter(t,e){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=e?this.wrap(e,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const f of n.slice().reverse())this.paintOutlinedText(f,this.width-6,s),s-=11;const r=(t.south+t.north)/2,c=Math.abs(ae(r,t.east,r,t.west).x)/this.width,l=Ac.SCALE_STEPS_M.find(f=>f/c<=this.width/3);if(l===void 0)return;const h=l/c,u=8,d=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(u,d),i.lineTo(u+h,d),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(l>=1e3?`${l/1e3} km`:`${l} m`,u,d-3)}paintOutlinedText(t,e,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(t,e,i),n.fillStyle="#fff",n.fillText(t,e,i)}wrap(t,e){const i=[];let n="";for(const s of t.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>e?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class gi{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(t,e){return gi.including(t.boundsAround(gi.MIN_SPAN_M,gi.MARGIN),e)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(t,e,i){const n=Math.min(gi.MAX_ZOOM,Math.max(gi.MIN_ZOOM,this.zoom*i)),s=this.centerX+(t-.5)/this.zoom,r=this.centerY+(e-.5)/this.zoom;this.centerX=s-(t-.5)/n,this.centerY=r-(e-.5)/n,this.zoom=n}panBy(t,e){this.centerX-=t/this.zoom,this.centerY-=e/this.zoom}refit(t,e){if(!this.changed)return;const i=this.boundsWithin(t),n=gi.mercatorY01(e.north),s=gi.mercatorY01(e.south),r=gi.mercatorY01(i.north),a=gi.mercatorY01(i.south);this.zoom=(e.east-e.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-e.west)/(e.east-e.west),this.centerY=((r+a)/2-n)/(s-n)}keepInView(t,e,i){if(!this.changed)return!1;const n=this.boundsWithin(t),s=gi.mercatorY01(n.north),r=gi.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(gi.mercatorY01(e.lat)-s)/(r-s);return a>=i&&a<=1-i&&c>=i&&c<=1-i?!1:(this.panBy(.5-a,.5-c),!0)}boundsWithin(t){if(!this.changed)return t;const e=.5/this.zoom,i=gi.mercatorY01(t.north),n=gi.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:gi.latitudeAt(i+(this.centerY-e)*(n-i)),south:gi.latitudeAt(i+(this.centerY+e)*(n-i))}}static including(t,e,i=3){const n=(t.north+t.south)/2,s=(t.east+t.west)/2,r=ae(n,t.east,n,s).x;let a=r;for(const c of e){const{x:l,z:h}=ae(c.lat,c.lng,n,s),u=Math.max(Math.abs(l),Math.abs(h));u<=r*i&&(a=Math.max(a,u*1.15))}return a<=r?t:{north:Bs(0,-a,n,s).lat,south:Bs(0,a,n,s).lat,east:Bs(a,0,n,s).lng,west:Bs(-a,0,n,s).lng}}static expand(t,e){const i=t.east-t.west,n=t.north-t.south;return{west:t.west-i*e,east:t.east+i*e,south:t.south-n*e,north:t.north+n*e}}static pointAt(t,e,i){const n=gi.mercatorY01(t.north),s=gi.mercatorY01(t.south);return{lat:gi.latitudeAt(n+i*(s-n)),lng:t.west+e*(t.east-t.west)}}static mercatorY01(t){const e=t*Math.PI/180;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}static latitudeAt(t){return Math.atan(Math.sinh(Math.PI*(1-2*t)))*180/Math.PI}}const ar=256,h5=3,u5=129,d5=7,f5=32768;class Yb{fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(t,e){const i=(t.south+t.north)/2,n=(t.west+t.east)/2,s=Math.abs(ae(i,t.east,i,t.west).x),r=Math.abs(ae(t.north,n,t.south,n).z),a=Math.max(s,r);let c=a5(i,a),l=h5;if(e.width>=u5){const g=M=>2*Math.ceil((a/dv(i,M)+1)/2)+1;let m=Gb(i,a/(e.width-1)/2);for(;m>c&&g(m)>d5;)m--;m>c&&(c=m,l=g(m))}const{tiles:h}=Xb(n,i,c,l),u=l*ar,d=new Float32Array(u*u),f=h[0];await Promise.all(h.map(g=>this.decodeTileInto(g,f,d,u)));const p=new Float32Array(e.width*e.height);for(let g=0;g<e.height;g++){const m=t.north+(t.south-t.north)*(g/(e.height-1));for(let M=0;M<e.width;M++){const v=t.west+(t.east-t.west)*(M/(e.width-1));p[g*e.width+M]=this.sampleAt(m,v,c,f,d,u)}}return{heights:p,width:e.width,height:e.height,bounds:t}}async decodeTileInto(t,e,i,n){const s=this.tileUrlTemplate.replace("{z}",String(t.z)).replace("{x}",String(t.x)).replace("{y}",String(t.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const a=await createImageBitmap(await r.blob()),c=document.createElement("canvas");c.width=ar,c.height=ar;const l=c.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(a,0,0);const{data:h}=l.getImageData(0,0,ar,ar),u=(t.x-e.x)*ar,d=(t.y-e.y)*ar;for(let f=0;f<ar;f++)for(let p=0;p<ar;p++){const g=(f*ar+p)*4,m=h[g]*256+h[g+1]+h[g+2]/256-f5,M=u+p,v=d+f;i[v*n+M]=m}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=Vb(e,t,i),l=(a-n.x)*ar,h=(c-n.y)*ar,u=Math.max(0,Math.min(r-1,Math.floor(l))),d=Math.max(0,Math.min(r-1,Math.floor(h))),f=Math.min(r-1,u+1),p=Math.min(r-1,d+1),g=l-u,m=h-d,M=s[d*r+u],v=s[d*r+f],x=s[p*r+u],y=s[p*r+f],w=M+(v-M)*g,b=x+(y-x)*g;return w+(b-w)*m}}class Gp{constructor(t,e,i,n){this.width=t,this.height=e,this.samples=i,this.values=n}at(t,e,i=0){return this.values[(e*this.width+t)*this.samples+i]}static parse(t){const e=new DataView(t);if(t.byteLength<8||e.getUint16(0)!==18761||e.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=e.getUint32(4,!0),n=e.getUint16(i,!0),s=new Map;for(let M=0;M<n;M++){const v=i+2+M*12;s.set(e.getUint16(v,!0),{type:e.getUint16(v+2,!0),count:e.getUint32(v+4,!0),value:e.getUint32(v+8,!0)})}const r=(M,v)=>{const x=s.get(M);if(x===void 0){if(v===void 0)throw new Error(`TIFF without tag ${M}`);return v}return x.type===3?x.value&65535:x.value},a=M=>{const v=s.get(M);if(v===void 0)throw new Error(`TIFF without tag ${M}`);const x=v.type===3?2:4,y=[];if(v.count*x<=4){const w=new DataView(new ArrayBuffer(4));w.setUint32(0,v.value,!0);for(let b=0;b<v.count;b++)y.push(x===2?w.getUint16(b*2,!0):w.getUint32(0,!0))}else for(let w=0;w<v.count;w++)y.push(x===2?e.getUint16(v.value+w*2,!0):e.getUint32(v.value+w*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const c=r(256),l=r(257),h=r(277,1),u=a(258)[0],d=r(339,1)===3;if(!(d&&u===32||!d&&u===8))throw new Error(`Unsupported TIFF samples: ${u} bits`);const f=a(273),p=a(279),g=new Uint8Array(c*l*h*(u/8));let m=0;for(let M=0;M<f.length&&m<g.length;M++){const v=Math.min(p[M],g.length-m);g.set(new Uint8Array(t,f[M],v),m),m+=v}if(m<g.length)throw new Error("Truncated TIFF");return new Gp(c,l,h,d?new Float32Array(g.buffer):g)}}class po extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class p5{constructor(t,e,i,n,s){this.heights=t,this.plants=e,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(t,e){const i=Math.floor(t/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-e/this.metresPerPixel);if(i<0||n<0||i>=this.size||n>=this.size)return;const s=n*this.size+i;if(!(this.plants[s]||this.buildings[s]))return this.heights[s]}tallestStructureNear(t,e,i){let n;const s=Math.ceil(i/this.metresPerPixel);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const c=this.structureAt(t+a*this.metresPerPixel,e+r*this.metresPerPixel);c!==void 0&&(n===void 0||c>n)&&(n=c)}return n}}class Fe{static covers(t,e){return t>=41.2&&t<=51.3&&e>=-5.4&&e<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??Fe.WMS,this.wfs=t.wfsEndpoint??Fe.WFS}static radius(t){return Math.min(t,Fe.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,Fe.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=Fe.lidarRadius(e),n=Math.ceil(2*i/Fe.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,Fe.HEIGHT_LAYER),this.raster(t,i,n,Fe.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new po("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===Fe.NO_DATA))throw new po("no-coverage","No LiDAR HD survey here yet");const c=new Uint8Array(n*n),l=new Uint8Array(n*n);for(let u=0;u<n*n;u++){const d=r.values[u*r.samples],f=r.values[u*r.samples+1],p=r.values[u*r.samples+2];c[u]=f>d&&f>p?1:0,l[u]=d>120&&f<90&&p<90?1:0}const h=2*i/n;return{size:n,metresPerPixel:h,heights:a,vegetation:c,building:l,structures:new p5(a,c,l,n,h)}}async laserDate(t){return Fe.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return Fe.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",t))}static latest(t){return t.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(t,e,i,n){const r=[n.lng-1e-4,n.lat-1e-4,n.lng+1e-4,n.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(t,e){const i=Fe.radius(e),n=Math.min(Fe.MAX_PHOTO_PIXELS,Math.ceil(2*i/Fe.METRES_PER_PIXEL)),s=await this.raster(t,i,n,Fe.PHOTO_LAYER);if(s.samples<3)throw new po("unreachable","The photograph came in a layout this does not read");return{size:n,metresPerPixel:2*i/n,samples:s.samples,values:s.values}}async vectors(t,e,i){const n=Fe.radius(e),s=n/Fe.METRES_PER_DEGREE,r=n/(Fe.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),c=`BBOX(geometrie,${[t.lng-r,t.lat-s,t.lng+r,t.lat+s].map(M=>M.toFixed(6)).join(",")},'EPSG:4326')`,[l,h,u,d,f,p]=await Promise.all([this.features("construction_lineaire",`${c} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${c} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${c} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",c,"voltage,geometrie"),i?this.features("batiment",c,Fe.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",c,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),g=i?await this.wholeWorship(p,f,[t.lng-r,t.lat-s,t.lng+r,t.lat+s]):[],m=[...f,...g];return{bridges:l,elevatedRoads:h,elevatedRailways:u,lines:d,buildings:m,zones:p,mapDate:Fe.latest(m.map(M=>M.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(t,e,i){const[n,s,r,a]=i,c=Fe.MAX_WHOLE_M/Fe.METRES_PER_DEGREE;let l;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,g]=Fe.extent(u);if(d>=n&&f>=s&&p<=r&&g<=a)continue;const m=[Math.max(d,n-c),Math.max(f,s-c),Math.min(p,r+c),Math.min(g,a+c)];l=l?[Math.min(l[0],m[0]),Math.min(l[1],m[1]),Math.max(l[2],m[2]),Math.max(l[3],m[3])]:m}if(!l)return[];const h=new Set(e.map(u=>u.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${l.map(d=>d.toFixed(6)).join(",")},'EPSG:4326')`,Fe.BUILDING_PROPERTIES,1e3)).filter(d=>!h.has(d.properties.cleabs))}catch{return[]}}static extent(t){let e=1/0,i=1/0,n=-1/0,s=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(e=Math.min(e,a[0]),n=Math.max(n,a[0]),i=Math.min(i,a[1]),s=Math.max(s,a[1])):Array.isArray(a)&&a.forEach(r)};return r(t.geometry.coordinates),[e,i,n,s]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,c=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const l of c)n.push(l.map(h=>({lat:h[1],lng:h[0]})))}return n}async waterSurfaces(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${e} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${e} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${e} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(t,e,i,n){const s=e/Fe.METRES_PER_DEGREE,r=e/(Fe.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-s,t.lng-r,t.lat+s,t.lng+r].map(l=>l.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let c;try{c=await this.fetchImpl(`${this.wms}?${a}`)}catch(l){throw new po("unreachable",l instanceof Error?l.message:String(l))}if(!c.ok)throw new po("unreachable",`The survey answered ${c.status}`);try{return Gp.parse(await c.arrayBuffer())}catch(l){throw new po("unreachable",l instanceof Error?l.message:String(l))}}async features(t,e,i,n=200){const s=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:t.includes(":")?t:`BDTOPO_V3:${t}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(n),CQL_FILTER:e,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(c){throw new po("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new po("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class Co{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(t,e){if(t.length<2||e.length<2)return!1;const i=e[0],n=e.map(a=>ae(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>ae(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const c=s[a],l=s[a+1],h=Math.hypot(l.x-c.x,l.z-c.z);if(h<1e-6)continue;const u=Math.max(1,Math.ceil(h/Co.SAMPLE_M)),d=Math.atan2(l.x-c.x,-(l.z-c.z));for(let f=0;f<=u;f++){const p=f/u,g=Co.nearest(n,c.x+(l.x-c.x)*p,c.z+(l.z-c.z)*p);g.distanceM>Co.NEAR_M||Co.angleBetween(d,g.heading)<=Co.ALIGNED_DEG&&(r+=h/u)}}return r>=Co.LONG_ENOUGH_M}static nearest(t,e,i){let n={distanceM:1/0,heading:0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.z-r.z,h=c*c+l*l,u=h<1e-9?0:Math.max(0,Math.min(1,((e-r.x)*c+(i-r.z)*l)/h)),d=Math.hypot(e-(r.x+c*u),i-(r.z+l*u));d<n.distanceM&&(n={distanceM:d,heading:Math.atan2(c,-l)})}return n}static angleBetween(t,e){const i=Math.abs((t-e)*180/Math.PI%180);return Math.min(i,180-i)}}class Pe{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??Pe.WMS,this.timeoutMs=t.timeoutMs??Pe.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??Pe.MAX_WINDOW_M,this.geoplatform=new Fe({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,i){const n={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!Fe.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(ae(n.lat,t.east,n.lat,t.west).x),r=Math.abs(ae(t.north,n.lng,t.south,n.lng).z);e=this.finer(e,s,r);const a={x:s/Math.max(1,e.width-1),y:r/Math.max(1,e.height-1)},c={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},l={south:t.south-c.y/Pe.METRES_PER_DEGREE,north:t.north+c.y/Pe.METRES_PER_DEGREE,west:t.west-c.x/(Pe.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(Pe.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},h=g=>Math.min(Pe.MAX_PIXELS,Math.max(Pe.MIN_PIXELS,Math.ceil(g/Pe.METRES_PER_PIXEL))),u={width:h(s+2*c.x),height:h(r+2*c.y)},d={x:(s+2*c.x)/u.width,y:(r+2*c.y)/u.height};let f=new Error("No layer of the IGN's relief answered");const p=Math.max(d.x,d.y)>Pe.COARSE_METRES_PER_PIXEL;for(const g of p?[...Pe.LAYERS].reverse():Pe.LAYERS)try{const m=await this.heights(l,u,g);g===Pe.LAYERS[0]&&await this.layBridgeDecks(m,l,u,i?.route);const M=this.sample(m,e,t,l,d,a);if(M)return{heights:M,width:e.width,height:e.height,bounds:t};f=new Error(`${g} does not cover this place`)}catch(m){f=m}throw f}finer(t,e,i){if(t.width<Pe.MESH_FROM_VERTICES||t.height<Pe.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/Pe.FINE_SPACING_M),c=Math.max(r-1,Math.min(Pe.MAX_SEGMENTS,a));return c%2===0?c:c+1};return{width:n(e,t.width)+1,height:n(i,t.height)+1}}async raster(t,e,i){const n=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[t.south,t.west,t.north,t.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.height),FORMAT:"image/geotiff"}),s=await this.fetchImpl(`${this.wms}?${n}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`The IGN's relief answered ${s.status}`);return Gp.parse(await s.arrayBuffer())}async heights(t,e,i){const n=await this.raster(t,e,i);if(n.samples!==1||!(n.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return n}async layBridgeDecks(t,e,i,n){if(!(!n||n.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(s=>s>Pe.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>Co.follows(n,a));if(s.length===0)return;const r=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,i,s),this.layRouteDecks(t,r,e,s)}catch{}}async layClassifiedDecks(t,e,i,n){try{const s=await this.raster(e,i,Pe.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(m,[M,v,x])=>s.values[m*s.samples]===M&&s.values[m*s.samples+1]===v&&s.values[m*s.samples+2]===x,a=t.width,c=t.height,l=new Uint8Array(a*c);let h=!1;for(let m=0;m<l.length;m++)r(m,Pe.DECK)&&(l[m]=1,h=!0);if(!h)return;const u=Pe.DECK_END_PIXELS,d=[];for(let m=0;m<l.length;m++){if(l[m]!==1)continue;const M=m%a,v=(m-M)/a;for(let x=-u;x<=u;x++)for(let y=-u;y<=u;y++){const w=M+y,b=v+x;if(w<0||b<0||w>=a||b>=c)continue;const E=b*a+w;l[E]===0&&r(E,Pe.NO_CLASS)&&d.push(E)}}for(const m of d)l[m]=1;const f=this.paint(n,e,a,c),p=this.touching(l,f,a,c);if(p.every(m=>m===0))return;const g=await this.heights(e,i,Pe.SURFACE_LAYER);if(g.width!==a||g.height!==c)return;for(let m=0;m<p.length;m++){if(p[m]===0)continue;const M=g.values[m];Number.isFinite(M)&&M>Pe.NO_DATA_BELOW&&M>t.values[m]&&(t.values[m]=M)}}catch{}}layRouteDecks(t,e,i,n){const{width:s,height:r}=t,a=(i.north+i.south)/2,c=(i.east-i.west)*Pe.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),l=(i.north-i.south)*Pe.METRES_PER_DEGREE,h=c/s,u=l/r,d=M=>({x:(M.lng-i.west)/(i.east-i.west)*c,y:(i.north-M.lat)/(i.north-i.south)*l}),f=(M,v)=>{const x=Math.floor(M/h),y=Math.floor(v/u);if(x<0||y<0||x>=s||y>=r)return;const w=e[y*s+x];return Number.isFinite(w)&&w>Pe.NO_DATA_BELOW?w:void 0},p=Pe.DECK_HALF_WIDTH_M,g=Pe.DECK_APPROACH_M,m=(M,v)=>{const x=Math.hypot(M.x-v.x,M.y-v.y)||1,y={x:(M.x-v.x)/x,y:(M.y-v.y)/x},w=[0,g/2,g].map(b=>f(M.x+y.x*b,M.y+y.y*b)).filter(b=>b!==void 0);return w.length>0?Math.max(...w):void 0};for(const M of Pe.chains(n.map(v=>v.map(d)))){const v=[0];for(let D=1;D<M.length;D++)v.push(v[D-1]+Math.hypot(M[D].x-M[D-1].x,M[D].y-M[D-1].y));const x=v[v.length-1];if(x<1||x>Pe.DECK_STRAIGHT_MAX_M)continue;const y=m(M[0],M[1]),w=m(M[M.length-1],M[M.length-2]);if(y===void 0||w===void 0)continue;const b=p+g,E=Math.max(0,Math.floor((Math.min(...M.map(D=>D.x))-b)/h)),S=Math.min(s-1,Math.ceil((Math.max(...M.map(D=>D.x))+b)/h)),A=Math.max(0,Math.floor((Math.min(...M.map(D=>D.y))-b)/u)),R=Math.min(r-1,Math.ceil((Math.max(...M.map(D=>D.y))+b)/u));for(let D=A;D<=R;D++)for(let I=E;I<=S;I++){const P=Pe.nearestAlong(M,v,{x:(I+.5)*h,y:(D+.5)*u});if(P.distance>p||P.s<-g||P.s>x+g)continue;const L=y+(w-y)*Math.min(1,Math.max(0,P.s/x)),O=D*s+I;e[O]>=L||(t.values[O]=L)}}}static chains(t){const e=t.filter(s=>s.length>=2).map(s=>[...s]),i=[],n=(s,r)=>Math.hypot(s.x-r.x,s.y-r.y)<=1;for(;e.length>0;){let s=e.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<e.length;a++){const c=e[a],l=s[0],h=s[s.length-1];if(n(h,c[0]))s=[...s,...c.slice(1)];else if(n(h,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else if(n(l,c[c.length-1]))s=[...c.slice(0,-1),...s];else if(n(l,c[0]))s=[...[...c].reverse().slice(0,-1),...s];else continue;e.splice(a,1),r=!0;break}}i.push(s)}return i}static nearestAlong(t,e,i){let n={s:0,distance:1/0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.y-r.y,h=c*c+l*l;if(h<1e-9)continue;let u=((i.x-r.x)*c+(i.y-r.y)*l)/h;s>0&&(u=Math.max(0,u)),s<t.length-2&&(u=Math.min(1,u));const d=Math.hypot(i.x-(r.x+c*u),i.y-(r.y+l*u));d<n.distance&&(n={s:e[s]+u*Math.sqrt(h),distance:d})}return n}paint(t,e,i,n){const s=new Uint8Array(i*n),r=c=>(c-e.west)/(e.east-e.west)*i,a=c=>(e.north-c)/(e.north-e.south)*n;for(const c of t)for(let l=0;l<c.length-1;l++){const h=r(c[l].lng),u=a(c[l].lat),d=r(c[l+1].lng),f=a(c[l+1].lat),p=Math.max(1,Math.ceil(Math.hypot(d-h,f-u)*2));for(let g=0;g<=p;g++){const m=Math.floor(h+(d-h)*g/p),M=Math.floor(u+(f-u)*g/p);for(let v=-1;v<=1;v++)for(let x=-1;x<=1;x++){const y=m+x,w=M+v;y>=0&&w>=0&&y<i&&w<n&&(s[w*i+y]=1)}}}return s}touching(t,e,i,n){const s=new Uint8Array(t.length),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++){if(t[a]===0||r[a]===1)continue;const c=[],l=[a];r[a]=1;let h=!1;for(;l.length>0;){const u=l.pop();c.push(u),e[u]===1&&(h=!0);const d=u%i,f=(u-d)/i;for(let p=-1;p<=1;p++)for(let g=-1;g<=1;g++){const m=d+g,M=f+p;if(m<0||M<0||m>=i||M>=n)continue;const v=M*i+m;t[v]===1&&r[v]===0&&(r[v]=1,l.push(v))}}if(h)for(const u of c)s[u]=1}return s}sample(t,e,i,n,s,r){const{width:a,height:c}=e,l=new Float32Array(a*c),h=new Uint8Array(a*c),u=Math.min(r.x,this.maxWindowM)/s.x,d=Math.min(r.y,this.maxWindowM)/s.y;let f=0;for(let p=0;p<c;p++){const g=i.north+(i.south-i.north)*(c===1?.5:p/(c-1)),m=(n.north-g)/(n.north-n.south)*t.height-.5;for(let M=0;M<a;M++){const x=(i.west+(i.east-i.west)*(a===1?.5:M/(a-1))-n.west)/(n.east-n.west)*t.width-.5,y=u>1||d>1?this.tent(t,x,m,Math.max(1,u),Math.max(1,d)):this.bilinear(t,x,m),w=p*a+M;y===void 0?f++:(l[w]=y,h[w]=1)}}if(!(f===a*c||f/(a*c)>Pe.MAX_HOLE_SHARE))return this.fill(l,h,a,c),l}tent(t,e,i,n,s){let r=0,a=0,c=0;const l=Math.max(0,Math.ceil(i-s)),h=Math.min(t.height-1,Math.floor(i+s)),u=Math.max(0,Math.ceil(e-n)),d=Math.min(t.width-1,Math.floor(e+n));for(let f=l;f<=h;f++){const p=1-Math.abs(f-i)/s;if(!(p<=0))for(let g=u;g<=d;g++){const m=p*(1-Math.abs(g-e)/n);if(m<=0)continue;c+=m;const M=t.at(g,f);!Number.isFinite(M)||M<Pe.NO_DATA_BELOW||(r+=m*M,a+=m)}}return c>0&&a>=c*.5?r/a:void 0}bilinear(t,e,i){const n=Math.max(0,Math.min(t.width-1,Math.floor(e))),s=Math.max(0,Math.min(t.height-1,Math.floor(i))),r=Math.min(t.width-1,n+1),a=Math.min(t.height-1,s+1),c=Math.max(0,Math.min(1,e-n)),l=Math.max(0,Math.min(1,i-s)),h=t.at(n,s),u=t.at(r,s),d=t.at(n,a),f=t.at(r,a);for(const m of[h,u,d,f])if(!Number.isFinite(m)||m<Pe.NO_DATA_BELOW)return;const p=h+(u-h)*c,g=d+(f-d)*c;return p+(g-p)*l}fill(t,e,i,n){let s=e.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let c=0;c<i;c++){const l=a*i+c;if(e[l])continue;let h=0,u=0;for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){const p=a+d,g=c+f;p<0||g<0||p>=n||g>=i||!e[p*i+g]||(h+=t[p*i+g],u++)}u>0&&r.push([l,h/u])}if(r.length===0)return;for(const[a,c]of r)t[a]=c,e[a]=1;s-=r.length}}}class m5{providers;constructor(...t){this.providers=t}async getElevationGrid(t,e,i){let n=new Error("No source of relief to ask");for(const s of this.providers)try{return await s.getElevationGrid(t,e,i)}catch(r){n=r}throw n}}const N0=256,g5=5;async function Kb(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(ae(n,o.east,n,o.west).x),a=Math.abs(ae(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:l,gridSize:h}=M5(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=Xb(s,n,l,h),f=h*N0,p=document.createElement("canvas");p.width=f,p.height=f;const g=p.getContext("2d");if(!g)throw new Error("2D canvas context unavailable");const m=u[0];await Promise.all(u.map(async y=>{const w=e(y),b=await i(w);if(!b.ok)throw new Error(`Imagery tile fetch failed (${b.status}): ${w}`);const E=await createImageBitmap(await b.blob());g.drawImage(E,(y.x-m.x)*N0,(y.y-m.y)*N0)}));const M=Math.min(Math.max(t.width,t.height),f);if(M===f)return{source:p,width:f,height:f,bounds:d};const v=document.createElement("canvas");v.width=M,v.height=M;const x=v.getContext("2d");if(!x)throw new Error("2D canvas context unavailable");return x.drawImage(p,0,0,f,f,0,0,M,M),{source:v,width:M,height:M,bounds:d}}function M5(o,t,e){let i=Gb(o,t/Math.max(1,e)),n=z2(o,i,t);for(;n>g5&&i>0;)i--,n=z2(o,i,t);return{zoom:i,gridSize:n,mPerPixel:dv(o,i)/N0}}function z2(o,t,e){const i=Math.ceil(e/2/dv(o,t));return Math.max(3,2*i+1)}class $b{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(t,e){return Kb(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Fs{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(t,e=Fs.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!i)return[...e];const[n,s,r,a]=i.slice(1).map(Number),c=(n+r)/2,l=(s+a)/2,h=Fs.FRANCE;return c>=h.south&&c<=h.north&&l>=h.west&&l<=h.east?[Fs.FRANCE_ENDPOINT,...e.filter(d=>d!==Fs.FRANCE_ENDPOINT)]:[...e]}fetchImpl;endpoints;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.endpoints=t.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(t){return this.queued(()=>this.ask(t))}queued(t){const e=Fs.queue.then(t,t);return Fs.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??Fs.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Fs.HANG_MS)});if(s.ok)return await s.json();if(e=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){e=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,Fs.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class Po{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;client;constructor(t={}){this.client=new Fs(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${Po.DRIVABLE.join("|")})$"](${e});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(t){const e=[];for(const i of t.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||e.push({id:`osm-${i.id??e.length}`,name:s.name,surface:Po.surfaceOf(s),widthM:Po.widthOf(s),...Po.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return e}static paintOf(t){const e=t.highway??"",i=t.junction==="roundabout"||t.junction==="circular",n=t.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(e==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(t.lanes??"",10),c=Number.parseInt(t.maxspeed??"",10),l=i?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(s||r)?"dual":e?"road":void 0;return{...l?{kind:l}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||e==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{}}}static widthOf(t){const e=Number.parseFloat(t.width??t.est_width??"");if(Number.isFinite(e)&&e>0)return e;const i=Number.parseInt(t.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:Po.WIDTH_M[t.highway]??Po.DEFAULT_WIDTH_M}static surfaceOf(t){const e=t.surface;return e==="dirt"||e==="earth"||e==="mud"?"dirt":e==="gravel"||e==="fine_gravel"||e==="compacted"||e==="ground"||e==="sand"||e==="unpaved"?"gravel":e?"paved":t.highway==="track"?"gravel":"paved"}}const Sm="https://ufoathome.org/roads/index.json";class eh{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??eh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRoads(t);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(t){let e;try{e=await this.load()}catch{return}const i=e.find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.ways)?(this.attributionRead=s.attribution,this.contemporaryRead=s.contemporary,s.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
1935
|
-
`);let e=eh.shared.get(t);return e||(e=this.fetchFirstAvailable(),eh.shared.set(t,e),e.then(i=>{i.length===0&&eh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.
|
|
1936
|
-
`);let e=ih.shared.get(t);return e||(e=this.fetchFirstAvailable(),ih.shared.set(t,e),e.then(i=>{i.length===0&&ih.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.194.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==bm?[e,bm]:[bm]).map(i=>i+t)}}class Rs{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=Rs.key(t);let i=Rs.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Rs.asked.set(e,i),i.catch(()=>Rs.asked.delete(e))),structuredClone(await i)}static forget(){Rs.asked.clear()}static key(t){return`v${Rs.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Rs.openCache(),n=Rs.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<Rs.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Rs.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-Rs.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Rs.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Uo{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new Fe(t)}static covers(t){return Fe.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>Uo.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=Uo.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=Uo.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Uo.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const g=f.map(m=>({lat:m[1],lng:m[0],...m.length>2&&Number.isFinite(m[2])&&m[2]>Uo.NO_ALTITUDE?{altitudeM:m[2]}:{}}));return g.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:g}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class Xn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(t={}){this.client=new Fs(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${Xn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Xn.ROUTES})$"];out body;`;return Xn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=Xn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(M=>ae(M.lat,M.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(M=>M.service===!!r.service);for(const M of Xn.samples(a)){u++;const v=Xn.waysAt(d,M);if(v.length===0)continue;const[x]=v;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const y of new Set(v.flatMap(w=>w.services)))h.set(y,(h.get(y)??0)+1)}const f=M=>[...M.entries()].sort((v,x)=>x[1]-v[1])[0]?.[0],p=r.name??f(c),g=r.voltageV??(r.electrification==="none"?void 0:f(l)),m=[...h.entries()].filter(([,M])=>M*4>=u).sort((M,v)=>v[1]-M[1]||M[0].localeCompare(v[0])).map(([M])=>M);return{...r,...p?{name:p}:{},...g?{voltageV:g}:{},...m.length>0?{services:m}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=Xn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=Xn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=Xn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>ae(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=Xn.SAMPLE_M/2;a<n;a+=Xn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(Xn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=Xn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class nh{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new Fs(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${nh.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Xn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=Xn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=Xn.voltageOf(r),l=nh.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=nh.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:nh.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class x5{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(t){if(!Uo.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class dn{constructor(t,e=Date.now){this.railways=t,this.now=e}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(t){const e=dn.key(t);let i=dn.asked.get(e)??dn.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},dn.asked.set(e,i),n.catch(()=>dn.asked.delete(e))}return structuredClone(await i.answer)}static forget(){dn.asked.clear(),dn.failedAt=-1/0}static key(t){return`v${dn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of dn.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await dn.openCache(),n=dn.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<dn.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-dn.failedAt<dn.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(dn.failedAt=this.now(),s)return s;throw a}return i&&dn.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-dn.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(dn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const Em="https://ufoathome.org/railways/index.json";class sh{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??sh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
1937
|
-
`);let e=sh.shared.get(t);return e||(e=this.fetchFirstAvailable(),sh.shared.set(t,e),e.then(i=>{i.length===0&&sh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.194.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==Em?[e,Em]:[Em]).map(i=>i+t)}}function qb(){return{elevation:Zb(),imagery:Jb(),roads:w5(),water:S5(),railways:b5()}}function Zb(){return new m5(new Pe,new Yb)}function Jb(){return new $b}function w5(){return new eh({fallback:new v5(new Fo,new Po)})}function S5(){return new ih({fallback:new Rs(new y5(new Fd,new _c))})}function b5(){return new sh({fallback:new dn(new x5(new Uo,new nh))})}const E5=new Set,Eh="show-observer-map",Ah="hide-milestones",Nc="minified";class He extends HTMLElement{static get observedAttributes(){return["src",Eh,Ah,Nc]}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 gi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];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=Hp.create();issues=[];issueCheck=0;sightingAudio=new O2;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new O2(t)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>He.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");He.setIcon(this.moreButton,t?Qt.UNFOLDED:Qt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(t){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!t){this.fitControls();return}const e=document.createElement("button");e.type="button",e.id="video-button",e.innerHTML=Qt.VIDEO,this.videoElement=e,this.labelVideoButton(),e.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(t,e)},{once:!0}),this.moreButton.after(e),this.fitControls()}async loadVideoButton(t,e){const{VideoButton:i}=await dt(async()=>{const{VideoButton:s}=await import("./VideoButton-Cy_r767Z.js");return{VideoButton:s}},[],import.meta.url);if(this.videoElement!==e)return;const n=new i(t,e);this.videoButton=n,this.messages&&(n.messages=this.messages),this.stageElement.append(n.panel),n.open()}labelVideoButton(){const t=this.videoElement;!t||this.videoButton||(t.title=this.messages?.recordVideo??"",t.setAttribute("aria-label",t.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(t){t!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,t&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(t){const e=this.currentTime,i=t.caption&&this.sighting.milestones.length>0?df(this.sighting.milestones,e):void 0,n=i?this.said.read(i.label)??"":void 0,s=this.canvas.getBoundingClientRect(),r=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:n,note:this.said.read(i.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...r&&s.width>0&&s.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-s.left)/s.width,top:(r.top-s.top)/s.height,width:r.width/s.width,height:r.height/s.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<He.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=gi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=gi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},He.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=gi.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${w3}</style>${x3}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Vh(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 Ac(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.citedMarks=this.shadow.getElementById("cited-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.seekPreview.hidden=!0,this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Eh&&this.applyObserverMapDefault(),t===Ah&&this.setMilestonesShown(!this.hasAttribute(Ah)),t===Nc){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Nc)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(Qb)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const t=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",t),t&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(t){this.sightingData=await ud.recording(t)}get sightingData(){return Nb(this.currentSighting)}set sightingData(t){const e=ha.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=kb(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;set titleShown(t){this.titleHidden=!t,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await dt(async()=>{const{default:r}=await import("./sightingSchema-CgwoRMl-.js");return{default:r}},[],import.meta.url);n=new hr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],kd.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(_5,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=(this.messages?.recordingIssues??"").replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=kd.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(t){this.cited=[...t],this.refreshCitedMarks()}refreshCitedMarks(){const t=this.player.seekableDuration;this.citedMarks.replaceChildren(...(t>0?this.cited:[]).map(e=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.innerHTML=Ie.INTERVIEW,i.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const n=e.quote??"";return i.title=n,i.setAttribute("aria-label",n),i.addEventListener("click",()=>this.player.seek(e.at*1e3)),i}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<He.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(A5,{bubbles:!0,composed:!0,detail:{at:t/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;if(!this.referenceOpacityTouched&&t.length>0){const e=String(t[0].opacity);this.referenceOpacityInput.value!==e&&(this.referenceOpacityInput.value=e,this.severalReferences||this.dispatchReferenceView())}for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),He.setIcon(this.referencesButton,i?Qt.PICTURES_ON:Qt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),He.setIcon(this.tracesButton,this.tracesShownState?Qt.TRACES_ON:Qt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?Gu(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshCitedMarks(),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=He.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){if(t.buttons!==0){this.seekPreview.hidden=!0;return}const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=He.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?df(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new Vh(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=He.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?df(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=ns.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<He.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(He.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/He.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/He.EXPOSURE_STEP_PX),s=Math.min(He.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=Ji.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(t,e){this.sayTimeMoved(t),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:E5;this.canvasRenderer.setStarPoints(Ji.starPointsOf(this.sighting.instrument,ke(this.sighting,t)?.fNumber));const n=(ke(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?Js.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(B_(this.currentSighting,t))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:t}}))}shifted(t,e){return e.x===0&&e.y===0?t:{...t,bounds:{...t.bounds,x:t.bounds.x+e.x,y:t.bounds.y+e.y}}}createPlayer(){const t=new H_(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*He.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?Qt.PLAY:Qt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){He.icons.get(t)!==e&&(He.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},He.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),He.setIcon(this.playPauseButton,t?Qt.PAUSE:Qt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Eh),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;He.setIcon(this.observerMapButton,t?Qt.MAP_ON:Qt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=xh.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=gi.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?gi.expand(t,He.OBSERVER_MAP_IMAGERY_AHEAD):t,n=gi.IMAGERY_PX*(e?1+2*He.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapSnapshotImagery,r=s?void 0:Jb();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?gi.expand(t,He.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(t){t!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=He.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=ke(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},He.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?df(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?Gu(this.currentSighting.milestones):[]){const a=ke(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?fa.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(Ji.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,Gu(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",He.setIcon(this.milestonesButton,this.milestonesShown?Qt.MILESTONES_ON:Qt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=ke(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Ma(i,t),{lat:s,lng:r}=Bs(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const n=ke(this.currentSighting,this.currentTime),s=fa.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return oi.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=He.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),He.setIcon(this.miniMuteButton,this.mutedState?Qt.MUTED:Qt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){He.setIcon(this.muteButton,Qt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}He.setIcon(this.muteButton,this.mutedState?Qt.MUTED:Qt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;He.setIcon(this.fullscreenButton,t?Qt.EXIT_FULLSCREEN:Qt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Pr(ko.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=C0(ko.preferencesFor(this),P0);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await t5.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.videoButton&&(this.videoButton.messages=t),this.labelVideoButton(),this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=F_(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?d1(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return mo(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?H2(B2(this.realStartMs+i)):mo(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?mo(t):mo(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return mo(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return mo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?mo(this.currentSighting.timeline.duration):this.canShowClockTime?H2(B2(this.realStartMs+this.realDurationMs)):mo(this.realDurationMs)}}function B2(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function H2(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function mo(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const p1="rr0-ufo";function jb(){customElements.get(p1)||customElements.define(p1,He)}const A5="timechange",_5="recordingissues",Qb="minifiedreset";/**
|
|
1935
|
+
`);let e=eh.shared.get(t);return e||(e=this.fetchFirstAvailable(),eh.shared.set(t,e),e.then(i=>{i.length===0&&eh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.195.0")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==Sm?[e,Sm]:[Sm]).map(i=>i+t)}}class Fo{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(t={}){this.platform=new Fe(t)}static covers(t){return Fe.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,n)=>Fo.wayOf(i,n))}static wayOf(t,e){if(t.geometry.type!=="LineString")return[];const i=t.geometry.coordinates.map(([d,f])=>({lat:f,lng:d}));if(i.length<2)return[];const n=String(t.properties.nature??""),s=Fo.BY_NATURE[n]??Fo.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),l=Fo.DIRECTIONS[String(t.properties.sens_de_circulation??"")],h=Fo.KINDS[n],u=[t.properties.cpx_toponyme_route_nommee,t.properties.nom_voie_ban_gauche,t.properties.nom_voie_ban_droite].find(d=>typeof d=="string"&&d.length>0);return[{id:String(t.properties.cleabs??`ign-${e}`),...u?{name:u}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...t.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...l?{direction:l}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{},points:i}]}}class v5{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(t){if(Fo.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class Fd{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new Fe(t)}static covers(t){return Fe.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,n)=>Fd.surfacesOf(i,n))}static surfacesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(t.properties.cleabs??`ign-water-${e}`);return s.flatMap((a,c)=>{const l=a.map(h=>Fd.open(h.map(u=>({lat:u[1],lng:u[0]})))).filter(h=>h.length>=3);return l.length>0?[{id:s.length>1?`${r}-${c}`:r,rings:l}]:[]})}static open(t){const e=t[0],i=t[t.length-1];return t.length>1&&e.lat===i.lat&&e.lng===i.lng?t.slice(0,-1):t}}class _c{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new Fs(t)}async getWater(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${e});way["waterway"="riverbank"](${e});)->.w;(relation["natural"="water"](${e});relation["waterway"="riverbank"](${e});)->.r;.w out geom;.r out body;way(r.r)(${e});out geom;`;return _c.surfacesFrom(await this.client.query(i))}static surfacesFrom(t){const e=t.elements??[],i=new Map;for(const r of e)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const n=[],s=new Set;for(const r of e){if(r.type!=="relation")continue;const a=l=>(r.members??[]).filter(h=>h.type==="way"&&h.role===l&&h.ref!==void 0&&i.has(h.ref)).map(h=>(s.add(h.ref),i.get(h.ref))),c=_c.rings(a("inner"));for(const[l,h]of _c.rings(a("outer")).entries()){const u=c.filter(d=>_c.contains(h,d[0]));n.push({id:`osm-r${r.id}-${l}`,rings:[h,...u]})}}for(const r of e)if(!(r.type!=="way"||!r.tags||r.id===void 0||s.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of _c.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(t){const e=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=t.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!e(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const c=i[a],l=s[s.length-1];if(e(l,c[0]))s=[...s,...c.slice(1)];else if(e(l,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&e(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(t,e){let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n],a=t[s];r.lat>e.lat!=a.lat>e.lat&&e.lng<(a.lng-r.lng)*(e.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class y5{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(Fd.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const bm="https://ufoathome.org/water/index.json";class ih{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??ih.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getWater(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.surfaces)?(this.attributionRead=s.attribution,s.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
1936
|
+
`);let e=ih.shared.get(t);return e||(e=this.fetchFirstAvailable(),ih.shared.set(t,e),e.then(i=>{i.length===0&&ih.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.195.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==bm?[e,bm]:[bm]).map(i=>i+t)}}class Rs{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=Rs.key(t);let i=Rs.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Rs.asked.set(e,i),i.catch(()=>Rs.asked.delete(e))),structuredClone(await i)}static forget(){Rs.asked.clear()}static key(t){return`v${Rs.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Rs.openCache(),n=Rs.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<Rs.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Rs.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-Rs.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Rs.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Uo{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new Fe(t)}static covers(t){return Fe.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>Uo.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=Uo.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=Uo.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Uo.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const g=f.map(m=>({lat:m[1],lng:m[0],...m.length>2&&Number.isFinite(m[2])&&m[2]>Uo.NO_ALTITUDE?{altitudeM:m[2]}:{}}));return g.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:g}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class Xn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(t={}){this.client=new Fs(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${Xn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Xn.ROUTES})$"];out body;`;return Xn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=Xn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(M=>ae(M.lat,M.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(M=>M.service===!!r.service);for(const M of Xn.samples(a)){u++;const v=Xn.waysAt(d,M);if(v.length===0)continue;const[x]=v;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const y of new Set(v.flatMap(w=>w.services)))h.set(y,(h.get(y)??0)+1)}const f=M=>[...M.entries()].sort((v,x)=>x[1]-v[1])[0]?.[0],p=r.name??f(c),g=r.voltageV??(r.electrification==="none"?void 0:f(l)),m=[...h.entries()].filter(([,M])=>M*4>=u).sort((M,v)=>v[1]-M[1]||M[0].localeCompare(v[0])).map(([M])=>M);return{...r,...p?{name:p}:{},...g?{voltageV:g}:{},...m.length>0?{services:m}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=Xn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=Xn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=Xn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>ae(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=Xn.SAMPLE_M/2;a<n;a+=Xn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(Xn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=Xn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class nh{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new Fs(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${nh.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Xn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=Xn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=Xn.voltageOf(r),l=nh.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=nh.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:nh.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class x5{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(t){if(!Uo.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class dn{constructor(t,e=Date.now){this.railways=t,this.now=e}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(t){const e=dn.key(t);let i=dn.asked.get(e)??dn.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},dn.asked.set(e,i),n.catch(()=>dn.asked.delete(e))}return structuredClone(await i.answer)}static forget(){dn.asked.clear(),dn.failedAt=-1/0}static key(t){return`v${dn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of dn.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await dn.openCache(),n=dn.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<dn.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-dn.failedAt<dn.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(dn.failedAt=this.now(),s)return s;throw a}return i&&dn.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-dn.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(dn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const Em="https://ufoathome.org/railways/index.json";class sh{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??sh.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
1937
|
+
`);let e=sh.shared.get(t);return e||(e=this.fetchFirstAvailable(),sh.shared.set(t,e),e.then(i=>{i.length===0&&sh.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.195.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==Em?[e,Em]:[Em]).map(i=>i+t)}}function qb(){return{elevation:Zb(),imagery:Jb(),roads:w5(),water:S5(),railways:b5()}}function Zb(){return new m5(new Pe,new Yb)}function Jb(){return new $b}function w5(){return new eh({fallback:new v5(new Fo,new Po)})}function S5(){return new ih({fallback:new Rs(new y5(new Fd,new _c))})}function b5(){return new sh({fallback:new dn(new x5(new Uo,new nh))})}const E5=new Set,Eh="show-observer-map",Ah="hide-milestones",Nc="minified";class He extends HTMLElement{static get observedAttributes(){return["src",Eh,Ah,Nc]}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 gi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];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=Hp.create();issues=[];issueCheck=0;sightingAudio=new O2;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new O2(t)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>He.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");He.setIcon(this.moreButton,t?Qt.UNFOLDED:Qt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(t){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!t){this.fitControls();return}const e=document.createElement("button");e.type="button",e.id="video-button",e.innerHTML=Qt.VIDEO,this.videoElement=e,this.labelVideoButton(),e.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(t,e)},{once:!0}),this.moreButton.after(e),this.fitControls()}async loadVideoButton(t,e){const{VideoButton:i}=await dt(async()=>{const{VideoButton:s}=await import("./VideoButton-Cy_r767Z.js");return{VideoButton:s}},[],import.meta.url);if(this.videoElement!==e)return;const n=new i(t,e);this.videoButton=n,this.messages&&(n.messages=this.messages),this.stageElement.append(n.panel),n.open()}labelVideoButton(){const t=this.videoElement;!t||this.videoButton||(t.title=this.messages?.recordVideo??"",t.setAttribute("aria-label",t.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(t){t!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,t&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(t){const e=this.currentTime,i=t.caption&&this.sighting.milestones.length>0?df(this.sighting.milestones,e):void 0,n=i?this.said.read(i.label)??"":void 0,s=this.canvas.getBoundingClientRect(),r=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:n,note:this.said.read(i.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...r&&s.width>0&&s.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-s.left)/s.width,top:(r.top-s.top)/s.height,width:r.width/s.width,height:r.height/s.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<He.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=gi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=gi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},He.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=gi.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${w3}</style>${x3}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Vh(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 Ac(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.citedMarks=this.shadow.getElementById("cited-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.seekPreview.hidden=!0,this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Eh&&this.applyObserverMapDefault(),t===Ah&&this.setMilestonesShown(!this.hasAttribute(Ah)),t===Nc){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Nc)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(Qb)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const t=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",t),t&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(t){this.sightingData=await ud.recording(t)}get sightingData(){return Nb(this.currentSighting)}set sightingData(t){const e=ha.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=kb(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;set titleShown(t){this.titleHidden=!t,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await dt(async()=>{const{default:r}=await import("./sightingSchema-CgwoRMl-.js");return{default:r}},[],import.meta.url);n=new hr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],kd.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(_5,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=(this.messages?.recordingIssues??"").replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=kd.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(t){this.cited=[...t],this.refreshCitedMarks()}refreshCitedMarks(){const t=this.player.seekableDuration;this.citedMarks.replaceChildren(...(t>0?this.cited:[]).map(e=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.innerHTML=Ie.INTERVIEW,i.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const n=e.quote??"";return i.title=n,i.setAttribute("aria-label",n),i.addEventListener("click",()=>this.player.seek(e.at*1e3)),i}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<He.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(A5,{bubbles:!0,composed:!0,detail:{at:t/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;if(!this.referenceOpacityTouched&&t.length>0){const e=String(t[0].opacity);this.referenceOpacityInput.value!==e&&(this.referenceOpacityInput.value=e,this.severalReferences||this.dispatchReferenceView())}for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),He.setIcon(this.referencesButton,i?Qt.PICTURES_ON:Qt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),He.setIcon(this.tracesButton,this.tracesShownState?Qt.TRACES_ON:Qt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?Gu(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshCitedMarks(),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=He.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){if(t.buttons!==0){this.seekPreview.hidden=!0;return}const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=He.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?df(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new Vh(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=He.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?df(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=ns.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<He.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(He.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/He.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/He.EXPOSURE_STEP_PX),s=Math.min(He.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=Ji.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(t,e){this.sayTimeMoved(t),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:E5;this.canvasRenderer.setStarPoints(Ji.starPointsOf(this.sighting.instrument,ke(this.sighting,t)?.fNumber));const n=(ke(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?Js.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(B_(this.currentSighting,t))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:t}}))}shifted(t,e){return e.x===0&&e.y===0?t:{...t,bounds:{...t.bounds,x:t.bounds.x+e.x,y:t.bounds.y+e.y}}}createPlayer(){const t=new H_(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*He.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?Qt.PLAY:Qt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){He.icons.get(t)!==e&&(He.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},He.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),He.setIcon(this.playPauseButton,t?Qt.PAUSE:Qt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Eh),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;He.setIcon(this.observerMapButton,t?Qt.MAP_ON:Qt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=xh.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=gi.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?gi.expand(t,He.OBSERVER_MAP_IMAGERY_AHEAD):t,n=gi.IMAGERY_PX*(e?1+2*He.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapSnapshotImagery,r=s?void 0:Jb();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?gi.expand(t,He.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(t){t!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=He.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=ke(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},He.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?df(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?Gu(this.currentSighting.milestones):[]){const a=ke(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?fa.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(Ji.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,Gu(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",He.setIcon(this.milestonesButton,this.milestonesShown?Qt.MILESTONES_ON:Qt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=ke(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Ma(i,t),{lat:s,lng:r}=Bs(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const n=ke(this.currentSighting,this.currentTime),s=fa.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return oi.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=He.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),He.setIcon(this.miniMuteButton,this.mutedState?Qt.MUTED:Qt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){He.setIcon(this.muteButton,Qt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}He.setIcon(this.muteButton,this.mutedState?Qt.MUTED:Qt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;He.setIcon(this.fullscreenButton,t?Qt.EXIT_FULLSCREEN:Qt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Pr(ko.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=C0(ko.preferencesFor(this),P0);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await t5.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.videoButton&&(this.videoButton.messages=t),this.labelVideoButton(),this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=F_(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?d1(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return mo(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?H2(B2(this.realStartMs+i)):mo(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?mo(t):mo(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return mo(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return mo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?mo(this.currentSighting.timeline.duration):this.canShowClockTime?H2(B2(this.realStartMs+this.realDurationMs)):mo(this.realDurationMs)}}function B2(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function H2(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function mo(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const p1="rr0-ufo";function jb(){customElements.get(p1)||customElements.define(p1,He)}const A5="timechange",_5="recordingissues",Qb="minifiedreset";/**
|
|
1938
1938
|
* @license
|
|
1939
1939
|
* Copyright 2010-2026 Three.js Authors
|
|
1940
1940
|
* SPDX-License-Identifier: MIT
|
|
@@ -8293,7 +8293,7 @@ ${l.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
8293
8293
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
8294
8294
|
}
|
|
8295
8295
|
`,transparent:!0,depthWrite:!1,side:An,fog:!1,blending:Jc,blendSrc:jc,blendDst:Ud})}static wallReflectance(t,e,i){const n=i(t,1,e);return 2*n/(1+n)}static DISCS={uDiscDirection:{value:[new _(0,1,0),new _(0,1,0)]},uDiscCosRadius:{value:[2,2]},uDiscRadiance:{value:[new _,new _]}};static DISC_INDEX={sun:0,moon:1};static setDisc(t,e){const i=cs.DISC_INDEX[t],n=cs.DISCS;if(!e){n.uDiscCosRadius.value[i]=2,n.uDiscRadiance.value[i].set(0,0,0);return}n.uDiscDirection.value[i].set(...e.direction).normalize(),n.uDiscCosRadius.value[i]=Math.cos(e.radiusRad),n.uDiscRadiance.value[i].set(...e.radiance)}setSurroundings(t){this.uniforms.uSurroundings.value=t}static reflectedResponse(t,e){return Ht.respond(e*Ht.relativeOfResponse(Math.max(t,1e-5)))}}class Is{static SIZE=64;static MOVE_M=.01;holder=new ki;cameras=[];faces=[];target=new qe(Is.SIZE,Is.SIZE);white=new Es({color:new at(1,1,1),side:An});scene=new nr;cabin;meshes=0;eye=new _;scratch=new _;constructor(){const t=[[new _(1,0,0),new _(0,1,0)],[new _(-1,0,0),new _(0,1,0)],[new _(0,1,0),new _(0,0,1)],[new _(0,-1,0),new _(0,0,-1)],[new _(0,0,1),new _(0,1,0)],[new _(0,0,-1),new _(0,1,0)]];for(const[e,i]of t){const n=new Kn(90,1,.02,20);n.up.copy(i),n.lookAt(e),this.holder.add(n),this.cameras.push(n),this.faces.push(new Uint8Array(Is.SIZE*Is.SIZE*4))}this.scene.background=new at(0,0,0)}get any(){return this.cabin!==void 0}update(t,e,i){if(!e){this.forget();return}e.updateWorldMatrix(!0,!0);const n=this.scratch.copy(i);e.worldToLocal(n);let s=0;e.traverse(r=>{r.isMesh&&s++}),!(e===this.cabin&&s===this.meshes&&n.distanceTo(this.eye)<Is.MOVE_M)&&(this.cabin=e,this.meshes=s,this.eye.copy(n),this.draw(t,e))}hides(t){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let e=0;e<6;e++){const i=this.cameras[e],n=this.scratch.copy(t).transformDirection(i.matrixWorldInverse);if(n.z>=0)continue;const s=n.x/-n.z,r=n.y/-n.z;if(Math.abs(s)>1||Math.abs(r)>1)continue;const a=Math.min(Is.SIZE-1,Math.floor((s+1)/2*Is.SIZE)),c=Math.min(Is.SIZE-1,Math.floor((r+1)/2*Is.SIZE));return this.faces[e][(c*Is.SIZE+a)*4]>127}return!1}forget(){this.holder.removeFromParent(),this.cabin=void 0,this.meshes=0}dispose(){this.forget(),this.target.dispose(),this.white.dispose()}draw(t,e){e.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];e.traverse(r=>{const a=r;if(!a.isMesh||!a.visible||(Array.isArray(a.material)?a.material:[a.material]).every(h=>h instanceof cs))return;const l=new pt(a.geometry,this.white);l.matrixAutoUpdate=!1,l.matrix.copy(a.matrixWorld),l.matrixWorld.copy(a.matrixWorld),i.push(l)});for(const r of i)this.scene.add(r);const n=t.getRenderTarget(),s=t.shadowMap.autoUpdate;t.shadowMap.autoUpdate=!1;for(let r=0;r<6;r++){const a=this.cameras[r];a.updateMatrixWorld(!0),t.setRenderTarget(this.target),t.clear(),t.render(this.scene,a),Ap.now(t,this.target,0,0,Is.SIZE,Is.SIZE,this.faces[r])}t.setRenderTarget(n),t.shadowMap.autoUpdate=s;for(const r of i)r.removeFromParent()}}const _g="https://ufoathome.org/models/index.json";class nd{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??dN()}async entries(t){const e=await this.load();return t?e.filter(i=>[i.kind].flat().includes(t)):e}async entry(t){return(await this.load()).find(e=>e.id===t)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
8296
|
-
`);let e=nd.shared.get(t);return e||(e=this.fetchFirstAvailable(),nd.shared.set(t,e),e.then(i=>{i.length===0&&nd.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function dN(){const o=`?v=${encodeURIComponent("0.
|
|
8296
|
+
`);let e=nd.shared.get(t);return e||(e=this.fetchFirstAvailable(),nd.shared.set(t,e),e.then(i=>{i.length===0&&nd.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function dN(){const o=`?v=${encodeURIComponent("0.195.0")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==_g?[t,_g]:[_g]).map(e=>e+o)}const fN=Te.point("decorModels").provide(Te.BUILT_IN,[{id:"ufoathome",name:"UFO@home",credit:"3D models re-hosted by UFO@home, each under its own author's licence",creditUrl:"https://ufoathome.org/models/",create:()=>new nd}]);class zA{constructor(t,e=fN){this.preferredId=t,this.sources=e}attribution="3D models, each under its own author's licence";built=new Map;catalogues(){const t=this.sources.find(i=>i.id===this.preferredId)??this.sources[0];return(t?[t,...this.sources.filter(i=>i!==t)]:[]).map(i=>{let n=this.built.get(i);return n||(n=i.create(),this.built.set(i,n)),n})}entries(t){const e=this.catalogues()[0];return e?e.entries(t):Promise.resolve([])}async entry(t){for(const e of this.catalogues()){const i=await e.entry(t).catch(()=>{});if(i)return i}}async moduleOf(t){const e=Te.point("decorModels");for(const i of this.sources){const n=e.ownerOf(i.id);if(!(n===void 0||n===Te.BUILT_IN)&&await this.catalogueOf(i).entry(t).catch(()=>{}))return n}}catalogueOf(t){return this.catalogues(),this.built.get(t)}}async function Tg(o){const{GLTFLoader:t}=await dt(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-CKDxld-A.js");return{GLTFLoader:i}},[],import.meta.url),e=new t;return new Promise((i,n)=>{e.load(o,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${o}: ${s instanceof Error?s.message:String(s)}`)))})}const BA=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"],iS=Math.PI/180;class Zs{static candelaToward(t,e,i){const n=t.lamps;if(!n||n.length===0)return 0;const s=t.attitude.headingDeg*iS,r={east:Math.sin(s),north:Math.cos(s)},a={east:Math.cos(s),north:-Math.sin(s)};let c=0;for(const l of n){const{intensity:h}=Wc(l,i);if(!(h>0)||!xb(l,i))continue;const u={eastM:t.eastM+a.east*l.offsetM.x+r.east*l.offsetM.z,northM:t.northM+a.north*l.offsetM.x+r.north*l.offsetM.z,upM:t.upM+l.offsetM.y},d=l.beamDeg===void 0?1:Zs.beamShare(l.beamDeg,r,u,e);c+=wb*h*d}return c}static magnitudeOf(t){return-14.18-2.5*Math.log10(t)}static TYCHO={diameterDeg(t){if(!(t>0))return 0;const e=Zs.magnitudeOf(t);return Zs.TYCHO_FIRST_ARCSEC*Math.pow(10,Zs.TYCHO_PER_MAGNITUDE*(1-e))/3600}};static TYCHO_FIRST_ARCSEC=150;static TYCHO_PER_MAGNITUDE=Math.log10(150/18)/5;static seeingOf(t){const e=t.event.place?.[0],i=t.event.time,n=JSON.stringify([i,e?.lat,e?.lng,t.event.utcOffsetHours]),s=Zs.seeings.get(t.event);if(s?.key===n)return s.seeing;const r=Zs.seeingFrom(t,e,i);return Zs.seeings.set(t.event,{key:n,seeing:r}),r}static seeings=new WeakMap;static seeingFrom(t,e,i){if(!e||typeof e.lat!="number"||typeof e.lng!="number"||i?.hour===void 0)return;const n=Ec(i,e.lng,t.event.utcOffsetHours);return n&&Bu("Sun",n,{lat:e.lat,lng:e.lng,elevationM:0}).altitudeDeg<=Zs.NIGHT_SUN_DEG?Zs.TYCHO:void 0}static NIGHT_SUN_DEG=-6;static luxAt(t,e){return e>0?t/(e*e):0}static beamShare(t,e,i,n){const s=n.eastM-i.eastM,r=n.northM-i.northM,a=n.upM-i.upM,c=Math.hypot(s,r,a);if(c===0)return 1;const l=(s*e.east+r*e.north)/c;if(l<=0)return 0;const h=Math.log(.5)/Math.log(Math.cos(t*iS));return Math.pow(l,h)}}const kl=Math.PI/180,bu=180/Math.PI;class ci{constructor(t,e,i,n){this.timeline=t,this.tolerance=e,this.sizeHowOf=i,this.seeing=n}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;projectionWithLights(t,e,i,n){const s=ci.projectionOf(t,e,n);if(!s||!this.seeing||!t.lamps?.length)return s;const r=Math.hypot(t.eastM-e.eastM,t.northM-e.northM,t.upM-e.upM),a=this.seeing.diameterDeg(Zs.luxAt(Zs.candelaToward(t,e,i),r));return a>s.angular.widthDeg||a>s.angular.heightDeg?{aim:s.aim,angular:{widthDeg:Math.max(s.angular.widthDeg,a),heightDeg:Math.max(s.angular.heightDeg,a)},lightSized:!0}:s}static sizeHows(t,e){return(i,n)=>{const s=t.allKeyframes;for(let r=s.length-1;r>=0;r--){const a=s[r];if(a.t>i)continue;const c=a.shapes.findIndex(h=>h.sourceId===n);if(c<0||!a.shapes[c].shape.angular)continue;const l=`timeline.keyframes.${r}.shapes.${c}.shape.angular`;return(e.at(l)??e.at(`${l}.widthDeg`))?.how}}}static lawsOf(t,e){return{direction(i,n,s){const r=t.law({kind:"heading",value:i.azimuthDeg},e),a=Math.abs(((n.azimuthDeg-i.azimuthDeg)%360+540)%360-180),c=t.law({kind:"elevation",value:i.altitudeDeg},e),l=Math.max(ci.DIRECTION_TOLERANCE_DEG,s);return a>(r.high??i.azimuthDeg)-i.azimuthDeg+l||n.altitudeDeg>(c.high??i.altitudeDeg)+l||n.altitudeDeg<(c.low??i.altitudeDeg)-l},size(i,n,s){const r=t.law({kind:"angularSize",value:i,how:s},e);return n<(r.low??i)/ci.SIZE_TOLERANCE||n>(r.high??i)*ci.SIZE_TOLERANCE}}}at(t,e,i,n){const s=[],r=new Map,a=[];for(const c of e){if(c.ensemble&&c.explains.length>0){const l=r.get(c.ensemble);l?l.push(c):r.set(c.ensemble,[c]);continue}a.push({id:c.id,explains:c.explains,predicted:this.projectionWithLights(c,i,t,n?.(c))})}for(const[c,l]of r){const h=l.flatMap(u=>n?.(u)??ci.outlineOf(u));a.push({id:c,explains:l[0].explains,predicted:ci.projectionOf(l[0],i,h)})}for(const c of a){const l=c.predicted;if(l)for(const h of c.explains){const u=this.timeline.getInterpolatedShapeAt(t,h);!u||u.transparency>=1||s.push({...ci.compare(h,c.id,{aim:u.aim,angular:u.angular,sizeHow:this.sizeHowOf?.(t,h)},{aim:l.aim,angular:l.angular},this.tolerance),...l.lightSized?{lightSized:!0}:{},title:u.title})}}return s}static compare(t,e,i,n,s){const r=[],a=i.aim?ci.separationDeg(i.aim,n.aim):void 0;if(a!==void 0){const u=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;(s?s.direction(i.aim,n.aim,u):a>Math.max(ci.DIRECTION_TOLERANCE_DEG,u))&&r.push("direction")}const c=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,l=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0,h=(u,d)=>s?s.size(d,d*u,i.sizeHow):!ci.withinSize(u);return c!==void 0&&h(c,i.angular.widthDeg)&&r.push("width"),l!==void 0&&h(l,i.angular.heightDeg)&&r.push("height"),{sourceId:t,bodyId:e,stated:i,predicted:n,separationDeg:a,widthRatio:c,heightRatio:l,disagreements:r}}static projectionOf(t,e,i){const n=i&&i.length>0?i:ci.outlineOf(t),s=i&&i.length>0?ci.centreOf(i):t,r=ci.normalized({eastM:s.eastM-e.eastM,northM:s.northM-e.northM,upM:s.upM-e.upM});if(!r)return;const a=ci.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},c=ci.cross(a,r);let l=1/0,h=-1/0,u=1/0,d=-1/0;for(const f of n){const p={eastM:f.eastM-e.eastM,northM:f.northM-e.northM,upM:f.upM-e.upM},g=ci.dot(p,r);if(g<=0)return;const m=Math.atan2(ci.dot(p,a),g),M=Math.atan2(ci.dot(p,c),g);l=Math.min(l,m),h=Math.max(h,m),u=Math.min(u,M),d=Math.max(d,M)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*bu+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*bu},angular:{widthDeg:(h-l)*bu,heightDeg:(d-u)*bu}}}static centreOf(t){const e=i=>(Math.min(...t.map(n=>n[i]))+Math.max(...t.map(n=>n[i])))/2;return{eastM:e("eastM"),northM:e("northM"),upM:e("upM")}}static separationDeg(t,e){const i=t.altitudeDeg*kl,n=e.altitudeDeg*kl,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((t.azimuthDeg-e.azimuthDeg)*kl);return Math.acos(Math.max(-1,Math.min(1,s)))*bu}static withinSize(t){return t<=ci.SIZE_TOLERANCE&&t>=1/ci.SIZE_TOLERANCE}static outlineOf(t){const e=t.sizeM.widthM/2,i=t.sizeM.lengthM/2,n=t.sizeM.heightM/2,s=[],r=t.model.url===void 0?t.model.id:void 0;if(r!==void 0&&r!=="box"&&BA.includes(r))for(let u=0;u<=ci.RINGS;u++){const d=u/ci.RINGS*Math.PI;for(let f=0;f<ci.SEGMENTS;f++){const p=f/ci.SEGMENTS*2*Math.PI;s.push([e*Math.sin(d)*Math.cos(p),i*Math.sin(d)*Math.sin(p),n*Math.cos(d)])}}else for(const u of[-e,e])for(const d of[-i,i])for(const f of[-n,n])s.push([u,d,f]);const c=t.attitude.headingDeg*kl,l=t.attitude.pitchDeg*kl,h=t.attitude.rollDeg*kl;return s.map(([u,d,f])=>{const p=u*Math.cos(h)+f*Math.sin(h),g=-u*Math.sin(h)+f*Math.cos(h),m=d*Math.cos(l)-g*Math.sin(l),M=d*Math.sin(l)+g*Math.cos(l);return{eastM:t.eastM+p*Math.cos(c)+m*Math.sin(c),northM:t.northM-p*Math.sin(c)+m*Math.cos(c),upM:t.upM+M}})}static dot(t,e){return t.eastM*e.eastM+t.northM*e.northM+t.upM*e.upM}static cross(t,e){return{eastM:t.northM*e.upM-t.upM*e.northM,northM:t.upM*e.eastM-t.eastM*e.upM,upM:t.eastM*e.northM-t.northM*e.eastM}}static normalized(t){const e=Math.hypot(t.eastM,t.northM,t.upM);return e>1e-9?{eastM:t.eastM/e,northM:t.northM/e,upM:t.upM/e}:void 0}}class Qs{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new pt(new ps(2,2),new De({uniforms:{uColor:{value:new at(0,0,0)},uRadius:{value:1}},vertexShader:Qs.VERTEX,fragmentShader:Qs.FRAGMENT,transparent:!0,depthWrite:!1,blending:Dn,toneMapped:!1})),this.mesh.name=t,this.mesh.frustumCulled=!1,this.mesh.renderOrder=e,this.mesh.visible=!1}shine(t,e,i){this.mesh.visible=!0,this.mesh.position.set(t.x,t.y,t.z),this.mesh.material.uniforms.uRadius.value=e,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(t,e,i,n){const s=Math.max(t,n*Qs.MIN_ANGLE_RAD),r=Qs.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Qs.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/(Qs.MAX_SHARE*Qs.FILL*Math.PI))}static VERTEX=`
|
|
8297
8297
|
uniform float uRadius;
|
|
8298
8298
|
varying vec2 vOffset;
|
|
8299
8299
|
void main() {
|